repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
lfaoro/goa
|
codegen/funcs_test.go
|
package codegen
import (
"testing"
)
func TestWrapText(t *testing.T) {
cases := map[string]struct {
maxChars int
str string
expected string
}{
"long_text": {
maxChars: 50,
str: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
expected: "Lorem ipsum dolor sit amet, consectetur\n" +
"adipiscing elit, sed do eiusmod tempor incididunt\n" +
"ut labore et dolore magna aliqua. Ut enim ad\n" +
"minim veniam, quis nostrud exercitation ullamco\n" +
"laboris nisi ut aliquip ex ea commodo consequat.",
},
"long_text_with_newlines": {
maxChars: 50,
str: "Lorem ipsum dolor sit amet,\n" +
"consectetur adipiscing elit,\n" +
"sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\n" +
"Ut enim ad minim veniam,\n" +
"quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
expected: "Lorem ipsum dolor sit amet,\n" +
"consectetur adipiscing elit,\n" +
"sed do eiusmod tempor incididunt ut labore et\n" +
"dolore magna aliqua.\n" +
"Ut enim ad minim veniam,\n" +
"quis nostrud exercitation ullamco laboris nisi ut\n" +
"aliquip ex ea commodo consequat.",
},
"respect_empty_lines": {
maxChars: 50,
str: "Lorem ipsum dolor sit amet,\n" +
"\n" +
"sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
expected: "Lorem ipsum dolor sit amet,\n" +
"\n" +
"sed do eiusmod tempor incididunt ut labore et\n" +
"dolore magna aliqua.",
},
"too_long_word_to_wrap_intact": {
maxChars: 15,
str: "Who said supercalifragilisticexpialidocious in a movie",
expected: "Who said\n" +
"supercalifragilisticexpialidocious\n" +
"in a movie",
},
"empty": {
maxChars: 50,
str: "",
expected: "",
},
}
for k, tc := range cases {
actual := WrapText(tc.str, tc.maxChars)
if actual != tc.expected {
t.Errorf("%s: got `%s`, expected `%s`", k, actual, tc.expected)
}
}
}
|
pin062788/spring-cloud
|
example-gateway/src/main/java/com/cloud/example/gateway/utils/NacosConfigUtil.java
|
/*
* Copyright 2019 https://github.com/romeoblog/spring-cloud.git Group.
*
* 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.cloud.example.gateway.utils;
/**
* The type Nacos Config Utils
*
* @author Benji
* @date 2019-05-30
*/
public final class NacosConfigUtil {
/**
* Nacos remoteAddress
*/
public static final String REMOTE_ADDRESS = "localhost";
/**
* Nacos Group ID
*/
public static final String GROUP_ID = "SENTINEL_GROUP";
/**
* Nacos Data ID
*/
public static final String FLOW_DATA_ID_POSTFIX = "-flow-rules";
public static final String DEGRADE_DATA_ID_POSTFIX = "-degrade-rules";
public static final String SYSTEM_DATA_ID_POSTFIX = "-system-rules";
public static final String PARAM_FLOW_DATA_ID_POSTFIX = "-param-rules";
public static final String CLUSTER_MAP_DATA_ID_POSTFIX = "-cluster-map";
/**
* cc for `cluster-client`
*/
public static final String CLIENT_CONFIG_DATA_ID_POSTFIX = "-cc-config";
/**
* cs for `cluster-server`
*/
public static final String SERVER_TRANSPORT_CONFIG_DATA_ID_POSTFIX = "-cs-transport-config";
public static final String SERVER_FLOW_CONFIG_DATA_ID_POSTFIX = "-cs-flow-config";
public static final String SERVER_NAMESPACE_SET_DATA_ID_POSTFIX = "-cs-namespace-set";
private NacosConfigUtil() {
}
}
|
h-2/SeqAnHTS
|
include/seqan/basic/alphabet_storage.h
|
<reponame>h-2/SeqAnHTS
// ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2015, <NAME>, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Knut Reinert or the FU Berlin nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN 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.
//
// ==========================================================================
// Author: <NAME> <<EMAIL>>
// Author: <NAME> <<EMAIL>>
// ==========================================================================
// Storage-related alphabet interface part. This means both
// construction type (simple, non-simple) and storage size.
// ==========================================================================
#ifndef SEQAN_INCLUDE_SEQAN_BASIC_ALPHABET_STORAGE_H_
#define SEQAN_INCLUDE_SEQAN_BASIC_ALPHABET_STORAGE_H_
#include <float.h>
namespace seqan {
// ============================================================================
// Forwards
// ============================================================================
template <typename TValue, typename TSpec>
class SimpleType;
// ============================================================================
// Tags, Classes, Enums
// ============================================================================
// ============================================================================
// Metafunctions
// ============================================================================
// ----------------------------------------------------------------------------
// Metafunction BitsPerValue
// ----------------------------------------------------------------------------
template <typename TValue>
struct BitsPerValue
{
static const unsigned VALUE = sizeof(TValue) * 8;
typedef unsigned Type;
};
template <typename TValue>
struct BitsPerValue<TValue const> : public BitsPerValue<TValue>
{};
// template <typename TValue>
// const unsigned BitsPerValue<TValue>::VALUE = ;
// ----------------------------------------------------------------------------
// Metafunction ValueSize
// ----------------------------------------------------------------------------
// TODO(holtgrew): Enable default implementation only for integers? Move to adapt builtins?
template <typename T>
struct ValueSize
{
typedef __uint64 Type;
static const Type VALUE = (BitsPerValue<T>::VALUE < 64)? 1ull << (BitsPerValue<T>::VALUE & 63) : 0ull;
};
template <typename T>
struct ValueSize<T const> : ValueSize<T>
{};
// TODO(holtgrew): Use static assertion to make sure that ValueSize is never called on floating point numbers? Include assertion for __int64 and __uint64?
template <>
struct ValueSize<__int64>
{
typedef __uint64 Type;
static const Type VALUE = 0;
};
template <>
struct ValueSize<__uint64>
{
typedef __uint64 Type;
static const Type VALUE = 0;
};
template <>
struct ValueSize<double>
{
typedef __uint64 Type;
static const Type VALUE = 0;
};
template <>
struct ValueSize<float>
{
typedef __uint64 Type;
static const Type VALUE = 0;
};
// The internal value size is used for alphabets with piggyback qualities,
// for example Dna5Q. Here, the public value size is 5 but the internal
// value size is 256.
template <typename TValue>
struct InternalValueSize_
: public ValueSize<TValue>
{};
// ----------------------------------------------------------------------------
// Metafunction BytesPerValue
// ----------------------------------------------------------------------------
/*!
* @mfn BytesPerValue
* @headerfile <seqan/basic.h>
* @brief Number of bytes needed to store a value.
*
* @signature BytesPerValue<T>::VALUE
*
* @tparam T The type to query.
*
* @return VALUE The number of bytes to store on T object.
*
* By default, this function returns <tt>ceil(BitsPerValue<T>::VALUE)</tt>. For built-in types, this is the same
* as <tt>sizeof(T)</tt>.
*
* @see FiniteOrderedAlphabetConcept#ValueSize
* @see AlphabetConcept#BitsPerValue
* @see IntegralForValue
*/
template <typename TValue>
struct BytesPerValue
{
enum { VALUE = (BitsPerValue<TValue>::VALUE + 7) / 8 };
};
// ----------------------------------------------------------------------------
// Metafunction IntegralForValue
// ----------------------------------------------------------------------------
/*!
* @mfn IntegralForValue
* @headerfile <seqan/basic.h>
* @brief Returns an itegral type that provides sufficient space to store a value.
*
* @signature IntegralForValue<T>::Type;
*
* @tparam T The type to query.
*
* @return Type An integral type.
*
* The type is the smallest unsigned integral type that has a size of at least BytesPerValue bytes.
*
* <table>
* <tr>
* <th>sizeof(T) in bytes</th>
* <th>integral types</th>
* </tr>
* <tr>
* <td>1</td>
* <td><tt>unsigned char</tt></td>
* </tr>
* <tr>
* <td>2</td>
* <td><tt>unsigned short</tt></td>
* </tr>
* <tr>
* <td>3</td>
* <td><tt>unsigned int</tt></td>
* </tr>
* <tr>
* <td>4</td>
* <td><tt>unsigned int</tt></td>
* </tr>
* <tr>
* <td>> 4</td>
* <td><tt>__int64</tt></td>
* </tr>
* </table>
*
* Note that the returned integral type cannot store <tt>T</tt> values, if <tt>T</tt> takes more than 8 bytes, since
* there exists no integral type that provides sufficient space to store types of this size.
*
* @see FiniteOrderedAlphabetConcept#ValueSize
* @see AlphabetConcept#BitsPerValue
* @see BytesPerValue
*/
template <int SIZE>
struct IntegralForValueImpl_
{
typedef __int64 Type;
};
// TODO(holtgrew): Switch to __uint8, __uint16, __uint32?
template <>
struct IntegralForValueImpl_<1>
{
typedef unsigned char Type;
};
template <>
struct IntegralForValueImpl_<2>
{
typedef unsigned short Type;
};
template <>
struct IntegralForValueImpl_<3>
{
typedef unsigned int Type;
};
template <>
struct IntegralForValueImpl_<4>
{
typedef unsigned int Type;
};
template <typename TValue>
struct IntegralForValue : IntegralForValueImpl_<BytesPerValue<TValue>::VALUE>
{};
// ============================================================================
// Functions
// ============================================================================
// ----------------------------------------------------------------------------
// Function ordValue()
// ----------------------------------------------------------------------------
// TODO(holtgrew): Enable only for integers, move to adapt builtins?
template <typename TValue>
SEQAN_HOST_DEVICE inline typename ValueSize<TValue>::Type
ordValue(TValue const & c)
{
return convert<unsigned>(static_cast<typename MakeUnsigned_<TValue>::Type const &>(c));
}
// The internal ord value is used for alphabets with piggyback qualities.
template <typename TValue>
SEQAN_HOST_DEVICE inline typename ValueSize<TValue>::Type
_internalOrdValue(TValue const & c)
{
return ordValue(c);
}
// ----------------------------------------------------------------------------
// Function valueSize<T>()
// ----------------------------------------------------------------------------
template <typename T>
SEQAN_HOST_DEVICE inline typename ValueSize<T>::Type
valueSize()
{
return +ValueSize<T>::VALUE;
}
} // namespace seqan
#endif // #ifndef SEQAN_INCLUDE_SEQAN_BASIC_ALPHABET_STORAGE_H_
|
originalix/HTML-CSS-Prictice
|
react/extremely-simple-flux-demo/dispatcher/AppDispatcher.js
|
var Dispatcher = require('flux').Dispatcher;
var AppDispatcher = new Dispatcher();
var ListStore = require('../stores/ListStore');
AppDispatcher.register(function (action) {
switch(action.actionType) {
case 'ADD_NEW_ITEM':
ListStore.addNewItemHandler(action.text);
ListStore.emitChange();
console.log('ADD_NEW_ITEM');
break;
default:
// pass
}
});
module.exports = AppDispatcher;
|
wallisyan/alibabacloud-python-sdk-v2
|
alibabacloud/clients/batchcompute_20150630.py
|
<reponame>wallisyan/alibabacloud-python-sdk-v2
# Copyright 2019 Alibaba Cloud Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from alibabacloud.client import AlibabaCloudClient
from alibabacloud.request import APIRequest
from alibabacloud.utils.parameter_validation import verify_params
class BatchComputeClient(AlibabaCloudClient):
def __init__(self, client_config, credentials_provider=None, retry_policy=None,
endpoint_resolver=None):
AlibabaCloudClient.__init__(self, client_config,
credentials_provider=credentials_provider,
retry_policy=retry_policy,
endpoint_resolver=endpoint_resolver)
self.product_code = 'BatchCompute'
self.api_version = '2015-06-30'
self.location_service_code = None
self.location_endpoint_type = 'openAPI'
def modify_job(self, resource_owner_id=None, resource_name=None):
api_request = APIRequest('ModifyJob', 'PUT', 'http', 'ROA', 'query')
api_request.uri_pattern = '/jobs/[ResourceName]'
api_request._params = {"ResourceOwnerId": resource_owner_id, "ResourceName": resource_name}
return self._handle_request(api_request).result
def release_job(self, resource_owner_id=None, resource_name=None):
api_request = APIRequest('ReleaseJob', 'DELETE', 'http', 'ROA', 'query')
api_request.uri_pattern = '/2013-01-11/jobs/[ResourceName]'
api_request._params = {"ResourceOwnerId": resource_owner_id, "ResourceName": resource_name}
return self._handle_request(api_request).result
def put_job(self, resource_owner_id=None, resource_name=None):
api_request = APIRequest('PutJob', 'PUT', 'http', 'ROA', 'query')
api_request.uri_pattern = '/jobs/[ResourceName]/Priority'
api_request._params = {"ResourceOwnerId": resource_owner_id, "ResourceName": resource_name}
return self._handle_request(api_request).result
def post_job(self, resource_owner_id=None):
api_request = APIRequest('PostJob', 'POST', 'http', 'ROA', 'query')
api_request.uri_pattern = '/jobs'
api_request._params = {"ResourceOwnerId": resource_owner_id}
return self._handle_request(api_request).result
def list_snapshots(self, resource_owner_id=None):
api_request = APIRequest('ListSnapshots', 'GET', 'http', 'ROA', 'query')
api_request.uri_pattern = '/snapshots'
api_request._params = {"ResourceOwnerId": resource_owner_id}
return self._handle_request(api_request).result
def list_jobs(self, resource_owner_id=None):
api_request = APIRequest('ListJobs', 'GET', 'http', 'ROA', 'query')
api_request.uri_pattern = '/jobs'
api_request._params = {"ResourceOwnerId": resource_owner_id}
return self._handle_request(api_request).result
def list_images(self, resource_owner_id=None):
api_request = APIRequest('ListImages', 'GET', 'http', 'ROA', 'query')
api_request.uri_pattern = '/images'
api_request._params = {"ResourceOwnerId": resource_owner_id}
return self._handle_request(api_request).result
def get_tasks(self, resource_owner_id=None, resource_name=None):
api_request = APIRequest('GetTasks', 'GET', 'http', 'ROA', 'query')
api_request.uri_pattern = '/jobs/[ResourceName]/tasks'
api_request._params = {"ResourceOwnerId": resource_owner_id, "ResourceName": resource_name}
return self._handle_request(api_request).result
def get_job_description(self, resource_owner_id=None, resource_name=None):
api_request = APIRequest('GetJobDescription', 'GET', 'http', 'ROA', 'query')
api_request.uri_pattern = '/jobs/[ResourceName]/description'
api_request._params = {"ResourceOwnerId": resource_owner_id, "ResourceName": resource_name}
return self._handle_request(api_request).result
def get_job(self, resource_owner_id=None, resource_name=None):
api_request = APIRequest('GetJob', 'GET', 'http', 'ROA', 'query')
api_request.uri_pattern = '/jobs/[ResourceName]'
api_request._params = {"ResourceOwnerId": resource_owner_id, "ResourceName": resource_name}
return self._handle_request(api_request).result
def delete_job(self, resource_owner_id=None, resource_name=None):
api_request = APIRequest('DeleteJob', 'DELETE', 'http', 'ROA', 'query')
api_request.uri_pattern = '/jobs/[ResourceName]'
api_request._params = {"ResourceOwnerId": resource_owner_id, "ResourceName": resource_name}
return self._handle_request(api_request).result
|
huahuajjh/requisition_land
|
src/com/tq/requisition/domain/model/account/IAccountRepository.java
|
<filename>src/com/tq/requisition/domain/model/account/IAccountRepository.java
package com.tq.requisition.domain.model.account;
import java.util.UUID;
import com.tq.requisition.domain.IRepository.IRepository;
import com.tq.requisition.domain.model.share.AccountState;
import com.tq.requisition.exception.AccountOperationException;
import com.tq.requisition.exception.DomainException;
import com.tq.requisition.infrastructure.utils.PageFormater;
/**
* 表示账户的聚合根仓储接口
* @author jjh
* @time 2015-12-20 23:26
*
* 增加一个检查用户账号是否存在的接口
* @author Bless
* @time 2016/3/3 9:51
*/
public interface IAccountRepository extends IRepository<Account>{
/**
* 登陆账户检测
* @param account
* 账户名
* @param pwd
* 账户密码
* @return boolean
* 返回一个boolean值,表明给定的用户名和密码是否存在对应的账户
*/
boolean login(String account,String pwd);
/**
* 登陆账户检测
* @param account
* 账户名
* @param pwd
* 账户密码
* @return Account
*/
Account login4session(String account,String pwd);
/**
* 根据id获取用户实体
* @param id
* 用户id
* @return
*/
Account getById(UUID id);
/**
* 创建新账户
* @param account
* 账户实例
* @return TODO
*/
Account createAccount(Account account) throws AccountOperationException;
/**
* 创建账户
* @param account
* 账户名
* @param pwd
* 密码
* @param state
* 账户状态
* @param name
* 姓名
*/
public void createAccount(String account,String pwd,AccountState state,String... name);
/**
* 修改密码
* @param id
* 账户id
* @param oldPwd
* 旧密码
* @param newPwd
* 新密码
*/
public void changePwd(UUID id,String oldPwd,String newPwd) throws DomainException;
/**
* 禁用账户
* @param id
* 账户id
*/
public void disableAccount(UUID id);
/**
* 更新账户信息
* @param account
* 待更新的账户
*/
public void updateAccount(Account account) throws AccountOperationException ;
/**
* 锁账户
* @param id
* 账户id
*/
public void lockAccount(UUID id);
/**
* 启用账户
* @param id
* 账户id
*/
public void enableAccount(UUID id);
/**
* 根据用户id检测是否存在该用户
* @param id
* 用户id
* @return boolean
* 如果存在该用户返回true,否则返回false
*/
public boolean existsById(UUID id);
/**
* 解除被删除部门及组织
* @param orgid
* 被删除组织id
*/
public void updateOrg(UUID orgid);
/**
* 更新账户仓储中被删除的所有部门id为null
* @param deptid
* 被删除的部门id
*/
public void updateDept(UUID deptid);
/**
* 指定角色被删除时,更新所有账号仓储的角色信息
* @param rid
* 被删除的角色id
*/
public void updateRole(UUID rid);
/**
* 分页获取账户列表
* @param userName
* 用户名
* @param name
* 姓名
* @param orgId
* 单位id
* @param deptId
* 部门id
* @param pageIndex
* 起始页
* @param pageNum
* 页码
* @return List<Account>
* 账户集合
*/
PageFormater queryByPage(String userName, String name, UUID orgId, UUID deptId, int pageIndex, int pageNum);
/**
* 根据用户账号检测是否存在该用户
* @param account
* 用户账号
* @return boolean
* 如果存在该用户返回true,否则返回false
*/
public boolean existsByAccount(String account);
}
|
dkaip/jvulkan
|
src/main/java/com/CIMthetics/jvulkan/VulkanCore/Structures/CreateInfos/VkPipelineColorBlendStateCreateInfo.java
|
<gh_stars>0
/*
* Copyright 2019-2020 <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.
*/
package com.CIMthetics.jvulkan.VulkanCore.Structures.CreateInfos;
import java.util.Collection;
import java.util.EnumSet;
import com.CIMthetics.jvulkan.VulkanCore.Enums.VkLogicOp;
import com.CIMthetics.jvulkan.VulkanCore.Enums.VkPipelineColorBlendStateCreateFlagBits;
import com.CIMthetics.jvulkan.VulkanCore.Enums.VkStructureType;
import com.CIMthetics.jvulkan.VulkanCore.Structures.VkPipelineColorBlendAttachmentState;
/**
*
<ul>
<li>
<code>pNext</code> is NULL or a pointer to an extension-specific structure.
</li>
<li>
<code>flags</code> is reserved for future use.
</li>
<li>
<code>logicOpEnable</code> controls whether to apply Logical Operations.
</li>
<li>
<code>logicOp</code> selects which logical operation to apply.
</li>
<li>
<code>attachmentCount</code> is the number of VkPipelineColorBlendAttachmentState elements in pAttachments. This value must equal the colorAttachmentCount for the subpass in which this pipeline is used.
</li>
<li>
<code>attachments</code> is a pointer to array of per target attachment states.
</li>
<li>
<code>blendConstants</code> is an array of four values used as the R, G, B, and A components of the blend constant that are used in blending, depending on the blend factor.
</li>
</ul>
* @author <NAME>
*
*/
public class VkPipelineColorBlendStateCreateInfo extends VulkanCreateInfoStructure
{
private EnumSet<VkPipelineColorBlendStateCreateFlagBits> flags = EnumSet.noneOf(VkPipelineColorBlendStateCreateFlagBits.class);
private boolean logicOpEnable;
private VkLogicOp logicOp;
private Collection<VkPipelineColorBlendAttachmentState> attachments;
private float[] blendConstants = new float[4];
public VkPipelineColorBlendStateCreateInfo()
{
super(VkStructureType.VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO);
}
public EnumSet<VkPipelineColorBlendStateCreateFlagBits> getFlags()
{
return flags;
}
public void setFlags(EnumSet<VkPipelineColorBlendStateCreateFlagBits> flags)
{
this.flags = flags;
}
public boolean isLogicOpEnable()
{
return logicOpEnable;
}
public void setLogicOpEnable(boolean logicOpEnable)
{
this.logicOpEnable = logicOpEnable;
}
public VkLogicOp getLogicOp()
{
return logicOp;
}
public void setLogicOp(VkLogicOp logicOp)
{
this.logicOp = logicOp;
}
public Collection<VkPipelineColorBlendAttachmentState> getAttachments()
{
return attachments;
}
public void setAttachments(
Collection<VkPipelineColorBlendAttachmentState> attachments)
{
this.attachments = attachments;
}
public float[] getBlendConstants()
{
return blendConstants;
}
public void setRedBlendConstant(float blendConstant)
{
blendConstants[0] = blendConstant;
}
public void setGreenBlendConstant(float blendConstant)
{
blendConstants[1] = blendConstant;
}
public void setBlueBlendConstant(float blendConstant)
{
blendConstants[2] = blendConstant;
}
public void setAlphaBlendConstant(float blendConstant)
{
blendConstants[3] = blendConstant;
}
}
|
stackfoundation/cli
|
core/pkg/hypervisor/detect_virtualbox_other.go
|
// +build !windows
package hypervisor
import "os/exec"
func DetectVBoxManageCmd() (string, bool) {
cmd := "VBoxManage"
if path, err := exec.LookPath(cmd); err == nil {
return path, true
}
return cmd, false
}
|
warmchang/turms
|
turms-server-common/src/main/java/im/turms/server/common/access/client/dto/constant/GroupMemberRole.java
|
<reponame>warmchang/turms
/*
* Copyright (C) 2019 The Turms Project
* https://github.com/turms-im/turms
*
* 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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: constant/group_member_role.proto
package im.turms.server.common.access.client.dto.constant;
/**
* Protobuf enum {@code im.turms.proto.GroupMemberRole}
*/
public enum GroupMemberRole
implements com.google.protobuf.ProtocolMessageEnum {
/**
* <code>OWNER = 0;</code>
*/
OWNER(0),
/**
* <code>MANAGER = 1;</code>
*/
MANAGER(1),
/**
* <code>MEMBER = 2;</code>
*/
MEMBER(2),
/**
* <code>GUEST = 3;</code>
*/
GUEST(3),
/**
* <code>ANONYMOUS_GUEST = 4;</code>
*/
ANONYMOUS_GUEST(4),
UNRECOGNIZED(-1),
;
/**
* <code>OWNER = 0;</code>
*/
public static final int OWNER_VALUE = 0;
/**
* <code>MANAGER = 1;</code>
*/
public static final int MANAGER_VALUE = 1;
/**
* <code>MEMBER = 2;</code>
*/
public static final int MEMBER_VALUE = 2;
/**
* <code>GUEST = 3;</code>
*/
public static final int GUEST_VALUE = 3;
/**
* <code>ANONYMOUS_GUEST = 4;</code>
*/
public static final int ANONYMOUS_GUEST_VALUE = 4;
public final int getNumber() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalArgumentException(
"Can't get the number of an unknown enum value.");
}
return value;
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static GroupMemberRole valueOf(int value) {
return forNumber(value);
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
*/
public static GroupMemberRole forNumber(int value) {
switch (value) {
case 0: return OWNER;
case 1: return MANAGER;
case 2: return MEMBER;
case 3: return GUEST;
case 4: return ANONYMOUS_GUEST;
default: return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<GroupMemberRole>
internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<
GroupMemberRole> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<GroupMemberRole>() {
public GroupMemberRole findValueByNumber(int number) {
return GroupMemberRole.forNumber(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor
getValueDescriptor() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalStateException(
"Can't get the descriptor of an unrecognized enum value.");
}
return getDescriptor().getValues().get(ordinal());
}
public final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptorForType() {
return getDescriptor();
}
public static final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptor() {
return im.turms.server.common.access.client.dto.constant.GroupMemberRoleOuterClass.getDescriptor().getEnumTypes().get(0);
}
private static final GroupMemberRole[] VALUES = values();
public static GroupMemberRole valueOf(
com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
if (desc.getType() != getDescriptor()) {
throw new java.lang.IllegalArgumentException(
"EnumValueDescriptor is not for this type.");
}
if (desc.getIndex() == -1) {
return UNRECOGNIZED;
}
return VALUES[desc.getIndex()];
}
private final int value;
private GroupMemberRole(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:im.turms.proto.GroupMemberRole)
}
|
lectureStudio/avdev
|
avdev-jni/src/main/cpp/dependencies/macos/coreaudio/src/CoreAudioOutputStream.cpp
|
/*
* Copyright 2016 <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.
*/
#include "CoreAudioOutputStream.h"
#include "Log.h"
namespace avdev
{
CoreAudioOutputStream::CoreAudioOutputStream(AudioDeviceID devID, PAudioSink sink) :
CoreAudioStream(devID, kAudioDevicePropertyScopeInput),
AudioOutputStream(sink)
{
}
float CoreAudioOutputStream::getVolume()
{
if (getState() == StreamState::CLOSED) {
return AudioOutputStream::getVolume();
}
return CoreAudioStream::getVolume();
}
void CoreAudioOutputStream::setVolume(float volume)
{
AudioOutputStream::setVolume(volume);
if (getState() != StreamState::CLOSED) {
CoreAudioStream::setVolume(volume);
}
}
bool CoreAudioOutputStream::getMute()
{
if (getState() == StreamState::CLOSED) {
return AudioOutputStream::getMute();
}
return CoreAudioStream::getMute();
}
void CoreAudioOutputStream::setMute(bool mute)
{
AudioOutputStream::setMute(mute);
if (getState() != StreamState::CLOSED) {
CoreAudioStream::setMute(mute);
}
}
void CoreAudioOutputStream::openInternal()
{
float volume = AudioOutputStream::getVolume();
unsigned latency = AudioOutputStream::getBufferLatency();
AudioFormat format = AudioOutputStream::getAudioFormat();
CoreAudioStream::open(CoreaAudioType::CoreAudioOutput, format, latency);
//CoreAudioStream::setVolume(volume);
}
void CoreAudioOutputStream::closeInternal()
{
CoreAudioStream::close();
freeAudioBuffer();
}
void CoreAudioOutputStream::startInternal()
{
CoreAudioStream::start();
}
void CoreAudioOutputStream::stopInternal()
{
CoreAudioStream::stop();
}
void CoreAudioOutputStream::initDeviceBuffer(unsigned int bufferSize)
{
initAudioBuffer(bufferSize);
}
OSStatus CoreAudioOutputStream::processAudio(AudioUnitRenderActionFlags * actionFlags, const AudioTimeStamp * timeStamp, UInt32 busNumber, UInt32 numberFrames, AudioBufferList * data)
{
OSStatus status = AudioUnitRender(auHAL, actionFlags, timeStamp, busNumber, numberFrames, &bufferList);
UInt32 frameBytes = numberFrames * deviceIOFormat.mBytesPerFrame;
AudioBuffer * audioBuffer = bufferList.mBuffers;
if (status == noErr) {
std::uint8_t * samples = nullptr;
// If a converter is present, then we have to resample audio.
if (converter != nullptr) {
convBufferList.mNumberBuffers = 1;
AudioBuffer * convAudioBuffer = convBufferList.mBuffers;
convAudioBuffer->mNumberChannels = converterFormat.mChannelsPerFrame;
convAudioBuffer->mDataByteSize = static_cast<UInt32>(convBuffer.size());
UInt32 convNumberPackets = convAudioBuffer->mDataByteSize / converterFormat.mBytesPerPacket;
// Fill sample buffer and convert samples.
OSStatus convStatus = AudioConverterFillComplexBuffer(converter, fillConverterBuffer, this, &convNumberPackets, &convBufferList, 0);
frameBytes = convNumberPackets * converterFormat.mBytesPerFrame;
if (convStatus == noErr) {
samples = reinterpret_cast<std::uint8_t *>(convAudioBuffer->mData);
}
else {
THROW_IF_FAILED(convStatus, "CoreAudio: Resample audio failed.");
}
}
else {
samples = reinterpret_cast<std::uint8_t *>(audioBuffer->mData);
}
if (samples != nullptr) {
writeAudio(samples, frameBytes);
}
}
else {
THROW_IF_FAILED(status, "CoreAudio: Render input samples failed.");
}
return status;
}
OSStatus CoreAudioOutputStream::fillConverterBuffer(AudioConverterRef audioConverter, UInt32 * numberDataPackets, AudioBufferList * data, AudioStreamPacketDescription ** outDataPacketDescription, void * context)
{
CoreAudioOutputStream * stream = static_cast<CoreAudioOutputStream *>(context);
// Tell the Audio Converter where it's source data is.
data->mBuffers[0].mData = stream->bufferList.mBuffers[0].mData;
// Tell the Audio Converter how much data is in each buffer.
data->mBuffers[0].mDataByteSize = *numberDataPackets * stream->deviceIOFormat.mBytesPerPacket;
return noErr;
}
}
|
xiayingfeng/android-atleap
|
atleap-core-test/src/androidTest/java/com/blandware/android/atleap/test/stub/RequestListenerStub.java
|
/*
* Copyright (C) 2013 Blandware (http://www.blandware.com)
*
* 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.blandware.android.atleap.test.stub;
import android.os.Looper;
import com.octo.android.robospice.persistence.exception.SpiceException;
import com.octo.android.robospice.request.listener.RequestListener;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* Created by agrebnev on 01.01.14.
*/
public class RequestListenerStub<T> implements RequestListener<T> {
protected Boolean isSuccessful = null;
protected boolean isExecutedInUIThread = false;
protected ReentrantLock lock = new ReentrantLock();
protected Condition requestFinishedCondition = lock.newCondition();
protected Exception exception;
protected List<T> resultHistory = new ArrayList<T>();
@Override
public void onRequestFailure(SpiceException exception) {
lock.lock();
try {
checkIsExectuedInUIThread();
isSuccessful = false;
this.exception = exception;
requestFinishedCondition.signal();
} finally {
lock.unlock();
}
}
@Override
public void onRequestSuccess(T arg0) {
lock.lock();
try {
checkIsExectuedInUIThread();
isSuccessful = true;
resultHistory.add(arg0);
requestFinishedCondition.signal();
} finally {
lock.unlock();
}
}
public List<T> getResultHistory() {
return resultHistory;
}
protected void checkIsExectuedInUIThread() {
if (Looper.myLooper() != null && Looper.myLooper() == Looper.getMainLooper()) {
isExecutedInUIThread = true;
}
}
public Boolean isSuccessful() {
return isSuccessful;
}
public Exception getReceivedException() {
return exception;
}
public boolean isExecutedInUIThread() {
return isExecutedInUIThread;
}
public void await(long millisecond) throws InterruptedException {
lock.lock();
try {
if (isSuccessful != null) {
return;
}
requestFinishedCondition.await(millisecond, TimeUnit.MILLISECONDS);
} finally {
lock.unlock();
}
}
public void resetSuccess() {
this.isSuccessful = null;
}
}
|
frizz/frizz
|
flux/dispatcher.go
|
package flux
import "sync"
type Dispatcher struct {
m sync.Mutex
notifier NotifierInterface
stores []StoreInterface
}
// NewDispatcher creates a new dispatcher and registers the provided stores
func NewDispatcher(notifier NotifierInterface, stores ...StoreInterface) *Dispatcher {
d := &Dispatcher{notifier: notifier}
for _, s := range stores {
d.Register(s)
}
return d
}
// Register adds a store to the dispatcher
func (d *Dispatcher) Register(store StoreInterface) {
d.m.Lock()
defer d.m.Unlock()
d.stores = append(d.stores, store)
}
// Dispatch sends an action to all registered stores
func (d *Dispatcher) Dispatch(action ActionInterface) chan struct{} {
done := make(chan struct{}, 1)
go func() {
payloads := make(map[StoreInterface]*Payload, len(d.stores))
d.handleAction(action, payloads)
d.sendNotifs(payloads)
close(done)
}()
return done
}
func (d *Dispatcher) handleAction(action ActionInterface, payloads map[StoreInterface]*Payload) {
d.m.Lock()
defer d.m.Unlock()
// Create a waitgroup and add the number of stores
wg := sync.WaitGroup{}
wg.Add(len(d.stores))
// Create the loop detector
loop := newLoopDetector()
for _, store := range d.stores {
payloads[store] = newPayload(action, store, payloads, loop, d.notifier)
}
for _, sr := range d.stores {
// The store will be used inside a goroutine, so we can't use sr, which is re-used by
// the range.
store := sr
payload := payloads[store]
go func() {
// Start the store handler.
finished := store.Handle(payload)
// If we finished syncronously, we close the tracker's Done channel. If we are
// still processing asyncronously, we leave it to be closed when the handler has
// finished.
if finished {
close(payload.Done)
}
}()
go func() {
// We wait for the tracker to finish
<-payload.finished()
wg.Done()
}()
}
wg.Wait()
}
func (d *Dispatcher) sendNotifs(payloads map[StoreInterface]*Payload) {
// all stores have finished processing, so we can start firing off
// notifs...
for _, p := range payloads {
for _, n := range p.notifs {
<-d.notifier.Notify(n.object, n.notif, n.data)
}
}
}
|
mikesprague/tad
|
src/components/ColumnList.js
|
/* @flow */
import * as React from 'react'
import ColumnRow from './ColumnRow'
/*
* A simple ordered list of columns. Supports re-ordering
*/
export default class ColumnList extends React.Component {
renderColumnRow (row: any) {
let key = row
if (typeof row !== 'string') {
key = row[0]
}
return (
<ColumnRow
key={key}
columnListType={this.props.columnListType}
schema={this.props.schema}
rowFormatter={this.props.rowFormatter}
stateRefUpdater={this.props.stateRefUpdater}
rowData={row} />
)
}
render () {
let extraHeaders = null
if (this.props.headerLabels) {
extraHeaders = this.props.headerLabels.map(hnm => {
return (
<th key={hnm} className='column-list-th'>{hnm}</th>
)
})
}
const columnRows = this.props.items.map(row => this.renderColumnRow(row))
return (
<div className='column-list'>
<div className='column-list-header'>
<table className='table column-selector-table'>
<thead>
<tr>
<th className='column-list-th col-colName'>Column</th>
{extraHeaders}
</tr>
</thead>
</table>
</div>
<div className='column-list-body'>
<table className='table table-hover column-selector-table'>
<tbody>
{columnRows}
</tbody>
</table>
</div>
</div>
)
}
}
|
PDarkTemplar/NeedMoreBeer
|
Front/src/stores/viewModels/Common.js
|
<gh_stars>0
// @flow
import { observable } from 'mobx';
class Common {
@observable initialized: boolean = false;
@observable loading: boolean = false;
}
export default Common;
|
dr1verrr/dr1ver.shop
|
pages/api/login.js
|
import axios from 'axios'
import { setCookie } from 'nookies'
export default async function login(req, res) {
const { password, identifier } = req.body
try {
const postRes = await axios.post(`${process.env.NEXT_PUBLIC_API_URL}/auth/local`, {
identifier,
password,
})
setCookie({ res }, 'jwt', postRes.data.jwt, {
httpOnly: true,
secure: process.env.NODE_ENV !== 'development',
maxAge: 30 * 24 * 60 * 60,
path: '/',
})
res.setHeader('Content-Type', 'text/plain')
res.status(200).end()
} catch (e) {
res.status(400).send(e.response.data)
console.log(e.response.data)
}
}
|
shelang/aghab
|
src/main/java/io/shelang/aghab/service/dto/LinkMetaDTO.java
|
<reponame>shelang/aghab
package io.shelang.aghab.service.dto;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.time.Instant;
@Data
@Accessors(chain = true)
@NoArgsConstructor
public class LinkMetaDTO {
private Long id;
private String title;
private String description;
private Instant createAt;
private Instant updateAt;
}
|
vbea/VbeaUtil
|
app/src/main/java/com/vbes/util/matisse/ui/adapter/PreviewPagerAdapter.java
|
<reponame>vbea/VbeaUtil
package com.vbes.util.matisse.ui.adapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.ViewGroup;
import com.vbes.util.matisse.entity.Item;
import com.vbes.util.matisse.ui.PreviewItemFragment;
import java.util.ArrayList;
import java.util.List;
public class PreviewPagerAdapter extends FragmentPagerAdapter {
private ArrayList<Item> mItems = new ArrayList<>();
private OnPrimaryItemSetListener mListener;
public PreviewPagerAdapter(FragmentManager manager, OnPrimaryItemSetListener listener) {
super(manager);
mListener = listener;
}
@Override
public Fragment getItem(int position) {
return PreviewItemFragment.newInstance(mItems.get(position));
}
@Override
public int getCount() {
return mItems.size();
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
if (mListener != null) {
mListener.onPrimaryItemSet(position);
}
}
public Item getMediaItem(int position) {
return mItems.get(position);
}
public void addAll(List<Item> items) {
mItems.addAll(items);
}
interface OnPrimaryItemSetListener {
void onPrimaryItemSet(int position);
}
}
|
Sub2n/React-Exercise
|
React/repos/styling-react/src/App.js
|
import React from 'react';
import StyledComponent from './StyledComponent';
const App = () => {
return <StyledComponent />;
};
export default App;
|
r8d8/lastlock
|
QCA4020_SDK/target/quartz/serializer/genedit_files/qz/include/qapi_ble_aios_func.h
|
<gh_stars>0
/*
* Copyright (c) 2018 Qualcomm Technologies, Inc.
* All Rights Reserved.
*/
// Copyright (c) 2018 Qualcomm Technologies, Inc.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below)
// provided that the following conditions are met:
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// Neither the name of Qualcomm Technologies, Inc. nor the names of its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
// NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
// OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef __QAPI_BLE_AIOS_FUNC_H__
#define __QAPI_BLE_AIOS_FUNC_H__
#include <stdint.h>
#include "qsCommon.h"
SerStatus_t Handle_qapi_BLE_AIOS_Initialize_Service(uint8_t *qsBuffer, uint16_t qsLength, PackedBuffer_t *qsOutputBuffer, uint8_t *uId);
SerStatus_t Handle_qapi_BLE_AIOS_Initialize_Service_Handle_Range(uint8_t *qsBuffer, uint16_t qsLength, PackedBuffer_t *qsOutputBuffer, uint8_t *uId);
SerStatus_t Handle_qapi_BLE_AIOS_Cleanup_Service(uint8_t *qsBuffer, uint16_t qsLength, PackedBuffer_t *qsOutputBuffer, uint8_t *uId);
SerStatus_t Handle_qapi_BLE_AIOS_Query_Number_Attributes(uint8_t *qsBuffer, uint16_t qsLength, PackedBuffer_t *qsOutputBuffer, uint8_t *uId);
SerStatus_t Handle_qapi_BLE_AIOS_Read_CCCD_Request_Response(uint8_t *qsBuffer, uint16_t qsLength, PackedBuffer_t *qsOutputBuffer, uint8_t *uId);
SerStatus_t Handle_qapi_BLE_AIOS_Write_CCCD_Request_Response(uint8_t *qsBuffer, uint16_t qsLength, PackedBuffer_t *qsOutputBuffer, uint8_t *uId);
SerStatus_t Handle_qapi_BLE_AIOS_Read_Presentation_Format_Request_Response(uint8_t *qsBuffer, uint16_t qsLength, PackedBuffer_t *qsOutputBuffer, uint8_t *uId);
SerStatus_t Handle_qapi_BLE_AIOS_Read_User_Description_Request_Response(uint8_t *qsBuffer, uint16_t qsLength, PackedBuffer_t *qsOutputBuffer, uint8_t *uId);
SerStatus_t Handle_qapi_BLE_AIOS_Write_User_Description_Request_Response(uint8_t *qsBuffer, uint16_t qsLength, PackedBuffer_t *qsOutputBuffer, uint8_t *uId);
SerStatus_t Handle_qapi_BLE_AIOS_Read_Value_Trigger_Setting_Request_Response(uint8_t *qsBuffer, uint16_t qsLength, PackedBuffer_t *qsOutputBuffer, uint8_t *uId);
SerStatus_t Handle_qapi_BLE_AIOS_Write_Value_Trigger_Setting_Request_Response(uint8_t *qsBuffer, uint16_t qsLength, PackedBuffer_t *qsOutputBuffer, uint8_t *uId);
SerStatus_t Handle_qapi_BLE_AIOS_Read_Time_Trigger_Setting_Request_Response(uint8_t *qsBuffer, uint16_t qsLength, PackedBuffer_t *qsOutputBuffer, uint8_t *uId);
SerStatus_t Handle_qapi_BLE_AIOS_Write_Time_Trigger_Setting_Request_Response(uint8_t *qsBuffer, uint16_t qsLength, PackedBuffer_t *qsOutputBuffer, uint8_t *uId);
SerStatus_t Handle_qapi_BLE_AIOS_Read_Number_Of_Digitals_Request_Response(uint8_t *qsBuffer, uint16_t qsLength, PackedBuffer_t *qsOutputBuffer, uint8_t *uId);
SerStatus_t Handle_qapi_BLE_AIOS_Read_Valid_Range_Request_Response(uint8_t *qsBuffer, uint16_t qsLength, PackedBuffer_t *qsOutputBuffer, uint8_t *uId);
SerStatus_t Handle_qapi_BLE_AIOS_Read_Characteristic_Request_Response(uint8_t *qsBuffer, uint16_t qsLength, PackedBuffer_t *qsOutputBuffer, uint8_t *uId);
SerStatus_t Handle_qapi_BLE_AIOS_Write_Characteristic_Request_Response(uint8_t *qsBuffer, uint16_t qsLength, PackedBuffer_t *qsOutputBuffer, uint8_t *uId);
SerStatus_t Handle_qapi_BLE_AIOS_Notify_Characteristic(uint8_t *qsBuffer, uint16_t qsLength, PackedBuffer_t *qsOutputBuffer, uint8_t *uId);
SerStatus_t Handle_qapi_BLE_AIOS_Indicate_Characteristic(uint8_t *qsBuffer, uint16_t qsLength, PackedBuffer_t *qsOutputBuffer, uint8_t *uId);
SerStatus_t Handle_qapi_BLE_AIOS_Decode_Presentation_Format(uint8_t *qsBuffer, uint16_t qsLength, PackedBuffer_t *qsOutputBuffer, uint8_t *uId);
SerStatus_t Handle_qapi_BLE_AIOS_Format_Value_Trigger_Setting(uint8_t *qsBuffer, uint16_t qsLength, PackedBuffer_t *qsOutputBuffer, uint8_t *uId);
SerStatus_t Handle_qapi_BLE_AIOS_Decode_Value_Trigger_Setting(uint8_t *qsBuffer, uint16_t qsLength, PackedBuffer_t *qsOutputBuffer, uint8_t *uId);
SerStatus_t Handle_qapi_BLE_AIOS_Format_Time_Trigger_Setting(uint8_t *qsBuffer, uint16_t qsLength, PackedBuffer_t *qsOutputBuffer, uint8_t *uId);
SerStatus_t Handle_qapi_BLE_AIOS_Decode_Time_Trigger_Setting(uint8_t *qsBuffer, uint16_t qsLength, PackedBuffer_t *qsOutputBuffer, uint8_t *uId);
SerStatus_t Handle_qapi_BLE_AIOS_Decode_Valid_Range(uint8_t *qsBuffer, uint16_t qsLength, PackedBuffer_t *qsOutputBuffer, uint8_t *uId);
FunctionHandler_t qapi_ble_aios_funclist[] =
{
Handle_qapi_BLE_AIOS_Initialize_Service, /* Function Index = 0 */
Handle_qapi_BLE_AIOS_Initialize_Service_Handle_Range, /* Function Index = 1 */
Handle_qapi_BLE_AIOS_Cleanup_Service, /* Function Index = 2 */
Handle_qapi_BLE_AIOS_Query_Number_Attributes, /* Function Index = 3 */
Handle_qapi_BLE_AIOS_Read_CCCD_Request_Response, /* Function Index = 4 */
Handle_qapi_BLE_AIOS_Write_CCCD_Request_Response, /* Function Index = 5 */
Handle_qapi_BLE_AIOS_Read_Presentation_Format_Request_Response, /* Function Index = 6 */
Handle_qapi_BLE_AIOS_Read_User_Description_Request_Response, /* Function Index = 7 */
Handle_qapi_BLE_AIOS_Write_User_Description_Request_Response, /* Function Index = 8 */
Handle_qapi_BLE_AIOS_Read_Value_Trigger_Setting_Request_Response, /* Function Index = 9 */
Handle_qapi_BLE_AIOS_Write_Value_Trigger_Setting_Request_Response, /* Function Index = 10 */
Handle_qapi_BLE_AIOS_Read_Time_Trigger_Setting_Request_Response, /* Function Index = 11 */
Handle_qapi_BLE_AIOS_Write_Time_Trigger_Setting_Request_Response, /* Function Index = 12 */
Handle_qapi_BLE_AIOS_Read_Number_Of_Digitals_Request_Response, /* Function Index = 13 */
Handle_qapi_BLE_AIOS_Read_Valid_Range_Request_Response, /* Function Index = 14 */
Handle_qapi_BLE_AIOS_Read_Characteristic_Request_Response, /* Function Index = 15 */
Handle_qapi_BLE_AIOS_Write_Characteristic_Request_Response, /* Function Index = 16 */
Handle_qapi_BLE_AIOS_Notify_Characteristic, /* Function Index = 17 */
Handle_qapi_BLE_AIOS_Indicate_Characteristic, /* Function Index = 18 */
Handle_qapi_BLE_AIOS_Decode_Presentation_Format, /* Function Index = 19 */
Handle_qapi_BLE_AIOS_Format_Value_Trigger_Setting, /* Function Index = 20 */
Handle_qapi_BLE_AIOS_Decode_Value_Trigger_Setting, /* Function Index = 21 */
Handle_qapi_BLE_AIOS_Format_Time_Trigger_Setting, /* Function Index = 22 */
Handle_qapi_BLE_AIOS_Decode_Time_Trigger_Setting, /* Function Index = 23 */
Handle_qapi_BLE_AIOS_Decode_Valid_Range, /* Function Index = 24 */
};
#define QAPI_BLE_AIOS_FUNC_LIST_SIZE (sizeof(qapi_ble_aios_funclist) / sizeof(FunctionHandler_t))
#endif // __QAPI_BLE_AIOS_FUNC_H__
|
mctouch/dlrm_for_pytorch
|
dlrm/nn/interactions.py
|
# Copyright (c) 2020 NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch
from dlrm.cuda_ext import dotBasedInteract
class Interaction:
@property
def num_interactions(self) -> int:
raise NotImplementedError()
def interact(self, bottom_output, bottom_mlp_output):
"""
:param bottom_output: [batch_size, 1 + #embeddings, embedding_dim]
:param bottom_mlp_output
:return:
"""
raise NotImplementedError()
class DotInteraction(Interaction):
def __init__(self, embedding_num: int, embedding_dim: int):
"""
Interactions are among outputs of all the embedding tables and bottom MLP, total number of
(num_embedding_tables + 1) vectors with size embedding_dim. ``dot`` product interaction computes dot product
between any 2 vectors. Output of interaction will have shape [num_interactions, embedding_dim].
"""
self._num_interaction_inputs = embedding_num + 1
self._embedding_dim = embedding_dim
self._tril_indices = torch.tensor([[i for i in range(self._num_interaction_inputs)
for _ in range(i)],
[j for i in range(self._num_interaction_inputs)
for j in range(i)]])
@property
def num_interactions(self) -> int:
n = (self._num_interaction_inputs * (self._num_interaction_inputs - 1)) // 2 + self._embedding_dim
return n + 1 # pad 1 to be multiple of 8
def interact(self, bottom_output, bottom_mlp_output):
"""
:param bottom_output: [batch_size, 1 + #embeddings, embedding_dim]
:param bottom_mlp_output
:return:
"""
batch_size = bottom_output.size()[0]
interaction = torch.bmm(bottom_output, torch.transpose(bottom_output, 1, 2))
interaction_flat = interaction[:, self._tril_indices[0], self._tril_indices[1]]
# concatenate dense features and interactions
zeros_padding = torch.zeros(batch_size, 1, dtype=bottom_output.dtype, device=bottom_output.device)
interaction_output = torch.cat(
(bottom_mlp_output, interaction_flat, zeros_padding), dim=1)
return interaction_output
class CudaDotInteraction(Interaction):
def __init__(self, dot_interaction: DotInteraction):
self._dot_interaction = dot_interaction
@property
def num_interactions(self):
return self._dot_interaction.num_interactions
def interact(self, bottom_output, bottom_mlp_output):
"""
:param bottom_output: [batch_size, 1 + #embeddings, embedding_dim]
:param bottom_mlp_output
:return:
"""
return dotBasedInteract(bottom_output, bottom_mlp_output)
class CatInteraction(Interaction):
def __init__(self, embedding_num: int, embedding_dim: int):
"""
Interactions are among outputs of all the embedding tables and bottom MLP, total number of
(num_embedding_tables + 1) vectors with size embdding_dim. ``cat`` interaction concatenate all the vectors
together. Output of interaction will have shape [num_interactions, embedding_dim].
"""
self._num_interaction_inputs = embedding_num + 1
self._embedding_dim = embedding_dim
@property
def num_interactions(self) -> int:
return self._num_interaction_inputs * self._embedding_dim
def interact(self, bottom_output, bottom_mlp_output):
"""
:param bottom_output: [batch_size, 1 + #embeddings, embedding_dim]
:param bottom_mlp_output
:return:
"""
return bottom_output.view(-1, self.num_interactions)
|
HastingsGreer/itk-js
|
examples/Webpack/test/config/itkConfigTest.js
|
const itkConfig = {
itkModulesPath: __BASE_PATH__ + '/dist/itk'
}
export default itkConfig
|
skylark-integration/skylark-dijit-mvc
|
.history/history-qface1-201304/src/qface/ui/drawing/_createjs/soundjs/HTMLAudioPlugin.js
|
<gh_stars>0
/*
* HTMLAudioPlugin for SoundJS
* Visit http://createjs.com/ for documentation, updates and examples.
*
*
* Copyright (c) 2012 <EMAIL>, inc.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* @module SoundJS
*/
// namespace:
this.createjs = this.createjs || {};
(function () {
/**
* Play sounds using HTML <audio> tags in the browser. This plugin is the second priority plugin installed
* by default, after the {{#crossLink "WebAudioPlugin"}}{{/crossLink}}, which is supported on Chrome, Safari, and
* iOS. This handles audio in all other modern browsers. For non-supported browsers, include and install the
* {{#crossLink "FlashPlugin"}}{{/crossLink}}.
*
* <h4>Known Browser and OS issues for HTML Audio</h4>
* <b>All browsers</b><br />
* Testing has shown in all browsers there is a limit to how many audio tag instances you are allowed. If you exceed
* this limit, you can expect to see unpredictable results. This will be seen as soon as you register sounds, as
* tags are precreated to all Chrome to load them. Please use {{#crossLink "Sound.MAX_INSTANCES"}}{{/crossLink}} as
* a guide to how many total audio tags you can safely use in all browsers.
*
* <b>IE 9 html audio quirk</b><br />
* Note in IE 9 there is a delay in applying volume changes to tags that occurs once playback is started. So if you have
* muted all sounds, they will all play during this delay until the mute applies internally. This happens regardless of
* when or how you apply the volume change, as the tag seems to need to play to apply it.
*
* <b>iOS 6 limitations</b><br />
* Note it is recommended to use {{#crossLink "WebAudioPlugin"}}{{/crossLink}} for iOS (6+). HTML Audio can only
* have one <audio> tag, can not preload or autoplay the audio, can not cache the audio, and can not play the
* audio except inside a user initiated event.
*
* <b>Android limitations</b><br />
* <li>We have no control over audio volume. Only the user can set volume on their device.</li>
* <li>We can only play audio inside a user event (touch). This currently means you cannot loop sound.</li></ul>
*
* See {{#crossLink "Sound"}}{{/crossLink}} for general notes on known issues.
*
* @class HTMLAudioPlugin
* @constructor
*/
function HTMLAudioPlugin() {
this.init();
}
var s = HTMLAudioPlugin;
/**
* The maximum number of instances that can be played. This is a browser limitation. The actual number varies from
* browser to browser (and is largely hardware dependant), but this is a safe estimate.
* @property MAX_INSTANCES
* @type {Number}
* @default 30
* @static
*/
s.MAX_INSTANCES = 30;
/**
* The capabilities of the plugin. This is generated via the the SoundInstance {{#crossLink "TMLAudioPlugin/generateCapabilities"}}{{/crossLink}}
* method. Please see the Sound {{#crossLink "Sound/getCapabilities"}}{{/crossLink}} method for an overview of all
* of the available properties.
* @property capabilities
* @type {Object}
* @static
*/
s.capabilities = null;
/**
* Event constant for the "canPlayThrough" event for cleaner code.
* @property AUDIO_READY
* @type {String}
* @default canplaythrough
* @static
*/
s.AUDIO_READY = "canplaythrough";
/**
* Event constant for the "ended" event for cleaner code.
* @property AUDIO_ENDED
* @type {String}
* @default ended
* @static
*/
s.AUDIO_ENDED = "ended";
/**
* Event constant for the "error" event for cleaner code.
* @property AUDIO_ERROR
* @type {String}
* @default error
* @static
*/
s.AUDIO_ERROR = "error"; //TODO: Handle error cases
/**
* Event constant for the "stalled" event for cleaner code.
* @property AUDIO_STALLED
* @type {String}
* @default stalled
* @static
*/
s.AUDIO_STALLED = "stalled";
/**
* Determine if the plugin can be used in the current browser/OS. Note that HTML audio is available in most modern
* browsers except iOS, where it is limited.
* @method isSupported
* @return {Boolean} If the plugin can be initialized.
* @static
*/
s.isSupported = function () {
if (createjs.Sound.BrowserDetect.isIOS) {
return false;
}
// You can enable this plugin on iOS by removing this line, but it is not recommended due to the limitations:
// iOS can only have a single <audio> instance, cannot preload or autoplay, cannot cache sound, and can only be
// played in response to a user event (click)
s.generateCapabilities();
var t = s.tag; // OJR do we still need this check, when cap will already be null if this is the case
if (t == null || s.capabilities == null) {
return false;
}
return true;
};
/**
* Determine the capabilities of the plugin. Used internally. Please see the Sound API {{#crossLink "Sound/getCapabilities"}}{{/crossLink}}
* method for an overview of plugin capabilities.
* @method generateCapabiities
* @static
* @protected
*/
s.generateCapabilities = function () {
if (s.capabilities != null) {
return;
}
var t = s.tag = document.createElement("audio");
if (t.canPlayType == null) {
return null;
}
s.capabilities = {
panning:true,
volume:true,
tracks:-1
};
// determine which extensions our browser supports for this plugin by iterating through Sound.SUPPORTED_EXTENSIONS
var supportedExtensions = createjs.Sound.SUPPORTED_EXTENSIONS;
var extensionMap = createjs.Sound.EXTENSION_MAP;
for (var i = 0, l = supportedExtensions.length; i < l; i++) {
var ext = supportedExtensions[i];
var playType = extensionMap[ext] || ext;
s.capabilities[ext] = (t.canPlayType("audio/" + ext) != "no" && t.canPlayType("audio/" + ext) != "") || (t.canPlayType("audio/" + playType) != "no" && t.canPlayType("audio/" + playType) != "");
} // OJR another way to do this might be canPlayType:"m4a", codex: mp4
}
var p = s.prototype = {
/**
* The capabilities of the plugin, created by the {{#crossLink "HTMLAudioPlugin/generateCapabilities"}}{{/crossLink}}
* method.
*/
capabilities:null,
/**
* Object hash indexed by the source of each file to indicate if an audio source is loaded, or loading.
* @property audioSources
* @type {Object}
* @protected
* @since 0.4.0
*/
audioSources:null,
/**
* The default number of instances to allow. Passed back to {{#crossLink "Sound"}}{{/crossLink}} when a source
* is registered using the {{#crossLink "Sound/register"}}{{/crossLink}} method. This is only used if
* a value is not provided.
*
* <b>NOTE this only exists as a limitation of HTML audio.</b>
* @property defaultNumChannels
* @type {Number}
* @default 2
* @since 0.4.0
*/
defaultNumChannels:2,
/**
* An initialization function run by the constructor
* @method init
* @private
*/
init:function () {
this.capabilities = s.capabilities;
this.audioSources = {};
},
/**
* Pre-register a sound instance when preloading/setup. This is called by {{#crossLink "Sound"}}{{/crossLink}}.
* Note that this provides an object containing a tag used for preloading purposes, which
* <a href="http://preloadjs.com">PreloadJS</a> can use to assist with preloading.
* @method register
* @param {String} src The source of the audio
* @param {Number} instances The number of concurrently playing instances to allow for the channel at any time.
* @return {Object} A result object, containing a tag for preloading purposes and a numChannels value for internally
* controlling how many instances of a source can be played by default.
*/
register:function (src, instances) {
this.audioSources[src] = true; // Note this does not mean preloading has started
var channel = TagPool.get(src);
var tag = null;
var l = instances || this.defaultNumChannels;
for (var i = 0; i < l; i++) { // OJR should we be enforcing s.MAX_INSTANCES here? Does the chrome bug still exist, or can we change this code?
tag = this.createTag(src);
channel.add(tag);
}
return {
tag:tag, // Return one instance for preloading purposes
numChannels:l // The default number of channels to make for this Sound or the passed in value
};
},
/**
* Create an HTML audio tag.
* @method createTag
* @param {String} src The source file to set for the audio tag.
* @return {HTMLElement} Returns an HTML audio tag.
* @protected
*/
createTag:function (src) {
var tag = document.createElement("audio");
tag.autoplay = false;
tag.preload = "none";
tag.src = src;
return tag;
},
/**
* Create a sound instance. If the sound has not been preloaded, it is internally preloaded here.
* @method create
* @param {String} src The sound source to use.
* @return {SoundInstance} A sound instance for playback and control.
*/
create:function (src) {
// if this sound has not be registered, create a tag and preload it
if (!this.isPreloadStarted(src)) {
var channel = TagPool.get(src);
var tag = this.createTag(src);
channel.add(tag);
this.preload(src, {tag:tag});
}
return new SoundInstance(src, this);
},
/**
* Checks if preloading has started for a specific source.
* @method isPreloadStarted
* @param {String} src The sound URI to check.
* @return {Boolean} If the preload has started.
* @since 0.4.0
*/
isPreloadStarted:function (src) {
return (this.audioSources[src] != null);
},
/**
* Internally preload a sound.
* @method preload
* @param {String} src The sound URI to load.
* @param {Object} instance An object containing a tag property that is an HTML audio tag used to load src.
* @since 0.4.0
*/
preload:function (src, instance) {
this.audioSources[src] = true;
new HTMLAudioLoader(src, instance.tag);
},
toString:function () {
return "[HTMLAudioPlugin]";
}
}
createjs.HTMLAudioPlugin = HTMLAudioPlugin;
// NOTE Documentation for the SoundInstance class in WebAudioPlugin file. Each plugin generates a SoundInstance that
// follows the same interface.
function SoundInstance(src, owner) {
this.init(src, owner);
}
var p = SoundInstance.prototype = {
src:null,
uniqueId:-1,
playState:null,
owner:null,
loaded:false,
offset:0,
delay:0,
volume:1,
pan:0,
duration:0,
remainingLoops:0,
delayTimeoutId:null,
tag:null,
muted:false,
paused:false,
// mix-ins:
// EventDispatcher methods:
addEventListener:null,
removeEventListener:null,
removeAllEventListeners:null,
dispatchEvent:null,
hasEventListener:null,
_listeners:null,
// Callbacks
onComplete:null,
onLoop:null,
onReady:null,
onPlayFailed:null,
onPlayInterrupted:null,
onPlaySucceeded:null,
// Proxies, make removing listeners easier.
endedHandler:null,
readyHandler:null,
stalledHandler:null,
// Constructor
init:function (src, owner) {
this.src = src;
this.owner = owner;
this.endedHandler = createjs.proxy(this.handleSoundComplete, this);
this.readyHandler = createjs.proxy(this.handleSoundReady, this);
this.stalledHandler = createjs.proxy(this.handleSoundStalled, this);
},
sendEvent:function (eventString) {
var event = {
target:this,
type:eventString
};
this.dispatchEvent(event);
},
cleanUp:function () {
var tag = this.tag;
if (tag != null) {
tag.pause();
try {
tag.currentTime = 0;
} catch (e) {
} // Reset Position
tag.removeEventListener(createjs.HTMLAudioPlugin.AUDIO_ENDED, this.endedHandler, false);
tag.removeEventListener(createjs.HTMLAudioPlugin.AUDIO_READY, this.readyHandler, false);
TagPool.setInstance(this.src, tag);
this.tag = null;
}
clearTimeout(this.delayTimeoutId);
if (window.createjs == null) {
return;
}
createjs.Sound.playFinished(this);
},
interrupt:function () {
if (this.tag == null) {
return;
}
this.playState = createjs.Sound.PLAY_INTERRUPTED;
if (this.onPlayInterrupted) {
this.onPlayInterrupted(this);
}
this.sendEvent("interrupted");
this.cleanUp();
this.paused = false;
},
// Public API
play:function (interrupt, delay, offset, loop, volume, pan) {
this.cleanUp(); //LM: Is this redundant?
createjs.Sound.playInstance(this, interrupt, delay, offset, loop, volume, pan);
},
beginPlaying:function (offset, loop, volume, pan) {
if (window.createjs == null) {
return -1;
}
var tag = this.tag = TagPool.getInstance(this.src);
if (tag == null) {
this.playFailed();
return -1;
}
this.duration = this.tag.duration * 1000;
// OJR would like a cleaner way to do this in init, discuss with LM
// need this for setPosition on stopped sounds
tag.addEventListener(createjs.HTMLAudioPlugin.AUDIO_ENDED, this.endedHandler, false);
// Reset this instance.
this.offset = offset;
this.volume = volume;
this.updateVolume(); // note this will set for mute and masterMute
this.remainingLoops = loop;
if (tag.readyState !== 4) {
tag.addEventListener(createjs.HTMLAudioPlugin.AUDIO_READY, this.readyHandler, false);
tag.addEventListener(createjs.HTMLAudioPlugin.AUDIO_STALLED, this.stalledHandler, false);
tag.load();
} else {
this.handleSoundReady(null);
}
this.onPlaySucceeded && this.onPlaySucceeded(this);
this.sendEvent("succeeded");
return 1;
},
// Note: Sounds stall when trying to begin playback of a new audio instance when the existing instances
// has not loaded yet. This doesn't mean the sound will not play.
handleSoundStalled:function (event) {
if (this.onPlayFailed != null) {
this.onPlayFailed(this);
}
this.sendEvent("failed");
this.cleanUp(); // OJR NOTE this will stop playback, and I think we should remove this and let the developer decide how to handle stalled instances
},
handleSoundReady:function (event) {
if (window.createjs == null) {
return;
}
this.playState = createjs.Sound.PLAY_SUCCEEDED;
this.paused = false;
this.tag.removeEventListener(createjs.HTMLAudioPlugin.AUDIO_READY, this.readyHandler, false);
if (this.offset >= this.getDuration()) {
this.playFailed(); // OJR: throw error?
return;
} else if (this.offset > 0) {
this.tag.currentTime = this.offset * 0.001;
}
if (this.remainingLoops == -1) {
this.tag.loop = true;
}
this.tag.play();
},
pause:function () {
if (!this.paused && this.playState == createjs.Sound.PLAY_SUCCEEDED && this.tag != null) {
this.paused = true;
// Note: when paused by user, we hold a reference to our tag. We do not release it until stopped.
this.tag.pause();
clearTimeout(this.delayTimeoutId);
return true;
}
return false;
},
resume:function () {
if (!this.paused || this.tag == null) {
return false;
}
this.paused = false;
this.tag.play();
return true;
},
stop:function () {
this.offset = 0;
this.pause();
this.playState = createjs.Sound.PLAY_FINISHED;
this.cleanUp();
return true;
},
setMasterVolume:function (value) {
this.updateVolume();
return true;
},
setVolume:function (value) {
if (Number(value) == null) {
return false;
}
value = Math.max(0, Math.min(1, value));
this.volume = value;
this.updateVolume();
return true;
},
updateVolume:function () {
if (this.tag != null) {
var newVolume = (this.muted || createjs.Sound.masterMute) ? 0 : this.volume * createjs.Sound.masterVolume;
if (newVolume != this.tag.volume) {
this.tag.volume = newVolume;
}
return true;
} else {
return false;
}
},
getVolume:function (value) {
return this.volume;
},
mute:function (isMuted) {
this.muted = isMuted;
this.updateVolume();
return true;
},
setMasterMute:function (isMuted) {
this.updateVolume();
return true;
},
setMute:function (isMuted) {
if (isMuted == null || isMuted == undefined) {
return false
}
;
this.muted = isMuted;
this.updateVolume();
return true;
},
getMute:function () {
return this.muted;
},
setPan:function (value) {
return false;
}, // Can not set pan in HTML
getPan:function () {
return 0;
},
getPosition:function () {
if (this.tag == null) {
return this.offset;
}
return this.tag.currentTime * 1000;
},
setPosition:function (value) {
if (this.tag == null) {
this.offset = value
} else try {
this.tag.currentTime = value * 0.001;
} catch (error) { // Out of range
return false;
}
return true;
},
getDuration:function () { // NOTE this will always return 0 until sound has been played.
return this.duration;
},
handleSoundComplete:function (event) {
this.offset = 0;
if (this.remainingLoops != 0) {
this.remainingLoops--;
//try { this.tag.currentTime = 0; } catch(error) {}
this.tag.play();
if (this.onLoop != null) {
this.onLoop(this);
}
this.sendEvent("loop");
return;
}
if (window.createjs == null) {
return;
}
this.playState = createjs.Sound.PLAY_FINISHED;
if (this.onComplete != null) {
this.onComplete(this);
}
this.sendEvent("complete");
this.cleanUp();
},
playFailed:function () {
if (window.createjs == null) {
return;
}
this.playState = createjs.Sound.PLAY_FAILED;
if (this.onPlayFailed != null) {
this.onPlayFailed(this);
}
this.sendEvent("failed");
this.cleanUp();
},
toString:function () {
return "[HTMLAudioPlugin SoundInstance]";
}
}
createjs.EventDispatcher.initialize(SoundInstance.prototype);
// Do not add SoundInstance to namespace.
/**
* An internal helper class that preloads html audio via HTMLAudioElement tags. Note that PreloadJS will NOT use
* this load class like it does Flash and WebAudio plugins.
* Note that this class and its methods are not documented properly to avoid generating HTML documentation.
* #class HTMLAudioLoader
* @param {String} src The source of the sound to load.
* @param {HTMLAudioElement} tag The audio tag of the sound to load.
* @constructor
* @private
* @since 0.4.0
*/
function HTMLAudioLoader(src, tag) {
this.init(src, tag);
}
HTMLAudioLoader.prototype = {
/**
* The source to be loaded.
* #property src
* @type {String}
* @default null
* @protected
*/
src:null,
/**
* The tag to load the source with / into.
* #property tag
* @type {AudioTag}
* @default null
* @protected
*/
tag:null,
/**
* An intervale used to give us progress.
* #property preloadTimer
* @type {String}
* @default null
* @protected
*/
preloadTimer:null,
// Proxies, make removing listeners easier.
loadedHandler:null,
// constructor
init:function (src, tag) {
this.src = src;
this.tag = tag;
this.preloadTimer = setInterval(createjs.proxy(this.preloadTick, this), 200);
// This will tell us when audio is buffered enough to play through, but not when its loaded.
// The tag doesn't keep loading in Chrome once enough has buffered, and we have decided that behaviour is sufficient.
// Note that canplaythrough callback doesn't work in Chrome, we have to use the event.
this.loadedHandler = createjs.proxy(this.sendLoadedEvent, this); // we need this bind to be able to remove event listeners
this.tag.addEventListener && this.tag.addEventListener("canplaythrough", this.loadedHandler);
this.tag.onreadystatechange = createjs.proxy(this.sendLoadedEvent, this); // OJR not 100% sure we need this, just copied from PreloadJS
this.tag.preload = "auto";
this.tag.src = src;
this.tag.load();
},
/**
* Allows us to have preloading progress and tell when its done.
* #method preloadTick
* @protected
*/
preloadTick:function () {
var buffered = this.tag.buffered;
var duration = this.tag.duration;
if (buffered.length > 0) {
if (buffered.end(0) >= duration - 1) {
this.handleTagLoaded();
}
}
},
/**
* Internal handler for when a tag is loaded.
* #method handleTagLoaded
* @protected
*/
handleTagLoaded:function () {
clearInterval(this.preloadTimer);
},
/**
* Communicates back to Sound that a load is complete.
* #method sendLoadedEvent
* @param {Object} evt The load Event
*/
sendLoadedEvent:function (evt) {
this.tag.removeEventListener && this.tag.removeEventListener("canplaythrough", this.loadedHandler); // cleanup and so we don't send the event more than once
this.tag.onreadystatechange = null; // cleanup and so we don't send the event more than once
createjs.Sound.sendLoadComplete(this.src); // fire event or callback on Sound
},
// used for debugging
toString:function () {
return "[HTMLAudioPlugin HTMLAudioLoader]";
}
}
// Do not add HTMLAudioLoader to namespace
/**
* The TagPool is an object pool for HTMLAudio tag instances. In Chrome, we have to pre-create the number of HTML
* audio tag instances that we are going to play before we load the data, otherwise the audio stalls.
* (Note: This seems to be a bug in Chrome)
* #class TagPool
* @param {String} src The source of the channel.
* @private
*/
function TagPool(src) {
this.init(src);
}
/**
* A hash lookup of each sound channel, indexed by the audio source.
* #property tags
* @static
* @private
*/
TagPool.tags = {};
/**
* Get a tag pool. If the pool doesn't exist, create it.
* #method get
* @param {String} src The source file used by the audio tag.
* @static
* @private
*/
TagPool.get = function (src) {
var channel = TagPool.tags[src];
if (channel == null) {
channel = TagPool.tags[src] = new TagPool(src);
}
return channel;
}
/**
* Get a tag instance. This is a shortcut method.
* #method getInstance
* @param {String} src The source file used by the audio tag.
* @static
* @private
*/
TagPool.getInstance = function (src) {
var channel = TagPool.tags[src];
if (channel == null) {
return null;
}
return channel.get();
}
/**
* Return a tag instance. This is a shortcut method.
* #method setInstance
* @param {String} src The source file used by the audio tag.
* @param {HTMLElement} tag Audio tag to set.
* @static
* @private
*/
TagPool.setInstance = function (src, tag) {
var channel = TagPool.tags[src];
if (channel == null) {
return null;
}
return channel.set(tag);
}
TagPool.prototype = {
/**
* The source of the tag pool.
* #property src
* @type {String}
* @private
*/
src:null,
/**
* The total number of HTMLAudio tags in this pool. This is the maximum number of instance of a certain sound
* that can play at one time.
* #property length
* @type {Number}
* @default 0
* @private
*/
length:0,
/**
* The number of unused HTMLAudio tags.
* #property available
* @type {Number}
* @default 0
* @private
*/
available:0,
/**
* A list of all available tags in the pool.
* #property tags
* @type {Array}
* @private
*/
tags:null,
// constructor
init:function (src) {
this.src = src;
this.tags = [];
},
/**
* Add an HTMLAudio tag into the pool.
* #method add
* @param {HTMLAudioElement} tag A tag to be used for playback.
*/
add:function (tag) {
this.tags.push(tag);
this.length++;
this.available++;
},
/**
* Get an HTMLAudioElement for immediate playback. This takes it out of the pool.
* #method get
* @return {HTMLAudioElement} An HTML audio tag.
*/
get:function () {
if (this.tags.length == 0) {
return null;
}
this.available = this.tags.length;
var tag = this.tags.pop();
if (tag.parentNode == null) {
document.body.appendChild(tag);
}
return tag;
},
/**
* Put an HTMLAudioElement back in the pool for use.
* #method set
* @param {HTMLAudioElement} tag HTML audio tag
*/
set:function (tag) {
var index = this.tags.indexOf(tag);
if (index == -1) {
this.tags.push(tag);
}
this.available = this.tags.length;
},
toString:function () {
return "[HTMLAudioPlugin TagPool]";
}
}
// do not add TagPool to namespace
}());
|
DEIPworld/deip-chain
|
libraries/protocol/include/deip/protocol/operations/approve_award_withdrawal_request_operation.hpp
|
<filename>libraries/protocol/include/deip/protocol/operations/approve_award_withdrawal_request_operation.hpp
#pragma once
#include <deip/protocol/base.hpp>
#include <fc/optional.hpp>
namespace deip {
namespace protocol {
struct approve_award_withdrawal_request_operation : public base_operation
{
external_id_type payment_number;
external_id_type award_number;
fc::optional<external_id_type> subaward_number;
account_name_type approver;
extensions_type extensions;
void validate() const;
void get_required_active_authorities(flat_set<account_name_type>& a) const
{
a.insert(approver);
}
};
}
}
FC_REFLECT( deip::protocol::approve_award_withdrawal_request_operation,
(payment_number)
(award_number)
(subaward_number)
(approver)
(extensions)
)
|
justlive1/earth-snow
|
snow-common-base/src/test/java/vip/justlive/common/base/util/ExpiringMapTest.java
|
<reponame>justlive1/earth-snow
package vip.justlive.common.base.util;
import java.util.concurrent.TimeUnit;
import org.junit.Assert;
import org.junit.Test;
import vip.justlive.common.base.util.ExpiringMap.CleanPolicy;
import vip.justlive.common.base.util.ExpiringMap.ExpiringPolicy;
/**
* @author wubo
*/
public class ExpiringMapTest {
@Test
public void test1() throws Exception {
ExpiringMap<String, Integer> expiringMap = ExpiringMap.<String, Integer>builder()
// 默认失效时间 1s
.expiration(1, TimeUnit.SECONDS)
// 累积4次
.accumulateThreshold(4).build();
String key = "key";
expiringMap.put(key, 1);
Assert.assertNotNull(expiringMap.get(key));
TimeUnit.SECONDS.sleep(2);
Assert.assertNull(expiringMap.get(key));
expiringMap.get(key);
expiringMap.get(key);
expiringMap.get(key);
// 等待清理线程执行完毕
TimeUnit.SECONDS.sleep(1);
Assert.assertEquals(0, expiringMap.realSize());
}
@Test
public void test2() throws Exception {
ExpiringMap<String, Integer> expiringMap = ExpiringMap.<String, Integer>builder()
// 默认失效时间 2s
.expiration(2, TimeUnit.SECONDS)
// 访问刷新
.expiringPolicy(ExpiringPolicy.ACCESSED)
// 累积
.accumulateThreshold(4).build();
String key = "key";
String k = "k";
expiringMap.put(key, 1);
expiringMap.put(k, 1);
Assert.assertNotNull(expiringMap.get(key));
Assert.assertNotNull(expiringMap.get(k));
TimeUnit.SECONDS.sleep(1);
Assert.assertNotNull(expiringMap.get(key));
TimeUnit.SECONDS.sleep(1);
Assert.assertNotNull(expiringMap.get(key));
TimeUnit.SECONDS.sleep(1);
Assert.assertNotNull(expiringMap.get(key));
Assert.assertNull(expiringMap.get(k));
}
@Test
public void test3() throws Exception {
ExpiringMap<String, Integer> expiringMap = ExpiringMap.<String, Integer>builder()
// 默认失效时间 2s
.expiration(2, TimeUnit.SECONDS)
// 定时清理任务
.cleanPolicy(CleanPolicy.SCHEDULE)
// 定时任务间隔
.scheduleDelay(3)
// 累积
.accumulateThreshold(4).build();
String key = "key";
expiringMap.put(key, 1);
Assert.assertNotNull(expiringMap.get(key));
TimeUnit.MILLISECONDS.sleep(2100);
Assert.assertNull(expiringMap.get(key));
Assert.assertEquals(1, expiringMap.realSize());
TimeUnit.SECONDS.sleep(2);
Assert.assertEquals(0, expiringMap.realSize());
}
@Test
public void test4() throws Exception {
ExpiringMap<String, Integer> expiringMap = ExpiringMap.<String, Integer>builder()
// 默认失效时间 1s
.expiration(1, TimeUnit.SECONDS)
// 累积4次
.accumulateThreshold(4).build();
String key = "key";
String k = "k";
expiringMap.put(key, 1, 2, TimeUnit.SECONDS);
expiringMap.put(k, 1);
Assert.assertNotNull(expiringMap.get(key));
Assert.assertNotNull(expiringMap.get(k));
TimeUnit.MILLISECONDS.sleep(1100);
Assert.assertNull(expiringMap.get(k));
Assert.assertNotNull(expiringMap.get(key));
TimeUnit.MILLISECONDS.sleep(1100);
Assert.assertNull(expiringMap.get(key));
}
}
|
NAzT/bluetoe
|
tests/test_characteristics.hpp
|
#ifndef BLUETOE_TESTS_CHARACTERISTICS_HPP
#define BLUETOE_TESTS_CHARACTERISTICS_HPP
#include <bluetoe/characteristic_value.hpp>
namespace {
std::uint32_t simple_value = 0xaabbccdd;
const std::uint32_t simple_const_value = 0xaabbccdd;
typedef bluetoe::characteristic<
bluetoe::characteristic_uuid< 0xD0B10674, 0x6DDD, 0x4B59, 0x89CA, 0xA009B78C956B >,
bluetoe::bind_characteristic_value< std::uint32_t, &simple_value >
> simple_char;
typedef bluetoe::characteristic<
bluetoe::characteristic_uuid16< 0xD0B1 >,
bluetoe::bind_characteristic_value< std::uint32_t, &simple_value >
> short_uuid_char;
typedef bluetoe::characteristic<
bluetoe::characteristic_uuid< 0xD0B10674, 0x6DDD, 0x4B59, 0x89CA, 0xA009B78C956B >,
bluetoe::bind_characteristic_value< const std::uint32_t, &simple_const_value >
> simple_const_char;
template < typename Char >
struct read_characteristic_properties : Char
{
read_characteristic_properties()
{
using suuid = bluetoe::service_uuid16< 0x4711 >;
using srv = bluetoe::server<>;
const bluetoe::details::attribute value_attribute = this->template attribute_at< std::tuple<>, 0, bluetoe::service< suuid >, srv >( 0 );
std::uint8_t buffer[ 100 ];
auto read = bluetoe::details::attribute_access_arguments::read( buffer, 0 );
BOOST_REQUIRE( bluetoe::details::attribute_access_result::success == value_attribute.access( read, 1 ) );
properties = buffer[ 0 ];
}
std::uint8_t properties;
};
}
#endif // include guard
|
somehowadev/libmsftband
|
libband/apps/phone.py
|
import struct
from datetime import datetime
from .app import App
from libband.tiles import CALLS
from libband.helpers import bytes_to_text
from libband.parser import MsftBandParser
from libband.filetimes import datetime_to_filetime
from libband.notifications import Notification, NotificationTypes
class CallNotification(Notification):
datetime = None
call_id = None
caller = 'Test Caller'
def __init__(self, guid, call_id, caller):
self.guid = guid
self.call_id = call_id
self.caller = caller
self.datetime = datetime.now()
def serialize(self):
caller = self.caller[:20]
packet = super().serialize()
packet += struct.pack("H", len(caller) * 2)
packet += struct.pack("L", self.call_id)
packet += struct.pack("<Qxx", datetime_to_filetime(self.datetime))
packet += MsftBandParser.serialize_text(caller)
return packet
class IncomingCallNotification(CallNotification):
notification_type = NotificationTypes.IncomingCall
class MissedCallNotification(CallNotification):
notification_type = NotificationTypes.MissedCall
class AnsweredCallNotification(CallNotification):
notification_type = NotificationTypes.AnsweredCall
class HangupCallNotification(CallNotification):
notification_type = NotificationTypes.HangupCall
class VoicemailNotification(CallNotification):
notification_type = NotificationTypes.Voicemail
class PhoneService(App):
app_name = "Phone Service"
guid = CALLS
def answered_call(self, call_id, caller):
self.band.send_notification(AnsweredCallNotification(
self.guid, call_id, caller))
def incoming_call(self, call_id, caller):
self.band.send_notification(IncomingCallNotification(
self.guid, call_id, caller))
def missed_call(self, call_id, caller):
self.band.send_notification(MissedCallNotification(
self.guid, call_id, caller))
def hangup_call(self, call_id, caller):
self.band.send_notification(HangupCallNotification(
self.guid, call_id, caller))
def voicemail(self, call_id, caller):
self.band.send_notification(VoicemailNotification(
self.guid, call_id, caller))
def push(self, guid, command, message):
message = super().push(guid, command, message)
if message:
if message["opcode"] == 348:
call_id = struct.unpack("L", command[4:8])[0]
text = bytes_to_text(command[10:-1])
message["command"] = "reply"
message["call_id"] = call_id
message["text"] = text
return message
|
frk/gosql
|
internal/analysis/error.go
|
package analysis
import (
"fmt"
"strconv"
"strings"
"text/template"
"github.com/frk/tagutil"
)
// analysis error
type anError struct {
Code errorCode
PkgPath string
TargetName string
BlockName string
RelField string
RelType RelType
FieldType string
FieldTypeKind string
FieldName string
// The full tag string.
TagString string
// The specific tag expression that caused the error.
TagExpr string
// The specific tag value that caused the error.
TagError string
// The name of the file in which the error occurs.
FileName string
// The specific line of the file at which the error occurs.
FileLine int
}
func (e *anError) Error() string {
sb := new(strings.Builder)
if err := error_templates.ExecuteTemplate(sb, e.Code.name(), e); err != nil {
panic(err)
}
return sb.String()
}
func (e *anError) FileAndLine() string {
return e.FileName + ":" + strconv.Itoa(e.FileLine)
}
func (e *anError) IsDirective() bool {
return e.FieldName == "_"
}
func (e *anError) IsSelectQueryKind() bool {
return strings.HasPrefix(tolower(e.TargetName), "select")
}
func (e *anError) TagExprIsUnary() bool {
_, _, _, rhs := parsePredicateExpr(e.TagExpr)
return len(rhs) == 0 && e.IsDirective()
}
func (e *anError) TagExprHasRHS() bool {
_, _, _, rhs := parsePredicateExpr(e.TagExpr)
return len(rhs) > 0
}
func (e *anError) TagExprPredicate() string {
_, op, _, _ := parsePredicateExpr(e.TagExpr)
return op
}
func (e *anError) IsSequence() bool {
return e.FieldTypeKind == "slice" || e.FieldTypeKind == "array"
}
func (e *anError) TagValueRel() string {
return tagutil.New(e.TagString).First("rel")
}
func (e *anError) TagValueSql() string {
return tagutil.New(e.TagString).Get("sql")
}
func (e *anError) TagValueSqlFirst() string {
return tagutil.New(e.TagString).First("sql")
}
func (e *anError) TagValueSqlSecond() string {
return tagutil.New(e.TagString).Second("sql")
}
func (e *anError) RelDefinition() string {
return fmt.Sprintf("%s %s", e.RelField, e.RelTypeShort())
}
// Reformats the field type to make it more readable.
func (e *anError) RelTypeShort() string {
// anon struct?
if e.RelType.Base.Name == "" && e.RelType.Base.Kind == TypeKindStruct {
return "struct{ ... }"
}
if e.RelType.Base.PkgPath == e.PkgPath {
return e.RelType.Base.Name
}
return e.RelType.Base.PkgName + "." + e.RelType.Base.Name
if i := strings.LastIndexByte(e.FieldType, '/'); i > -1 {
return e.FieldType[i+1:]
}
return e.FieldType
}
func (e *anError) FieldDefinition() string {
if len(e.TagString) > 0 {
return fmt.Sprintf("%s %s `%s`", e.FieldName, e.FieldTypeShort(), e.TagString)
}
return fmt.Sprintf("%s %s", e.FieldName, e.FieldTypeShort())
}
// Reformats the field type to make it more readable.
func (e *anError) FieldTypeShort() string {
// non-empty anon struct?
if strings.HasPrefix(e.FieldType, "struct{") && e.FieldType != "struct{}" && e.FieldType != "struct{ }" {
return "struct{ ... }"
}
if e.FieldTypePkgPath() == e.PkgPath {
return e.FieldTypeName()
}
if i := strings.LastIndexByte(e.FieldType, '/'); i > -1 {
return e.FieldType[i+1:]
}
return e.FieldType
}
func (e *anError) FieldTypeName() string {
if i := strings.LastIndexByte(e.FieldType, '.'); i > -1 {
return e.FieldType[i+1:]
}
return e.FieldType
}
func (e *anError) FieldTypePkgPath() string {
if i := strings.LastIndexByte(e.FieldType, '.'); i > -1 {
return e.FieldType[:i]
}
return ""
}
func (e *anError) FieldKind() (out string) {
if e.FieldName == "_" {
return "directive"
}
return "field"
}
func (e *anError) TargetXxx() (out string) {
key := tolower(e.TargetName)
if len(key) > 5 {
key = key[:6]
}
switch key {
case "insert":
out = "InsertXxx"
case "update":
out = "UpdateXxx"
case "select":
out = "SelectXxx"
case "delete":
out = "DeleteXxx"
case "filter":
out = "FilterXxx"
default:
out = "<unknown>"
}
return out
}
func (e *anError) TargetKind() (out string) {
key := tolower(e.TargetName)
if len(key) > 5 {
key = key[:6]
}
switch key {
case "insert", "update", "select", "delete":
out = "query"
case "filter":
out = "filter"
default:
out = "<unknown>"
}
return out
}
type errorCode uint8
func (e errorCode) name() string { return fmt.Sprintf("error_template_%d", e) }
const (
_ errorCode = iota
errBadFieldTypeInt
errBadFieldTypeStruct
errBadIterTypeInterface
errBadIterTypeFunc
errBadRelType
errIllegalQueryField
errIllegalStructDirective
errIllegalIteratorField
errConflictingRelTag
errConflictingRelName
errConflictingRelAlias
errConflictingWhere
errConflictingOnConfictTarget
errConflictingOnConfictAction
errConflictingResultTarget
errConflictingRelationDirective
errConflictingFieldOrDirective
errConflictingFilterConstructor
errMissingRelField
errMissingTagValue
errMissingTagColumnList
errMissingOnConflictTarget
errMissingFilterConstructor
errBadIdentTagValue
errBadColIdTagValue
errBadRelIdTagValue
errBadBoolTagValue
errBadUIntegerTagValue
errBadNullsOrderTagValue
errBadOverrideTagValue
errBadDirectiveBooleanExpr
errBadBetweenPredicate
errBadJoinConditionLHS
errIllegalSliceUpdateModifier
errIllegalListPredicate
errIllegalUnaryPredicate
errIllegalFieldQuantifier
errIllegalPredicateQuantifier
errUnknownColumnQualifier
errColumnFieldUnknown
)
var error_template_string = `
{{ define "` + errBadFieldTypeInt.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Bad field type."}}
Cannot use {{R .FieldTypeShort}} as the type of the {{Wb .FieldName}} field in {{Wb .TargetName}}.
{{Wb "FIX:"}} change the field type to one of: {{Ci "int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64"}}.
{{ end }}
{{ define "` + errBadFieldTypeStruct.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Bad field type."}}
Cannot use {{R .FieldTypeShort}} (kind {{R .FieldTypeKind}}) as the type of the {{Wb .FieldName}} field in {{Wb .TargetName}}.
{{Wb "FIX:"}} change the field type to be of kind {{Ci "struct"}}.
{{ end }}
{{ define "` + errBadIterTypeInterface.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Bad iterator interface type."}}
The type {{R .FieldTypeShort}} of the {{.TargetName}}.{{Wb .FieldName}} field {{Wu "IS NOT"}} a valid "{{W "iterator interface"}}" type.
{{Wb "HINT:"}} a valid "{{W "iterator interface"}}" type {{Wu "MUST"}} satisfy all of the following requirements:
- The interface MUST have exactly {{Wu "one"}} method.
- The interface method MUST be {{Wu "accessible"}} from the generated code, i.e. the method must either be exported or, if unexported, the interface type itself must be anonymous or declared in the same package as the target query type.
- The interface method's signature MUST have exactly {{Wu "one parameter"}} type and exactly {{Wu "one result"}} type.
- The interface method's parameter MUST be of a {{Wu "named struct"}} type, or a pointer to a {{Wu "named struct"}} type.
- The interface method's result type MUST be the standard {{Ci "error"}} type.
{{ end }}
{{ define "` + errBadIterTypeFunc.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Bad iterator func type."}}
The type {{R .FieldTypeShort}} of the {{.TargetName}}.{{Wb .FieldName}} field {{Wu "IS NOT"}} a valid "{{W "iterator func"}}" type.
{{Wb "HINT:"}} a valid "{{W "iterator func"}}" type {{Wu "MUST"}} satisfy all of the following requirements:
- The function's signature MUST have exactly {{Wu "one parameter"}} type and exactly {{Wu "one result"}} type.
- The function's parameter MUST be of a {{Wu "named struct"}} type, or a pointer to a {{Wu "named struct"}} type.
- The function's result type MUST be the standard {{Ci "error"}} type.
{{ end }}
{{ define "` + errBadRelType.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Bad \"rel\" type."}}
The type {{R .FieldTypeShort}} of the {{.TargetName}}.{{Wb .FieldName}} field {{Wu "IS NOT"}} a valid "{{W "iterator func"}}" type.
{{Wb "HINT:"}} a valid "{{W "rel"}}" type {{Wu "MUST"}} be one of the following:
- A {{Wu "named or unnamed struct"}} type.
- A {{Wu "pointer to a named struct"}} type.
- A {{Wu "slice of named structs"}} type.
- A {{Wu "slice of pointers to named structs"}} type.
- An {{Wu "array of named structs"}} type.
- An {{Wu "array of pointers to named structs"}} type.
- A valid {{Wu "iterator interface"}} type.
- A valid {{Wu "iterator func"}} type.
{{ end }}
{{ define "` + errIllegalQueryField.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Illegal " .FieldKind "."}}
The {{Wb .TargetXxx}} {{.TargetKind}} types {{Wu "DO NOT"}} support the {{R .FieldDefinition}} {{.FieldKind}}.
{{Wb "FIX:"}} Remove the {{R .FieldDefinition}} {{.FieldKind}} from the {{Wb .TargetName}} {{.TargetKind}} type.
{{ end }}
{{ define "` + errIllegalStructDirective.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Illegal directive field."}}
The {{Wb .BlockName}} struct {{Wu "DOES NOT"}} support the {{R .FieldName}} {{R .FieldTypeShort}} directive.
{{Wb "FIX:"}} Remove the {{R .FieldName}} {{R .FieldTypeShort}} directive from the {{Wb .BlockName}} struct of the {{W .TargetName}} {{.TargetKind}} type.
{{ end }}
{{ define "` + errIllegalIteratorField.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Illegal iterator type field."}}
The {{Wb .TargetXxx}} struct types {{Wu "DO NOT"}} allow for the "rel" field's type to be of the "{{Wi "iterator"}}" kind.
{{Wb "FIX:"}} Change the type of the "{{R .FieldName}} {{R .FieldTypeShort}}" field in {{Wb .TargetName}} to a "{{Wi "non-iterator"}}" kind.
{{ end }}
{{ define "` + errConflictingRelTag.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Conflicting \"rel\" tag."}}
The field {{R .FieldDefinition}} in {{Wb .TargetName}} is in conflict with another field that also has a "{{Wb "rel"}}" tag.
{{Wb "FIX:"}} Make sure that the {{Wb .TargetName}} {{.TargetKind}} type has {{Wu "only one"}} field with the "{{Wb "rel"}}" tag.
{{ end }}
{{ define "` + errConflictingRelAlias.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Conflicting relation alias."}}
The relation alias "{{R .TagError}}" is used more than once in {{Wb .TargetName}} causing a name collision.
{{Wb "HINT:"}} A {{Wi "relation_alias"}} MUST be unique within a query.
{{ end }}
{{ define "` + errConflictingRelName.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Conflicting relation name."}}
The relation name "{{R .TagError}}" is used more than once in {{Wb .TargetName}} causing a name collision.
{{Wb "HINT:"}} A {{Wi "relation_name"}} MUST be unique within a query or it MUST be hidden behind a unique {{Wi "relation_alias"}}.
{{ end }}
{{ define "` + errConflictingWhere.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Conflicting \"where\" fields / directives."}}
{{if .IsDirective -}}
The {{R .FieldTypeShort}} directive in {{Wb .TargetName}} is in conflict with another field or directive.
{{else -}}
The field {{R .FieldName}} (type {{R .FieldTypeShort}}) in {{Wb .TargetName}} is in conflict with another field or directive.
{{end -}}
{{if .IsSelectQueryKind -}}
{{Wb "HINT:"}} The {{Wb .TargetXxx}} query types can have {{Wu "only one"}} WHERE producing field which MUST be one of the following:
- A field of type {{Ci "gosql.Filter"}}.
- A struct field named {{Wu "Where"}} (case insensitive).
{{else -}}
{{Wb "HINT:"}} The {{Wb .TargetXxx}} query types can have {{Wu "only one"}} WHERE producing field or directive which MUST be one of the following:
- A directive field of type {{Ci "gosql.All"}}.
- A field of type {{Ci "gosql.Filter"}}.
- A struct field named {{Wu "Where"}} (case insensitive).
{{end -}}
{{ end }}
{{ define "` + errConflictingOnConfictTarget.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Conflicting \"on conflict\" target directives."}}
The {{R .FieldTypeShort}} directive is in conflict with another "target" directive of the {{Wb .BlockName}} struct in the {{Wb .TargetName}} query type.
{{Wb "HINT:"}} The {{Wb .BlockName}} struct can have {{Wu "only one"}} of the following "target" directives:
- The {{Ci "gosql.Column"}} directive.
- The {{Ci "gosql.Index"}} directive.
- The {{Ci "gosql.Constraint"}} directive.
{{ end }}
{{ define "` + errConflictingOnConfictAction.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Conflicting \"on conflict\" action directives."}}
The {{R .FieldTypeShort}} directive is in conflict with another "action" directive of the {{Wb .BlockName}} struct in the {{Wb .TargetName}} query type.
{{Wb "HINT:"}} The {{Wb .BlockName}} struct can have {{Wu "only one"}} of the following "action" directives:
- The {{Ci "gosql.Ignore"}} directive.
- The {{Ci "gosql.Update"}} directive.
{{ end }}
{{ define "` + errConflictingResultTarget.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Conflicting \"result\" fields / directives."}}
{{if .IsDirective -}}
The {{R .FieldTypeShort}} directive in {{Wb .TargetName}} is in conflict with another "result" field or directive.
{{else -}}
The field {{R .FieldName}} (type {{R .FieldTypeShort}}) in {{Wb .TargetName}} is in conflict with another "result" field or directive.
{{end -}}
{{Wb "HINT:"}} The {{Wb "InsertXxx"}}, {{Wb "UpdateXxx"}}, and {{Wb "DeleteXxx"}} query struct types can have {{Wu "only one"}} of the following:
- The {{Ci "gosql.Return"}} directive.
- A field named {{Wu "RowsAffected"}} (case insensitive) which MUST be of one of the following types: {{Ci "int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64"}}.
- A field named {{Wu "Result"}} (case insensitive) whose type MUST be one of the following:
- A {{Wu "named or unnamed struct"}} type.
- A {{Wu "pointer to a named struct"}} type.
- A {{Wu "slice of named structs"}} type.
- A {{Wu "slice of pointers to named structs"}} type.
- An {{Wu "array of named structs"}} type.
- An {{Wu "array of pointers to named structs"}} type.
- A valid {{Wu "iterator interface"}} type.
- A valid {{Wu "iterator func"}} type.
{{ end }}
{{ define "` + errConflictingRelationDirective.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Conflicting \"gosql.Relation\" directive."}}
The {{R .FieldTypeShort}} directive is in conflict with another directive of the same type.
{{Wb "FIX:"}} Make sure that the {{Wb .BlockName}} struct field in {{Wb .TargetName}} has {{Wu "only one"}} {{R .FieldTypeShort}} directive.
{{ end }}
{{ define "` + errConflictingFieldOrDirective.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Conflicting fields / directives."}}
{{if .IsDirective -}}
The {{R .FieldTypeShort}} directive is in conflict with another field or directive of its "kind".
{{Wb "FIX:"}} Make sure that the {{Wb .TargetName}} struct type has, at most, {{Wu "only one"}} field / directive of the same "kind" as the {{R .FieldTypeShort}} directive.
{{else -}}
The field {{R .FieldName}} (type {{R .FieldTypeShort}}) in {{Wb .TargetName}} is in conflict with another field or directive of its "kind".
{{Wb "FIX:"}} Make sure that the {{Wb .TargetName}} struct type has, at most, {{Wu "only one"}} field / directive of the same "kind" as the {{R .FieldName}} (type {{R .FieldTypeShort}}) field.
{{end -}}
{{ end }}
{{ define "` + errConflictingFilterConstructor.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Conflicting filter constructor field."}}
The field {{R .FieldName}} (type {{R .FieldTypeShort}}) in {{Wb .TargetName}} is in conflict with another field that implements the "gosql.FilterConstructor" interface.
{{Wb "FIX:"}} Make sure that the {{R .TargetName}} struct type has {{Wu "exactly one"}} field that implements the "gosql.FilterConstructor" interface.
{{ end }}
{{ define "` + errMissingRelField.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Missing \"rel\" field."}}
The {{R .TargetName}} struct type has no field with the "rel" tag.
{{Wb "FIX:"}} Make sure that the {{R .TargetName}} struct type has {{Wu "exactly one"}} field with the "rel" tag.
{{ end }}
{{ define "` + errMissingTagValue.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Missing \"sql\" tag value."}}
The {{R .FieldName}} {{R .FieldTypeShort}} field / directive in {{Wb .TargetName}} is missing a value in its "sql" tag, or it is missing the tag completely.
{{Wb "FIX:"}} Make sure that the {{R .FieldName}} {{R .FieldTypeShort}} field / directive in {{Wb .TargetName}} has the "sql" tag with a value that's valid for that field / directive.
{{ end }}
{{ define "` + errMissingTagColumnList.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Missing \"sql\" tag with column list."}}
The {{R .FieldName}} {{R .FieldTypeShort}} field / directive in {{Wb .TargetName}} is missing a list of columns in its "sql" tag, or it is missing the tag completely.
{{Wb "FIX:"}} Make sure that the {{R .FieldName}} {{R .FieldTypeShort}} field / directive in {{Wb .TargetName}} has the "sql" tag with a valid list of columns.
{{ end }}
{{ define "` + errMissingOnConflictTarget.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Missing on_conflict target directive."}}
The {{R .FieldName}} struct field in {{Wb .TargetName}} is missing a "target" directive.
{{Wb "FIX:"}} Make sure that {{R .FieldName}} in {{Wb .TargetName}} has {{Wb "exactly one"}} of the following "target" directives:
- The {{Ci "gosql.Column"}} directive.
- The {{Ci "gosql.Index"}} directive.
- The {{Ci "gosql.Constraint"}} directive.
{{ end }}
{{ define "` + errMissingFilterConstructor.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Missing filter constructor field."}}
The {{R .TargetName}} struct type has no field that implements the "gosql.FilterConstructor" interface.
{{Wb "FIX:"}} Make sure that the {{R .TargetName}} struct type has {{Wu "exactly one"}} field that implements the "gosql.FilterConstructor" interface.
{{ end }}
{{ define "` + errBadIdentTagValue.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Bad identifier value in tag."}}
The "sql" tag value {{R .TagValueSqlFirst}} in {{R .FieldDefinition}} from {{Wb .TargetName}} is an invalid {{Wi "identifier"}}.
{{Wb "HINT:"}} A valid {{Wi "identifier"}} MUST begin with a letter (a-z [case insensitive]) or an underscore (_), ` +
`subsequent characters in the {{Wi "identifier"}} can be letters, underscores, and digits (0-9). Put another way, ` +
`a valid {{Wi "identifier"}} MUST match the following regular expression: {{G ` + "`" + rxIdent.String() + "`" + `}}
{{ end }}
{{ define "` + errBadColIdTagValue.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Bad column_identifier value in tag."}}
The "sql" tag value {{R .TagError}} in {{R .FieldDefinition}} from {{Wb .TargetName}} is an invalid {{Wi "column_identifier"}}.
{{Wb "HINT:"}} A valid {{Wi "column_identifier"}} MUST be of the format {{Wi "[rel_alias.]column_name"}} where ` +
`both the {{Wi "rel_alias"}} and the {{Wi "column_name"}} are valid {{Wi "identifiers"}}. A valid ` +
`{{Wi "identifier"}} MUST begin with a letter (a-z [case insensitive]) or an underscore (_) and any subsequent ` +
`characters in the {{Wi "identifier"}} can be letters, underscores, and digits (0-9). Put another way, a valid ` +
`{{Wi "column_identifier"}} MUST match the following regular expression: {{G ` + "`" + rxColIdent.String() + "`" + `}}
{{ end }}
{{ define "` + errBadRelIdTagValue.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Bad relation_identifier value in tag."}}
The "sql" tag value {{R .TagError}} in {{R .FieldDefinition}} from {{Wb .TargetName}} is an invalid {{Wi "relation_identifier"}}.
{{Wb "HINT:"}} A valid {{Wi "relation_identifier"}} MUST be of the format {{Wi "[schema_name.]relation_name[:alias_name]"}} ` +
`where {{Wi "schema_name"}}, {{Wi "relation_name"}}, and {{Wi "alias_name"}} are all valid {{Wi "identifiers"}}. ` +
`A valid {{Wi "identifier"}} MUST begin with a letter (a-z [case insensitive]) or an underscore (_) and any subsequent ` +
`characters in the {{Wi "identifier"}} can be letters, underscores, and digits (0-9). Put another way, a valid ` +
`{{Wi "relation_identifier"}} MUST match the following regular expression: {{G ` + "`" + rxRelIdent.String() + "`" + `}}
{{ end }}
{{ define "` + errBadBoolTagValue.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Bad boolean value in tag."}}
The "bool" tag value {{R .TagError}} in {{R .FieldDefinition}} from {{Wb .TargetName}} is an invalid {{Wi "boolean"}} value.
{{Wb "HINT:"}} A valid {{Wi "boolean"}} value MUST be either {{G "AND"}} or {{G "OR"}} (case insensitive).
{{ end }}
{{ define "` + errBadUIntegerTagValue.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Bad unsigned_integer value in tag."}}
The "sql" tag value {{R .TagError}} in {{R .FieldDefinition}} from {{Wb .TargetName}} is an invalid {{Wi "unsigned_integer"}} value.
{{Wb "FIX:"}} Change {{R .TagError}} to a valid unsigned integer value.
{{ end }}
{{ define "` + errBadNullsOrderTagValue.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Bad nulls_order value in tag."}}
The "sql" tag value {{R .TagError}} in {{R .FieldDefinition}} from {{Wb .TargetName}} is an invalid {{Wi "nulls_order"}} value.
{{Wb "HINT:"}} A valid {{Wi "nulls_order"}} value MUST be either {{G "NULLSFIRST"}} or {{G "NULLSLAST"}} (case insensitive).
{{ end }}
{{ define "` + errBadOverrideTagValue.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Bad overriding_kind value in tag."}}
The "sql" tag value {{R .TagError}} in {{R .FieldDefinition}} from {{Wb .TargetName}} is an invalid {{Wi "overriding_kind"}} value.
{{Wb "HINT:"}} A valid {{Wi "overriding_kind"}} value MUST be either {{G "USER"}} or {{G "SYSTEM"}} (case insensitive).
{{ end }}
{{ define "` + errBadDirectiveBooleanExpr.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Bad boolean_expression in directive."}}
The expression "{{R .TagError}}" in {{R .FieldDefinition}} from {{W .TargetName}}{{if .BlockName}}.{{Wb .BlockName}}{{end}} ` +
`is an invalid {{Wi "boolean_expression"}} for a directive.
{{Wb "HINT:"}} A valid {{Wi "boolean_expression"}} in a directive MUST be a {{Wu "complete"}} binary or unary expression.
{{ end }}
{{ define "` + errBadBetweenPredicate.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Bad between_predicate type."}}
The {{R .FieldName}} {{R .FieldTypeShort}} field from {{Wb .TargetName}} has an invalid {{Wi "between_predicate"}} type.
{{Wb "FIX:"}} A valid {{Wi "between_predicate"}} type MUST be a {{Ci "struct"}} type that satisfies the following requirements:
- The {{Ci "struct"}} type MUST have {{Wu "exactly two"}} fields, no more and no less.
- One of the fields MUST be tagged with the letter "{{Wb "x"}}" and the other field MUST be tagged with the letter "{{Wb "y"}}" (case insensitive).
- The fields MUST be either of the {{Ci "gosql.Column"}} directive, or they MUST be named and of a normal non-directive type.
{{Wb "EXAMPLE:"}} type T struct {
F int {{raw "sql:\"x\""}}
_ gosql.Column {{raw "sql:\"t.col_name,y\""}}
}
{{ end }}
{{ define "` + errBadJoinConditionLHS.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Bad join_condition LHS."}}
The LHS "{{R .TagError}}" of the "{{R .TagExpr}}" expression in {{R (raw .TagString)}} is not allowed.
{{Wb "HINT:"}} The {{Wb "LHS"}} of a {{Wi "join_condition"}} expression MUST refer to a column of the relation being joined.
{{ end }}
{{ define "` + errIllegalSliceUpdateModifier.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Illegal slice update modifier."}}
The {{R .TargetXxx}} query types with a "rel" field of {{Wb "slice"}} type {{Wu "DO NOT"}} support {{R .FieldDefinition}} {{.FieldKind}}s.
{{Wb "FIX:"}} remove the {{R .FieldDefinition}} {{.FieldKind}} from the {{Wb .TargetName}} query type.
{{ end }}
{{ define "` + errIllegalListPredicate.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Illegal list predicate."}}
The use of a {{Wi "list_predicate"}} with a field of non-sequence type is illegal ({{R .TagError}} in "{{R .TagExpr}}" from the field {{R .FieldDefinition}} in {{W .TargetName}}).
{{Wb "FIX:"}} Change the {{Wi "list_predicate"}} {{R .TagError}} to a non-sequence predicate, or change the {{R .FieldName}} field's type {{R .FieldType}} to a {{Wu "sequence"}} type, i.e. {{Ci "slice"}}, or {{Ci "array"}}.
{{ end }}
{{ define "` + errIllegalUnaryPredicate.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Illegal unary predicate."}}
{{if .IsDirective -}}
The use of a {{Wi "unary_predicate"}} in a {{Wi "binary_expression"}} is illegal ({{R .TagError}} in "{{R .TagExpr}}" from the directive {{R .FieldDefinition}} in {{W .TargetName}}).
{{Wb "FIX:"}} Change the {{Wi "binary_expression"}} "{{R .TagExpr}}" to a valid {{Wi "unary_expression"}}, or replace the {{Wi "unary_predicate"}} {{R .TagError}} with a {{Wi "binary_predicate"}}.
{{else -}}
The use of a {{Wi "unary_predicate"}} is illegal in the tag of a plain field ({{R .TagError}} in "{{R .TagExpr}}" from the field {{R .FieldDefinition}} in {{W .TargetName}}).
{{Wb "FIX:"}} In the expression "{{R .TagExpr}}" remove the {{Wi "unary_predicate"}} {{R .TagError}} or replace it with a {{Wi "binary_predicate"}}.
{{end -}}
{{ end }}
{{ define "` + errIllegalFieldQuantifier.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Illegal field quantifier."}}
The use of a {{Wi "predicate_quantifier"}} with a {{Wu "non-sequence"}} field is illegal ({{R .TagError}} in "{{R .TagExpr}}" from the {{.FieldKind}} {{R .FieldDefinition}} in {{W .TargetName}}).
{{Wb "FIX:"}} Remove the {{Wi "predicate_quantifier"}} {{R .TagError}} from the expression "{{R .TagExpr}}", or change the {{R .FieldName}} field's type {{R .FieldType}} to a {{Wu "sequence"}} type, i.e. {{Ci "slice"}}, or {{Ci "array"}}.
{{ end }}
{{ define "` + errIllegalPredicateQuantifier.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Illegal predicate quantifier."}}
{{if .TagExprIsUnary -}}
The use of a {{Wi "predicate_quantifier"}} in a directive's {{Wi "unary_expression"}} is illegal ({{R .TagError}} in "{{R .TagExpr}}" from the {{.FieldKind}} {{R .FieldDefinition}} in {{W .TargetName}}).
{{else -}}
The use of a {{Wi "predicate_quantifier"}} with a {{Wu "non-quantifiable"}} predicate is illegal ({{R .TagError}} in "{{R .TagExpr}}" from the {{.FieldKind}} {{R .FieldDefinition}} in {{W .TargetName}}).
{{end -}}
{{if (or .TagExprHasRHS (not .IsDirective)) -}}
{{Wb "FIX:"}} Remove the {{Wi "predicate_quantifier"}} {{R .TagError}} from the expression "{{R .TagExpr}}", or change the {{Wu "non-quantifiable"}} predicate {{R .TagExprPredicate}} to a {{Wu "quantifiable"}} one.
{{else -}}
{{Wb "FIX:"}} Remove the {{Wi "predicate_quantifier"}} {{R .TagError}} from the expression "{{R .TagExpr}}".
{{end -}}
{{ end }}
{{ define "` + errUnknownColumnQualifier.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Unknown column qualifier."}}
The column qualifier "{{R .TagError}}" in {{Wb .TargetName}} field {{R .FieldDefinition}} references an unknown, as of yet unspecified relation.
{{Wb "HINT:"}} Make sure that "{{R .TagError}}" does not contain any typos, and that it is referenced {{Wu "after"}} being first specified in the same tag or another tag in the same query.
{{ end }}
{{ define "` + errColumnFieldUnknown.name() + `" -}}
{{Wb .FileAndLine}}: {{Y "Column has no matching field."}}
The column "{{R .TagError}}" referenced in "{{R .FieldDefinition}}" has no matching field in "{{R .RelDefinition}}" type.
{{Wb "HINT:"}} Columns referenced by the {{W .FieldTypeShort}} directive MUST have a matching field in the "{{W "rel"}}" type.
{{ end }}
` // `
var error_templates = template.Must(template.New("t").Funcs(template.FuncMap{
// white color (terminal)
"w": func(v ...string) string { return getcolor("\033[0;37m", v) },
"wb": func(v ...string) string { return getcolor("\033[1;37m", v) },
"wi": func(v ...string) string { return getcolor("\033[3;37m", v) },
"wu": func(v ...string) string { return getcolor("\033[4;37m", v) },
// cyan color (terminal)
"c": func(v ...string) string { return getcolor("\033[0;36m", v) },
"cb": func(v ...string) string { return getcolor("\033[1;36m", v) },
"ci": func(v ...string) string { return getcolor("\033[3;36m", v) },
"cu": func(v ...string) string { return getcolor("\033[4;36m", v) },
/////////////////////////////////////////////////////////////////////////
// High Intensity
/////////////////////////////////////////////////////////////////////////
// red color HI (terminal)
"R": func(v ...string) string { return getcolor("\033[0;91m", v) },
"Rb": func(v ...string) string { return getcolor("\033[1;91m", v) },
"Ri": func(v ...string) string { return getcolor("\033[3;91m", v) },
"Ru": func(v ...string) string { return getcolor("\033[4;91m", v) },
// green color HI (terminal)
"G": func(v ...string) string { return getcolor("\033[0;92m", v) },
"Gb": func(v ...string) string { return getcolor("\033[1;92m", v) },
"Gi": func(v ...string) string { return getcolor("\033[3;92m", v) },
"Gu": func(v ...string) string { return getcolor("\033[4;92m", v) },
// yellow color HI (terminal)
"Y": func(v ...string) string { return getcolor("\033[0;93m", v) },
"Yb": func(v ...string) string { return getcolor("\033[1;93m", v) },
"Yi": func(v ...string) string { return getcolor("\033[3;93m", v) },
"Yu": func(v ...string) string { return getcolor("\033[4;93m", v) },
// blue color HI (terminal)
"B": func(v ...string) string { return getcolor("\033[0;94m", v) },
"Bb": func(v ...string) string { return getcolor("\033[1;94m", v) },
"Bi": func(v ...string) string { return getcolor("\033[3;94m", v) },
"Bu": func(v ...string) string { return getcolor("\033[4;94m", v) },
// cyan color HI (terminal)
"C": func(v ...string) string { return getcolor("\033[0;96m", v) },
"Cb": func(v ...string) string { return getcolor("\033[1;96m", v) },
"Ci": func(v ...string) string { return getcolor("\033[3;96m", v) },
"Cu": func(v ...string) string { return getcolor("\033[4;96m", v) },
// white color HI (terminal)
"W": func(v ...string) string { return getcolor("\033[0;97m", v) },
"Wb": func(v ...string) string { return getcolor("\033[1;97m", v) },
"Wi": func(v ...string) string { return getcolor("\033[3;97m", v) },
"Wu": func(v ...string) string { return getcolor("\033[4;97m", v) },
// no color (terminal)
"off": func() string { return "\033[0m" },
"raw": func(s string) string { return "`" + s + "`" },
"Up": strings.ToUpper,
}).Parse(error_template_string))
func getcolor(c string, v []string) string {
if len(v) > 0 {
return fmt.Sprintf("%s%v\033[0m", c, stringsStringer(v))
}
return c
}
type stringsStringer []string
func (s stringsStringer) String() string {
return strings.Join([]string(s), "")
}
|
MarioHenze/cgv
|
cgv/data/data_format.cxx
|
#include "data_format.h"
#include <iostream>
#include <cgv/utils/tokenizer.h>
#include <cgv/utils/scan.h>
using namespace cgv::utils;
namespace cgv {
namespace data {
/// construct an undefined data format
data_format::data_format()
{
}
/// construct from description string
data_format::data_format(const std::string& description)
{
set_data_format(description);
}
/// set the data format from a description string
bool data_format::set_data_format(const std::string& description)
{
if (description.empty()) {
dimensions.clear();
component_format::clear();
return true;
}
last_error = "";
size_t p = description.find_first_of(']');
if (p == std::string::npos) {
last_error = "no <]> found in description";
return false;
}
if (!component_format::set_component_format(description.substr(0,p+1)))
return false;
std::string sub_descr = description.substr(p+1);
std::vector<token> toks;
tokenizer(sub_descr).set_sep("():|,").bite_all(toks);
if (toks.size() < 3) {
last_error = "incomplete format description";
return false;
}
if (to_string(toks.back()) != ")") {
last_error = "format description not terminated by <)>";
return false;
}
unsigned int i=0;
unsigned int di = 0;
int last_a = 1;
if (to_string(toks[i]) == "|") {
if (!is_integer(to_string(toks[1]), last_a)) {
last_error = "expected integer after <|>";
return false;
}
i += 2;
}
if (to_string(toks[i]) != "(") {
last_error = "expected <(> to define dimensions";
return false;
}
if (++i == toks.size()) {
last_error = "incomplete format description";
return false;
}
dimensions.clear();
do {
int n, ld = di, a = 1;
if (!is_integer(to_string(toks[i]),n)) {
last_error = "expected integer after <(> or <,>";
return false;
}
++i;
if (i+1 < toks.size()) {
if (to_string(toks[i]) == ":") {
if (!is_integer(to_string(toks[i+1]),ld)) {
last_error = "expected integer after <:>";
return false;
}
i += 2;
}
}
if (i+1 < toks.size()) {
if (to_string(toks[i]) == "|") {
if (!is_integer(to_string(toks[i+1]),a)) {
last_error = "expected integer after <:>";
return false;
}
i += 2;
}
}
dimensions.push_back(dimension_info(n,last_a,ld));
last_a = a;
if (to_string(toks[i]) == ")")
return true;
if (to_string(toks[i]) != ",") {
last_error = "expected <,> after definition of dimension";
return false;
}
++i;
++di;
} while (true);
return true;
}
/// construct a 1d data format from width and the information needed to construct a component info
data_format::data_format(unsigned int _width,
TypeId _ct, const std::string& _cnl,
unsigned int a, unsigned int d0, unsigned int d1,
unsigned int d2, unsigned int d3) : component_format(_ct,_cnl,a,d0,d1,d2,d3)
{
dimensions.push_back(dimension_info(_width));
}
/// construct a 1d data format from width and the information needed to construct a component info
data_format::data_format(unsigned int _width,
TypeId _ct, ComponentFormat _cf,
unsigned int a, unsigned int d0, unsigned int d1,
unsigned int d2, unsigned int d3) : component_format(_ct,_cf,a,d0,d1,d2,d3)
{
dimensions.push_back(dimension_info(_width));
}
/// construct a 2d data format from width and height
data_format::data_format(unsigned int _width, unsigned int _height,
TypeId _ct, const std::string& _cnl,
unsigned int a, unsigned int d0, unsigned int d1,
unsigned int d2, unsigned int d3) : component_format(_ct,_cnl,a,d0,d1,d2,d3)
{
dimensions.push_back(dimension_info(_width));
dimensions.push_back(dimension_info(_height,1,1));
}
/// construct a 2d data format from width and height
data_format::data_format(unsigned int _width, unsigned int _height,
TypeId _ct, ComponentFormat _cf,
unsigned int a, unsigned int d0, unsigned int d1,
unsigned int d2, unsigned int d3) : component_format(_ct,_cf,a,d0,d1,d2,d3)
{
dimensions.push_back(dimension_info(_width));
dimensions.push_back(dimension_info(_height,1,1));
}
/// construct a 3d data format from width, height and depth
data_format::data_format(unsigned int _width, unsigned int _height, unsigned int _depth,
TypeId _ct, const std::string& _cnl,
unsigned int a, unsigned int d0, unsigned int d1,
unsigned int d2, unsigned int d3) : component_format(_ct,_cnl,a,d0,d1,d2,d3)
{
dimensions.push_back(dimension_info(_width));
dimensions.push_back(dimension_info(_height,1,1));
dimensions.push_back(dimension_info(_depth,1,2));
}
/// construct a 3d data format from width, height and depth
data_format::data_format(unsigned int _width, unsigned int _height, unsigned int _depth,
TypeId _ct, ComponentFormat _cf,
unsigned int a, unsigned int d0, unsigned int d1,
unsigned int d2, unsigned int d3) : component_format(_ct,_cf,a,d0,d1,d2,d3)
{
dimensions.push_back(dimension_info(_width));
dimensions.push_back(dimension_info(_height,1,1));
dimensions.push_back(dimension_info(_depth,1,2));
}
/// construct a 4d data format from width, height, depth and count
data_format::data_format(unsigned int _width, unsigned int _height,
unsigned int _depth, unsigned int _count,
TypeId _ct, const std::string& _cnl,
unsigned int a, unsigned int d0, unsigned int d1,
unsigned int d2, unsigned int d3) : component_format(_ct,_cnl,a,d0,d1,d2,d3)
{
dimensions.push_back(dimension_info(_width));
dimensions.push_back(dimension_info(_height,1,1));
dimensions.push_back(dimension_info(_depth,1,2));
dimensions.push_back(dimension_info(_count,1,3));
}
/// construct a 4d data format from width, height, depth and count
data_format::data_format(unsigned int _width, unsigned int _height,
unsigned int _depth, unsigned int _count,
TypeId _ct, ComponentFormat _cf,
unsigned int a, unsigned int d0, unsigned int d1,
unsigned int d2, unsigned int d3) : component_format(_ct,_cf,a,d0,d1,d2,d3)
{
dimensions.push_back(dimension_info(_width));
dimensions.push_back(dimension_info(_height,1,1));
dimensions.push_back(dimension_info(_depth,1,2));
dimensions.push_back(dimension_info(_count,1,3));
}
/// set the dimensions to the given values
void data_format::set_dimensions(unsigned _d0, unsigned _d1, unsigned _d2, unsigned _d3)
{
set_width(_d0);
if (_d1 != -1)
set_height(_d1);
if (_d2 != -1)
set_depth(_d2);
if (_d3 != -1)
set_nr_time_steps(_d3);
}
/// return the dimension of the data set
unsigned int data_format::get_nr_dimensions() const
{
return (unsigned int) dimensions.size();
}
/// set the dimension of the data set
void data_format::set_nr_dimensions(unsigned int _d)
{
dimensions.resize(_d);
}
/// return the number of data entries in the given dimension
unsigned int data_format::get_resolution(unsigned int i) const
{
if (i >= get_nr_dimensions())
return 0;
return dimensions[i].resolution;
}
/// set the number of data entries in the given dimension
void data_format::set_resolution(unsigned int i, unsigned int resolution)
{
if (i >= get_nr_dimensions())
dimensions.resize(i+1);
dimensions[i].resolution = resolution;
}
/// return the layout dimension of a given dimension
unsigned int data_format::get_layout_dimension(unsigned int i) const
{
if (i >= get_nr_dimensions())
return i;
return dimensions[i].layout_dimension;
}
/// set the layout dimension of a given dimension
void data_format::get_layout_dimension(unsigned int i, unsigned int layout_dim)
{
if (i >= get_nr_dimensions())
dimensions.resize(i+1);
dimensions[i].layout_dimension = layout_dim;
}
/// return the total number of data entries
unsigned int data_format::get_nr_entries() const
{
unsigned int size = 1;
for (unsigned int i=0; i<get_nr_dimensions(); ++i)
size *= get_resolution(i);
return size;
}
/// return the total number of bytes necessary to store the data
unsigned int data_format::get_nr_bytes() const
{
return get_nr_entries()*get_entry_size();
}
/// return the number of entries in the first dimension
unsigned int data_format::get_width() const
{
return get_resolution(0);
}
/// return the number of entries in the second dimension
unsigned int data_format::get_height() const
{
return get_resolution(1);
}
/// return the number of entries in the third dimension
unsigned int data_format::get_depth() const
{
return get_resolution(2);
}
/// return the number of entries in the last dimension
unsigned int data_format::get_nr_time_steps() const
{
if (get_nr_dimensions() == 0)
return 1;
return get_resolution(get_nr_dimensions()-1);
}
/// return the alignment of entries
unsigned int data_format::get_entry_alignment() const
{
if (get_nr_dimensions() == 0)
return 1;
return dimensions[0].alignment;
}
/// return the alignment of a given dimension
unsigned int data_format::get_alignment(unsigned int i) const
{
if (i+1 >= get_nr_dimensions())
return 1;
return dimensions[i+1].alignment;
}
/// set the number of entries in the first dimension
void data_format::set_width(unsigned int _width)
{
set_resolution(0, _width);
}
/// set the number of entries in the second dimension
void data_format::set_height(unsigned int _height)
{
set_resolution(1, _height);
}
/// set the number of entries in the third dimension
void data_format::set_depth(unsigned int _depth)
{
set_resolution(2, _depth);
}
/// set the number of entries in the last dimension
void data_format::set_nr_time_steps(unsigned int _nr_time_steps)
{
if (get_nr_dimensions() == 0)
return;
set_resolution(get_nr_dimensions()-1, _nr_time_steps);
}
/// set the alignment of entries
void data_format::set_entry_alignment(unsigned int _a)
{
if (get_nr_dimensions() == 0)
dimensions.resize(1);
dimensions[0].alignment = _a;
}
/// set the alignment of a given dimension
void data_format::set_alignment(unsigned int i, unsigned int _a)
{
if (i >= get_nr_dimensions())
dimensions.resize(i+1);
if (i+1 >= get_nr_dimensions())
return;
dimensions[i+1].alignment = _a;
}
/// return the component_format info by simple conversion of the this pointer
const component_format& data_format::get_component_format() const
{
return *static_cast<const component_format*>(this);
}
/// set component_format by simply assigning to a converted this pointer
void data_format::set_component_format(const component_format& cf)
{
*static_cast<component_format*>(this) = cf;
}
/// comparison between component formats
bool data_format::operator == (const data_format& df) const
{
if (get_nr_dimensions() != df.get_nr_dimensions())
return false;
for (unsigned int i=0; i<get_nr_dimensions(); ++i) {
if (get_resolution(i) != df.get_resolution(i))
return false;
if (get_alignment(i) != df.get_alignment(i))
return false;
}
return get_component_format() == df.get_component_format();
}
/// comparison between component formats
bool data_format::operator != (const data_format& df) const
{
return !(*this == df);
}
/// define stream out operator
std::ostream& operator << (std::ostream& os, const data_format& df)
{
os << df.get_component_format();
if (df.get_nr_dimensions() > 0 && df.get_entry_alignment() != 1)
os << '|' << df.get_entry_alignment();
os << "(";
for (unsigned int i=0; i<df.get_nr_dimensions(); ++i) {
if (i > 0)
os << ',';
os << df.get_resolution(i);
if (df.get_layout_dimension(i) != i)
os << ':' << df.get_layout_dimension(i);
if (df.get_alignment(i) != 1)
os << '|' << df.get_alignment(i);
}
return os << ')';
}
}
}
|
rajkishan0/Java_Lab
|
Odd even prog/CheckEvenOdd.java
|
import java.util.Scanner;
class CheckEvenOdd
{
public static void main(String args[])
{
int num;
System.out.println("Enter an integer number");
//The input provided by the user is stored in num
Scanner input=new Scanner (System.in);
num=input.nextInt();
if(num%2==0)
System.out.println("Entered number is even");
else
System.out.println("Entered number is odd");
}
}
|
oxelson/gempak
|
gempak/source/textlib/wbc/wbcdcon.c
|
#include "geminc.h"
#include "gemprm.h"
void wbc_dcon ( char *wtype, int len1, int len2, char *constr,
char *perstr, int *iret )
/************************************************************************
* wbc_dcon *
* *
* This function creates the watch conditions explanation paragraph for *
* severe thunderstorms and tornadoes. This information is used by the *
* SPC's PWN and SEL text products. *
* *
* wbc_dcon ( wtype, len1, len2, constr, perstr, iret ) *
* *
* Input parameters: *
* *wtype char Watch type *
* len1 int Max length of constr *
* len2 int Max length of perstr *
* *
* Output parameters: *
* *constr char CONDITIONS ARE FAVORABLE string *
* *perstr char PERSONS IN THESE AREAS string *
* *iret int Return Code *
* *
** *
* Log: *
* <NAME>/NCEP 5/03 *
* <NAME>/NCEP 10/03 Increased ncpy length 51->52 *
* <NAME>/SAIC 02/04 Removed unused variable hold *
***********************************************************************/
{
int len, ier;
char tmpstr[500];
/*-------------------------------------------------------------------*/
*iret = 0;
tmpstr[0] = '\0';
constr[0] = '\0';
perstr[0] = '\0';
/*
* Create 'CONDITIONS ARE FAVORABLE' string.
*/
tmpstr[0] = '\0';
if ( strcmp(wtype,"SEVERE THUNDERSTORM") == 0 ){
sprintf ( tmpstr, "A %s WATCH MEANS CONDITIONS ARE", wtype);
cst_ncat ( tmpstr, " FAVORABLE FOR SEVERE THUNDERSTORMS", &len, &ier);
}
if ( strcmp(wtype,"TORNADO") == 0 ){
sprintf ( tmpstr, "A %s WATCH MEANS CONDITIONS ARE", wtype);
cst_ncat ( tmpstr, " FAVORABLE FOR TORNADOES AND SEVERE THUNDERSTORMS",
&len, &ier);
}
cst_ncat ( tmpstr, " IN AND CLOSE TO THE WATCH AREA.", &len, &ier);
len = G_MIN ( len1, (int)strlen(tmpstr) );
cst_ncpy ( constr, tmpstr, len, &ier );
/*
* Create 'PERSONS IN THESE AREAS' sstring.
*/
len = 200;
cst_ncpy ( perstr, " PERSONS IN THESE AREAS SHOULD BE ON THE LOOKOUT FOR",
52, &ier);
cst_ncat ( perstr, " THREATENING WEATHER CONDITIONS AND LISTEN FOR LATER",
&len, &ier);
cst_ncat ( perstr, " STATEMENTS AND POSSIBLE WARNINGS.", &len, &ier);
}
|
maritime-web/Enav-Services
|
map-tiles/src/test/java/dk/dma/embryo/tiles/image/Image2TilesUsingMaptilerTest.java
|
<reponame>maritime-web/Enav-Services
/* Copyright (c) 2011 Danish Maritime Authority.
*
* 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 dk.dma.embryo.tiles.image;
import org.apache.commons.io.FileUtils;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* Created by <NAME> on 8/20/14.
*/
public class Image2TilesUsingMaptilerTest {
private File tmp;
private File initDir(File dest, String name) {
File dir = new File(dest, name);
dk.dma.embryo.common.util.FileUtils.createDirectoriesIfNeeded(dir);
return dir;
}
@Before
public void setup() {
File conf = new File(getClass().getResource("/default-configuration.properties").getFile());
File target = conf.getParentFile().getParentFile();
tmp = initDir(target, "tmp");
}
@Test
public void testLogFileDeleter() throws IOException, InterruptedException {
File sourceDir = new File(getClass().getResource("/logs").getFile());
File destDir = new File(tmp, "logs");
FileUtils.deleteQuietly(destDir);
Thread.sleep(50);
FileUtils.copyDirectory(sourceDir, destDir);
Thread.sleep(50);
DateTime limit = DateTime.parse("2014-11-20T00:00:00-00:00");
assertTrue(new File(destDir, "Source_Type_20141119-XX-error.log").exists());
assertTrue(new File(destDir, "Source_Type_20141119-XX-output.log").exists());
assertTrue(new File(destDir, "Source_Type_20141120-XX-error.log").exists());
assertTrue(new File(destDir, "Source_Type_20141120-XX-output.log").exists());
Image2TilesUsingMaptiler.LogFileDeleter deleter = new Image2TilesUsingMaptiler.LogFileDeleter(limit);
deleter.deleteFiles(destDir);
assertFalse(new File(destDir, "Source_Type_20141119-XX-error.log").exists());
assertFalse(new File(destDir, "Source_Type_20141119-XX-output.log").exists());
assertTrue(new File(destDir, "Source_Type_20141120-XX-error.log").exists());
assertTrue(new File(destDir, "Source_Type_20141120-XX-output.log").exists());
}
}
|
lpapp/leetcode
|
binary-tree/solve-problems-recursively/symmetric-tree.cpp
|
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isSymmetric_iterative(TreeNode* root) {
vector<TreeNode*> levelNodes;
if (root) levelNodes.push_back(root);
while (!levelNodes.empty()) {
for (int start = 0, end = levelNodes.size() - 1; start < end; ++start, --end) {
if (!levelNodes[start] and !levelNodes[end]) continue;
else if (!levelNodes[start] or !levelNodes[end] or levelNodes[start]->val != levelNodes[end]->val) return false;
}
vector<TreeNode*> parents = levelNodes;
levelNodes.clear();
for (TreeNode* parent : parents) {
if (parent) { levelNodes.push_back(parent->left); levelNodes.push_back(parent->right); }
}
}
return true;
}
bool isSymmetric_iterative_queue(TreeNode* root) {
queue<TreeNode*> q; q.push(root->left); q.push(root->right);
while (!q.empty()) {
TreeNode* left = q.front(); q.pop();
TreeNode* right = q.front(); q.pop();
if (!left and !right) continue;
if (!left or !right or left->val != right->val) return false;
q.push(left->left); q.push(right->right); q.push(left->right); q.push(right->left);
}
return true;
}
bool isSymmetric_recursive(TreeNode* left, TreeNode* right) {
if (!left and !right) return true;
if (!left or !right or left->val != right->val) return false;
return isSymmetric_recursive(left->left, right->right) and isSymmetric_recursive(left->right, right->left);
}
bool isSymmetric(TreeNode* root) {
return isSymmetric_recursive(root->left, root->right);
}
};
int main()
{
Solution s;
TreeNode* tree1 = new TreeNode(1);
tree1->left = new TreeNode(2);
tree1->right = new TreeNode(2);
tree1->left->left = new TreeNode(3);
tree1->left->right = new TreeNode(4);
tree1->right->left = new TreeNode(4);
tree1->right->right = new TreeNode(3);
cout << "root = [1,2,2,3,4,4,3] => true: " << s.isSymmetric(tree1) << endl;
TreeNode* tree2 = new TreeNode(1);
tree2->left = new TreeNode(2);
tree2->right = new TreeNode(2);
tree2->left->right = new TreeNode(3);
tree2->right->right = new TreeNode(3);
cout << "root = [1,2,2,null,3,null,3] => false: " << s.isSymmetric(tree2) << endl;
TreeNode* tree3 = new TreeNode(1);
cout << "root = [1] => true: " << s.isSymmetric(tree3) << endl;
return 0;
}
|
ArnisLielturks/Urho3D-Project-Template
|
app/src/main/cpp/UI/PopupMessage/PopupMessageWindow.h
|
#pragma once
#include <Urho3D/UI/Button.h>
#include <Urho3D/UI/Window.h>
#include <Urho3D/UI/Text.h>
#include "../BaseWindow.h"
class PopupMessageWindow : public BaseWindow
{
URHO3D_OBJECT(PopupMessageWindow, BaseWindow);
public:
PopupMessageWindow(Context* context);
virtual ~PopupMessageWindow();
virtual void Init() override;
protected:
virtual void Create() override;
private:
void SubscribeToEvents();
SharedPtr<Button> okButton_;
SharedPtr<Window> baseWindow_;
Button* CreateButton(const String& text, int width, IntVector2 position);
Text* CreateLabel(const String& text, int fontSize);
};
|
JoeBuzh/DeepWater
|
dao/test.py
|
# -*- encoding: utf-8 -*-
'''
@Filename : run.py
@Datetime : 2020/09/22 16:59:29
@Author : Joe-Bu
@version : 1.0
'''
""" ORM Test """
import sys
sys.path.append('../')
import traceback
import pandas as pd
from dao.orm.SQLite_dynamic import orm
from dao.orm.SQLite_dynamic import AutoStation, MonSection
from dao.orm.SQLite_dynamic import ObsDataRaw, ObsDataQcLinear
def test():
try:
session = orm.create_session()
# orm test
auto_stat_records = session.query(AutoStation.name, AutoStation.lon, AutoStation.lat).filter_by(provincename='北京市').all()
moni_sect_records = session.query(MonSection.rb_name, MonSection.riverlak, MonSection.rb_code).filter_by(provincename='河北省').all()
raw_records = session.query(ObsDataRaw.time, ObsDataRaw.name, ObsDataRaw.pH, ObsDataRaw.codmn).filter_by(time='2020-08-08 12:00:00').all()
qc_records = session.query(ObsDataQcLinear.time, ObsDataQcLinear.pH, ObsDataQcLinear.tp).filter_by(time='2020-08-08 12:00:00').all()
print(pd.DataFrame(auto_stat_records))
print("*"*66)
print(pd.DataFrame(moni_sect_records))
print("*"*66)
print(pd.DataFrame(raw_records))
print("*"*66)
print(pd.DataFrame(qc_records))
except Exception as e:
traceback.print_exc()
if __name__ == '__main__':
test()
|
FelipePM01/ProjetoMediumWar
|
src/src/peca/Archer.java
|
<reponame>FelipePM01/ProjetoMediumWar
package peca;
import java.awt.Image;
import card.ICardBanco;
import card.ICardJogadorPeca;
import tabuleiro.Tile;
public class Archer extends Ranged{
/**
*
*/
private static final long serialVersionUID = -6369254339259024631L;
private static String[] refImagens= {"assets/archer0.png","assets/archer1.png","assets/archer2.png","assets/archer3.png","assets/archer4.png","assets/archer5.png","assets/archer6.png","assets/archer7.png","assets/archer8.png"};
public Archer(double scale){
super(scale);
setup(4);
}
public Archer(IPeca peca,ICardBanco card) {
super(peca,card);
correction[0]=12;
correction[1]=14;
}
public Archer(IPecaCardBanco peca,ICardJogadorPeca card) {
super(peca,card);
correction[0]=12;
correction[1]=14;
}
public Archer(IPecaCardJogador peca,Tile tile){
super(peca, tile);
setup(2);
correction[0]=6;
correction[1]=4;
flipCorrection=6;
projectileCorrection[0]=22;
projectileCorrection[1]=16;
}
public String toString(){
return "Archer ";
}
private void setup(int x) {
animationFramesMove = new Image[3];
animationFramesAttack = new Image[6];
for(int i=0;i<9;i++){
if(i<3)
animationFramesMove[i]=adjustScale(refImagens[i],x);
else
animationFramesAttack[i-3]=adjustScale(refImagens[i],x);
}
currentFrame = 0;
currentAnimation = animationFramesMove;
speed=2.0;
baseMoveAnimDuration=1000;
setLife(150);
setEndurance(5);
alcance=6;
attackSpeed=2;
baseAttackAnimDuration=1000;
attackDamage=10;
purchaseValue=3;
saleValue=1;
giftValue=2;
maxLife=life;
}
public double[] getCenterPosition() {
return getCenterPosition(12,19);
}
public Projectile create(double scale,double[] posicao,IPecaTile target,double dano,IPecaCardJogador origem) {
return new Arrow(scale,posicao,target,dano,origem);
}
}
|
Hendrikto/jena
|
jena-arq/src/test/java/org/apache/jena/sparql/function/library/TestFnFunctionsString.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jena.sparql.function.library;
import static org.apache.jena.sparql.expr.NodeValue.FALSE;
import static org.apache.jena.sparql.expr.NodeValue.TRUE;
import static org.apache.jena.sparql.expr.NodeValue.nvONE;
import static org.apache.jena.sparql.expr.NodeValue.nvZERO;
import static org.apache.jena.sparql.expr.LibTestExpr.test;
import static org.junit.Assert.fail;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.sparql.expr.Expr;
import org.apache.jena.sparql.expr.ExprEvalException;
import org.apache.jena.sparql.expr.LibTestExpr;
import org.apache.jena.sparql.expr.NodeValue;
import org.apache.jena.sparql.util.ExprUtils;
import org.apache.jena.sys.JenaSystem ;
import org.junit.Test ;
public class TestFnFunctionsString {
static { JenaSystem.init(); }
@Test public void exprStrLen1() { test("fn:string-length('')", nvZERO) ; }
@Test public void exprStrLen2() { test("fn:string-length('a')", nvONE) ; }
// Test from JENA-785
@Test public void exprStrLen3() { test("fn:string-length('𐐈𐑌𐐻𐐪𐑉𐐿𐐻𐐮𐐿𐐲')", NodeValue.makeInteger(10l)) ; }
// F&O strings are one-based, and substring takes a length
@Test public void exprSubstring1() { test("fn:substring('',0)", NodeValue.makeString("")) ; }
@Test public void exprSubstring2() { test("fn:substring('',1)", NodeValue.makeString("")) ; }
@Test public void exprSubstring3() { test("fn:substring('',1,0)", NodeValue.makeString("")) ; }
@Test public void exprSubstring4() { test("fn:substring('',1,1)", NodeValue.makeString("")) ; }
@Test public void exprSubstring5() { test("fn:substring('abc',1)", NodeValue.makeString("abc")) ; }
@Test public void exprSubstring6() { test("fn:substring('abc',2)", NodeValue.makeString("bc")) ; }
@Test public void exprSubstring7() { test("fn:substring('a',1,1)", NodeValue.makeString("a")) ; }
@Test public void exprSubstring8() { test("fn:substring('a',1,2)", NodeValue.makeString("a")) ; }
@Test public void exprSubstring9() { test("fn:substring('a',0)", NodeValue.makeString("")) ; }
// Uses round()
@Test public void exprSubstring10() { test("fn:substring('abc',1.6,1.33)", NodeValue.makeString("b")) ; }
// This test was added because the test suite had 1199 tests in.
@Test public void exprSubstring11() { test("fn:substring('abc',-1, -15.3)", NodeValue.makeString("")) ; }
// Test from JENA-785
@Test public void exprSubstring12() { test("fn:substring('𐐈𐑌𐐻𐐪𐑉𐐿𐐻𐐮𐐿𐐲', 1, 1)", NodeValue.makeString("𐐈")) ; }
@Test public void exprStrStart0() { test("fn:starts-with('abc', '')", TRUE) ; }
@Test public void exprStrStart1() { test("fn:starts-with('abc', 'a')", TRUE) ; }
@Test public void exprStrStart2() { test("fn:starts-with('abc', 'ab')", TRUE) ; }
@Test public void exprStrStart3() { test("fn:starts-with('abc', 'abc')", TRUE) ; }
@Test public void exprStrStart4() { test("fn:starts-with('abc', 'abcd')", FALSE) ; }
@Test public void exprStrEnds0() { test("fn:ends-with('abc', '')", TRUE) ; }
@Test public void exprStrEnds1() { test("fn:ends-with('abc', 'c')", TRUE) ; }
@Test public void exprStrEnds2() { test("fn:ends-with('abc', 'bc')", TRUE) ; }
@Test public void exprStrEnds3() { test("fn:ends-with('abc', 'abc')", TRUE) ; }
@Test public void exprStrEnds4() { test("fn:ends-with('abc', 'zabc')", FALSE) ; }
@Test public void exprStrCase1() { test("fn:lower-case('aBc')", NodeValue.makeString("abc")) ; }
@Test public void exprStrCase2() { test("fn:lower-case('abc')", NodeValue.makeString("abc")) ; }
@Test public void exprStrCase3() { test("fn:upper-case('abc')", NodeValue.makeString("ABC")) ; }
@Test public void exprStrCase4() { test("fn:upper-case('ABC')", NodeValue.makeString("ABC")) ; }
@Test public void exprStrContains0() { test("fn:contains('abc', '')", TRUE) ; }
@Test public void exprStrContains1() { test("fn:contains('abc', 'a')", TRUE) ; }
@Test public void exprStrContains2() { test("fn:contains('abc', 'b')", TRUE) ; }
@Test public void exprStrContains3() { test("fn:contains('abc', 'c')", TRUE) ; }
@Test public void exprStrContains4() { test("fn:contains('abc', 'ab')", TRUE) ; }
@Test public void exprStrContains5() { test("fn:contains('abc', 'bc')", TRUE) ; }
@Test public void exprStrContains6() { test("fn:contains('abc', 'abc')", TRUE) ; }
@Test public void exprStrContains7() { test("fn:contains('abc', 'Xc')", FALSE) ; }
@Test public void exprStrContains8() { test("fn:contains('abc', 'Xa')", FALSE) ; }
@Test public void exprStrNormalizeSpace0() { test("fn:normalize-space(' The wealthy curled darlings of our nation. ')",
NodeValue.makeString("The wealthy curled darlings of our nation.")) ; }
@Test public void exprStrNormalizeSpace1() { test("fn:normalize-space('')",NodeValue.nvEmptyString) ; }
@Test public void exprStrNormalizeSpace2() { test("fn:normalize-space(' Aaa ')",NodeValue.makeString("Aaa")) ; }
@Test public void exprStrNormalizeSpace3() { test("fn:normalize-space('A a a a a ')",NodeValue.makeString("A a a a a")) ; }
// https://www.w3.org/TR/xpath-functions-30/#func-normalize-unicode
// and
// from http://www.unicode.org/reports/tr15/
//l
@Test public void exprStrNormalizeUnicode0() { test("fn:normalize-unicode('Äffin','nfd')",NodeValue.makeString("Äffin")) ; }
@Test public void exprStrNormalizeUnicode1() { test("fn:normalize-unicode('Äffin','nfc')",NodeValue.makeString("Äffin")) ; }
//m
@Test public void exprStrNormalizeUnicode2() { test("fn:normalize-unicode('Ä\\uFB03n','nfd')",NodeValue.makeString("Äffin")) ; }
@Test public void exprStrNormalizeUnicode3() { test("fn:normalize-unicode('Ä\\uFB03n','nfc')",NodeValue.makeString("Äffin")) ; }
//n
@Test public void exprStrNormalizeUnicode4() { test("fn:normalize-unicode('Henry IV','nfd')",NodeValue.makeString("Henry IV")) ; }
@Test public void exprStrNormalizeUnicode5() { test("fn:normalize-unicode('Henry IV','nfc')",NodeValue.makeString("Henry IV")) ; }
//l'
@Test public void exprStrNormalizeUnicode6() { test("fn:normalize-unicode('Äffin','nfkd')",NodeValue.makeString("Äffin")) ; }
@Test public void exprStrNormalizeUnicode7() { test("fn:normalize-unicode('Äffin','nfkc')",NodeValue.makeString("Äffin")) ; }
// r
String hw_ka="\uFF76";
String hw_ten="\uFF9F";
@Test public void exprStrNormalizeUnicode8() { test("fn:normalize-unicode('"+hw_ka+hw_ten+"','nfd')",NodeValue.makeString(hw_ka+hw_ten)) ; }
@Test public void exprStrNormalizeUnicode9() {
test("fn:normalize-unicode('"+hw_ka+hw_ten+"','nfc')",NodeValue.makeString(hw_ka+hw_ten)) ;
}
// Not sure why the following tests are not passing
// both examples are taken from the http://www.unicode.org/reports/tr15/ (Table 8 r')
// the translation of hw_ka,hw_ten,ka and ten are taken from Table 4 of the same document
//
// I (<NAME>) took the ga translation by association (it was not defined in the unicode report)
// and chosen to be: KATAKANA LETTER GA U+30AC
// Everything seems ok to me so there are two options in my opinion:
// 1) the java implementation of the nfkd has some flaws
// 2) the unicode example is wrong (I cannot judge as I do not know japanese or unicode enough :))
// The test is failing because the expected string has code when looking in the debugger (UTF-16?) (12459 | 12442)
// while the Nomalizer.normalize is giving (12459 | 12441)
// @Test public void exprStrNormalizeUnicode10() {
// String ka = "\u30AB";
// String ten="\u3099";
// test("fn:normalize-unicode('"+hw_ka+hw_ten+"','nfkd')", NodeValue.makeString(ka+ten)) ;
// }
// @Test public void exprStrNormalizeUnicode11() {
// String ga="\u30AC";
// test("fn:normalize-unicode('"+hw_ka+hw_ten+"','nfkc')",NodeValue.makeString(ga)) ;
// }
// empty argument <-> returns the input string
@Test public void exprStrNormalizeUnicode12() { test("fn:normalize-unicode('some word','')",NodeValue.makeString("some word")) ; }
// one argument <-> NFC
@Test public void exprStrNormalizeUnicode13() { test("fn:normalize-unicode('Äffin')",NodeValue.makeString("Äffin")) ; }
@Test public void exprFnReplace01() { test("fn:replace('abc', 'b', 'Z')", NodeValue.makeString("aZc")) ; }
@Test public void exprFnReplace02() { test("fn:replace('abc', 'b.', 'Z')", NodeValue.makeString("aZ")) ; }
@Test public void exprFnReplace03() { test("fn:replace('abcbd', 'b.', 'Z')", NodeValue.makeString("aZZ")) ; }
@Test public void exprFnReplace04() { test("fn:replace('abcbd'^^xsd:string, 'b.', 'Z')", NodeValue.makeNode("aZZ", XSDDatatype.XSDstring)) ; }
@Test public void exprFnReplace05() { test("fn:replace('abcbd'@en, 'b.', 'Z')", NodeValue.makeNode("aZZ", "en", (String)null)) ; }
@Test public void exprFnReplace06() { test("fn:replace('abcbd', 'B.', 'Z', 'i')", NodeValue.makeString("aZZ")) ; }
// Bad pattern : dynamic (eval time) exception.
// The pattern for fn:replace is not compiled on build - if that changes, this test will fail.
// See exprReplace14.
@Test
public void exprReplace15() {
testEvalException("fn:replace('abc', '^(a){-9}', 'ABC')");
}
private void testEvalException(String exprStr) {
Expr expr = ExprUtils.parse(exprStr) ;
try {
NodeValue r = expr.eval(null, LibTestExpr.createTest()) ;
fail("No exception raised") ;
}
catch (ExprEvalException ex) {}
}
}
|
a-shah8/LeetCode
|
Easy/746_minCostClimbingStairs.py
|
<filename>Easy/746_minCostClimbingStairs.py
class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
for i in range(len(cost)-3, -1, -1):
cost[i] += min(cost[i+1], cost[i+2])
return min(cost[0], cost[1])
|
tbnorth/flexx
|
flexxamples/demos/d3_collision.py
|
# doc-export: CollisionWidget
"""
Example using 3D. Adapted from a demo by <NAME>.
"""
from flexx import flx
from pscript import RawJS
from pscript.stubs import Math, d3, window
flx.assets.associate_asset(__name__, 'https://d3js.org/d3.v3.min.js')
class CollisionWidget(flx.Widget):
""" A widget showing a collision demo based on D3.
"""
CSS = """
.flx-CollisionWidget {
background: #fff;
border: 1px solid black;
border-radius: 6px;
}
"""
def init(self):
self.node.id = self.id
window.setTimeout(self.load_viz, 500)
@flx.reaction
def _resize(self):
w, h = self.size
if len(self.node.children) > 0:
svg = self.node.children[0]
svg.setAttribute('width', w)
svg.setAttribute('height', h)
def load_viz(self):
w, h = self.size
nodes = d3.range(200).map(lambda: {'radius': Math.random() * 12 + 4})
color = d3.scale.category10()
force = d3.layout.force().gravity(0.05).charge(lambda d, i: 0 if i else -2000)\
.nodes(nodes).size([w, h])
root = nodes[0]
root.radius = 0
root.fixed = True
force.start()
x = d3.select('#' + self.id)
print(x, self.id)
svg = RawJS('x.append("svg").attr("width", w).attr("height", h)')
x = RawJS(
'svg.selectAll("circle").data(nodes.slice(1)).enter().append("circle")')
x.attr("r", lambda d: d.radius).style("fill", lambda d, i: color(i % 3))
def on_tick(e):
q = d3.geom.quadtree(nodes)
i = 0
n = nodes.length
while i < n-1:
i += 1
q.visit(collide(nodes[i]))
svg.selectAll("circle").attr("cx", lambda d: d.x).attr("cy", lambda d: d.y)
force.on("tick", on_tick)
def on_mousemove():
p1 = d3.mouse(self.node)
root.px = p1[0]
root.py = p1[1]
force.resume()
svg.on("mousemove", on_mousemove)
def collide(node):
r = node.radius + 16
nx1 = node.x - r
nx2 = node.x + r
ny1 = node.y - r
ny2 = node.y + r
def func(quad, x1, y1, x2, y2):
if quad.point and quad.point is not node:
x = node.x - quad.point.x
y = node.y - quad.point.y
s = Math.sqrt(x * x + y * y)
r = node.radius + quad.point.radius
if (s < r):
s = (s - r) / s * .5
x *= s
y *= s
node.x -= x
node.y -= y
quad.point.x += x
quad.point.y += y
return x1 > nx2 or x2 < nx1 or y1 > ny2 or y2 < ny1
return func
class CollisionDemo(flx.Widget):
def init(self):
with flx.VSplit():
with flx.HSplit():
CollisionWidget()
CollisionWidget()
with flx.HSplit():
CollisionWidget()
CollisionWidget()
if __name__ == '__main__':
flx.launch(CollisionDemo, 'app')
flx.run()
|
PyDee/Spiders
|
jsparse/meijiexia/url_file.py
|
<reponame>PyDee/Spiders
mjx_weibo = [
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=1',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=2',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=3',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=4',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=5',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=6',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=7',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=8',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=9',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=10',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=11',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=12',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=13',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=14',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=15',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=16',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=17',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=18',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=19',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=20',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=21',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=22',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=23',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=24',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=25',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=26',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=27',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=28',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=29',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=30',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=31',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=32',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=33',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=34',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=35',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=36',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=37',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=38',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=39',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=40',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=41',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=42',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=43',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=44',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=45',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=46',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=47',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=48',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=49',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=50',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=51',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=52',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=53',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=54',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=55',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=56',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=57',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=58',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=59',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=60',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=61',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=62',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=63',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=64',
'https://www.meijiexia.com/medias-76-0-0-0_0.html?time=&fans=&price=&pro=&per_page=65',
]
mjx_dy = [
'https://www.meijiexia.com/medias-424-0-0-0_0.html?time=&fans=&price=&pro=&per_page=1',
'https://www.meijiexia.com/medias-424-0-0-0_0.html?time=&fans=&price=&pro=&per_page=2',
'https://www.meijiexia.com/medias-424-0-0-0_0.html?time=&fans=&price=&pro=&per_page=3',
'https://www.meijiexia.com/medias-424-0-0-0_0.html?time=&fans=&price=&pro=&per_page=4',
'https://www.meijiexia.com/medias-424-0-0-0_0.html?time=&fans=&price=&pro=&per_page=5',
]
mjx_ks = [
'https://www.meijiexia.com/medias-605-0-0-0_0.html?time=&fans=&price=&pro=&per_page=1',
'https://www.meijiexia.com/medias-605-0-0-0_0.html?time=&fans=&price=&pro=&per_page=2',
'https://www.meijiexia.com/medias-605-0-0-0_0.html?time=&fans=&price=&pro=&per_page=3',
'https://www.meijiexia.com/medias-605-0-0-0_0.html?time=&fans=&price=&pro=&per_page=4',
'https://www.meijiexia.com/medias-605-0-0-0_0.html?time=&fans=&price=&pro=&per_page=5',
'https://www.meijiexia.com/medias-605-0-0-0_0.html?time=&fans=&price=&pro=&per_page=6',
'https://www.meijiexia.com/medias-605-0-0-0_0.html?time=&fans=&price=&pro=&per_page=7',
'https://www.meijiexia.com/medias-605-0-0-0_0.html?time=&fans=&price=&pro=&per_page=8',
'https://www.meijiexia.com/medias-605-0-0-0_0.html?time=&fans=&price=&pro=&per_page=9',
]
mjx_xhs = [
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=1',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=2',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=3',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=4',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=5',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=6',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=7',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=8',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=9',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=10',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=11',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=12',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=13',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=14',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=15',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=16',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=17',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=18',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=19',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=20',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=21',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=22',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=23',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=24',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=25',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=26',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=27',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=28',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=29',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=30',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=31',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=32',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=33',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=34',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=35',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=36',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=37',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=38',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=39',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=40',
'https://www.meijiexia.com/medias-425-0-0-0_0.html?time=&fans=&price=&pro=&per_page=41',
]
|
Benbentwo/jx
|
pkg/jx/cmd/step/create/step_create_jenkins_config.go
|
<gh_stars>1-10
package create
import (
"fmt"
"github.com/jenkins-x/jx/pkg/jx/cmd/helper"
"io/ioutil"
"strings"
"github.com/jenkins-x/jx/pkg/jx/cmd/opts"
"github.com/jenkins-x/jx/pkg/jx/cmd/templates"
"github.com/jenkins-x/jx/pkg/kube"
"github.com/jenkins-x/jx/pkg/log"
"github.com/jenkins-x/jx/pkg/util"
"github.com/pkg/errors"
"github.com/spf13/cobra"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
var (
createJenkinsConfigLong = templates.LongDesc(`
Creates the Jenkins config.xml file from a number of ConfigMaps for Pod Templates
`)
createJenkinsConfigExample = templates.Examples(`
jx step create jenkins config
`)
)
// StepCreateJenkinsConfigOptions contains the command line flags
type StepCreateJenkinsConfigOptions struct {
opts.StepOptions
Output string
}
// NewCmdStepCreateJenkinsConfig Creates a new Command object
func NewCmdStepCreateJenkinsConfig(commonOpts *opts.CommonOptions) *cobra.Command {
options := &StepCreateJenkinsConfigOptions{
StepOptions: opts.StepOptions{
CommonOptions: commonOpts,
},
}
cmd := &cobra.Command{
Use: "jenkins config",
Short: "Creates the Jenkins config.xml file from a number of ConfigMaps for Pod Templates",
Long: createJenkinsConfigLong,
Example: createJenkinsConfigExample,
Run: func(cmd *cobra.Command, args []string) {
options.Cmd = cmd
options.Args = args
err := options.Run()
helper.CheckErr(err)
},
}
cmd.Flags().StringVarP(&options.Output, "output", "o", "config.xml", "the output file generated")
return cmd
}
// Run implements this command
func (o *StepCreateJenkinsConfigOptions) Run() error {
kubeClient, ns, err := o.KubeClientAndDevNamespace()
if err != nil {
return err
}
configMapInterface := kubeClient.CoreV1().ConfigMaps(ns)
selector := kube.LabelKind + "=" + kube.ValueKindPodTemplateXML
list, err := configMapInterface.List(metav1.ListOptions{
LabelSelector: selector,
})
if err != nil {
return errors.Wrapf(err, "failed to load Pod Template XML ConfigMaps with selector %s in namespace %s", selector, ns)
}
cmName := kube.SecretJenkins
cm, err := configMapInterface.Get(cmName, metav1.GetOptions{})
if err != nil {
return errors.Wrapf(err, "failed to load ConfigMap %s in namespace %s", cmName, ns)
}
configXml := ""
if cm.Data != nil {
configXml = cm.Data["config.xml"]
}
if configXml == "" {
return fmt.Errorf("no config.xml key in ConfigMap %s in namespace %s", cmName, ns)
}
var buffer strings.Builder
found := false
lines := strings.Split(configXml, "\n")
for _, line := range lines {
buffer.WriteString(line)
buffer.WriteString("\n")
if strings.TrimSpace(line) == "<templates>" && !found {
found = true
for _, cm := range list.Items {
data := cm.Data
if data != nil {
configXML := data["config.xml"]
if configXML != "" {
for _, cl := range strings.Split(configXML, "\n") {
buffer.WriteString(" ")
buffer.WriteString(cl)
buffer.WriteString("\n")
}
}
}
}
}
}
fileXML := buffer.String()
err = ioutil.WriteFile(o.Output, []byte(fileXML), util.DefaultWritePermissions)
if err != nil {
return errors.Wrapf(err, "failed to write file %s", o.Output)
}
log.Infof("generated Jenkins configuration file %s\n", util.ColorInfo(o.Output))
return nil
}
|
Cajivah/streamacho
|
server/meeting/src/main/java/com/streamacho/meeting/config/web/SpringWebMvcConfig.java
|
<filename>server/meeting/src/main/java/com/streamacho/meeting/config/web/SpringWebMvcConfig.java
package com.streamacho.meeting.config.web;
import com.streamacho.meeting.config.converter.StringToRoomStatusConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class SpringWebMvcConfig implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new StringToRoomStatusConverter());
}
}
|
ziocleto/trends.bar
|
projects/trends.bar/src/components/dashboardProject/subcomponents/DataSources/DataSourcesCreatorLogic.js
|
<reponame>ziocleto/trends.bar<filename>projects/trends.bar/src/components/dashboardProject/subcomponents/DataSources/DataSourcesCreatorLogic.js
import {api, useApi} from "../../../../futuremodules/api/apiEntryPoint";
import {addNewScript} from "../../../../futuremodules/fetch/fetchApiCalls";
import {useEffect} from "react";
import {editingDataSourceD} from "../../../dashboardUser/DashboardUserLogic";
export const useGatherSource = (layout, setLayout, dispatch) => {
const fetchApi = useApi('fetch');
const fetchResult = fetchApi[0];
const fetchDispatch = fetchApi[1];
useEffect(() => {
if ( fetchResult && fetchResult.ret ) {
console.log("Redraw useGatherSource", fetchResult.ret);
dispatch([editingDataSourceD, fetchResult.ret]);
fetchDispatch(null);
}
},
[fetchResult, fetchDispatch, dispatch]
);
const updater = (sourceDocument) => {
api(fetchApi, addNewScript, {url: sourceDocument, trendId: layout.trendId}).then();
};
return updater;
};
|
CiscoISE/terraform-provider-ciscoise
|
ciscoise/logger.go
|
<reponame>CiscoISE/terraform-provider-ciscoise
package ciscoise
import (
"log"
"os"
)
func createLogger() *logger {
l := &logger{l: log.New(os.Stderr, "", log.LstdFlags)}
return l
}
type logger struct {
l *log.Logger
}
func (l *logger) Errorf(format string, v ...interface{}) {
log.Printf("[ERROR] [RESTY] "+format, v...)
}
func (l *logger) Warnf(format string, v ...interface{}) {
log.Printf("[WARN] [RESTY] "+format, v...)
}
func (l *logger) Debugf(format string, v ...interface{}) {
log.Printf("[DEBUG] [RESTY] "+format, v...)
}
|
Kuangcp/kcp-tool-java
|
kcp-aop/src/main/java/com/github/kuangcp/aop/proxy/JdkProxyFactory.java
|
<filename>kcp-aop/src/main/java/com/github/kuangcp/aop/proxy/JdkProxyFactory.java
package com.github.kuangcp.aop.proxy;
import com.github.kuangcp.aop.ProxyUtil;
import com.github.kuangcp.aop.aspect.Aspect;
import com.github.kuangcp.aop.interceptor.JDKInterceptor;
/**
* @author https://github.com/kuangcp on 2019-10-06 18:30
*/
public class JdkProxyFactory extends ProxyFactory {
private static final long serialVersionUID = -817544713057450519L;
@Override
@SuppressWarnings("unchecked")
public <T> T proxy(T target, Aspect aspect) {
ClassLoader classLoader = target.getClass().getClassLoader();
JDKInterceptor interceptor = new JDKInterceptor(target, aspect);
Class<?>[] interfaces = target.getClass().getInterfaces();
return (T) ProxyUtil.newProxyInstance(classLoader, interceptor, interfaces);
}
}
|
bitcrystal/edk
|
Sample/Universal/Network/PxeBc/Dxe/hton.h
|
<gh_stars>10-100
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module name:
hton.h
Abstract:
Byte swapping macros.
--*/
#ifndef _HTON_H_
#define _HTON_H_
//
// Only Intel order functions are defined at this time.
//
#define HTONS(v) (UINT16) ((((v) << 8) & 0xff00) + (((v) >> 8) & 0x00ff))
#define HTONL(v) \
(UINT32) ((((v) << 24) & 0xff000000) + (((v) << 8) & 0x00ff0000) + (((v) >> 8) & 0x0000ff00) + (((v) >> 24) & 0x000000ff))
#define HTONLL(v) swap64 (v)
#define U8PTR(na) ((UINT8 *) &(na))
#define NTOHS(ns) ((UINT16) (((*U8PTR (ns)) << 8) +*(U8PTR (ns) + 1)))
#define NTOHL(ns) \
((UINT32) (((*U8PTR (ns)) << 24) + ((*(U8PTR (ns) + 1)) << 16) + ((*(U8PTR (ns) + 2)) << 8) +*(U8PTR (ns) + 3)))
#endif /* _HTON_H_ */
/* EOF - hton.h */
|
uk-gov-mirror/hmcts.div-petitioner-frontend
|
app/core/middleware/loadContent.test.js
|
const { expect } = require('test/util/chai');
const loadContent = require('app/core/middleware/loadContent');
const commonContent = require('app/middleware/commonContent');
const test = (step, block) => {
const req = { session: { language: 'en' } };
const res = { locals: {} };
const next = () => {
block(req, res);
};
commonContent(req, res, () => {
loadContent.bind(step)(req, res, next);
});
};
const contentBlock = content => {
return { resources: { en: { translation: { content } } } };
};
describe('loadContent middleware', () => {
it('loads content from the step in to i18n', done => {
const step = { content: contentBlock({ foo: 'foo is Foo' }) };
test(step, req => {
expect(req.i18n.t('foo')).to.eq('foo is Foo');
done();
});
});
it('does not error when no content is provided', done => {
const step = {};
test(step, req => {
expect(req.i18n.t('bar')).to.eq('bar');
done();
});
});
});
|
netx-ulx/varanus
|
utils/src/main/java/net/varanus/util/functional/functions/ExceptionalFunction.java
|
package net.varanus.util.functional.functions;
import java.util.Objects;
/**
* @param <T>
* @param <R>
* @param <X>
*/
@FunctionalInterface
public interface ExceptionalFunction<T, R, X extends Throwable>
{
public R apply( T t ) throws X;
public default <V> ExceptionalFunction<V, R,
X> compose( ExceptionalFunction<? super V, ? extends T, ? extends X> before )
{
Objects.requireNonNull(before);
return ( V v ) -> apply(before.apply(v));
}
public default <V> ExceptionalFunction<T, V,
X> andThen( ExceptionalFunction<? super R, ? extends V, ? extends X> after )
{
Objects.requireNonNull(after);
return ( T t ) -> after.apply(apply(t));
}
public static <T, X extends Throwable> ExceptionalFunction<T, T, X> identity()
{
return t -> t;
}
}
|
SferaDev/XDADevCon
|
android/src/main/java/com/google/samples/apps/iosched/nearby/MetadataResolver.java
|
<reponame>SferaDev/XDADevCon
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.nearby;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.util.Log;
import android.util.Patterns;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.google.samples.apps.iosched.Config.METADATA_URL;
import static com.google.samples.apps.iosched.util.LogUtils.makeLogTag;
/**
* Class for resolving BLE device metadata via proxy.
*/
public class MetadataResolver {
static String TAG = makeLogTag("MetadataResolver");
static Map<String, String> mDeviceUrlMap;
static RequestQueue mRequestQueue;
static boolean mIsInitialized = false;
public static void initialize(Context context) {
mDeviceUrlMap = new HashMap<String, String>();
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(context);
}
mIsInitialized = true;
}
public static String getURLForDevice(NearbyDevice device) {
if (!mIsInitialized) {
Log.e(TAG, "Not initialized.");
return null;
}
// If the device name is already a URL, use it.
String deviceName = device.getName();
String url = deviceName;
if (Patterns.WEB_URL.matcher(deviceName).matches()) {
// TODO: Improve this.
// For now, if there's no scheme present, add a default http:// scheme.
if (!url.startsWith("http://") && !url.startsWith("https://")) {
url = "http://" + url;
}
} else {
// Otherwise, try doing the lookup.
url = mDeviceUrlMap.get(deviceName);
}
return url;
}
public static void getBatchMetadata(List<NearbyDevice> batchList) {
if (!mIsInitialized) {
Log.e(TAG, "Not initialized.");
return;
}
JSONObject jsonObj = createRequestObject(batchList);
Map<String, NearbyDevice> deviceMap = new HashMap<String, NearbyDevice>();
for (int i = 0; i < batchList.size(); i++) {
NearbyDevice nearbyDevice = batchList.get(i);
deviceMap.put(nearbyDevice.getUrl(), nearbyDevice);
}
JsonObjectRequest jsObjRequest = createMetadataRequest(jsonObj, deviceMap);
// Queue the request
mRequestQueue.add(jsObjRequest);
}
private static JsonObjectRequest createMetadataRequest(JSONObject jsonObj, final Map<String, NearbyDevice> deviceMap) {
return new JsonObjectRequest(
METADATA_URL,
jsonObj,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonResponse) {
try {
JSONArray foundMetaData = jsonResponse.getJSONArray("metadata");
int deviceCount = foundMetaData.length();
for (int i = 0; i < deviceCount; i++) {
JSONObject deviceData = foundMetaData.getJSONObject(i);
String title = "Unknown name";
String url = "Unknown url";
String description = "Unknown description";
String iconUrl = "/favicon.ico";
String id = deviceData.getString("id");
if (deviceData.has("title")) {
title = deviceData.getString("title");
}
if (deviceData.has("url")) {
url = deviceData.getString("url");
}
if (deviceData.has("description")) {
description = deviceData.getString("description");
}
if (deviceData.has("icon")) {
// We might need to do some magic here.
iconUrl = deviceData.getString("icon");
}
// Provisions for a favicon specified as a relative URL.
if (!iconUrl.startsWith("http")) {
// Lets just assume we are dealing with a relative path.
Uri fullUri = Uri.parse(url);
Uri.Builder builder = fullUri.buildUpon();
// Append the default favicon path to the URL.
builder.path(iconUrl);
iconUrl = builder.toString();
}
DeviceMetadata deviceMetadata = new DeviceMetadata();
deviceMetadata.title = title;
deviceMetadata.description = description;
deviceMetadata.siteUrl = url;
deviceMetadata.iconUrl = iconUrl;
downloadIcon(deviceMetadata, deviceMap.get(id));
// Look up the device from the input and update the data
deviceMap.get(id).onDeviceInfo(deviceMetadata);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
Log.i(TAG, "VolleyError: " + volleyError.toString());
}
}
);
}
private static JSONObject createRequestObject(List<NearbyDevice> devices) {
JSONObject jsonObj = new JSONObject();
try {
JSONArray urlArray = new JSONArray();
for(int dIdx = 0; dIdx < devices.size(); dIdx++) {
NearbyDevice device = devices.get(dIdx);
JSONObject urlObject = new JSONObject();
urlObject.put("url", device.getUrl());
urlObject.put("rssi", device.getLastRSSI());
urlArray.put(urlObject);
}
JSONObject location = new JSONObject();
location.put("lat", 49.129837);
location.put("lon", 120.38142);
jsonObj.put("location", location);
jsonObj.put("objects", urlArray);
} catch(JSONException ignored) {
}
return jsonObj;
}
/**
* Asynchronously download the image for the nearby device.
* @param metadata
* @param listener
*/
private static void downloadIcon(final DeviceMetadata metadata, final OnMetadataListener listener) {
ImageRequest imageRequest = new ImageRequest(metadata.iconUrl, new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap response) {
Log.i(TAG, "Got an image: " + response.toString());
metadata.icon = response;
listener.onDeviceInfo(metadata);
}
}, 0, 0, null, null);
mRequestQueue.add(imageRequest);
}
public interface OnMetadataListener {
public void onDeviceInfo(DeviceMetadata deviceMetadata);
}
}
|
HongZhaoHua/jstarcraft-dataset
|
src/main/java/com/jstarcraft/crawler/trade/security/bond/essence/EssenceIssueBond.java
|
<gh_stars>1-10
package com.jstarcraft.crawler.trade.security.bond.essence;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.noear.snack.ONode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import com.jstarcraft.core.common.conversion.json.JsonUtility;
import com.jstarcraft.core.utility.StringUtility;
import com.jstarcraft.crawler.trade.security.IssueSecurity;
import jodd.net.URLDecoder;
/**
* 安信新债
*
* 新债日历:https://www.essence.com.cn/service/sharesandbonds
*
* @author Birdy
*
*/
public class EssenceIssueBond implements IssueSecurity {
protected static final Logger logger = LoggerFactory.getLogger(EssenceIssueBond.class);
protected static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
/** 新债列表模板 */
// https://www.essence.com.cn/api/newbonds?pageNo={page}&pageSize={size}
private static final String issueUrl = URLDecoder.decode("https://www.essence.com.cn/api/newbonds?pageNo={}&pageSize={}");
private ONode node;
protected EssenceIssueBond(ONode node) {
this.node = node;
}
@Override
public String getSecurityCode() {
return node.get("securityCode").getString();
}
@Override
public String getSecurityName() {
return node.get("securityName").getString();
}
private LocalDate getDate(String data) {
try {
return LocalDate.parse(data, formatter);
} catch (DateTimeParseException exception) {
return null;
}
}
@Override
public LocalDate getIssueDate() {
return getDate(node.get("issueDate").getString());
}
@Override
public LocalDate getListDate() {
return getDate(node.get("listDate").getString());
}
public static Map<String, EssenceIssueBond> getIssueBondsByPage(RestTemplate template, int page, int size) {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.USER_AGENT, "PostmanRuntime/7.28.0");
headers.add(HttpHeaders.ACCEPT, "application/json");
HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(null, headers);
String url = StringUtility.format(issueUrl, page, size);
url = URLDecoder.decode(url);
ResponseEntity<String> response = template.exchange(url, HttpMethod.GET, request, String.class);
String data = response.getBody();
if (logger.isDebugEnabled()) {
logger.debug(JsonUtility.prettyJson(data));
}
ONode root = ONode.load(data);
List<ONode> nodes = root.get("data").ary();
// TODO 获取总数
int count = root.get("total").getInt();
Map<String, EssenceIssueBond> bonds = new LinkedHashMap<>();
for (ONode node : nodes) {
EssenceIssueBond bond = new EssenceIssueBond(node);
bonds.put(bond.getSecurityCode(), bond);
}
return bonds;
}
}
|
safehousetech/gocloud
|
dns/designate/designate.go
|
<filename>dns/designate/designate.go<gh_stars>0
package designate
//Designate ..
type Designate struct {
}
|
michel-pi/xenforo-documentation
|
docs/2-1-0/d8/d05/class_x_f_1_1_cli_1_1_command_1_1_development_1_1_export_options.js
|
var class_x_f_1_1_cli_1_1_command_1_1_development_1_1_export_options =
[
[ "execute", "d8/d05/class_x_f_1_1_cli_1_1_command_1_1_development_1_1_export_options.html#ab31c72b72ddaf7116db5d84c055d3c0b", null ],
[ "getContentTypeDetails", "d8/d05/class_x_f_1_1_cli_1_1_command_1_1_development_1_1_export_options.html#a7a746c4a2abcc06c040b14fcd087e493", null ]
];
|
MRixen/rbc_Diagnose
|
afreechart/src/main/java/org/afree/data/xy/XYIntervalSeries.java
|
/* ===========================================================
* AFreeChart : a free chart library for Android(tm) platform.
* (based on JFreeChart and JCommon)
* ===========================================================
*
* (C) Copyright 2010, by ICOMSYSTECH Co.,Ltd.
* (C) Copyright 2000-2008, by Object Refinery Limited and Contributors.
*
* Project Info:
* AFreeChart: http://code.google.com/p/afreechart/
* JFreeChart: http://www.jfree.org/jfreechart/index.html
* JCommon : http://www.jfree.org/jcommon/index.html
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* [Android is a trademark of Google Inc.]
*
* ---------------------
* XYIntervalSeries.java
* ---------------------
*
* (C) Copyright 2010, by ICOMSYSTECH Co.,Ltd.
*
* Original Author: shiraki (for ICOMSYSTECH Co.,Ltd);
* Contributor(s): <NAME> ;
* <NAME>;
*
* Changes (from 19-Nov-2010)
* --------------------------
* 19-Nov-2010 : port JFreeChart 1.0.13 to Android as "AFreeChart"
*
* ------------- JFreeChart ---------------------------------------------
* (C) Copyright 2006-2008, by Object Refinery Limited.
*
* Original Author: <NAME> (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 20-Oct-2006 : Version 1 (DG);
* 13-Feb-2007 : Added several new accessor methods (DG);
*
*/
package org.afree.data.xy;
import org.afree.data.ComparableObjectItem;
import org.afree.data.ComparableObjectSeries;
/**
* A list of (x, x-low, x-high, y, y-low, y-high) data items.
*
* @since JFreeChart 1.0.3
*
* @see XYIntervalSeriesCollection
*/
public class XYIntervalSeries extends ComparableObjectSeries {
/**
*
*/
private static final long serialVersionUID = -1068821547400750660L;
/**
* Creates a new empty series. By default, items added to the series will
* be sorted into ascending order by x-value, and duplicate x-values will
* be allowed (these defaults can be modified with another constructor).
*
* @param key the series key (<code>null</code> not permitted).
*/
public XYIntervalSeries(Comparable key) {
this(key, true, true);
}
/**
* Constructs a new xy-series that contains no data. You can specify
* whether or not duplicate x-values are allowed for the series.
*
* @param key the series key (<code>null</code> not permitted).
* @param autoSort a flag that controls whether or not the items in the
* series are sorted.
* @param allowDuplicateXValues a flag that controls whether duplicate
* x-values are allowed.
*/
public XYIntervalSeries(Comparable key, boolean autoSort,
boolean allowDuplicateXValues) {
super(key, autoSort, allowDuplicateXValues);
}
/**
* Adds a data item to the series.
*
* @param x the x-value.
* @param xLow the lower bound of the x-interval.
* @param xHigh the upper bound of the x-interval.
* @param y the y-value.
* @param yLow the lower bound of the y-interval.
* @param yHigh the upper bound of the y-interval.
*/
public void add(double x, double xLow, double xHigh, double y, double yLow,
double yHigh) {
super.add(new XYIntervalDataItem(x, xLow, xHigh, y, yLow, yHigh), true);
}
/**
* Returns the x-value for the specified item.
*
* @param index the item index.
*
* @return The x-value (never <code>null</code>).
*/
public Number getX(int index) {
XYIntervalDataItem item = (XYIntervalDataItem) getDataItem(index);
return item.getX();
}
/**
* Returns the lower bound of the x-interval for the specified item in the
* series.
*
* @param index the item index.
*
* @return The lower bound of the x-interval.
*
* @since JFreeChart 1.0.5
*/
public double getXLowValue(int index) {
XYIntervalDataItem item = (XYIntervalDataItem) getDataItem(index);
return item.getXLowValue();
}
/**
* Returns the upper bound of the x-interval for the specified item in the
* series.
*
* @param index the item index.
*
* @return The upper bound of the x-interval.
*
* @since JFreeChart 1.0.5
*/
public double getXHighValue(int index) {
XYIntervalDataItem item = (XYIntervalDataItem) getDataItem(index);
return item.getXHighValue();
}
/**
* Returns the y-value for the specified item.
*
* @param index the item index.
*
* @return The y-value.
*/
public double getYValue(int index) {
XYIntervalDataItem item = (XYIntervalDataItem) getDataItem(index);
return item.getYValue();
}
/**
* Returns the lower bound of the Y-interval for the specified item in the
* series.
*
* @param index the item index.
*
* @return The lower bound of the Y-interval.
*
* @since JFreeChart 1.0.5
*/
public double getYLowValue(int index) {
XYIntervalDataItem item = (XYIntervalDataItem) getDataItem(index);
return item.getYLowValue();
}
/**
* Returns the upper bound of the y-interval for the specified item in the
* series.
*
* @param index the item index.
*
* @return The upper bound of the y-interval.
*
* @since JFreeChart 1.0.5
*/
public double getYHighValue(int index) {
XYIntervalDataItem item = (XYIntervalDataItem) getDataItem(index);
return item.getYHighValue();
}
/**
* Returns the data item at the specified index.
*
* @param index the item index.
*
* @return The data item.
*/
public ComparableObjectItem getDataItem(int index) {
return super.getDataItem(index);
}
}
|
fengjixuchui/blazefox
|
src/js/wasm/WasmTable.cpp
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=8 sts=4 et sw=4 tw=99:
*
* Copyright 2016 Mozilla Foundation
*
* 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 "wasm/WasmTable.h"
#include "mozilla/CheckedInt.h"
#include "vm/JSContext.h"
#include "vm/Realm.h"
#include "wasm/WasmInstance.h"
#include "wasm/WasmJS.h"
using namespace js;
using namespace js::wasm;
using mozilla::CheckedInt;
Table::Table(JSContext* cx, const TableDesc& desc, HandleWasmTableObject maybeObject,
UniqueByteArray array)
: maybeObject_(maybeObject),
observers_(cx->zone()),
array_(std::move(array)),
kind_(desc.kind),
length_(desc.limits.initial),
maximum_(desc.limits.maximum),
external_(desc.external)
{}
/* static */ SharedTable
Table::create(JSContext* cx, const TableDesc& desc, HandleWasmTableObject maybeObject)
{
// The raw element type of a Table depends on whether it is external: an
// external table can contain functions from multiple instances and thus
// must store an additional instance pointer in each element.
UniqueByteArray array;
if (desc.external) {
array.reset((uint8_t*)cx->pod_calloc<ExternalTableElem>(desc.limits.initial));
} else {
array.reset((uint8_t*)cx->pod_calloc<void*>(desc.limits.initial));
}
if (!array) {
return nullptr;
}
return SharedTable(cx->new_<Table>(cx, desc, maybeObject, std::move(array)));
}
void
Table::tracePrivate(JSTracer* trc)
{
// If this table has a WasmTableObject, then this method is only called by
// WasmTableObject's trace hook so maybeObject_ must already be marked.
// TraceEdge is called so that the pointer can be updated during a moving
// GC. TraceWeakEdge may sound better, but it is less efficient given that
// we know object_ is already marked.
if (maybeObject_) {
MOZ_ASSERT(!gc::IsAboutToBeFinalized(&maybeObject_));
TraceEdge(trc, &maybeObject_, "wasm table object");
}
if (external_) {
ExternalTableElem* array = externalArray();
for (uint32_t i = 0; i < length_; i++) {
if (array[i].tls) {
array[i].tls->instance->trace(trc);
} else {
MOZ_ASSERT(!array[i].code);
}
}
}
}
void
Table::trace(JSTracer* trc)
{
// The trace hook of WasmTableObject will call Table::tracePrivate at
// which point we can mark the rest of the children. If there is no
// WasmTableObject, call Table::tracePrivate directly. Redirecting through
// the WasmTableObject avoids marking the entire Table on each incoming
// edge (once per dependent Instance).
if (maybeObject_) {
TraceEdge(trc, &maybeObject_, "wasm table object");
} else {
tracePrivate(trc);
}
}
void**
Table::internalArray() const
{
MOZ_ASSERT(!external_);
return (void**)array_.get();
}
ExternalTableElem*
Table::externalArray() const
{
MOZ_ASSERT(external_);
return (ExternalTableElem*)array_.get();
}
void
Table::set(uint32_t index, void* code, const Instance* instance)
{
if (external_) {
ExternalTableElem& elem = externalArray()[index];
if (elem.tls) {
JSObject::writeBarrierPre(elem.tls->instance->objectUnbarriered());
}
elem.code = code;
elem.tls = instance->tlsData();
MOZ_ASSERT(elem.tls->instance->objectUnbarriered()->isTenured(),
"no writeBarrierPost (Table::set)");
} else {
internalArray()[index] = code;
}
}
void
Table::setNull(uint32_t index)
{
// Only external tables can set elements to null after initialization.
ExternalTableElem& elem = externalArray()[index];
if (elem.tls) {
JSObject::writeBarrierPre(elem.tls->instance->objectUnbarriered());
}
elem.code = nullptr;
elem.tls = nullptr;
}
void
Table::copy(uint32_t dstIndex, uint32_t srcIndex)
{
if (external_) {
ExternalTableElem& dst = externalArray()[dstIndex];
if (dst.tls) {
JSObject::writeBarrierPre(dst.tls->instance->objectUnbarriered());
}
ExternalTableElem& src = externalArray()[srcIndex];
dst.code = src.code;
dst.tls = src.tls;
if (dst.tls) {
MOZ_ASSERT(dst.code);
MOZ_ASSERT(dst.tls->instance->objectUnbarriered()->isTenured(),
"no writeBarrierPost (Table::copy)");
} else {
MOZ_ASSERT(!dst.code);
}
} else {
internalArray()[dstIndex] = internalArray()[srcIndex];
}
}
uint32_t
Table::grow(uint32_t delta, JSContext* cx)
{
// This isn't just an optimization: movingGrowable() assumes that
// onMovingGrowTable does not fire when length == maximum.
if (!delta) {
return length_;
}
uint32_t oldLength = length_;
CheckedInt<uint32_t> newLength = oldLength;
newLength += delta;
if (!newLength.isValid()) {
return -1;
}
if (maximum_ && newLength.value() > maximum_.value()) {
return -1;
}
MOZ_ASSERT(movingGrowable());
JSRuntime* rt = cx->runtime(); // Use JSRuntime's MallocProvider to avoid throwing.
// Note that realloc does not release array_'s pointee (which is returned by
// externalArray()) on failure which is exactly what we need here.
ExternalTableElem* newArray = rt->pod_realloc(externalArray(), length_, newLength.value());
if (!newArray) {
return -1;
}
Unused << array_.release();
array_.reset((uint8_t*)newArray);
// Realloc does not zero the delta for us.
PodZero(newArray + length_, delta);
length_ = newLength.value();
for (InstanceSet::Range r = observers_.all(); !r.empty(); r.popFront()) {
r.front()->instance().onMovingGrowTable();
}
return oldLength;
}
bool
Table::movingGrowable() const
{
return !maximum_ || length_ < maximum_.value();
}
bool
Table::addMovingGrowObserver(JSContext* cx, WasmInstanceObject* instance)
{
MOZ_ASSERT(movingGrowable());
if (!observers_.putNew(instance)) {
ReportOutOfMemory(cx);
return false;
}
return true;
}
size_t
Table::sizeOfExcludingThis(MallocSizeOf mallocSizeOf) const
{
return mallocSizeOf(array_.get());
}
|
rccoder/HIT-Survey
|
scripts/admin/emailtemplates.js
|
<gh_stars>10-100
// $Id: saved.js 9330 2010-10-24 22:23:56Z c_schmitz $
$(document).ready(function(){
handle=$('.tabsinner').tabs(
{
show: loadHTMLEditor
});
// Binds the Default value buttons for each email template subject and body text
$('.fillin').bind('click', function(e) {
e.preventDefault;
var newval = $(this).attr('data-value');
var target = $('#' + $(this).attr('data-target'));
$(target).val(newval);
updateCKeditor($(this).attr('data-target'),newval);
});
});
/**
* This function loads each FCKeditor only when the tab is clicked and only if it is not already loaded
*/
function loadHTMLEditor(event, ui)
{
return;
if (typeof ui.panel.selector != 'undefined')
{
sSelector=ui.panel.selector;
}
else
{
sSelector='#'+ui.panel.id;
}
if ($(sSelector+' iframe').size()==0)
{
sCKEditorInstanceName='oFCKeditor_'+$(sSelector+' textarea').attr('id').replace(/-/i, "_");
eval("if (typeof "+sCKEditorInstanceName+" != 'undefined')"+sCKEditorInstanceName+".ReplaceTextarea();");
}
}
function KCFinder_callback(url)
{
addAttachment(window.KCFinder.target, url);
window.KCFinder = null;
}
function editAttachmentRelevance(e)
{
e.preventDefault();
var target = $(this).parents('tr').find('input.relevance');
var span = $(this).parents('tr').find('span.relevance');
$('#attachment-relevance-editor textarea').val($(target).val());
$('#attachment-relevance-editor').dialog({
'modal': true,
'minWidth' : 400,
'minHeight' :200,
'height': 300,
'target' : target,
'title' : 'Relevance equation for: ' + $(this).parents('tr').find('span.filename').text()
});
}
function addAttachment(target, url, relevance, size)
{
if (typeof relevance == 'undefined')
{
var relevance = '1';
}
if (typeof size == 'undefined')
{
var size = '-';
}
var filename = decodeURIComponent(url.replace(/^.*[\\\/]/, ''));
var baserow = '<tr>';
// Actions
baserow = baserow + '<td>';
baserow = baserow + '<img alt="Remove attachment" class="btnattachmentremove" src="' + LS.data.adminImageUrl + 'deleteanswer.png">';
//baserow = baserow + '<img alt="Edit attachment relevance" class="btnattachmentrelevance" src="/styles/gringegreen/images/global.png">';
baserow = baserow + '</td>';
baserow = baserow + '<td><span class="filename"></span><input class="filename" type="hidden"></td>';
baserow = baserow + '<td><span class="filesize"></span></td>';
baserow = baserow + '<td><span class="relevance"></span><input class="relevance" type="hidden"></td>';
//baserow = baserow + '<td><img alt="Edit attachment relevance" class="btndelanswer" src="/styles/gringegreen/images/global.png"></td>';
baserow = baserow + '</tr>';
if ($(target).is('table'))
{
var newrow = $(baserow).clone();
var templatetype = $(target).attr('data-template');
var index = $(target).find('tr').length - 1;
$(newrow).find('span.relevance').text(relevance);
$(newrow).find('input.relevance').val(relevance).attr('name', 'attachments' + templatetype + '[' + index + '][relevance]');
$(newrow).find('input.filename').attr('name', 'attachments' + templatetype + '[' + index + '][url]');
$(newrow).appendTo(target);
}
else
{
var newrow = target;
}
$('span.relevance').unbind('click').bind('click', editAttachmentRelevance);
$('img.btnattachmentremove').unbind('click').bind('click', removeAttachment);
$('span.filename').unbind('click').bind('click', function(e) {
e.preventDefault();
var target = $(this).parents('tr');
openKCFinder_singleFile(target);
});
$(newrow).find('span.filesize').text(formatFileSize(size));
$(newrow).find('span.filename').text(filename);
$(newrow).find('input.filename').val(url);
}
function removeAttachment(e)
{
e.preventDefault();
$(this).parents('tr').remove();
}
function formatFileSize(bytes)
{
if (bytes >= 1000000)
{
return (bytes / 1000000).toFixed(2) + 'MB';
}
else if (bytes < 1000000)
{
return (bytes / 1000).toFixed(0) + 'KB';
}
return bytes;
}
function openKCFinder_singleFile(target) {
window.KCFinder = {};
window.KCFinder.target = target;
window.KCFinder.callBack = KCFinder_callback;
window.open(LS.data.baseUrl + '/third_party/kcfinder/browse.php?opener=custom&type=files&CKEditor=email_invite_en&langCode='+sKCFinderLanguage, 'kcfinder_single', 'height=600px, width=800px, modal=yes');
}
$('#attachment-relevance-editor button').click(function()
{
$('#attachment-relevance-editor').dialog('close');
var relevance = $('#attachment-relevance-editor textarea').val();
$('#attachment-relevance-editor').dialog('option', 'target').val(relevance);
var span = $('#attachment-relevance-editor').dialog('option', 'target').parents('tr').find('span.relevance');
if (relevance.length > 50)
{
$(span).text(relevance.replace(/(\r\n|\n|\r)/gm,"").substr(0, 47) + '...');
}
else
{
$(span).text(relevance);
}
});
|
NightKev/Renol-IRC
|
commands/show_Version.py
|
ID = "version"
permission = 0
def execute(self, name, params, channel, userdata, rank):
self.sendChatMessage(self.send, channel, "Yoshi2's IRC Bot v0.3")
|
19920625lsg/liuyubobobo-algorithms
|
Part2BasicGraph/src/main/java/Chapter15Matching/Section5to7Hungarian/HungarianBFS.java
|
/***********************************************************
* @Description : 基于图的BFS遍历实现的匈牙利算法(Hungarian算法)
* @author : 梁山广(<NAME>)
* @date : 2019/12/28 0:29
* @email : <EMAIL>
***********************************************************/
package Chapter15Matching.Section5to7Hungarian;
import Chapter02GraphExpress.Graph;
import Chapter04DFSInAction.Section10BiPartitionDetect.GraphDFSBiPartitionDetect;
import java.util.*;
public class HungarianBFS {
/**
* 要找最大匹配的二分图
*/
private Graph graph;
/**
* 最大匹配的值
*/
private int maxMatch = 0;
/**
* match[v]=w表示顶点v在图中匹配的顶点是w
*/
private int[] matching;
public HungarianBFS(Graph graph) {
GraphDFSBiPartitionDetect biPartitionDetect = new GraphDFSBiPartitionDetect(graph);
if (!biPartitionDetect.isBiPartition()) {
throw new IllegalArgumentException("匹配问题必须针对地是二分图!");
}
this.graph = graph;
// 二分图中的顶点颜色区分,一半为0(左侧),一半为1(右侧)
int[] colors = biPartitionDetect.getColors();
int V = graph.V();
matching = new int[V];
Arrays.fill(matching, -1);
for (int v = 0; v < V; v++) {
// 只遍历二分图中左侧还未被遍历的点(颜色为0)
if (colors[v] == 0 && matching[v] == -1) {
// 每个左侧的点都进行一次bfs来找增广路径
if (bfs(v)) {
// 本地bfs找到了一条增广路径
maxMatch++;
}
}
}
}
/**
* bfs找增广路径
*
* @param source bfs遍历的起点
* @return 本次bfs是否找到了增广路径
*/
private boolean bfs(int source) {
Queue<Integer> queue = new ArrayDeque<>();
int V = graph.V();
// 记录节点访问顺序的数组,每次bfs都需要新建自己的pre
int[] pre = new int[V];
Arrays.fill(pre, -1);
queue.add(source);
// 起点的上一个访问节点认为是自己
pre[source] = source;
while (!queue.isEmpty()) {
// v一定要用二分图左侧的顶点(本类中0标记)
int v = queue.remove();
for (int w : graph.adj(v)) {
// w是二分图右侧的顶点
if (pre[w] == -1) {
if (matching[w] != -1) {
// w已经匹配
pre[w] = v;
// 和w匹配的边的前一条边记为w
pre[matching[w]] = w;
// 添加左侧的点到queue中,queue中只存左侧的点
queue.add(matching[w]);
} else {
// 在二分图右侧找到了一个未匹配的点,即找到了增广路径
pre[w] = v;
List<Integer> augPath = getAugPath(pre, v, w);
// 匈牙利算法核心:匹配状态取反。即匹配边变非匹配边、非匹配边变匹配边
for (int i = 0; i < augPath.size(); i += 2) {
matching[augPath.get(i)] = augPath.get(i + 1);
matching[augPath.get(i + 1)] = augPath.get(i);
}
return true;
}
}
}
}
return false;
}
/**
* 获取增广路径详情
*
* @param pre 节点访问顺序数组
* @param start 路径起点
* @param end 路径终点
* @return 路径上的点的顺序列表
*/
private List<Integer> getAugPath(int[] pre, int start, int end) {
List<Integer> path = new ArrayList<>();
int cur = end;
while (cur != start) {
path.add(cur);
cur = pre[cur];
}
path.add(start);
// 增广路径无论正反都是增广路径,所以这里逆序与否均可了
Collections.reverse(path);
return path;
}
/**
* 获取最大匹配数
*/
public int getMaxMatch() {
return maxMatch;
}
/**
* 当前的最大匹配是否是完全匹配(也可以叫完全匹配,即所有的点都有二分图另一侧的点和自己匹配而且匹配对互不干扰O)
*/
public boolean isPrefectMatch() {
return maxMatch * 2 == graph.V();
}
}
|
2802harsh/Teamder-1
|
client/src/components/Profile/Menu.js
|
import React, { useContext } from 'react';
// import Edit from './Edit';
import Edit from './Edit1';
import {Link} from 'react-router-dom';
import {userDataContext} from './profilePage';
import NewChat from './NewChat';
import SERVER_URL from '../../utils/constants';
import axios from 'axios';
axios.defaults.withCredentials = true;
const Menu = (props) => {
const [data, setData] = useContext(userDataContext);
function handleLogout(){
axios.get(`${SERVER_URL}/logout`);
window.location = "/";
}
return <>
<div className="menu">
<ul>
{data.username !== localStorage.getItem("username") ? (
<li><NewChat user={data.username}/></li>
) : (
<li><Link to="/chats" style={{textDecoration:"none", color:"inherit"}}>Chats</Link></li>
)}
{data.username !== localStorage.getItem("username") ? (
""
) : (
<li><Link to="/connect" style={{textDecoration:"none", color:"inherit"}}>Explore</Link></li>
)}
<li><Link to="/profile" style={{textDecoration:"none", color:"inherit"}}>Search a User</Link></li>
{data.username===localStorage.getItem("username") && <li><Link to="/hackathons" style={{textDecoration:"none", color:"inherit"}}>Hackathons</Link></li>}
{data.username===localStorage.getItem("username") && <li><Edit/></li>}
{data.username===localStorage.getItem("username") && (
<li onClick={handleLogout}>Logout</li>) }
</ul>
</div>
</>
}
export default Menu;
|
Fusion-Rom/android_external_chromium_org_third_party_WebKit
|
Source/platform/graphics/test/MockImageDecoder.h
|
<gh_stars>1-10
/*
* Copyright (C) 2012 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef MockImageDecoder_h
#include "platform/image-decoders/ImageDecoder.h"
#include "wtf/PassOwnPtr.h"
namespace blink {
class MockImageDecoderClient {
public:
virtual void decoderBeingDestroyed() = 0;
virtual void frameBufferRequested() = 0;
virtual ImageFrame::Status status() = 0;
virtual size_t frameCount() = 0;
virtual int repetitionCount() const = 0;
virtual float frameDuration() const = 0;
// Clients can control the behavior of MockImageDecoder::decodedSize() by
// overriding this method. The default implementation causes
// MockImageDecoder::decodedSize() to return the same thing as
// MockImageDecoder::size(). See the precise implementation of
// MockImageDecoder::decodedSize() below.
virtual IntSize decodedSize() const { return IntSize(); }
};
class MockImageDecoder : public ImageDecoder {
public:
static PassOwnPtr<MockImageDecoder> create(MockImageDecoderClient* client) { return adoptPtr(new MockImageDecoder(client)); }
MockImageDecoder(MockImageDecoderClient* client)
: ImageDecoder(ImageSource::AlphaPremultiplied, ImageSource::GammaAndColorProfileApplied, noDecodedImageByteLimit)
, m_client(client)
{ }
~MockImageDecoder()
{
m_client->decoderBeingDestroyed();
}
virtual IntSize decodedSize() const OVERRIDE
{
return m_client->decodedSize().isEmpty() ? size() : m_client->decodedSize();
}
virtual bool setSize(unsigned width, unsigned height) OVERRIDE
{
ImageDecoder::setSize(width, height);
m_frameBufferCache.resize(1);
m_frameBufferCache[0].setSize(width, height);
return true;
}
virtual String filenameExtension() const OVERRIDE
{
return "mock";
}
virtual size_t frameCount() OVERRIDE
{
return m_client->frameCount();
}
virtual int repetitionCount() const OVERRIDE
{
return m_client->repetitionCount();
}
virtual ImageFrame* frameBufferAtIndex(size_t) OVERRIDE
{
m_client->frameBufferRequested();
m_frameBufferCache[0].setStatus(m_client->status());
return &m_frameBufferCache[0];
}
virtual bool frameIsCompleteAtIndex(size_t) const OVERRIDE
{
return m_client->status() == ImageFrame::FrameComplete;
}
virtual float frameDurationAtIndex(size_t) const OVERRIDE
{
return m_client->frameDuration();
}
void setFrameHasAlpha(bool hasAlpha) { m_frameBufferCache[0].setHasAlpha(hasAlpha); }
private:
MockImageDecoderClient* m_client;
};
class MockImageDecoderFactory : public ImageDecoderFactory {
public:
static PassOwnPtr<MockImageDecoderFactory> create(MockImageDecoderClient* client, const SkISize& decodedSize)
{
return adoptPtr(new MockImageDecoderFactory(client, IntSize(decodedSize.width(), decodedSize.height())));
}
static PassOwnPtr<MockImageDecoderFactory> create(MockImageDecoderClient* client, const IntSize& decodedSize)
{
return adoptPtr(new MockImageDecoderFactory(client, decodedSize));
}
virtual PassOwnPtr<ImageDecoder> create() OVERRIDE
{
OwnPtr<MockImageDecoder> decoder = MockImageDecoder::create(m_client);
decoder->setSize(m_decodedSize.width(), m_decodedSize.height());
decoder->setFrameHasAlpha(false);
return decoder.release();
}
private:
MockImageDecoderFactory(MockImageDecoderClient* client, const IntSize& decodedSize)
: m_client(client)
, m_decodedSize(decodedSize)
{
}
MockImageDecoderClient* m_client;
IntSize m_decodedSize;
};
} // namespace blink
#endif // MockImageDecoder_h
|
sniceio/hektor
|
hektor-fsm/src/main/java/io/hektor/fsm/builder/exceptions/FinalStateTransitionsException.java
|
<gh_stars>1-10
package io.hektor.fsm.builder.exceptions;
/**
* Indicates that you tried to define transitions on a final state. A final state cannot have
* transitions since that state is, well, final. As in, once the FSM reaching this state, it's
* dead, no way back.
*
* @author <EMAIL>
*/
public class FinalStateTransitionsException extends StateBuilderException {
public FinalStateTransitionsException(final Enum state) {
super(state, "A final state cannot have transitions");
}
}
|
google-cloud-sdk-unofficial/google-cloud-sdk
|
lib/googlecloudsdk/command_lib/util/declarative/clients/client_base.py
|
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. 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.
"""Library for retrieving declarative clients."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import abc
from googlecloudsdk.core import exceptions as c_except
import six
class ClientException(c_except.Error):
"""General Purpose Exception."""
class ResourceNotFoundException(ClientException):
"""Exception for when a requested resource doesn't exist."""
@six.add_metaclass(abc.ABCMeta)
class DeclarativeClient(object):
"""Abstract class representing a high level declarative service."""
@abc.abstractmethod
def Export(self, file_path):
raise NotImplementedError(
'DeclarativeService Parse function must be implemented.')
@abc.abstractmethod
def ExportAll(self, file_path):
raise NotImplementedError(
'DeclarativeService Export function must be implemented.')
@abc.abstractmethod
def BulkExport(self, file_path):
raise NotImplementedError(
'DeclarativeService Export function must be implemented.')
|
syaifuddinh/electric-repair
|
public/core/marketing/vendor_prices/core.js
|
var vendorPrices = angular.module('vendorPrices', ['ui.router'], () => {})
vendorPrices.config(($stateProvider, $urlRouterProvider) => {
})
vendorPrices.service('vendorPricesService', function($http, $rootScope) {
var api = {}
var url = {}
url.store = () => baseUrl + '/marketing/vendor_price'
url.show = (id) => baseUrl + '/marketing/vendor_price/' + id
url.datatable = () => baseUrl + '/api/marketing/vendor_price_datatable'
this.url = url
api.store = function(payload, fn) {
if(!fn)
fn = (dt) => {}
$http.post(url.store(), payload).then(function(resp) {
toastr.success(resp.data.message)
fn(resp)
}, function(error) {
$rootScope.disBtn=false;
if (error.status==422) {
var det="";
angular.forEach(error.data.errors,function(val,i) {
det+="- "+val+"<br>";
});
toastr.warning(det,error.data.message);
} else {
toastr.error(error.data.message,"Error Has Found !");
}
});
}
api.show = function(id, fn) {
if(!fn)
fn = (dt) => {}
$http.get(url.show(id)).then(function(resp) {
fn(resp.data)
}, function(){
});
}
this.api = api
})
|
LeedsCC/QEWD-Courier
|
helm/openehr_service/lib/shared/validation.js
|
/*
----------------------------------------------------------------------------
| |
| Copyright (c) 2019 Ripple Foundation Community Interest Company |
| All rights reserved. |
| |
| http://rippleosi.org |
| Email: <EMAIL> |
| |
| Author: <NAME> <<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. |
----------------------------------------------------------------------------
17 April 2019
*/
'use strict';
const validUrl = require('valid-url');
function respondErr(err) {
return {
error: err
};
}
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function isPatientIdValid(patientId) {
if (!patientId || patientId === '') {
return respondErr(`patientId ${patientId} must be defined`);
}
if (!isNumeric(patientId)) {
return respondErr(`patientId ${patientId} is invalid`);
}
return {
ok: true
};
}
function isFeedPayloadValid(payload) {
if (!payload.author || payload.author === '') {
return respondErr('Author missing or empty');
}
if (!payload.name || payload.name === '') {
return respondErr('Feed name missing or empty');
}
if (!payload.landingPageUrl || payload.landingPageUrl === '') {
return respondErr('Landing page URL missing or empty');
}
if (!validUrl.isWebUri(payload.landingPageUrl)) {
return respondErr('Landing page URL is invalid');
}
if (!payload.rssFeedUrl || payload.rssFeedUrl === '') {
return respondErr('RSS Feed URL missing or empty');
}
if (!validUrl.isWebUri(payload.rssFeedUrl)) {
return respondErr('RSS Feed URL is invalid');
}
return {
ok: true
};
}
function isEmpty(obj) {
if (!obj) return true;
if (typeof obj !== 'object') return true;
for (let name in obj) {
if (obj.hasOwnProperty(name)) {
return false;
}
}
return true;
}
function isTop3ThingsPayloadValid(payload) {
if (!payload.name1 || payload.name1 === '') {
return respondErr('You must specify at least 1 Top Thing');
}
if (!payload.description1 || payload.description1 === '') {
return respondErr('You must specify at least 1 Top Thing');
}
if (!payload.name2 || payload.name2 === '') {
if (payload.description2 && payload.description2 !== '') {
return respondErr('A Description for the 2nd Top Thing was defined, but its summary name was not defined');
}
payload.name2 = '';
payload.description2 = '';
} else {
payload.description2 = payload.description2 || '';
}
if (!payload.name3 || payload.name3 === '') {
if (payload.description3 && payload.description3 !== '') {
return respondErr('A Description for the 3rd Top Thing was defined, but its summary name was not defined');
}
payload.name3 = '';
payload.description3 = '';
} else {
payload.description3 = payload.description3 || '';
}
return {
ok: true
};
}
/**
* Returns true if heading valid. Otherwise returns an error
*
* @param {Object} headingsConfig
* @param {string} heading
* @return {Boolean}
*/
function isHeadingValid(headingsConfig, heading) {
if (!heading || !headingsConfig[heading]) {
return respondErr(`Invalid or missing heading: ${heading}`);
}
return {
ok: true
};
}
function isGuid(s) {
const regexGuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
return regexGuid.test(s);
}
/**
* Returns true if site valid. Otherwise returns error
*
* @param {Object} sitesConfig
* @param {string} site
* @return {Boolean}
*/
function isSiteValid(sitesConfig, site) {
if (!site || !sitesConfig[site]) {
return respondErr('Invalid site');
}
return {
ok: true
};
}
function isSourceIdValid(sourceId) {
if (!sourceId) return respondErr(`sourceId ${sourceId} must be defined`);
const pieces = sourceId.split('-');
if (pieces.length !== 6) return respondErr(`sourceId ${sourceId} is invalid`);
// remove host name element
pieces.shift();
const guid = pieces.join('-');
if (!isGuid(guid)) return respondErr(`sourceId ${sourceId} is invalid`);
return {
ok: true
};
}
module.exports = {
isNumeric,
isPatientIdValid,
isFeedPayloadValid,
isEmpty,
isTop3ThingsPayloadValid,
isHeadingValid,
isGuid,
isSiteValid,
isSourceIdValid,
respondErr
};
|
atultherajput/evpoco
|
evnet/include/Poco/evnet/EVServerResponse.h
|
<filename>evnet/include/Poco/evnet/EVServerResponse.h<gh_stars>1-10
//
// EVServerResponse.h
//
// Library: evnet
// Package: HTTPServer
// Module: EVServerResponse
//
// Definition of the EVServerResponse class.
//
//
#ifndef EVNet_EVServerResponse_INCLUDED
#define EVNet_EVServerResponse_INCLUDED
#include "Poco/Net/Net.h"
namespace Poco {
namespace evnet {
class Net_API EVServerResponse
/// This is a marker class for any server reuqest
/// representing server-side requests.
///
{
public:
EVServerResponse();
/// Creates the EVServerResponse, using the
/// given EVServerSession.
~EVServerResponse();
/// Destroys the EVServerResponse.
};
} } // namespace Poco::evnet
#endif // EVNet_EVServerRequest_INCLUDED
|
eswdd/cougar
|
disco-framework/disco-zipkin-common/src/test/java/uk/co/exemel/disco/modules/zipkin/impl/ZipkinAnnotationsStoreTest.java
|
<reponame>eswdd/cougar<gh_stars>0
/*
* Copyright 2015, The Sporting Exchange Limited
*
* 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 uk.co.exemel.disco.modules.zipkin.impl;
import uk.co.exemel.disco.modules.zipkin.api.ZipkinData;
import com.twitter.zipkin.gen.*;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import java.nio.ByteBuffer;
import java.util.Arrays;
import static org.junit.Assert.*;
import static org.mockito.MockitoAnnotations.initMocks;
public class ZipkinAnnotationsStoreTest {
@Mock
private ZipkinData zipkinData;
@Mock
private Endpoint endpoint;
private ZipkinAnnotationsStore victim;
private String key = "key";
@Before
public void init() {
initMocks(this);
victim = new ZipkinAnnotationsStore(zipkinData);
}
@Test
public void addAnnotation_OnStringOverload_ShouldAddBinaryAnnotation() {
String value = "value";
ByteBuffer wrappedValue = ByteBuffer.wrap(value.getBytes());
ZipkinAnnotationsStore result = victim.addAnnotation(key, value);
assertNotNull(result);
Span generatedSpan = result.generate();
assertEquals(1, generatedSpan.getBinary_annotationsSize());
BinaryAnnotation createdBinaryAnnotation = generatedSpan.getBinary_annotations().get(0);
assertEquals(key, createdBinaryAnnotation.getKey());
assertEquals(AnnotationType.STRING, createdBinaryAnnotation.getAnnotation_type());
assertTrue(Arrays.equals(wrappedValue.array(), createdBinaryAnnotation.getValue()));
}
@Test
public void addAnnotation_OnShortOverload_ShouldAddBinaryAnnotation() {
short value = 327;
ByteBuffer wrappedValue = ByteBuffer.allocate(Short.SIZE / 8).putShort(value);
ZipkinAnnotationsStore result = victim.addAnnotation(key, value);
assertNotNull(result);
Span generatedSpan = result.generate();
assertEquals(1, generatedSpan.getBinary_annotationsSize());
BinaryAnnotation createdBinaryAnnotation = generatedSpan.getBinary_annotations().get(0);
assertEquals(key, createdBinaryAnnotation.getKey());
assertEquals(AnnotationType.I16, createdBinaryAnnotation.getAnnotation_type());
assertTrue(Arrays.equals(wrappedValue.array(), createdBinaryAnnotation.getValue()));
}
@Test
public void addAnnotation_OnIntOverload_ShouldAddBinaryAnnotation() {
int value = 327;
ByteBuffer wrappedValue = ByteBuffer.allocate(Integer.SIZE / 8).putInt(value);
ZipkinAnnotationsStore result = victim.addAnnotation(key, value);
assertNotNull(result);
Span generatedSpan = result.generate();
assertEquals(1, generatedSpan.getBinary_annotationsSize());
BinaryAnnotation createdBinaryAnnotation = generatedSpan.getBinary_annotations().get(0);
assertEquals(key, createdBinaryAnnotation.getKey());
assertEquals(AnnotationType.I32, createdBinaryAnnotation.getAnnotation_type());
assertTrue(Arrays.equals(wrappedValue.array(), createdBinaryAnnotation.getValue()));
}
@Test
public void addAnnotation_OnLongOverload_ShouldAddBinaryAnnotation() {
long value = 327L;
ByteBuffer wrappedValue = ByteBuffer.allocate(Long.SIZE / 8).putLong(value);
ZipkinAnnotationsStore result = victim.addAnnotation(key, value);
assertNotNull(result);
Span generatedSpan = result.generate();
assertEquals(1, generatedSpan.getBinary_annotationsSize());
BinaryAnnotation createdBinaryAnnotation = generatedSpan.getBinary_annotations().get(0);
assertEquals(key, createdBinaryAnnotation.getKey());
assertEquals(AnnotationType.I64, createdBinaryAnnotation.getAnnotation_type());
assertTrue(Arrays.equals(wrappedValue.array(), createdBinaryAnnotation.getValue()));
}
@Test
public void addAnnotation_OnDoubleOverload_ShouldAddBinaryAnnotation() {
double value = 327D;
ByteBuffer wrappedValue = ByteBuffer.allocate(Double.SIZE / 8).putDouble(value);
ZipkinAnnotationsStore result = victim.addAnnotation(key, value);
assertNotNull(result);
Span generatedSpan = result.generate();
assertEquals(1, generatedSpan.getBinary_annotationsSize());
BinaryAnnotation createdBinaryAnnotation = generatedSpan.getBinary_annotations().get(0);
assertEquals(key, createdBinaryAnnotation.getKey());
assertEquals(AnnotationType.DOUBLE, createdBinaryAnnotation.getAnnotation_type());
assertTrue(Arrays.equals(wrappedValue.array(), createdBinaryAnnotation.getValue()));
}
@Test
public void addAnnotation_OnBooleanOverload_ShouldAddBinaryAnnotation() {
ByteBuffer wrappedValue = ByteBuffer.wrap(new byte[]{1});
ZipkinAnnotationsStore result = victim.addAnnotation(key, true);
assertNotNull(result);
Span generatedSpan = result.generate();
assertEquals(1, generatedSpan.getBinary_annotationsSize());
BinaryAnnotation createdBinaryAnnotation = generatedSpan.getBinary_annotations().get(0);
assertEquals(key, createdBinaryAnnotation.getKey());
assertEquals(AnnotationType.BOOL, createdBinaryAnnotation.getAnnotation_type());
assertTrue(Arrays.equals(wrappedValue.array(), createdBinaryAnnotation.getValue()));
}
@Test
public void addAnnotation_OnBytesOverload_ShouldAddBinaryAnnotation() {
byte[] value = "327".getBytes();
ByteBuffer wrappedValue = ByteBuffer.wrap(value);
ZipkinAnnotationsStore result = victim.addAnnotation(key, value);
assertNotNull(result);
Span generatedSpan = result.generate();
assertEquals(1, generatedSpan.getBinary_annotationsSize());
BinaryAnnotation createdBinaryAnnotation = generatedSpan.getBinary_annotations().get(0);
assertEquals(key, createdBinaryAnnotation.getKey());
assertEquals(AnnotationType.BYTES, createdBinaryAnnotation.getAnnotation_type());
assertTrue(Arrays.equals(wrappedValue.array(), createdBinaryAnnotation.getValue()));
}
@Test
public void addAnnotation_ShouldAddRegularAnnotation() {
String value = "value";
long timestamp = System.currentTimeMillis();
victim.defaultEndpoint(endpoint);
ZipkinAnnotationsStore result = victim.addAnnotation(timestamp, value);
assertNotNull(result);
Span generatedSpan = result.generate();
assertEquals(1, generatedSpan.getAnnotationsSize());
Annotation createdAnnotation = generatedSpan.getAnnotations().get(0);
assertEquals(timestamp, createdAnnotation.getTimestamp());
assertEquals(value, createdAnnotation.getValue());
assertEquals(endpoint, createdAnnotation.getHost());
}
@Test
public void addBinaryAnnotation_WhenAnEndpointIsDefined_ShouldSetEndpointAsHost() {
short value = 327;
ByteBuffer wrappedValue = ByteBuffer.allocate(Short.SIZE / 8).putShort(value);
victim.defaultEndpoint(endpoint);
ZipkinAnnotationsStore result = victim.addAnnotation(key, value);
assertNotNull(result);
Span generatedSpan = result.generate();
assertEquals(1, generatedSpan.getBinary_annotationsSize());
BinaryAnnotation createdBinaryAnnotation = generatedSpan.getBinary_annotations().get(0);
assertEquals(key, createdBinaryAnnotation.getKey());
assertEquals(AnnotationType.I16, createdBinaryAnnotation.getAnnotation_type());
assertTrue(Arrays.equals(wrappedValue.array(), createdBinaryAnnotation.getValue()));
assertEquals(endpoint, createdBinaryAnnotation.getHost());
}
}
|
anuragpathak0/C-Plus-Plus
|
Tut 7/checking.cpp
|
<reponame>anuragpathak0/C-Plus-Plus
#include <iostream>
using namespace std;
int main()
{
float d=3.14;
long double e=3.14;
cout<<"The value of d is "<<d<<endl<<"The value of e is "<<e<<endl;
cout<<"The size of d is "<<sizeof(d)<<endl;
cout<<"The size of e is "<<sizeof(e)<<endl;
cout<<"The size of 3.14 is "<<sizeof(3.14)<<endl;
return 0;
}
|
DavidLlorens/algoritmia
|
src/tests/datastructures/test_mergefindsets.py
|
<reponame>DavidLlorens/algoritmia
#coding: latin1
import unittest
from algoritmia.datastructures.mergefindsets import (NaiveMergeFindSet, RankUnionMFset,
PathCompressionMFset, MergeFindSet)
from algoritmia.datastructures.maps import IntKeyMap
class TestNaiveMFset(unittest.TestCase):
def setUp(self):
self.mf1 = NaiveMergeFindSet()
self.mf2 = NaiveMergeFindSet(((i,) for i in range(10)), createMap=lambda nodes: IntKeyMap(capacity=max(nodes)+1))
def test_mfsets(self):
for i in range(10):
self.mf1.add(i)
for i in range(10):
self.assertEqual(self.mf1.find(i), i)
self.assertEqual(self.mf2.find(i), i)
for i in range(0, 10, 2):
self.mf1.merge(i, i+1)
self.mf2.merge(i, i+1)
for i in range(0, 10, 2):
self.assertEqual(self.mf1.find(i), self.mf1.find(i+1))
self.assertEqual(self.mf2.find(i), self.mf2.find(i+1))
for i in range(0, 10-3, 4):
self.mf1.merge(i, i+3)
self.mf2.merge(i, i+3)
for i in range(0, 10-4, 4):
self.assertEqual(self.mf1.find(i), self.mf1.find(i+1))
self.assertEqual(self.mf1.find(i), self.mf1.find(i+2))
self.assertEqual(self.mf1.find(i), self.mf1.find(i+3))
self.assertEqual(self.mf2.find(i), self.mf2.find(i+1))
self.assertEqual(self.mf2.find(i), self.mf2.find(i+2))
self.assertEqual(self.mf2.find(i), self.mf2.find(i+3))
def test_repr(self):
aux = dict((i, set()) for i in range(10))
for i in range(10):
aux[self.mf2.find(i)].add(i)
all = set(frozenset(v) for v in aux.values())
mf2 = eval(repr(self.mf2))
aux = dict((i, set()) for i in range(10))
for i in range(10):
aux[self.mf2.find(i)].add(i)
all2 = set(frozenset(v) for v in aux.values())
self.assertEqual(all, all2)
class TestRankUnionMFset(unittest.TestCase):
def setUp(self):
self.mf1 = RankUnionMFset()
self.mf2 = RankUnionMFset(((i,) for i in range(10)), createMap=lambda nodes: IntKeyMap(capacity=max(nodes)+1))
def test_mfsets(self):
for i in range(10):
self.mf1.add(i)
for i in range(10):
self.assertEqual(self.mf1.find(i), i)
self.assertEqual(self.mf2.find(i), i)
for i in range(0, 10, 2):
self.mf1.merge(i, i+1)
self.mf2.merge(i, i+1)
for i in range(0, 10, 2):
self.assertEqual(self.mf1.find(i), self.mf1.find(i+1))
self.assertEqual(self.mf2.find(i), self.mf2.find(i+1))
for i in range(0, 10-3, 4):
self.mf1.merge(i, i+3)
self.mf2.merge(i, i+3)
for i in range(0, 10-4, 4):
self.assertEqual(self.mf1.find(i), self.mf1.find(i+1))
self.assertEqual(self.mf1.find(i), self.mf1.find(i+2))
self.assertEqual(self.mf1.find(i), self.mf1.find(i+3))
self.assertEqual(self.mf2.find(i), self.mf2.find(i+1))
self.assertEqual(self.mf2.find(i), self.mf2.find(i+2))
self.assertEqual(self.mf2.find(i), self.mf2.find(i+3))
def test_repr(self):
aux = dict((i, set()) for i in range(10))
for i in range(10):
aux[self.mf2.find(i)].add(i)
all = set(frozenset(v) for v in aux.values())
mf2 = eval(repr(self.mf2))
aux = dict((i, set()) for i in range(10))
for i in range(10):
aux[self.mf2.find(i)].add(i)
all2 = set(frozenset(v) for v in aux.values())
self.assertEqual(all, all2)
class TestPathCompressionMFset(unittest.TestCase):
def setUp(self):
self.mf1 = PathCompressionMFset()
self.mf2 = PathCompressionMFset(((i,) for i in range(10)), createMap=lambda nodes: IntKeyMap(capacity=max(nodes)+1))
def test_mfsets(self):
for i in range(10):
self.mf1.add(i)
for i in range(10):
self.assertEqual(self.mf1.find(i), i)
self.assertEqual(self.mf2.find(i), i)
for i in range(0, 10, 2):
self.mf1.merge(i, i+1)
self.mf2.merge(i, i+1)
for i in range(0, 10, 2):
self.assertEqual(self.mf1.find(i), self.mf1.find(i+1))
self.assertEqual(self.mf2.find(i), self.mf2.find(i+1))
for i in range(0, 10-3, 4):
self.mf1.merge(i, i+3)
self.mf2.merge(i, i+3)
for i in range(0, 10-4, 4):
self.assertEqual(self.mf1.find(i), self.mf1.find(i+1))
self.assertEqual(self.mf1.find(i), self.mf1.find(i+2))
self.assertEqual(self.mf1.find(i), self.mf1.find(i+3))
self.assertEqual(self.mf2.find(i), self.mf2.find(i+1))
self.assertEqual(self.mf2.find(i), self.mf2.find(i+2))
self.assertEqual(self.mf2.find(i), self.mf2.find(i+3))
def test_repr(self):
aux = dict((i, set()) for i in range(10))
for i in range(10):
aux[self.mf2.find(i)].add(i)
all = set(frozenset(v) for v in aux.values())
mf2 = eval(repr(self.mf2))
aux = dict((i, set()) for i in range(10))
for i in range(10):
aux[self.mf2.find(i)].add(i)
all2 = set(frozenset(v) for v in aux.values())
self.assertEqual(all, all2)
class TestMFset(unittest.TestCase):
def setUp(self):
self.mf1 = MergeFindSet()
self.mf2 = MergeFindSet(((i,) for i in range(10)), createMap=lambda nodes: IntKeyMap(capacity=max(nodes)+1))
def test_mfsets(self):
for i in range(10):
self.mf1.add(i)
for i in range(10):
self.assertEqual(self.mf1.find(i), i)
self.assertEqual(self.mf2.find(i), i)
for i in range(0, 10, 2):
self.mf1.merge(i, i+1)
self.mf2.merge(i, i+1)
for i in range(0, 10, 2):
self.assertEqual(self.mf1.find(i), self.mf1.find(i+1))
self.assertEqual(self.mf2.find(i), self.mf2.find(i+1))
for i in range(0, 10-3, 4):
self.mf1.merge(i, i+3)
self.mf2.merge(i, i+3)
for i in range(0, 10-4, 4):
self.assertEqual(self.mf1.find(i), self.mf1.find(i+1))
self.assertEqual(self.mf1.find(i), self.mf1.find(i+2))
self.assertEqual(self.mf1.find(i), self.mf1.find(i+3))
self.assertEqual(self.mf2.find(i), self.mf2.find(i+1))
self.assertEqual(self.mf2.find(i), self.mf2.find(i+2))
self.assertEqual(self.mf2.find(i), self.mf2.find(i+3))
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
|
GaneshSPatil/Transpiler
|
src/lib/arithmeticOperations.js
|
const util = require('./util.js');
const getNumber = util.getNumber;
const operators = {
'*': function(num1, num2, variables) {
return getNumber(num1, variables).value * getNumber(num2, variables).value;
},
'+': function(num1, num2, variables) {
return getNumber(num1, variables).value + getNumber(num2, variables).value;
},
'-': function(num1, num2, variables) {
return getNumber(num1, variables).value - getNumber(num2, variables).value;
},
'/': function(num1, num2, variables) {
return getNumber(num1, variables).value / getNumber(num2, variables).value;
},
'%': function(num1, num2, variables) {
return getNumber(num1, variables).value % getNumber(num2, variables).value;
}
};
module.exports = operators;
|
nleiva/telemetry-proto
|
proto_go/cisco_ios_xr_ipv6_new_dhcpv6d_oper/dhcpv6/nodes/node/proxy/profiles/profile/throttle_infos/throttle_info/ipv6_dhcpv6d_mac_throttle.pb.go
|
<filename>proto_go/cisco_ios_xr_ipv6_new_dhcpv6d_oper/dhcpv6/nodes/node/proxy/profiles/profile/throttle_infos/throttle_info/ipv6_dhcpv6d_mac_throttle.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: ipv6_dhcpv6d_mac_throttle.proto
package cisco_ios_xr_ipv6_new_dhcpv6d_oper_dhcpv6_nodes_node_proxy_profiles_profile_throttle_infos_throttle_info
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
// IPv6 DHCP Mac Throttle
type Ipv6Dhcpv6DMacThrottle_KEYS struct {
NodeName string `protobuf:"bytes,1,opt,name=node_name,json=nodeName,proto3" json:"node_name,omitempty"`
ProfileName string `protobuf:"bytes,2,opt,name=profile_name,json=profileName,proto3" json:"profile_name,omitempty"`
MacAddress string `protobuf:"bytes,3,opt,name=mac_address,json=macAddress,proto3" json:"mac_address,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *Ipv6Dhcpv6DMacThrottle_KEYS) Reset() { *m = Ipv6Dhcpv6DMacThrottle_KEYS{} }
func (m *Ipv6Dhcpv6DMacThrottle_KEYS) String() string { return proto.CompactTextString(m) }
func (*Ipv6Dhcpv6DMacThrottle_KEYS) ProtoMessage() {}
func (*Ipv6Dhcpv6DMacThrottle_KEYS) Descriptor() ([]byte, []int) {
return fileDescriptor_ipv6_dhcpv6d_mac_throttle_14af36ce68ca4376, []int{0}
}
func (m *Ipv6Dhcpv6DMacThrottle_KEYS) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Ipv6Dhcpv6DMacThrottle_KEYS.Unmarshal(m, b)
}
func (m *Ipv6Dhcpv6DMacThrottle_KEYS) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Ipv6Dhcpv6DMacThrottle_KEYS.Marshal(b, m, deterministic)
}
func (dst *Ipv6Dhcpv6DMacThrottle_KEYS) XXX_Merge(src proto.Message) {
xxx_messageInfo_Ipv6Dhcpv6DMacThrottle_KEYS.Merge(dst, src)
}
func (m *Ipv6Dhcpv6DMacThrottle_KEYS) XXX_Size() int {
return xxx_messageInfo_Ipv6Dhcpv6DMacThrottle_KEYS.Size(m)
}
func (m *Ipv6Dhcpv6DMacThrottle_KEYS) XXX_DiscardUnknown() {
xxx_messageInfo_Ipv6Dhcpv6DMacThrottle_KEYS.DiscardUnknown(m)
}
var xxx_messageInfo_Ipv6Dhcpv6DMacThrottle_KEYS proto.InternalMessageInfo
func (m *Ipv6Dhcpv6DMacThrottle_KEYS) GetNodeName() string {
if m != nil {
return m.NodeName
}
return ""
}
func (m *Ipv6Dhcpv6DMacThrottle_KEYS) GetProfileName() string {
if m != nil {
return m.ProfileName
}
return ""
}
func (m *Ipv6Dhcpv6DMacThrottle_KEYS) GetMacAddress() string {
if m != nil {
return m.MacAddress
}
return ""
}
type Ipv6Dhcpv6DMacThrottle struct {
// Client MAC address
BindingChaddr []byte `protobuf:"bytes,50,opt,name=binding_chaddr,json=bindingChaddr,proto3" json:"binding_chaddr,omitempty"`
// DHCP access interface
Ifname []byte `protobuf:"bytes,51,opt,name=ifname,proto3" json:"ifname,omitempty"`
// State of entry
State uint32 `protobuf:"varint,52,opt,name=state,proto3" json:"state,omitempty"`
// Time Left in secs
TimeLeft uint32 `protobuf:"varint,53,opt,name=time_left,json=timeLeft,proto3" json:"time_left,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *Ipv6Dhcpv6DMacThrottle) Reset() { *m = Ipv6Dhcpv6DMacThrottle{} }
func (m *Ipv6Dhcpv6DMacThrottle) String() string { return proto.CompactTextString(m) }
func (*Ipv6Dhcpv6DMacThrottle) ProtoMessage() {}
func (*Ipv6Dhcpv6DMacThrottle) Descriptor() ([]byte, []int) {
return fileDescriptor_ipv6_dhcpv6d_mac_throttle_14af36ce68ca4376, []int{1}
}
func (m *Ipv6Dhcpv6DMacThrottle) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Ipv6Dhcpv6DMacThrottle.Unmarshal(m, b)
}
func (m *Ipv6Dhcpv6DMacThrottle) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Ipv6Dhcpv6DMacThrottle.Marshal(b, m, deterministic)
}
func (dst *Ipv6Dhcpv6DMacThrottle) XXX_Merge(src proto.Message) {
xxx_messageInfo_Ipv6Dhcpv6DMacThrottle.Merge(dst, src)
}
func (m *Ipv6Dhcpv6DMacThrottle) XXX_Size() int {
return xxx_messageInfo_Ipv6Dhcpv6DMacThrottle.Size(m)
}
func (m *Ipv6Dhcpv6DMacThrottle) XXX_DiscardUnknown() {
xxx_messageInfo_Ipv6Dhcpv6DMacThrottle.DiscardUnknown(m)
}
var xxx_messageInfo_Ipv6Dhcpv6DMacThrottle proto.InternalMessageInfo
func (m *Ipv6Dhcpv6DMacThrottle) GetBindingChaddr() []byte {
if m != nil {
return m.BindingChaddr
}
return nil
}
func (m *Ipv6Dhcpv6DMacThrottle) GetIfname() []byte {
if m != nil {
return m.Ifname
}
return nil
}
func (m *Ipv6Dhcpv6DMacThrottle) GetState() uint32 {
if m != nil {
return m.State
}
return 0
}
func (m *Ipv6Dhcpv6DMacThrottle) GetTimeLeft() uint32 {
if m != nil {
return m.TimeLeft
}
return 0
}
func init() {
proto.RegisterType((*Ipv6Dhcpv6DMacThrottle_KEYS)(nil), "cisco_ios_xr_ipv6_new_dhcpv6d_oper.dhcpv6.nodes.node.proxy.profiles.profile.throttle_infos.throttle_info.ipv6_dhcpv6d_mac_throttle_KEYS")
proto.RegisterType((*Ipv6Dhcpv6DMacThrottle)(nil), "cisco_ios_xr_ipv6_new_dhcpv6d_oper.dhcpv6.nodes.node.proxy.profiles.profile.throttle_infos.throttle_info.ipv6_dhcpv6d_mac_throttle")
}
func init() {
proto.RegisterFile("ipv6_dhcpv6d_mac_throttle.proto", fileDescriptor_ipv6_dhcpv6d_mac_throttle_14af36ce68ca4376)
}
var fileDescriptor_ipv6_dhcpv6d_mac_throttle_14af36ce68ca4376 = []byte{
// 278 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x91, 0xc1, 0x4b, 0xc3, 0x30,
0x14, 0xc6, 0x89, 0xe2, 0xd8, 0xb2, 0xcd, 0x43, 0x10, 0xa9, 0x08, 0xae, 0x0e, 0x84, 0x9e, 0x7a,
0x70, 0xba, 0xbb, 0x88, 0x27, 0xc5, 0x43, 0x3d, 0x79, 0x7a, 0x64, 0xc9, 0xab, 0x0d, 0xb4, 0x49,
0x69, 0xc2, 0x9c, 0x47, 0xff, 0x00, 0xff, 0x67, 0xc9, 0x6b, 0x27, 0x78, 0xd8, 0xe5, 0x91, 0xef,
0xf7, 0xbd, 0xf7, 0xe5, 0x85, 0xf0, 0x85, 0x69, 0xb7, 0x6b, 0xd0, 0x95, 0x6a, 0xb7, 0x6b, 0x0d,
0x8d, 0x54, 0x10, 0xaa, 0xce, 0x85, 0x50, 0x63, 0xde, 0x76, 0x2e, 0x38, 0x51, 0x29, 0xe3, 0x95,
0x03, 0xe3, 0x3c, 0xec, 0x3a, 0xa0, 0x6e, 0x8b, 0x9f, 0x7f, 0x13, 0xae, 0xc5, 0x2e, 0xef, 0x45,
0x6e, 0x9d, 0x46, 0x4f, 0x35, 0xce, 0xee, 0xbe, 0x62, 0x2d, 0x4d, 0x8d, 0x7e, 0x7f, 0xc8, 0xf7,
0xd9, 0x60, 0x6c, 0xe9, 0xfc, 0x7f, 0xb9, 0xfc, 0x66, 0xfc, 0xea, 0xe0, 0x36, 0xf0, 0xfc, 0xf4,
0xfe, 0x26, 0x2e, 0xf9, 0x24, 0xc6, 0x83, 0x95, 0x0d, 0x26, 0x2c, 0x65, 0xd9, 0xa4, 0x18, 0x47,
0xf0, 0x2a, 0x1b, 0x14, 0xd7, 0x7c, 0x36, 0xdc, 0xd3, 0xfb, 0x47, 0xe4, 0x4f, 0x07, 0x46, 0x2d,
0x0b, 0x3e, 0x8d, 0xa1, 0x52, 0xeb, 0x0e, 0xbd, 0x4f, 0x8e, 0xa9, 0x83, 0x37, 0x52, 0x3d, 0xf4,
0x64, 0xf9, 0xc3, 0xf8, 0xc5, 0xc1, 0x1d, 0xc4, 0x0d, 0x3f, 0xdd, 0x18, 0xab, 0x8d, 0xfd, 0x00,
0x55, 0xc5, 0x90, 0xe4, 0x36, 0x65, 0xd9, 0xac, 0x98, 0x0f, 0xf4, 0x91, 0xa0, 0x38, 0xe7, 0x23,
0x53, 0xd2, 0x0a, 0x2b, 0xb2, 0x07, 0x25, 0xce, 0xf8, 0x89, 0x0f, 0x32, 0x60, 0x72, 0x97, 0xb2,
0x6c, 0x5e, 0xf4, 0x22, 0xbe, 0x29, 0x98, 0x06, 0xa1, 0xc6, 0x32, 0x24, 0xf7, 0xe4, 0x8c, 0x23,
0x78, 0xc1, 0x32, 0x6c, 0x46, 0xf4, 0x09, 0xab, 0xdf, 0x00, 0x00, 0x00, 0xff, 0xff, 0x1e, 0x6f,
0x1c, 0xb8, 0xa7, 0x01, 0x00, 0x00,
}
|
zhz44/mindspore
|
mindspore/ccsrc/plugin/device/ascend/kernel/aicpu/aicpu_ops/environ/aicpu_environ_manager.cc
|
<filename>mindspore/ccsrc/plugin/device/ascend/kernel/aicpu/aicpu_ops/environ/aicpu_environ_manager.cc<gh_stars>1-10
/**
* Copyright 2022 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 "environ/aicpu_environ_manager.h"
#include <string>
namespace aicpu {
constexpr auto kScalarTensorShapeDim = 1;
constexpr auto kScalarTensorShapeSize = 1;
constexpr auto kEnvValueTypeAttr = "value_type";
int64_t EnvironMgr::Create() {
std::unique_lock<std::mutex> lock(mutex);
if (env_handles_count_ >= INT64_MAX) {
AICPU_LOGE(" The handles number:%d is out of range: ", env_handles_count_);
return AICPU_KERNEL_STATE_PARAM_INVALID;
}
int64_t ret_handle = ++env_handles_count_;
auto env = std::make_shared<Environ>(ret_handle);
AICPU_CHECK_NULLPTR(env, AICPU_KERNEL_STATE_PARAM_INVALID, "env is null.");
envs_[ret_handle] = env;
return ret_handle;
}
EnvironPtr EnvironMgr::Get(int64_t handle) {
std::unique_lock<std::mutex> lock(mutex);
const auto &envIter = envs_.find(handle);
if (envIter != envs_.end()) {
auto &result = envIter->second;
return result;
}
return nullptr;
}
void EnvironMgr::Clear() {
std::unique_lock<std::mutex> lock(mutex);
for (auto &env : envs_) {
AICPU_CHECK_NULLPTR_VOID(env.second, "env is null.")
env.second->Clear();
}
envs_.clear();
}
bool EnvironMgr::IsScalarTensor(const aicpuops::Tensor &tensor) {
aicpuops::TensorShape shape = tensor.tensor_shape();
if (shape.dim_size() == 0) {
AICPU_LOGD("The shape is empty.");
return true;
}
if ((shape.dim_size() == kScalarTensorShapeDim) && (shape.dim(aicpu::kIndex0).size() == kScalarTensorShapeSize)) {
AICPU_LOGD("The tensor is scalar.");
return true;
}
return false;
}
bool EnvironMgr::CheckEnvInput(const aicpuops::NodeDef &node_def) {
::google::protobuf::Map<::std::string, ::aicpuops::AttrValue> nodedef_map = node_def.attrs();
auto value_type_attr = nodedef_map[kEnvValueTypeAttr].i();
if ((value_type_attr != kObjectTypeTensorType) && (value_type_attr != kObjectTypeEnvType)) {
AICPU_LOGE("The value type is not supported: [%d]", value_type_attr);
return false;
}
// Check the input handle.
if (!IsScalarTensor(node_def.inputs(aicpu::kIndex0))) {
AICPU_LOGE("The input handle checks invalid.");
return false;
}
// Check the input key
if (!IsScalarTensor(node_def.inputs(aicpu::kIndex1))) {
AICPU_LOGE("The input key checks invalid.");
return false;
}
// Check the input value
if ((value_type_attr == kObjectTypeEnvType) && (!IsScalarTensor(node_def.inputs(aicpu::kIndex2)))) {
AICPU_LOGE("The input value checks invalid.");
return false;
}
return true;
}
} // namespace aicpu
|
kgavrailov/multiapps-controller
|
com.sap.cloud.lm.sl.cf.core/src/main/java/com/sap/cloud/lm/sl/cf/core/helpers/v2_0/UserProvidedResourceResolver.java
|
package com.sap.cloud.lm.sl.cf.core.helpers.v2_0;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.sap.cloud.lm.sl.cf.core.helpers.v1_0.ResourceTypeFinder;
import com.sap.cloud.lm.sl.mta.builders.v2_0.ParametersChainBuilder;
import com.sap.cloud.lm.sl.mta.model.v1_0.Module;
import com.sap.cloud.lm.sl.mta.model.v2_0.Platform;
import com.sap.cloud.lm.sl.mta.model.v2_0.RequiredDependency;
import com.sap.cloud.lm.sl.mta.model.v2_0.Resource;
import com.sap.cloud.lm.sl.mta.model.v2_0.Target;
public class UserProvidedResourceResolver extends com.sap.cloud.lm.sl.cf.core.helpers.v1_0.UserProvidedResourceResolver {
private ParametersChainBuilder parametersChainBuilder;
public UserProvidedResourceResolver(ResourceTypeFinder resourceHelper,
com.sap.cloud.lm.sl.mta.model.v2_0.DeploymentDescriptor descriptor, Target target, Platform platform) {
super(resourceHelper, descriptor, target, platform);
this.parametersChainBuilder = new ParametersChainBuilder(descriptor, target, platform);
}
@Override
protected List<Map<String, Object>> buildModuleChain(com.sap.cloud.lm.sl.mta.model.v1_0.Module module) {
return parametersChainBuilder.buildModuleChain(module.getName());
}
@Override
protected void updateModuleRequiredDependencies(Module module, com.sap.cloud.lm.sl.mta.model.v1_0.Resource userProvidedResource) {
com.sap.cloud.lm.sl.mta.model.v2_0.Module moduleV2 = (com.sap.cloud.lm.sl.mta.model.v2_0.Module) module;
Resource resourceV2 = (Resource) userProvidedResource;
List<RequiredDependency> moduleRequiredDependencies = new ArrayList<>(moduleV2.getRequiredDependencies2_0());
RequiredDependency.Builder requiredDependencyBuilder = new RequiredDependency.Builder();
requiredDependencyBuilder.setName(resourceV2.getName());
moduleRequiredDependencies.add(requiredDependencyBuilder.build());
moduleV2.setRequiredDependencies2_0(moduleRequiredDependencies);
}
@Override
protected Resource createResource(String userProvidedServiceName, Map<String, Object> parameters) {
Resource.Builder builder = getResourceBuilder();
builder.setName(userProvidedServiceName);
builder.setType(resourceHelper.getResourceTypeName());
builder.setParameters(parameters);
return builder.build();
}
@Override
protected Resource.Builder getResourceBuilder() {
return new Resource.Builder();
}
}
|
isabella232/griffin-1
|
griffin-core/src/main/java/com/ebay/oss/griffin/vo/OverViewStatistics.java
|
/*
Copyright (c) 2016 eBay Software Foundation.
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.ebay.oss.griffin.vo;
public class OverViewStatistics {
private int assets;
private int metrics;
private DQHealthStats status;
public int getAssets() {
return assets;
}
public void setAssets(int assets) {
this.assets = assets;
}
public int getMetrics() {
return metrics;
}
public void setMetrics(int metrics) {
this.metrics = metrics;
}
public DQHealthStats getStatus() {
return status;
}
public void setStatus(DQHealthStats status) {
this.status = status;
}
}
|
franz1981/infinispan
|
core/src/main/java/org/infinispan/commands/write/InvalidateVersionsCommand.java
|
<filename>core/src/main/java/org/infinispan/commands/write/InvalidateVersionsCommand.java<gh_stars>1-10
package org.infinispan.commands.write;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.concurrent.CompletionStage;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.commands.remote.BaseRpcCommand;
import org.infinispan.container.DataContainer;
import org.infinispan.container.versioning.InequalVersionComparisonResult;
import org.infinispan.container.versioning.SimpleClusteredVersion;
import org.infinispan.distribution.DistributionManager;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.persistence.manager.OrderedUpdatesManager;
import org.infinispan.scattered.BiasManager;
import org.infinispan.statetransfer.StateTransferLock;
import org.infinispan.util.ByteString;
import org.infinispan.util.concurrent.CompletableFutures;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* Must be {@link VisitableCommand} as we want to catch it in persistence handling etc.
*
* @author <NAME> <<EMAIL>>
*/
public class InvalidateVersionsCommand extends BaseRpcCommand {
private static final Log log = LogFactory.getLog(InvalidateVersionsCommand.class);
private static final boolean trace = log.isTraceEnabled();
public static final int COMMAND_ID = 67;
// This is the topologyId in which this command is valid (in case that it comes from the state transfer)
private int topologyId;
private Object[] keys;
private int[] topologyIds;
private long[] versions;
// Removed means that the comparison will remove current versions as well
private boolean removed;
public InvalidateVersionsCommand() {
this(null);
}
public InvalidateVersionsCommand(ByteString cacheName) {
super(cacheName);
}
public InvalidateVersionsCommand(ByteString cacheName, int topologyId, Object[] keys, int[] topologyIds, long[] versions, boolean removed) {
super(cacheName);
this.topologyId = topologyId;
this.keys = keys;
this.topologyIds = topologyIds;
this.versions = versions;
this.removed = removed;
}
@Override
public CompletionStage<?> invokeAsync(ComponentRegistry componentRegistry) {
StateTransferLock stateTransferLock = componentRegistry.getStateTransferLock();
if (stateTransferLock != null) {
stateTransferLock.acquireSharedTopologyLock();
}
try {
DistributionManager distributionManager = componentRegistry.getDistributionManager();
if (topologyId >= 0 && distributionManager != null) {
int currentTopologyId = distributionManager.getCacheTopology().getTopologyId();
if (topologyId > currentTopologyId) {
if (trace) {
log.tracef("Delaying command %s, current topology id %d", this, currentTopologyId);
}
return stateTransferLock.topologyFuture(topologyId).thenCompose(nil -> invokeAsync(componentRegistry));
} else if (topologyId < currentTopologyId) {
log.ignoringInvalidateVersionsFromOldTopology(this.topologyId, currentTopologyId);
if (trace) {
log.tracef("Ignored command is %s", this);
}
return CompletableFutures.completedNull();
}
}
for (int i = 0; i < keys.length; ++i) {
Object key = keys[i];
if (key == null) break;
SimpleClusteredVersion version = new SimpleClusteredVersion(topologyIds[i], versions[i]);
BiasManager biasManager = componentRegistry.getBiasManager().running();
if (biasManager != null) {
biasManager.revokeLocalBias(key);
}
DataContainer dataContainer = componentRegistry.getInternalDataContainer().running();
dataContainer.compute(key, (k, oldEntry, factory) -> {
if (oldEntry == null) {
return null;
}
SimpleClusteredVersion localVersion = (SimpleClusteredVersion) oldEntry.getMetadata().version();
InequalVersionComparisonResult result = localVersion.compareTo(version);
if (result == InequalVersionComparisonResult.BEFORE || (removed && result == InequalVersionComparisonResult.EQUAL)) {
return null;
} else {
return oldEntry;
}
});
}
} finally {
if (stateTransferLock != null) {
stateTransferLock.releaseSharedTopologyLock();
}
}
OrderedUpdatesManager orderedUpdatesManager = componentRegistry.getOrderedUpdatesManager().running();
return orderedUpdatesManager.invalidate(keys).thenApply(nil -> null).toCompletableFuture();
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public boolean isReturnValueExpected() {
return false;
}
@Override
public void writeTo(ObjectOutput output) throws IOException {
output.writeInt(topologyId);
// TODO: topology ids are mostly the same - sort the arrays according to topologyIds and use compaction encoding
output.writeInt(keys.length);
for (int i = 0; i < keys.length; ++i) {
if (keys[i] == null) {
output.writeObject(null);
break;
} else {
output.writeObject(keys[i]);
output.writeInt(topologyIds[i]);
output.writeLong(versions[i]);
}
}
output.writeBoolean(removed);
}
@Override
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
topologyId = input.readInt();
keys = new Object[input.readInt()];
topologyIds = new int[keys.length];
versions = new long[keys.length];
for (int i = 0; i < keys.length; ++i) {
Object key = input.readObject();
if (key == null) {
break;
}
keys[i] = key;
topologyIds[i] = input.readInt();
versions[i] = input.readLong();
}
removed = input.readBoolean();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("InvalidateVersionsCommand{topologyId=").append(topologyId)
.append(", removed=").append(removed).append(": ");
if (keys.length > 0 && keys[0] != null) {
sb.append(keys[0]).append(" -> ").append(versions[0]);
} else {
sb.append("<no-keys>");
}
for (int i = 1; i < keys.length; ++i) {
if (keys[i] == null) break;
sb.append(", ").append(keys[i]).append(" -> ").append(versions[i]);
}
return sb.append("}").toString();
}
}
|
njj-gov/oauth-2.0-sdk-with-openid-connect-extensions
|
src/main/java/com/nimbusds/oauth2/sdk/auth/verifier/JWTAuthenticationClaimsSetVerifier.java
|
<filename>src/main/java/com/nimbusds/oauth2/sdk/auth/verifier/JWTAuthenticationClaimsSetVerifier.java<gh_stars>0
/*
* oauth2-oidc-sdk
*
* Copyright 2012-2016, Connect2id Ltd and contributors.
*
* 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.nimbusds.oauth2.sdk.auth.verifier;
import java.util.Set;
import net.jcip.annotations.Immutable;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.proc.BadJWTException;
import com.nimbusds.oauth2.sdk.assertions.jwt.JWTAssertionDetailsVerifier;
import com.nimbusds.oauth2.sdk.id.Audience;
/**
* JWT client authentication claims set verifier.
*
* <p>Related specifications:
*
* <ul>
* <li>OpenID Connect Core 1.0, section 9.
* <li>JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and
* Authorization Grants (RFC 7523).
* </ul>
*/
@Immutable
class JWTAuthenticationClaimsSetVerifier extends JWTAssertionDetailsVerifier {
// Cache JWT exceptions for quick processing of bad claims
/**
* Missing or invalid JWT claim exception.
*/
private static final BadJWTException ISS_SUB_MISMATCH_EXCEPTION =
new BadJWTException("Issuer and subject JWT claims don't match");
/**
* Creates a new JWT client authentication claims set verifier.
*
* @param expectedAudience The permitted audience (aud) claim values.
* Must not be empty or {@code null}. Should
* typically contain the token endpoint URI and
* for OpenID provider it may also include the
* issuer URI.
*/
public JWTAuthenticationClaimsSetVerifier(final Set<Audience> expectedAudience) {
super(expectedAudience);
}
@Override
public void verify(final JWTClaimsSet claimsSet)
throws BadJWTException {
super.verify(claimsSet);
// iss == sub
if (! claimsSet.getIssuer().equals(claimsSet.getSubject())) {
throw ISS_SUB_MISMATCH_EXCEPTION;
}
}
}
|
zhangguozhangyue/bigdatapig
|
src/main/java/cn/bluedot/core/domain/FetalStructure.java
|
<filename>src/main/java/cn/bluedot/core/domain/FetalStructure.java
package cn.bluedot.core.domain;
/**
*
* @author hxp
* 2018��8��7�� ����4:31:12
*/
public class FetalStructure {
/**
* ̥�νṹID
*/
private long fetalStructureID;
/**
* �����
*/
private String pigNo;
/**
* ĸ���ܲ�����
*/
private int totalNumber;
/**
* �����
*/
private int survivalNumber;
/**
* 30����̥��
*/
private long pregnacyRate;
/**
* ������
*/
private long deliveryRate;
public long getFetalStructureID() {
return fetalStructureID;
}
public void setFetalStructureID(long fetalStructureID) {
this.fetalStructureID = fetalStructureID;
}
public String getPigNo() {
return pigNo;
}
public void setPigNo(String pigNo) {
this.pigNo = pigNo;
}
public int getTotalNumber() {
return totalNumber;
}
public void setTotalNumber(int totalNumber) {
this.totalNumber = totalNumber;
}
public int getSurvivalNumber() {
return survivalNumber;
}
public void setSurvivalNumber(int survivalNumber) {
this.survivalNumber = survivalNumber;
}
public long getPregnacyRate() {
return pregnacyRate;
}
public void setPregnacyRate(long pregnacyRate) {
this.pregnacyRate = pregnacyRate;
}
public long getDeliveryRate() {
return deliveryRate;
}
public void setDeliveryRate(long deliveryRate) {
this.deliveryRate = deliveryRate;
}
}
|
Alx06/WinObjC
|
include/Platform/Universal Windows/UWP/WindowsSecurityAuthenticationOnlineId.h
|
<gh_stars>1-10
//******************************************************************************
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//******************************************************************************
// WindowsSecurityAuthenticationOnlineId.h
// Generated from winmd2objc
#pragma once
#include "interopBase.h"
@class WSAOOnlineIdServiceTicketRequest, WSAOOnlineIdServiceTicket, WSAOUserAuthenticationOperation, WSAOSignOutUserOperation, WSAOUserIdentity, WSAOOnlineIdAuthenticator;
@protocol WSAOIOnlineIdServiceTicketRequest, WSAOIOnlineIdServiceTicketRequestFactory, WSAOIOnlineIdServiceTicket, WSAOIUserIdentity, WSAOIOnlineIdAuthenticator;
// Windows.Security.Authentication.OnlineId.CredentialPromptType
enum _WSAOCredentialPromptType {
WSAOCredentialPromptTypePromptIfNeeded = 0,
WSAOCredentialPromptTypeRetypeCredentials = 1,
WSAOCredentialPromptTypeDoNotPrompt = 2,
};
typedef unsigned WSAOCredentialPromptType;
#include "WindowsFoundationCollections.h"
#include "WindowsFoundation.h"
// Windows.Foundation.AsyncActionCompletedHandler
#ifndef __WFAsyncActionCompletedHandler__DEFINED
#define __WFAsyncActionCompletedHandler__DEFINED
typedef void(^WFAsyncActionCompletedHandler)(RTObject<WFIAsyncAction>* asyncInfo, WFAsyncStatus asyncStatus);
#endif // __WFAsyncActionCompletedHandler__DEFINED
#import <Foundation/Foundation.h>
// Windows.Security.Authentication.OnlineId.OnlineIdServiceTicketRequest
#ifndef __WSAOOnlineIdServiceTicketRequest_DEFINED__
#define __WSAOOnlineIdServiceTicketRequest_DEFINED__
WINRT_EXPORT
@interface WSAOOnlineIdServiceTicketRequest : RTObject
+ (WSAOOnlineIdServiceTicketRequest*)createOnlineIdServiceTicketRequest:(NSString *)service policy:(NSString *)policy ACTIVATOR;
+ (WSAOOnlineIdServiceTicketRequest*)createOnlineIdServiceTicketRequestAdvanced:(NSString *)service ACTIVATOR;
@property (readonly) NSString * policy;
@property (readonly) NSString * service;
@end
#endif // __WSAOOnlineIdServiceTicketRequest_DEFINED__
// Windows.Security.Authentication.OnlineId.OnlineIdServiceTicket
#ifndef __WSAOOnlineIdServiceTicket_DEFINED__
#define __WSAOOnlineIdServiceTicket_DEFINED__
WINRT_EXPORT
@interface WSAOOnlineIdServiceTicket : RTObject
@property (readonly) int errorCode;
@property (readonly) WSAOOnlineIdServiceTicketRequest* request;
@property (readonly) NSString * value;
@end
#endif // __WSAOOnlineIdServiceTicket_DEFINED__
// Windows.Foundation.IAsyncInfo
#ifndef __WFIAsyncInfo_DEFINED__
#define __WFIAsyncInfo_DEFINED__
@protocol WFIAsyncInfo
@property (readonly) HRESULT errorCode;
@property (readonly) unsigned int id;
@property (readonly) WFAsyncStatus status;
- (void)cancel;
- (void)close;
@end
#endif // __WFIAsyncInfo_DEFINED__
// Windows.Security.Authentication.OnlineId.UserAuthenticationOperation
#ifndef __WSAOUserAuthenticationOperation_DEFINED__
#define __WSAOUserAuthenticationOperation_DEFINED__
WINRT_EXPORT
@interface WSAOUserAuthenticationOperation : RTObject <WFIAsyncInfo>
@property (readonly) HRESULT errorCode;
@property (readonly) unsigned int id;
@property (readonly) WFAsyncStatus status;
// Failed to generate property Completed (Can't marshal Windows.Foundation.AsyncOperationCompletedHandler`1<Windows.Security.Authentication.OnlineId.UserIdentity>)
// Could not find base class Windows.Foundation.IAsyncOperation`1<Windows.Security.Authentication.OnlineId.UserIdentity> type information
- (void)cancel;
- (void)close;
@end
#endif // __WSAOUserAuthenticationOperation_DEFINED__
// Windows.Foundation.IAsyncAction
#ifndef __WFIAsyncAction_DEFINED__
#define __WFIAsyncAction_DEFINED__
@protocol WFIAsyncAction <WFIAsyncInfo>
@property (copy) WFAsyncActionCompletedHandler completed;
- (void)getResults;
- (void)cancel;
- (void)close;
@end
#endif // __WFIAsyncAction_DEFINED__
// Windows.Security.Authentication.OnlineId.SignOutUserOperation
#ifndef __WSAOSignOutUserOperation_DEFINED__
#define __WSAOSignOutUserOperation_DEFINED__
WINRT_EXPORT
@interface WSAOSignOutUserOperation : RTObject <WFIAsyncAction, WFIAsyncInfo>
@property (readonly) HRESULT errorCode;
@property (readonly) unsigned int id;
@property (readonly) WFAsyncStatus status;
@property (copy) WFAsyncActionCompletedHandler completed;
- (void)getResults;
- (void)cancel;
- (void)close;
@end
#endif // __WSAOSignOutUserOperation_DEFINED__
// Windows.Security.Authentication.OnlineId.UserIdentity
#ifndef __WSAOUserIdentity_DEFINED__
#define __WSAOUserIdentity_DEFINED__
WINRT_EXPORT
@interface WSAOUserIdentity : RTObject
@property (readonly) NSString * firstName;
@property (readonly) NSString * id;
@property (readonly) BOOL isBetaAccount;
@property (readonly) BOOL isConfirmedPC;
@property (readonly) NSString * lastName;
@property (readonly) NSString * safeCustomerId;
@property (readonly) NSString * signInName;
@property (readonly) NSArray* tickets;
@end
#endif // __WSAOUserIdentity_DEFINED__
// Windows.Security.Authentication.OnlineId.OnlineIdAuthenticator
#ifndef __WSAOOnlineIdAuthenticator_DEFINED__
#define __WSAOOnlineIdAuthenticator_DEFINED__
WINRT_EXPORT
@interface WSAOOnlineIdAuthenticator : RTObject
+ (instancetype)create ACTIVATOR;
@property WFGUID* applicationId;
@property (readonly) NSString * authenticatedSafeCustomerId;
@property (readonly) BOOL canSignOut;
// Failed to generate member AuthenticateUserAsync (Can't marshal Windows.Foundation.IAsyncOperation`1<Windows.Security.Authentication.OnlineId.UserIdentity>)
// Failed to generate member AuthenticateUserAsync (Can't marshal Windows.Foundation.IAsyncOperation`1<Windows.Security.Authentication.OnlineId.UserIdentity>)
- (WSAOSignOutUserOperation*)signOutUserAsync;
@end
#endif // __WSAOOnlineIdAuthenticator_DEFINED__
|
mlange05/atlas
|
src/atlas/trans/ifs/VorDivToUVIFS.h
|
<filename>src/atlas/trans/ifs/VorDivToUVIFS.h
/*
* (C) Copyright 2013 ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
* In applying this licence, ECMWF does not waive the privileges and immunities
* granted to it by virtue of its status as an intergovernmental organisation
* nor does it submit to any jurisdiction.
*/
#pragma once
#include "transi/trans.h"
#include "atlas/trans/VorDivToUV.h"
//-----------------------------------------------------------------------------
// Forward declarations
namespace atlas {
class FunctionSpace;
}
//-----------------------------------------------------------------------------
namespace atlas {
namespace trans {
//-----------------------------------------------------------------------------
class VorDivToUVIFS : public trans::VorDivToUVImpl {
public:
VorDivToUVIFS( const FunctionSpace&, const eckit::Configuration& = util::NoConfig() );
VorDivToUVIFS( int truncation, const eckit::Configuration& = util::NoConfig() );
virtual ~VorDivToUVIFS();
virtual int truncation() const override { return truncation_; }
// pure virtual interface
// -- IFS style API --
// These fields have special interpretation required. You need to know what
// you're doing.
// See IFS trans library.
/*!
* @brief Compute spectral wind (U/V) from spectral vorticity/divergence
*
* U = u*cos(lat)
* V = v*cos(lat)
*
* @param nb_fields [in] Number of fields
* @param vorticity [in] Spectral vorticity
* @param divergence [in] Spectral divergence
* @param U [out] Spectral wind U = u*cos(lat)
* @param V [out] Spectral wind V = v*cos(lat)
*/
virtual void execute( const int nb_coeff, const int nb_fields, const double vorticity[], const double divergence[],
double U[], double V[], const eckit::Configuration& = util::NoConfig() ) const override;
private:
int truncation_;
};
// ------------------------------------------------------------------
} // namespace trans
} // namespace atlas
|
utexas-rl-texplore/rl_suite
|
rl_agent/src/Models/MultipleClassifiers.cc
|
/** \file MultipleClassifiers.cc
Implements the Multiple Classifiers class.
\author <NAME>
*/
#include "MultipleClassifiers.hh"
MultipleClassifiers::MultipleClassifiers(int id, int modelType, int predType,
int nModels, int trainMode,
int trainFreq,
float featPct, float expPct,
float treeThreshold, bool stoch,
float featRange, Random rng):
id(id), modelType(modelType), predType(predType), nModels(nModels),
mode(trainMode), freq(trainFreq),
featPct(featPct), expPct(expPct),
treeThresh(treeThreshold), stoch(stoch),
addNoise(!stoch && (modelType == M5MULTI || modelType == M5SINGLE || modelType == M5ALLMULTI || modelType == M5ALLSINGLE || modelType == LSTMULTI || modelType == LSTSINGLE)),
featRange(featRange),
rng(rng)
{
STDEBUG = false;//true;
ACC_DEBUG = false;//true;
PRED_DEBUG = false; //true;
CONF_DEBUG = false;
COPYDEBUG = false;
nsteps = 0;
cout << "Created MultClass " << id << " with nModels: " << nModels << ", addNoise: " << addNoise << endl;
for (int i = -1; i < id; i++)
rng.uniform(0,1);
initModels();
}
MultipleClassifiers::MultipleClassifiers(const MultipleClassifiers &t):
id(t.id), modelType(t.modelType), predType(t.predType), nModels(t.nModels),
mode(t.mode), freq(t.freq),
featPct(t.featPct), expPct(t.expPct),
treeThresh(t.treeThresh), stoch(t.stoch), addNoise(t.addNoise),
featRange(t.featRange), rng(t.rng)
{
COPYDEBUG = t.COPYDEBUG;
if (COPYDEBUG) cout << " MC copy constructor id " << id << endl;
STDEBUG = t.STDEBUG;
ACC_DEBUG = t.ACC_DEBUG;
PRED_DEBUG = t.PRED_DEBUG;
CONF_DEBUG = t.CONF_DEBUG;
nsteps = t.nsteps;
accuracy = t.accuracy;
infos.resize(nModels);
models.resize(nModels);
if (COPYDEBUG) cout << "models size now " << models.size() << " nModels: " << nModels << endl;
// copy each model
for (unsigned i = 0; i < models.size(); i++){
if (COPYDEBUG)cout << "MC copy model " << i << endl;
models[i] = t.models[i]->getCopy();
}
if (COPYDEBUG) cout << "MC copy complete models size: " << models.size() << endl;
}
MultipleClassifiers* MultipleClassifiers::getCopy(){
MultipleClassifiers* copy = new MultipleClassifiers(*this);
return copy;
}
MultipleClassifiers::~MultipleClassifiers() {
for (unsigned i = 0; i < models.size(); i++){
delete models[i];
}
models.clear();
accuracy.clear();
infos.clear();
}
bool MultipleClassifiers::trainInstances(std::vector<classPair> &instances){
if (STDEBUG) cout << id << " MultClass trainInstances: " << instances.size() << endl;
bool changed = false;
std::vector< std::vector<classPair> >subsets(nModels);
for (int i = 0; i < nModels; i++){
subsets[i].reserve(instances.size());
}
for (unsigned j = 0; j < instances.size(); j++){
bool didUpdate = false;
// train each model
for (int i = 0; i < nModels; i++){
// check accuracy of this model
if (predType == BEST || predType == WEIGHTAVG){
for (unsigned j = 0; j < instances.size(); j++){
updateModelAccuracy(i, instances[j].in, instances[j].out);
}
}
// create new vector with some random subset of experiences
if (rng.uniform() < expPct){
float origOutput = instances[j].out;
if (addNoise) instances[j].out += rng.uniform(-0.2,0.2)*treeThresh;
subsets[i].push_back(instances[j]);
if (addNoise) instances[j].out = origOutput;
didUpdate = true;
}
} // model loop
// make sure someone got this instance
if (!didUpdate){
int model = rng.uniformDiscrete(0,nModels-1);
//cout << "none got instance, update model " << model << endl;
if (addNoise) instances[j].out += rng.uniform(-0.2,0.2)*treeThresh;
subsets[model].push_back(instances[j]);
}
} // instances loop
// now update models
for (int i = 0; i < nModels; i++){
if (subsets[i].size() > 0){
if (STDEBUG) cout << id << " train model " << i << " on subset of size "
<< subsets[i].size() << endl;
bool singleChange = models[i]->trainInstances(subsets[i]);
changed = changed || singleChange;
}
}
nsteps += instances.size();
return changed;
}
// here the target output will be a single value
bool MultipleClassifiers::trainInstance(classPair &instance){
if (STDEBUG) cout << id << " trainInstance" << endl;
bool changed = false;
// train each model
bool didUpdate = false;
for (int i = 0; i < nModels; i++){
// check accuracy of this model
if (predType == BEST || predType == WEIGHTAVG){
updateModelAccuracy(i, instance.in, instance.out);
}
// update with new experience
if (rng.uniform() < expPct){
didUpdate = true;
float origOutput = instance.out;
if (addNoise) instance.out += rng.uniform(-0.2,0.2)*treeThresh;
bool singleChange = models[i]->trainInstance(instance);
if (addNoise) instance.out = origOutput;
changed = changed || singleChange;
}
}
// make sure some model got the transition
if (!didUpdate){
int model = rng.uniformDiscrete(0,nModels-1);
if (addNoise) instance.out += rng.uniform(-0.2,0.2)*treeThresh;
bool singleChange = models[model]->trainInstance(instance);
changed = singleChange || changed;
}
nsteps++;
return changed;
}
// get all the models outputs and combine them somehow
void MultipleClassifiers::testInstance(const std::vector<float> &input, std::map<float, float>* retval){
if (STDEBUG) cout << id << " testInstance" << endl;
if ((int)infos.size() != nModels){
infos.resize(nModels);
}
for (unsigned i = 0; i < infos.size(); i++){
infos[i].clear();
}
retval->clear();
// possibly have to init our model
if ((int)models.size() != nModels)
initModels();
///////////////////////////////////
// return best
if (predType == BEST){
float acc = -1.0;
int best = -1;
for (int i = 0; i < nModels; i++){
if (PRED_DEBUG) cout << "Model " << i << " has acc "
<< accuracy[i] << endl;
if (accuracy[i] > acc){
acc = accuracy[i];
best = i;
}
}
if (PRED_DEBUG) cout << id << " Returning model " << best
<< " with accuracy " << acc << endl;
models[best]->testInstance(input, retval);
return;
}
//////////////////////////////////////
/////////////////////////////////////////
// calculate weights for weighted avg
std::vector<float> weights(nModels, 1.0);
if (predType == WEIGHTAVG){
float accSum = 0.0;
for (int j = 0; j < nModels; j++){
accSum += accuracy[j];
}
if (accSum > 0.0){
for (int j = 0; j < nModels; j++){
weights[j] = (float)nModels * accuracy[j] / accSum;
if (PRED_DEBUG || ACC_DEBUG) cout << "Model " << j << " acc: "
<< accuracy[j] << " weight: "
<< weights[j] << endl;
}
}
}
/////////////////////////////////////////
// get state action info from each tree in our set
for (int j = 0; j < nModels; j++){
models[j]->testInstance(input, &(infos[j]));
}
// make a list of all outcomes any model predicted
for (int i = 0; i < nModels; i++){
for (std::map<float, float>::iterator it = infos[i].begin();
it != infos[i].end(); it++){
float outcome = (*it).first;
float prob = (*it).second;
// only if prob > 0
if (prob > 0){
// see if its not already in there
if (!retval->count(outcome)){
if (PRED_DEBUG) cout << " new outcome " << outcome << endl;
// check if it really is a new one
for (std::map<float, float>::iterator j = retval->begin();
j != retval->end(); j++){
if (fabs(outcome - j->first) < treeThresh){
if (PRED_DEBUG) cout << "within treeThresh of " << j->first << endl;
outcome = j->first;
break;
}
}
}
(*retval)[outcome] += (prob * weights[i] / (float)nModels);
if (PRED_DEBUG) cout << "inserting outcome " << outcome
<< " from model " << i
<< " with prob: " << prob
<< " and weight: " << weights[i]
<< " now total prob: " << (*retval)[outcome] << endl;
}
}
}
}
float MultipleClassifiers::getConf(const std::vector<float> &input){
if (STDEBUG || CONF_DEBUG) cout << id << " getConf" << endl;
if ((int)infos.size() != nModels){
infos.resize(nModels);
}
// get predictions if we haven't
if (predType == BEST || predType == SEPARATE){
if (CONF_DEBUG) cout << "conf: getting predictions again" << endl;
for (int j = 0; j < nModels; j++){
infos[j].clear();
models[j]->testInstance(input, &(infos[j]));
}
}
float conf = 0;
// for deterministic trees, calculating a distribution of outcomes
// calculate kl divergence
if (modelType == RMAX || modelType == SLF || modelType == C45TREE ||
modelType == STUMP ){
conf = 1.0 - klDivergence(input);
}
// for continuous trees, providing a single continuous prediction
// calcluate variance
else {
// use scaled sd
conf = 1.0 - sqrt(variance(input)) / featRange;
}
if (CONF_DEBUG) cout << "return conf: " << conf << endl;
return conf;
}
// calculate kl divergence of these predictions
float MultipleClassifiers::klDivergence(const std::vector<float> &input){
// KL divergence equation
// D_KL(P||Q) = SUM_i P(i) log (P(i)/Q(i))
float totalKL = 0.0;
// I guess let's take the avg KL divergence of comparisons
// between all pairs of models
for (int i = 0; i < nModels; i++){
for (int j = 0; j < nModels; j++){
if (i == j) continue;
float singleKL = 0.0;
for (std::map<float, float>::iterator it = infos[i].begin();
it != infos[i].end(); it++){
float outcome = (*it).first;
float prob = (*it).second;
if (prob == 0){
continue;
}
if (CONF_DEBUG)
cout << "model " << i << " predicts " << outcome << " with prob "
<< prob << ", model " << j << " has prob "
<< infos[j][outcome] << endl;
float jProb = infos[j][outcome];
if (jProb == 0) jProb = 0.01;
singleKL += prob * log(prob / jProb);
}
totalKL += singleKL;
if (CONF_DEBUG)
cout << "D_KL(" << i << "||" << j << ") = " << singleKL
<< " klsum: " << totalKL << endl;
} // outcomes of model i
} // models
int npairs = nModels * (nModels - 1);
float avgKL = totalKL / (float)npairs;
// normalize. since my 0 prob is really 0.01, and log 1/0.01 = 4.60517, we'll divide by that
avgKL /= 4.60517;
if (CONF_DEBUG) cout << "AvgKL: " << avgKL << endl << endl;
return avgKL;
}
// calculate the variance of these predictions
float MultipleClassifiers::variance(const std::vector<float> &input){
float sum = 0.0;
float sumSqr = 0.0;
for (int i = 0; i < nModels; i++){
float val = infos[i].begin()->first;
sum += val;
sumSqr += (val*val);
}
float mean = sum / (float)nModels;
float variance = (sumSqr - sum*mean) / (float)(nModels-1.0);
if (CONF_DEBUG) cout << "variance of predictions is " << variance << endl;
return variance;
}
// init models
void MultipleClassifiers::initModels(){
if (STDEBUG) cout << "initModels()" << endl;
models.resize(nModels);
accuracy.resize(nModels, 0.0);
// init the trees or stumps
for (int i = 0; i < nModels; i++){
if (modelType == C45TREE){
models[i] = new C45Tree(id + i*(1+nModels), mode, freq, 0, featPct, rng);
}
else if (modelType == M5MULTI){
models[i] = new M5Tree(id + i*(1+nModels), mode, freq, 0, featPct, false, false, treeThresh, rng);
}
else if (modelType == M5ALLMULTI){
models[i] = new M5Tree(id + i*(1+nModels), mode, freq, 0, featPct, false, true, treeThresh, rng);
}
else if (modelType == M5ALLSINGLE){
models[i] = new M5Tree(id + i*(1+nModels), mode, freq, 0, featPct, true, true, treeThresh, rng);
}
else if (modelType == M5SINGLE){
models[i] = new M5Tree(id + i*(1+nModels), mode, freq, 0, featPct, true, false, treeThresh, rng);
}
else if (modelType == LSTSINGLE){
models[i] = new LinearSplitsTree(id + i*(1+nModels), mode, freq, 0, featPct, true, treeThresh, rng);
}
else if (modelType == LSTMULTI){
models[i] = new LinearSplitsTree(id + i*(1+nModels), mode, freq, 0, featPct, false, treeThresh, rng);
}
else if (modelType == STUMP){
models[i] = new Stump(id + 1*(1+nModels), mode, freq, 0, featPct, rng);
}
else if (modelType == ALLM5TYPES){
// select an m5 type randomly. so multivariate v single and allfeats v subtree feats
bool simple = rng.bernoulli(0.5);
bool allFeats = rng.bernoulli(0.5);
//cout << "ALL types init tree " << i << " with simple: " << simple << " and allFeats: " << allFeats << endl;
models[i] = new M5Tree(id + i*(1+nModels), mode, freq, 0, featPct, simple, allFeats, treeThresh, rng);
}
else {
cout << "Invalid model type for this committee" << endl;
exit(-1);
}
}
}
void MultipleClassifiers::updateModelAccuracy(int i, const std::vector<float> &in,
float output){
if (ACC_DEBUG) cout << "Check model accuracy " << i << " curr: " << accuracy[i] << endl;
// get prediction
std::map<float, float> pred;
models[i]->testInstance(in, &pred);
// see if it was correct
bool correct = true;
// check trans prob
// for now, just see if prob of next was ML from this model
float prob = pred[output];
if (ACC_DEBUG) cout << "Model " << i << " predicted outcome "
<< output << " with prob: " << prob << endl;
if (prob <= 0.5)
correct = false;
// update accuracy
accuracy[i] = accuracy[i] * (float)nsteps/(float)(nsteps+1.0);
if (correct)
accuracy[i] += 1.0/(float)(nsteps+1.0);
if (ACC_DEBUG) cout << "Model " << i << " new accuracy: " << accuracy[i] << endl;
}
|
David-Jackson/SensESP
|
docs/generated/docs/search/enumvalues_1.js
|
<filename>docs/generated/docs/search/enumvalues_1.js
var searchData=
[
['bus_5fvoltage_1562',['bus_voltage',['../class_i_n_a219_value.html#a3e9bd0837f3e8b5cbe6f0cb1d2ed9110a6a7c7ba59fd86975b97fc7a8b7efce23',1,'INA219Value']]],
['buttonpress_1563',['ButtonPress',['../click__type_8h.html#a4a760072c8c7ae604f801ff82824b666ae331802be240d79912c365112ad41ddb',1,'click_type.h']]],
['buttonrelease_1564',['ButtonRelease',['../click__type_8h.html#a4a760072c8c7ae604f801ff82824b666ac58a283b80d411649376455b98710c95',1,'click_type.h']]]
];
|
KitwareMedical/itk-tube-web
|
src/ui/TubeTreeView.js
|
import React from 'react';
import PropTypes from 'prop-types';
import { observer } from 'mobx-react';
import { Spin, Button, Table } from 'antd';
import style from '../Tube.mcss';
import PopupColorPicker from './PopupColorPicker';
@observer
class Container extends React.Component {
static propTypes = {
stores: PropTypes.object.isRequired,
};
constructor(props) {
super(props);
this.state = this.initialState;
}
get initialState() {
return {
selection: {
keys: [],
rows: [],
},
};
}
createTubeTree(tubes) {
const keys = tubes.keys();
// shallow copy tubes
const tubesCopy = {};
for (let i = 0; i < keys.length; ++i) {
const id = keys[i];
tubesCopy[id] = Object.assign({}, tubes.get(id));
}
// assign children
for (let i = 0; i < keys.length; ++i) {
const id = keys[i];
const tube = tubesCopy[id];
if (tube.parent !== -1) {
const parent = tubesCopy[tube.parent];
if (!parent.children) {
parent.children = [];
}
parent.children.push(tube);
}
}
// create tree as ordered list, with only tubes that have no parents
const tree = keys
.filter(id => tubesCopy[id].parent === -1)
.map(id => tubesCopy[id]);
return tree;
}
render() {
const { stores: { tubeStore } } = this.props;
const { selection } = this.state;
const tubeTree = this.createTubeTree(tubeStore.tubes);
return (
<TubeTreeView
tubeTree={tubeTree}
selection={selection}
onVisibilityChange={(id, visible) => tubeStore.setTubeVisibility(id, visible)}
onColorChange={(id, color) => tubeStore.setTubeColor(id, color)}
onDelete={id => tubeStore.deleteTube(id)}
onReparent={(parent) => {
tubeStore.reparent(parent, this.state.selection.rows.map(t => t.id));
// clear selection
this.setState({ selection: { keys: [], rows: [] } });
}}
onSelectionChange={(keys, rows) => this.setState({ selection: { keys, rows } })}
/>
);
}
}
export default Container;
function TubeTreeView({
tubeTree,
selection,
onColorChange,
onVisibilityChange,
onDelete,
onReparent,
onSelectionChange,
}) {
const makeTubeControls = (color, visible, changeColor, changeVisible, deleteTube) => (
<span>
<PopupColorPicker
color={color}
onChange={rgb => changeColor(rgb)}
/>
<span className="ant-divider" />
<Button onClick={changeVisible}>
<i className={visible ? 'fa fa-eye' : 'fa fa-eye-slash'} />
</Button>
<span className="ant-divider" />
<Button onClick={deleteTube}>
<i className="fa fa-trash" />
</Button>
</span>
);
const makeReparentButton = reparentTubes => (
<Button onClick={reparentTubes}>
Make parent
</Button>
);
const columns = [
{
title: 'ID',
dataIndex: 'id',
},
{
title: '# of points',
dataIndex: 'mesh',
render: (mesh, tube) => (tube.status === 'done' && mesh ? mesh.length : '-'),
},
{
title: '',
dataIndex: '',
render: (_, tube) => {
if (tube.status === 'done') {
// no selection, so make standard tube controls
if (selection.keys.length === 0) {
return makeTubeControls(
tube.color.map(c => c * 255),
tube.visible,
// onColorChange
rgb => onColorChange(tube.id, [rgb.r / 255, rgb.g / 255, rgb.b / 255]),
// onVisibilityChange
() => onVisibilityChange(tube.id, !tube.visible),
// onDelete
() => onDelete(tube.id),
);
}
// selection exists, so show reparent button
return makeReparentButton(() => onReparent(tube.id));
}
// tube is pending, so show spinner
return <Spin />;
},
},
];
const rowSelection = {
selectedRowKeys: selection.keys,
onChange: onSelectionChange,
};
return (
<div className={[style.verticalContainer, style.itemStretch, style.border].join(' ')}>
<div className={[style.itemStretch, style.overflowScroll].join(' ')}>
<Table
rowKey="id"
pagination={false}
columns={columns}
dataSource={tubeTree}
rowSelection={rowSelection}
/>
</div>
</div>
);
}
TubeTreeView.propTypes = {
tubeTree: PropTypes.array.isRequired,
selection: PropTypes.shape({
keys: PropTypes.array.isRequired,
rows: PropTypes.array.isRequired,
}).isRequired,
onColorChange: PropTypes.func,
onVisibilityChange: PropTypes.func,
onDelete: PropTypes.func,
onReparent: PropTypes.func,
onSelectionChange: PropTypes.func,
};
TubeTreeView.defaultProps = {
onColorChange: () => {},
onVisibilityChange: () => {},
onDelete: () => {},
onReparent: () => {},
onSelectionChange: () => {},
};
|
QM-Quality-Manager/legacy-rest-api
|
libraries/node/examples/localization/get_display_tag_names.js
|
<filename>libraries/node/examples/localization/get_display_tag_names.js
const { LocalizationService } = require('../../lib/services');
const fs = require('fs');
const endPoint = "http://localhost:8080/qmplus/rest";
// const endPoint = null;
(async () => {
// Create user service
let service = new LocalizationService(endPoint);
// Execute the service
let result = await service.displayTagNames("", "mobile");
// Print the returned results
console.log(JSON.stringify(result, null, 2))
})().then(() => {}).catch(err => {
console.dir(err);
process.exit(0);
})
|
rhysd/rill
|
rill/ast/detail/base_type.hpp
|
<filename>rill/ast/detail/base_type.hpp<gh_stars>0
#pragma once
#include <type_traits>
namespace rill
{
namespace ast
{
namespace detail
{
template<typename=void>
struct ast_base_type_specifier {};
template<typename T>
using ast_base_type = typename ast_base_type_specifier<T>::type;
template<typename T>
using raw_ast_base_type = ast_base_type<std::decay_t<T>>;
} // namesapce detail
} // namespace ast
} // namespace rill
|
bpodell/whiteboard
|
05/__test__/link.test.js
|
<gh_stars>0
'use strict';
const link = require('../lib/link.js');
require('jest');
describe('#link', function () {
let proper = {
value: 1, next: {value: 2, next: {value: 3, next: {value: 4, next: null }}},
};
let nullLink = {
value: 1, next: {value: null, next: {value: 3, next: {value: 4, next: null }}},
};
it('should return half the object', function() {
expect(link.count(proper)).toEqual({value: 3, next: { value:4, next: null}});
});
it('should return err if input is not a linked list', function() {
expect(link.count('hello')).toEqual('err');
});
it('should return err if linked list has any null values', function() {
expect(link.count(nullLink)).toEqual('err');
});
});
|
ENDERZOMBI102/LoaderComplex
|
loadercomplex-bukkit/src/main/java/com/enderzombi102/loadercomplex/bukkit/impl/BukkitLoader.java
|
<filename>loadercomplex-bukkit/src/main/java/com/enderzombi102/loadercomplex/bukkit/impl/BukkitLoader.java
package com.enderzombi102.loadercomplex.bukkit.impl;
import com.enderzombi102.loadercomplex.api.Loader;
import com.enderzombi102.loadercomplex.api.Registry;
import com.enderzombi102.loadercomplex.api.utils.LoaderType;
import org.bukkit.Bukkit;
public class BukkitLoader implements Loader {
private final BukkitRegistry registry = new BukkitRegistry();
@Override
public LoaderType getLoaderType() {
return LoaderType.Bukkit;
}
@Override
public Registry getRegistry() {
return this.registry;
}
@Override
public String getMinecraftVersion() {
return Bukkit.getVersion();
}
@Override
public String getLoaderVersion() {
return Bukkit.getBukkitVersion();
}
@Override
public boolean isModLoaded(String id) {
return Bukkit.getPluginManager().getPlugin(id) != null;
}
}
|
gavineadie/Pachyderm
|
Applications/Pachyderm3/Sources/org/pachyderm/woc/AdminSettings.java
|
package org.pachyderm.woc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.webobjects.appserver.WOComponent;
import com.webobjects.appserver.WOContext;
public class AdminSettings extends AdminHelper {
private static Logger LOG = LoggerFactory.getLogger(AdminMonitor.class);
private static final long serialVersionUID = -169272400575177606L;
public AdminSettings(WOContext context) {
super(context);
}
public WOComponent submitAction () {
LOG.info(">> SUBMIT <<");
return null;
}
}
|
jinxiyang/Yunfan
|
app/src/main/java/com/yang/yunfan/ui/main/VideoFragment.java
|
<filename>app/src/main/java/com/yang/yunfan/ui/main/VideoFragment.java
package com.yang.yunfan.ui.main;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.yang.yunfan.R;
import com.yang.yunfan.ui.base.BaseFragment;
import com.yang.yunfan.ui.video.WeipaiVideoListFragment;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* A simple {@link Fragment} subclass.
*/
public class VideoFragment extends BaseFragment {
@BindView(R.id.status_bar)
View statusBar;
@BindView(R.id.tool_bar)
Toolbar toolBar;
@BindView(R.id.tv_title)
TextView tvTitle;
public VideoFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_video, container, false);
ButterKnife.bind(this, view);
tvTitle.setText(R.string.video);
return view;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getChildFragmentManager().beginTransaction().replace(R.id.contentFrame, new WeipaiVideoListFragment()).commit();
}
}
|
gridgentoo/gridgain
|
modules/core/src/test/java/org/gridgain/grid/GridExceptionHelpLinksSelfTest.java
|
package org.gridgain.grid;
import junit.framework.*;
import org.jetbrains.annotations.*;
import java.util.*;
import static org.gridgain.grid.util.GridUtils.*;
/**
* Tests for proper link output in stack traces.
*/
public class GridExceptionHelpLinksSelfTest extends TestCase {
/**
* @throws Exception If failed.
*/
public void testDefaultLinks() throws Exception {
assertTrue(hasLinksInMessage(new GridException("test"), DFLT_HELP_LINKS));
assertTrue(hasLinksInMessage(new GridException(new Exception()), DFLT_HELP_LINKS));
assertTrue(hasLinksInMessage(new GridException("test", new Exception()), DFLT_HELP_LINKS));
assertTrue(hasLinksInMessage(new GridRuntimeException("test"), DFLT_HELP_LINKS));
assertTrue(hasLinksInMessage(new GridRuntimeException(new Exception()), DFLT_HELP_LINKS));
assertTrue(hasLinksInMessage(new GridRuntimeException("test", new Exception()), DFLT_HELP_LINKS));
}
/**
* Tests default links suppression.
*/
public void testLinksUniqueness() {
assertLinksAppearOnce(
new GridException("test",
new GridException("test nested",
new GridException("last"))),
DFLT_HELP_LINKS);
assertLinksAppearOnce(
new GridRuntimeException("test",
new GridRuntimeException("test nested",
new GridRuntimeException("last"))),
DFLT_HELP_LINKS);
assertLinksAppearOnce(
new GridException("test",
new GridRuntimeException("test nested",
new GridException("last"))),
DFLT_HELP_LINKS);
assertLinksAppearOnce(
new GridRuntimeException("test",
new GridException("test nested",
new GridRuntimeException("last"))),
DFLT_HELP_LINKS);
}
/**
* @param e Root exception.
* @param links Set of links to ensure present only once in full stack trace.
*/
@SuppressWarnings("TypeMayBeWeakened")
private void assertLinksAppearOnce(Throwable e, List<String>... links) {
Set<List<String>> seen = new HashSet<>();
while (e != null) {
for (List<String> l : links)
if (hasLinksInMessage(e, l))
assertTrue(seen.add(l));
e = e.getCause();
}
}
/**
* @param e Exception
* @param links List of links.
* @return Whether exception has all passed links in it's message.
*/
private boolean hasLinksInMessage(Throwable e, @Nullable Iterable<String> links) {
if (links == null)
return true;
for (String link : links)
if (!e.getMessage().contains(link))
return false;
return true;
}
}
|
athenagroup/brxm
|
site-toolkit/components/core/src/main/java/org/hippoecm/hst/core/sitemenu/HstSiteMenuUtils.java
|
/*
* Copyright 2013 <NAME>. (http://www.onehippo.com)
*
* 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.hippoecm.hst.core.sitemenu;
import org.hippoecm.hst.configuration.sitemenu.HstSiteMenuItemConfiguration;
import org.hippoecm.hst.core.request.HstRequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HstSiteMenuUtils {
private static final Logger log = LoggerFactory.getLogger(HstSiteMenuUtils.class);
private HstSiteMenuUtils(){
}
public static boolean isUserInRole(final HstSiteMenuItemConfiguration hstSiteMenuItemConfiguration, final HstRequestContext hstRequestContext) {
for (String role : hstSiteMenuItemConfiguration.getRoles()) {
if (hstRequestContext.getServletRequest().isUserInRole(role)) {
log.debug("Found HstSiteMenuItemConfiguration '{}' to be in role '{}'", hstSiteMenuItemConfiguration.getName(), role);
return true;
}
}
log.debug("No matching role found for HstSiteMenuItemConfiguration '{}'", hstSiteMenuItemConfiguration.getName());
return false;
}
}
|
tillprochaska/honeypot
|
app/views/sensor_readings/index.json.jbuilder
|
# frozen_string_literal: true
json.array!(@sensor_readings) do |sensor_reading|
json.extract! sensor_reading, :id, :created_at, :calibrated_value, :uncalibrated_value, :annotation, :release
end
|
mrcybenz/test
|
codes/01-02-01-01-es2015-spec/12-arrow-func-this.js
|
// 箭头函数与 this
// 箭头函数不会改变 this 指向
const person = {
name: 'tom',
// sayHi: function () {
// console.log(`hi, my name is ${this.name}`)
// }
sayHi: () => {
console.log(`hi, my name is ${this.name}`)
},
sayHiAsync: function () {
// const _this = this
// setTimeout(function () {
// console.log(_this.name)
// }, 1000)
console.log(this)
setTimeout(() => {
// console.log(this.name)
console.log(this)
}, 1000)
}
}
person.sayHiAsync()
|
zhangxdnw/pc_remote_android
|
app/com_ss_android_ugc_aweme/180101/live_gift.py
|
<filename>app/com_ss_android_ugc_aweme/180101/live_gift.py
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File : live_gift.py
@Contact : <EMAIL>
@License : MIT
@Modify Time @Author @Version @Description
------------ ------- -------- -----------
2021/10/25 17:43 zxd 1.0 None
"""
import sys
import uiautomator2 as u2
from uiautomator2 import Device
from app.com_ss_android_ugc_aweme import constant
from app.com_ss_android_ugc_aweme.common import live_common
sys.path.append('app/com_ss_android_ugc_aweme/180101')
from constant180101 import *
def main(device: Device, params: str):
gift_type, page, index = live_common.check_gift_params(params);
if not live_common.live_do_gift(device, live_gift_click_id, "", page, "", "", ""):
return constant.LIVE_ERROR
else:
return constant.SUCCESS
if __name__ == '__main__':
main(u2.connect(), '{"type":0, "page":1, "index":2}')
|
mohdab98/cmps252_hw4.2
|
src/cmps252/HW4_2/UnitTesting/record_58.java
|
package cmps252.HW4_2.UnitTesting;
import static org.junit.jupiter.api.Assertions.*;
import java.io.FileNotFoundException;
import java.util.List;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import cmps252.HW4_2.Customer;
import cmps252.HW4_2.FileParser;
@Tag("8")
class Record_58 {
private static List<Customer> customers;
@BeforeAll
public static void init() throws FileNotFoundException {
customers = FileParser.getCustomers(Configuration.CSV_File);
}
@Test
@DisplayName("Record 58: FirstName is Ivan")
void FirstNameOfRecord58() {
assertEquals("Ivan", customers.get(57).getFirstName());
}
@Test
@DisplayName("Record 58: LastName is Cimaglia")
void LastNameOfRecord58() {
assertEquals("Cimaglia", customers.get(57).getLastName());
}
@Test
@DisplayName("Record 58: Company is Surveying And Mapping Inc")
void CompanyOfRecord58() {
assertEquals("Surveying And Mapping Inc", customers.get(57).getCompany());
}
@Test
@DisplayName("Record 58: Address is 29524 Kohoutek Way")
void AddressOfRecord58() {
assertEquals("29524 Kohoutek Way", customers.get(57).getAddress());
}
@Test
@DisplayName("Record 58: City is Union City")
void CityOfRecord58() {
assertEquals("Union City", customers.get(57).getCity());
}
@Test
@DisplayName("Record 58: County is Alameda")
void CountyOfRecord58() {
assertEquals("Alameda", customers.get(57).getCounty());
}
@Test
@DisplayName("Record 58: State is CA")
void StateOfRecord58() {
assertEquals("CA", customers.get(57).getState());
}
@Test
@DisplayName("Record 58: ZIP is 94587")
void ZIPOfRecord58() {
assertEquals("94587", customers.get(57).getZIP());
}
@Test
@DisplayName("Record 58: Phone is 510-429-4828")
void PhoneOfRecord58() {
assertEquals("510-429-4828", customers.get(57).getPhone());
}
@Test
@DisplayName("Record 58: Fax is 510-429-1348")
void FaxOfRecord58() {
assertEquals("510-429-1348", customers.get(57).getFax());
}
@Test
@DisplayName("Record 58: Email is <EMAIL>")
void EmailOfRecord58() {
assertEquals("<EMAIL>", customers.get(57).getEmail());
}
@Test
@DisplayName("Record 58: Web is http://www.ivancimaglia.com")
void WebOfRecord58() {
assertEquals("http://www.ivancimaglia.com", customers.get(57).getWeb());
}
}
|
brainvisa/aims-free
|
ecat/src/lib/lib_compress/c_uvlc.c
|
<filename>ecat/src/lib/lib_compress/c_uvlc.c
/*
* Copyright (C) 1993 University of Louvain, Louvain-la-Neuve, Belgium
* Telecommunication Laboratory.
*
* This program may be used free of charge by the members
* of all academic and/or scientific institutions.
* ANY OTHER USE IS PROHIBITED.
* It may also be included in any package
* - provided that this text is not removed from
* the source code and that reference to this original
* work is done ;
* - provided that this package is itself available
* for use, free of charge, to the members of all
* academic and/or scientific institutions.
* Nor the author, nor the Universite Catholique de Louvain, in any
* way guarantee that this program will fullfill any particular
* requirement, nor even that its use will always be harmless.
*
*
*/
/*
pcpet.c
pcpet (-in param) in out
param is a file containing
skipdpcm (int)
Long (int)
skipdpcm==1 if skip adpcm
skipdpcm==0 if not
Long = Length used for the UVLC (<1025)
*/
#include <ecat/lib_compress/uvlc.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* main routine */
void pcpet(skipdpcm, Long, input_filename, output_filename, ncol,nline)
int skipdpcm, Long;
char *input_filename, *output_filename;
int ncol,nline;
{
int *p1,*p2,i,j,i1,d1,d2,d3,d4,dmin;
int pout,rout,length,pp[1024], nind;
short ij;
FILE *input, *output;
nind=0;
input = fopen(input_filename,"r");
output = fopen(output_filename,"w");
/* get input header from input*/
/*
rewind(input);
fread(&ncol,4,1,input);
fread(&nline,4,1,input);
*/
p1=(int *) malloc(sizeof(int)*ncol*nline);
p2=(int *) malloc(sizeof(int)*ncol*nline);
for(i=0; i<nline; i++)
for(j=0; j<ncol; j++)
{
if ( fread(&ij,2,1,input) == 1 )
p2[i*ncol+j]=ij;
}
/*
rewind(output);
fwrite(&ncol,4,1,output);
fwrite(&nline,4,1,output);
*/
pout=0;
rout=0;
length=0;
for(i=0; i<nline; i++)
for(j=0; j<ncol; j++)
{
dmin=1000;d1=1000;d2=1000;d3=1000;d4=1000;
if(j>1)d1=abs(p2[i*ncol+j-1]-p2[i*ncol+j-2]);
if(i>1)d2=abs(p2[(i-1)*ncol+j]-p2[(i-2)*ncol+j]);
if(i>1&&j>1)d3=abs(p2[(i-1)*ncol+j-1]-p2[(i-2)*ncol+j-2]);
if(i>1&&j<(ncol-2))d4=abs(p2[(i-1)*ncol+j+1]-p2[(i-2)*ncol+j+2]);
if(d1<dmin)
{
dmin=d1;p1[i*ncol+j]=p2[i*ncol+j]-p2[i*ncol+j-1];
}
if(d2<dmin)
{
dmin=d2;p1[i*ncol+j]=p2[i*ncol+j]-p2[(i-1)*ncol+j];
}
if(d3<dmin)
{
dmin=d3;p1[i*ncol+j]=p2[i*ncol+j]-p2[(i-1)*ncol+j-1];
}
if(d4<dmin)
{
dmin=d4;p1[i*ncol+j]=p2[i*ncol+j]-p2[(i-1)*ncol+j+1];
}
if(dmin>=1000)
{
dmin=0;
if(j>0)p1[i*ncol+j]=p2[i*ncol+j]-p2[i*ncol+j-1];
else p1[i*ncol+j]=p2[i*ncol+j];
}
if(skipdpcm==0) pp[length]=p1[i*ncol+j];
else pp[length]=p2[i*ncol+j];
length+=1;
if(length==Long)
{
uvlc(pp,Long,output,&pout,&rout);
nind+=1;
length=0;
}
}
if(length!=0)
{
for(i1=length; i1<Long; i1++)pp[i1]=0;
uvlc(pp,Long,output,&pout,&rout);
nind+=1;
}
fwrite(&rout,4,1,output);
fclose(output);
fclose(input);
}
|
pozdnyakov/chromium-crosswalk
|
webkit/browser/dom_storage/dom_storage_namespace.h
|
<filename>webkit/browser/dom_storage/dom_storage_namespace.h
// Copyright (c) 2012 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.
#ifndef WEBKIT_BROWSER_DOM_STORAGE_DOM_STORAGE_NAMESPACE_H_
#define WEBKIT_BROWSER_DOM_STORAGE_DOM_STORAGE_NAMESPACE_H_
#include <map>
#include "base/basictypes.h"
#include "base/files/file_path.h"
#include "base/memory/ref_counted.h"
#include "webkit/browser/webkit_storage_browser_export.h"
class GURL;
namespace dom_storage {
class DomStorageArea;
class DomStorageTaskRunner;
class SessionStorageDatabase;
// Container for the set of per-origin Areas.
// See class comments for DomStorageContext for a larger overview.
class WEBKIT_STORAGE_BROWSER_EXPORT DomStorageNamespace
: public base::RefCountedThreadSafe<DomStorageNamespace> {
public:
// Option for PurgeMemory.
enum PurgeOption {
// Purge unopened areas only.
PURGE_UNOPENED,
// Purge aggressively, i.e. discard cache even for areas that have
// non-zero open count.
PURGE_AGGRESSIVE,
};
// Constructor for a LocalStorage namespace with id of 0
// and an optional backing directory on disk.
DomStorageNamespace(const base::FilePath& directory, // may be empty
DomStorageTaskRunner* task_runner);
// Constructor for a SessionStorage namespace with a non-zero id and an
// optional backing on disk via |session_storage_database| (may be NULL).
DomStorageNamespace(int64 namespace_id,
const std::string& persistent_namespace_id,
SessionStorageDatabase* session_storage_database,
DomStorageTaskRunner* task_runner);
int64 namespace_id() const { return namespace_id_; }
const std::string& persistent_namespace_id() const {
return persistent_namespace_id_;
}
// Returns the storage area for the given origin,
// creating instance if needed. Each call to open
// must be balanced with a call to CloseStorageArea.
DomStorageArea* OpenStorageArea(const GURL& origin);
void CloseStorageArea(DomStorageArea* area);
// Returns the area for |origin| if it's open, otherwise NULL.
DomStorageArea* GetOpenStorageArea(const GURL& origin);
// Creates a clone of |this| namespace including
// shallow copies of all contained areas.
// Should only be called for session storage namespaces.
DomStorageNamespace* Clone(int64 clone_namespace_id,
const std::string& clone_persistent_namespace_id);
void DeleteLocalStorageOrigin(const GURL& origin);
void DeleteSessionStorageOrigin(const GURL& origin);
void PurgeMemory(PurgeOption purge);
void Shutdown();
unsigned int CountInMemoryAreas() const;
private:
friend class base::RefCountedThreadSafe<DomStorageNamespace>;
// Struct to hold references to our contained areas and
// to keep track of how many tabs have a given area open.
struct AreaHolder {
scoped_refptr<DomStorageArea> area_;
int open_count_;
AreaHolder();
AreaHolder(DomStorageArea* area, int count);
~AreaHolder();
};
typedef std::map<GURL, AreaHolder> AreaMap;
~DomStorageNamespace();
// Returns a pointer to the area holder in our map or NULL.
AreaHolder* GetAreaHolder(const GURL& origin);
int64 namespace_id_;
std::string persistent_namespace_id_;
base::FilePath directory_;
AreaMap areas_;
scoped_refptr<DomStorageTaskRunner> task_runner_;
scoped_refptr<SessionStorageDatabase> session_storage_database_;
};
} // namespace dom_storage
#endif // WEBKIT_BROWSER_DOM_STORAGE_DOM_STORAGE_NAMESPACE_H_
|
6543-forks/fuxi
|
pkg/api/workload/handler/secret.go
|
package handler
import (
"encoding/json"
"github.com/gin-gonic/gin"
v1 "k8s.io/api/core/v1"
"net/http"
)
// Get Secret
func (w *WorkloadsAPI) GetSecret(g *gin.Context) {
namespace := g.Param("namespace")
name := g.Param("name")
item, err := w.secret.Get(namespace, name)
if err != nil {
toInternalServerError(g, "", err)
return
}
g.JSON(http.StatusOK, item)
}
// List Secret
func (w *WorkloadsAPI) ListSecret(g *gin.Context) {
list, err := w.secret.List("", "", 0, 0, nil)
if err != nil {
toInternalServerError(g, "", err)
return
}
secretList := &v1.SecretList{}
marshalData, err := json.Marshal(list)
if err != nil {
toInternalServerError(g, "", err)
return
}
err = json.Unmarshal(marshalData, secretList)
if err != nil {
toInternalServerError(g, "", err)
return
}
g.JSON(http.StatusOK, secretList)
}
|
ScalablyTyped/SlinkyTyped
|
e/exceljs/src/main/scala/typingsSlinky/exceljs/anon/PartialCsvReadOptions.scala
|
package typingsSlinky.exceljs.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
/* Inlined std.Partial<exceljs.exceljs.CsvReadOptions> */
@js.native
trait PartialCsvReadOptions extends StObject {
var dateFormats: js.UndefOr[js.Array[String]] = js.native
var map: js.UndefOr[js.Function2[/* value */ js.Any, /* index */ Double, _]] = js.native
var parserOptions: js.UndefOr[PartialFastCsvParserOptio] = js.native
var sheetName: js.UndefOr[String] = js.native
}
object PartialCsvReadOptions {
@scala.inline
def apply(): PartialCsvReadOptions = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[PartialCsvReadOptions]
}
@scala.inline
implicit class PartialCsvReadOptionsMutableBuilder[Self <: PartialCsvReadOptions] (val x: Self) extends AnyVal {
@scala.inline
def setDateFormats(value: js.Array[String]): Self = StObject.set(x, "dateFormats", value.asInstanceOf[js.Any])
@scala.inline
def setDateFormatsUndefined: Self = StObject.set(x, "dateFormats", js.undefined)
@scala.inline
def setDateFormatsVarargs(value: String*): Self = StObject.set(x, "dateFormats", js.Array(value :_*))
@scala.inline
def setMap(value: (/* value */ js.Any, /* index */ Double) => _): Self = StObject.set(x, "map", js.Any.fromFunction2(value))
@scala.inline
def setMapUndefined: Self = StObject.set(x, "map", js.undefined)
@scala.inline
def setParserOptions(value: PartialFastCsvParserOptio): Self = StObject.set(x, "parserOptions", value.asInstanceOf[js.Any])
@scala.inline
def setParserOptionsUndefined: Self = StObject.set(x, "parserOptions", js.undefined)
@scala.inline
def setSheetName(value: String): Self = StObject.set(x, "sheetName", value.asInstanceOf[js.Any])
@scala.inline
def setSheetNameUndefined: Self = StObject.set(x, "sheetName", js.undefined)
}
}
|
chgogos/oop
|
cpp_playground/ex035/profile1.cpp
|
#include <iostream>
#include <cmath>
void test1()
{
double sum = 0.0;
for (int i = 0; i < 1000000; i++)
{
for (int j = 0; j < 100; j++)
{
double x = i + 0.1;
sum += sqrt(x);
}
}
std::cout << sum << std::endl;
}
int main()
{
test1();
return 0;
}
|
christian-posta/gloo-mesh
|
pkg/meshctl/commands/install/enterprise/enterprise.go
|
package enterprise
import (
"context"
"github.com/rotisserie/eris"
"github.com/solo-io/gloo-mesh/pkg/meshctl/commands/install/internal/flags"
"github.com/solo-io/gloo-mesh/pkg/meshctl/install/gloomesh"
"github.com/solo-io/gloo-mesh/pkg/meshctl/install/helm"
"github.com/solo-io/gloo-mesh/pkg/meshctl/registration"
"github.com/solo-io/gloo-mesh/pkg/meshctl/utils"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
func Command(ctx context.Context, globalFlags *utils.GlobalFlags) *cobra.Command {
opts := &options{}
cmd := &cobra.Command{
Use: "enterprise",
Short: "Install Gloo Mesh enterprise",
RunE: func(cmd *cobra.Command, args []string) error {
opts.Verbose = globalFlags.Verbose
return install(ctx, opts)
},
}
opts.addToFlags(cmd.Flags())
cmd.SilenceUsage = true
return cmd
}
type options struct {
flags.Options
licenseKey string
skipUI bool
skipRBAC bool
}
func (o *options) addToFlags(flags *pflag.FlagSet) {
o.AddToFlags(flags)
flags.StringVar(&o.licenseKey, "license", "", "Gloo Mesh Enterprise license key")
cobra.MarkFlagRequired(flags, "license")
flags.BoolVar(&o.skipUI, "skip-ui", false, "Skip installation of the Gloo Mesh UI")
flags.BoolVar(&o.skipRBAC, "skip-rbac", false, "Skip installation of the RBAC Webhook")
}
func install(ctx context.Context, opts *options) error {
const (
repoURI = "https://storage.googleapis.com/gloo-mesh-enterprise"
chartName = "gloo-mesh-enterprise"
)
if opts.Version == "" {
version, err := helm.GetLatestChartVersion(repoURI, chartName)
if err != nil {
return err
}
opts.Version = version
}
installer := opts.GetInstaller(gloomesh.GlooMeshEnterpriseChartUriTemplate)
installer.Values["licenseKey"] = opts.licenseKey
if opts.skipUI {
installer.Values["gloo-mesh-ui.enabled"] = "false"
}
if opts.skipRBAC {
installer.Values["rbac-webhook.enabled"] = "false"
}
if err := installer.InstallGlooMeshEnterprise(ctx); err != nil {
return eris.Wrap(err, "installing gloo-mesh-enterprise")
}
if opts.Register && !opts.DryRun {
registrantOpts := opts.GetRegistrationOptions()
registrant, err := registration.NewRegistrant(®istrantOpts)
if err != nil {
return eris.Wrap(err, "initializing registrant")
}
if err := registrant.RegisterCluster(ctx); err != nil {
return eris.Wrap(err, "registering management-plane cluster")
}
}
return nil
}
|
kode54/it2play
|
it2drivers/sb16_m.c
|
/*
** ---- SB16 IT2 driver (mixing code) ----
*/
#include <stdint.h>
#include <stdbool.h>
#include "../it_structs.h"
#include "../it_music.h"
#include "sb16_m.h"
#define Get32BitI8Waveform /* 8bb: "12 Bit Interpolated" */ \
sample = smp[0]; \
sample2 = smp[1]; \
sample2 -= sample; \
sample2 *= (int32_t)sc->SmpError; \
sample2 >>= MIX_FRAC_BITS; \
sample += sample2;
#define Get32BitI16Waveform /* 8bb: "12 Bit Interpolated" */ \
sample = smp[0] >> 8; \
sample2 = smp[1] >> 8; \
sample2 -= sample; \
sample2 *= (int32_t)sc->SmpError; \
sample2 >>= MIX_FRAC_BITS; \
sample += sample2;
#define Get32Bit8Waveform /* 8bb: "32Bit Interpolated" */ \
sample = smp[0]; \
sample2 = smp[1]; \
sample2 -= sample; \
sample2 *= (int32_t)sc->SmpError; \
sample2 >>= MIX_FRAC_BITS-8; \
sample <<= 8; \
sample += sample2;
#define Get32Bit16Waveform /* 8bb: "32Bit Interpolated" */ \
sample = smp[0]; \
sample2 = smp[1]; \
sample2 -= sample; \
sample2 >>= 1; \
sample2 *= (int32_t)sc->SmpError; \
sample2 >>= MIX_FRAC_BITS-1; \
sample += sample2;
#define UpdatePos \
sc->SmpError += Driver.Delta; \
smp += (int32_t)sc->SmpError >> MIX_FRAC_BITS; \
sc->SmpError &= MIX_FRAC_MASK;
#define M12Mix8_M \
sample = *smp; \
MixBufPtr16[0] -= MixSegment[LeftVolume16 + (uint8_t)sample]; \
MixBufPtr16[2] -= MixSegment[RightVolume16 + (uint8_t)sample]; \
MixBufPtr16 += 4; \
UpdatePos
#define M12Mix16_M \
sample = (*smp) >> 8; \
MixBufPtr16[0] -= MixSegment[LeftVolume16 + (uint8_t)sample]; \
MixBufPtr16[2] -= MixSegment[RightVolume16 + (uint8_t)sample]; \
MixBufPtr16 += 4; \
UpdatePos
#define M12Mix8S_M \
sample = *smp; \
MixBufPtr16[0] -= MixSegment[LeftVolume16 + (uint8_t)sample]; \
MixBufPtr16[2] += MixSegment[RightVolume16 + (uint8_t)sample]; \
MixBufPtr16 += 4; \
UpdatePos
#define M12Mix16S_M \
sample = (*smp) >> 8; \
MixBufPtr16[0] -= MixSegment[LeftVolume16 + (uint8_t)sample]; \
MixBufPtr16[2] += MixSegment[RightVolume16 + (uint8_t)sample]; \
MixBufPtr16 += 4; \
UpdatePos
#define M12Mix8I_M \
Get32BitI8Waveform \
MixBufPtr16[0] -= MixSegment[LeftVolume16 + (uint8_t)sample]; \
MixBufPtr16[2] -= MixSegment[RightVolume16 + (uint8_t)sample]; \
MixBufPtr16 += 4; \
UpdatePos
#define M12Mix16I_M \
Get32BitI16Waveform \
MixBufPtr16[0] -= MixSegment[LeftVolume16 + (uint8_t)sample]; \
MixBufPtr16[2] -= MixSegment[RightVolume16 + (uint8_t)sample]; \
MixBufPtr16 += 4; \
UpdatePos
#define M12Mix8IS_M \
Get32BitI8Waveform \
MixBufPtr16[0] -= MixSegment[LeftVolume16 + (uint8_t)sample]; \
MixBufPtr16[2] += MixSegment[RightVolume16 + (uint8_t)sample]; \
MixBufPtr16 += 4; \
UpdatePos
#define M12Mix16IS_M \
Get32BitI16Waveform \
MixBufPtr16[0] -= MixSegment[LeftVolume16 + (uint8_t)sample]; \
MixBufPtr16[2] += MixSegment[RightVolume16 + (uint8_t)sample]; \
MixBufPtr16 += 4; \
UpdatePos
#define M32Mix8_M \
sample = *smp << 8; \
(*MixBufPtr++) -= sample * sc->LeftVolume; \
(*MixBufPtr++) -= sample * sc->RightVolume; \
UpdatePos
#define M32Mix16_M \
sample = *smp; \
(*MixBufPtr++) -= sample * sc->LeftVolume; \
(*MixBufPtr++) -= sample * sc->RightVolume; \
UpdatePos
#define M32Mix8S_M \
sample = *smp << 8; \
(*MixBufPtr++) -= sample * sc->LeftVolume; \
(*MixBufPtr++) += sample * sc->RightVolume; \
UpdatePos
#define M32Mix16S_M \
sample = *smp; \
(*MixBufPtr++) -= sample * sc->LeftVolume; \
(*MixBufPtr++) += sample * sc->RightVolume; \
UpdatePos
#define M32Mix8I_M \
Get32Bit8Waveform \
(*MixBufPtr++) -= sample * sc->LeftVolume; \
(*MixBufPtr++) -= sample * sc->RightVolume; \
UpdatePos
#define M32Mix16I_M \
Get32Bit16Waveform \
(*MixBufPtr++) -= sample * sc->LeftVolume; \
(*MixBufPtr++) -= sample * sc->RightVolume; \
UpdatePos
#define M32Mix8IS_M \
Get32Bit8Waveform \
(*MixBufPtr++) -= sample * sc->LeftVolume; \
(*MixBufPtr++) += sample * sc->RightVolume; \
UpdatePos
#define M32Mix16IS_M \
Get32Bit16Waveform \
(*MixBufPtr++) -= sample * sc->LeftVolume; \
(*MixBufPtr++) += sample * sc->RightVolume; \
UpdatePos
const mixFunc SB16_MixFunctionTables[16] =
{
(mixFunc)M12Mix8,
(mixFunc)M12Mix16,
(mixFunc)M12Mix8S,
(mixFunc)M12Mix16S,
(mixFunc)M12Mix8I,
(mixFunc)M12Mix16I,
(mixFunc)M12Mix8IS,
(mixFunc)M12Mix16IS,
(mixFunc)M32Mix8,
(mixFunc)M32Mix16,
(mixFunc)M32Mix8S,
(mixFunc)M32Mix16S,
(mixFunc)M32Mix8I,
(mixFunc)M32Mix16I,
(mixFunc)M32Mix8IS,
(mixFunc)M32Mix16IS
};
// 8bb: globalized
int16_t MixSegment[MIXTABLESIZE]; // 8bb: volume LUT for 16-bit mix mode
uint32_t LeftVolume16, RightVolume16;
// ------------------
void M12Mix8(slaveChn_t *sc, int32_t *MixBufPtr, int32_t NumSamples)
{
const int8_t *base = (int8_t *)sc->SmpOffs->Data;
const int8_t *smp = base + sc->SampleOffset;
int32_t sample;
int16_t *MixBufPtr16 = (int16_t *)MixBufPtr + 1;
for (int32_t i = 0; i < (NumSamples & 3); i++)
{
M12Mix8_M
}
NumSamples >>= 2;
for (int32_t i = 0; i < NumSamples; i++)
{
M12Mix8_M
M12Mix8_M
M12Mix8_M
M12Mix8_M
}
sc->SampleOffset = (int32_t)(smp - base);
}
void M12Mix16(slaveChn_t *sc, int32_t *MixBufPtr, int32_t NumSamples)
{
const int16_t *base = (int16_t *)sc->SmpOffs->Data;
const int16_t *smp = base + sc->SampleOffset;
int32_t sample;
int16_t *MixBufPtr16 = (int16_t *)MixBufPtr + 1;
for (int32_t i = 0; i < (NumSamples & 3); i++)
{
M12Mix16_M
}
NumSamples >>= 2;
for (int32_t i = 0; i < NumSamples; i++)
{
M12Mix16_M
M12Mix16_M
M12Mix16_M
M12Mix16_M
}
sc->SampleOffset = (int32_t)(smp - base);
}
void M12Mix8S(slaveChn_t *sc, int32_t *MixBufPtr, int32_t NumSamples)
{
const int8_t *base = (int8_t *)sc->SmpOffs->Data;
const int8_t *smp = base + sc->SampleOffset;
int32_t sample;
int16_t *MixBufPtr16 = (int16_t *)MixBufPtr + 1;
for (int32_t i = 0; i < (NumSamples & 3); i++)
{
M12Mix8S_M
}
NumSamples >>= 2;
for (int32_t i = 0; i < NumSamples; i++)
{
M12Mix8S_M
M12Mix8S_M
M12Mix8S_M
M12Mix8S_M
}
sc->SampleOffset = (int32_t)(smp - base);
}
void M12Mix16S(slaveChn_t *sc, int32_t *MixBufPtr, int32_t NumSamples)
{
const int16_t *base = (int16_t *)sc->SmpOffs->Data;
const int16_t *smp = base + sc->SampleOffset;
int32_t sample;
int16_t *MixBufPtr16 = (int16_t *)MixBufPtr + 1;
for (int32_t i = 0; i < (NumSamples & 3); i++)
{
M12Mix16S_M
}
NumSamples >>= 2;
for (int32_t i = 0; i < NumSamples; i++)
{
M12Mix16S_M
M12Mix16S_M
M12Mix16S_M
M12Mix16S_M
}
sc->SampleOffset = (int32_t)(smp - base);
}
void M12Mix8I(slaveChn_t *sc, int32_t *MixBufPtr, int32_t NumSamples)
{
const int8_t *base = (int8_t *)sc->SmpOffs->Data;
const int8_t *smp = base + sc->SampleOffset;
int32_t sample, sample2;
int16_t *MixBufPtr16 = (int16_t *)MixBufPtr + 1;
for (int32_t i = 0; i < (NumSamples & 3); i++)
{
M12Mix8I_M
}
NumSamples >>= 2;
for (int32_t i = 0; i < NumSamples; i++)
{
M12Mix8I_M
M12Mix8I_M
M12Mix8I_M
M12Mix8I_M
}
sc->SampleOffset = (int32_t)(smp - base);
}
void M12Mix16I(slaveChn_t *sc, int32_t *MixBufPtr, int32_t NumSamples)
{
const int16_t *base = (int16_t *)sc->SmpOffs->Data;
const int16_t *smp = base + sc->SampleOffset;
int32_t sample, sample2;
int16_t *MixBufPtr16 = (int16_t *)MixBufPtr + 1;
for (int32_t i = 0; i < (NumSamples & 3); i++)
{
M12Mix16I_M
}
NumSamples >>= 2;
for (int32_t i = 0; i < NumSamples; i++)
{
M12Mix16I_M
M12Mix16I_M
M12Mix16I_M
M12Mix16I_M
}
sc->SampleOffset = (int32_t)(smp - base);
}
void M12Mix8IS(slaveChn_t *sc, int32_t *MixBufPtr, int32_t NumSamples)
{
const int8_t *base = (int8_t *)sc->SmpOffs->Data;
const int8_t *smp = base + sc->SampleOffset;
int32_t sample, sample2;
int16_t *MixBufPtr16 = (int16_t *)MixBufPtr + 1;
for (int32_t i = 0; i < (NumSamples & 3); i++)
{
M12Mix8IS_M
}
NumSamples >>= 2;
for (int32_t i = 0; i < NumSamples; i++)
{
M12Mix8IS_M
M12Mix8IS_M
M12Mix8IS_M
M12Mix8IS_M
}
sc->SampleOffset = (int32_t)(smp - base);
}
void M12Mix16IS(slaveChn_t *sc, int32_t *MixBufPtr, int32_t NumSamples)
{
const int16_t *base = (int16_t *)sc->SmpOffs->Data;
const int16_t *smp = base + sc->SampleOffset;
int32_t sample, sample2;
int16_t *MixBufPtr16 = (int16_t *)MixBufPtr + 1;
for (int32_t i = 0; i < (NumSamples & 3); i++)
{
M12Mix16IS_M
}
NumSamples >>= 2;
for (int32_t i = 0; i < NumSamples; i++)
{
M12Mix16IS_M
M12Mix16IS_M
M12Mix16IS_M
M12Mix16IS_M
}
sc->SampleOffset = (int32_t)(smp - base);
}
void M32Mix8(slaveChn_t *sc, int32_t *MixBufPtr, int32_t NumSamples)
{
const int8_t *base = (int8_t *)sc->SmpOffs->Data;
const int8_t *smp = base + sc->SampleOffset;
int32_t sample;
for (int32_t i = 0; i < (NumSamples & 3); i++)
{
M32Mix8_M
}
NumSamples >>= 2;
for (int32_t i = 0; i < NumSamples; i++)
{
M32Mix8_M
M32Mix8_M
M32Mix8_M
M32Mix8_M
}
sc->SampleOffset = (int32_t)(smp - base);
}
void M32Mix16(slaveChn_t *sc, int32_t *MixBufPtr, int32_t NumSamples)
{
const int16_t *base = (int16_t *)sc->SmpOffs->Data;
const int16_t *smp = base + sc->SampleOffset;
int32_t sample;
for (int32_t i = 0; i < (NumSamples & 3); i++)
{
M32Mix16_M
}
NumSamples >>= 2;
for (int32_t i = 0; i < NumSamples; i++)
{
M32Mix16_M
M32Mix16_M
M32Mix16_M
M32Mix16_M
}
sc->SampleOffset = (int32_t)(smp - base);
}
void M32Mix8S(slaveChn_t *sc, int32_t *MixBufPtr, int32_t NumSamples)
{
const int8_t *base = (int8_t *)sc->SmpOffs->Data;
const int8_t *smp = base + sc->SampleOffset;
int32_t sample;
for (int32_t i = 0; i < (NumSamples & 3); i++)
{
M32Mix8S_M
}
NumSamples >>= 2;
for (int32_t i = 0; i < NumSamples; i++)
{
M32Mix8S_M
M32Mix8S_M
M32Mix8S_M
M32Mix8S_M
}
sc->SampleOffset = (int32_t)(smp - base);
}
void M32Mix16S(slaveChn_t *sc, int32_t *MixBufPtr, int32_t NumSamples)
{
const int16_t *base = (int16_t *)sc->SmpOffs->Data;
const int16_t *smp = base + sc->SampleOffset;
int32_t sample;
for (int32_t i = 0; i < (NumSamples & 3); i++)
{
M32Mix16S_M
}
NumSamples >>= 2;
for (int32_t i = 0; i < NumSamples; i++)
{
M32Mix16S_M
M32Mix16S_M
M32Mix16S_M
M32Mix16S_M
}
sc->SampleOffset = (int32_t)(smp - base);
}
void M32Mix8I(slaveChn_t *sc, int32_t *MixBufPtr, int32_t NumSamples)
{
const int8_t *base = (int8_t *)sc->SmpOffs->Data;
const int8_t *smp = base + sc->SampleOffset;
int32_t sample, sample2;
for (int32_t i = 0; i < (NumSamples & 3); i++)
{
M32Mix8I_M
}
NumSamples >>= 2;
for (int32_t i = 0; i < NumSamples; i++)
{
M32Mix8I_M
M32Mix8I_M
M32Mix8I_M
M32Mix8I_M
}
sc->SampleOffset = (int32_t)(smp - base);
}
void M32Mix16I(slaveChn_t *sc, int32_t *MixBufPtr, int32_t NumSamples)
{
const int16_t *base = (int16_t *)sc->SmpOffs->Data;
const int16_t *smp = base + sc->SampleOffset;
int32_t sample, sample2;
for (int32_t i = 0; i < (NumSamples & 3); i++)
{
M32Mix16I_M
}
NumSamples >>= 2;
for (int32_t i = 0; i < NumSamples; i++)
{
M32Mix16I_M
M32Mix16I_M
M32Mix16I_M
M32Mix16I_M
}
sc->SampleOffset = (int32_t)(smp - base);
}
void M32Mix8IS(slaveChn_t *sc, int32_t *MixBufPtr, int32_t NumSamples)
{
const int8_t *base = (int8_t *)sc->SmpOffs->Data;
const int8_t *smp = base + sc->SampleOffset;
int32_t sample, sample2;
for (int32_t i = 0; i < (NumSamples & 3); i++)
{
M32Mix8IS_M
}
NumSamples >>= 2;
for (int32_t i = 0; i < NumSamples; i++)
{
M32Mix8IS_M
M32Mix8IS_M
M32Mix8IS_M
M32Mix8IS_M
}
sc->SampleOffset = (int32_t)(smp - base);
}
void M32Mix16IS(slaveChn_t *sc, int32_t *MixBufPtr, int32_t NumSamples)
{
const int16_t *base = (int16_t *)sc->SmpOffs->Data;
const int16_t *smp = base + sc->SampleOffset;
int32_t sample, sample2;
for (int32_t i = 0; i < (NumSamples & 3); i++)
{
M32Mix16IS_M
}
NumSamples >>= 2;
for (int32_t i = 0; i < NumSamples; i++)
{
M32Mix16IS_M
M32Mix16IS_M
M32Mix16IS_M
M32Mix16IS_M
}
sc->SampleOffset = (int32_t)(smp - base);
}
|
kifj/ioc-unit
|
modules/ioc-unit-ejb/src/main/java/com/oneandone/iocunit/ejb/trainterceptors/TransactionalInterceptorMandatory.java
|
package com.oneandone.iocunit.ejb.trainterceptors;
import static javax.transaction.Transactional.TxType.MANDATORY;
import javax.annotation.Priority;
import javax.interceptor.Interceptor;
import javax.transaction.Transactional;
/**
* @author aschoerk
*/
@Interceptor
@Priority(Interceptor.Priority.PLATFORM_BEFORE + 200)
@Transactional(MANDATORY)
public class TransactionalInterceptorMandatory extends TransactionalInterceptorJtaBase {
}
|
pmark/jivepages
|
spec/views/boxes/new.html.erb_spec.rb
|
<reponame>pmark/jivepages
require File.dirname(__FILE__) + '/../../spec_helper'
describe "/boxes/new.html.erb" do
include BoxesHelper
before(:each) do
@box = mock_model(Box)
@box.stub!(:new_record?).and_return(true)
@box.stub!(:jivepage_id).and_return("1")
@box.stub!(:cell_id).and_return("1")
@box.stub!(:content).and_return("MyText")
@box.stub!(:position).and_return("1")
assigns[:box] = @box
end
it "should render new form" do
render "/boxes/new.html.erb"
response.should have_tag("form[action=?][method=post]", boxes_path) do
with_tag("textarea#box_content[name=?]", "box[content]")
with_tag("input#box_position[name=?]", "box[position]")
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.