repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
ollfkaih/lego
|
lego/apps/events/migrations/0016_auto_20180223_1614.py
|
<reponame>ollfkaih/lego
# Generated by Django 2.0.2 on 2018-02-23 16:14
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("events", "0015_event_responsible_group")]
operations = [
migrations.AlterField(
model_name="event",
name="responsible_group",
field=models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="events",
to="users.AbakusGroup",
),
)
]
|
PhenixRTS/PlatformTesting
|
scripts/run.js
|
/**
* Copyright 2020 Phenix Real Time Solutions, 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.
*/
const Logger = require('./logger.js');
const logger = new Logger('');
function run(module) {
if (typeof module !== 'object') { // eslint-disable-line lodash/prefer-lodash-typecheck
throw new Error(`run accepts object argument only, ${module} was passed in`);
}
const start = new Date();
logger.log(`Starting ${global.process.argv[2]}...`);
return module
.finally(() => {
const end = new Date();
const time = end.getTime() - start.getTime();
logger.log(`Finished ${global.process.argv[2]} after ${time} ms`);
}).catch(e => {
throw e;
});
}
if (global.process.argv.length > 2) {
const module = require(`./${global.process.argv[2]}.js`);
run(module)
.catch(err => {
if (err.length) {
err.forEach(e => console.error(e));
} else {
console.error(err);
}
global.process.exit(1);
});
}
module.exports = run;
|
paulmach/osmzen
|
util/streetnames/shorten_test.go
|
<reponame>paulmach/osmzen
package streetnames
import "testing"
func TestShorten(t *testing.T) {
cases := []struct {
in, out string
}{
{"Wodehouse Avenue", "Wodehouse Ave."},
{"Wodehouse Rd", "Wodehouse Rd."},
{"Wodehouse Street North", "Wodehouse St. N"},
{"South Wodehouse Boulevard", "S Wodehouse Blvd."},
{"East Highway", "East Hwy."},
{"North Expressway Northeast", "North Expwy. NE"},
{"SW North Lane", "SW North Ln."},
{"Street Dr", "Street Dr."},
{"Road Street North", "Road St. N"},
{"Parkway", "Parkway"},
{" East Highway ", "East Hwy."},
}
for _, tc := range cases {
t.Run(tc.in, func(t *testing.T) {
r := Shorten(tc.in)
if r != tc.out {
t.Errorf("incorrect shorten: %v != %v", r, tc.out)
}
})
}
}
|
ibalajiarun/go-consensus
|
protocols/dqpbft/dqpbftpb/types.go
|
<gh_stars>1-10
package dqpbftpb
import (
"bytes"
fmt "fmt"
proto "github.com/gogo/protobuf/proto"
"github.com/ibalajiarun/go-consensus/peer/peerpb"
)
type Index uint64
type View uint64
func (idx *Index) GetAndIncrement() Index {
index := *idx
*idx = *idx + 1
return index
}
func (m *InstanceState) IsPrePrepared() bool {
return m.Status == InstanceState_PrePrepared
}
func (m *InstanceState) IsPrepared() bool {
return m.Status == InstanceState_Prepared
}
func (m *InstanceState) IsCommitted() bool {
return m.Status == InstanceState_Committed
}
func (m *OInstanceState) IsPrePrepared() bool {
return m.Status == OInstanceState_OPrePrepared
}
func (m *OInstanceState) IsPrepared() bool {
return m.Status == OInstanceState_OPrepared
}
func (m *OInstanceState) IsCommitted() bool {
return m.Status == OInstanceState_OCommitted
}
func (m InstanceID) Equals(other InstanceID) bool {
return m.ReplicaID == other.ReplicaID && m.Index == other.Index
}
func (m *AgreementMessage) Equals(other *AgreementMessage) bool {
if m.View != other.View {
return false
}
if !m.InstanceID.Equals(other.InstanceID) {
return false
}
return bytes.Equal(m.CommandHash, other.CommandHash)
}
func (m *OAgreementMessage) Equals(other *OAgreementMessage) bool {
if m.View != other.View {
return false
}
if m.Index != other.Index {
return false
}
return bytes.Equal(m.CommandHash, other.CommandHash)
}
// WrapMessageInner wraps a union type of Message in a new isMessage_Type.
func WrapMessageInner(msg proto.Message) isDQPBFTMessage_Type {
switch t := msg.(type) {
case *AgreementMessage:
return &DQPBFTMessage_Agreement{Agreement: t}
case *OAgreementMessage:
return &DQPBFTMessage_OAgreement{OAgreement: t}
default:
panic(fmt.Sprintf("proto: unexpected type %T in WrapMessageInner", t))
}
}
// WrapDQPBFTMessage wraps a union type of Message in a new PBFTMessage without a
// destination.
func WrapDQPBFTMessage(msg proto.Message) *DQPBFTMessage {
return &DQPBFTMessage{Type: WrapMessageInner(msg)}
}
func ReplicaIDEquals(a, b []peerpb.PeerID) bool {
if len(a) != len(b) {
return false
}
for i, v := range a {
if v != b[i] {
return false
}
}
return true
}
func InstancesEquals(a, b []InstanceID) bool {
if len(a) != len(b) {
return false
}
for i, v := range a {
if !v.Equals(b[i]) {
return false
}
}
return true
}
|
fallingsoulm/easy-archetype-module
|
easy-archetype-security/easy-archetype-security-starter/src/main/java/io/github/fallingsoulm/easy/archetype/security/oauth/TokenConfig.java
|
<gh_stars>0
package io.github.fallingsoulm.easy.archetype.security.oauth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.jwk.JwkTokenStore;
import org.springframework.util.Assert;
/**
* 令牌配置
*
* @author luyanan
* @since 2021/2/19
**/
@ConditionalOnMissingBean(TokenConfig.class)
@Configuration
public class TokenConfig {
@Autowired
private SpringSecurityOauthProperties springSecurityOauthProperties;
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
Assert.hasText(springSecurityOauthProperties.getTokenSigningKey(), "资源服务器密钥不能为空");
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
// 对称密钥,资源服务器使用该密钥进行验证
converter.setSigningKey(springSecurityOauthProperties.getTokenSigningKey());
return converter;
}
}
|
NextZeus/beyond-webapp
|
unicom/libs/vmss/index.js
|
<reponame>NextZeus/beyond-webapp
var soap = require('soap');
var path = require('path');
var async = require('async');
var soapClient;
var VMSS = {};
VMSS.soap = function(next) {
if (soapClient) return next();
// create soap client
soap.createClient(
path.join(__dirname, 'wsdl.xml'),
function(err, client) {
if (err) throw err;
console.log('soapClient is created.');
soapClient = client;
next();
}
);
};
VMSS.soap2 = function(userName, userPawd, action, done) {
async.series([
function(callback){
VMSS.soap(function(){
callback();
});
},
function(callback){
VMSS.bind(userName, userPawd, callback);
},
action,
function(callback){
VMSS.unBind(userName, callback);
},
], function(err,results){
done(err,results[2]);
});
};
var binded = false;
VMSS.bind = function(userName, userPawd, callback) {
if (binded) return callback();
soapClient.bind({
userName: userName,
userPawd: userPawd,
}, function(err, result) {
if (err) return callback(err);
binded = true;
callback(err, result);
});
};
VMSS.unBind = function(userName, callback) {
if(!binded) return callback();
soapClient.unBind({
userName: userName
}, function(err, result) {
if (err) return callback(err);
binded = false;
callback(err, result);
});
};
VMSS.sendProductBag = function(phones, seq_no, operUser, operPawd, code, Final_seq_id, Tastedate, callback) {
if (typeof phones == 'string') phones = [phones];
soapClient.sendProductBag({
phones: phones,
seq_no: seq_no,
operUser: operUser,
operPawd: operPawd,
code: code,
Final_seq_id: Final_seq_id,
Tastedate: Tastedate
}, callback);
};
VMSS.querySeqNo = function(seq_no, operUser, operPawd, btime, etime) {
soapClient.querySeqNo({
seq_no: seq_no,
operUser: operUser,
operPawd: operPawd,
btime: btime,
etime: etime,
}, function(err, result) {
console.log(result);
callback(err, result);
});
};
VMSS.queryResult = function(seq_no, usernumber, operUser, operPawd) {
soapClient.queryResult({
seq_no: seq_no,
usernumber: usernumber,
operUser: operUser,
operPawd: operPawd
}, function(err, result) {
console.log(result);
callback(err, result);
});
};
exports = module.exports = VMSS;
//unit test
if (process.argv[1] === __filename) {
var _ = require('underscore');
var util = require('util');
//** USE CASE 1
VMSS.soap(function() {
// console.log(_.keys(VMSS));
// console.log(_.functions(VMSS));
// console.log(_.keys(VMSS));
// return;
VMSS.bind('sp_jstz', 'sp_jstz', function(err, result) {
if (err) return console.log(err);
console.log(result);
VMSS.unBind('sp_jstz', function(err, result) {
if (err) return console.log(err);
console.log(result);
});
});
});
//** USE CASE 2
VMSS.soap(function(){
async.series([
function(callback){
VMSS.bind('sp_jstz', 'sp_jstz', callback);
},
//action,
function(callback){
VMSS.unBind('sp_jstz', callback);
},
], function(err,results){
if(err) return console.log(err);
console.log(results);
});
});
//** USE CASE 3
VMSS.soap2('sp_jstz', 'sp_jstz',function(callback){
VMSS.queryResult('seq_no','usernumber', 'operUser', 'operPawd', callback);
},function(err,result){
if(err) return console.log(err);
//** queryResult() 的返回结果
console.log(result);
});
}
|
DragonJoker/Aria
|
source/Aria/Database/DbParameteredObject.cpp
|
<reponame>DragonJoker/Aria
#include "Database/DbParameteredObject.hpp"
#include "Database/DbParameter.hpp"
#include <algorithm>
#include <sstream>
namespace aria::db
{
static const std::string ERROR_DB_PARAMETER_INDEX = "No query parameter at index: ";
static const std::string ERROR_DB_PARAMETER_NAME = "No query parameter named: ";
static const std::string ERROR_DB_PARAMETER_ALREADY_ADDED = "Parameter with givent name already exists: ";
static const std::string ERROR_DB_PARAMETER_INITIALISATION = "Parametered object initialisation failed: ";
static const std::string ERROR_DB_PARAMETER_CLEANUP = "Statement cleanup failed: ";
static const std::string WARNING_DB_PARAMETER_NULL = "Trying to add a null parameter.";
ParameteredObject::ParameteredObject()
: m_initialised( false )
{
}
bool ParameteredObject::initialise()
{
bool ret = false;
try
{
ret = doInitialise();
m_initialised = true;
}
catch ( std::exception & exc )
{
wxLogError( wxString() << ERROR_DB_PARAMETER_INITIALISATION + exc.what() );
}
catch ( ... )
{
wxLogError( wxString() << ERROR_DB_PARAMETER_INITIALISATION + "Unknown error" );
}
return ret;
}
void ParameteredObject::cleanup()
{
try
{
doCleanup();
}
catch ( std::exception & exc )
{
wxLogError( wxString() << ERROR_DB_PARAMETER_CLEANUP + exc.what() );
}
catch ( ... )
{
wxLogError( wxString() << ERROR_DB_PARAMETER_CLEANUP + "Unknown error" );
}
}
Parameter * ParameteredObject::getParameter( uint32_t index )const
{
if ( index >= m_parameters.size() )
{
std::stringstream message;
message << ERROR_DB_PARAMETER_INDEX << index;
throw std::runtime_error{ message.str() };
}
return m_parameters[index].get();
}
Parameter * ParameteredObject::getParameter( const std::string & name )const
{
auto it = std::find_if( m_parameters.begin()
, m_parameters.end()
, [&name]( ParameterPtr const & lookup )
{
return lookup->getName() == name;
} );
if ( it == m_parameters.end() )
{
std::stringstream message;
message << ERROR_DB_PARAMETER_NAME << name;
throw std::runtime_error{ message.str() };
}
return it->get();
}
FieldType ParameteredObject::getParameterType( uint32_t index )
{
return getParameter( index )->getType();
}
FieldType ParameteredObject::getParameterType( const std::string & name )
{
return getParameter( name )->getType();
}
void ParameteredObject::setParameterNull( uint32_t index )
{
getParameter( index )->setNull();
}
void ParameteredObject::setParameterNull( const std::string & name )
{
getParameter( name )->setNull();
}
void ParameteredObject::setParameterValue( uint32_t index
, const ValuedObject & object )
{
getParameter( index )->setValue( object );
}
void ParameteredObject::setParameterValue( const std::string & name
, const ValuedObject & object )
{
getParameter( name )->setValue( object );
}
Parameter * ParameteredObject::doAddParameter( ParameterPtr parameter )
{
Parameter * ret{};
if ( parameter )
{
auto it = std::find_if( m_parameters.begin()
, m_parameters.end()
, [¶meter]( ParameterPtr const & lookup )
{
return lookup->getName() == parameter->getName();
} );
if ( it == m_parameters.end() )
{
ret = parameter.get();
m_parameters.emplace_back( std::move( parameter ) );
}
else
{
throw std::runtime_error{ ERROR_DB_PARAMETER_ALREADY_ADDED + parameter->getName() };
}
}
else
{
wxLogWarning( wxString() << WARNING_DB_PARAMETER_NULL );
}
return ret;
}
}
|
kimjand/cxf
|
distribution/src/main/release/samples/jax_rs/tracing_opentracing_camel/src/main/java/demo/jaxrs/tracing/server/camel/Server.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 demo.jaxrs.tracing.server.camel;
import org.apache.camel.opentracing.starter.CamelOpenTracing;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.WebApplicationType;
import org.springframework.context.annotation.Bean;
import io.jaegertracing.Configuration;
import io.jaegertracing.Configuration.CodecConfiguration;
import io.jaegertracing.Configuration.ReporterConfiguration;
import io.jaegertracing.Configuration.SamplerConfiguration;
import io.jaegertracing.Configuration.SenderConfiguration;
import io.jaegertracing.internal.propagation.TextMapCodec;
import io.jaegertracing.internal.samplers.ConstSampler;
import io.opentracing.Tracer;
import io.opentracing.propagation.Format.Builtin;
@EnableAutoConfiguration
@SpringBootApplication
@CamelOpenTracing
public class Server {
public static void main(String[] args) {
new SpringApplicationBuilder(Server.class)
.web(WebApplicationType.NONE)
.build()
.run(args);
}
@Bean
Tracer tracer() {
return new Configuration("camel-server")
.withSampler(
new SamplerConfiguration()
.withType(ConstSampler.TYPE)
.withParam(1))
.withReporter(new ReporterConfiguration().withSender(
new SenderConfiguration()
.withEndpoint("http://localhost:14268/api/traces")
))
.withCodec(
new CodecConfiguration()
.withCodec(Builtin.TEXT_MAP, new TextMapCodec(true))
)
.getTracer();
}
}
|
zhangkn/iOS14Header
|
System/Library/Frameworks/PhotosUI.framework/PUEditExtensionActivityViewController.h
|
/*
* This header is generated by classdump-dyld 1.0
* on Monday, September 28, 2020 at 5:54:49 PM Mountain Standard Time
* Operating System: Version 14.0 (Build 18A373)
* Image Source: /System/Library/Frameworks/PhotosUI.framework/PhotosUI
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>.
*/
#import <ShareSheet/UIActivityViewController.h>
@protocol PUEditExtensionActivityViewControllerDelegate;
@interface PUEditExtensionActivityViewController : UIActivityViewController {
id<PUEditExtensionActivityViewControllerDelegate> _editExtensionActivityViewControllerDelegate;
}
@property (assign,nonatomic,__weak) id<PUEditExtensionActivityViewControllerDelegate> editExtensionActivityViewControllerDelegate; //@synthesize editExtensionActivityViewControllerDelegate=_editExtensionActivityViewControllerDelegate - In the implementation block
-(BOOL)isPhotosOrCamera;
-(BOOL)_shouldUseModernDesign;
-(BOOL)appWantsLargePreview;
-(id<PUEditExtensionActivityViewControllerDelegate>)editExtensionActivityViewControllerDelegate;
-(void)setEditExtensionActivityViewControllerDelegate:(id<PUEditExtensionActivityViewControllerDelegate>)arg1 ;
-(void)_performActivity:(id)arg1 ;
@end
|
felipecosta09/cloudone-workload-controltower-lifecycle
|
source/deepsecurity/api/computer_groups_api.py
|
<reponame>felipecosta09/cloudone-workload-controltower-lifecycle<filename>source/deepsecurity/api/computer_groups_api.py
# coding: utf-8
"""
Trend Micro Deep Security API
Copyright 2018 - 2020 Trend Micro Incorporated.<br/>Get protected, stay secured, and keep informed with Trend Micro Deep Security's new RESTful API. Access system data and manage security configurations to automate your security workflows and integrate Deep Security into your CI/CD pipeline. # noqa: E501
OpenAPI spec version: 12.5.841
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from deepsecurity.api_client import ApiClient
class ComputerGroupsApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def create_computer_group(self, computer_group, api_version, **kwargs): # noqa: E501
"""Create a Computer Group # noqa: E501
Create a new computer group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_computer_group(computer_group, api_version, async_req=True)
>>> result = thread.get()
:param async_req bool
:param ComputerGroup computer_group: The settings of the new computer group. (required)
:param str api_version: The version of the api being called. (required)
:return: ComputerGroup
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.create_computer_group_with_http_info(computer_group, api_version, **kwargs) # noqa: E501
else:
(data) = self.create_computer_group_with_http_info(computer_group, api_version, **kwargs) # noqa: E501
return data
def create_computer_group_with_http_info(self, computer_group, api_version, **kwargs): # noqa: E501
"""Create a Computer Group # noqa: E501
Create a new computer group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_computer_group_with_http_info(computer_group, api_version, async_req=True)
>>> result = thread.get()
:param async_req bool
:param ComputerGroup computer_group: The settings of the new computer group. (required)
:param str api_version: The version of the api being called. (required)
:return: ComputerGroup
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['computer_group', 'api_version'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_computer_group" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'computer_group' is set
if ('computer_group' not in params or
params['computer_group'] is None):
raise ValueError("Missing the required parameter `computer_group` when calling `create_computer_group`") # noqa: E501
# verify the required parameter 'api_version' is set
if ('api_version' not in params or
params['api_version'] is None):
raise ValueError("Missing the required parameter `api_version` when calling `create_computer_group`") # noqa: E501
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'api_version' in params:
header_params['api-version'] = params['api_version'] # noqa: E501
form_params = []
local_var_files = {}
body_params = None
if 'computer_group' in params:
body_params = params['computer_group']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['DefaultAuthentication'] # noqa: E501
return self.api_client.call_api(
'/computergroups', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='ComputerGroup', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_computer_group(self, computer_group_id, api_version, **kwargs): # noqa: E501
"""Delete a Computer Group # noqa: E501
Delete a computer group by ID. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_computer_group(computer_group_id, api_version, async_req=True)
>>> result = thread.get()
:param async_req bool
:param int computer_group_id: The ID number of the computer group to delete. (required)
:param str api_version: The version of the api being called. (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.delete_computer_group_with_http_info(computer_group_id, api_version, **kwargs) # noqa: E501
else:
(data) = self.delete_computer_group_with_http_info(computer_group_id, api_version, **kwargs) # noqa: E501
return data
def delete_computer_group_with_http_info(self, computer_group_id, api_version, **kwargs): # noqa: E501
"""Delete a Computer Group # noqa: E501
Delete a computer group by ID. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_computer_group_with_http_info(computer_group_id, api_version, async_req=True)
>>> result = thread.get()
:param async_req bool
:param int computer_group_id: The ID number of the computer group to delete. (required)
:param str api_version: The version of the api being called. (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['computer_group_id', 'api_version'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_computer_group" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'computer_group_id' is set
if ('computer_group_id' not in params or
params['computer_group_id'] is None):
raise ValueError("Missing the required parameter `computer_group_id` when calling `delete_computer_group`") # noqa: E501
# verify the required parameter 'api_version' is set
if ('api_version' not in params or
params['api_version'] is None):
raise ValueError("Missing the required parameter `api_version` when calling `delete_computer_group`") # noqa: E501
if 'computer_group_id' in params and not re.search('\\d+', str(params['computer_group_id'])): # noqa: E501
raise ValueError("Invalid value for parameter `computer_group_id` when calling `delete_computer_group`, must conform to the pattern `/\\d+/`") # noqa: E501
collection_formats = {}
path_params = {}
if 'computer_group_id' in params:
path_params['computerGroupID'] = params['computer_group_id'] # noqa: E501
query_params = []
header_params = {}
if 'api_version' in params:
header_params['api-version'] = params['api_version'] # noqa: E501
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['DefaultAuthentication'] # noqa: E501
return self.api_client.call_api(
'/computergroups/{computerGroupID}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def describe_computer_group(self, computer_group_id, api_version, **kwargs): # noqa: E501
"""Describe a Computer Group # noqa: E501
Describe a computer group by ID. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.describe_computer_group(computer_group_id, api_version, async_req=True)
>>> result = thread.get()
:param async_req bool
:param int computer_group_id: The ID number of the computer group to describe. (required)
:param str api_version: The version of the api being called. (required)
:return: ComputerGroup
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.describe_computer_group_with_http_info(computer_group_id, api_version, **kwargs) # noqa: E501
else:
(data) = self.describe_computer_group_with_http_info(computer_group_id, api_version, **kwargs) # noqa: E501
return data
def describe_computer_group_with_http_info(self, computer_group_id, api_version, **kwargs): # noqa: E501
"""Describe a Computer Group # noqa: E501
Describe a computer group by ID. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.describe_computer_group_with_http_info(computer_group_id, api_version, async_req=True)
>>> result = thread.get()
:param async_req bool
:param int computer_group_id: The ID number of the computer group to describe. (required)
:param str api_version: The version of the api being called. (required)
:return: ComputerGroup
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['computer_group_id', 'api_version'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method describe_computer_group" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'computer_group_id' is set
if ('computer_group_id' not in params or
params['computer_group_id'] is None):
raise ValueError("Missing the required parameter `computer_group_id` when calling `describe_computer_group`") # noqa: E501
# verify the required parameter 'api_version' is set
if ('api_version' not in params or
params['api_version'] is None):
raise ValueError("Missing the required parameter `api_version` when calling `describe_computer_group`") # noqa: E501
if 'computer_group_id' in params and not re.search('\\d+', str(params['computer_group_id'])): # noqa: E501
raise ValueError("Invalid value for parameter `computer_group_id` when calling `describe_computer_group`, must conform to the pattern `/\\d+/`") # noqa: E501
collection_formats = {}
path_params = {}
if 'computer_group_id' in params:
path_params['computerGroupID'] = params['computer_group_id'] # noqa: E501
query_params = []
header_params = {}
if 'api_version' in params:
header_params['api-version'] = params['api_version'] # noqa: E501
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['DefaultAuthentication'] # noqa: E501
return self.api_client.call_api(
'/computergroups/{computerGroupID}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='ComputerGroup', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def list_computer_groups(self, api_version, **kwargs): # noqa: E501
"""List Computer Groups # noqa: E501
Lists all computer groups. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_computer_groups(api_version, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str api_version: The version of the api being called. (required)
:return: ComputerGroups
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.list_computer_groups_with_http_info(api_version, **kwargs) # noqa: E501
else:
(data) = self.list_computer_groups_with_http_info(api_version, **kwargs) # noqa: E501
return data
def list_computer_groups_with_http_info(self, api_version, **kwargs): # noqa: E501
"""List Computer Groups # noqa: E501
Lists all computer groups. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_computer_groups_with_http_info(api_version, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str api_version: The version of the api being called. (required)
:return: ComputerGroups
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['api_version'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_computer_groups" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'api_version' is set
if ('api_version' not in params or
params['api_version'] is None):
raise ValueError("Missing the required parameter `api_version` when calling `list_computer_groups`") # noqa: E501
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'api_version' in params:
header_params['api-version'] = params['api_version'] # noqa: E501
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['DefaultAuthentication'] # noqa: E501
return self.api_client.call_api(
'/computergroups', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='ComputerGroups', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def modify_computer_group(self, computer_group_id, api_version, **kwargs): # noqa: E501
"""Modify a Computer Group # noqa: E501
Modify a computer group by ID. Any unset elements will be left unchanged. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.modify_computer_group(computer_group_id, api_version, async_req=True)
>>> result = thread.get()
:param async_req bool
:param int computer_group_id: The ID number of the computer group to modify. (required)
:param str api_version: The version of the api being called. (required)
:param ComputerGroup computer_group: The settings of the computer group to modify.
:return: ComputerGroup
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.modify_computer_group_with_http_info(computer_group_id, api_version, **kwargs) # noqa: E501
else:
(data) = self.modify_computer_group_with_http_info(computer_group_id, api_version, **kwargs) # noqa: E501
return data
def modify_computer_group_with_http_info(self, computer_group_id, api_version, **kwargs): # noqa: E501
"""Modify a Computer Group # noqa: E501
Modify a computer group by ID. Any unset elements will be left unchanged. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.modify_computer_group_with_http_info(computer_group_id, api_version, async_req=True)
>>> result = thread.get()
:param async_req bool
:param int computer_group_id: The ID number of the computer group to modify. (required)
:param str api_version: The version of the api being called. (required)
:param ComputerGroup computer_group: The settings of the computer group to modify.
:return: ComputerGroup
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['computer_group_id', 'api_version', 'computer_group'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method modify_computer_group" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'computer_group_id' is set
if ('computer_group_id' not in params or
params['computer_group_id'] is None):
raise ValueError("Missing the required parameter `computer_group_id` when calling `modify_computer_group`") # noqa: E501
# verify the required parameter 'api_version' is set
if ('api_version' not in params or
params['api_version'] is None):
raise ValueError("Missing the required parameter `api_version` when calling `modify_computer_group`") # noqa: E501
if 'computer_group_id' in params and not re.search('\\d+', str(params['computer_group_id'])): # noqa: E501
raise ValueError("Invalid value for parameter `computer_group_id` when calling `modify_computer_group`, must conform to the pattern `/\\d+/`") # noqa: E501
collection_formats = {}
path_params = {}
if 'computer_group_id' in params:
path_params['computerGroupID'] = params['computer_group_id'] # noqa: E501
query_params = []
header_params = {}
if 'api_version' in params:
header_params['api-version'] = params['api_version'] # noqa: E501
form_params = []
local_var_files = {}
body_params = None
if 'computer_group' in params:
body_params = params['computer_group']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['DefaultAuthentication'] # noqa: E501
return self.api_client.call_api(
'/computergroups/{computerGroupID}', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='ComputerGroup', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def search_computer_groups(self, api_version, **kwargs): # noqa: E501
"""Search Computer Groups # noqa: E501
Search for computer groups using optional filters. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.search_computer_groups(api_version, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str api_version: The version of the api being called. (required)
:param SearchFilter search_filter: A collection of options used to filter the search results.
:return: ComputerGroups
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.search_computer_groups_with_http_info(api_version, **kwargs) # noqa: E501
else:
(data) = self.search_computer_groups_with_http_info(api_version, **kwargs) # noqa: E501
return data
def search_computer_groups_with_http_info(self, api_version, **kwargs): # noqa: E501
"""Search Computer Groups # noqa: E501
Search for computer groups using optional filters. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.search_computer_groups_with_http_info(api_version, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str api_version: The version of the api being called. (required)
:param SearchFilter search_filter: A collection of options used to filter the search results.
:return: ComputerGroups
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['api_version', 'search_filter'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method search_computer_groups" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'api_version' is set
if ('api_version' not in params or
params['api_version'] is None):
raise ValueError("Missing the required parameter `api_version` when calling `search_computer_groups`") # noqa: E501
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'api_version' in params:
header_params['api-version'] = params['api_version'] # noqa: E501
form_params = []
local_var_files = {}
body_params = None
if 'search_filter' in params:
body_params = params['search_filter']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['DefaultAuthentication'] # noqa: E501
return self.api_client.call_api(
'/computergroups/search', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='ComputerGroups', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
|
zenglongGH/spresense
|
sdk/modules/include/bluetooth/hal/bt_event.h
|
<reponame>zenglongGH/spresense<filename>sdk/modules/include/bluetooth/hal/bt_event.h<gh_stars>100-1000
/****************************************************************************
* modules/include/bluetooth/hal/bt_event.h
*
* Copyright 2018 Sony Semiconductor Solutions Corporation
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name of Sony Semiconductor Solutions Corporation nor
* the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file bt_event.h
* @author Sony Semiconductor Solutions Corporation
* @brief Bluetooth HAL I/F for event handler.
* @details This header file includes bluetooth event related definitions
* for HAL I/F.
* Event handler will be use this definition for switch events.
* - Event type
* - Event structure
*/
#ifndef __MODULES_INCLUDE_BLUETOOTH_HAL_BT_EVENT_H
#define __MODULES_INCLUDE_BLUETOOTH_HAL_BT_EVENT_H
/****************************************************************************
* Included Files
****************************************************************************/
#include <stdint.h>
#include <bluetooth/bluetooth.h>
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/**
*@name Max event data length
*@{
*/
#define BT_MAX_EVENT_DATA_LEN 1024
/** @} */
/**
*@name Max ble advertise data length
*@{
*/
#define BLE_MAX_ADV_DATA_LEN 31
/** @} */
/****************************************************************************
* Public Types
****************************************************************************/
/**
* @enum BT_GROUP_ID
* @brief Bluetooth profile and protocol ID
*/
typedef enum
{
BT_GROUP_COMMON = 0, /**< Common group */
BT_GROUP_A2DP, /**< A2DP */
BT_GROUP_AVRCP, /**< AVRCP */
BT_GROUP_HFP, /**< HFP */
BT_GROUP_SPP, /**< SPP */
BT_GROUP_RFCOMM, /**< RFCOMM */
BLE_GROUP_COMMON, /**< BLE Common */
BLE_GROUP_GATT /**< BLE GATT */
} BT_GROUP_ID;
/**
* @enum BT_COMMON_EVENT_ID
* @brief Bluetooth event ID for common function
*/
typedef enum
{
BT_COMMON_EVENT_CMD_STATUS = 0, /**< Command status event */
BT_COMMON_EVENT_PAIRING_COMPLETE, /**< Pairing complete event */
BT_COMMON_EVENT_INQUIRY_RESULT, /**< Inquiry result event */
BT_COMMON_EVENT_INQUIRY_COMPLETE, /**< Inquiry complete event */
BT_COMMON_EVENT_CONN_STAT_CHANGE, /**< Connection status change event */
BT_COMMON_EVENT_CONN_DEV_NAME, /**< Connected device name event */
BT_COMMON_EVENT_BOND_INFO, /**< Bonding information event */
} BT_COMMON_EVENT_ID;
/**
* @enum BT_A2DP_EVENT_ID
* @brief Bluetooth event ID for A2DP
*/
typedef enum
{
BT_A2DP_EVENT_CMD_STATUS = 0, /**< Command status event */
BT_A2DP_EVENT_CONNECT, /**< Connect event */
BT_A2DP_EVENT_DISCONNECT, /**< Disconnect event */
BT_A2DP_EVENT_MEDIA_PACKET, /**< Media packet receive event */
} BT_A2DP_EVENT_ID;
/**
* @enum BT_AVRCP_EVENT_ID
* @brief Bluetooth event ID for A2DP
*/
typedef enum
{
BT_AVRCP_EVENT_CMD_STATUS = 0, /**< Command status event */
BT_AVRCC_EVENT_CONNECT, /**< AVRCP controller connect event */
BT_AVRCC_EVENT_DISCONNECT, /**< AVRCP vontroller disconnect event */
BT_AVRCT_EVENT_CONNECT, /**< AVRCP target connect event */
BT_AVRCT_EVENT_DISCONNECT, /**< AVRCP target disconnect event */
BT_AVRCP_EVENT_PLAY_STAT_CHANGE, /**< Play status change event */
BT_AVRCP_EVENT_TRACK_CHANGE, /**< Play track change event */
BT_AVRCP_EVENT_TRACK_REACH_END, /**< Play track reach end event */
BT_AVRCP_EVENT_TRACK_REACH_START, /**< Play track reach start event */
BT_AVRCP_EVENT_PLAY_POS_CHANGE, /**< Play position change event */
BT_AVRCP_EVENT_BATT_STAT_CHANGE, /**< Battery status change event */
BT_AVRCP_EVENT_SYS_STATUS_CHANGE, /**< System status change event */
BT_AVRCP_EVENT_APP_SETT_CHANGE, /**< Application settings change event */
BT_AVRCP_EVENT_NOW_PLAY_CHANGE, /**< Content of Now Playing folder change event */
BT_AVRCP_EVENT_AVAI_PLAYER_CHANGE, /**< Available players change event */
BT_AVRCP_EVENT_ADDR_PLAYER_CHANGE, /**< Addressed player change event */
BT_AVRCP_EVENT_UIDS_CHANGE, /**< UIDs change event */
BT_AVRCP_EVENT_VOLUME_CHANGE, /**< Volume change on the target device event */
} BT_AVRCP_EVENT_ID;
/**
* @enum BT_HFP_EVENT_ID
* @brief Bluetooth event ID for HFP
*/
typedef enum
{
BT_HFP_EVENT_CMD_STATUS = 0, /**< Command status event */
BT_HFP_EVENT_HF_CONNECT, /**< HFP connect event */
BT_HFP_EVENT_HF_DISCONNECT, /**< HFP disconnect event */
BT_HFP_EVENT_AUDIO_CONNECT, /**< HFP audio connect event */
BT_HFP_EVENT_AUDIO_DISCONNECT, /**< HFP audio disconnect event */
BT_HFP_EVENT_AG_FEATURE_RESP, /**< HFP AG feature response event */
BT_HFP_EVENT_AT_CMD_RESP, /**< HFP AT command response event */
} BT_HFP_EVENT_ID;
/**
* @enum BT_SPP_EVENT_ID
* @brief Bluetooth event ID for SPP
*/
typedef enum
{
BT_SPP_EVENT_CONNECT = 0, /**< Connect event */
BT_SPP_EVENT_DISCONNECT, /**< Disconnect event */
BT_SPP_EVENT_CONNECT_FAIL, /**< Connection fail event */
BT_SPP_EVENT_RX_DATA, /**< Receive SPP data event */
} BT_SPP_EVENT_ID;
/**
* @enum BLE_COMMON_EVENT_ID
* @brief Bluetooth LE event ID for common function
*/
typedef enum
{
BLE_COMMON_EVENT_CONN_STAT_CHANGE = 0, /**< Connection status change event */
BLE_COMMON_EVENT_CONN_DEV_NAME, /**< Device name receive event */
BLE_COMMON_EVENT_SCAN_RESULT, /**< Scan result event */
} BLE_COMMON_EVENT_ID;
/**
* @enum BLE_COMMON_EVENT_ID
* @brief Bluetooth LE event ID for common function
*/
typedef enum
{
BLE_GATT_EVENT_WRITE_REQ = 0, /**< GATT Characteristic write request event */
BLE_GATT_EVENT_READ_REQ, /**< GATT Characteristic read request event */
BLE_GATT_EVENT_NOTIFY_REQ, /**< GATT Characteristic notify request event */
BLE_GATT_EVENT_WRITE_RESP, /**< GATT Characteristic write response event */
BLE_GATT_EVENT_READ_RESP, /**< GATT Characteristic read response event */
BLE_GATT_EVENT_NOTIFY_RESP, /**< GATT Characteristic notify response event */
BLE_GATT_EVENT_DB_DISCOVERY_COMPLETE, /**< GATTC discovery requested by host completed */
} BLE_GATT_EVENT_ID;
/**
* @struct bt_event_t
* @brief Bluetooth parent event data type
*/
struct bt_event_t
{
uint8_t group_id; /**< Event group ID @ref BT_GROUP_ID */
uint8_t event_id; /**< Event sub ID */
uint8_t data[BT_MAX_EVENT_DATA_LEN]; /**< Event data */
};
/**
* @struct bt_event_cmd_stat_t
* @brief Bluetooth command status event data type
*/
struct bt_event_cmd_stat_t
{
uint8_t group_id; /**< Event group ID @ref BT_GROUP_ID */
uint8_t event_id; /**< Event sub ID */
BT_CMD_STATUS cmd_status; /**< Command status @ref BT_CMD_STATUS */
};
/**
* @struct bt_event_pair_cmplt_t
* @brief Bluetooth pairing complete event data type
*/
struct bt_event_pair_cmplt_t
{
uint8_t group_id; /**< Event group ID @ref BT_GROUP_ID */
uint8_t event_id; /**< Event sub ID @ref BT_COMMON_EVENT_ID */
BT_ADDR addr; /**< Pairing target device address @ref BT_ADDR */
BT_PAIR_STATUS status; /**< Pairing status @ref BT_PAIR_STATUS */
};
/**
* @struct bt_event_inquiry_rslt_t
* @brief Bluetooth inquiry result event data type
*/
struct bt_event_inquiry_rslt_t
{
uint8_t group_id; /**< Event group ID @ref BT_GROUP_ID */
uint8_t event_id; /**< Event sub ID @ref BT_COMMON_EVENT_ID */
BT_ADDR addr; /**< Scaned device address @ref BT_ADDR */
char name[BT_NAME_LEN]; /**< Scaned device name */
};
/**
* @struct bt_event_conn_stat_t
* @brief Bluetooth connection status change event data type
*/
struct bt_event_conn_stat_t
{
uint8_t group_id; /**< Event group ID @ref BT_GROUP_ID */
uint8_t event_id; /**< Event sub ID @ref BT_COMMON_EVENT_ID */
BT_ADDR addr; /**< Target address @ref BT_ADDR */
bool connected; /**< Connection status */
uint8_t status;
};
/**
* @struct bt_event_dev_name_t
* @brief Bluetooth change device name event data type
*/
struct bt_event_dev_name_t
{
uint8_t group_id; /**< Event group ID @ref BT_GROUP_ID */
uint8_t event_id; /**< Event sub ID @ref BT_COMMON_EVENT_ID */
char name[BT_NAME_LEN]; /**< Connected device name */
};
/**
* @struct bt_event_bond_info_t
* @brief Bluetooth new bonding information event data type
*/
struct bt_event_bond_info_t
{
uint8_t group_id; /**< Event group ID @ref BT_GROUP_ID */
uint8_t event_id; /**< Event sub ID @ref BT_COMMON_EVENT_ID */
BT_ADDR addr; /**< Bond device address @ref BT_ADDR */
};
/**
* @struct bt_a2dp_event_connect_t
* @brief Bluetooth A2DP connection event data type
*/
struct bt_a2dp_event_connect_t
{
uint8_t group_id; /**< Event group ID @ref BT_GROUP_ID */
uint8_t event_id; /**< Event sub ID @ref BT_A2DP_EVENT_ID */
uint16_t handle; /**< Handle ID for A2DP connection */
BT_ADDR addr; /**< Connected device address @ref BT_ADDR */
BT_AUDIO_CODEC_INFO codecInfo;
};
/**
* @struct bt_a2dp_event_recv_t
* @brief Bluetooth A2DP receive data event data type
*/
struct bt_a2dp_event_recv_t
{
uint8_t group_id; /**< Event group ID @ref BT_GROUP_ID */
uint8_t event_id; /**< Event sub ID @ref BT_A2DP_EVENT_ID */
BT_ADDR addr; /**< Connected device address @ref BT_ADDR */
int len; /**< Receive data length */
uint8_t data[BT_MAX_EVENT_DATA_LEN]; /**< Receive data */
};
/**
* @struct bt_avrcp_event_connect_t
* @brief Bluetooth AVRCP connection event data type
*/
struct bt_avrcp_event_connect_t
{
uint8_t group_id; /**< Event group ID @ref BT_GROUP_ID */
uint8_t event_id; /**< Event sub ID @ref BT_AVRCP_EVENT_ID */
uint16_t handle; /**< Handle ID for AVRCP connection */
BT_ADDR addr; /**< Connected device address @ref BT_ADDR */
};
/**
* @struct bt_avrcp_event_play_position_t
* @brief Bluetooth AVRCP play position event data type
*/
struct bt_avrcp_event_play_position_t
{
uint8_t group_id; /**< Event group ID @ref BT_GROUP_ID */
uint8_t event_id; /**< Event sub ID @ref BT_AVRCP_EVENT_ID */
uint16_t handle; /**< Handle ID for AVRCP connection */
uint32_t position;/**< Play Position */
};
/**
* @struct bt_hfp_event_connect_t
* @brief Bluetooth HFP connection event data type
*/
struct bt_hfp_event_connect_t
{
uint8_t group_id; /**< Event group ID @ref BT_GROUP_ID */
uint8_t event_id; /**< Event sub ID @ref BT_HFP_EVENT_ID */
uint16_t handle; /**< Handle ID for HFP connection */
BT_ADDR addr; /**< Connected device address @ref BT_ADDR */
BT_PROFILE_TYPE hfp_type; /**< Connected profile type @ref BT_PROFILE_TYPE */
};
/**
* @struct bt_hfp_event_ag_feature_t
* @brief Bluetooth HFP ag feature event data type
*/
struct bt_hfp_event_ag_feature_t
{
uint8_t group_id; /**< Event group ID @ref BT_GROUP_ID */
uint8_t event_id; /**< Event sub ID @ref BT_HFP_EVENT_ID */
BT_ADDR addr; /**< Connected device address @ref BT_ADDR */
BT_HFP_AG_FEATURE_FLAG ag_flag; /**< Support AG feature flag @ref BT_HFP_AG_FEATURE_FLAG */
};
/**
* @struct bt_hfp_event_at_cmd_t
* @brief Bluetooth HFP at command event data type
*/
struct bt_hfp_event_at_cmd_t
{
uint8_t group_id; /**< Event group ID @ref BT_GROUP_ID */
uint8_t event_id; /**< Event sub ID @ref BT_HFP_EVENT_ID */
BT_ADDR addr; /**< Connected device address @ref BT_ADDR */
char at_resp[BT_MAX_EVENT_DATA_LEN]; /**< AT command response */
};
/**
* @struct bt_spp_event_connect_t
* @brief Bluetooth SPP connection event data type
*/
struct bt_spp_event_connect_t
{
uint8_t group_id; /**< Event group ID @ref BT_GROUP_ID */
uint8_t event_id; /**< Event sub ID @ref BT_SPP_EVENT_ID */
uint16_t handle; /**< Handle ID for SPP connection */
BT_ADDR addr; /**< Connected device address @ref BT_ADDR */
BT_CONNECT_FAIL_REASON_ID reason; /**< Connection fail reason @ref BT_CONNECT_FAIL_REASON_ID */
};
/**
* @struct bt_spp_event_recv_data_t
* @brief Bluetooth SPP Rx event data type
*/
struct bt_spp_event_recv_data_t
{
uint8_t group_id; /**< Event group ID @ref BT_GROUP_ID */
uint8_t event_id; /**< Event sub ID @ref BT_SPP_EVENT_ID */
BT_ADDR addr; /**< Connected device address @ref BT_ADDR */
int len; /**< Receive data length */
uint8_t data[BT_MAX_EVENT_DATA_LEN]; /**< Receive data */
};
/**
* @struct ble_event_conn_stat_t
* @brief Bluetooth LE connection status change event data type
*/
struct ble_event_conn_stat_t
{
uint8_t group_id; /**< Event group ID @ref BT_GROUP_ID */
uint8_t event_id; /**< Event sub ID @ref BLE_COMMON_EVENT_ID */
uint16_t handle; /**< Handle ID for BLE connection */
BT_ADDR addr; /**< Target address @ref BT_ADDR */
bool connected; /**< Connection status */
};
/**
* @struct ble_event_conn_stat_t
* @brief Bluetooth LE connection status change event data type
*/
struct ble_event_dev_name_t
{
uint8_t group_id; /**< Event group ID @ref BT_GROUP_ID */
uint8_t event_id; /**< Event sub ID @ref BLE_COMMON_EVENT_ID */
BT_ADDR addr; /**< Target address @ref BT_ADDR */
char name[BT_NAME_LEN]; /**< Connected device name */
};
/**
* @struct ble_gatt_event_write_req_t
* @brief Bluetooth LE GATT Write request event
*/
struct ble_gatt_event_write_req_t
{
uint8_t group_id; /**< Event group ID @ref BT_GROUP_ID */
uint8_t event_id; /**< Event sub ID @ref BLE_GATT_EVENT_ID */
uint16_t serv_handle; /**< Service handle ID @ref ble_gatt_service_s */
uint16_t char_handle; /**< Characteristic handle ID @ref ble_gatt_char_s */
uint16_t length; /**< Write data length */
uint8_t data[BT_MAX_EVENT_DATA_LEN]; /**< Write data */
};
/**
* @struct ble_gatt_event_read_req_t
* @brief Bluetooth LE GATT Read request event
*/
struct ble_gatt_event_read_req_t
{
uint8_t group_id; /**< Event group ID @ref BT_GROUP_ID */
uint8_t event_id; /**< Event sub ID @ref BLE_GATT_EVENT_ID */
uint16_t serv_handle; /**< Service handle ID @ref ble_gatt_service_s */
uint16_t char_handle; /**< Characteristic handle ID @ref ble_gatt_char_s */
};
/**
* @struct ble_gatt_event_notify_req_t
* @brief Bluetooth LE GATT Notify request event
*/
struct ble_gatt_event_notify_req_t
{
uint8_t group_id; /**< Event group ID @ref BT_GROUP_ID */
uint8_t event_id; /**< Event sub ID @ref BLE_GATT_EVENT_ID */
uint16_t serv_handle; /**< Service handle ID @ref ble_gatt_service_s */
uint16_t char_handle; /**< Characteristic handle ID @ref ble_gatt_char_s */
bool enable; /**< Notify enable/disable */
};
/**
* @struct ble_gatt_event_write_rsp_t
* @brief Bluetooth LE GATT Write response event
*/
struct ble_gatt_event_write_rsp_t
{
uint8_t group_id; /**< Event group ID @ref BT_GROUP_ID */
uint8_t event_id; /**< Event sub ID @ref BLE_GATT_EVENT_ID */
uint16_t serv_handle; /**< Service handle ID @ref ble_gatt_service_s */
uint16_t conn_handle; /**< Connection handle ID */
uint16_t char_handle; /**< Characteristic handle ID @ref ble_gatt_char_s */
uint8_t status; /**< Write status */
};
/**
* @struct ble_gatt_event_read_rsp_t
* @brief Bluetooth LE GATT Read response event
*/
struct ble_gatt_event_read_rsp_t
{
uint8_t group_id; /**< Event group ID @ref BT_GROUP_ID */
uint8_t event_id; /**< Event sub ID @ref BLE_GATT_EVENT_ID */
uint16_t serv_handle; /**< Service handle ID @ref ble_gatt_service_s */
uint16_t conn_handle; /**< Connection handle ID */
uint16_t char_handle; /**< Characteristic handle ID @ref ble_gatt_char_s */
uint16_t length; /**< Read data length */
uint8_t data[BT_MAX_EVENT_DATA_LEN]; /**< Read data */
};
/**
* @struct ble_event_adv_rept_t
* @brief Bluetooth LE advertise report event
*/
struct ble_event_adv_rept_t
{
uint8_t group_id; /**< Event group ID @ref BT_GROUP_ID */
uint8_t event_id; /**< Event sub ID @ref BLE_GATT_EVENT_ID */
int8_t rssi; /**< Received Signal Strength Indication in dBm. */
uint8_t scan_rsp; /**< If 1, the report corresponds to a scan response */
uint8_t length; /**< Scan response data length */
uint8_t data[BLE_MAX_ADV_DATA_LEN]; /**< Scan response data */
BT_ADDR addr; /**< Advertising device address @ref BT_ADDR */
};
/**
* @struct BT_AVRC_SUPPORT_NOTIFY_EVENT
* @brief BT avrc supported notify event
*/
typedef struct {
bool playStatusChange; /**< Playback Status Changed */
bool trackChange; /**< Track Changed */
bool trackReachedEnd; /**< Track End Reached */
bool trackReachedStart; /**< Track Reached Start */
bool playPosChanged; /**< Playback position changed */
bool batteryStatusChange; /**< Battery status changed */
bool systemStatusChange; /**< System status changed */
bool appSettingChange; /**< Player application settings changed */
bool nowPlayingChange; /**< Now Playing Content Changed (AVRCP 1.4) */
bool avalPlayerChange; /**< Available Players Changed Notification (AVRCP 1.4) */
bool addrPlayChange; /**< Addressed Player Changed Notification (AVRCP 1.4) */
bool uidsChange; /**< UIDs Changed Notification (AVRCP 1.4) */
bool volumeChange; /**< Notify Volume Change (AVRCP 1.4) */
} BT_AVRC_SUPPORT_NOTIFY_EVENT;
#endif /* __MODULES_INCLUDE_BLUETOOTH_HAL_BT_EVENT_H */
|
marco-foscato/Lib-INVENT
|
tests/unit_tests/fixtures/paths.py
|
<reponame>marco-foscato/Lib-INVENT
import os
import json
from definitions import ROOT_DIR
with open(os.path.join(ROOT_DIR, 'configurations/config.json'), 'r') as f:
config = json.load(f)
MAIN_TEST_PATH = config["MAIN_TEST_PATH"]
MODEL_PATH = f'{ROOT_DIR}/trained_models/recap.model'
CHEMBL_TL_MODEL_PATH = f'{ROOT_DIR}/trained_models/reaction_based.model'
DATA_PATH = f'{ROOT_DIR}/tests/unit_tests/unit.test.data'
|
EikeStein/replication-kit-chp-study
|
code/gumtree/core/src/test/java/com/github/gumtreediff/test/TestOptimizedMatchers.java
|
<filename>code/gumtree/core/src/test/java/com/github/gumtreediff/test/TestOptimizedMatchers.java
/*
* This file is part of GumTree.
*
* GumTree 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.
*
* GumTree 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 GumTree. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2015-2016 <NAME> <<EMAIL>>
* Copyright 2015-2016 <NAME> <<EMAIL>>
*/
package com.github.gumtreediff.test;
import com.github.gumtreediff.matchers.CompositeMatchers;
import com.github.gumtreediff.matchers.MappingStore;
import com.github.gumtreediff.tree.ITree;
import com.github.gumtreediff.utils.Pair;
import com.github.gumtreediff.tree.TreeContext;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class TestOptimizedMatchers {
@Test
public void testRtedabcdefMatcher() {
Pair<TreeContext, TreeContext> trees = TreeLoader.getZsSlidePair();
ITree src = trees.first.getRoot();
ITree dst = trees.second.getRoot();
MappingStore mappings = new CompositeMatchers.Rtedacdef().match(src, dst);
assertEquals(5, mappings.size());
assertTrue(mappings.has(src, dst));
assertTrue(mappings.has(src.getChild(0).getChild(0), dst.getChild(0)));
assertTrue(mappings.has(src.getChild(0).getChild(0).getChild(0), dst.getChild(0).getChild(0)));
assertTrue(mappings.has(src.getChild(0).getChild(1), dst.getChild(1).getChild(0)));
assertTrue(mappings.has(src.getChild(0).getChild(2), dst.getChild(1)));
}
@Test
public void testCdabcdefParMatcher() {
Pair<TreeContext, TreeContext> trees = TreeLoader.getZsSlidePair();
ITree src = trees.first.getRoot();
ITree dst = trees.second.getRoot();
MappingStore mappings = new CompositeMatchers.CdabcdefPar().match(src, dst);
assertEquals(5, mappings.size());
assertTrue(mappings.has(src.getChild(0).getChild(0), dst.getChild(0)));
assertTrue(mappings.has(src.getChild(0).getChild(0).getChild(0), dst.getChild(0).getChild(0)));
assertTrue(mappings.has(src.getChild(0).getChild(1), dst.getChild(1).getChild(0)));
assertTrue(mappings.has(src.getChild(0).getChild(2), dst.getChild(1)));
assertTrue(mappings.has(src.getChild(0), dst));
}
@Test
public void testGtbcdefMatcher() {
Pair<TreeContext, TreeContext> trees = TreeLoader.getZsSlidePair();
ITree src = trees.first.getRoot();
ITree dst = trees.second.getRoot();
MappingStore mappings = new CompositeMatchers.Rtedacdef().match(src, dst);
assertEquals(5, mappings.size());
assertTrue(mappings.has(src, dst));
assertTrue(mappings.has(src.getChild(0).getChild(0), dst.getChild(0)));
assertTrue(mappings.has(src.getChild(0).getChild(0).getChild(0), dst.getChild(0).getChild(0)));
assertTrue(mappings.has(src.getChild(0).getChild(1), dst.getChild(1).getChild(0)));
assertTrue(mappings.has(src.getChild(0).getChild(2), dst.getChild(1)));
}
}
|
bmunozi/onesaitplatform-cloud
|
sources/modules/control-panel/src/main/resources/static/dataflow/3.3.0/common/directives/recordTree/recordTree.js
|
/*
* Copyright 2017 StreamSets Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Record Tree Directive
*/
angular.module('recordTreeDirectives', ['RecursionHelper'])
.directive('recordTree', function(RecursionHelper, $modal) {
'use strict';
var linkFunction = function (scope) {
var mapListLimit = 50;
angular.extend(scope, {
updatedValue: false,
updatedField: false,
limit: mapListLimit,
listMapKey: undefined,
mapKeys: (scope.recordValue && scope.recordValue.value) ? Object.keys(scope.recordValue.value) : [],
onClick: function($event) {
$event.preventDefault();
if(scope.isRoot) {
scope.isOpen = !scope.record.expand;
scope.record.expand = scope.isOpen;
if(scope.isOpen && scope.diffRecord) {
var diffRecords = scope.diffRecord;
if(!_.isArray(diffRecords)) {
diffRecords = [diffRecords];
}
angular.forEach(diffRecords, function(diffRecord) {
diffRecord.expand = true;
});
}
} else {
scope.isOpen = !scope.isOpen;
}
},
/**
* Set dirty flag to true when record is updated in Preview Mode.
*
* @param recordUpdated
* @param recordValue
*/
recordValueUpdated: function(recordUpdated, recordValue) {
scope.$emit('recordUpdated', recordUpdated, recordValue);
},
/**
* On Record Value updated.
*
* @param recordUpdated
* @param recordValue
* @param dateRecordValue
*/
recordDateValueUpdated: function(recordUpdated, recordValue, dateRecordValue) {
recordValue.value = dateRecordValue.getTime();
scope.$emit('recordUpdated', recordUpdated, recordValue);
},
/**
* Returns Date
* @param milliSeconds
* @returns {Date}
*/
getDate: function(milliSeconds) {
return new Date(milliSeconds);
},
/**
* Callback function when Show more link clicked.
*
* @param $event
*/
onShowMoreClick: function($event) {
$event.preventDefault();
scope.limit += mapListLimit;
},
/**
* Callback function when Show all link clicked.
*
* @param $event
*/
onShowAllClick: function($event) {
$event.preventDefault();
scope.limit = scope.valueLength;
},
/**
* Returns key for listMap value
* @param recordValue
*/
getListMapKey: function(recordValue) {
var path = recordValue.sqpath,
pathSplit = path ? path.split('/') : undefined,
lastFieldName;
if(pathSplit && pathSplit.length > 0 ) {
lastFieldName = pathSplit[pathSplit.length - 1];
//handle special case field name containing slash eg. /'foo/bar'
if(lastFieldName.indexOf("'") !== -1 &&
!(lastFieldName.charAt(0) == '\'' && lastFieldName.charAt(lastFieldName.length - 1) == '\'')) {
//If path contains slash inside name, split it by "/'"
pathSplit = path.split("/'");
if(pathSplit.length > 0) {
lastFieldName = "'" + pathSplit[pathSplit.length - 1];
}
}
}
//return scope.singleQuoteUnescape(lastFieldName);
return lastFieldName;
},
/**
* Unescape single quote escaped field path
* @param path
* @returns {*}
*/
singleQuoteUnescape: function(path) {
if(path != null && /[\[\]\/"']/.test(path) && path.length > 2) {
path = path.replace("\\\"", "\"").replace("\\\\\'", "'");
return path.substring(1, path.length - 1);
}
return path;
},
/**
* Display stack trace in modal dialog.
*
* @param header
*/
showStackTrace: function (header) {
$modal.open({
templateUrl: 'errorModalContent.html',
controller: 'ErrorModalInstanceController',
size: 'lg',
backdrop: true,
resolve: {
errorObj: function () {
return {
RemoteException: {
localizedMessage: header.errorMessage,
stackTrace: header.errorStackTrace
}
};
}
}
});
}
});
if(scope.diffType && scope.recordValue) {
if(scope.recordValue.type !== 'MAP' && scope.recordValue.type !== 'LIST' && scope.recordValue.type !== 'LIST_MAP') {
if(!scope.diffRecordValue || scope.recordValue.path !== scope.diffRecordValue.path) {
scope.updatedField = true;
} else if(scope.recordValue.value !== scope.diffRecordValue.value ||
scope.recordValue.type !== scope.diffRecordValue.type){
scope.updatedValue = true;
}
} else {
if(!scope.diffRecordValue || !angular.equals(scope.recordValue.value, scope.diffRecordValue.value) ) {
scope.updatedField = true;
}
}
}
if(scope.recordValue && (scope.recordValue.type === 'MAP' || scope.recordValue.type === 'LIST' ||
scope.recordValue.type === 'LIST_MAP')) {
scope.valueLength = _.size(scope.recordValue.value);
}
};
return {
restrict: 'E',
replace: true,
scope: {
record: '=',
recordValue: '=',
diffType: '=',
diffRecord: '=',
diffRecordValue: '=',
fieldName: '=',
fieldIndex: '=',
isRoot: '=',
isError: '=',
editable: '=',
selectable: '=',
selectedPath: '=',
showHeader: '=',
showFieldType: '='
},
templateUrl: 'common/directives/recordTree/recordTree.tpl.html',
compile: function (element) {
// Use the compile function from the RecursionHelper,
// And return the linking function(s) which it returns
return RecursionHelper.compile(element, linkFunction);
}
};
});
|
mrm-xiefan/lunania-ai
|
catvsdog/01_job/predict.py
|
<gh_stars>10-100
import os
import utils
import config
import traceback
import argparse
import logging.config
from luna import LunaExcepion
logging.config.fileConfig("logging.conf")
logger = logging.getLogger()
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--model', default='1', help='1: small cnn. 2: top trained. 3: fine tuned.')
parser.add_argument('--image', required=True, help='input an image to predict')
return parser.parse_args()
if __name__ == '__main__':
try:
logger.info("------ start ------")
utils.lock()
args = parse_args()
if not os.path.exists(args.image):
raise LunaExcepion(config.inputerr)
from keras.models import Sequential, Model
from keras.models import load_model
from keras.preprocessing import image
from keras.applications.vgg16 import VGG16
from keras.layers import Input, Activation, Dropout, Flatten, Dense
import numpy as np
if args.model == '1':
# 学習済みのモデルをロード
model = load_model(os.path.join(config.result_dir, 'scratch_model.h5'))
# model.summary()
elif args.model == '2':
# 学習済みのモデルをロード
top_model = load_model(os.path.join(config.result_dir, 'bottleneck_model.h5'))
# VGGのモデルをロード、FC層は自分の学習済みのモデルにするので、不要
input_tensor = Input(shape=(config.img_height, config.img_width, config.channels))
vgg16_model = VGG16(include_top=False, weights='imagenet', input_tensor=input_tensor)
# 二つのモデルを結合する
model = Model(inputs=vgg16_model.input, outputs=top_model(vgg16_model.output))
# model.summary()
elif args.model == '3':
# VGGのモデルをロード、FC層は自分の学習済みのモデルにするので、不要
input_tensor = Input(shape=(config.img_height, config.img_width, config.channels))
vgg16_model = VGG16(include_top=False, weights='imagenet', input_tensor=input_tensor)
# fc層のガラを作る
top_model = Sequential()
top_model.add(Flatten(input_shape=vgg16_model.output_shape[1:]))
top_model.add(Dense(256, activation='relu'))
top_model.add(Dropout(0.5))
top_model.add(Dense(1, activation='sigmoid'))
# 二つのモデルを結合する
model = Model(inputs=vgg16_model.input, outputs=top_model(vgg16_model.output))
# 学習済みの重みをロード
model.load_weights(os.path.join(config.result_dir, 'finetuning_weights.h5'))
# compile
model.compile(
loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy']
)
# model.summary()
else:
raise LunaExcepion(config.inputerr)
# 画像を読み込んで4次元テンソルへ変換
img = image.load_img(args.image, target_size=(config.img_height, config.img_width))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
# 学習時にImageDataGeneratorのrescaleで正規化したので同じ処理が必要
x = x / 255.0
# クラスを予測
# 入力は1枚の画像なので[0]のみ
pred = model.predict(x)[0]
# {'dog': 1, 'cat': 0}
print({"error": "", "data": {"value": '%.10f' % (pred[0])}})
except (KeyboardInterrupt, SystemExit):
utils.unlock()
utils.error(config.syserr)
except LunaExcepion as e:
utils.error(e.value)
if (e.value == config.locked):
exit()
logger.info("------ end ------")
except Exception as e:
logger.error(e)
logger.error(traceback.format_exc())
utils.error(config.syserr)
utils.unlock()
logger.info("------ end ------")
|
zhuaiballl/venus_lite
|
tools/gengen/util/testing.go
|
package gengen
import (
"fmt"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/specs-actors/v6/actors/builtin/market"
"github.com/filecoin-project/specs-actors/v6/actors/builtin/miner"
tutil "github.com/filecoin-project/specs-actors/v6/support/testing"
"github.com/filecoin-project/venus_lite/pkg/constants"
)
// MakeCommitCfgs creates n gengen commit configs, casting strings to cids.
func MakeCommitCfgs(n int) ([]*CommitConfig, error) {
cfgs := make([]*CommitConfig, n)
for i := 0; i < n; i++ {
commP := tutil.MakeCID(fmt.Sprintf("commP: %d", i), &market.PieceCIDPrefix)
commR := tutil.MakeCID(fmt.Sprintf("commR: %d", i), &miner.SealedCIDPrefix)
commD := tutil.MakeCID(fmt.Sprintf("commD: %d", i), &market.PieceCIDPrefix)
dealCfg := &DealConfig{
CommP: commP,
PieceSize: uint64(2048),
Verified: false,
EndEpoch: int64(538000),
}
cfgs[i] = &CommitConfig{
CommR: commR,
CommD: commD,
SectorNum: abi.SectorNumber(i),
DealCfg: dealCfg,
ProofType: constants.DevRegisteredSealProof,
}
}
return cfgs, nil
}
|
dandycheung/curlconverter
|
test/fixtures/javascript/post_json_multiple_headers.js
|
<reponame>dandycheung/curlconverter
fetch('https://localhost:28139/rest/login-sessions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Version': '200'
},
// body: '{"userName":"username123","password":"<PASSWORD>", "authLoginDomain":"local"}',
body: JSON.stringify({
'userName': 'username123',
'password': '<PASSWORD>',
'authLoginDomain': 'local'
})
});
|
redshark2016/base_springmvc
|
src/base/main/com/redshark/model/User.java
|
package com.redshark.model;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.management.relation.RoleInfo;
public class User implements Serializable {
private static final long serialVersionUID = -2465519067844351347L;
private String id;
private String user_name;
private String password;
private String idcard;// 身份证
private String real_name;// 真实姓名
private Date birthday;
private String email;// 邮箱
private String question;// 密码提示问题
private String answer;// 找回密码答案
private Date reg_date;// 注册时间
private String type;// 用户身份
private String login_num;// 登录次数
private Date last_login_date;// 最后登录时间
private Date current_login_date;// 当前登录时间
private Integer auditType;// 认证类型
private Long status;// 用户状态 0:禁用 1:
private String lastlogin;
private String organization;
private List<RoleInfo> roleList;
private Date last_update_time;
private String old_user_name; //二期资源网中用户名,用于绑定二期账号信息
private Integer sort; //排序
private String active_flag;
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
public String getLastlogin() {
return lastlogin;
}
public void setLastlogin(String lastlogin) {
this.lastlogin = lastlogin;
}
public Integer getAuditType() {
return auditType;
}
public void setAuditType(Integer auditType) {
this.auditType = auditType;
}
public Long getStatus() {
return status;
}
public void setStatus(Long status) {
this.status = status;
}
public String getOrganization() {
return organization;
}
public void setOrganization(String organization) {
this.organization = organization;
}
public List<RoleInfo> getRoleList() {
return roleList;
}
public void setRoleList(List<RoleInfo> roleList) {
this.roleList = roleList;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getIdcard() {
return idcard;
}
public void setIdcard(String idcard) {
this.idcard = idcard;
}
public String getReal_name() {
return real_name;
}
public void setReal_name(String real_name) {
this.real_name = real_name;
}
public Date getReg_date() {
return reg_date;
}
public void setReg_date(Date reg_date) {
this.reg_date = reg_date;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getLogin_num() {
return login_num;
}
public void setLogin_num(String login_num) {
this.login_num = login_num;
}
public Date getLast_login_date() {
return last_login_date;
}
public void setLast_login_date(Date last_login_date) {
this.last_login_date = last_login_date;
}
public Date getCurrent_login_date() {
return current_login_date;
}
public void setCurrent_login_date(Date current_login_date) {
this.current_login_date = current_login_date;
}
public Date getLast_update_time() {
return last_update_time;
}
public void setLast_update_time(Date last_update_time) {
this.last_update_time = last_update_time;
}
public String getOld_user_name() {
return old_user_name;
}
public void setOld_user_name(String old_user_name) {
this.old_user_name = old_user_name;
}
public String getActive_flag() {
return active_flag;
}
public void setActive_flag(String active_flag) {
this.active_flag = active_flag;
}
}
|
jcreamer898/ko.ninja
|
server/httpList.js
|
<gh_stars>10-100
var _ = require('underscore');
module.exports = function (app) {
var list = [{
id: 1,
name: '<NAME>'
}, {
id: 2,
name: 'Ham'
}];
function getListItemIndex (id) {
for (var i = 0; i < list.length; i++) {
if (list[i].id == id) {
return i;
}
}
}
app.get('/item', function (req, res) {
res.send(list);
});
// FindOne list item
app.get('/item/:id', function (req, res) {
var item = list[getListItemIndex(req.params.id)];
res.send(item || {
error: true,
message: 'There was an error finding your list'
});
});
// Insert list item
app.post('/item', function (req, res) {
var data = req.body;
data.id = new Date().getTime();
list.push(data);
res.send(data);
});
// Update list item
app.put('/item/:id', function (req, res) {
var item = getListItemIndex(req.params.id);
list[item] = req.body;
res.send((list[item]) ? req.params : {
error: true,
message: 'There was an error updating your list'
});
});
// Delete list item
app['delete']('/item/:id', function (req, res) {
for (var i = 0; i < list.length; i++) {
if (list[i].id == req.params.id) {
list.splice(i, 1);
res.send({
success: true
});
}
}
});
};
|
guiiyanxD/PrimerParcial2
|
public/Jointjs/tutorials/js/element-tools-all.js
|
(function elementToolsAll() {
var graph = new joint.dia.Graph;
var paper = new joint.dia.Paper({
el: document.getElementById('paper-element-tools-all'),
model: graph,
width: 600,
height: 100,
gridSize: 10,
drawGrid: true,
background: {
color: 'rgba(255, 165, 0, 0.3)'
}
});
var element = new joint.shapes.standard.Rectangle();
element.position(240, 30);
element.resize(100, 40);
element.attr({
body: {
fill: 'white',
stroke: 'black',
strokeWidth: 2
},
label: {
text: 'Hello, World!',
fill: 'black'
}
});
element.addTo(graph);
var boundaryTool = new joint.elementTools.Boundary();
var removeButton = new joint.elementTools.Remove();
var toolsView = new joint.dia.ToolsView({
tools: [boundaryTool, removeButton]
});
var elementView = element.findView(paper);
elementView.addTools(toolsView);
}());
|
Grimace1975/bclcontrib-scriptsharp
|
ref.neo/tools/radiant/TabsDlg.cpp
|
<reponame>Grimace1975/bclcontrib-scriptsharp
/*
===========================================================================
Doom 3 GPL Source Code
Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 GPL Source Code (?Doom 3 Source Code?).
Doom 3 Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Doom 3 Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#include "../../idlib/precompiled.h"
#pragma hdrstop
#include "QE3.H"
#include "TabsDlg.h"
// CTabsDlg dialog
//IMPLEMENT_DYNAMIC ( CTabsDlg , CDialog )
CTabsDlg::CTabsDlg(UINT ID , CWnd* pParent /*=NULL*/)
: CDialog(ID, pParent)
{
m_DragTabActive = false;
}
BEGIN_MESSAGE_MAP(CTabsDlg, CDialog)
//}}AFX_MSG_MAP
// ON_NOTIFY(TCN_SELCHANGE, IDC_TAB1, OnTcnSelchangeTab1)
ON_WM_LBUTTONDOWN()
ON_WM_LBUTTONUP()
ON_WM_MOUSEMOVE()
ON_WM_DESTROY()
END_MESSAGE_MAP()
void CTabsDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_TAB_INSPECTOR, m_Tabs);
}
// CTabsDlg message handlers
BOOL CTabsDlg::OnInitDialog()
{
CDialog::OnInitDialog();
return TRUE; // return TRUE unless you set the focus to a control
}
void CTabsDlg::OnTcnSelchange(NMHDR *pNMHDR, LRESULT *pResult)
{
int ID = TabCtrl_GetCurSel ( pNMHDR->hwndFrom );
if ( ID >= 0 )
{
TCITEM item;
item.mask = TCIF_PARAM;
ShowAllWindows ( FALSE );
TabCtrl_GetItem (m_Tabs.GetSafeHwnd() , ID , &item);
DockedWindowInfo* info = (DockedWindowInfo*)item.lParam;
ASSERT ( info );
info->m_TabControlIndex = ID;
info->m_Window->ShowWindow(TRUE);
}
}
void CTabsDlg::DockWindow ( int ID , bool dock )
{
DockedWindowInfo* info = NULL;
m_Windows.Lookup ( (WORD)ID , (void*&)info );
ASSERT ( info );
ASSERT ( m_Tabs.GetSafeHwnd() );
ShowAllWindows ( FALSE );
if ( !dock )
{
//make a containing window and assign the dialog to it
CRect rect;
CString classname = AfxRegisterWndClass ( CS_DBLCLKS , 0 , 0 , 0 );
info->m_State = DockedWindowInfo::FLOATING;
info->m_Window->GetWindowRect(rect);
info->m_Container.CreateEx ( WS_EX_TOOLWINDOW , classname , info->m_Title , WS_THICKFRAME | WS_SYSMENU | WS_POPUP | WS_CAPTION, rect , this , 0 );
info->m_Window->SetParent ( &info->m_Container );
info->m_Window->ShowWindow(TRUE);
info->m_Container.SetDockManager(this);
info->m_Container.ShowWindow(TRUE);
info->m_Container.SetDialog ( info->m_Window , info->m_ID );
if (info->m_TabControlIndex >= 0 )
{
m_Tabs.DeleteItem( info->m_TabControlIndex );
}
if ( m_Tabs.GetItemCount() > 0 )
{
m_Tabs.SetCurFocus( 0 );
}
CString placementName = info->m_Title + "Placement";
LoadWindowPlacement(info->m_Container , placementName);
}
else
{
info->m_State = DockedWindowInfo::DOCKED;
info->m_TabControlIndex = m_Tabs.InsertItem( TCIF_TEXT | TCIF_IMAGE | TCIF_PARAM , 0 , info->m_Title , info->m_ImageID , (LPARAM)info);
info->m_Window->SetParent ( this );
info->m_Window->ShowWindow (TRUE);
info->m_Container.SetDockManager( NULL ); //so it doesn't try to call back and redock this window
info->m_Container.DestroyWindow ();
CRect rect;
GetWindowRect ( rect );
//stupid hack to get the window reitself properly
rect.DeflateRect(0,0,0,1);
MoveWindow(rect);
rect.InflateRect(0,0,0,1);
MoveWindow(rect);
}
UpdateTabControlIndices ();
FocusWindow ( ID );
if ( info->m_DockCallback )
{
info->m_DockCallback ( dock , info->m_ID , info->m_Window );
}
SaveWindowPlacement ();
}
int CTabsDlg::PreTranslateMessage ( MSG* msg )
{
if ( msg->message == WM_LBUTTONDBLCLK && msg->hwnd == m_Tabs.GetSafeHwnd() )
{
HandleUndock ();
return TRUE;
}
//steal lbutton clicks for the main dialog too, but let the tabs do their default thing as well
if ( msg->message == WM_LBUTTONDOWN && msg->hwnd == m_Tabs.GetSafeHwnd()) {
m_Tabs.SendMessage ( msg->message , msg->wParam , msg->lParam );
m_DragTabActive = true;
}
else if ( msg->message == WM_LBUTTONUP && msg->hwnd == m_Tabs.GetSafeHwnd()) {
m_Tabs.SendMessage ( msg->message , msg->wParam , msg->lParam );
m_DragTabActive = false;
}
return CDialog::PreTranslateMessage(msg);
}
bool CTabsDlg::RectWithinDockManager ( CRect& rect )
{
CRect tabsRect,intersectionRect;
m_Tabs.GetWindowRect ( tabsRect );
intersectionRect.IntersectRect( tabsRect , rect );
return !(intersectionRect.IsRectEmpty());
}
void CTabsDlg::OnLButtonDown(UINT nFlags, CPoint point)
{
CDialog::OnLButtonDown(nFlags, point);
}
void CTabsDlg::OnLButtonUp(UINT nFlags, CPoint point)
{
if ( m_DragTabActive && ((abs ( point.x - m_DragDownPoint.x ) > 50) || (abs ( point.y - m_DragDownPoint.y ) > 50)))
{
HandleUndock();
m_DragTabActive = false;
}
CDialog::OnLButtonUp(nFlags, point);
}
void CTabsDlg::HandleUndock ()
{
TCITEM item;
item.mask = TCIF_PARAM;
int curSel = TabCtrl_GetCurSel ( m_Tabs.GetSafeHwnd());
TabCtrl_GetItem (m_Tabs.GetSafeHwnd() , curSel , &item);
DockedWindowInfo* info = (DockedWindowInfo*)item.lParam;
ASSERT ( info );
DockWindow ( info->m_ID , false );
}
void CTabsDlg::OnMouseMove(UINT nFlags, CPoint point)
{
CDialog::OnMouseMove(nFlags, point);
}
void CTabsDlg::AddDockedWindow ( CWnd* wnd , int ID , int imageID , const CString& title , bool dock , pfnOnDockEvent dockCallback )
{
DockedWindowInfo* info = NULL;
m_Windows.Lookup( (WORD)ID , (void*&)info);
ASSERT ( wnd );
ASSERT ( info == NULL );
info = new DockedWindowInfo ( wnd , ID , imageID , title , dockCallback);
m_Windows.SetAt ( (WORD)ID , info );
DockWindow ( ID , dock );
UpdateTabControlIndices ();
}
void CTabsDlg::ShowAllWindows ( bool show )
{
POSITION pos;
WORD ID;
DockedWindowInfo* info = NULL;
for( pos = m_Windows.GetStartPosition(); pos != NULL ; )
{
m_Windows.GetNextAssoc( pos, ID, (void*&)info );
ASSERT ( info->m_Window );
if ( info->m_State == DockedWindowInfo::DOCKED )
{
info->m_Window->ShowWindow( show );
}
}
}
void CTabsDlg::FocusWindow ( int ID )
{
DockedWindowInfo* info = NULL;
m_Windows.Lookup( (WORD)ID , (void*&)info);
ASSERT ( info );
ASSERT ( info->m_Window );
if ( info->m_State == DockedWindowInfo::DOCKED )
{
TabCtrl_SetCurFocus ( m_Tabs.GetSafeHwnd() , info->m_TabControlIndex );
}
else
{
info->m_Container.SetFocus();
}
}
void CTabsDlg::UpdateTabControlIndices ()
{
TCITEM item;
item.mask = TCIF_PARAM;
DockedWindowInfo* info = NULL;
int itemCount = m_Tabs.GetItemCount();
for ( int i = 0 ; i < itemCount ; i ++ )
{
if ( !m_Tabs.GetItem( i , &item ) )
{
Sys_Error ( "UpdateTabControlIndices(): GetItem failed!\n" );
}
info = (DockedWindowInfo*)item.lParam;
info->m_TabControlIndex = i;
}
}
void CTabsDlg::OnDestroy()
{
TCITEM item;
item.mask = TCIF_PARAM;
DockedWindowInfo* info = NULL;
for ( int i = 0 ; i < m_Tabs.GetItemCount() ; i ++ )
{
m_Tabs.GetItem( i , &item );
info = (DockedWindowInfo*)item.lParam;
ASSERT( info );
delete info;
}
CDialog::OnDestroy();
}
bool CTabsDlg::IsDocked ( CWnd* wnd )
{
bool docked = false;
DockedWindowInfo* info = NULL;
CString placementName;
POSITION pos;
WORD wID;
for( pos = m_Windows.GetStartPosition(); pos != NULL ; )
{
m_Windows.GetNextAssoc( pos, wID, (void*&)info );
if ( info->m_Window == wnd ) {
docked = (info->m_State == DockedWindowInfo::DOCKED);
break;
}
}
return docked;
}
void CTabsDlg::SaveWindowPlacement( int ID )
{
DockedWindowInfo* info = NULL;
CString placementName;
POSITION pos;
WORD wID = ID;
for( pos = m_Windows.GetStartPosition(); pos != NULL ; )
{
m_Windows.GetNextAssoc( pos, wID, (void*&)info );
if ( (info->m_State == DockedWindowInfo::FLOATING) && ((ID == -1) || (ID == info->m_ID))) {
placementName = info->m_Title + "Placement";
::SaveWindowPlacement(info->m_Container.GetSafeHwnd() , placementName);
}
}
}
|
solidonline/hms-cordova-plugin
|
cordova-plugin-hms-awareness/example/cordova/www/js/ambientLightbarrier.js
|
/*
Copyright 2020-2021. Huawei Technologies Co., Ltd. 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
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
document.addEventListener("DOMContentLoaded", function () {
document.getElementById("addAmbientLightBarrierRange").addEventListener("click", addAmbientLightBarrierRange);
document.getElementById("addAmbientLightBarrierAbove").addEventListener("click", addAmbientLightBarrierAbove);
document.getElementById("addAmbientLightBarrierBelow").addEventListener("click", addAmbientLightBarrierBelow);
}, false);
function addAmbientLightBarrierRange() {
let barrierLabel = "AmbientLightBarrierRange";
let lowLuxValue = 500.0;
let highLuxValue = 2500.0;
AwarenessBarrier.AmbientLightBarrier.range(lowLuxValue, highLuxValue)
.subscribe((data) => {
console.log(JSON.stringify(data));
}).catch((err) => {
console.log(JSON.stringify(err));
}).run(barrierLabel);
}
function addAmbientLightBarrierAbove() {
let barrierLabel = "AmbientLightBarrierAbove";
let highLuxValue = 2500.0;
AwarenessBarrier.AmbientLightBarrier.above(highLuxValue)
.subscribe((data) => {
console.log(JSON.stringify(data));
}).catch((err) => {
console.log(JSON.stringify(err));
}).run(barrierLabel);
}
function addAmbientLightBarrierBelow() {
let barrierLabel = "AmbientLightBarrierBelow";
let lowLuxValue = 500.0;
AwarenessBarrier.AmbientLightBarrier.below(lowLuxValue)
.subscribe((data) => {
console.log(JSON.stringify(data));
}).catch((err) => {
console.log(JSON.stringify(err));
}).run(barrierLabel);
}
|
poyun/study-spring-data-jpa
|
src/main/java/cn/caofanqi/study/studyspringdatajpa/pojo/domain/JpaAnnotationDemo.java
|
<reponame>poyun/study-spring-data-jpa<gh_stars>1-10
package cn.caofanqi.study.studyspringdatajpa.pojo.domain;
import cn.caofanqi.study.studyspringdatajpa.pojo.enums.Sex;
import lombok.Data;
import javax.persistence.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;
/**
* JPA基本注解
* @author caofanqi
*
* @Entity用于添加在实体类上,定义该JAVA类成为被JPA管理的实体,将映射到制定的数据库表。
* 如定义一个实体类Category,它将映射到数据库中的category表中。
*
* @Table 指定数据库的表名,与@Entity一同使用。
* name:表的名字,如果不写,系统认为和实体类一致。
* catalog,schema用于设置目录和此表所在schema,一般不需要填写;
* uniqueConstraints,唯一性约束,只有创建表的时候有用,默认不需要;
* indexes,索引,只有创建表的时候有用,默认不需要。
*/
@Data
@Entity
@Table(name = "Jpa_annotation_demo",
uniqueConstraints = {@UniqueConstraint(name = "uk_name",columnNames = {"name"})},
indexes = {@Index(name = "idx_xxx",columnList = "xxx,name")})
public class JpaAnnotationDemo {
/**
* @Id定义属性为数据库中的主键列,一个实体里面必须有一个。
*
* @GeneratedValue,主键生成策略。
* 属性strategy,id的生成策略,GenerationType.TABLE,通过表产生主键,框架由表模拟序列产生主键,使用该策略可以使应用更易于数据库移植;
* GenerationType.SEQUENCE,通过序列产生主键,通过@SequenceGenerator注解指定序列名,MySql不支持这种方式;
* GenerationType.IDENTITY,数据库id自增长,多用于MySql;
* GenerationType.AUTO,JPA自动选择合适的策略,默认选项。
* 属性generator:通过Sequence生成id,常见Orcale数据库id生成,需要配合@SequenceGenerator使用。
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/**
* @Basic,表示属性是到数据库表字段的映射。如果实体的字段上没有任何注解,默认即为@Basic;
* 属性 fetch,抓取方式,默认FetchType.EAGER(立即加载),FetchType.LAZY(延迟加载,主要应用在大字段上面);
* 属性optional,设置这个字段是否可以为null,默认是true。
*/
@Basic
private String name;
private String xxx;
/**
* @Transient,非持久化属性,表示该属性并非是一个到数据库表的字段的映射,与@Basic作用相反。JPA映射数据库的时候忽略它。
*/
@Transient
private String yyy;
/**
* @Column,定义该属性对应数据库中的列名。
* 属性name,数据库中的列名。如果不写默认和实体属性名一致;
* 属性unique,是否唯一。默认false;
* 属性nullable,是否允许为空。默认为true;
* 属性insertable,执行insert操作的时候是否包含此字段,默认为true;
* 属性updatable,执行updatable操作的时候是否包含此字段,默认为true;
* 属性columnDefinition,表示该字段在数据库中的实际类型。
* 属性length,数据库字段的长度,默认255;
* 属性table,precision,scale,一般不设置。
*/
@Column(name = "jpa_ddd",columnDefinition="decimal")
private Integer ddd;
/**
* @Temporal:用来设置Date类型的属性映射到对应精度的字段。TemporalType.DATE,映射为数据库date,TemporalType.TIME映射为数据库time,TemporalType.TIMESTAMP,映射为datetime。
*/
@Temporal(TemporalType.DATE)
private Date createDate;
@Temporal(TemporalType.TIME)
private Date createTime;
@Temporal(TemporalType.TIMESTAMP)
private Date createDateTime;
/**
* jdk8可以使用以下新的时间类型替代Date
*/
private LocalDate localDate;
private LocalTime localTime;
private LocalDateTime localDateTime;
/**
* @Enumerated:映射枚举字段。属性value,默认是EnumType.ORDINAL(枚举字段的下标),EnumType.STRING枚举字段的Name;
*/
@Enumerated(EnumType.STRING)
private Sex sex;
/**
* @Lob,将属性字段映射成数据库支持的大对象类型,支持一下两种数据库类型的字段。
* Clob(Character Large Objects)类型是长字符串类型,java.sql.Clob、Character[]、char[]和String将被映射成Clob类型。
* Blob(Binary Large Objects)类型是字节类型,java.sql.Blob、Byte[]、byte[]和实现了Serializable接口的类型将被映射为Blob类型。
* Clob、Blob占用内存空间较大,一般配合@Basic(fetch=FetchType.LAZY)将其设置为延迟加载。
*/
@Lob
private String bigText;
}
|
anshika581/competitive-programming-1
|
src/codebook/dp/Knapsack.java
|
<filename>src/codebook/dp/Knapsack.java
/*
* Dynamic programming algorithm that computes the maximum value that you can obtain from putting n elements (each with integral value and weight) in a knapsack that can fit
* a total of n weight.
*
* Time complexity: O(NM) where N is the number of items and the M is the size of the knapsack
*/
package codebook.dp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Knapsack {
static BufferedReader br;
static PrintWriter out;
static StringTokenizer st;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
//br = new BufferedReader(new FileReader("in.txt"));
//out = new PrintWriter(new FileWriter("out.txt"));
// number of items
int n = readInt();
// size of knapsack
int m = readInt();
int[] weight = new int[n + 1];
int[] value = new int[n + 1];
int[] dp = new int[m + 1];
for (int i = 1; i <= n; i++) {
weight[i] = readInt();
value[i] = readInt();
}
for (int i = 1; i <= n; i++)
// 0-1 knapsack; for unbounded then iterate the opposite way
for (int j = m; j >= 0; j--)
if (j - weight[i] >= 0)
dp[j] = Math.max(dp[j], dp[j - weight[i]] + value[i]);
out.println(dp[m]);
out.close();
}
static String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine().trim());
return st.nextToken();
}
static long readLong() throws IOException {
return Long.parseLong(next());
}
static int readInt() throws IOException {
return Integer.parseInt(next());
}
static double readDouble() throws IOException {
return Double.parseDouble(next());
}
static char readCharacter() throws IOException {
return next().charAt(0);
}
static String readLine() throws IOException {
return br.readLine().trim();
}
}
|
Orcthanc/Kestrel
|
Kestrel/src/Core/File.hpp
|
#pragma once
#include <kstpch.hpp>
namespace Kestrel {
struct Filereader {
static std::vector<uint8_t> read_uint8t( const std::string& filepath );
static std::vector<int8_t> read_int8t( const std::string& filepath );
static std::string read_string( const std::string& filepath );
};
}
|
GaryGo/CodeIgniter-MiniBlog
|
third-party-code/umeditor-dev/_test/plugins/enterkey.js
|
module( 'plugins.enterkey' );
///*不作处理chrome会产生div*/
test( 'chrome删除div', function () {
var editor = te.obj[0];
var range = te.obj[1];
var body = editor.body;
if(ua.browser.chrome){
editor.body.innerHTML = '<h1>一级标题</h1><div><br/></div>';
range.setStart( body.firstChild.firstChild, 4 ).collapse( 1 ).select();
ua.keydown(editor.body,{'keyCode':13});
ua.keyup(editor.body,{'keyCode':13});
range.selectNode(body.lastChild).select();
var index = editor.undoManger.index;
var br = ua.browser.ie ? '' : '<br>';
equal(editor.undoManger.list.length,1,'保存现场');
setTimeout( function () {
equal( body.childNodes.length, 2, '2个子节点' );
equal(body.lastChild.tagName.toLowerCase(),'div','div转成p');
equal(ua.getChildHTML(body),'<h1>一级标题</h1><div><br></div>','检查内容');
start();
}, 60 );
stop();
}else{
}
} );
test( 'formatBlock', function () {
if(ua.browser.ie) return ;//ie时没有做处理
var editor = te.obj[0];
var range = te.obj[1];
editor.setContent( '<table><tbody><tr><td>hello1</td><td ></td></tr><tr><td >hello2</td><td ></td></tr></tbody></table>' );
var tds = editor.body.getElementsByTagName('td');
range.setStart(tds[0].firstChild,6).collapse(true).select();
ua.keydown(editor.body,{'keyCode':13});
setTimeout( function () {
ua.keyup(editor.body,{'keyCode':13});
setTimeout( function () {
var td = editor.body.getElementsByTagName('td')[0];
if(!ua.browser.ie){
equal(td.firstChild&&td.firstChild.tagName.toLowerCase(),'p','加上p');
equal(td.firstChild.innerHTML,'hello1','hello1');
}
else
equal(ua.getChildHTML(td),'hello1','try');
start();
}, 60 );
}, 60 );
stop();
} );
test( '跨td不删', function () {
var editor = te.obj[0];
var range = te.obj[1];
editor.setContent( '<table><tbody><tr><td> hello1</td><td ></td></tr><tr><td >hello2</td><td ></td></tr></tbody></table>' );
var tds = editor.body.getElementsByTagName('td');
range.setStart(tds[0],0).setEnd(tds[2],1).select();
editor.addListener("keydown", function (type, evt) {
setTimeout( function () {
ok(evt.defaultPrevented||!evt.returnValue, "keydown");
start();
}, 60 );
});
ua.keydown(editor.body,{'keyCode':13});
stop();
} );
|
fossabot/design_principles_dojo
|
src/test/java/com/thoughtworks/game_of_life/core/WorldTest.java
|
<reponame>fossabot/design_principles_dojo<filename>src/test/java/com/thoughtworks/game_of_life/core/WorldTest.java
package com.thoughtworks.game_of_life.core;
import org.junit.Before;
import org.junit.Test;
import static com.thoughtworks.game_of_life.core.Location.at;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
public class WorldTest {
private World world;
@Before
public void setUp() throws Exception {
world = new World();
}
@Test
public void world_should_be_initially_empty() {
assertThat(world.isEmpty(), is(true));
}
@Test
public void world_should_be_non_empty_after_adding_a_live_cell() {
world.setLiving(at(1, 1));
assertThat(world.isEmpty(), is(false));
}
@Test
public void empty_world_should_be_empty_after_advancing() {
world.advance();
assertThat(world.isEmpty(), is(true));
}
@Test
public void live_cells_with_fewer_than_two_live_neighbours_dies() {
world.setLiving(at(2, 2));
world.setLiving(at(2, 3));
world.advance();
assertThat(world.isEmpty(), is(true));
}
@Test
public void live_cells_with_two_live_neighbours_survives() {
world.setLiving(at(2, 2));
world.setLiving(at(2, 3));
world.setLiving(at(2, 4));
world.advance();
assertThat(world.isAlive(at(2, 3)), is(true));
assertThat(world.isEmpty(), is(false));
}
@Test
public void live_cells_with_three_live_neighbours_survives() {
world.setLiving(at(2, 3));
world.setLiving(at(2, 2));
world.setLiving(at(2, 4));
world.setLiving(at(3, 3));
world.advance();
assertThat(world.isAlive(at(2, 3)), is(true));
}
@Test
public void live_cells_with_more_than_three_live_neighbours_dies() {
world.setLiving(at(2, 3));
world.setLiving(at(2, 2));
world.setLiving(at(2, 4));
world.setLiving(at(3, 3));
world.setLiving(at(1, 3));
world.advance();
assertThat(world.isAlive(at(2, 3)), is(false));
}
@Test
public void dead_cell_with_exactly_three_live_neighbours_becomes_alive() {
world.setLiving(at(2, 2));
world.setLiving(at(2, 4));
world.setLiving(at(3, 3));
world.advance();
assertThat(world.isAlive(at(2, 3)), is(true));
}
}
|
kettanaito/react-advanced-form
|
cypress/integration/validation/other/index.js
|
<reponame>kettanaito/react-advanced-form
describe('Other', () => {
require('./ConditionalSchema.spec')
require('./AjaxPrefilling.spec')
})
|
yuri0x7c1/uxerp
|
uxcrm-ofbiz/generated-entity/src/main/java/org/apache/ofbiz/webapp/website/WebPage.java
|
<reponame>yuri0x7c1/uxerp
package org.apache.ofbiz.webapp.website;
import lombok.experimental.FieldNameConstants;
import java.io.Serializable;
import lombok.Getter;
import lombok.Setter;
import java.sql.Timestamp;
import org.apache.ofbiz.entity.GenericValue;
import java.util.List;
import java.util.ArrayList;
/**
* Web Page
*/
@FieldNameConstants
public class WebPage implements Serializable {
public static final long serialVersionUID = 4601365251141622784L;
public static final String NAME = "WebPage";
/**
* Web Page Id
*/
@Getter
@Setter
private String webPageId;
/**
* Page Name
*/
@Getter
@Setter
private String pageName;
/**
* Web Site Id
*/
@Getter
@Setter
private String webSiteId;
/**
* Last Updated Stamp
*/
@Getter
@Setter
private Timestamp lastUpdatedStamp;
/**
* Last Updated Tx Stamp
*/
@Getter
@Setter
private Timestamp lastUpdatedTxStamp;
/**
* Created Stamp
*/
@Getter
@Setter
private Timestamp createdStamp;
/**
* Created Tx Stamp
*/
@Getter
@Setter
private Timestamp createdTxStamp;
/**
* Content Id
*/
@Getter
@Setter
private String contentId;
public WebPage(GenericValue value) {
webPageId = (String) value.get(FIELD_WEB_PAGE_ID);
pageName = (String) value.get(FIELD_PAGE_NAME);
webSiteId = (String) value.get(FIELD_WEB_SITE_ID);
lastUpdatedStamp = (Timestamp) value.get(FIELD_LAST_UPDATED_STAMP);
lastUpdatedTxStamp = (Timestamp) value.get(FIELD_LAST_UPDATED_TX_STAMP);
createdStamp = (Timestamp) value.get(FIELD_CREATED_STAMP);
createdTxStamp = (Timestamp) value.get(FIELD_CREATED_TX_STAMP);
contentId = (String) value.get(FIELD_CONTENT_ID);
}
public static WebPage fromValue(org.apache.ofbiz.entity.GenericValue value) {
return new WebPage(value);
}
public static List<WebPage> fromValues(List<GenericValue> values) {
List<WebPage> entities = new ArrayList<>();
for (GenericValue value : values) {
entities.add(new WebPage(value));
}
return entities;
}
}
|
ArnisLielturks/Urho3D-Project-Template
|
app/src/main/cpp/Levels/Voxel/Chunk.h
|
#ifdef VOXEL_SUPPORT
#pragma once
#include <queue>
#include <Urho3D/Graphics/CustomGeometry.h>
#include <Urho3D/Graphics/Geometry.h>
#include <Urho3D/Scene/Scene.h>
#include <Urho3D/Core/Object.h>
#include <Urho3D/Scene/Node.h>
#include <Urho3D/Core/WorkQueue.h>
#include <Urho3D/Graphics/VertexBuffer.h>
#include <Urho3D/Graphics/IndexBuffer.h>
#include <Urho3D/Graphics/Model.h>
#include <Urho3D/IO/MemoryBuffer.h>
#include "VoxelDefs.h"
#include "ChunkMesh.h"
const int SIZE_X = 16;
const int SIZE_Y = 16;
const int SIZE_Z = 16;
const int PART_COUNT = 3;
using namespace Urho3D;
class Chunk : public Object {
URHO3D_OBJECT(Chunk, Object);
Chunk(Context* context);
virtual ~Chunk();
static void RegisterObject(Context* context);
public:
void Init(Scene* scene, const Vector3& position);
void Load();
const Vector3& GetPosition();
Node* GetNode() { return node_; }
void Save();
void MarkForDeletion(bool value);
bool IsMarkedForDeletion();
void MarkActive(bool value);
bool IsActive();
void SetActive();
BlockType GetBlockValue(int x, int y, int z);
bool Render();
VoxelBlock* GetBlockAt(IntVector3 position);
int GetSunlight(int x, int y, int z);
void SetSunlight(int x, int y, int z, int value);
int GetTorchlight(int x, int y, int z);
void SetTorchlight(int x, int y, int z, int value = 15);
unsigned char GetLightValue(int x, int y, int z);
void SetSunlight(int value);
bool ShouldRender();
bool IsLoaded();
bool IsGeometryCalculated();
void CalculateLight();
void CalculateGeometry();
void MarkForGeometryCalculation();
Chunk* GetNeighbor(BlockSide side);
void SetVoxel(int x, int y, int z, BlockType block);
BlockSide GetNeighborDirection(const IntVector3& position);
IntVector3 GetNeighborBlockPosition(const IntVector3& position);
Vector3 NeighborBlockWorldPosition(BlockSide side, IntVector3 blockPosition);
IntVector3 GetChunkBlock(Vector3 position);
void SetDistance(int distance);
const int GetDistance() const;
bool IsRequestedFromServer();
void LoadFromServer();
void ProcessServerResponse(MemoryBuffer& buffer);
void SetBlockData(const IntVector3& blockPosition, BlockType type);
bool ShouldSave();
private:
void HandleUpdate(StringHash eventType, VariantMap& eventData);
void HandleHit(StringHash eventType, VariantMap& eventData);
void HandleAdd(StringHash eventType, VariantMap& eventData);
Vector2 GetTextureCoord(BlockSide side, BlockType blockType, Vector2 position);
bool IsBlockInsideChunk(IntVector3 position);
void CreateNode();
void RemoveNode();
bool BlockHaveNeighbor(BlockSide side, int x, int y, int z);
BlockType GetBlockNeighbor(BlockSide side, int x, int y, int z);
unsigned char NeighborLightValue(BlockSide side, int x, int y, int z);
int GetPartIndex(int x, int y, int z);
void SendHitToServer(const IntVector3& position);
void SendAddToServer(const IntVector3& position, BlockType type);
Vector<SharedPtr<Node>> parts_;
SharedPtr<Node> node_;
SharedPtr<Node> waterNode_;
SharedPtr<Node> groundNode_;
SharedPtr<Node> label_;
Scene* scene_;
Vector3 position_;
VoxelBlock data_[SIZE_X][SIZE_Y][SIZE_Z];
unsigned char lightMap_[SIZE_X][SIZE_Y][SIZE_Z];
bool shouldDelete_{false};
bool isActive_{true};
Mutex mutex_;
bool loaded_{false};
bool requestedFromServer_{false};
Timer remoteLoadTimer_;
bool shouldRender_{false};
bool notified_{false};
int renderIndex_{0};
Timer saveTimer_;
int renderCounter_{0};
int distance_{0};
ChunkMesh chunkMesh_;
ChunkMesh chunkWaterMesh_;
int calculateIndex_{0};
int lastCalculatateIndex_{0};
bool shouldSave_{false};
int renderCount_{0};
};
#endif
|
aconstlink/snakeoil
|
audio/object.h
|
//------------------------------------------------------------
// snakeoil (c) <NAME>
// Distributed under the MIT license
//------------------------------------------------------------
#ifndef _SNAKEOIL_AUDIO_OBJECT_H_
#define _SNAKEOIL_AUDIO_OBJECT_H_
#include "api.h"
#include "protos.h"
#include "typedefs.h"
#include "result.h"
#include <snakeoil/core/assert.h>
namespace so_audio
{
/// non-copyable due to uniqueness of driver objects.
class SNAKEOIL_AUDIO_API object
{
so_this_typedefs( object ) ;
private:
so_audio::api_object_ptr_t _driver_object_ptr = nullptr ;
public:
so_audio::api_object_ptr_t get_driver_object( void_t )
{
return _driver_object_ptr ;
}
so_audio::api_object_cptr_t get_driver_object( void_t ) const
{
return _driver_object_ptr ;
}
void_t set_driver_object( so_audio::api_object_ptr_t ptr )
{
_driver_object_ptr = ptr ;
}
public:
object( void_t ){}
object( so_audio::api_object_ptr_t ptr ) : _driver_object_ptr(ptr) {}
object( this_cref_t ) = delete ;
object( this_rref_t rhv )
{
so_move_member_ptr( _driver_object_ptr, rhv ) ;
}
virtual ~object( void_t )
{
so_assert( has_no_dirver_object() ) ;
}
this_ref_t operator = ( this_rref_t rhv )
{
so_move_member_ptr( _driver_object_ptr, rhv ) ;
return *this ;
}
this_ref_t operator = ( this_cref_t ) = delete ;
public:
bool_t has_driver_object( void_t ) const
{
return _driver_object_ptr != nullptr ;
}
bool_t has_no_dirver_object( void_t ) const
{
return _driver_object_ptr == nullptr ;
}
public:
virtual void_t destroy( void_t ) = 0 ;
};
}
#endif
|
stpangst/onemall
|
order-service-project/order-service-app/src/main/java/cn/iocoder/mall/orderservice/service/cart/CartService.java
|
package cn.iocoder.mall.orderservice.service.cart;
import cn.iocoder.common.framework.exception.util.ServiceExceptionUtil;
import cn.iocoder.common.framework.util.CollectionUtils;
import cn.iocoder.mall.orderservice.convert.cart.CartConvert;
import cn.iocoder.mall.orderservice.dal.mysql.dataobject.cart.CartItemDO;
import cn.iocoder.mall.orderservice.dal.mysql.mapper.cart.CartItemMapper;
import cn.iocoder.mall.orderservice.service.cart.bo.CartItemAddBO;
import cn.iocoder.mall.orderservice.service.cart.bo.CartItemBO;
import cn.iocoder.mall.orderservice.service.cart.bo.CartItemListQueryBO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import java.util.Collection;
import java.util.List;
import static cn.iocoder.mall.orderservice.enums.OrderErrorCodeConstants.CARD_ITEM_NOT_FOUND;
import static cn.iocoder.mall.orderservice.enums.OrderErrorCodeConstants.CARD_ITEM_SKU_QUANTITY_NOT_ENOUGH;
/**
* 购物车 Service
*/
@Service
@Validated
public class CartService {
@Autowired
private CartItemMapper cartItemMapper;
/**
* 添加商品到购物车
*
* @param addBO 添加商品信息
* @param skuQuantity 商品 SKU 的库存,主要用于库存校验
*/
public void addCartItem(@Valid CartItemAddBO addBO, Integer skuQuantity) {
// 查询 CartItemDO
CartItemDO itemDO = cartItemMapper.selectByUserIdAndSkuId(addBO.getUserId(), addBO.getSkuId());
// 存在,则进行数量更新
if (itemDO != null) {
if (addBO.getQuantity() + itemDO.getQuantity() > skuQuantity) {
// 校验库存
throw ServiceExceptionUtil.exception(CARD_ITEM_SKU_QUANTITY_NOT_ENOUGH);
}
cartItemMapper.updateById(new CartItemDO().setId(itemDO.getId()).setSelected(true)
.setQuantity(addBO.getQuantity() + itemDO.getQuantity()));
return;
}
// 不存在,则进行插入
if (addBO.getQuantity() > skuQuantity) {
// 校验库存
throw ServiceExceptionUtil.exception(CARD_ITEM_SKU_QUANTITY_NOT_ENOUGH);
}
cartItemMapper.insert(CartConvert.INSTANCE.convert(addBO).setSelected(true));
}
/**
* 更新购物车商品数量
*
* @param userId 用户编号
* @param skuId 商品 SKU 编号
* @param quantity 数量
* @param skuQuantity 商品 SKU 的库存,主要用于库存校验
*/
public void updateCartItemQuantity(Integer userId, Integer skuId, Integer quantity, Integer skuQuantity) {
if (quantity > skuQuantity) {
// 校验库存
throw ServiceExceptionUtil.exception(CARD_ITEM_SKU_QUANTITY_NOT_ENOUGH);
}
// 查询 CartItemDO
CartItemDO itemDO = cartItemMapper.selectByUserIdAndSkuId(userId, skuId);
if (itemDO == null) {
throw ServiceExceptionUtil.exception(CARD_ITEM_NOT_FOUND);
}
// 更新数量
cartItemMapper.updateById(new CartItemDO().setId(itemDO.getId()).setQuantity(quantity));
}
/**
* 更新购物车商品是否选中
*
* @param userId 用户编号
* @param skuIds 商品 SKU 编号数组
* @param selected 是否选中
*/
public void updateCartItemSelected(Integer userId, Collection<Integer> skuIds, Boolean selected) {
// 查询 CartItemDO 列表
List<CartItemDO> itemDOs = cartItemMapper.selectListByUserIdAndSkuIds(userId, skuIds);
if (skuIds.size() != itemDOs.size()) {
throw ServiceExceptionUtil.exception(CARD_ITEM_NOT_FOUND);
}
// 更新选中
cartItemMapper.updateByIds(CollectionUtils.convertSet(itemDOs, CartItemDO::getId),
new CartItemDO().setSelected(selected));
}
/**
* 购物车删除商品
*
* @param userId 用户编号
* @param skuIds 商品 SKU 编号的数组
*/
public void deleteCartItems(Integer userId, List<Integer> skuIds) {
// 查询 CartItemDO 列表
List<CartItemDO> itemDOs = cartItemMapper.selectListByUserIdAndSkuIds(userId, skuIds);
if (CollectionUtils.isEmpty(itemDOs)) {
return;
}
// 批量标记删除
cartItemMapper.deleteBatchIds(CollectionUtils.convertSet(itemDOs, CartItemDO::getId));
}
/**
* 查询用户在购物车中的商品数量
*
* @param userId 用户编号
* @return 商品数量
*/
public Integer sumCartItemQuantity(Integer userId) {
return cartItemMapper.selectSumQuantityByUserId(userId);
}
/**
* 查询用户在购物车种的商品列表
*
* @param queryBO 查询条件 BO
* @return 购物车中商品列表信息
*/
public List<CartItemBO> listCartItems(CartItemListQueryBO queryBO) {
List<CartItemDO> cartItemDOs = cartItemMapper.selectList(queryBO);
return CartConvert.INSTANCE.convertList(cartItemDOs);
}
}
|
rachwal/DesignPatterns
|
operational/src/memento/move_command.h
|
// Based on "Design Patterns: Elements of Reusable Object-Oriented Software"
// book by <NAME>, <NAME>, <NAME>, and <NAME>
//
// Created by <NAME>. The National Institute of Advanced Industrial Science and Technology, Japan.
#ifndef OPERATIONAL_MEMENTO_MOVE_COMMAND_H_
#define OPERATIONAL_MEMENTO_MOVE_COMMAND_H_
#include "constraint_solver_interface.h"
namespace operational
{
namespace memento
{
class MoveCommand
{
public:
MoveCommand(ConstraintSolverInterface* solver, Graphic* target, const structural::commons::Point<float>& delta);
void Execute();
void Unexecute();
private:
ConstraintSolverInterface* solver_;
ConstraintSolverMemento* state_;
structural::commons::Point<float> delta_;
Graphic* target_;
};
}
}
#endif
|
BenniN/OpenPEARLThesis
|
OpenPEARL/openpearl-code/compiler/src/org/smallpearl/compiler/Compiler.java
|
<filename>OpenPEARL/openpearl-code/compiler/src/org/smallpearl/compiler/Compiler.java
/*
* [The "BSD license"]
* Copyright (c) 2012-2017 <NAME>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.smallpearl.compiler;
import org.antlr.v4.runtime.*;
import org.stringtemplate.v4.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.concurrent.TimeUnit;
import static org.smallpearl.compiler.Log.LEVEL_INFO;
import static org.smallpearl.compiler.Log.LEVEL_NONE;
import static org.smallpearl.compiler.Log.LEVEL_WARN;
import static org.smallpearl.compiler.Log.LEVEL_DEBUG;
import static org.smallpearl.compiler.Log.LEVEL_ERROR;
public class Compiler {
static String version = "v0.8.9.40";
static String grammarName;
static String startRuleName;
static List<String> inputFiles = new ArrayList<String>();
static String m_sourceFilename = "";
static boolean printAST = false;
static String psFile = null;
static String outputFilename = null;
static boolean showTokens = false;
static boolean trace = true;
static boolean diagnostics = false;
static String encoding = null;
static boolean SLL = false;
static boolean nosemantic = false;
static boolean constantfolding = true;
static int verbose = 0;
static String groupFile = "SmallPearlCpp.stg";
static boolean lineSeparatorHasToBeModified = true;
static boolean dumpDFA = false;
static boolean dumpSymbolTable = false;
static boolean dumpConstantPool = false;
static boolean debug = false;
static boolean debugSTG = false;
static boolean stacktrace = false;
static boolean imc = true;
static boolean printSysInfo = false;
static int noOfErrors = 0;
static int noOfWarnings = 0;
static int warninglevel = 255;
static int lineWidth = 80;
static boolean coloured = false;
public static void main(String[] args) {
int i, j;
if (args.length < 1) {
printHelp();
return;
}
long startTime = System.nanoTime();
Runtime runtime = Runtime.getRuntime();
ConstantPool constantPool = new ConstantPool();
SymbolTableVisitor symbolTableVisitor = new SymbolTableVisitor(verbose, constantPool);
if (!checkAndProcessArguments(args)) {
return;
}
ErrorStack.useColors(coloured);
// Setup logger
Log.Logger logger = new Log.Logger();
Log.setLogger(logger);
//Log.set(LEVEL_INFO);
for (i = 0; i < inputFiles.size(); i++) {
SmallPearlLexer lexer = null;
AST ast = new AST();
m_sourceFilename = inputFiles.get(i);
logger.setLogFilename(getBaseName(m_sourceFilename) + ".log");
Log.info("OpenPEARL compiler version " + version);
Log.info("Start compiling of:" + m_sourceFilename);
Log.debug("Performing syntax check");
try {
lexer = new SmallPearlLexer(new ANTLRFileStream(m_sourceFilename));
}
catch(IOException ex) {
System.out.println("Error:" + ex.getMessage());
System.exit(-2);
}
lexer.removeErrorListeners();
lexer.addErrorListener(DescriptiveErrorListener.INSTANCE);
CommonTokenStream tokens = new CommonTokenStream(lexer);
SmallPearlParser parser = new SmallPearlParser(tokens);
parser.removeErrorListeners();
parser.addErrorListener(DescriptiveErrorListener.INSTANCE);
parser.setBuildParseTree(true);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Start Analysis
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ParserRuleContext tree = parser.program();
if (printAST) {
System.out.println("Parse tree:");
System.out.println(tree.toStringTree(parser));
}
if (dumpDFA) {
parser.dumpDFA();
}
try {
if (parser.getNumberOfSyntaxErrors() <= 0) {
symbolTableVisitor.visit(tree);
if (dumpSymbolTable) {
symbolTableVisitor.symbolTable.dump();
}
}
ExpressionTypeVisitor expressionTypeVisitor = new ExpressionTypeVisitor(verbose, debug, symbolTableVisitor, constantPool, ast);
if (ErrorStack.getTotalErrorCount()<=0) {
expressionTypeVisitor.visit(tree);
}
if (ErrorStack.getTotalErrorCount()<=0) {
ConstantFoldingVisitor constantFoldingVisitor = new ConstantFoldingVisitor(symbolTableVisitor, ast);
constantFoldingVisitor.visit(tree);
}
ConstantPoolVisitor constantPoolVisitor = new ConstantPoolVisitor(lexer.getSourceName(),
verbose,
debug,
symbolTableVisitor,
constantPool,
expressionTypeVisitor,
ast);
if (ErrorStack.getTotalErrorCount()<=0) {
constantPoolVisitor.visit(tree);
}
ConstantExpressionEvaluatorVisitor constantExpressionVisitor = new ConstantExpressionEvaluatorVisitor(verbose, debug, symbolTableVisitor, constantPoolVisitor);
if (ErrorStack.getTotalErrorCount()<=0) {
constantExpressionVisitor.visit(tree);
}
if (ErrorStack.getTotalErrorCount()<=0) {
FixUpSymbolTableVisitor fixUpSymbolTableVisitor = new FixUpSymbolTableVisitor(verbose,debug,symbolTableVisitor,expressionTypeVisitor,constantPoolVisitor,ast);
fixUpSymbolTableVisitor.visit(tree);
}
// expressionTypeVisitor.visit(tree);
if (dumpConstantPool) {
ConstantPool.dump();
}
if (ErrorStack.getTotalErrorCount() <= 0 && !nosemantic) {
SemanticCheck semanticCheck = new SemanticCheck(lexer.getSourceName(), verbose, debug, tree, symbolTableVisitor, expressionTypeVisitor, ast);
}
if (ErrorStack.getTotalErrorCount() <= 0 && imc) {
SystemPartExport(lexer.getSourceName(), tree);
}
if (ErrorStack.getTotalErrorCount() <= 0) {
CppGenerate(lexer.getSourceName(), tree, symbolTableVisitor, expressionTypeVisitor, constantExpressionVisitor, ast);
}
}
catch(Exception ex) {
System.err.println(ex.getMessage());
ex.printStackTrace();
if (debug) {
ex.printStackTrace();
}
if ( verbose > 0 ) {
System.err.println("Compilation aborted.");
}
if (dumpSymbolTable) {
symbolTableVisitor.symbolTable.dump();
}
if (dumpConstantPool) {
ConstantPool.dump();
}
if ( stacktrace ) {
System.err.println( getStackTrace(ex));
}
System.exit(-1);
}
if (ErrorStack.getTotalErrorCount()>0) {
System.out.println("compilation aborted with errors");
if ( verbose > 0 ) {
System.err.println("Compilation aborted.");
}
if (dumpSymbolTable) {
symbolTableVisitor.symbolTable.dump();
}
if (dumpConstantPool) {
ConstantPool.dump();
}
System.exit(-1);
}
noOfErrors = parser.getNumberOfSyntaxErrors();
System.out.flush();
System.out.println();
System.out.println("Number of errors in " + inputFiles.get(i) + " encountered: " + noOfErrors);
if ( printSysInfo) {
String lines;
long difference = System.nanoTime() - startTime;
lines = "System Information:\n";
lines += "Total execution time: " +
String.format("%d.%d sec",
TimeUnit.NANOSECONDS.toSeconds(difference),
TimeUnit.NANOSECONDS.toMillis(difference) - TimeUnit.NANOSECONDS.toSeconds(difference) * 1000);
SystemInformation sysinfo = new SystemInformation();
lines += "\n" + sysinfo.Info();
Log.info(lines);
System.out.println(lines);
}
if ( noOfErrors == 0 ) {
System.exit(0);
} else {
System.exit(1);
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void printHelp() {
System.err.println("java org.smallpearl.compiler \n" +
" Options: \n" +
" --help Print this help message \n" +
" --version Print version information \n" +
" --verbose Print more information \n" +
" --quiet Be quiet \n" +
" --trace \n" +
" --nosemantic Disable semantic checker \n" +
" --noconstantfolding Disable constant folding \n" +
" --printAST Print Abtract Syntax Tree \n" +
" --dumpDFA Print DFA \n" +
" --dumpSymbolTable Print the SymbolTable \n" +
" --dumpConstantPool Print the constant pool \n" +
" --debug Generate debug information \n" +
" --stacktrace Print stacktrace in case of an \n" +
" exception \n" +
" --warninglevel <m_level> Set the warning m_level \n" +
" Level 0: no warning \n" +
" Level 255: all warnings (default) \n" +
" --imc Enable Inter Module Checker \n" +
" file \n" +
" --sysinfo Print system information \n" +
" --coloured mark errors with colour \n" +
" --output <filename> Filename of the generated code \n" +
" infile ... \n");
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static boolean checkAndProcessArguments(String[] args) {
int i = 0;
while (i < args.length) {
String arg = args[i];
i++;
if (arg.charAt(0) != '-') { // input file name
inputFiles.add(arg);
continue;
}
if (arg.equals("--help")) {
printHelp();
System.exit(0);
} else if (arg.equals("--printAST")) {
printAST = true;
} else if (arg.equals("--tokens")) {
showTokens = true;
} else if (arg.equals("--trace")) {
trace = true;
} else if (arg.equals("--SLL")) {
SLL = true;
} else if (arg.equals("--sysinfo")) {
printSysInfo = true;
} else if (arg.equals("--nosemantic")) {
nosemantic = true;
} else if (arg.equals("--noconstantfolding")) {
constantfolding = false;
} else if (arg.equals("--diagnostics")) {
diagnostics = true;
} else if (arg.equals("--dumpDFA")) {
dumpDFA = true;
} else if (arg.equals("--dumpSymbolTable")) {
dumpSymbolTable = true;
} else if (arg.equals("--dumpConstantPool")) {
dumpConstantPool = true;
} else if (arg.equals("--debug")) {
debug = true;
Log.set(LEVEL_DEBUG);
} else if (arg.equals("--debugSTG")) {
debugSTG = true;
} else if (arg.equals("--stacktrace")) {
stacktrace = true;
} else if (arg.equals("--imc")) {
imc = true;
} else if (arg.equals("--coloured")) {
coloured = true;
} else if (arg.equals("--output")) {
if (i >= args.length) {
System.err.println("missing filename on --output");
return false;
}
outputFilename = args[i];
i++;
continue;
} else if (arg.equals("-encoding")) {
if (i >= args.length) {
System.err.println("missing encoding on -encoding");
return false;
}
encoding = args[i];
i++;
} else if (arg.equals("--ps")) {
if (i >= args.length) {
System.err.println("missing filename on --ps");
return false;
}
psFile = args[i];
i++;
} else if (arg.equals("--version")) {
System.out.println("OpenPEARL compiler version "+version);
i++;
} else if (arg.equals("--warninglevel")) {
if (i >= args.length) {
System.err.println("missing warning m_level on --warninglevel");
return false;
}
warninglevel = Integer.parseInt(args[i]);
i++;
} else {
System.out.println("Unknown command line argument:" + arg);
return false;
}
}
return true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private static Void CppGenerate(String sourceFileName,
ParserRuleContext tree,
SymbolTableVisitor symbolTableVisitor,
ExpressionTypeVisitor expressionTypeVisitor,
ConstantExpressionEvaluatorVisitor constantExpressionEvaluatorVisitor,
AST ast) {
CppCodeGeneratorVisitor cppCodeGenerator = new CppCodeGeneratorVisitor( sourceFileName,
groupFile,
verbose,
debug,
symbolTableVisitor,
expressionTypeVisitor,
constantExpressionEvaluatorVisitor,
ast);
ST code = cppCodeGenerator.visit(tree);
if ( debugSTG ) {
System.out.println( "Press a key to continue" );
code.inspect();
try {
int ch = System.in.read();
}
catch (IOException ex) {
}
}
if (outputFilename != null) {
try {
if ( outputFilename.lastIndexOf(".") == - 1 ) {
outputFilename += ".cc";
}
if (verbose>0) {
System.out.println("Generating output file "+outputFilename);
}
PrintWriter writer = new PrintWriter(outputFilename, "UTF-8");
writer.println(code.render(lineWidth));
writer.close();
} catch (IOException e) {
System.err.println("Problem writing to the file " + outputFilename);
}
} else {
if(verbose>0) {
System.out.println("Generated output:");
}
System.out.println(code.render(lineWidth));
}
return null;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private static Void SystemPartExport(String sourceFileName, ParserRuleContext tree) {
String outputFileName = sourceFileName;
SystemPartExporter systemPartExporter = new SystemPartExporter(sourceFileName,verbose, debug);
ST systemPart = systemPartExporter.visit(tree);
if ( debugSTG ) {
System.out.println( "Press a key to continue" );
systemPart.inspect();
try {
int ch = System.in.read();
}
catch (IOException ex) {
}
}
outputFileName = getBaseName(outputFileName).concat(".xml");
try {
if (verbose>0) {
System.out.println("Generating IMC file "+outputFileName);
}
PrintWriter writer = new PrintWriter(outputFileName, "UTF-8");
writer.println(systemPart.render(lineWidth));
writer.close();
} catch (IOException e) {
System.err.println("Problem writing the IMC file " + outputFileName);
}
return null;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static String getStackTrace(Throwable t) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw, true);
t.printStackTrace(pw);
pw.flush();
sw.flush();
return sw.toString();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static String getBaseName(String filename) {
String basename = "";
if (filename != null) {
basename = filename.substring(0, filename.lastIndexOf('.'));
}
return basename;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static String getSourceFilename() {
return m_sourceFilename;
}
}
|
Lywx/FalconEngine
|
src/FalconEngine/Graphics/Renderer/VisualEffectInstance.cpp
|
#include <FalconEngine/Graphics/Renderer/VisualEffectInstance.h>
#include <FalconEngine/Graphics/Renderer/VisualEffect.h>
#include <FalconEngine/Graphics/Renderer/VisualEffectPass.h>
#include <FalconEngine/Graphics/Renderer/Resource/Texture.h>
#include <FalconEngine/Graphics/Renderer/Resource/Sampler.h>
namespace FalconEngine
{
/************************************************************************/
/* Constructors and Destructor */
/************************************************************************/
VisualEffectInstance::VisualEffectInstance(const std::shared_ptr<VisualEffect>& effect) :
mEffect(effect)
{
for (int i = 0; i < mEffect->GetPassNum(); ++i)
{
mEffectInstancePassList.push_back(std::make_unique<VisualEffectInstancePass>(mEffect->GetShader(i)));
}
}
VisualEffectInstance::~VisualEffectInstance()
{
}
/************************************************************************/
/* Public Members */
/************************************************************************/
const VisualEffect *
VisualEffectInstance::GetEffect() const
{
return mEffect.get();
}
VisualEffect *
VisualEffectInstance::GetEffect()
{
return mEffect.get();
}
int
VisualEffectInstance::GetPassNum() const
{
return mEffect->GetPassNum();
}
VisualEffectInstancePass *
VisualEffectInstance::GetPass(int passIndex)
{
return mEffectInstancePassList.at(passIndex).get();
}
int
VisualEffectInstance::GetShaderInstancingNum(int passIndex) const
{
return mEffectInstancePassList.at(passIndex)->GetInstancingNum();
}
void
VisualEffectInstance::SetShaderInstancingNum(int passIndex, int instancingNum)
{
mEffectInstancePassList.at(passIndex)->SetInstancingNum(instancingNum);
}
const Texture *
VisualEffectInstance::GetShaderTexture(int passIndex, int textureUnit) const
{
return mEffectInstancePassList.at(passIndex)->GetTexture(textureUnit);
}
void
VisualEffectInstance::SetShaderTexture(int passIndex, int textureUnit, const Texture *texture,
TextureMode textureMode, ShaderType shaderType)
{
SetShaderTexture(passIndex, textureUnit, texture, textureMode, GetShaderMask(shaderType));
}
void
VisualEffectInstance::SetShaderTexture(int passIndex,
int textureUnit,
const Texture *texture,
TextureMode textureMode,
unsigned int shaderMask)
{
FALCON_ENGINE_CHECK_NULLPTR(texture);
mEffectInstancePassList.at(passIndex)->SetTexture(textureUnit, texture, textureMode, shaderMask);
}
const Sampler *
VisualEffectInstance::GetShaderSampler(int passIndex, int textureUnit) const
{
return mEffectInstancePassList.at(passIndex)->GetSampler(textureUnit);
}
void
VisualEffectInstance::SetShaderSampler(int passIndex, int textureUnit, const Sampler *sampler,
ShaderType shaderType)
{
SetShaderSampler(passIndex, textureUnit, sampler, GetShaderMask(shaderType));
}
void
VisualEffectInstance::SetShaderSampler(int passIndex,
int textureUnit,
const Sampler *sampler,
unsigned int shaderMask)
{
FALCON_ENGINE_CHECK_NULLPTR(sampler);
mEffectInstancePassList.at(passIndex)->SetSampler(textureUnit, sampler, shaderMask);
}
}
|
txwhhny/vtk
|
Rendering/VolumeOpenGL2/vtkOpenGLVolumeGradientOpacityTable.h
|
<gh_stars>100-1000
/*=========================================================================
Program: Visualization Toolkit
Module: vtkOpenGLVolumeGradientOpacityTable.h
Copyright (c) <NAME>, <NAME>, <NAME>
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#ifndef vtkOpenGLVolumeGradientOpacityTable_h
#define vtkOpenGLVolumeGradientOpacityTable_h
#ifndef __VTK_WRAP__
#include "vtkOpenGLVolumeLookupTable.h"
// Forward declarations
class vtkOpenGLRenderWindow;
//----------------------------------------------------------------------------
class vtkOpenGLVolumeGradientOpacityTable : public vtkOpenGLVolumeLookupTable
{
public:
vtkTypeMacro(vtkOpenGLVolumeGradientOpacityTable, vtkOpenGLVolumeLookupTable);
void PrintSelf(ostream& os, vtkIndent indent) override;
static vtkOpenGLVolumeGradientOpacityTable* New();
protected:
vtkOpenGLVolumeGradientOpacityTable() = default;
/**
* Update the internal texture object using the gradient opacity transfer
* function
*/
void InternalUpdate(vtkObject* func, int blendMode, double sampleDistance, double unitDistance,
int filterValue) override;
private:
vtkOpenGLVolumeGradientOpacityTable(const vtkOpenGLVolumeGradientOpacityTable&) = delete;
vtkOpenGLVolumeGradientOpacityTable& operator=(
const vtkOpenGLVolumeGradientOpacityTable&) = delete;
};
#endif // __VTK_WRAP__
#endif // vtkOpenGLVolumeGradientOpacityTable_h
// VTK-HeaderTest-Exclude: vtkOpenGLVolumeGradientOpacityTable.h
|
biothings/biothings_interactions
|
biointeract/hub/dataload/sources/ctdchemgene/uploader.py
|
<reponame>biothings/biothings_interactions
import os
import gzip
import biothings, config
biothings.config_for_app(config)
import biothings.hub.dataload.uploader as uploader
from .parser import CTDChemGeneParser
class CTDChemGeneUploader(uploader.BaseSourceUploader):
# main_source = "ConsensusPathDB"
name = "CTD_chem_gene_ixns"
collection_name = "CTD_chem_gene_ixns"
zip_file_name = "CTD_chem_gene_ixns.tsv.gz"
# __metadata__ = {"mapper": 'consensuspathdb_mapper'}
def load_data(self, data_folder):
downloaded_file = os.path.join(data_folder, self.zip_file_name)
self.logger.info("Load data from file '%s'" % downloaded_file)
return CTDChemGeneParser.parse_tsv_file(gzip.open(downloaded_file, mode='rt'))
|
didadadida93/hacktiv8-bootcamp
|
phase0/week2/p0-w2-exercises-3.js
|
let name = "Arief";
let peran = "Tabib";
if (name === '') {
console.log("Nama harus diisi!");
} else {
if (peran === '') {
console.log(`Halo ${name}, Pilih peranmu untuk memulai game!`);
} else {
console.log(`Selamat datang di Dunia Proxytia, ${name}`);
if (peran.toLowerCase() === 'ksatria') {
console.log(`Halo Ksatria ${name}, kamu dapat menyerang dengan senjatamu!`);
} else if (peran.toLowerCase() === 'tabib') {
console.log(`Halo Tabib ${name}, kamu akan membantu temanmu yang terluka.`);
} else if (peran.toLowerCase() === 'penyihir') {
console.log(`Halo Penyihir ${name}, ciptakan keajaiban yang membantu kemenanganmu!`);
} else {
console.log(`Peran ${peran} tidak tersedia.`);
}
}
}
|
mirohs/prog1javalib
|
src/prog1/graphics/Shape.java
|
/*
* Copyright 2016 michaelrohs.
*
* 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 prog1.graphics;
import javafx.scene.paint.Color;
/**
* An abstract shape.
* @author michaelrohs
*/
abstract class Shape extends Image {
private final Color color;
private final Pen pen;
public Shape(double width, double height, Color color, Pen pen) {
super(width, height);
this.color = color;
this.pen = pen;
}
@Override
protected abstract javafx.scene.Node render();
protected javafx.scene.Node render(javafx.scene.shape.Shape s) {
s.setFill(color);
if (pen != null) {
s.setStroke(pen.color);
s.setStrokeWidth(pen.width);
s.setStrokeType(pen.type);
s.setStrokeLineCap(pen.cap);
s.setStrokeLineJoin(pen.join);
// .setStrokeMiterLimit(10.0);
// .setStrokeDashOffset(0.0);
// .getStrokeDashArray().addAll(7.0, 21.0);
} else {
s.setStroke(null);
}
// if (clip != null) {
// s.setClip(clip.render());
// }
if (pressFunction != null) {
// System.out.println("Shape.render: pressFunction = " + pressFunction);
// System.out.println(Thread.currentThread());
s.addEventHandler(javafx.scene.input.MouseEvent.MOUSE_PRESSED, (javafx.scene.input.MouseEvent e) -> {
pressFunction.apply(new MouseEvent(e), pressFunctionTarget);
e.consume();
ApplicationBase.draw();
});
}
if (releaseFunction != null) {
// System.out.println("Shape.render: releaseFunction = " + releaseFunction);
// System.out.println(Thread.currentThread());
s.addEventHandler(javafx.scene.input.MouseEvent.MOUSE_RELEASED, (javafx.scene.input.MouseEvent e) -> {
releaseFunction.apply(new MouseEvent(e), releaseFunctionTarget);
e.consume();
ApplicationBase.draw();
});
}
if (moveFunction != null) {
s.addEventHandler(javafx.scene.input.MouseEvent.MOUSE_MOVED, (javafx.scene.input.MouseEvent e) -> {
moveFunction.apply(new MouseEvent(e), moveFunctionTarget);
e.consume();
ApplicationBase.draw();
});
}
if (dragFunction != null) {
s.addEventHandler(javafx.scene.input.MouseEvent.MOUSE_DRAGGED, (javafx.scene.input.MouseEvent e) -> {
dragFunction.apply(new MouseEvent(e), dragFunctionTarget);
e.consume();
ApplicationBase.draw();
});
}
return s;
}
@Override
protected String toString(String indent) {
return indent + String.format("<" + getClass().getSimpleName() +
" width=\"%.1f\" height=\"%.1f\" color=\"%s\" pen=\"%s\"/>\n",
width, height,
color == null ? "null" : color.toString(),
pen == null ? "null" : pen.toString());
}
}
|
trollknurr/sourcegraph
|
cmd/frontend/internal/pkg/search/query/syntax/query.go
|
package syntax
import (
"bytes"
"fmt"
"regexp"
"strings"
)
// A Query contains the parse tree of a query.
type Query struct {
Input string // the original input query string
Expr []*Expr // expressions in this query
}
func (q *Query) String() string {
return ExprString(q.Expr)
}
// WithErrorsQuoted converts a query like `f:foo b(ar` to `f:foo "b(ar"`.
func (q *Query) WithErrorsQuoted() *Query {
q2 := &Query{}
for _, e := range q.Expr {
e2 := e.WithErrorsQuoted()
q2.Expr = append(q2.Expr, &e2)
}
return q2
}
// An Expr describes an expression in a query.
type Expr struct {
Pos int // the starting character position of the query expression
Not bool // the expression is negated (e.g., -term or -field:term)
Field string // the field that this expression applies to
Value string // the raw field value
ValueType TokenType // the type of the value
}
func (e Expr) String() string {
var buf bytes.Buffer
if e.Not {
buf.WriteByte('-')
}
if e.Field != "" {
buf.WriteString(e.Field)
buf.WriteByte(':')
}
if e.ValueType == TokenPattern {
buf.WriteByte('/')
}
buf.WriteString(e.Value)
if e.ValueType == TokenPattern {
buf.WriteByte('/')
}
return buf.String()
}
// WithErrorsQuoted returns a new version of the expression,
// quoting in case of TokenError or an invalid regular expression.
func (e Expr) WithErrorsQuoted() Expr {
e2 := e
needsQuoting := false
switch e.ValueType {
case TokenError:
needsQuoting = true
case TokenPattern, TokenLiteral:
_, err := regexp.Compile(e2.Value)
if err != nil {
needsQuoting = true
}
}
if needsQuoting {
e2.Not = false
e2.Field = ""
e2.Value = fmt.Sprintf("%q", e.String())
e2.ValueType = TokenQuoted
}
return e2
}
// ExprString returns the query string that parses to expr.
func ExprString(expr []*Expr) string {
s := make([]string, len(expr))
for i, e := range expr {
s[i] = e.String()
}
return strings.Join(s, " ")
}
|
agent1894/Quant-Practice-Workspace
|
Cpp_Workspace/C++ Primer Plus/Chapter06/Chapter6_exercise8.cpp
|
// 6.11.8 -- read and count characters
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
{
using namespace std;
cout << "Enter the file name: ";
string filename;
cin >> filename;
ifstream inFile;
inFile.open(filename);
if (!inFile.is_open()) // failed to open file
{
cout << "Could not open the file " << filename << endl;
cout << "Program terminating. " << endl;
exit(EXIT_FAILURE);
}
int count = 0;
char ch;
inFile >> ch;
while (inFile >> ch) // while input good and not at EOF
++count; // one more item read
if (inFile.eof())
cout << "End of file reached." << endl;
else
cout << "Input terminated for unknown reason. " << endl;
cout << "The file has " << count << " characters." << endl;
inFile.close();
return 0;
}
|
EricChang82/springBootDemo
|
springBootDemo/src/main/java/cn/dataModel/TextEditor.java
|
package cn.dataModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import cn.Util;
@Component
public class TextEditor {
@Autowired
private SpellChecker spellChecker3332;
public SpellChecker getSpellChecker( ) {
return spellChecker3332;
}
public void setSpellChecker(SpellChecker spellChecker1 ){
this.spellChecker3332 = spellChecker1;
}
public void spellCheck() {
Util.print("1111111");
// spellChecker3332.checkSpelling();
}
}
|
amvb/GUCEF
|
plugins/COMCORE/pubsubpluginMSMQ/src/pubsubpluginMSMQ_CMsmqPubSubClient.cpp
|
<reponame>amvb/GUCEF
/*
* pubsubpluginMSMQ: Generic GUCEF COMCORE plugin for providing pubsub via Microsoft MSMQ
*
* Copyright (C) 1998 - 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.
*/
/*-------------------------------------------------------------------------//
// //
// INCLUDES //
// //
//-------------------------------------------------------------------------*/
#include <Objbase.h>
#include <string.h>
#ifndef GUCEF_MT_CSCOPEMUTEX_H
#include "gucefMT_CScopeMutex.h"
#define GUCEF_MT_CSCOPEMUTEX_H
#endif /* GUCEF_MT_CSCOPEMUTEX_H ? */
#ifndef GUCEF_CORE_DVOSWRAP_H
#include "DVOSWRAP.h"
#define GUCEF_CORE_DVOSWRAP_H
#endif /* GUCEF_CORE_DVOSWRAP_H */
#ifndef GUCEF_CORE_METRICSMACROS_H
#include "gucefCORE_MetricsMacros.h"
#define GUCEF_CORE_METRICSMACROS_H
#endif /* GUCEF_CORE_METRICSMACROS_H ? */
#ifndef GUCEF_CORE_CTASKMANAGER_H
#include "gucefCORE_CTaskManager.h"
#define GUCEF_CORE_CTASKMANAGER_H
#endif /* GUCEF_CORE_CTASKMANAGER_H */
#include "pubsubpluginMSMQ_CMsmqPubSubClient.h"
/*-------------------------------------------------------------------------//
// //
// NAMESPACE //
// //
//-------------------------------------------------------------------------*/
namespace GUCEF {
namespace PUBSUBPLUGIN {
namespace MSMQ {
/*-------------------------------------------------------------------------//
// //
// GLOBAL VARS //
// //
//-------------------------------------------------------------------------*/
const CORE::CString CMsmqPubSubClient::TypeName = "MSMQ";
/*-------------------------------------------------------------------------//
// //
// IMPLEMENTATION //
// //
//-------------------------------------------------------------------------*/
CMsmqPubSubClient::CMsmqPubSubClient( const COMCORE::CPubSubClientConfig& config )
: COMCORE::CPubSubClient()
, m_config( config )
, m_metricsTimer( GUCEF_NULL )
, m_topicMap()
, m_threadPool()
{GUCEF_TRACE;
if ( GUCEF_NULL != config.pulseGenerator )
{
if ( config.desiredFeatures.supportsMetrics )
{
m_metricsTimer = new CORE::CTimer( *config.pulseGenerator, 1000 );
m_metricsTimer->SetEnabled( config.desiredFeatures.supportsMetrics );
}
}
else
{
if ( config.desiredFeatures.supportsMetrics )
{
m_metricsTimer = new CORE::CTimer( 1000 );
m_metricsTimer->SetEnabled( config.desiredFeatures.supportsMetrics );
}
}
if ( config.desiredFeatures.supportsSubscribing )
m_threadPool = CORE::CCoreGlobal::Instance()->GetTaskManager().GetOrCreateThreadPool( "MsmqPubSubClient(" + CORE::ToString( this ) + ")", true );
RegisterEventHandlers();
}
/*-------------------------------------------------------------------------*/
CMsmqPubSubClient::~CMsmqPubSubClient()
{GUCEF_TRACE;
if ( !m_threadPool.IsNULL() )
m_threadPool->RequestAllThreadsToStop( true, false );
delete m_metricsTimer;
m_metricsTimer = GUCEF_NULL;
}
/*-------------------------------------------------------------------------*/
COMCORE::CPubSubClientConfig&
CMsmqPubSubClient::GetConfig( void )
{GUCEF_TRACE;
return m_config;
}
/*-------------------------------------------------------------------------*/
CORE::ThreadPoolPtr
CMsmqPubSubClient::GetThreadPool( void )
{GUCEF_TRACE;
return m_threadPool;
}
/*-------------------------------------------------------------------------*/
bool
CMsmqPubSubClient::GetSupportedFeatures( COMCORE::CPubSubClientFeatures& features )
{GUCEF_TRACE;
features.supportsBinaryPayloads = true; // The MSMQ body property supports a binary payload
features.supportsPerMsgIds = true; // MSMQ has the concept of a message ID which is unique and an additional non-unique label
features.supportsPrimaryPayloadPerMsg = true; // For MSMQ "BODY" is the primary payload which is also in of itself a key-value message propery
features.supportsKeyValueSetPerMsg = false; // Arbitrary key-value app data is not natively supported by MSMQ
features.supportsDuplicateKeysPerMsg = false; // TODO: Since arbitrary key-value app data is not native and we simulate this we will do so in a manner that supports duplicate keys
features.supportsMetaDataKeyValueSetPerMsg = true; // This is native to MSMQ
features.supportsMultiHostSharding = false; // MSMQ is tied to the Windows O/S and queues are not auto shared across such O/S instances
features.supportsPublishing = true; // We support being a MSQM queue publisher in this plugin
features.supportsSubscribing = true; // We support being a MSMQ queue subscriber in this plugin
features.supportsMetrics = true; // This plugin has support for reporting its own set of metrics
features.supportsAutoReconnect = true; // Not applicable to local queues and for remote queues MSMQ supports the concept of "offline mode"
features.supportsBookmarkingConcept = true; // Always getting the top msg in the queue could be thought of as "remembering your last read position" so as such we will claim MSMQ supports this
features.supportsAutoBookmarking = true; // Always getting the top msg in the queue could be thought of as "remembering your last read position" so as such we will claim MSMQ supports this
features.supportsMsgIdBasedBookmark = false; // MSMQ does not support this concept. receiving messages removes them from the O/S queue
features.supportsMsgDateTimeBasedBookmark = false; // MSMQ does not support this concept. receiving messages removes them from the O/S queue
return true;
}
/*-------------------------------------------------------------------------*/
COMCORE::CPubSubClientTopic*
CMsmqPubSubClient::CreateTopicAccess( const COMCORE::CPubSubClientTopicConfig& topicConfig )
{GUCEF_TRACE;
CMsmqPubSubClientTopic* rcTopic = new CMsmqPubSubClientTopic( this );
if ( rcTopic->LoadConfig( topicConfig ) )
{
m_topicMap[ topicConfig.topicName ] = rcTopic;
}
return rcTopic;
}
/*-------------------------------------------------------------------------*/
COMCORE::CPubSubClientTopic*
CMsmqPubSubClient::GetTopicAccess( const CORE::CString& topicName )
{GUCEF_TRACE;
TTopicMap::iterator i = m_topicMap.find( topicName );
if ( i != m_topicMap.end() )
{
return (*i).second;
}
return GUCEF_NULL;
}
/*-------------------------------------------------------------------------*/
void
CMsmqPubSubClient::DestroyTopicAccess( const CORE::CString& topicName )
{GUCEF_TRACE;
TTopicMap::iterator i = m_topicMap.find( topicName );
if ( i != m_topicMap.end() )
{
delete (*i).second;
m_topicMap.erase( i );
}
}
/*-------------------------------------------------------------------------*/
const CORE::CString&
CMsmqPubSubClient::GetType( void ) const
{GUCEF_TRACE;
return TypeName;
}
/*-------------------------------------------------------------------------*/
bool
CMsmqPubSubClient::SaveConfig( CORE::CDataNode& tree ) const
{GUCEF_TRACE;
return false;
}
/*-------------------------------------------------------------------------*/
bool
CMsmqPubSubClient::LoadConfig( const CORE::CDataNode& treeroot )
{GUCEF_TRACE;
return false;
}
/*-------------------------------------------------------------------------*/
bool
CMsmqPubSubClient::Disconnect( void )
{GUCEF_TRACE;
return true;
}
/*-------------------------------------------------------------------------*/
bool
CMsmqPubSubClient::Connect( void )
{GUCEF_TRACE;
return true;
}
/*-------------------------------------------------------------------------*/
bool
CMsmqPubSubClient::IsConnected( void )
{GUCEF_TRACE;
return true;
}
/*-------------------------------------------------------------------------*/
void
CMsmqPubSubClient::RegisterEventHandlers( void )
{GUCEF_TRACE;
if ( GUCEF_NULL != m_metricsTimer )
{
TEventCallback callback( this, &CMsmqPubSubClient::OnMetricsTimerCycle );
SubscribeTo( m_metricsTimer ,
CORE::CTimer::TimerUpdateEvent ,
callback );
}
}
/*-------------------------------------------------------------------------*/
void
CMsmqPubSubClient::OnMetricsTimerCycle( CORE::CNotifier* notifier ,
const CORE::CEvent& eventId ,
CORE::CICloneable* eventData )
{GUCEF_TRACE;
TTopicMap::iterator i = m_topicMap.begin();
while ( i != m_topicMap.end() )
{
(*i).second->OnMetricsTimerCycle( notifier ,
eventId ,
eventData );
++i;
}
}
/*-------------------------------------------------------------------------//
// //
// NAMESPACE //
// //
//-------------------------------------------------------------------------*/
}; /* namespace MSMQ */
}; /* namespace PUBSUBPLUGIN */
}; /* namespace GUCEF */
/*--------------------------------------------------------------------------*/
|
NullableInt/design.swedbankpay.com
|
src/App/utils/RenderRoutes/index.js
|
import React from "react";
import PropTypes from "prop-types";
import { Switch, Route, Redirect } from "react-router-dom";
const RenderRoutes = ({ path, redirect, routes, appFolder }) => (
<Switch>
<Route exact path={path} render={() => <Redirect to={redirect} />}/>
{routes.map(route => {
const { path, componentPath } = route;
const RouteRenderComponent = React.lazy(() => import(/* webpackChunkName: "doc-route.chunk_" */ `../../${appFolder}/${componentPath}/index.js`));
return <Route key={`doc_route_${path}`} exact path={path} render={() => <RouteRenderComponent />} />;
})}
<Redirect from={`${path}/*`} to="/404" />
</Switch>
);
RenderRoutes.propTypes = {
path: PropTypes.string.isRequired,
redirect: PropTypes.string.isRequired,
routes: PropTypes.array.isRequired,
appFolder: PropTypes.string.isRequired
};
export default RenderRoutes;
|
GabrielSturtevant/mage
|
Mage.Sets/src/mage/cards/t/TelJiladJustice.java
|
<reponame>GabrielSturtevant/mage
package mage.cards.t;
import java.util.UUID;
import mage.abilities.effects.common.DestroyTargetEffect;
import mage.abilities.effects.keyword.ScryEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.target.common.TargetArtifactPermanent;
/**
*
* @author Plopman
*/
public final class TelJiladJustice extends CardImpl {
public TelJiladJustice(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{1}{G}");
// Destroy target artifact.
this.getSpellAbility().addEffect(new DestroyTargetEffect());
this.getSpellAbility().addTarget(new TargetArtifactPermanent());
// Scry 2.
this.getSpellAbility().addEffect(new ScryEffect(2));
}
private TelJiladJustice(final TelJiladJustice card) {
super(card);
}
@Override
public TelJiladJustice copy() {
return new TelJiladJustice(this);
}
}
|
deduper/raml-java-tools
|
raml-to-pojo/src/test/java/org/raml/ramltopojo/plugin/PluginTwo.java
|
package org.raml.ramltopojo.plugin;
/**
* Created. There, you have it.
*/
public class PluginTwo {
}
|
evgeniums/cpp-validator
|
include/dracosha/validator/utils/make_types_tuple.hpp
|
/**
@copyright <NAME> 2020
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
/****************************************************************************/
/** @file validator/utils/make_types_tuple.hpp
*
* Defines helper to create a tuple of types from variadic arguments.
*
*/
/****************************************************************************/
#ifndef DRACOSHA_VALIDATOR_MAKE_TYPES_TUPLE_HPP
#define DRACOSHA_VALIDATOR_MAKE_TYPES_TUPLE_HPP
#include <dracosha/validator/config.hpp>
DRACOSHA_VALIDATOR_NAMESPACE_BEGIN
//-------------------------------------------------------------
/**
@brief Make tuple of hana::type_c<> from variadic arguments.
*/
template <typename ...Args>
constexpr auto make_types_tuple(Args&&...)
{
return hana::tuple_t<std::decay_t<Args>...>;
}
//-------------------------------------------------------------
DRACOSHA_VALIDATOR_NAMESPACE_END
#endif // DRACOSHA_VALIDATOR_MAKE_TYPES_TUPLE_HPP
|
lkwr/react-bootstrap-icons
|
src/icons/cloudy.js
|
<gh_stars>100-1000
import React, { forwardRef } from 'react';
import PropTypes from 'prop-types';
const Cloudy = forwardRef(({ color, size, ...rest }, ref) => {
return (
<svg
ref={ref}
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 16 16"
width={size}
height={size}
fill={color}
{...rest}
>
<path d="M13.405 8.527a5.001 5.001 0 0 0-9.499-1.004A3.5 3.5 0 1 0 3.5 14.5H13a3 3 0 0 0 .405-5.973zM8.5 5.5a4 4 0 0 1 3.976 3.555.5.5 0 0 0 .5.445H13a2 2 0 0 1-.001 4H3.5a2.5 2.5 0 1 1 .605-4.926.5.5 0 0 0 .596-.329A4.002 4.002 0 0 1 8.5 5.5z" />
</svg>
);
});
Cloudy.propTypes = {
color: PropTypes.string,
size: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
};
Cloudy.defaultProps = {
color: 'currentColor',
size: '1em',
};
export default Cloudy;
|
raymondlu/EffectNodes-for-cocos2dx
|
effectNodes/tinyWingsTerrain/ensTinyWingsTerrainNode.h
|
//
// ensTinyWingsTerrainSprite.h
// HelloCpp
//
// Created by <NAME> (wantnon) on 13-12-16.
//
//
#ifndef __HelloCpp__ensTinyWingsTerrainNode__
#define __HelloCpp__ensTinyWingsTerrainNode__
#include <iostream>
#include <vector>
using namespace std;
#include "cocos2d.h"
using namespace cocos2d;
#include "common/ensCommon.h"
namespace_ens_begin
//ref to: http://www.cnblogs.com/andyque/archive/2011/07/01/2095479.html
//and https://github.com/diwu/Tiny-Wings-Remake-on-Android
class CtinyWingsTerrainSprite:public CCSprite{
public:
CtinyWingsTerrainSprite(){
m_dx=10;
m_mesh=NULL;
m_indexVBO=NULL;
m_isDrawDebug=false;
m_texture=NULL;
m_program=NULL;
m_texNonlinearFactor=0.7;
m_ribbonRotation=75.0;
m_ribbonRepeat=7.5;
m_width=0;
m_height=0;
m_nRow=4;
m_insertControlPointCount=4;
}
virtual~CtinyWingsTerrainSprite(){
if(m_mesh)m_mesh->release();
if(m_indexVBO)m_indexVBO->release();
if(m_texture)m_texture->release();
if(m_program)m_program->release();
}
void init(float width,float height,int insertControlPointCount);
void draw();
void drawWire();
void reGenerateShape(int insertControlPointCount);
void reGenerateColors();
bool getIsDrawDebug()const {return m_isDrawDebug;}
void setIsDrawDebug(bool value){m_isDrawDebug=value;}
void setTexNonlinearFactor(float value){m_texNonlinearFactor=value;}
float getTexNonlinearFactor()const{return m_texNonlinearFactor;}
void setRibbonRotation(float value){m_ribbonRotation=value;}
float getRibbonRotation()const{return m_ribbonRotation;}
void setRibbonRepeat(float value){m_ribbonRepeat=value;}
float getRibbonRepeat()const{return m_ribbonRepeat;}
float getWidth()const{return m_width;}
float getHeight()const{return m_height;}
int getInsertControlPointCount()const{return m_insertControlPointCount;}
protected:
void submit();
void updateMesh();
protected:
CCTexture2D*m_texture;
vector<vector<CCPoint> > m_pointMat;//in local space
float m_dx;
int m_nRow;//must >=2
Cmesh*m_mesh;
CindexVBO*m_indexVBO;
bool m_isDrawDebug;
CGLProgramWithUnifos*m_program;
float m_texNonlinearFactor;
vector<ccColor4F> m_colorList;
float m_ribbonRotation;
float m_ribbonRepeat;
float m_width;
float m_height;
int m_insertControlPointCount;
};
namespace_ens_end
#endif /* defined(__HelloCpp__ensTinyWingsTerrainNode__) */
|
lin10086/easy_oa
|
src/main/java/cn/gson/oasys/mappers/TaskLoggerPOMapper.java
|
package cn.gson.oasys.mappers;
import cn.gson.oasys.modelV2.po.TaskLoggerPO;
import cn.gson.oasys.modelV2.po.TaskLoggerPOExample;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectKey;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.UpdateProvider;
import org.apache.ibatis.type.JdbcType;
public interface TaskLoggerPOMapper {
@SelectProvider(type=TaskLoggerPOSqlProvider.class, method="countByExample")
long countByExample(TaskLoggerPOExample example);
@DeleteProvider(type=TaskLoggerPOSqlProvider.class, method="deleteByExample")
int deleteByExample(TaskLoggerPOExample example);
@Delete({
"delete from aoa_task_logger",
"where logger_id = #{loggerId,jdbcType=BIGINT}"
})
int deleteByPrimaryKey(Long loggerId);
@Insert({
"insert into aoa_task_logger (create_time, logger_ticking, ",
"task_id, username, ",
"logger_statusid)",
"values (#{createTime,jdbcType=TIMESTAMP}, #{loggerTicking,jdbcType=VARCHAR}, ",
"#{taskId,jdbcType=BIGINT}, #{username,jdbcType=VARCHAR}, ",
"#{loggerStatusid,jdbcType=INTEGER})"
})
@SelectKey(statement="SELECT LAST_INSERT_ID()", keyProperty="loggerId", before=false, resultType=Long.class)
int insert(TaskLoggerPO record);
@InsertProvider(type=TaskLoggerPOSqlProvider.class, method="insertSelective")
@SelectKey(statement="SELECT LAST_INSERT_ID()", keyProperty="loggerId", before=false, resultType=Long.class)
int insertSelective(TaskLoggerPO record);
@SelectProvider(type=TaskLoggerPOSqlProvider.class, method="selectByExample")
@Results({
@Result(column="logger_id", property="loggerId", jdbcType=JdbcType.BIGINT, id=true),
@Result(column="create_time", property="createTime", jdbcType=JdbcType.TIMESTAMP),
@Result(column="logger_ticking", property="loggerTicking", jdbcType=JdbcType.VARCHAR),
@Result(column="task_id", property="taskId", jdbcType=JdbcType.BIGINT),
@Result(column="username", property="username", jdbcType=JdbcType.VARCHAR),
@Result(column="logger_statusid", property="loggerStatusid", jdbcType=JdbcType.INTEGER)
})
List<TaskLoggerPO> selectByExample(TaskLoggerPOExample example);
@Select({
"select",
"logger_id, create_time, logger_ticking, task_id, username, logger_statusid",
"from aoa_task_logger",
"where logger_id = #{loggerId,jdbcType=BIGINT}"
})
@Results({
@Result(column="logger_id", property="loggerId", jdbcType=JdbcType.BIGINT, id=true),
@Result(column="create_time", property="createTime", jdbcType=JdbcType.TIMESTAMP),
@Result(column="logger_ticking", property="loggerTicking", jdbcType=JdbcType.VARCHAR),
@Result(column="task_id", property="taskId", jdbcType=JdbcType.BIGINT),
@Result(column="username", property="username", jdbcType=JdbcType.VARCHAR),
@Result(column="logger_statusid", property="loggerStatusid", jdbcType=JdbcType.INTEGER)
})
TaskLoggerPO selectByPrimaryKey(Long loggerId);
@UpdateProvider(type=TaskLoggerPOSqlProvider.class, method="updateByExampleSelective")
int updateByExampleSelective(@Param("record") TaskLoggerPO record, @Param("example") TaskLoggerPOExample example);
@UpdateProvider(type=TaskLoggerPOSqlProvider.class, method="updateByExample")
int updateByExample(@Param("record") TaskLoggerPO record, @Param("example") TaskLoggerPOExample example);
@UpdateProvider(type=TaskLoggerPOSqlProvider.class, method="updateByPrimaryKeySelective")
int updateByPrimaryKeySelective(TaskLoggerPO record);
@Update({
"update aoa_task_logger",
"set create_time = #{createTime,jdbcType=TIMESTAMP},",
"logger_ticking = #{loggerTicking,jdbcType=VARCHAR},",
"task_id = #{taskId,jdbcType=BIGINT},",
"username = #{username,jdbcType=VARCHAR},",
"logger_statusid = #{loggerStatusid,jdbcType=INTEGER}",
"where logger_id = #{loggerId,jdbcType=BIGINT}"
})
int updateByPrimaryKey(TaskLoggerPO record);
}
|
ZhiQiAnSecFork/ssf
|
src/network/ssf/layer/proxy/negotiate_auth_strategy.h
|
<gh_stars>1000+
#ifndef SSF_LAYER_PROXY_NEGOTIATE_AUTH_STRATEGY_H_
#define SSF_LAYER_PROXY_NEGOTIATE_AUTH_STRATEGY_H_
#include <memory>
#include <vector>
#include "ssf/layer/proxy/auth_strategy.h"
#include "ssf/layer/proxy/platform_auth_impl.h"
namespace ssf {
namespace layer {
namespace proxy {
class NegotiateAuthStrategy : public AuthStrategy {
public:
NegotiateAuthStrategy(const HttpProxy& proxy_ctx);
virtual ~NegotiateAuthStrategy(){};
std::string AuthName() const override;
bool Support(const HttpResponse& response) const override;
void ProcessResponse(const HttpResponse& response) override;
void PopulateRequest(HttpRequest* p_request) override;
private:
std::unique_ptr<PlatformAuthImpl> p_impl_;
};
} // proxy
} // layer
} // ssf
#endif // SSF_LAYER_PROXY_NEGOTIATE_AUTH_STRATEGY_H_
|
Shashi-rk/azure-sdk-for-java
|
sdk/digitaltwins/azure-resourcemanager-digitaltwins/src/test/java/com/azure/resourcemanager/digitaltwins/DigitalTwinsLifecycleTests.java
|
<filename>sdk/digitaltwins/azure-resourcemanager-digitaltwins/src/test/java/com/azure/resourcemanager/digitaltwins/DigitalTwinsLifecycleTests.java
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.resourcemanager.digitaltwins;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.management.AzureEnvironment;
import com.azure.core.management.Region;
import com.azure.core.management.profile.AzureProfile;
import com.azure.core.test.TestBase;
import com.azure.core.test.annotation.DoNotRecord;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.resourcemanager.digitaltwins.models.CheckNameRequest;
import com.azure.resourcemanager.digitaltwins.models.CheckNameResult;
import com.azure.resourcemanager.digitaltwins.models.DigitalTwinsDescription;
import com.azure.resourcemanager.digitaltwins.models.Operation;
import com.azure.resourcemanager.resources.ResourceManager;
import com.azure.resourcemanager.resources.models.ResourceGroup;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class DigitalTwinsLifecycleTests extends TestBase {
private static final String DEFAULT_INSTANCE_NAME = "DigitalTwinsSdk";
private static final Region DEFAULT_REGION = Region.US_WEST_CENTRAL;
private static final String DEFAULT_RESOURCE_GROUP_NAME = "rg2b9842374ecf8";
@Test
@DoNotRecord(skipInPlayback = true)
public void lifecycleTest() {
String rgName = DEFAULT_RESOURCE_GROUP_NAME;
ResourceManager resourceManager = ResourceManager
.authenticate(new DefaultAzureCredentialBuilder().build(), new AzureProfile(AzureEnvironment.AZURE))
.withDefaultSubscription();
AzureDigitalTwinsManager digitalTwinsManager = AzureDigitalTwinsManager
.authenticate(new DefaultAzureCredentialBuilder().build(), new AzureProfile(AzureEnvironment.AZURE));
ResourceGroup group = resourceManager.resourceGroups()
.define(rgName)
.withRegion(DEFAULT_REGION)
.create();
Assertions.assertNotNull(group);
try {
CheckNameResult checkNameResult = digitalTwinsManager.digitalTwins()
.checkNameAvailability(DEFAULT_REGION.toString(), new CheckNameRequest().withName(DEFAULT_INSTANCE_NAME));
if (!checkNameResult.nameAvailable()) {
PagedIterable<DigitalTwinsDescription> allDigitalTwins = digitalTwinsManager
.digitalTwins().list();
for (DigitalTwinsDescription digitalTwin : allDigitalTwins) {
if (digitalTwin.name().equals(DEFAULT_INSTANCE_NAME)) {
digitalTwinsManager.digitalTwins().deleteById(digitalTwin.id());
break;
}
}
checkNameResult = digitalTwinsManager.digitalTwins()
.checkNameAvailability(rgName, new CheckNameRequest().withName(DEFAULT_INSTANCE_NAME));
Assertions.assertTrue(checkNameResult.nameAvailable());
}
// Create DigitalTwins resource
DigitalTwinsDescription instance = digitalTwinsManager
.digitalTwins()
.define(DEFAULT_INSTANCE_NAME)
.withRegion(DEFAULT_REGION)
.withExistingResourceGroup(rgName)
.create();
Assertions.assertNotNull(instance);
Assertions.assertEquals(DEFAULT_INSTANCE_NAME, instance.name());
Assertions.assertEquals(DEFAULT_REGION, instance.region());
// Add and get tags
final String key1 = "Key1";
final String value1 = "Value1";
final String key2 = "Key2";
final String value2 = "Value2";
Map<String, String> tags = new HashMap<>();
tags.put(key1, value1);
tags.put(key2, value2);
instance = instance.update()
.withTags(tags)
.apply();
Assertions.assertEquals(value1, instance.tags().get(key1));
Assertions.assertEquals(value2, instance.tags().get(key2));
List<DigitalTwinsDescription> list = digitalTwinsManager.digitalTwins()
.listByResourceGroup(rgName)
.stream().collect(Collectors.toList());
Assertions.assertTrue(list.size() > 0);
List<String> myOpNames = digitalTwinsManager.operations().list()
.stream().map(Operation::name)
.collect(Collectors.toList());
Assertions.assertTrue(myOpNames.contains("Microsoft.DigitalTwins/digitalTwinsInstances/read"));
Assertions.assertTrue(myOpNames.contains("Microsoft.DigitalTwins/digitalTwinsInstances/write"));
Assertions.assertTrue(myOpNames.contains("Microsoft.DigitalTwins/digitalTwinsInstances/delete"));
Assertions.assertTrue(myOpNames.contains("Microsoft.DigitalTwins/eventroutes/read"));
Assertions.assertTrue(myOpNames.contains("Microsoft.DigitalTwins/digitaltwins/read"));
Assertions.assertTrue(myOpNames.contains("Microsoft.DigitalTwins/models/read"));
} finally {
resourceManager.resourceGroups().beginDeleteByName(rgName);
}
}
}
|
dogchenya/xc-ros
|
src/xcroscpp/include/ros/internal_timer_manager.h
|
<reponame>dogchenya/xc-ros<gh_stars>0
#ifndef _XCROSCPP_INTERNAL_TIMER_MANAGER_H_
#define _XCROSCPP_INTERNAL_TIMER_MANAGER_H_
#include "ros/forwards.h"
#include <ros/time.h>
#include "ros/xcroscpp_common.h"
namespace xcros
{
template<typename T, typename D, typename E> class TimerManager;
typedef TimerManager<SteadyTime, WallDuration, SteadyTimerEvent> InternalTimerManager;
typedef boost::shared_ptr<InternalTimerManager> InternalTimerManagerPtr;
ROSCPP_DECL void initInternalTimerManager();
ROSCPP_DECL InternalTimerManagerPtr getInternalTimerManager();
} // namespace xcros
#endif // _XCROSCPP_INTERNAL_TIMER_MANAGER_H
|
airslie/renalware-core
|
spec/dummy/db/seeds/surveys/seeds.rb
|
# frozen_string_literal: true
require_relative "./surveys"
|
Ahmad-Milan/gatsby-milan
|
src/components/templates/store-layout/InteriorPhotos.js
|
import React from 'react'
function InteriorPhotos({store, imgPath, defaultImages}) {
return (
<div className="w-100 d-flex justify-content-center flex-wrap mb-n3">
<div className="col-sm-6 col-lg-3 p-1">
<img
src={ store.proPhotos ? `${imgPath}FrontDesk.jpg` : defaultImages.frontdesk }
alt={`Milan Laser ${store.location} Front Desk`} className="img-fluid" />
</div>
<div className="col-sm-6 col-lg-3 p-1">
<img
src={ store.proPhotos ? `${imgPath}Lobby.jpg` : defaultImages.lobby }
alt={`Milan Laser ${store.location} Lobby`}className="img-fluid" />
</div>
<div className="col-sm-6 col-lg-3 p-1">
<img
src={ store.proPhotos ? `${imgPath}ConsultationRoom.jpg` : defaultImages.consultroom }
alt={`Milan Laser ${store.location} Consultation Room`} className="img-fluid" />
</div>
<div className="col-sm-6 col-lg-3 p-1">
<img
src={ store.proPhotos ? `${imgPath}TXRoom.jpg` : defaultImages.txroom }
alt={`Milan Laser ${store.location} Treatment Room`} className="img-fluid" />
</div>
</div>
)
}
export default InteriorPhotos
|
broadinstitute/tissue_purifier
|
tests/model_utils/test_benckmark_mixin.py
|
import pytest
import torch
import numpy
import pandas
from tissue_purifier.model_utils.benckmark_mixin import classify_and_regress
from sklearn.neighbors import KNeighborsRegressor, KNeighborsClassifier
@pytest.mark.parametrize("n_splits, n_repeats", [(1, 1), (2, 1), (2, 2)])
def test_classify_regress_knn(n_splits, n_repeats, capsys):
""" Test that knn classifier regressor works """
n, p = 23, 12
my_dict = {
"feature_a": torch.randn((n, p)),
"feature_b": torch.randn((n, 2*p)),
"label_a": torch.randint(low=0, high=5, size=[n]),
"label_b": ["wt" if i < 0.5*n else "dis" for i in range(n)],
"label_c": torch.zeros(n),
"regress_a": torch.randn(n),
"regress_b": numpy.random.randn(n)
}
feature_keys, classify_keys, regress_keys = [], [], []
for k in my_dict.keys():
if k.startswith("feature"):
feature_keys.append(k)
elif k.startswith("label"):
classify_keys.append(k)
elif k.startswith("regress"):
regress_keys.append(k)
def exclude_self(d):
w = numpy.ones_like(d)
w[:, 0] = 0.0
return w
kn_kargs = {
"n_neighbors": 5,
"weights": exclude_self,
}
df_tot = classify_and_regress(
input_dict=my_dict,
feature_keys=feature_keys,
regress_keys=regress_keys,
classify_keys=classify_keys,
regressor=KNeighborsRegressor(**kn_kargs),
classifier=KNeighborsClassifier(**kn_kargs),
n_splits=n_splits,
n_repeats=n_repeats)
df_tot["combined_key"] = df_tot["x_key"] + "_" + df_tot["y_key"]
assert isinstance(df_tot, pandas.DataFrame)
assert df_tot.shape[0] == n_repeats * n_splits * len(feature_keys) * (len(regress_keys) + len(classify_keys))
# with capsys.disabled():
# # inside this context the stdout will not be captured
# print(n_repeats, n_splits)
# df_mean = df_tot.groupby("combined_key").mean()
# for row in df_mean.itertuples():
# for k, v in row._asdict().items():
# if isinstance(v, float) and numpy.isfinite(v):
# name = "kn/" + row.Index + "/" + k + "/mean"
# print(name, v)
#
# df_std = df_tot.groupby("combined_key").std()
# for row in df_std.itertuples():
# for k, v in row._asdict().items():
# if isinstance(v, float) and numpy.isfinite(v):
# name = "kn/" + row.Index + "/" + k + "/std"
# print(name, v)
|
vanacekj/midpoint
|
model/notifications-impl/src/test/java/com/evolveum/midpoint/notifications/impl/TestTextFormatter.java
|
<filename>model/notifications-impl/src/test/java/com/evolveum/midpoint/notifications/impl/TestTextFormatter.java
/**
* Copyright (c) 2010-2017 Evolveum
*
* 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.evolveum.midpoint.notifications.impl;
import com.evolveum.midpoint.notifications.impl.formatters.TextFormatter;
import com.evolveum.midpoint.prism.PrismContext;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.util.PrismTestUtil;
import com.evolveum.midpoint.schema.DeltaConvertor;
import com.evolveum.midpoint.schema.MidPointPrismContextFactory;
import com.evolveum.midpoint.schema.constants.MidPointConstants;
import com.evolveum.midpoint.util.PrettyPrinter;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectModificationType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import org.xml.sax.SAXException;
import javax.xml.bind.JAXBException;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
/**
* @author mederly
*/
@ContextConfiguration(locations = {"classpath:ctx-task.xml",
"classpath:ctx-repo-cache.xml",
"classpath:ctx-provisioning.xml",
"classpath*:ctx-repository-test.xml",
"classpath:ctx-configuration-test.xml",
"classpath:ctx-common.xml",
"classpath:ctx-repo-common.xml",
"classpath:ctx-security.xml",
"classpath:ctx-security-enforcer.xml",
"classpath:ctx-audit.xml",
"classpath:ctx-model.xml",
"classpath:ctx-model-common.xml",
"classpath:ctx-notifications-test.xml",
"classpath*:ctx-notifications.xml"})
public class TestTextFormatter extends AbstractTestNGSpringContextTests {
public static final String OBJECTS_DIR_NAME = "src/test/resources/objects";
public static final String USER_JACK_FILE = OBJECTS_DIR_NAME + "/user-jack.xml";
public static final String ACCOUNT_JACK_FILE = OBJECTS_DIR_NAME + "/account-jack.xml";
public static final String CHANGES_DIR_NAME = "src/test/resources/changes";
public static final String USER_JACK_MODIFICATION_FILE = CHANGES_DIR_NAME + "/user-jack-modification.xml";
protected static final List<ItemPath> auxiliaryPaths = Arrays.asList(
UserType.F_FAMILY_NAME, // for testing purposes
ShadowType.F_METADATA,
ItemPath.create(ShadowType.F_ACTIVATION, ActivationType.F_VALIDITY_STATUS),
ItemPath.create(ShadowType.F_ACTIVATION, ActivationType.F_VALIDITY_CHANGE_TIMESTAMP),
ItemPath.create(ShadowType.F_ACTIVATION, ActivationType.F_EFFECTIVE_STATUS),
ItemPath.create(ShadowType.F_ACTIVATION, ActivationType.F_DISABLE_TIMESTAMP),
ItemPath.create(ShadowType.F_ACTIVATION, ActivationType.F_ARCHIVE_TIMESTAMP),
ItemPath.create(ShadowType.F_ACTIVATION, ActivationType.F_ENABLE_TIMESTAMP),
ShadowType.F_ITERATION,
ShadowType.F_ITERATION_TOKEN,
UserType.F_LINK_REF,
ShadowType.F_TRIGGER
);
private static final List<ItemPath> synchronizationPaths = Arrays.asList(
ShadowType.F_SYNCHRONIZATION_SITUATION,
ShadowType.F_SYNCHRONIZATION_SITUATION_DESCRIPTION,
ShadowType.F_SYNCHRONIZATION_TIMESTAMP,
ShadowType.F_FULL_SYNCHRONIZATION_TIMESTAMP);
@Autowired
private TextFormatter textFormatter;
@Autowired
private PrismContext prismContext;
static {
// We set the locale to US to avoid translation of item names.
// It is crucial that this method is called before TextFormatter class is loaded.
// Currently this solution suffices but it is quite fragile. If something would change
// in this respect and breaking it, a different mechanism to set correct locale would need to be used.
Locale.setDefault(Locale.US);
}
@BeforeSuite
public void setup() throws SchemaException, SAXException, IOException {
PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX);
PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY);
}
@Test
public void test010FormatUser() throws Exception {
// GIVEN
PrismObject<UserType> jack = PrismTestUtil.parseObject(new File(USER_JACK_FILE));
System.out.println(jack.debugDump());
// WHEN
String jackFormattedHideNone = textFormatter.formatObject(jack, null, true);
System.out.println("no hidden paths + show operational attributes: " + jackFormattedHideNone);
String jackFormattedHideOper = textFormatter.formatObject(jack, null, false);
System.out.println("no hidden paths + hide operational attributes: " + jackFormattedHideOper);
String jackFormattedHideAux = textFormatter.formatObject(jack, auxiliaryPaths, true);
System.out.println("hide auxiliary paths + show operational attributes: " + jackFormattedHideAux);
String jackFormattedHideAuxAndOper = textFormatter.formatObject(jack, auxiliaryPaths, false);
System.out.println("hide auxiliary paths + hide operational attributes: " + jackFormattedHideAuxAndOper);
// THEN
// if fails with hidden operational attribute when it should be shown ('hide none'), check the schema.properties
final String CREATE_TIMESTAMP = "Created at:";
final String EFFECTIVE_STATUS = "Effective status: ENABLED";
final String FAMILY_NAME = "Family name: Sparrow";
final String SHIP = "ship: Black Pearl";
assertTrue("hidden operational attribute when it should be shown ('hide none')", jackFormattedHideNone.contains(CREATE_TIMESTAMP));
assertTrue("hidden auxiliary attribute (effective status) when it should be shown ('hide none')", jackFormattedHideNone.contains(EFFECTIVE_STATUS));
assertTrue("hidden auxiliary attribute (family name) when it should be shown ('hide none')", jackFormattedHideNone.contains(FAMILY_NAME));
assertTrue("hidden standard attribute when it should be shown ('hide none')", jackFormattedHideNone.contains(SHIP));
assertTrue("shown operational attribute when it should be hidden ('hide oper')", !jackFormattedHideOper.contains(CREATE_TIMESTAMP));
assertTrue("shown operational attribute when it should be shown ('hide oper')", !jackFormattedHideOper.contains(EFFECTIVE_STATUS));
assertTrue("hidden auxiliary attribute (family name) when it should be shown ('hide oper')", jackFormattedHideOper.contains(FAMILY_NAME));
assertTrue("hidden standard attribute when it should be shown ('hide oper')", jackFormattedHideOper.contains(SHIP));
assertTrue("shown auxiliary attribute (metadata) when it should be hidden ('hide aux')", !jackFormattedHideAux.contains(CREATE_TIMESTAMP));
assertTrue("shown auxiliary attribute (family name) when it should be hidden ('hide aux')", !jackFormattedHideAux.contains(FAMILY_NAME));
assertTrue("shown auxiliary attribute (effective status) when it should be hidden ('hide aux')", !jackFormattedHideAux.contains(EFFECTIVE_STATUS));
assertTrue("hidden standard attribute when it should be shown ('hide aux')", jackFormattedHideAux.contains(SHIP));
assertTrue("shown operational attribute when it should be hidden ('hide aux and oper')", !jackFormattedHideAuxAndOper.contains(CREATE_TIMESTAMP));
assertTrue("shown auxiliary attribute (effective status) when it should be hidden ('hide aux and oper')", !jackFormattedHideAuxAndOper.contains(EFFECTIVE_STATUS));
assertTrue("shown auxiliary attribute (family name) when it should be hidden ('hide aux and oper')", !jackFormattedHideAuxAndOper.contains(FAMILY_NAME));
assertTrue("hidden standard attribute when it should be shown ('hide aux and oper')", jackFormattedHideAuxAndOper.contains(SHIP));
}
@Test
public void test020FormatUserModification() throws Exception {
// GIVEN
ObjectDelta<UserType> delta = parseDelta(USER_JACK_MODIFICATION_FILE);
PrismObject<UserType> jack = PrismTestUtil.parseObject(new File(USER_JACK_FILE));
System.out.println(delta.debugDump());
// WHEN
String deltaFormattedHideNone = textFormatter.formatObjectModificationDelta(delta, null, true, jack, null);
System.out.println("no hidden paths + show operational attributes: " + deltaFormattedHideNone);
String deltaFormattedHideOper = textFormatter.formatObjectModificationDelta(delta, null, false, jack, null);
System.out.println("no hidden paths + hide operational attributes: " + deltaFormattedHideOper);
String deltaFormattedHideAux = textFormatter.formatObjectModificationDelta(delta, auxiliaryPaths, true, jack, null);
System.out.println("hide auxiliary paths + show operational attributes: " + deltaFormattedHideAux);
String deltaFormattedHideAuxAndOper = textFormatter.formatObjectModificationDelta(delta, auxiliaryPaths, false, jack, null);
System.out.println("hide auxiliary paths + hide operational attributes: " + deltaFormattedHideAuxAndOper);
// THEN
checkNotes(deltaFormattedHideAux);
checkNotes(deltaFormattedHideAuxAndOper);
checkNotes(deltaFormattedHideNone);
checkNotes(deltaFormattedHideOper);
// if fails with hidden operational attribute when it should be shown ('hide none'), check the schema.properties
final String CREATE_TIMESTAMP = "Created at:";
assertTrue("hidden operational attribute when it should be shown ('hide none')", deltaFormattedHideNone.contains(CREATE_TIMESTAMP));
assertTrue("hidden auxiliary attribute (family name) when it should be shown ('hide none')", deltaFormattedHideNone.contains("SPARROW"));
assertTrue("hidden password change when it should be shown ('hide none')", deltaFormattedHideNone.contains("(protected string)"));
assertTrue("hidden standard attribute when it should be shown ('hide none')", deltaFormattedHideNone.contains("BLACK PEARL"));
assertTrue("shown operational attribute when it should be hidden ('hide oper')", !deltaFormattedHideOper.contains(CREATE_TIMESTAMP));
assertTrue("hidden auxiliary attribute (family name) when it should be shown ('hide oper')", deltaFormattedHideOper.contains("SPARROW"));
assertTrue("hidden password change when it should be shown ('hide oper')", deltaFormattedHideOper.contains("(protected string)"));
assertTrue("hidden standard attribute when it should be shown ('hide oper')", deltaFormattedHideOper.contains("BLACK PEARL"));
assertTrue("shown auxiliary attribute (metadata) when it should be hidden ('hide aux')", !deltaFormattedHideAux.contains(CREATE_TIMESTAMP));
assertTrue("shown auxiliary attribute (family name) when it should be hidden ('hide aux')", !deltaFormattedHideAux.contains("SPARROW"));
assertTrue("hidden standard attribute when it should be shown ('hide aux')", deltaFormattedHideAux.contains("BLACK PEARL"));
assertTrue("shown operational attribute when it should be hidden ('hide aux and oper')", !deltaFormattedHideAuxAndOper.contains(CREATE_TIMESTAMP));
assertTrue("shown auxiliary attribute (family name) when it should be hidden ('hide aux and oper')", !deltaFormattedHideAuxAndOper.contains("SPARROW"));
assertTrue("hidden standard attribute when it should be shown ('hide aux and oper')", deltaFormattedHideAuxAndOper.contains("BLACK PEARL"));
}
private void checkNotes(String notification) {
String NOTES_DELIMITER = "Notes:";
int i = notification.indexOf(NOTES_DELIMITER);
if (i == -1) {
throw new AssertionError("No Notes section in " + notification);
}
String notes = notification.substring(i);
assertFalse(notes.contains("Assignment #1"));
assertFalse(notes.contains("Assignment #2"));
assertFalse(notes.contains("Assignment #3"));
assertTrue(notes.contains("Assignment[1]"));
assertTrue(notes.contains("Assignment[2]"));
assertFalse(notes.contains("Assignment[3]"));
}
@Test
public void test030FormatAccount() throws Exception {
// GIVEN
PrismObject<ShadowType> jack = PrismTestUtil.parseObject(new File(ACCOUNT_JACK_FILE));
System.out.println(jack.debugDump());
// WHEN
String jackFormattedHideNone = textFormatter.formatAccountAttributes(jack.asObjectable(), null, true);
System.out.println("no hidden paths + show operational attributes: " + jackFormattedHideNone);
String jackFormattedHideAux = textFormatter.formatAccountAttributes(jack.asObjectable(), auxiliaryPaths, true);
System.out.println("hide auxiliary paths + show operational attributes: " + jackFormattedHideAux);
// THEN
final String NAME = "Name: jack";
final String PASSWORD = "(<PASSWORD>)";
final String ADMINISTRATIVE_STATUS = "Administrative status: ENABLED";
final String EFFECTIVE_STATUS = "Effective status: ENABLED";
assertTrue("account name is not shown", jackFormattedHideNone.contains(NAME));
assertTrue("account password is not shown", jackFormattedHideNone.contains(PASSWORD));
assertTrue("administrative status is not shown", jackFormattedHideNone.contains(ADMINISTRATIVE_STATUS));
assertTrue("effective status is not shown", jackFormattedHideNone.contains(EFFECTIVE_STATUS));
assertTrue("account name is not shown", jackFormattedHideAux.contains(NAME));
assertTrue("account password is not shown", jackFormattedHideAux.contains(PASSWORD));
assertTrue("administrative status is not shown", jackFormattedHideAux.contains(ADMINISTRATIVE_STATUS));
assertTrue("effective status is shown although it should be hidden", !jackFormattedHideAux.contains(EFFECTIVE_STATUS));
// AssertJUnit.assertTrue("hidden operational attribute when it should be shown ('hide none')", jackFormattedHideNone.contains("createTimestamp:"));
// AssertJUnit.assertTrue("hidden auxiliary attribute (effective status) when it should be shown ('hide none')", jackFormattedHideNone.contains("Effective Status: ENABLED"));
// AssertJUnit.assertTrue("hidden auxiliary attribute (family name) when it should be shown ('hide none')", jackFormattedHideNone.contains("Family Name: Sparrow"));
// AssertJUnit.assertTrue("hidden standard attribute when it should be shown ('hide none')", jackFormattedHideNone.contains("ship: Black Pearl"));
//
// AssertJUnit.assertTrue("shown operational attribute when it should be hidden ('hide oper')", !jackFormattedHideOper.contains("createTimestamp:"));
// AssertJUnit.assertTrue("hidden auxiliary attribute when it should be shown ('hide oper')", jackFormattedHideOper.contains("Effective Status: ENABLED"));
// AssertJUnit.assertTrue("hidden auxiliary attribute (family name) when it should be shown ('hide oper')", jackFormattedHideOper.contains("Family Name: Sparrow"));
// AssertJUnit.assertTrue("hidden standard attribute when it should be shown ('hide oper')", jackFormattedHideOper.contains("ship: Black Pearl"));
//
// AssertJUnit.assertTrue("shown auxiliary attribute (metadata) when it should be hidden ('hide aux')", !jackFormattedHideAux.contains("createTimestamp:"));
// AssertJUnit.assertTrue("shown auxiliary attribute (family name) when it should be hidden ('hide aux')", !jackFormattedHideAux.contains("Family Name: Sparrow"));
// AssertJUnit.assertTrue("shown auxiliary attribute (effective status) when it should be hidden ('hide aux')", !jackFormattedHideAux.contains("Effective Status: ENABLED"));
// AssertJUnit.assertTrue("hidden standard attribute when it should be shown ('hide aux')", jackFormattedHideAux.contains("ship: Black Pearl"));
//
// AssertJUnit.assertTrue("shown operational attribute when it should be hidden ('hide aux and oper')", !jackFormattedHideAuxAndOper.contains("createTimestamp:"));
// AssertJUnit.assertTrue("shown auxiliary attribute (effective status) when it should be hidden ('hide aux and oper')", !jackFormattedHideAuxAndOper.contains("Effective Status: ENABLED"));
// AssertJUnit.assertTrue("shown auxiliary attribute (family name) when it should be hidden ('hide aux and oper')", !jackFormattedHideAuxAndOper.contains("Family Name: Sparrow"));
// AssertJUnit.assertTrue("hidden standard attribute when it should be shown ('hide aux and oper')", jackFormattedHideAuxAndOper.contains("ship: Black Pearl"));
}
private ObjectDelta<UserType> parseDelta(String filename) throws JAXBException, SchemaException, IOException {
ObjectModificationType modElement = PrismTestUtil.parseAtomicValue(new File(filename), ObjectModificationType.COMPLEX_TYPE);
return DeltaConvertor.createObjectDelta(modElement, UserType.class, prismContext);
}
}
|
pingidentity/browser-extensions
|
firefox/addon-sdk/test/test-require.js
|
<reponame>pingidentity/browser-extensions
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const traceback = require("sdk/console/traceback");
exports.test_no_args = function(test) {
var passed = false;
try {
var oops = require(); // leave this on line 6!
} catch(e) {
let msg = e.toString();
test.assertEqual(msg.indexOf("Error: you must provide a module name when calling require() from "), 0);
test.assertNotEqual(msg.indexOf("test-require"), -1, msg);
// we'd also like to assert that the right filename and linenumber is in
// the stack trace, but this currently doesn't work (see bugs 679591 and
// 551604)
if (0) {
let tb = traceback.fromException(e);
let lastFrame = tb[tb.length-1];
test.assertNotEqual(lastFrame.filename.indexOf("test-require.js"), -1,
lastFrame.filename);
test.assertEqual(lastFrame.lineNo, 6);
test.assertEqual(lastFrame.funcName, "??");
}
passed = true;
}
test.assert(passed, 'require() with no args should raise helpful error');
};
|
ankurshukla1993/IOT-test
|
coeey/android/arch/persistence/db/SimpleSQLiteQuery.java
|
<filename>coeey/android/arch/persistence/db/SimpleSQLiteQuery.java
package android.arch.persistence.db;
public class SimpleSQLiteQuery implements SupportSQLiteQuery {
private final Object[] mBindArgs;
private final String mQuery;
public SimpleSQLiteQuery(String query, Object[] bindArgs) {
this.mQuery = query;
this.mBindArgs = bindArgs;
}
public SimpleSQLiteQuery(String query) {
this(query, null);
}
public String getSql() {
return this.mQuery;
}
public void bindTo(SupportSQLiteProgram statement) {
bind(statement, this.mBindArgs);
}
public static void bind(SupportSQLiteProgram statement, Object[] bindArgs) {
if (bindArgs != null) {
int limit = bindArgs.length;
for (int i = 0; i < limit; i++) {
bind(statement, i + 1, bindArgs[i]);
}
}
}
private static void bind(SupportSQLiteProgram statement, int index, Object arg) {
if (arg == null) {
statement.bindNull(index);
} else if (arg instanceof byte[]) {
statement.bindBlob(index, (byte[]) arg);
} else if (arg instanceof Float) {
statement.bindDouble(index, (double) ((Float) arg).floatValue());
} else if (arg instanceof Double) {
statement.bindDouble(index, ((Double) arg).doubleValue());
} else if (arg instanceof Long) {
statement.bindLong(index, ((Long) arg).longValue());
} else if (arg instanceof Integer) {
statement.bindLong(index, (long) ((Integer) arg).intValue());
} else if (arg instanceof Short) {
statement.bindLong(index, (long) ((Short) arg).shortValue());
} else if (arg instanceof Byte) {
statement.bindLong(index, (long) ((Byte) arg).byteValue());
} else if (arg instanceof String) {
statement.bindString(index, (String) arg);
} else {
throw new IllegalArgumentException("Cannot bind " + arg + " at index " + index + " Supported types: null, byte[], float, double, long, int, short, byte," + " string");
}
}
}
|
zieemer/buttons
|
out/chrome/Default/Extensions/dbaonaocldpohelilahfhnkmjankmbcc/5.10.14_0/components/search/search.controller.js
|
'use strict';
export let SearchController = [
'$scope',
'$rootScope',
'$window',
'searchService',
'statService',
'utilsService',
(
$scope,
$rootScope,
$window,
searchService,
statService,
utilsService
) => {
/**
* Using this to prevent suggestions request after search was submitted
* @type {Boolean}
*/
let searchSubmitted = false;
let suggestionsUpdateForbidden = false;
const MIN_QUERY_LENGTH = 3;
$scope.closeThis = () => {
$scope.suggestions = [];
};
$scope.queryPlaceholder = '';
$scope.searchButtonTitle = chrome.i18n.getMessage('searchButton');
let SEARCH_ENGINE = '';
let SEARCH_ID;
function getSearchOptions () {
return searchService
.getSearch()
.then(search => {
suggestionsUpdateForbidden = false;
SEARCH_ENGINE = search.name;
SEARCH_ID = search.id;
$scope.searchLogo = search.image;
return search;
});
}
getSearchOptions();
$scope.focus = () => $rootScope.$broadcast('hideFormsAndPopups');
$scope.search = () => {
if (!$scope.query || !$scope.query.trim()) return false;
searchSubmitted = true;
if (!SEARCH_ENGINE) {
getSearchOptions()
.then(res => {
statService.send('searchSD', {SEARCH_ENGINE, searchId: SEARCH_ID, keyword: $scope.query});
});
} else {
// TODO: DRY
statService.send('searchSD', {SEARCH_ENGINE, searchId: SEARCH_ID, keyword: $scope.query});
}
searchService
.getSearchURL(encodeURIComponent($scope.query))
.then(res => {
if (!res) return;
$window.location.href = res;
})
.catch(err => console.error(err));
};
$scope.useSuggestion = suggestion => {
$scope.query = suggestion;
$scope.search();
};
$scope.selectSuggestion = suggestion => {
if (suggestion) {
suggestionsUpdateForbidden = true;
$scope.query = suggestion;
}
};
$scope.allowSuggests = () => {
suggestionsUpdateForbidden = false;
};
$scope.$watch('query', utilsService.debounce((newValue, oldValue) => {
if (searchSubmitted || suggestionsUpdateForbidden) return;
if (!newValue || newValue.length < MIN_QUERY_LENGTH || newValue === oldValue) {
$scope.suggestions = [];
return;
}
console.log('Request suggestions', newValue);
searchService
.suggest(newValue)
.then(res => {
if (res[0] === $scope.query) {
console.log('Got suggestions', res[1]);
$scope.suggestions = res[1];
} else {
console.log('Get outdated response');
}
}, err => console.error(err));
}, 300));
$scope.$on('hideFormsAndPopups', clearSuggestion);
$scope.$on('ESC', clearSuggestion);
$scope.$on('searchUpdate', getSearchOptions);
function clearSuggestion () {
$scope.suggestions = [];
suggestionsUpdateForbidden = false;
}
}];
|
iakobos/mocha
|
lib/mocha/module_method.rb
|
require 'mocha/class_method'
module Mocha
class ModuleMethod < ClassMethod
end
end
|
JavaSaBr/jmonkey-builder
|
src/main/java/com/ss/editor/part3d/editor/Editor3DPart.java
|
<reponame>JavaSaBr/jmonkey-builder
package com.ss.editor.part3d.editor;
import com.jme3.app.state.AppState;
/**
* The interface to implement a 3D part of editor.
*
* @author JavaSaBr
*/
public interface Editor3DPart extends AppState {
}
|
awong9/t5
|
app/src/main/java/com/csc413/team5/fud5/tests/SelectorDemoActivity.java
|
package com.csc413.team5.fud5.tests;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.TextView;
import com.csc413.team5.fud5.R;
import com.csc413.team5.fud5.utils.ServiceUtil;
import com.csc413.team5.restaurantapiwrapper.DistanceUnit;
import com.csc413.team5.restaurantapiwrapper.RestaurantApiClient;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class SelectorDemoActivity extends AppCompatActivity
implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
public static final String TAG = "SelectorDemo";
RatingBar starRating;
TextView txtDebug;
EditText editLocation, editSearchTerm, editMaxRadius;
Button btnFoodPlz;
protected String mAddressString;
protected GoogleApiClient mGoogleApiClient; // client for Google API requests
protected Location mLastLocation; // stores latitude, longitude of device's last known location
protected Address mLastLocationAddress; // representation of lat,long as address
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selector_demo);
editLocation = (EditText) findViewById(R.id.editTextRSDLocation);
editSearchTerm = (EditText) findViewById(R.id.editTextRSDSearchTerm);
editMaxRadius = (EditText) findViewById(R.id.editTextRSDMaxRadius);
starRating = (RatingBar) findViewById(R.id.ratingBarRSD);
btnFoodPlz = (Button) findViewById(R.id.buttonRSDFuzPlz);
btnFoodPlz.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onClickButtonFudPlz();
}
});
txtDebug = (TextView) findViewById(R.id.textViewRSDDebug);
buildGoogleApiClient();
mGoogleApiClient.connect();
}
/**
* Check if location services are active. If so, get the current location then call
* the RestaurantListTask background task to perform the Yelp API query.
*/
@Override
public void onConnected(Bundle bundle) {
if (!ServiceUtil.isLocationServicesOn(this)) {
txtDebug.setText("Location services are off");
} else {
// get approximate address from location
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
Geocoder geocoder;
List<Address> addresses = null;
geocoder = new Geocoder(this, Locale.getDefault());
try {
// the last parameter specifies max locations turn return; we just need 1
addresses = geocoder
.getFromLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addresses != null) {
mLastLocationAddress = addresses.get(0);
mAddressString = RestaurantApiClient.addressToString(mLastLocationAddress);
editLocation.setText(mAddressString);
} else {
txtDebug.setText("Network is unavailable");
}
}
}
/**
* Re-establish a connection with GoogleApiClient services if the connected is suspended.
*
* @param i
*/
@Override
public void onConnectionSuspended(int i) {
// The connection to Google Play services was lost for some reason. We call connect() to
// attempt to re-establish the connection.
Log.i(TAG, "Google Play services connection suspended. Reconnecting...");
mGoogleApiClient.connect();
}
/**
* See ConnectionResult documentation for possible error codes.
*
* @param connectionResult
*/
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "Google Play services connection failed: ConnectionResult.getErrorCode() = "
+ connectionResult.getErrorCode());
}
/*****************************
* Activity's helper methods *
*****************************/
/**
* Builds a GoogleApiClient, adds API LocationServices.
*/
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
public void onClickButtonFudPlz() {
String location = editLocation.getText().toString();
if (location.compareTo("") == 0) {
txtDebug.setText("Location field must be non-empty");
return;
}
String searchTerm = editSearchTerm.getText().toString();
if (searchTerm.compareTo("") == 0)
searchTerm = "food";
if (editMaxRadius.getText().toString().compareTo("") == 0) {
txtDebug.setText("Max Radius field must be non-empty");
return;
}
int maxRadius = (int) RestaurantApiClient
.convertDistanceUnits(Double.parseDouble(editMaxRadius.getText().toString()),
DistanceUnit.MILES, DistanceUnit.METERS);
if (maxRadius > 40000) {
txtDebug.setText("Max radius allowed is 24.85 miles");
return;
}
double minRating = starRating.getRating();
Intent intent = new Intent(this, SelectorDemoResultsActivity.class);
intent.putExtra("location", location);
intent.putExtra("searchTerm", searchTerm);
intent.putExtra("maxRadius", maxRadius);
intent.putExtra("minRating", minRating);
startActivity(intent);
}
}
|
Mcpg/cmike
|
kernel/src/ports/os_get_via_serial.c
|
#include <mikeos.h>
void _os_get_via_serial(int* ax, int* bx, int* cx, int* dx, int* si, int* di)
{
char result;
if (os_get_via_serial(&result))
{
*ax = ((*ax & 0xFF00) ^ 0x8000) | (result & 0xFF);
}
else
{
*ax = *ax | 0x8000;
}
}
int os_get_via_serial(char* byte)
{
int retval = 0;
asm("int $0x14" : "=a" (retval) : "a" (0x0200), "d" (0));
*byte = retval & 0xFF;
return (retval >> 8) & 0xFF;
}
|
kenneycode/fusion-java
|
libfusionjava/src/main/java/io/github/kenneycode/fusionjava/framebuffer/FrameBuffer.java
|
package io.github.kenneycode.fusionjava.framebuffer;
import io.github.kenneycode.fusionjava.util.GLUtil;
import io.github.kenneycode.fusionjava.common.Ref;
import static android.opengl.GLES20.GL_COLOR_ATTACHMENT0;
import static android.opengl.GLES20.GL_FRAMEBUFFER;
import static android.opengl.GLES20.GL_RGBA;
import static android.opengl.GLES20.GL_TEXTURE_2D;
import static android.opengl.GLES20.GL_UNSIGNED_BYTE;
import static android.opengl.GLES20.glBindFramebuffer;
import static android.opengl.GLES20.glBindTexture;
import static android.opengl.GLES20.glFramebufferTexture2D;
import static android.opengl.GLES20.glTexImage2D;
import static android.opengl.GLES20.glViewport;
/**
*
* Coded by kenney
*
* http://www.github.com/kenneycode/fusion-java
*
* FrameBuffer类,可以做为一帧渲染的输入/输出
*
*/
public class FrameBuffer extends Ref {
public int width = 0;
public int height = 0;
public int texture = 0;
public int frameBuffer = 0;
/**
*
* 绑定此FrameBuffer,绑定后将渲染到此FrameBuffer上
*
* @param width 宽度
* @param height 高度
*
*/
public void bind(int width, int height) {
bind(width, height, -1);
}
/**
*
* 绑定此FrameBuffer,绑定后将渲染到此FrameBuffer上
*
* @param width 宽度
* @param height 高度
* @param externalTexture 外部纹理,当指定外部纹理时,外部纹理会附着到此FrameBuffer上
*
*/
public void bind(int width, int height, int externalTexture) {
if (width != 0 && height != 0) {
if (externalTexture == 0) {
if (frameBuffer != 0) {
GLUtil.deleteFrameBuffer(frameBuffer);
}
if (texture != 0) {
GLUtil.deleteTexture(texture);
}
} else {
if (frameBuffer == 0) {
frameBuffer = GLUtil.createFrameBuffer();
}
if (externalTexture != -1 && externalTexture != texture) {
GLUtil.deleteTexture(texture);
texture = 0;
}
if (width != this.width || height != this.height || texture == 0) {
this.width = width;
this.height = height;
if (texture == 0) {
if (externalTexture > 0) {
texture = externalTexture;
} else {
texture = GLUtil.createTexture();
}
glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
texture, 0);
}
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, null);
glBindTexture(GL_TEXTURE_2D, 0);
}
}
}
glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);
glViewport(0, 0, width, height);
}
}
|
phatblat/macOSPrivateFrameworks
|
PrivateFrameworks/InputContext/_ICNullLexiconManager.h
|
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
#import "NSObject.h"
#import "_ICLexiconManaging.h"
@class NSMutableArray;
@interface _ICNullLexiconManager : NSObject <_ICLexiconManaging>
{
NSMutableArray *_contactObservers;
}
- (void).cxx_destruct;
- (void)hibernate;
- (void)warmUp;
- (void)unloadLexicons;
- (id)loadLexiconsUsingFilter:(CDUnknownBlockType)arg1;
- (id)loadLexicons:(CDUnknownBlockType)arg1;
- (void)removeContactObserver:(CDUnknownBlockType)arg1;
- (CDUnknownBlockType)addContactObserver:(CDUnknownBlockType)arg1;
- (id)init;
@end
|
fossabot/leetcode-3
|
problems/reshape-the-matrix/reshape_the_matrix.go
|
package reshape_the_matrix
func matrixReshape(nums [][]int, r int, c int) [][]int {
m, n := len(nums), len(nums[0])
if m*n != r*c {
return nums
}
ans := make([][]int, r)
for i := 0; i < r; i++ {
ans[i] = make([]int, c)
}
i, j := 0, 0
for _, row := range nums {
for _, v := range row {
ans[i][j] = v
if j++; j == c {
i++
j = 0
}
}
}
return ans
}
|
merceyz/babel-plugin-optimize-clsx
|
test/fixtures/find-function-names/no-import/output.js
|
clsx({
foo: true,
});
|
exKAZUu-Research/WillingQuiz
|
server/app/models/teacher.rb
|
<filename>server/app/models/teacher.rb
# == Schema Information
#
# Table name: teachers
#
# id :uuid not null, primary key
# name :string not null
# school_id :uuid not null
# created_at :datetime not null
# updated_at :datetime not null
#
class Teacher < ApplicationRecord
has_many :users, dependent: :nullify
validates_presence_of :name
end
|
andrewgross/moto
|
moto/emr/utils.py
|
import random
import string
def random_job_id(size=13):
chars = range(10) + list(string.uppercase)
job_tag = ''.join(unicode(random.choice(chars)) for x in range(size))
return 'j-{0}'.format(job_tag)
def random_instance_group_id(size=13):
chars = range(10) + list(string.uppercase)
job_tag = ''.join(unicode(random.choice(chars)) for x in range(size))
return 'i-{0}'.format(job_tag)
|
aksr/wmii
|
lib/libstuff/geom/rect_contains_p.c
|
<filename>lib/libstuff/geom/rect_contains_p.c
/* Copyright ©2006-2010 <NAME> <<EMAIL> at Gmail>
* See LICENSE file for license details.
*/
#include <stuff/geom.h>
bool
rect_contains_p(Rectangle r, Rectangle r2) {
return r2.min.x >= r.min.x
&& r2.max.x <= r.max.x
&& r2.min.y >= r.min.y
&& r2.max.y <= r.max.y;
}
|
ronakshah2895/Handshake-Lab1
|
backend/actions/jobs.js
|
const fs = require('fs');
const { v1: uuidv1 } = require('uuid');
const { literal } = require('sequelize');
const { User, Job, jobApplication } = require('../models/index');
function postJob(req, res) {
Job.create({
...req.body,
creatorId: req.user.id,
}).then((job) => {
const {
title, category, location, salary, deadline, createdAt, description,
} = job;
res.send({
title,
category,
location,
salary,
deadline,
createdAt,
description,
creator: { name: req.user.name, email: req.user.email },
});
});
}
function getJobs(req, res) {
let filterObj;
if (req.user.is_company) filterObj = { where: { creatorId: req.user.id } };
else filterObj = { where: literal('job_applications.id IS NULL') };
Job.findAll({
...filterObj,
attributes: ['id', 'title', 'category', 'location', 'salary', 'deadline', 'createdAt', 'description'],
include: [{
model: User,
as: 'creator',
attributes: ['name', 'email'],
}, {
model: jobApplication,
where: {
applicantId: req.user.id,
},
attributes: [],
required: false,
}],
order: [['deadline', 'DESC']],
}).then((jobs) => {
res.send(jobs);
});
}
function applyJob(req, res) {
const resume = req.files[0];
if (!fs.existsSync('public/resumes')) {
fs.mkdirSync('public/resumes');
}
const fileExt = resume.originalname.substring(resume.originalname.lastIndexOf('.'));
const path = `resumes/${uuidv1() + fileExt}`;
fs.writeFile(`public/${path}`, resume.buffer, () => {
jobApplication.create({
resume: path,
jobId: req.body.jobId,
applicantId: req.user.id,
status: 'Pending',
}).then(() => {
res.send(req.body.jobId);
});
});
}
function getApplications(req, res) {
let appFilter;
if (req.body && req.body.jobId) appFilter = { jobId: req.body.jobId };
else appFilter = { applicantId: req.user.id };
Job.findAll({
attributes: ['title'],
include: [{
model: User,
as: 'creator',
attributes: ['name'],
}, {
model: jobApplication,
where: {
...appFilter,
},
include: [{
model: User,
as: 'applicant',
attributes: ['name', 'email', 'profile_image'],
}],
attributes: ['id', 'status', 'createdAt', 'resume'],
}],
}).then((applications) => {
res.send(applications);
});
}
function updateAppStatus(req, res) {
jobApplication.update({
status: req.body.status,
}, {
where: {
id: req.body.appId,
},
}).then(() => {
res.send(req.body.appId);
});
}
module.exports = {
postJob, getJobs, applyJob, getApplications, updateAppStatus,
};
|
internet-com/kit
|
examples/web/cmd/app/handlers/user.go
|
// Package handlers contains the handler logic for processing requests.
package handlers
import (
"context"
"net/http"
"github.com/ardanlabs/kit/examples/web/internal/sys/app"
"github.com/ardanlabs/kit/examples/web/internal/user"
"github.com/ardanlabs/kit/web"
)
// UserList returns all the existing users in the system.
// 200 Success, 404 Not Found, 500 Internal
func UserList(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {
v := ctx.Value(app.KeyValues).(*app.Values)
u, err := user.List(ctx, v.TraceID, v.DB)
if err != nil {
web.Error(ctx, w, err)
return err
}
return web.Respond(ctx, w, u, http.StatusOK)
}
|
seowalex/tp
|
src/test/java/chopchop/commons/util/EitherTest.java
|
// EitherTest.java
package chopchop.commons.util;
import java.util.NoSuchElementException;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static chopchop.testutil.Assert.assertThrows;
public class EitherTest {
private final Either<String, Integer> l1 = Either.left("foo");
private final Either<String, Integer> l2 = Either.left("foofoo");
private final Either<String, Integer> r1 = Either.right(123);
private final Either<String, Integer> r2 = Either.right(246);
@Test
public void test_values() {
assertTrue(l1.isLeft());
assertFalse(l1.isRight());
assertTrue(r1.isRight());
assertFalse(r1.isLeft());
assertEquals("foo", l1.fromLeft());
assertEquals(123, r1.fromRight());
assertThrows(NoSuchElementException.class, () -> l1.fromRight());
assertThrows(NoSuchElementException.class, () -> r1.fromLeft());
assertTrue(l1.fromLeftOpt().isPresent());
assertTrue(l1.fromRightOpt().isEmpty());
assertTrue(r1.fromRightOpt().isPresent());
assertTrue(r1.fromLeftOpt().isEmpty());
assertThrows(AssertionError.class, () -> new Either<>("asdf", "bsdf"));
// this is a bit hacky, but just make a new Strings() class owo
var s = new Strings();
}
@Test
public void test_mapping() {
assertEquals(l2, l1.mapLeft(x -> x + x));
assertEquals(r2, r1.mapRight(x -> x + x));
assertEquals(l1, l1.mapRight(x -> x + x));
assertEquals(r1, r1.mapLeft(x -> x + x));
}
@Test
public void test_equals() {
assertNotEquals(l1, "foo");
assertEquals(l1, l1);
assertEquals(l2, l1.mapLeft(x -> x + x));
assertEquals(r2, r1.mapRight(x -> x + x));
var n1 = Either.left(null);
var n2 = Either.right(null);
assertEquals(n1, n2);
assertNotEquals(n1, l1);
assertNotEquals(n1, r1);
}
@Test
public void test_toString() {
assertEquals("Left(foo)", l1.toString());
assertEquals("Right(123)", r1.toString());
}
}
|
haiko21/LittleGPTracker
|
sources/Application/Controllers/ControlRoom.h
|
<filename>sources/Application/Controllers/ControlRoom.h
#ifndef _CONTROLROOM_H_
#define _CONTROLROOM_H_
#include "Foundation/T_Singleton.h"
#include "Services/Controllers/ControlNode.h"
class ControlRoom:public T_Singleton<ControlRoom>,public ControlNode {
public:
ControlRoom() ;
~ControlRoom() ;
bool Init() ;
void Close() ;
bool Attach(const char *nodeUrl,const char *controllerUrl) ;
AssignableControlNode *GetControlNode(const std::string url) ;
bool LoadMapping(const char *path) ;
void Dump() ;
} ;
#endif
|
DmitriyKostyanetsky/job4j
|
chapter_004/src/test/java/ru/job4j/thread/ThreadTest.java
|
package ru.job4j.thread;
import org.junit.Test;
import ru.job4j.treads.condition.Task;
import ru.job4j.treads.condition.Visibility;
public class ThreadTest {
@Test
public void testThread() throws InterruptedException {
Task task = new Task(new Task.Account());
Thread thread1 = new Thread(task);
Thread thread2 = new Thread(task);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
}
@Test
public void testThread2() throws InterruptedException {
Visibility vis = new Visibility();
Thread thread1 = new Thread(vis);
thread1.start();
vis.aVoid();
thread1.join();
}
}
|
theshaodi/algorithm004-05
|
Week 1/id_595/LeetCode_641_595.js
|
/*
* @lc app=leetcode.cn id=641 lang=javascript
*
* [641] 设计循环双端队列
*
* https://leetcode-cn.com/problems/design-circular-deque/description/
*
* algorithms
* Medium (46.52%)
* Likes: 17
* Dislikes: 0
* Total Accepted: 2.1K
* Total Submissions: 4.5K
* Testcase Example: '["MyCircularDeque","insertLast","insertLast","insertFront","insertFront","getRear","isFull","deleteLast","insertFront","getFront"]\n[[3],[1],[2],[3],[4],[],[],[],[4],[]]'
*
* 设计实现双端队列。
* 你的实现需要支持以下操作:
*
*
* MyCircularDeque(k):构造函数,双端队列的大小为k。
* insertFront():将一个元素添加到双端队列头部。 如果操作成功返回 true。
* insertLast():将一个元素添加到双端队列尾部。如果操作成功返回 true。
* deleteFront():从双端队列头部删除一个元素。 如果操作成功返回 true。
* deleteLast():从双端队列尾部删除一个元素。如果操作成功返回 true。
* getFront():从双端队列头部获得一个元素。如果双端队列为空,返回 -1。
* getRear():获得双端队列的最后一个元素。 如果双端队列为空,返回 -1。
* isEmpty():检查双端队列是否为空。
* isFull():检查双端队列是否满了。
*
*
* 示例:
*
* MyCircularDeque circularDeque = new MycircularDeque(3); // 设置容量大小为3
* circularDeque.insertLast(1); // 返回 true
* circularDeque.insertLast(2); // 返回 true
* circularDeque.insertFront(3); // 返回 true
* circularDeque.insertFront(4); // 已经满了,返回 false
* circularDeque.getRear(); // 返回 2
* circularDeque.isFull(); // 返回 true
* circularDeque.deleteLast(); // 返回 true
* circularDeque.insertFront(4); // 返回 true
* circularDeque.getFront(); // 返回 4
*
*
*
*
* 提示:
*
*
* 所有值的范围为 [1, 1000]
* 操作次数的范围为 [1, 1000]
* 请不要使用内置的双端队列库。
*
*
*/
// @lc code=start
/**
* Initialize your data structure here. Set the size of the deque to be k.
* @param {number} k
*/
var MyCircularDeque = function(k) {
this.arrDeque = new Array(k + 1);
this.head = 0;
this.rear = 0;
this.n = k + 1;
this.k = k;
};
/**
* Adds an item at the front of Deque. Return true if the operation is successful.
* @param {number} value
* @return {boolean}
*/
MyCircularDeque.prototype.insertFront = function(value) {
if(!this.isFull()) {
this.head = (--this.head + this.n) % this.n;
this.arrDeque[this.head] = value;
return true;
} else {
return false;
}
};
/**
* Adds an item at the rear of Deque. Return true if the operation is successful.
* @param {number} value
* @return {boolean}
*/
MyCircularDeque.prototype.insertLast = function(value) {
if(!this.isFull()) {
this.arrDeque[this.rear] = value;
this.rear = (++this.rear) % this.n;
return true;
} else {
return false;
}
};
/**
* Deletes an item from the front of Deque. Return true if the operation is successful.
* @return {boolean}
*/
MyCircularDeque.prototype.deleteFront = function() {
if(!this.isEmpty()) {
this.head = (++this.head) % this.n;
return true;
} else {
return false;
}
};
/**
* Deletes an item from the rear of Deque. Return true if the operation is successful.
* @return {boolean}
*/
MyCircularDeque.prototype.deleteLast = function() {
if(!this.isEmpty()) {
this.rear = (--this.rear + this.n) % this.n;
return true;
} else {
return false;
}
};
/**
* Get the front item from the deque.
* @return {number}
*/
MyCircularDeque.prototype.getFront = function() {
return this.isEmpty() ? -1 : this.arrDeque[this.head];
};
/**
* Get the last item from the deque.
* @return {number}
*/
MyCircularDeque.prototype.getRear = function() {
return this.isEmpty() ? -1 : this.arrDeque[(this.rear-1+this.n)%(this.n)];
};
/**
* Checks whether the circular deque is empty or not.
* @return {boolean}
*/
MyCircularDeque.prototype.isEmpty = function() {
if(this.head === this.rear) return true;
return false;
};
/**
* Checks whether the circular deque is full or not.
* @return {boolean}
*/
MyCircularDeque.prototype.isFull = function() {
return (this.rear - this.head + this.n) % this.n === this.k;
};
/**
* Your MyCircularDeque object will be instantiated and called as such:
* var obj = new MyCircularDeque(k)
* var param_1 = obj.insertFront(value)
* var param_2 = obj.insertLast(value)
* var param_3 = obj.deleteFront()
* var param_4 = obj.deleteLast()
* var param_5 = obj.getFront()
* var param_6 = obj.getRear()
* var param_7 = obj.isEmpty()
* var param_8 = obj.isFull()
*/
// @lc code=end
|
jimmydief/babel-plugin-transform-async-to-promises
|
tests/await complex switch/case-fallthrough with code.js
|
<reponame>jimmydief/babel-plugin-transform-async-to-promises
let called = false;
expect((await f(5, async () => 2, () => called = true))).toBe(2);
expect(called).toBe(true);
|
SkygearIO/skygear-server
|
pkg/core/imageprocessing/asset_type.go
|
package imageprocessing
type AssetType string
const (
AssetTypeImage AssetType = "image"
)
|
ethansaxenian/RosettaDecode
|
lang/Go/add-a-variable-to-a-class-instance-at-runtime.go
|
<gh_stars>1-10
package main
import (
"bufio"
"fmt"
"log"
"os"
)
type SomeStruct struct {
runtimeFields map[string]string
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
ss := SomeStruct{make(map[string]string)}
scanner := bufio.NewScanner(os.Stdin)
fmt.Println("Create two fields at runtime: ")
for i := 1; i <= 2; i++ {
fmt.Printf(" Field #%d:\n", i)
fmt.Print(" Enter name : ")
scanner.Scan()
name := scanner.Text()
fmt.Print(" Enter value : ")
scanner.Scan()
value := scanner.Text()
check(scanner.Err())
ss.runtimeFields[name] = value
fmt.Println()
}
for {
fmt.Print("Which field do you want to inspect ? ")
scanner.Scan()
name := scanner.Text()
check(scanner.Err())
value, ok := ss.runtimeFields[name]
if !ok {
fmt.Println("There is no field of that name, try again")
} else {
fmt.Printf("Its value is '%s'\n", value)
return
}
}
}
|
Melatonin64/snowplow
|
3-enrich/scala-common-enrich/src/test/scala/com.snowplowanalytics.snowplow.enrich.common/utils/TestResourcesRepositoryRef.scala
|
package com.snowplowanalytics
package snowplow.enrich.common.utils
// Java
import java.io.IOException
// Scala
import scala.util.control.NonFatal
// Jackson
import com.fasterxml.jackson.core.JsonParseException
import com.fasterxml.jackson.databind.JsonNode
import com.github.fge.jackson.JsonLoader
// Scalaz
import scalaz.Scalaz._
//Snowplow
import com.snowplowanalytics.iglu.client.repositories.{RepositoryRef, RepositoryRefConfig}
import com.snowplowanalytics.iglu.client.{SchemaKey, Validated, utils, validation}
// Iglu
import iglu.client.utils.{ValidationExceptions => VE}
import iglu.client.validation.ProcessingMessageMethods._
/**
* Iglu repository ref that looks up a schema in test resources.
*/
case class TestResourcesRepositoryRef(override val config: RepositoryRefConfig, path: String) extends RepositoryRef {
/**
* Prioritize searching this class of repository to ensure that tests use it
*/
override val classPriority: Int = 1
/**
* Human-readable descriptor for this
* type of repository ref.
*/
val descriptor = "test"
/**
* Retrieves an IgluSchema from the Iglu Repo as
* a JsonNode.
*
* @param schemaKey The SchemaKey uniquely identifies
* the schema in Iglu
* @return a Validation boxing either the Schema's
* JsonNode on Success, or an error String
* on Failure
*/
def lookupSchema(schemaKey: SchemaKey): Validated[Option[JsonNode]] = {
val schemaPath = s"${path}/${schemaKey.toPath}"
try {
JsonLoader.fromPath(schemaPath).some.success
} catch {
case jpe: JsonParseException => // Child of IOException so match first
s"Problem parsing ${schemaPath} as JSON in ${descriptor} Iglu repository ${config.name}: %s"
.format(VE.stripInstanceEtc(jpe.getMessage))
.failure
.toProcessingMessage
case ioe: IOException =>
None.success // Schema not found
case NonFatal(e) =>
s"Unknown problem reading and parsing ${schemaPath} in ${descriptor} Iglu repository ${config.name}: ${VE
.getThrowableMessage(e)}".failure.toProcessingMessage
}
}
}
|
irinabov/debian-qpid-cpp-1.35.0
|
src/qpid/messaging/amqp/util.h
|
<filename>src/qpid/messaging/amqp/util.h
#ifndef QPID_MESSAGING_AMQP_UTIL_H
#define QPID_MESSAGING_AMQP_UTIL_H
/*
*
* 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.
*
*/
#include <string>
extern "C" {
#include <proton/engine.h>
}
namespace qpid {
namespace messaging {
namespace amqp {
std::string get_error_string(pn_condition_t* error, const std::string& general, const std::string& delim = std::string(" with "));
}}} // namespace qpid::messaging::amqp
#endif /*!QPID_MESSAGING_AMQP_UTIL_H*/
|
cfe84/42sh
|
src/expansion/expand.c
|
/*
** expand.c for 42sh in /goinfre/grosli_o-42sh/src/expansion
**
** Made by <NAME>
** Login <<EMAIL>>
**
** Started on Sun Jan 16 15:09:42 2005 <NAME>
** Last update Tue Jan 18 18:14:54 2005 <NAME>
*/
/**
** @file expand.c
** Contains the mainframe of expansion module
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include "../global.h"
#include "../ast.h"
#include "expand.h"
#include "paths.h"
#include "unquoting.h"
/**
** Returns a string tab containing the translation of the entire chained list
** @param cmd The chained list which has to be transformed
*/
char **get_cmd(struct s_cmd *cmd)
{
int i = 0;
struct s_cmd *p = NULL;
char **args = NULL;
for (p = cmd; p != NULL; p = p->next)
i++;
if ((args = malloc((i + 1) * sizeof (char *))) == NULL)
return NULL;
i = 0;
for (p = cmd; p != NULL; p = p->next)
args[i++] = remove_quote(p->cmd);
args[i] = NULL;
return args;
}
/**
** Launches the expansion functions for the current AST, and launches
** this function for all the sub-AST contained in the current AST
** @param ast The Abstract Syntax Tree to expand
** @param g The Global Structure of the program
*/
static void expand_ast(struct s_ast *ast, struct s_glob *g)
{
if (ast == NULL)
return;
expand_paths(ast, g);
ast->cmd = get_cmd(ast->cmd_list);
expand_ast(ast->left, g);
expand_ast(ast->right, g);
expand(ast->cond, g);
expand(ast->list, g);
}
/**
** Parses a chained list of ASTs, and launches the expansion for
** each AST of the list
** @param ast The list of ASTs to expand
** @param g The Global Structure of the program
*/
void expand(struct s_ast_list *ast_list, struct s_glob *g)
{
if (ast_list == NULL)
return;
while (ast_list != NULL)
{
expand_ast(ast_list->ast, g);
ast_list = ast_list->next;
}
}
|
bracikaa/openproject
|
lib/api/v3/principals/principal_representer.rb
|
#-- encoding: UTF-8
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2021 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 <NAME>
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See docs/COPYRIGHT.rdoc for more details.
#++
require 'roar/decorator'
require 'roar/json/hal'
module API
module V3
module Principals
class PrincipalRepresenter < ::API::Decorators::Single
include AvatarHelper
include API::Decorators::DateProperty
include ::API::Caching::CachedRepresenter
def self.create(user, current_user:)
new(user, current_user: current_user)
end
def initialize(user, current_user:)
super(user, current_user: current_user)
end
self_link
link :memberships,
cache_if: -> { current_user_allowed_to_see_members? } do
filters = [
{
principal: {
operator: '=',
values: [represented.id.to_s]
}
}
]
{
href: api_v3_paths.path_for(:memberships, filters: filters),
title: I18n.t(:label_member_plural)
}
end
property :id,
render_nil: true
property :name,
render_nil: true
date_time_property :created_at,
cache_if: -> { current_user_is_admin_or_self }
date_time_property :updated_at,
cache_if: -> { current_user_is_admin_or_self }
def current_user_is_admin_or_self
current_user_is_admin || represented.id == current_user.id
end
def current_user_is_admin
current_user.admin?
end
def current_user_allowed_to_see_members?
current_user.allowed_to?(:view_members, nil, global: true) ||
current_user.allowed_to?(:manage_members, nil, global: true)
end
end
end
end
end
|
hao-wang/Montage
|
js-test-suite/testsuite/7910db6d4b621a8f4a3358bf32b76e1f.js
|
<gh_stars>10-100
load("1d8ada728956c1a3d52d68d1d4d6dd52.js");
// Copyright 2016 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Flags: --allow-natives-syntax
try {
%Call(1, 0);
} catch (e) {
assertTrue(e instanceof TypeError);
}
|
NikkiLoveGod/vis-academy
|
src/demos/building-a-geospatial-app/starting-code/src/charts.js
|
import React from "react";
import { charts } from "./style";
import { VerticalBarSeries, XAxis, XYPlot, YAxis } from "react-vis";
export default function Charts({ pickups }) {
return (
<div style={charts}>
<h2>Pickups by hour</h2>
<p>As percentage of all trips</p>
<XYPlot height={140} width={480}>
<XAxis />
<YAxis />
<VerticalBarSeries data={pickups} />
</XYPlot>
</div>
);
}
|
TotteKarlsson/dsl
|
Common/dslException.cpp
|
#pragma hdrstop
#include "dslException.h"
#include "dslLogger.h"
//---------------------------------------------------------------------------
namespace dsl
{
DSLException::DSLException(const string& desc)
:
mMessage(desc)
{}
DSLException::DSLException(const stringstream& msg)
:
mMessage(msg.str())
{}
DSLException::~DSLException() throw()
{}
const char* DSLException::what() const throw()
{
Log(lError) << mMessage;
return mMessage.c_str();
}
string DSLException::Message() const
{
return mMessage;
}
DerivedDSLException::DerivedDSLException(const string& msg)
:
DSLException(msg)
{}
}
|
galaxy-book/cyclone
|
pkg/server/handler/v1alpha1/healthcheck.go
|
<filename>pkg/server/handler/v1alpha1/healthcheck.go
package v1alpha1
import (
"context"
"github.com/caicloud/cyclone/pkg/server/apis/v1alpha1"
)
// HealthCheck checks the health status of Cyclone server.
func HealthCheck(ctx context.Context) (v1alpha1.HealthStatus, error) {
return v1alpha1.HealthStatus{
Status: "healthy",
}, nil
}
|
Kevinskwk/ILP
|
Final/Ma Yuchen-1.py
|
<gh_stars>1-10
def myseries(n):
s=n*(n+1)/2
return s
def sqnum(n):
root=n**0.5
if root % 1 == 0:
return True
else:
return False
print 'T100 = '+str(myseries(100))
print 'T2000 = '+str(myseries(2000))
print 'T50000 = '+str(myseries(50000))
i=0
n=8
SquareNumbers=[]
while i<2:
n+=1
T = myseries(n)
if sqnum(T) == True:
i+=1
SquareNumbers.append(T)
print "The next two square nambers are:"
for x in SquareNumbers:
print x
|
drrost/s2c1-libmx-tests
|
tests/t10/test_00.c
|
#include "../../lib/test_lib.h"
#include "../../libmx.h"
char *test_case_name = "mx_foreach";
void mx_printint(int n) {
printf("%d\n", n);
}
// Tests
void test_foreach() {
// Given
int arr[] = {1, 2, 3, 4, 5};
intercept_stdout();
// When
mx_foreach(arr, 5, mx_printint);
// Then
restore_stdout();
ASSERT_STDOUT_EQUALS("1\n2\n3\n4\n5\n");
}
|
joshualy/numerical_computing
|
Vol3A/SQL1/spec.py
|
# Name this file 'solutions.py'.
"""Volume III Lab : SQL1.
<Name>
<Class>
<Date>
"""
import sqlite3 as sql
import csv
# Problem 1
def new_tables():
""" Create two tables in the database "sql1". Call the first table
MajorInfo with columns MajorCode(int) and MajorName(string). Call the
second table CourseInfo with columns CourseID(int) and CourseName(string).
"""
raise NotImplementedError("Problem 1 Incomplete")
# Problem 2
def icd9tables():
""" Create a table called ICD in the database sql2. Import the data from
icd9.csv. There should be 4 columns: id(int),gender(text), age(int), and
codes (string).
"""
raise NotImplementedError("Problem 2 Incomplete")
# Problem 3
def sampletables():
""" Create a table from the data given in the lab in the sql1 database."""
raise NotImplementedError("Problem 3 Incomplete")
# Problem 4
def freqcodes():
""" Using the ICD9 table that you created in problem 2. How many men
between the ages of 25 and 25 are there? How many women between those
same ages? Return your answers as a tuple.
"""
raise NotImplementedError("Problem 4 Incomplete")
|
kazssym/bountysource-core
|
spec/controllers/api/v2/fundraiser_rewards_controller_spec.rb
|
<reponame>kazssym/bountysource-core<filename>spec/controllers/api/v2/fundraiser_rewards_controller_spec.rb
require 'spec_helper'
describe Api::V2::FundraiserRewardsController do
end
|
faezezps/SiMQC
|
hotpot/scripts/train_eval/ranked_scores_to_hotpot_pred.py
|
import argparse
from ast import literal_eval
import json
import pandas as pd
import numpy as np
def df_to_pred(df, filename, return_results=False, return_titles=False):
span_q_col = "span_question_scores"
yes_no_q_col = "yes_no_question_scores"
yes_no_scores_col = "yes_no_confidence_scores"
span_scores_col = "predicted_score"
group_cols = ['question_id']
answer_dict = {}
sp_dict = {}
titles_dict = {}
for gid, group in df[[span_scores_col, span_q_col, yes_no_q_col, yes_no_scores_col,
'text_answer', 'predicted_sp', 'titles'] +
group_cols].groupby(group_cols):
max_span_question_score = group[span_q_col].expanding().apply(lambda x: x.max(), raw=True).values
max_yes_no_question_score = group[yes_no_q_col].expanding().apply(lambda x: x.max(), raw=True).values
is_yes_no_expanding = np.stack([max_span_question_score, max_yes_no_question_score], axis=0).argmax(axis=0)
span_used_predictions = group[span_scores_col].expanding().apply(lambda x: x.argmax(), raw=True)
yes_no_used_predictions = group[yes_no_scores_col].expanding().apply(lambda x: x.argmax(), raw=True)
pred_idx = int(yes_no_used_predictions.values[-1]) if is_yes_no_expanding[-1] else int(
span_used_predictions.values[-1])
sp_dict[gid] = group['predicted_sp'].values[pred_idx]
if type(sp_dict[gid]) == str:
sp_dict[gid] = literal_eval(sp_dict[gid])
if return_results and return_titles:
titles_dict[gid] = group['titles'].values[pred_idx]
if type(titles_dict[gid]) == str:
titles_dict[gid] = literal_eval(titles_dict[gid])
answer_dict[gid] = group['text_answer'].values[pred_idx]
if return_results and return_titles:
return answer_dict, sp_dict, titles_dict
elif return_results:
return answer_dict, sp_dict
with open(filename, 'w') as f:
json.dump({'answer': answer_dict, 'sp': sp_dict}, f)
def main():
parser = argparse.ArgumentParser(description="produces a prediction file from a ranked scores file")
parser.add_argument('answers', help='answer file')
parser.add_argument('out_file', help="file to write the predictions to")
args = parser.parse_args()
print("Loading answers..")
answer_df = pd.read_csv(args.answers)
df_to_pred(answer_df, args.out_file)
if __name__ == "__main__":
main()
|
venkateshprasad123/wb
|
Java_GUI/src/com/ibm/safr/we/data/DAOFactoryHolder.java
|
package com.ibm.safr.we.data;
/*
* Copyright Contributors to the GenevaERS Project. SPDX-License-Identifier: Apache-2.0 (c) Copyright IBM Corporation 2008.
*
* 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 java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.logging.Logger;
import java.util.prefs.Preferences;
import com.ibm.safr.we.SAFRUtilities;
import com.ibm.safr.we.constants.UserPreferencesNodes;
import com.ibm.safr.we.internal.data.PGDAOFactory;
import com.ibm.safr.we.preferences.SAFRPreferences;
public class DAOFactoryHolder {
static transient Logger logger = Logger
.getLogger("com.ibm.safr.we.data.DAOFactoryHolder");
static DAOFactory daoFactory = null;
static DAOFactory backupDaoFactory = null;
static void initWithPreferences() throws DAOException {
// Get Connection settings from preferences
Preferences preferences = SAFRPreferences.getDefaultConnectionPreferences();
if (preferences == null) {
throw new NullPointerException(
"User Preferences file for connection is either absent or corrupted.");
}
Preferences connection = preferences;
try {
ConnectionParameters params = new ConnectionParameters();
String dbtype = connection.get(UserPreferencesNodes.DATABASETYPE, "");
if (dbtype != null && dbtype.length()>0) {
params.setType(DBType.valueOf(dbtype));
}
String url = "jdbc:"
+ connection.get(UserPreferencesNodes.DATABASETYPE, "")
.toLowerCase() + "://"
+ connection.get(UserPreferencesNodes.SERVER, "") + ":"
+ connection.get(UserPreferencesNodes.PORT, "") + "/"
+ connection.get(UserPreferencesNodes.DATABASENAME, "") + "?currentSchema="
+ connection.get(UserPreferencesNodes.SCHEMA, "");
// Uncomment for JDBC trace
/* + ":traceDirectory=c:\\temp"
+ ";traceFile=trace"
+ ";traceFileAppend=false"
+ ";traceLevel=" + com.ibm.db2.jcc.DB2BaseDataSource.TRACE_STATEMENT_CALLS + ";";*/
params.setUrl(url);
params.setDatabase(connection.get(
UserPreferencesNodes.DATABASENAME, ""));
params.setPort(connection.get(UserPreferencesNodes.PORT, ""));
params.setServer(connection.get(UserPreferencesNodes.SERVER, ""));
params.setSchema(connection.get(UserPreferencesNodes.SCHEMA, ""));
params.setUserName(connection.get(UserPreferencesNodes.USERID, ""));
genDAOFactory(params);
} catch (IllegalStateException e) {
throw new IllegalStateException(
"User Preferences file for connection is either absent or corrupted.");
}
}
public static void initWithPropertiesFile(InputStream file) throws DAOException {
try {
BufferedInputStream stream = new BufferedInputStream(file);
Properties prop = new Properties();
prop.load(stream);
ConnectionParameters params = new ConnectionParameters();
params.setType(DBType.valueOf((String) prop.get("TYPE")));
params.setServer((String) prop.get("SERVER"));
params.setPort((String) prop.get("PORT"));
params.setDatabase((String) prop.get("DATABASE"));
params.setSchema((String) prop.get("SCHEMA"));
params.setUserName((String) prop.get("USER"));
params.setPassWord((String) prop.get("PASS"));
String url = "jdbc:"
+ ((String)prop.get("TYPE")).toLowerCase() + "://"
+ prop.get("SERVER") + ":"
+ prop.get("PORT") + "/"
+ prop.get("DATABASE") + "?currentSchema="
+ prop.get("SCHEMA");
// Uncomment for JDBC trace
/* + ":traceDirectory=c:\\temp"
+ ";traceFile=trace"
+ ";traceFileAppend=false"
+ ";traceLevel=" + com.ibm.db2.jcc.DB2BaseDataSource.TRACE_STATEMENT_CALLS + ";";*/
params.setUrl(url);
genDAOFactory(params);
String userId = prop.getProperty("SAFRUSER");
Integer envId = Integer.valueOf(prop.getProperty("SAFRENV"));
Integer groupId = Integer.valueOf(prop.getProperty("SAFRGRP"));
if (groupId == null) {
groupId = 0;
}
UserSessionParameters uparams = new UserSessionParameters(userId,
envId, groupId);
daoFactory.setSAFRLogin(uparams);
} catch (IOException e) {
throw new DAOException(
"Unable to load properies for the connection." + SAFRUtilities.LINEBREAK
+ e.toString());
}
}
static void genDAOFactory(ConnectionParameters params) throws DAOException {
if (daoFactory != null) {
if (params.getType() == DBType.PostgresQL) {
((PGDAOFactory) daoFactory).reconnect();
} else {
logger.severe("Invalid Database type" + params.getType().toString());
throw new DAOException("Invalid Database type");
}
} else {
if (params.getType() == DBType.PostgresQL) {
daoFactory = new PGDAOFactory(params);
} else {
logger.severe("Invalid Database type" + params.getType().toString());
throw new DAOException("Invalid Database type");
}
}
}
public static DAOFactory getDAOFactory() throws DAOException {
if (daoFactory == null) {
initWithPreferences();
}
return daoFactory;
}
public static void setDaoFactory(DAOFactory daoFactory) {
DAOFactoryHolder.daoFactory = daoFactory;
}
/**
* Get the ODBC connection string for the selected database type. This
* string is prepared based on the configuration done in Connection Manager.
*
* @return the ODBC string for the current DB connection or null if the
* selected database type is not DB2.<br>
* <br>
* Example: for DB2 server the string returned by this function
* could be:<br>
* <code>Driver={IBM DB2 ODBC DRIVER};Hostname=bmsdev2.boulder.ibm.com;Port=5050;Protocol=TCPIP;UID=kaputin;PWD=<PASSWORD>;Database=BMS2DB2Z</code>
*/
// public static String getODBCConnectionString() {
// String returnStr = null;
// ConnectionParameters params = daoFactory.getConnectionParameters();
// if (params.getType() == DBType.DB2) {
// returnStr = "Driver=";
// returnStr += "{IBM DB2 ODBC SAFR WE DRIVER};";
// returnStr += "Hostname=" + params.getServer() + ";";
// returnStr += "Port=" + params.getPort() + ";";
// returnStr += "Protocol=TCPIP;";
// returnStr += "UID=" + params.getUserName() + ";";
// returnStr += "PWD=" + params.getPassWord() + ";";
// returnStr += "Database=" + params.getDatabase();
// }
// if (params.getType() == DBType.PostgresQL) {
// // returnStr = "Driver=";
// // returnStr += "{IBM DB2 ODBC SAFR WE DRIVER};";
// // returnStr += "Hostname=" + params.getServer() + ";";
// // returnStr += "Port=" + params.getPort() + ";";
// // returnStr += "Protocol=TCPIP;";
// // returnStr += "UID=" + params.getUserName() + ";";
// // returnStr += "PWD=" + params.getPassWord() + ";";
// // returnStr += "Database=" + params.getDatabase();
// }
// return returnStr;
// }
/**
* Get the ODBC connection string for the selected database type for the old compiler. This
* string is prepared based on the configuration done in Connection Manager.
*
* @return the ODBC string for the current DB connection or null if the
* selected database type is not DB2.<br>
* <br>
* Example: for DB2 server the string returned by this function
* could be:<br>
* <code>Driver={IBM DB2 ODBC SAFR WE DRIVER};Hostname=bmsdev2.boulder.ibm.com;Port=5050;Protocol=TCPIP;UID=kaputin;PWD=<PASSWORD>;Database=BMS2DB2Z</code>
*/
// public static String getODBCConnectionStringOld() {
// String returnStr = null;
// ConnectionParameters params = daoFactory.getConnectionParameters();
// if (params.getType() == DBType.DB2) {
// returnStr = "Driver=";
// returnStr += "{IBM DB2 ODBC SAFR WE DRIVER};";
// returnStr += "Hostname=" + params.getServer() + ";";
// returnStr += "Port=" + params.getPort() + ";";
// returnStr += "Protocol=TCPIP;";
// returnStr += "UID=" + params.getUserName() + ";";
// returnStr += "PWD=" + <PASSWORD>() + ";";
// returnStr += "Database=" + params.getDatabase();
// }
// return returnStr;
// }
/**
* Disconnects the active connection.
*
* @throws DAOException
* if an error occurs.
*/
public static void closeDAOFactory() throws DAOException {
if (daoFactory != null) {
try {
daoFactory.disconnect();
} finally {
// set the factory reference to null so that it can retry
// connection using latest preference entries.
daoFactory = null;
}
}
}
/**
* Disconnects the backup connection.
*
* @throws DAOException
* if an error occurs.
*/
public static void closeBackupDAOFactory() throws DAOException {
if (backupDaoFactory != null) {
try {
backupDaoFactory.disconnect();
} finally {
// set the factory reference to null so that it can retry
// connection using latest preference entries.
backupDaoFactory = null;
}
}
}
/**
* backupDaoFactory *
*/
public static void backupDAOFactory() {
backupDaoFactory = daoFactory;
daoFactory = null;
}
/**
* restoreDaoFactory
*
* @throws DAOException
* if an error occurs.
*/
public static void restoreDAOFactory() throws DAOException {
if (daoFactory != null) {
daoFactory.disconnect();
}
daoFactory = backupDaoFactory;
backupDaoFactory = null;
}
}
|
phatblat/macOSPrivateFrameworks
|
PrivateFrameworks/CloudServices/SecureBackup.h
|
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
#import "NSObject.h"
#import "NSSecureCoding.h"
@class EscrowPrerecord, NSData, NSDate, NSDictionary, NSError, NSObject<OS_dispatch_queue>, NSString, SESWrapper;
@interface SecureBackup : NSObject <NSSecureCoding>
{
BOOL _deleteAll;
BOOL _emcsMode;
BOOL _fmipRecovery;
BOOL _icdp;
BOOL _idmsRecovery;
BOOL _silent;
BOOL _stingray;
BOOL _synchronize;
BOOL _useCachedPassphrase;
BOOL _useRecoveryPET;
BOOL _usesMultipleiCSC;
BOOL _usesRandomPassphrase;
BOOL _usesRecoveryKey;
BOOL _suppressServerFiltering;
NSString *_appleID;
NSString *_authToken;
NSDate *_backOffDate;
NSData *_certData;
NSString *_countryDialCode;
NSString *_countryCode;
NSString *_dsid;
NSString *_emcsCred;
NSDictionary *_emcsDict;
NSString *_encodedMetadata;
NSDictionary *_escrowRecord;
NSString *_escrowProxyURL;
NSString *_fmipUUID;
NSString *_iCloudEnv;
NSData *_iCloudIdentityData;
NSString *_iCloudPassword;
NSData *_idmsData;
NSDictionary *_metadata;
NSDictionary *_metadataHash;
NSString *_oldEMCSCred;
NSString *_passphrase;
NSString *_recordID;
NSString *_recoveryKey;
NSString *_smsTarget;
NSString *_verificationToken;
NSObject<OS_dispatch_queue> *_queue;
NSError *_error;
NSString *_activityLabel;
NSString *_activityUUID;
NSString *_hsa2CachedPrerecordUUID;
EscrowPrerecord *_prerecord;
SESWrapper *_ses;
}
+ (unsigned int)daemonPasscodeRequestOpinion:(id *)arg1;
+ (unsigned int)needPasscodeForHSA2EscrowRecordUpdate:(id *)arg1;
+ (void)asyncRequestEscrowRecordUpdate;
+ (BOOL)supportsSecureCoding;
+ (id)_ClassCreateSecureBackupConcurrentConnection;
@property(retain, nonatomic) SESWrapper *ses; // @synthesize ses=_ses;
@property(retain, nonatomic) EscrowPrerecord *prerecord; // @synthesize prerecord=_prerecord;
@property(copy, nonatomic) NSString *hsa2CachedPrerecordUUID; // @synthesize hsa2CachedPrerecordUUID=_hsa2CachedPrerecordUUID;
@property(nonatomic) BOOL suppressServerFiltering; // @synthesize suppressServerFiltering=_suppressServerFiltering;
@property(copy, nonatomic) NSString *activityUUID; // @synthesize activityUUID=_activityUUID;
@property(copy, nonatomic) NSString *activityLabel; // @synthesize activityLabel=_activityLabel;
@property(retain, nonatomic) NSError *error; // @synthesize error=_error;
@property(retain, nonatomic) NSObject<OS_dispatch_queue> *queue; // @synthesize queue=_queue;
@property(copy, nonatomic) NSString *verificationToken; // @synthesize verificationToken=_verificationToken;
@property(nonatomic) BOOL usesRecoveryKey; // @synthesize usesRecoveryKey=_usesRecoveryKey;
@property(nonatomic) BOOL usesRandomPassphrase; // @synthesize usesRandomPassphrase=_usesRandomPassphrase;
@property(nonatomic) BOOL usesMultipleiCSC; // @synthesize usesMultipleiCSC=_usesMultipleiCSC;
@property(nonatomic) BOOL useRecoveryPET; // @synthesize useRecoveryPET=_useRecoveryPET;
@property(nonatomic) BOOL useCachedPassphrase; // @synthesize useCachedPassphrase=_useCachedPassphrase;
@property(nonatomic) BOOL synchronize; // @synthesize synchronize=_synchronize;
@property(nonatomic) BOOL stingray; // @synthesize stingray=_stingray;
@property(nonatomic) BOOL silent; // @synthesize silent=_silent;
@property(copy, nonatomic) NSString *smsTarget; // @synthesize smsTarget=_smsTarget;
@property(copy, nonatomic) NSString *recoveryKey; // @synthesize recoveryKey=_recoveryKey;
@property(copy, nonatomic) NSString *recordID; // @synthesize recordID=_recordID;
@property(copy, nonatomic) NSString *passphrase; // @synthesize passphrase=_passphrase;
@property(copy, nonatomic) NSString *oldEMCSCred; // @synthesize oldEMCSCred=_oldEMCSCred;
@property(retain, nonatomic) NSDictionary *metadataHash; // @synthesize metadataHash=_metadataHash;
@property(retain, nonatomic) NSDictionary *metadata; // @synthesize metadata=_metadata;
@property(nonatomic) BOOL idmsRecovery; // @synthesize idmsRecovery=_idmsRecovery;
@property(retain, nonatomic) NSData *idmsData; // @synthesize idmsData=_idmsData;
@property(copy, nonatomic) NSString *iCloudPassword; // @synthesize iCloudPassword=_iCloudPassword;
@property(retain, nonatomic) NSData *iCloudIdentityData; // @synthesize iCloudIdentityData=_iCloudIdentityData;
@property(copy, nonatomic) NSString *iCloudEnv; // @synthesize iCloudEnv=_iCloudEnv;
@property(nonatomic) BOOL icdp; // @synthesize icdp=_icdp;
@property(copy, nonatomic) NSString *fmipUUID; // @synthesize fmipUUID=_fmipUUID;
@property(nonatomic) BOOL fmipRecovery; // @synthesize fmipRecovery=_fmipRecovery;
@property(copy, nonatomic) NSString *escrowProxyURL; // @synthesize escrowProxyURL=_escrowProxyURL;
@property(retain, nonatomic) NSDictionary *escrowRecord; // @synthesize escrowRecord=_escrowRecord;
@property(copy, nonatomic) NSString *encodedMetadata; // @synthesize encodedMetadata=_encodedMetadata;
@property(nonatomic) BOOL emcsMode; // @synthesize emcsMode=_emcsMode;
@property(retain, nonatomic) NSDictionary *emcsDict; // @synthesize emcsDict=_emcsDict;
@property(copy, nonatomic) NSString *emcsCred; // @synthesize emcsCred=_emcsCred;
@property(copy, nonatomic) NSString *dsid; // @synthesize dsid=_dsid;
@property(nonatomic) BOOL deleteAll; // @synthesize deleteAll=_deleteAll;
@property(copy, nonatomic) NSString *countryCode; // @synthesize countryCode=_countryCode;
@property(copy, nonatomic) NSString *countryDialCode; // @synthesize countryDialCode=_countryDialCode;
@property(retain, nonatomic) NSData *certData; // @synthesize certData=_certData;
@property(retain, nonatomic) NSDate *backOffDate; // @synthesize backOffDate=_backOffDate;
@property(copy, nonatomic) NSString *authToken; // @synthesize authToken=_authToken;
@property(copy, nonatomic) NSString *appleID; // @synthesize appleID=_appleID;
- (void).cxx_destruct;
- (void)getCertificates:(CDUnknownBlockType)arg1;
- (id)beginHSA2PasscodeRequest:(_Bool)arg1 uuid:(id)arg2 error:(id *)arg3;
- (id)beginHSA2PasscodeRequest:(_Bool)arg1 error:(id *)arg2;
- (void)prepareHSA2EscrowRecordContents:(_Bool)arg1 reply:(CDUnknownBlockType)arg2;
- (id)srpRecoveryBlobFromSRPInitResponse:(id)arg1;
- (void)srpRecoveryUpdateDSID:(id)arg1 recoveryPassphrase:(id)arg2;
- (id)srpInitNonce;
- (void)setBackOffDateWithInfo:(id)arg1 completionBlock:(CDUnknownBlockType)arg2;
- (void)backOffDateWithInfo:(id)arg1 completionBlock:(CDUnknownBlockType)arg2;
- (id)backupWithInfo:(id)arg1;
- (void)changeSMSTargetWithInfo:(id)arg1 completionBlock:(CDUnknownBlockType)arg2;
- (id)changeSMSTargetWithInfo:(id)arg1;
- (_Bool)changeSMSTargetWithError:(id *)arg1;
- (void)getCountrySMSCodesWithInfo:(id)arg1 completionBlockWithResults:(CDUnknownBlockType)arg2;
- (void)startSMSChallengeWithInfo:(id)arg1 completionBlock:(CDUnknownBlockType)arg2;
- (void)startSMSChallengeWithInfo:(id)arg1 completionBlockWithResults:(CDUnknownBlockType)arg2;
- (id)startSMSChallengeWithInfo:(id)arg1 results:(id *)arg2;
- (id)startSMSChallengeWithError:(id *)arg1;
- (void)uncachePassphraseWithInfo:(id)arg1 completionBlock:(CDUnknownBlockType)arg2;
- (id)uncachePassphraseWithInfo:(id)arg1;
- (void)cachePassphraseWithInfo:(id)arg1 completionBlock:(CDUnknownBlockType)arg2;
- (id)cachePassphraseWithInfo:(id)arg1;
- (void)stashRecoveryDataWithInfo:(id)arg1 completionBlock:(CDUnknownBlockType)arg2;
- (void)disableWithInfo:(id)arg1 completionBlock:(CDUnknownBlockType)arg2;
- (id)disableWithInfo:(id)arg1;
- (_Bool)disableWithError:(id *)arg1;
- (void)recoverWithInfo:(id)arg1 completionBlock:(CDUnknownBlockType)arg2;
- (void)recoverWithInfo:(id)arg1 completionBlockWithResults:(CDUnknownBlockType)arg2;
- (id)recoverWithInfo:(id)arg1 results:(id *)arg2;
- (id)recoverWithError:(id *)arg1;
- (void)enableWithInfo:(id)arg1 completionBlock:(CDUnknownBlockType)arg2;
- (id)enableWithInfo:(id)arg1;
- (_Bool)enableWithError:(id *)arg1;
- (void)updateMetadataWithInfo:(id)arg1 completionBlock:(CDUnknownBlockType)arg2;
- (id)updateMetadataWithInfo:(id)arg1;
- (_Bool)updateMetadataWithError:(id *)arg1;
- (void)getAccountInfoWithInfo:(id)arg1 completionBlock:(CDUnknownBlockType)arg2;
- (void)getAccountInfoWithInfo:(id)arg1 completionBlockWithResults:(CDUnknownBlockType)arg2;
- (id)getAccountInfoWithInfo:(id)arg1 results:(id *)arg2;
- (id)getAccountInfoWithError:(id *)arg1;
- (void)stateCaptureWithCompletionBlock:(CDUnknownBlockType)arg1;
- (void)notificationInfo:(CDUnknownBlockType)arg1;
- (void)setBackOffDateWithCompletionBlock:(CDUnknownBlockType)arg1;
- (void)backOffDateWithCompletionBlock:(CDUnknownBlockType)arg1;
- (void)backupWithInfo:(id)arg1 completionBlock:(CDUnknownBlockType)arg2;
- (void)changeSMSTargetWithCompletionBlock:(CDUnknownBlockType)arg1;
- (void)getCountrySMSCodesWithResults:(CDUnknownBlockType)arg1;
- (void)startSMSChallengeWithResults:(CDUnknownBlockType)arg1;
- (void)uncachePassphrase;
- (void)uncacheRecoveryKeyWithCompletionBlock:(CDUnknownBlockType)arg1;
- (void)cacheRecoveryKeyWithCompletionBlock:(CDUnknownBlockType)arg1;
- (void)uncachePassphraseWithCompletionBlock:(CDUnknownBlockType)arg1;
- (void)cachePassphraseWithCompletionBlock:(CDUnknownBlockType)arg1;
- (void)cachePassphrase;
- (void)updateMetadataWithCompletionBlock:(CDUnknownBlockType)arg1;
- (void)stashRecoveryDataWithCompletionBlock:(CDUnknownBlockType)arg1;
- (void)disableWithCompletionBlock:(CDUnknownBlockType)arg1;
- (void)recoverRecordContents:(CDUnknownBlockType)arg1;
- (void)recoverWithResults:(CDUnknownBlockType)arg1;
- (void)enableWithCompletionBlock:(CDUnknownBlockType)arg1;
- (void)getAccountInfoWithResults:(CDUnknownBlockType)arg1;
- (void)populateWithInfo:(id)arg1;
- (id)initWithCoder:(id)arg1;
- (void)encodeWithCoder:(id)arg1;
- (id)init;
- (id)initWithUserActivityLabel:(id)arg1;
- (id)_CreateSecureBackupConnection;
@end
|
srcarter3/awips2
|
cave/com.raytheon.viz.hydrocommon/src/com/raytheon/viz/hydrocommon/textreport/StationListReport.java
|
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.viz.hydrocommon.textreport;
/**
* Sorted Station List Report.
*
* <pre>
*
* SOFTWARE HISTORY
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Sep 18, 2009 2260 mpduff Initial creation
* Sep 11, 2012 13781 wkwock add print menu
*
* </pre>
*
* @author mpduff
* @version 1.0
*/
public class StationListReport extends TextReport {
private static final String HDR_FORMAT = " %-10s %-30s %-70s Page %2d";
private static final String TITLE_LID = "LIST OF LOCATIONS SORTED BY LID";
private static final String TITLE_NAME = "LIST OF LOCATIONS SORTED BY NAME";
private static final String TITLE_COUNTY = "LIST OF LOCATIONS SORTED BY COUNTY";
private static final String TITLE_BASIN = "LIST OF LOCATIONS SORTED BY BASIN";
private static final String TITLE_OBSERVER = "LIST OF LOCATIONS SORTED BY OBSERVER";
private static final int STALIST_RECORD_LIMIT_PER_PAGE = 54;
/* Types used for ordering columns */
protected static final int STALIST_LID = 1;
protected static final int STALIST_NAM = 2;
protected static final int STALIST_COU = 3;
protected static final int STALIST_BAS = 4;
protected static final int STALIST_WFO = 5;
protected static final int STALIST_OBS = 6;
private static final int[] sortedby_lid = { STALIST_LID, STALIST_NAM,
STALIST_COU, STALIST_BAS, STALIST_WFO, STALIST_OBS, 0 };
private static final int[] sortedby_name = { STALIST_NAM, STALIST_LID,
STALIST_COU, STALIST_BAS, STALIST_WFO, STALIST_OBS, 0 };
private static final int[] sortedby_county = { STALIST_COU, STALIST_LID,
STALIST_NAM, STALIST_BAS, STALIST_WFO, STALIST_OBS, 0 };
private static final int[] sortedby_basin = { STALIST_BAS, STALIST_LID,
STALIST_NAM, STALIST_COU, STALIST_WFO, STALIST_OBS, 0 };
private static final int[] sortedby_observer = { STALIST_OBS, STALIST_LID,
STALIST_NAM, STALIST_COU, STALIST_BAS, STALIST_WFO, 0 };
/**
* Get the text of the report.
*
* @param sort
* The column to sort on
*/
@Override
public String getText(int sort) {
/* Get the text . */
String text = generateReport(sort);
text = text.replace("null", "");
return text;
}
/**
* Get the text for the dialog.
*/
@Override
public String loadTextWidget() {
return getText(0);//, TEXTREPORTS_REASON_NORMAL);
}
public int[] getSortArray(int sort) {
int[] sortArray=null;
switch (sort) {
case TextReportConstants.STALIST_SORTBY_LID:
sortArray = sortedby_lid;
break;
case TextReportConstants.STALIST_SORTBY_NAME:
sortArray = sortedby_name;
break;
case TextReportConstants.STALIST_SORTBY_COUNTY:
sortArray = sortedby_county;
break;
case TextReportConstants.STALIST_SORTBY_BASIN:
sortArray = sortedby_basin;
break;
case TextReportConstants.STALIST_SORTBY_OBSERVER:
sortArray = sortedby_observer;
break;
}
return sortArray;
}
/**
* Generate the report.
*
* @param sort
* Which column to sort on
*
* @return
* The text
*/
public String generateSpecialReport(int sort, int[] sortArray) {
StringBuilder buffer = new StringBuilder();
String hdrTitle = "LIST OF LOCATIONS";
// Get the data for the report
StationList[] slData = TextReportDataManager.getInstance()
.getStnListData(sort);
int recordLimit; /* max num records per "8 1/2 x 11" page */
int count = 0; /* for counting the num of records processed so far */
int pageNum = 1;
recordLimit = STALIST_RECORD_LIMIT_PER_PAGE;
/* Check sort type. */
switch (sort) {
case TextReportConstants.STALIST_SORTBY_LID:
hdrTitle = TITLE_LID;
break;
case TextReportConstants.STALIST_SORTBY_NAME:
hdrTitle = TITLE_NAME;
break;
case TextReportConstants.STALIST_SORTBY_COUNTY:
hdrTitle = TITLE_COUNTY;
break;
case TextReportConstants.STALIST_SORTBY_BASIN:
hdrTitle = TITLE_BASIN;
break;
case TextReportConstants.STALIST_SORTBY_OBSERVER:
hdrTitle = TITLE_OBSERVER;
break;
}
/* Build header line. */
buffer.append(getHeaderLine(hdrTitle, pageNum, sortArray));
/*
* Keep building the list of locations (& headers) for the given
* pageType until there are no more records or until the record_limit is
* reached.
*/
for (int j = 0; j < slData.length; j++) {
/* Write out a single output line as specified by the order. */
buffer.append(" ");
for (int i = 0; i < sortArray.length; i++) {
switch (sortArray[i]) {
case STALIST_LID:
buffer.append(String.format("%-8s", slData[j].getLid()));
break;
case STALIST_NAM:
if (slData[j].getName() != null) {
if (slData[j].getName().length() > 20) {
buffer.append(String.format("%-20s", slData[j]
.getName().substring(0, 20)));
} else {
buffer.append(String.format("%-20s", slData[j]
.getName()));
}
} else {
buffer.append(String.format("%-8s", " "));
}
break;
case STALIST_COU:
buffer
.append(String.format("%-20s", slData[j]
.getCounty()));
break;
case STALIST_BAS:
if (slData[j].getRb() != null) {
if (slData[j].getRb().length() > 20) {
buffer.append(String.format("%-20s", slData[j]
.getRb().substring(0, 20)));
} else {
buffer.append(String.format("%-20s", slData[j]
.getRb()));
}
} else {
buffer.append(String.format("%-20s", " "));
}
break;
case STALIST_WFO:
buffer.append(String.format("%-3s", slData[j].getWfo()));
break;
case STALIST_OBS:
if (slData[j].getLastname() != null) {
if (slData[j].getLastname().length() > 24) {
buffer.append(String.format("%-24s", slData[j]
.getLastname().substring(0, 24)));
} else {
buffer.append(String.format("%-24s", slData[j]
.getLastname()));
}
} else {
buffer.append(String.format("%-24s", " "));
}
break;
}
buffer.append(" ");
}
if (slData[j].getHPhone() != null) {
if (slData[j].getHPhone().length() > 12) {
buffer.append(String.format("%-12s", slData[j].getHPhone()
.substring(0, 12)));
} else {
buffer
.append(String.format("%-12s", slData[j]
.getHPhone()));
}
} else {
buffer.append(String.format("%-12s", " "));
}
buffer.append(" ");
if (slData[j].getOPhone() != null) {
if (slData[j].getOPhone().length() > 14) {
buffer.append(String.format("%-14s\n", slData[j]
.getOPhone().substring(0, 14)));
} else {
buffer.append(String.format("%-14s\n", slData[j]
.getOPhone()));
}
} else {
buffer.append(String.format("%-14s\n", " "));
}
count++;
/*
* End of page reached, print header and reset count, increment
* pageNum
*/
if (count == recordLimit) {
pageNum++;
buffer.append("\n");
buffer.append(getHeaderLine(hdrTitle, pageNum, sortArray));
count = 0;
}
}
/* Paginate */
for (int i = count; i < 60; i++) {
buffer.append("\n");
}
return buffer.toString();
}
/**
* Generate the report.
*
* @param sort
* Which column to sort on
*
* @return
* The text
*/
private String generateReport(int sort) {
StringBuilder buffer = new StringBuilder();
String hdrTitle = "LIST OF LOCATIONS";
// Get the data for the report
StationList[] slData = TextReportDataManager.getInstance()
.getStnListData(sort);
int recordLimit; /* max num records per "8 1/2 x 11" page */
int count = 0; /* for counting the num of records processed so far */
int pageNum = 1;
int[] sortArray = null;
recordLimit = STALIST_RECORD_LIMIT_PER_PAGE;
/* Check sort type. */
switch (sort) {
case TextReportConstants.STALIST_SORTBY_LID:
hdrTitle = TITLE_LID;
sortArray = sortedby_lid;
break;
case TextReportConstants.STALIST_SORTBY_NAME:
hdrTitle = TITLE_NAME;
sortArray = sortedby_name;
break;
case TextReportConstants.STALIST_SORTBY_COUNTY:
hdrTitle = TITLE_COUNTY;
sortArray = sortedby_county;
break;
case TextReportConstants.STALIST_SORTBY_BASIN:
hdrTitle = TITLE_BASIN;
sortArray = sortedby_basin;
break;
case TextReportConstants.STALIST_SORTBY_OBSERVER:
hdrTitle = TITLE_OBSERVER;
sortArray = sortedby_observer;
break;
}
/* Build header line. */
buffer.append(getHeaderLine(hdrTitle, pageNum, sortArray));
/*
* Keep building the list of locations (& headers) for the given
* pageType until there are no more records or until the record_limit is
* reached.
*/
for (int j = 0; j < slData.length; j++) {
/* Write out a single output line as specified by the order. */
buffer.append(" ");
for (int i = 0; i < sortArray.length; i++) {
switch (sortArray[i]) {
case STALIST_LID:
buffer.append(String.format("%-8s", slData[j].getLid()));
break;
case STALIST_NAM:
if (slData[j].getName() != null) {
if (slData[j].getName().length() > 20) {
buffer.append(String.format("%-20s", slData[j]
.getName().substring(0, 20)));
} else {
buffer.append(String.format("%-20s", slData[j]
.getName()));
}
} else {
buffer.append(String.format("%-8s", " "));
}
break;
case STALIST_COU:
buffer
.append(String.format("%-20s", slData[j]
.getCounty()));
break;
case STALIST_BAS:
if (slData[j].getRb() != null) {
if (slData[j].getRb().length() > 20) {
buffer.append(String.format("%-20s", slData[j]
.getRb().substring(0, 20)));
} else {
buffer.append(String.format("%-20s", slData[j]
.getRb()));
}
} else {
buffer.append(String.format("%-20s", " "));
}
break;
case STALIST_WFO:
buffer.append(String.format("%-3s", slData[j].getWfo()));
break;
case STALIST_OBS:
if (slData[j].getLastname() != null) {
if (slData[j].getLastname().length() > 24) {
buffer.append(String.format("%-24s", slData[j]
.getLastname().substring(0, 24)));
} else {
buffer.append(String.format("%-24s", slData[j]
.getLastname()));
}
} else {
buffer.append(String.format("%-24s", " "));
}
break;
}
buffer.append(" ");
}
if (slData[j].getHPhone() != null) {
if (slData[j].getHPhone().length() > 12) {
buffer.append(String.format("%-12s", slData[j].getHPhone()
.substring(0, 12)));
} else {
buffer
.append(String.format("%-12s", slData[j]
.getHPhone()));
}
} else {
buffer.append(String.format("%-12s", " "));
}
buffer.append(" ");
if (slData[j].getOPhone() != null) {
if (slData[j].getOPhone().length() > 14) {
buffer.append(String.format("%-14s\n", slData[j]
.getOPhone().substring(0, 14)));
} else {
buffer.append(String.format("%-14s\n", slData[j]
.getOPhone()));
}
} else {
buffer.append(String.format("%-14s\n", " "));
}
count++;
/*
* End of page reached, print header and reset count, increment
* pageNum
*/
if (count == recordLimit) {
pageNum++;
buffer.append("\n");
buffer.append(getHeaderLine(hdrTitle, pageNum, sortArray));
count = 0;
}
}
/* Paginate */
for (int i = count; i < 60; i++) {
buffer.append("\n");
}
return buffer.toString();
}
/**
* Build the header lines of the report.
*
* @param title
* The page title
* @param pageNum
* The page number
* @return The header lines
*/
private String getHeaderLine(String title, int pageNum, int[] sortArray) {
StringBuffer hdr = new StringBuffer();
hdr.append(" ");
hdr.append(String.format(HDR_FORMAT, getDate(), " ", title, pageNum));
hdr.append("\n\n");
hdr.append(String.format("%-105s %s\n", " ",
"-------PHONE NUMBERS-------\n"));
hdr.append(" ");
for (int i = 0; i < sortArray.length; i++) {
switch (sortArray[i]) {
case STALIST_LID:
hdr.append("LID ");
break;
case STALIST_NAM:
hdr.append("LOCATION ");
break;
case STALIST_COU:
hdr.append("COUNTY ");
break;
case STALIST_BAS:
hdr.append("BASIN ");
break;
case STALIST_WFO:
hdr.append("WFO");
break;
case STALIST_OBS:
hdr.append("OBSERVER ");
break;
}
hdr.append(" ");
}
hdr.append("HOME WORK \n");
hdr.append(" ");
for (int i = 0; i < sortArray.length; i++) {
switch (sortArray[i]) {
case STALIST_LID:
hdr.append("--------");
break;
case STALIST_NAM:
hdr.append("--------------------");
break;
case STALIST_COU:
hdr.append("--------------------");
break;
case STALIST_BAS:
hdr.append("--------------------");
break;
case STALIST_WFO:
hdr.append("---");
break;
case STALIST_OBS:
hdr.append("------------------------");
break;
}
hdr.append(" ");
}
hdr.append("------------ --------------\n");
return hdr.toString();
}
}
|
huaicheng/IODA-SOSP21-AE
|
src/iodaLinux/drivers/gpu/drm/amd/display/dc/dcn10/dcn10_opp.c
|
<gh_stars>1-10
/*
* Copyright 2012-15 Advanced Micro Devices, 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 COPYRIGHT HOLDER(S) OR AUTHOR(S) 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.
*
* Authors: AMD
*
*/
#include "dm_services.h"
#include "dcn10_opp.h"
#include "reg_helper.h"
#define REG(reg) \
(oppn10->regs->reg)
#undef FN
#define FN(reg_name, field_name) \
oppn10->opp_shift->field_name, oppn10->opp_mask->field_name
#define CTX \
oppn10->base.ctx
/************* FORMATTER ************/
/**
* set_truncation
* 1) set truncation depth: 0 for 18 bpp or 1 for 24 bpp
* 2) enable truncation
* 3) HW remove 12bit FMT support for DCE11 power saving reason.
*/
static void set_truncation(
struct dcn10_opp *oppn10,
const struct bit_depth_reduction_params *params)
{
REG_UPDATE_3(FMT_BIT_DEPTH_CONTROL,
FMT_TRUNCATE_EN, params->flags.TRUNCATE_ENABLED,
FMT_TRUNCATE_DEPTH, params->flags.TRUNCATE_DEPTH,
FMT_TRUNCATE_MODE, params->flags.TRUNCATE_MODE);
}
static void set_spatial_dither(
struct dcn10_opp *oppn10,
const struct bit_depth_reduction_params *params)
{
/*Disable spatial (random) dithering*/
REG_UPDATE_7(FMT_BIT_DEPTH_CONTROL,
FMT_SPATIAL_DITHER_EN, 0,
FMT_SPATIAL_DITHER_MODE, 0,
FMT_SPATIAL_DITHER_DEPTH, 0,
FMT_TEMPORAL_DITHER_EN, 0,
FMT_HIGHPASS_RANDOM_ENABLE, 0,
FMT_FRAME_RANDOM_ENABLE, 0,
FMT_RGB_RANDOM_ENABLE, 0);
/* only use FRAME_COUNTER_MAX if frameRandom == 1*/
if (params->flags.FRAME_RANDOM == 1) {
if (params->flags.SPATIAL_DITHER_DEPTH == 0 || params->flags.SPATIAL_DITHER_DEPTH == 1) {
REG_UPDATE_2(FMT_CONTROL,
FMT_SPATIAL_DITHER_FRAME_COUNTER_MAX, 15,
FMT_SPATIAL_DITHER_FRAME_COUNTER_BIT_SWAP, 2);
} else if (params->flags.SPATIAL_DITHER_DEPTH == 2) {
REG_UPDATE_2(FMT_CONTROL,
FMT_SPATIAL_DITHER_FRAME_COUNTER_MAX, 3,
FMT_SPATIAL_DITHER_FRAME_COUNTER_BIT_SWAP, 1);
} else {
return;
}
} else {
REG_UPDATE_2(FMT_CONTROL,
FMT_SPATIAL_DITHER_FRAME_COUNTER_MAX, 0,
FMT_SPATIAL_DITHER_FRAME_COUNTER_BIT_SWAP, 0);
}
/*Set seed for random values for
* spatial dithering for R,G,B channels*/
REG_SET(FMT_DITHER_RAND_R_SEED, 0,
FMT_RAND_R_SEED, params->r_seed_value);
REG_SET(FMT_DITHER_RAND_G_SEED, 0,
FMT_RAND_G_SEED, params->g_seed_value);
REG_SET(FMT_DITHER_RAND_B_SEED, 0,
FMT_RAND_B_SEED, params->b_seed_value);
/* FMT_OFFSET_R_Cr 31:16 0x0 Setting the zero
* offset for the R/Cr channel, lower 4LSB
* is forced to zeros. Typically set to 0
* RGB and 0x80000 YCbCr.
*/
/* FMT_OFFSET_G_Y 31:16 0x0 Setting the zero
* offset for the G/Y channel, lower 4LSB is
* forced to zeros. Typically set to 0 RGB
* and 0x80000 YCbCr.
*/
/* FMT_OFFSET_B_Cb 31:16 0x0 Setting the zero
* offset for the B/Cb channel, lower 4LSB is
* forced to zeros. Typically set to 0 RGB and
* 0x80000 YCbCr.
*/
REG_UPDATE_6(FMT_BIT_DEPTH_CONTROL,
/*Enable spatial dithering*/
FMT_SPATIAL_DITHER_EN, params->flags.SPATIAL_DITHER_ENABLED,
/* Set spatial dithering mode
* (default is Seed patterrn AAAA...)
*/
FMT_SPATIAL_DITHER_MODE, params->flags.SPATIAL_DITHER_MODE,
/*Set spatial dithering bit depth*/
FMT_SPATIAL_DITHER_DEPTH, params->flags.SPATIAL_DITHER_DEPTH,
/*Disable High pass filter*/
FMT_HIGHPASS_RANDOM_ENABLE, params->flags.HIGHPASS_RANDOM,
/*Reset only at startup*/
FMT_FRAME_RANDOM_ENABLE, params->flags.FRAME_RANDOM,
/*Set RGB data dithered with x^28+x^3+1*/
FMT_RGB_RANDOM_ENABLE, params->flags.RGB_RANDOM);
}
static void oppn10_program_bit_depth_reduction(
struct output_pixel_processor *opp,
const struct bit_depth_reduction_params *params)
{
struct dcn10_opp *oppn10 = TO_DCN10_OPP(opp);
set_truncation(oppn10, params);
set_spatial_dither(oppn10, params);
/* TODO
* set_temporal_dither(oppn10, params);
*/
}
/**
* set_pixel_encoding
*
* Set Pixel Encoding
* 0: RGB 4:4:4 or YCbCr 4:4:4 or YOnly
* 1: YCbCr 4:2:2
*/
static void set_pixel_encoding(
struct dcn10_opp *oppn10,
const struct clamping_and_pixel_encoding_params *params)
{
switch (params->pixel_encoding) {
case PIXEL_ENCODING_RGB:
case PIXEL_ENCODING_YCBCR444:
REG_UPDATE(FMT_CONTROL, FMT_PIXEL_ENCODING, 0);
break;
case PIXEL_ENCODING_YCBCR422:
REG_UPDATE(FMT_CONTROL, FMT_PIXEL_ENCODING, 1);
break;
case PIXEL_ENCODING_YCBCR420:
REG_UPDATE(FMT_CONTROL, FMT_PIXEL_ENCODING, 2);
break;
default:
break;
}
}
/**
* Set Clamping
* 1) Set clamping format based on bpc - 0 for 6bpc (No clamping)
* 1 for 8 bpc
* 2 for 10 bpc
* 3 for 12 bpc
* 7 for programable
* 2) Enable clamp if Limited range requested
*/
static void opp_set_clamping(
struct dcn10_opp *oppn10,
const struct clamping_and_pixel_encoding_params *params)
{
REG_UPDATE_2(FMT_CLAMP_CNTL,
FMT_CLAMP_DATA_EN, 0,
FMT_CLAMP_COLOR_FORMAT, 0);
switch (params->clamping_level) {
case CLAMPING_FULL_RANGE:
REG_UPDATE_2(FMT_CLAMP_CNTL,
FMT_CLAMP_DATA_EN, 1,
FMT_CLAMP_COLOR_FORMAT, 0);
break;
case CLAMPING_LIMITED_RANGE_8BPC:
REG_UPDATE_2(FMT_CLAMP_CNTL,
FMT_CLAMP_DATA_EN, 1,
FMT_CLAMP_COLOR_FORMAT, 1);
break;
case CLAMPING_LIMITED_RANGE_10BPC:
REG_UPDATE_2(FMT_CLAMP_CNTL,
FMT_CLAMP_DATA_EN, 1,
FMT_CLAMP_COLOR_FORMAT, 2);
break;
case CLAMPING_LIMITED_RANGE_12BPC:
REG_UPDATE_2(FMT_CLAMP_CNTL,
FMT_CLAMP_DATA_EN, 1,
FMT_CLAMP_COLOR_FORMAT, 3);
break;
case CLAMPING_LIMITED_RANGE_PROGRAMMABLE:
/* TODO */
default:
break;
}
}
static void oppn10_set_dyn_expansion(
struct output_pixel_processor *opp,
enum dc_color_space color_sp,
enum dc_color_depth color_dpth,
enum signal_type signal)
{
struct dcn10_opp *oppn10 = TO_DCN10_OPP(opp);
REG_UPDATE_2(FMT_DYNAMIC_EXP_CNTL,
FMT_DYNAMIC_EXP_EN, 0,
FMT_DYNAMIC_EXP_MODE, 0);
/*00 - 10-bit -> 12-bit dynamic expansion*/
/*01 - 8-bit -> 12-bit dynamic expansion*/
if (signal == SIGNAL_TYPE_HDMI_TYPE_A ||
signal == SIGNAL_TYPE_DISPLAY_PORT ||
signal == SIGNAL_TYPE_DISPLAY_PORT_MST ||
signal == SIGNAL_TYPE_VIRTUAL) {
switch (color_dpth) {
case COLOR_DEPTH_888:
REG_UPDATE_2(FMT_DYNAMIC_EXP_CNTL,
FMT_DYNAMIC_EXP_EN, 1,
FMT_DYNAMIC_EXP_MODE, 1);
break;
case COLOR_DEPTH_101010:
REG_UPDATE_2(FMT_DYNAMIC_EXP_CNTL,
FMT_DYNAMIC_EXP_EN, 1,
FMT_DYNAMIC_EXP_MODE, 0);
break;
case COLOR_DEPTH_121212:
REG_UPDATE_2(FMT_DYNAMIC_EXP_CNTL,
FMT_DYNAMIC_EXP_EN, 1,/*otherwise last two bits are zero*/
FMT_DYNAMIC_EXP_MODE, 0);
break;
default:
break;
}
}
}
static void opp_program_clamping_and_pixel_encoding(
struct output_pixel_processor *opp,
const struct clamping_and_pixel_encoding_params *params)
{
struct dcn10_opp *oppn10 = TO_DCN10_OPP(opp);
opp_set_clamping(oppn10, params);
set_pixel_encoding(oppn10, params);
}
static void oppn10_program_fmt(
struct output_pixel_processor *opp,
struct bit_depth_reduction_params *fmt_bit_depth,
struct clamping_and_pixel_encoding_params *clamping)
{
struct dcn10_opp *oppn10 = TO_DCN10_OPP(opp);
if (clamping->pixel_encoding == PIXEL_ENCODING_YCBCR420)
REG_UPDATE(FMT_MAP420_MEMORY_CONTROL, FMT_MAP420MEM_PWR_FORCE, 0);
/* dithering is affected by <CrtcSourceSelect>, hence should be
* programmed afterwards */
oppn10_program_bit_depth_reduction(
opp,
fmt_bit_depth);
opp_program_clamping_and_pixel_encoding(
opp,
clamping);
return;
}
static void oppn10_set_stereo_polarity(
struct output_pixel_processor *opp,
bool enable, bool rightEyePolarity)
{
struct dcn10_opp *oppn10 = TO_DCN10_OPP(opp);
REG_UPDATE(FMT_CONTROL, FMT_STEREOSYNC_OVERRIDE, enable);
}
/*****************************************/
/* Constructor, Destructor */
/*****************************************/
static void dcn10_opp_destroy(struct output_pixel_processor **opp)
{
kfree(TO_DCN10_OPP(*opp));
*opp = NULL;
}
static struct opp_funcs dcn10_opp_funcs = {
.opp_set_dyn_expansion = oppn10_set_dyn_expansion,
.opp_program_fmt = oppn10_program_fmt,
.opp_program_bit_depth_reduction = oppn10_program_bit_depth_reduction,
.opp_set_stereo_polarity = oppn10_set_stereo_polarity,
.opp_destroy = dcn10_opp_destroy
};
void dcn10_opp_construct(struct dcn10_opp *oppn10,
struct dc_context *ctx,
uint32_t inst,
const struct dcn10_opp_registers *regs,
const struct dcn10_opp_shift *opp_shift,
const struct dcn10_opp_mask *opp_mask)
{
int i;
oppn10->base.ctx = ctx;
oppn10->base.inst = inst;
oppn10->base.funcs = &dcn10_opp_funcs;
oppn10->base.mpc_tree.dpp[0] = inst;
oppn10->base.mpc_tree.mpcc[0] = inst;
oppn10->base.mpc_tree.num_pipes = 1;
for (i = 0; i < MAX_PIPES; i++)
oppn10->base.mpcc_disconnect_pending[i] = false;
oppn10->regs = regs;
oppn10->opp_shift = opp_shift;
oppn10->opp_mask = opp_mask;
}
|
Yangxiaohan0120/LearningJava
|
src/main/java/LeetCode/InsertionSortList.java
|
<filename>src/main/java/LeetCode/InsertionSortList.java
package LeetCode;
/**
* @ author: yxh
* @ created: 2022-02-10 : 4:18 PM
*/
public class InsertionSortList {
// 为一个链表实现插入排序
public InsertionSortList() {
}
}
|
KMDice/kmdice-wallet
|
packages/dice-app/app/containers/App/saga/__tests__/startKMDiceChainSaga.spec.js
|
<filename>packages/dice-app/app/containers/App/saga/__tests__/startKMDiceChainSaga.spec.js<gh_stars>1-10
// @flow
import { fromJS } from 'immutable';
import { runSaga } from 'redux-saga';
import startKMDiceChainSaga from '../startKMDiceChainSaga';
import {
KMDICE_CHAIN_START,
KMDICE_CHAIN_GET_INFO,
KMDICE_CHAIN_START_SUCCESS
} from '../../constants';
import data from '../../../__tests__/app-state.json';
const TIMEOUT = 10 * 100;
describe('containers/App/saga/startKMDiceChainSaga', () => {
it(
'should handle startKMDiceChainSaga correctly',
async done => {
const dispatched = [];
const store = fromJS(data);
const saga = await runSaga(
{
dispatch: action => dispatched.push(action),
getState: () => store
},
startKMDiceChainSaga,
{
type: KMDICE_CHAIN_START,
payload: {}
}
).done;
expect(saga).toEqual(undefined);
expect(dispatched).toEqual([
{ type: KMDICE_CHAIN_GET_INFO },
{
type: KMDICE_CHAIN_START_SUCCESS,
payload: {
pubkey: null
}
}
]);
done();
},
TIMEOUT
);
it(
'should handle startKMDiceChainSaga correctly with pubkey option',
async done => {
const pubkey = 'pubkey';
const dispatched = [];
const store = fromJS(data);
const saga = await runSaga(
{
dispatch: action => dispatched.push(action),
getState: () => store
},
startKMDiceChainSaga,
{
type: KMDICE_CHAIN_START,
payload: {
pubkey
}
}
).done;
expect(saga).toEqual(undefined);
expect(dispatched).toEqual([
{ type: KMDICE_CHAIN_GET_INFO },
{
type: KMDICE_CHAIN_START_SUCCESS,
payload: {
pubkey
}
}
]);
done();
},
TIMEOUT
);
});
|
tg1716/SLAM
|
libs/base/src/utils/CServerTCPSocket_WIN.cpp
|
/* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2017, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include "base-precomp.h" // Precompiled headers
#include <MRPT/config.h>
#ifdef MRPT_OS_WINDOWS
#include <winsock.h>
#if (__BORLANDC__) || (_MSC_VER)
#pragma comment(lib, "WS2_32.LIB")
#endif
#include <mrpt/utils/CServerTCPSocket.h>
#include <mrpt/utils/CClientTCPSocket.h>
#include <mrpt/system/os.h>
using namespace mrpt::utils;
/*---------------------------------------------------------------
Constructor
---------------------------------------------------------------*/
CServerTCPSocket::CServerTCPSocket(
unsigned short listenPort, const std::string& IPaddress,
int maxConnectionsWaiting, mrpt::utils::VerbosityLevel verbosityLevel)
: COutputLogger("CServerTCPSocket")
{
MRPT_START
setVerbosityLevel(verbosityLevel);
// Init the WinSock Library:
// ----------------------------
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD(2, 0);
if (0 != WSAStartup(wVersionRequested, &wsaData))
THROW_EXCEPTION(getLastErrorStr());
// Create the socket and put it listening:
setupSocket(listenPort, IPaddress, maxConnectionsWaiting);
MRPT_END
}
/*---------------------------------------------------------------
Destructor
---------------------------------------------------------------*/
CServerTCPSocket::~CServerTCPSocket()
{
// Delete socket:
if (m_serverSock != INVALID_SOCKET) closesocket(m_serverSock);
WSACleanup();
}
#endif // MRPT_OS_WINDOWS
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.