repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
decilio4g/delicias-do-tchelo
|
node_modules/@styled-icons/entypo/Upload/Upload.esm.js
|
<gh_stars>0
import { __assign } from "tslib";
import * as React from 'react';
import { StyledIconBase } from '@styled-icons/styled-icon';
export var Upload = React.forwardRef(function (props, ref) {
var attrs = {
"fill": "currentColor",
"xmlns": "http://www.w3.org/2000/svg",
};
return (React.createElement(StyledIconBase, __assign({ iconAttrs: attrs, iconVerticalAlign: "middle", iconViewBox: "0 0 20 20" }, props, { ref: ref }),
React.createElement("path", { d: "M8 12h4V6h3l-5-5-5 5h3v6zm11.338 1.532c-.21-.224-1.611-1.723-2.011-2.114A1.503 1.503 0 0016.285 11h-1.757l3.064 2.994h-3.544a.274.274 0 00-.24.133L12.992 16H7.008l-.816-1.873a.276.276 0 00-.24-.133H2.408L5.471 11H3.715c-.397 0-.776.159-1.042.418-.4.392-1.801 1.891-2.011 2.114-.489.521-.758.936-.63 1.449l.561 3.074c.128.514.691.936 1.252.936h16.312c.561 0 1.124-.422 1.252-.936l.561-3.074c.126-.513-.142-.928-.632-1.449z", key: "k0" })));
});
Upload.displayName = 'Upload';
export var UploadDimensions = { height: 20, width: 20 };
|
SemihBKGR/hibou
|
web-app/src/main/java/com/smh/hibouwebapp/jwt/UserToken.java
|
<reponame>SemihBKGR/hibou
package com.smh.hibouwebapp.jwt;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserToken {
private String id;
private String username;
}
|
creoii/Custom
|
src/main/java/creoii/custom/mixin/block/CactusBlockMixin.java
|
package creoii.custom.mixin.block;
import creoii.custom.util.tags.EntityTypeTags;
import creoii.custom.util.tags.ItemTags;
import net.minecraft.block.BlockState;
import net.minecraft.block.CactusBlock;
import net.minecraft.entity.Entity;
import net.minecraft.entity.ItemEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(CactusBlock.class)
public class CactusBlockMixin {
@Inject(method = "onEntityCollision", at = @At("HEAD"), cancellable = true)
private void custom$negateCactusDamage(BlockState state, World world, BlockPos pos, Entity entity, CallbackInfo ci) {
if (entity instanceof ItemEntity) {
if (((ItemEntity) entity).getStack().isIn(ItemTags.CACTUS_IMMUNE)) {
ci.cancel();
}
} else if (entity.getType().isIn(EntityTypeTags.CACTUS_IMMUNE)) ci.cancel();
}
}
|
Jcoderre/Rocket-Elevator-Foundation
|
app/views/admin_users/show.json.jbuilder
|
json.partial! "admin_users/admin_user", admin_user: @admin_user
|
joaocarvalhop/exerciciosUdemy
|
src/lambdas/Produto.java
|
<gh_stars>0
package lambdas;
public class Produto {
final String nome;
final double preco;
final double desconto;
public Produto(String nome, double preco, double desconto) {
this.nome = nome;
this.preco = preco;
this.desconto = desconto;
}
public String toString() {
double precofinal = preco * (1 - desconto);
return "nome: " + nome + " R$" + precofinal;
}
}
|
darcy/aws-lambda-stream
|
test/unit/connectors/eventbridge.test.js
|
import 'mocha';
import { expect } from 'chai';
import sinon from 'sinon';
import AWS from 'aws-sdk-mock';
import Connector from '../../../src/connectors/eventbridge';
import { debug } from '../../../src/utils';
describe('connectors/eventbridge.js', () => {
afterEach(() => {
AWS.restore('EventBridge');
});
it('should publish', async () => {
const spy = sinon.spy((params, cb) => cb(null, {}));
AWS.mock('EventBridge', 'putEvents', spy);
const inputParams = {
Entries: [
{
EventBusName: 'b1',
DetailType: 't1',
Detail: JSON.stringify({ type: 't1' }),
},
],
};
const data = await new Connector({
debug: debug('eventbridge'),
}).putEvents(inputParams);
expect(spy).to.have.been.calledWith({
Entries: inputParams.Entries,
});
expect(data).to.deep.equal({});
});
});
|
lakodali/osc-core
|
osc-ui/src/main/java/org/osc/core/broker/view/vc/UpdateVirtualizationConnectorWindow.java
|
<reponame>lakodali/osc-core
/*******************************************************************************
* Copyright (c) Intel Corporation
* Copyright (c) 2017
*
* 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.osc.core.broker.view.vc;
import org.apache.log4j.Logger;
import org.osc.core.broker.service.api.UpdateVirtualizationConnectorServiceApi;
import org.osc.core.broker.service.api.plugin.PluginService;
import org.osc.core.broker.service.api.server.EncryptionApi;
import org.osc.core.broker.service.api.server.ServerApi;
import org.osc.core.broker.service.api.server.ValidationApi;
import org.osc.core.broker.service.dto.VirtualizationConnectorDto;
import org.osc.core.broker.service.request.DryRunRequest;
import org.osc.core.broker.service.request.VirtualizationConnectorRequest;
import org.osc.core.broker.service.response.BaseJobResponse;
import org.osc.core.broker.service.ssl.X509TrustManagerApi;
import org.osc.core.broker.view.util.ViewUtil;
import org.osc.core.common.controller.ControllerType;
public class UpdateVirtualizationConnectorWindow extends BaseVCWindow {
private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(UpdateVirtualizationConnectorWindow.class);
final String CAPTION = "Edit Virtualization Connector";
private final UpdateVirtualizationConnectorServiceApi updateVirtualizationConnectorService;
private final ServerApi server;
public UpdateVirtualizationConnectorWindow(VirtualizationConnectorView vcView,
UpdateVirtualizationConnectorServiceApi updateVirtualizationConnectorService,
PluginService pluginService, ValidationApi validator,
X509TrustManagerApi trustManager, ServerApi server,
EncryptionApi encryption) throws Exception {
super(pluginService, validator, trustManager, encryption);
this.server = server;
this.currentVCObject = vcView.getParentContainer().getItem(vcView.getParentItemId());
this.updateVirtualizationConnectorService = updateVirtualizationConnectorService;
createWindow(this.CAPTION);
}
@Override
public void populateForm() {
buildForm();
// filling text fields with existing table data
this.name.setValue(this.currentVCObject.getItemProperty("name").getValue().toString());
this.virtualizationType.select(this.currentVCObject.getItemProperty("type").getValue().toString());
this.virtualizationType.setEnabled(false);
updateForm(this.virtualizationType.getValue().toString());
VirtualizationConnectorDto vcObject = this.currentVCObject.getBean();
if (vcObject.isControllerDefined()) {
this.controllerIP.setValue(vcObject.getControllerIP());
this.controllerUser.setValue(vcObject.getControllerUser());
this.controllerPW.setValue(vcObject.getControllerPassword());
this.controllerType.setValue(vcObject.getControllerType());
} else {
this.controllerType.setValue(ControllerType.NONE);
this.controllerType.setEnabled(true);
}
this.providerIP.setValue(vcObject.getProviderIP());
this.adminTenantName.setValue(vcObject.getAdminTenantName());
this.providerUser.setValue(vcObject.getProviderUser());
this.providerPW.setValue(vcObject.getProviderPassword());
this.providerAttributes = vcObject.getProviderAttributes();
}
@Override
public void submitForm() {
try {
if (validateForm()) {
// creating add request with user entered data
DryRunRequest<VirtualizationConnectorRequest> updateRequest = createRequest();
updateRequest.getDto().setId(this.currentVCObject.getBean().getId());
log.debug("Updating virtualization connector - " + this.name.getValue().trim());
// no response needed for update request
BaseJobResponse response = this.updateVirtualizationConnectorService.dispatch(updateRequest);
close();
ViewUtil.showJobNotification(response.getJobId(), this.server);
}
} catch (Exception exception) {
sslAwareHandleException(exception);
}
}
}
|
nithu0115/amazon-vpc-resource-controller-k8s
|
pkg/node/manager.go
|
// Copyright 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.
package node
import (
"fmt"
"reflect"
"runtime"
"strings"
"sync"
"github.com/aws/amazon-vpc-resource-controller-k8s/pkg/aws/ec2/api"
"github.com/aws/amazon-vpc-resource-controller-k8s/pkg/config"
"github.com/aws/amazon-vpc-resource-controller-k8s/pkg/k8s"
"github.com/aws/amazon-vpc-resource-controller-k8s/pkg/provider"
"github.com/go-logr/logr"
v1 "k8s.io/api/core/v1"
)
type manager struct {
// Log is the logger for node manager
Log logr.Logger
// lock to prevent multiple routines to write/update to data store concurrently
lock sync.RWMutex
// dataStore is the in memory data store of all the managed nodes in the cluster
dataStore map[string]Node
// resourceProviders is the list of resource providers
resourceProviders []provider.ResourceProvider
// ec2APIHelper is the helper function to get instance details from EC2 API
ec2APIHelper api.EC2APIHelper
// k8sWrapper is the wrapper to get k8s object
k8sWrapper k8s.K8sWrapper
}
type Manager interface {
AddOrUpdateNode(v1Node *v1.Node) error
DeleteNode(nodeName string) error
GetNode(nodeName string) (node Node, managed bool)
}
// NewNodeManager returns a new node manager
func NewNodeManager(logger logr.Logger, provider []provider.ResourceProvider, ec2APIHelper api.EC2APIHelper, k8sWrapper k8s.K8sWrapper) Manager {
return &manager{
resourceProviders: provider,
Log: logger,
dataStore: make(map[string]Node),
ec2APIHelper: ec2APIHelper,
k8sWrapper: k8sWrapper,
}
}
// GetNode returns the node from in memory store
func (m *manager) GetNode(nodeName string) (node Node, managed bool) {
m.lock.RLock()
defer m.lock.RUnlock()
node, managed = m.dataStore[nodeName]
return
}
// AddNode adds or updates the node to the node manager cache and performs resource initialization/updates based
// on the managed status of the node.
func (m *manager) AddOrUpdateNode(v1Node *v1.Node) error {
// postUnlockOperation is any operation that involves making network call. It must be done after
// releasing the node manager lock to allow concurrent processing of multiple nodes and not blocking
// the GetNode call in the critical path of pod processing.
postUnlockOperation, err := m.addOrUpdateNode(v1Node)
if err != nil {
return err
}
return m.performPostUnlockOperation(v1Node.Name, postUnlockOperation)
}
// DeleteNode deletes the nodes from the cache and cleans up the resources used by all the resource providers
func (m *manager) DeleteNode(nodeName string) error {
// postUnlockOperation is any operation that involves making network call. It must be done after
// releasing the node manager lock to allow concurrent processing of multiple nodes and not blocking
// the GetNode call in the critical path of pod processing.
postUnlockOperation, err := m.deleteNode(nodeName)
if err != nil {
return err
}
return m.performPostUnlockOperation(nodeName, postUnlockOperation)
}
// addOrUpdateNode adds eligible nodes to the cache. If the node was previously managed and
// is not eligible for management currently, the node is removed
func (m *manager) addOrUpdateNode(v1Node *v1.Node) (postUnlockOperation func([]provider.ResourceProvider, api.EC2APIHelper) error, err error) {
m.lock.Lock()
defer m.lock.Unlock()
log := m.Log.WithValues("node name", v1Node.Name, "request", "add/update")
node, managed := m.dataStore[v1Node.Name]
if managed { // Cache hit
shouldManageNode := m.isSelectedForManagement(v1Node)
if shouldManageNode {
log.V(1).Info("no updates on the managed status of the node")
err = m.updateSubnetIfUsingENIConfig(node, v1Node)
postUnlockOperation = node.UpdateResources
return
}
delete(m.dataStore, v1Node.Name)
postUnlockOperation = node.DeleteResources
log.Info("node removed from the list of managed node as it's not eligible for management anymore")
} else { // Cache miss
isSelected := m.isSelectedForManagement(v1Node)
if !isSelected {
log.V(1).Info("skipping as node is not eligible for management by controller")
return
}
// Node is eligible for management.
instanceId := getNodeInstanceID(v1Node)
os := getNodeOS(v1Node)
if instanceId == "" || os == "" {
err = fmt.Errorf("instance id %s or os %s not found in the label", instanceId, os)
log.Error(err, "not adding node to list of managed node")
return
}
node := NewNode(m.Log.WithName("node initializer").WithValues("name",
v1Node.Name), v1Node.Name, instanceId, os)
err = m.updateSubnetIfUsingENIConfig(node, v1Node)
if err != nil {
return
}
m.dataStore[v1Node.Name] = node
postUnlockOperation = node.InitResources
log.Info("node added to list of managed node")
}
return
}
// deleteNode deletes the nodes from the node manager cache
func (m *manager) deleteNode(nodeName string) (postUnlockOperation func([]provider.ResourceProvider, api.EC2APIHelper) error, err error) {
m.lock.Lock()
defer m.lock.Unlock()
log := m.Log.WithValues("node name", nodeName, "request", "delete")
node, managed := m.dataStore[nodeName]
if !managed {
log.Info("node is not managed by controller, not processing the request")
return
}
delete(m.dataStore, nodeName)
postUnlockOperation = node.DeleteResources
log.Info("node removed from list of managed node")
return
}
// updateSubnetIfUsingENIConfig updates the subnet id for the node to the subnet specified in ENIConfig if the node is
// using custom networking
func (m *manager) updateSubnetIfUsingENIConfig(node Node, k8sNode *v1.Node) error {
eniConfigName, isPresent := k8sNode.Labels[config.CustomNetworkingLabel]
if isPresent {
eniConfig, err := m.k8sWrapper.GetENIConfig(eniConfigName)
if err != nil {
return fmt.Errorf("failed to find the ENIConfig %s: %v", eniConfigName, err)
}
if eniConfig.Spec.Subnet != "" {
m.Log.V(1).Info("node is using custom networking, updating the subnet", "node", k8sNode.Name,
"subnet", eniConfig.Spec.Subnet)
node.UpdateCustomNetworkingSpecs(eniConfig.Spec.Subnet, eniConfig.Spec.SecurityGroups)
return nil
}
return fmt.Errorf("failed to find subnet in eniconfig spec %s", eniConfigName)
} else {
node.UpdateCustomNetworkingSpecs("", nil)
}
return nil
}
// performPostUnlockOperation performs the operation on a node without taking the node manager lock
func (m *manager) performPostUnlockOperation(nodeName string, postUnlockOperation func([]provider.ResourceProvider, api.EC2APIHelper) error) error {
log := m.Log.WithValues("node", nodeName)
if postUnlockOperation == nil {
return nil
}
err := postUnlockOperation(m.resourceProviders, m.ec2APIHelper)
operationName := runtime.FuncForPC(reflect.ValueOf(postUnlockOperation).Pointer()).Name()
if err == nil {
log.V(1).Info("successfully performed node operation", "operation", operationName)
return nil
}
m.lock.Lock()
defer m.lock.Unlock()
log.Error(err, "failed to performed node operation", "operation", operationName)
if err == ErrInitResources {
// Remove entry from the cache, so it's initialized again
log.Info("removing the node from cache as it failed to initialize")
delete(m.dataStore, nodeName)
}
return err
}
// isSelectedForManagement returns true if the node should be managed by the controller
func (m *manager) isSelectedForManagement(v1node *v1.Node) bool {
//return isWindowsNode(v1node) || canAttachTrunk(v1node)
return canAttachTrunk(v1node)
}
// getNodeInstanceID returns the EC2 instance ID of a node
func getNodeInstanceID(node *v1.Node) string {
var instanceID string
if node.Spec.ProviderID != "" {
// ProviderID is preferred when available.
// aws:///us-west-2c/i-01234567890abcdef
id := strings.Split(node.Spec.ProviderID, "/")
instanceID = id[len(id)-1]
}
return instanceID
}
// getNodeOS returns the operating system of a node.
func getNodeOS(node *v1.Node) string {
labels := node.GetLabels()
os := labels[config.NodeLabelOS]
if os == "" {
// For older k8s version.
os = labels[config.NodeLabelOSBeta]
}
return os
}
// isWindowsNode returns true if the "kubernetes.io/os" or "beta.kubernetes.io/os" is set to windows
func isWindowsNode(node *v1.Node) bool {
labels := node.GetLabels()
nodeOS, ok := labels[config.NodeLabelOS]
if !ok {
nodeOS, ok = labels[config.NodeLabelOSBeta]
if !ok {
return false
}
}
return nodeOS == config.OSWindows
}
// canAttachTrunk returns true if the node has capability to attach a Trunk ENI
func canAttachTrunk(node *v1.Node) bool {
_, ok := node.Labels[config.HasTrunkAttachedLabel]
return ok
}
|
limaofeng/jfantasy-framework
|
core/src/test/java/org/jfantasy/framework/crypto/RSAUtilTest.java
|
<gh_stars>1-10
package org.jfantasy.framework.crypto;
import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.util.DigestUtils;
public class RSAUtilTest {
private static final Log LOG = LogFactory.getLog(RSAUtilTest.class);
@Test
public void testGenerateKeyPair() throws Exception {
KeyPair keyPair = RSAUtil.generateKeyPair();
// 公钥
RSAPublicKey pubKey = (RSAPublicKey) keyPair.getPublic();
// 私钥
RSAPrivateKey priKey = (RSAPrivateKey) keyPair.getPrivate();
LOG.debug("pubKey = " + pubKey.toString());
LOG.debug("priKey = " + priKey.toString());
}
@Test
public void testEncrypt() throws Exception {
RSAPublicKey recoveryPubKey = RSAUtil.getRSAPublicKey(pubKey);
String source = DigestUtils.md5DigestAsHex("加密的数据".getBytes());
LOG.debug("原始字符串:" + source);
String enstr = RSAUtil.encrypt(recoveryPubKey, source);
LOG.debug("加密后的:" + enstr + "\n长度:" + enstr.length());
RSAPrivateKey recoveryPriKey = RSAUtil.getRSAPrivateKey(priKey);
String destr = RSAUtil.decrypt(recoveryPriKey, enstr);
LOG.debug("解码字符:" + destr);
assert destr.equals(source);
}
private String pubKey;
private String priKey;
@BeforeEach
public void setUp() throws Exception {
pubKey =
"RSA Public Key\n"
+ " modulus: c3bdfbc49c74cf42af50b2b265c1ea88db13e20e5c5dbb22126aede5ec23fe4aa9eee378082437e69debbba775865925c54a7f660395aa31d64aa2549e365b0b7e46c0a09109900d00b1e298b245d9f0df25e59d0ab83731b837ac5916a4907cc730532d106dce1bcc951fd98694395a94e935af0fa11d9c992d90372b79d0c5\n"
+ " public exponent: 10001";
priKey =
"RSA Private CRT Key\n"
+ " modulus: c3bdfbc49c74cf42af50b2b265c1ea88db13e20e5c5dbb22126aede5ec23fe4aa9eee378082437e69debbba775865925c54a7f660395aa31d64aa2549e365b0b7e46c0a09109900d00b1e298b245d9f0df25e59d0ab83731b837ac5916a4907cc730532d106dce1bcc951fd98694395a94e935af0fa11d9c992d90372b79d0c5\n"
+ " public exponent: 10001\n"
+ " private exponent: aedc9f778a95473a39478bfb96afdf07173ef1e90656ad7fc89841a1ee8c50f4fe4dec632452c6a57c5a44af5a6c04639b95ebad84724532744f04293795334ac444198c46c5d67856d46623042cd0cb91b7a25412e8a1586872bef134e0a05e18da6cdf62339885b617d8ae85ac7f10e4362d3a14ea44f8094132cfa5b8cdd9\n"
+ " primeP: fcb71810c8276ebfcfaca4e29dc960f7021dc9210789be00f62c914e9e11f22aeda85862d01618e40b1b073f102bba5b48deee6543b9ef7eff9d696892907d8f\n"
+ " primeQ: c6494ff8748f9f3290b2fa9a4945fa02ba966c351e314c08bd964588c9cee4e1cf11ce5fab0c491ca6c9d083bb6761d7de28f7d1a74b39f6d04b55b8bd964a6b\n"
+ " primeExponentP: 29d4a4c7225a649a9b6598656a78caf418059625417a2b593d66632700433832a2e41abd407467ea576c41e6ce666e926d9d791889fd5d07488865ca4978615\n"
+ " primeExponentQ: c4daf3f20e86a7de6399cd026fcc7131545d128089c117637615426353377c345287b30377a572d06725e545634077fb002c5c1c60a266a18a99c038f0bfcc91\n"
+ " crtCoefficient: 6dda38f5d57439dffa98987e9da7ced158704d67a19d1a66f6938b32e6992f6aace1072fd4732cc7d86e9cf243bb20783213ae2e9f20fa2eae4403a2e44e3d52\n";
}
@Test
public void testDecrypt() throws Exception {}
}
|
bhagyasakalanka/wso2-axis2
|
modules/clustering/src/org/apache/axis2/clustering/state/commands/StateClusteringCommandCollection.java
|
<gh_stars>1-10
/*
* 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.axis2.clustering.state.commands;
import org.apache.axis2.clustering.ClusteringFault;
import org.apache.axis2.clustering.state.StateClusteringCommand;
import org.apache.axis2.context.ConfigurationContext;
import java.util.ArrayList;
import java.util.List;
/**
* A StateClusteringCommand consisting of a collection of other StateClusteringCommands
*/
public class StateClusteringCommandCollection extends StateClusteringCommand {
private final List<StateClusteringCommand> commands;
public StateClusteringCommandCollection(List<StateClusteringCommand> commands) {
this.commands = commands;
}
public void execute(ConfigurationContext configContext) throws ClusteringFault {
for (StateClusteringCommand command : commands) {
command.execute(configContext);
}
}
public boolean isEmpty(){
return commands != null && commands.isEmpty();
}
public String toString() {
return "StateClusteringCommandCollection";
}
}
|
ayresmajor/Curso-python
|
Aula Python/Aula 16 ex4.py
|
<reponame>ayresmajor/Curso-python
a = (1, 2, 9)
b = (5, 6, 9, 5415)
c = a + b
d = b + a
print(a)
print(b)
print(c)
print(d)
print(c.count(9)) #count conta quantas vezes aparece determinado elemento
print(c.index(5)) #index indica a posição de determinado elemento
print(c.index(9,3))
|
monarch-initiative/phenol
|
phenol-core/src/test/java/org/monarchinitiative/phenol/ontology/testdata/hpo/ToyHpoAnnotation.java
|
<reponame>monarch-initiative/phenol
package org.monarchinitiative.phenol.ontology.testdata.hpo;
import com.google.common.collect.ComparisonChain;
import org.monarchinitiative.phenol.ontology.data.TermAnnotation;
import org.monarchinitiative.phenol.ontology.data.TermId;
import javax.annotation.Nonnull;
public class ToyHpoAnnotation implements TermAnnotation {
private static final long serialVersionUID = 1L;
private final TermId termId;
private final TermId label;
public ToyHpoAnnotation(TermId termId, String label) {
this.termId = termId;
this.label = TermId.of("VEG", label);
}
@Override
public TermId getTermId() {
return termId;
}
@Override
public TermId getLabel() {
return label;
}
@Override
public int compareTo(@Nonnull TermAnnotation o) {
if (!(o instanceof ToyHpoAnnotation)) {
throw new RuntimeException("Cannot compare " + o + " to " + this);
}
ToyHpoAnnotation that = (ToyHpoAnnotation) o;
return ComparisonChain.start()
.compare(this.termId, that.termId)
.compare(this.label, that.label)
.result();
}
@Override
public String toString() {
return "VegetableTermAnnotation [termId=" + termId + ", label=" + label + "]";
}
}
|
Will33ELS/FastAsyncWorldEdit
|
worldedit-core/src/main/java/com/boydti/fawe/object/extent/TransformExtent.java
|
<reponame>Will33ELS/FastAsyncWorldEdit
package com.boydti.fawe.object.extent;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.extent.transform.BlockTransformExtent;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.math.MutableBlockVector3;
import com.sk89q.worldedit.math.MutableVector3;
import com.sk89q.worldedit.math.Vector3;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockStateHolder;
public class TransformExtent extends BlockTransformExtent {
private final MutableVector3 mutable1 = new MutableVector3();
private final MutableBlockVector3 mutable2 = new MutableBlockVector3();
private BlockVector3 min;
public TransformExtent(Extent parent) {
super(parent);
}
@Override
public ResettableExtent setExtent(Extent extent) {
min = null;
return super.setExtent(extent);
}
@Override
public BlockVector3 getMinimumPoint() {
BlockVector3 pos1 = getPos(super.getMinimumPoint());
BlockVector3 pos2 = getPos(super.getMaximumPoint());
return pos1.getMinimum(pos2);
}
@Override
public BlockVector3 getMaximumPoint() {
BlockVector3 pos1 = getPos(super.getMinimumPoint());
BlockVector3 pos2 = getPos(super.getMaximumPoint());
return pos1.getMaximum(pos2);
}
@Override
public void setOrigin(BlockVector3 pos) {
this.min = pos;
}
public BlockVector3 getPos(BlockVector3 pos) {
if (min == null) {
min = pos;
}
mutable1.mutX(pos.getX() - min.getX());
mutable1.mutY(pos.getY() - min.getY());
mutable1.mutZ(pos.getZ() - min.getZ());
Vector3 tmp = getTransform().apply(mutable1);
mutable2.mutX(tmp.getX() + min.getX());
mutable2.mutY(tmp.getY() + min.getY());
mutable2.mutZ(tmp.getZ() + min.getZ());
return mutable2;
}
public BlockVector3 getPos(int x, int y, int z) {
if (min == null) {
min = BlockVector3.at(x, y, z);
}
mutable1.mutX(x - min.getX());
mutable1.mutY(y - min.getY());
mutable1.mutZ(z - min.getZ());
Vector3 tmp = getTransform().apply(mutable1);
mutable2.mutX(tmp.getX() + min.getX());
mutable2.mutY(tmp.getY() + min.getY());
mutable2.mutZ(tmp.getZ() + min.getZ());
return tmp.toBlockPoint();
}
@Override
public BlockState getBlock(int x, int y, int z) {
BlockVector3 p = getPos(x, y, z);
return transform(super.getBlock(p.getX(), p.getY(), p.getZ()));
}
@Override
public BaseBlock getFullBlock(BlockVector3 position) {
return transform(super.getFullBlock(getPos(position)));
}
@Override
public BiomeType getBiomeType(int x, int y, int z) {
BlockVector3 p = getPos(x, y, z);
return super.getBiomeType(p.getX(), y, p.getZ());
}
@Override
public <T extends BlockStateHolder<T>> boolean setBlock(int x, int y, int z, T block)
throws WorldEditException {
return super.setBlock(getPos(x, y, z), transformInverse(block));
}
@Override
public <B extends BlockStateHolder<B>> boolean setBlock(BlockVector3 location, B block)
throws WorldEditException {
return super.setBlock(getPos(location), transformInverse(block));
}
@Override
public boolean setBiome(int x, int y, int z, BiomeType biome) {
BlockVector3 p = getPos(x, y, z);
return super.setBiome(p.getX(), p.getY(), p.getZ(), biome);
}
}
|
stevedanomodolor/Simulation-and-control-of-BLDC-motor-with-methods-on-data-transfer-and-visualization
|
Multithreaded-software/src/algorithms/motor_simulation_control_functions.c
|
// Software based on http://www.sosw.poznan.pl/tfitzer/pmsm/
// Copyright <NAME> 17/05/2020 Ku leuven UPC EEBE
// Project: Bachelor thesis- Simulaton and control of a BLDC motor with methods on data transfer and visualitzation
// Tutor : <NAME>
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
// @file motor_simulation_control_functions.c
// @brief Implementation of functions to change motors state
//
// This file contains the implementation of C compatible functions for manipulating the motor's current state
#include <string.h>
#include "motor_simulation_control_functions.h"
bool slider_max_point(slider * paramtres) {
if (paramtres->current_value >= paramtres->max_boundary) {
return true;
}
return false;
}
bool slider_min_point(slider * paramtres) {
if (paramtres->current_value <= paramtres->min_boundary) {
return true;
}
return false;
}
void increase_vbus_value(conf_motor_simulation_control * configuration)
{
sliders_input_para type = vbus;
if(!slider_max_point(configuration->input_parametres->slider_input[type])) {
configuration->input_parametres->slider_input[type]->current_value+= 1;
}
printf_current_input_value(configuration->input_parametres->slider_input[type]->current_value, vbus);
}
void decrease_vbus_value(conf_motor_simulation_control * configuration)
{
sliders_input_para type = vbus;
if(!slider_min_point(configuration->input_parametres->slider_input[type])) {
configuration->input_parametres->slider_input[type]->current_value-= 1;
}
printf_current_input_value(configuration->input_parametres->slider_input[type]->current_value, vbus);
}
void increase_torque_value(conf_motor_simulation_control * configuration)
{
sliders_input_para type = loadt;
if(!slider_max_point(configuration->input_parametres->slider_input[type])) {
configuration->input_parametres->slider_input[type]->current_value+= 1;
}
printf_current_input_value(configuration->input_parametres->slider_input[type]->current_value, loadt);
}
void decrease_torque_value(conf_motor_simulation_control * configuration)
{
sliders_input_para type = loadt;
if(!slider_min_point(configuration->input_parametres->slider_input[type])) {
configuration->input_parametres->slider_input[type]->current_value-= 1;
}
printf_current_input_value(configuration->input_parametres->slider_input[type]->current_value, loadt);
}
void increase_inertia_value(conf_motor_simulation_control * configuration)
{
sliders_input_para type = loadj;
if(!slider_max_point(configuration->input_parametres->slider_input[type])) {
configuration->input_parametres->slider_input[type]->current_value+= 1;
}
printf_current_input_value(configuration->input_parametres->slider_input[type]->current_value, loadj);
}
void decrease_inertia_value(conf_motor_simulation_control * configuration)
{
sliders_input_para type = loadj;
if(!slider_min_point(configuration->input_parametres->slider_input[type])) {
configuration->input_parametres->slider_input[type]->current_value-= 1;
}
printf_current_input_value(configuration->input_parametres->slider_input[type]->current_value, loadj);
}
void increase_speedref_value(conf_motor_simulation_control * configuration)
{
sliders_input_para type = rpm_ref;
if(!slider_max_point(configuration->input_parametres->slider_input[type])) {
configuration->input_parametres->slider_input[type]->current_value+= 10;
}
printf_current_input_value(configuration->input_parametres->slider_input[type]->current_value, rpm_ref);
}
void decrease_speedref_value(conf_motor_simulation_control * configuration)
{
sliders_input_para type = rpm_ref;
if(!slider_min_point(configuration->input_parametres->slider_input[type])) {
configuration->input_parametres->slider_input[type]->current_value-= 10;
}
printf_current_input_value(configuration->input_parametres->slider_input[type]->current_value, rpm_ref);
}
void increase_posref_value(conf_motor_simulation_control * configuration)
{
sliders_input_para type = pos_ref;
if(!slider_max_point(configuration->input_parametres->slider_input[type])) {
configuration->input_parametres->slider_input[type]->current_value+= 10;
}
printf_current_input_value(configuration->input_parametres->slider_input[type]->current_value, pos_ref);
}
void decrease_posref_value(conf_motor_simulation_control * configuration)
{
sliders_input_para type = pos_ref;
if(!slider_min_point(configuration->input_parametres->slider_input[type])) {
configuration->input_parametres->slider_input[type]->current_value-= 10;
}
printf_current_input_value(configuration->input_parametres->slider_input[type]->current_value, pos_ref);
}
void restart(conf_motor_simulation_control * configuration)
{
configuration->simulation_parametres->t = 0; // s
configuration->simulation_parametres->last_loop = 0;
configuration->simulation_parametres->calculated_stream_rate = 0;
configuration->simulation_parametres->angle = 0;
configuration->simulation_parametres->velocity = 0;
configuration->simulation_parametres->position = 0;
configuration->simulation_parametres->ia = 0;
configuration->simulation_parametres->ib = 0;
configuration->simulation_parametres->vel_t = 0;
configuration->simulation_parametres->torque = 0;
configuration->simulation_parametres->new_loop=0;
configuration->simulation_parametres->calculated_stream_rate=0;
configuration->simulation_parametres-> angleDeg = 0;
configuration->simulation_parametres-> vel_cmd = 0;
configuration->simulation_parametres-> set_pos = 0;
for (int i = 0; i < 4; i++)
{
motor_pid_parametre.pid_result_c[i].p_state = 0; // current proportional state
motor_pid_parametre.pid_result_c[i].int_state = 0; // current integral state
motor_pid_parametre.pid_result_c[i].d_state = 0; // curent derivative state
motor_pid_parametre.pid_result_c[i].previous_error = 0;
}
// resetting motor variables
motor_parametre.ia = 0; // phase current
motor_parametre.ib = 0;
motor_parametre.ic = 0;
motor_parametre.ialpha = 0; // ialpha, ibeta, id, iq //TODO: specific explanation of each term
motor_parametre.ibeta = 0;
motor_parametre.id = 0;
motor_parametre.iq = 0;
motor_parametre.van = 0; // pahse voltage
motor_parametre.vbn = 0;
motor_parametre.vcn = 0;
motor_parametre.bemfa = 0; //back-emf voltage
motor_parametre.bemfb = 0;
motor_parametre.bemfc = 0;
motor_parametre.torque = 0; // torque motor_parametre.velocity= 0; // motor velocity(radians/s)
motor_parametre.position = 0; // motor position (radaians)
// FOC resetting
foc_parametre.ialpha = 0; // ialpha, ibeta, id, iq //TODO: specific explanation of each term
foc_parametre.ibeta = 0;
foc_parametre.iq = 0;
foc_parametre.id = 0;
foc_parametre.valpha = 0;
foc_parametre.vbeta = 0;
foc_parametre.va = 0;
foc_parametre.vb = 0;
foc_parametre.vc = 0;
foc_parametre.torque = 0; // torque
foc_parametre.flux = 0;
foc_parametre.id_pid = 0; // value defined
foc_parametre.iq_pid = 0; // value defiined
// Resetting openloop variable
openloop_motor_parametre.va = 0;
openloop_motor_parametre.vb = 0;
openloop_motor_parametre.vc = 0;
}
void update_simulation_varible(conf_motor_simulation_control *configuration)
{
float Vbus = configuration->input_parametres->slider_input[vbus]->current_value * 1.0;
float Torque = configuration->input_parametres->slider_input[loadt]->current_value * 1E-3;
float Inertia = configuration->input_parametres->slider_input[loadj]->current_value * 1E-5;
float Rpm_ref = configuration->input_parametres->slider_input[rpm_ref]->current_value * 1.0;
float Pos_ref = configuration->input_parametres->slider_input[pos_ref]->current_value * 1.0;
float va, vb, vc;
int steps;
struct timespec start;
// To make sure that the time was collected correctly
if (clock_gettime(CLOCK_MONOTONIC, &start) == -1)
{
perror("clock gettime");
printf("Timing error\n");
exit(EXIT_FAILURE);
}
configuration->simulation_parametres->new_loop = start.tv_nsec; // getting milli seconds value
/// TODO: CONFIRM IF CORRECT
if (configuration->simulation_parametres->last_loop == 0)
{
configuration->simulation_parametres->last_loop = configuration->simulation_parametres->new_loop;
}
else
{
configuration->simulation_parametres->calculated_stream_rate = (1000000000 / (configuration->simulation_parametres->new_loop-configuration->simulation_parametres->last_loop ));
configuration->simulation_parametres->last_loop = configuration->simulation_parametres->new_loop;
// configuration->simulation_parametres->angle = 0;
// configuration->simulation_parametres->angleDeg = 0;
steps = 1 / (configuration->simulation_parametres->calculated_stream_rate * configuration->simulation_parametres->dt);
for (int i = 0; i < steps; i++)
{
configuration->simulation_parametres->angle = configuration->simulation_parametres->position * motor_model_parametre.pole / 2;
configuration->simulation_parametres->angleDeg = configuration->simulation_parametres->angle / M_PI * 180.0;
if (configuration->input_parametres->mode == open_mode)
{
OpenLoop(configuration->simulation_parametres->t, Vbus, Rpm_ref);
va = openloop_motor_parametre.va;
vb = openloop_motor_parametre.vb;
vc = openloop_motor_parametre.vc;
}
if (configuration->input_parametres->mode == foc_speed)
{
configuration->simulation_parametres->torque = update_PID(rpm_pid, (Rpm_ref - configuration->simulation_parametres->velocity)) * motor_model_parametre.Tmax;
update_foc_control_variable(configuration->simulation_parametres->t, configuration->simulation_parametres->dt, Vbus, configuration->simulation_parametres->ia, configuration->simulation_parametres->ib, 0, (-configuration->simulation_parametres->torque / motor_model_parametre.Kt), configuration->simulation_parametres->angle);
va = foc_parametre.va;
vb = foc_parametre.vb;
vc = foc_parametre.vc;
}
if (configuration->input_parametres->mode == foc_pos)
{
configuration->simulation_parametres->set_pos = Pos_ref;
if (Pos_ref== 0)
{
configuration->simulation_parametres->set_pos = sin(configuration->simulation_parametres->t / 2 * (M_PI * 2.0)) * 1800 + 1800;
}
configuration->simulation_parametres->vel_cmd = update_PID(pos_pid, (configuration->simulation_parametres->set_pos - configuration->simulation_parametres->angleDeg)) * 10000;
configuration->simulation_parametres->vel_cmd = max_num(-Rpm_ref, min_num(Rpm_ref, configuration->simulation_parametres->vel_cmd));
configuration->simulation_parametres->torque = update_PID(rpm_pid, configuration->simulation_parametres->vel_cmd - configuration->simulation_parametres->velocity) * motor_model_parametre.Tmax;
update_foc_control_variable(configuration->simulation_parametres->t, configuration->simulation_parametres->dt, Vbus, configuration->simulation_parametres->ia, configuration->simulation_parametres->ib, 0, (-configuration->simulation_parametres->torque / motor_model_parametre.Kt), configuration->simulation_parametres->angle);
va = foc_parametre.va;
vb = foc_parametre.vb;
vc = foc_parametre.vc;
}
update_motor_control_variable(configuration->simulation_parametres->t, configuration->simulation_parametres->dt, va, vb, vc, Torque, Inertia);
configuration->simulation_parametres->t += configuration->simulation_parametres->dt;
if (configuration->simulation_parametres->t)
{
configuration->simulation_parametres->velocity = 0.97 * configuration->simulation_parametres->velocity + 0.03 * ((motor_parametre.position - configuration->simulation_parametres->position) / (configuration->simulation_parametres->t - configuration->simulation_parametres->vel_t) * (30 / M_PI));
}
configuration->simulation_parametres->vel_t = configuration->simulation_parametres->t;
configuration->simulation_parametres->position = motor_parametre.position;
configuration->simulation_parametres->ia = motor_parametre.ia;
configuration->simulation_parametres->ib = motor_parametre.ib;
}
configuration->motor_state->time = configuration->simulation_parametres->t; // time of simulation in seconds
configuration->motor_state->va = va;
configuration->motor_state->vc = vb;
configuration->motor_state->vb = vc;
configuration->motor_state->rpm = configuration->simulation_parametres->velocity;
if (configuration->simulation_parametres->angleDeg <= 360) {
configuration->motor_state->pos = configuration->simulation_parametres->angleDeg;
}
else {
configuration->motor_state->pos = 360;
}// curent position
configuration->motor_state->torque = configuration->simulation_parametres->torque;
configuration->motor_state->iq = motor_parametre.iq;
configuration->motor_state->id = motor_parametre.id;
configuration->motor_state->calculated_stream_rate = configuration->simulation_parametres->calculated_stream_rate;
}
}
float max_num(float a, float b)
{
if (a < b)
{
return b;
}
return a;
}
float min_num(float a, float b)
{
if (a < b)
{
return a;
}
return b;
}
void change_controller_mode(conf_motor_simulation_control *configuration, controller mode ){
configuration->input_parametres->mode = mode;
}
void printf_current_input_value(int value, sliders_input_para para)
{
char *input_para = (char*) malloc(10 * sizeof(char));;
switch(para)
{
case vbus: strcpy(input_para, "vbus"); break;
case loadt: strcpy(input_para ,"loadt"); break;
case loadj: strcpy(input_para ,"loadj"); break;
case rpm_ref: strcpy(input_para, "rpm_ref"); break;
case pos_ref: strcpy(input_para ,"pos_ref"); break;
}
printf("The current input value for %s is: %d\n", input_para, value);
free(input_para);
}
|
gopherli/leetcode_go
|
jianzhi_offer/offer_39_test.go
|
package jianzhi_offer
import (
"log"
"testing"
)
func TestOffer39(t *testing.T) {
nums := []int{1, 2, 3, 2, 2, 2, 5, 4, 2}
mostNum := MajorityElement(nums)
log.Printf("数组%v最多的元素mostNum:%d", nums, mostNum)
}
|
PavanKishore21/probability
|
tensorflow_probability/python/internal/tensor_util.py
|
# Copyright 2018 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tools for processing Tensors."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.compat.v2 as tf
from tensorflow_probability.python.internal import dtype_util
from tensorflow_probability.python.internal import prefer_static
__all__ = [
'convert_nonref_to_tensor',
'discover_trainable_variables',
'discover_variables',
'identity_as_tensor',
'is_module',
'is_ref',
'is_trainable_variable',
'is_variable',
]
def convert_nonref_to_tensor(value, dtype=None, dtype_hint=None,
as_shape_tensor=False, name=None):
"""Converts the given `value` to a `Tensor` if input is nonreference type.
This function converts Python objects of various types to `Tensor` objects
only if the input has nonreference semantics. Reference semantics are
characterized by `tensor_util.is_ref` and is any object which is a
`tf.Variable` or instance of `tf.Module`. This function accepts any input
which `tf.convert_to_tensor` would also.
Note: This function diverges from default Numpy behavior for `float` and
`string` types when `None` is present in a Python list or scalar. Rather
than silently converting `None` values, an error will be thrown.
Args:
value: An object whose type has a registered `Tensor` conversion function.
dtype: Optional element type for the returned tensor. If missing, the
type is inferred from the type of `value`.
dtype_hint: Optional element type for the returned tensor,
used when dtype is None. In some cases, a caller may not have a
dtype in mind when converting to a tensor, so dtype_hint
can be used as a soft preference. If the conversion to
`dtype_hint` is not possible, this argument has no effect.
as_shape_tensor: Optional boolean when if `True` uses
`prefer_static.convert_to_shape_tensor` instead of `tf.convert_to_tensor`
for JAX compatibility.
name: Optional name to use if a new `Tensor` is created.
Returns:
tensor: A `Tensor` based on `value`.
Raises:
TypeError: If no conversion function is registered for `value` to `dtype`.
RuntimeError: If a registered conversion function returns an invalid value.
ValueError: If the `value` is a tensor not of given `dtype` in graph mode.
#### Examples:
```python
from tensorflow_probability.python.internal import tensor_util
x = tf.Variable(0.)
y = tensor_util.convert_nonref_to_tensor(x)
x is y
# ==> True
x = tf.constant(0.)
y = tensor_util.convert_nonref_to_tensor(x)
x is y
# ==> True
x = np.array(0.)
y = tensor_util.convert_nonref_to_tensor(x)
x is y
# ==> False
tf.is_tensor(y)
# ==> True
x = tfp.util.DeferredTensor(13.37, lambda x: x)
y = tensor_util.convert_nonref_to_tensor(x)
x is y
# ==> True
tf.is_tensor(y)
# ==> True
tf.equal(y, 13.37)
# ==> True
```
"""
# We explicitly do not use a tf.name_scope to avoid graph clutter.
if value is None:
return None
if is_ref(value):
if dtype is None:
return value
dtype_base = dtype_util.base_dtype(dtype)
value_dtype_base = dtype_util.base_dtype(value.dtype)
if dtype_base != value_dtype_base:
raise TypeError('Mutable type must be of dtype "{}" but is "{}".'.format(
dtype_util.name(dtype_base), dtype_util.name(value_dtype_base)))
return value
if as_shape_tensor:
return prefer_static.convert_to_shape_tensor(
value, dtype=dtype, dtype_hint=dtype_hint, name=name)
return tf.convert_to_tensor(
value, dtype=dtype, dtype_hint=dtype_hint, name=name)
def identity_as_tensor(value):
"""Converts `value` to `Tensor` while ensuring an op is added to the graph."""
t = tf.convert_to_tensor(value)
if t is value:
t = tf.identity(value)
return t
def is_ref(x):
"""Evaluates if the object has reference semantics.
An object is deemed "reference" if it is a `tf.Variable` instance or is
derived from a `tf.Module` with `dtype` and `shape` properties.
Args:
x: Any object.
Returns:
is_ref: Python `bool` indicating input is has nonreference semantics, i.e.,
is a `tf.Variable` or a `tf.Module` with `dtype` and `shape` properties.
"""
# TODO(b/134430874): Consider making this recurse through nests, e.g.,
# `tensor_util.is_ref([tf.Variable(0.), np.array(1.)])`
# returns True. Note: we'd need to actually create a tf.Module on user's
# behalf and it would need a `dtype` and `shape`. (I.e., there would be some
# work to support this.)
return (
is_variable(x) or
(is_module(x) and hasattr(x, 'dtype') and hasattr(x, 'shape'))
)
def is_variable(x):
"""Returns `True` when input is a `tf.Variable`, otherwise `False`."""
return isinstance(x, tf.Variable)
def is_trainable_variable(x):
"""Returns `True` when input is trainable `tf.Variable`, otherwise `False`."""
return is_variable(x) and getattr(x, 'trainable', False)
def is_module(x):
"""Returns `True` when input is a `tf.Module`, otherwise `False`."""
return isinstance(x, tf.Module)
class _Track(tf.Module):
"""Bridge to create functional interface for variable tracking."""
def __init__(self, *args, **kwargs):
self._args = args
self._kwargs = kwargs
def discover_trainable_variables(x):
"""Returns `tuple` of all trainable `tf.Variables` discoverable in input.
Warning: unlike possibly `tf.Module`, use of this function only does a static,
"one-time" discovery. (This is self-evidently true from its functional
nature.)
Args:
x: An object to inspected for `tf.Variable` dependencies.
Returns:
trainable_vars: A Python `tuple` of `tf.Variable`s with `trainable=True`.
"""
return _Track(x).trainable_variables
def discover_variables(x):
"""Returns `tuple` of all `tf.Variables` discoverable in input.
Warning: unlike possibly `tf.Module`, use of this function only does a static,
"one-time" discovery. (This is self-evidently true from its functional
nature.)
Args:
x: An object to inspected for `tf.Variable` dependencies.
Returns:
vars: A Python `tuple` of `tf.Variable`s, regardless of their value of
`trainable`.
"""
return _Track(x).variables
|
vakuum/gosu-lang-old
|
gosu-core-api/src/main/java/gw/lang/parser/IForwardingFunctionSymbol.java
|
/*
* Copyright 2013 <NAME>, Inc.
*/
package gw.lang.parser;
public interface IForwardingFunctionSymbol
{
}
|
dbsteward/dbsteward-go
|
lib/format/pgsql8/diff_views.go
|
<filename>lib/format/pgsql8/diff_views.go
package pgsql8
import (
"github.com/dbsteward/dbsteward/lib"
"github.com/dbsteward/dbsteward/lib/model"
"github.com/dbsteward/dbsteward/lib/output"
)
type DiffViews struct {
}
func NewDiffViews() *DiffViews {
return &DiffViews{}
}
// TODO(go,core) lift some of these to sql99
func (self *DiffViews) CreateViewsOrdered(ofs output.OutputFileSegmenter, oldDoc *model.Definition, newDoc *model.Definition) {
self.forEachViewInDepOrder(newDoc, func(newRef model.ViewRef) {
oldSchema := oldDoc.TryGetSchemaNamed(newRef.Schema.Name)
var oldView *model.View
if oldSchema != nil {
// TODO(go,nth) allow nil receivers in TryGet methods to alleviate branching
oldView = oldSchema.TryGetViewNamed(newRef.View.Name)
}
if self.shouldCreateView(oldView, newRef.View) {
ofs.WriteSql(GlobalView.GetCreationSql(newRef.Schema, newRef.View)...)
}
})
}
func (self *DiffViews) shouldCreateView(oldView, newView *model.View) bool {
return oldView == nil || lib.GlobalDBSteward.AlwaysRecreateViews || !oldView.Equals(newView, model.SqlFormatPgsql8)
}
func (self *DiffViews) DropViewsOrdered(ofs output.OutputFileSegmenter, oldDoc *model.Definition, newDoc *model.Definition) {
self.forEachViewInDepOrder(oldDoc, func(oldViewRef model.ViewRef) {
newSchema := newDoc.TryGetSchemaNamed(oldViewRef.Schema.Name)
newView := newSchema.TryGetViewNamed(oldViewRef.View.Name)
if self.shouldDropView(oldViewRef.View, newSchema, newView) {
ofs.WriteSql(GlobalView.GetDropSql(oldViewRef.Schema, oldViewRef.View)...)
}
})
}
func (self *DiffViews) shouldDropView(oldView *model.View, newSchema *model.Schema, newView *model.View) bool {
// don't drop the view if new_schema is null - we've already dropped the view by this point
// otherwise, drop if it changed or no longer exists
return newSchema != nil && !oldView.Equals(newView, model.SqlFormatPgsql8)
}
func (self *DiffViews) forEachViewInDepOrder(doc *model.Definition, callback func(model.ViewRef)) {
// TODO(go,3) unify this with XmlParser.TableDepOrder?
if doc == nil {
return
}
visited := map[model.ViewRef]bool{}
for _, rootSchema := range doc.Schemas {
for _, rootView := range rootSchema.Views {
ref := model.ViewRef{rootSchema, rootView}
if _, ok := visited[ref]; ok {
continue
}
self.dfsViewDeps(doc, ref, visited, callback)
}
}
}
func (self *DiffViews) dfsViewDeps(doc *model.Definition, ref model.ViewRef, visited map[model.ViewRef]bool, callback func(model.ViewRef)) {
if _, ok := visited[ref]; ok {
return
}
visited[ref] = true
for _, dep := range GlobalView.GetDependencies(doc, ref.Schema, ref.View) {
self.dfsViewDeps(doc, dep, visited, callback)
}
callback(ref)
}
|
javagossip/armeria
|
zipkin/src/test/java/com/linecorp/armeria/server/tracing/TracingServiceTest.java
|
/*
* Copyright 2016 LINE Corporation
*
* LINE Corporation 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 com.linecorp.armeria.server.tracing;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Test;
import org.mockito.ArgumentMatchers;
import com.github.kristofa.brave.Brave;
import com.github.kristofa.brave.KeyValueAnnotation;
import com.github.kristofa.brave.Sampler;
import com.github.kristofa.brave.SpanId;
import com.github.kristofa.brave.TraceData;
import com.linecorp.armeria.common.SessionProtocol;
import com.linecorp.armeria.common.logging.DefaultRequestLog;
import com.linecorp.armeria.common.logging.RequestLog;
import com.linecorp.armeria.common.thrift.ThriftCall;
import com.linecorp.armeria.common.thrift.ThriftReply;
import com.linecorp.armeria.common.tracing.HelloService;
import com.linecorp.armeria.common.tracing.SpanCollectingReporter;
import com.linecorp.armeria.server.Service;
import com.linecorp.armeria.server.ServiceRequestContext;
import io.netty.channel.Channel;
import zipkin.Annotation;
import zipkin.Span;
public class TracingServiceTest {
private static final String TEST_SERVICE = "test-service";
private static final String TEST_METHOD = "hello";
@Test
public void shouldSubmitSpanWhenRequestIsSampled() throws Exception {
SpanCollectingReporter reporter = testServiceInvocation(true /* sampled */);
// only one span should be submitted
assertThat(reporter.spans(), hasSize(1));
// check span name
Span span = reporter.spans().get(0);
assertThat(span.name, is(TEST_METHOD));
// check # of annotations
List<Annotation> annotations = span.annotations;
assertThat(annotations, hasSize(2));
// check annotation values
List<String> values = annotations.stream().map(anno -> anno.value).collect(Collectors.toList());
assertThat(values, is(containsInAnyOrder("sr", "ss")));
// check service name
List<String> serviceNames = annotations.stream()
.map(anno -> anno.endpoint.serviceName)
.collect(Collectors.toList());
assertThat(serviceNames, is(contains(TEST_SERVICE, TEST_SERVICE)));
}
@Test
public void shouldNotSubmitSpanWhenRequestIsNotSampled() throws Exception {
SpanCollectingReporter reporter = testServiceInvocation(false /* not sampled */);
// don't submit any spans
assertThat(reporter.spans(), hasSize(0));
}
private static SpanCollectingReporter testServiceInvocation(boolean sampled) throws Exception {
SpanCollectingReporter reporter = new SpanCollectingReporter();
Brave brave = new Brave.Builder(TEST_SERVICE)
.reporter(reporter)
.traceSampler(Sampler.create(1.0f))
.build();
@SuppressWarnings("unchecked")
Service<ThriftCall, ThriftReply> delegate = mock(Service.class);
TraceData traceData = TraceData.builder()
.sample(sampled)
.spanId(SpanId.builder().traceId(1).spanId(2).parentId(3L).build())
.build();
TracingServiceImpl stub = new TracingServiceImpl(delegate, brave, traceData);
ThriftCall req = new ThriftCall(0, HelloService.Iface.class, "hello", "trustin");
DefaultRequestLog reqLog = new DefaultRequestLog();
reqLog.start(mock(Channel.class), SessionProtocol.H2C, "localhost", TEST_METHOD, "/");
reqLog.end();
ServiceRequestContext ctx = mock(ServiceRequestContext.class);
// AbstractTracingService prefers RpcRequest.method() to ctx.method(), so "POST" should be ignored.
when(ctx.method()).thenReturn("POST");
when(ctx.requestLogFuture()).thenReturn(reqLog);
ctx.onEnter(ArgumentMatchers.isA(Runnable.class));
ctx.onExit(ArgumentMatchers.isA(Runnable.class));
ThriftReply res = new ThriftReply(0, "Hello, trustin!");
when(delegate.serve(ctx, req)).thenReturn(res);
// do invoke
stub.serve(ctx, req);
verify(delegate, times(1)).serve(eq(ctx), eq(req));
return reporter;
}
private static class TracingServiceImpl extends AbstractTracingService<ThriftCall, ThriftReply> {
private final TraceData traceData;
TracingServiceImpl(Service<ThriftCall, ThriftReply> delegate, Brave brave, TraceData traceData) {
super(delegate, brave);
this.traceData = traceData;
}
@Override
protected TraceData getTraceData(ServiceRequestContext ctx, ThriftCall req) {
return traceData;
}
@Override
protected List<KeyValueAnnotation> annotations(ServiceRequestContext ctx, RequestLog req,
ThriftReply res) {
return Collections.emptyList();
}
}
}
|
JasonSWFu/speechbrain
|
tests/unittests/test_checkpoints.py
|
import pytest
def test_checkpointer(tmpdir):
from speechbrain.utils.checkpoints import Checkpointer
import torch
class Recoverable(torch.nn.Module):
def __init__(self, param):
super().__init__()
self.param = torch.nn.Parameter(torch.tensor([param]))
def forward(self, x):
return x * self.param
recoverable = Recoverable(2.0)
recoverables = {"recoverable": recoverable}
recoverer = Checkpointer(tmpdir, recoverables)
recoverable.param.data = torch.tensor([1.0])
# Should not be possible since no checkpoint saved yet:
assert not recoverer.recover_if_possible()
result = recoverable(10.0)
# Check that parameter has not been loaded from original value:
assert recoverable.param.data == torch.tensor([1.0])
ckpt = recoverer.save_checkpoint()
# Check that the name recoverable has a save file:
# NOTE: Here assuming .pt filename; if convention changes, change test
assert (ckpt.path / "recoverable.ckpt").exists()
# Check that saved checkpoint is found, and location correct:
assert recoverer.list_checkpoints()[0] == ckpt
assert recoverer.list_checkpoints()[0].path.parent == tmpdir
recoverable.param.data = torch.tensor([2.0])
recoverer.recover_if_possible()
# Check that parameter has been loaded immediately:
assert recoverable.param.data == torch.tensor([1.0])
result = recoverable(10.0)
# And result correct
assert result == 10.0
other = Recoverable(2.0)
recoverer.add_recoverable("other", other)
# Check that both objects are now found:
assert recoverer.recoverables["recoverable"] == recoverable
assert recoverer.recoverables["other"] == other
new_ckpt = recoverer.save_checkpoint()
# Check that now both recoverables have a save file:
assert (new_ckpt.path / "recoverable.ckpt").exists()
assert (new_ckpt.path / "other.ckpt").exists()
assert new_ckpt in recoverer.list_checkpoints()
recoverable.param.data = torch.tensor([2.0])
other.param.data = torch.tensor([10.0])
chosen_ckpt = recoverer.recover_if_possible()
# Should choose newest by default:
assert chosen_ckpt == new_ckpt
# Check again that parameters have been loaded immediately:
assert recoverable.param.data == torch.tensor([1.0])
assert other.param.data == torch.tensor([2.0])
other_result = other(10.0)
# And again we should have the correct computations:
assert other_result == 20.0
# Recover from oldest, which does not have "other":
# This also tests a custom sort
# Raises by default:
with pytest.raises(RuntimeError):
chosen_ckpt = recoverer.recover_if_possible(
importance_key=lambda x: -x.meta["unixtime"]
)
# However this operation may have loaded the first object
# so let's set the values manually:
recoverable.param.data = torch.tensor([2.0])
other.param.data = torch.tensor([10.0])
recoverer.allow_partial_load = True
chosen_ckpt = recoverer.recover_if_possible(
importance_key=lambda x: -x.meta["unixtime"]
)
# Should have chosen the original:
assert chosen_ckpt == ckpt
# And should recover recoverable:
assert recoverable.param.data == torch.tensor([1.0])
# But not other:
other_result = other(10.0)
assert other.param.data == torch.tensor([10.0])
assert other_result == 100.0
# Test saving names checkpoints with meta info, and custom filter
epoch_ckpt = recoverer.save_checkpoint(name="ep1", meta={"loss": 2.0})
assert "ep1" in epoch_ckpt.path.name
other.param.data = torch.tensor([2.0])
recoverer.save_checkpoint(meta={"loss": 3.0})
chosen_ckpt = recoverer.recover_if_possible(
ckpt_predicate=lambda ckpt: "loss" in ckpt.meta,
importance_key=lambda ckpt: -ckpt.meta["loss"],
)
assert chosen_ckpt == epoch_ckpt
assert other.param.data == torch.tensor([10.0])
# Make sure checkpoints can't be name saved by the same name
with pytest.raises(FileExistsError):
recoverer.save_checkpoint(name="ep1")
def test_recovery_custom_io(tmpdir):
from speechbrain.utils.checkpoints import register_checkpoint_hooks
from speechbrain.utils.checkpoints import mark_as_saver
from speechbrain.utils.checkpoints import mark_as_loader
from speechbrain.utils.checkpoints import Checkpointer
@register_checkpoint_hooks
class CustomRecoverable:
def __init__(self, param):
self.param = int(param)
@mark_as_saver
def save(self, path):
with open(path, "w") as fo:
fo.write(str(self.param))
@mark_as_loader
def load(self, path, end_of_epoch, device):
del end_of_epoch # Unused
del device
with open(path) as fi:
self.param = int(fi.read())
custom_recoverable = CustomRecoverable(0)
recoverer = Checkpointer(tmpdir, {"custom_recoverable": custom_recoverable})
custom_recoverable.param = 1
# First, make sure no checkpoints are found
# (e.g. somehow tmpdir contaminated)
ckpt = recoverer.recover_if_possible()
assert ckpt is None
ckpt = recoverer.save_checkpoint()
custom_recoverable.param = 2
loaded_ckpt = recoverer.recover_if_possible()
# Make sure we got the same thing:
assert ckpt == loaded_ckpt
# With this custom recoverable, the load is instant:
assert custom_recoverable.param == 1
def test_checkpoint_deletion(tmpdir):
from speechbrain.utils.checkpoints import Checkpointer
import torch
class Recoverable(torch.nn.Module):
def __init__(self, param):
super().__init__()
self.param = torch.nn.Parameter(torch.tensor([param]))
def forward(self, x):
return x * self.param
recoverable = Recoverable(1.0)
recoverables = {"recoverable": recoverable}
recoverer = Checkpointer(tmpdir, recoverables)
first_ckpt = recoverer.save_checkpoint()
recoverer.delete_checkpoints()
# Will not delete only checkpoint by default:
assert first_ckpt in recoverer.list_checkpoints()
second_ckpt = recoverer.save_checkpoint()
recoverer.delete_checkpoints()
# Oldest checkpoint is deleted by default:
assert first_ckpt not in recoverer.list_checkpoints()
# Other syntax also should work:
recoverer.save_and_keep_only()
assert second_ckpt not in recoverer.list_checkpoints()
# Can delete all checkpoints:
recoverer.delete_checkpoints(num_to_keep=0)
assert not recoverer.list_checkpoints()
# Now each should be kept:
# Highest foo
c1 = recoverer.save_checkpoint(meta={"foo": 2})
# Latest CKPT after filtering
c2 = recoverer.save_checkpoint(meta={"foo": 1})
# Filtered out
c3 = recoverer.save_checkpoint(meta={"epoch_ckpt": True})
recoverer.delete_checkpoints(
num_to_keep=1,
max_keys=["foo"],
importance_keys=[lambda c: c.meta["unixtime"]],
ckpt_predicate=lambda c: "epoch_ckpt" not in c.meta,
)
assert all(c in recoverer.list_checkpoints() for c in [c1, c2, c3])
# Reset:
recoverer.delete_checkpoints(num_to_keep=0)
assert not recoverer.list_checkpoints()
# Test the keeping multiple checkpoints without predicate:
# This should be deleted:
c_to_delete = recoverer.save_checkpoint(meta={"foo": 2})
# Highest foo
c1 = recoverer.save_checkpoint(meta={"foo": 3})
# Latest CKPT after filtering
c2 = recoverer.save_checkpoint(meta={"foo": 1})
recoverer.delete_checkpoints(
num_to_keep=1,
importance_keys=[lambda c: c.meta["unixtime"], lambda c: c.meta["foo"]],
)
assert all(c in recoverer.list_checkpoints() for c in [c1, c2])
assert c_to_delete not in recoverer.list_checkpoints()
def test_multiple_ckpts_and_criteria(tmpdir):
from speechbrain.utils.checkpoints import Checkpointer
import torch
class Recoverable(torch.nn.Module):
def __init__(self, param):
super().__init__()
self.param = torch.nn.Parameter(torch.tensor([param]))
def forward(self, x):
return x * self.param
recoverable = Recoverable(1.0)
recoverables = {"recoverable": recoverable}
recoverer = Checkpointer(tmpdir, recoverables)
# Here testing multiple checkpoints with equal meta criteria
recoverer.save_and_keep_only(
meta={"error": 5}, min_keys=["error"], keep_recent=True
)
# By default, get the most recent one:
first_ckpt = recoverer.find_checkpoint()
recoverer.save_and_keep_only(
meta={"error": 5}, min_keys=["error"], keep_recent=True
)
second_ckpt = recoverer.find_checkpoint()
assert first_ckpt.meta["unixtime"] < second_ckpt.meta["unixtime"]
recoverer.save_and_keep_only(
meta={"error": 6}, min_keys=["error"], keep_recent=True
)
third_ckpt = recoverer.find_checkpoint()
remaining_ckpts = recoverer.list_checkpoints()
assert first_ckpt not in remaining_ckpts
assert second_ckpt in remaining_ckpts
assert third_ckpt in remaining_ckpts
# With equal importance criteria, the latest checkpoint should always be
# returned
fourth_ckpt = recoverer.save_checkpoint(meta={"error": 5})
found_ckpt = recoverer.find_checkpoint(min_key="error")
assert found_ckpt == fourth_ckpt
fifth_ckpt = recoverer.save_checkpoint(meta={"error": 5})
# Similarly for getting multiple checkpoints:
found_ckpts = recoverer.find_checkpoints(
min_key="error", max_num_checkpoints=2
)
assert found_ckpts == [fifth_ckpt, fourth_ckpt]
def test_torch_meta(tmpdir):
from speechbrain.utils.checkpoints import Checkpointer
import torch
class Recoverable(torch.nn.Module):
def __init__(self, param):
super().__init__()
self.param = torch.nn.Parameter(torch.tensor([param]))
def forward(self, x):
return x * self.param
recoverable = Recoverable(1.0)
recoverables = {"recoverable": recoverable}
recoverer = Checkpointer(tmpdir, recoverables)
saved = recoverer.save_checkpoint(
meta={"loss": torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0])}
)
loaded = recoverer.recover_if_possible()
assert saved.meta["loss"].allclose(loaded.meta["loss"])
def test_checkpoint_hook_register(tmpdir):
from speechbrain.utils.checkpoints import register_checkpoint_hooks
from speechbrain.utils.checkpoints import mark_as_saver
from speechbrain.utils.checkpoints import mark_as_loader
from speechbrain.utils.checkpoints import Checkpointer
# First a proper interface:
@register_checkpoint_hooks
class CustomRecoverable:
def __init__(self, param):
self.param = int(param)
@mark_as_saver
def save(self, path):
with open(path, "w") as fo:
fo.write(str(self.param))
@mark_as_loader
def load(self, path, end_of_epoch, device):
del end_of_epoch # Unused
with open(path) as fi:
self.param = int(fi.read())
recoverable = CustomRecoverable(1.0)
checkpointer = Checkpointer(tmpdir, {"recoverable": recoverable})
checkpointer.save_checkpoint()
recoverable.param = 2.0
checkpointer.recover_if_possible()
assert recoverable.param == 1.0
# Improper interfaces:
with pytest.raises(TypeError):
class BadRecoverable:
def __init__(self, param):
self.param = int(param)
def save(self, path):
with open(path, "w") as fo:
fo.write(str(self.param))
@mark_as_loader
def load(self, path, end_of_epoch): # MISSING device
del end_of_epoch # Unused
with open(path) as fi:
self.param = int(fi.read())
with pytest.raises(TypeError):
class BadRecoverable: # noqa: F811
def __init__(self, param):
self.param = int(param)
@mark_as_saver
def save(self, path, extra_arg): # Extra argument
with open(path, "w") as fo:
fo.write(str(self.param))
def load(self, path, end_of_epoch, device):
del end_of_epoch # Unused
with open(path) as fi:
self.param = int(fi.read())
|
COS301-SE-2021/GeoCode
|
backend/src/main/java/tech/geocodeapp/geocode/user/service/UserServiceImpl.java
|
<filename>backend/src/main/java/tech/geocodeapp/geocode/user/service/UserServiceImpl.java
package tech.geocodeapp.geocode.user.service;
import org.springframework.stereotype.Service;
import tech.geocodeapp.geocode.collectable.repository.CollectableRepository;
import tech.geocodeapp.geocode.collectable.request.CreateCollectableRequest;
import tech.geocodeapp.geocode.collectable.request.GetCollectableByIDRequest;
import tech.geocodeapp.geocode.collectable.service.CollectableService;
import tech.geocodeapp.geocode.general.CheckNullRequestParameters;
import tech.geocodeapp.geocode.general.exception.NullRequestParameterException;
import tech.geocodeapp.geocode.general.response.Response;
import tech.geocodeapp.geocode.general.security.CurrentUserDetails;
import tech.geocodeapp.geocode.leaderboard.repository.PointRepository;
import tech.geocodeapp.geocode.mission.request.GetMissionByIdRequest;
import tech.geocodeapp.geocode.mission.request.UpdateCompletionRequest;
import tech.geocodeapp.geocode.mission.service.MissionService;
import tech.geocodeapp.geocode.user.model.User;
import tech.geocodeapp.geocode.user.repository.UserRepository;
import tech.geocodeapp.geocode.user.request.*;
import tech.geocodeapp.geocode.user.response.*;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* This class implements the UserService interface
*/
@Service("UserService")
public class UserServiceImpl implements UserService {
private final UserRepository userRepo;
private final CollectableRepository collectableRepo;
private final PointRepository pointRepo;
@NotNull(message = "Collectable Service Implementation may not be null.")
private final CollectableService collectableService;
@NotNull(message = "Mission Service Implementation may not be null.")
private final MissionService missionService;
private final String invalidUserIdMessage = "Invalid User id";
private final UUID trackableTypeUUID = new UUID(0, 0);
private final CheckNullRequestParameters checkNullRequestParameters = new CheckNullRequestParameters();
public UserServiceImpl(UserRepository userRepo, CollectableRepository collectableRepo, PointRepository pointRepo, CollectableService collectableService, MissionService missionService) {
this.userRepo = userRepo;
this.collectableRepo = collectableRepo;
this.pointRepo = pointRepo;
this.collectableService = collectableService;
this.missionService = missionService;
}
/**
* Gets the Collectable that the User is currently holding
* @param request The GetCurrentCollectableRequest object
* @return A GetCurrentCollectableResponse object: (success, message, object)
*/
public GetCurrentCollectableResponse getCurrentCollectable(GetCurrentCollectableRequest request) throws NullRequestParameterException{
if (request == null) {
return new GetCurrentCollectableResponse(false, "The GetCurrentCollectableRequest object passed was NULL", null);
}
checkNullRequestParameters.checkRequestParameters(request);
var optionalUser = userRepo.findById(request.getUserID());
if(optionalUser.isEmpty()){
return new GetCurrentCollectableResponse(false, invalidUserIdMessage, null);
}
var currentUserCollectable = optionalUser.get().getCurrentCollectable();
return new GetCurrentCollectableResponse(true, "The user's Collectable was successfully returned", currentUserCollectable);
}
/**
* Gets the User's trackableObject
* @param request The GetUserTrackableRequest object
* @return A GetUserTrackableResponse object: (success, message, object)
*/
public GetUserTrackableResponse getUserTrackable(GetUserTrackableRequest request) throws NullRequestParameterException{
if (request == null) {
return new GetUserTrackableResponse(false, "The GetUserTrackableRequest object passed was NULL", null);
}
checkNullRequestParameters.checkRequestParameters(request);
var optionalUser = userRepo.findById(request.getUserID());
if(optionalUser.isEmpty()){
return new GetUserTrackableResponse(false, invalidUserIdMessage, null);
}
var userTrackable = optionalUser.get().getTrackableObject();
return new GetUserTrackableResponse(true, "The user's Trackable was successfully returned", userTrackable);
}
/**
* Updates the location of the User's trackable
* @param request The UpdateLocationRequest object
* @return A UpdateLocationResponse object: (success, message, object)
*/
public UpdateLocationResponse updateLocation(UpdateLocationRequest request) throws NullRequestParameterException {
if (request == null) {
return new UpdateLocationResponse(false, "The UpdateLocationRequest object passed was NULL", null);
}
checkNullRequestParameters.checkRequestParameters(request);
var optionalUser = userRepo.findById(request.getUserID());
if(optionalUser.isEmpty()){
return new UpdateLocationResponse(false, invalidUserIdMessage, null);
}
var currentUser = optionalUser.get();
var trackableObject = currentUser.getTrackableObject();
//update the trackable's location
trackableObject.changeLocation(request.getLocation());
collectableRepo.save(trackableObject);
return new UpdateLocationResponse(true, "The trackable object's location was successfully updated", trackableObject);
}
/**
* Gets the IDs of the CollectableTypes that the User has found so far
* @param request The GetFoundCollectableTypesRequest object
* @return A GetCollectableTypesResponse object: (success, message, object)
*/
public GetFoundCollectableTypesResponse getFoundCollectableTypes(GetFoundCollectableTypesRequest request) throws NullRequestParameterException{
if (request == null) {
return new GetFoundCollectableTypesResponse(false, "The GetFoundCollectableTypesRequest object passed was NULL", null);
}
checkNullRequestParameters.checkRequestParameters(request);
var optionalUser = userRepo.findById(request.getUserID());
if(optionalUser.isEmpty()){
return new GetFoundCollectableTypesResponse(false, invalidUserIdMessage, null);
}
//get IDs for all the found CollectableTypes for the current User
var currentUser = optionalUser.get();
var foundCollectableTypes = currentUser.getFoundCollectableTypes();
List<UUID> foundCollectableTypeIDs = new ArrayList<>();
foundCollectableTypes.forEach(collectableType -> foundCollectableTypeIDs.add(collectableType.getId()));
return new GetFoundCollectableTypesResponse(true, "The IDs of the User's found CollectableTypes was successfully returned", foundCollectableTypeIDs);
}
/**
* Gets the IDs of the GeoCodes that the User has found so far
* @param request The GetFoundGeoCodesRequest object
* @return A GetFoundGeoCodesResponse object: (success, message, object)
*/
public GetFoundGeoCodesResponse getFoundGeoCodes(GetFoundGeoCodesRequest request) throws NullRequestParameterException {
if (request == null) {
return new GetFoundGeoCodesResponse(false, "The GetFoundGeoCodesRequest object passed was NULL", null);
}
checkNullRequestParameters.checkRequestParameters(request);
var optionalUser = userRepo.findById(request.getUserID());
if(optionalUser.isEmpty()){
return new GetFoundGeoCodesResponse(false, invalidUserIdMessage, null);
}
//get IDs for all the found GeoCodes for the current User
var currentUser = optionalUser.get();
var foundGeoCodes = currentUser.getFoundGeocodes();
List<UUID> foundGeoCodeIDs = new ArrayList<>();
foundGeoCodes.forEach(foundGeoCode -> foundGeoCodeIDs.add(foundGeoCode.getId()));
return new GetFoundGeoCodesResponse(true, "The IDs of the User's found GeoCodes was successfully returned", foundGeoCodeIDs);
}
/**
* Gets the IDs of the GeoCodes that the User owns
* @param request The GetOwnedGeoCodesRequest object
* @return A GetOwnedGeoCodesResponse object: (success, message, object)
* @throws NullRequestParameterException Exception for 1 or more NULL parameters when making a User request
*/
public GetOwnedGeoCodesResponse getOwnedGeoCodes(GetOwnedGeoCodesRequest request) throws NullRequestParameterException {
if (request == null) {
return new GetOwnedGeoCodesResponse(false, "The GetOwnedGeoCodesRequest object passed was NULL", null);
}
checkNullRequestParameters.checkRequestParameters(request);
var optionalUser = userRepo.findById(request.getUserID());
if(optionalUser.isEmpty()){
return new GetOwnedGeoCodesResponse(false, invalidUserIdMessage, null);
}
//get IDs for all the GeoCodes owned by the current User
var currentUser = optionalUser.get();
var ownedGeocodes = currentUser.getOwnedGeocodes();
List<UUID> ownedGeoCodeIDs = new ArrayList<>();
ownedGeocodes.forEach(ownedGeocode -> ownedGeoCodeIDs.add(ownedGeocode.getId()));
return new GetOwnedGeoCodesResponse(true, "The IDs of the User's owned GeoCodes was successfully returned", ownedGeoCodeIDs);
}
/**
* Gets the Leaderboard details for all Leaderboards that a given User is on
* @param request The GetMyLeaderboardsRequest object
* @return A GetMyLeaderboardsResponse object: (success, message, object)
* @throws NullRequestParameterException Exception for 1 or more NULL parameters when making a User request
*/
public GetMyLeaderboardsResponse getMyLeaderboards(GetMyLeaderboardsRequest request) throws NullRequestParameterException{
if (request == null) {
return new GetMyLeaderboardsResponse(false, "The GetMyLeaderboardsRequest object passed was NULL", null);
}
checkNullRequestParameters.checkRequestParameters(request);
/* check if user ID is invalid */
var optionalUser = userRepo.findById(request.getUserID());
if(optionalUser.isEmpty()){
return new GetMyLeaderboardsResponse(false, invalidUserIdMessage, null);
}
var currentUser = optionalUser.get();
var leaderboardDetailsList = pointRepo.getMyLeaderboards(currentUser.getId());
return new GetMyLeaderboardsResponse(true, "The details for the User's Leaderboards were successfully returned", leaderboardDetailsList);
}
/**
* Gets the User's Missions
* @param request GetMyMissionsRequest object
* @return GetMyMissionsResponse object
*/
public GetMyMissionsResponse getMyMissions(GetMyMissionsRequest request) throws NullRequestParameterException {
if(request == null){
return new GetMyMissionsResponse(false, "The GetMyMissionsRequest object passed was NULL", null);
}
checkNullRequestParameters.checkRequestParameters(request);
//check if the UserID is invalid
var optionalUser = userRepo.findById(request.getUserID());
if(optionalUser.isEmpty()){
return new GetMyMissionsResponse(false, invalidUserIdMessage, null);
}
var user = optionalUser.get();
return new GetMyMissionsResponse(true, "User Missions returned", user.getMissions());
}
/**
* Adds the given GeoCode to the User's list of Owned GeoCodes
* @param request AddToOwnedGeoCodesRequest object
* @return AddToOwnedGeoCodesResponse object
*/
public AddToOwnedGeoCodesResponse addToOwnedGeoCodes(AddToOwnedGeoCodesRequest request) throws NullRequestParameterException{
if(request == null){
return new AddToOwnedGeoCodesResponse(false, "The AddToOwnedGeoCodesRequest object passed was NULL");
}
checkNullRequestParameters.checkRequestParameters(request);
//add the GeoCodeID to the User's list of owned GeoCodes
var user = request.getUser();
var geoCode = request.getGeocode();
user.addOwnedGeocodesItem(geoCode);
userRepo.save(user);
return new AddToOwnedGeoCodesResponse(true, "GeoCode added to the owned GeoCodes");
}
/**
* Adds the given GeoCode to the User's list of Found GeoCodes
* @param request AddToFoundGeoCodesRequest object
* @return AddToFoundGeoCodesResponse object
*/
public AddToFoundGeoCodesResponse addToFoundGeoCodes(AddToFoundGeoCodesRequest request) throws NullRequestParameterException{
if(request == null){
return new AddToFoundGeoCodesResponse(false, "The AddToFoundGeoCodesRequest object passed was NULL");
}
checkNullRequestParameters.checkRequestParameters(request);
var user = request.getUser();
var geoCode = request.getGeocode();
//add the GeoCodeID to the User's list of owned GeoCodes
user.addFoundGeocodesItem(geoCode);
userRepo.save(user);
return new AddToFoundGeoCodesResponse(true, "GeoCode added to the found GeoCodes");
}
/**
* Adds the CollectableType to the User's found CollectableTypes list
* @param request AddToFoundCollectableTypesRequest object
* @return AddToFoundCollectableTypesResponse object
*/
public AddToFoundCollectableTypesResponse addToFoundCollectableTypes(AddToFoundCollectableTypesRequest request) throws NullRequestParameterException{
if(request == null){
return new AddToFoundCollectableTypesResponse(false, "The AddToFoundCollectableTypesRequest object passed was NULL");
}
checkNullRequestParameters.checkRequestParameters(request);
var collectableType = request.getCollectableType();
var user = request.getUser();
user.addFoundCollectableTypesItem(collectableType);
userRepo.save(user);
return new AddToFoundCollectableTypesResponse(true, "CollectableType added to the found CollectableTypes");
}
/**
* Gets the User for the given id if they exist
* @param request The GetUserByIdRequest object
* @return The User if they exist, else NULL contained in a GetUserByIdResponse object
*/
public GetUserByIdResponse getUserById(GetUserByIdRequest request) throws NullRequestParameterException {
if(request == null){
return new GetUserByIdResponse(false, "The GetUserByIdRequest object passed was NULL", null);
}
checkNullRequestParameters.checkRequestParameters(request);
var id = request.getUserID();
var optionalUser = userRepo.findById(id);
return optionalUser.map(user -> new GetUserByIdResponse(true, "The User was found", user)).orElseGet(
() -> new GetUserByIdResponse(false, invalidUserIdMessage, null));
}
/**
* Gets the current User using the Keycloak details
* @return The current User
*/
public User getCurrentUser(){
/* make request to get the current User*/
var request = new GetUserByIdRequest(CurrentUserDetails.getID());
try {
return getUserById(request).getUser();
} catch(NullRequestParameterException e){
return null;
}
}
/**
* @deprecated use CurrentUserDetails.getID()
* Gets the current user ID using the Keycloak details
* @return The current user ID
*/
public UUID getCurrentUserID(){
return CurrentUserDetails.getID();
}
/**
* Registers a new user
* @param request The id for the User
*/
public Response handleLogin(HandleLoginRequest request) throws NullRequestParameterException{
if(request == null){
return new Response(false, "The HandleLoginRequest object passed was NULL");
}
checkNullRequestParameters.checkRequestParameters(request);
//check if the User already exists
boolean exists = userRepo.existsById(CurrentUserDetails.getID());
if(exists){
return new Response(true, "User ID already exists");
}
//the User is a new User
var newUser = new User(CurrentUserDetails.getID(), CurrentUserDetails.getUsername());
// In case a new user has the same username as an existing user
// This should only happen if the existing user has deleted their Keycloak account
var oldUser = userRepo.findByUsernameIgnoreCase(newUser.getUsername());
if (oldUser != null && !oldUser.getId().equals(newUser.getId())) {
// Rename the old user
var newUsername = "DeletedUser"+oldUser.getId();
oldUser.setUsername(newUsername);
userRepo.save(oldUser);
}
//create the user's trackable object which will always have a Mission
var createCollectableRequest = new CreateCollectableRequest(trackableTypeUUID, request.getLocation());
var createCollectableResponse = collectableService.createCollectable(createCollectableRequest);
if(!createCollectableResponse.isSuccess()){
return new Response(false, createCollectableResponse.getMessage());
}
var collectableResponse = createCollectableResponse.getCollectable();
//get the trackable object
var getCollectableIdRequest = new GetCollectableByIDRequest(collectableResponse.getId());
var getCollectableByIDResponse = collectableService.getCollectableByID(getCollectableIdRequest);
var trackableObject = getCollectableByIDResponse.getCollectable();
newUser.setTrackableObject(trackableObject);
newUser.setCurrentCollectable(trackableObject);
//add trackable object's Mission to the User's Missions
var getMissionByIDRequest = new GetMissionByIdRequest(trackableObject.getMissionID());
var mission = missionService.getMissionById(getMissionByIDRequest).getMission();
this.addToMyMissions(new AddToMyMissionsRequest(newUser, mission));
/* check that the new User was successfully saved */
var check = userRepo.save(newUser);
if(!newUser.equals(check)){
return new Response(false, "New User registration failed");
}
return new Response(true, "New User registered");
}
//GeoCode helper functions
/**
* Swaps the currentCollectable of the current user with the given Collectable
* @param request The UUID identifying the Collectable to swap with the currentCollectable
* @return The original currentCollectable
*/
public SwapCollectableResponse swapCollectable( SwapCollectableRequest request ) throws NullRequestParameterException {
if(request == null){
return new SwapCollectableResponse(false, "The SwapCollectableRequest object passed was NULL", null);
}
checkNullRequestParameters.checkRequestParameters(request);
var user = request.getUser();
var geoCode = request.getGeoCode();
//swap out the currentCollectable
var oldCurrentCollectable = user.getCurrentCollectable();
var newCurrentCollectable = request.getCollectable();
user.setCurrentCollectable(newCurrentCollectable);
//add the GeoCode to the User's found GeoCodes
this.addToFoundGeoCodes(new AddToFoundGeoCodesRequest(user, geoCode));
//add the CollectableType to the User's found CollectableTypes
this.addToFoundCollectableTypes(new AddToFoundCollectableTypesRequest(user, newCurrentCollectable.getType()));
//add the Collectable's Mission to the User's Missions
var newCurrentCollectableMissionID = newCurrentCollectable.getMissionID();
if(newCurrentCollectableMissionID != null){
var newCurrentCollectableMission = missionService.getMissionById(new GetMissionByIdRequest(newCurrentCollectableMissionID)).getMission();
this.addToMyMissions(new AddToMyMissionsRequest(user, newCurrentCollectableMission));
}else{
//save() called in addToMyMissions
userRepo.save(user);
}
var oldCurrentCollectableMissionID = oldCurrentCollectable.getMissionID();
if(oldCurrentCollectableMissionID != null){
var oldCurrentCollectableMission = missionService.getMissionById(new GetMissionByIdRequest(oldCurrentCollectableMissionID)).getMission();
//update the completion of the Mission
var updateCompletionRequest = new UpdateCompletionRequest(oldCurrentCollectableMission, geoCode.getLocation());
missionService.updateCompletion(updateCompletionRequest);
}
return new SwapCollectableResponse(true, "The User's Collectable was swapped with the Collectable in the GeoCode", oldCurrentCollectable );
}
/**
* Add the given Mission to the User's list of missions
* @param request AddToMyMissionsRequest object
* @return AddToMyMissionsResponse object
*/
public AddToMyMissionsResponse addToMyMissions(AddToMyMissionsRequest request) throws NullRequestParameterException {
if(request == null){
return new AddToMyMissionsResponse(false, "The AddToMyMissionsRequest object passed was NULL");
}
checkNullRequestParameters.checkRequestParameters(request);
var user = request.getUser();
var mission = request.getMission();
user.addMissionsItem(mission);
userRepo.save(user);
return new AddToMyMissionsResponse(true, "Mission added to the User's Missions");
}
}
|
mynameisrufus/wedviteapp
|
app/validators/wedding_wording_validator.rb
|
<filename>app/validators/wedding_wording_validator.rb
class WeddingWordingValidator < ActiveModel::Validator
def validate record
wording = record.send(options[:attribute])
record.errors[options[:attribute]] << error_message unless
test wording, guest_tag_test
end
def test wording, test
!(wording =~ test).nil?
end
def guest_tag_test
/{{(\s|)guest.name(\s|)}}/
end
def error_message
<<EOL
Your invitation has lost it's tag for the guests name! ake sure you have this tag in your invitation:
<code>
{{ guest.name }}
</code>
EOL
end
end
|
talsewell/cerberus
|
tests/gcc-torture/breakdown/not_supported/simd/pr65427.c
|
#include "cerberus.h"
/* PR tree-optimization/65427 */
typedef int V __attribute__ ((vector_size (8 * sizeof (int))));
V a, b, c, d, e, f;
__attribute__((noinline, noclone)) void
foo (int x, int y)
{
do
{
if (x)
d = a ^ c;
else
d = a ^ b;
}
while (y);
}
int
main ()
{
a = (V) { 1, 2, 3, 4, 5, 6, 7, 8 };
b = (V) { 0x40, 0x80, 0x40, 0x80, 0x40, 0x80, 0x40, 0x80 };
e = (V) { 0x41, 0x82, 0x43, 0x84, 0x45, 0x86, 0x47, 0x88 };
foo (0, 0);
if (__builtin_memcmp (&d, &e, sizeof (V)) != 0)
__builtin_abort ();
c = (V) { 0x80, 0x40, 0x80, 0x40, 0x80, 0x40, 0x80, 0x40 };
f = (V) { 0x81, 0x42, 0x83, 0x44, 0x85, 0x46, 0x87, 0x48 };
foo (1, 0);
if (__builtin_memcmp (&d, &f, sizeof (V)) != 0)
__builtin_abort ();
return 0;
}
|
ytree-project/ytree
|
ytree/data_structures/save_arbor.py
|
<filename>ytree/data_structures/save_arbor.py
"""
save_arbor supporting functions
"""
import json
import numpy as np
import os
import types
from unyt import uconcatenate
from yt.frontends.ytdata.utilities import save_as_dataset
from ytree.utilities.io import ensure_dir
from ytree.utilities.logger import ytreeLogger as mylog
#-----------------------------------------------------------------------------
# Copyright (c) ytree development team. All rights reserved.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
def save_arbor(arbor, filename=None, fields=None, trees=None,
max_file_size=524288):
"""
Save the arbor to a file.
This is the internal function called by Arbor.save_arbor.
"""
if isinstance(trees, types.GeneratorType):
trees = list(trees)
arbor._plant_trees()
update, filename = determine_save_state(
arbor, filename, fields, trees)
filename = determine_output_filename(filename, ".h5")
fields = determine_field_list(arbor, fields, update)
if not fields:
mylog.warning(
"No action will be taken for the following reasons:\n"
" - This dataset is already a YTreeArbor.\n"
" - No filename has been given.\n"
" - No new analysis fields have been created.\n"
" - No custom list of trees has been provided.")
return None
group_nnodes, group_ntrees, root_field_data = \
save_data_files(arbor, filename, fields, trees,
max_file_size, update)
header_filename = save_header_file(
arbor, filename, fields, root_field_data,
group_nnodes, group_ntrees)
return header_filename
def determine_save_state(arbor, filename, fields, trees):
"""
Determine if we can just output new analysis fields to
sidecar files and skip saving the rest.
If updating return filenames associated with currently loaded arbor.
"""
from ytree.frontends.ytree.arbor import YTreeArbor
if not isinstance(arbor, YTreeArbor):
return False, filename
if filename is not None:
return False, filename
if fields not in [None, "all"]:
return False, filename
if trees is not None and len(trees) != arbor.size:
return False, filename
return True, arbor.parameter_filename
def determine_output_filename(path, suffix):
"""
Figure out the output filename.
"""
if path is None:
path = 'arbor'
if path.endswith(suffix):
dirname = os.path.dirname(path)
filename = path[:-len(suffix)]
else:
dirname = path
filename = os.path.join(
dirname, os.path.basename(path))
ensure_dir(dirname)
return filename
def determine_field_list(arbor, fields, update):
"""
Get the list of fields to be saved.
"""
if fields in [None, "all"]:
# If this is an update, don't resave disk fields.
field_list = arbor.analysis_field_list.copy()
# Add in previously saved analysis fields
if update:
field_list.extend(
[field for field in arbor.field_list
if arbor.field_info[field].get("type") == "analysis_saved"])
else:
field_list.extend(arbor.field_list)
# If a field has an alias, get that instead.
fields = []
for field in field_list:
fields.extend(
arbor.field_info[field].get("aliases", [field]))
else:
fields.extend([f for f in ["uid", "desc_uid"]
if f not in fields])
return fields
def get_output_fieldnames(fields):
"""
Get filenames as they will be written to disk.
"""
return [field.replace("/", "_") for field in fields]
def save_data_files(arbor, filename, fields, trees,
max_file_size, update):
"""
Write all data files by grouping trees together.
Return arrays of number of nodes and trees written to each file
as well as a dictionary of root fields.
If update is True, use the file layout of the arbor instead of
calculating from max_file_size.
"""
if trees is None:
trees = arbor._yield_root_nodes(range(arbor.size))
save_size = arbor.size
else:
save_size = len(trees)
root_field_data = dict((field, []) for field in fields)
group_nnodes = []
group_ntrees = []
current_group = []
cg_nnodes = 0
cg_ntrees = 0
def my_save(cg_number, cg_nnodes, cg_ntrees):
group_nnodes.append(cg_nnodes)
group_ntrees.append(cg_ntrees)
total_guess = int(np.round(save_size * cg_number / sum(group_ntrees)))
save_data_file(
arbor, filename, fields,
np.array(current_group), root_field_data,
cg_number, total_guess)
if update:
file_sizes = np.diff(arbor._node_io._ei, prepend=0)
i = 1
for tree in trees:
current_group.append(tree)
cg_nnodes += tree.tree_size
cg_ntrees += 1
# if updating, use file sizes of loaded arbor
if (update and len(current_group) == file_sizes[i-1]) or \
cg_nnodes > max_file_size:
my_save(i, cg_nnodes, cg_ntrees)
current_group = []
cg_nnodes = 0
cg_ntrees = 0
i += 1
if current_group:
my_save(i, cg_nnodes, cg_ntrees)
group_nnodes = np.array(group_nnodes)
group_ntrees = np.array(group_ntrees)
return group_nnodes, group_ntrees, root_field_data
def save_data_file(arbor, filename, fields, tree_group,
root_field_data,
current_iteration, total_guess):
"""
Write data file for a single group of trees.
"""
fieldnames = get_output_fieldnames(fields)
arbor._node_io_loop(
arbor._node_io.get_fields,
pbar=f"Getting fields [{current_iteration} / ~{total_guess}]",
root_nodes=tree_group, fields=fields, root_only=False)
main_fdata = {}
main_ftypes = {}
analysis_fdata = {}
analysis_ftypes = {}
my_tree_size = np.array([tree.tree_size for tree in tree_group])
my_tree_end = my_tree_size.cumsum()
my_tree_start = my_tree_end - my_tree_size
for field, fieldname in zip(fields, fieldnames):
fi = arbor.field_info[field]
if fi.get("type") in ["analysis", "analysis_saved"]:
my_fdata = analysis_fdata
my_ftypes = analysis_ftypes
else:
my_fdata = main_fdata
my_ftypes = main_ftypes
my_ftypes[fieldname] = "data"
my_fdata[fieldname] = uconcatenate(
[node.field_data[field] if node.is_root else node["tree", field]
for node in tree_group])
root_field_data[field].append(my_fdata[fieldname][my_tree_start])
# In case we have saved any non-root trees,
# mark them as having no descendents.
if "desc_uid" in main_fdata:
main_fdata["desc_uid"][my_tree_start] = -1
for node in tree_group:
arbor.reset_node(node)
if main_fdata:
main_fdata["tree_start_index"] = my_tree_start
main_fdata["tree_end_index"] = my_tree_end
main_fdata["tree_size"] = my_tree_size
for ft in ["tree_start_index",
"tree_end_index",
"tree_size"]:
main_ftypes[ft] = "index"
my_filename = f"{filename}_{current_iteration-1:04d}.h5"
save_as_dataset({}, my_filename, main_fdata,
field_types=main_ftypes)
if analysis_fdata:
my_filename = f"{filename}_{current_iteration-1:04d}-analysis.h5"
save_as_dataset({}, my_filename, analysis_fdata,
field_types=analysis_ftypes)
def save_header_file(arbor, filename, fields, root_field_data,
group_nnodes, group_ntrees):
"""
Write the header file.
"""
ds = {}
for attr in ["hubble_constant",
"omega_matter",
"omega_lambda"]:
if getattr(arbor, attr, None) is not None:
ds[attr] = getattr(arbor, attr)
# Data structures for disk fields.
main_fi = {}
main_rdata = {}
main_rtypes = {}
# Analysis fields saved separately.
analysis_fi = {}
analysis_rdata = {}
analysis_rtypes = {}
fieldnames = get_output_fieldnames(fields)
for field, fieldname in zip(fields, fieldnames):
fi = arbor.field_info[field]
if fi.get("type") in ["analysis", "analysis_saved"]:
my_fi = analysis_fi
my_rdata = analysis_rdata
my_rtypes = analysis_rtypes
else:
my_fi = main_fi
my_rdata = main_rdata
my_rtypes = main_rtypes
my_fi[fieldname] = \
dict((key, fi[key])
for key in ["units", "description"]
if key in fi)
my_rdata[fieldname] = uconcatenate(root_field_data[field])
my_rtypes[fieldname] = "data"
# all saved trees will be roots
if "desc_uid" in main_rdata:
main_rdata["desc_uid"][:] = -1
# Save the primary fields.
header_filename = f"{filename}.h5"
if main_fi:
tree_end_index = group_ntrees.cumsum()
tree_start_index = tree_end_index - group_ntrees
extra_attrs = {
"arbor_type": "YTreeArbor",
"unit_registry_json": arbor.unit_registry.to_json(),
"unit_system_name": arbor.unit_registry.unit_system.name}
if arbor.box_size is not None:
extra_attrs["box_size"] = arbor.box_size
extra_attrs["field_info"] = json.dumps(main_fi)
extra_attrs["total_files"] = group_nnodes.size
extra_attrs["total_trees"] = group_ntrees.sum()
extra_attrs["total_nodes"] = group_nnodes.sum()
hdata = {"tree_start_index": tree_start_index,
"tree_end_index" : tree_end_index,
"tree_size" : group_ntrees}
hdata.update(main_rdata)
del main_rdata
htypes = dict((f, "index") for f in hdata)
htypes.update(main_rtypes)
save_as_dataset(ds, header_filename, hdata,
field_types=htypes,
extra_attrs=extra_attrs)
del hdata
# Save analysis fields to a sidecar file.
if analysis_fi:
extra_attrs = {}
extra_attrs["field_info"] = json.dumps(analysis_fi)
hdata = analysis_rdata
del analysis_rdata
htypes = dict((f, "index") for f in hdata)
htypes.update(analysis_rtypes)
analysis_header_filename = f"{filename}-analysis.h5"
save_as_dataset(ds, analysis_header_filename, hdata,
field_types=htypes,
extra_attrs=extra_attrs)
del hdata
return header_filename
|
google-ar/chromium
|
chrome/browser/browsing_data/cache_counter.cc
|
<reponame>google-ar/chromium<filename>chrome/browser/browsing_data/cache_counter.cc<gh_stars>100-1000
// Copyright (c) 2015 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 "chrome/browser/browsing_data/cache_counter.h"
#include "chrome/browser/profiles/profile.h"
#include "components/browsing_data/content/conditional_cache_counting_helper.h"
#include "components/browsing_data/core/pref_names.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/net_errors.h"
CacheCounter::CacheResult::CacheResult(const CacheCounter* source,
int64_t cache_size,
bool is_upper_limit)
: FinishedResult(source, cache_size),
cache_size_(cache_size),
is_upper_limit_(is_upper_limit) {}
CacheCounter::CacheResult::~CacheResult() {}
CacheCounter::CacheCounter(Profile* profile)
: profile_(profile),
weak_ptr_factory_(this) {}
CacheCounter::~CacheCounter() {
}
const char* CacheCounter::GetPrefName() const {
return browsing_data::prefs::kDeleteCache;
}
void CacheCounter::Count() {
base::WeakPtr<browsing_data::ConditionalCacheCountingHelper> counter =
browsing_data::ConditionalCacheCountingHelper::CreateForRange(
content::BrowserContext::GetDefaultStoragePartition(profile_),
GetPeriodStart(), base::Time::Max())
->CountAndDestroySelfWhenFinished(
base::Bind(&CacheCounter::OnCacheSizeCalculated,
weak_ptr_factory_.GetWeakPtr()));
}
void CacheCounter::OnCacheSizeCalculated(int64_t result_bytes,
bool is_upper_limit) {
// A value less than 0 means a net error code.
if (result_bytes < 0)
return;
auto result =
base::MakeUnique<CacheResult>(this, result_bytes, is_upper_limit);
ReportResult(std::move(result));
}
|
OscarRPR/samurai-reborn
|
ModelingProject1/SourceCode/Input/Player/Controller.h
|
<reponame>OscarRPR/samurai-reborn<gh_stars>1-10
#pragma once
#include <GameInputContext.h>
#include <RawInputConstants.h>
#include <GameInputStructs.h>
namespace InputMapping
{
class Controller
{
public:
Controller(){};
~Controller();
int getPlayerID() { return playerID; }
void setPlayerID(int id) { playerID = id; }
int getTypeController() { return typeController; }
virtual bool isEnabled() { return enabled; }
void setIsEnabled(bool enabled) { this->enabled = enabled; }
std::string getFileContextList() { return filenameContext; }
std::list<Key>* getListKeys() { return &keys; }
std::map<RawInputButton, GameCoreStates::SpriteState>* getStateMap() { return &stateMap; }
void initializeKeys(std::list<Key> listKeys, std::map<RawInputButton, GameCoreStates::SpriteState> mapKeys,
std::map<RawInputButton, GameCoreStates::Action> actionKeys);
void setWasPreviouslyPressedAllKeys();
Key& getKeyAssociatedToState(int state, int directionX = 0);
void setRawButtonState(Key key, MappedInput& inputs);
bool checkIfCanCleanStateVector(MappedInput& inputs);
void countAndClearStates(MappedInput& inputs);
int countStatesInMapper(MappedInput& inputs, int state);
bool verifyDoubleTappingForJumping(MappedInput& inputs, GameCoreStates::SpriteState state);
void pushBackNewState(MappedInput& inputs, int state, int valueButton);
virtual void parseRawInput(Key& key, MappedInput& inputs){};
virtual Key getKeyDirectionX(int directionX){ return Key(); }
virtual void updateStateKeys(MappedInput& inputs){};
private:
bool mapButtonToAction(RawInputButton button, GameCoreStates::Action& out) const;
bool mapButtonToState(RawInputButton button, GameCoreStates::SpriteState& state) const;
protected:
Controller(int id);
int playerID, typeController;
bool enabled;
std::string filenameContext;
std::list<Key> keys;
std::map<RawInputButton, GameCoreStates::SpriteState> stateMap;
std::map<RawInputButton, GameCoreStates::Action> actionMap;
};
}
|
KnowingNothing/akg-test
|
src/pass/math_intrin_rewrite.cc
|
/**
* Copyright 2019-2021 Huawei Technologies Co., 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.
*/
#include <tvm/ir.h>
#include <tvm/expr.h>
#include <tvm/ir_mutator.h>
#include <tvm/ir_pass.h>
#include <cmath>
#include "pass/utils.h"
#include "pass/rewrite_simplify_cce.h"
namespace akg {
namespace ir {
class TensorOperandFinder : public IRVisitor {
public:
bool Find(const Expr &e) {
Visit(e);
return find_;
}
void Visit_(const Call *op) override {
if (op->func.as<OperationNode>()) {
find_ = true;
}
IRVisitor::Visit_(op);
}
private:
bool find_{false};
};
class DivRewriter : public IRMutator {
public:
Expr Mutate_(const Div *op, const Expr &e) final {
const std::string productName = GetProductName();
// In mini need mutate div to rec
if (productName != "cloud") {
if (op->b.type().is_float()) {
auto it =
std::find_if(cache_.begin(), cache_.end(), [&](const std::pair<Expr, Expr> &i) { return Equal(e, i.first); });
if (it != cache_.end()) {
return (*it).second;
}
// rewrite division to vrec intrinsic
// a / b -> a * (vrec(b))
auto new_e = Simplify_cce(Mul::make(
Mutate(op->a), Call::make(op->type, "rec", Array<Expr>{Mutate(op->b)}, Call::CallType::PureIntrinsic)));
cache_.Set(e, new_e);
return new_e;
}
}
return IRMutator::Mutate_(op, e);
}
private:
Map<Expr, Expr> cache_;
};
class RecRewriter : public IRMutator {
public:
Expr Mutate_(const Call *op, const Expr &e) final {
if (op->name == "rec" && op->args.size() == 1) {
// rewrite division to vrec intrinsic
// rec(4) -> 1/4
CHECK(isZero(op->args[0]) == false) << " Invalid expression! div 0 error ";
if (isImm(op->args[0])) {
return Simplify_cce(1 / op->args[0]);
}
}
return IRMutator::Mutate_(op, e);
}
};
// rewrite rsqrt to 1 / sqrt intrinsic on cloud
// rsqrt(data) -> 1 / sqrt(data)
class RsqrtRewriter : public IRMutator {
public:
Expr Mutate_(const Call *op, const Expr &e) final {
const std::string productName = GetProductName();
if (productName == "cloud" && op->name == "rsqrt" && op->args.size() == 1) {
CHECK(isZero(op->args[0]) == false) << " Invalid expression! div 0 error ";
return Simplify_cce(1 / Call::make(op->type, "sqrt", op->args, Call::CallType::PureIntrinsic));
}
return IRMutator::Mutate_(op, e);
}
};
// float(floor(A[i])) --> floor(A[i]) when type(floor) = float
class RmCast : public IRMutator {
public:
Expr Mutate_(const Cast *op, const Expr &e) final {
Expr cast = IRMutator::Mutate_(op, e);
const Cast *ca = cast.as<Cast>();
CHECK(ca);
if (const Cast *cast_ca = ca->value.as<Cast>()) {
if (cast_ca->type == op->type) {
return ca->value;
}
}
return cast;
}
};
// a*b if(a==0 || b==0) return 0;
class MulZeroOpt : public IRMutator {
public:
Expr Mutate_(const Mul *op, const Expr &e) final {
if (isZero(op->a)) return op->a;
if (isZero(op->b)) return op->b;
return IRMutator::Mutate_(op, e);
}
};
// pow(A, B) --> exp(log(|A|)*B)
// if A is negative and B is odd, the result need to multiply -1
class PowRewriter : public IRMutator {
public:
Expr Mutate_(const Call *op, const Expr &e) final {
if (op->name == "pow") {
if (op->args[0].as<FloatImm>() && op->args[1].as<FloatImm>()) {
return FloatImm::make(op->args[0].as<FloatImm>()->type,
pow(op->args[0].as<FloatImm>()->value, op->args[1].as<FloatImm>()->value));
}
if (isZero(Mutate(op->args[0]))) {
return FloatImm::make(op->type, 1.0);
}
auto dtype = e.type();
auto a = Mutate(op->args[0]);
auto b = Mutate(op->args[1]);
auto a_abs = Call::make(dtype, "fabs", {a}, Call::PureIntrinsic);
auto exp_log_value = Call::make(
dtype, "exp", {Mul::make(Call::make(dtype, "log", {a_abs}, Call::PureIntrinsic), b)}, Call::PureIntrinsic);
// For the pow, if value of a is a negative number, the corresponding value of b must be an integer,
// for example, the corresponding value of b is 1.0, -2.0, 3.0.
// if b is odd, `-2 * (ceil(b*0.5)*2 - b) + 1` is -1, if b is even, the value is 1
auto round_dtype = Int(32);
auto b_half_ceil =
Cast::make(dtype, Call::make(round_dtype, "ceil", {Mul::make(b, make_const(dtype, 0.5))}, Call::PureIntrinsic));
auto odd = Add::make(Mul::make(Sub::make(Mul::make(b_half_ceil, make_const(dtype, 2)), b), make_const(dtype, -2)),
make_const(dtype, 1));
return Select::make(LT::make(a, make_const(dtype, 0)), Mul::make(odd, exp_log_value), exp_log_value);
}
return IRMutator::Mutate_(op, e);
}
};
// tanh(A) --> (exp(A)-exp(-A))/(exp(A)+exp(-A))
class TanhRewriter : public IRMutator {
public:
Expr Mutate_(const Call *op, const Expr &e) final {
if (op->name == "tanh") {
auto type = op->args[0].type();
Expr a = Mutate(op->args[0]);
Expr exp_a = Call::make(type, "exp", {a}, Call::PureIntrinsic);
Expr exp_n_a = Call::make(type, "exp", {-a}, Call::PureIntrinsic);
Expr num = Sub::make(exp_a, exp_n_a);
Expr den = Add::make(exp_a, exp_n_a);
return Div::make(num, den);
}
return IRMutator::Mutate_(op, e);
}
};
// !a --> sub(1,a)
class NotRewriter : public IRMutator {
public:
Expr Mutate_(const Not *op, const Expr &e) final {
// vsub instrunction does not support bool or int8 type
air::DataType sub_dtype = Float(16);
Expr res = Sub::make(make_const(sub_dtype, 1.0), Cast::make(sub_dtype, Mutate(op->a)));
return Cast::make(e.type(), res);
}
};
// In tvm, mod is truncmod
// mod(a,b) --> a - b*trunc(a/b)
// floormod(a,b) --> a - b*floor(a/b)
class ModRewriter : public IRMutator {
public:
template <typename T>
Expr MutateModOp(const T *op, const Expr &e, const std::string &round_mode) {
if (TensorOperandFinder().Find(e)) {
// vdiv instruction dose not support int
if (e.type().is_float()) {
Expr a = Mutate(op->a);
Expr b = Mutate(op->b);
Expr qutotient = Div::make(a, b);
Expr round_qutotient = Call::make(Int(32), round_mode, {qutotient}, Call::CallType::PureIntrinsic);
return Sub::make(a, Mul::make(b, Cast::make(b.type(), round_qutotient)));
}
}
return IRMutator::Mutate_(op, e);
}
Expr Mutate_(const Mod *op, const Expr &e) final { return MutateModOp(op, e, "trunc"); }
Expr Mutate_(const FloorMod *op, const Expr &e) final { return MutateModOp(op, e, "floor"); }
};
// The trunc instruction is not supported on mini
// trunc(x) --> min(ceil(x),0) + max(floor(x),0)
class TruncRewriter : public IRMutator {
public:
Expr Mutate_(const Call *op, const Expr &e) final {
if (op->name == "trunc" && TensorOperandFinder().Find(e)) {
const std::string productName = GetProductName();
if (productName != "cloud") {
auto round_type = e.type();
if (!round_type.is_int()) {
round_type = Int(32);
}
Expr x = Mutate(op->args[0]);
Expr ceil_x = Call::make(round_type, "ceil", {x}, Call::CallType::PureIntrinsic);
Expr floor_x = Call::make(round_type, "floor", {x}, Call::CallType::PureIntrinsic);
Expr zero = make_zero(round_type);
Expr trunc_x = Add::make(Min::make(ceil_x, zero), Max::make(floor_x, zero));
if (trunc_x.type() != e.type()) {
trunc_x = Cast::make(e.type(), trunc_x);
}
return trunc_x;
}
}
return IRMutator::Mutate_(op, e);
}
};
// tvm_if_then_else(cond, true, false) --> select(cond, true, false)
class IfThenElseRewriter : public IRMutator {
Expr Mutate_(const Call *op, const Expr &e) final {
if (op->name == "tvm_if_then_else") {
CHECK_EQ(op->args.size(), 3);
auto select = Select::make(Mutate(op->args[0]), Mutate(op->args[1]), Mutate(op->args[2]));
return select;
}
return IRMutator::Mutate_(op, e);
}
};
// cmp(a,b) --> select(cmp(a,b), 1, 0)
class CmpRewriter : public IRMutator {
public:
template <typename T>
Expr MutateCmpOp(const T *op, const Expr &e) {
if (TensorOperandFinder().Find(e)) {
Expr a = Mutate(op->a);
Expr b = Mutate(op->b);
auto sel_type = a.type();
Expr sel = Select::make(T::make(a, b), make_const(sel_type, 1), make_zero(sel_type));
// vector instrunction does not support float32 cast to bool(int8)
if (sel.type() == Float(32)) {
sel = Cast::make(Float(16), sel);
}
return Cast::make(e.type(), sel);
}
return IRMutator::Mutate_(op, e);
}
Expr Mutate_(const EQ *op, const Expr &e) final { return MutateCmpOp(op, e); }
Expr Mutate_(const NE *op, const Expr &e) final { return MutateCmpOp(op, e); }
Expr Mutate_(const LT *op, const Expr &e) final { return MutateCmpOp(op, e); }
Expr Mutate_(const LE *op, const Expr &e) final { return MutateCmpOp(op, e); }
Expr Mutate_(const GT *op, const Expr &e) final { return MutateCmpOp(op, e); }
Expr Mutate_(const GE *op, const Expr &e) final { return MutateCmpOp(op, e); }
// do not rewrite cmp op that already in cond of select
Expr Mutate_(const Select *op, const Expr &e) final {
Expr t = this->Mutate(op->true_value);
Expr f = this->Mutate(op->false_value);
return Select::make(op->condition, t, f);
}
// do not rewrite cmp op that in cond of if
Stmt Mutate_(const IfThenElse *op, const Stmt &s) final {
Stmt then_case = this->Mutate(op->then_case);
Stmt else_case;
if (op->else_case.defined()) {
else_case = this->Mutate(op->else_case);
}
return IfThenElse::make(op->condition, then_case, else_case);
}
};
/* Removes FloorMod and FloorDiv where denominator matches loop bounds.
* Example:
* for (i, 0, I) {
* a(floormod(i, I)) = b(floordiv(i, I))
* }
* should be optimized to:
* for (i, 0, I) {
* a(i) = b(0)
* }
* Future work: enhance it with more general algebraic simplification.
*/
class ModDivOpt : public IRMutator {
private:
Stmt Mutate_(const For *op, const Stmt &s) final {
loop_bounds.emplace(op->loop_var.get(), Simplify(op->min + op->extent));
Stmt stmt = IRMutator::Mutate_(op, s);
loop_bounds.erase(op->loop_var.get());
return stmt;
}
Expr Mutate_(const FloorDiv *op, const Expr &e) final {
Expr a = Simplify(op->a);
Expr b = Simplify(op->b);
if (auto var = a.as<Variable>()) {
if (loop_bounds.count(var)) {
if (Equal(loop_bounds[var], b)) {
return Expr(0);
}
}
}
return IRMutator::Mutate_(op, e);
}
Expr Mutate_(const FloorMod *op, const Expr &e) final {
Expr a = Simplify(op->a);
Expr b = Simplify(op->b);
if (auto var = a.as<Variable>()) {
if (loop_bounds.count(var)) {
if (Equal(loop_bounds[var], b)) {
return a;
}
}
}
return IRMutator::Mutate_(op, e);
}
std::unordered_map<const Variable *, Expr> loop_bounds;
};
Stmt MathIntrinRewrite(Stmt stmt) {
stmt = IfThenElseRewriter().Mutate(stmt);
stmt = CmpRewriter().Mutate(stmt);
stmt = ModRewriter().Mutate(stmt);
stmt = TruncRewriter().Mutate(stmt);
stmt = NotRewriter().Mutate(stmt);
stmt = RsqrtRewriter().Mutate(stmt);
stmt = TanhRewriter().Mutate(stmt);
stmt = DivRewriter().Mutate(stmt);
stmt = RmCast().Mutate(stmt);
stmt = RecRewriter().Mutate(stmt);
stmt = MulZeroOpt().Mutate(stmt);
stmt = PowRewriter().Mutate(stmt);
stmt = ModDivOpt().Mutate(stmt);
return stmt;
}
} // namespace ir
} // namespace akg
|
dbuschman7/collection-of-things
|
parsers/src/main/scala/me/lightspeed7/parsers/simpleScala/package.scala
|
package me.lightspeed7.parsers
import scala.util._
package object simpleScala {
//
// Parser Trait
// ///////////////////////
trait Parser[+A] extends (Stream[Character] => Result[A]) { outer =>
def ~[B](that: => Parser[B]) = new SequenceParser(this, that)
def |[B](that: => Parser[B]) = new DisParser(this, that)
def ^^[B](f: A => B) = new Parser[B] {
def apply(s: Stream[Character]) = outer(s) match {
case Success(v, rem) => Success(f(v), rem)
case f: Failure => f
}
}
def ^^^[B](v: => B) = new Parser[B] {
def apply(s: Stream[Character]) = outer(s) match {
case Success(_, rem) => Success(v, rem)
case f: Failure => f
}
}
}
sealed trait Result[+A]
case class Success[+A](value: A, rem: Stream[Character]) extends Result[A]
case class Failure(msg: String) extends Result[Nothing]
//
// Keyword Parser
// ///////////////////////
trait RegexpParsers {
implicit def keyword(str: String) = new Parser[String] {
def apply(s: Stream[Character]) = {
val trunc = s take str.length
lazy val errorMessage = "Expected '%s' got '%s'".format(str, trunc.mkString)
if (trunc.lengthCompare(str.length) != 0)
Failure(errorMessage)
else {
val succ = trunc.zipWithIndex forall {
case (c, i) => c == str(i)
}
if (succ) Success(str, s drop str.length)
else Failure(errorMessage)
}
}
}
}
//
// Combinators
// ////////////////////////
class SequenceParser[+A, +B](l: => Parser[A],
r: => Parser[B]) extends Parser[(A, B)] {
lazy val left = l
lazy val right = r
def apply(s: Stream[Character]) = left(s) match {
case Success(a, rem) => right(rem) match {
case Success(b, rem) => Success((a, b), rem)
case f: Failure => f
}
case f: Failure => f
}
}
class DisParser[+A](left: Parser[A], right: Parser[A]) extends Parser[A] {
def apply(s: Stream[Character]) = left(s) match {
case res: Success[A] => res
case _: Failure => right(s)
}
}
}
|
d8corp/innet-server
|
lib/plugins/cms/index.js
|
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var cms = require('./cms.js');
exports.cms = cms.cms;
|
jamestunnell/musicality
|
spec/composition/model/pitch_class_spec.rb
|
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper')
include PitchClasses
describe PitchClass do
it 'should define the MOD constant' do
expect(PitchClass.constants).to include(:MOD)
end
describe '.from_i' do
it 'should return the given integer % PitchClass::MOD' do
expect(PitchClass.from_i(-1)).to eq(11)
expect(PitchClass.from_i(12)).to eq(0)
expect(PitchClass.from_i(2)).to eq(2)
expect(PitchClass.from_i(16)).to eq(4)
end
end
it 'should add the #to_pc method to the Integer class' do
expect(5.methods).to include(:to_pc)
end
it 'should add the #to_pc method to the Pitch class' do
expect(Pitch.new.methods).to include(:to_pc)
end
it 'should add the #to_pcs method to Enumerable classes, like Array' do
expect([1,2,3].methods).to include(:to_pcs)
end
describe 'Pitch#to_pc' do
it 'should send semitone through PitchClass.from_i' do
[ C4, D3, E5, G5,
Pitch.new(semitone: 4),
Pitch.new(semitone: 13),
].each do |pitch|
expect(pitch.to_pc).to eq(PitchClass.from_i(pitch.semitone))
end
end
end
describe 'Integer#to_pc' do
it 'should pass self to PitchClass.from_i' do
[-1,12,2,16].each do |i|
expect(i.to_pc).to eq(PitchClass.from_i(i))
end
end
end
describe 'Integer#to_pcs' do
it 'should pass self to PitchClass.from_i' do
expect([-1,12,2,16].to_pcs).to eq([-1.to_pc,12.to_pc,2.to_pc,16.to_pc])
end
end
describe '.invert' do
before :all do
@cases = {
C => C,
Db => B,
D => Bb,
Eb => A,
E => Ab,
F => G,
Gb => Gb
}
end
it 'should produce a pitch class' do
@cases.each do |input_pc, output_pc|
expect(PitchClass.invert(input_pc)).to eq(output_pc)
end
end
it 'should produce a pitch class that when inverted again produces the original pitch class' do
@cases.each do |input_pc, output_pc|
expect(PitchClass.invert(output_pc)).to eq(input_pc)
end
end
end
end
|
cyrex562/Net-Loom
|
src/lowpan6.cpp
|
<filename>src/lowpan6.cpp
/**
* @file
*
* 6LowPAN output for IPv6. Uses ND tables for link-layer addressing. Fragments packets to 6LowPAN units.
*
* This implementation aims to conform to IEEE 802.15.4(-2015), RFC 4944 and RFC 6282.
* @todo: RFC 6775.
*/
/*
* Copyright (c) 2015 Inico Technologies Ltd.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: <NAME> <<EMAIL>>
*
*
* Please coordinate changes and requests with I<NAME>
* <<EMAIL>>
*/
/**
* @defgroup sixlowpan 6LoWPAN (RFC4944)
* @ingroup netifs
* 6LowPAN netif implementation
*/
#include <lowpan6.h>
#include <ip.h>
#include <packet_buffer.h>
#include <ip_addr.h>
#include <network_interface.h>
#include <nd6.h>
#include <udp.h>
#include <tcpip.h>
#include <ieee802154.h>
#include <lowpan6_common.h>
#include <lwip_debug.h>
#include <cstring>
// LWIP_6LOWPAN_DO_CALC_CRC(buf, len) LWIP_6LOWPAN_CALC_CRC(buf, len)
/** This is a helper struct for reassembly of fragments
* (IEEE 802.15.4 limits to 127 bytes)
*/
struct lowpan6_reass_helper {
struct lowpan6_reass_helper *next_packet;
struct PacketBuffer *reass;
struct PacketBuffer *frags;
uint8_t timer;
struct Lowpan6LinkAddr sender_addr;
uint16_t datagram_size;
uint16_t datagram_tag;
};
/** This struct keeps track of per-netif state */
struct lowpan6_ieee802154_data {
/** fragment reassembly list */
struct lowpan6_reass_helper *reass_list;
/** address context for compression */
Ip6Addr lowpan6_context[LWIP_6LOWPAN_NUM_CONTEXTS];
/** Datagram Tag for fragmentation */
uint16_t tx_datagram_tag;
/** local PAN ID for IEEE 802.15.4 header */
uint16_t ieee_802154_pan_id;
/** Sequence Number for IEEE 802.15.4 transmission */
uint8_t tx_frame_seq_num;
};
/* Maximum frame size is 127 bytes minus CRC size */
#define LOWPAN6_MAX_PAYLOAD (127 - 2)
/** Currently, this state is global, since there's only one 6LoWPAN netif */
static struct lowpan6_ieee802154_data lowpan6_data;
#define LWIP_6LOWPAN_CONTEXTS(netif) lowpan6_data.lowpan6_context
static const struct Lowpan6LinkAddr ieee_802154_broadcast = {2, {0xff, 0xff}};
static struct Lowpan6LinkAddr short_mac_addr = {2, {0, 0}};
/* IEEE 802.15.4 specific functions: */
/** Write the IEEE 802.15.4 header that encapsulates the 6LoWPAN frame.
* Src and dst PAN IDs are filled with the ID set by @ref lowpan6_set_pan_id.
*
* Since the length is variable:
* @returns the header length
*/
static uint8_t
lowpan6_write_iee802154_header(struct ieee_802154_hdr *hdr, const struct Lowpan6LinkAddr *src,
const struct Lowpan6LinkAddr *dst)
{
uint16_t fc = IEEE_802154_FC_FT_DATA; /* send data packet (2003 frame version) */
fc |= IEEE_802154_FC_PANID_COMPR; /* set PAN ID compression, for now src and dst PANs are equal */
if (dst != &ieee_802154_broadcast) {
fc |= IEEE_802154_FC_ACK_REQ; /* data packet, no broadcast: ack required. */
}
if (dst->addr_len == 2) {
fc |= IEEE_802154_FC_DST_ADDR_MODE_SHORT;
} else {
lwip_assert("invalid dst address length", dst->addr_len == 8);
fc |= IEEE_802154_FC_DST_ADDR_MODE_EXT;
}
if (src->addr_len == 2) {
fc |= IEEE_802154_FC_SRC_ADDR_MODE_SHORT;
} else {
lwip_assert("invalid src address length", src->addr_len == 8);
fc |= IEEE_802154_FC_SRC_ADDR_MODE_EXT;
}
hdr->frame_control = fc;
hdr->sequence_number = lowpan6_data.tx_frame_seq_num++;
hdr->destination_pan_id = lowpan6_data.ieee_802154_pan_id; /* pan id */
uint8_t* buffer = (uint8_t *)hdr;
uint8_t ieee_header_len = 5;
uint8_t i = dst->addr_len;
/* reverse memcpy of dst addr */
while (i-- > 0) {
buffer[ieee_header_len++] = dst->addr[i];
}
/* Source PAN ID skipped due to PAN ID Compression */
i = src->addr_len;
/* reverse memcpy of src addr */
while (i-- > 0) {
buffer[ieee_header_len++] = src->addr[i];
}
return ieee_header_len;
}
/** Parse the IEEE 802.15.4 header from a PacketBuffer.
* If successful, the header is hidden from the PacketBuffer.
*
* PAN IDs and seuqence number are not checked
*
* @param p input PacketBuffer, p->payload pointing at the IEEE 802.15.4 header
* @param src pointer to source address filled from the header
* @param dest pointer to destination address filled from the header
* @returns ERR_OK if successful
*/
static LwipStatus
lowpan6_parse_iee802154_header(struct PacketBuffer *p, struct Lowpan6LinkAddr *src,
struct Lowpan6LinkAddr *dest)
{
int8_t i; /* Parse IEEE 802.15.4 header */
uint8_t* puc = (uint8_t *)p->payload;
uint16_t frame_control = puc[0] | (puc[1] << 8);
uint16_t datagram_offset = 2;
if (frame_control & IEEE_802154_FC_SEQNO_SUPPR) {
if (IEEE_802154_FC_FRAME_VERSION_GET(frame_control) <= 1) {
/* sequence number suppressed, this is not valid for versions 0/1 */
return ERR_VAL;
}
} else {
datagram_offset++;
}
datagram_offset += 2; /* Skip destination PAN ID */
uint16_t addr_mode = frame_control & IEEE_802154_FC_DST_ADDR_MODE_MASK;
if (addr_mode == IEEE_802154_FC_DST_ADDR_MODE_EXT) {
/* extended address (64 bit) */
dest->addr_len = 8;
/* reverse memcpy: */
for (i = 0; i < 8; i++) {
dest->addr[i] = puc[datagram_offset + 7 - i];
}
datagram_offset += 8;
} else if (addr_mode == IEEE_802154_FC_DST_ADDR_MODE_SHORT) {
/* short address (16 bit) */
dest->addr_len = 2;
/* reverse memcpy: */
dest->addr[0] = puc[datagram_offset + 1];
dest->addr[1] = puc[datagram_offset];
datagram_offset += 2;
} else {
/* unsupported address mode (do we need "no address"?) */
return ERR_VAL;
}
if (!(frame_control & IEEE_802154_FC_PANID_COMPR)) {
/* No PAN ID compression, skip source PAN ID */
datagram_offset += 2;
}
addr_mode = frame_control & IEEE_802154_FC_SRC_ADDR_MODE_MASK;
if (addr_mode == IEEE_802154_FC_SRC_ADDR_MODE_EXT) {
/* extended address (64 bit) */
src->addr_len = 8;
/* reverse memcpy: */
for (i = 0; i < 8; i++) {
src->addr[i] = puc[datagram_offset + 7 - i];
}
datagram_offset += 8;
} else if (addr_mode == IEEE_802154_FC_DST_ADDR_MODE_SHORT) {
/* short address (16 bit) */
src->addr_len = 2;
src->addr[0] = puc[datagram_offset + 1];
src->addr[1] = puc[datagram_offset];
datagram_offset += 2;
} else {
/* unsupported address mode (do we need "no address"?) */
return ERR_VAL;
}
/* hide IEEE802.15.4 header. */
// if (pbuf_remove_header(p, datagram_offset)) {
// return ERR_VAL;
// }
return STATUS_SUCCESS;
}
/** Calculate the 16-bit CRC as required by IEEE 802.15.4 */
uint16_t
lowpan6_calc_crc(const void* buf, uint16_t len)
{
#define CCITT_POLY_16 0x8408U
uint16_t crc = 0;
const uint8_t* p = (const uint8_t*)buf;
for (uint16_t i = 0; i < len; i++) {
uint8_t data = *p;
for (uint8_t b = 0U; b < 8U; b++) {
if (((data ^ crc) & 1) != 0) {
crc = (uint16_t)((crc >> 1) ^ CCITT_POLY_16);
} else {
crc = (uint16_t)(crc >> 1);
}
data = (uint8_t)(data >> 1);
}
p++;
}
return crc;
}
/* Fragmentation specific functions: */
static void
free_reass_datagram(struct lowpan6_reass_helper *lrh)
{
if (lrh->reass) {
free_pkt_buf(lrh->reass);
}
if (lrh->frags) {
free_pkt_buf(lrh->frags);
}
delete lrh;
}
/**
* Removes a datagram from the reassembly queue.
**/
static void
dequeue_datagram(struct lowpan6_reass_helper *lrh, struct lowpan6_reass_helper *prev)
{
if (lowpan6_data.reass_list == lrh) {
lowpan6_data.reass_list = lowpan6_data.reass_list->next_packet;
} else {
/* it wasn't the first, so it must have a valid 'prev' */
lwip_assert("sanity check linked list", prev != nullptr);
prev->next_packet = lrh->next_packet;
}
}
/**
* Periodic timer for 6LowPAN functions:
*
* - Remove incomplete/old packets
*/
void
lowpan6_tmr(void)
{
struct lowpan6_reass_helper*lrh_prev = nullptr;
struct lowpan6_reass_helper* lrh = lowpan6_data.reass_list;
while (lrh != nullptr) {
struct lowpan6_reass_helper* lrh_next = lrh->next_packet;
if ((--lrh->timer) == 0) {
dequeue_datagram(lrh, lrh_prev);
free_reass_datagram(lrh);
} else {
lrh_prev = lrh;
}
lrh = lrh_next;
}
}
/*
* Encapsulates data into IEEE 802.15.4 frames.
* Fragments an IPv6 datagram into 6LowPAN units, which fit into IEEE 802.15.4 frames.
* If configured, will compress IPv6 and or UDP headers.
* */
static LwipStatus
lowpan6_frag(NetworkInterface*netif, struct PacketBuffer *p, const struct Lowpan6LinkAddr *src, const struct Lowpan6LinkAddr *dst)
{
uint16_t frag_len;
uint8_t lowpan6_header_len;
uint8_t hidden_header_len;
uint16_t crc;
LwipStatus err = ERR_IF;
lwip_assert("lowpan6_frag: netif->linkoutput not set", netif->linkoutput != nullptr);
/* We'll use a dedicated PacketBuffer for building 6LowPAN fragments. */
// struct PacketBuffer* p_frag = pbuf_alloc();
PacketBuffer p_frag{};
if (p_frag == nullptr) {
// MIB2_STATS_NETIF_INC(netif, ifoutdiscards);
return ERR_MEM;
}
lwip_assert("this needs a PacketBuffer in one piece", p_frag->len == p_frag->tot_len);
/* Write IEEE 802.15.4 header. */
uint8_t* buffer = (uint8_t *)p_frag->payload;
uint8_t ieee_header_len = lowpan6_write_iee802154_header(
(struct ieee_802154_hdr *)buffer,
src,
dst);
lwip_assert("ieee_header_len < p_frag->len", ieee_header_len < p_frag->len);
/* Perform 6LowPAN IPv6 header compression according to RFC 6282 */
/* do the header compression (this does NOT copy any non-compressed data) */
err = lowpan6_compress_headers(netif, (uint8_t *)p->payload, p->len,
&buffer[ieee_header_len], p_frag->len - ieee_header_len, &lowpan6_header_len,
&hidden_header_len, LWIP_6LOWPAN_CONTEXTS(netif), src, dst);
if (err != STATUS_SUCCESS) {
// MIB2_STATS_NETIF_INC(netif, ifoutdiscards);
free_pkt_buf(p_frag);
return err;
}
// pbuf_remove_header(p, hidden_header_len);
/* Calculate remaining packet length */
uint16_t remaining_len = p->tot_len;
if (remaining_len > 0x7FF) {
// MIB2_STATS_NETIF_INC(netif, ifoutdiscards);
/* datagram_size must fit into 11 bit */
free_pkt_buf(p_frag);
return ERR_VAL;
}
/* Fragment, or 1 packet? */
uint16_t max_data_len = LOWPAN6_MAX_PAYLOAD - ieee_header_len - lowpan6_header_len;
if (remaining_len > max_data_len) {
/* We must move the 6LowPAN header to make room for the FRAG header. */
memmove(&buffer[ieee_header_len + 4], &buffer[ieee_header_len], lowpan6_header_len);
/* Now we need to fragment the packet. FRAG1 header first */
buffer[ieee_header_len] = 0xc0 | (((p->tot_len + hidden_header_len) >> 8) & 0x7);
buffer[ieee_header_len + 1] = (p->tot_len + hidden_header_len) & 0xff;
lowpan6_data.tx_datagram_tag++;
buffer[ieee_header_len + 2] = (lowpan6_data.tx_datagram_tag >> 8) & 0xff;
buffer[ieee_header_len + 3] = lowpan6_data.tx_datagram_tag & 0xff;
/* Fragment follows. */
uint16_t data_len = (max_data_len - 4) & 0xf8;
frag_len = data_len + lowpan6_header_len;
pbuf_copy_partial(p, buffer + ieee_header_len + lowpan6_header_len + 4, frag_len - lowpan6_header_len, 0);
remaining_len -= frag_len - lowpan6_header_len;
/* datagram offset holds the offset before compression */
uint16_t datagram_offset = frag_len - lowpan6_header_len + hidden_header_len;
lwip_assert("datagram offset must be a multiple of 8", (datagram_offset & 7) == 0);
/* Calculate frame length */
p_frag->len = p_frag->tot_len = ieee_header_len + 4 + frag_len + 2; /* add 2 bytes for crc*/
/* 2 bytes CRC */
crc = lowpan6_calc_crc(p_frag->payload, p_frag->len - 2);
pbuf_take_at(p_frag, (uint8_t*)&crc, p_frag->len - 2);
/* send the packet */
Logf(true, "lowpan6_send: sending packet %p\n", (uint8_t *)p);
err = netif->linkoutput(netif, p_frag);
while ((remaining_len > 0) && (err == STATUS_SUCCESS)) {
struct ieee_802154_hdr *hdr = (struct ieee_802154_hdr *)buffer;
/* new frame, new seq num for ACK */
hdr->sequence_number = lowpan6_data.tx_frame_seq_num++;
buffer[ieee_header_len] |= 0x20; /* Change FRAG1 to FRAGN */
lwip_assert("datagram offset must be a multiple of 8", (datagram_offset & 7) == 0);
buffer[ieee_header_len + 4] = (uint8_t)(datagram_offset >> 3); /* datagram offset in FRAGN header (datagram_offset is max. 11 bit) */
frag_len = (127 - ieee_header_len - 5 - 2) & 0xf8;
if (frag_len > remaining_len) {
frag_len = remaining_len;
}
pbuf_copy_partial(p, buffer + ieee_header_len + 5, frag_len, p->tot_len - remaining_len);
remaining_len -= frag_len;
datagram_offset += frag_len;
/* Calculate frame length */
p_frag->len = p_frag->tot_len = frag_len + 5 + ieee_header_len + 2;
/* 2 bytes CRC */
crc = lowpan6_calc_crc(p_frag->payload, p_frag->len - 2);
pbuf_take_at(p_frag, (uint8_t*)&crc, p_frag->len - 2);
/* send the packet */
Logf(true, "lowpan6_send: sending packet %p\n", (uint8_t *)p);
err = netif->linkoutput(netif, p_frag);
}
} else {
/* It fits in one frame. */
frag_len = remaining_len;
/* Copy IPv6 packet */
pbuf_copy_partial(p, buffer + ieee_header_len + lowpan6_header_len, frag_len, 0);
remaining_len = 0;
/* Calculate frame length */
p_frag->len = p_frag->tot_len = frag_len + lowpan6_header_len + ieee_header_len + 2;
lwip_assert("", p_frag->len <= 127);
/* 2 bytes CRC */
crc = lowpan6_calc_crc(p_frag->payload, p_frag->len - 2);
pbuf_take_at(p_frag, (uint8_t*)&crc, p_frag->len - 2);
/* send the packet */
Logf(true, "lowpan6_send: sending packet %p\n", (uint8_t *)p);
err = netif->linkoutput(netif, p_frag);
}
free_pkt_buf(p_frag);
return err;
}
/**
* @ingroup sixlowpan
* Set context
*/
LwipStatus
lowpan6_set_context(uint8_t idx, const Ip6Addr*context)
{
if (idx >= LWIP_6LOWPAN_NUM_CONTEXTS) {
return STATUS_E_INVALID_ARG;
}
set_ip6_addr(&lowpan6_data.lowpan6_context[idx], context);
return STATUS_SUCCESS;
}
/**
* @ingroup sixlowpan
* Set short address
*/
LwipStatus
lowpan6_set_short_addr(uint8_t addr_high, uint8_t addr_low)
{
short_mac_addr.addr[0] = addr_high;
short_mac_addr.addr[1] = addr_low;
return STATUS_SUCCESS;
}
/* Create IEEE 802.15.4 address from netif address */
static LwipStatus
lowpan6_hwaddr_to_addr(NetworkInterface*netif, struct Lowpan6LinkAddr *addr)
{
addr->addr_len = 8;
if (netif->hwaddr_len == 8) {
//
if (sizeof(netif->hwaddr) < 8)
{
printf("netif hwaddr must be greater than 8\n");
return ERR_VAL;
}
memcpy(addr->addr, netif->hwaddr, 8);
} else if (netif->hwaddr_len == 6) {
/* Copy from MAC-48 */
memcpy(addr->addr, netif->hwaddr, 3);
addr->addr[3] = addr->addr[4] = 0xff;
memcpy(&addr->addr[5], &netif->hwaddr[3], 3);
} else {
/* Invalid address length, don't know how to convert this */
return ERR_VAL;
}
return STATUS_SUCCESS;
}
/**
* @ingroup sixlowpan
* Resolve and fill-in IEEE 802.15.4 address header for outgoing IPv6 packet.
*
* Perform Header Compression and fragment if necessary.
*
* @param netif The lwIP network interface which the IP packet will be sent on.
* @param q The PacketBuffer(s) containing the IP packet to be sent.
* @param ip6addr The IP address of the packet destination.
*
* @return LwipStatus
*/
LwipStatus
lowpan6_output(NetworkInterface*netif, struct PacketBuffer *q, const Ip6Addr*ip6addr)
{
LwipStatus result;
const uint8_t *hwaddr;
struct Lowpan6LinkAddr src, dest;
Ip6Addr ip6_src; /* Check if we can compress source address (use aligned copy) */
struct Ip6Hdr* ip6_hdr = (struct Ip6Hdr *)q->payload;
ip6_addr_copy_from_packed(&ip6_src, &ip6_hdr->src);
assign_ip6_addr_zone(&ip6_src, IP6_UNICAST, netif,);
if (lowpan6_get_address_mode(&ip6_src, &short_mac_addr) == 3) {
src.addr_len = 2;
src.addr[0] = short_mac_addr.addr[0];
src.addr[1] = short_mac_addr.addr[1];
} else
{
result = lowpan6_hwaddr_to_addr(netif, &src);
if (result != STATUS_SUCCESS) {
return result;
}
}
/* multicast destination IP address? */
if (is_ip6_addr_mcast(ip6addr)) {
/* We need to send to the broadcast address.*/
return lowpan6_frag(netif, q, &src, &ieee_802154_broadcast);
}
/* We have a unicast destination IP address */
/* @todo anycast? */
if (src.addr_len == 2) {
/* If source address was compressable to short_mac_addr, and dest has same subnet and
* is also compressable to 2-bytes, assume we can infer dest as a short address too. */
dest.addr_len = 2;
dest.addr[0] = ((uint8_t *)q->payload)[38];
dest.addr[1] = ((uint8_t *)q->payload)[39];
if ((src.addr_len == 2) && (cmp_ip6_net_zoneless((Ip6Addr*)&ip6_hdr->src, (Ip6Addr*)&ip6_hdr->dest)) &&
(lowpan6_get_address_mode(ip6addr, &dest) == 3)) {
return lowpan6_frag(netif, q, &src, &dest);
}
}
/* Ask ND6 what to do with the packet. */
result = nd6_get_next_hop_addr_or_queue(netif, q, ip6addr, &hwaddr);
if (result != STATUS_SUCCESS) {
return result;
}
/* If no hardware address is returned, nd6 has queued the packet for later. */
if (hwaddr == nullptr) {
return STATUS_SUCCESS;
}
/* Send out the packet using the returned hardware address. */
dest.addr_len = netif->hwaddr_len;
/* XXX: Inferring the length of the source address from the destination address
* is not correct for IEEE 802.15.4, but currently we don't get this information
* from the neighbor cache */
memcpy(dest.addr, hwaddr, netif->hwaddr_len);
return lowpan6_frag(netif, q, &src, &dest);
}
/**
* @ingroup sixlowpan
* NETIF input function: don't free the input PacketBuffer when returning != ERR_OK!
*/
LwipStatus
lowpan6_input(struct PacketBuffer *p, NetworkInterface*netif)
{
struct Lowpan6LinkAddr src, dest;
uint16_t datagram_size = 0;
uint16_t datagram_tag;
struct lowpan6_reass_helper *lrh, *lrh_prev = nullptr;
if (p == nullptr) {
return STATUS_SUCCESS;
}
if (p->len != p->tot_len) {
/* for now, this needs a PacketBuffer in one piece */
goto lowpan6_input_discard;
}
if (lowpan6_parse_iee802154_header(p, &src, &dest) != STATUS_SUCCESS) {
goto lowpan6_input_discard;
}
/* Check dispatch. */
uint8_t* puc = (uint8_t *)p->payload;
uint8_t b = *puc;
if ((b & 0xf8) == 0xc0) {
/* FRAG1 dispatch. add this packet to reassembly list. */
datagram_size = ((uint16_t)(puc[0] & 0x07) << 8) | (uint16_t)puc[1];
datagram_tag = ((uint16_t)puc[2] << 8) | (uint16_t)puc[3];
/* check for duplicate */
lrh = lowpan6_data.reass_list;
while (lrh != nullptr) {
uint8_t discard = 0;
struct lowpan6_reass_helper* lrh_next = lrh->next_packet;
if ((lrh->sender_addr.addr_len == src.addr_len) &&
(memcmp(lrh->sender_addr.addr, src.addr, src.addr_len) == 0)) {
/* address match with packet in reassembly. */
if ((datagram_tag == lrh->datagram_tag) && (datagram_size == lrh->datagram_size)) {
/* duplicate fragment. */
goto lowpan6_input_discard;
} else {
/* We are receiving the start of a new datagram. Discard old one (incomplete). */
discard = 1;
}
}
if (discard) {
dequeue_datagram(lrh, lrh_prev);
free_reass_datagram(lrh);
} else {
lrh_prev = lrh;
}
/* Check next datagram in queue. */
lrh = lrh_next;
}
// pbuf_remove_header(p, 4); /* hide frag1 dispatch */
lrh = new lowpan6_reass_helper;
if (lrh == nullptr) {
goto lowpan6_input_discard;
}
lrh->sender_addr.addr_len = src.addr_len;
for (int8_t i = 0; i < src.addr_len; i++) {
lrh->sender_addr.addr[i] = src.addr[i];
}
lrh->datagram_size = datagram_size;
lrh->datagram_tag = datagram_tag;
lrh->frags = nullptr;
if (*(uint8_t *)p->payload == 0x41) {
/* This is a complete IPv6 packet, just skip dispatch byte. */
// pbuf_remove_header(p, 1); /* hide dispatch byte. */
lrh->reass = p;
} else if ((*(uint8_t *)p->payload & 0xe0 ) == 0x60) {
lrh->reass = lowpan6_decompress(p, datagram_size, LWIP_6LOWPAN_CONTEXTS(netif), &src, &dest);
if (lrh->reass == nullptr) {
/* decompression failed */
delete lrh;
goto lowpan6_input_discard;
}
}
/* TODO: handle the case where we already have FRAGN received */
lrh->next_packet = lowpan6_data.reass_list;
lrh->timer = 2;
lowpan6_data.reass_list = lrh;
return STATUS_SUCCESS;
} else if ((b & 0xf8) == 0xe0) {
/* FRAGN dispatch, find packet being reassembled. */
datagram_size = ((uint16_t)(puc[0] & 0x07) << 8) | (uint16_t)puc[1];
datagram_tag = ((uint16_t)puc[2] << 8) | (uint16_t)puc[3];
uint16_t datagram_offset = (uint16_t)puc[4] << 3;
// pbuf_remove_header(p, 4); /* hide frag1 dispatch but keep datagram offset for reassembly */
for (lrh = lowpan6_data.reass_list; lrh != nullptr; lrh_prev = lrh, lrh = lrh->next_packet) {
if ((lrh->sender_addr.addr_len == src.addr_len) &&
(memcmp(lrh->sender_addr.addr, src.addr, src.addr_len) == 0) &&
(datagram_tag == lrh->datagram_tag) &&
(datagram_size == lrh->datagram_size)) {
break;
}
}
if (lrh == nullptr) {
/* rogue fragment */
goto lowpan6_input_discard;
}
/* Insert new PacketBuffer into list of fragments. Each fragment is a PacketBuffer,
this only works for unchained pbufs. */
lwip_assert("p->next == NULL", p->next == nullptr);
if (lrh->reass != nullptr) {
/* FRAG1 already received, check this offset against first len */
if (datagram_offset < lrh->reass->len) {
/* fragment overlap, discard old fragments */
dequeue_datagram(lrh, lrh_prev);
free_reass_datagram(lrh);
goto lowpan6_input_discard;
}
}
if (lrh->frags == nullptr) {
/* first FRAGN */
lrh->frags = p;
} else {
/* find the correct place to insert */
struct PacketBuffer *q, *last;
uint16_t new_frag_len = p->len - 1; /* p->len includes datagram_offset byte */
for (q = lrh->frags, last = nullptr; q != nullptr; last = q, q = q->next) {
uint16_t q_datagram_offset = ((uint8_t *)q->payload)[0] << 3;
uint16_t q_frag_len = q->len - 1;
if (datagram_offset < q_datagram_offset) {
if (datagram_offset + new_frag_len > q_datagram_offset) {
/* overlap, discard old fragments */
dequeue_datagram(lrh, lrh_prev);
free_reass_datagram(lrh);
goto lowpan6_input_discard;
}
/* insert here */
break;
} else if (datagram_offset == q_datagram_offset) {
if (q_frag_len != new_frag_len) {
/* fragment mismatch, discard old fragments */
dequeue_datagram(lrh, lrh_prev);
free_reass_datagram(lrh);
goto lowpan6_input_discard;
}
/* duplicate, ignore */
free_pkt_buf(p);
return STATUS_SUCCESS;
}
}
/* insert fragment */
if (last == nullptr) {
lrh->frags = p;
} else {
last->next = p;
p->next = q;
}
}
/* check if all fragments were received */
if (lrh->reass) {
uint16_t offset = lrh->reass->len;
struct PacketBuffer *q;
for (q = lrh->frags; q != nullptr; q = q->next) {
uint16_t q_datagram_offset = ((uint8_t *)q->payload)[0] << 3;
if (q_datagram_offset != offset) {
/* not complete, wait for more fragments */
return STATUS_SUCCESS;
}
offset += q->len - 1;
}
if (offset == datagram_size) {
/* all fragments received, combine pbufs */
uint16_t datagram_left = datagram_size - lrh->reass->len;
for (q = lrh->frags; q != nullptr; q = q->next) {
/* hide datagram_offset byte now */
// pbuf_remove_header(q, 1);
q->tot_len = datagram_left;
datagram_left -= q->len;
}
lwip_assert("datagram_left == 0", datagram_left == 0);
q = lrh->reass;
q->tot_len = datagram_size;
q->next = lrh->frags;
lrh->frags = nullptr;
lrh->reass = nullptr;
dequeue_datagram(lrh, lrh_prev);
delete lrh;
/* @todo: distinguish unicast/multicast */
return recv_ip6_pkt(q, netif);
}
}
/* PacketBuffer enqueued, waiting for more fragments */
return STATUS_SUCCESS;
} else {
if (b == 0x41) {
/* This is a complete IPv6 packet, just skip dispatch byte. */
// pbuf_remove_header(p, 1); /* hide dispatch byte. */
} else if ((b & 0xe0 ) == 0x60) {
/* IPv6 headers are compressed using IPHC. */
p = lowpan6_decompress(p, datagram_size, LWIP_6LOWPAN_CONTEXTS(netif), &src, &dest);
if (p == nullptr) {
return STATUS_SUCCESS;
}
} else {
goto lowpan6_input_discard;
}
/* @todo: distinguish unicast/multicast */
return recv_ip6_pkt(p, netif);
}
lowpan6_input_discard:
free_pkt_buf(p);
/* always return ERR_OK here to prevent the caller freeing the PacketBuffer */
return STATUS_SUCCESS;
}
/**
* @ingroup sixlowpan
*/
LwipStatus
lowpan6_if_init(NetworkInterface*netif)
{
netif->name[0] = 'L';
netif->name[1] = '6';
netif->output_ip6 = lowpan6_output;
/* maximum transfer unit */
netif->mtu = 1280;
/* broadcast capability */
netif->flags = NETIF_FLAG_BCAST /* | NETIF_FLAG_LOWPAN6 */;
return STATUS_SUCCESS;
}
/**
* @ingroup sixlowpan
* Set PAN ID
*/
LwipStatus
lowpan6_set_pan_id(uint16_t pan_id)
{
lowpan6_data.ieee_802154_pan_id = pan_id;
return STATUS_SUCCESS;
}
/**
* @ingroup sixlowpan
* Pass a received packet to tcpip_thread for input processing
*
* @param p the received packet, p->payload pointing to the
* IEEE 802.15.4 header.
* @param inp the network interface on which the packet was received
*/
LwipStatus
tcpip_6lowpan_input(struct PacketBuffer *p, NetworkInterface*inp)
{
return tcpip_inpkt(p, inp, lowpan6_input);
}
|
rRaDuCaN/our-awesome-mart
|
our-awesome-mart-demo-client/src/components/Home/NavigationBar/SearchFormSupplements/InputSearch.js
|
import React from 'react'
import './InputSearch.css'
export default function InputSearch() {
return (
<input
type="text"
placeholder="Search"
name="search"
aria-label="Search"
autoCapitalize="off"
autoComplete="off"
autoCorrect="off"
className="InputSearch"/>
);
}
|
2772263973/PTPDroid
|
soot-infoflow/src/soot/jimple/infoflow/data/pathBuilders/DefaultPathBuilderFactory.java
|
<gh_stars>1-10
package soot.jimple.infoflow.data.pathBuilders;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import soot.jimple.infoflow.InfoflowConfiguration.PathBuildingAlgorithm;
import soot.jimple.infoflow.InfoflowConfiguration.PathConfiguration;
import soot.jimple.infoflow.InfoflowManager;
import soot.jimple.infoflow.solver.executors.InterruptableExecutor;
/**
* Default factory class for abstraction path builders
*
* @author <NAME>
*/
public class DefaultPathBuilderFactory implements IPathBuilderFactory {
private final PathConfiguration pathConfiguration;
/**
* Creates a new instance of the {@link DefaultPathBuilderFactory} class
*
* @param config
* The configuration for reconstructing data flow paths
*/
public DefaultPathBuilderFactory(PathConfiguration config) {
this.pathConfiguration = config;
}
/**
* Creates a new executor object for spawning worker threads
*
* @param maxThreadNum
* The number of threads to use
* @return The generated executor
*/
private InterruptableExecutor createExecutor(int maxThreadNum) {
int numThreads = Runtime.getRuntime().availableProcessors();
InterruptableExecutor executor = new InterruptableExecutor(
maxThreadNum == -1 ? numThreads : Math.min(maxThreadNum, numThreads), Integer.MAX_VALUE, 30,
TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
executor.setThreadFactory(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thr = new Thread(r, "Path reconstruction");
return thr;
}
});
return executor;
}
@Override
public IAbstractionPathBuilder createPathBuilder(InfoflowManager manager, int maxThreadNum) {
return createPathBuilder(manager, createExecutor(maxThreadNum));
}
@Override
public IAbstractionPathBuilder createPathBuilder(InfoflowManager manager, InterruptableExecutor executor) {
switch (pathConfiguration.getPathBuildingAlgorithm()) {
case Recursive:
return new RecursivePathBuilder(manager, executor);
case ContextSensitive:
return new ContextSensitivePathBuilder(manager, executor);
case ContextInsensitive:
return new ContextInsensitivePathBuilder(manager, executor);
case ContextInsensitiveSourceFinder:
return new ContextInsensitiveSourceFinder(manager, executor);
case None:
return new EmptyPathBuilder();
}
throw new RuntimeException("Unsupported path building algorithm");
}
@Override
public boolean supportsPathReconstruction() {
switch (pathConfiguration.getPathBuildingAlgorithm()) {
case Recursive:
case ContextSensitive:
case ContextInsensitive:
return true;
case ContextInsensitiveSourceFinder:
case None:
return false;
}
throw new RuntimeException("Unsupported path building algorithm");
}
@Override
public boolean isContextSensitive() {
return pathConfiguration.getPathBuildingAlgorithm() == PathBuildingAlgorithm.ContextSensitive;
}
}
|
DYevhen/dashboard
|
core/src/main/java/com/exadel/core/servlets/ImportNewsServlet.java
|
<reponame>DYevhen/dashboard
package com.exadel.core.servlets;
import com.exadel.core.services.PageService;
import com.exadel.core.services.RssImporter;
import lombok.extern.slf4j.Slf4j;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.HttpConstants;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.apache.sling.servlets.annotations.SlingServletPaths;
import org.apache.sling.servlets.annotations.SlingServletResourceTypes;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import javax.servlet.Servlet;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.GregorianCalendar;
@Slf4j
@Component(service = Servlet.class, property = {
"sling.servlet.methods="+HttpConstants.METHOD_POST
})
@SlingServletPaths(value = "/content/dashboard/import-news/start")
/*@SlingServletResourceTypes(
resourceTypes = "dashboard/components/granite-page",
methods = HttpConstants.METHOD_GET,
extensions = "html",
selectors = "granite-page-get")*/
public class ImportNewsServlet extends SlingAllMethodsServlet {
@Reference
private PageService pageService;
@Reference
private RssImporter rssImporter;
@Override
protected void doGet(SlingHttpServletRequest req, SlingHttpServletResponse resp) throws IOException {
log.info("======================================SERVLET START=============================================");
pageService.createCards(rssImporter.getData());
pageService.setLastExecution(new GregorianCalendar());
resp.setCharacterEncoding(StandardCharsets.UTF_8.displayName());
resp.setContentType("text/plain");
resp.setStatus(SlingHttpServletResponse.SC_ACCEPTED);
resp.getWriter().print("Success!");
resp.sendRedirect("/content/dashboard/import-news.html");
log.info("======================================SERVLET END===============================================");
}
}
|
pierre/collector
|
src/test/java/com/ning/metrics/collector/MockEvent.java
|
<reponame>pierre/collector
/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning 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 com.ning.metrics.collector;
import com.ning.metrics.serialization.event.StubEvent;
import com.ning.metrics.serialization.thrift.hadoop.TBooleanWritable;
public class MockEvent extends StubEvent
{
private String outputPath = "/var/tmp/mock-event";
@Override
public String getOutputDir(final String prefix)
{
return outputPath;
}
public void setOutputPath(final String s)
{
outputPath = s;
}
/**
* The basic StubEvent returns a String - which the Hadoop writer won't understand.
*
* @return stupid payload
*/
@Override
public Object getData()
{
return new TBooleanWritable(true);
}
}
|
jaiskid/LeetCode-Solutions
|
C++/number-of-islands-ii.cpp
|
// Time: O(klog*k) ~= O(k), k is the length of the positions
// Space: O(k)
// Using unordered_map.
class Solution {
public:
vector<int> numIslands2(int m, int n, vector<pair<int, int>>& positions) {
vector<int> numbers;
int number = 0;
const vector<pair<int, int>> directions{{0, -1}, {0, 1},
{-1, 0}, {1, 0}};
unordered_map<int, int> set;
for (const auto& position : positions) {
const auto& node = make_pair(position.first, position.second);
set[node_id(node, n)] = node_id(node, n);
++number;
for (const auto& d : directions) {
const auto& neighbor = make_pair(position.first + d.first,
position.second + d.second);
if (neighbor.first >= 0 && neighbor.first < m &&
neighbor.second >= 0 && neighbor.second < n &&
set.find(node_id(neighbor, n)) != set.end()) {
if (find_set(node_id(node, n), &set) !=
find_set(node_id(neighbor, n), &set)) {
// Merge different islands, amortised time: O(log*k) ~= O(1)
union_set(&set, node_id(node, n), node_id(neighbor, n));
--number;
}
}
}
numbers.emplace_back(number);
}
return numbers;
}
int node_id(const pair<int, int>& node, const int n) {
return node.first * n + node.second;
}
int find_set(int x, unordered_map<int, int> *set) {
if ((*set)[x] != x) {
(*set)[x] = find_set((*set)[x], set); // path compression.
}
return (*set)[x];
}
void union_set(unordered_map<int, int> *set, const int x, const int y) {
int x_root = find_set(x, set), y_root = find_set(y, set);
(*set)[min(x_root, y_root)] = max(x_root, y_root);
}
};
// Time: O(klog*k) ~= O(k), k is the length of the positions
// Space: O(m * n)
// Using vector.
class Solution2 {
public:
/**
* @param n an integer
* @param m an integer
* @param operators an array of point
* @return an integer array
*/
vector<int> numIslands2(int m, int n, vector<pair<int, int>>& positions) {
vector<int> numbers;
int number = 0;
const vector<pair<int, int>> directions{{0, -1}, {0, 1},
{-1, 0}, {1, 0}};
vector<int> set(m * n, -1);
for (const auto& position : positions) {
const auto& node = make_pair(position.first, position.second);
set[node_id(node, n)] = node_id(node, n);
++number;
for (const auto& d : directions) {
const auto& neighbor = make_pair(position.first + d.first,
position.second + d.second);
if (neighbor.first >= 0 && neighbor.first < m &&
neighbor.second >= 0 && neighbor.second < n &&
set[node_id(neighbor, n)] != -1) {
if (find_set(node_id(node, n), &set) !=
find_set(node_id(neighbor, n), &set)) {
// Merge different islands, amortised time: O(log*k) ~= O(1)
union_set(&set, node_id(node, n), node_id(neighbor, n));
--number;
}
}
}
numbers.emplace_back(number);
}
return numbers;
}
int node_id(const pair<int, int>& node, const int m) {
return node.first * m + node.second;
}
int find_set(int x, vector<int> *set) {
int parent = x;
while ((*set)[parent] != parent) {
parent = (*set)[parent];
}
while ((*set)[x] != x) {
int tmp = (*set)[x];
(*set)[x] = parent;
x = tmp;
}
return parent;
}
void union_set(vector<int> *set, const int x, const int y) {
int x_root = find_set(x, set), y_root = find_set(y, set);
(*set)[min(x_root, y_root)] = max(x_root, y_root);
}
};
|
gyoisamurai/GyoiBoard
|
atd/migrations/0011_auto_20210329_2236.py
|
# Generated by Django 3.1.7 on 2021-03-29 13:36
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('atd', '0010_scanresult_attack_method'),
]
operations = [
migrations.RenameField(
model_name='scanresult',
old_name='task_id',
new_name='scan_id',
),
]
|
CoenRijsdijk/Bytecoder
|
classlib/java.desktop/src/main/resources/META-INF/modules/java.desktop/classes/com/sun/imageio/plugins/gif/GIFStreamMetadataFormatResources.java
|
/*
* Copyright (c) 2001, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.imageio.plugins.gif;
import java.util.ListResourceBundle;
public class GIFStreamMetadataFormatResources extends ListResourceBundle {
public GIFStreamMetadataFormatResources() {}
protected Object[][] getContents() {
return new Object[][] {
// Node name, followed by description
{ "Version", "The file version, either 87a or 89a" },
{ "LogicalScreenDescriptor",
"The logical screen descriptor, except for the global color table" },
{ "GlobalColorTable", "The global color table" },
{ "ColorTableEntry", "A global color table entry" },
// Node name + "/" + AttributeName, followed by description
{ "Version/value",
"The version string" },
{ "LogicalScreenDescriptor/logicalScreenWidth",
"The width in pixels of the whole picture" },
{ "LogicalScreenDescriptor/logicalScreenHeight",
"The height in pixels of the whole picture" },
{ "LogicalScreenDescriptor/colorResolution",
"The number of bits of color resolution, beteen 1 and 8" },
{ "LogicalScreenDescriptor/pixelAspectRatio",
"If 0, indicates square pixels, else W/H = (value + 15)/64" },
{ "GlobalColorTable/sizeOfGlobalColorTable",
"The number of entries in the global color table" },
{ "GlobalColorTable/backgroundColorIndex",
"The index of the color table entry to be used as a background" },
{ "GlobalColorTable/sortFlag",
"True if the global color table is sorted by frequency" },
{ "ColorTableEntry/index", "The index of the color table entry" },
{ "ColorTableEntry/red",
"The red value for the color table entry" },
{ "ColorTableEntry/green",
"The green value for the color table entry" },
{ "ColorTableEntry/blue",
"The blue value for the color table entry" },
};
}
}
|
ngayngo9x/q-micro-thrift-demo
|
src/main/java/com/pheu/thrift/example/EchoHandler.java
|
<filename>src/main/java/com/pheu/thrift/example/EchoHandler.java<gh_stars>0
package com.pheu.thrift.example;
import org.apache.thrift.TException;
import com.pheu.example.TestThriftService;
public class EchoHandler implements TestThriftService.Iface {
private int port;
public EchoHandler(int port) {
this.port = port;
}
@Override
public String echo(String message) throws TException {
return "Hello " + message + ", port=" + port;
}
@Override
public void echo1(String message) throws TException {
System.out.println(echo(message));
}
}
|
LaudateCorpus1/nerve-2
|
nerve/quotation/src/main/java/network/nerve/quotation/util/HttpRequestUtil.java
|
package network.nerve.quotation.util;
import io.nuls.core.model.StringUtils;
import io.nuls.core.parse.JSONUtils;
import network.nerve.quotation.model.bo.Chain;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import static network.nerve.quotation.constant.QuotationConstant.TIMEOUT_MILLIS;
/**
* @author: Loki
* @date: 2020/08/11
*/
public class HttpRequestUtil {
public static Map<String, Object> httpRequest(Chain chain, String url) {
try {
String dataStr = _httpRequest(chain, url);
if (StringUtils.isBlank(dataStr)) {
return null;
}
Map<String, Object> data = JSONUtils.jsonToMap(dataStr);
return data;
} catch (Exception e){
chain.getLogger().error("调用接口:{} 异常, {}", url, e.getMessage());
return null;
}
}
public static List<Map> httpRequestList(Chain chain, String url) {
try {
String dataStr = _httpRequest(chain, url);
if (StringUtils.isBlank(dataStr)) {
return null;
}
List<Map> dataList = JSONUtils.json2pojo(dataStr, List.class);
return dataList;
} catch (Exception e){
chain.getLogger().error("调用接口:{} 异常, {}", url, e.getMessage());
return null;
}
}
private static String _httpRequest(Chain chain, String url) {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
/*HttpHost proxy = new HttpHost("127.0.0.1", 1080);*/
HttpGet httpGet = new HttpGet(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(TIMEOUT_MILLIS)/*.setProxy(proxy)*/
.setSocketTimeout(TIMEOUT_MILLIS).setConnectTimeout(TIMEOUT_MILLIS).build();
httpGet.setConfig(requestConfig);
CloseableHttpResponse response;
try {
response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
String dataStr = EntityUtils.toString(entity);
return dataStr;
}
chain.getLogger().error("调用接口:{} 异常, StatusCode:{}", url, response.getStatusLine().getStatusCode());
return null;
} catch (IOException e) {
chain.getLogger().error("调用接口:{} 异常, {}", url, e.getMessage());
return null;
} catch (Exception e){
chain.getLogger().error("调用接口:{} 异常, {}", url, e.getMessage());
return null;
}
}
}
|
davido/closure-templates
|
java/src/com/google/template/soy/exprtree/FunctionNode.java
|
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.template.soy.exprtree;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.auto.value.AutoOneOf;
import com.google.auto.value.AutoValue;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.template.soy.base.SourceFilePath;
import com.google.template.soy.base.SourceLocation;
import com.google.template.soy.base.SourceLocation.Point;
import com.google.template.soy.base.internal.Identifier;
import com.google.template.soy.basetree.CopyState;
import com.google.template.soy.plugin.restricted.SoySourceFunction;
import com.google.template.soy.shared.internal.BuiltinFunction;
import com.google.template.soy.shared.restricted.SoyFunction;
import com.google.template.soy.shared.restricted.SoyFunctions;
import com.google.template.soy.shared.restricted.SoyPureFunction;
import com.google.template.soy.types.FunctionType;
import com.google.template.soy.types.SoyType;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nullable;
/**
* A node representing a function (with args as children).
*
* <p>Important: Do not use outside of Soy code (treat as superpackage-private).
*/
public final class FunctionNode extends AbstractParentExprNode implements ExprNode.CallableExpr {
public static final SoySourceFunction UNRESOLVED =
new SoySourceFunction() {
@Override
public String toString() {
return "UNRESOLVED";
}
};
/** All the information a runtime needs to execute a call to an extern. */
@AutoValue
public abstract static class ExternRef {
public static ExternRef of(SourceFilePath path, String name, FunctionType signature) {
return new AutoValue_FunctionNode_ExternRef(path, name, signature);
}
public abstract SourceFilePath path();
public abstract String name();
public abstract FunctionType signature();
}
/**
* Either a {@link SoyFunction} or a {@link SoySourceFunction}. TODO(b/19252021): use
* SoySourceFunction everywhere.
*/
@AutoOneOf(FunctionRef.Type.class)
public abstract static class FunctionRef {
enum Type {
SOY_FUNCTION,
SOY_SOURCE_FUNCTION,
EXTERN
}
public static FunctionRef of(Object soyFunction) {
if (soyFunction instanceof SoyFunction) {
return of((SoyFunction) soyFunction);
} else if (soyFunction instanceof SoySourceFunction) {
return of((SoySourceFunction) soyFunction);
} else if (soyFunction instanceof ExternRef) {
return of((ExternRef) soyFunction);
} else {
throw new ClassCastException(String.valueOf(soyFunction));
}
}
public static FunctionRef of(SoyFunction soyFunction) {
return AutoOneOf_FunctionNode_FunctionRef.soyFunction(soyFunction);
}
public static FunctionRef of(SoySourceFunction soySourceFunction) {
return AutoOneOf_FunctionNode_FunctionRef.soySourceFunction(soySourceFunction);
}
public static FunctionRef of(ExternRef functionType) {
return AutoOneOf_FunctionNode_FunctionRef.extern(functionType);
}
abstract Type type();
abstract SoyFunction soyFunction();
abstract SoySourceFunction soySourceFunction();
abstract ExternRef extern();
public Object either() {
switch (type()) {
case SOY_FUNCTION:
return soyFunction();
case SOY_SOURCE_FUNCTION:
return soySourceFunction();
case EXTERN:
return extern();
}
throw new AssertionError();
}
}
private static final class FunctionState {
@Nullable private FunctionRef function;
@Nullable private ImmutableList<SoyType> allowedParamTypes;
private boolean allowedToInvokeAsFunction = false;
}
public static FunctionNode newPositional(
Identifier name, BuiltinFunction soyFunction, SourceLocation sourceLocation) {
FunctionNode fn =
new FunctionNode(
sourceLocation, name, null, ParamsStyle.POSITIONAL, ImmutableList.of(), null);
fn.setSoyFunction(soyFunction);
return fn;
}
public static FunctionNode newPositional(
Identifier name, SoySourceFunction soyFunction, SourceLocation sourceLocation) {
FunctionNode fn =
new FunctionNode(
sourceLocation, name, null, ParamsStyle.POSITIONAL, ImmutableList.of(), null);
fn.setSoyFunction(soyFunction);
return fn;
}
public static FunctionNode newPositional(
Identifier name, SourceLocation sourceLocation, @Nullable List<Point> commaLocations) {
return new FunctionNode(
sourceLocation,
name,
null,
ParamsStyle.POSITIONAL,
ImmutableList.of(),
commaLocations == null ? null : ImmutableList.copyOf(commaLocations));
}
public static FunctionNode newNamed(
Identifier name, Iterable<Identifier> paramNames, SourceLocation sourceLocation) {
return new FunctionNode(
sourceLocation, name, null, ParamsStyle.NAMED, ImmutableList.copyOf(paramNames), null);
}
private final Identifier name;
private final ExprNode nameExpr;
private final ParamsStyle paramsStyle;
/** When paramsStyle is NAMED this contains the list of named parameters. Otherwise empty. */
private final ImmutableList<Identifier> paramNames;
@Nullable private final ImmutableList<SourceLocation.Point> commaLocations;
// Mutable state stored in this AST node from various passes.
private final FunctionState state = new FunctionState();
FunctionNode(
SourceLocation sourceLocation,
Identifier name,
ExprNode nameExpr,
ParamsStyle paramsStyle,
ImmutableList<Identifier> paramNames,
@Nullable ImmutableList<Point> commaLocations) {
super(sourceLocation);
Preconditions.checkArgument(paramNames.isEmpty() || paramsStyle == ParamsStyle.NAMED);
Preconditions.checkArgument((name == null) != (nameExpr == null));
this.name = name;
this.nameExpr = nameExpr;
this.paramsStyle = paramsStyle;
this.paramNames = paramNames;
this.commaLocations = commaLocations;
}
/**
* Copy constructor.
*
* @param orig The node to copy.
*/
private FunctionNode(FunctionNode orig, CopyState copyState) {
super(orig, copyState);
this.name = orig.name;
this.nameExpr = orig.nameExpr != null ? orig.nameExpr.copy(copyState) : null;
this.paramsStyle = orig.paramsStyle;
this.paramNames = orig.paramNames;
this.state.function = orig.state.function;
this.state.allowedParamTypes = orig.state.allowedParamTypes;
this.state.allowedToInvokeAsFunction = orig.state.allowedToInvokeAsFunction;
this.commaLocations = orig.commaLocations;
}
@Override
public Optional<ImmutableList<SourceLocation.Point>> getCommaLocations() {
return Optional.ofNullable(commaLocations);
}
@Override
public Kind getKind() {
return Kind.FUNCTION_NODE;
}
/** Returns whether this function has a static name. */
public boolean hasStaticName() {
return name != null;
}
/** Returns the function name. */
public String getStaticFunctionName() {
return name.identifier();
}
/** Returns the function name or empty string if there is no static name. */
public String getFunctionName() {
return name != null ? name.identifier() : "";
}
/** If this function does not have a static name then it has a name expression. */
public ExprNode getNameExpr() {
return Preconditions.checkNotNull(nameExpr);
}
@Override
public ParamsStyle getParamsStyle() {
return paramsStyle;
}
@Override
public Identifier getIdentifier() {
return name;
}
/** Returns the location of the function name. */
public SourceLocation getFunctionNameLocation() {
return name != null ? name.location() : nameExpr.getSourceLocation();
}
public boolean isResolved() {
return state.function != null;
}
public boolean allowedToInvokeAsFunction() {
return this.state.allowedToInvokeAsFunction;
}
public void setAllowedToInvokeAsFunction(boolean cond) {
this.state.allowedToInvokeAsFunction = cond;
}
public Object getSoyFunction() {
checkState(
this.state.function != null,
"setSoyFunction() hasn't been called yet %s %s",
name,
getSourceLocation());
return state.function.either();
}
public void setSoyFunction(Object soyFunction) {
checkNotNull(soyFunction);
FunctionRef newRef = FunctionRef.of(soyFunction);
checkState(
this.state.function == null || this.state.function.equals(newRef),
"setSoyFunction() was already called; %s; %s (previous) != %s (current)",
getSourceLocation().toLineColumnString(),
this.state.function,
newRef);
this.state.function = newRef;
}
public void setAllowedParamTypes(List<SoyType> allowedParamTypes) {
checkState(paramsStyle == ParamsStyle.POSITIONAL || numChildren() == 0);
checkState(
allowedParamTypes.size() == numChildren(),
"allowedParamTypes.size (%s) != numChildren (%s)",
allowedParamTypes.size(),
numChildren());
this.state.allowedParamTypes = ImmutableList.copyOf(allowedParamTypes);
}
/** Returns null if ResolveExpressionTypesPass has not run yet. */
@Nullable
public ImmutableList<SoyType> getAllowedParamTypes() {
checkState(paramsStyle == ParamsStyle.POSITIONAL || numChildren() == 0);
return state.allowedParamTypes;
}
/**
* Returns the list of proto initialization call param names.
*
* <p>Each param name corresponds to each of this node's children, which are the param values.
*/
@Override
public ImmutableList<Identifier> getParamNames() {
Preconditions.checkState(paramsStyle == ParamsStyle.NAMED || numChildren() == 0);
return paramNames;
}
@Override
public String toSourceString() {
StringBuilder sourceSb = new StringBuilder();
sourceSb
.append(hasStaticName() ? getStaticFunctionName() : nameExpr.toSourceString())
.append('(');
if (paramsStyle == ParamsStyle.POSITIONAL) {
boolean isFirst = true;
for (ExprNode child : getChildren()) {
if (isFirst) {
isFirst = false;
} else {
sourceSb.append(", ");
}
sourceSb.append(child.toSourceString());
}
} else if (paramsStyle == ParamsStyle.NAMED) {
for (int i = 0; i < numChildren(); i++) {
if (i > 0) {
sourceSb.append(", ");
}
sourceSb.append(paramNames.get(i)).append(": ");
sourceSb.append(getChild(i).toSourceString());
}
}
sourceSb.append(')');
return sourceSb.toString();
}
@Override
public FunctionNode copy(CopyState copyState) {
return new FunctionNode(this, copyState);
}
/**
* Whether or not this function is pure.
*
* <p>See {@link SoyPureFunction} for the definition of a pure function.
*/
public boolean isPure() {
if (!isResolved()) {
return false;
}
if (state.function.type() == FunctionRef.Type.EXTERN) {
return false;
}
return SoyFunctions.isPure(state.function.either());
}
@Override
public List<ExprNode> getParams() {
return getChildren();
}
@Override
public int numParams() {
return numChildren();
}
}
|
idjevm/popcorn-time-desktop
|
test/e2e/HomePage.e2e.js
|
import { Selector } from 'testcafe';
import {
BASE_URL,
getPageTitle,
getPageUrl,
cardlistSelector,
cardSelector,
scrollBottom,
navigateTo,
clearConfigs
} from './helpers';
fixture`Home Page`.page(BASE_URL).beforeEach(() => clearConfigs());
test('it should have the expected title', async t => {
await t.expect(getPageTitle()).eql('Popcorn Time');
});
test('it should display cards list and cards', async t => {
await navigateTo(t, 'shows');
await t
.expect(cardlistSelector.visible)
.ok()
.expect(cardSelector.visible)
.ok();
});
test('it should search items', async t => {
await t
.typeText('#pct-search-input', "harry potter and the philosopher's stone")
.pressKey('enter');
await t
.expect(
(await cardSelector.find('.Card--title').nth(0).innerText).toLowerCase()
)
.contains("harry potter and the philosopher's stone");
});
test('it should search items (2)', async t => {
await navigateTo(t, 'home');
await t
.typeText('#pct-search-input', 'lord of the rings', { replace: true })
.pressKey('enter');
await t
.expect(
(await cardSelector.find('.Card--title').nth(0).innerText).toLowerCase()
)
.contains('lord of the rings');
});
test('it should navigate to item on CardList click', async t => {
await navigateTo(t, 'shows');
await t
.click(cardSelector)
.expect(getPageUrl())
.contains('#/item/shows/')
.expect(Selector('#title').visible)
.ok()
.expect(Selector('[data-e2e="summary"]').visible)
.ok();
});
test('it should navigate between movies and shows', async t => {
await navigateTo(t, 'shows');
await t.expect(getPageUrl()).contains('#/item/shows');
await navigateTo(t, 'movies');
await t.expect(getPageUrl()).contains('#/item/movies');
});
test('it should paginate items on scroll to bottom of viewport', async t => {
await navigateTo(t, 'shows');
const selector1 = await Selector('.Card a').count;
await scrollBottom();
await t
.expect(Selector('.Loader').visible)
.notOk()
.wait(3000);
const selector2 = await Selector('.Card a').count;
await t.expect(selector1).lt(selector2);
});
test('it should move card selector left and right', async t => {
await navigateTo(t, 'movies');
await t
.pressKey('right')
.expect(
Selector('.Card')
.nth(1)
.withAttribute('class', 'Card Card--selected').visible
)
.ok()
.pressKey('left')
.expect(
Selector('.Card')
.nth(0)
.withAttribute('class', 'Card Card--selected').visible
)
.ok()
.pressKey('left')
.expect(
Selector('.Card')
.nth(0)
.withAttribute('class', 'Card Card--selected').visible
)
.ok();
});
test('it should navigate to card on enter press', async t => {
await navigateTo(t, 'movies');
await t
.pressKey('right')
.expect(
Selector('.Card')
.nth(1)
.withAttribute('class', 'Card Card--selected').visible
)
.ok()
.pressKey('enter')
.expect(getPageUrl())
.contains('item');
});
|
rgarner/beis-report-official-development-assistance
|
app/presenters/external_income_presenter.rb
|
<filename>app/presenters/external_income_presenter.rb
class ExternalIncomePresenter < SimpleDelegator
def amount
ActionController::Base.helpers.number_to_currency(super, unit: "£")
end
def oda_funding
super ? "Yes" : "No"
end
end
|
CristianeMayara/QuizAdmReact
|
quiz_adm/src/views/User/UserEdit/UserEdit.js
|
import React, { Component } from "react";
import {
Col,
Row,
Card,
Form,
Input,
Label,
Button,
CardBody,
FormGroup,
CardFooter,
CardHeader
} from "reactstrap";
import { connect } from "react-redux";
import { thunkEditUser, thunkFetchUser } from "../../../actions/User/UserThunk";
class UserEdit extends Component {
constructor(props) {
super(props);
this.state = {
user: {}
};
this.handleCreate = this.handleEdit.bind(this);
this.handleChangeInput = this.handleChangeInput.bind(this);
}
async componentWillMount() {
let { id } = this.props.match.params;
await this.props.fetchUser(id);
this.setState({ ...this.state, user: this.props.editUser.user });
}
handleEdit(user) {
this.props.handleEditUser(user);
this.props.history.push("user/list");
}
handleChangeInput(event) {
const { target } = event;
const { value, name } = target;
let { user } = this.state;
user[name] = value;
return this.setState({ user });
}
render() {
return (
<div className="animated fadeIn">
<Row>
<Col xs="12" md="12">
<Card>
<CardHeader>Edit a User</CardHeader>
<CardBody>
<Form>
<FormGroup>
<Label htmlFor="name">Name:</Label>
<Input
name="name"
type="text"
placeholder="Enter user name"
onChange={this.handleChangeInput}
value={this.state.user.name || ""}
/>
</FormGroup>
<FormGroup>
<Label htmlFor="email">Email:</Label>
<Input
name="email"
type="text"
placeholder="Enter user email"
onChange={this.handleChangeInput}
value={this.state.user.email || ""}
/>
</FormGroup>
<FormGroup>
<Label htmlFor="password">Password:</Label>
<Input
name="password"
type="text"
onChange={this.handleChangeInput}
placeholder="Enter user password"
/>
</FormGroup>
<FormGroup check>
<Label check htmlFor="active" />
<Input
type="checkbox"
defaultChecked={this.state.user.active}
/>
Active?
</FormGroup>
</Form>
</CardBody>
<CardFooter>
<Button
type="button"
color="primary"
onClick={() => this.handleEdit(this.state.user)}
>
Save
</Button>
</CardFooter>
</Card>
</Col>
</Row>
</div>
);
}
}
const mapStateToProps = state => {
return {
editUser: state.userStore.editUser
};
};
const mapDispathToProps = dispatch => {
return {
handleEditUser: user => dispatch(thunkEditUser(user)),
fetchUser: id => dispatch(thunkFetchUser(id))
};
};
export default connect(
mapStateToProps,
mapDispathToProps
)(UserEdit);
|
darrowcoucla/libraryweb-site-sahil
|
www/sites/all/modules/contrib/references_dialog/js/references-dialog.js
|
(function ($) {
var $window = $(window);
Drupal.behaviors.referencesDialog = {
attach: function (context, settings) {
// Add appropriate classes on all fields that should have it. This is
// necessary since we don't actually know what markup we are dealing with.
if (typeof settings.ReferencesDialog !== 'undefined') {
$.each(settings.ReferencesDialog.fields, function (key, widget_settings) {
$('.' + key + ' a.references-dialog-activate', context).click(function (e) {
e.preventDefault();
Drupal.ReferencesDialog.open($(this).attr('href'), $(this).html());
Drupal.ReferencesDialog.entityIdReceived = function (entity_type, entity_id, label) {
if (typeof widget_settings.format !== 'undefined') {
var value = widget_settings.format
.replace('$label', label)
.replace('$entity_id', entity_id)
.replace('$entity_type', entity_type);
}
// If we have a callback path, let's invoke that.
if (typeof widget_settings.callback_path !== 'undefined') {
var entity_info = {
label: label,
entity_id: entity_id,
entity_type: entity_type
};
Drupal.ReferencesDialog.invokeCallback(widget_settings.callback_path, entity_info, widget_settings.callback_settings);
}
// If we have a target, use that.
else if (typeof widget_settings.target !== 'undefined') {
var target = $('#' + widget_settings.target);
target.val(value);
target.change();
}
// If we have none of the above, we just insert the value in the item
// that invoked this.
else {
var key_el = $('#' + key);
key_el.val(value);
key_el.change();
}
}
return false;
});
});
}
}
};
/**
* Our dialog object. Can be used to open a dialog to anywhere.
*/
Drupal.ReferencesDialog = {
dialog_open: false,
open_dialog: null
}
Drupal.ReferencesDialog.invokeCallback = function (callback, entity_info, settings) {
if (typeof settings == 'object') {
entity_info.settings = settings;
}
$.post(callback, entity_info);
}
/**
* If this property is set to be a function, it
* will be called when an entity is recieved from an overlay.
*/
Drupal.ReferencesDialog.entityIdReceived = null;
/**
* Open a dialog window.
* @param string href the link to point to.
*/
Drupal.ReferencesDialog.open = function (href, title) {
if (!this.dialog_open) {
// Add render references dialog, so that we know that we should be in a
// dialog.
href += (href.indexOf('?') > -1 ? '&' : '?') + 'render=references-dialog';
// Get the current window size and do 75% of the width and 90% of the height.
// @todo Add settings for this so that users can configure this by themselves.
var window_width = $window.width() / 100*75;
var window_height = $window.height() / 100*90;
this.open_dialog = $('<iframe class="references-dialog-iframe" src="' + href + '"></iframe>').dialog({
width: window_width,
height: window_height,
modal: true,
resizable: false,
position: ['center', 50],
title: title,
close: function () { Drupal.ReferencesDialog.dialog_open = false; }
}).width(window_width-10).height(window_height);
$window.bind('resize scroll', function () {
// Move the dialog the main window moves.
if (typeof Drupal.ReferencesDialog == 'object' && Drupal.ReferencesDialog.open_dialog != null) {
Drupal.ReferencesDialog.open_dialog.
dialog('option', 'position', ['center', 10]);
Drupal.ReferencesDialog.setDimensions();
}
});
this.dialog_open = true;
}
}
/**
* Set dimensions of the dialog dependning on the current winow size
* and scroll position.
*/
Drupal.ReferencesDialog.setDimensions = function () {
if (typeof Drupal.ReferencesDialog == 'object') {
var window_width = $window.width() / 100*75;
var window_height = $window.height() / 100*90;
this.open_dialog.
dialog('option', 'width', window_width).
dialog('option', 'height', window_height).
width(window_width-10).height(window_height);
}
}
/**
* Close the dialog and provide an entity id and a title
* that we can use in various ways.
*/
Drupal.ReferencesDialog.close = function (entity_type, entity_id, title) {
this.open_dialog.dialog('close');
this.open_dialog.dialog('destroy');
this.open_dialog = null;
this.dialog_open = false;
// Call our entityIdReceived function if we have one.
// this is used as an event.
if (typeof this.entityIdReceived == 'function') {
this.entityIdReceived(entity_type, entity_id, title);
}
}
}(jQuery));
|
zhangkn/iOS14Header
|
System/Library/Frameworks/MediaPlayer.framework/MPMediaKitEntityTranslatorContext.h
|
<filename>System/Library/Frameworks/MediaPlayer.framework/MPMediaKitEntityTranslatorContext.h
/*
* This header is generated by classdump-dyld 1.0
* on Sunday, September 27, 2020 at 11:39:50 AM Mountain Standard Time
* Operating System: Version 14.0 (Build 18A373)
* Image Source: /System/Library/Frameworks/MediaPlayer.framework/MediaPlayer
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>.
*/
@protocol MPMediaKitEntityRelationshipPayloadProvider;
@class NSString;
@interface MPMediaKitEntityTranslatorContext : NSObject {
NSString* _personID;
id<MPMediaKitEntityRelationshipPayloadProvider> _relationshipPayloadProvider;
}
@property (nonatomic,copy) NSString * personID; //@synthesize personID=_personID - In the implementation block
@property (nonatomic,retain) id<MPMediaKitEntityRelationshipPayloadProvider> relationshipPayloadProvider; //@synthesize relationshipPayloadProvider=_relationshipPayloadProvider - In the implementation block
-(NSString *)personID;
-(void)setPersonID:(NSString *)arg1 ;
-(id<MPMediaKitEntityRelationshipPayloadProvider>)relationshipPayloadProvider;
-(void)setRelationshipPayloadProvider:(id<MPMediaKitEntityRelationshipPayloadProvider>)arg1 ;
@end
|
ppngiap/cppstdlib
|
string/stringiter1.cpp
|
<filename>string/stringiter1.cpp<gh_stars>10-100
/* The following code example is taken from the book
* "The C++ Standard Library - A Tutorial and Reference, 2nd Edition"
* by <NAME>, Addison-Wesley, 2012
*
* (C) Copyright <NAME> 2012.
* Permission to copy, use, modify, sell and distribute this software
* is granted provided this copyright notice appears in all copies.
* This software is provided "as is" without express or implied
* warranty, and with no claim as to its suitability for any purpose.
*/
#include <string>
#include <iostream>
#include <algorithm>
#include <cctype>
#include <regex>
using namespace std;
int main()
{
// create a string
string s("The zip code of Braunschweig in Germany is 38100");
cout << "original: " << s << endl;
// lowercase all characters
transform (s.cbegin(), s.cend(), // source
s.begin(), // destination
[] (char c) { // operation
return tolower(c);
});
cout << "lowered: " << s << endl;
// uppercase all characters
transform (s.cbegin(), s.cend(), // source
s.begin(), // destination
[] (char c) { // operation
return toupper(c);
});
cout << "uppered: " << s << endl;
// search case-insensitive for Germany
string g("Germany");
string::const_iterator pos;
pos = search (s.cbegin(),s.cend(), // source string in which to search
g.cbegin(),g.cend(), // substring to search
[] (char c1, char c2) { // comparison criterion
return toupper(c1) == toupper(c2);
});
if (pos != s.cend()) {
cout << "substring \"" << g << "\" found at index "
<< pos - s.cbegin() << endl;
}
}
|
chiayuexian/iconex_android
|
iconex/src/main/java/foundation/icon/iconex/dialogs/TitleMsgDialog.java
|
package foundation.icon.iconex.dialogs;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import androidx.annotation.NonNull;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import foundation.icon.iconex.R;
/**
* Created by js on 2018. 4. 2..
*/
public class TitleMsgDialog extends Dialog {
private String title, message;
private TextView txtTitle, txtMsg;
private Button btnOK;
public TitleMsgDialog(@NonNull Context context) {
super(context);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
setContentView(R.layout.dialog_title_msg);
setCancelable(false);
setCanceledOnTouchOutside(false);
txtTitle = findViewById(R.id.txt_title);
txtTitle.setText(title);
txtMsg = findViewById(R.id.txt_msg);
txtMsg.setText(message);
btnOK = findViewById(R.id.btn_ok);
btnOK.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
}
public void setTitle(String title) {
this.title = title;
}
public void setMessage(String msg) {
this.message = msg;
}
}
|
disrupted/Trakttv.bundle
|
Trakttv.bundle/Contents/Libraries/Shared/plugin/core/libraries/tests/cryptography_.py
|
from plugin.core.libraries.tests.core.base import BaseTest
class Cryptography(BaseTest):
name = 'cryptography'
optional = True
@staticmethod
def test_import():
import cryptography.hazmat.bindings.openssl.binding
return {
'versions': {
'cryptography': getattr(cryptography, '__version__', None)
}
}
|
flitzmo-hso/flitzmo_agv_control_system
|
Versionen/2021_06_15/rmf_ws/install/rmf_traffic_msgs/include/rmf_traffic_msgs/msg/region.h
|
<gh_stars>0
// generated from rosidl_generator_c/resource/idl.h.em
// with input from rmf_traffic_msgs:msg/Region.idl
// generated code does not contain a copyright notice
#ifndef RMF_TRAFFIC_MSGS__MSG__REGION_H_
#define RMF_TRAFFIC_MSGS__MSG__REGION_H_
#include "rmf_traffic_msgs/msg/detail/region__struct.h"
#include "rmf_traffic_msgs/msg/detail/region__functions.h"
#include "rmf_traffic_msgs/msg/detail/region__type_support.h"
#endif // RMF_TRAFFIC_MSGS__MSG__REGION_H_
|
yuppaoh/eWatchEjbApplication
|
eWatchLogin/eWatchLogin-ejb/build/generated-sources/ap-source-output/entities/Orderdetails_.java
|
<reponame>yuppaoh/eWatchEjbApplication
package entities;
import entities.Orders;
import entities.Products;
import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@Generated(value="EclipseLink-2.5.2.v20140319-rNA", date="2021-04-05T17:07:34")
@StaticMetamodel(Orderdetails.class)
public class Orderdetails_ {
public static volatile SingularAttribute<Orderdetails, Float> unitPrice;
public static volatile SingularAttribute<Orderdetails, Integer> quantity;
public static volatile SingularAttribute<Orderdetails, Products> productId;
public static volatile SingularAttribute<Orderdetails, Orders> orderId;
public static volatile SingularAttribute<Orderdetails, Integer> id;
}
|
bolatov/contests
|
acmp.ru/p114.cpp
|
#include <bits/stdc++.h>
using namespace std;
#ifndef int64
#define int64 long long
#endif
int main() {
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
#endif
int n, k;
cin >> n >> k;
vector<pair<int64, int64>> dp(n + 1, {0, 0});
dp[1] = {1, k - 1};
for (int i = 2; i <= n; ++i) {
int64 f = dp[i - 1].second;
int64 s = (k - 1) * (dp[i - 1].first + dp[i - 1].second);
dp[i] = {f, s};
}
cout << dp[n].second << endl;
return 0;
}
|
arkiny/OSwithMSVC
|
Chapter/14_DLL/Core/Loader.h
|
#pragma once
#include "windef.h"
class Process;
#define PROCESS_GENESIS_ID 101
class Loader
{
public:
Loader();
~Loader();
virtual Process* CreateProcessFromMemory(const char* appName, LPTHREAD_START_ROUTINE lpStartAddress, void* param) = 0;
virtual Process* CreateProcessFromFile(char* appName, void* param) = 0;
int GetNextProcessId() { return m_nextProcessId++; }
static int m_nextProcessId;
};
|
lum1n0us/intel-device-resource-mgt-lib
|
ibroker/ams-api-gateway/src/main/java/com/intel/iot/ams/api/CfgMgrAPIs.java
|
/*
* Copyright (C) 2020 Intel Corporation. All rights reserved. SPDX-License-Identifier: Apache-2.0
*/
package com.intel.iot.ams.api;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.intel.iot.ams.api.requestbody.PostCfgIdPayload;
import com.intel.iot.ams.entity.*;
import com.intel.iot.ams.entity.TemplateItem.TemplateConfigItem;
import com.intel.iot.ams.service.*;
import com.intel.iot.ams.utils.HashUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
/**
* RESTAPIs implementation of APIs document Chapter 2.4 Cloud configuration management
*
* @author <NAME> <<EMAIL>>
*/
@RestController
@RequestMapping("/ams_user_cloud")
public class CfgMgrAPIs {
private static final Logger logger = LoggerFactory.getLogger(CfgMgrAPIs.class);
@Autowired private CfgIdentifierService cfgIdSrv;
@Autowired private CfgInstanceService cfgInstSrv;
@Autowired private CfgContentService cfgCntSrv;
@Autowired private ProductService pSrv;
/** * added by wangning */
@Autowired private AmsClientService amsSrv;
@Autowired private ClientCurrentCfgService clicSrv;
@Autowired private ProductInstalledService prdinstSrv;
@Autowired private ClientcfgCheckPointService clickpSrv;
@Autowired private AmsTemplateService amsTpltSrv;
@Autowired private LogService logSrv;
private static final int DFLTOFFSET = 0; // The first page, which starts
// from 0
private static final int DFLTLIMIT = 10; // Default size for each page.
// to 100
private static final int MAXLIMIT = 100;
// end wn
// ----------------------------------------------------------------
//
// RESTful APIs
//
// ----------------------------------------------------------------
/**
* ----------------------------------------------------------------
*
* <p>Chapter 2.4.1 User system post configuration instance to target
*
* <p>----------------------------------------------------------------
*/
/**
* User posts configuration instance to target
*
* <p>RESTful API: POST /ams/v1/config/instance
*
* @param payload the POST payload data
* @return an instance of ResponseEntity<String> with response code
*/
@RequestMapping(
value = "/ams/v1/config/instance",
produces = "application/json",
method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<String> postCfgInstanceToTarget(
@RequestParam(value = "product_name", required = true) String productName,
@RequestParam(value = "path_name", required = true) String pathName,
@RequestParam(value = "target_type", required = true) String targetType,
@RequestParam(value = "target_id", required = true) String targetId,
@RequestParam(value = "content_name", required = false) String contentName,
@RequestBody(required = false) String payload) {
if (contentName == null && (payload == null || payload.equals(""))) {
return new ResponseEntity<String>(
"content_name and payload cannot be null at the same time!", HttpStatus.BAD_REQUEST);
}
Product p = pSrv.findByName(productName);
if (p == null) {
return new ResponseEntity<String>("Unknown Product: " + productName, HttpStatus.BAD_REQUEST);
}
pathName.trim().replaceAll("\\\\", "/");
if (pathName.startsWith("./")) {
pathName = pathName.substring(1);
} else {
if (!pathName.startsWith("/")) {
pathName = "/" + pathName;
}
}
CfgContent content = null;
if (contentName != null && !contentName.equals("")) {
content = cfgCntSrv.findBySharedName(contentName);
if (content == null) {
return new ResponseEntity<String>(
"Shared content \"" + contentName + "\" cannot be found.", HttpStatus.NOT_FOUND);
}
}
CfgIdentifier cfgId =
cfgIdSrv.findByUserNameAndPathNameAndTargetType(productName, pathName, targetType);
if (cfgId == null) {
cfgId = new CfgIdentifier();
cfgId.setPathName(pathName);
cfgId.setUserName(productName);
cfgId.setTargetType(targetType);
cfgId.setCfgUuid(UUID.randomUUID().toString());
cfgIdSrv.save(cfgId);
/** Log to MySQL */
logSrv.LogToMysql(
"Add",
"Software Config",
"Add config, software name: "
+ cfgId.getUserName()
+ ", "
+ "config pathname: "
+ cfgId.getPathName()
+ " , "
+ "config targetType:"
+ cfgId.getTargetType()
+ "",
null);
}
CfgInstance instance =
cfgInstSrv.findByCfgIdentifierUUIDAndTargetId(cfgId.getCfgUuid(), targetId);
if (instance == null) {
instance = new CfgInstance();
instance.setCfgUuid(cfgId.getCfgUuid());
instance.setTargetId(targetId);
if (content == null) {
if (payload != null && !payload.equals("")) {
String hash = HashUtils.getMd5Hash(payload.getBytes());
content = new CfgContent();
content.setContentType(2);
content.setContent(payload);
content.setContentHash(hash);
cfgCntSrv.save(content);
/** Log to MySQL */
logSrv.LogToMysql(
"Add",
"Software Config",
"Add customized content for instance whose target id:" + instance.getTargetId() + "",
null);
instance.setContentId(content.getId());
}
} else {
instance.setContentId(content.getId());
}
cfgInstSrv.save(instance);
/** Log to MySQL */
logSrv.LogToMysql(
"Add",
"Software Config",
"Add config instance, targetId: " + instance.getTargetId() + "",
null);
} else {
if (instance.getContentId() != null) {
CfgContent old = cfgCntSrv.findById(instance.getContentId());
if (old != null && old.getContentType() == 2) {
cfgCntSrv.delete(old);
/** Log to MySQL */
logSrv.LogToMysql(
"Delete",
"Software Config",
"Delete customized content of instance whose target id: "
+ instance.getTargetId()
+ "",
null);
}
}
if (content == null) {
if (payload != null && !payload.equals("")) {
String hash = HashUtils.getMd5Hash(payload.getBytes());
content = new CfgContent();
content.setContentType(2);
content.setContent(payload);
content.setContentHash(hash);
cfgCntSrv.save(content);
/** Log to MySQL */
logSrv.LogToMysql(
"Add",
"Software Config",
"Add customized content for instance whose target id: " + instance.getTargetId() + "",
null);
instance.setContentId(content.getId());
}
} else {
instance.setContentId(content.getId());
}
cfgInstSrv.update(instance);
/** Log to MySQL */
logSrv.LogToMysql(
"Update",
"Software Config",
"Update config instance, targetId" + instance.getTargetId() + "",
null);
}
return new ResponseEntity<String>(HttpStatus.OK);
}
/**
* ----------------------------------------------------------------
*
* <p>Chapter 2.4.2 User system post default content for configuration identifier
*
* <p>----------------------------------------------------------------
*/
/**
* User posts default content for configuration identifier
*
* <p>RESTful API: POST /ams/v1/config/identifier
*
* @return an instance of ResponseEntity<String> with response code
*/
@RequestMapping(
value = "/ams/v1/config/identifier",
produces = "application/json",
method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<String> postDefaultContentToCfgIdentifier(
@RequestParam(value = "product_name", required = true) String productName,
@RequestParam(value = "path_name", required = true) String pathName,
@RequestParam(value = "target_type", required = true) String targetType,
@RequestBody String payload) {
Product p = pSrv.findByName(productName);
if (p == null) {
return new ResponseEntity<String>("No such Product: " + productName, HttpStatus.BAD_REQUEST);
}
if (payload == null) {
return new ResponseEntity<String>("No Payload", HttpStatus.BAD_REQUEST);
}
PostCfgIdPayload info = parseCfgIdPayload(payload);
pathName.trim().replaceAll("\\\\", "/");
if (pathName.startsWith("./")) {
pathName = pathName.substring(1);
} else {
if (!pathName.startsWith("/")) {
pathName = "/" + pathName;
}
}
CfgContent content = null;
CfgIdentifier cfgId =
cfgIdSrv.findByUserNameAndPathNameAndTargetType(p.getName(), pathName, targetType);
if (cfgId == null) {
cfgId = new CfgIdentifier();
cfgId.setPathName(pathName);
cfgId.setUserName(p.getName());
cfgId.setTargetType(targetType);
cfgId.setCfgUuid(UUID.randomUUID().toString());
if (info != null) {
if (info.getContent() != null && !info.getContent().equals("")) {
String hash = HashUtils.getMd5Hash(info.getContent().getBytes());
content = new CfgContent();
content.setContentType(0);
content.setContent(info.getContent());
content.setContentHash(hash);
cfgCntSrv.save(content);
/** Log to MySQL */
logSrv.LogToMysql(
"Add",
"Software Config",
"Add default content for config, config pathName:"
+ cfgId.getPathName()
+ ", config targetType: "
+ cfgId.getTargetType()
+ ", software name:"
+ cfgId.getUserName()
+ "",
null);
cfgId.setDefaultContentId(content.getId());
}
if (info.getSchema() != null && !info.getSchema().equals("")) {
cfgId.setSchema(info.getSchema());
}
}
cfgIdSrv.save(cfgId);
/** Log to MySQL */
logSrv.LogToMysql(
"Add",
"Software Config",
"Add software config, software name: "
+ cfgId.getUserName()
+ ", "
+ "config pathname: "
+ cfgId.getPathName()
+ ", "
+ "config targetType:"
+ cfgId.getTargetType()
+ "",
null);
} else {
if (info != null) {
if (info.getContent() != null && !info.getContent().equals("")) {
String hash = HashUtils.getMd5Hash(info.getContent().getBytes());
if (cfgId.getDefaultContentId() != null) {
content = cfgCntSrv.findById(cfgId.getDefaultContentId());
}
if (content != null) {
content.setContent(info.getContent());
content.setContentHash(hash);
cfgCntSrv.update(content);
/** Log to MySQL */
logSrv.LogToMysql(
"Update",
"Software Config",
"Update default content for config, config pathName:"
+ cfgId.getPathName()
+ ", config targetType: "
+ cfgId.getTargetType()
+ ", software name:"
+ cfgId.getUserName()
+ "",
null);
} else {
content = new CfgContent();
content.setContentType(0);
content.setContent(info.getContent());
content.setContentHash(hash);
cfgCntSrv.save(content);
/** Log to MySQL */
logSrv.LogToMysql(
"Add",
"Software Config",
"Add default content for config, config pathName:"
+ cfgId.getPathName()
+ ", config targetType: "
+ cfgId.getTargetType()
+ ", software name:"
+ cfgId.getUserName()
+ "",
null);
}
cfgId.setDefaultContentId(content.getId());
} else {
if (cfgId.getDefaultContentId() != null) {
content = cfgCntSrv.findById(cfgId.getDefaultContentId());
if (content != null) {
cfgCntSrv.delete(content);
/** Log to MySQL */
logSrv.LogToMysql(
"Delete",
"Software Config",
"Delete default of config, config pathName:"
+ cfgId.getPathName()
+ ", config targetType: "
+ cfgId.getTargetType()
+ ", software name:"
+ cfgId.getUserName()
+ "",
null);
}
cfgId.setDefaultContentId(null);
}
}
if (info.getSchema() != null && !info.getSchema().equals("")) {
cfgId.setSchema(info.getSchema());
} else {
cfgId.setSchema(null);
}
cfgIdSrv.update(cfgId);
/** Log to MySQL */
logSrv.LogToMysql(
"Update",
"Software Config",
"Update software config, software name: "
+ cfgId.getUserName()
+ ", "
+ "config pathname: "
+ cfgId.getPathName()
+ " , "
+ "config targetType:"
+ cfgId.getTargetType()
+ "",
null);
}
}
return new ResponseEntity<String>(HttpStatus.OK);
}
/**
* ----------------------------------------------------------------
*
* <p>Chapter 2.4.3 Query configuration identifier information
*
* <p>----------------------------------------------------------------
*/
/**
* User query configuration identifier information
*
* <p>RESTful API: GET /ams/v1/config/identifier
*
* @return an instance of ResponseEntity<String> with response code
*/
@RequestMapping(
value = "/ams/v1/config/identifier",
produces = "application/json",
method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<String> getCfgIdentifier(
@RequestParam(value = "product_name", required = false) String productName,
@RequestParam(value = "path_name", required = false) String pathName,
@RequestParam(value = "target_type", required = false) String targetType) {
if (productName != null) {
Product p = pSrv.findByName(productName);
if (p == null) {
return new ResponseEntity<String>(
"Unknown Product: " + productName, HttpStatus.BAD_REQUEST);
}
}
if (pathName != null) {
pathName.trim().replaceAll("\\\\", "/");
if (pathName.startsWith("./")) {
pathName = pathName.substring(1);
} else {
if (!pathName.startsWith("/")) {
pathName = "/" + pathName;
}
}
}
JsonArray jResult = new JsonArray();
List<CfgIdentifier> idList = null;
if (productName == null && pathName == null && targetType == null) {
idList = cfgIdSrv.findAll();
}
if (productName != null && pathName == null && targetType == null) {
idList = cfgIdSrv.findByUserName(productName);
}
if (productName == null && pathName != null && targetType == null) {
idList = cfgIdSrv.findByPathName(pathName);
}
if (productName == null && pathName == null && targetType != null) {
idList = cfgIdSrv.findByTargetType(targetType);
}
if (productName != null && pathName != null && targetType == null) {
idList = cfgIdSrv.findByUserNameAndPathName(productName, pathName);
}
if (productName != null && pathName == null && targetType != null) {
idList = cfgIdSrv.findByUserNameAndTargetType(productName, targetType);
}
if (productName != null && pathName != null && targetType != null) {
CfgIdentifier id =
cfgIdSrv.findByUserNameAndPathNameAndTargetType(productName, pathName, targetType);
if (id != null) {
idList = new ArrayList<CfgIdentifier>();
idList.add(id);
}
}
if (idList != null) {
for (CfgIdentifier cfgId : idList) {
JsonObject j = cfgIdSerialize(cfgId);
if (j != null) {
jResult.add(j);
}
}
}
return new ResponseEntity<String>(jResult.toString(), HttpStatus.OK);
}
/**
* ----------------------------------------------------------------
*
* <p>Chapter 2.4.4 Delete configuration identifier
*
* <p>----------------------------------------------------------------
*/
/**
* Delete a configuration identifier
*
* <p>RESTful API: DELETE /ams/v1/config/identifier
*
* @return an instance of ResponseEntity<String> with response code
*/
@RequestMapping(
value = "/ams/v1/config/identifier",
produces = "application/json",
method = RequestMethod.DELETE)
public ResponseEntity<String> deleteCfgId(
@RequestParam(value = "product_name", required = false) String productName,
@RequestParam(value = "path_name", required = false) String pathName,
@RequestParam(value = "target_type", required = false) String targetType) {
if (productName == null || pathName == null) {
return new ResponseEntity<String>(
"Query parameter \"product_name\", \"path_name\" and \"target_type\" are required.",
HttpStatus.BAD_REQUEST);
}
Product p = pSrv.findByName(productName);
if (p == null) {
return new ResponseEntity<String>("Unknown Product: " + productName, HttpStatus.BAD_REQUEST);
}
if (pathName != null) {
pathName.trim().replaceAll("\\\\", "/");
if (pathName.startsWith("./")) {
pathName = pathName.substring(1);
} else {
if (!pathName.startsWith("/")) {
pathName = "/" + pathName;
}
}
}
CfgIdentifier cfgId =
cfgIdSrv.findByUserNameAndPathNameAndTargetType(productName, pathName, targetType);
if (cfgId != null) {
List<CfgInstance> instanceList = cfgInstSrv.findByCfgIdentifierUUID(cfgId.getCfgUuid());
if (instanceList != null) {
for (CfgInstance instance : instanceList) {
CfgContent content = cfgCntSrv.findById(instance.getContentId());
if (content != null) {
/** Delete individual content before delete instance */
if (content.getContentType() == 2) {
cfgCntSrv.delete(content);
/** Log to MySQL */
logSrv.LogToMysql(
"Delete",
"Software Config",
"Delete customized content of instance whose target id: "
+ instance.getTargetId()
+ "",
null);
}
}
cfgInstSrv.delete(instance);
/** Log to MySQL */
logSrv.LogToMysql(
"Delete",
"Software Config",
"Delete config instance, targetId: " + instance.getTargetId() + "",
null);
}
}
if (cfgId.getDefaultContentId() != null) {
CfgContent defaultCnt = cfgCntSrv.findById(cfgId.getDefaultContentId());
if (defaultCnt != null) {
cfgCntSrv.delete(defaultCnt);
/** Log to MySQL */
logSrv.LogToMysql(
"Delete",
"Software Config",
"Delete default content of config, config pathName:"
+ cfgId.getPathName()
+ ", config targetType: "
+ cfgId.getTargetType()
+ ", software name:"
+ cfgId.getUserName()
+ "",
null);
}
}
cfgIdSrv.delete(cfgId);
/** Log to MySQL */
logSrv.LogToMysql(
"Delete",
"Software Config",
"Delete config, software name: "
+ cfgId.getUserName()
+ ", "
+ "config pathname: "
+ cfgId.getPathName()
+ " , "
+ "config targetType:"
+ cfgId.getTargetType()
+ "",
null);
}
return new ResponseEntity<String>(HttpStatus.OK);
}
/**
* ----------------------------------------------------------------
*
* <p>Chapter 2.4.5 Query shared configuration content information
*
* <p>----------------------------------------------------------------
*/
/**
* User query configuration content information
*
* <p>RESTful API: GET /ams/v1/config/shared
*
* @return an instance of ResponseEntity<String> with response code
*/
// @RequestMapping(value = "/ams/v1/config/shared", produces =
// "application/json",
// method = RequestMethod.GET)
// @ResponseBody
// public ResponseEntity<String>
// getSharedContent(@RequestParam(value = "shared_name", required = false)
// String sharedName,
// @RequestParam(value = "name_like", required = false) String nameLike,
// @RequestParam(value = "tag", required = false) String tag) {
//
// if (sharedName != null || nameLike != null || tag != null) {
// if (sharedName != null) {
// CfgContent content = cfgCntSrv.findBySharedName(sharedName);
// if (content == null) {
// logger.warn("No shared content found for " + sharedName);
// return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
// }
// return new ResponseEntity<String>(cfgContentSerialize(content).toString(),
// HttpStatus.OK);
// } else {
//
// JsonArray jResult = new JsonArray();
// List<CfgContent> cntList = null;
//
// if (tag != null && nameLike == null) {
// /* WHERE tag == ?tag */
// cntList = cfgCntSrv.findByTag(tag);
// } else if (tag == null && nameLike != null) {
// /* WHERE sharedName like ?nameLike */
// cntList = cfgCntSrv.findByNameLike(nameLike);
// } else { // tag != null && nameLike != null
// /* WHERE tag == ?tag AND sharedName like ?nameLike */
// cntList = cfgCntSrv.findByNameLikeAndTag(nameLike, tag);
// }
//
// if (cntList != null) {
// for (CfgContent content : cntList) {
// jResult.add(cfgContentSerialize(content));
// }
// } else {
// logger.warn("No shared content found for *" + nameLike + "*" + " with tag "
// + (tag == null ? "null" : tag));
// }
// return new ResponseEntity<String>(jResult.toString(), HttpStatus.OK);
// }
// }
//
// JsonArray jResult = new JsonArray();
//
// List<CfgContent> cntList = cfgCntSrv.findAll();
// if (cntList != null) {
// for (CfgContent content : cntList) {
// jResult.add(cfgContentSerialize(content));
// }
// } else {
// logger.warn("No shared content found in server!");
// }
//
// return new ResponseEntity<String>(jResult.toString(), HttpStatus.OK);
// }
@RequestMapping(
value = "/ams/v1/config/shared",
produces = "application/json",
method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<String> getSharedContent_new(
@RequestParam(value = "shared_name", required = false) String sharedName,
@RequestParam(value = "name_like", required = false) String nameLike,
@RequestParam(value = "tag", required = false) String tag,
@RequestParam(value = "content_type", required = false) Integer contentType,
@RequestParam(value = "fuzz_str", required = false) String fuzzStr,
@RequestParam(value = "offset", required = false) Integer offset,
@RequestParam(value = "limit", required = false) Integer limit) {
logger.debug(
"getCfgContent shared_name={}, name_like={}, tag={},content_type={}, fuzz_str={}",
sharedName,
nameLike,
tag,
contentType,
fuzzStr);
JsonArray jResult = new JsonArray();
List<CfgContent> cntList = null;
if (sharedName == null
&& nameLike == null
&& tag == null
&& contentType == null
&& fuzzStr == null) {
logger.warn(
"At least, should give \"fuzz_str=\" or one of sharedName, nameLike,tag or contentType");
return new ResponseEntity<String>(HttpStatus.BAD_REQUEST);
}
if (fuzzStr != null
&& (sharedName != null || nameLike != null || tag != null || contentType != null)) {
return new ResponseEntity<String>(
"Fuzzy search cannot be used together with other parameters.", HttpStatus.BAD_REQUEST);
}
// right now, contentType can't be used with other parameters.
if (contentType != null && (sharedName != null || nameLike != null || tag != null)) {
return new ResponseEntity<String>(
"Query parameter contentType cannot be used together with other parameters.",
HttpStatus.BAD_REQUEST);
}
if (offset != null) {
if (offset < 0) {
logger.warn("offset must be equal to or larger than 0.");
return new ResponseEntity<String>(
"offset must be equal to or larger than 0.", HttpStatus.BAD_REQUEST);
}
} else {
offset = DFLTOFFSET;
}
if (limit != null) {
if (limit > MAXLIMIT) {
logger.warn("limit is too large");
return new ResponseEntity<String>("limit is too large", HttpStatus.BAD_REQUEST);
}
} else {
limit = DFLTLIMIT;
}
if (sharedName != null || nameLike != null || tag != null) {
if (sharedName != null) {
CfgContent content = cfgCntSrv.findBySharedName(sharedName);
if (content == null) {
logger.warn("No shared content found for " + sharedName);
return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<String>(cfgContentSerialize(content).toString(), HttpStatus.OK);
} else {
if (tag != null && nameLike == null) {
/* WHERE tag == ?tag */
cntList = cfgCntSrv.findByTag(tag);
} else if (tag == null && nameLike != null) {
/* WHERE sharedName like ?nameLike */
cntList = cfgCntSrv.findByNameLike(nameLike);
} else { // tag != null && nameLike != null
/* WHERE tag == ?tag AND sharedName like ?nameLike */
cntList = cfgCntSrv.findByNameLikeAndTag(nameLike, tag);
}
if (cntList != null) {
for (CfgContent content : cntList) {
jResult.add(cfgContentSerialize(content));
}
} else {
logger.warn(
"No shared content found for *"
+ nameLike
+ "*"
+ " with tag "
+ (tag == null ? "null" : tag));
}
return new ResponseEntity<String>(jResult.toString(), HttpStatus.OK);
}
} else {
// find one type content or fuzz search.
if (contentType != null) {
cntList = cfgCntSrv.findByType(contentType);
} else if (fuzzStr != null) {
logger.debug("fuzzStr={}, size={}", fuzzStr, fuzzStr.length());
cntList = cfgCntSrv.fuzzySearch(fuzzStr, offset, limit);
}
}
if (cntList != null) {
for (CfgContent content : cntList) {
jResult.add(cfgContentSerialize(content));
}
} else {
logger.warn("No shared content found in server!");
}
return new ResponseEntity<String>(jResult.toString(), HttpStatus.OK);
}
/**
* ----------------------------------------------------------------
*
* <p>Chapter 2.4.6 Create/Update shared configuration content
*
* <p>----------------------------------------------------------------
*/
/**
* Create/Update shared configuration content
*
* <p>RESTful API: POST /ams/v1/config/shared
*
* @return an instance of ResponseEntity<String> with response code
*/
@RequestMapping(
value = "/ams/v1/config/shared",
produces = "application/json",
method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<String> postSharedContent(@RequestBody Map<String, String> payload) {
if (payload == null || payload.size() == 0 || payload.get("content") == null) {
logger.warn("payload.content is empty");
return new ResponseEntity<String>(
"content in payload cannot be null", HttpStatus.BAD_REQUEST);
}
if (payload.get("shared_name") == null) {
logger.warn("payload.shared_name is empty");
return new ResponseEntity<String>(
"\"shared_name\" in payload cannot be null", HttpStatus.BAD_REQUEST);
}
String hash = HashUtils.getMd5Hash(payload.get("content").getBytes());
CfgContent content = cfgCntSrv.findBySharedName(payload.get("shared_name"));
if (content == null) {
content = new CfgContent();
content.setContentType(1);
content.setSharedName(payload.get("shared_name"));
content.setContent(payload.get("content"));
content.setContentHash(hash);
content.setTag(payload.get("tag"));
content.setDescription(payload.get("description"));
cfgCntSrv.save(content);
/** Log to MySQL */
logSrv.LogToMysql(
"Add",
"Shared Content",
"Add shared content, shared name:" + content.getSharedName() + "",
null);
} else {
content.setContent(payload.get("content"));
content.setContentHash(hash);
if (payload.get("tag") != null) content.setTag(payload.get("tag"));
if (payload.get("description") != null) content.setDescription(payload.get("description"));
cfgCntSrv.update(content);
/** Log to MySQL */
logSrv.LogToMysql(
"Update",
"Shared Content",
"Update shared content, shared name:" + content.getSharedName() + "",
null);
}
return new ResponseEntity<String>(HttpStatus.OK);
}
/**
* ----------------------------------------------------------------
*
* <p>Chapter 2.4.7 Delete shared configuration content
*
* <p>----------------------------------------------------------------
*/
/**
* Delete shared configuration content
*
* <p>RESTful API: DELETE /ams/v1/config/shared
*
* @return an instance of ResponseEntity<String> with response code
*/
@RequestMapping(
value = "/ams/v1/config/shared",
produces = "application/json",
method = RequestMethod.DELETE)
public ResponseEntity<String> deleteSharedCnt(
@RequestParam(value = "shared_name", required = false) String sharedName) {
/** TODO: how to deal with the instance which use the shared content */
if (sharedName != null) {
CfgContent content = cfgCntSrv.findBySharedName(sharedName);
if (content != null) {
cfgCntSrv.delete(content);
/** Log to MySQL */
logSrv.LogToMysql(
"Delete",
"Shared Content",
"Delete shared content, shared name:" + content.getSharedName() + "",
null);
}
}
return new ResponseEntity<String>(HttpStatus.OK);
}
/**
* ----------------------------------------------------------------
*
* <p>Chapter 2.4.8 Query configuration instance information
*
* <p>----------------------------------------------------------------
*/
/**
* User query configuration instance information
*
* <p>RESTful API: GET /ams/v1/config/instance
*
* @return an instance of ResponseEntity<String> with response code
*/
@RequestMapping(
value = "/ams/v1/config/instance",
produces = "application/json",
method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<String> getCfgInstance(
@RequestParam(value = "product_name", required = true) String productName,
@RequestParam(value = "path_name", required = false) String pathName,
@RequestParam(value = "target_type", required = false) String targetType,
@RequestParam(value = "target_id", required = false) String targetId) {
if (targetId != null && targetType == null) {
return new ResponseEntity<String>(
"Query parameter \"target_id\" must be used together with \"target_type\"!",
HttpStatus.BAD_REQUEST);
}
Product p = pSrv.findByName(productName);
if (p == null) {
return new ResponseEntity<String>("Unknown Product: " + productName, HttpStatus.BAD_REQUEST);
}
if (pathName != null) {
pathName.trim().replaceAll("\\\\", "/");
if (pathName.startsWith("./")) {
pathName = pathName.substring(1);
} else {
if (!pathName.startsWith("/")) {
pathName = "/" + pathName;
}
}
}
JsonArray jResult = new JsonArray();
List<CfgIdentifier> idList = null;
if (pathName != null && targetType != null) {
CfgIdentifier cfgId =
cfgIdSrv.findByUserNameAndPathNameAndTargetType(p.getName(), pathName, targetType);
if (cfgId != null) {
idList = new ArrayList<CfgIdentifier>();
idList.add(cfgId);
}
}
if (pathName != null && targetType == null) {
idList = cfgIdSrv.findByUserNameAndPathName(productName, pathName);
}
if (pathName == null && targetType != null) {
idList = cfgIdSrv.findByUserNameAndTargetType(productName, targetType);
}
if (pathName == null && targetType == null) {
idList = cfgIdSrv.findByUserName(productName);
}
if (idList != null) {
for (CfgIdentifier cfgId : idList) {
if (targetId == null) {
List<CfgInstance> instanceList = cfgInstSrv.findByCfgIdentifierUUID(cfgId.getCfgUuid());
if (instanceList != null) {
for (CfgInstance instance : instanceList) {
JsonObject j = cfgInstanceSerialize(cfgId, instance);
if (j != null) {
jResult.add(j);
}
}
}
} else {
CfgInstance cfgInstance =
cfgInstSrv.findByCfgIdentifierUUIDAndTargetId(cfgId.getCfgUuid(), targetId);
if (cfgInstance != null) {
JsonObject j = cfgInstanceSerialize(cfgId, cfgInstance);
if (j != null) {
jResult.add(j);
}
}
}
}
}
return new ResponseEntity<String>(jResult.toString(), HttpStatus.OK);
}
/**
* ----------------------------------------------------------------
*
* <p>Chapter 2.4.9 Delete configuration instance
*
* <p>----------------------------------------------------------------
*/
/**
* Delete configuration instance
*
* <p>RESTful API: DELETE /ams/v1/config/instance
*
* @return an instance of ResponseEntity<String> with response code
*/
@RequestMapping(
value = "/ams/v1/config/instance",
produces = "application/json",
method = RequestMethod.DELETE)
public ResponseEntity<String> deleteCfgInstance(
@RequestParam(value = "product_name", required = true) String productName,
@RequestParam(value = "path_name", required = true) String pathName,
@RequestParam(value = "target_type", required = true) String targetType,
@RequestParam(value = "target_id", required = true) String targetId) {
Product p = pSrv.findByName(productName);
if (p == null) {
return new ResponseEntity<String>("Unknown Product: " + productName, HttpStatus.BAD_REQUEST);
}
if (pathName != null) {
pathName.trim().replaceAll("\\\\", "/");
if (pathName.startsWith("./")) {
pathName = pathName.substring(1);
} else {
if (!pathName.startsWith("/")) {
pathName = "/" + pathName;
}
}
}
CfgIdentifier cfgId =
cfgIdSrv.findByUserNameAndPathNameAndTargetType(p.getName(), pathName, targetType);
if (cfgId != null) {
CfgInstance instance =
cfgInstSrv.findByCfgIdentifierUUIDAndTargetId(cfgId.getCfgUuid(), targetId);
if (instance != null) {
CfgContent content = cfgCntSrv.findById(instance.getContentId());
if (content != null) {
if (content.getContentType() == 2) {
cfgCntSrv.delete(content);
/** Log to MySQL */
logSrv.LogToMysql(
"Delete",
"Software Config",
"Delete customized content of instance whose target id: "
+ instance.getTargetId()
+ "",
null);
}
}
cfgInstSrv.delete(instance);
/** Log to MySQL */
logSrv.LogToMysql(
"Delete",
"Software Config",
"Delete config instance, targetId: " + instance.getTargetId() + "",
null);
}
}
return new ResponseEntity<String>(HttpStatus.OK);
}
/**
* Serialize the Configuration identifier to JSON Object
*
* @return the JSON object serialized from the configuration identifier.
*/
private JsonObject cfgIdSerialize(CfgIdentifier cfgId) {
Product p = pSrv.findByName(cfgId.getUserName());
if (p == null) {
return null;
}
JsonObject jCfgId = new JsonObject();
jCfgId.addProperty("cfg_uuid", cfgId.getCfgUuid());
jCfgId.addProperty("product_name", p.getName());
jCfgId.addProperty("path_name", cfgId.getPathName());
jCfgId.addProperty("target_type", cfgId.getTargetType());
if (cfgId.getDefaultContentId() != null) {
CfgContent content = cfgCntSrv.findById(cfgId.getDefaultContentId());
if (content != null && !content.equals("")) {
jCfgId.addProperty("default_content", new String(content.getContent()));
}
}
if (cfgId.getSchema() != null) {
jCfgId.addProperty("schema", cfgId.getSchema());
}
return jCfgId;
}
/**
* Serialize the Configuration instance to JSON Object
*
* @return the JSON object serialized from the configuration instance.
*/
private JsonObject cfgInstanceSerialize(CfgIdentifier cfgId, CfgInstance cfgInstance) {
Product p = pSrv.findByName(cfgId.getUserName());
if (p == null) {
return null;
}
JsonObject jCfgInstance = new JsonObject();
jCfgInstance.addProperty("cfg_uuid", cfgId.getCfgUuid());
jCfgInstance.addProperty("product_name", p.getName());
jCfgInstance.addProperty("path_name", cfgId.getPathName());
jCfgInstance.addProperty("target_type", cfgId.getTargetType());
if (cfgInstance.getTargetId() != null) {
jCfgInstance.addProperty("target_id", cfgInstance.getTargetId());
}
if (cfgInstance.getContentId() != null) {
CfgContent content = cfgCntSrv.findById(cfgInstance.getContentId());
if (content != null && !content.equals("")) {
if (content.getContentType() == 1) {
if (content.getSharedName() != null) {
jCfgInstance.addProperty("content_name", content.getSharedName());
jCfgInstance.addProperty("content", new String(content.getContent()));
}
} else if (content.getContentType() == 2) {
jCfgInstance.addProperty("content", new String(content.getContent()));
}
}
}
return jCfgInstance;
}
/**
* Serialize the Configuration content to JSON Object
*
* @return the JSON object serialized from the configuration content.
*/
private JsonObject cfgContentSerialize(CfgContent content) {
if (content == null) {
return null;
}
JsonObject jCfgContent = new JsonObject();
if (content.getSharedName() != null) {
jCfgContent.addProperty("shared_name", content.getSharedName());
}
jCfgContent.addProperty("content_hash", content.getContentHash());
if (content.getFormatId() != null) {
jCfgContent.addProperty("format_id", content.getFormatId());
}
if (content.getTag() != null) {
jCfgContent.addProperty("tag", content.getTag());
}
if (content.getDescription() != null) {
jCfgContent.addProperty("description", content.getDescription());
}
jCfgContent.addProperty("content", new String(content.getContent()));
return jCfgContent;
}
private PostCfgIdPayload parseCfgIdPayload(String strPayload) {
if (strPayload == null) {
return null;
}
PostCfgIdPayload payload;
Gson gson = new Gson();
try {
payload = gson.fromJson(strPayload, PostCfgIdPayload.class);
} catch (JsonSyntaxException jse) {
return null;
}
return payload;
}
/**
* Added by WangNing
*
* <p>RESTful Api:// GET ams/v1/config/getClientdifferCfgs //
*/
@RequestMapping(
value = "/ams/v1/config/getClientdifferCfgs",
produces = "application/json",
method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<String> getClientCfgs(
@RequestParam(value = "clientId", required = true) String clientId) {
AmsClient client = amsSrv.findByClientUUID(clientId);
if (client == null)
return new ResponseEntity<String>(
"Cannot find client with clientUuId: " + clientId, HttpStatus.BAD_REQUEST);
List<ClientCfgCheckPoint> cpList = clickpSrv.findByClientId(client.getId());
if (cpList == null)
return new ResponseEntity<String>(
"Cannot find client checkpoint with clientUuId: " + clientId, HttpStatus.BAD_REQUEST);
AmsTemplate template = amsTpltSrv.findByName(client.getTemplateName());
List<TemplateItem> tempList = null;
if (template != null) {
tempList = parseTemplateContent(template.getContent());
}
// get template_item list in project template content
AmsTemplate proj_template = amsTpltSrv.findByName("projectId_" + client.getProjectId() + "");
List<TemplateItem> proj_itemList = null;
if (proj_template != null) {
proj_itemList = parseTemplateContent(proj_template.getContent());
}
// get template_item list in global template content
AmsTemplate global_template = amsTpltSrv.findByName("_global_");
List<TemplateItem> global_itemList = null;
if (global_template != null) {
global_itemList = parseTemplateContent(global_template.getContent());
}
JsonArray jResult = new JsonArray();
for (ClientCfgCheckPoint cp : cpList) {
List<CfgIdentifier> idList =
cfgIdSrv.findByUserNameAndTargetType(cp.getProductName(), cp.getTargetType());
if (idList == null) {
continue;
}
for (CfgIdentifier id : idList) {
/**
* priority : INSTANCE 1st; TEMPLATE 2nd; DEFAULT 3rd;
*
* <p>mark the state and source;
*
* <p>if( targetId exist ) // the ConfigData from Client include targetId { if ( the content
* searched by targetId&ClientUuid exist) { if content.hashcode equals to the
* configcontent.hashcode in cloud then sync_state is sync(synchronized)
*
* <p>if contend.hashcode doesn't equals to the config.hashcode in cloud the sync_state is
* update(Client local should be updated) } else { goto next if (template or default); }
*
* <p>*** anyway, the config should always be updated to the cloud; ***
*
* <p>in this situation, the source is CUSTOM; }
*
* <p>else if (targetId is null) // { if( templates searched by clientId exist ) { loop the
* templates ; then source is TEMPLATE; } else { goto default; source is DEFAULT; } sync is
* NEW; }
*/
String Src = "";
String Sync = "";
CfgContent content = null;
/** Step 1: Find exact instance content */
if (cp.getTargetId() != null && !cp.getTargetId().equals("")) {
CfgInstance instance =
cfgInstSrv.findByCfgIdentifierUUIDAndTargetId(id.getCfgUuid(), cp.getTargetId());
if (instance != null && instance.getContentId() != null) {
content = cfgCntSrv.findById(instance.getContentId());
Src = "CUSTOM";
}
}
/** Step 2: Find template content */
if (content == null && tempList != null) {
for (TemplateItem item : tempList) {
boolean isFoundProduct = false;
if (item.getProductName() != null
&& item.getProductName().equals(cp.getProductName())) {
isFoundProduct = true;
if (item.getCfgs() != null) {
for (TemplateConfigItem cfgItem : item.getCfgs()) {
String pathName = cfgItem.getPathName();
pathName.trim().replaceAll("\\\\", "/");
if (pathName.startsWith("./")) {
pathName = pathName.substring(1);
} else {
if (!pathName.startsWith("/")) {
pathName = "/" + pathName;
}
}
String cfgType = cfgItem.getCfgType();
if (pathName.equals(id.getPathName()) && cfgType.equals(id.getTargetType())) {
content = cfgCntSrv.findBySharedName(cfgItem.getContentName());
Src = "TEMPLATE";
break;
}
}
}
}
if (isFoundProduct) {
break;
}
}
}
/** Step 2.2: Find project default template content */
if (content == null && global_itemList != null) {
for (TemplateItem item : global_itemList) {
boolean isFoundProduct = false;
if (item.getProductName() != null
&& item.getProductName().equals(cp.getProductName())) {
isFoundProduct = true;
if (item.getCfgs() != null) {
for (TemplateConfigItem cfgItem : item.getCfgs()) {
String pathName = cfgItem.getPathName();
pathName.trim().replaceAll("\\\\", "/");
if (pathName.startsWith("./")) {
pathName = pathName.substring(1);
} else {
if (!pathName.startsWith("/")) {
pathName = "/" + pathName;
}
}
String cfgType = cfgItem.getCfgType();
if (pathName.equals(id.getPathName()) && cfgType.equals(id.getTargetType())) {
content = cfgCntSrv.findBySharedName(cfgItem.getContentName());
Src = "TEMPLATE";
break;
}
}
}
}
if (isFoundProduct) {
break;
}
}
}
/** Step 2.3: Find global template content */
if (content == null && global_itemList != null) {
for (TemplateItem item : global_itemList) {
boolean isFoundProduct = false;
if (item.getProductName() != null
&& item.getProductName().equals(cp.getProductName())) {
isFoundProduct = true;
if (item.getCfgs() != null) {
for (TemplateConfigItem cfgItem : item.getCfgs()) {
String pathName = cfgItem.getPathName();
pathName.trim().replaceAll("\\\\", "/");
if (pathName.startsWith("./")) {
pathName = pathName.substring(1);
} else {
if (!pathName.startsWith("/")) {
pathName = "/" + pathName;
}
}
String cfgType = cfgItem.getCfgType();
if (pathName.equals(id.getPathName()) && cfgType.equals(id.getTargetType())) {
content = cfgCntSrv.findBySharedName(cfgItem.getContentName());
Src = "TEMPLATE";
break;
}
}
}
}
if (isFoundProduct) {
break;
}
}
}
/** Step 3: Find default content */
if (content == null && id.getDefaultContentId() != null) {
content = cfgCntSrv.findById(id.getDefaultContentId());
Src = "DEFAULT";
}
/**
* Step 4: Add cfg to response only if the deployed cfg is different with the client current
* cfg
*/
if (content != null) {
ClientCurrentCfg currentCfg =
clicSrv.findByClientIdAndProductNameAndTargetTypeAndTargetIdAndPathName(
cp.getClientId(),
cp.getProductName(),
cp.getTargetType(),
cp.getTargetId(),
id.getPathName());
JsonObject jElement = new JsonObject();
if (cp.getTargetId() != "") {
jElement.addProperty("tid", cp.getTargetId());
}
jElement.addProperty("pn", id.getUserName());
jElement.addProperty("tt", cp.getTargetType());
jElement.addProperty("path", id.getPathName());
jElement.addProperty("id", content.getId().toString());
/** CUSTOM: the hash in ClientCurrentCfg is equals content.hash */
if (currentCfg != null && currentCfg.getHash().equals(content.getContentHash())) {
Sync = "sync";
} else if (currentCfg != null && !currentCfg.getHash().equals(content.getContentHash())) {
Sync = "update";
} else {
Sync = "new";
}
jElement.addProperty("Sync", Sync);
jElement.addProperty("Src", Src);
jResult.add(jElement);
}
}
}
return new ResponseEntity<String>(jResult.toString(), HttpStatus.OK);
}
// end
private List<TemplateItem> parseTemplateContent(String content) {
List<TemplateItem> list;
Gson gson = new Gson();
try {
list = gson.fromJson(content, new TypeToken<List<TemplateItem>>() {}.getType());
} catch (JsonSyntaxException jse) {
return null;
}
return list;
}
}
|
Zueuk/JitCat
|
include/jitcat/CatOperatorNewArray.h
|
<reponame>Zueuk/JitCat<filename>include/jitcat/CatOperatorNewArray.h
/*
This file is part of the JitCat library.
Copyright (C) <NAME> 2019
Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT).
*/
#pragma once
#include "jitcat/CatTypedExpression.h"
namespace jitcat::AST
{
class CatTypeNode;
class CatOperatorNewArray: public CatTypedExpression
{
public:
CatOperatorNewArray(CatTypeNode* arrayItemType, const Tokenizer::Lexeme& lexeme);
CatOperatorNewArray(const CatOperatorNewArray& other);
virtual CatASTNode* copy() const override final;
virtual void print() const override final;
virtual CatASTNodeType getNodeType() const override final;
virtual std::any execute(CatRuntimeContext* runtimeContext) override final;
virtual bool typeCheck(CatRuntimeContext* compiletimeContext, ExpressionErrorManager* errorManager, void* errorContext) override final;
virtual const CatGenericType& getType() const override final;
virtual bool isConst() const override final;
virtual CatTypedExpression* constCollapse(CatRuntimeContext* compileTimeContext) override final;
private:
std::unique_ptr<CatTypeNode> arrayType;
CatGenericType newType;
};
}
|
Foxcapades/lib-go-raml
|
v0/internal/util/assign/any-map.go
|
<gh_stars>0
package assign
import (
"github.com/Foxcapades/lib-go-raml/v0/pkg/raml"
"github.com/Foxcapades/lib-go-yaml/v1/pkg/xyml"
"gopkg.in/yaml.v3"
)
// ToStringMap appends the values of the given YAML mapping to the given
// StringMap.
func ToStringMap(v *yaml.Node, ref raml.StringMap) error {
return xyml.MapForEach(v, func(key, val *yaml.Node) error {
if err := xyml.RequireString(key); err != nil {
return err
} else if err := xyml.RequireString(val); err != nil {
return err
}
ref.Put(key.Value, val.Value)
return nil
})
}
// TODO: decompose the yaml node further
func ToUntypedMap(y *yaml.Node, ref raml.UntypedMap) error {
return xyml.MapForEach(y, func(k, v *yaml.Node) error {
if err := xyml.RequireString(k); err != nil {
return err
}
ref.Put(k.Value, v)
return nil
})
}
|
Chupik/Mixbox
|
Frameworks/InAppServices/Sources/Support/AccessibilityForTestAutomation/AccessibilityForTestAutomationInitializer/Implementation/ObjectiveC/LibAccessibilityAccessibilityInitializer/LibAccessibilityAccessibilityInitializer.h
|
<reponame>Chupik/Mixbox
#ifdef MIXBOX_ENABLE_IN_APP_SERVICES
@import Foundation;
@interface LibAccessibilityAccessibilityInitializer : NSObject
- (nullable NSString *)initializeAccessibilityOrReturnError;
@end
#endif
|
ryoma-jp/samples
|
python/correlation-analysis_causal-analysis/lib/correlation_analysis.py
|
<gh_stars>0
#! -*- coding: utf-8 -*-
#---------------------------------
# モジュールのインポート
#---------------------------------
import numpy as np
#---------------------------------
# 定数定義
#---------------------------------
#---------------------------------
# 関数 : ピアソンの積率相関係数
# [Input]
# * x: 独立変数(ndarray)
# * y: 従属変数(ndarray)
# [Output]
# * r: ピアソンの積率相関係数
# [T.B.D]
# * 多次元のデータ間の相関が計算できるように拡張したい
#---------------------------------
def peason(x, y):
x_err = x - x.mean()
y_err = y - y.mean()
r = np.dot(x_err, y_err) / np.sqrt(np.sum(x_err ** 2) * np.sum(y_err ** 2))
return r
#---------------------------------
# 関数 : スピアマンの順位相関係数
# [Input]
# * x: 独立変数(ndarray)
# * y: 従属変数(ndarray)
# [Output]
# * rho: スピアマンの順位相関係数
#---------------------------------
def spearman(x, y):
n = len(x)
rho = 1 - (6 * np.sum((x-y)**2)) / (n * (n+1) * (n-1))
return rho
#---------------------------------
# 関数 : メイン関数(ライブラリのテスト用)
#---------------------------------
def main():
import argparse
def _argparse():
parser = argparse.ArgumentParser(description='相関分析モジュールのテスト',
formatter_class=argparse.RawTextHelpFormatter)
# --- 引数を追加 ---
# [T.B.D]
args = parser.parse_args()
return args
# --- 引数処理 ---
args = _argparse()
print('[INFO] Arguments')
print(' * T.B.D')
# --- データを乱数で生成(1D) ---
rng = np.random.default_rng(seed=1234)
x = rng.random(3)
y = rng.random(3)
print("[Peason (1D input)]")
print(" * np.corrcoef = {}".format(np.corrcoef(x, y)))
print(" * peason = {}".format(peason(x, y)))
# --- データを乱数で生成(2D) ---
rng = np.random.default_rng(seed=1234)
x = rng.random([3, 3])
y = rng.random([3, 3])
corrcoef = np.corrcoef(x, y, rowvar=True)
print("[Peason (2D input)]")
print(" * np.corrcoef = {}".format(corrcoef))
print(" * np.corrcoef.shape = {}".format(corrcoef.shape))
print(" * peason = {}".format([peason(x[0], x[i]) for i in range(3)]))
print(" * peason = {}".format([peason(x[1], x[i]) for i in range(3)]))
print(" * peason = {}".format([peason(x[2], x[i]) for i in range(3)]))
print(" * peason = {}".format([peason(x[0], y[i]) for i in range(3)]))
print(" * peason = {}".format([peason(x[1], y[i]) for i in range(3)]))
print(" * peason = {}".format([peason(x[2], y[i]) for i in range(3)]))
print(" * peason = {}".format([peason(y[0], x[i]) for i in range(3)]))
print(" * peason = {}".format([peason(y[1], x[i]) for i in range(3)]))
print(" * peason = {}".format([peason(y[2], x[i]) for i in range(3)]))
print(" * peason = {}".format([peason(y[0], y[i]) for i in range(3)]))
print(" * peason = {}".format([peason(y[1], y[i]) for i in range(3)]))
print(" * peason = {}".format([peason(y[2], y[i]) for i in range(3)]))
return
#---------------------------------
# メイン処理
#---------------------------------
if __name__ == '__main__':
main()
|
Gems/prowide-iso20022
|
model-acmt-types/src/generated/java/com/prowidesoftware/swift/model/mx/dic/OriginalTransactionReference14.java
|
<reponame>Gems/prowide-iso20022
package com.prowidesoftware.swift.model.mx.dic;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.datatype.XMLGregorianCalendar;
import com.prowidesoftware.swift.model.mx.adapters.IsoDateTimeAdapter;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
/**
* Set of elements used to provide reference information to the original message.
*
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "OriginalTransactionReference14", propOrder = {
"msgId",
"msgNmId",
"creDtTm",
"orgnlTx"
})
public class OriginalTransactionReference14 {
@XmlElement(name = "MsgId")
protected String msgId;
@XmlElement(name = "MsgNmId")
protected String msgNmId;
@XmlElement(name = "CreDtTm", type = String.class)
@XmlJavaTypeAdapter(IsoDateTimeAdapter.class)
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar creDtTm;
@XmlElement(name = "OrgnlTx")
protected List<PaymentIdentification3> orgnlTx;
/**
* Gets the value of the msgId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMsgId() {
return msgId;
}
/**
* Sets the value of the msgId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public OriginalTransactionReference14 setMsgId(String value) {
this.msgId = value;
return this;
}
/**
* Gets the value of the msgNmId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMsgNmId() {
return msgNmId;
}
/**
* Sets the value of the msgNmId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public OriginalTransactionReference14 setMsgNmId(String value) {
this.msgNmId = value;
return this;
}
/**
* Gets the value of the creDtTm property.
*
* @return
* possible object is
* {@link String }
*
*/
public XMLGregorianCalendar getCreDtTm() {
return creDtTm;
}
/**
* Sets the value of the creDtTm property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public OriginalTransactionReference14 setCreDtTm(XMLGregorianCalendar value) {
this.creDtTm = value;
return this;
}
/**
* Gets the value of the orgnlTx property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the orgnlTx property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getOrgnlTx().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link PaymentIdentification3 }
*
*
*/
public List<PaymentIdentification3> getOrgnlTx() {
if (orgnlTx == null) {
orgnlTx = new ArrayList<PaymentIdentification3>();
}
return this.orgnlTx;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
@Override
public boolean equals(Object that) {
return EqualsBuilder.reflectionEquals(this, that);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
/**
* Adds a new item to the orgnlTx list.
* @see #getOrgnlTx()
*
*/
public OriginalTransactionReference14 addOrgnlTx(PaymentIdentification3 orgnlTx) {
getOrgnlTx().add(orgnlTx);
return this;
}
}
|
8LabSolutions/Soldino-Poc
|
src/components/containers/BusinessListContainer.js
|
/* eslint-disable no-unused-vars */
import { connect } from 'react-redux';
import React from 'react';
import { withToastManager } from 'react-toast-notifications';
import UsersList from '../presentational/UsersList';
import governmentActionCreator from "../../actionsCreator/governmentActionCreator"
import {BUSINESS} from "../../constants/actionTypes"
import ButtonState from './ButtonState';
import { printShipment } from '../../auxiliaryFunctions';
import { searchaction } from '../../actions/searchaction';
import { ERRORTOAST } from '../../constants/fixedValues';
/**
* @description map the resetSearch, getUserList, printUser actions into the UsersList component
* @param {*} dispatch
* @param {*} ownProps
*/
const mapDispatchToProps = (dispatch, ownProps) => {
const { toastManager } = ownProps;
return {
/**
* @description reset the searched string
*/
resetSearch: () => {
dispatch(searchaction(""))
},
/**
* @description get all the business users in a list
* @param {*} amount users to get
* @param {*} index start value (index*amount is the first user position)
*/
getUserList: (amount, index)=> {
governmentActionCreator.getUserList(amount, index, BUSINESS)
.then((action)=>{
dispatch(action);
})
.catch((err)=>{
toastManager.add(err, ERRORTOAST);
})
},
/**
* @description print a formatted business user
* @param {*} business to print
*/
printUser: (business)=>{
let dynamicText
(business.state===true) ? dynamicText="Disable" : dynamicText="Enable";
var button = <ButtonState text={dynamicText} state={business.state} address={business.address} type={BUSINESS} />
const Line = (business) =>(
<li key={business.address} className="list-group-item userlist-item">
<strong className="customCursor">Company name: </strong>
<span className="customCursor">{business.name}</span>
<br />
<strong className="customCursor">VAT number: </strong>
<span className="customCursor">{business.VATnumber}</span>
<br />
<strong className="customCursor">Email: </strong>
<span className="customCursor">{business.email}</span>
<br />
<strong className="customCursor">Wallet address: </strong>
<span className="customCursor">{business.address}</span>
<br />
<strong className="customCursor">Headquarters: </strong>
<span className="customCursor">{printShipment([business.streetName, business.streetNumber, business.postCode, business.district])}</span>
<br />
{button}
</li>
)
return Line(business);
}
}
}
/**
* @description map the businessList and searchProduct state values into the UsersList component
* @param {*} state
*/
const mapStateToProps = (state) => {
return {
userList: state.businessList,
searchProduct: state.searchProduct
}
}
/**
* @description connect the state and action to the UsersList props
*/
const BusinessListContainer = connect(mapStateToProps, mapDispatchToProps)(UsersList);
export default withToastManager(BusinessListContainer);
|
janesma/amd_gpa
|
Src/GPUPerfAPIDX12/DX12DataRequest.h
|
<reponame>janesma/amd_gpa<filename>Src/GPUPerfAPIDX12/DX12DataRequest.h
//==============================================================================
// Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved.
/// \author AMD Developer Tools Team
/// \file
/// \brief DX12DataRequest declaration
//==============================================================================
#ifndef _DX12_DATA_REQUEST_H_
#define _DX12_DATA_REQUEST_H_
#include <GPADataRequest.h>
/// DX12 counter data request
///
/// An intermediate DX12 data request interface to enable using the proxy design pattern
class DX12DataRequest : public GPA_DataRequest
{
public:
/// Destroy this DX12 counter data request instance
virtual ~DX12DataRequest();
virtual bool BeginRequest(
GPA_ContextState* pContextState,
gpa_uint32 selectionID,
const vector<gpa_uint32>* pCounters)
= 0;
virtual bool EndRequest() = 0;
virtual void ReleaseCounters() = 0;
/// Get the number of active counters
/// \return Get number of active counters
size_t GetActiveCountersCount() const;
protected:
/// Construct a DX12 counter data request instance
DX12DataRequest();
/// Set the number of active counters
/// \param[in] activeCountersCount The number of active counters
void SetActiveCountersCount(const size_t activeCountersCount);
private:
/// Copy constructor - private override to disable usage
DX12DataRequest(const DX12DataRequest& other) = delete;
/// Move constructor - private override to disable usage
DX12DataRequest(DX12DataRequest&& other) = delete;
/// Copy operator - private override to disable usage
DX12DataRequest& operator=(const DX12DataRequest& other) = delete;
/// Move operator - private override to disable usage
DX12DataRequest& operator=(DX12DataRequest&& other) = delete;
}; // end of class DX12DataRequest
#endif // _DX12_DATA_REQUEST_H_
|
Atul9/rails_event_store
|
rails_event_store/lib/rails_event_store/active_job_dispatcher.rb
|
require 'active_job'
module RailsEventStore
class ActiveJobDispatcher < RubyEventStore::AsyncDispatcher
def initialize(proxy_strategy: AsyncProxyStrategy::Inline.new)
super(proxy_strategy: proxy_strategy, scheduler: ActiveJobScheduler.new)
end
class ActiveJobScheduler
def call(klass, serialized_event)
klass.perform_later(serialized_event.to_h)
end
def async_handler?(klass)
Class === klass && klass < ActiveJob::Base
end
end
end
end
|
enrrou/otc-provider-jet
|
apis/networking/v1alpha1/zz_secgrouprulev2_types.go
|
/*
Copyright 2021 The Crossplane Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by terrajet. DO NOT EDIT.
package v1alpha1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
v1 "github.com/crossplane/crossplane-runtime/apis/common/v1"
)
type SecgroupRuleV2Observation struct {
ID *string `json:"id,omitempty" tf:"id,omitempty"`
}
type SecgroupRuleV2Parameters struct {
// +kubebuilder:validation:Optional
Description *string `json:"description,omitempty" tf:"description,omitempty"`
// +kubebuilder:validation:Required
Direction *string `json:"direction" tf:"direction,omitempty"`
// +kubebuilder:validation:Required
Ethertype *string `json:"ethertype" tf:"ethertype,omitempty"`
// +kubebuilder:validation:Optional
PortRangeMax *int64 `json:"portRangeMax,omitempty" tf:"port_range_max,omitempty"`
// +kubebuilder:validation:Optional
PortRangeMin *int64 `json:"portRangeMin,omitempty" tf:"port_range_min,omitempty"`
// +kubebuilder:validation:Optional
Protocol *string `json:"protocol,omitempty" tf:"protocol,omitempty"`
// +kubebuilder:validation:Optional
Region *string `json:"region,omitempty" tf:"region,omitempty"`
// +kubebuilder:validation:Optional
RemoteGroupID *string `json:"remoteGroupId,omitempty" tf:"remote_group_id,omitempty"`
// +kubebuilder:validation:Optional
RemoteIPPrefix *string `json:"remoteIpPrefix,omitempty" tf:"remote_ip_prefix,omitempty"`
// +kubebuilder:validation:Required
SecurityGroupID *string `json:"securityGroupId" tf:"security_group_id,omitempty"`
// +kubebuilder:validation:Optional
TenantID *string `json:"tenantId,omitempty" tf:"tenant_id,omitempty"`
}
// SecgroupRuleV2Spec defines the desired state of SecgroupRuleV2
type SecgroupRuleV2Spec struct {
v1.ResourceSpec `json:",inline"`
ForProvider SecgroupRuleV2Parameters `json:"forProvider"`
}
// SecgroupRuleV2Status defines the observed state of SecgroupRuleV2.
type SecgroupRuleV2Status struct {
v1.ResourceStatus `json:",inline"`
AtProvider SecgroupRuleV2Observation `json:"atProvider,omitempty"`
}
// +kubebuilder:object:root=true
// SecgroupRuleV2 is the Schema for the SecgroupRuleV2s API
// +kubebuilder:printcolumn:name="READY",type="string",JSONPath=".status.conditions[?(@.type=='Ready')].status"
// +kubebuilder:printcolumn:name="SYNCED",type="string",JSONPath=".status.conditions[?(@.type=='Synced')].status"
// +kubebuilder:printcolumn:name="EXTERNAL-NAME",type="string",JSONPath=".metadata.annotations.crossplane\\.io/external-name"
// +kubebuilder:printcolumn:name="AGE",type="date",JSONPath=".metadata.creationTimestamp"
// +kubebuilder:subresource:status
// +kubebuilder:resource:scope=Cluster,categories={crossplane,managed,otcjet}
type SecgroupRuleV2 struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec SecgroupRuleV2Spec `json:"spec"`
Status SecgroupRuleV2Status `json:"status,omitempty"`
}
// +kubebuilder:object:root=true
// SecgroupRuleV2List contains a list of SecgroupRuleV2s
type SecgroupRuleV2List struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []SecgroupRuleV2 `json:"items"`
}
// Repository type metadata.
var (
SecgroupRuleV2_Kind = "SecgroupRuleV2"
SecgroupRuleV2_GroupKind = schema.GroupKind{Group: CRDGroup, Kind: SecgroupRuleV2_Kind}.String()
SecgroupRuleV2_KindAPIVersion = SecgroupRuleV2_Kind + "." + CRDGroupVersion.String()
SecgroupRuleV2_GroupVersionKind = CRDGroupVersion.WithKind(SecgroupRuleV2_Kind)
)
func init() {
SchemeBuilder.Register(&SecgroupRuleV2{}, &SecgroupRuleV2List{})
}
|
ironjan/jeo
|
format/gdal/src/main/java/io/jeo/gdal/GDALDataset.java
|
/* Copyright 2014 The jeo project. 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.
*/
package io.jeo.gdal;
import io.jeo.geom.Bounds;
import io.jeo.raster.Band;
import io.jeo.raster.DataBuffer;
import io.jeo.raster.DataType;
import io.jeo.raster.Raster;
import io.jeo.raster.Stats;
import io.jeo.util.Dimension;
import io.jeo.util.Key;
import io.jeo.util.Rect;
import io.jeo.util.Util;
import org.gdal.gdal.Dataset;
import org.gdal.gdal.gdal;
import org.gdal.osr.SpatialReference;
import io.jeo.data.Driver;
import io.jeo.data.FileData;
import io.jeo.raster.RasterDataset;
import io.jeo.raster.RasterQuery;
import io.jeo.proj.Proj;
import org.osgeo.proj4j.CoordinateReferenceSystem;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static org.gdal.gdalconst.gdalconstConstants.*;
public class GDALDataset implements RasterDataset, FileData {
Dataset dataset;
File file;
GDAL driver;
public GDALDataset(File file, Dataset dataset, GDAL driver) {
this.file = file;
this.dataset = dataset;
this.driver = driver;
}
@Override
public File file() {
return file;
}
@Override
public String name() {
return Util.base(file.getName());
}
public String description() {
return dataset.GetDescription();
}
@Override
public Driver<?> driver() {
return driver;
}
@Override
public Map<Key<?>, Object> driverOptions() {
LinkedHashMap<Key<?>, Object> opts = new LinkedHashMap<Key<?>, Object>();
opts.put(GDAL.FILE, file);
return opts;
}
@Override
public CoordinateReferenceSystem crs() throws IOException {
String proj = dataset.GetProjection();
if (proj != null) {
SpatialReference ref = new SpatialReference(proj);
return Proj.crs(ref.ExportToProj4());
}
return null;
}
@Override
public Bounds bounds() throws IOException {
return bounds(dataset);
}
Bounds bounds(Dataset dataset) {
Dimension size = size(dataset);
double[] tx = dataset.GetGeoTransform();
return new Bounds(tx[0], tx[0] + size.width() * tx[1],
tx[3], tx[3] + size.width()*tx[4] + size.height()*tx[5]);
}
@Override
public Dimension size() {
return size(dataset);
}
Dimension size(Dataset dataset) {
return new Dimension(dataset.getRasterXSize(), dataset.getRasterYSize());
}
public Rect rect() {
return rect(dataset);
}
Rect rect(Dataset dataset) {
Dimension size = size(dataset);
return new Rect(0, 0, size.width(), size.height());
}
@Override
public List<Band> bands() throws IOException {
int nbands = dataset.GetRasterCount();
List<Band> bands = new ArrayList<Band>(nbands);
for (int i = 1; i <= nbands; i++) {
bands.add(new GDALBand(dataset.GetRasterBand(i)));
}
return bands;
}
@Override
public Raster read(RasterQuery query) throws IOException {
Raster raster = new Raster();
Dataset data = dataset;
// reprojection
raster.crs(crs());
if (query.crs() != null && !Proj.equal(query.crs(), crs())) {
String srcWkt = toWKT(crs());
String dstWkt = toWKT(query.crs());
//TODO: allow query to specify interpolation method
data = gdal.AutoCreateWarpedVRT(dataset, srcWkt, dstWkt);
raster.crs(query.crs());
}
// area of raster to load
Rect r = rect(data); // raster space
Bounds bbox = bounds(data); // world space
if (query.bounds() != null) {
// intersect bounds with query bounds
Bounds i = bbox.intersection(query.bounds());
r = r.map(i, bbox);
bbox = i;
}
raster.bounds(bbox);
// raster size
Dimension s = query.size();
if (s == null) {
// use the size of the query bounds if that is set
if(query.bounds()!=null) {
s = new Dimension(r.width(), r.height());
}
else {
s = size(data);
}
}
raster.size(s);
// band selection
List<GDALBand> queryBands = bands(query.bands());
int[] bands = new int[queryBands.size()];
for (int i = 0 ; i < queryBands.size(); i++) {
GDALBand band = queryBands.get(i);
bands[i] = band.index();
}
raster.bands((List)queryBands);
// figure out the buffer type if not specified
DataType datatype = query.datatype();
if (datatype == null) {
datatype = DataType.BYTE;
for (int i = 0 ; i < queryBands.size(); i++) {
GDALBand band = queryBands.get(i);
DataType dt = band.datatype();
if (dt.compareTo(datatype) > 0) {
datatype = dt;
}
}
}
ByteBuffer buffer = ByteBuffer.allocateDirect(s.width()*s.height()*datatype.size());
buffer.order(ByteOrder.nativeOrder());
if (bands.length == 1) {
// single band, read in same units as requested buffer
data.ReadRaster_Direct(r.left, r.top, r.width(), r.height(), s.width(), s.height(),
toGDAL(datatype), buffer, bands, 0, 0, 0);
}
else {
// multi band mode, read as byte and back into buffer
data.ReadRaster_Direct(r.left, r.top, r.width(), r.height(), s.width(), s.height(),
GDT_Byte, buffer, bands, datatype.size(), 0, 1);
}
return raster.data(DataBuffer.create(buffer, datatype));
}
int toGDAL(DataType datatype) {
switch(datatype) {
case CHAR:
break;
case BYTE:
return GDT_Byte;
case SHORT:
return GDT_Int16;
case INT:
return GDT_Int32;
case LONG:
return GDT_UInt32;
case FLOAT:
return GDT_Float32;
case DOUBLE:
return GDT_Float64;
}
throw new IllegalArgumentException("unsupported data type: " + datatype);
}
String toWKT(CoordinateReferenceSystem crs) {
SpatialReference ref = new SpatialReference();
ref.ImportFromProj4(Proj.toString(crs));
return ref.ExportToWkt();
}
List<GDALBand> bands(int[] bands) throws IOException {
List<Band> allBands = bands();
if (bands == null || bands.length == 0) {
return (List) allBands;
}
List<GDALBand> list = new ArrayList(bands.length);
for (int b : bands) {
list.add((GDALBand) allBands.get(b));
}
return list;
}
@Override
public void close() {
if (dataset != null) {
dataset.delete();
dataset = null;
}
}
static class GDALBand implements Band {
org.gdal.gdal.Band band;
GDALBand(org.gdal.gdal.Band band) {
this.band = band;
}
@Override
public String name() {
return band.GetDescription();
}
int index() {
return band.GetBand();
}
@Override
public Color color() {
int ci = band.GetColorInterpretation();
return ci == GCI_Undefined ? Color.UNDEFINED :
ci == GCI_GrayIndex ? Color.GRAY :
ci == GCI_RedBand ? Color.RED :
ci == GCI_GreenBand ? Color.GREEN :
ci == GCI_BlueBand ? Color.BLUE : Color.GRAY;
}
@Override
public DataType datatype() {
int dt = band.GetRasterDataType();
return dt == GDT_Byte ? DataType.BYTE :
dt == GDT_Int16 ? DataType.SHORT :
dt == GDT_UInt16 ? DataType.INT :
dt == GDT_Int32 ? DataType.INT :
dt == GDT_UInt32 ? DataType.LONG :
dt == GDT_Float32 ? DataType.FLOAT :
dt == GDT_Float64 ? DataType.DOUBLE :
null;
//TODO
//GDT_CInt16
//GDT_CInt32
//GDT_CFloat32
//GDT_CFloat64
}
@Override
public Double nodata() {
Double[] nodata = new Double[]{null};
band.GetNoDataValue(nodata);
return nodata[0];
}
@Override
public Stats stats() throws IOException {
Stats stats = new Stats();
double[] arr = new double[2];
band.ComputeRasterMinMax(arr);
stats.min(arr[0]).max(arr[1]);
band.ComputeBandStats(arr);
stats.mean(arr[0]).stdev(arr[1]);
return stats;
}
}
}
|
cablelabs/lpwanserver-web-client
|
src/components/fetch/FetchNetworks.js
|
<filename>src/components/fetch/FetchNetworks.js
import React from 'react';
import PT from 'prop-types';
import FetchResources from './FetchResources';
import networkStore from "../../stores/NetworkStore";
//******************************************************************************
// Interface
//******************************************************************************
// This is a render prop component. prop.render will be called
// when the fetch is complete, passing it the fetch results.
FetchNetworks.propTypes = {
id: PT.string,
// if provided, single network fetched, passes {network} to render.prop
// if not provided, all networks fetched, passes [{network}] to render.prop
fitler: PT.func,
// filter function to apply when fetching list
render: PT.func
// this funcion is called with results of the fetch
// called as props.render({network}), for single fetch,
// called as props.render([{network}]) for list fetch
};
//
// <FetchNetworks render={ networks =>
// networks.map( network => <div>{network.name}</div> )
// }/>
//
// <FetchNetworks id={networkId} render={ network =>
// <div>{network.name}</div> )
// }/>
//******************************************************************************
// Component
//******************************************************************************
export default function FetchNetworks(props) {
const { id, render, filter } = props;
return (
<FetchResources
{...{ id, render, filter }}
fetchMethodName={ id ? 'getNetwork' : 'getNetworks' }
fetcher={networkStore}
/>
);
}
|
BoKna031/nistagram
|
agent/dto/showProductDTO.go
|
package dto
type ShowProductDTO struct {
ID uint `json:"id"`
Name string `json:"name"`
PicturePath string `json:"picturePath"`
PricePerItem float64 `json:"pricePerItem"`
Quantity uint `json:"quantity"`
}
|
CRogers/obc
|
lablgtk/ml_gtksourceview2.c
|
/**************************************************************************/
/* Lablgtk */
/* */
/* This program is free software; you can redistribute it */
/* and/or modify it under the terms of the GNU Library General */
/* Public License as published by the Free Software Foundation */
/* version 2, with the exception described in file COPYING which */
/* comes with the library. */
/* */
/* 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 Library General Public License for more details. */
/* */
/* You should have received a copy of the GNU Library 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 */
/* */
/* */
/**************************************************************************/
#include <assert.h>
#include <gtksourceview/gtksourceview.h>
#include <gtksourceview/gtksourcelanguagemanager.h>
#include <gtksourceview/gtksourceiter.h>
#include <gtksourceview/gtksourcestylescheme.h>
#include <gtksourceview/gtksourcestyleschememanager.h>
#include <caml/mlvalues.h>
#include <caml/alloc.h>
#include <caml/memory.h>
#include <caml/callback.h>
#include <caml/fail.h>
#include <caml/custom.h>
#include <caml/callback.h>
#include "wrappers.h"
#include "ml_glib.h"
#include "ml_gdk.h"
#include "ml_gtk.h"
#include "ml_gobject.h"
#include "ml_gdkpixbuf.h"
#include "ml_pango.h"
#include "ml_gtktext.h"
#include "gtk_tags.h"
#include "gdk_tags.h"
#include "sourceView2_tags.h"
#include <string.h>
#include "sourceView2_tags.c"
Make_OptFlags_val(Source_search_flag_val)
CAMLprim value ml_gtk_source_style_scheme_init(value unit)
{ /* Since these are declared const, must force gcc to call them! */
GType t = gtk_source_style_scheme_get_type();
return Val_GType(t);
}
CAMLprim value ml_gtk_source_style_scheme_manager_init(value unit)
{ /* Since these are declared const, must force gcc to call them! */
GType t = gtk_source_style_scheme_manager_get_type();
return Val_GType(t);
}
CAMLprim value ml_gtk_source_language_init(value unit)
{ /* Since these are declared const, must force gcc to call them! */
GType t = gtk_source_language_get_type();
return Val_GType(t);
}
CAMLprim value ml_gtk_source_language_manager_init(value unit)
{ /* Since these are declared const, must force gcc to call them! */
GType t =
gtk_source_language_manager_get_type();
return Val_GType(t);
}
CAMLprim value ml_gtk_source_buffer_init(value unit)
{ /* Since these are declared const, must force gcc to call them! */
GType t = gtk_source_buffer_get_type();
return Val_GType(t);
}
CAMLprim value ml_gtk_source_view_init(value unit)
{ /* Since these are declared const, must force gcc to call them! */
GType t = gtk_source_view_get_type();
return Val_GType(t);
}
static gpointer string_val(value v)
{
return String_val(v);
}
GSList *ml_gslist_of_string_list(value list)
{
return GSList_val(list, string_val);
}
#define GtkSourceStyleScheme_val(val) check_cast(GTK_SOURCE_STYLE_SCHEME,val)
#define Val_GtkSourceStyleScheme(val) (Val_GObject((GObject*)val))
#define Val_GtkSourceStyleScheme_new(val) (Val_GObject_new((GObject*)val))
#define Val_option_GtkSourceStyleScheme(val) \
Val_option(val, Val_GtkSourceStyleScheme)
#define GtkSourceStyleSchemeManager_val(val) \
check_cast(GTK_SOURCE_STYLE_SCHEME_MANAGER,val)
#define Val_GtkSourceStyleSchemeManager(val) (Val_GObject((GObject*)val))
#define Val_GtkSourceLanguage(val) (Val_GObject((GObject*)val))
#define Val_option_GtkSourceLanguage(val) Val_option(val,Val_GtkSourceLanguage)
#define GtkSourceLanguage_val(val) check_cast(GTK_SOURCE_LANGUAGE,val)
#define GtkSourceLanguageManager_val(val)\
check_cast(GTK_SOURCE_LANGUAGE_MANAGER,val)
#define Val_GtkSourceLanguageManager(val) (Val_GObject((GObject*)val))
#define GtkSourceTagStyle_val(val) Pointer_val(val)
#define GtkSourceMark_val(val) check_cast(GTK_SOURCE_MARK,val)
#define Val_GtkSourceMark(val) (Val_GObject((GObject*)val))
#define Val_GtkSourceMark_new(val) (Val_GObject_new((GObject*)val))
#define Val_option_GtkSourceMark(val) Val_option(val,Val_GtkSourceMark)
#define GtkSourceBuffer_val(val) check_cast(GTK_SOURCE_BUFFER,val)
#define Val_GtkSourceBuffer(val) (Val_GObject((GObject*)val))
#define Val_GtkSourceBuffer_new(val) (Val_GObject_new((GObject*)val))
#define GtkSourceView_val(val) check_cast(GTK_SOURCE_VIEW,val)
#define GtkTextIter_val(val) ((GtkTextIter*)MLPointer_val(val))
#define Val_GtkTextIter(it) (copy_memblock_indirected(it,sizeof(GtkTextIter)))
#define Val_option_GtkAny(v) Val_option(v,Val_GtkAny)
#define string_list_of_GSList(l) Val_GSList(l, (value_in) Val_string)
#define GdkPixbuf_option_val(val) Option_val(val, GdkPixbuf_val, NULL)
#define GdkColor_option_val(val) Option_val(val, GdkColor_val, NULL)
static value val_gtksourcemark(gpointer v)
{
return Val_GtkSourceMark(v);
}
value source_marker_list_of_GSList(gpointer list)
{
return Val_GSList(list, val_gtksourcemark);
}
static value val_gtksourcelanguage(gpointer v)
{
return Val_GtkSourceLanguage(v);
}
value source_language_list_of_GSList(gpointer list)
{
return Val_GSList(list, val_gtksourcelanguage);
}
ML_1 (gtk_source_style_scheme_get_name, GtkSourceStyleScheme_val, Val_string)
ML_1 (gtk_source_style_scheme_get_description, GtkSourceStyleScheme_val, Val_string)
ML_0 (gtk_source_style_scheme_manager_new, Val_GtkAny_sink)
ML_0 (gtk_source_style_scheme_manager_get_default,
Val_GtkSourceStyleSchemeManager)
ML_2 (gtk_source_style_scheme_manager_get_scheme,
GtkSourceStyleSchemeManager_val, String_val,
Val_option_GtkSourceStyleScheme)
ML_1 (gtk_source_style_scheme_manager_get_scheme_ids,
GtkSourceStyleSchemeManager_val, string_list_of_strv)
ML_1 (gtk_source_style_scheme_manager_get_search_path,
GtkSourceStyleSchemeManager_val, string_list_of_strv)
ML_2 (gtk_source_style_scheme_manager_set_search_path,
GtkSourceStyleSchemeManager_val, strv_of_string_list, Unit)
ML_2 (gtk_source_style_scheme_manager_prepend_search_path,
GtkSourceStyleSchemeManager_val, String_val, Unit)
ML_2 (gtk_source_style_scheme_manager_append_search_path,
GtkSourceStyleSchemeManager_val, String_val, Unit)
ML_1 (gtk_source_style_scheme_manager_force_rescan,
GtkSourceStyleSchemeManager_val, Unit)
ML_1 (gtk_source_language_get_id, GtkSourceLanguage_val, Val_string)
ML_1 (gtk_source_language_get_name, GtkSourceLanguage_val, Val_string)
ML_1 (gtk_source_language_get_section, GtkSourceLanguage_val, Val_string)
ML_1 (gtk_source_language_get_hidden, GtkSourceLanguage_val, Val_bool)
ML_2 (gtk_source_language_get_metadata, GtkSourceLanguage_val,
String_option_val, Val_optstring)
ML_1 (gtk_source_language_get_mime_types, GtkSourceLanguage_val,
string_list_of_strv2)
ML_1 (gtk_source_language_get_globs, GtkSourceLanguage_val,
string_list_of_strv2)
ML_2 (gtk_source_language_get_style_name, GtkSourceLanguage_val, String_val,
Val_optstring)
ML_1 (gtk_source_language_get_style_ids, GtkSourceLanguage_val,
string_list_of_strv2)
ML_0 (gtk_source_language_manager_new, Val_GtkAny_sink)
ML_0(gtk_source_language_manager_get_default,Val_GtkSourceLanguageManager)
/* This function leaks the strv. It needs to be freed before returning. */
ML_2(gtk_source_language_manager_set_search_path,GtkSourceLanguageManager_val,
strv_of_string_list,Unit)
#if 0
// I need to find a test for this code
CAMLprim value ml_gtk_source_language_manager_set_search_path(value lm, value sl)
{
gchar** strv = strv_of_string_list(sl);
gchar **index = strv;
gtk_source_language_manager_set_search_path(GtkSourceLanguageManager_val(lm),strv);
while(*index != NULL) {g_free(*strv); strv++; };
g_free(strv);
return Val_unit;
}
#endif
ML_1(gtk_source_language_manager_get_search_path,GtkSourceLanguageManager_val,
string_list_of_strv)
ML_1(gtk_source_language_manager_get_language_ids,GtkSourceLanguageManager_val,
string_list_of_strv)
ML_2(gtk_source_language_manager_get_language,GtkSourceLanguageManager_val,
String_val,Val_option_GtkSourceLanguage)
ML_3 (gtk_source_language_manager_guess_language, GtkSourceLanguageManager_val,
String_option_val, String_option_val, Val_option_GtkSourceLanguage)
ML_2 (gtk_source_mark_new, String_val, String_val, Val_GtkSourceMark_new)
ML_1 (gtk_source_mark_get_category, GtkSourceMark_val, Val_string)
ML_2 (gtk_source_mark_next, GtkSourceMark_val, String_option_val, Val_option_GtkSourceMark)
ML_2 (gtk_source_mark_prev, GtkSourceMark_val, String_option_val, Val_option_GtkSourceMark)
ML_1 (gtk_source_buffer_new, GtkTextTagTable_val, Val_GtkSourceBuffer_new)
ML_1 (gtk_source_buffer_new_with_language, GtkSourceLanguage_val, Val_GtkAny_sink)
ML_1 (gtk_source_buffer_can_undo, GtkSourceBuffer_val, Val_bool)
ML_1 (gtk_source_buffer_can_redo, GtkSourceBuffer_val, Val_bool)
ML_1 (gtk_source_buffer_undo, GtkSourceBuffer_val, Unit)
ML_1 (gtk_source_buffer_redo, GtkSourceBuffer_val, Unit)
ML_1 (gtk_source_buffer_begin_not_undoable_action, GtkSourceBuffer_val, Unit)
ML_1 (gtk_source_buffer_end_not_undoable_action, GtkSourceBuffer_val, Unit)
ML_4 (gtk_source_buffer_create_source_mark, GtkSourceBuffer_val,
String_option_val, String_option_val, GtkTextIter_val, Val_GtkSourceMark)
ML_4 (gtk_source_buffer_remove_source_marks, GtkSourceBuffer_val,
GtkTextIter_val, GtkTextIter_val, String_option_val, Unit)
ML_3 (gtk_source_buffer_get_source_marks_at_iter, GtkSourceBuffer_val,
GtkTextIter_val,String_option_val, source_marker_list_of_GSList)
ML_3 (gtk_source_buffer_get_source_marks_at_line, GtkSourceBuffer_val,
Int_val,String_option_val, source_marker_list_of_GSList)
ML_3 (gtk_source_buffer_forward_iter_to_source_mark, GtkSourceBuffer_val, GtkTextIter_val, String_option_val, Val_bool)
ML_3 (gtk_source_buffer_backward_iter_to_source_mark, GtkSourceBuffer_val, GtkTextIter_val, String_option_val, Val_bool)
ML_3 (gtk_source_buffer_ensure_highlight, GtkSourceBuffer_val,
GtkTextIter_val, GtkTextIter_val, Unit)
ML_2 (gtk_source_buffer_set_highlight_matching_brackets, GtkSourceBuffer_val, Bool_val, Unit);
ML_0 (gtk_source_view_new, Val_GtkWidget_sink)
ML_1 (gtk_source_view_new_with_buffer, GtkSourceBuffer_val, Val_GtkWidget_sink)
ML_2 (gtk_source_view_get_mark_category_priority,
GtkSourceView_val, String_val, Val_int)
ML_3 (gtk_source_view_set_mark_category_priority,
GtkSourceView_val, String_val, Int_val, Unit)
ML_3 (gtk_source_view_set_mark_category_pixbuf, GtkSourceView_val,
String_val, GdkPixbuf_option_val, Unit)
ML_2 (gtk_source_view_get_mark_category_pixbuf, GtkSourceView_val,
String_val, Val_option_GdkPixbuf)
ML_3 (gtk_source_view_set_mark_category_background,
GtkSourceView_val, String_val, GdkColor_option_val, Unit)
CAMLprim value ml_gtk_source_view_get_mark_category_background
(value sv, value s, value c) {
CAMLparam3(sv, s, c);
CAMLlocal2(color, result);
GdkColor dest;
if (gtk_source_view_get_mark_category_background(
GtkSourceView_val(sv), String_val(s), &dest)) {
color = Val_copy(dest);
result = alloc_small(1, 0);
Field(result, 0) = color;
}
else
result = Val_unit;
CAMLreturn(result);
}
Make_Flags_val(Source_draw_spaces_flags_val)
#define Val_flags_Draw_spaces_flags(val) \
ml_lookup_flags_getter(ml_table_source_draw_spaces_flags, val)
ML_1 (gtk_source_view_get_draw_spaces,
GtkSourceView_val, Val_flags_Draw_spaces_flags)
ML_2 (gtk_source_view_set_draw_spaces,
GtkSourceView_val, Flags_Source_draw_spaces_flags_val, Unit)
/* This code was taken from gedit */
/* assign a unique name */
static G_CONST_RETURN gchar *
get_widget_name (GtkWidget *w)
{
const gchar *name;
name = gtk_widget_get_name (w);
g_return_val_if_fail (name != NULL, NULL);
if (strcmp (name, g_type_name (GTK_WIDGET_TYPE (w))) == 0)
{
static guint d = 0;
gchar *n;
n = g_strdup_printf ("%s_%u_%u", name, d, g_random_int());
d++;
gtk_widget_set_name (w, n);
g_free (n);
name = gtk_widget_get_name (w);
}
return name;
}
/* There is no clean way to set the cursor-color, so we are stuck
* with the following hack: set the name of each widget and parse
* a gtkrc string.
*/
static void
gtk_modify_cursor_color (GtkWidget *textview,
GdkColor *color)
{
static const char cursor_color_rc[] =
"style \"svs-cc\"\n"
"{\n"
"GtkSourceView::cursor-color=\"#%04x%04x%04x\"\n"
"}\n"
"widget \"*.%s\" style : application \"svs-cc\"\n";
const gchar *name;
gchar *rc_temp;
name = get_widget_name (textview);
g_return_if_fail (name != NULL);
if (color != NULL)
{
rc_temp = g_strdup_printf (cursor_color_rc,
color->red,
color->green,
color->blue,
name);
}
else
{
GtkRcStyle *rc_style;
rc_style = gtk_widget_get_modifier_style (textview);
rc_temp = g_strdup_printf (cursor_color_rc,
rc_style->text [GTK_STATE_NORMAL].red,
rc_style->text [GTK_STATE_NORMAL].green,
rc_style->text [GTK_STATE_NORMAL].blue,
name);
}
gtk_rc_parse_string (rc_temp);
gtk_widget_reset_rc_styles (textview);
g_free (rc_temp);
}
/* end of gedit code */
ML_2(gtk_modify_cursor_color,GtkWidget_val,GdkColor_val,Unit);
#define Make_search(dir) \
CAMLprim value ml_gtk_source_iter_##dir##_search (value ti,\
value str,\
value flag,\
value ti_stop,\
value ti_start,\
value ti_lim)\
{ CAMLparam5(ti,str,flag,ti_start,ti_stop);\
CAMLxparam1(ti_lim);\
CAMLlocal2(res,coup);\
GtkTextIter* ti1,*ti2;\
gboolean b;\
ti1=gtk_text_iter_copy(GtkTextIter_val(ti_start));\
ti2=gtk_text_iter_copy(GtkTextIter_val(ti_stop));\
b=gtk_source_iter_##dir##_search(GtkTextIter_val(ti),\
String_val(str),\
OptFlags_Source_search_flag_val(flag),\
ti1,\
ti2,\
Option_val(ti_lim,GtkTextIter_val,NULL));\
if (!b) res = Val_unit;\
else \
{ res = alloc(1,0);\
coup = alloc_tuple(2);\
Store_field(coup,0,Val_GtkTextIter(ti1));\
Store_field(coup,1,Val_GtkTextIter(ti2));\
Store_field(res,0,coup);};\
CAMLreturn(res);}
Make_search(forward);
Make_search(backward);
ML_bc6(ml_gtk_source_iter_forward_search);
ML_bc6(ml_gtk_source_iter_backward_search);
|
Svetuf/imageregistration
|
previous/lib/src/imgreg/matching/knn/knn_matching.cpp
|
#include "knn_matching.h"
#include <iostream>
#include <vector>
#include "../../features/features.h"
void KnnMatching::init() { matcher = cv::DescriptorMatcher::create(matcherType); }
std::vector<cv::DMatch> KnnMatching::getMatches(cv::Ptr<Features> features1,
cv::Ptr<Features> features2,
int k) const {
std::vector<std::vector<cv::DMatch>> knnMatches;
matcher->knnMatch(features1->descriptors, features2->descriptors, knnMatches, k);
std::vector<cv::DMatch> matches{};
for (auto& knnMatch : knnMatches) {
if (knnMatch[0].distance < ratio * knnMatch[1].distance) {
matches.push_back(knnMatch[0]);
}
}
return matches;
}
void KnnMatching::free() { matcher = nullptr; }
void KnnMatching::setMatcherType(cv::DescriptorMatcher::MatcherType matcherType_) {
KnnMatching::matcherType = matcherType_;
}
void KnnMatching::setRatio(float ratio_) { KnnMatching::ratio = ratio_; }
|
Angus-Liu/smilcool
|
smilcool-server/src/main/java/com/smilcool/server/core/service/MessageService.java
|
package com.smilcool.server.core.service;
import com.smilcool.server.core.pojo.po.Message;
import java.util.List;
/**
* @author Angus
* @date 2019/5/8
*/
public interface MessageService {
Message addMessage(Message message);
List<Message> getUnsignedMessageList(Integer receiveUserId);
void signMessage(Integer id);
}
|
wakiki/ri_cal
|
lib/ri_cal/property_value/recurrence_rule/recurring_day.rb
|
<reponame>wakiki/ri_cal<filename>lib/ri_cal/property_value/recurrence_rule/recurring_day.rb<gh_stars>0
module RiCal
class PropertyValue
class RecurrenceRule < PropertyValue
#- c2009 <NAME>, All rights reserved. Refer to the file README.txt for the license
#
# Instances of RecurringDay are used to represent values in BYDAY recurrence rule parts
#
class RecurringDay # :nodoc:
attr_reader :wday, :index, :rrule
DayNames = %w{SU MO TU WE TH FR SA} unless defined? DayNames
day_nums = {}
unless defined? DayNums
DayNames.each_with_index { |name, i| day_nums[name] = i }
DayNums = day_nums
end
attr_reader :source, :scope
def initialize(source, rrule, scope = :monthly)
@source = source
@rrule = rrule
@scope = scope
wd_match = source.match(/([+-]?\d*)(SU|MO|TU|WE|TH|FR|SA)/)
if wd_match
@day, @ordinal = wd_match[2], wd_match[1]
@wday = DayNums[@day]
@index = (@ordinal == "") ? nil : @ordinal.to_i
end
end
def valid?
!@day.nil?
end
def ==(another)
self.class === another && to_a = another.to_a
end
def to_a
[@day, @ordinal]
end
# return a list id for a given time to allow the enumerator to cache lists
def list_id(time)
case @scope
when :yearly
time.year
when :monthly
(time.year * 100) + time.month
when :weekly
time.at_start_of_week_with_wkst(rrule.wkst_day).jd
end
end
# return a list of times which match the time parameter within the scope of the RecurringDay
def matches_for(time)
case @scope
when :yearly
yearly_matches_for(time)
when :monthly
monthly_matches_for(time)
when :weekly
weekly_matches_for(time)
else
walkback = caller.grep(/recurrence/i)
raise "Logic error!#{@scope.inspect}\n #{walkback.join("\n ")}"
end
end
def yearly_matches_for(time)
if @ordinal == ""
t = time.nth_wday_in_year(1, wday)
result = []
year = time.year
while t.year == year
result << t
t = t.advance(:week => 1)
end
result
else
[time.nth_wday_in_year(@ordinal.to_i, wday)]
end
end
def monthly_matches_for(time)
if @ordinal == ""
t = time.nth_wday_in_month(1, wday)
result = []
month = time.month
while t.month == month
result << t
t = t.advance(:days => 7)
end
result
else
result = [time.nth_wday_in_month(index, wday)]
result
end
end
def weekly_matches_for(time)
date = time.start_of_week_with_wkst(rrule.wkst_day)
date += 1 while date.wday != wday
[time.change(:year => date.year, :month => date.month, :day => date.day)]
end
def to_s
"#{@ordinal}#{@day}"
end
def ordinal_match(date_or_time)
if @ordinal == "" || @scope == :weekly
true
else
if @scope == :yearly
date_or_time.nth_wday_in_year?(index, wday)
else
date_or_time.nth_wday_in_month?(index, wday)
end
end
end
# Determine if a particular date, time, or date_time is included in the recurrence
def include?(date_or_time)
date_or_time.wday == wday && ordinal_match(date_or_time)
end
end
end
end
end
|
grovertb/material
|
packages/cui-material/src/TableSortLabel/TableSortLabel.js
|
<gh_stars>0
export { default } from '@mui/material/TableSortLabel'
|
dcseal/finess
|
apps/2d/euler/lib/SetWaveSpd.cpp
|
<gh_stars>0
#include <cmath>
#include "dog_math.h"
#include "dogdefs.h"
#include "IniParams.h"
// This is a user-supplied routine that sets the
// HLLE wave speeds for use in "RiemannSolve"
//
// Euler equations for gas dynamics
//
void SetWaveSpd(const dTensor1& nvec,
const dTensor1& xedge,
const dTensor1& Ql,
const dTensor1& Qr,
const dTensor1& Auxl,
const dTensor1& Auxr,
double& s1,double& s2)
{
// Gas constant
const double gamma = global_ini_params.get_gamma();
// Left states
const double rhol = Ql.get(1);
const double u1l = Ql.get(2)/rhol;
const double u2l = Ql.get(3)/rhol;
const double u3l = Ql.get(4)/rhol;
const double energyl = Ql.get(5);
const double pressl = (gamma-1.0e0)*(energyl-0.5e0*rhol*(u1l*u1l+u2l*u2l+u3l*u3l));
// Right states
const double rhor = Qr.get(1);
const double u1r = Qr.get(2)/rhor;
const double u2r = Qr.get(3)/rhor;
const double u3r = Qr.get(4)/rhor;
const double energyr = Qr.get(5);
const double pressr = (gamma-1.0e0)*(energyr-0.5e0*rhor*(u1r*u1r+u2r*u2r+u3r*u3r));
// Average states
const double rho = 0.5e0*(rhol+rhor);
const double u1 = 0.5e0*(u1l+u1r);
const double u2 = 0.5e0*(u2l+u2r);
const double u3 = 0.5e0*(u3l+u3r);
const double press = 0.5e0*(pressl+pressr);
// Sound speeds
const double nmag = sqrt(pow(nvec.get(1),2) + pow(nvec.get(2),2));
const double cl = nmag*sqrt( fabs(gamma*pressl/rhol ) );
const double cr = nmag*sqrt( fabs(gamma*pressr/rhor ) );
const double c = nmag*sqrt( fabs(gamma*press/rho ) );
if( press < 0 || rho < 0 )
{
printf("negative pressure or density\n");
printf(" press = %f, rho = %f\n", press, rho );
// exit(1);
}
// normal velocities
const double un = nvec.get(1)*u1 + nvec.get(2)*u2;
const double unl = nvec.get(1)*u1l + nvec.get(2)*u2l;
const double unr = nvec.get(1)*u1r + nvec.get(2)*u2r;
// Minimum speed
s1 = Min(unl-cl, un-c);
// Maximum speed
s2 = Max(unr+cr, un+c);
}
|
MahboobehMohammadi/deriv-app
|
packages/p2p/src/utils/string.js
|
<filename>packages/p2p/src/utils/string.js
export const toSentenceCase = string => {
if (!string) {
return '';
}
return string[0].toUpperCase() + string.slice(1);
};
export const countDecimalPlaces = value => {
return ((value.toString().split('.') || [])[1] || []).length;
};
|
Staatsgeheim/NDceRpc
|
research/JavaDceRpc/jarapac-0.3.8/src/jarapac/ndr/NdrBuffer.java
|
<gh_stars>1-10
package ndr;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import jcifs.util.Encdec;
public class NdrBuffer {
int referent;
HashMap referents;
static class Entry {
int referent;
Object obj;
}
public byte[] buf;
public int start;
public int index;
public int length;
public NdrBuffer deferred;
public NdrBuffer(byte[] buf, int start) {
this.buf = buf;
this.start = index = start;
length = 0;
deferred = this;
}
public NdrBuffer derive(int idx) {
NdrBuffer nb = new NdrBuffer(buf, start);
nb.index = idx;
nb.deferred = deferred;
return nb;
}
public void reset() {
this.index = start;
length = 0;
deferred = this;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public int getCapacity() {
return buf.length - start;
}
public byte[] getBuffer() {
return buf;
}
public int align(int boundary, byte value) {
int n = align(boundary);
int i = n;
while (i > 0) {
buf[index - i] = value;
i--;
}
return n;
}
public void writeOctetArray(byte[] b, int i, int l) {
System.arraycopy(b, i, buf, index, l);
advance(l);
}
public void readOctetArray(byte[] b, int i, int l) {
System.arraycopy(buf, index, b, i, l);
advance(l);
}
public int getLength() {
return deferred.length;
}
public void advance(int n) {
index += n;
if ((index - start) > deferred.length) {
deferred.length = index - start;
}
}
public int align(int boundary) {
int m = boundary - 1;
int i = index - start;
int n = ((i + m) & ~m) - i;
advance(n);
return n;
}
public void enc_ndr_small(int s) {
buf[index] = (byte)(s & 0xFF);
advance(1);
}
public int dec_ndr_small() {
int val = buf[index] & 0xFF;
advance(1);
return val;
}
public void enc_ndr_short(int s) {
align(2);
Encdec.enc_uint16le((short)s, buf, index);
advance(2);
}
public int dec_ndr_short() {
align(2);
int val = Encdec.dec_uint16le(buf, index);
advance(2);
return val;
}
public void enc_ndr_long(int l) {
align(4);
Encdec.enc_uint32le(l, buf, index);
advance(4);
}
public int dec_ndr_long() {
align(4);
int val = Encdec.dec_uint32le(buf, index);
advance(4);
return val;
}
/* float */
/* double */
public void enc_ndr_string(String s) {
align(4);
int i = index;
int len = s.length();
Encdec.enc_uint32le(len + 1, buf, i); i += 4;
Encdec.enc_uint32le(0, buf, i); i += 4;
Encdec.enc_uint32le(len + 1, buf, i); i += 4;
try {
System.arraycopy(s.getBytes("UnicodeLittleUnmarked"), 0, buf, i, len * 2);
} catch( UnsupportedEncodingException uee ) {
}
i += len * 2;
buf[i++] = (byte)'\0';
buf[i++] = (byte)'\0';
advance(i - index);
}
public String dec_ndr_string() throws NdrException {
align(4);
int i = index;
String val = null;
int len = Encdec.dec_uint32le(buf, i);
i += 12;
if (len != 0) {
len--;
int size = len * 2;
try {
if (size < 0 || size > 0xFFFF) throw new NdrException( NdrException.INVALID_CONFORMANCE );
val = new String(buf, i, size, "UnicodeLittle");
i += size + 2;
} catch( UnsupportedEncodingException uee ) {
}
}
advance(i - index);
return val;
}
private int getDceReferent(Object obj) {
Entry e;
if (referents == null) {
referents = new HashMap();
referent = 1;
}
if ((e = (Entry)referents.get(obj)) == null) {
e = new Entry();
e.referent = referent++;
e.obj = obj;
referents.put(obj, e);
}
return e.referent;
}
public void enc_ndr_referent(Object obj, int type) {
if (obj == null) {
enc_ndr_long(0);
return;
}
switch (type) {
case 1: /* unique */
case 3: /* ref */
enc_ndr_long(System.identityHashCode(obj));
return;
case 2: /* ptr */
enc_ndr_long(getDceReferent(obj));
return;
}
}
public String toString() {
return "start=" + start + ",index=" + index + ",length=" + getLength();
}
}
|
czizzy/L7
|
src/layer/raster_layer.js
|
<filename>src/layer/raster_layer.js
import Layer from '../core/layer';
import * as THREE from '../core/three';
import RasterMaterial from '../geom/material/rasterMaterial';
import { RasterBuffer } from '../geom/buffer/raster';
export default class RasterLayer extends Layer {
draw() {
this.type = 'raster';
const source = this.layerSource;
// 加载 完成事件
const styleOptions = this.get('styleOptions');
const buffer = new RasterBuffer({
layerData: source.data,
rampColors: styleOptions.rampColors
});
this.initGeometry(buffer.attributes);
const rasterConfig = source.data.dataArray[0];
const material = new RasterMaterial({
u_texture: buffer.u_raster,
u_colorTexture: buffer.u_colorTexture,
u_opacity: 1.0,
u_extent: buffer.u_extent,
u_min: rasterConfig.min,
u_max: rasterConfig.max,
u_dimension: buffer.attributes.dimension
});
const rasterMesh = new THREE.Mesh(this.geometry, material);
this.add(rasterMesh);
return this;
}
animateFunc() {
const animateOptions = this.get('animateOptions');
this.material.setValue('u_bands', this.animateData.index % 3);
this.material.setValue('u_texture', this.animateData.rasters[ Math.floor(this.animateData.index / 3) % 8]);
this.animateData.index++;
if (animateOptions) {
animateOptions(this.animateData.index);
}
setTimeout(() => {
this.animateId = requestAnimationFrame(this.animateFunc.bind(this));
}, 500);
}
cancelAnimate() {
window.cancelAnimationFrame(this.animateId);
}
initGeometry(attributes) {
this.geometry = new THREE.BufferGeometry();
this.geometry.setIndex(attributes.indices);
this.geometry.addAttribute('position', new THREE.Float32BufferAttribute(attributes.vertices, 3));
this.geometry.addAttribute('uv', new THREE.Float32BufferAttribute(attributes.uvs, 2));
}
}
|
shishuihao/third-party-api
|
third-party-api-pay-chinaums-sdk/src/main/java/cn/shishuihao/thirdparty/api/pay/chinaums/sdk/request/ChinaumsV1NetPayRefundRequest.java
|
package cn.shishuihao.thirdparty.api.pay.chinaums.sdk.request;
import cn.shishuihao.thirdparty.api.pay.chinaums.sdk.domain.RefundSubOrder;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.ToString;
import lombok.experimental.SuperBuilder;
import lombok.extern.jackson.Jacksonized;
/**
* 退款.
* 当成功交易之后一段时间内,由于买家或商户的原因需要退款时,
* 商户可以通过本接口将支付款退还给买家,退款请求验证成功之后,银商将通知支付渠道方按照退款规则把支付款按原路退回到买家帐号上。
* 退款订单号refundOrderId也需遵循商户订单号生成规范,即以银商分配的4位来源编号作为账单号的前4位,且在商户系统中 此账单号保证唯一。
* 总长度需大于6位,小于28位。
* 银商的推荐规则为(无特殊情况下,建议遵守此规则):{来源编号(4位)}{时间(yyyyMMddmmHHssSSS)(17位)}{7位随机数}
*
* @author shishuihao
* @version 1.0.0
*/
@Jacksonized
@ToString
@SuperBuilder
@Getter
public class ChinaumsV1NetPayRefundRequest
extends AbstractChinaumsRequest {
/**
* 商户订单号 字符串 6..64 是 原交易订单号.
*/
@JsonProperty("merOrderId")
private final String merOrderId;
/**
* 支付订单号 字符串 6..64 否.
*/
@JsonProperty("targetOrderId")
private final String targetOrderId;
/**
* 要退货的金额 数字型 1..100000000 是.
* 若下单接口中上送了分账标记字 段divisionFlag,
* 则该字段 refundAmount=subOrders 中totalAmount之和 +platformAmount.
*/
@JsonProperty("refundAmount")
private final Integer refundAmount;
/**
* 退款订单号 字符串 6..32 否.
* 多次退款必传,每次退款上送的 refundOrderId值需不同,
* 若多次退货,且后续退货上送的 merOrderId和refundOrderId字段与之前退货上送的值一致,将不会走退货逻辑,
* 而是返回已有退货订单的退货信息,遵循商户订单号生成规范.
*/
@JsonProperty("refundOrderId")
private final String refundOrderId;
/**
* 平台商户退款分账金额 数字型 0..100000000 否.
* 若原交易是分账交易,则分账金额必传,且退款接口 platformAmount小于下单接口中上送的platformAmount.
*/
@JsonProperty("platformAmount")
private final Integer platformAmount;
/**
* 子订单信息 数组→JSON 否.
* 若原交易有分账,退款时必填。
* 且退款接口totalAmount小于下单接口中上送的subOrders中对 应mid下的totalAmount。
* (一 次只能对一个子商户进行退款 ).
*/
@JsonProperty("subOrders")
private final RefundSubOrder[] subOrders;
/**
* 退货说明 字符串 ⇐255 否.
*/
@JsonProperty("refundDesc")
private final String refundDesc;
}
|
audip/cerebro
|
src/app/components/overview/controller.js
|
angular.module('cerebro').controller('OverviewController', ['$scope', '$http',
'$window', '$location', 'OverviewDataService', 'AlertService', 'ModalService',
'RefreshService',
function($scope, $http, $window, $location, OverviewDataService, AlertService,
ModalService, RefreshService) {
$scope.data = undefined;
$scope.indices = undefined;
$scope.nodes = undefined;
$scope.unassigned_shards = 0;
$scope.relocating_shards = 0;
$scope.initializing_shards = 0;
$scope.closed_indices = 0;
$scope.special_indices = 0;
$scope.shardAllocation = true;
$scope.indices_filter = new IndexFilter('', false, false, true, true, 0);
$scope.nodes_filter = new NodeFilter('', true, false, false, false, 0);
$scope.getPageSize = function() {
return Math.max(Math.round($window.innerWidth / 280), 1);
};
$scope.paginator = new Paginator(
1,
$scope.getPageSize(),
[],
$scope.indices_filter)
;
$scope.page = $scope.paginator.getPage();
$($window).resize(function() {
$scope.$apply(function() {
$scope.paginator.setPageSize($scope.getPageSize());
});
});
$scope.$watch(
function() {
return RefreshService.lastUpdate();
},
function() {
$scope.refresh();
},
true
);
$scope.refresh = function() {
OverviewDataService.getOverview(
function(data) {
$scope.data = data;
$scope.setIndices(data.indices);
$scope.setNodes(data.nodes);
$scope.unassigned_shards = data.unassigned_shards;
$scope.relocating_shards = data.relocating_shards;
$scope.initializing_shards = data.initializing_shards;
$scope.closed_indices = data.closed_indices;
$scope.special_indices = data.special_indices;
$scope.shardAllocation = data.shard_allocation;
if (!$scope.unassigned_shards &&
!$scope.relocating_shards &&
!$scope.initializing_shards) {
$scope.indices_filter.healthy = true;
}
},
function(error) {
AlertService.error('Error while loading data', error);
$scope.data = undefined;
$scope.indices = undefined;
$scope.nodes = undefined;
$scope.unassigned_shards = 0;
$scope.relocating_shards = 0;
$scope.initializing_shards = 0;
$scope.closed_indices = 0;
$scope.special_indices = 0;
$scope.shardAllocation = true;
}
);
};
$scope.$watch('paginator', function() {
if ($scope.data) {
$scope.setIndices($scope.data.indices);
}
}, true);
$scope.setIndices = function(indices) {
$scope.paginator.setCollection(indices);
$scope.page = $scope.paginator.getPage();
};
$scope.$watch('nodes_filter', function() {
if ($scope.data) {
$scope.setNodes($scope.data.nodes);
}
},
true);
$scope.setNodes = function(nodes) {
$scope.nodes = nodes.filter(function(node) {
return $scope.nodes_filter.matches(node);
});
};
var success = function(data) {
RefreshService.refresh();
AlertService.success('Operation successfully executed', data);
};
var error = function(data) {
AlertService.error('Operation failed', data);
};
var displayInfo = function(info) {
ModalService.showInfo(info);
};
$scope.openIndex = function(index) {
ModalService.promptConfirmation(
'Open ' + index + '?',
function() {
OverviewDataService.openIndex(index, success, error);
}
);
};
$scope.closeIndex = function(index) {
ModalService.promptConfirmation(
'Close ' + index + '?',
function() {
OverviewDataService.closeIndex(index, success, error);
}
);
};
$scope.deleteIndex = function(index) {
ModalService.promptConfirmation(
'Delete ' + index + '?',
function() {
OverviewDataService.deleteIndex(index, success, error);
}
);
};
$scope.clearIndexCache = function(index) {
ModalService.promptConfirmation(
'Clear ' + index + ' cache?',
function() {
OverviewDataService.clearIndexCache(index, success, error);
}
);
};
$scope.refreshIndex = function(index) {
ModalService.promptConfirmation(
'Refresh index ' + index + '?',
function() {
OverviewDataService.refreshIndex(index, success, error);
}
);
};
$scope.flushIndex = function(index) {
ModalService.promptConfirmation(
'Flush index ' + index + '?',
function() {
OverviewDataService.flushIndex(index, success, error);
}
);
};
$scope.forceMerge = function(index) {
ModalService.promptConfirmation(
'Optimize index ' + index + '?',
function() {
OverviewDataService.forceMerge(index, success, error);
}
);
};
// Mass actions
$scope.closeIndices = function() {
var indices = $scope.paginator.getResults().map(function(index) {
return index.name;
});
ModalService.promptConfirmation(
'Close all ' + indices.length + ' selected indices?',
function() {
OverviewDataService.closeIndex(indices.join(','), success, error);
}
);
};
$scope.openIndices = function() {
var indices = $scope.paginator.getResults().map(function(index) {
return index.name;
});
ModalService.promptConfirmation(
'Open all ' + indices.length + ' selected indices?',
function() {
OverviewDataService.openIndex(indices.join(','), success, error);
}
);
};
$scope.forceMerges = function() {
var indices = $scope.paginator.getResults().map(function(index) {
return index.name;
});
ModalService.promptConfirmation(
'Optimize all ' + indices.length + ' selected indices?',
function() {
OverviewDataService.forceMerge(indices.join(','), success, error);
}
);
};
$scope.refreshIndices = function() {
var indices = $scope.paginator.getResults().map(function(index) {
return index.name;
});
ModalService.promptConfirmation(
'Refresh all ' + indices.length + ' selected indices?',
function() {
OverviewDataService.refreshIndex(indices.join(','), success, error);
}
);
};
$scope.flushIndices = function() {
var indices = $scope.paginator.getResults().map(function(index) {
return index.name;
});
ModalService.promptConfirmation(
'Flush all ' + indices.length + ' selected indices?',
function() {
OverviewDataService.flushIndex(indices.join(','), success, error);
}
);
};
$scope.clearIndicesCache = function() {
var indices = $scope.paginator.getResults().map(function(index) {
return index.name;
});
ModalService.promptConfirmation(
'Clear all ' + indices.length + ' selected indices cache?',
function() {
OverviewDataService.clearIndexCache(
indices.join(','), success, error
);
}
);
};
$scope.deleteIndices = function() {
var indices = $scope.paginator.getResults().map(function(index) {
return index.name;
});
ModalService.promptConfirmation(
'Delete all ' + indices.length + ' selected indices?',
function() {
OverviewDataService.deleteIndex(indices.join(','), success, error);
}
);
};
$scope.shardStats = function(index, node, shard) {
OverviewDataService.getShardStats(index, node, shard, displayInfo, error);
};
$scope.nodeStats = function(node) {
OverviewDataService.nodeStats(node, displayInfo, error);
};
$scope.indexStats = function(index) {
OverviewDataService.indexStats(index, displayInfo, error);
};
$scope.getIndexSettings = function(index) {
OverviewDataService.getIndexSettings(index, displayInfo, error);
};
$scope.getIndexMapping = function(index) {
OverviewDataService.getIndexMapping(index, displayInfo, error);
};
$scope.disableShardAllocation = function() {
OverviewDataService.disableShardAllocation(success, error);
};
$scope.enableShardAllocation = function() {
OverviewDataService.enableShardAllocation(success, error);
};
$scope.showIndexSettings = function(index) {
$location.path('index_settings').search('index', index);
};
$scope.select = function(shard) {
$scope.relocatingShard = shard;
};
$scope.relocateShard = function(node) {
var s = $scope.relocatingShard;
OverviewDataService.relocateShard(s.shard, s.index, s.node, node.id,
function(response) {
$scope.relocatingShard = undefined;
RefreshService.refresh();
AlertService.info('Relocation successfully started', response);
},
function(error) {
AlertService.error('Error while starting relocation', error);
}
);
};
$scope.isSelected = function(shard) {
var relocating = $scope.relocatingShard;
return relocating && shard.index === relocating.index &&
shard.node === relocating.node && shard.shard === relocating.shard;
};
$scope.canReceiveShard = function(index, node) {
var shard = $scope.relocatingShard;
if (shard && index) { // in case num indices < num columns
if (shard.node !== node.id && shard.index === index.name) {
var shards = index.shards[node.id];
if (shards) {
var sameShard = function(s) {
return s.shard === shard.shard;
};
if (shards.filter(sameShard).length === 0) {
return true;
}
} else {
return true;
}
}
}
return false;
};
}]);
|
HaoNanYanToMe/SpringAnoSing
|
src/main/java/com/prism/springas/utils/excel/ExcelView.java
|
<filename>src/main/java/com/prism/springas/utils/excel/ExcelView.java
package com.prism.springas.utils.excel;
import com.prism.springas.utils.BasePage;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.springframework.web.servlet.view.document.AbstractExcelView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
public class ExcelView extends AbstractExcelView {
@Override
protected void buildExcelDocument(Map<String, Object> model,
HSSFWorkbook workbook, HttpServletRequest request,
HttpServletResponse response) throws Exception {
List<BasePage> mt = (List<BasePage>) model.get("dataSet");
HSSFSheet sheet = workbook.createSheet(model.get("tableName").toString());
//处理Excel表头字体样式(Cell)
HSSFFont fontCell =workbook.createFont();
fontCell.setFontHeightInPoints((short) 10); //字体高度
fontCell.setColor(HSSFFont.COLOR_RED); //字体颜色
fontCell.setFontName("微软雅黑"); //字体
fontCell.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); //宽度
//处理Excel表头样式(Cell)
HSSFCellStyle cellStyle =workbook.createCellStyle();
cellStyle.setFont(fontCell);
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); //水平布局:居中
cellStyle.setWrapText(true);
//处理Excel内容字体样式(Row)
HSSFFont fontRow =workbook.createFont();
fontRow.setFontHeightInPoints((short) 10); //字体高度
fontRow.setFontName("微软雅黑"); //字体
//处理Excel表头样式(Row)
HSSFCellStyle rowStyle =workbook.createCellStyle();
rowStyle.setFont(fontRow);
rowStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); //水平布局:居中
rowStyle.setWrapText(true);
//处理Excel表头字体样式(无数据导出)
HSSFFont fontNull =workbook.createFont();
fontNull.setFontHeightInPoints((short) 16); //字体高度
fontNull.setColor(HSSFFont.COLOR_RED); //字体颜色
fontNull.setFontName("微软雅黑"); //字体
fontNull.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); //宽度
//处理Excel表头样式(无数据导出)
HSSFCellStyle cellNull =workbook.createCellStyle();
cellNull.setFont(fontNull);
cellNull.setAlignment(HSSFCellStyle.ALIGN_CENTER); //水平布局:居中
cellNull.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);//垂直
cellNull.setWrapText(true);
ExcelViewConfig cfg = new ExcelViewConfig();
//判断是否有内容
if(mt.size() != 0) {
//获取字段列表(需和mapper中保持一致,若用到了as字段,则填写as字段的值即可,支持中文)
String [] cellName = model.get("cellName").toString().split(",");
String [] cellParseName = model.get("cellParseName").toString().split(",");
HSSFCell cell;
sheet.setDefaultColumnWidth(cellName.length);
for (int i = 0; i <= cellParseName.length; i++) {
cell = getCell(sheet, 0, i);
if (i == cellName.length) {
setText(cell, "");
} else {
setText(cell, cellParseName[i]);
}
cell.setCellStyle(cellStyle);
}
for (int i = 0; i < mt.size(); i++) {
HSSFRow row = sheet.createRow(i + 1);
BasePage pd = mt.get(i);
//循环CellName获取值
for (int j = 0; j < cellName.length; j++) {
cell = row.createCell(j);
if (j < cellName.length) {
Object o = pd.get(cellName[j].trim());
cell.setCellValue(o==null?"":cfg.parseCellValue(cellName[j],o.toString()));
} else {
row.createCell(j).setCellValue("");
}
cell.setCellStyle(rowStyle);
}
}
for (int i = 0; i <= cellName.length; i++) {
// ==**==本方法在linux不适用
sheet.autoSizeColumn((short) i,true); //调整列宽度
// sheet.setColumnWidth((short) i,cellName.toString().getBytes().length*2*256);
}
}else{
HSSFCell cell = getCell(sheet,0,0);
setText(cell, "Sorry,It's no true Data!(很抱歉,没有符合的数据或您权限不足!)");
cell.setCellStyle(cellNull);
sheet.setColumnWidth(0,2000);
sheet.addMergedRegion(new CellRangeAddress(0,10,0,20));
}
// 处理中文文件名Name
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "filename="
+ new String(cfg.parseTableName(model.get("tableName").toString()).getBytes("gb2312"), "iso8859-1"));//设置文件头编码方式和文件名
OutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
}
}
|
AliYildizoz909/photo-channel-spa
|
src/components/channel/channelHooks.js
|
import React, { useState, useEffect } from "react"
import { Container, Row, Col, ListGroup, Badge, Tabs, Tab, Table } from 'react-bootstrap'
import { Button } from 'react-bootstrap'
import { Link, useHistory } from 'react-router-dom'
import axios from "axios";
import { useSelector, useDispatch } from 'react-redux'
import { SUBS_API_URL, deleteSubsPath } from "../../redux/actions/subscrib/subsEndPoints"
import { authHeaderObj } from "../../redux/helpers/localStorageHelper"
import PhotoCardHook, { MapPhotoCard } from "../photoCard/photoCardHook";
import { getIsSubsApi } from "../../redux/actions/subscrib/subsAsyncAction";
import { getIsSubsSuccess, getSubscribersSuccess } from "../../redux/actions/subscrib/subsActionCreators";
import PhotoGallery from "../photos/PhotoGallery";
import { redirectErrPage } from "../../redux/helpers/historyHelper";
import { getChannelOwnerPath } from "../../redux/actions/channel/channelEndPoints";
import { getChannelIsOwnerSuccess } from "../../redux/actions/channel/channelActionCreators";
import { getChannelGallerySuccess, getChannelPhotosSuccess } from "../../redux/actions/photo/photoActionCreators";
export function SubsButton({ channelId, subsCount }) {
const subscribers = useSelector(state => state.channelReducer.subscribers);
const currentUser = useSelector(state => state.currentUserReducer.detail)
const isSubs = useSelector(state => state.isSubsReducer);
const [subsCnt, setSubsCnt] = useState(subsCount)
const history = useHistory()
const isLogged = useSelector(state => state.isLoggedReducer);
const dispatch = useDispatch();
useEffect(() => setSubsCnt(subsCount), [])
if (!isLogged) {
return (<JustSubsButton variant="outline-primary" subsCount={subsCnt} onClick={() => history.push('/login')} text="Abone ol" />)
}
const subsThen = () => {
setSubsCnt(prevState => prevState + 1)
dispatch(getIsSubsSuccess(true))
dispatch(getSubscribersSuccess([...subscribers, { firstName: currentUser.firstName, lastName: currentUser.lastName, id: currentUser.id, userName: currentUser.userName }]))
}
const unSubsThen = () => {
setSubsCnt(prevState => prevState - 1);
dispatch(getIsSubsSuccess(false));
dispatch(getSubscribersSuccess([...subscribers.filter(s => s.id !== currentUser.id)]))
}
const [subs, unSubs] = SubsApi(channelId, subsThen, unSubsThen, dispatch)
return isSubs ? <JustSubsButton variant="primary" subsCount={subsCnt} onClick={unSubs} text="Abone olundu" /> :
<JustSubsButton variant="outline-primary" subsCount={subsCnt} onClick={subs} text="Abone ol" />
}
export function SubsApi(channelId, subsThen, unSubsThen, dispatch) {
const subs = () => {
var fd = new FormData()
fd.append("channelId", channelId)
axios.post(SUBS_API_URL, fd, { headers: authHeaderObj() }).then(() => {
subsThen()
}).catch(err => redirectErrPage(err, dispatch));
}
const unSubs = () => {
axios.delete(deleteSubsPath(channelId), { headers: authHeaderObj() }).then(() => {
unSubsThen()
}).catch(err => redirectErrPage(err, dispatch));
}
return [subs, unSubs];
}
function JustSubsButton({ text, subsCount, variant, onClick }) {
return <Button variant={variant} onClick={onClick} className="btn-lg mb-3 bottom-right ">
<Badge pill variant="secondary">{subsCount}</Badge>{" " + text}
</Button>
}
export function ChannelPhotos({ channelId }) {
const channelPhotos = useSelector(state => state.channelReducer.channelPhotos);
const photoGallery = useSelector(state => state.channelReducer.photoGallery);
const dispatch = useDispatch();
return <div className="mt-3">
<MapPhotoCard refreshPhotos={(id) => {
dispatch(getChannelPhotosSuccess([...channelPhotos.filter(p => p.photoId !== id)]))
dispatch(getChannelGallerySuccess([...photoGallery.filter(p => p.photoId !== id)]))
}} removeButton={true} photos={channelPhotos} />
</div>
}
export function Flow({ renderState, channelId }) {
const [flowState, setFlowState] = useState();
useEffect(() => setFlowState(renderState), [])
return <div>
<Row>
<Col md="12">
<Tabs
id="controlled-tab-example"
activeKey={flowState}
onSelect={(k) => setFlowState(k)}
>
<Tab eventKey="gallery" title="Galeri">
<Col >
<PhotoGallery channelId={channelId} />
</Col>
</Tab>
<Tab eventKey="photos" title="Fotoğraflar">
<Col md={{ offset: 1 }}>
<ChannelPhotos channelId={channelId} />
</Col>
</Tab>
<Tab eventKey="about" title="Kanal Hakkında">
<Col>
<ChannelAbout channelId={channelId} />
</Col>
</Tab>
</Tabs>
</Col>
</Row>
</div>
}
export function ChannelCategories() {
const categories = useSelector(state => state.channelReducer.categories);
return <ListGroup>{categories.length !== 0 ?
<ListGroup.Item>
{
categories.map((c, i) => {
return <h4 className="d-inline-flex mr-2" key={i}><Link to={"/feed/" + c.name.toLowerCase()}><Badge variant="info">
{c.name}
</Badge></Link></h4>
})
}
</ListGroup.Item>
:
<ListGroup.Item>
<h4 className="d-inline-flex mr-2" ><Badge variant="secondary">
Kategorize edilmemiş
</Badge></h4>
</ListGroup.Item>}
</ListGroup>
}
export function ChannelAbout({ channelId }) {
const channelDetail = useSelector(state => state.channelReducer.channelDetail);
const subscribers = useSelector(state => state.channelReducer.subscribers);
const [owner, setOwner] = useState({})
const currentUserId = useSelector(state => state.currentUserReducer.detail.id)
const isOwner = useSelector(state => state.channelIsOwnerReducer)
const dispatch = useDispatch();
useEffect(() => {
axios.get(getChannelOwnerPath(channelId)).then(res => {
setOwner(res.data)
dispatch(getChannelIsOwnerSuccess(currentUserId === res.data.id))
}
).catch(err => {
redirectErrPage(err, dispatch)
})
}, [])
return <Container>
<Row className="mt-4">
<Col>
<h3 className="font-weight-normal d-inline-flex ">{channelDetail.name}</h3>
<h6 className="font-weight-light d-inline-flex float-right mt-4"> {new Date(channelDetail.createdDate).toLocaleDateString()}</h6>
<hr />
</Col>
</Row>
<Row>
<Col>
<h4 className="text-primary">Aboneler <Badge variant="primary">{channelDetail.subscribersCount}</Badge></h4>
<hr />
<Table striped hover>
<tbody>
{
subscribers.map(subs => {
return <tr key={subs.id}>
<td>
<span>{subs.firstName + " " + subs.lastName}</span>
<Link to={"/profile/" + subs.id} className="text-primary text-decoration-none"><h6 className="float-right">{subs.userName}</h6></Link>
</td>
</tr>
})
}
</tbody>
</Table>
</Col>
<Col>
<h4 className=" d-inline-flex text-dark"><NAME></h4>
{
isOwner ?
<h5 className="font-weight-light d-inline-flex float-right mt-4">
<Link className="text-decoration-none" to={channelId + "/settings"}> <span className="fa fa-cog"></span> Ayarlara git</Link>
</h5> : null
}
<hr />
<Table striped hover>
<tbody>
<tr>
<td style={{ width: 3 }}>
<b>{owner.firstName + " " + owner.lastName}</b>
<Link to={"/profile/" + owner.id} className="text-decoration-none"><h6 className="float-right">{owner.userName}</h6></Link>
</td>
</tr>
</tbody>
</Table>
</Col>
</Row>
</Container>
}
|
4ngel2769/LambdaDiscordBot
|
src/main/java/bot/java/lambda/command/commands/common/RandomCommand.java
|
package bot.java.lambda.command.commands.common;
import bot.java.lambda.command.CommandContext;
import bot.java.lambda.command.category.HelpCategory;
import bot.java.lambda.command.type.CommandHandler;
import bot.java.lambda.command.type.ICommand;
import java.util.List;
import java.util.OptionalInt;
import java.util.Random;
@CommandHandler
public class RandomCommand implements ICommand {
@Override
public void handle(CommandContext ctx) {
try {
final List<String> args = ctx.getArgs();
if (args.isEmpty()) {
ctx.getChannel().sendMessage("Missing Arguments").queue();
return;
}
Random random = new Random();
if (args.size() == 1) {
final OptionalInt num = random.ints(0, Integer.parseInt(args.get(0))).findFirst();
ctx.getChannel().sendMessage("" + (num.isPresent() ? num.getAsInt() : "Something went wrong")).queue();
return;
}
int a = Integer.parseInt(args.get(0));
final int b = Integer.parseInt(args.get(1));
final OptionalInt num = a < b ? random.ints(a, b).findFirst() : random.ints(b, a).findFirst();
ctx.getChannel().sendMessage("" + (num.isPresent() ? num.getAsInt() : "Something went wrong")).queue();
} catch (NumberFormatException e) {
ctx.getChannel().sendMessage("Invalid Input! Provide Numbers").queue();
e.fillInStackTrace();
}
}
@Override
public String getName() {
return "random";
}
@Override
public String getHelp(String prefix) {
return "Gives you random number between your bounds\n" +
"Usage : " + prefix + "random <number> <number>";
}
@Override
public HelpCategory getHelpCategory() {
return HelpCategory.COM;
}
@Override
public int getCoolDown() {
return 10;
}
}
|
madebr/edyn
|
include/edyn/util/rigidbody.hpp
|
#ifndef EDYN_UTIL_RIGIDBODY_HPP
#define EDYN_UTIL_RIGIDBODY_HPP
#include <vector>
#include <optional>
#include <entt/entity/fwd.hpp>
#include "edyn/math/vector3.hpp"
#include "edyn/math/quaternion.hpp"
#include "edyn/math/matrix3x3.hpp"
#include "edyn/shapes/shapes.hpp"
#include "edyn/comp/material.hpp"
namespace edyn {
enum class rigidbody_kind : uint8_t {
// A rigid body with non-zero and finite mass that reacts to forces and
// impulses and can be affected by constraints.
rb_dynamic,
// A rigid body that is not affected by others and can be moved directly.
rb_kinematic,
// A rigid body that is not affected by others and never changes.
rb_static
};
struct rigidbody_def {
// The entity kind will determine which components are added to it
// in the `make_rigidbody` call.
rigidbody_kind kind {rigidbody_kind::rb_dynamic};
// Initial position and orientation.
vector3 position {vector3_zero};
quaternion orientation {quaternion_identity};
// Mass properties for dynamic entities.
scalar mass {1};
matrix3x3 inertia {matrix3x3_identity};
// Initial linear and angular velocity.
vector3 linvel {vector3_zero};
vector3 angvel {vector3_zero};
// Center of mass offset from origin in object space.
std::optional<vector3> center_of_mass;
// Gravity acceleration. If not set, the default value from
// `edyn::get_gravity` will be assigned.
std::optional<vector3> gravity;
// Optional shape for collidable entities.
std::optional<shapes_variant_t> shape;
// Optional material. If not set, the rigid body will not respond to
// collisions, i.e. it becomes a _sensor_.
std::optional<edyn::material> material {edyn::material{}};
uint64_t collision_group {~0ULL};
uint64_t collision_mask {~0ULL};
// Mark all contacts involving this rigid body as continuous.
bool continuous_contacts {false};
// Whether this entity will be used for presentation and needs
// position/orientation interpolation.
bool presentation {true};
// Prevent this rigid body from sleeping while it barely moves.
bool sleeping_disabled {false};
/**
* @brief Assigns the default moment of inertia of the current shape
* using the current mass.
* Assumes `shape` to contain a value.
*/
void update_inertia();
};
/**
* @brief Assigns to `entity` all necessary components to build a rigid body
* according to the given definition.
* @param entity Target rigid body entity.
* @param registry Data source and destination.
* @param def Rigid body definition.
*/
void make_rigidbody(entt::entity, entt::registry &, const rigidbody_def &);
/**
* @brief Creates an entity and assigns all necessary components to build a
* rigid body according to the given definition.
* @param registry Data source and destination.
* @param def Rigid body definition.
* @return Rigid body entity.
*/
entt::entity make_rigidbody(entt::registry &, const rigidbody_def &);
/**
* @brief Creates many rigid bodies at once.
* A new island is created and all bodies are inserted into it.
* @param registry Data source.
* @param defs Rigid body definitions.
* @return Entities corresponding to each rigid body definition.
*/
std::vector<entt::entity> batch_rigidbodies(entt::registry ®istry, const std::vector<rigidbody_def> &defs);
/**
* @brief Applies `impulse` to entity.
* @param registry Data source.
* @param entity Rigid body entity.
* @param impulse Impulse vector.
* @param rel_location Location where the impulse should be applied relative to
* the entity's center/position, in world space, i.e.
* `actual_world_space_location - position`.
*/
void rigidbody_apply_impulse(entt::registry &, entt::entity,
const vector3 &impulse,
const vector3 &rel_location);
void update_kinematic_position(entt::registry &, entt::entity, const vector3 &, scalar dt);
void update_kinematic_orientation(entt::registry &, entt::entity, const quaternion &, scalar dt);
void clear_kinematic_velocities(entt::registry &);
bool validate_rigidbody(entt::entity &, entt::registry &);
/**
* @brief Set the mass of a rigid body.
* Propagates changes across island workers.
* @param registry Data source.
* @param entity Rigid body entity.
* @param mass The new rigid body mass.
*/
void set_rigidbody_mass(entt::registry &, entt::entity, scalar mass);
/**
* @brief Set the moment of inertia of a rigid body.
* Propagates changes across island workers.
* @param registry Data source.
* @param entity Rigid body entity.
* @param inertia The new moment of inertia.
*/
void set_rigidbody_inertia(entt::registry &, entt::entity, const matrix3x3 &inertia);
/**
* @brief Besides assigning the new friction coefficient to the rigid body's
* material, it also updates the friction of the contact points of all
* manifolds involving this rigid body.
* @param registry Data source.
* @param entity Rigid body entity.
* @param friction The new friction coefficient.
*/
void set_rigidbody_friction(entt::registry &, entt::entity, scalar);
/**
* @brief Offset the rigid body center of mass. The value represents an offset
* from the rigid body's origin in object space.
* @remark When the center of mass offset changes, the position and linear
* velocity change as well to reflect the value in the new location. This
* dependency makes it necessary to do these updates in the island worker or
* else the simulation will be slightly disturbed. For this reason, this call
* does not immediately update the center of mass.
* @param registry Data source.
* @param entity Rigid body entity.
* @param com Center of mass offset.
*/
void set_center_of_mass(entt::registry &, entt::entity, const vector3 &com);
void apply_center_of_mass(entt::registry &, entt::entity, const vector3 &com);
/**
* @brief Get location of rigid body's origin in world space. The position and
* origin will match if the center of mass offset is zero.
* @param registry Data source.
* @param entity Rigid body entity.
* @return Origin location in the world.
*/
vector3 get_rigidbody_origin(const entt::registry &, entt::entity);
/**
* @brief Get interpolated location of rigid body's origin in world space for
* presentation.
* @param registry Data source.
* @param entity Rigid body entity.
* @return Origin location in the world for presentation.
*/
vector3 get_rigidbody_present_origin(const entt::registry &, entt::entity);
}
#endif // EDYN_UTIL_RIGIDBODY_HPP
|
pdecat/facelets
|
src/main/java/com/sun/facelets/compiler/UITextHandler.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 com.sun.facelets.compiler;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import javax.el.ELException;
import javax.faces.FacesException;
import javax.faces.component.UIComponent;
import com.sun.facelets.FaceletContext;
import com.sun.facelets.FaceletException;
import com.sun.facelets.FaceletHandler;
import com.sun.facelets.el.ELText;
import com.sun.facelets.tag.TextHandler;
import com.sun.facelets.tag.jsf.ComponentSupport;
import com.sun.facelets.util.FastWriter;
/**
* @author <NAME>
* @version $Id: UITextHandler.java,v 1.10 2008-07-13 19:01:33 rlubke Exp $
*/
final class UITextHandler extends AbstractUIHandler {
private final ELText txt;
private final String alias;
private final int length;
public UITextHandler(String alias, ELText txt) {
this.alias = alias;
this.txt = txt;
this.length = txt.toString().length();
}
public void apply(FaceletContext ctx, UIComponent parent)
throws IOException, FacesException, FaceletException, ELException {
if (parent != null) {
try {
ELText nt = this.txt.apply(ctx.getExpressionFactory(), ctx);
UIComponent c = new UIText(this.alias, nt);
c.setId(ComponentSupport.getViewRoot(ctx, parent).createUniqueId());
this.addComponent(ctx, parent, c);
} catch (Exception e) {
throw new ELException(this.alias + ": "+ e.getMessage(), e.getCause());
}
}
}
public String toString() {
return this.txt.toString();
}
public String getText() {
return this.txt.toString();
}
public String getText(FaceletContext ctx) {
Writer writer = new FastWriter(this.length);
try {
this.txt.apply(ctx.getExpressionFactory(), ctx).write(writer, ctx);
} catch (IOException e) {
throw new ELException(this.alias + ": "+ e.getMessage(), e.getCause());
}
return writer.toString();
}
}
|
alwell-kevin/ears
|
pkg/plugin/types.go
|
<gh_stars>1-10
// Copyright 2020 Comcast Cable Communications Management, LLC
//
// 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 plugin
import (
"github.com/xmidt-org/ears/pkg/secret"
"github.com/xmidt-org/ears/pkg/tenant"
"sync"
"github.com/xmidt-org/ears/pkg/bit"
"github.com/xmidt-org/ears/pkg/filter"
"github.com/xmidt-org/ears/pkg/receiver"
"github.com/xmidt-org/ears/pkg/sender"
)
// === Plugin =========================================================
//go:generate rm -f testing_mock.go
//go:generate moq -out testing_mock.go . Hasher NewPluginerer Pluginer
// Hasher defines the hashing interface that a pluginer
// needs to implement
type Hasher interface {
// PluginerHash calculates the hash of a receiver based on the
// given configuration
PluginerHash(config interface{}) (string, error)
}
// NewPluginerer is something that is able to return a new Pluginer
type NewPluginerer interface {
Hasher
NewPluginer(config interface{}) (Pluginer, error)
}
// Pluginer defines values that should be returned in order to
// get visibility into which plugin was loaded and how it was
// configured.
type Pluginer interface {
Name() string
Version() string
CommitID() string
Config() string
// A bitmask of supported types
SupportedTypes() bit.Mask
}
const (
TypePluginer bit.Mask = 1 << iota
TypeReceiver
TypeSender
TypeFilter
)
type HashFn func(i interface{}) (string, error)
// TODO: Question -- How do these stay in sync with the package?
// Do we define them in the package alongside the interface definition?
type NewPluginerFn func(config interface{}) (Pluginer, error)
type NewReceiverFn func(tid tenant.Id, plugin string, name string, config interface{}, secrets secret.Vault) (receiver.Receiver, error)
type NewSenderFn func(tid tenant.Id, plugin string, name string, config interface{}, secrets secret.Vault) (sender.Sender, error)
type NewFiltererFn func(tid tenant.Id, plugin string, name string, config interface{}, secrets secret.Vault) (filter.Filterer, error)
// Plugin implements Pluginer
type Plugin struct {
sync.Mutex
name string
version string
commitID string
config interface{}
types bit.Mask
hashPluginer HashFn
hashReceiver HashFn
hashFilter HashFn
hashSender HashFn
newPluginer NewPluginerFn
newReceiver NewReceiverFn
newSender NewSenderFn
newFilterer NewFiltererFn
}
// === Errors =========================================================
// ErrorCode holds a numeric value that can be used to communicate an
// enumerated list of error codes back to the caller. It is expected
// that the user of the plugin will reference the plugin documentation
// to determine the meaning of the error.
type ErrorCode int
// TODO: Define an enumeration of codes to use to help determine
// how to handle the error
// Error wraps a plugin's errors. Because this package will have
// no knowledge of which plugins it's importing, the convention is for the
// plugin to set a Code associated with the plugin.
type Error struct {
Err error
Code ErrorCode
}
// InvalidConfigError is returned when a configuration parameter
// results in a plugin error
type InvalidConfigError struct {
Err error
}
// NotSupportedError can be returned if a plugin doesn't support publishing
// subscribing.
type NotSupportedError struct{}
type NilPluginError struct{}
|
pulipulichen/PACOR
|
app/Models/Traits/Tokenization.js
|
<filename>app/Models/Traits/Tokenization.js
'use strict'
const TokenizationHelper = use('App/Helpers/TokenizationHelper')
const tokenize = function (html) {
let properties = {}
if (typeof(html) !== 'string') {
return false
}
//console.log('Tokenization', 1)
properties.rawText = TokenizationHelper.htmlToText(html)
properties.rawText = TokenizationHelper.removePunctuations(properties.rawText)
//console.log('Tokenization', 2)
properties.charFrequency = TokenizationHelper.parseCharFrequency(properties.rawText)
properties.wordFrequency = TokenizationHelper.parseWordFrequency(properties.rawText, ['n', 'v', 'adj'])
//console.log('Tokenization', 3)
return properties
}
class Tokenization {
register(Model, {fromField, toField}) {
if (typeof(fromField) !== 'string' || typeof(toField) !== 'string') {
throw 'Lost fromField and toField'
}
/**
* 這似乎是不能用的
*/
// Model.addHook('afterSave', async (instance) => {
// if (!instance[toField]) {
// return false
// }
// let html = instance[fromField]
//
// let properties = tokenize(html)
// instance[toField] = properties
// await instance.save()
// //console.log('Tokenization', 4)
// })
/**
* 似乎是不能這樣做...
*/
/*
Model.addHook('afterSave', async (instance) => {
//console.log(instance[toField])
if (instance[toField] !== null) {
return false
}
console.log('Tokenization', toField, instance[toField])
let html = instance[fromField]
let properties = tokenize(html)
instance[toField] = properties
await instance.save()
//console.log('Tokenization', 4)
})
*/
Model.addHook('beforeSave', async (instance) => {
//console.log(instance[toField])
// if (!instance[toField]
// || (typeof(instance[toField]) === 'object' && Object.keys(instance[toField]).length === 0)) {
// return false
// }
let html = instance[fromField]
let properties = tokenize(html)
instance[toField] = properties
//console.log('Tokenization', 4)
})
} // register (Model) {
}
module.exports = Tokenization
|
Yoda2798/YodasMod
|
src/main/java/YodasMod/relics/Duality2.java
|
package YodasMod.relics;
import com.megacrit.cardcrawl.actions.common.ApplyPowerAction;
import com.megacrit.cardcrawl.actions.common.RelicAboveCreatureAction;
import com.megacrit.cardcrawl.actions.utility.UseCardAction;
import com.megacrit.cardcrawl.cards.AbstractCard;
import com.megacrit.cardcrawl.characters.AbstractPlayer;
import com.megacrit.cardcrawl.dungeons.AbstractDungeon;
import com.megacrit.cardcrawl.powers.LoseStrengthPower;
import com.megacrit.cardcrawl.powers.StrengthPower;
import static YodasMod.YodasMod.makeID;
public class Duality2 extends AbstractEasyRelic {
public static final String ID = makeID("Duality2");
public Duality2() {
super(ID, RelicTier.UNCOMMON, LandingSound.MAGICAL, AbstractCard.CardColor.PURPLE);
}
public void onUseCard(AbstractCard card, UseCardAction action) {
if (card.type == AbstractCard.CardType.SKILL) {
this.flash();
AbstractPlayer p = AbstractDungeon.player;
this.addToBot(new RelicAboveCreatureAction(p, this));
this.addToBot(new ApplyPowerAction(p, p, new StrengthPower(p, 1), 1));
this.addToBot(new ApplyPowerAction(p, p, new LoseStrengthPower(p, 1), 1));
}
}
}
|
Coders-Beyond-Bars/website_gatsby
|
src/pages/index.js
|
<filename>src/pages/index.js
import React, { Component } from "react"
import { Link } from "gatsby"
import { Typography, Grid, Hidden } from "@material-ui/core"
import { withStyles } from "@material-ui/styles"
import Layout from "components/Layout"
import Section from "components/Section"
import CBBButton from "components/CBBButton"
import MasterHeaderSection from 'sections/MasterHeaderSection'
import PartnersSection from "sections/PartnersSection"
import styles from "assets/jss/pages/home"
import stockImage1 from "assets/images/stock/stock1-800x800.jpg"
import stockImage2 from "assets/images/stock/stock2-800x800.jpg"
import stockImage3 from "assets/images/stock/stock3-800x800.jpg"
import stockImage4 from "assets/images/stock/recidivism.jpg"
import stockImage5 from "assets/images/stock/unemployment.jpg"
import Context from 'context'
const SECTIONS = [
"header",
"challenges"
]
class Index extends Component {
constructor(props) {
super(props)
this.state = {
section: 'header',
setSection: this.setSection,
yCoordinates: SECTIONS.reduce((obj, item) => {
obj[item] = 0
return obj
}, {})
}
}
componentDidMount() {
window.addEventListener('resize', this.handleResize)
window.scrollTo({ top: 0, behavior: 'smooth' })
setTimeout(
function() {
this.handleResize()
}.bind(this),
1000
)
}
componentWillUnmount() {
window.removeEventListener('resize', this.handleResize)
}
handleResize = () => {
const { yCoordinates } = this.state
Object.keys(yCoordinates).forEach(section => {
const dom = document.getElementById(section)
this.setState(prevState => ({
...prevState,
yCoordinates: {
...prevState.yCoordinates,
[section]: dom.offsetTop
}
}))
})
}
setSection = section => {
this.setState({ section })
const navBar = document.getElementById("navbar")
window.scrollTo({
top: this.state.yCoordinates[section] - navBar.offsetHeight,
behavior: "smooth"
})
}
render() {
const { classes } = this.props;
return (
<>
<Context.Provider value={this.state}>
<Layout title="Home" >
<MasterHeaderSection id="header" />
<Section
id="challenges"
title="Challenges"
subtitle="Too many Americans are barred from growing economic opportunities due to their experience with the criminal-justice system"
shaded
>
<Grid container spacing={4}>
<Grid item xs={12} sm={12} md={5}>
<img src={stockImage4} alt="Prison" className={classes.fullWidth} />
</Grid>
<Grid item xs={12} sm={12} md={7} className={classes.verticalCenter}>
<Typography
variant="h4"
gutterBottom
color="inherit"
>
Too many Americans are impacted by criminal-justice system
</Typography>
<Typography
variant="h6"
gutterBottom
color="inherit"
>
There are over 2 million individuals behind bars in
county jails, state prisons, and federal penitentiaries at any give moment across the country.
To put this into another perspective, more than one in one-hundred adults
between the ages of eighteen and sixty-five are behind bars in the
US.
</Typography>
<Typography
variant="h6"
gutterBottom
color="inherit"
>
This figure does not even include millions more who are
on parole or probation and are still part of the correctional
system.
</Typography>
<Typography
variant="h6"
gutterBottom
color="inherit"
>
We call these individuals, <strong>"Returning Citizens."</strong>
They are our family members, friends, neighbors, and valuable members of our community.
</Typography>
</Grid>
<Grid item xs={12} sm={12} md={7} className={classes.verticalCenter}>
<Typography
variant="h4"
gutterBottom
color="inherit"
>
Returning Citizens are deemed 'untouchable' by employers
</Typography>
<Typography
variant="h6"
gutterBottom
color="inherit"
>
Up to 60% of returning citizens remain jobless a year after their release due to their criminal
records and lack of employable skills. Locked out of gainful employment opportunities, many returning citizens
fall back to substance abuse or engage in criminal activities.
According to research reported by the Department of Justice, 67.8% of returning citizens
were arrested again within 3 years of their release and 76.6% within 5 years.
</Typography>
<Typography
variant="h6"
gutterBottom
color="inherit"
>
Urban Institute reported in its 2008 research report that individuals who made
more than $10 an hour were half as likely to return to prison as those making less than $7 an hour.
Their finding shows us that having a stable source of income and a career path with the potential for financial upward mobility
should be crucial pillars of a successful re-entry process for returning citizens.
</Typography>
</Grid>
<Grid item xs={12} sm={12} md={5}>
<img src={stockImage5} alt="Job Line" className={classes.fullWidth} />
</Grid>
</Grid>
</Section>
<Section
id="solutions"
title="Who We Are"
subtitle="Our vision of the future is a place where returning citizens
can become productive, contributing members of our society again."
>
<Grid container spacing={4}>
<Grid item xs={12} sm={12} md={5}>
<img src={stockImage3} alt="About Us" className={classes.fullWidth}/>
</Grid>
<Grid item xs={12} sm={12} md={7} className={classes.verticalCenter}>
<Typography
variant="h4"
gutterBottom
color="secondary"
>
We 'reboot' careers and lives
</Typography>
<Typography
variant="h6"
gutterBottom
color="secondary"
>
Studies show that having gainful employment
with a stable income is the best solution
to preventing returning citizens from going back to correctional systems.
</Typography>
<Typography
variant="h6"
gutterBottom
color="secondary"
>
Reboot to Tech empowers and equips returning citizens
with skills in high-tech industries and on-site work experience
to help them attain successful careers and regain
the dignity of becoming contributing members of society.
</Typography>
<div className={classes.buttonContainer}>
<CBBButton
size="large"
color="primary"
component={Link}
to="/about/"
>
Read More
</CBBButton>
</div>
</Grid>
</Grid>
</Section>
<Section
shaded
title="What We Can Do for You"
subtitle="Are you a returning citizen or someone who knows a friend or family member who is?"
>
<Grid container spacing={4}>
<Grid item xs={12} sm={12} md={5}>
<img src={stockImage1} alt="Returning Citizens" className={classes.fullWidth} />
</Grid>
<Grid item xs={12} sm={12} md={7} className={classes.verticalCenter} >
<Typography variant="h4" gutterBottom>
Reboot your career and life
</Typography>
<Typography variant="h6" gutterBottom >
You've made mistakes in the past, but those mistakes define
who you are and your worth as a member of your community.
We understand your frustration with navigating a job market that doesn't give you a fair look.
We worked with many other returning citizens who faced similar circumstances.
</Typography>
<Typography variant="h6" gutterBottom>
It's time to reboot your career and life. Let us show you how.
</Typography>
<div className={classes.buttonContainer}>
<CBBButton
size="large"
color="secondary"
component={Link}
to="/getInvolved/"
>
Ready to get started?
</CBBButton>
</div>
</Grid>
</Grid>
</Section>
<Section
title="Partnering with Us"
subtitle="Tap into one of the largest untapped labor force in the country"
>
<Grid container spacing={4}>
<Hidden mdUp>
<Grid item xs={12} sm={12} md={5}>
<img src={stockImage2} alt="Corporate Partnerships" className={classes.fullWidth} />
</Grid>
</Hidden>
<Grid item xs={12} sm={12} md={7} className={classes.verticalCenter}>
<Typography variant="h4" gutterBottom color="secondary">
Let us help you find your next star employee
</Typography>
<Typography variant="h6" gutterBottom color="secondary">
Returning citizens constitute one of the largest untapped potential labor force in the country.
Often shunned by traditional employers, many returning citizens hold a strong yearning for a second-chance
to become contributing members of our society again. They are ready to work and commit to an
employer willing to give them a chance.
</Typography>
<Typography variant="h6" gutterBottom color="secondary">
Discover how you can make a deep impact on the lives of returning citizens while
retaining talented and committed employees ready to add value to your firm.
</Typography>
<br />
<div className={classes.buttonContainer}>
<CBBButton
size="large"
color="primary"
component={Link}
to="/companies/"
>
Partner with us
</CBBButton>
</div>
</Grid>
<Hidden smDown>
<Grid item xs={12} sm={12} md={5}>
<img src={stockImage2} alt="Corporate Partnerships" className={classes.fullWidth} />
</Grid>
</Hidden>
</Grid>
</Section>
<PartnersSection id="partners"/>
</Layout>
</Context.Provider>
</>
)
}
}
export default withStyles(styles)(Index)
|
AdityaSidharta/bamboos
|
bamboos/utils/model/model_zoo.py
|
from typing import Any
from sklearn.ensemble import (
AdaBoostClassifier,
AdaBoostRegressor,
BaggingClassifier,
BaggingRegressor,
ExtraTreesClassifier,
ExtraTreesRegressor,
GradientBoostingClassifier,
GradientBoostingRegressor,
RandomForestClassifier,
RandomForestRegressor,
)
from sklearn.linear_model import (
ElasticNet,
Lasso,
LinearRegression,
LogisticRegression,
Ridge,
RidgeClassifier,
)
from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor
from sklearn.neural_network import MLPClassifier, MLPRegressor
from sklearn.svm import LinearSVC, LinearSVR, SVC, SVR
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
from bamboos.utils.model.ligthgbm_model import LGBModel
from bamboos.utils.model.sklearn_model import SkLearnModel
from bamboos.utils.model.xgboost_model import XGBoostModel
estimator_dict = {
"LinearRegression": LinearRegression,
"Ridge": Ridge,
"Lasso": Lasso,
"ElasticNet": ElasticNet,
"SVR": SVR,
"LinearSVR": LinearSVR,
"KNeighborsRegressor": KNeighborsRegressor,
"DecisionTreeRegressor": DecisionTreeRegressor,
"AdaBoostRegressor": AdaBoostRegressor,
"BaggingRegressor": BaggingRegressor,
"ExtraTreesRegressor": ExtraTreesRegressor,
"GradientBoostingRegressor": GradientBoostingRegressor,
"RandomForestRegressor": RandomForestRegressor,
"MLPRegressor": MLPRegressor,
"LogisticRegression": LogisticRegression,
"RidgeClassifier": RidgeClassifier,
"SVC": SVC,
"LinearSVC": LinearSVC,
"GaussianNB": GaussianNB,
"KNeighborsClassifier": KNeighborsClassifier,
"DecisionTreeClassifier": DecisionTreeClassifier,
"AdaBoostClassifier": AdaBoostClassifier,
"BaggingClassifier": BaggingClassifier,
"ExtraTreesClassifier": ExtraTreesClassifier,
"GradientBoostingClassifier": GradientBoostingClassifier,
"RandomForestClassifier": RandomForestClassifier,
"MLPClassifier": MLPClassifier,
}
def get_estimator(model_name: str):
if model_name in estimator_dict.keys():
return estimator_dict[model_name]
raise ValueError("model_name is not inside catalyst model dictionary")
def createModel(model_name: str, model_type: str, num_class: int = None, **kwargs):
if model_type == "multiclass":
if num_class is None:
raise AssertionError("For multiclass model, num_class must be provided")
model: Any
if "XGBoost" in model_name:
if num_class:
model = XGBoostModel(model_name, model_type, num_class=num_class, **kwargs)
else:
model = XGBoostModel(model_name, model_type, **kwargs)
elif "LightGBM" in model_name:
if num_class:
model = LGBModel(model_name, model_type, num_class=num_class, **kwargs)
else:
model = LGBModel(model_name, model_type, **kwargs)
else:
estimator = get_estimator(model_name)
if num_class:
model = SkLearnModel(
model_name, estimator(**kwargs), model_type, num_class=num_class
)
else:
model = SkLearnModel(model_name, estimator(**kwargs), model_type)
return model
def regression_model_dict() -> dict:
"""
Wrapper function containing dictionary of all sklearn, xgboost, and light gbm models for regression dataset.
Returns:
Dictionary containing all sklearn, xgboost, and light gbm models for regression dataset
"""
return {
"LinearRegression": createModel("LinearRegression", "regression"),
"Ridge": createModel("Ridge", "regression"),
"Lasso": createModel("Lasso", "regression"),
"ElasticNet": createModel("ElasticNet", "regression"),
"KNeighborsRegressor": createModel("KNeighborsRegressor", "regression"),
"DecisionTreeRegressor": createModel("DecisionTreeRegressor", "regression"),
"AdaBoostRegressor": createModel("AdaBoostRegressor", "regression"),
"BaggingRegressor": createModel("BaggingRegressor", "regression"),
"ExtraTreesRegressor": createModel(
"ExtraTreesRegressor", "regression", n_estimators=100
),
"GradientBoostingRegressor": createModel(
"GradientBoostingRegressor", "regression"
),
"RandomForestRegressor": createModel(
"RandomForestRegressor", "regression", n_estimators=100
),
"XGBoost": createModel("XGBoostRegressor", "regression", num_boost_round=100),
"LightGBM": createModel("LightGBMRegressor", "regression", num_boost_round=100),
}
def binary_model_dict() -> dict:
"""
Wrapper function containing dictionary of all sklearn, xgboost, and light gbm models for binary dataset.
Returns:
Dictionary containing all sklearn, xgboost, and light gbm models for binary dataset
"""
return {
"LogisticRegression": createModel(
"LogisticRegression", "binary", solver="lbfgs", max_iter=1000
),
"GaussianNB": createModel("GaussianNB", "binary"),
"KNeighborsClassifier": createModel("KNeighborsClassifier", "binary"),
"DecisionTreeClassifier": createModel("DecisionTreeClassifier", "binary"),
"AdaBoostClassifier": createModel("AdaBoostClassifier", "binary"),
"BaggingClassifier": createModel("BaggingClassifier", "binary"),
"ExtraTreesClassifier": createModel(
"ExtraTreesClassifier", "binary", n_estimators=100
),
"GradientBoostingClassifier": createModel(
"GradientBoostingClassifier", "binary"
),
"RandomForestClassifier": createModel(
"RandomForestClassifier", "binary", n_estimators=100
),
"XGBoost": createModel("XGBoostBinary", "binary", num_boost_round=100),
"LightGBM": createModel("LightGBMBinary", "binary", num_boost_round=100),
}
def multiclass_model_dict(num_class: int) -> dict:
"""
Wrapper function containing dictionary of all sklearn, xgboost, and light gbm models for multiclass dataset.
Args:
num_class (int): Number of class in the multiclass dataset
Returns:
Dictionary containing all sklearn, xgboost, and light gbm models for multiclass dataset
"""
return {
"LogisticRegression": createModel(
"LogisticRegression",
"multiclass",
num_class=num_class,
multi_class="multinomial",
solver="lbfgs",
max_iter=1000,
),
"GaussianNB": createModel("GaussianNB", "multiclass", num_class=num_class),
"KNeighborsClassifier": createModel(
"KNeighborsClassifier", "multiclass", num_class=num_class
),
"DecisionTreeClassifier": createModel(
"DecisionTreeClassifier", "multiclass", num_class=num_class
),
"ExtraTreesClassifier": createModel(
"ExtraTreesClassifier", "multiclass", num_class=num_class, n_estimators=100
),
"RandomForestClassifier": createModel(
"RandomForestClassifier",
"multiclass",
num_class=num_class,
n_estimators=100,
),
"XGBoost": createModel(
"XGBoostBinary", "multiclass", num_class=num_class, num_boost_round=100
),
"LightGBM": createModel(
"LightGBMBinary", "multiclass", num_class=num_class, num_boost_round=100
),
}
|
taufique71/sports-programming
|
uva/11448 - Who Said Crisis.cpp
|
<reponame>taufique71/sports-programming
#include <iostream>
#include <cstring>
#define MAX 10010
using namespace std;
class BigNumber
{
public:
char* add(char s1[], char s2[]) // addition
{
char *a = new char[MAX];
char *b = new char[MAX];
if(strlen(s1) >= strlen(s2))
{
strcpy(a,s1);
strcpy(b,s2);
}
else
{
strcpy(b,s1);
strcpy(a,s2);
}
char* temp = new char[MAX];
char* result = new char[MAX];
int len_a = strlen(a) - 1;
int len_b = strlen(b) - 1;
temp[MAX - 1] = '\0';
int len_temp = MAX - 2;
int carry = 0;
int i;
while(len_b >= 0)
{
temp[len_temp] = (b[len_b]-48 + a[len_a]-48 + carry) % 10 + 48;
carry = (b[len_b]-48 + a[len_a]-48 + carry) / 10;
len_temp--;
len_a--;
len_b--;
}
while(len_a >= 0)
{
temp[len_temp] = (a[len_a]-48 + carry) % 10 + 48;
carry = (a[len_a]-48 + carry) / 10;
len_temp--;
len_a--;
}
temp[len_temp] = carry % 10 + 48;
carry = carry / 10;
while(temp[len_temp] == '0') len_temp++;
for(i = 0 ; temp[len_temp] ; i++,len_temp++) result[i] = temp[len_temp];
result[i] = '\0';
return result;
}
int is_greater(char a[], char b[]) // Greater than or not tester
{
int len_a = strlen(a);
int len_b = strlen(b);
if(len_a > len_b) return 1;
else if(len_a < len_b) return -1;
else return strcmp(a,b);
}
int is_lesser(char a[], char b[]) // Lesser than or not tester
{
int len_a = strlen(a);
int len_b = strlen(b);
if(len_a < len_b) return 1;
else if(len_a > len_b) return -1;
else return strcmp(b,a);
}
char* subtract(char s1[], char s2[]) // Subtraction(returns just defference not negetive value)
{
char* a = new char[MAX];
char* b = new char[MAX];
char* temp = new char[MAX];
char* res = new char[MAX];
int i,j;
if(is_greater(s1,s2) >= 0)
{
strcpy(a,s1);
for(i = 0 ; a[i] ; i++) b[i] = '0';
b[i] = '\0';
i--;
for(j = strlen(s2) - 1 ; j >= 0 ; j--,i--) b[i] = s2[j];
}
else
{
strcpy(a,s2);
for(i = 0 ; a[i] ; i++) b[i] = '0';
b[i] = '\0';
i--;
for(j = strlen(s1) - 1 ; j >= 0 ; j--,i--) b[i] = s1[j];
}
int borrow = 0;
int num1,num2;
temp[strlen(a)] = '\0';
for(i = strlen(a) - 1 ; i >= 0 ; i--)
{
num2 = b[i] - 48 + borrow;
num1 = a[i] - 48;
if(num2 > num1)
{
num1 += 10;
borrow = 1;
}
else borrow = 0;
temp[i] = num1 - num2 + 48;
}
i = 0;
j = 0;
while(temp[i] == '0') i++;
if(temp[i]) for(j = 0 ; temp[i] ; j++,i++) res[j] = temp[i];
else res[j++] = '0';
res[j] = '\0';
return res;
}
};
int main()
{
BigNumber big;
char first[MAX],second[MAX];
int n_case;
cin >> n_case;
getchar();
while(n_case--)
{
cin >> first >> second;
if(big.is_greater(first,second) >= 0) cout << big.subtract(first,second) << endl;
else cout << '-' << big.subtract(first,second) << endl;
}
return 0;
}
|
ajaymr12/openram
|
compiler/drc/design_rules.py
|
# See LICENSE for licensing information.
#
# Copyright (c) 2016-2019 Regents of the University of California and The Board
# of Regents for the Oklahoma Agricultural and Mechanical College
# (acting for and on behalf of Oklahoma State University)
# All rights reserved.
#
import debug
from drc_value import *
from drc_lut import *
class design_rules():
"""
This is a class that implements the design rules structures.
"""
def __init__(self, name):
self.tech_name = name
self.rules = {}
def add(self, name, value):
self.rules[name] = value
def __call__(self, name, *args):
rule = self.rules[name]
if callable(rule):
return rule(*args)
else:
return rule
def __setitem__(self, b, c):
"""
For backward compatibility with existing rules.
"""
self.rules[b] = c
def __getitem__(self, b):
"""
For backward compatibility with existing rules.
"""
rule = self.rules[b]
if not callable(rule):
return rule
else:
debug.error("Must call complex DRC rule {} with arguments.".format(b),-1)
|
fluorumlabs/dtrack-maven-plugin
|
src/main/java/com/github/fluorumlabs/dtrack/model/ManagedUser.java
|
<gh_stars>0
/*
* Copyright 2021 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Dependency-Track API
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 4.2.1
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package com.github.fluorumlabs.dtrack.model;
import java.util.Objects;
import java.util.Arrays;
import com.github.fluorumlabs.dtrack.model.Permission;
import com.github.fluorumlabs.dtrack.model.Team;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* ManagedUser
*/
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2021-05-21T09:42:21.596Z")
public class ManagedUser {
@SerializedName("username")
private String username = null;
@SerializedName("newPassword")
private String newPassword = null;
@SerializedName("confirmPassword")
private String confirmPassword = null;
@SerializedName("lastPasswordChange")
private Double lastPasswordChange = null;
@SerializedName("fullname")
private String fullname = null;
@SerializedName("email")
private String email = null;
@SerializedName("suspended")
private Boolean suspended = null;
@SerializedName("forcePasswordChange")
private Boolean forcePasswordChange = null;
@SerializedName("nonExpiryPassword")
private Boolean nonExpiryPassword = null;
@SerializedName("teams")
private List<Team> teams = null;
@SerializedName("permissions")
private List<Permission> permissions = null;
public ManagedUser username(String username) {
this.username = username;
return this;
}
/**
* Get username
* @return username
**/
@ApiModelProperty(value = "")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public ManagedUser newPassword(String newPassword) {
this.newPassword = <PASSWORD>;
return this;
}
/**
* Get newPassword
* @return newPassword
**/
@ApiModelProperty(value = "")
public String getNewPassword() {
return <PASSWORD>Password;
}
public void setNewPassword(String newPassword) {
this.newPassword = <PASSWORD>;
}
public ManagedUser confirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
return this;
}
/**
* Get confirmPassword
* @return confirmPassword
**/
@ApiModelProperty(value = "")
public String getConfirmPassword() {
return confirmPassword;
}
public void setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
}
public ManagedUser lastPasswordChange(Double lastPasswordChange) {
this.lastPasswordChange = lastPasswordChange;
return this;
}
/**
* Get lastPasswordChange
* @return lastPasswordChange
**/
@ApiModelProperty(required = true, value = "")
public Double getLastPasswordChange() {
return lastPasswordChange;
}
public void setLastPasswordChange(Double lastPasswordChange) {
this.lastPasswordChange = lastPasswordChange;
}
public ManagedUser fullname(String fullname) {
this.fullname = fullname;
return this;
}
/**
* Get fullname
* @return fullname
**/
@ApiModelProperty(value = "")
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public ManagedUser email(String email) {
this.email = email;
return this;
}
/**
* Get email
* @return email
**/
@ApiModelProperty(value = "")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public ManagedUser suspended(Boolean suspended) {
this.suspended = suspended;
return this;
}
/**
* Get suspended
* @return suspended
**/
@ApiModelProperty(value = "")
public Boolean isSuspended() {
return suspended;
}
public void setSuspended(Boolean suspended) {
this.suspended = suspended;
}
public ManagedUser forcePasswordChange(Boolean forcePasswordChange) {
this.forcePasswordChange = forcePasswordChange;
return this;
}
/**
* Get forcePasswordChange
* @return forcePasswordChange
**/
@ApiModelProperty(value = "")
public Boolean isForcePasswordChange() {
return forcePasswordChange;
}
public void setForcePasswordChange(Boolean forcePasswordChange) {
this.forcePasswordChange = forcePasswordChange;
}
public ManagedUser nonExpiryPassword(Boolean nonExpiryPassword) {
this.nonExpiryPassword = <PASSWORD>Password;
return this;
}
/**
* Get nonExpiryPassword
* @return nonExpiryPassword
**/
@ApiModelProperty(value = "")
public Boolean isNonExpiryPassword() {
return nonExpiryPassword;
}
public void setNonExpiryPassword(Boolean nonExpiryPassword) {
this.nonExpiryPassword = nonExpiryPassword;
}
public ManagedUser teams(List<Team> teams) {
this.teams = teams;
return this;
}
public ManagedUser addTeamsItem(Team teamsItem) {
if (this.teams == null) {
this.teams = new ArrayList<>();
}
this.teams.add(teamsItem);
return this;
}
/**
* Get teams
* @return teams
**/
@ApiModelProperty(value = "")
public List<Team> getTeams() {
return teams;
}
public void setTeams(List<Team> teams) {
this.teams = teams;
}
public ManagedUser permissions(List<Permission> permissions) {
this.permissions = permissions;
return this;
}
public ManagedUser addPermissionsItem(Permission permissionsItem) {
if (this.permissions == null) {
this.permissions = new ArrayList<>();
}
this.permissions.add(permissionsItem);
return this;
}
/**
* Get permissions
* @return permissions
**/
@ApiModelProperty(value = "")
public List<Permission> getPermissions() {
return permissions;
}
public void setPermissions(List<Permission> permissions) {
this.permissions = permissions;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ManagedUser managedUser = (ManagedUser) o;
return Objects.equals(this.username, managedUser.username) &&
Objects.equals(this.newPassword, <PASSWORD>User.newPassword) &&
Objects.equals(this.confirmPassword, managedUser.confirmPassword) &&
Objects.equals(this.lastPasswordChange, managedUser.lastPasswordChange) &&
Objects.equals(this.fullname, managedUser.fullname) &&
Objects.equals(this.email, managedUser.email) &&
Objects.equals(this.suspended, managedUser.suspended) &&
Objects.equals(this.forcePasswordChange, managedUser.forcePasswordChange) &&
Objects.equals(this.nonExpiryPassword, managedUser.nonExpiryPassword) &&
Objects.equals(this.teams, managedUser.teams) &&
Objects.equals(this.permissions, managedUser.permissions);
}
@Override
public int hashCode() {
return Objects.hash(username, newPassword, confirmPassword, lastPasswordChange, fullname, email, suspended, forcePasswordChange, nonExpiryPassword, teams, permissions);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ManagedUser {\n");
sb.append(" username: ").append(toIndentedString(username)).append("\n");
sb.append(" newPassword: ").append(toIndentedString(newPassword)).append("\n");
sb.append(" confirmPassword: ").append(toIndentedString(confirmPassword)).append("\n");
sb.append(" lastPasswordChange: ").append(toIndentedString(lastPasswordChange)).append("\n");
sb.append(" fullname: ").append(toIndentedString(fullname)).append("\n");
sb.append(" email: ").append(toIndentedString(email)).append("\n");
sb.append(" suspended: ").append(toIndentedString(suspended)).append("\n");
sb.append(" forcePasswordChange: ").append(toIndentedString(forcePasswordChange)).append("\n");
sb.append(" nonExpiryPassword: ").append(toIndentedString(nonExpiryPassword)).append("\n");
sb.append(" teams: ").append(toIndentedString(teams)).append("\n");
sb.append(" permissions: ").append(toIndentedString(permissions)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
synacts/digitalid-utility
|
property/src/main/java/net/digitalid/utility/property/set/ReadOnlySetProperty.java
|
/*
* Copyright (C) 2017 Synacts GmbH, Switzerland (<EMAIL>)
*
* 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 net.digitalid.utility.property.set;
import javax.annotation.Nonnull;
import net.digitalid.utility.annotations.generics.Unspecifiable;
import net.digitalid.utility.annotations.method.Pure;
import net.digitalid.utility.annotations.type.ThreadSafe;
import net.digitalid.utility.collaboration.annotations.TODO;
import net.digitalid.utility.collaboration.enumerations.Author;
import net.digitalid.utility.collaboration.enumerations.Priority;
import net.digitalid.utility.collections.set.ReadOnlySet;
import net.digitalid.utility.freezable.annotations.NonFrozen;
import net.digitalid.utility.property.Property;
import net.digitalid.utility.validation.annotations.elements.NonNullableElements;
import net.digitalid.utility.validation.annotations.type.ReadOnly;
import net.digitalid.utility.validation.annotations.value.Valid;
/**
* This read-only property stores a set of values.
*
* @see WritableSetProperty
* @see ReadOnlyVolatileSetProperty
* @see ReadOnlySetPropertyImplementation
*/
@ThreadSafe
@ReadOnly(WritableSetProperty.class)
@TODO(task = "Restrict the ReadOnlySet to a SynchronizedReadOnlySet.", date = "2016-09-27", author = Author.KASPAR_ETTER, assignee = Author.KASPAR_ETTER, priority = Priority.MIDDLE)
public interface ReadOnlySetProperty<@Unspecifiable VALUE, @Unspecifiable READONLY_SET extends ReadOnlySet<@Nonnull @Valid VALUE>, @Unspecifiable EXCEPTION1 extends Exception, @Unspecifiable EXCEPTION2 extends Exception, @Unspecifiable OBSERVER extends SetObserver<VALUE, READONLY_SET, EXCEPTION1, EXCEPTION2, OBSERVER, PROPERTY>, @Unspecifiable PROPERTY extends ReadOnlySetProperty<VALUE, READONLY_SET, EXCEPTION1, EXCEPTION2, OBSERVER, PROPERTY>> extends Property<OBSERVER>, Valid.Value<VALUE> {
/* -------------------------------------------------- Getter -------------------------------------------------- */
/**
* Returns a read-only set with the values of this property.
*/
@Pure
public @Nonnull @NonFrozen @NonNullableElements READONLY_SET get() throws EXCEPTION1, EXCEPTION2;
}
|
reinago/megamol
|
plugins/gui/src/graph/ParameterGroups.cpp
|
<reponame>reinago/megamol<gh_stars>0
/*
* ParameterGroups.cpp
*
* Copyright (C) 2020 by Universitaet Stuttgart (VIS).
* Alle Rechte vorbehalten.
*/
#include "stdafx.h"
#include "ParameterGroups.h"
using namespace megamol;
using namespace megamol::core;
using namespace megamol::gui;
megamol::gui::ParameterGroups::ParameterGroups(void)
: group_widget_ids()
, tooltip()
, speed_knob_pos(ImVec2(0.0f, 0.0f))
, time_knob_pos(ImVec2(0.0f, 0.0f))
, image_buttons() {
// Add group widget data for animation widget group
/// View3D_2::anim
GroupWidgetData animation;
animation.active = false;
animation.type.emplace(Param_t::BOOL, 1);
animation.type.emplace(Param_t::BUTTON, 3);
animation.type.emplace(Param_t::FLOAT, 2);
animation.callback = [&, this](ParamPtrVector_t& params,
megamol::core::param::AbstractParamPresentation::Presentation presentation,
megamol::gui::ParameterPresentation::WidgetScope in_scope) -> bool {
return this->group_widget_animation(params, presentation, in_scope);
};
group_widget_ids["anim"] = animation;
}
megamol::gui::ParameterGroups::~ParameterGroups(void) {}
bool megamol::gui::ParameterGroups::PresentGUI(megamol::gui::ParamVector_t& inout_params,
const std::string& in_module_fullname, const std::string& in_search, bool in_extended, bool in_ignore_extended,
megamol::gui::ParameterPresentation::WidgetScope in_scope,
const std::shared_ptr<TransferFunctionEditor> in_external_tf_editor, bool* out_open_external_tf_editor) {
if (out_open_external_tf_editor != nullptr) (*out_open_external_tf_editor) = false;
// Nothing to do if there are no parameters
if (inout_params.empty()) return true;
if (in_scope == ParameterPresentation::WidgetScope::LOCAL) {
/// LOCAL
ImGui::BeginGroup();
ImGui::Indent();
}
// Analyse parameter group membership and draw ungrouped parameters
ParamGroup_t group_map;
for (auto& param : inout_params) {
auto param_namespace = param.GetNameSpace();
if (!in_ignore_extended) {
param.present.extended = in_extended;
}
if (!param_namespace.empty()) {
// Sort parameters with namespace to group
group_map[param_namespace].first.emplace_back(¶m);
group_map[param_namespace].second[param.type]++;
} else {
// Draw parameters without namespace directly at the beginning
this->draw_parameter(
param, in_module_fullname, in_search, in_scope, in_external_tf_editor, out_open_external_tf_editor);
}
}
// Draw grouped parameters
for (auto& group : group_map) {
auto group_name = group.first;
bool found_group_widget = false;
// Draw group widget (if defined) ...
for (auto& group_widget_id : this->group_widget_ids) {
// Check for same group name and count of different parameter types
/// TODO Is this check too expensive? (remove check for group_name)
if ((group_widget_id.second.type == group.second.second) && (group_widget_id.first == group_name)) {
found_group_widget = true;
group_widget_id.second.active = true;
ImGui::PushID(group_widget_id.first.c_str());
if (in_scope == ParameterPresentation::WidgetScope::LOCAL) {
if (in_extended) {
// Visibility
bool visible = group_widget_id.second.IsGUIVisible();
if (ImGui::RadioButton("###visibile", visible)) {
group_widget_id.second.SetGUIVisible(!visible);
}
this->tooltip.ToolTip("Visibility", ImGui::GetItemID(), 0.5f);
ImGui::SameLine();
// Read-only option
bool readonly = group_widget_id.second.IsGUIReadOnly();
if (ImGui::Checkbox("###readonly", &readonly)) {
group_widget_id.second.SetGUIReadOnly(readonly);
}
this->tooltip.ToolTip("Read-Only", ImGui::GetItemID(), 0.5f);
ImGui::SameLine();
ParameterPresentation::OptionButton(
"param_groups", "", (group_widget_id.second.GetGUIPresentation() != Present_t::Basic));
if (ImGui::BeginPopupContextItem("param_present_button_context", 0)) {
for (auto& present_name_pair : group_widget_id.second.GetPresentationNameMap()) {
if (group_widget_id.second.IsPresentationCompatible(present_name_pair.first)) {
if (ImGui::MenuItem(present_name_pair.second.c_str(), nullptr,
(present_name_pair.first == group_widget_id.second.GetGUIPresentation()))) {
group_widget_id.second.SetGUIPresentation(present_name_pair.first);
}
}
}
ImGui::EndPopup();
}
this->tooltip.ToolTip("Presentation", ImGui::GetItemID(), 0.5f);
ImGui::SameLine();
}
// Call group widget draw function
if (group_widget_id.second.IsGUIVisible() || in_extended) {
if (group_widget_id.second.IsGUIReadOnly()) {
GUIUtils::ReadOnlyWigetStyle(true);
}
if (group_widget_id.second.GetGUIPresentation() ==
param::AbstractParamPresentation::Presentation::Basic) {
this->draw_grouped_parameters(group_name, group.second.first, in_module_fullname, in_search,
in_scope, in_external_tf_editor, out_open_external_tf_editor);
} else {
if (!group_widget_id.second.callback(
group.second.first, group_widget_id.second.GetGUIPresentation(), in_scope)) {
megamol::core::utility::log::Log::DefaultLog.WriteError(
"No widget presentation '%s' available for group widget '%s'. [%s, %s, line %d]\n",
group_widget_id.second
.GetPresentationName(group_widget_id.second.GetGUIPresentation())
.c_str(),
group_name.c_str(), __FILE__, __FUNCTION__, __LINE__);
}
}
if (group_widget_id.second.IsGUIReadOnly()) {
GUIUtils::ReadOnlyWigetStyle(false);
}
}
} else {
// GLOBAL
group_widget_id.second.callback(
group.second.first, group_widget_id.second.GetGUIPresentation(), in_scope);
}
ImGui::PopID();
}
}
// ... else draw grouped parameters with no custom group widget using namespace header.
if (!found_group_widget) {
if (in_scope == ParameterPresentation::WidgetScope::LOCAL) {
/// LOCAL
this->draw_grouped_parameters(group_name, group.second.first, in_module_fullname, in_search, in_scope,
in_external_tf_editor, out_open_external_tf_editor);
} else {
/// GLOBAL
for (auto& param : group.second.first) {
this->draw_parameter((*param), in_module_fullname, in_search, in_scope, in_external_tf_editor,
out_open_external_tf_editor);
}
}
}
}
if (in_scope == ParameterPresentation::WidgetScope::LOCAL) {
/// LOCAL
ImGui::Unindent();
ImGui::EndGroup();
}
return true;
}
bool megamol::gui::ParameterGroups::ParameterGroupGUIStateToJSON(
nlohmann::json& inout_json, const std::string& module_fullname) {
for (auto& group_widget_id : group_widget_ids) {
if (group_widget_id.second.active) {
std::string param_fullname = module_fullname + "::parametergroup::" + group_widget_id.first;
group_widget_id.second.ParameterGUIStateToJSON(inout_json, param_fullname);
}
}
return false;
}
bool megamol::gui::ParameterGroups::ParameterGroupGUIStateFromJSONString(
const std::string& in_json_string, const std::string& module_fullname) {
for (auto& group_widget_id : group_widget_ids) {
std::string param_fullname = module_fullname + "::parametergroup::" + group_widget_id.first;
if (group_widget_id.second.ParameterGUIStateFromJSONString(in_json_string, param_fullname)) {
group_widget_id.second.active = true;
}
}
return false;
}
void megamol::gui::ParameterGroups::draw_parameter(megamol::gui::Parameter& inout_param,
const std::string& in_module_fullname, const std::string& in_search,
megamol::gui::ParameterPresentation::WidgetScope in_scope,
const std::shared_ptr<TransferFunctionEditor> in_external_tf_editor, bool* out_open_external_tf_editor) {
if ((inout_param.type == Param_t::TRANSFERFUNCTION) && (in_external_tf_editor != nullptr)) {
inout_param.present.ConnectExternalTransferFunctionEditor(in_external_tf_editor);
}
if (in_scope == ParameterPresentation::WidgetScope::GLOBAL) {
/// GLOBAL
inout_param.PresentGUI(in_scope);
} else {
/// LOCAL
auto param_name = inout_param.full_name;
bool param_searched = true;
if (in_scope == ParameterPresentation::WidgetScope::LOCAL) {
param_searched = megamol::gui::StringSearchWidget::FindCaseInsensitiveSubstring(param_name, in_search);
}
bool visible = (inout_param.present.IsGUIVisible() || inout_param.present.extended) && param_searched;
if (visible) {
if (inout_param.PresentGUI(in_scope)) {
// Open window calling the transfer function editor callback
if ((inout_param.type == Param_t::TRANSFERFUNCTION) && (in_external_tf_editor != nullptr)) {
if (out_open_external_tf_editor != nullptr) (*out_open_external_tf_editor) = true;
auto param_fullname = std::string(in_module_fullname.c_str()) + "::" + inout_param.full_name;
in_external_tf_editor->SetConnectedParameter(&inout_param, param_fullname);
}
}
}
}
}
void megamol::gui::ParameterGroups::draw_grouped_parameters(const std::string& in_group_name, ParamPtrVector_t& params,
const std::string& in_module_fullname, const std::string& in_search,
megamol::gui::ParameterPresentation::WidgetScope in_scope,
const std::shared_ptr<TransferFunctionEditor> in_external_tf_editor, bool* out_open_external_tf_editor) {
// Skip if no parameter is visible and extended mode is not set.
bool visible = false;
bool extended = false;
for (auto& param : params) {
visible = visible || param->present.IsGUIVisible();
extended = extended || param->present.extended;
}
if (!visible && !extended) return;
// Open namespace header when parameter search is active.
if (!in_search.empty()) {
auto headerId = ImGui::GetID(in_group_name.c_str());
ImGui::GetStateStorage()->SetInt(headerId, 1);
}
if (ImGui::CollapsingHeader(in_group_name.c_str(), ImGuiTreeNodeFlags_DefaultOpen)) {
ImGui::Indent();
for (auto& param : params) {
this->draw_parameter(
(*param), in_module_fullname, in_search, in_scope, in_external_tf_editor, out_open_external_tf_editor);
}
ImGui::Unindent();
}
}
bool megamol::gui::ParameterGroups::group_widget_animation(ParamPtrVector_t& params,
megamol::core::param::AbstractParamPresentation::Presentation presentation,
megamol::gui::ParameterPresentation::WidgetScope in_scope) {
if (presentation != param::AbstractParamPresentation::Presentation::Group_Animation) return false;
ImGuiStyle& style = ImGui::GetStyle();
const std::string group_label("Animation");
const ImVec2 button_size =
ImVec2(1.5f * ImGui::GetFrameHeightWithSpacing(), 1.5f * ImGui::GetFrameHeightWithSpacing());
const float knob_size = 2.5f * ImGui::GetFrameHeightWithSpacing();
if (in_scope == ParameterPresentation::WidgetScope::LOCAL) {
// LOCAL
ImGui::TextDisabled(group_label.c_str());
return true;
}
// Check required parameters
/// Find specific parameters of group by name because of parameter type can occure multiple times.
Parameter* param_play = nullptr;
Parameter* param_time = nullptr;
Parameter* param_speed = nullptr;
for (auto& param_ptr : params) {
if ((param_ptr->GetName() == "play") && (param_ptr->type == Param_t::BOOL)) {
param_play = param_ptr;
}
if ((param_ptr->GetName() == "time") && (param_ptr->type == Param_t::FLOAT)) {
param_time = param_ptr;
}
if ((param_ptr->GetName() == "speed") && (param_ptr->type == Param_t::FLOAT)) {
param_speed = param_ptr;
}
}
if ((param_play == nullptr) || (param_time == nullptr) || (param_speed == nullptr)) {
megamol::core::utility::log::Log::DefaultLog.WriteError(
"Unable to find all required parameters by name for animation group widget. [%s, %s, line %d]\n", __FILE__,
__FUNCTION__, __LINE__);
return false;
}
// Load button textures (once)
if (!this->image_buttons.play.IsLoaded()) {
this->image_buttons.play.LoadTextureFromFile("../share/resources/transport_ctrl_play.png");
}
if (!this->image_buttons.pause.IsLoaded()) {
this->image_buttons.pause.LoadTextureFromFile("../share/resources/transport_ctrl_pause.png");
}
if (!this->image_buttons.fastforward.IsLoaded()) {
this->image_buttons.fastforward.LoadTextureFromFile("../share/resources/transport_ctrl_fast-forward.png");
}
if (!this->image_buttons.fastrewind.IsLoaded()) {
this->image_buttons.fastrewind.LoadTextureFromFile("../share/resources/transport_ctrl_fast-rewind.png");
}
if ((!this->image_buttons.play.IsLoaded()) || (!this->image_buttons.pause.IsLoaded()) ||
(!this->image_buttons.fastforward.IsLoaded()) || (!this->image_buttons.fastrewind.IsLoaded())) {
megamol::core::utility::log::Log::DefaultLog.WriteError(
"Unable to load all required button textures for animation group widget. [%s, %s, line %d]\n", __FILE__,
__FUNCTION__, __LINE__);
return false;
}
// ------------------------------------------------------------------------
if (in_scope == ParameterPresentation::WidgetScope::GLOBAL) {
// GLOBAL
ImGui::Begin(group_label.c_str(), nullptr,
ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar |
ImGuiWindowFlags_NoCollapse);
} else { // if (in_scope == ParameterPresentation::WidgetScope::LOCAL) {
/// LOCAL
/*
float child_height = frame_height * 4.5f;
auto child_flags = ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDecoration;
ImGui::BeginChild("group_widget_animation", ImVec2(0.0f, child_height), true, child_flags);
// Caption
ImGui::TextUnformatted(group_label.c_str());
*/
}
// Transport Buttons ------------------------------------------------------
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, style.Colors[ImGuiCol_ButtonActive]);
ImGui::PushStyleColor(ImGuiCol_ButtonActive, style.Colors[ImGuiCol_ButtonHovered]);
bool play = std::get<bool>(param_play->GetValue());
float time = std::get<float>(param_time->GetValue());
float speed = std::get<float>(param_speed->GetValue());
std::string button_label;
ImTextureID button_tex;
/// PLAY - PAUSE
if (!play) {
if (this->image_buttons.play.Button("Play", button_size)) {
play = !play;
}
} else {
if (this->image_buttons.pause.Button("Pause", button_size)) {
play = !play;
}
}
ImGui::SameLine();
/// SLOWER
if (this->image_buttons.fastrewind.Button("Slower", button_size)) {
// play = true;
speed /= 1.5f;
}
this->tooltip.ToolTip(button_label, ImGui::GetItemID(), 1.0f, 5.0f);
ImGui::SameLine();
/// FASTER
if (this->image_buttons.fastforward.Button("Faster", button_size)) {
// play = true;
speed *= 1.5f;
}
ImGui::PopStyleColor(3);
// ImGui::SameLine();
ImVec2 cursor_pos = ImGui::GetCursorPos();
// Time -------------------------------------------------------------------
ImGui::BeginGroup();
std::string label("time");
float font_size = ImGui::CalcTextSize(label.c_str()).x;
ImGui::SetCursorPosX(cursor_pos.x + (knob_size - font_size) / 2.0f);
ImGui::TextUnformatted(label.c_str());
ParameterPresentation::KnobButton(
label, knob_size, time, param_time->GetMinValue<float>(), param_time->GetMaxValue<float>());
ImGui::Text(param_time->present.float_format.c_str(), time);
ImGui::EndGroup();
ImGui::SameLine();
// Speed -------------------------------------------------------------------
ImGui::BeginGroup();
label = "speed";
font_size = ImGui::CalcTextSize(label.c_str()).x;
ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (knob_size - font_size) / 2.0f);
ImGui::TextUnformatted(label.c_str());
ParameterPresentation::KnobButton(
label, knob_size, speed, param_speed->GetMinValue<float>(), param_speed->GetMaxValue<float>());
ImGui::Text(param_speed->present.float_format.c_str(), speed);
ImGui::EndGroup();
// ------------------------------------------------------------------------
param_play->SetValue(play);
param_time->SetValue(time);
param_speed->SetValue(speed);
if (in_scope == ParameterPresentation::WidgetScope::GLOBAL) {
/// GLOBAL
ImGui::End();
} else { // if (in_scope == ParameterPresentation::WidgetScope::LOCAL) {
/// LOCAL
/*
ImGui::EndChild();
*/
}
return true;
}
|
httpsgithu/dsentric
|
maps/src/main/scala/dsentric/filter/DFilterSyntax.scala
|
<gh_stars>1-10
package dsentric.filter
import com.github.ghik.silencer.silent
import dsentric.{DArray, DObject, Data, Path, PathLensOps}
import dsentric.codecs.{DCollectionCodec, DataCodec}
import dsentric.contracts.{DynamicProperty, ExpectedProperty, MaybeProperty, Property}
import dsentric.operators.Optionable
import scala.util.matching.Regex
sealed trait PropertyFilterOps[T] extends Any {
def prop: Property[_, T]
protected def nest(value: Any): DFilter =
new DFilter(PathLensOps.pathToMap(prop._path, value))
}
trait DFilterSyntax {
implicit def toValueFilterOps[T](prop: Property[_, T]): ValueFilterOps[T] =
new ValueFilterOps(prop)
implicit def toMaybeFilterOps[T](prop: MaybeProperty[_, T]): ExistsFilterOps[T] =
new ExistsFilterOps(prop)
implicit def toEmptyFilterOps[T](prop: DynamicProperty[_, T]): ExistsFilterOps[T] =
new ExistsFilterOps(prop)
implicit def toNumericFilterOps[T >: dsentric.operators.Numeric](prop: Property[_, T]): NumericFilterOps[T] =
new NumericFilterOps(prop)
implicit def toStringFilterOps[T >: Optionable[String]](prop: Property[_, T]): StringFilterOps[T] =
new StringFilterOps(prop)
implicit def toIterableFilterOps[R <: DObject, T, C[_] <: Iterable[_]](
prop: Property[R, C[T]]
): IterableFilterOps[R, T, C] =
new IterableFilterOps(prop)
implicit def toDArrayFilterOps[R <: DObject](prop: ExpectedProperty[R, DArray]): DArrayFilterOps[R] =
new DArrayFilterOps(prop)
}
final class IterableFilterOps[R <: DObject, T, C[_] <: Iterable[_]](val prop: Property[R, C[T]])
extends AnyVal
with PropertyFilterOps[C[T]] {
def $elemMatch(f: Property[R, T] => DFilter): DFilter = {
val codec = prop._codec.asInstanceOf[DCollectionCodec[C[T], T]].valueCodec
nest(Map("$elemMatch" -> f(DynamicProperty(codec, "", Path.empty, prop._root)).value))
}
}
final class DArrayFilterOps[R <: DObject](val prop: ExpectedProperty[R, DArray])
extends AnyVal
with PropertyFilterOps[DArray] {
def $elemMatch(f: Property[R, Data] => DFilter): DFilter =
nest(Map("$elemMatch" -> f(DynamicProperty(DataCodec, "", Path.empty, prop._root)).value))
}
final class ValueFilterOps[T](val prop: Property[_, T]) extends AnyVal with PropertyFilterOps[T] {
def $eq(value: T): DFilter =
if (prop._path.isEmpty)
new DFilter(Map("$eq" -> prop._codec(value)))
else
nest(prop._codec(value))
//Currently not supporting chaining of $ne in an && for the same field
def $ne(value: T): DFilter =
nest(Map("$ne" -> prop._codec(value)))
def $in(values: T*): DFilter =
nest(Map("$in" -> values.map(prop._codec(_)).toVector))
def $nin(values: T*): DFilter =
nest(Map("$nin" -> values.map(prop._codec(_)).toVector))
}
final class ExistsFilterOps[T](val prop: Property[_, T]) extends AnyVal with PropertyFilterOps[T] {
def $exists(value: Boolean): DFilter = nest(Map("$exists" -> value))
}
final class NumericFilterOps[T >: dsentric.operators.Numeric](val prop: Property[_, T])
extends AnyVal
with PropertyFilterOps[T] {
def $lt(value: Double): DFilter = nest(Map("$lt" -> value))
def $lt(value: Long): DFilter = nest(Map("$lt" -> value))
def $gt(value: Double): DFilter = nest(Map("$gt" -> value))
def $gt(value: Long): DFilter = nest(Map("$gt" -> value))
def $lte(value: Double): DFilter = nest(Map("$lte" -> value))
def $lte(value: Long): DFilter = nest(Map("$lte" -> value))
def $gte(value: Double): DFilter = nest(Map("$gte" -> value))
def $gte(value: Long): DFilter = nest(Map("$gte" -> value))
}
final class StringFilterOps[T >: Optionable[String]](val prop: Property[_, T])
extends AnyVal
with PropertyFilterOps[T] {
def $regex(value: String): DFilter = nest(Map("$regex" -> value))
@silent
def $regex(value: String, options: String): DFilter =
nest(Map("$regex" -> value, "$options" -> options))
def $regex(r: Regex): DFilter = nest(Map("$regex" -> r.regex))
def $like(value: String): DFilter = nest(Map("$like" -> value))
}
final class CaseInsensitiveFilterOps[T](val prop: Property[_, T]) extends PropertyFilterOps[T] {
def $eq(value: T): DFilter =
nest(Map("$regex" -> ("^" + DFilterOps.string2RegexEscapedString(value.toString) + "$"), "$options" -> "i"))
}
object DFilterSyntax extends DFilterSyntax
|
Mingyueyixi/xposed-rimet
|
app/src/main/java/com/sky/xposed/rimet/data/model/WifiModel.java
|
/*
* Copyright (c) 2020 The sky Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sky.xposed.rimet.data.model;
import java.io.Serializable;
import java.util.List;
/**
* Created by sky on 2020/3/25.
*/
public class WifiModel implements Serializable {
private String mName;
private boolean mEnabled;
private int mState;
private String mSsId;
private String mBssId;
private String mMacAddress;
private List<ScanResult> mScanResults;
public WifiModel(String name) {
mName = name;
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public boolean isEnabled() {
return mEnabled;
}
public void setEnabled(boolean enabled) {
mEnabled = enabled;
}
public int getState() {
return mState;
}
public void setState(int state) {
mState = state;
}
public String getSsId() {
return mSsId;
}
public void setSsId(String ssId) {
mSsId = ssId;
}
public String getBssId() {
return mBssId;
}
public void setBssId(String bssId) {
mBssId = bssId;
}
public String getMacAddress() {
return mMacAddress;
}
public void setMacAddress(String macAddress) {
mMacAddress = macAddress;
}
public List<ScanResult> getScanResults() {
return mScanResults;
}
public void setScanResults(List<ScanResult> scanResults) {
mScanResults = scanResults;
}
public static final class ScanResult implements Serializable {
private String mSsId;
private String mBssId;
public ScanResult() {
}
public ScanResult(String ssId, String bssId) {
mSsId = ssId;
mBssId = bssId;
}
public String getSsId() {
return mSsId;
}
public void setSsId(String ssId) {
mSsId = ssId;
}
public String getBssId() {
return mBssId;
}
public void setBssId(String bssId) {
mBssId = bssId;
}
}
public String getDesc() {
return "SSID: " + getSsId() + "\n" +
"BSSID: " + getBssId() + "\n" +
"MacAddress: " + getMacAddress();
}
}
|
arikfr/turbodbc
|
cpp/turbodbc/Library/src/descriptions/integer_description.cpp
|
<reponame>arikfr/turbodbc
#include <turbodbc/descriptions/integer_description.h>
#include <sqlext.h>
#include <boost/variant/get.hpp>
#include <cstring>
namespace turbodbc {
integer_description::integer_description() = default;
integer_description::integer_description(std::string name, bool supports_null) :
description(std::move(name), supports_null)
{
}
integer_description::~integer_description() = default;
std::size_t integer_description::do_element_size() const
{
return sizeof(int64_t);
}
SQLSMALLINT integer_description::do_column_c_type() const
{
return SQL_C_SBIGINT;
}
SQLSMALLINT integer_description::do_column_sql_type() const
{
return SQL_BIGINT;
}
SQLSMALLINT integer_description::do_digits() const
{
return 0;
}
type_code integer_description::do_get_type_code() const
{
return type_code::integer;
}
}
|
alicanli1995/PaytenPatikaBootcamp
|
Week4/CodingExercise/src/test/java/com/example/weekthree/example/actor/ActorControllerIntegrationTest.java
|
<gh_stars>1-10
package com.example.weekthree.example.actor;
import com.example.weekthree.controller.request.ActorCreateRequest;
import com.example.weekthree.controller.response.ActorCreateResponse;
import com.example.weekthree.dto.actor.ActorEntity;
import com.example.weekthree.dto.actor.ActorJpaDto;
import com.example.weekthree.example.BaseIntegrationTest;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.jdbc.Sql;
import java.time.LocalDateTime;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
class ActorControllerIntegrationTest extends BaseIntegrationTest {
@Autowired
ActorJpaDto actorJpaRepository;
@BeforeAll
static void beforeAll() {
}
@AfterAll
static void afterAll() {
}
@BeforeEach
void setUp() {
}
@AfterEach
void tearDown() {
}
@Test
@Sql(scripts = "/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
void should_create_actor() {
//given
ActorCreateRequest request = new ActorCreateRequest();
request.setActorName("test actor");
request.setBirthDate(LocalDateTime.of(1990, 1, 12, 13, 0, 0)); //yükselenini hesaplamayacaksak saate gerek yok
//when
ResponseEntity<ActorCreateResponse> response = testRestTemplate.postForEntity("/actor", request, ActorCreateResponse.class);
//then
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED);
assertThat(response.getBody()).isNotNull();
assertThat(response.getBody().getId()).isNotNull();
Optional<ActorEntity> actorEntity = actorJpaRepository.findById(response.getBody().getId());
assertThat(actorEntity).isPresent();
assertThat(actorEntity.get()).extracting("actorName", "birthDate")
.containsExactly("test actor", LocalDateTime.of(1990, 1, 12, 13, 0, 0));
}
}
|
liphx/cplusplus
|
thinking-in-cpp/code/2-6-algorithm5.cpp
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
template<typename T>
void print(vector<T>& data){
for(auto x: data){
cout << x << " ";
}
cout << endl;
}
int main()
{
//线性查找
vector<int> data { 1, 1, 2, -1, 5};
auto iter = find(data.begin(), data.end(), -1);
if(iter != data.end())
cout << *iter << endl;
//=>-1
iter = find_if(data.begin(), data.end(), [](int x){ return x > 2; });
if(iter != data.end())
cout << *iter << endl;
//=>5
iter = adjacent_find(data.begin(), data.end());
if(iter != data.end())
cout << *iter << endl;
//=>1
iter = adjacent_find(data.begin(), data.end(), [](int x, int y){ return x+y > 3; });
if(iter != data.end())
cout << *iter << endl;
//=>-1
vector<string> str1 { "eee", "bcd" };
vector<string> str2 { "bcd", "cde" };
auto iter2 = find_first_of(str1.begin(), str1.end(), str2.begin(), str2.end());
if(iter2 != str1.end())
cout << *iter2 << endl;
//=>bcd
iter2 = find_first_of(str1.begin(), str1.end(), str2.begin(), str2.end(),
[](string x, string y){ return x > y; });
if(iter2 != str1.end())
cout << *iter2 << endl;
//=>eee
//search find_end 查找序列2是否在序列1中出现
iter2 = search(str1.begin(), str1.end(), str2.begin(), str2.begin());
if(iter2 != str1.end())
cout << *iter2 << endl;
//=>eee
iter2 = search(str1.begin(), str1.end(), str2.begin(), str2.begin()+1);
if(iter2 != str1.end())
cout << *iter2 << endl;
//=>bcd
iter2 = search(str1.begin(), str1.end(), str2.begin(), str2.end());
if(iter2 != str1.end())
cout << *iter2 << endl;
//null
iter2 = find_end(str1.begin(), str1.end(), str2.begin(), str2.begin()+1);
if(iter2 != str1.end())
cout << *iter2 << endl;
//=>bcd
vector<bool> b{ 0, 1, 1, 0, 0, 0};
auto iter3 = search_n(b.begin(), b.end(), 2, true);
if(iter3 != b.end())
cout << *iter3 << endl;//=>1
iter3 = search_n(b.begin(), b.end(), 3, false);
if(iter3 != b.end())
cout << *iter3 << endl;//=>0
string s("defabc");
auto iter4 = min_element(s.begin(), s.end());
cout << *iter4 << endl;//=>a
iter4 = max_element(s.begin(), s.end());
cout << *iter4 << endl;//=>f
return 0;
}
|
mrexox/evil-client
|
spec/features/operation/middleware_spec.rb
|
RSpec.describe "operation request" do
before do
# Adds header tag to request/response
class Test::Middleware
extend Dry::Initializer
param :app
def call(env)
env["HTTP_Variables"].update tags
status, headers, body = app.call(env)
[status, headers.merge(tags), body]
end
end
class Foo < Test::Middleware
def tags; { "Tag" => "Foo" }; end
end
class Bar < Test::Middleware
def tags; { "Tag" => "Bar" }; end
end
load "spec/fixtures/test_client.rb"
class Test::Client < Evil::Client
middleware { Foo }
scope :crm do
middleware { Bar }
end
end
stub_request(:any, //).to_return(status: 200, body: [], headers: {})
end
subject do
Test::Client.new(subdomain: "europe", user: "andy", password: "<PASSWORD>")
.crm(version: 4)
.users
.fetch(id: 1)
end
it "applies middleware in a proper order" do
expected_request = \
a_request(:get, "https://europe.example.com/crm/v4/users/1")
.with headers: { "Tag" => "Bar" }
expect(subject).to eq [200, { "Tag" => "Foo" }, []]
expect(expected_request).to have_been_made
end
end
|
DipsyCyber/nOG
|
commands/economy/set-bal.js
|
const economy = require("../../util/economy")
module.exports = {
commands: ['set-bal', 'setbal'],
description: 'Bot Admin only command that sets a user\'s balance in a guild',
ownerOnly: true,
minArgs: 1,
maxArgs: 2,
expectedArgs: '[user] <value>',
category: 'Economy',
guildOnly: true,
run: async ({ message, args }) => {
let target = message.mentions.users.first()
let noTarget = false
if (!target) {
noTarget = true
target = message.author
}
const coins = noTarget ? args[0] : args[1]
if (isNaN(coins)) return message.reply('Please provide a valid number of coins.')
await economy.setCoins(message.guild.id, target.id, coins)
return message.reply(`Set ${target}'s balance to ${coins}`)
}
}
|
moonwave99/playa-old
|
src/renderer/util/Player.js
|
import { EventEmitter } from 'events';
import Promise from 'bluebird';
import { encodePath } from '../util/helpers/url';
export default class Player extends EventEmitter {
constructor({
mediaFileLoader,
resolution = 1000,
scrobbleThreshold,
audioElement,
}) {
super();
this.mediaFileLoader = mediaFileLoader;
this.resolution = resolution;
this.scrobbleThreshold = scrobbleThreshold;
this.timer = null;
this.loading = false;
this.playing = false;
this.alreadyScrobbled = false;
this.currentPlaylist = null;
this.currentAlbum = null;
this.currentTrack = null;
this.lastPlayedTrack = null;
this.lastAction = null;
this.playbackDirection = 0;
this.currentTrackPlayedAmount = 0;
this.player = audioElement;
this.player.onplaying = this.onPlaying.bind(this);
this.player.onpause = this.onPause.bind(this);
this.player.onended = this.onEnded.bind(this);
}
startTimer() {
if (this.timer) {
return;
}
this.timer = setInterval(() => {
this.checkScrobble();
this.emit('playerTick');
}, this.resolution);
}
clearTimer() {
if (this.timer) {
clearInterval(this.timer);
}
this.currentTrackPlayedAmount = 0;
this.alreadyScrobbled = false;
this.timer = null;
}
checkScrobble() {
if (!this.currentTrack || this.alreadyScrobbled) {
return;
}
const amount = this.currentTrackPlayedAmount += (this.resolution * 0.001);
const absoluteScrobbled = amount > this.scrobbleThreshold.absolute;
const relativeScrobbled = amount / this.currentTrack.duration > this.scrobbleThreshold.percent;
if (absoluteScrobbled || relativeScrobbled) {
this.emit('scrobbleTrack', this.currentTrack, this.currentTrackPlayedAmount);
this.alreadyScrobbled = true;
}
}
onPause() {
this.playing = false;
this.clearTimer();
this.emit('nowplaying');
}
onPlaying() {
if (!this.timer) {
this.startTimer();
}
this.playing = true;
this.emit('nowplaying');
}
onEnded() {
this.nextTrack();
}
playbackInfo() {
return {
position: this.player.currentTime,
playing: this.playing,
currentTrack: this.currentTrack,
currentAlbum: this.currentAlbum,
};
}
play() {
this.player.play();
}
pause() {
this.player.pause();
}
nextTrack() {
this.lastAction = 'next';
const nextTrack = this.currentAlbum.findNextById(this.currentTrack.id);
if (!nextTrack) {
return this.nextAlbum().then(() => {
this.gotoTrack(this.currentAlbum.tracks[0].id);
});
}
this.gotoTrack(nextTrack.id);
return true;
}
prevTrack() {
this.lastAction = 'prev';
const prevTrack = this.currentAlbum.findPrevById(this.currentTrack.id);
if (!prevTrack) {
return this.prevAlbum().then(() => {
this.gotoTrack(this.currentAlbum.tracks[0].id);
});
}
this.gotoTrack(prevTrack.id);
return true;
}
gotoTrack(id = this.currentAlbum.tracks[0].id) {
const currentTrack = this.currentAlbum.findById(id);
if (!currentTrack) {
return;
}
this.currentTrack = currentTrack;
this.player.src = encodePath(this.currentTrack.filename);
this.play();
this.emit('trackChange');
}
seek(to) {
this.player.currentTime = this.player.duration * to;
}
nextAlbum() {
const nextAlbum = this.currentPlaylist.getNext(this.currentAlbum);
if (!nextAlbum) {
return false;
}
return this.loadAlbum(nextAlbum);
}
prevAlbum() {
const prevAlbum = this.currentPlaylist.getPrevious(this.currentAlbum);
if (!prevAlbum) {
return false;
}
return this.loadAlbum(prevAlbum);
}
loadAlbum(album) {
const isNewAlbum = !this.currentAlbum || (this.currentAlbum.id !== album.id);
if (!isNewAlbum) {
this.emit('trackChange');
return Promise.resolve(this.currentAlbum);
}
this.currentAlbum = album;
this.clearTimer();
this.emit('trackChange');
return Promise.resolve(album);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.