repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
jhostyk/atav
|
src/main/java/function/external/primateai/PrimateAICommand.java
|
package function.external.primateai;
import global.Data;
/**
*
* @author nick
*/
public class PrimateAICommand {
public static boolean isListPrimateAI = false;
public static boolean isIncludePrimateAI = false;
// filter option
public static float minPrimateAI = Data.NO_FILTER;
public static boolean isMinPrimateAIValid(float value) {
if (minPrimateAI == Data.NO_FILTER) {
return true;
}
return value >= minPrimateAI
|| value == Data.FLOAT_NA;
}
}
|
maxgram/react-saga-universal
|
config/server/server.dev.js
|
import express from 'express'
import path from 'path'
import webpack from 'webpack'
import webpackDevMiddleware from 'webpack-dev-middleware'
import webpackHotMiddleware from 'webpack-hot-middleware'
import { renderDom } from '../../src/html'
// const DEV_HOST = process.env.HOST
// const DEV_PORT = process.env.PORT
const PORT = process.env.PORT
const CWD = process.cwd()
const config = require('../webpack/config.dev')
const compiler = webpack(config)
const app = express()
app.use(webpackDevMiddleware(compiler, {
stats: 'minimal',
publicPath: config.output.publicPath,
}))
app.use(webpackHotMiddleware(compiler, {
log: console.log,
path: "/__webpack_hmr",
heartbeat: 10000
}))
app.use('/static', express.static(path.resolve(CWD, './static/')))
app.use('/dist', express.static(path.resolve(CWD, './dist/')))
app.get('/favicon.ico', (req, res) => {res.send(204)})
app.get(/.*/, (req, res) => {res.end(renderDom(''))})
// server.listen(DEV_PORT, DEV_HOST, () => {
// console.log('Node Express Server is running on http://%s:%s', DEV_HOST, DEV_PORT)
// })
app.listen(PORT, (error) => {
if (error) console.error(error)
else console.info(`App is UP on port ${PORT}!\n`)
})
|
wied03/ansible-ruby
|
lib/ansible/ruby/modules/generated/network/nxos/nxos_udld.rb
|
# frozen_string_literal: true
# See LICENSE.txt at root of repository
# GENERATED FILE - DO NOT EDIT!!
require 'ansible/ruby/modules/base'
module Ansible
module Ruby
module Modules
# Manages UDLD global configuration params.
class Nxos_udld < Base
# @return [:enabled, :disabled, nil] Toggles aggressive mode.
attribute :aggressive
validates :aggressive, expression_inclusion: {:in=>[:enabled, :disabled], :message=>"%{value} needs to be :enabled, :disabled"}, allow_nil: true
# @return [Integer, nil] Message time in seconds for UDLD packets or keyword 'default'.
attribute :msg_time
validates :msg_time, type: Integer
# @return [:yes, :no, nil] Ability to reset all ports shut down by UDLD. 'state' parameter cannot be 'absent' when this is present.
attribute :reset
validates :reset, expression_inclusion: {:in=>[:yes, :no], :message=>"%{value} needs to be :yes, :no"}, allow_nil: true
# @return [:present, :absent, nil] Manage the state of the resource. When set to 'absent', aggressive and msg_time are set to their default values.
attribute :state
validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>"%{value} needs to be :present, :absent"}, allow_nil: true
end
end
end
end
|
malston/spring-credhub
|
spring-credhub-core/src/main/java/org/springframework/credhub/core/certificate/ReactiveCredHubCertificateTemplate.java
|
<reponame>malston/spring-credhub<gh_stars>0
/*
* Copyright 2016-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*/
package org.springframework.credhub.core.certificate;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.credhub.core.ExceptionUtils;
import org.springframework.credhub.core.ReactiveCredHubOperations;
import org.springframework.credhub.support.CredentialName;
import org.springframework.credhub.support.certificate.CertificateCredentialDetails;
import org.springframework.credhub.support.certificate.CertificateSummary;
import org.springframework.credhub.support.certificate.CertificateSummaryData;
import org.springframework.http.HttpStatus;
import org.springframework.util.Assert;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Implements the interactions with CredHub to retrieve, regenerate, and update
* certificates.
*
* @author <NAME>
*/
public class ReactiveCredHubCertificateTemplate implements ReactiveCredHubCertificateOperations {
private static final String BASE_URL_PATH = "/api/v1/certificates";
private static final String NAME_URL_QUERY = BASE_URL_PATH + "?name={name}";
private static final String REGENERATE_URL_PATH = BASE_URL_PATH + "/{id}/regenerate";
private static final String UPDATE_TRANSITIONAL_URL_PATH = BASE_URL_PATH + "/{id}/update_transitional_version";
private static final String BULK_REGENERATE_URL_PATH = "/api/v1/bulk-regenerate";
private static final String TRANSITIONAL_REQUEST_FIELD = "set_as_transitional";
private static final String VERSION_REQUEST_FIELD = "version";
private static final String SIGNED_BY_REQUEST_FIELD = "signed_by";
private static final String REGENERATED_CREDENTIALS_RESPONSE_FIELD = "regenerated_credentials";
private ReactiveCredHubOperations credHubOperations;
/**
* Create a new {@link ReactiveCredHubCertificateTemplate}.
*
* @param credHubOperations the {@link ReactiveCredHubOperations} to use for interactions with CredHub
*/
public ReactiveCredHubCertificateTemplate(ReactiveCredHubOperations credHubOperations) {
this.credHubOperations = credHubOperations;
}
@Override
public Flux<CertificateSummary> getAll() {
return credHubOperations.doWithWebClient(webClient -> webClient
.get()
.uri(BASE_URL_PATH)
.retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError)
.bodyToMono(CertificateSummaryData.class)
.flatMapMany(data -> Flux.fromIterable(data.getCertificates())));
}
@Override
public Mono<CertificateSummary> getByName(final CredentialName name) {
Assert.notNull(name, "certificate name must not be null");
return credHubOperations.doWithWebClient(webClient -> webClient
.get()
.uri(NAME_URL_QUERY, name.getName())
.retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError)
.bodyToMono(CertificateSummaryData.class)
.flatMapMany(data -> Flux.fromIterable(data.getCertificates())))
.single();
}
@Override
public Mono<CertificateCredentialDetails> regenerate(final String id, final boolean setAsTransitional) {
Assert.notNull(id, "credential ID must not be null");
final ParameterizedTypeReference<CertificateCredentialDetails> ref =
new ParameterizedTypeReference<CertificateCredentialDetails>() {};
Map<String, Boolean> request = new HashMap<>(1);
request.put(TRANSITIONAL_REQUEST_FIELD, setAsTransitional);
return credHubOperations.doWithWebClient(webClient -> webClient
.post()
.uri(REGENERATE_URL_PATH, id)
.syncBody(request)
.retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError)
.bodyToMono(ref));
}
@Override
public Flux<CredentialName> regenerate(final CredentialName certificateName) {
Assert.notNull(certificateName, "certificate name must not be null");
final ParameterizedTypeReference<Map<String, List<CredentialName>>> ref =
new ParameterizedTypeReference<Map<String, List<CredentialName>>>() {};
Map<String, Object> request = new HashMap<>(1);
request.put(SIGNED_BY_REQUEST_FIELD, certificateName.getName());
return credHubOperations.doWithWebClient(webClient -> webClient
.post()
.uri(BULK_REGENERATE_URL_PATH)
.syncBody(request)
.retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError)
.bodyToFlux(ref)
.flatMap(body -> Flux.fromIterable(body.get(REGENERATED_CREDENTIALS_RESPONSE_FIELD))));
}
public Flux<CertificateCredentialDetails> updateTransitionalVersion(final String id,
final String versionId) {
Assert.notNull(id, "credential ID must not be null");
Map<String, String> request = new HashMap<>(1);
request.put(VERSION_REQUEST_FIELD, versionId);
return credHubOperations.doWithWebClient(webClient -> webClient
.put()
.uri(UPDATE_TRANSITIONAL_URL_PATH, id)
.syncBody(request)
.retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError)
.bodyToFlux(CertificateCredentialDetails.class));
}
}
|
fstabin/fsGuns
|
src/fsGuns/Permissions.java
|
package fsGuns;
public class Permissions {
static public final String command_browse = "fsguns.command.browse";
static public final String command_workbench = "fsguns.command.workbench";
static public final String command_set_firemode = "fsguns.command.set_firemode";
static public final String command_reload = "fsguns.command.reload";
static public final String fire = "fsguns.fire";
}
|
filfreire/questions-three
|
tests/reporters/junit_reporter/test_report_building.py
|
from copy import copy
from datetime import datetime
from unittest import TestCase, main
from expects import expect, contain, equal, end_with, have_length
import junit_xml
from twin_sister import open_dependency_context
from questions_three.constants import TestEvent, TestStatus
from questions_three.event_broker import EventBroker
from questions_three.reporters.junit_reporter import JunitReporter
from questions_three.reporters.result_compiler.suite_results import SuiteResults, TestResult
from twin_sister.fakes import FakeDatetime, MasterSpy
from questions_three.vanilla import format_exception
def return_empty_string(*args, **kwargs):
return ""
class TestReportBuilding(TestCase):
def setUp(self):
EventBroker.reset()
self.context = open_dependency_context()
defanged = copy(junit_xml.TestSuite)
defanged.to_xml_string = return_empty_string
self.spy = MasterSpy(defanged, affect_only_functions=False)
self.context.inject(junit_xml.TestSuite, self.spy)
self.results = SuiteResults()
self.sut = JunitReporter()
self.sut.activate()
def tearDown(self):
self.context.close()
def publish_results(self):
EventBroker.publish(event=TestEvent.suite_results_compiled, suite_results=self.results)
def retrieve_report(self):
# Our master spy monitors the TestSuite class,
# so each of its return value spies monitors an instance of the class.
spies = self.spy.return_value_spies
# We expect only one instance to have been created
expect(spies).to(have_length(1))
return spies[0].unwrap_spy_target()
def test_sets_suite_name(self):
expected = "Dingo"
self.results.suite_name = expected
self.publish_results()
report = self.retrieve_report()
expect(report.name).to(end_with(expected))
def test_sets_suite_timestamp_to_suite_start_time(self):
expected = datetime.fromtimestamp(1516899650.147505)
fake_time = FakeDatetime()
fake_time.fixed_time = expected
self.context.inject(datetime, fake_time)
self.publish_results()
report = self.retrieve_report()
expect(report.timestamp).to(equal(expected.isoformat()))
def test_adds_correct_number_of_test_cases(self):
expected = 42
self.results.tests = [TestResult(test_name=str(n)) for n in range(expected)]
self.publish_results()
report = self.retrieve_report()
expect(report.test_cases).to(have_length(expected))
def test_sets_test_name(self):
expected = "Son of SPAM"
self.results.tests = [TestResult(test_name=expected)]
self.publish_results()
report = self.retrieve_report()
expect(report.test_cases).to(have_length(1))
expect(report.test_cases[0].name).to(equal(expected))
def test_sets_test_timestamp_to_test_start_time(self):
expected = datetime.fromtimestamp(1516900087.97135)
result = TestResult(test_name="spam")
result.start_time = expected
self.results.tests = [result]
self.publish_results()
report = self.retrieve_report()
expect(report.test_cases[0].timestamp).to(equal(expected.isoformat()))
def test_sets_test_elapsed_sec(self):
start_time = datetime.fromtimestamp(1516900087.97135)
end_time = datetime.fromtimestamp(1516900089.52436)
result = TestResult(test_name="bacon")
result.start_time = start_time
result.end_time = end_time
self.results.tests = [result]
self.publish_results()
report = self.retrieve_report()
expect(report.test_cases[0].elapsed_sec).to(equal((end_time - start_time).total_seconds()))
def test_does_not_set_status_for_passed_test(self):
result = TestResult(test_name="spam")
result.status = TestStatus.passed
self.results.tests = [result]
self.publish_results()
report = self.retrieve_report()
expect(report.test_cases).to(have_length(1))
expect(report.test_cases[0].status).to(equal(None))
def test_sets_status_for_failed_test(self):
result = TestResult(test_name="spam")
result.status = TestStatus.failed
self.results.tests = [result]
self.publish_results()
report = self.retrieve_report()
expect(report.test_cases).to(have_length(1))
expect(report.test_cases[0].status).to(equal("failure"))
def test_sets_status_for_errant_test(self):
result = TestResult(test_name="spam")
result.status = TestStatus.erred
self.results.tests = [result]
self.publish_results()
report = self.retrieve_report()
expect(report.test_cases).to(have_length(1))
expect(report.test_cases[0].status).to(equal("error"))
def test_sets_status_for_skipped_test(self):
result = TestResult(test_name="spam")
result.status = TestStatus.skipped
self.results.tests = [result]
self.publish_results()
report = self.retrieve_report()
expect(report.test_cases).to(have_length(1))
expect(report.test_cases[0].status).to(equal("skipped"))
def test_does_not_set_error_message_for_passed_test(self):
result = TestResult(test_name="spam")
result.status = TestStatus.passed
self.results.tests = [result]
self.publish_results()
report = self.retrieve_report()
expect(report.test_cases).to(have_length(1))
expect(report.test_cases[0].error_message).to(equal(None))
def test_does_not_set_failure_message_for_passed_test(self):
result = TestResult(test_name="spam")
result.status = TestStatus.passed
self.results.tests = [result]
self.publish_results()
report = self.retrieve_report()
expect(report.test_cases).to(have_length(1))
expect(report.test_cases[0].failure_message).to(equal(None))
def test_sets_message_for_failed_test(self):
expected = "I broke it real good"
result = TestResult(test_name="spam")
result.status = TestStatus.failed
result.exception = Exception(expected)
self.results.tests = [result]
self.publish_results()
report = self.retrieve_report()
expect(report.test_cases).to(have_length(1))
expect(report.test_cases[0].failure_message).to(contain(expected))
def test_sets_output_for_failed_test(self):
exception = RuntimeError("Failed intentionally")
result = TestResult(test_name="spam")
result.status = TestStatus.failed
result.exception = exception
self.results.tests = [result]
self.publish_results()
report = self.retrieve_report()
expect(report.test_cases).to(have_length(1))
expect(report.test_cases[0].failure_output).to(contain(format_exception(exception)))
def test_sets_message_for_errant_test(self):
expected = "I tried to think but nothing happened"
result = TestResult(test_name="spam")
result.status = TestStatus.erred
result.exception = Exception(expected)
self.results.tests = [result]
self.publish_results()
report = self.retrieve_report()
expect(report.test_cases).to(have_length(1))
expect(report.test_cases[0].error_message).to(contain(expected))
def test_sets_output_for_errant_test(self):
exception = RuntimeError("Failed intentionally")
result = TestResult(test_name="spam")
result.status = TestStatus.erred
result.exception = exception
self.results.tests = [result]
self.publish_results()
report = self.retrieve_report()
expect(report.test_cases).to(have_length(1))
expect(report.test_cases[0].error_output).to(contain(format_exception(exception)))
def test_sets_message_for_skipped_test(self):
expected = "Run away!"
result = TestResult(test_name="spam")
result.status = TestStatus.skipped
result.exception = Exception(expected)
self.results.tests = [result]
self.publish_results()
report = self.retrieve_report()
expect(report.test_cases).to(have_length(1))
expect(report.test_cases[0].skipped_message).to(contain(expected))
def test_does_not_set_output_for_skipped_test(self):
exception = RuntimeError("Failed intentionally")
result = TestResult(test_name="spam")
result.status = TestStatus.skipped
result.exception = exception
self.results.tests = [result]
self.publish_results()
report = self.retrieve_report()
expect(report.test_cases).to(have_length(1))
expect(report.test_cases[0].skipped_output).to(equal(None))
if "__main__" == __name__:
main()
|
mschmidt271/Tines
|
src/core/sacado/Sacado_SFINAE_Macros.hpp
|
// @HEADER
// ***********************************************************************
//
// Sacado Package
// Copyright (2006) Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// This library 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 2.1 of the
// License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
// USA
// Questions? Contact <NAME> (<EMAIL>) or <NAME>
// (<EMAIL>).
//
// ***********************************************************************
// @HEADER
#ifndef SACADO_SFINAE_MACROS_H
#define SACADO_SFINAE_MACROS_H
#include "Sacado_mpl_enable_if.hpp"
#include "Sacado_mpl_disable_if.hpp"
#include "Sacado_mpl_is_same.hpp"
#include "Sacado_mpl_is_convertible.hpp"
#include "Sacado_mpl_type_wrap.hpp"
/* Define some macros useful for disabling template function overloads */
#define SACADO_ENABLE_IF_SAME(TYPE1, TYPE2, RETURN_TYPE) \
typename mpl::enable_if_c<mpl::is_convertible< TYPE1 , TYPE2 >::value && ExprLevel<TYPE1>::value == ExprLevel<TYPE2>::value, RETURN_TYPE >::type
#define SACADO_ENABLE_EXPR_FUNC(RETURN_TYPE) \
SACADO_ENABLE_IF_SAME(typename Expr<S>::value_type, value_type, RETURN_TYPE)
#define SACADO_ENABLE_EXPR_CTOR_DEF SACADO_ENABLE_EXPR_FUNC(void*)
#define SACADO_ENABLE_EXPR_CTOR_DECL SACADO_ENABLE_EXPR_CTOR_DEF = 0
#define SACADO_FAD_ENABLE_EXPR_FUNC \
SACADO_ENABLE_IF_SAME(typename Expr<S>::value_type, typename FAD::value_type, FAD&)
#define SACADO_EXP_ENABLE_EXPR_FUNC(RETURN_TYPE) \
SACADO_ENABLE_IF_SAME(typename Expr<S>::derived_type::value_type, value_type, RETURN_TYPE)
#define SACADO_EXP_ENABLE_EXPR_CTOR_DEF \
typename mpl::enable_if_c< \
mpl::is_convertible< typename Expr<S>::derived_type::value_type , \
value_type >::value && \
(ExprLevel< typename Expr<S>::derived_type::value_type >::value == \
ExprLevel< value_type >::value) && \
!is_view, void* >::type
#define SACADO_EXP_ENABLE_EXPR_CTOR_DECL SACADO_EXP_ENABLE_EXPR_CTOR_DEF = 0
#define SACADO_FAD_EXP_ENABLE_EXPR_FUNC \
SACADO_ENABLE_IF_SAME(typename Expr<S>::derived_type::value_type, typename FAD::value_type, FAD&)
#define SACADO_ENABLE_IF_CONVERTIBLE(TYPE1, TYPE2, RETURN_TYPE) \
typename Sacado::mpl::enable_if<Sacado::mpl::is_convertible< TYPE1 , TYPE2 >, RETURN_TYPE >::type
#define SACADO_ENABLE_VALUE_FUNC(RETURN_TYPE) \
SACADO_ENABLE_IF_CONVERTIBLE(S, value_type, RETURN_TYPE)
#define SACADO_ENABLE_VALUE_CTOR_DEF SACADO_ENABLE_VALUE_FUNC(void*)
#define SACADO_ENABLE_VALUE_CTOR_DECL SACADO_ENABLE_VALUE_CTOR_DEF = 0
#define SACADO_EXP_ENABLE_VALUE_CTOR_DEF \
typename mpl::enable_if_c< \
Sacado::mpl::is_convertible< S , value_type >::value && \
!is_view, void* >::type
#define SACADO_EXP_ENABLE_VALUE_CTOR_DECL SACADO_EXP_ENABLE_VALUE_CTOR_DEF = 0
#define SACADO_FAD_OP_ENABLE_EXPR_EXPR(OP) \
typename mpl::enable_if_c< IsFadExpr<T1>::value && IsFadExpr<T2>::value && \
ExprLevel<T1>::value == ExprLevel<T2>::value, \
Expr< OP< T1, T2 > > \
>::type
#define SACADO_FAD_EXP_OP_ENABLE_EXPR_EXPR(OP) \
typename mpl::enable_if_c< IsFadExpr<T1>::value && IsFadExpr<T2>::value && \
ExprLevel<T1>::value == ExprLevel<T2>::value, \
OP< typename Expr<T1>::derived_type, typename Expr<T2>::derived_type, false, false, typename T1::expr_spec_type > \
>::type
#define SACADO_FAD_OP_ENABLE_SCALAR_EXPR(OP) \
typename mpl::disable_if<mpl::is_same< typename Expr<T>::value_type, typename Expr<T>::scalar_type>, Expr< OP< ConstExpr<typename Expr<T>::scalar_type>, Expr<T> > > >::type
#define SACADO_FAD_OP_ENABLE_EXPR_SCALAR(OP) \
typename mpl::disable_if<mpl::is_same< typename Expr<T>::value_type, typename Expr<T>::scalar_type>, Expr< OP< Expr<T>, ConstExpr<typename Expr<T>::scalar_type> > > >::type
#define SACADO_FAD_EXP_OP_ENABLE_SCALAR_EXPR(OP) \
typename mpl::disable_if<mpl::is_same< typename T::value_type, typename T::scalar_type>, OP< typename T::scalar_type, typename Expr<T>::derived_type, true, false, typename T::expr_spec_type > >::type
#define SACADO_FAD_EXP_OP_ENABLE_EXPR_SCALAR(OP) \
typename mpl::disable_if<mpl::is_same< typename T::value_type, typename T::scalar_type>, OP< typename Expr<T>::derived_type, typename T::scalar_type, false, true, typename T::expr_spec_type > >::type
#endif // SACADO_SFINAE_MACROS_H
|
V-yg/BgMan
|
src/main/java/com/yiie/exceptions/RestExceptionHandler.java
|
package com.yiie.exceptions;
import com.yiie.enums.BaseResponseCode;
import com.yiie.utils.DataResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.List;
/**
* Time:2020-1-2 13:57
* Email: <EMAIL>
* Desc:controller 层全局异常统一处理类
*
* @author: yiie
* @version:1.0.0
*/
@RestControllerAdvice
@Slf4j
public class RestExceptionHandler {
/**
* 系统繁忙
* @param e
* @param <T>
* @return
*/
@ExceptionHandler(Exception.class)
public <T> DataResult<T> handleException(Exception e){
log.error("Exception,exception:{}", e);
return DataResult.getResult(BaseResponseCode.SYSTEM_BUSY);
}
/**
* 自定义全局异常处理
* @param e
* @param <T>
* @return
*/
@ExceptionHandler(value = BusinessException.class)
<T> DataResult<T> businessExceptionHandler(BusinessException e) {
log.error("BusinessException,exception:{}", e);
return new DataResult<>(e.getMessageCode(),e.getDetailMessage());
}
/**
* 没有权限 403
* @param e
* @param <T>
* @return
*/
@ExceptionHandler(value = AuthorizationException.class)
public <T> DataResult<T> erroPermission(AuthorizationException e){
log.error("BusinessException,exception:{}", e);
return new DataResult<>(BaseResponseCode.UNAUTHORIZED_ERROR);
}
/**
* 处理validation 框架异常
* @param e
* @param <T>
* @return
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
<T> DataResult<T> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
log.error("methodArgumentNotValidExceptionHandler bindingResult.allErrors():{},exception:{}", e.getBindingResult().getAllErrors(), e);
List<ObjectError> errors = e.getBindingResult().getAllErrors();
return createValidExceptionResp(errors);
}
private <T> DataResult<T> createValidExceptionResp(List<ObjectError> errors) {
String[] msgs = new String[errors.size()];
int i = 0;
for (ObjectError error : errors) {
msgs[i] = error.getDefaultMessage();
log.info("msg={}",msgs[i]);
i++;
}
return DataResult.getResult(BaseResponseCode.METHODARGUMENTNOTVALIDEXCEPTION.getCode(), msgs[0]);
}
}
|
PythonCoderAS/Hondana
|
tests/test_client.py
|
from __future__ import annotations
import pathlib
from hondana.client import Client
TOKEN_PATH: pathlib.Path = pathlib.Path(__file__).parent / ".client_refresh_token"
def clone_client(auth: bool = False) -> Client:
if auth is True:
return Client(username="Test", password="<PASSWORD>")
return Client()
class TestClient:
def test_auth(self):
client = clone_client()
assert client._http._authenticated is False
assert client._http.username is None
assert client._http.password is None
client.login(username="Test", password="<PASSWORD>")
assert client._http._authenticated is True
assert client._http.username is not None
assert client._http.password is not None
def test_refresh_token_dump(self):
client = clone_client(auth=True)
token = "<PASSWORD>"
client._http._refresh_token = token
client.dump_refresh_token(file=True, path=TOKEN_PATH, mode="w")
with open(TOKEN_PATH) as fp:
text = fp.read()
assert text == token
TOKEN_PATH.unlink(missing_ok=True)
|
isabella232/stdcxx
|
tests/regress/23.vector.cons.stdcxx-294.cpp
|
/************************************************************************
*
* 23.vector.cons.stdcxx-294.cpp - regression test for STDCXX-294
*
* http://issues.apache.org/jira/browse/STDCXX-294
*
* $Id$
*
***************************************************************************
*
* 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 <assert.h>
#include <vector>
int main()
{
static const int a[] = { 1, 2, 3, 4, 5 };
std::vector<int> v (a, a + sizeof a / sizeof *a);
v.insert (v.begin () + 2, 2, -1);
static const int b[] = { 1, 2, -1, -1, 3, 4, 5 };
const int pass = v == std::vector<int>(b, b + sizeof b / sizeof *b);
assert (pass);
return 1 - pass;
}
|
windows-development/Windows-classic-samples
|
Samples/Win7Samples/winui/RegisterHotKey/RegisterHotKey.cpp
|
<reponame>windows-development/Windows-classic-samples
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (C) 2008 Microsoft Corporation. All rights reserved.
//
// The following example shows how to use the RegisterHotKey function with the MOD_NOREPEAT flag.
// In this example, the hotkey 'ALT+b' is registered for the main thread. When the hotkey is pressed,
// the thread will receive a WM_HOTKEY message, which will get picked up in the GetMessage call.
// Because this example uses MOD_ALT with the MOD_NOREPEAT value for fsModifiers, the thread will
// only receive another WM_HOTKEY message when the 'b' key is released and then pressed again while
// the 'ALT' key is being pressed down.
//
#include <windows.h>
#include <stdio.h>
int wmain(int argc, wchar_t *argv[])
{
if (RegisterHotKey(NULL, 1, MOD_ALT | MOD_NOREPEAT, 0x42)) //0x42 is 'b'
{
wprintf(L"Hotkey 'alt+b' registered, using MOD_NOREPEAT flag\n");
}
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
if (msg.message == WM_HOTKEY)
{
wprintf(L"WM_HOTKEY received\n");
}
}
return 0;
}
|
mthli/Type
|
app/src/main/java/io/github/mthli/type/event/BlockEvent.java
|
/*
* Copyright 2016 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package io.github.mthli.type.event;
public class BlockEvent {
private boolean isBullet;
private boolean isQuote;
public BlockEvent() {}
public BlockEvent(boolean isBullet, boolean isQuote) {
this.isBullet = isBullet;
this.isQuote = isQuote;
}
public boolean isBullet() {
return isBullet;
}
public void setBullet(boolean isBullet) {
this.isBullet = isBullet;
}
public boolean isQuote() {
return isQuote;
}
public void setQuote(boolean isQuote) {
this.isQuote = isQuote;
}
}
|
leo0228/U8Project
|
u8sdk_baidu/src/main/java/com/u8/sdk/BaiduApplication.java
|
<gh_stars>1-10
package com.u8.sdk;
import com.baidu.gamesdk.BDGameSDK;
import com.baidu.sapi2.base.debug.Log;
import com.tendcloud.tenddata.TalkingDataGA;
import android.content.Context;
import android.content.res.Configuration;
/***
* Baidu SDK 需要自定义的Application,同时需要配置到SDK_Manifest.xml中
*
*/
public class BaiduApplication implements IApplicationListener{
//U8Application
@Override
public void onProxyCreate() {
BDGameSDK.initApplication(U8SDK.getInstance().getApplication());
SDKParams params = U8SDK.getInstance().getSDKParams();
String talkingAppid = params.getString("TALKING_APPID");
String talkingChannel = params.getString("TALKING_CHANNEL");
Log.e("bdsdk", "TALKING_APPID" + params.getString("TALKING_APPID"));
TalkingDataGA.init(U8SDK.getInstance().getApplication(), talkingAppid, talkingChannel);
// try{
// Class<?> clazz = Class.forName("com.baidu.gamesdk.BDGameSDK");
// Method m = clazz.getMethod("initApplication", Application.class);
// m.invoke(null, U8SDK.getInstance().getApplication());
// }catch(Exception e){
// e.printStackTrace();
// }
}
@Override
public void onProxyAttachBaseContext(Context base) {
}
@Override
public void onProxyConfigurationChanged(Configuration config) {
}
@Override
public void onProxyTerminate() {
// TODO Auto-generated method stub
}
}
|
graphiteSWE/TestFolder
|
DeSpeect/Model/SpeectWrapper/src/configuration.cpp
|
#include "configuration.h"
//initialize the configuration as empty string and say that all configuration where never asked
Configuration::Configuration()
:config(std::vector<std::string>())
,changed(std::vector<bool>())
{
for(int i=0;i<MAXSIZE;++i)
{
config.push_back(std::string(""));
changed.push_back(true);
}
}
//set the new string in the right place and tell that the string could be different
bool Configuration::setConfig(Configuration::configName name,const std::string& Data)
{
if(name!=MAXSIZE)
{
config[name]=Data;
changed[name]=true;
return true;
}
return false;
}
//return if the string in the name could be changed since last get
bool Configuration::hasChanged(Configuration::configName name)
{
return changed[name];
}
//return the string and tell that is same as last get
const std::string& Configuration::getConfig(Configuration::configName name)
{
if(name!=MAXSIZE)
{
changed[name]=false;
return config[name];
}
}
|
Falcort/CPOA
|
src/metier/Photo.java
|
package metier;
public class Photo
{
private int IDPhoto;
private String placePhoto;
private int yearPhoto;
private String wayPhoto;
public Photo(int IDPhoto, String placePhoto, int yearPhoto, String wayPhoto)
{
this.IDPhoto = IDPhoto;
this.placePhoto = placePhoto;
this.yearPhoto = yearPhoto;
this.wayPhoto = wayPhoto;
}
public Photo()
{
}
public void setIDPhoto(int IDPhoto) {
this.IDPhoto = IDPhoto;
}
public int getIDPhoto() {
return IDPhoto;
}
public String getPlacePhoto() {
return placePhoto;
}
public int getYearPhoto() {
return yearPhoto;
}
public String getWayPhoto() {
return wayPhoto;
}
public void setPlacePhoto(String placePhoto) {
this.placePhoto = placePhoto;
}
public void setYearPhoto(int yearPhoto) {
this.yearPhoto = yearPhoto;
}
public void setWayPhoto(String wayPhoto) {
this.wayPhoto = wayPhoto;
}
}
|
XuanYuan1122/momole
|
app/src/main/java/com/moemoe/lalala/view/widget/map/utils/GeoUtils.java
|
/*************************************************************************
* Copyright (c) 2015 Lemberg Solutions
*
* 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.moemoe.lalala.view.widget.map.utils;
import android.graphics.Point;
import android.location.Location;
import android.util.Log;
import com.moemoe.lalala.view.widget.map.MapWidget;
public class GeoUtils
{
/**
* Helper function to translate position on the map to geographic coordinates. Map should be calibrated in order for
* this method to take effect. Result will be returned in last parameter.
* @param v - com.ls.MapWidget
* @param x - x coordinate in map coordinate system.
* @param y - y coordinate in map coordinate system.
* @param location - out parameter. Will contain latitude and longitude of point on the map.
*/
public static void translate(MapWidget v, int x, int y, Location location)
{
MapCalibrationData calibration = v.getConfig().getGpsConfig().getCalibration();
if (calibration == null) {
Log.w("GeoUtils", "Can't translate. No calibration data!");
}
calibration.translate(x, y, location);
}
/**
* Helper function to convert position on the map to geographic coordinates. Result will be returned in last parameter.
* @param v - com.ls.MapWidget
* @param point - position on the map in pixels. Instance of android.graphics.Point
* @param location - out parameter. Will contain latitude and longitude of point on the map.
*/
public static void translate(MapWidget v, Point point, Location location)
{
MapCalibrationData calibration = v.getConfig().getGpsConfig().getCalibration();
if (calibration == null) {
Log.w("GeoUtils", "Can't translate. No calibration data!");
}
calibration.translate(point.x, point.y, location);
}
/**
* Converts location to position on the map. Result will be returned in last parameter.
* @param v - com.ls.MapWidget
* @param location instance of android.location.Location object.
* @param position - out parameter. Can be null.
* @return returns the same object that was passed as position, or if it is null - returns new Point object.
*/
public static void translate(MapWidget v, Location location, Point point)
{
MapCalibrationData calibration = v.getConfig().getGpsConfig().getCalibration();
if (calibration == null) {
Log.w("GeoUtils", "Can't translate. No calibration data!");
}
calibration.translate(location, point);
}
}
|
cashmerepipeline/CashmereRez
|
Packages/arch/AMD64/package.py
|
# -*- coding: utf-8 -*-
name = 'arch'
version = 'AMD64'
|
faraz891/gitlabhq
|
spec/services/packages/nuget/search_service_spec.rb
|
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe Packages::Nuget::SearchService do
let_it_be(:user) { create(:user) }
let_it_be(:group) { create(:group) }
let_it_be(:subgroup) { create(:group, parent: group) }
let_it_be(:project) { create(:project, namespace: subgroup) }
let_it_be(:package_a) { create(:nuget_package, project: project, name: 'DummyPackageA') }
let_it_be(:packages_b) { create_list(:nuget_package, 5, project: project, name: 'DummyPackageB') }
let_it_be(:packages_c) { create_list(:nuget_package, 5, project: project, name: 'DummyPackageC') }
let_it_be(:package_d) { create(:nuget_package, project: project, name: 'FooBarD') }
let_it_be(:other_package_a) { create(:nuget_package, name: 'DummyPackageA') }
let_it_be(:other_package_a) { create(:nuget_package, name: 'DummyPackageB') }
let(:search_term) { 'ummy' }
let(:per_page) { 5 }
let(:padding) { 0 }
let(:include_prerelease_versions) { true }
let(:options) { { include_prerelease_versions: include_prerelease_versions, per_page: per_page, padding: padding } }
describe '#execute' do
subject { described_class.new(user, target, search_term, options).execute }
shared_examples 'handling all the conditions' do
it { expect_search_results 3, package_a, packages_b, packages_c }
context 'with a smaller per page count' do
let(:per_page) { 2 }
it { expect_search_results 3, package_a, packages_b }
end
context 'with 0 per page count' do
let(:per_page) { 0 }
it { expect_search_results 3, [] }
end
context 'with a negative per page count' do
let(:per_page) { -1 }
it { expect { subject }.to raise_error(ArgumentError, 'negative per_page') }
end
context 'with a padding' do
let(:padding) { 2 }
it { expect_search_results 3, packages_c }
end
context 'with a too big padding' do
let(:padding) { 5 }
it { expect_search_results 3, [] }
end
context 'with a negative padding' do
let(:padding) { -1 }
it { expect { subject }.to raise_error(ArgumentError, 'negative padding') }
end
context 'with search term' do
let(:search_term) { 'umm' }
it { expect_search_results 3, package_a, packages_b, packages_c }
end
context 'with nil search term' do
let(:search_term) { nil }
it { expect_search_results 4, package_a, packages_b, packages_c, package_d }
end
context 'with empty search term' do
let(:search_term) { '' }
it { expect_search_results 4, package_a, packages_b, packages_c, package_d }
end
context 'with prefix search term' do
let(:search_term) { 'dummy' }
it { expect_search_results 3, package_a, packages_b, packages_c }
end
context 'with suffix search term' do
let(:search_term) { 'packagec' }
it { expect_search_results 1, packages_c }
end
context 'with pre release packages' do
let_it_be(:package_e) { create(:nuget_package, project: project, name: 'DummyPackageE', version: '3.2.1-alpha') }
context 'including them' do
it { expect_search_results 4, package_a, packages_b, packages_c, package_e }
end
context 'excluding them' do
let(:include_prerelease_versions) { false }
it { expect_search_results 3, package_a, packages_b, packages_c }
context 'when mixed with release versions' do
let_it_be(:package_e_release) { create(:nuget_package, project: project, name: 'DummyPackageE', version: '3.2.1') }
it { expect_search_results 4, package_a, packages_b, packages_c, package_e_release }
end
end
end
end
context 'with project' do
let(:target) { project }
before do
project.add_developer(user)
end
it_behaves_like 'handling all the conditions'
end
context 'with subgroup' do
let(:target) { subgroup }
before do
subgroup.add_developer(user)
end
it_behaves_like 'handling all the conditions'
end
context 'with group' do
let(:target) { group }
before do
group.add_developer(user)
end
it_behaves_like 'handling all the conditions'
end
def expect_search_results(total_count, *results)
search = subject
expect(search.total_count).to eq total_count
expect(search.results).to match_array(Array.wrap(results).flatten)
end
end
end
|
Umiiii/electrum
|
ios/CustomCode/Modules/Tab_Mine/View/OKUnitTableViewCell.h
|
<gh_stars>1-10
//
// OKUnitTableViewCell.h
// OneKey
//
// Created by xiaoliang on 2020/10/30.
// Copyright © 2020 OneKey. All rights reserved..
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@class OKUnitTableViewCellModel;
@interface OKUnitTableViewCell : UITableViewCell
@property (nonatomic,strong)OKUnitTableViewCellModel *model;
@end
NS_ASSUME_NONNULL_END
|
openharmony-gitee-mirror/distributeddatamgr_datamgr
|
services/distributeddataservice/adapter/dfx/test/unittest/fake/hiview/include/hiview.h
|
<reponame>openharmony-gitee-mirror/distributeddatamgr_datamgr
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef HIVIEW_HIVIEW_H
#define HIVIEW_HIVIEW_H
#include <mutex>
#include <iostream>
#include "hievent.h"
class HiView {
public:
/**
* A abstract class for which classes can be report by HiView.
*/
class Reportable {
public:
virtual ~Reportable() {}
virtual HiEvent& ToHiEvent() = 0;
};
/**
* Report a HiEvent.
* @param event reference of l-value.
*/
static void Report(HiEvent& event)
{
}
/**
* Report a HiEvent.
* @param event reference of r-value.
*/
static void Report(HiEvent&& event);
/**
* Report a Reportable.
* @param reportable self-defined class which implement Reportable.
*/
static void Report(HiView::Reportable& reportable);
/**
* Create a HiEvent by single bool value.
* @param eventID ID of event.
* @param key single payload's key.
* @param value single payload's value.
*
* @return HiEvent
*/
static HiEvent ByPair(int eventID, const std::string& key, bool value);
/**
* Create a HiEvent by single byte value.
* @param eventID ID of event.
* @param key single payload's key.
* @param value single payload's value.
*
* @return HiEvent
*/
static HiEvent ByPair(int eventID, const std::string& key, unsigned char value);
/**
* Create a HiEvent by single byte value.
* @param eventID ID of event.
* @param key single payload's key.
* @param value single payload's value.
*
* @return HiEvent
*/
static HiEvent ByPair(int eventID, const std::string& key, int value);
/**
* Create a HiEvent by single byte value.
* @param eventID ID of event.
* @param key single payload's key.
* @param value single payload's value.
*
* @return HiEvent
*/
static HiEvent ByPair(int eventID, const std::string& key, long value);
/**
* Create a HiEvent by single byte value.
* @param eventID ID of event.
* @param key single payload's key.
* @param value single payload's value.
*
* @return HiEvent
*/
static HiEvent ByPair(int eventID, const std::string& key, float value);
/**
* Create a HiEvent by single byte value.
* @param eventID ID of event.
* @param key single payload's key.
* @param value single payload's value.
*
* @return HiEvent
*/
static HiEvent ByPair(int eventID, const std::string& key, const std::string& value);
/**
* Create a HiEvent by json formatten string.
* @param eventID ID of event.
* @param key single payload's key.
* @param value json formatten string.
*
* @return HiEvent
*/
static HiEvent ByJson(int eventID, const std::string& json);
private:
static void ReportImpl(HiEvent&& event);
};
#endif
|
andrus/bootique
|
bootique/src/main/java/com/nhl/bootique/jackson/SubtypeResolverFactory.java
|
package com.nhl.bootique.jackson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import com.fasterxml.jackson.databind.jsontype.SubtypeResolver;
import com.fasterxml.jackson.databind.jsontype.impl.StdSubtypeResolver;
import com.nhl.bootique.log.BootLogger;
/**
* @since 0.13
*/
class SubtypeResolverFactory {
private BootLogger logger;
private ClassLoader classLoader;
private Class<?> serviceType;
SubtypeResolverFactory(ClassLoader classLoader, Class<?> serviceType, BootLogger logger) {
this.logger = logger;
this.classLoader = classLoader;
this.serviceType = serviceType;
}
SubtypeResolver createResolver() {
StdSubtypeResolver resolver = new StdSubtypeResolver();
Collection<Class<?>> subtypes;
try {
subtypes = resolveSubclasses();
} catch (IOException | ClassNotFoundException e) {
throw new IllegalStateException("Couldn't load subclasses for type: " + serviceType.getName(), e);
}
Class<?>[] subtypesArray = subtypes.toArray(new Class<?>[subtypes.size()]);
resolver.registerSubtypes(subtypesArray);
return resolver;
}
Collection<Class<?>> resolveSubclasses() throws IOException, ClassNotFoundException {
Collection<Class<?>> subclasses = new ArrayList<>();
String location = serviceLocation();
Enumeration<URL> serviceLists = classLoader.getResources(location);
while (serviceLists.hasMoreElements()) {
URL url = serviceLists.nextElement();
appendSubclasses(url, subclasses);
}
return subclasses;
}
void appendSubclasses(URL url, Collection<Class<?>> subclasses) throws IOException, ClassNotFoundException {
try (BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"))) {
String line;
while ((line = in.readLine()) != null) {
subclasses.add(loadClass(line.trim()));
}
}
}
Class<?> loadClass(String className) throws ClassNotFoundException {
logger.trace(() -> "Loading config subtype: " + className);
return classLoader.loadClass(className);
}
String serviceLocation() {
return "META-INF/services/" + serviceType.getName();
}
}
|
theapache64/musicdog
|
client/app/src/main/java/com/theah64/soundclouddownloader/utils/PrefUtils.java
|
<filename>client/app/src/main/java/com/theah64/soundclouddownloader/utils/PrefUtils.java
package com.theah64.soundclouddownloader.utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
/**
* Created by shifar on 15/9/16.
*/
public class PrefUtils {
private static final String X = PrefUtils.class.getSimpleName();
public static final String KEY_IS_START_ON_NEW_TRACK = "is_start_app_on_new_track";
private static PrefUtils instance;
private final SharedPreferences pref;
private PrefUtils(final Context context) {
this.pref = PreferenceManager.getDefaultSharedPreferences(context);
}
public static PrefUtils getInstance(final Context context) {
if (instance == null) {
instance = new PrefUtils(context);
}
return instance;
}
public SharedPreferences getPref() {
return pref;
}
public SharedPreferences.Editor getEditor() {
return pref.edit();
}
}
|
dk-extdev/FPR-Angular-Admin
|
src/main/java/com/fpr360/service/MerchantAccountService.java
|
package com.fpr360.service;
import com.fpr360.domain.MerchantAccount;
import com.fpr360.repository.MerchantAccountRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
/**
* Service Implementation for managing MerchantAccount.
*/
@Service
@Transactional
public class MerchantAccountService {
private final Logger log = LoggerFactory.getLogger(MerchantAccountService.class);
private final MerchantAccountRepository merchantAccountRepository;
public MerchantAccountService(MerchantAccountRepository merchantAccountRepository) {
this.merchantAccountRepository = merchantAccountRepository;
}
/**
* Save a merchantAccount.
*
* @param merchantAccount the entity to save
* @return the persisted entity
*/
public MerchantAccount save(MerchantAccount merchantAccount) {
log.debug("Request to save MerchantAccount : {}", merchantAccount); return merchantAccountRepository.save(merchantAccount);
}
/**
* Get all the merchantAccounts.
*
* @param pageable the pagination information
* @return the list of entities
*/
@Transactional(readOnly = true)
public Page<MerchantAccount> findAll(Pageable pageable) {
log.debug("Request to get all MerchantAccounts");
return merchantAccountRepository.findAll(pageable);
}
/**
* Get one merchantAccount by id.
*
* @param id the id of the entity
* @return the entity
*/
@Transactional(readOnly = true)
public Optional<MerchantAccount> findOne(Long id) {
log.debug("Request to get MerchantAccount : {}", id);
return merchantAccountRepository.findById(id);
}
/**
* Delete the merchantAccount by id.
*
* @param id the id of the entity
*/
public void delete(Long id) {
log.debug("Request to delete MerchantAccount : {}", id);
merchantAccountRepository.deleteById(id);
}
}
|
patil215/v8
|
fuzzer_output/interesting/sample_1554109134982.js
|
function main() {
let v2 = 0;
const v3 = v2 + 1;
v2 = v3;
let v10 = 0;
do {
const v11 = Function.name;
const v12 = v10 + 1;
v10 = v12;
} while (v10 < 3);
}
%NeverOptimizeFunction(main);
main();
|
brunosabot/conference-hall
|
src/screens/speaker/event/submitWizard/submitWizard.container.js
|
<reponame>brunosabot/conference-hall<gh_stars>0
import { compose } from 'redux'
import { inject } from '@k-ramel/react'
import { forRoute } from '@k-redux-router/react-k-ramel'
import loader from 'components/loader'
import { isCfpOpened } from 'store/reducers/data/events.selector'
import SubmitWizard from './submitWizard'
const mapStore = (store, props, { router }) => {
const eventId = router.getParam('eventId')
const event = store.data.events.get(eventId) || {}
const { currentStep } = store.ui.speaker.submission.get()
return {
loaded: !!event,
cfpOpened: isCfpOpened(event.id)(store),
eventId: event.id,
eventName: event.name,
currentStep,
load: () => store.dispatch('@@ui/ON_LOAD_EVENT'),
}
}
export default compose(
forRoute('speaker-event-submit-wizard'),
inject(mapStore),
loader,
)(SubmitWizard)
|
Linindoo/vboot
|
vTohru-orm-common/src/main/java/cn/vtohru/orm/transaction/AbstractTrans.java
|
package cn.vtohru.orm.transaction;
import cn.vtohru.orm.dataaccess.IDataAccessObject;
import java.util.ArrayList;
import java.util.List;
public abstract class AbstractTrans implements Trans {
protected List<IDataAccessObject<?>> dataAccessObjects = new ArrayList<>();
@Override
public <T> Trans add(IDataAccessObject<T> dataAccessObject) {
dataAccessObjects.add(dataAccessObject);
return this;
}
@Override
public List<IDataAccessObject<?>> getDataAccess() {
return this.dataAccessObjects;
}
}
|
steven004/specs
|
src/systems/filecoin_markets/deal/deal.go
|
package deal
import actor "github.com/filecoin-project/specs/systems/filecoin_vm/actor"
import block "github.com/filecoin-project/specs/systems/filecoin_blockchain/struct/block"
const MIN_PROVIDER_DEAL_COLLATERAL_PER_EPOCH = actor.TokenAmount(1) // TODO: Placeholder
const MIN_CLIENT_DEAL_COLLATERAL_PER_EPOCH = actor.TokenAmount(1) // TODO: Placeholder
func (d *StorageDeal_I) Proposal() StorageDealProposal {
// TODO: extract from d.ProposalMessage
var proposal StorageDealProposal
return proposal
}
func (d *StorageDeal_I) CID() DealCID {
// TODO: should be generated in codegen
var cid DealCID
return cid
}
func (p *StorageDealProposal_I) Duration() block.ChainEpoch {
return (p.EndEpoch() - p.StartEpoch())
}
func (p *StorageDealProposal_I) ClientBalanceRequirement() actor.TokenAmount {
balanceRequirementPerEpoch := p.ClientCollateralPerEpoch() + p.StoragePricePerEpoch()
return actor.TokenAmount(uint64(balanceRequirementPerEpoch) * uint64(p.Duration()))
}
func (p *StorageDealProposal_I) ProviderBalanceRequirement() actor.TokenAmount {
return actor.TokenAmount(uint64(p.ProviderCollateralPerEpoch()) * uint64(p.Duration()))
}
func (p *StorageDealProposal_I) CID() ProposalCID {
// TODO: should be generated in codegen
var cid ProposalCID
return cid
}
|
roj234/rojlib
|
lac/injector/mapper/Mover.java
|
<gh_stars>1-10
/*
* This file is a part of MoreItems
*
* The MIT License (MIT)
*
* Copyright (c) 2021 Roj234
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package lac.injector.mapper;
import roj.asm.Parser;
import roj.asm.cst.CstRef;
import roj.asm.mapper.util.Context;
import roj.asm.mapper.util.Desc;
import roj.asm.tree.*;
import roj.asm.tree.attr.AttrBootstrapMethods;
import roj.asm.tree.attr.AttrBootstrapMethods.BootstrapMethod;
import roj.asm.tree.attr.Attribute;
import roj.asm.tree.insn.InsnNode;
import roj.asm.tree.insn.InvokeDynInsnNode;
import roj.asm.util.InsnList;
import roj.collect.HashBiMap;
import roj.collect.MyHashMap;
import roj.collect.MyHashSet;
import roj.util.Helpers;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
/**
* Your description here
*
* @author Roj233
* @version 0.1
* @since 2021/10/17 10:30
*/
public class Mover {
private final HashBiMap<Desc, Desc> methodMove = new HashBiMap<>();
private final HashBiMap<String, String> classMove = new HashBiMap<>();
private Function<Desc, Desc> fallback;
public void setFallback(Function<Desc, Desc> fallback) {
this.fallback = fallback;
}
public HashBiMap<Desc, Desc> getMethodMove() {
return methodMove;
}
public HashBiMap<String, String> getClassMove() {
return classMove;
}
public void map(List<Context> ctxs) {
Map<String, List<Movable>> moved = new MyHashMap<>();
Desc checker = new Desc("", "");
for (int i = 0; i < ctxs.size(); i++) {
ConstantData data = ctxs.get(i).getData();
List<CstRef> refs = ctxs.get(i).getMethodConstants();
for (int j = 0; j < refs.size(); j++) {
CstRef ref = refs.get(j);
Desc desc = methodMove.get(checker.read(ref));
if (desc == null)
desc = methodMove.getByValue(checker);
if (desc != null) {
ref.setClazz(data.cp.getClazz(desc.owner));
ref.desc(data.cp.getDesc(desc.name, ref.desc().getType().getString()));
}
}
String name = classMove.get(data.name);
if (name != null)
data.cp.setUTFValue(data.nameCst.getValue(), name);
checker.owner = data.name;
List<? extends MethodNode> ms = data.methods;
for (int j = ms.size() - 1; j >= 0; j--) {
MethodNode m = ms.get(j);
checker.name = m.name();
checker.param = m.rawDesc();
Desc desc = methodMove.get(checker);
if (desc == null)
desc = methodMove.getByValue(checker);
if (desc != null) {
if (!desc.owner.equals(data.name)) {
Movable mv = new Movable();
Method e = mv.node = m instanceof Method ? (Method) m : new Method(data, (MethodSimple) m);
e.name = desc.name;
if (!ctxs.get(i).getInvokeDynamic().isEmpty()) {
checkLambdaRef(data, mv);
}
moved.computeIfAbsent(desc.owner, Helpers.fnArrayList()).add(mv);
ms.remove(j);
} else {
if (m instanceof Method) {
((Method) m).name = desc.name;
} else {
((SimpleComponent) m).name = data.cp.getUtf(desc.name);
}
}
}
}
}
if (moved.isEmpty()) return;
Map<Desc, Desc> duplicateFallback = new MyHashMap<>();
MyHashSet<Desc> tmp = new MyHashSet<>();
for (int i = 0; i < ctxs.size(); i++) {
ConstantData data = ctxs.get(i).getData();
List<Movable> append = moved.remove(data.name);
if (append != null) {
List<? extends MethodNode> methods = data.methods;
for (int j = 0; j < append.size(); j++) {
methods.add(Helpers.cast(append.get(j).node));
}
for (int j = methods.size() - 1; j >= 0; j--) {
MethodNode m = methods.get(j);
Desc desc = new Desc(data.name, m.name(), m.rawDesc());
if (!tmp.add(desc)) {
append.remove(m);
methods.remove(j);
Desc put = duplicateFallback.put(desc, desc = fallback.apply(desc));
if (null != put)
throw new IllegalArgumentException("Method occur twice: " + m.ownerClass() + '.' + m.name() + ' ' + m.rawDesc());
Movable mv = new Movable();
Method e = mv.node = m instanceof Method ? (Method) m : new Method(data, (MethodSimple) m);
e.name = desc.name;
if (!ctxs.get(i).getInvokeDynamic().isEmpty()) {
checkLambdaRef(data, mv);
}
moved.computeIfAbsent(desc.owner, Helpers.fnArrayList()).add(mv);
}
}
satisfyBSM(ctxs.get(i), append);
tmp.clear();
}
}
if (duplicateFallback.isEmpty()) return;
for (int i = 0; i < ctxs.size(); i++) {
ConstantData data = ctxs.get(i).getData();
List<CstRef> refs = ctxs.get(i).getMethodConstants();
for (int j = 0; j < refs.size(); j++) {
CstRef ref = refs.get(j);
Desc desc = duplicateFallback.get(checker.read(ref));
if (desc != null) {
ref.setClazz(data.cp.getClazz(desc.owner));
ref.desc(data.cp.getDesc(desc.name, ref.desc().getType().getString()));
}
}
}
if (moved.isEmpty()) return;
for (int i = 0; i < ctxs.size(); i++) {
ConstantData data = ctxs.get(i).getData();
List<Movable> append = moved.remove(data.name);
if (append != null) {
List<? extends MethodNode> methods = data.methods;
for (int j = 0; j < append.size(); j++) {
methods.add(Helpers.cast(append.get(j).node));
}
satisfyBSM(ctxs.get(i), append);
}
}
}
private static void satisfyBSM(Context ctx, List<Movable> append) {
ConstantData data = ctx.getData();
for (int i = 0; i < append.size(); i++) {
Movable mv = append.get(i);
if (!mv.idn.isEmpty()) {
AttrBootstrapMethods bm = getBSM(data);
if (bm == null) {
data.attributes.putByName(bm = new AttrBootstrapMethods());
}
for (Map.Entry<BootstrapMethod, List<InvokeDynInsnNode>> entry : mv.idn.entrySet()) {
char id = (char) bm.methods.size();
BootstrapMethod clone = entry.getKey().clone();
bm.methods.add(clone);
for (InvokeDynInsnNode node : entry.getValue()) {
node.tableIdx = id;
}
}
}
}
}
private static void checkLambdaRef(ConstantData data, Movable e) {
InsnList insn = e.node.code.instructions;
for (int k = 0; k < insn.size(); k++) {
InsnNode node = insn.get(k);
if (node.nodeType() == InsnNode.T_INVOKE_DYNAMIC) {
AttrBootstrapMethods bm = getBSM(data);
if (bm == null)
throw new IllegalStateException("有InvokeDyn却没有BSM属性 " + data.name);
if (e.idn.isEmpty())
e.idn = new MyHashMap<>();
InvokeDynInsnNode node1 = (InvokeDynInsnNode) node;
e.idn.computeIfAbsent(bm.methods.get(node1.tableIdx), Helpers.fnLinkedList()).add(node1);
}
}
}
private static AttrBootstrapMethods getBSM(ConstantData data) {
Attribute attr = (Attribute) data.attributes.getByName("BootstrapMethods");
AttrBootstrapMethods bm;
if (attr instanceof AttrBootstrapMethods) {
bm = (AttrBootstrapMethods) attr;
} else {
if (attr == null) return null;
bm = new AttrBootstrapMethods(Parser.reader(attr), data.cp);
data.attributes.putByName(bm);
}
return bm;
}
public void put(Desc from, Desc to) {
from = from.copy();
from.param = "";
if (methodMove.containsKey(to) || methodMove.containsValue(from))
throw new IllegalStateException("Duplicate mapping! " + from + " => " + to + "\n existA: " + methodMove.get(from) + " => " + from + "\n existB: " + to + " => " + methodMove.get(to));
methodMove.forcePut(from, to);
}
public void putClass(String from, String to) {
classMove.put(from, to);
}
public void clear() {
methodMove.clear();
classMove.clear();
}
public boolean putIfAbsent(Desc from, Desc to) {
from = from.copy();
from.param = "";
if (methodMove.containsKey(to) || methodMove.containsValue(from))
return false;
methodMove.forcePut(from, to);
return true;
}
private static final class Movable {
Method node;
Map<AttrBootstrapMethods.BootstrapMethod, List<InvokeDynInsnNode>> idn = Collections.emptyMap();
}
}
|
szkkteam/agrosys
|
frontend/app/farmApp/cropProduction_old/backup_old/season/components/index.js
|
<filename>frontend/app/farmApp/cropProduction_old/backup_old/season/components/index.js<gh_stars>0
export { default as SeasonLayout } from './SeasonLayout'
export { default as SeasonList } from './SeasonList'
export { default as SeasonCreateButton } from './SeasonCreateButton'
export { default as SeasonAppBar } from './SeasonAppBar'
export { default as SeasonOverviewLayout } from './SeasonOverviewLayout'
export { default as SeasonOverviewToolbar } from './SeasonOverviewToolbar'
export { default as SeasonSelectorDialog } from './SeasonSelectorDialog'
export { default as SeasonSelector } from './SeasonSelector'
export { default as SeasonCreateForm } from './SeasonCreateForm'
|
artas360/pythran
|
pythran/pythonic/numpy/diagflat.hpp
|
<filename>pythran/pythonic/numpy/diagflat.hpp
#ifndef PYTHONIC_NUMPY_DIAGFLAT_HPP
#define PYTHONIC_NUMPY_DIAGFLAT_HPP
#include "pythonic/include/numpy/diagflat.hpp"
#include "pythonic/numpy/diag.hpp"
namespace pythonic
{
namespace numpy
{
FPROXY_IMPL(pythonic::numpy, diagflat, diag);
}
}
#endif
|
apollofy-music-project/SongShare
|
packages/web/src/pages/CreatePlaylist/CreatePlaylist.js
|
<filename>packages/web/src/pages/CreatePlaylist/CreatePlaylist.js
import React, { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { createPlaylistRequest } from '../../redux/Playlists/playlists-actions';
import '../PlaylistView/styles.scss';
import PlaylistViewHeader from '../../components/PlaylistViewHeader';
function CreatePlaylist() {
const dispatch = useDispatch();
useEffect(() => {
dispatch(createPlaylistRequest());
}, [dispatch]);
return (
<>
<PlaylistViewHeader from="createView" />
</>
);
}
export default CreatePlaylist;
|
gemacoin/gpl-wallet
|
node_modules/mdi-material-ui/LeafCircleOutline.js
|
<filename>node_modules/mdi-material-ui/LeafCircleOutline.js<gh_stars>0
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _createIcon = _interopRequireDefault(require("./util/createIcon"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var _default = (0, _createIcon["default"])('M8.04 16.34C9.05 13.83 10.19 10.96 14.5 10C14.5 10 9.5 10 7.88 14.63C7.88 14.63 7 13.75 7 12.75S8 9.63 10.5 9.13C11.21 9 12 8.87 12.78 8.76C14.75 8.5 16.64 8.22 17 7.5C17 7.5 15.5 16 10 16C9.82 16 9.57 15.94 9.33 15.85L8.86 17L7.91 16.67L8.04 16.34M12 4C16.41 4 20 7.59 20 12S16.41 20 12 20 4 16.41 4 12 7.59 4 12 4M12 2C6.5 2 2 6.5 2 12S6.5 22 12 22 22 17.5 22 12 17.5 2 12 2Z');
exports["default"] = _default;
|
zero88/msa-sql
|
service/src/main/java/io/github/zero88/qwe/sql/workflow/step/SQLBatchStep.java
|
package io.github.zero88.qwe.sql.workflow.step;
/**
* Represents a direct execution step in batch into/onto database
*
* @since 1.0.0
*/
public interface SQLBatchStep extends SQLStep {
}
|
ethanabrooks/teacher-RL
|
epoch_counter.py
|
from collections import defaultdict
import numpy as np
class EpochCounter:
last_return_name = "last_return"
def __init__(self, num_processes):
self.episode_rewards = []
self.episode_time_steps = []
self.rewards = np.zeros(num_processes)
self.time_steps = np.zeros(num_processes)
self.infos_name = defaultdict(list)
self.last_return = 0
def update(self, reward, done, infos):
self.rewards += reward.numpy()
self.time_steps += np.ones_like(done)
self.episode_rewards += list(self.rewards[done])
self.episode_time_steps += list(self.time_steps[done])
self.rewards[done] = 0
self.time_steps[done] = 0
for info in infos:
for k, v in info.items():
self.infos_name[k].append(v)
def reset(self):
self.last_return = np.mean(self.episode_rewards)
self.episode_rewards = []
self.episode_time_steps = []
self.infos_name = defaultdict(list)
def items(self, prefix=""):
if self.episode_rewards:
yield prefix + "epoch_returns", np.mean(self.episode_rewards)
if self.episode_time_steps:
yield prefix + "epoch_time_steps", np.mean(self.episode_time_steps)
yield prefix + self.last_return_name, self.last_return
for k, vs in self.infos_name.items():
yield prefix + k, np.mean(vs)
|
wied03/ansible-ruby
|
lib/ansible/ruby/modules/helpers/aws.rb
|
# frozen_string_literal: true
# see LICENSE.txt in project root
module Ansible
module Ruby
module Modules
module Helpers
# For some of the AWS modules, we don't detect the region attribute
module Aws
def self.included(base)
base.attribute :region
base.validates :region, type: String, presence: true
end
end
end
end
end
end
|
0xcaffebabe/blb
|
blb-backend/business-service-api/pay-service-api/src/main/java/wang/ismy/blb/api/pay/enums/PayTypeEnum.java
|
package wang.ismy.blb.api.pay.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* @author MY
* @date 2020/4/9 11:13
*/
@Getter
@AllArgsConstructor
public enum PayTypeEnum {
/** 支付宝支付 */
ALI_PAY(0,"支付宝");
private Integer code;
private String type;
public static PayTypeEnum valueOf(Integer code) {
for (PayTypeEnum value : values()) {
if (value.code.equals(code)) {
return value;
}
}
return null;
}
}
|
dgoemans/merchant-center-application-kit
|
packages/mc-dev-authentication/routes/logout.js
|
<gh_stars>10-100
module.exports = (response, additionalCookieParameters = []) => {
// NOTE: removing the cookie only works if your are running the MC API
// locally, otherwise the cookie won't get removed as it's set to a
// proper domain (e.g. commercetools.com), which we can't unset from localhost.
response.setHeader(
'Set-Cookie',
[
`mcAccessToken=''`, // <-- unset the value
'Path=/',
`Expires=${new Date(0).toUTCString()}`, // <-- put a date in the past
'HttpOnly',
]
.concat(additionalCookieParameters)
.join('; ')
);
};
|
hd5970/ONOS
|
core/api/src/main/java/org/onosproject/net/device/DeviceClockProviderService.java
|
<reponame>hd5970/ONOS
/*
* Copyright 2014 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.net.device;
import org.onosproject.mastership.MastershipTerm;
import org.onosproject.net.DeviceId;
/**
* Interface for feeding term information to a logical clock service
* that vends per device timestamps.
*/
public interface DeviceClockProviderService {
/**
* Checks if this service can issue Timestamp for specified device.
*
* @param deviceId device identifier.
* @return true if timestamp can be issued for specified device
*/
public boolean isTimestampAvailable(DeviceId deviceId);
/**
* Updates the mastership term for the specified deviceId.
*
* @param deviceId device identifier.
* @param term mastership term.
*/
public void setMastershipTerm(DeviceId deviceId, MastershipTerm term);
}
|
nikitavlaev/embox
|
src/compat/libc/string/memcmp.c
|
/**
* @file
* @brief Implementation of #memcmp() function.
*
* @date 23.11.09
* @author <NAME>
*/
#include <string.h>
int memcmp(const void *_dst, const void *_src, size_t n) {
const unsigned char *dst = (const unsigned char *) _dst;
const unsigned char *src = (const unsigned char *) _src;
if (!n) {
return 0;
}
while (--n && *dst == *src) {
++dst;
++src;
}
return *dst - *src;
}
|
linz/snap
|
src/snaplib/util/errdef.c
|
<gh_stars>1-10
#include "snapconfig.h"
/*
errdef.c : part of the gina_pci translator
Copyright: Department of Survey and Land Information
New Zealand
Author: <NAME>, Research and Development Group
Revision: October 1990
*/
/*
$Log: errdef.c,v $
Revision 1.2 2004/04/22 02:35:24 ccrook
Setting up to support linux compilation (x86 architecture)
Revision 1.1 1995/12/22 18:58:16 CHRIS
Initial revision
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "util/errdef.h" /* Error code definitions */
static errhandler_type user_error_handler = (errhandler_type)0;
static FILE *error_file = NULL;
static int error_level = 0;
static int use_prefix = 1;
static int error_count = 0;
#define LOCATION_LEN 256
static char location[LOCATION_LEN] = {0};
int default_error_handler(int sts, const char *mess1, const char *mess2)
{
FILE *out = error_file ? error_file : stderr;
if (use_prefix)
{
if (FATAL_ERROR_CONDITION(sts))
{
fprintf(out, "\nFatal error: ");
}
else if (WARNING_ERROR_CONDITION(sts))
{
fprintf(out, "\nWarning: ");
}
else
{
fprintf(out, "\nInformation: ");
}
}
fprintf(out, "%s\n", mess1);
if (mess2 != NULL) fprintf(out, "%s\n", mess2);
return sts;
}
int null_error_handler(int sts, const char *mess1, const char *mess2)
{
if (!FATAL_ERROR_CONDITION(sts)) return sts;
return default_error_handler(sts, mess1, mess2);
}
int handle_error(int sts, const char *mess1, const char *mess2)
{
if (!REPORTABLE_ERROR(sts)) return sts;
if (WARNING_ERROR_CONDITION(sts)) error_count++;
if (sts >= error_level || FATAL_ERROR_CONDITION(sts))
{
if (mess1 == NULL) switch (sts)
{
case FILE_OPEN_ERROR:
{
mess1 = "Error opening file";
break;
}
case FILE_READ_ERROR:
{
mess1 = "Error reading file";
break;
}
case FILE_WRITE_ERROR:
{
mess1 = "Error writing file";
break;
}
case UNEXPECTED_EOF:
{
mess1 = "End of file encountered";
break;
}
case SYNTAX_ERROR:
{
mess1 = "Syntax error";
break;
}
case INVALID_DATA:
{
mess1 = "Invalid data error";
break;
}
case MISSING_DATA:
{
mess1 = "Missing data";
break;
}
case INCONSISTENT_DATA:
{
mess1 = "Inconsistent data";
break;
}
case TOO_MUCH_DATA:
{
mess1 = "Too much data";
break;
}
case MEM_ALLOC_ERROR:
{
mess1 = "Memory allocation error";
break;
}
case INTERNAL_ERROR:
{
mess1 = "Internal program error";
break;
}
case OPERATION_ABORTED:
{
mess1 = "Aborted by user";
break;
}
default:
{
if (INFO_ERROR_CONDITION(sts))
{
mess1 = "Notice";
}
else
{
mess1 = "Undefined error";
}
}
}
if (mess2 == NULL && location[0]) mess2 = location;
if (user_error_handler)
{
(*user_error_handler)(sts, mess1, mess2);
}
else
{
default_error_handler(sts, mess1, mess2);
}
}
if (FATAL_ERROR_CONDITION(sts)) exit(sts);
return sts;
}
FILE *set_error_file(FILE *err)
{
FILE *oldfile = error_file;
error_file = err;
return oldfile;
}
int set_error_level(int level)
{
int oldlevel = error_level;
error_level = level;
return oldlevel;
}
int set_error_prefix(int prefix)
{
int oldprefix = use_prefix;
use_prefix = prefix;
return oldprefix;
}
errhandler_type set_error_handler(errhandler_type errhndler)
{
errhandler_type olderrhndler;
olderrhndler = user_error_handler;
user_error_handler = errhndler;
return olderrhndler;
}
int get_error_count(void)
{
int errc = error_count;
// error_count = 0;
return errc;
}
void set_error_location(const char *loc)
{
if (loc)
{
strncpy(location, loc, LOCATION_LEN - 1);
location[LOCATION_LEN - 1] = 0;
}
else
{
location[0] = 0;
}
}
|
Uintra/Uintra
|
src/Uintra/App_Plugins/UintraGroupMember/member.service.js
|
<gh_stars>10-100
(function (angular) {
'use strict';
var service = function ($http) {
var self = this;
var baseUrl = "/umbraco/backoffice/api/MemberApi/";
self.memberChanged = function(memberId) {
return $http.post(baseUrl + "MemberChanged?memberId=" + memberId);
}
}
service.$inject = ["$http"];
angular.module('umbraco').service('memberService', service);
})(angular);
|
ankosoftware/gatsby-prismic-template
|
src/components/slices.component.js
|
import React from "react"
import { DefaultSlice } from "./slices/default.slice"
import { Features } from "./slices/features.slice"
import { BlockWithImage } from "./slices/block-with-image.slice"
import { Form } from "./slices/form.slice"
import { ScriptSlice } from "./slices/script.slice"
import { TextSlice } from "./slices/text.slice"
import { ItemsCollection } from "./slices/items-collection.slice"
import { Pricing } from "./slices/pricing.slice"
import { MenuSlice } from "./slices/menu.slice"
import { GallerySlice } from "./slices/gallery.slice"
export const Slices = ({ body }) => {
if (body) {
return body.map(slice => {
if (slice.primary || slice.fields) {
switch (slice.type) {
case "feature":
return <Features slice={slice} />
case "block-with-text-and-image":
return <BlockWithImage slice={slice} />
case "form":
return <Form slice={slice} />
case "custom-script":
return <ScriptSlice slice={slice} />
case "items-collection":
return <ItemsCollection slice={slice} />
case "text":
return <TextSlice slice={slice} />
case "pricing-plans":
return <Pricing slice={slice} />
case "menu":
return <MenuSlice slice={slice} />
case "gallery":
return <GallerySlice slice={slice}/>
default:
return <DefaultSlice slice={slice} />
}
}
return null
})
}
return null
}
|
hzm2016/assistive-gym-robosuite
|
code/pytorch/utils/GPREPS_real_solver.py
|
<reponame>hzm2016/assistive-gym-robosuite
import numpy as np
from envs.abb.models import utils
from code.pytorch.methods import TD3
from ECPL_pytorch.argmin import argmin_g as argmin
from envs.abb.env_abb_assembly import env_assembly_search
from algorithms.calculations import calculation
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import DotProduct, WhiteKernel
from code.pytorch.Regression.GMRbasedGP.utils.gmr import Gmr
class Old_Solver(object):
def __init__(self,
env):
# ##################### Hyper Parameters ######################
self.K = 15 # 上层policy训练循环总数
self.N = 10 # 在上层policy的一个训练周期中,下层RL训练,改变context参数的次数
self.n = 1 # 下层RL训练,每改变一次context参数,执行RL的episode数
self.d = 1 # 下层RL每d个step更新一次网络参数
self.M = 5 # 在上层policy的一个训练周期中,通过model获得artificial trajectory的过程中,改变context参数的次数
self.L = 20 # 每改变一次context参数,通过model获得artificial trajectory的次数
# Initialize assembly environment
self.env = env
self.init_state = np.hstack(
[np.array([0, 0, 0, 0, 0, 0]), np.hstack([self.env.set_initial_pos, self.env.set_initial_euler])])
self.state_bound = np.array([10, 10, 10, 1, 1, 1, 0.2, 0.2, 7, 0.10, 0.10, 0.10])
# self.action_bound = np.array([0.4, 0.15, 0.26, 0.09, 0.09, 0.10])
# # Set seeds
# torch.manual_seed(args.seed)
# np.random.seed(args.seed)
# RL parameters
self.MAX_EP_STEPS = 200 # RL的最大步数
self.batch_size = 64
self.discount = 0.99
self.tau = 0.005
self.policy_noise = 0.2
self.RL_buffer_size = 6000
self.state_dim = self.env.observation_dim
self.action_dim = self.env.action_dim
self.max_RL_action = 1.
self.min_RL_action = -1.
# Initialize RL policy
self.done = False
self.safe = True
self.pd = True
self.var = 0.3
'open TD_3'
"Lower-level RL policy"
# path_TD_3 = 'C:/Users/liucc/Desktop/RL_assembly/TD3_100/TD_3.txt'
# file_TD_3 = open(path_TD_3, 'rb')
# self.policy = pickle.load(file_TD_3)
self.policy = TD3.TD3(self.state_dim,
self.action_dim,
self.max_RL_action)
" Replay buffer for lower-level policy "
# path_replay_buffer = 'C:/Users/liucc/Desktop/RL_assembly/TD3_100/replay_buffer.txt'
# file_replay_buffer = open(path_replay_buffer, 'rb')
# self.replay_buffer = pickle.load(file_replay_buffer)
self.replay_buffer = utils.ReplayBuffer(self.RL_buffer_size)
self.episode_timesteps = 0
self.total_timesteps = 0
self.episode_reward = 0
self.episode_number = 0
" Contextual parameters "
self.context_dim = 3 # 速度和深度系数共3维
self.contextual_action_dim = 2 # Kp and Kd
self.contextual_action_bound = 0.01 # Kp和Kd的范围暂定为0.1
buffer_size = 60
# Initialize Contextual Policy
self.replay_buffer_model = utils.ReplayBuffer(buffer_size)
self.gpreps = GPREPS(self.context_dim, self.contextual_action_dim, self.M, self.contextual_action_bound)
# self.r_model = R_MODEL(self.policy, self.env, self.context_dim, self.contextual_action_dim, self.observation_dim, self.action_dim, self.MAX_EP_STEPS)
# self.s_model = S_MODEL()
'temp data'
self.Reward = []
self.State = []
self.IM_Action = []
self.R = []
def train_once(self):
if self.total_timesteps >= 200:
self.policy.train(self.replay_buffer,
self.batch_size,
self.discount,
self.tau,
self.policy_noise)
print('policy trained')
else:
pass
def RL_reset(self):
self.env.reset()
self.state = self.env.start_noise()
self.state = self.state - self.init_state
self.done = False
self.safe = True
self.episode_reward = 0
self.episode_timesteps = 0
# u(z) 暂定s[速度系数, 深度系数]为0.6~1.0之间随机量
def __get_z(self):
depth = np.random.rand(1)[0] * 2 - 1 # -1~1之间随机数
z = (np.random.rand(3) - 0.5) / 100 + np.array([0, depth, 0])
self.z_ = np.array([0, 0, 0])
return z
# execute reinforcement learning and store data for model training
def train(self):
# n training cycles
self.gpreps.memory = []
R = 0
for i in range(self.N):
z = self.__get_z()
print('context parameter z:', z)
self.env.set_context(z)
w = self.gpreps.choose_action(z)[0]
print('contextual action w:', w)
self.env.set_pd(w)
self.episode_number = 0
self.var = 0.3
# Start DDPG training
while self.episode_number < self.n:
self.RL_reset()
while self.episode_timesteps < self.MAX_EP_STEPS:
# 'train RL policy'
# if self.episode_timesteps % self.d == 0:
# self.train_once()
print('Pose:', self.state[6:9], 'Force:', self.state[:3])
action = self.policy.select_action(np.array(self.state / self.state_bound))
# print('RL action:', action)
# action = np.random.normal(action, self.var).clip(self.min_RL_action, self.max_RL_action)
# action = np.array([0, 0, 0, 0, 0, 0])
'record state'
self.State.append(np.hstack([np.array([self.episode_timesteps]), self.state]))
_, new_state, reward, self.done, self.safe, im_action = self.env.step(action)
new_state = new_state - self.init_state
print('Im_action:', im_action)
print('--------', 'Episode:', self.episode_number, 'STEP::', self.episode_timesteps, 'Reward:',
reward, '--------')
'record im_action'
self.IM_Action.append(im_action)
# store data into buffer
self.replay_buffer.add((self.state / self.state_bound, new_state / self.state_bound, action, reward,
self.done, 0)) # for RL training
self.episode_reward += reward
self.state = new_state.copy()
self.episode_timesteps += 1
self.total_timesteps += 1
if self.var >= 0.01:
self.var *= 0.999
if self.done:
self.episode_number += 1
if self.episode_timesteps == self.MAX_EP_STEPS:
self.Reward.append([z, w, self.episode_timesteps, self.episode_reward, 'Unfinished'])
elif self.safe == False:
self.Reward.append([z, w, self.episode_timesteps, self.episode_reward, 'Failed'])
else:
self.Reward.append([z, w, self.episode_timesteps, self.episode_reward, 'Successful'])
print('Episode', i, 'Step', self.episode_timesteps, 'Total reward:', self.episode_reward,
'var:', self.var)
R += self.episode_reward
break
self.gpreps.store_data(z, w / self.contextual_action_bound, self.episode_reward)
self.R.append(R / self.N)
np.save('C:/Users/W<NAME>/Desktop/TD3_control_reward.npy', self.R)
np.save('C:/Users/<NAME>/Desktop/TD3_control_reward.npy', self.Reward)
np.save('C:/Users/<NAME>/Desktop/TD3_control_state.npy', self.State)
np.save('C:/Users/<NAME>/Desktop//TD3_control_action.npy', self.IM_Action)
# main function for upper level training
def contextual_main(self):
for k in range(self.K):
print('Training cycle', k)
# run RL and collect data
print('Running RL...')
self.train()
# train reward and context model
# print('Training GMR models...')
# self.r_model.train_reward_model(self.replay_buffer_model)
# self.s_model.train_context_model()
# Predict Rewards and Store Data
# print('Artificial trajectories')
# for j in range(self.M):
# # Predict Rewards
# R = 0.
# Z = self.__get_z()
# W = self.gpreps.choose_action(Z)
#
# # Predict L Trajectories
# for l in range(self.L):
# R += self.r_model.trajectory(Z, W)
# reward = R / self.L
# print('Artificial running cycle', j+1, 'ra:', Z[0], 'rd:', Z[1], 'reward:', reward)
#
# # Construct Artificial Dataset D
# self.gpreps.store_data(Z, W, reward)
# # Sample and Update Policy
# S_ = self.z_average
if k >= 2:
self.gpreps.learn(self.z_)
print('************ Training cycle finished **************')
print('')
class Solver(object):
def __init__(self):
# ##################### Hyper Parameters ######################
self.K = 34 # 上层policy训练循环总数
self.N = 5 # 在上层policy的一个训练周期中,下层RL训练,改变context参数的次数
self.n = 1 # 下层RL训练,每改变一次context参数,执行RL的episode数
self.d = 1 # 下层RL每d个step更新一次网络参数
self.M = 1 # 在上层policy的一个训练周期中,通过model获得artificial trajectory的过程中,改变context参数的次数
self.L = 10 # 每改变一次context参数,通过model获得artificial trajectory的次数
# Initialize assembly environment
self.env = env_assembly_search()
self.init_state = np.hstack([np.array([0,0,0,0,0,0]), np.hstack([self.env.set_initial_pos, self.env.set_initial_euler])])
self.action_bound = np.array([0.23, 0.23, 0.75, 0.06, 0.06, 0.03])
self.dpos_bound = np.array([0.190, 0.157, 0.745, 0.110, 0.086, 0.012])
self.force_bound = np.array([9.39, 9.32, 8.70, 1.00, 0.87, 0.92])
self.pos_bound = np.array([1.96, 1.99, 23.93, 0.009, 0.06, 0.010])
self.state_bound = np.hstack([self.force_bound, self.pos_bound])
# # Set seeds
# torch.manual_seed(args.seed)
# np.random.seed(args.seed)
# RL parameters
self.MAX_EP_STEPS = 300 # RL的最大步数
self.batch_size = 64
self.discount = 0.99
self.tau = 0.005
self.policy_noise = 0.2
RL_buffer_size = 6000
state_dim = self.env.observation_dim
action_dim = self.env.action_dim
self.max_RL_action = 1.
self.min_RL_action = -1.
# Initialize RL policy
self.done = False
self.safe = True
self.pd = True
self.var = 0.3
'open TD_3'
self.policy = TD3.TD3(state_dim, action_dim, self.max_RL_action)
'open replay buffer'
self.replay_buffer = utils.ReplayBuffer(RL_buffer_size)
self.episode_timesteps = 0
self.total_timesteps = 0
self.episode_reward = 0
self.episode_number = 0
# Contextual parameters
self.context_dim = 1 # 速度和深度系数共3维
self.contextual_action_dim = 4 # Kp and Kd
self.z_ = np.array([175])
self.contextual_action_bound = np.array([0.008, 0.008, 0.004, 0.001])
buffer_size = 10
# Initialize Contextual Policy
self.replay_buffer_model = utils.ReplayBuffer(buffer_size)
self.gpreps = GPREPS(self.context_dim, self.contextual_action_dim, buffer_size, self.z_, self.contextual_action_bound)
# data efficient hrl
self.replay_buffer_high = utils.ReplayBufferHighLevel()
self.replay_buffer_low = utils.ReplayBufferOption()
'temp data'
self.Reward = []
self.State = []
self.IM_Action = []
self.R = []
def train_once(self):
if self.total_timesteps >= 300:
self.policy.train(self.replay_buffer, self.batch_size, self.discount, self.tau, self.policy_noise)
print('policy trained')
else:
pass
def RL_reset(self):
self.env.reset()
self.env.start_noise()
self.state = self.env.state
self.state = self.state - self.init_state
self.done = False
self.safe = True
self.episode_reward = 0
self.episode_timesteps = 0
# 暂定目标装配完成步数为z, 取值100-250随机值
def __get_z(self):
z = np.random.randint(0, 4, 1) * 50 + 100
self.z_ = np.array([175])
return z
# execute reinforcement learning and store data for model training
def train(self):
"n training cycles"
R = 0
for i in range(self.N):
z = self.__get_z()
print('context parameter z:', z)
self.env.set_context(z)
w = self.gpreps.choose_action(z/self.z_)[0]
print('contextual action w:', w)
self.env.set_pd(w)
self.episode_number = 0
# self.var = 0.3
"Start DDPG training"
while self.episode_number < self.n:
self.RL_reset()
while self.episode_timesteps < self.MAX_EP_STEPS:
'train RL policy'
if self.episode_timesteps % self.d == 0:
self.train_once()
print('Pose:', self.state[6:9], 'Force:', self.state[:3])
action = self.policy.select_action(np.array(self.state/self.state_bound))
# print('RL action:', action)
# action = np.random.normal(action, self.var).clip(self.min_RL_action, self.max_RL_action)
# action = np.array([0, 0, 0, 0, 0, 0])
'record state'
self.State.append(np.hstack([np.array([self.episode_timesteps]), self.state]))
_, new_state, reward, self.done, self.safe, im_action = self.env.step(action)
new_state = new_state - self.init_state
print('Im_action:', im_action)
print('--------', 'Episode:', i*self.n+self.episode_number, 'STEP::', self.episode_timesteps, 'Reward:', reward, '--------')
'record im_action'
self.IM_Action.append(im_action)
'store data into buffer'
self.replay_buffer.add((self.state/self.state_bound, new_state/self.state_bound, action, reward, self.done, 0)) # for RL training
self.replay_buffer_model.add((self.state, new_state, im_action)) # for model training
'update state parameters'
self.episode_reward += reward
self.state = new_state.copy()
self.episode_timesteps += 1
self.total_timesteps += 1
if self.var >= 0.01:
self.var *= 0.999
if self.done:
if self.episode_timesteps == self.MAX_EP_STEPS - 1:
self.Reward.append([z, w, self.episode_timesteps, self.episode_reward, 'Unfinished'])
print('Episode', i * self.n + self.episode_number, 'Step', self.episode_timesteps, 'Total reward:', self.episode_reward, 'Unfinished')
elif not self.safe:
self.Reward.append([z, w, self.episode_timesteps, self.episode_reward, 'Failed'])
print('Episode', i * self.n + self.episode_number, 'Step', self.episode_timesteps, 'Total reward:', self.episode_reward, 'Failed')
else:
self.Reward.append([z, w, self.episode_timesteps, self.episode_reward, 'Successful'])
print('Episode', i * self.n + self.episode_number, 'Step', self.episode_timesteps, 'Total reward:', self.episode_reward, 'Successful')
self.episode_number += 1
R += self.episode_reward
break
self.gpreps.store_data(z/self.z_, w/self.contextual_action_bound, self.episode_reward)
self.R.append(R / self.N)
np.save('cycle_R.npy', self.R)
np.save('Contextual_Policy_Search_reward.npy', self.Reward)
np.save('Contextual_Policy_Search_state.npy', self.State)
np.save('Contextual_Policy_Search_action.npy', self.IM_Action)
# main function for upper level training
def contextual_main(self):
"Load initial data"
Aa = np.load('model_based_17x10 (2)/Contextual_Policy_Search_Aa.npy', allow_pickle=True)
reward = np.load('model_based_17x10 (2)/Contextual_Policy_Search_reward.npy', allow_pickle=True)
state = np.load('model_based_17x10 (2)/Contextual_Policy_Search_state.npy', allow_pickle=True)
action = np.load('model_based_17x10 (2)/Contextual_Policy_Search_action.npy', allow_pickle=True)
for i in range(30):
z = reward[i][0]
w = reward[i][1]
r = reward[i][3]
self.gpreps.store_data(z/self.z_, w/self.contextual_action_bound, r)
self.Reward.append(reward[i])
self.gpreps.learn(self.z_/self.z_)
# self.gpreps.a = Aa[-1][:, :1]
# self.gpreps.A = Aa[-1][:, 1:]
print('Episode imported, size:', len(self.Reward), len(self.gpreps.memory))
t = 0
for i in range(len(state)):
if state[i][0] == 0:
t += 1
if t == 31:
break
self.State.append(state[i])
self.IM_Action.append(action[i])
print('State data imported, size:', len(self.State))
"main"
for k in range(self.K):
print('Training cycle', k)
# run RL and collect data
print('Running RL...')
self.train()
# 'Sample and Update Policy'
# if k >= 1:
# # train_model = True
# '第0,1,3,5,7,9...周期拟合forward model'
# if k % 4 == 1:
# train_model = True
# else:
# train_model = False
# self.gpreps.artificial_trajectory(self.State, self.IM_Action, self.L, self.policy, train_model)
if k >= 0:
self.gpreps.learn(self.z_/self.z_)
print('************ Training cycle finished **************')
print('')
class GPREPS(object):
def __init__(self, z_dim, w_dim, memory_dim, z_, w_bound):
# initialize parameters
self.memory = []
self.pointer = 0
self.w_dim, self.z_dim, self.memory_dim, self.z_, self.w_bound = w_dim, z_dim, memory_dim, z_, w_bound
# build actor
self.a = np.zeros((w_dim, 1), dtype=np.float32)
self.a[0][0] = -0.1
self.a[1][0] = 0.1
self.A = np.zeros((w_dim, z_dim), dtype=np.float32)
self.COV = np.eye((w_dim), dtype=np.float32) / 10
self.COV_index = 50
self.Aa = []
print('initial COV matrix:')
print(self.COV)
# impedance bound
self.action_bound = np.array([0.23, 0.23, 0.75, 0.06, 0.06, 0.03])
self.dpos_bound = np.array([0.190, 0.157, 0.745, 0.110, 0.086, 0.012])
self.force_bound = np.array([9.39, 9.32, 8.70, 1.00, 0.87, 0.92])
self.pos_bound = np.array([1.96, 1.99, 23.93, 0.009, 0.06, 0.010])
self.state_bound = np.hstack([self.force_bound, self.pos_bound])
def choose_action(self, z):
z = np.array([z])
u = self.a + np.dot(self.A, z.transpose())
u = u.transpose()[0]
return np.clip(np.random.multivariate_normal(mean=u, cov=self.COV, size=1) * self.w_bound, -self.w_bound, self.w_bound)
def learn(self, z_):
'learning'
eta, theta = argmin(self.memory, z_, self.z_dim)
p = 0.
P_ = []
Z = []
B = []
for i in range(len(self.memory)):
z, w, r = self.memory[i]
z = np.array([z])
w = np.array(w)
r = np.array([r])
p = np.exp((r - np.dot(z, theta)) / eta)
z_ = np.c_[np.array([1.]), z]
Z.append(z_[0])
B.append(w)
P_.append(p[0])
P_, B, Z = np.array(P_), np.array(B), np.array(Z)
P = P_ * np.eye(len(self.memory))
'calculate mean action'
target1 = np.linalg.inv(np.dot(np.dot(Z.transpose(), P), Z))
# print(np.shape(P), np.shape(Z.transpose()), np.shape(B))
target2 = np.dot(np.dot(Z.transpose(), P), B)
target = np.dot(target1, target2).transpose()
self.a = target[:, :1]
self.A = target[:, 1:]
# calculate the COV
Err = 0
for i in range(len(self.memory)):
z, w, r = self.memory[i]
z = np.array([z])
w = np.array([w])
err = w - self.a - np.dot(self.A, z.transpose())
Err += np.dot(err, err.transpose()) * P_[i]
self.COV = Err / np.sum(P_) / self.COV_index
# self.COV_index *= 1.25
print('Upper Policy COV:', self.COV * self.COV_index)
print('Contextual policy search upper level parameters updated')
'record policy'
self.Aa.append(target)
np.save('Contextual_Policy_Search_Aa.npy', self.Aa)
def store_data(self, z, w, r):
transition = [z, w, [r]]
if len(self.memory) == self.memory_dim:
index = self.pointer % self.memory_dim # replace the old memory with new memory
self.memory[index] = transition
else:
self.memory.append(transition)
self.pointer += 1
def train_model(self, state_, action_):
print('Start training forward model')
"Parameters"
nb_samples = 2
input_dim = 12
output_dim = 6
in_idx_state = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
out_idx_state = [12, 13, 14, 15, 16, 17]
in_idx_force = [0, 1, 2, 3, 4, 5]
out_idx_force = [6, 7, 8, 9, 10, 11]
in_idx_mean = [0]
out_idx_mean = [1, 2, 3, 4, 5, 6]
nb_states = 8
'data'
if len(state_) >= 5000:
state_ = np.array(state_)[-5000:]
action_ = np.array(action_)[-5000:]
else:
state_ = np.array(state_)
action_ = np.array(action_)
print('data size', np.shape(state_), np.shape(action_))
'phase searching'
state = []
dpos = []
action = []
for i in range(len(state_) - 1):
if state_[i + 1][0] != 0:
if state_[i][9] >= -6.5:
state.append(state_[i][1:])
dpos.append(state_[i + 1][7:] - state_[i][7:])
action.append(action_[i])
state = np.array(state)
pos = state[:, 6:]
force = state[:, :6]
dpos = np.array(dpos)
action = np.array(action)
input = np.hstack([pos/self.pos_bound, action/self.action_bound])
output = dpos/self.dpos_bound
data_state = np.hstack([input, output])
print(np.shape(data_state))
'train gpr model'
kernel = DotProduct() + WhiteKernel()
self.gpr_force_model = GaussianProcessRegressor(kernel=kernel,
random_state=0).fit(pos/self.pos_bound, force/self.force_bound)
self.gpr_state_model = GaussianProcessRegressor(kernel=kernel,
random_state=0).fit(input, output)
'stage insertion'
state = []
dpos = []
action = []
for i in range(len(state_) - 1):
if state_[i + 1][0] != 0:
if state_[i][9] <= -5.5:
state.append(state_[i][1:])
dpos.append(state_[i + 1][7:] - state_[i][7:])
action.append(action_[i])
state = np.array(state)
pos = state[:, 6:]
force = state[:, :6]
data_force = np.hstack([pos, force]) / np.hstack([self.pos_bound, self.force_bound])
dpos = np.array(dpos)
action = np.array(action)
input = np.hstack([pos/self.pos_bound, action/self.action_bound])
output = dpos/self.dpos_bound
data_state = np.hstack([input, output])
self.gmr_force_model = Gmr(nb_states=nb_states, nb_dim=12, in_idx=in_idx_force, out_idx=out_idx_force)
self.gmr_force_model.init_params_kbins(data_force.T, nb_samples=nb_samples)
self.gmr_force_model.gmm_em(data_force.T)
self.gmr_state_model = Gmr(nb_states=nb_states, nb_dim=18, in_idx=in_idx_state, out_idx=out_idx_state)
self.gmr_state_model.init_params_kbins(data_state.T, nb_samples=nb_samples)
self.gmr_state_model.gmm_em(data_state.T)
def artificial_trajectory(self, State, Action, L, RL_policy, train_model):
if train_model:
self.train_model(State, Action)
state = 0
t = 0
for i in range(len(State)):
if State[i][0] == 0:
state += State[i][1:]
t += 1
state_init = state / t
print('initial state:', state_init)
REWARD = []
cal = calculation()
l = 0
while l < L:
# contextual parameters
z = np.random.randint(0, 4, 1) * 50 + 100
cal.set_context(z)
w = self.choose_action(z/self.z_)[0]
cal.set_pd(w)
# initialize the observation
done = False
safe = True
R = 0
var = np.array([0, 0, 0, 0, 0, 0, 1., 1., 0, 0, 0, 0])
state = np.random.normal(state_init, var)
cal.reset()
"start a trajecory"
for i in range(300):
"choose action"
# action = RL_policy.select_action(np.array(state / self.state_bound))
action = np.array([0, 0, 0, 0, 0, 0])
im_action = cal.step(state, action, i)
"step"
'calculate dpos'
if state[8] >= -6.:
dpos, _ = self.gpr_state_model.predict([np.hstack([state[6:] / self.pos_bound, im_action / self.action_bound])], return_std=1, return_cov=0)
dpos = dpos[0]
dpos *= self.dpos_bound
else:
dpos, cov_dpos, _ = self.gmr_state_model.gmr_predict(np.hstack([state[6:] / self.pos_bound, im_action / self.action_bound]))
dpos *= self.dpos_bound
cov_dpos = cov_dpos * self.dpos_bound ** 2 / 16
dpos = np.random.multivariate_normal(mean=dpos, cov=cov_dpos, size=1)[0]
'problem check'
if dpos[2] == 0:
safe = False
if not safe:
print('trajectory failed')
break
'calculate pos'
pos = state[6:] + dpos
'calculate force'
if state[8] >= -6.:
force, _ = self.gpr_force_model.predict([pos/self.pos_bound], return_std=1, return_cov=0)
force = force[0]
force *= self.force_bound
else:
force, cov_force, _ = self.gmr_force_model.gmr_predict(pos / self.pos_bound)
force *= self.force_bound
cov_force = cov_force * self.force_bound ** 2 / 16
force = np.random.multivariate_normal(mean=force, cov=cov_force, size=1)[0]
'calculate new state'
new_state = np.hstack([force, pos])
reward, done, safe = cal.get_reward(state, new_state, i)
'update parameters'
state = new_state.copy()
R += reward
if done or not safe:
if i == 299:
REWARD.append([z[0], w, i, R, 'Unfinished'])
print('trajectory episode', l, 'step', i, w, 'reward', R, 'Unfinished')
elif safe == False:
REWARD.append([z[0], w, i, R, 'Failed'])
print('trajectory episode', l, 'step', i, w, 'reward', R, 'Failed')
else:
REWARD.append([z[0], w, i, R, 'Successful'])
print('trajectory episode', l, 'step', i, w, 'reward', R, 'Successful')
self.store_data(z/self.z_, w/self.w_bound, R)
l += 1
break
# **** 程序结构 ****
solver = Solver()
solver.contextual_main()
|
kelu124/pyS3
|
org/apache/poi/ss/formula/FormulaParser$SimpleRangePart.java
|
package org.apache.poi.ss.formula;
import org.apache.poi.ss.util.CellReference;
final class FormulaParser$SimpleRangePart {
private final String _rep;
private final Type _type;
private enum Type {
CELL,
ROW,
COLUMN;
public static Type get(boolean hasLetters, boolean hasDigits) {
if (hasLetters) {
return hasDigits ? CELL : COLUMN;
} else {
if (hasDigits) {
return ROW;
}
throw new IllegalArgumentException("must have either letters or numbers");
}
}
}
public FormulaParser$SimpleRangePart(String rep, boolean hasLetters, boolean hasNumbers) {
this._rep = rep;
this._type = Type.get(hasLetters, hasNumbers);
}
public boolean isCell() {
return this._type == Type.CELL;
}
public boolean isRowOrColumn() {
return this._type != Type.CELL;
}
public CellReference getCellReference() {
if (this._type == Type.CELL) {
return new CellReference(this._rep);
}
throw new IllegalStateException("Not applicable to this type");
}
public boolean isColumn() {
return this._type == Type.COLUMN;
}
public boolean isRow() {
return this._type == Type.ROW;
}
public String getRep() {
return this._rep;
}
public boolean isCompatibleForArea(FormulaParser$SimpleRangePart part2) {
return this._type == part2._type;
}
public String toString() {
StringBuilder sb = new StringBuilder(64);
sb.append(getClass().getName()).append(" [");
sb.append(this._rep);
sb.append("]");
return sb.toString();
}
}
|
pbaris/jmix
|
jmix-security/security-ui/src/main/java/io/jmix/securityui/role/annotation/MenuPolicy.java
|
<reponame>pbaris/jmix<gh_stars>10-100
/*
* Copyright 2020 Haulmont.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.jmix.securityui.role.annotation;
import io.jmix.security.role.annotation.ResourceRole;
import java.lang.annotation.*;
/**
* Defines menu resource policy in annotated resource role. Multiple {@code MenuPolicy} annotations may be placed on a single
* method. {@code MenuPolicy} annotation may present on multiple methods of the same class. Annotated method may have
* any name and return type.
* <p>
* Example:
* <pre>
* @ResourceRole(name = "My Role", code = "myRole")
* public interface MyRole {
*
* @MenuPolicy(menuIds = {"menu1", "menuItem1"})
* @MenuPolicy(menuIds = "menuItem1")
* void menus();
* }
* </pre>
*
* @see ResourceRole
* @see io.jmix.security.model.ResourcePolicy
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(MenuPolicyContainer.class)
public @interface MenuPolicy {
String[] menuIds() default {};
}
|
netyjq/data-center
|
data-center-service/src/main/java/com/yjq/data/service/alarm/MailSendHandler.java
|
package com.yjq.data.service.alarm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;
import java.util.Properties;
/**
* @author <EMAIL>
* @date 2018/4/9
*/
@Component
public class MailSendHandler implements InitializingBean {
public static final Logger logger = LoggerFactory.getLogger(MailSendHandler.class);
/**
* 发送告警的邮箱账号
*/
@Value("${alarm.mail.address}")
private String SENDER;
/**
* 发送告警的邮箱密码
*/
@Value("${alarm.mail.password}")
private String PASSWORD;
/**
* 邮箱服务器
*/
@Value("${alarm.mail.server}")
private String MAIL_SERVER_HOST;
private JavaMailSenderImpl mailSender;
/**
* 发送邮件
* @param receiver 收件人邮箱
* @param subject 邮件主题
* @param content 邮件内容
*/
protected boolean send(String receiver, String subject, String content) {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setTo(receiver);
simpleMailMessage.setFrom(SENDER);
simpleMailMessage.setSubject(subject);
simpleMailMessage.setText(content);
try {
mailSender.send(simpleMailMessage);
logger.info(">>> 告警邮件发送成功. receiver: {}, content: {}", receiver, content);
} catch (Exception e) {
logger.error(">>> 告警邮件发送异常. receiver: {}, content: {}", receiver, content, e);
return false;
}
return true;
}
@Override
public void afterPropertiesSet() throws Exception {
mailSender = new JavaMailSenderImpl();
mailSender.setUsername(SENDER);
mailSender.setPassword(PASSWORD);
// 发件人邮箱的 SMTP 服务器地址
mailSender.setHost(MAIL_SERVER_HOST);
mailSender.setPort(465);
//协议SMTP+SSL
mailSender.setProtocol("smtps");
mailSender.setDefaultEncoding("utf-8");
Properties javaMailProperties = new Properties();
javaMailProperties.put("mail.smtp.ssl.enable", true);
mailSender.setJavaMailProperties(javaMailProperties);
}
}
|
laukvik/csv-view
|
src/main/java/no/laukvik/csvview/utils/FileChooserExtensions.java
|
package no.laukvik.csvview.utils;
import javafx.stage.FileChooser;
/**
* JavaFX helper methods.
*
*/
public final class FileChooserExtensions {
/**
* All supported FileChooser Extensions.
*/
public static final FileChooser.ExtensionFilter[] SUPPORTED_EXTENSIONS = {
buildCSV(), buildTSV(), buildResourceBundle(), buildTextFile(), buildJsonFile(), buildHtmlFile(), buildXmlFile()
};
/**
* Hide constructor in this builder class.
*/
private FileChooserExtensions() {
}
public static FileChooser.ExtensionFilter buildCompatible() {
return new FileChooser.ExtensionFilter("All formats", "*.csv", "*.tsv");
}
/**
* Extension for CSV files.
*
* @return filter
*/
public static FileChooser.ExtensionFilter buildTSV() {
return new FileChooser.ExtensionFilter("Tab separated files", "*.tsv");
}
/**
* Extension for CSV files.
*
* @return filter
*/
public static FileChooser.ExtensionFilter buildCSV() {
return new FileChooser.ExtensionFilter("Comma separated files", "*.csv");
}
/**
* Extension for ResourceBundle files.
* @return filter
*/
public static FileChooser.ExtensionFilter buildResourceBundle() {
return new FileChooser.ExtensionFilter("Resource bundles", "*.properties");
}
/**
* Extension for TXT files.
* @return filter
*/
private static FileChooser.ExtensionFilter buildTextFile() {
return new FileChooser.ExtensionFilter("Text files", "*.txt");
}
/**
* Extension for JSON files.
* @return filter
*/
public static FileChooser.ExtensionFilter buildJsonFile() {
return new FileChooser.ExtensionFilter("JSON files", "*.json");
}
/**
* Extension for HTML files.
* @return filter
*/
public static FileChooser.ExtensionFilter buildHtmlFile() {
return new FileChooser.ExtensionFilter("HTML files", "*.html");
}
/**
* Extension for XML files.
* @return filter
*/
public static FileChooser.ExtensionFilter buildXmlFile() {
return new FileChooser.ExtensionFilter("XML files", "*.xml");
}
}
|
sidorovpavel/writing-javascript-actions
|
.github/actions/joke-action/node_modules/lodash/fp/all.js
|
module.exports = require('lodash/fp/every');
|
gnicol/GitSwarm
|
perforce_swarm/validation_tests/lib/config.rb
|
<filename>perforce_swarm/validation_tests/lib/config.rb
class CONFIG
P4_PORT = 'p4_port'.freeze
P4_USER = 'p4_user'.freeze
P4_PASSWORD = '<PASSWORD>'.freeze
P4_DEPOT_ROOT = 'p4_gitswarm_depot_root'.freeze
GS_URL = 'gitswarm_url'.freeze
GS_USER = 'gitswarm_username'.freeze
GS_PASSWORD = '<PASSWORD>'.freeze
SECURE_GF = 'secure_git_fusion'.freeze
SECURE_GF_DEPOT_ROOT = 'secure_git_fusion_depot_root'.freeze
RUN_ID = 'run_id'.freeze # static run_id for test development (enforce_permissions_spec)
SKIP_SETUP = 'skip_setup'.freeze # skip setup for test development (enforce_permissions_spec)
SKIP_TEARDOWN = 'skip_teardown'.freeze # skip teardown for test development (enforce_permissions_spec)
@config = nil
# One time only
unless @config
# Load Config
LOG.info('Loading config...')
@config = YAML.load_file('config.yml')
LOG.info @config
LOG.level(@config['log_level']) if @config['log_level']
end
def self.get(property)
@config[property]
end
def self.set(property, value)
@config[property] = value
end
end
|
Prospector/RebornCore
|
src/main/java/reborncore/common/recipes/ExtendedRecipeRemainder.java
|
<reponame>Prospector/RebornCore<gh_stars>0
package reborncore.common.recipes;
import net.minecraft.item.ItemStack;
public interface ExtendedRecipeRemainder {
default ItemStack getRemainderStack(ItemStack stack){
return ItemStack.EMPTY;
}
}
|
stephenfin/pypowervm
|
pypowervm/tasks/master_mode.py
|
# Copyright 2015 IBM Corp.
#
# 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.
"""Tasks to request and release master mode."""
from oslo_config import cfg
from oslo_log import log as logging
import pypowervm.const as c
import pypowervm.log as lgc
from pypowervm.wrappers import job
import pypowervm.wrappers.managed_system as ms
LOG = logging.getLogger(__name__)
CONF = cfg.CONF
_SUFFIX_PARM_REQUEST_MASTER = 'RequestMaster'
_SUFFIX_PARM_RELEASE_MASTER = 'ReleaseMaster'
CO_MGMT_MASTER_STATUS = "coManagementMasterStatus"
class MasterMode(object):
"""Valid master modes used when requesting master.
NORMAL: Default mode
TEMP: When released, the original master is immediately restored.
"""
NORMAL = "norm"
TEMP = "temp"
@lgc.logcall
def request_master(msys, mode=MasterMode.NORMAL,
timeout=CONF.pypowervm_job_request_timeout):
"""Request master mode for the provided Managed System.
:param msys: Managed System wrapper requesting master mode
:param mode: The requested master mode type.
There are 2 options:
MasterMode.NORMAL ("norm"): default
MasterMode.TEMP ("temp"): when released, the original
master is immediately restored
:param timeout: maximum number of seconds for job to complete
"""
resp = msys.adapter.read(ms.System.schema_type, msys.uuid,
suffix_type=c.SUFFIX_TYPE_DO,
suffix_parm=_SUFFIX_PARM_REQUEST_MASTER)
job_wrapper = job.Job.wrap(resp.entry)
job_parms = [job_wrapper.create_job_parameter(CO_MGMT_MASTER_STATUS,
mode)]
job_wrapper.run_job(msys.uuid, job_parms=job_parms, timeout=timeout)
@lgc.logcall
def release_master(msys, timeout=CONF.pypowervm_job_request_timeout):
"""Release master mode for the provided Managed System.
:param msys: Managed System wrapper requesting master mode
:param timeout: maximum number of seconds for job to complete
"""
resp = msys.adapter.read(ms.System.schema_type, msys.uuid,
suffix_type=c.SUFFIX_TYPE_DO,
suffix_parm=_SUFFIX_PARM_RELEASE_MASTER)
job_wrapper = job.Job.wrap(resp.entry)
job_wrapper.run_job(msys.uuid, timeout=timeout)
|
prolog/shadow-of-the-wyrm
|
engine/maps/tiles/features/source/IFeatureManipulatorFactory.cpp
|
<filename>engine/maps/tiles/features/source/IFeatureManipulatorFactory.cpp
#include "IFeatureManipulatorFactory.hpp"
#include "DefaultFeatureManipulator.hpp"
#include "FenceManipulator.hpp"
#include "ForgeManipulator.hpp"
#include "PewManipulator.hpp"
#include "GoodAltarManipulator.hpp"
#include "NeutralAltarManipulator.hpp"
#include "EvilAltarManipulator.hpp"
#include "DoorGateManipulator.hpp"
#include "BarrelManipulator.hpp"
#include "JewelerWorkbenchManipulator.hpp"
#include "KilnManipulator.hpp"
#include "PulperManipulator.hpp"
#include "SarcophagusManipulator.hpp"
#include "SlotMachineManipulator.hpp"
#include "TableManipulator.hpp"
#include "TanneryManipulator.hpp"
#include "TrapManipulator.hpp"
#include "WheelAndLoomManipulator.hpp"
FeatureManipulatorPtr IFeatureManipulatorFactory::create_manipulator(FeaturePtr feature)
{
FeatureManipulatorPtr manipulator;
if (feature != nullptr)
{
ClassIdentifier class_id = feature->get_class_identifier();
if (class_id == ClassIdentifier::CLASS_ID_PEW)
{
manipulator = std::make_unique<PewManipulator>(feature);
}
else if (class_id == ClassIdentifier::CLASS_ID_GOOD_ALTAR)
{
manipulator = std::make_unique<GoodAltarManipulator>(feature);
}
else if (class_id == ClassIdentifier::CLASS_ID_NEUTRAL_ALTAR)
{
manipulator = std::make_unique<NeutralAltarManipulator>(feature);
}
else if (class_id == ClassIdentifier::CLASS_ID_EVIL_ALTAR)
{
manipulator = std::make_unique<EvilAltarManipulator>(feature);
}
else if (class_id == ClassIdentifier::CLASS_ID_DOOR || class_id == ClassIdentifier::CLASS_ID_GATE)
{
manipulator = std::make_unique<DoorGateManipulator>(feature);
}
else if (class_id == ClassIdentifier::CLASS_ID_BARREL)
{
manipulator = std::make_unique<BarrelManipulator>(feature);
}
else if (class_id == ClassIdentifier::CLASS_ID_FORGE)
{
manipulator = std::make_unique<ForgeManipulator>(feature);
}
else if (class_id == ClassIdentifier::CLASS_ID_JEWELER_WORKBENCH)
{
manipulator = std::make_unique<JewelerWorkbenchManipulator>(feature);
}
else if (class_id == ClassIdentifier::CLASS_ID_TANNERY)
{
manipulator = std::make_unique<TanneryManipulator>(feature);
}
else if (class_id == ClassIdentifier::CLASS_ID_WHEEL_AND_LOOM)
{
manipulator = std::make_unique<WheelAndLoomManipulator>(feature);
}
else if (class_id == ClassIdentifier::CLASS_ID_TRAP)
{
manipulator = std::make_unique<TrapManipulator>(feature);
}
else if (class_id == ClassIdentifier::CLASS_ID_SARCOPHAGUS)
{
manipulator = std::make_unique<SarcophagusManipulator>(feature);
}
else if (class_id == ClassIdentifier::CLASS_ID_TABLE)
{
manipulator = std::make_unique<TableManipulator>(feature);
}
else if (class_id == ClassIdentifier::CLASS_ID_SLOT_MACHINE)
{
manipulator = std::make_unique<SlotMachineManipulator>(feature);
}
else if (class_id == ClassIdentifier::CLASS_ID_PULPER)
{
manipulator = std::make_unique<PulperManipulator>(feature);
}
else if (class_id == ClassIdentifier::CLASS_ID_KILN)
{
manipulator = std::make_unique<KilnManipulator>(feature);
}
else if (class_id == ClassIdentifier::CLASS_ID_FENCE)
{
manipulator = std::make_unique<FenceManipulator>(feature);
}
// All other features
else
{
manipulator = std::make_unique<DefaultFeatureManipulator>(feature);
}
}
return manipulator;
}
|
R-Layer/Bears-Team-22
|
server/components/search/search-routes.js
|
const express = require("express");
const {getQuestion, prepopulate} = require("./search-controller");
const router = express.Router(); // eslint-disable-line new-cap
router.get("/search", getQuestion);
router.get("/pre-populate", prepopulate);
module.exports = router;
|
sensera/objectagon-core
|
object/src/bdd/java/feature/util/TaskWait.java
|
<reponame>sensera/objectagon-core
package feature.util;
import org.objectagon.core.exception.ErrorClass;
import org.objectagon.core.exception.ErrorKind;
import org.objectagon.core.exception.SevereError;
import org.objectagon.core.exception.UserException;
import org.objectagon.core.msg.Message;
import org.objectagon.core.msg.message.SimpleMessage;
import org.objectagon.core.msg.protocol.StandardProtocol;
import org.objectagon.core.task.Task;
/**
* Created by christian on 2016-03-17.
*/
public class TaskWait {
private final Task task;
private boolean completed = false;
private Message.MessageName messageName;
private Iterable<Message.Value> values;
private StandardProtocol.ErrorClass errorClass;
private StandardProtocol.ErrorKind errorKind;
private TaskWait(Task task) {
this.task = task;
}
public static TaskWait create(Task task) {
return new TaskWait(task);
}
public Message startAndWait(long timeout) throws UserException {
task.addFailedAction(this::failed)
.addSuccessAction(this::success)
.start();
synchronized (this) {
if (!completed) {
try {
wait(timeout);
} catch (InterruptedException e) {
e.printStackTrace();
throw new SevereError(ErrorClass.UNKNOWN, ErrorKind.TIMEOUT);
}
if (!completed)
throw new UserException(ErrorClass.UNKNOWN, ErrorKind.TIMEOUT);
if (messageName==null)
throw new UserException(errorClass, errorKind, values);
}
return SimpleMessage.simple(messageName, values);
}
}
private synchronized void success(Message.MessageName messageName, Iterable<Message.Value> values) {
this.messageName = messageName;
this.values = values;
completed = true;
this.notifyAll();
}
private synchronized void failed(StandardProtocol.ErrorClass errorClass, StandardProtocol.ErrorKind errorKind, Iterable<Message.Value> values) {
this.errorClass = errorClass;
this.errorKind = errorKind;
this.values = values;
completed = true;
this.notifyAll();
}
}
|
Abdirahman0022/cawo
|
external/go-server-server/go/model_offer_passenger.go
|
/*
* AirGateway NDC JSON API
*
* This API allows shopping and booking with IATA's New Distribution Capabilities (NDC) standard. It provides aggregated shopping capabilities (AirShopping), detailed offer description (OfferPrice), flight seat selection (SeatAvailability) and booking flight reservations (OrderCreate). Some fields in our API (when noticed) use the PADIS Standard v16.1. Find more information <a href=http://www.iata.org/whatwedo/workgroups/Pages/padis.aspx>here</a>
*
* API version: 1.1
* Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)
*/
package swagger
// Recognized Travelers list
type OfferPassenger struct {
// Traveler given name
Given string `json:"given,omitempty"`
PassengerType string `json:"passengerType"`
// Traveler surname
Surname string `json:"surname,omitempty"`
// Traveler title
Title string `json:"title,omitempty"`
// Traveler object key
TravelerReference string `json:"travelerReference"`
}
|
PW486/leetcode
|
solutions/cpp/42-trapping-rain-water.cc
|
<reponame>PW486/leetcode
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int trap(vector<int> &height) {
int trap = 0, minHeight = 0;
int front = 0, back = height.size() - 1;
while (front < back) {
if (height[front] > minHeight && height[back] > minHeight) {
trap +=
(min(height[front], height[back]) - minHeight) * (back - front + 1);
minHeight = min(height[front], height[back]);
}
if (height[front] < height[back]) {
trap -= height[front];
front++;
} else {
trap -= height[back];
back--;
}
}
trap -= minHeight;
return trap;
}
};
int main() {
vector<int> height = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
cout << Solution().trap(height) << endl;
return 0;
}
|
vkola-lab/multi-task
|
lookupcsv/derived_tables/NACC/match_csf.py
|
import csv
from collections import defaultdict
import datetime
mriTable = 'zip_id_data_6months.csv'
csfTable = '../../raw_tables/NACC/kolachalama06022020csf.csv'
mriMap = defaultdict(dict)
with open(mriTable, 'r') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
id = row['ID']
time = (int(row['Year']), int(row['Month']), int(row['Day']))
mriMap[id][time] = row['zipname']
# print(mriMap)
csfMap = defaultdict(dict)
with open(csfTable, 'r') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
id = row['NACCID']
time = (int(row['CSFLPYR']), int(row['CSFLPMO']), int(row['CSFLPDY']))
csfMap[id][time] = [row['CSFABETA'], row['CSFPTAU'], row['CSFTTAU']]
print(csfMap)
def find_closest(mri_time, diags):
min_diff = 1000000
ans = None
mriDate = datetime.date(*mri_time)
diagTimes = diags.keys()
for time in diagTimes:
diagDate = datetime.date(*time)
diff = diagDate - mriDate
diff = abs(diff.days)
if diff < min_diff and diff < 183: # within +/- 6 months
min_diff = diff
ans = time
return ans
content = []
for id in mriMap:
if id not in csfMap:
continue
mris = mriMap[id]
csfs = csfMap[id]
print(id, '---------------------------------------------')
print(mris)
print(csfs)
pairs = []
for mri_time in mris:
csf_time = find_closest(mri_time, csfs)
if not csf_time: continue
# if csfs[csf_time][0] == '': continue
pairs.append((mris[mri_time], id, csfs[csf_time], csf_time))
print(pairs)
content.extend(pairs)
with open('mri_csf_table_6months.csv', 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=['zipname', 'ID', 'CSFABETA', 'CSFPTAU', 'CSFTTAU'])
writer.writeheader()
case = {}
for row in content:
case['zipname'] = row[0]
case['ID'] = row[1]
for i, vari in enumerate(['CSFABETA', 'CSFPTAU', 'CSFTTAU']):
case[vari] = row[2][i]
writer.writerow(case)
|
dmgerman/hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/docker/TestDockerVolumeCommand.java
|
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * 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. */
end_comment
begin_package
DECL|package|org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.docker
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|server
operator|.
name|nodemanager
operator|.
name|containermanager
operator|.
name|linux
operator|.
name|runtime
operator|.
name|docker
package|;
end_package
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Assert
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Test
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|junit
operator|.
name|Assert
operator|.
name|assertEquals
import|;
end_import
begin_class
DECL|class|TestDockerVolumeCommand
specifier|public
class|class
name|TestDockerVolumeCommand
block|{
annotation|@
name|Test
DECL|method|testDockerVolumeCommand ()
specifier|public
name|void
name|testDockerVolumeCommand
parameter_list|()
block|{
name|DockerVolumeCommand
name|dockerVolumeCommand
init|=
operator|new
name|DockerVolumeCommand
argument_list|(
literal|"create"
argument_list|)
decl_stmt|;
name|assertEquals
argument_list|(
literal|"volume"
argument_list|,
name|dockerVolumeCommand
operator|.
name|getCommandOption
argument_list|()
argument_list|)
expr_stmt|;
name|Assert
operator|.
name|assertTrue
argument_list|(
name|dockerVolumeCommand
operator|.
name|getDockerCommandWithArguments
argument_list|()
operator|.
name|get
argument_list|(
literal|"sub-command"
argument_list|)
operator|.
name|contains
argument_list|(
literal|"create"
argument_list|)
argument_list|)
expr_stmt|;
name|dockerVolumeCommand
operator|.
name|setDriverName
argument_list|(
literal|"driver1"
argument_list|)
expr_stmt|;
name|dockerVolumeCommand
operator|.
name|setVolumeName
argument_list|(
literal|"volume1"
argument_list|)
expr_stmt|;
name|Assert
operator|.
name|assertTrue
argument_list|(
name|dockerVolumeCommand
operator|.
name|getDockerCommandWithArguments
argument_list|()
operator|.
name|get
argument_list|(
literal|"driver"
argument_list|)
operator|.
name|contains
argument_list|(
literal|"driver1"
argument_list|)
argument_list|)
expr_stmt|;
name|Assert
operator|.
name|assertTrue
argument_list|(
name|dockerVolumeCommand
operator|.
name|getDockerCommandWithArguments
argument_list|()
operator|.
name|get
argument_list|(
literal|"volume"
argument_list|)
operator|.
name|contains
argument_list|(
literal|"volume1"
argument_list|)
argument_list|)
expr_stmt|;
block|}
block|}
end_class
end_unit
|
Sally7/demo
|
src/api/MilitiaService.js
|
<gh_stars>0
/**
* Created by mac on 18/1/9.
*/
import http from '@/utils/Request'
const MilitiaService = {
async doSearch(pformId){
var res = await http({
url: 'dyform_doSearchDynamicForms.do',
data: {pformId:pformId}
});
return res;
},
async ageStatistics(type,archivesAreaId,townId,villageId){
var res = await http({
url: 'user_doStatisticsUserDynamicForm.do',
data: {type:'age',userSearch:{
archivesAreaId:archivesAreaId,townId:townId,villageId:villageId,archiveType:2
}}
});
return res;
},
async politicalIdentityStatistics(type,archivesAreaId,townId,villageId){
var res = await http({
url: 'user_doStatisticsUserDynamicForm.do',
data: {type:'politicalIdentity',userSearch:{
archivesAreaId:archivesAreaId,townId:townId,villageId:villageId,archiveType:2
}}
});
return res;
},
async specialtyStatistics(formItemId,type,archivesAreaId,townId,villageId){
var res = await http({
url: 'user_doStatisticsUserDynamicForm.do',
data: {formItemId:'4028475a5c9df54b015c9df96aa00477',type:'militaryProfessional',userSearch:{
archivesAreaId:archivesAreaId,townId:townId,villageId:villageId,archiveType:2
}}
});
return res;
},
async educationStatistics(formItemId,type,archivesAreaId,townId,villageId){
var res = await http({
url: 'user_doStatisticsUserDynamicForm.do',
data: {type:'education',userSearch:{
archivesAreaId:archivesAreaId,townId:townId,villageId:villageId,archiveType:2
}}
});
return res;
},
async armyYearStatistics(type,archivesAreaId,townId,villageId){
var res = await http({
url: 'user_doStatisticsUserDynamicForm.do',
data: {type:'armyYear',userSearch:{
archivesAreaId:archivesAreaId,townId:townId,villageId:villageId,archiveType:2
}}
});
return res;
},
async allAreaStatistics(townId,villageId,archivesAreaId){
var res = await http({
url: 'user_doStatisticsAreaUserDynamicForm.do',
data: {userSearch:{townId:townId,archivesAreaId:archivesAreaId,villageId:villageId,archiveType:2}}
});
return res;
},
async militiaTypeStatistics(townId,villageId,archivesAreaId,valueIds,formItemId,type){
var res = await http({
url: 'user_doStatisticsAreaUserDynamicForm.do',
data: {userSearch:{townId:townId,villageId:villageId,archivesAreaId:archivesAreaId,archiveType:2},valueIds:valueIds,formItemId:'4028475a5c9df54b015c9df96aa00447',type:'areaMilitiaType'}
});
return res;
},
}
export default MilitiaService
|
StepSim/Quabla
|
src/quabla/simulator/dynamics/DynamicsTrajectory.java
|
package quabla.simulator.dynamics;
import quabla.simulator.Coordinate;
import quabla.simulator.numerical_analysis.vectorOperation.MathematicalMatrix;
import quabla.simulator.numerical_analysis.vectorOperation.MathematicalVector;
import quabla.simulator.rocket.Rocket;
import quabla.simulator.variable.AbstractVariable;
/**
* DynamicsTrajectory is an extension of {@link quabla.simulator.dynamics.AbstractDynamics}.
* */
public class DynamicsTrajectory extends AbstractDynamics {
private Rocket rocket;
MathematicalVector velENU = new MathematicalVector();
MathematicalVector omegaBODY = new MathematicalVector();
MathematicalVector velAirENU = new MathematicalVector();
MathematicalVector velAirBODY = new MathematicalVector();
MathematicalVector windENU = new MathematicalVector();
MathematicalVector gENU = new MathematicalVector();
MathematicalVector thrust = new MathematicalVector ();
MathematicalVector forceAero = new MathematicalVector ();
MathematicalVector forceENU = new MathematicalVector ();
MathematicalVector accENU = new MathematicalVector ();
MathematicalVector armMoment = new MathematicalVector();
MathematicalVector momentAero = new MathematicalVector();
MathematicalVector momentAeroDamping = new MathematicalVector();
MathematicalVector momentJetDamping = new MathematicalVector();
MathematicalVector momentGyro = new MathematicalVector();
MathematicalVector omegadot = new MathematicalVector();
DynamicsMinuteChangeTrajectory delta = new DynamicsMinuteChangeTrajectory();
public DynamicsTrajectory(Rocket rocket) {
this.rocket = rocket;
}
@Override
public DynamicsMinuteChangeTrajectory calculateDynamics(AbstractVariable variable) {
// Import variable
velENU = variable.getVelENU();
omegaBODY = variable.getOmegaBODY();
MathematicalVector quat = new MathematicalVector(Coordinate.nomalizeQuat(variable.getQuat().toDouble()));
double altitude = variable.getAltitude();
double t = variable.getTime();
double m = rocket.getMass(t);
double mDot = rocket.mdot(t);
double p = omegaBODY.toDouble(0);
double q = omegaBODY.toDouble(1);
double r = omegaBODY.toDouble(2);
// Translation coodinate
MathematicalMatrix dcmENU2BODY = new MathematicalMatrix(Coordinate.getDCM_ENU2BODYfromQuat(quat.toDouble()));
MathematicalMatrix dcmBODY2ENU = dcmENU2BODY.transpose();
// alpha , beta
windENU.set(rocket.wind.getWindENU(altitude));
velAirENU = velENU.sub(windENU);
velAirBODY = dcmENU2BODY.dot(velAirENU);
double velAirAbs = velAirBODY.norm();
double v = velAirBODY.toDouble(1);
double w = velAirBODY.toDouble(2);
double alpha , beta; //angle of atack , angle of side-slip
if(velAirAbs <= 0.0) {
alpha = 0.0;
beta = 0.0;
}else {
alpha = Math.asin(w / velAirAbs);
beta = Math.asin(v / velAirAbs);
}
// Environment
gENU.set(0.0 , 0.0 , - rocket.atm.getGravity(altitude));
double P0 = rocket.atm.getAtomosphericPressure(0.0);
double P = rocket.atm.getAtomosphericPressure(altitude);
double rho = rocket.atm.getAirDensity(altitude);
double Cs = rocket.atm.getSoundSpeed(altitude);
double Mach = velAirAbs / Cs;
double pressureDynamics = 0.5 * rho * Math.pow(velAirAbs, 2);
// Thrust
if(rocket.engine.thrust(t) > 0.0) {
double thrustPressure = (P0 - P)* rocket.engine.Ae;
thrust.set(rocket.engine.thrust(t) + thrustPressure, 0.0, 0.0);
}else {
thrust.set(MathematicalVector.ZERO);
}
// Aero Force
double drag = pressureDynamics * rocket.aero.Cd(Mach) * rocket.S;
double normal = pressureDynamics * rocket.aero.CNa(Mach) * rocket.S * alpha;
double side = pressureDynamics * rocket.aero.CNa(Mach) * rocket.S * beta;
forceAero.set(- drag , - side , - normal);
// Newton Equation
forceENU = dcmBODY2ENU.dot(thrust.add(forceAero));
// Accelaration
accENU = forceENU.multiply(1 / m).add(gENU);
// Center of Gravity , Pressure
double lcg = rocket.getLcg(t);
double lcgProp = rocket.getLcgProp(t);
double lcp = rocket.aero.Lcp(Mach);
// Momento of Inertia
double IjRoll = rocket.getIjRoll(t);
double IjPitch = rocket.getIjPitch(t);
double[] Ij = {IjRoll, IjPitch, IjPitch};
double IjDotPitch = rocket.getIjDotPitch(t);
double IjDotRoll = rocket.getIjDotRoll(t);
double[] IjDot = {IjDotRoll, IjDotPitch, IjDotPitch};
// Aero Moment
armMoment.set(lcg - lcp, 0.0, 0.0);
momentAero = armMoment.cross(forceAero);
// Aero Damping Moment
momentAeroDamping .set(
pressureDynamics * rocket.aero.Clp * rocket.S * (0.5*Math.pow(rocket.D, 2)/velAirAbs) * p,
pressureDynamics * rocket.aero.Cmq * rocket.S * (0.5*Math.pow(rocket.L, 2)/velAirAbs) * q,
pressureDynamics * rocket.aero.Cnr * rocket.S * (0.5*Math.pow(rocket.L, 2)/velAirAbs) * r);
// Jet Damping Moment
momentJetDamping.set(
(- IjDot[0] - mDot * 0.5 * (0.25*Math.pow(rocket.engine.de, 2))) * p,
(- IjDot[1] - mDot * (Math.pow(lcg - lcgProp, 2) - Math.pow(rocket.L - lcgProp, 2))) * q,
(- IjDot[2] - mDot * (Math.pow(lcg - lcgProp, 2) - Math.pow(rocket.L - lcgProp, 2))) * r);
momentGyro.set(
(Ij[1] - Ij[2])*q*r,
(Ij[2] - Ij[0])*p*r,
(Ij[0] - Ij[1])*p*q);
MathematicalVector moment = momentGyro.add(momentAero).add(momentAeroDamping).add(momentJetDamping);
omegadot.set(
moment.toDouble(0) / Ij[0],
moment.toDouble(1) / Ij[1],
moment.toDouble(2) / Ij[2]);
// Kinematics Equation
MathematicalMatrix tensor = new MathematicalMatrix(Coordinate.Omega_tensor(p, q, r));
MathematicalVector quatdot = tensor.dot(quat).multiply(0.5);
delta.setDeltaPosENU(velENU);
delta.setDeltaVelENU(accENU);
delta.setDeltaOmegaBODY(omegadot);
delta.setDeltaQuat(quatdot);
return delta;
}
}
|
kamranrad1993/ngfx
|
includes/ngfx/porting/vulkan/VKBlit.h
|
/*
* Copyright 2020 GoPro Inc.
*
* 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.
*/
#pragma once
#include <vulkan/vulkan.h>
namespace ngfx {
struct VKBlit {
struct Region {
VkOffset3D p0, p1;
};
static void
blitImage(VkCommandBuffer cmdBuffer, VkImage srcImage, uint32_t srcLevel,
VkImage dstImage, uint32_t dstLevel, Region srcRegion,
Region dstRegion, uint32_t srcBaseLayer = 0,
uint32_t srcLayerCount = 1, uint32_t dstBaseLayer = 0,
uint32_t dstLayerCount = 1,
VkImageLayout srcImageLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
VkImageLayout dstImageLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
VkFilter filter = VK_FILTER_LINEAR);
};
}; // namespace ngfx
|
bound1ess/codeforces-problemset-2
|
244/a.cpp
|
#include <cstdio>
const int N = 1234;
int a[N], b[N];
int main() {
freopen("input", "rt", stdin);
freopen("output", "wt", stdout);
int n, k;
scanf("%d%d", &n, &k);
for (int i = 0; i < k; ++i) {
scanf("%d", a + i);
--a[i];
}
for (int i = 0; i < n * k; ++i) {
b[i] = -1;
}
for (int i = 0; i < k; ++i) {
b[a[i]] = i;
}
for (int i = 0; i < k; ++i) {
for (int j = 0; j < n - 1; ++j) {
for (int q = 0; q < n * k; ++q) {
if (b[q] == -1) {
b[q] = i;
break;
}
}
}
}
for (int i = 0; i < k; ++i) {
bool first = true;
for (int j = 0; j < n; ++j) {
for (int q = 0; q < n * k; ++q) {
if (b[q] != i) {
continue;
}
if ( ! first) {
putchar(' ');
} else {
first = false;
}
printf("%d", q + 1);
b[q] = -1;
}
}
putchar('\n');
}
return 0;
}
|
dmzgroup/dmz
|
frameworks/object/plugins/timeout/dmzObjectPluginTimeout.cpp
|
<gh_stars>1-10
#include <dmzEventModuleCommon.h>
#include <dmzObjectAttributeMasks.h>
#include <dmzObjectModule.h>
#include <dmzRuntimeConfig.h>
#include <dmzRuntimeConfigToTypesBase.h>
#include <dmzRuntimeObjectType.h>
#include <dmzRuntimePluginFactoryLinkSymbol.h>
#include <dmzRuntimePluginInfo.h>
#include "dmzObjectPluginTimeout.h"
/*!
\class dmz::ObjectPluginTimeout
\ingroup Object
\brief Destroys local objects of specified types after a defined interval.
\details The plugin uses the timeout field in the object-type definition. If the timeout
field is defined, all local object of that object type will be destroyed after the
specified time has elapsed. If the detonate parameter is set to true, the plugin
will create a detonation event before deleting the object.
\code
<dmz>
<runtime>
<object-type name="object name">
<timeout value="time is seconds" detonate="true/false"/>
</object-type>
</runtime>
</dmz>
\endcode
*/
//! \cond
dmz::ObjectPluginTimeout::ObjectPluginTimeout (const PluginInfo &Info, Config &local) :
Plugin (Info),
TimeSlice (Info),
ObjectObserverUtil (Info, local),
_log (Info),
_eventMod (0),
_defaultTimeout (new TimeoutStruct (False, -1.0)) {
_init (local);
}
dmz::ObjectPluginTimeout::~ObjectPluginTimeout () {
_timeoutTable.clear ();
if (_defaultTimeout) { delete _defaultTimeout; _defaultTimeout = 0; }
_masterTimeoutTable.empty ();
}
// Plugin Interface
void
dmz::ObjectPluginTimeout::update_plugin_state (
const PluginStateEnum State,
const UInt32 Level) {
if (State == PluginStateInit) {
}
else if (State == PluginStateStart) {
}
else if (State == PluginStateStop) {
}
else if (State == PluginStateShutdown) {
}
}
void
dmz::ObjectPluginTimeout::discover_plugin (
const PluginDiscoverEnum Mode,
const Plugin *PluginPtr) {
if (Mode == PluginDiscoverAdd) {
if (!_eventMod) { _eventMod = EventModuleCommon::cast (PluginPtr); }
}
else if (Mode == PluginDiscoverRemove) {
if (_eventMod && (_eventMod == EventModuleCommon::cast (PluginPtr))) {
_eventMod = 0;
}
}
}
// TimeSlice Interface
void
dmz::ObjectPluginTimeout::update_time_slice (const Float64 DeltaTime) {
HashTableHandleIterator it;
TimeoutStruct *ptr (0);
while (_objTable.get_next (it, ptr)) {
ptr->timeout -= DeltaTime;
if (ptr->timeout < 0.0) {
const Handle Object (it.get_hash_key ());
ObjectModule *objMod = get_object_module ();
if (objMod) {
if (ptr->Detonate && _eventMod) {
_eventMod->create_detonation_event (Object, 0);
}
objMod->destroy_object (Object);
}
}
}
}
// Object Observer Interface
void
dmz::ObjectPluginTimeout::create_object (
const UUID &Identity,
const Handle ObjectHandle,
const ObjectType &Type,
const ObjectLocalityEnum Locality) {
if (Locality == ObjectLocal) {
TimeoutStruct *ts = _find_timeout (Type);
if (ts && (ts->timeout > 0.0)) {
TimeoutStruct *ptr = new TimeoutStruct (*ts);
if (ptr && !_objTable.store (ObjectHandle, ptr)) { delete ptr; ptr = 0; }
}
}
}
void
dmz::ObjectPluginTimeout::destroy_object (
const UUID &Identity,
const Handle ObjectHandle) {
TimeoutStruct *ptr = _objTable.remove (ObjectHandle);
if (ptr) { delete ptr; ptr = 0; }
}
dmz::ObjectPluginTimeout::TimeoutStruct *
dmz::ObjectPluginTimeout::_find_timeout (const ObjectType &Type) {
ObjectType current (Type);
TimeoutStruct *result = _timeoutTable.lookup (current.get_handle ());
while (!result && current) {
const Float64 Timeout =
config_to_float64 ("timeout.value", current.get_config (), -1.0);
const Boolean Detonate =
config_to_boolean ("timeout.detonate", current.get_config (), False);
if (Timeout > 0.0) {
result = new TimeoutStruct (Detonate, Timeout);
if (result && _masterTimeoutTable.store (current.get_handle (), result)) {
_timeoutTable.store (Type.get_handle (), result);
}
else if (result) { delete result; result = 0; }
current.set_type_context (0);
}
else {
current.become_parent ();
if (current) {
result = _timeoutTable.lookup (current.get_handle ());
if (result) { _timeoutTable.store (Type.get_handle (), result); }
}
}
}
if (!result) {
_timeoutTable.store (Type.get_handle (), _defaultTimeout);
}
return result;
}
void
dmz::ObjectPluginTimeout::_init (Config &local) {
activate_default_object_attribute (ObjectCreateMask | ObjectDestroyMask);
}
//! \endcond
extern "C" {
DMZ_PLUGIN_FACTORY_LINK_SYMBOL dmz::Plugin *
create_dmzObjectPluginTimeout (
const dmz::PluginInfo &Info,
dmz::Config &local,
dmz::Config &global) {
return new dmz::ObjectPluginTimeout (Info, local);
}
};
|
66254264/BasePopup
|
app/src/main/java/razerdp/demo/ui/transition/SubsamplingScaleImageViewSharedTransition.java
|
<filename>app/src/main/java/razerdp/demo/ui/transition/SubsamplingScaleImageViewSharedTransition.java
package razerdp.demo.ui.transition;
import android.animation.Animator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Point;
import android.graphics.PointF;
import android.os.Build;
import android.transition.Transition;
import android.transition.TransitionValues;
import android.util.AttributeSet;
import android.view.ViewGroup;
import androidx.annotation.RequiresApi;
import com.davemorrissey.labs.subscaleview.ImageViewState;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import razerdp.basepopup.R;
/**
* Created by 大灯泡 on 2019/8/26
* <p>
* Description:大图浏览transition
*/
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class SubsamplingScaleImageViewSharedTransition extends Transition {
private static final String PROPNAME_STATE = "com.example:transition:state";
private static final String PROPNAME_SIZE = "com.example:transition:size";
private static final String PROPNAME_CENTER_X = "com.example:transition:center_x";
private static final String PROPNAME_CENTER_Y = "com.example:transition:center_y";
private static final int FIT_CENTER = 0;
private static final int CENTER_CROP = 1;
private int subsamplingScaleType;
private int imageViewScaleType;
private int direction;
/**
* For manual creation through code. Initializes transition with all default values and no specified targets.
*/
public SubsamplingScaleImageViewSharedTransition() {
imageViewScaleType = 0;
direction = 0;
subsamplingScaleType = 0;
}
/**
* Created from XML, targets {@link SubsamplingScaleImageView} class.
*/
public SubsamplingScaleImageViewSharedTransition(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SubsamplingScaleImageViewSharedTransition);
direction = a.getInt(R.styleable.SubsamplingScaleImageViewSharedTransition_transitionDirection, 0);
subsamplingScaleType = a.getInt(R.styleable.SubsamplingScaleImageViewSharedTransition_subsamplingImageViewScaleType, FIT_CENTER);
imageViewScaleType = a.getInt(R.styleable.SubsamplingScaleImageViewSharedTransition_imageViewScaleType, FIT_CENTER);
a.recycle();
addTarget(SubsamplingScaleImageView.class);
}
@Override
public void captureStartValues(TransitionValues transitionValues) {
captureValues(transitionValues);
}
@Override
public void captureEndValues(TransitionValues transitionValues) {
captureValues(transitionValues);
}
private void captureValues(TransitionValues transitionValues) {
if (transitionValues.view instanceof SubsamplingScaleImageView) {
Point size = new Point(transitionValues.view.getWidth(), transitionValues.view.getHeight());
transitionValues.values.put(PROPNAME_SIZE, size);
SubsamplingScaleImageView ssiv = (SubsamplingScaleImageView) transitionValues.view;
transitionValues.values.put(PROPNAME_STATE, ssiv.getState());
}
}
@Override
public Animator createAnimator(ViewGroup sceneRoot, TransitionValues startValues, TransitionValues endValues) {
if (startValues == null || endValues == null) {
return null;
}
ImageViewState subsamplingState = (ImageViewState) startValues.values.get(PROPNAME_STATE);
Point startSize = (Point) startValues.values.get(PROPNAME_SIZE);
Point endSize = (Point) endValues.values.get(PROPNAME_SIZE);
if (startSize == null || endSize == null || subsamplingState == null || startSize.equals(endSize)) {
return null;//missing some values, don't animate
}
final SubsamplingScaleImageView view = (SubsamplingScaleImageView) startValues.view;
Point imgSize = new Point(view.getSWidth(), view.getSHeight());
if (imgSize.x == 0 || imgSize.y == 0) {
return null; //no image size, skip animation.
}
//resolve transition direction (enter or leaving), assumes enter if view gets larger
boolean isEntering = direction == 0 ? (startSize.x < endSize.x || startSize.y < endSize.y) : direction == 1;
final PointF centerFrom;
float scaleFrom;
float scaleTo;
ValueAnimator valueAnimator;
PointF centerTo = new PointF(imgSize.x / 2, imgSize.y / 2);
if (isEntering) {
centerFrom = new PointF(imgSize.x / 2, imgSize.y / 2);
scaleFrom = getMinIfTrue(startSize.x / (float) imgSize.x, startSize.y / (float) imgSize.y,
imageViewScaleType == FIT_CENTER);
scaleTo = getMinIfTrue(imgSize.x / (float) endSize.x, imgSize.y / (float) endSize.y,
subsamplingScaleType == FIT_CENTER);
} else {
centerFrom = subsamplingState.getCenter();
scaleFrom = subsamplingState.getScale();
scaleTo = getMinIfTrue(endSize.x / (float) imgSize.x, endSize.y / (float) imgSize.y,
imageViewScaleType == FIT_CENTER);
}
PropertyValuesHolder prop_scale = PropertyValuesHolder.ofFloat(PROPNAME_SIZE, scaleFrom, scaleTo);
PropertyValuesHolder prop_center_x = PropertyValuesHolder.ofFloat(PROPNAME_CENTER_X, centerFrom.x, centerTo.x);
PropertyValuesHolder prop_center_y = PropertyValuesHolder.ofFloat(PROPNAME_CENTER_Y, centerFrom.y, centerTo.y);
valueAnimator = ValueAnimator.ofPropertyValuesHolder(prop_scale, prop_center_x, prop_center_y);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
PointF newCenter = new PointF((float) animation.getAnimatedValue(PROPNAME_CENTER_X), (float) animation
.getAnimatedValue(PROPNAME_CENTER_Y));
view.setScaleAndCenter((float) animation.getAnimatedValue(PROPNAME_SIZE), newCenter);
}
});
return valueAnimator;
}
/**
* Does {@link Math#min(float, float)} or {@link Math#max(float, float)} depending on boolean.
*
* @param val1 value to compare
* @param val2 value to compare
* @param con condition to check
* @return If <code>con</code> return minimum of 2 values, otherwise return max.
*/
private float getMinIfTrue(float val1, float val2, boolean con) {
return con ? Math.min(val1, val2) : Math.max(val1, val2);
}
public SubsamplingScaleImageViewSharedTransition setSubsamplingScaleType(int subsamplingScaleType) {
this.subsamplingScaleType = subsamplingScaleType;
return this;
}
public SubsamplingScaleImageViewSharedTransition setImageViewScaleType(int imageViewScaleType) {
this.imageViewScaleType = imageViewScaleType;
return this;
}
public SubsamplingScaleImageViewSharedTransition setDirection(int direction) {
this.direction = direction;
return this;
}
}
|
czs108/LeetCode-Solutions
|
Easy/35. Search Insert Position/solution (1).py
|
<filename>Easy/35. Search Insert Position/solution (1).py
# 35. Search Insert Position
# Runtime: 44 ms, faster than 91.82% of Python3 online submissions for Search Insert Position.
# Memory Usage: 14.5 MB, less than 5.97% of Python3 online submissions for Search Insert Position.
class Solution:
def searchInsert(self, nums: list[int], target: int) -> int:
if target in nums:
return nums.index(target)
else:
for i in range(len(nums)):
if nums[i] >= target:
return i
return len(nums)
|
oneofsunshine/program_learning
|
C_C++/oop_assignment/courseTest/copyConstructor.cpp
|
#include<iostream>
using namespace std;
class A
{
public:
int v;
A(int n) {
v = n;
cout<<"Constructor called"<<endl;
}
A(const A & a) {
v = a.v;
cout<<"Copy constructor called"<<endl;
}
};
A Func() {
A b(4);
return b;
}
int main()
{
cout<<Func().v<<endl;
return 0;
}
|
jonatas-rezende/estatistica_web
|
codigos/Estatistica/src/br/com/estatisticaweb/modelo/dto/Projeto.java
|
package br.com.estatisticaweb.modelo.dto;
/**
* Classe para representação de um artigo
* @author Aluno
*/
public class Projeto {
private Integer id;
private String nome;
private Integer quantidadeRepeticoes;
private Double significancia;
private Integer teste;
private Usuario usuario;
//Função que retorna um identificador de um artigo
public Integer getId() {
return id;
}
//Função que modifica o identficador de um artigo
public void setId(Integer id) {
this.id = id;
}
//Função que retorna um nome de um projeto
public String getNome() {
return nome;
}
//Função que modifica um nome de um projeto
public void setNome(String nome) {
this.nome = nome;
}
//Função que retorna um repeticao de um projeto
public Integer getQuantidadeRepeticoes() {
return quantidadeRepeticoes;
}
//Função que modifica o repeticao de um projeto
public void setQuantidadeRepeticoes(Integer quantidadeRepeticoes) {
this.quantidadeRepeticoes = quantidadeRepeticoes;
}
//Função que retorna um significancia de um projeto
public Double getSignificancia() {
return significancia;
}
//Função que modifica o significancia de um projeto
public void setSignificancia(Double significancia) {
this.significancia = significancia;
}
//Função que retorna um teste de um projeto
public Integer getTeste() {
return teste;
}
//Função que modifica um teste de um projeto
public void setTeste(Integer teste) {
this.teste = teste;
}
//Função que retorna um usuario de um projeto
public Usuario getUsuario() {
return usuario;
}
//Função que modifica o usuario de um projeto
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
}
|
bytebin/deepworld-gameserver
|
server/messages/dialog_message.rb
|
class DialogMessage < BaseMessage
configure compression: true
data_fields :dialog_id, :config
end
|
Jay-Y/yServer
|
system/system-jpa-core/src/main/java/modules/system/svc/impl/DictServiceImpl.java
|
<filename>system/system-jpa-core/src/main/java/modules/system/svc/impl/DictServiceImpl.java
package modules.system.svc.impl;
import modules.system.dao.DictDao;
import modules.system.model.Dict;
import modules.system.svc.DictService;
import modules.system.svc.base.SysBaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.yserver.core.datasource.DataSource;
import java.util.List;
/**
* Description: DictServiceImpl.<br>
* Date: 2016/9/14 20:09<br>
* Author: ysj
*/
@Service
@DataSource("default")
@Transactional
public class DictServiceImpl extends SysBaseServiceImpl<Dict, DictDao> implements DictService
{
@Autowired
private DictDao dao;
@Override
public DictDao getDao()
{
return dao;
}
@Override
public List<Dict> findListByType(String type)
{
return dao.findListByType(type);
}
}
|
wakeyefei/blog2019
|
java11httpclient/server/src/main/java/ch/rasc/httpclient/User.java
|
<filename>java11httpclient/server/src/main/java/ch/rasc/httpclient/User.java
package ch.rasc.httpclient;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class User {
private final long id;
private final String username;
@JsonCreator
public User(@JsonProperty("id") long id,
@JsonProperty("username") String username) {
this.id = id;
this.username = username;
}
public long getId() {
return this.id;
}
public String getUsername() {
return this.username;
}
@Override
public String toString() {
return "User [id=" + this.id + ", username=" + this.username + "]";
}
}
|
IsaaColomer/Vroom
|
Vroom/src/Modules/Editor.cpp
|
#include "Globals.h"
#include "Application.h"
#include "Editor.h"
#include "ModuleInput.h"
#include <stdlib.h>
#include <fstream>
#include <string>
#include "imgui.h"
#include "imgui/backends/imgui_impl_sdl.h"
#include "imgui/backends/imgui_impl_opengl3.h"
#include "SDL_opengl.h"
#include "MeshComponent.h"
extern std::list<std::string> logH;
Editor::Editor(Application* app, bool start_enabled) : Module(app, start_enabled)
{
}
Editor::~Editor()
{
}
bool Editor::Start()
{
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
ImGui::StyleColorsDark();
ImGui_ImplSDL2_InitForOpenGL(App->window->window, App->renderer3D->context);
ImGui_ImplOpenGL3_Init();
columns = 64;
fps_log.push_back(0.f);
ms_log.push_back(0.f);
// ------------------- READ THE ABOUT SECTION FROMT TXT FILE -------------------
std::ifstream aboutFile;
aboutFile.open("About.txt");
std::string str;
while (std::getline(aboutFile, str))
{
aboutText += str += "\n";
}
aboutFile.close();
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;
return true;
}
void Editor::RecursiveTree(GameObject* go)
{
ImGuiTreeNodeFlags parentFlags = ImGuiTreeNodeFlags_None | ImGuiTreeNodeFlags_FramePadding | ImGuiTreeNodeFlags_DefaultOpen | (go->gameObjects.empty() ? ImGuiTreeNodeFlags_Leaf : 0);
if (go == selectedNode)
{
parentFlags |= ImGuiTreeNodeFlags_Selected;
}
bool open = ImGui::TreeNodeEx(go->name.c_str(), parentFlags);
if (ImGui::IsItemHovered() && ImGui::IsMouseReleased(ImGuiMouseButton_::ImGuiMouseButton_Left))
{
selectedNode = go;
}
if (open) {
// Recursive call...
for (size_t i = 0; i < go->gameObjects.size(); i++)
{
RecursiveTree(go->gameObjects.at(i));
};
ImGui::TreePop();
}
}
update_status Editor::Update(float dt)
{
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplSDL2_NewFrame();
ImGui::NewFrame();
// ------------------- TOP MENU -------------------
if (showDemoWindow)
ImGui::ShowDemoWindow(&showDemoWindow);
ImGui::BeginMainMenuBar();
if (ImGui::BeginMenu("Options"))
{
if (ImGui::MenuItem("Settings"))
{
settings = !settings;
}
ImGui::EndMenu();
}
// ------------------- PRINT FPS -------------------
if (settings)
{
ImGui::Begin("General Options", &settings);
if (ImGui::CollapsingHeader("Application Settings"))
{
sprintf_s(configName, 25, ENGINENAME);
ImGui::InputText("App Name", configName, 25);
sprintf_s(configName, 25, UNIVERSITY);
ImGui::InputText("University Name", configName, 25);
if (ImGui::CollapsingHeader("Performace Information"))
{
if (ImGui::SliderInt("Frame Rate Limit", &App->maxFps, 1.0f, 144.0f))
{
}
sprintf_s(title, 25, "Framerate %.1f", fps_log[fps_log.size() - 1]);
ImGui::PlotHistogram("##framerate", &fps_log[0], fps_log.size(), 0, title, 0.0f, 100.0f, ImVec2(310, 100));
sprintf_s(title, 25, "Milliseconds %.1f", ms_log[ms_log.size() - 1]);
ImGui::PlotHistogram("##milliseconds", &ms_log[0], ms_log.size(), 0, title, 0.0f, 100.0f, ImVec2(310, 100));
}
}
if (ImGui::CollapsingHeader("Screen Settings"))
{
if (ImGui::Checkbox("\tToggle Fullscreen", &fullscreen))
{
App->window->SetFullscreen(fullscreen);
}
if (ImGui::Checkbox("\tToggle Resizable", &resizable))
{
}
ImGui::SameLine();
if (ImGui::Checkbox("\tToggle FullscreenDesktop", &fullscreenDesktop))
{
App->window->SetFullscreenDesktop(fullscreenDesktop);
}
if (resizable)
{
if (ImGui::SliderFloat("Width", &App->window->winWidth, 500, 1920))
{
App->window->SetWindowSize();
}
if (ImGui::SliderFloat("Height", &App->window->winHeight, 500, 1080))
{
App->window->SetWindowSize();
}
}
if (ImGui::Checkbox("\tToggle Borderless", &borderless))
{
App->window->SetResizable(borderless);
}
if (ImGui::SliderFloat("Brightness", &App->window->brightness, 0.0f, 1.0f))
{
App->window->SetWindowBrightness();
}
}
if (ImGui::CollapsingHeader("System Information"))
{
ImGui::Text("Ram memory of the System: ");
ImGui::SameLine();
ImGui::TextColored({255,255,0,1},"%d Gb", SDL_GetSystemRAM() / 1024);
ImGui::Text("CPU threats count:");
ImGui::SameLine();
ImGui::TextColored({255,255,0,1},"%d", SDL_GetCPUCount());
ImGui::Text("GPU: ");
ImGui::SameLine();
ImGui::TextColored({ 255,255,0,1 }, "%s", glGetString(GL_RENDERER));
SDL_version version;
SDL_GetVersion(&version);
ImGui::Text("SDL Version:");
ImGui::SameLine();
ImGui::TextColored(ImVec4(1, 1, 0, 1), "%d.%d.%d", version.major, version.minor, version.patch);
ImGui::Text("OpenGL Version:");
ImGui::SameLine();
ImGui::TextColored(ImVec4(1, 1, 0, 1), "%s", glGetString(GL_VERSION));
}
if (ImGui::Button("Save", { 50, 50 }))
{
App->SaveEditorConfiguration();
App->LoadEditorConfiguration();
}
ImGui::End();
}
if (console)
{
ImGui::SetNextWindowPos(ImVec2(0, App->window->winHeight-ch));
ImGui::SetNextWindowSize(ImVec2(ImGui::GetWindowWidth(), 200));
ImGui::Begin("Console");
for (auto& a : logH)
{
ImGui::TextWrapped(a.c_str());
}
ImGui::End();
}
if (ImGui::BeginMenu("Help"))
{
if (ImGui::MenuItem("GUI Demo"))
{
showDemoWindow = !showDemoWindow;
}
if (ImGui::MenuItem("Documentation"))
{
App->RequestBrowser("https://github.com/IsaaColomer/Vroom/wiki");
}
if (ImGui::MenuItem("Vroom GitHub"))
{
App->RequestBrowser("https://github.com/IsaaColomer/Vroom");
}
if (ImGui::MenuItem("Download latest"))
{
App->RequestBrowser("https://github.com/IsaaColomer/Vroom/releases");
}
if (ImGui::MenuItem("Report a bug"))
{
App->RequestBrowser("https://github.com/IsaaColomer/Vroom/issues");
}
if (ImGui::MenuItem("About"))
{
showAboutWindow = !showAboutWindow;
}
ImGui::EndMenu();
}
if (showAboutWindow)
{
ImGui::Begin("About", &showAboutWindow);
ImGui::Text("%s", aboutText.c_str());
ImGui::End();
}
if (ImGui::BeginMenu("Exit"))
{
if (ImGui::MenuItem("Close"))
{
return UPDATE_STOP;
}
ImGui::EndMenu();
}
if (inspector)
InspectorDraw();
if (ImGui::BeginMenu("Create"))
{
if (ImGui::MenuItem("Cube"))
{
App->scene_intro->LoadCube();
}
if (ImGui::MenuItem("Sphere"))
{
App->scene_intro->LoadSphere();
}
if (ImGui::MenuItem("Cylinder"))
{
App->scene_intro->LoadCylinder();
}
ImGui::EndMenu();
}
if (hier)
{
ImGui::SetNextWindowPos(ImVec2(0, ImGui::GetWindowHeight()));
ImGui::SetNextWindowSize(ImVec2(300,h));
ImGui::Begin("Hierarchy");
if (App->scene_intro->root != nullptr)
{
RecursiveTree(App->scene_intro->root);
}
ImGui::End();
}
if (fullscreenDesktop)
{
h = 1000;
ch = -280;
}
else
{
h = 500;
ch = 200;
}
// ------------------- CALLING THE FPS FUNCTION -------------------
CalculateFrames(&fps_log, dt, columns);
// ------------------- CALLING THE MS FUNCTION -------------------
CalculateMilliseconds(&ms_log, dt, columns);
ImGui::EndMainMenuBar();
ImGuiIO& io = ImGui::GetIO(); (void)io;
ImGui::Render();
glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y);
//glClearColor(clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w);
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
return UPDATE_CONTINUE;
}
bool Editor::CleanUp()
{
return true;
}
void Editor::CalculateFrames(std::vector<float>* fps_log, float dt, int columns)
{
// ------------------- CALCULATE FPS -------------------
if (fps_log->size() <= columns)
fps_log->push_back(1 / dt);
else
{
fps_log->erase(fps_log->begin());
fps_log->push_back(1 / dt);
}
}
void Editor::CalculateMilliseconds(std::vector<float>* ms_log, float dt, int columns)
{
// ------------------- MILLISECONDS FPS -------------------
if (ms_log->size() <= columns)
ms_log->push_back(dt*1000);
else
{
ms_log->erase(ms_log->begin());
ms_log->push_back(dt * 1000);
}
}
void Editor::InspectorDraw()
{
ImGui::SetNextWindowPos(ImVec2(ImGui::GetWindowWidth()-w, ImGui::GetWindowHeight()));
ImGui::SetNextWindowSize(ImVec2(w, h));
if (ImGui::Begin("Inspector"))
{
if (App->scene_intro->root != nullptr)
{
Transform* t = dynamic_cast<Transform*>(App->scene_intro->root->GetComponent(Component::Type::TRANSFORM));
if (App->scene_intro->root != nullptr)
{
for (int i = 0; i < App->scene_intro->root->gameObjects.size(); ++i)
{
if (App->scene_intro->root->gameObjects.at(i) == selectedNode)
{
Materialss* ma = App->scene_intro->root->gameObjects.at(i)->mat;
Meshs* m = App->scene_intro->root->gameObjects.at(i)->meshss;
if (ImGui::CollapsingHeader("Mesh"))
{
ImGui::Checkbox("Enable Mesh", &m->showMesh);
ImGui::Text("Path to fbx: %s", m->pathToFbx);
ImGui::Checkbox("Enable Normals", &m->showNormals);
}
if (ImGui::CollapsingHeader("Texture") && ma != nullptr)
{
ImGui::Checkbox("Enable Texture", &m->showTextures);
ImGui::Text("Path to file: %s", ma->pathToImage);
ImGui::Image((void*)(intptr_t)ma->inpectorImage, ImVec2(128, 128));
ImGui::Text("Width: %d | Height: %d", ma->tW, ma->tH);
}
for (int j = 0; j < App->scene_intro->root->gameObjects.at(i)->components.size(); ++j)
{
App->scene_intro->root->gameObjects.at(i)->components.at(j)->Draw();
if (App->input->GetKey(SDL_SCANCODE_F) == KEY_DOWN)
{
Transform* l = dynamic_cast<Transform*>(selectedNode->GetComponent(Component::Type::TRANSFORM));
App->camera->LookAt(l->position);
OUR_LOG("FOCUSED");
}
if (App->input->GetKey(SDL_SCANCODE_LALT) == KEY_REPEAT)
{
if (App->input->GetMouseButton(SDL_BUTTON_RIGHT) == KEY_REPEAT)
{
Transform* l = dynamic_cast<Transform*>(selectedNode->GetComponent(Component::Type::TRANSFORM));
App->camera->LookAt(l->position);
OUR_LOG("ROTATING AROUND OBJECT");
}
}
}
}
}
}
else
{
OUR_LOG("No object detected");
}
}
ImGui::End();
}
}
|
halaei/2048
|
js/have_fun.js
|
<filename>js/have_fun.js<gh_stars>1-10
function haveFun(size)
{
var configurations = {
3: {
initNumberOfTiles: 2,
numberOfRandomTiles: function(){return 1;},
getNewTileValue: function(){return 2;}
},
4: {
initNumberOfTiles: 3,
numberOfRandomTiles: function(){return 1;},
getNewTileValue: function(){return Math.random() < .7 ? 2 : 4;}
},
5: {
initNumberOfTiles: 3,
numberOfRandomTiles: function(){return 2;},
getNewTileValue: function(){return Math.random() < .9 ? 4 : 8;}
}
};
var conf = configurations[size] ? configurations[size]: configurations[5];
var game_div = document.getElementById("Triangular2048MainDiv");
var view = game_div.getElementsByClassName("canvas_view")[0];
var reset = game_div.getElementsByClassName("restart-button")[0];
var score = game_div.getElementsByClassName("score")[0];
var highscore = game_div.getElementsByClassName("highscore")[0];
var storage = new LocalStorageManager();
return new Game(
new Grid(size),
new StatusLog(storage),
[new KeyboardController(document), new TouchController(view), new Reset(reset)],
new CanvasView(view, size),
new Scorboard(score, highscore, 0, storage),
conf
);
}
|
iltempe/osmosi
|
sumo/tools/simpla/_platoonmode.py
|
<reponame>iltempe/osmosi
"""
@author <NAME>
@date 2017-04-09
-----------------------------------
SUMO, Simulation of Urban MObility; see http://sumo.dlr.de/
Copyright (C) 2008-2017 DLR (http://www.dlr.de/) and contributors
This file is part of SUMO.
SUMO 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.
-----------------------------------
"""
from enum import Enum
# Platoon modes
class PlatoonMode(Enum):
NONE = 0
LEADER = 1
FOLLOWER = 2
CATCHUP = 3
CATCHUP_FOLLOWER = 4
|
buck54321/gi
|
giv/textbuf/opts.go
|
<filename>giv/textbuf/opts.go
// Copyright (c) 2020, The GoKi Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package textbuf
import (
"github.com/goki/gi/gi"
"github.com/goki/ki/indent"
"github.com/goki/pi/filecat"
"github.com/goki/pi/pi"
)
// Opts contains options for TextBufs -- contains everything necessary to
// conditionalize editing of a given text file
type Opts struct {
gi.EditorPrefs `desc:"editor prefs from gogi prefs"`
CommentLn string `desc:"character(s) that start a single-line comment -- if empty then multi-line comment syntax will be used"`
CommentSt string `desc:"character(s) that start a multi-line comment or one that requires both start and end"`
CommentEd string `desc:"character(s) that end a multi-line comment or one that requires both start and end"`
}
// CommentStrs returns the comment start and end strings, using line-based CommentLn first if set
// and falling back on multi-line / general purpose start / end syntax
func (tb *Opts) CommentStrs() (comst, comed string) {
comst = tb.CommentLn
if comst == "" {
comst = tb.CommentSt
comed = tb.CommentEd
}
return
}
// IndentChar returns the indent character based on SpaceIndent option
func (tb *Opts) IndentChar() indent.Char {
if tb.SpaceIndent {
return indent.Space
}
return indent.Tab
}
// ConfigSupported configures options based on the supported language info in GoPi
// returns true if supported
func (tb *Opts) ConfigSupported(sup filecat.Supported) bool {
if sup == filecat.NoSupport {
return false
}
lp, ok := pi.StdLangProps[sup]
if !ok {
return false
}
tb.CommentLn = lp.CommentLn
tb.CommentSt = lp.CommentSt
tb.CommentEd = lp.CommentEd
for _, flg := range lp.Flags {
switch flg {
case pi.IndentSpace:
tb.SpaceIndent = true
case pi.IndentTab:
tb.SpaceIndent = false
}
}
return true
}
// SupportedComments returns the comment strings for supported file types,
// and returns the standard C-style comments otherwise.
func SupportedComments(fpath string) (comLn, comSt, comEd string) {
comLn = "//"
comSt = "/*"
comEd = "*/"
mtyp, _, err := filecat.MimeFromFile(fpath)
if err != nil {
return
}
sup := filecat.MimeSupported(mtyp)
if sup == filecat.NoSupport {
return
}
lp, ok := pi.StdLangProps[sup]
if !ok {
return
}
comLn = lp.CommentLn
comSt = lp.CommentSt
comEd = lp.CommentEd
return
}
|
kristiankime/calc-tutor
|
test/com/artclod/xml/NodesSpec.scala
|
<reponame>kristiankime/calc-tutor<gh_stars>1-10
package com.artclod.xml
import org.junit.runner.RunWith
import org.scalatestplus.play._
import play.api.test.Helpers._
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
class NodesSpec extends PlaySpec {
"nodeCount" should {
"be 1 for a single element" in {
Nodes.nodeCount(<a></a>) mustBe(1)
}
"be 3 for an element with two children" in {
Nodes.nodeCount(<top><a/><b/></top>) mustBe(3)
}
"be 4 for an element with two children, one of which has a child" in {
Nodes.nodeCount(<top><a><asub/></a><b/></top>) mustBe(4)
}
}
}
|
vdkkia/seek
|
lib/tasks/app.rake
|
require 'rubygems'
require 'rake'
namespace :app do
desc 'Displays the current version.'
task(version: :environment) do
puts Seek::Version.read
end
end
|
zzgchina888/msdn-code-gallery-microsoft
|
Official Windows Platform Sample/Windows 8.1 Store app samples/[C++]-Windows 8.1 Store app samples/Audio effects discovery sample/C++/RenderEffects.xaml.cpp
|
<reponame>zzgchina888/msdn-code-gallery-microsoft
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
//
// RenderEffects.xaml.cpp
// Implementation of the RenderEffects class
//
#include "pch.h"
#include "RenderEffects.xaml.h"
#include "ppl.h"
using namespace Windows::System;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Platform;
using namespace Windows::UI;
using namespace Windows::UI::Core;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Navigation;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::Storage;
using namespace Windows::Storage::Streams;
using namespace Windows::Media;
using namespace Windows::Media::MediaProperties;
using namespace Windows::Media::Capture;
using namespace Windows::Media::Devices;
using namespace Windows::Media::Effects;
using namespace SDKSample::AudioEffects;
using namespace concurrency;
String^ RenderEffects::CategoryTypeToString(AudioRenderCategory categoryType)
{
switch (categoryType)
{
case AudioRenderCategory::Other:
return L"Other";
case AudioRenderCategory::ForegroundOnlyMedia:
return L"ForegroundOnlyMedia";
case AudioRenderCategory::BackgroundCapableMedia:
return L"BackgroundCapableMedia";
case AudioRenderCategory::Communications:
return L"Communications";
case AudioRenderCategory::Alerts:
return L"Alerts";
case AudioRenderCategory::SoundEffects:
return L"SoundEffects";
case AudioRenderCategory::GameEffects:
return L"GameEffects";
case AudioRenderCategory::GameMedia:
return L"GameMedia";
default:
return L"Unknown";
}
}
String^ RenderEffects::EffectTypeToString(AudioEffectType effectType)
{
switch (effectType)
{
case AudioEffectType::Other:
return L"Other";
case AudioEffectType::AcousticEchoCancellation:
return L"AcousticEchoCancellation";
case AudioEffectType::NoiseSuppression:
return L"NoiseSuppression";
case AudioEffectType::AutomaticGainControl:
return L"AutomaticGainControl";
case AudioEffectType::BeamForming:
return L"BeamForming";
case AudioEffectType::ConstantToneRemoval:
return L"ConstantToneRemoval";
case AudioEffectType::Equalizer:
return L"Equalizer";
case AudioEffectType::LoudnessEqualizer:
return L"LoudnessEqualizer";
case AudioEffectType::BassBoost:
return L"BassBoost";
case AudioEffectType::VirtualSurround:
return L"VirtualSurround";
case AudioEffectType::VirtualHeadphones:
return L"VirtualHeadphones";
case AudioEffectType::SpeakerFill:
return L"SpeakerFill";
case AudioEffectType::RoomCorrection:
return L"RoomCorrection";
case AudioEffectType::BassManagement:
return L"BassManagement";
case AudioEffectType::EnvironmentalEffects:
return L"EnvironmentalEffects";
case AudioEffectType::SpeakerProtection:
return L"SpeakerProtection";
case AudioEffectType::SpeakerCompensation:
return L"SpeakerCompensation";
case AudioEffectType::DynamicRangeCompression:
return L"DynamicRangeCompression";
default:
return L"Unknown";
}
}
RenderEffects::RenderEffects()
{
m_DevicesListBox = nullptr;
m_EffectsListBox = nullptr;
m_EffectsLabel = nullptr;
m_CategoriesList = nullptr;
InitializeComponent();
ScenarioInit();
}
void RenderEffects::ScenarioInit()
{
if (m_DevicesListBox == nullptr)
{
m_DevicesListBox = safe_cast<ListBox^>(static_cast<IFrameworkElement^>(this)->FindName("DevicesList"));
}
if (m_EffectsListBox == nullptr)
{
m_EffectsListBox = safe_cast<ListBox^>(static_cast<IFrameworkElement^>(this)->FindName("EffectsList"));
}
if (m_EffectsLabel == nullptr)
{
m_EffectsLabel = safe_cast<TextBlock^>(static_cast<IFrameworkElement^>(this)->FindName("lblEffects"));
}
if (m_CategoriesList == nullptr)
{
m_CategoriesList = safe_cast<ComboBox^>(static_cast<IFrameworkElement^>(this)->FindName("CategoriesList"));
}
m_MonitorStarted = false;
m_RenderEffectsManager = nullptr;
m_DeviceList = nullptr;
m_EffectsLabel->Text = L"Effects";
DisplayEmptyEffectsList ();
DisplayEmptyDevicesList();
DisplayCategoriesList ();
}
void RenderEffects::ScenarioClose()
{
if (m_RenderEffectsManager != nullptr)
{
m_RenderEffectsManager->AudioRenderEffectsChanged -= m_renderEffectsRegistrationToken;
m_RenderEffectsManager = nullptr;
}
if (m_CategoriesList != nullptr)
{
m_CategoriesList->LayoutUpdated -= m_renderLayoutRegistrationToken;
}
}
void RenderEffects::ShowStatusMessage(String^ text)
{
rootPage->NotifyUser(text, NotifyType::StatusMessage);
}
void RenderEffects::ShowExceptionMessage(Exception^ ex)
{
rootPage->NotifyUser(ex->Message, NotifyType::ErrorMessage);
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
void RenderEffects::OnNavigatedTo(NavigationEventArgs^ e)
{
// A pointer back to the main page. This is needed if you want to call methods in MainPage such
// as NotifyUser()
rootPage = MainPage::Current;
}
void RenderEffects::OnNavigatedFrom(NavigationEventArgs^ e)
{
// A pointer back to the main page. This is needed if you want to call methods in MainPage such
// as NotifyUser()
ScenarioClose();
}
void RenderEffects::OnRenderEffectsChanged(AudioRenderEffectsManager ^ sender, Object^ e)
{
create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High,
ref new Windows::UI::Core::DispatchedHandler([this]()
{
IVectorView<AudioEffect^>^ EffectsList = m_RenderEffectsManager->GetAudioRenderEffects();
DisplayEffectsList( EffectsList );
})));
}
IVectorView<AudioEffect^>^ RenderEffects::UpdateEffectsList(AudioRenderEffectsManager ^& EffectsManager, Windows::Foundation::EventRegistrationToken& evttoken, String^ DeviceId, AudioRenderCategory cat, bool enableMonitor)
{
EffectsManager = AudioEffectsManager::CreateAudioRenderEffectsManager( DeviceId, cat, AudioProcessing::Default );
if (EffectsManager != nullptr)
{
if (enableMonitor)
{
evttoken = EffectsManager->AudioRenderEffectsChanged += ref new TypedEventHandler<AudioRenderEffectsManager ^, Object ^>(this, &RenderEffects::OnRenderEffectsChanged);
}
return EffectsManager->GetAudioRenderEffects();
}
else
{
return nullptr;
}
}
void RenderEffects::StartStopMonitor(Object^ sender, RoutedEventArgs^ e)
{
if ( m_MonitorStarted == true )
{
// Stop Monitoring
if (m_RenderEffectsManager != nullptr)
{
m_RenderEffectsManager->AudioRenderEffectsChanged -= m_renderEffectsRegistrationToken;
m_RenderEffectsManager = nullptr;
}
m_MonitorStarted = false;
// No longer in monitoring mode, re-enable "Refresh Effects List" button
btnRefreshEffects->IsEnabled = true;
m_EffectsLabel->Text = L"Effects";
DisplayEmptyEffectsList();
btnStartStopMonitor->Content = "Start Monitoring";
}
else
{
int j = -1;
AudioRenderCategory category = CategorySelected();
IVectorView<AudioEffect^>^ EffectsList = nullptr;
if ( m_DevicesListBox != nullptr )
{
j = m_DevicesListBox->SelectedIndex;
}
if (j < 0)
{
// No item selected in device list; just query audio effects active on the default render device
EffectsList = UpdateEffectsList(m_RenderEffectsManager, m_renderEffectsRegistrationToken, MediaDevice::GetDefaultAudioRenderId(AudioDeviceRole::Communications),
category, true);
m_EffectsLabel->Text = L"Effects Active on {Default Device}";
}
else
{
EffectsList = UpdateEffectsList(m_RenderEffectsManager, m_renderEffectsRegistrationToken, m_DeviceList->GetAt(j)->Id,
category, true);
m_EffectsLabel->Text = L"Effects Active on {" + m_DeviceList->GetAt(j)->Name + "}";
}
m_MonitorStarted = true;
// Now in monitoring mode, disable "Refresh Effects List" button
btnRefreshEffects->IsEnabled = false;
DisplayEffectsList(EffectsList);
btnStartStopMonitor->Content = "Stop Monitoring";
}
}
void RenderEffects::RefreshList(Object^ sender, RoutedEventArgs^ e)
{
int j = -1;
AudioRenderEffectsManager^ RenderEffectsManagerLocal = nullptr;
IVectorView<AudioEffect^>^ EffectsList = nullptr;
AudioRenderCategory category = CategorySelected();
if (m_DevicesListBox != nullptr)
{
j = m_DevicesListBox->SelectedIndex;
}
if (j < 0)
{
// No item selected in device list; just query audio effects active on the default render device
EffectsList = UpdateEffectsList(RenderEffectsManagerLocal, m_renderEffectsRegistrationToken, Windows::Media::Devices::MediaDevice::GetDefaultAudioRenderId(AudioDeviceRole::Communications),
category, false);
m_EffectsLabel->Text = L"Effects Active on {Default Device}";
}
else
{
EffectsList = UpdateEffectsList(RenderEffectsManagerLocal, m_renderEffectsRegistrationToken, m_DeviceList->GetAt(j)->Id,
category, false);
m_EffectsLabel->Text = L"Effects Active on {" + m_DeviceList->GetAt(j)->Name + "}";
}
DisplayEffectsList(EffectsList);
RenderEffectsManagerLocal = nullptr;
}
void RenderEffects::DisplayEmptyEffectsList()
{
m_EffectsListBox->Items->Clear();
m_EffectsListBox->Items->Append(L"Click \"Refresh Effects List\" or \"Start Monitoring\" to display audio effects");
m_EffectsListBox->IsEnabled = false;
}
void RenderEffects::DisplayEmptyDevicesList()
{
m_DevicesListBox->Items->Append(L"Click \"Enumerate Devices\" to display audio devices");
m_DevicesListBox->IsEnabled = false;
}
void RenderEffects::DisplayCategoriesList()
{
m_CategoriesList->Items->Clear();
for (AudioRenderCategory category = AudioRenderCategory::Other; category <= AudioRenderCategory::GameMedia; category++ )
{
m_CategoriesList->Items->Append(CategoryTypeToString(category));
}
m_renderLayoutRegistrationToken = m_CategoriesList->LayoutUpdated += ref new EventHandler<Object ^>(this, &RenderEffects::OnLayoutUpdated);
}
void RenderEffects::DisplayEffectsList( IVectorView<AudioEffect^>^ EffectsList )
{
AudioEffect^ effect = nullptr;
AudioEffectType effectType;
if (EffectsList != nullptr)
{
m_EffectsListBox->Items->Clear();
if (EffectsList->Size > 0)
{
for (unsigned int i = 0; i < EffectsList->Size; i++)
{
effect = EffectsList->GetAt(i);
effectType = effect->AudioEffectType;
String ^message = ref new String(EffectTypeToString(effectType)->Data());
m_EffectsListBox->Items->Append(message);
}
}
else
{
m_EffectsListBox->Items->Append(L"[No Effects]");
}
m_EffectsListBox->IsEnabled = true;
}
}
AudioRenderCategory RenderEffects::CategorySelected()
{
if (m_CategoriesList != nullptr && m_CategoriesList->SelectedIndex >= 0)
{
return (AudioRenderCategory) m_CategoriesList->SelectedIndex;
}
else
{
// Default Category
return AudioRenderCategory::Communications;
}
}
void RenderEffects::EnumerateDevices(Object^ sender, RoutedEventArgs^ e)
{
// Get the string identifier of the audio renderer
String^ AudioSelector = MediaDevice::GetAudioRenderSelector();
create_task(Windows::Devices::Enumeration::DeviceInformation::FindAllAsync(AudioSelector)).then([this] (DeviceInformationCollection^ DeviceInfoCollection)
{
if ((DeviceInfoCollection == nullptr) || (DeviceInfoCollection->Size == 0))
{
this->ShowStatusMessage("No Devices Found.");
}
else
{
m_DeviceList = DeviceInfoCollection;
m_DevicesListBox->Items->Clear();
// Enumerate through the devices and the custom properties
for (unsigned int i = 0; i < DeviceInfoCollection->Size; i++)
{
DeviceInformation^ deviceInfo = DeviceInfoCollection->GetAt(i);
String^ DeviceInfoString = deviceInfo->Name;
m_DevicesListBox->Items->Append(DeviceInfoString);
}
m_DevicesListBox->IsEnabled = true;
}
});
}
void RenderEffects::OnLayoutUpdated(Object ^sender, Object ^args)
{
// This Cpp sample does not include "Audio" in "Background Tasks" declaration; so disable the "BackgroundCapableMedia" category from drop-down list
ComboBoxItem ^cb = (ComboBoxItem ^) m_CategoriesList->ContainerFromIndex((int) AudioRenderCategory::BackgroundCapableMedia);
// Perform disabling only after ComboBoxItem has been rendered
if (cb != nullptr)
{
cb->IsEnabled = FALSE;
}
}
|
zabrewer/batfish
|
projects/batfish-common-protocol/src/main/java/org/batfish/datamodel/answers/AnswerStatus.java
|
package org.batfish.datamodel.answers;
public enum AnswerStatus {
FAILURE,
NOTFOUND,
STALE,
SUCCESS
}
|
mmontes11/iot
|
packages/back/src/controllers/rest/observationsController.js
|
<gh_stars>10-100
import _ from "underscore";
import httpStatus from "http-status";
import Promise from "bluebird";
import constants from "../../utils/responseKeys";
import modelFactory from "../../helpers/modelFactory";
import thingController from "./thingController";
import mqttController from "../mqtt/mqttController";
const _createOrUpdateThing = async (req, createdObservations) => {
const latestObservation = _.max(createdObservations, observation => observation.phenomenonTime);
return thingController.createOrUpdateThing(req, latestObservation.phenomenonTime);
};
const _handleResponse = (res, createdObservations, invalidObservations) => {
if (_.isEmpty(createdObservations)) {
const response = {
[constants.invalidObservationsArrayKey]: invalidObservations,
};
return res.status(httpStatus.BAD_REQUEST).json(response);
} else if (_.isEmpty(invalidObservations)) {
const response = {
[constants.createdObservationsArrayKey]: createdObservations,
};
return res.status(httpStatus.CREATED).json(response);
}
const response = {
[constants.createdObservationsArrayKey]: createdObservations,
[constants.invalidObservationsArrayKey]: invalidObservations,
};
return res.status(httpStatus.MULTI_STATUS).json(response);
};
const createObservations = async (req, res) => {
const observations = req.body[constants.observationsArrayKey];
const createdObservations = [];
const invalidObservations = [];
const savePromises = [];
_.forEach(observations, observation => {
try {
const newObservation = modelFactory.createObservationUsingKind(req, observation);
savePromises.push(newObservation.save().reflect());
} catch (err) {
invalidObservations.push(observation);
}
});
await Promise.all(savePromises).each((inspection, index) => {
if (inspection.isFulfilled()) {
createdObservations.push(inspection.value());
} else {
invalidObservations.push(observations[index]);
}
});
let thing;
try {
if (!_.isEmpty(createdObservations)) {
thing = await _createOrUpdateThing(req, createdObservations);
}
} catch (err) {
return thingController.handleThingCreationError(req, res, createdObservations);
}
await mqttController.publishObservations(thing, createdObservations);
return _handleResponse(res, createdObservations, invalidObservations);
};
export default { createObservations };
|
aMurryFly/Old_Courses
|
Basic_Python/2_Martes/6_while.py
|
numero= int(input('Teclee un numero positivo'))
while numero<0:
print('Escribió un número negativo')
print(numero)
numero = int(input('Vuelva a escribir un número'))
print('Programa terminado')
|
matthewboman/myhike
|
public/build/es5/components/Navbar/NavAdmin.js
|
<gh_stars>0
"use strict";
var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
var _prototypeProperties = function (child, staticProps, instanceProps) { if (staticProps) Object.defineProperties(child, staticProps); if (instanceProps) Object.defineProperties(child.prototype, instanceProps); };
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc && desc.writable) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
var _react = require("react");
var React = _interopRequire(_react);
var Component = _react.Component;
var Link = require("react-router").Link;
var connect = require("react-redux").connect;
var Modal = _interopRequire(require("react-modal"));
var APIManager = require("../../utils").APIManager;
var actions = _interopRequire(require("../../actions"));
var _User = require("../User");
var Login = _User.Login;
var Register = _User.Register;
var NavAdmin = (function (Component) {
function NavAdmin() {
_classCallCheck(this, NavAdmin);
_get(Object.getPrototypeOf(NavAdmin.prototype), "constructor", this).call(this);
this.state = {
modalIsOpen: false,
isLogin: false,
isRegister: false
};
this.openLogin = this.openLogin.bind(this);
this.openRegister = this.openRegister.bind(this);
this.closeModal = this.closeModal.bind(this);
}
_inherits(NavAdmin, Component);
_prototypeProperties(NavAdmin, null, {
openLogin: {
value: function openLogin() {
this.setState({
modalIsOpen: true,
isLogin: true
});
},
writable: true,
configurable: true
},
openRegister: {
value: function openRegister() {
this.setState({
modalIsOpen: true,
isRegister: true
});
},
writable: true,
configurable: true
},
closeModal: {
value: function closeModal() {
this.setState({
modalIsOpen: false,
isLogin: false,
isRegister: false
});
this.props.displayError("");
},
writable: true,
configurable: true
},
login: {
value: function login(credentials) {
this.props.currentUserReceived(credentials);
this.setState({
modalIsOpen: false
});
},
writable: true,
configurable: true
},
logout: {
value: function logout(event) {
event.preventDefault();
this.props.logoutUser(null);
},
writable: true,
configurable: true
},
renderModalHeader: {
value: function renderModalHeader() {
return React.createElement(
"div",
{ className: "modal-header" },
React.createElement(
"span",
{ className: "modal-title" },
this.state.isRegister ? "Register" : "Login"
),
React.createElement("span", { onClick: this.closeModal, className: "x-button" })
);
},
writable: true,
configurable: true
},
renderModalType: {
value: function renderModalType() {
var _this = this;
if (this.state.isRegister) {
return React.createElement(
"div",
{ className: "modal-register" },
React.createElement(Register, { onClose: this.closeModal })
);
} else if (this.state.isLogin) {
return React.createElement(
"div",
{ className: "modal-login" },
React.createElement(Login, { onLogin: this.login.bind(this),
displayError: function (error) {
return _this.props.displayError(error);
},
error: this.props.error
})
);
}
},
writable: true,
configurable: true
},
renderIfNoUser: {
value: function renderIfNoUser() {
return React.createElement(
"ul",
{ className: "nav navbar-nav navbar-right" },
React.createElement(
"li",
null,
React.createElement(
Link,
{ to: "/create-hike" },
"Create Hike"
)
),
React.createElement(
"li",
null,
React.createElement(
"a",
{ onClick: this.openLogin, className: "nav-link" },
"Login"
)
),
React.createElement(
"li",
null,
React.createElement(
"a",
{ onClick: this.openRegister, className: "nav-link" },
"Register"
)
)
);
},
writable: true,
configurable: true
},
renderIfUser: {
value: function renderIfUser() {
return React.createElement(
"ul",
{ className: "nav navbar-nav navbar-right" },
React.createElement(
"li",
null,
React.createElement(
Link,
{ to: "/create-hike" },
"Create Hike"
)
),
React.createElement(
"li",
null,
React.createElement(
Link,
{ to: "/currentuser" },
"Account"
)
),
React.createElement(
"li",
null,
React.createElement(
"a",
{ onClick: this.logout.bind(this), className: "nav-link" },
"Log out"
)
)
);
},
writable: true,
configurable: true
},
render: {
value: function render() {
return React.createElement(
"div",
{ className: "nav-admin" },
this.props.user ? this.renderIfUser() : this.renderIfNoUser(),
React.createElement(
Modal,
{
className: "account-modal",
overlayClassName: "account-modal-overlay",
isOpen: this.state.modalIsOpen,
onAfterOpen: this.afterOpenModal,
onRequestClose: this.closeModal,
contentLabel: "account modal"
},
this.renderModalHeader(),
React.createElement(
"div",
{ className: "modal-body" },
this.renderModalType()
)
)
);
},
writable: true,
configurable: true
}
});
return NavAdmin;
})(Component);
var stateToProps = function (state) {
return {
user: state.account.user,
error: state.message.error
};
};
var dispatchToProps = function (dispatch) {
return {
currentUserReceived: function (user) {
return dispatch(actions.currentUserReceived(user));
},
displayError: function (error) {
return dispatch(actions.displayError(error));
},
logoutUser: function (user) {
return dispatch(actions.logoutUser(user));
} };
};
module.exports = connect(stateToProps, dispatchToProps)(NavAdmin);
|
ForrestPi/ObjectDetection
|
SSD/SSD_FPN_GIoU/model/neck/__init__.py
|
from .build_neck import Neck
from .ssd_neck import SSDNeck
|
MalteSchledjewski/edacc_gui
|
src/edacc/experiment/ExperimentController.java
|
<reponame>MalteSchledjewski/edacc_gui<gh_stars>1-10
package edacc.experiment;
import com.mysql.jdbc.exceptions.MySQLStatementCancelledException;
import edacc.model.SolverConfigCache;
import edacc.EDACCExperimentMode;
import edacc.api.costfunctions.*;
import edacc.experiment.tabs.solver.SolverConfigurationEntry;
import edacc.experiment.tabs.solver.SolverConfigurationEntryModel;
import edacc.model.ClientDAO;
import edacc.model.ComputationMethodDoesNotExistException;
import edacc.model.ConfigurationScenario;
import edacc.model.ConfigurationScenarioDAO;
import edacc.model.ConfigurationScenarioParameter;
import edacc.model.Cost;
import edacc.model.CostDAO;
import edacc.model.DatabaseConnector;
import edacc.model.ExpResultHasSolvPropertyNotInDBException;
import edacc.model.Experiment;
import edacc.model.ExperimentDAO;
import edacc.model.ExperimentHasGridQueue;
import edacc.model.ExperimentHasGridQueueDAO;
import edacc.model.ExperimentHasInstance;
import edacc.model.ExperimentHasInstanceDAO;
import edacc.model.ExperimentResult;
import edacc.model.ExperimentResultDAO;
import edacc.model.ExperimentResultDAO.IdValue;
import edacc.model.ExperimentResultDAO.SeedGroupExperimentIdInstanceId;
import edacc.model.ExperimentResultHasProperty;
import edacc.model.ExperimentResultNotInDBException;
import edacc.model.ResultCode;
import edacc.model.ResultCodeNotInDBException;
import edacc.model.StatusCode;
import edacc.model.StatusCodeDAO;
import edacc.model.GridQueue;
import edacc.model.GridQueueDAO;
import edacc.model.Instance;
import edacc.model.InstanceClassDAO;
import edacc.model.InstanceClassMustBeSourceException;
import edacc.model.InstanceDAO;
import edacc.model.InstanceHasProperty;
import edacc.model.InstanceNotInDBException;
import edacc.model.NoConnectionToDBException;
import edacc.model.Parameter;
import edacc.model.ParameterDAO;
import edacc.model.ParameterInstance;
import edacc.model.ParameterInstanceDAO;
import edacc.model.Property;
import edacc.model.PropertyDAO;
import edacc.model.Solver;
import edacc.model.SolverConfiguration;
import edacc.model.SolverDAO;
import edacc.model.PropertyNotInDBException;
import edacc.model.ResultCodeDAO;
import edacc.model.SolverBinaries;
import edacc.model.SolverBinariesDAO;
import edacc.model.SolverConfigurationDAO;
import edacc.model.StatusCodeNotInDBException;
import edacc.model.TaskCancelledException;
import edacc.model.Tasks;
import edacc.model.Verifier;
import edacc.model.VerifierConfiguration;
import edacc.model.VerifierConfigurationDAO;
import edacc.model.VerifierDAO;
import edacc.properties.PropertyTypeNotExistException;
import edacc.satinstances.ConvertException;
import edacc.satinstances.PropertyValueType;
import edacc.util.Pair;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.sql.Date;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultMutableTreeNode;
/**
* Experiment design more controller class, handles requests by the GUI
* for creating, removing, loading, etc. experiments.
* @author daniel, simon
*/
public class ExperimentController {
EDACCExperimentMode main;
private Experiment activeExperiment;
private static RandomNumberGenerator rnd = new JavaRandom();
// caching experiments
private ExperimentResultCache experimentResultCache;
/** caching solver configs */
public SolverConfigCache solverConfigCache;
/** the cpu time property. Will be created when creating an experiment controller. */
public static Property PROP_CPUTIME;
private ConfigurationScenario configScenario;
private ConfigurationScenario savedScenario;
private SolverConfigurationEntryModel solverConfigurationEntryModel;
/**
* Creates a new experiment Controller
* @param experimentMode the experiment mode to be used
*/
public ExperimentController(EDACCExperimentMode experimentMode) {
this.main = experimentMode;
solverConfigurationEntryModel = new SolverConfigurationEntryModel();
PROP_CPUTIME = new Property();
PROP_CPUTIME.setName("CPU-Time (s)");
}
/**
* Initializes the experiment controller. Loads the experiments and the instances classes.
* @throws SQLException
* @throws InstanceClassMustBeSourceException
* @throws IOException
* @throws NoConnectionToDBException
* @throws PropertyNotInDBException
* @throws PropertyTypeNotExistException
* @throws ComputationMethodDoesNotExistException
*/
public void initialize() throws SQLException, InstanceClassMustBeSourceException, IOException, NoConnectionToDBException, PropertyNotInDBException, PropertyTypeNotExistException, ComputationMethodDoesNotExistException {
InstanceDAO.clearCache();
StatusCodeDAO.initialize();
ResultCodeDAO.initialize();
ClientDAO.clearCache();
SolverBinariesDAO.clearCache();
SolverDAO.clearCache();
ParameterDAO.clearCache();
ExperimentDAO.clearCache();
SolverConfigurationDAO.clearCache();
ParameterInstanceDAO.clearCache();
VerifierDAO.clearCache();
VerifierConfigurationDAO.clearCache();
ArrayList<Experiment> experiments = new ArrayList<Experiment>();
experiments.addAll(ExperimentDAO.getAll());
main.expTableModel.setExperiments(experiments);
DefaultMutableTreeNode root = (DefaultMutableTreeNode) InstanceClassDAO.getAllAsTreeFast();
main.instanceClassTreeModel.setRoot(root);
ArrayList<Instance> instances = new ArrayList<Instance>();
instances.addAll(InstanceDAO.getAll());
main.insTableModel.setInstances(instances, true, true);
final boolean isCompetitionDB = DatabaseConnector.getInstance().isCompetitionDB();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (!isCompetitionDB) {
main.insTableModel.fireTableStructureChanged();
main.tableInstances.removeColumn(main.tableInstances.getColumnModel().getColumn(InstanceTableModel.COL_BENCHTYPE));
}
}
});
}
/**
* Loads an experiment, the solvers and the solver configurations.
* @param exp
* @param task
* @throws SQLException
* @throws Exception
*/
public void loadExperiment(Experiment exp, final Tasks task) throws SQLException, Exception {
unloadExperiment();
main.reinitializeSolvers();
activeExperiment = exp;
main.jobsTableModel.setDefaultCost(exp.getDefaultCost());
ArrayList<Solver> vs = new ArrayList<Solver>();
task.setStatus("Loading solvers..");
vs.addAll(SolverDAO.getAll());
main.solTableModel.setSolvers(vs);
task.setTaskProgress(.25f);
task.setStatus("Loading solver configurations..");
// now load solver configs of the current experiment
if (solverConfigCache != null) {
solverConfigCache.changeExperiment(activeExperiment);
} else {
solverConfigCache = new SolverConfigCache(activeExperiment);
solverConfigCache.reload();
}
solverConfigurationEntryModel.clear();
for (SolverConfiguration solverConfig : solverConfigCache.getAll()) {
solverConfigurationEntryModel.add(new SolverConfigurationEntry(solverConfig, activeExperiment));
}
solverConfigurationEntryModel.fireDataChanged();
task.setTaskProgress(.5f);
task.setStatus("Loading instances..");
refreshInstanceSelection();
task.setTaskProgress(.75f);
task.setStatus("Loading experiment results..");
experimentResultCache = new ExperimentResultCache(activeExperiment);
PropertyChangeListener cancelExperimentResultDAOStatementListener = null;
if (Tasks.getTaskView() != null) {
task.setCancelable(true);
cancelExperimentResultDAOStatementListener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if ("state".equals(evt.getPropertyName()) && task.isCancelled()) {
try {
ExperimentResultDAO.cancelStatement();
} catch (SQLException ex) {
}
}
}
};
task.addPropertyChangeListener(cancelExperimentResultDAOStatementListener);
}
try {
experimentResultCache.updateExperimentResults(task);
} catch (MySQLStatementCancelledException ex) {
throw new TaskCancelledException();
} finally {
task.setCancelable(false);
if (cancelExperimentResultDAOStatementListener != null) {
task.removePropertyChangeListener(cancelExperimentResultDAOStatementListener);
}
}
main.generateJobsTableModel.updateNumRuns();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Util.updateTableColumnWidth(main.tblGenerateJobs, 1);
}
});
if (activeExperiment.isConfigurationExp()) {
configScenario = ConfigurationScenarioDAO.getConfigurationScenarioByExperimentId(activeExperiment.getId());
// we need a new instance for this
savedScenario = ConfigurationScenarioDAO.getConfigurationScenarioByExperimentId(activeExperiment.getId());
}
main.afterExperimentLoaded();
}
/**
* Removes an experiment form the db.
* @param id
* @throws SQLException
* @throws InstanceClassMustBeSourceException
* @throws IOException
* @throws NoConnectionToDBException
* @throws PropertyNotInDBException
* @throws PropertyTypeNotExistException
* @throws ComputationMethodDoesNotExistException
*/
public void removeExperiment(int id) throws SQLException, InstanceClassMustBeSourceException, IOException, NoConnectionToDBException, PropertyNotInDBException, PropertyTypeNotExistException, ComputationMethodDoesNotExistException {
Experiment e = ExperimentDAO.getById(id);
if (e.equals(activeExperiment)) {
unloadExperiment();
}
ExperimentDAO.removeExperiment(e);
initialize();
}
/**
* Returns the experiment result cache
* @return the experiment result cache
*/
public ExperimentResultCache getExperimentResults() {
return experimentResultCache;
}
/**
* returns a reference to the currently loaded experiment or null, if none
* @return active experiment reference
*/
public Experiment getActiveExperiment() {
return activeExperiment;
}
/**
* unloads the currently loaded experiment, i.e. sets activeExperiment to null
* and calls UI functions to disable the experiment design tabs
*/
public void unloadExperiment() {
activeExperiment = null;
experimentResultCache = null;
main.afterExperimentUnloaded();
}
/**
* invoked by the UI to create a new experiment, also calls initialize to load
* instances and solvers
* @param name
* @param description
* @param configurationExp
* @return the newly created experiment
* @throws SQLException
* @throws InstanceClassMustBeSourceException
* @throws IOException
* @throws NoConnectionToDBException
* @throws PropertyNotInDBException
* @throws PropertyTypeNotExistException
* @throws ComputationMethodDoesNotExistException
*/
public Experiment createExperiment(String name, String description, boolean configurationExp, Experiment.Cost defaultCost, Integer solverOutputPreserveFirst, Integer solverOutputPreserveLast, Integer watcherOutputPreserveFirst, Integer watcherOutputPreserveLast, Integer verifierOutputPreserveFirst, Integer verifierOutputPreserveLast, VerifierConfiguration verifierConfig, Cost cost, boolean minimize, Double costPenalty) throws SQLException, InstanceClassMustBeSourceException, IOException, NoConnectionToDBException, PropertyNotInDBException, PropertyTypeNotExistException, ComputationMethodDoesNotExistException {
java.util.Date d = new java.util.Date();
Experiment res = ExperimentDAO.createExperiment(name, new Date(d.getTime()), description, configurationExp, defaultCost, solverOutputPreserveFirst, solverOutputPreserveLast, watcherOutputPreserveFirst, watcherOutputPreserveLast, verifierOutputPreserveFirst, verifierOutputPreserveLast, cost == null ? null : cost.getId(), minimize, costPenalty);
if (verifierConfig != null) {
verifierConfig.setIdExperiment(res.getId());
VerifierConfigurationDAO.save(verifierConfig);
}
initialize();
return res;
}
/**
* This will save the settings for the given experiment.
* @param exp the experiment
* @throws SQLException
*/
public void saveExperiment(Experiment exp) throws SQLException {
ExperimentDAO.save(exp);
}
/**
* Saves all solver configurations with parameter instances in the solver
* config panel.
* @param task
* @throws SQLException
* @throws InterruptedException
* @throws InvocationTargetException
* @throws PropertyNotInDBException
* @throws PropertyTypeNotExistException
* @throws IOException
* @throws NoConnectionToDBException
* @throws ComputationMethodDoesNotExistException
* @throws ExpResultHasSolvPropertyNotInDBException
* @throws ExperimentResultNotInDBException
* @throws StatusCodeNotInDBException
* @throws ResultCodeNotInDBException
* @throws Exception
*/
public void saveSolverConfigurations(Tasks task) throws SQLException, InterruptedException, InvocationTargetException, PropertyNotInDBException, PropertyTypeNotExistException, IOException, NoConnectionToDBException, ComputationMethodDoesNotExistException, ExpResultHasSolvPropertyNotInDBException, ExperimentResultNotInDBException, StatusCodeNotInDBException, ResultCodeNotInDBException, Exception {
// TODO: there are some points where this task should never be canceled (by an application crash or lost db connection)... fix them!
task.setStatus("Checking jobs..");
// check for solver configurations with no value for parameters which must have values
boolean yta = false;
for (Solver solver : solverConfigurationEntryModel.getSolvers()) {
for (SolverConfigurationEntry entry : solverConfigurationEntryModel.getEntries(solver)) {
if (entry.isModified() && entry.hasEmptyValues()) {
String[] options = {"Yes", "Yes to all", "No"};
int userinput = JOptionPane.showOptionDialog(Tasks.getTaskView(),
"The solver configuration " + entry.getName() + " has no value for a parameter which must have a value.\nDo you want to continue?",
"Warning",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE,
null, options, options[0]);
if (userinput == 1) {
yta = true;
break;
} else if (userinput == 2) {
return;
}
}
}
if (yta) {
break;
}
}
// check for deleted solver configurations (jobs have to be deleted)
experimentResultCache.updateExperimentResults();
ArrayList<SolverConfiguration> deletedSolverConfigurations = solverConfigCache.getAllDeleted();
final ArrayList<ExperimentResult> deletedJobs = new ArrayList<ExperimentResult>();
final HashSet<Integer> scIds = new HashSet<Integer>();
for (SolverConfiguration sc : deletedSolverConfigurations) {
scIds.add(sc.getId());
}
for (ExperimentResult job : experimentResultCache.values()) {
if (scIds.contains(job.getSolverConfigId())) {
deletedJobs.add(job);
}
}
// check for modified solver configurations (jobs have to be deleted)
// this will append (to deletedJobs) all modified solver configurations, i.e. the solver configurations are not marked as deleted and
// * the seed group of the solver configurations has been changed or
// * some parameter instances have been modified/deleted or added
ArrayList<SolverConfiguration> modifiedSolverConfigurations = solverConfigurationEntryModel.getModifiedSolverConfigurations();
yta = false;
boolean nta = false;
for (SolverConfiguration sc : modifiedSolverConfigurations) {
int userinput = -1;
if (!yta && !nta) {
String[] options = {"Yes", "Yes to all", "No", "No to all"};
userinput = JOptionPane.showOptionDialog(Tasks.getTaskView(),
"The parameter values of the solver configuration " + sc.getName() + " have been changed.\nDo you want to delete the affected jobs?",
"Warning",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE,
null, options, options[0]);
if (userinput == 1) {
yta = true;
} else if (userinput == 3) {
nta = true;
}
}
if (!nta && (yta || userinput == 0)) {
deletedJobs.addAll(ExperimentResultDAO.getAllBySolverConfiguration(sc));
}
}
if (deletedJobs.size() > 0) {
int notDeletableJobsCount = 0;
for (ExperimentResult job : deletedJobs) {
if (job.getStatus() != StatusCode.NOT_STARTED) {
notDeletableJobsCount++;
}
}
String msg = "";
if (notDeletableJobsCount > 0) {
msg = "There are " + notDeletableJobsCount + " started jobs and " + (deletedJobs.size() - notDeletableJobsCount) + " jobs waiting in the database which would be deleted. ";
} else {
msg = "There are " + deletedJobs.size() + " jobs waiting in the database which would be deleted. ";
}
msg += "Do you want to continue?";
int userInput = javax.swing.JOptionPane.showConfirmDialog(Tasks.getTaskView(), msg, "Jobs would be changed", javax.swing.JOptionPane.YES_NO_OPTION);
if (userInput == 1) {
return;
} else {
task.setStatus("Deleting jobs..");
ExperimentResultDAO.deleteExperimentResults(deletedJobs);
}
}
task.setStatus("Saving solver configurations..");
// first look for unsaved solver configurations..
List<SolverConfiguration> solverConfigurations = new LinkedList<SolverConfiguration>();
for (Solver s : solverConfigurationEntryModel.getSolvers()) {
// iterate over solvers
for (SolverConfigurationEntry entry : solverConfigurationEntryModel.getEntries(s)) {
// iterate over solver configs
if (entry.getSolverConfig() == null) {
SolverConfiguration sc = new SolverConfiguration();
sc.setSolverBinary(entry.getSolverBinary());
sc.setExperiment_id(activeExperiment.getId());
sc.setSeed_group(entry.getSeedGroup());
sc.setName(entry.getName());
sc.setHint(entry.getHint());
entry.setSolverConfig(sc);
solverConfigurations.add(sc);
}
}
}
solverConfigCache.createAll(solverConfigurations);
// look for all parameter instances, create new ones, save all
List<ParameterInstance> parameterInstances = new LinkedList<ParameterInstance>();
for (Solver s : solverConfigurationEntryModel.getSolvers()) {
// iterate over solvers
for (SolverConfigurationEntry entry : solverConfigurationEntryModel.getEntries(s)) {
// iterate over solver configs
if (entry.getSolverConfig() == null) {
entry.setSolverConfig(solverConfigCache.createSolverConfiguration(entry.getSolverBinary(), activeExperiment.getId(), entry.getSeedGroup(), entry.getName(), entry.getHint()));
} else {
entry.getSolverConfig().setSolverBinary(entry.getSolverBinary());
entry.getSolverConfig().setName(entry.getName());
entry.getSolverConfig().setSeed_group(entry.getSeedGroup());
entry.getSolverConfig().setHint(entry.getHint());
}
parameterInstances.addAll(entry.getParameterInstances());
}
}
ParameterInstanceDAO.saveBulk(parameterInstances);
// save modified solver configurations and delete deleted
solverConfigCache.saveAll();
refreshGenerateJobsModel();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Util.updateTableColumnWidth(main.tblGenerateJobs, 1);
}
});
}
/**
* This will clean up all changed data for the solver configurations.
* @param task
* @throws SQLException
*/
public void undoSolverConfigurations(Tasks task) throws SQLException {
solverConfigCache.reload();
refreshSolverConfigurationModel();
}
public void refreshSolverConfigurationModel() throws SQLException {
solverConfigurationEntryModel.clear();
for (SolverConfiguration solverConfig : solverConfigCache.getAll()) {
solverConfigurationEntryModel.add(new SolverConfigurationEntry(solverConfig, activeExperiment));
}
solverConfigurationEntryModel.fireDataChanged();
main.setTitles();
}
public void refreshGenerateJobsModel() throws SQLException, IOException {
getExperimentResults().updateExperimentResults();
main.generateJobsTableModel.updateNumRuns();
}
public void refreshInstanceSelection() throws SQLException {
// select instances for the experiment
Vector<ExperimentHasInstance> ehi = new Vector<ExperimentHasInstance>();
ehi.addAll(ExperimentHasInstanceDAO.getExperimentHasInstanceByExperimentId(activeExperiment.getId()));
main.insTableModel.setExperimentHasInstances(ehi);
}
/**
* saves the instances selection of the currently loaded experiment
* @param task
* @throws SQLException
* @throws InterruptedException
* @throws InvocationTargetException
* @throws PropertyNotInDBException
* @throws PropertyTypeNotExistException
* @throws IOException
* @throws NoConnectionToDBException
* @throws ComputationMethodDoesNotExistException
* @throws ExpResultHasSolvPropertyNotInDBException
* @throws ExperimentResultNotInDBException
* @throws StatusCodeNotInDBException
* @throws ResultCodeNotInDBException
*/
public void saveExperimentHasInstances(Tasks task) throws SQLException, InterruptedException, InvocationTargetException, PropertyNotInDBException, PropertyTypeNotExistException, IOException, NoConnectionToDBException, ComputationMethodDoesNotExistException, ExpResultHasSolvPropertyNotInDBException, ExperimentResultNotInDBException, StatusCodeNotInDBException, ResultCodeNotInDBException {
task.setStatus("Checking jobs..");
ArrayList<ExperimentHasInstance> deletedInstances = main.insTableModel.getDeletedExperimentHasInstances();
if (deletedInstances.size() > 0) {
experimentResultCache.updateExperimentResults(task);
HashSet<Integer> instanceIds = new HashSet<Integer>();
for (ExperimentHasInstance ehi : deletedInstances) {
instanceIds.add(ehi.getInstances_id());
}
ArrayList<ExperimentResult> deletedJobs = experimentResultCache.getResultsByInstanceIds(instanceIds);
if (!deletedJobs.isEmpty()) {
int notDeletableJobsCount = 0;
for (ExperimentResult job : deletedJobs) {
if (job.getStatus() != StatusCode.NOT_STARTED) {
notDeletableJobsCount++;
}
}
String msg = "";
if (notDeletableJobsCount > 0) {
msg = "There are " + notDeletableJobsCount + " started jobs and " + (deletedJobs.size() - notDeletableJobsCount) + " jobs waiting in the database which would be deleted. Do you want to continue?";
} else {
msg = "There are " + deletedJobs.size() + " jobs waiting in the database which would be deleted. Do you want to continue?";
}
int userInput = javax.swing.JOptionPane.showConfirmDialog(Tasks.getTaskView(), msg, "Jobs would be deleted", javax.swing.JOptionPane.YES_NO_OPTION);
if (userInput == 1) {
return;
} else {
task.setStatus("Deleting jobs..");
ExperimentResultDAO.deleteExperimentResults(deletedJobs);
}
}
}
task.setStatus("Saving instances..");
// First: add all new ExperimentHasInstance objects
List<ExperimentHasInstance> ehi = new LinkedList<ExperimentHasInstance>();
for (Integer instanceId : main.insTableModel.getNewInstanceIds()) {
ehi.add(ExperimentHasInstanceDAO.createExperimentHasInstance(activeExperiment.getId(), instanceId));
}
ExperimentHasInstanceDAO.save(ehi);
// Then: remove all removed ExperimentHasInstance objects
ehi = main.insTableModel.getDeletedExperimentHasInstances();
for (ExperimentHasInstance i : main.insTableModel.getDeletedExperimentHasInstances()) {
ExperimentHasInstanceDAO.removeExperimentHasInstance(i);
}
ExperimentHasInstanceDAO.save(ehi);
main.insTableModel.setExperimentHasInstances(ExperimentHasInstanceDAO.getExperimentHasInstanceByExperimentId(activeExperiment.getId()));
main.generateJobsTableModel.updateNumRuns();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Util.updateTableColumnWidth(main.tblGenerateJobs, 1);
}
});
}
/**
* method used for auto seed generation, uses the random number generator
* referenced by this.rnd
* @return integer between 0 and max inclusively
*/
public int generateSeed(int max) {
return rnd.nextInt(max + 1);
}
/**
* generates the ExperimentResults (jobs) in the database for the currently active experiment
* Doesn't overwrite existing jobs
* @param task
* @param cpuTimeLimit
* @param memoryLimit
* @param wallClockTimeLimit
* @param stackSizeLimit
* @param maxSeed
* @return number of jobs added to the experiment results table
* @throws SQLException
* @throws TaskCancelledException
* @throws IOException
* @throws PropertyTypeNotExistException
* @throws PropertyNotInDBException
* @throws NoConnectionToDBException
* @throws ComputationMethodDoesNotExistException
* @throws ExpResultHasSolvPropertyNotInDBException
* @throws ExperimentResultNotInDBException
* @throws StatusCodeNotInDBException
* @throws ResultCodeNotInDBException
*/
public synchronized Pair<Integer, Integer> generateJobs(final Tasks task, int cpuTimeLimit, int memoryLimit, int wallClockTimeLimit, int stackSizeLimit, int maxSeed) throws SQLException, TaskCancelledException, IOException, PropertyTypeNotExistException, PropertyNotInDBException, NoConnectionToDBException, ComputationMethodDoesNotExistException, ExpResultHasSolvPropertyNotInDBException, ExperimentResultNotInDBException, StatusCodeNotInDBException, ResultCodeNotInDBException {
PropertyChangeListener cancelExperimentResultDAOStatementListener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if ("state".equals(evt.getPropertyName()) && task.isCancelled()) {
try {
ExperimentResultDAO.cancelStatement();
} catch (SQLException ex) {
}
}
}
};
task.setOperationName("Generating jobs for experiment " + activeExperiment.getName());
task.setStatus("Loading data from database");
experimentResultCache.updateExperimentResults();
// get instances of this experiment
LinkedList<Instance> listInstances = InstanceDAO.getAllByExperimentId(activeExperiment.getId());
// get solver configurations of this experiment
ArrayList<SolverConfiguration> vsc = solverConfigCache.getAll();
int jobs_deleted = 0;
int jobs_added = 0;
HashMap<SeedGroup, Integer> linked_seeds = new HashMap<SeedGroup, Integer>();
ArrayList<ExperimentResult> experiment_results = new ArrayList<ExperimentResult>();
ArrayList<ExperimentResult> deleteJobs = new ArrayList<ExperimentResult>();
//ArrayList<IdValue<Integer>> updateJobs = new ArrayList<IdValue<Integer>>();
task.setStatus("Preparing..");
int elements = 0; // # jobs when finished
for (Instance i : listInstances) {
for (SolverConfiguration sc : vsc) {
int numRuns = main.generateJobsTableModel.getNumRuns(i, sc);
elements += numRuns;
int currentNumRuns = experimentResultCache.getNumRuns(sc.getId(), i.getId());
if (currentNumRuns > numRuns) {
// we have to delete jobs
ArrayList<Integer> runs = new ArrayList<Integer>();
for (int run = 0; run < currentNumRuns; run++) {
runs.add(run);
}
int runsToDelete = currentNumRuns - numRuns;
/* don't delete jobs randomly, because seed groups will be destroyed! */
//Random random = new Random();
for (int k = 0; k < runsToDelete; k++) {
if (runs.isEmpty()) {
break;
}
int index = runs.size() -1;//random.nextInt(runs.size());
deleteJobs.add(experimentResultCache.getResult(sc.getId(), i.getId(), runs.get(index)));
runs.remove(index);
}
/*for (int k = 0; k < runs.size(); k++) {
updateJobs.add(new IdValue<Integer>(experimentResultCache.getResult(sc.getId(), i.getId(), runs.get(k)).getId(), k));
}*/
}
}
}
if (!deleteJobs.isEmpty()) {
// We have to delete jobs
String msg = "The number of runs specified is less than the number of runs in this experiment. There are " + deleteJobs.size() + " jobs which would be deleted. Do you want to continue?";
int userInput = javax.swing.JOptionPane.showConfirmDialog(Tasks.getTaskView(), msg, "Jobs would be deleted", javax.swing.JOptionPane.YES_NO_OPTION);
task.setCancelable(true);
task.setTaskProgress(0.f);
if (userInput == 1) {
return new Pair<Integer, Integer>(0,0);
} else {
task.setStatus("Deleting jobs..");
task.addPropertyChangeListener(cancelExperimentResultDAOStatementListener);
try {
ExperimentResultDAO.setAutoCommit(false);
ExperimentResultDAO.deleteExperimentResults(deleteJobs, task);
jobs_deleted += deleteJobs.size();
//task.setStatus("Updating existing jobs..");
//ExperimentResultDAO.batchUpdateRun(updateJobs);
} catch (Exception ex) {
DatabaseConnector.getInstance().getConn().rollback();
if (ex instanceof MySQLStatementCancelledException) {
throw new TaskCancelledException();
}
if (ex instanceof SQLException) {
throw (SQLException) ex;
} else if (ex instanceof TaskCancelledException) {
throw (TaskCancelledException) ex;
}
} finally {
ExperimentResultDAO.setAutoCommit(true);
}
task.removePropertyChangeListener(cancelExperimentResultDAOStatementListener);
}
}
task.setCancelable(false);
task.setStatus("Updating local cache..");
experimentResultCache.updateExperimentResults();
task.setCancelable(true);
task.setStatus("Preparing job generation");
HashMap<Integer, Boolean> solverConfigHasSeed = new HashMap<Integer, Boolean>();
// first pass over already existing jobs to accumulate existing linked seeds
for (SolverConfiguration c : vsc) {
Vector<Parameter> params = ParameterDAO.getParameterFromSolverId(c.getSolverBinary().getIdSolver());
boolean hasSeed = false;
for (Parameter p : params) {
if ("seed".equals(p.getName())) {
hasSeed = true;
break;
}
}
solverConfigHasSeed.put(c.getId(), hasSeed);
if (!hasSeed) {
// don't generate seed groups for solver configurations which have no seed
continue;
}
for (Instance i : listInstances) {
ArrayList<ExperimentResult> jobs = experimentResultCache.getResults(c.getId(), i.getId());
for (ExperimentResult job : jobs) {
// use the already existing jobs to populate the seed group hash table so jobs of newly added solver configs use
// the same seeds as already existing jobs
int seed = job.getSeed();
SeedGroup sg = new SeedGroup(c.getSeed_group(), i.getId(), job.getRun());
if (!linked_seeds.containsKey(sg)) {
linked_seeds.put(sg, new Integer(seed));
}
}
}
}
if (task.isCancelled()) {
throw new TaskCancelledException();
}
int done = 1;
for (Instance i : listInstances) {
for (SolverConfiguration c : vsc) {
for (int run = 0; run < main.generateJobsTableModel.getNumRuns(i, c); ++run) {
task.setTaskProgress((float) done / (float) elements);
if (task.isCancelled()) {
throw new TaskCancelledException();
}
// task.setStatus("Adding job " + done + " of " + elements);
// check if job already exists
if (!experimentResultCache.contains(c.getId(), i.getId(), run)) {
if (solverConfigHasSeed.get(c.getId())) {
Integer seed = linked_seeds.get(new SeedGroup(c.getSeed_group(), i.getId(), run));
if (seed != null) {
experiment_results.add(ExperimentResultDAO.createExperimentResult(run, 0, 0, StatusCode.NOT_STARTED, seed.intValue(), ResultCode.UNKNOWN, 0, 0, 0, c.getId(), activeExperiment.getId(), i.getId(), null, cpuTimeLimit, memoryLimit, wallClockTimeLimit, stackSizeLimit));
} else {
Integer new_seed = new Integer(generateSeed(maxSeed));
linked_seeds.put(new SeedGroup(c.getSeed_group(), i.getId(), run), new_seed);
experiment_results.add(ExperimentResultDAO.createExperimentResult(run, 0, 0, StatusCode.NOT_STARTED, new_seed.intValue(), ResultCode.UNKNOWN, 0, 0, 0, c.getId(), activeExperiment.getId(), i.getId(), null, cpuTimeLimit, memoryLimit, wallClockTimeLimit, stackSizeLimit));
}
} else {
experiment_results.add(ExperimentResultDAO.createExperimentResult(run, 0, 0, StatusCode.NOT_STARTED, 0, ResultCode.UNKNOWN, 0, 0, 0, c.getId(), activeExperiment.getId(), i.getId(), null, cpuTimeLimit, memoryLimit, wallClockTimeLimit, stackSizeLimit));
}
jobs_added++;
}
done++;
}
}
}
task.setTaskProgress(0.f);
task.addPropertyChangeListener(cancelExperimentResultDAOStatementListener);
task.setStatus("Saving changes to database..");
try {
ExperimentResultDAO.batchSave(experiment_results, task);
} catch (SQLException ex) {
if (ex.getMessage().contains("cancelled")) {
throw new TaskCancelledException();
}
throw ex;
}
task.removePropertyChangeListener(cancelExperimentResultDAOStatementListener);
experimentResultCache.updateExperimentResults();
main.generateJobsTableModel.updateNumRuns();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Util.updateTableColumnWidth(main.tblGenerateJobs, 1);
}
});
return new Pair<Integer, Integer>(jobs_added, jobs_deleted);
}
/**
* returns the number maximum run of the jobs in the database for the given experiment
* @return the number of jobs in the db
*/
public int getMaxRun() {
try {
return ExperimentResultDAO.getMaximumRun(activeExperiment);
} catch (Exception e) {
return 0;
}
}
/**
* Updates the job browser table
*/
public synchronized void loadJobs(Tasks task) {
try {
boolean autocommit = DatabaseConnector.getInstance().getConn().getAutoCommit();
DatabaseConnector.getInstance().getConn().setAutoCommit(false);
try {
experimentResultCache.updateExperimentResults(task);
// TODO: also update solver config cache if needed and cache parameter instances of solver configs
// maybe this should be done in experimentResultCache?
// temporary: simple synchronize, but may not be needed..
solverConfigCache.synchronize();
} finally {
DatabaseConnector.getInstance().getConn().setAutoCommit(autocommit);
}
final ExperimentResultsBrowserTableModel sync = main.jobsTableModel;
synchronized (sync) {
ArrayList<ExperimentResult> results = main.jobsTableModel.getJobs();
final HashSet<Integer> changedRows = new HashSet<Integer>();
if (results != null) {
if (results.size() != experimentResultCache.size()) {
results = null;
} else {
for (int i = 0; i < results.size(); i++) {
ExperimentResult er = results.get(i);
ExperimentResult tmp = experimentResultCache.getResult(er.getSolverConfigId(), er.getInstanceId(), er.getRun());
if (tmp == null) {
results = null;
break;
} else if (!er.getStatus().equals(tmp.getStatus()) || !er.getDatemodified().equals(tmp.getDatemodified())) {
results.set(i, tmp);
changedRows.add(i);
}
}
if (results != null && results.size() != experimentResultCache.size()) {
results = null;
}
}
}
if (results == null) {
results = new ArrayList<ExperimentResult>();
results.addAll(experimentResultCache.values());
main.jobsTableModel.setJobs(results);
main.resultBrowserRowFilter.updateFilterTypes();
main.jobsTableModel.fireTableDataChanged();
} else {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (changedRows.size() > 1000) {
main.jobsTableModel.fireTableDataChanged();
} else {
for (Integer i : changedRows) {
main.jobsTableModel.fireTableRowsUpdated(i, i);
}
}
}
});
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
main.tableJobs.invalidate();
main.tableJobs.revalidate();
main.tableJobs.repaint();
}
});
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
main.updateJobsFilterStatus();
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Generates a ZIP archive with the necessary files for the grid.
* @param location
* @param exportInstances
* @param exportSolvers
* @param exportClient
* @param exportRunsolver
* @param exportConfig
* @param clientBinary
* @param task
* @throws FileNotFoundException
* @throws IOException
* @throws NoConnectionToDBException
* @throws SQLException
* @throws ClientBinaryNotFoundException
* @throws InstanceNotInDBException
* @throws TaskCancelledException
*/
public void generatePackage(String location, boolean exportInstances, boolean exportSolvers, boolean exportClient, boolean exportRunsolver, boolean exportConfig, boolean exportVerifier, File clientBinary, File verifierBinary, Tasks task) throws FileNotFoundException, IOException, NoConnectionToDBException, SQLException, ClientBinaryNotFoundException, InstanceNotInDBException, TaskCancelledException, InterruptedException {
File tmpDir = new File("tmp");
tmpDir.mkdir();
task.setCancelable(true);
Calendar cal = Calendar.getInstance();
String dateStr = cal.get(Calendar.YEAR) + "" + (cal.get(Calendar.MONTH) < 9 ? "0" + (cal.get(Calendar.MONTH) + 1) : (cal.get(Calendar.MONTH) + 1)) + "" + (cal.get(Calendar.DATE) < 10 ? "0" + cal.get(Calendar.DATE) : cal.get(Calendar.DATE));
ArrayList<ExperimentHasGridQueue> eqs = ExperimentHasGridQueueDAO.getExperimentHasGridQueueByExperiment(activeExperiment);
int count = 0;
for (ExperimentHasGridQueue eq : eqs) {
GridQueue queue = GridQueueDAO.getById(eq.getIdGridQueue());
File zipFile = new File(location + Util.getFilename(activeExperiment.getName() + "_" + queue.getName() + "_" + dateStr + ".zip"));
if (zipFile.exists()) {
zipFile.delete();
}
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
ZipEntry entry;
task.setOperationName("Generating Package " + (++count) + " of " + eqs.size());
ArrayList<SolverBinaries> solverBinaries;
if (exportSolvers) {
solverBinaries = SolverBinariesDAO.getSolverBinariesInExperiment(activeExperiment);
} else {
solverBinaries = new ArrayList<SolverBinaries>();
}
LinkedList<Instance> instances;
if (exportInstances) {
instances = InstanceDAO.getAllByExperimentId(activeExperiment.getId());
} else {
instances = new LinkedList<Instance>();
}
int total = solverBinaries.size() + instances.size();
int done = 0;
if (!task.isCancelled() && exportSolvers) {
// add solvers to zip file
for (SolverBinaries binary : solverBinaries) {
done++;
task.setTaskProgress((float) done / (float) total);
if (task.isCancelled()) {
task.setStatus("Cancelled");
break;
}
task.setStatus("Writing solver " + done + " of " + solverBinaries.size());
ZipInputStream zis = new ZipInputStream(SolverBinariesDAO.getZippedBinaryFile(binary));
ZipEntry entryIn;
byte[] buffer = new byte[4 * 1024];
while ((entryIn = zis.getNextEntry()) != null) {
if (entryIn.isDirectory()) {
continue;
}
entry = new ZipEntry("solvers" + System.getProperty("file.separator") + binary.getMd5() + System.getProperty("file.separator") + entryIn.getName());
zos.putNextEntry(entry);
int read;
while ((read = zis.read(buffer, 0, buffer.length)) != -1) {
zos.write(buffer, 0, read);
}
zos.closeEntry();
}
}
}
if (!task.isCancelled() && exportInstances) {
// add instances to zip file
for (Instance i : instances) {
done++;
task.setTaskProgress((float) done / (float) total);
if (task.isCancelled()) {
task.setStatus("Cancelled");
break;
}
task.setStatus("Writing instance " + (done - solverBinaries.size()) + " of " + instances.size());
File f = InstanceDAO.getBinaryFileOfInstance(i);
entry = new ZipEntry("instances" + System.getProperty("file.separator") + i.getMd5() + "_" + i.getName());
addFileToZIP(f, entry, zos);
}
}
if (!task.isCancelled()) {
task.setStatus("Writing client");
// add configuration File
if (exportConfig) {
String verifierFilename = verifierBinary == null ? null : "verifiers/" + verifierBinary.getName();
addConfigurationFile(zos, queue, verifierFilename);
}
// add run script
// addRunScript(zos, exportInstances, exportSolvers, queue);
// add client binary
if (exportClient) {
addClient(zos, clientBinary);
}
// add runsolver
if (exportRunsolver) {
addRunsolver(zos);
}
// add verifier
if (exportVerifier) {
addVerifier(zos, verifierBinary);
}
}
zos.close();
// delete tmp directory
deleteDirectory(new File("tmp"));
if (task.isCancelled()) {
throw new TaskCancelledException("Cancelled");
}
}
}
private boolean deleteDirectory(File dir) {
if (dir.exists()) {
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
deleteDirectory(files[i]);
} else {
files[i].delete();
}
}
}
return (dir.delete());
}
/**
* Adds a file to an open zip file.
* @param f the location of the file to be added.
* @param entry the zip entry to be created.
* @param zos the open ZIPOutputStream of the zip file.
*/
private void addFileToZIP(File f, ZipEntry entry, ZipOutputStream zos) throws FileNotFoundException, IOException {
FileInputStream in = new FileInputStream(f);
zos.putNextEntry(entry);
byte[] buf = new byte[256 * 1024];
int len;
while ((len = in.read(buf)) > -1) {
zos.write(buf, 0, len);
}
zos.closeEntry();
in.close();
}
/**
* Assigns all gridQueues to the active experiment.
* This means: It creates a new ExperimentHasGridQueue object for each queue
* and deletes all ExperimentHasGridQueue objects which are not in queues vektor
* and persists it in the db
* @param queues
* @throws SQLException
*/
public void assignQueuesToExperiment(ArrayList<GridQueue> queues, Experiment experiment) throws SQLException {
boolean autoCommit = DatabaseConnector.getInstance().getConn().getAutoCommit();
try {
DatabaseConnector.getInstance().getConn().setAutoCommit(false);
// create all ExperimentHasGridQueue objects which do not exist
for (GridQueue q : queues) {
// check if assignment already exists
if (ExperimentHasGridQueueDAO.getByExpAndQueue(experiment, q) != null) {
continue;
}
ExperimentHasGridQueueDAO.createExperimentHasGridQueue(experiment, q);
}
// remove all ExperimentHasGridQueue objects which are not in the queues vektor
ArrayList<ExperimentHasGridQueue> ehgqs = ExperimentHasGridQueueDAO.getExperimentHasGridQueueByExperiment(experiment);
for (ExperimentHasGridQueue egq : ehgqs) {
boolean found = false;
for (GridQueue q : queues) {
if (egq.getIdGridQueue() == q.getId()) {
found = true;
break;
}
}
if (!found) {
ExperimentHasGridQueueDAO.removeExperimentHasGridQueue(egq);
}
}
} catch (SQLException e) {
DatabaseConnector.getInstance().getConn().rollback();
throw e;
} finally {
DatabaseConnector.getInstance().getConn().setAutoCommit(autoCommit);
}
}
private void addConfigurationFile(ZipOutputStream zos, GridQueue activeQueue, String verifierFilename) throws IOException {
// generate content of config file
String sConf =
"host = $host\n"
+ "username = $user\n"
+ "password = <PASSWORD>"
+ "database = $db\n"
+ "gridqueue = $q\n";
DatabaseConnector con = DatabaseConnector.getInstance();
sConf = sConf.replace("$host", con.getHostname());
sConf = sConf.replace("$user", con.getUsername());
sConf = sConf.replace("$pwd", con.getPassword());
sConf = sConf.replace("$db", con.getDatabase());
sConf = sConf.replace("$q", String.valueOf(activeQueue.getId()));
if (verifierFilename != null) {
sConf += "verifier = " + verifierFilename + "\n";
}
// write file into zip archive
ZipEntry entry = new ZipEntry("config");
zos.putNextEntry(entry);
zos.write(sConf.getBytes());
zos.closeEntry();
}
private void addRunScript(ZipOutputStream zos, boolean hasInstances, boolean hasSolvers, GridQueue q) throws IOException {
String sRun = "#!/bin/bash\n"
+ "chmod a-rwx client\n"
+ "chmod u+rwx client\n"
+ "chmod a-rwx config\n"
+ "chmod u+rw config\n"
+ (hasSolvers ? "chmod a-rwx solvers/*\n" : "")
+ (hasSolvers ? "chmod u+rwx solvers/*\n" : "")
+ (hasInstances ? "chmod a-rwx instances/*\n" : "")
+ (hasInstances ? "chmod u+rw instances/*\n" : "")
+ "for (( i = 0; i < " + q.getNumCPUs() + "; i++ ))\n"
+ "do\n"
+ " qsub start_client.pbs\n"
+ "done\n";
// write file into zip archive
ZipEntry entry = new ZipEntry("run.sh");
zos.putNextEntry(entry);
zos.write(sRun.getBytes());
zos.closeEntry();
}
private void addClient(ZipOutputStream zos, File clientBinary) throws IOException, ClientBinaryNotFoundException {
String[] files = new String[]{"AUTHORS", clientBinary.getName(), "LICENSE", "README"};
for (String filename : files) {
File f = new File(clientBinary.getParentFile() + System.getProperty("file.separator") + filename);
if (!f.exists() || f.isDirectory()) {
continue;
}
InputStream in = new FileInputStream(f);
if (in == null) {
throw new ClientBinaryNotFoundException();
}
ZipEntry entry = new ZipEntry(filename);
zos.putNextEntry(entry);
byte[] buf = new byte[1024];
int data;
while ((data = in.read(buf)) > -1) {
zos.write(buf, 0, data);
}
zos.closeEntry();
in.close();
}
}
private void addVerifier(ZipOutputStream zos, File verifierBinary) throws IOException, ClientBinaryNotFoundException {
InputStream in = new FileInputStream(verifierBinary);
if (in == null) {
throw new ClientBinaryNotFoundException();
}
ZipEntry entry = new ZipEntry("verifiers/" + verifierBinary.getName());
zos.putNextEntry(entry);
byte[] buf = new byte[1024];
int data;
while ((data = in.read(buf)) > -1) {
zos.write(buf, 0, data);
}
zos.closeEntry();
in.close();
}
private void addRunsolver(ZipOutputStream zos) throws IOException, ClientBinaryNotFoundException {
String[] files = new String[]{"runsolver", "runsolver_copyright.txt"};
for (String filename : files) {
InputStream in = new FileInputStream(new File(Util.getPath() + System.getProperty("file.separator") + "bin" + System.getProperty("file.separator") + filename));
if (in == null) {
throw new ClientBinaryNotFoundException();
}
ZipEntry entry = new ZipEntry(filename);
zos.putNextEntry(entry);
byte[] buf = new byte[1024];
int data;
while ((data = in.read(buf)) > -1) {
zos.write(buf, 0, data);
}
zos.closeEntry();
in.close();
}
}
/**
* Exports all jobs and all columns currently visible to a CSV file.
* @param file
* @param task
* @throws IOException
*/
public void exportCSV(File file, Tasks task) throws IOException {
task.setCancelable(true);
task.setOperationName("Exporting jobs to CSV file");
if (file.exists()) {
file.delete();
}
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));
for (int i = 0; i < main.tableJobs.getColumnCount(); i++) {
int vis_col = main.tableJobs.convertColumnIndexToModel(i);
out.write("\"" + main.jobsTableModel.getColumnName(vis_col) + "\"");
if (i < main.tableJobs.getColumnCount() - 1) {
out.write(",");
}
}
out.write('\n');
int total = main.getTableJobs().getRowCount();
int done = 0;
for (int i = 0; i < main.tableJobs.getRowCount(); i++) {
int vis = main.getTableJobs().convertRowIndexToModel(i);
done++;
task.setTaskProgress((float) done / (float) total);
if (task.isCancelled()) {
task.setStatus("Cancelled");
break;
}
task.setStatus("Exporting row " + done + " of " + total);
for (int col = 0; col < main.tableJobs.getColumnCount(); col++) {
int vis_col = main.tableJobs.convertColumnIndexToModel(col);
if (main.jobsTableModel.getValueAt(vis, vis_col) == null) {
out.write("\"-\"");
} else {
out.write("\"" + main.jobsTableModel.getValueAt(vis, vis_col).toString() + "\"");
}
if (col < main.tableJobs.getColumnCount() - 1) {
out.write(",");
}
}
out.write('\n');
}
out.flush();
out.close();
}
/**
* Exports all jobs and all columns currently visible to a TeX file.
* @param file
* @param task
* @throws IOException
*/
public void exportTeX(File file, Tasks task) throws IOException {
Tasks.getTaskView().setCancelable(true);
task.setOperationName("Exporting jobs to TeX file");
if (file.exists()) {
file.delete();
}
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));
String format = "|";
String columns = "";
for (int i = 0; i < main.tableJobs.getColumnCount(); i++) {
int vis_col = main.tableJobs.convertColumnIndexToModel(i);
columns += main.jobsTableModel.getColumnName(vis_col);
if (main.jobsTableModel.getColumnClass(vis_col) == Integer.class
|| main.jobsTableModel.getColumnClass(vis_col) == Double.class
|| main.jobsTableModel.getColumnClass(vis_col) == Float.class
|| main.jobsTableModel.getColumnClass(vis_col) == int.class
|| main.jobsTableModel.getColumnClass(vis_col) == double.class
|| main.jobsTableModel.getColumnClass(vis_col) == float.class) {
format += "r|";
} else {
format += "l|";
}
if (i < main.jobsTableModel.getColumnCount() - 1) {
columns += "&";
}
}
out.write("\\documentclass[a4paper]{report}\n");
out.write("\\title{Results of " + activeExperiment.getName() + "}\n");
out.write("\\begin{document}\n");
out.write("\\begin{tabular}[h]{" + format + "}\n");
out.write("\\hline\n");
out.write(columns + " \\\\\n");
out.write("\\hline\n");
int total = main.getTableJobs().getRowCount();
int done = 0;
for (int i = 0; i < main.tableJobs.getRowCount(); i++) {
int vis = main.getTableJobs().convertRowIndexToModel(i);
done++;
task.setTaskProgress((float) done / (float) total);
if (task.isCancelled()) {
task.setStatus("Cancelled");
break;
}
task.setStatus("Exporting row " + done + " of " + total);
for (int col = 0; col < main.tableJobs.getColumnCount(); col++) {
int vis_col = main.tableJobs.convertColumnIndexToModel(col);
if (main.jobsTableModel.getValueAt(vis, vis_col) == null) {
out.write("-");
} else {
out.write(main.jobsTableModel.getValueAt(vis, vis_col).toString());
}
if (col < main.jobsTableModel.getColumnCount() - 1) {
out.write(" & ");
}
}
out.write("\\\\\n");
}
out.write("\\hline\n");
out.write("\\end{tabular}\n");
out.write("\\end{document}\n");
out.flush();
out.close();
}
/**
* Sets the priority of the currently visible jobs in the job browser to <code>priority</code>,
* updates the local cached experiment results and updates the gui.
* @param priority the new priority for the jobs
* @throws SQLException
* @throws IOException
* @throws PropertyTypeNotExistException
* @throws PropertyNotInDBException
* @throws NoConnectionToDBException
* @throws ComputationMethodDoesNotExistException
* @throws ExpResultHasSolvPropertyNotInDBException
* @throws ExperimentResultNotInDBException
*/
public void setPriority(int priority) throws SQLException, IOException, PropertyTypeNotExistException, PropertyNotInDBException, NoConnectionToDBException, ComputationMethodDoesNotExistException, ExpResultHasSolvPropertyNotInDBException, ExperimentResultNotInDBException {
ArrayList<ExperimentResult> jobs = main.jobsTableModel.getJobs();
ArrayList<IdValue<Integer>> values = new ArrayList<IdValue<Integer>>();
for (int i = 0; i < main.tableJobs.getRowCount(); i++) {
int vis = main.getTableJobs().convertRowIndexToModel(i);
if (jobs.get(vis).getPriority() != priority) {
values.add(new IdValue<Integer>(jobs.get(vis).getId(), priority));
}
}
ExperimentResultDAO.batchUpdatePriority(values);
this.loadJobs(null);
}
/**
* Sets the status of all currently visible jobs in the job browser to <code>status</code>,
* updates the local cached experiment results and updates the gui.
* @param status the new status for the jobs
* @throws SQLException
*/
public void setStatus(StatusCode status) throws SQLException {
ArrayList<ExperimentResult> jobs = main.jobsTableModel.getJobs();
ArrayList<ExperimentResult> updatedJobs = new ArrayList<ExperimentResult>();
for (int i = 0; i < main.tableJobs.getRowCount(); i++) {
int vis = main.getTableJobs().convertRowIndexToModel(i);
if (!jobs.get(vis).getStatus().equals(status)) {
updatedJobs.add(jobs.get(vis));
}
}
ExperimentResultDAO.batchUpdateStatus(updatedJobs, status);
this.loadJobs(null);
}
/**
* Returns an <code>ArrayList</code> of all experiments in the experiments table
* @return <code>ArrayList</code> of experiments
*/
public ArrayList<Experiment> getExperiments() {
ArrayList<Experiment> experiments = new ArrayList<Experiment>();
for (int row = 0; row < main.expTableModel.getRowCount(); row++) {
experiments.add(main.expTableModel.getExperimentAt(row));
}
return experiments;
}
/**
* Returns the experiment with the given name.
* @param name
* @return the experiment
* @throws SQLException
*/
public Experiment getExperiment(String name) throws SQLException {
return ExperimentDAO.getExperimentByName(name);
}
/**
* Returns the output of an experiment result as a string
* @param type for possible types see edacc.model.ExperimentResult
* @param er the experiment result for which the output should be returned
* @return output of the experiment result as a string
* @throws SQLException
* @throws NoConnectionToDBException
* @throws IOException
* @see edacc.model.ExperimentResult
*/
public String getExperimentResultOutput(int type, ExperimentResult er) throws SQLException, NoConnectionToDBException, IOException {
return ExperimentResultDAO.getOutputText(type, er);
}
/**
* returns a hashmap containing the maximum limits of the experiment results for the currently loaded experiment.<br/>
* <br/>
* possible keys are: cpuTimeLimit, memoryLimit, wallClockTimeLimit, stackSizeLimit, outputSizeLimitFirst, outputSizeLimitLast
* @return HashMap for the limits
* @throws SQLException
* @throws Exception
*/
public HashMap<String, Integer> getMaxLimits() throws SQLException, Exception {
HashMap<String, Integer> res = new HashMap<String, Integer>();
int cpuTimeLimit = -1;
int memoryLimit = -1;
int wallClockTimeLimit = -1;
int stackSizeLimit = -1;
experimentResultCache.updateExperimentResults();
for (ExperimentResult er : experimentResultCache.values()) {
if (er.getCPUTimeLimit() > cpuTimeLimit) {
cpuTimeLimit = er.getCPUTimeLimit();
}
if (er.getMemoryLimit() > memoryLimit) {
memoryLimit = er.getMemoryLimit();
}
if (er.getWallClockTimeLimit() > wallClockTimeLimit) {
wallClockTimeLimit = er.getWallClockTimeLimit();
}
if (er.getStackSizeLimit() > stackSizeLimit) {
stackSizeLimit = er.getStackSizeLimit();
}
}
res.put("cpuTimeLimit", cpuTimeLimit);
res.put("memoryLimit", memoryLimit);
res.put("wallClockTimeLimit", wallClockTimeLimit);
res.put("stackSizeLimit", stackSizeLimit);
return res;
}
/**
* Imports data from the specified solver configurations to the currently loaded experiment. <br/>
* <br/>
* <br/>
* Let e_i be the experiments to import data from and e the currently loaded experiment then
* the following statements are valid for the merged experiment: <br/>
* * instances(e) = UNION{instances(e_i)}
* * sc(e) = UNION{sc(e_i)}, sc_1 == sc_2 iff they are equal in their semantics (same solver, same parameters)
* * ... tbd
* @param task
* @param solverConfigIds
* @param duplicate
* @throws SQLException
* @throws Exception
*/
public void importDataFromSolverConfigurations(Tasks task, ArrayList<Integer> solverConfigIds, ArrayList<Boolean> duplicate) throws SQLException, Exception {
/* if (solverConfigIds.size() != duplicate.size()) {
throw new IllegalArgumentException("solverConfigIds.size() != duplicate.size()");
}
final boolean autocommit = DatabaseConnector.getInstance().getConn().getAutoCommit();
DatabaseConnector.getInstance().getConn().setAutoCommit(false);
try {
HashSet<Integer> experimentIds = new HashSet<Integer>();
for (int scId : solverConfigIds) {
experimentIds.add(SolverConfigurationDAO.getSolverConfigurationById(scId).getExperiment_id());
}
boolean first = true;
boolean useNotFinishedJobs = true;
for (int expId : experimentIds) {
Experiment exp = ExperimentDAO.getById(expId);
if (first) {
first = false;
activeExperiment.setAutoGeneratedSeeds(exp.isAutoGeneratedSeeds());
activeExperiment.setCPUTimeLimit(exp.getCPUTimeLimit());
activeExperiment.setLinkSeeds(exp.isLinkSeeds());
activeExperiment.setMaxSeed(exp.getMaxSeed());
activeExperiment.setMemoryLimit(exp.getMemoryLimit());
activeExperiment.setOutputSizeLimit(exp.getOutputSizeLimit());
activeExperiment.setStackSizeLimit(exp.getStackSizeLimit());
activeExperiment.setWallClockTimeLimit(exp.getWallClockTimeLimit());
} else {
activeExperiment.setAutoGeneratedSeeds(activeExperiment.isAutoGeneratedSeeds() | exp.isAutoGeneratedSeeds());
activeExperiment.setLinkSeeds(activeExperiment.isLinkSeeds() | exp.isLinkSeeds());
if (activeExperiment.getMaxSeed() < exp.getMaxSeed()) {
activeExperiment.setMaxSeed(exp.getMaxSeed());
}
if (activeExperiment.getCPUTimeLimit() != exp.getCPUTimeLimit()) {
useNotFinishedJobs = false;
if (activeExperiment.getCPUTimeLimit() < exp.getCPUTimeLimit() && activeExperiment.getCPUTimeLimit() != -1) {
activeExperiment.setCPUTimeLimit(exp.getCPUTimeLimit());
}
}
if (activeExperiment.getMemoryLimit() != exp.getMemoryLimit()) {
useNotFinishedJobs = false;
if (activeExperiment.getMemoryLimit() < exp.getMemoryLimit() && activeExperiment.getMemoryLimit() != -1) {
activeExperiment.setMemoryLimit(exp.getMemoryLimit());
}
}
if (activeExperiment.getOutputSizeLimit() != exp.getOutputSizeLimit()) {
useNotFinishedJobs = false;
if (activeExperiment.getOutputSizeLimit() < exp.getOutputSizeLimit() && activeExperiment.getOutputSizeLimit() != -1) {
activeExperiment.setOutputSizeLimit(exp.getOutputSizeLimit());
}
}
if (activeExperiment.getStackSizeLimit() != exp.getStackSizeLimit()) {
useNotFinishedJobs = false;
if (activeExperiment.getStackSizeLimit() < exp.getStackSizeLimit() && activeExperiment.getStackSizeLimit() != -1) {
activeExperiment.setStackSizeLimit(exp.getStackSizeLimit());
}
}
if (activeExperiment.getWallClockTimeLimit() != exp.getWallClockTimeLimit()) {
useNotFinishedJobs = false;
if (activeExperiment.getWallClockTimeLimit() < exp.getWallClockTimeLimit() && activeExperiment.getWallClockTimeLimit() != -1) {
activeExperiment.setWallClockTimeLimit(exp.getWallClockTimeLimit());
}
}
}
}
boolean haveToDuplicate = false;
//activeExperiment.setAutoGeneratedSeeds(true);
int numRuns = 0;
ArrayList<Integer> newIds = new ArrayList<Integer>();
for (int i = 0; i < solverConfigIds.size(); i++) {
haveToDuplicate |= duplicate.get(i);
int scId = solverConfigIds.get(i);
SolverConfiguration sc = SolverConfigurationDAO.getSolverConfigurationById(scId);
task.setOperationName("Processing data from solver configuration " + sc.getName() + " (" + (i + 1) + " / " + solverConfigIds.size() + "):");
task.setTaskProgress((float) (i + 1) / solverConfigIds.size());
RunCountSCId tmp = this.importDataFromSolverConfiguration(task, sc, useNotFinishedJobs);
if (tmp.runcount > numRuns) {
numRuns = tmp.runcount;
}
newIds.add(tmp.scid);
}
if (haveToDuplicate) {
task.setStatus("Duplicating results..");
LinkedList<Instance> instances = InstanceDAO.getAllByExperimentId(activeExperiment.getId());
updateExperimentResults();
Random random = new Random();
ArrayList<ExperimentResult> newResults = new ArrayList<ExperimentResult>();
ArrayList<ExperimentResult> oldResults = new ArrayList<ExperimentResult>();
for (int k = 0; k < solverConfigIds.size(); k++) {
for (Instance instance : instances) {
if (task.isCancelled()) {
throw new TaskCancelledException();
}
if (duplicate.get(k)) {
int runCount = this.getResults(newIds.get(k), instance.getId()).size();
// int runCount = ExperimentDAO.getRunCountInExperimentForSolverConfigurationAndInstance(activeExperiment, newIds.get(k), instance.getId());
ArrayList<ExperimentResult> results = getResults(newIds.get(k), instance.getId());
if (results.size() > 0) {
for (int t = runCount; t < numRuns; t++) {
ExperimentResult er = results.get(random.nextInt(results.size()));
newResults.add(ExperimentResultDAO.createExperimentResult(t, er.getPriority(), er.getComputeQueue(), er.getStatus().getDefaultValue(), er.getSeed(), er.getResultCode(), er.getResultTime(), er.getSolverConfigId(), activeExperiment.getId(), er.getInstanceId(), er.getStartTime()));
oldResults.add(er);
}
}
}
}
}
if (newResults.size() > 0) {
task.setStatus("Saving results..");
ExperimentResultDAO.batchSave(newResults);
if (task.isCancelled()) {
throw new TaskCancelledException();
}
task.setStatus("Saving outputs..");
ExperimentResultDAO.batchCopyOutputs(oldResults, newResults);
}
if (task.isCancelled()) {
throw new TaskCancelledException();
}
}
generateJobs(numRuns, task);
task.setStatus("Finalizing..");
ExperimentDAO.save(activeExperiment);
updateExperimentResults();
} catch (Exception e) {
DatabaseConnector.getInstance().getConn().rollback();
throw e;
} finally {
DatabaseConnector.getInstance().getConn().setAutoCommit(autocommit);
}*/
}
/**
* Imports data from the specified solver configs, instances and runs (if <code>statusCodes</code> is not empty) to the active experiment.
* @param task
* @param selectedSolverConfigs the solver configs to import
* @param selectedInstances the instances to import
* @param statusCodes also import runs with status code in this list
* @throws SQLException
* @throws Exception
*/
public void importData(Tasks task, List<SolverConfiguration> selectedSolverConfigs, List<Instance> selectedInstances, List<StatusCode> statusCodes) throws SQLException, Exception {
if (main.hasUnsavedChanges()) {
throw new IllegalArgumentException("Assertion failure: Has unsaved changes.");
}
// assertion: no unsaved data.
task.setOperationName("Importing data from " + selectedSolverConfigs.size() + " solver configurations and " + selectedInstances.size() + " instances..");
boolean autoCommit = DatabaseConnector.getInstance().getConn().getAutoCommit();
try {
DatabaseConnector.getInstance().getConn().setAutoCommit(false);
task.setStatus("Loading instances..");
// get selected instance ids for active experiment
HashSet<Integer> instanceIds = new HashSet<Integer>();
for (Instance i : InstanceDAO.getAllByExperimentId(activeExperiment.getId())) {
instanceIds.add(i.getId());
}
task.setStatus("Determining seed group..");
// get highest seed group which doesn't exist
int seed_group = 0;
for (SolverConfiguration sc : solverConfigCache.getAll()) {
if (sc.getSeed_group() >= seed_group) {
seed_group = sc.getSeed_group() + 1;
}
}
task.setStatus("Checking existing solver configurations..");
// check for existing solver configs with same semantics to the imported ones
HashMap<Integer, Integer> mapHisScToMySc = new HashMap<Integer, Integer>();
for (SolverConfiguration sc2 : selectedSolverConfigs) {
for (SolverConfiguration sc : solverConfigCache.getAll()) {
if (sc.hasEqualSemantics(sc2)) {
mapHisScToMySc.put(sc2.getId(), sc.getId());
}
}
}
task.setStatus("Saving new solver configurations..");
ArrayList<ParameterInstance> newPis = new ArrayList<ParameterInstance>();
// save solver configurations which doesn't exist
for (SolverConfiguration sc : selectedSolverConfigs) {
if (!mapHisScToMySc.containsKey(sc.getId())) {
SolverConfiguration sc2 = solverConfigCache.createSolverConfiguration(sc.getSolverBinary(), activeExperiment.getId(), seed_group++, sc.getName(), sc.getHint());
ArrayList<ParameterInstance> pis = new ArrayList<ParameterInstance>();
for (ParameterInstance pi : ParameterInstanceDAO.getBySolverConfig(sc)) {
// ParameterInstanceDAO.createParameterInstance(pi.getParameter_id(), sc2, pi.getValue());
ParameterInstance npi = new ParameterInstance();
npi.setParameter_id(pi.getParameter_id());
npi.setSolverConfiguration(sc2);
npi.setValue(pi.getValue());
newPis.add(npi);
pis.add(npi);
}
// update map
for (SolverConfiguration tmp : selectedSolverConfigs) {
if (tmp.hasEqualSemantics(sc2.getSolverBinary(), pis)) {
mapHisScToMySc.put(tmp.getId(), sc2.getId());
}
}
}
}
task.setStatus("Saving parameters for newly created solver configurations..");
// save parameter instances
ParameterInstanceDAO.saveBulk(newPis);
task.setStatus("Saving instances..");
// save instances
List<ExperimentHasInstance> ehis = new LinkedList<ExperimentHasInstance>();
for (Instance i : selectedInstances) {
if (!instanceIds.contains(i.getId())) {
ehis.add(ExperimentHasInstanceDAO.createExperimentHasInstance(activeExperiment.getId(), i.getId()));
}
}
ExperimentHasInstanceDAO.save(ehis);
// import jobs
if (!statusCodes.isEmpty()) {
task.setStatus("Preparing import of jobs..");
ArrayList<ExperimentResult> resultsToImport = new ArrayList<ExperimentResult>();
ArrayList<ExperimentResult> importedResults = new ArrayList<ExperimentResult>();
HashMap<Pair<SolverConfiguration, Instance>, List<ExperimentResult>> experimentResults = ExperimentResultDAO.getBySolverConfigurationsAndInstances(selectedSolverConfigs, selectedInstances);
List<Integer> selectedInstanceIds = new LinkedList<Integer>();
for (Instance i : selectedInstances)
selectedInstanceIds.add(i.getId());
HashSet<Integer> seedGroupSet = new HashSet<Integer>();
for (Integer scId : mapHisScToMySc.values()) {
SolverConfiguration sc = SolverConfigurationDAO.getSolverConfigurationById(scId);
seedGroupSet.add(sc.getSeed_group());
}
List<Integer> seedGroups = new LinkedList<Integer>();
List<Integer> expIds = new LinkedList<Integer>();
for (Integer i : seedGroupSet)
seedGroups.add(i);
expIds.add(activeExperiment.getId());
HashMap<SeedGroupExperimentIdInstanceId, Integer> seedGroupMap = ExperimentResultDAO.getMaxRunsForSeedGroupsByExperimentIdsAndInstanceId(seedGroups, expIds, selectedInstanceIds);
task.setStatus("Importing jobs..");
HashMap<Integer, HashMap<Integer, Integer>> instanceSeedGroupFirstRun = new HashMap<Integer, HashMap<Integer, Integer>>();
for (Instance i : selectedInstances) {
HashMap<Integer, Integer> seedGroupFirstRun = instanceSeedGroupFirstRun.get(i.getId());
if (seedGroupFirstRun == null) {
seedGroupFirstRun = new HashMap<Integer, Integer>();
instanceSeedGroupFirstRun.put(i.getId(), seedGroupFirstRun);
}
for (SolverConfiguration sc : selectedSolverConfigs) {
List<ExperimentResult> tmp = experimentResults.get(new Pair<SolverConfiguration, Instance>(sc, i));
SolverConfiguration solverConfig = SolverConfigurationDAO.getSolverConfigurationById(mapHisScToMySc.get(sc.getId()));
Integer firstRun = seedGroupFirstRun.get(solverConfig.getSeed_group());
if (firstRun == null) {
// firstRun = ExperimentResultDAO.getMaxRunForSeedGroupByExperimentIdAndInstanceId(solverConfig.getSeed_group(), activeExperiment.getId(), i.getId()) + 1;
firstRun = seedGroupMap.get(new SeedGroupExperimentIdInstanceId(solverConfig.getSeed_group(), activeExperiment.getId(), i.getId()));
if (firstRun == null)
firstRun = 0;
}
if (tmp != null) {
for (ExperimentResult er : tmp) {
boolean contains = false;
for (StatusCode stat : statusCodes) {
if (er.getStatus().equals(stat)) {
contains = true;
break;
}
}
if (contains) {
resultsToImport.add(er);
importedResults.add(ExperimentResultDAO.createExperimentResult(firstRun++, er.getPriority(), er.getComputeQueue(), er.getStatus(), er.getSeed(), er.getResultCode(), er.getResultTime(), er.getWallTime(), er.getCost(), mapHisScToMySc.get(sc.getId()), activeExperiment.getId(), er.getInstanceId(), er.getStartTime(), er.getCPUTimeLimit(), er.getMemoryLimit(), er.getWallClockTimeLimit(), er.getStackSizeLimit()));
}
}
}
seedGroupFirstRun.put(solverConfig.getSeed_group(), firstRun);
}
}
ExperimentResultDAO.batchSave(importedResults);
ExperimentResultDAO.batchCopyOutputs(resultsToImport, importedResults);
}
solverConfigCache.reload();
if (!statusCodes.isEmpty()) {
experimentResultCache.updateExperimentResults();
main.generateJobsTableModel.updateNumRuns();
// no use of seed here because seeds are given by seed groups if jobs have to be generated
generateJobs(task, -1, -1, -1, -1, 0);
}
DatabaseConnector.getInstance().getConn().setAutoCommit(autoCommit);
} catch (Exception ex) {
if (autoCommit)
DatabaseConnector.getInstance().getConn().rollback();
DatabaseConnector.getInstance().getConn().setAutoCommit(autoCommit);
throw ex;
}
}
/**
* Checks if a grid queue is assigned to this experiment
* @return true, iff a grid queue is assigned
*/
public boolean hasGridQueuesAssigned() {
try {
if (activeExperiment == null) {
return false;
}
return !ExperimentHasGridQueueDAO.getExperimentHasGridQueueByExperiment(activeExperiment).isEmpty();
} catch (SQLException ex) {
return false;
}
}
/**
* Checks if data in the experiment design tabs is modified.
* @return true, iff some data is modified
*/
public boolean experimentResultsIsModified() {
boolean res = false;
try {
experimentResultCache.updateExperimentResults();
LinkedList<Instance> instances = InstanceDAO.getAllByExperimentId(activeExperiment.getId());
for (SolverConfiguration sc : solverConfigCache.getAll()) {
for (Instance i : instances) {
int savedNumRuns = experimentResultCache.getNumRuns(sc.getId(), i.getId());
main.generateJobsTableModel.setSavedNumRuns(i, sc, savedNumRuns);
if (main.generateJobsTableModel.getNumRuns(i, sc) != savedNumRuns) {
res = true;
}
}
}
} catch (Exception e) {
}
return res;
}
public boolean configurationScenarioIsModified() {
if (activeExperiment == null || !activeExperiment.isConfigurationExp()) {
return false;
}
if (savedScenario == null) {
return true;
}
if (main.configScenarioTableModel.getSolverBinary() == null || savedScenario.getIdSolverBinary() != main.configScenarioTableModel.getSolverBinary().getId()) {
return true;
}
HashMap<Integer, ConfigurationScenarioParameter> configParameters = main.configScenarioTableModel.getConfigScenarioParameters();
if (configParameters == null) {
return true;
}
if (savedScenario.getParameters().size() != configParameters.size()) {
return true;
}
for (ConfigurationScenarioParameter param : configParameters.values()) {
if (!ConfigurationScenarioDAO.configurationScenarioParameterIsSaved(param)) {
return true;
}
}
return false;
}
public boolean solverConfigsIsModified() {
return (solverConfigCache != null && solverConfigCache.isModified()) || (solverConfigurationEntryModel == null ? false : solverConfigurationEntryModel.isModified());
}
/**
* Returns a double value for the given property value type and the string value
* @param type
* @param value
* @return null, iff the property value type doesn't represent Integer, Float or Double or an error occurred.
*/
private Double transformPropertyValueTypeToDouble(PropertyValueType type, String value) {
Double res = null;
try {
if (type.getJavaType() == Integer.class) {
res = new Double((Integer) type.getJavaTypeRepresentation(value));
} else if (type.getJavaType() == Float.class) {
res = new Double((Float) type.getJavaTypeRepresentation(value));
} else if (type.getJavaType() == Double.class) {
res = (Double) type.getJavaTypeRepresentation(value);
}
} catch (ConvertException ex) {
return null;
}
return res;
}
/**
* Returns the value for the given property and the given experiment result.
* @param result
* @param property
* @return null, iff the experiment result`s status is RUNNING, NOTSTARTED, LAUNCHERCRASH, VERIFIERCRASH, WATCHERCRASH or the property isn't calculated or the result isn't successfully verified. In case of the cpu-time property CPUTimeLmit can be returned.
*/
public Double getValue(ExperimentResult result, Property property) {
return getValue(result, property, true);
}
/**
* Returns the value for the given property and the given experiment result.
* @param result
* @param property
* @param useTimeOutForCPUProp
* @return null, iff the experiment result`s status is RUNNING, NOTSTARTED, LAUNCHERCRASH, VERIFIERCRASH, WATCHERCRASH or the property isn't calculated or the result isn't successfully verified. In case of the cpu-time property CPUTimeLmit can be returned.
*/
public Double getValue(ExperimentResult result, Property property, boolean useTimeOutForCPUProp) {
if (result.getStatus() == StatusCode.RUNNING
|| result.getStatus() == StatusCode.NOT_STARTED
|| result.getStatus() == StatusCode.LAUNCHERCRASH
|| result.getStatus() == StatusCode.VERIFIERCRASH
|| result.getStatus() == StatusCode.WATCHERCRASH) {
return null;
}
if (property == PROP_CPUTIME) {
if (!String.valueOf(result.getResultCode().getResultCode()).startsWith("1")) {
if (useTimeOutForCPUProp) {
return new Double(result.getCPUTimeLimit());
} else {
return null;
}
}
return Double.valueOf(result.getResultTime());
} else {
if (!String.valueOf(result.getResultCode().getResultCode()).startsWith("1")) {
return null;
}
ExperimentResultHasProperty erhsp = result.getPropertyValues().get(property.getId());
if (erhsp == null || erhsp.getValue().isEmpty()) {
return null;
}
return transformPropertyValueTypeToDouble(property.getPropertyValueType(), erhsp.getValue().get(0));
}
}
/**
* Returns the value of the property for this instance
* @param instance the instance
* @param property the property
* @return null, iff the property isn't calculated or some error occurred.
*/
public Double getValue(Instance instance, Property property) {
InstanceHasProperty ihip = instance.getPropertyValues().get(property.getId());
if (ihip == null) {
return null;
}
return transformPropertyValueTypeToDouble(property.getPropertyValueType(), ihip.getValue());
}
/**
* Returns all instances.
* @return arraylist of the instances
* @throws SQLException
* @throws InstanceClassMustBeSourceException
* @throws IOException
* @throws NoConnectionToDBException
* @throws PropertyNotInDBException
* @throws PropertyTypeNotExistException
* @throws ComputationMethodDoesNotExistException
*/
public ArrayList<Instance> getInstances() throws SQLException, InstanceClassMustBeSourceException, IOException, NoConnectionToDBException, PropertyNotInDBException, PropertyTypeNotExistException, ComputationMethodDoesNotExistException {
if (activeExperiment == null) {
return null;
}
ArrayList<Instance> res = new ArrayList<Instance>();
res.addAll(InstanceDAO.getAllByExperimentId(activeExperiment.getId()));
return res;
}
/**
* Returns all solver configurations.
* @return arraylist of the solver configurations
* @throws SQLException
*/
public ArrayList<SolverConfiguration> getSolverConfigurations() throws SQLException {
if (activeExperiment == null) {
return null;
}
return solverConfigCache.getAll();
}
/**
* Returns all result properties; adds CPUTime as result property.
* @return arraylist of the result properties
* @throws Exception
*/
public ArrayList<Property> getResultProperties() throws Exception {
ArrayList<Property> res = new ArrayList<Property>();
res.add(ExperimentController.PROP_CPUTIME);
res.addAll(PropertyDAO.getAllResultProperties());
return res;
}
/**
* Returns all instance properties.
* @return arraylist of the instance properties
* @throws Exception
*/
public ArrayList<Property> getInstanceProperties() throws Exception {
ArrayList<Property> res = new ArrayList<Property>();
res.addAll(PropertyDAO.getAllInstanceProperties());
return res;
}
public void updateConfigScenarioTable(SolverBinaries solverBinary) throws SQLException {
main.configScenarioTableModel.setConfigurationScenario(solverBinary, configScenario);
}
public void saveConfigurationScenario() throws SQLException {
SolverBinaries solverBinary = main.configScenarioTableModel.getSolverBinary();
if (configScenario == null) {
configScenario = new ConfigurationScenario();
configScenario.setIdExperiment(activeExperiment.getId());
configScenario.setNew();
}
configScenario.setIdSolverBinary(solverBinary.getId());
configScenario.getParameters().clear();
configScenario.getParameters().addAll(main.configScenarioTableModel.getConfigScenarioParameters().values());
ConfigurationScenarioDAO.save(configScenario);
// we need a new instance for this
savedScenario = ConfigurationScenarioDAO.getConfigurationScenarioByExperimentId(activeExperiment.getId());
}
public ConfigurationScenario getConfigurationScenarioForExperiment(Experiment exp) throws SQLException {
ConfigurationScenario scenario = ConfigurationScenarioDAO.getConfigurationScenarioByExperimentId(exp.getId());
return scenario;
}
public ConfigurationScenario getConfigScenario() {
return configScenario;
}
public void refreshConfiguratorOutput() throws SQLException {
if (configScenario != null) {
ConfigurationScenarioDAO.updateConfiguratorOutput(configScenario);
}
}
public void reloadConfigurationScenario() throws SQLException {
configScenario = ConfigurationScenarioDAO.getConfigurationScenarioByExperimentId(activeExperiment.getId());
}
public SolverConfigurationEntryModel getSolverConfigurationEntryModel() {
return solverConfigurationEntryModel;
}
/**
* Returns an instance of a cost function from the given database representation,
* or null, if no such cost function exists.
* @param databaseRepresentation
* @return instance of CostFunction
*/
public CostFunction costFunctionByName(String databaseRepresentation) {
if (activeExperiment == null) {
throw new IllegalArgumentException("No experiment loaded.");
}
if ("average".equals(databaseRepresentation)) {
return new Average(activeExperiment.getDefaultCost(), activeExperiment.getMinimize());
} else if ("median".equals(databaseRepresentation)) {
return new Median(activeExperiment.getDefaultCost(), activeExperiment.getMinimize());
} else if (databaseRepresentation != null && databaseRepresentation.startsWith("par")) {
try {
int penaltyFactor = Integer.valueOf(databaseRepresentation.substring(3));
return new PARX(activeExperiment.getDefaultCost(), activeExperiment.getMinimize(), activeExperiment.getCostPenalty() != null ? activeExperiment.getCostPenalty() : 0.f, penaltyFactor);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
return null;
}
/**
* Calculates the costs for the specified solver configurations. Persists all changes to db.<br/>
* @param costFunction
* @param solverConfigs
* @throws Exception
*/
public void calculateCosts(Tasks task, String costFunction, ArrayList<SolverConfiguration> solverConfigs) throws Exception {
task.setOperationName("Calculating cost for " + costFunction);
if (costFunction == null) {
throw new IllegalArgumentException("cost function cannot be null");
} else if (solverConfigs == null || solverConfigs.isEmpty()) {
throw new IllegalArgumentException("no solver configurations for cost calculation selected");
} else if (activeExperiment == null) {
throw new IllegalArgumentException("no experiment loaded");
}
for (SolverConfiguration solverConfig : solverConfigs) {
if (solverConfig.getExperiment_id() != activeExperiment.getId()) {
throw new IllegalArgumentException("calculating costs for other experiments than the loaded experiment is currently not supported");
}
}
CostFunction cFunction = costFunctionByName(costFunction);
if (cFunction == null) {
throw new Exception("invalid cost function");
}
task.setStatus("Updating jobs..");
experimentResultCache.updateExperimentResults();
task.setStatus("Calculating..");
for (SolverConfiguration solverConfig : solverConfigs) {
Double cost = cFunction.calculateCost(experimentResultCache.getResults(solverConfig.getId()));
solverConfig.setCost(cost);
solverConfig.setCost_function(cFunction.databaseRepresentation());
}
}
public List<Verifier> getVerifiers() throws SQLException {
return VerifierDAO.getAllVerifiers();
}
public void saveVerifierConfig(VerifierConfiguration verifierConfig) throws SQLException {
VerifierConfigurationDAO.save(verifierConfig);
}
public VerifierConfiguration getVerifierConfig(int expId) throws SQLException {
return VerifierConfigurationDAO.getByExperimentId(expId);
}
public List<Cost> getCosts() throws SQLException {
return CostDAO.getAllCosts();
}
}
|
MeowMC/Vivecraft_116
|
src/org/vivecraft/gui/settings/GuiVRControls.java
|
<filename>src/org/vivecraft/gui/settings/GuiVRControls.java
/**
* Copyright 2013 <NAME>, StellaArtois
* Licensed under the LGPL 3.0 or later (See LICENSE.md for details)
*/
package org.vivecraft.gui.settings;
import com.mojang.blaze3d.matrix.MatrixStack;
import net.minecraft.client.gui.AbstractGui;
import net.minecraft.client.gui.screen.Screen;
import net.optifine.Lang;
import org.vivecraft.gui.framework.GuiVROptionsBase;
import org.vivecraft.gui.framework.VROptionEntry;
import org.vivecraft.settings.VRSettings;
public class GuiVRControls extends GuiVROptionsBase {
private static VROptionEntry[] controlsSettings = new VROptionEntry[]{
new VROptionEntry(VRSettings.VrOptions.DUMMY, true),
new VROptionEntry(VRSettings.VrOptions.DUMMY, true),
new VROptionEntry(VRSettings.VrOptions.DUMMY, true),
new VROptionEntry(VRSettings.VrOptions.DUMMY, true),
new VROptionEntry(VRSettings.VrOptions.DUMMY, true),
new VROptionEntry(VRSettings.VrOptions.DUMMY, true),
new VROptionEntry(VRSettings.VrOptions.REVERSE_HANDS),
new VROptionEntry(VRSettings.VrOptions.RIGHT_CLICK_DELAY),
new VROptionEntry(VRSettings.VrOptions.ALLOW_ADVANCED_BINDINGS, true)
};
public GuiVRControls(Screen par1GuiScreen) {
super(par1GuiScreen);
}
@Override
public void init() {
vrTitle = "vivecraft.options.screen.controls";
super.init(controlsSettings, true);
super.addDefaultButtons();
}
@Override
public void render(MatrixStack matrixstack, int mouseX, int mouseY, float partialTicks) {
super.render(matrixstack, mouseX, mouseY, partialTicks);
drawCenteredString(matrixstack, minecraft.fontRenderer, Lang.get("vivecraft.messages.controls.1"), this.width / 2, this.height / 2 - minecraft.fontRenderer.FONT_HEIGHT / 2 - minecraft.fontRenderer.FONT_HEIGHT - 3, 16777215);
drawCenteredString(matrixstack, minecraft.fontRenderer, Lang.get("vivecraft.messages.controls.2"), this.width / 2, this.height / 2 - minecraft.fontRenderer.FONT_HEIGHT / 2, 16777215);
drawCenteredString(matrixstack, minecraft.fontRenderer, Lang.get("vivecraft.messages.controls.3"), this.width / 2, this.height / 2 - minecraft.fontRenderer.FONT_HEIGHT / 2 + minecraft.fontRenderer.FONT_HEIGHT + 3, 16777215);
}
@Override
protected void loadDefaults() {
VRSettings vrSettings = minecraft.vrSettings;
vrSettings.vrReverseHands = false;
vrSettings.allowAdvancedBindings = false;
vrSettings.rightclickDelay = 6;
}
}
|
plotor/vertx-zero
|
vertx-zeus/up-metis/src/main/java/com/htl/domain/tables/records/LctDistinctRecord.java
|
/*
* This file is generated by jOOQ.
*/
package com.htl.domain.tables.records;
import com.htl.domain.tables.LctDistinct;
import com.htl.domain.tables.interfaces.ILctDistinct;
import java.time.LocalDateTime;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record13;
import org.jooq.Row13;
import org.jooq.impl.UpdatableRecordImpl;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.10.7"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class LctDistinctRecord extends UpdatableRecordImpl<LctDistinctRecord> implements Record13<String, String, String, String, Integer, String, Boolean, String, String, String, LocalDateTime, String, LocalDateTime>, ILctDistinct {
private static final long serialVersionUID = -131126600;
/**
* Setter for <code>DB_HTL.LCT_DISTINCT.PK_ID</code>. uniqueId,PK_ID
*/
@Override
public LctDistinctRecord setPkId(String value) {
set(0, value);
return this;
}
/**
* Getter for <code>DB_HTL.LCT_DISTINCT.PK_ID</code>. uniqueId,PK_ID
*/
@Override
public String getPkId() {
return (String) get(0);
}
/**
* Setter for <code>DB_HTL.LCT_DISTINCT.S_NAME</code>. 名称,name,S_NAME
*/
@Override
public LctDistinctRecord setSName(String value) {
set(1, value);
return this;
}
/**
* Getter for <code>DB_HTL.LCT_DISTINCT.S_NAME</code>. 名称,name,S_NAME
*/
@Override
public String getSName() {
return (String) get(1);
}
/**
* Setter for <code>DB_HTL.LCT_DISTINCT.S_CODE</code>. code,S_CODE
*/
@Override
public LctDistinctRecord setSCode(String value) {
set(2, value);
return this;
}
/**
* Getter for <code>DB_HTL.LCT_DISTINCT.S_CODE</code>. code,S_CODE
*/
@Override
public String getSCode() {
return (String) get(2);
}
/**
* Setter for <code>DB_HTL.LCT_DISTINCT.J_CONFIG</code>. config,J_CONFIG
*/
@Override
public LctDistinctRecord setJConfig(String value) {
set(3, value);
return this;
}
/**
* Getter for <code>DB_HTL.LCT_DISTINCT.J_CONFIG</code>. config,J_CONFIG
*/
@Override
public String getJConfig() {
return (String) get(3);
}
/**
* Setter for <code>DB_HTL.LCT_DISTINCT.I_ORDER</code>. 区域排序,order,I_ORDER
*/
@Override
public LctDistinctRecord setIOrder(Integer value) {
set(4, value);
return this;
}
/**
* Getter for <code>DB_HTL.LCT_DISTINCT.I_ORDER</code>. 区域排序,order,I_ORDER
*/
@Override
public Integer getIOrder() {
return (Integer) get(4);
}
/**
* Setter for <code>DB_HTL.LCT_DISTINCT.R_CITY_ID</code>. REF:关联城市,cityId,R_CITY_ID
*/
@Override
public LctDistinctRecord setRCityId(String value) {
set(5, value);
return this;
}
/**
* Getter for <code>DB_HTL.LCT_DISTINCT.R_CITY_ID</code>. REF:关联城市,cityId,R_CITY_ID
*/
@Override
public String getRCityId() {
return (String) get(5);
}
/**
* Setter for <code>DB_HTL.LCT_DISTINCT.IS_ACTIVE</code>. active,IS_ACTIVE
*/
@Override
public LctDistinctRecord setIsActive(Boolean value) {
set(6, value);
return this;
}
/**
* Getter for <code>DB_HTL.LCT_DISTINCT.IS_ACTIVE</code>. active,IS_ACTIVE
*/
@Override
public Boolean getIsActive() {
return (Boolean) get(6);
}
/**
* Setter for <code>DB_HTL.LCT_DISTINCT.Z_SIGMA</code>. sigma,Z_SIGMA
*/
@Override
public LctDistinctRecord setZSigma(String value) {
set(7, value);
return this;
}
/**
* Getter for <code>DB_HTL.LCT_DISTINCT.Z_SIGMA</code>. sigma,Z_SIGMA
*/
@Override
public String getZSigma() {
return (String) get(7);
}
/**
* Setter for <code>DB_HTL.LCT_DISTINCT.Z_LANGUAGE</code>. language,Z_LANGUAGE
*/
@Override
public LctDistinctRecord setZLanguage(String value) {
set(8, value);
return this;
}
/**
* Getter for <code>DB_HTL.LCT_DISTINCT.Z_LANGUAGE</code>. language,Z_LANGUAGE
*/
@Override
public String getZLanguage() {
return (String) get(8);
}
/**
* Setter for <code>DB_HTL.LCT_DISTINCT.Z_CREATE_BY</code>. createBy,Z_CREATE_BY
*/
@Override
public LctDistinctRecord setZCreateBy(String value) {
set(9, value);
return this;
}
/**
* Getter for <code>DB_HTL.LCT_DISTINCT.Z_CREATE_BY</code>. createBy,Z_CREATE_BY
*/
@Override
public String getZCreateBy() {
return (String) get(9);
}
/**
* Setter for <code>DB_HTL.LCT_DISTINCT.Z_CREATE_TIME</code>. createTime,Z_CREATE_TIME
*/
@Override
public LctDistinctRecord setZCreateTime(LocalDateTime value) {
set(10, value);
return this;
}
/**
* Getter for <code>DB_HTL.LCT_DISTINCT.Z_CREATE_TIME</code>. createTime,Z_CREATE_TIME
*/
@Override
public LocalDateTime getZCreateTime() {
return (LocalDateTime) get(10);
}
/**
* Setter for <code>DB_HTL.LCT_DISTINCT.Z_UPDATE_BY</code>. updateBy,Z_UPDATE_BY
*/
@Override
public LctDistinctRecord setZUpdateBy(String value) {
set(11, value);
return this;
}
/**
* Getter for <code>DB_HTL.LCT_DISTINCT.Z_UPDATE_BY</code>. updateBy,Z_UPDATE_BY
*/
@Override
public String getZUpdateBy() {
return (String) get(11);
}
/**
* Setter for <code>DB_HTL.LCT_DISTINCT.Z_UPDATE_TIME</code>. updateTime,Z_UPDATE_TIME
*/
@Override
public LctDistinctRecord setZUpdateTime(LocalDateTime value) {
set(12, value);
return this;
}
/**
* Getter for <code>DB_HTL.LCT_DISTINCT.Z_UPDATE_TIME</code>. updateTime,Z_UPDATE_TIME
*/
@Override
public LocalDateTime getZUpdateTime() {
return (LocalDateTime) get(12);
}
// -------------------------------------------------------------------------
// Primary key information
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Record1<String> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record13 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Row13<String, String, String, String, Integer, String, Boolean, String, String, String, LocalDateTime, String, LocalDateTime> fieldsRow() {
return (Row13) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public Row13<String, String, String, String, Integer, String, Boolean, String, String, String, LocalDateTime, String, LocalDateTime> valuesRow() {
return (Row13) super.valuesRow();
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field1() {
return LctDistinct.LCT_DISTINCT.PK_ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field2() {
return LctDistinct.LCT_DISTINCT.S_NAME;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field3() {
return LctDistinct.LCT_DISTINCT.S_CODE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field4() {
return LctDistinct.LCT_DISTINCT.J_CONFIG;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field5() {
return LctDistinct.LCT_DISTINCT.I_ORDER;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field6() {
return LctDistinct.LCT_DISTINCT.R_CITY_ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Boolean> field7() {
return LctDistinct.LCT_DISTINCT.IS_ACTIVE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field8() {
return LctDistinct.LCT_DISTINCT.Z_SIGMA;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field9() {
return LctDistinct.LCT_DISTINCT.Z_LANGUAGE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field10() {
return LctDistinct.LCT_DISTINCT.Z_CREATE_BY;
}
/**
* {@inheritDoc}
*/
@Override
public Field<LocalDateTime> field11() {
return LctDistinct.LCT_DISTINCT.Z_CREATE_TIME;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field12() {
return LctDistinct.LCT_DISTINCT.Z_UPDATE_BY;
}
/**
* {@inheritDoc}
*/
@Override
public Field<LocalDateTime> field13() {
return LctDistinct.LCT_DISTINCT.Z_UPDATE_TIME;
}
/**
* {@inheritDoc}
*/
@Override
public String component1() {
return getPkId();
}
/**
* {@inheritDoc}
*/
@Override
public String component2() {
return getSName();
}
/**
* {@inheritDoc}
*/
@Override
public String component3() {
return getSCode();
}
/**
* {@inheritDoc}
*/
@Override
public String component4() {
return getJConfig();
}
/**
* {@inheritDoc}
*/
@Override
public Integer component5() {
return getIOrder();
}
/**
* {@inheritDoc}
*/
@Override
public String component6() {
return getRCityId();
}
/**
* {@inheritDoc}
*/
@Override
public Boolean component7() {
return getIsActive();
}
/**
* {@inheritDoc}
*/
@Override
public String component8() {
return getZSigma();
}
/**
* {@inheritDoc}
*/
@Override
public String component9() {
return getZLanguage();
}
/**
* {@inheritDoc}
*/
@Override
public String component10() {
return getZCreateBy();
}
/**
* {@inheritDoc}
*/
@Override
public LocalDateTime component11() {
return getZCreateTime();
}
/**
* {@inheritDoc}
*/
@Override
public String component12() {
return getZUpdateBy();
}
/**
* {@inheritDoc}
*/
@Override
public LocalDateTime component13() {
return getZUpdateTime();
}
/**
* {@inheritDoc}
*/
@Override
public String value1() {
return getPkId();
}
/**
* {@inheritDoc}
*/
@Override
public String value2() {
return getSName();
}
/**
* {@inheritDoc}
*/
@Override
public String value3() {
return getSCode();
}
/**
* {@inheritDoc}
*/
@Override
public String value4() {
return getJConfig();
}
/**
* {@inheritDoc}
*/
@Override
public Integer value5() {
return getIOrder();
}
/**
* {@inheritDoc}
*/
@Override
public String value6() {
return getRCityId();
}
/**
* {@inheritDoc}
*/
@Override
public Boolean value7() {
return getIsActive();
}
/**
* {@inheritDoc}
*/
@Override
public String value8() {
return getZSigma();
}
/**
* {@inheritDoc}
*/
@Override
public String value9() {
return getZLanguage();
}
/**
* {@inheritDoc}
*/
@Override
public String value10() {
return getZCreateBy();
}
/**
* {@inheritDoc}
*/
@Override
public LocalDateTime value11() {
return getZCreateTime();
}
/**
* {@inheritDoc}
*/
@Override
public String value12() {
return getZUpdateBy();
}
/**
* {@inheritDoc}
*/
@Override
public LocalDateTime value13() {
return getZUpdateTime();
}
/**
* {@inheritDoc}
*/
@Override
public LctDistinctRecord value1(String value) {
setPkId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public LctDistinctRecord value2(String value) {
setSName(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public LctDistinctRecord value3(String value) {
setSCode(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public LctDistinctRecord value4(String value) {
setJConfig(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public LctDistinctRecord value5(Integer value) {
setIOrder(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public LctDistinctRecord value6(String value) {
setRCityId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public LctDistinctRecord value7(Boolean value) {
setIsActive(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public LctDistinctRecord value8(String value) {
setZSigma(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public LctDistinctRecord value9(String value) {
setZLanguage(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public LctDistinctRecord value10(String value) {
setZCreateBy(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public LctDistinctRecord value11(LocalDateTime value) {
setZCreateTime(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public LctDistinctRecord value12(String value) {
setZUpdateBy(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public LctDistinctRecord value13(LocalDateTime value) {
setZUpdateTime(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public LctDistinctRecord values(String value1, String value2, String value3, String value4, Integer value5, String value6, Boolean value7, String value8, String value9, String value10, LocalDateTime value11, String value12, LocalDateTime value13) {
value1(value1);
value2(value2);
value3(value3);
value4(value4);
value5(value5);
value6(value6);
value7(value7);
value8(value8);
value9(value9);
value10(value10);
value11(value11);
value12(value12);
value13(value13);
return this;
}
// -------------------------------------------------------------------------
// FROM and INTO
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public void from(ILctDistinct from) {
setPkId(from.getPkId());
setSName(from.getSName());
setSCode(from.getSCode());
setJConfig(from.getJConfig());
setIOrder(from.getIOrder());
setRCityId(from.getRCityId());
setIsActive(from.getIsActive());
setZSigma(from.getZSigma());
setZLanguage(from.getZLanguage());
setZCreateBy(from.getZCreateBy());
setZCreateTime(from.getZCreateTime());
setZUpdateBy(from.getZUpdateBy());
setZUpdateTime(from.getZUpdateTime());
}
/**
* {@inheritDoc}
*/
@Override
public <E extends ILctDistinct> E into(E into) {
into.from(this);
return into;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached LctDistinctRecord
*/
public LctDistinctRecord() {
super(LctDistinct.LCT_DISTINCT);
}
/**
* Create a detached, initialised LctDistinctRecord
*/
public LctDistinctRecord(String pkId, String sName, String sCode, String jConfig, Integer iOrder, String rCityId, Boolean isActive, String zSigma, String zLanguage, String zCreateBy, LocalDateTime zCreateTime, String zUpdateBy, LocalDateTime zUpdateTime) {
super(LctDistinct.LCT_DISTINCT);
set(0, pkId);
set(1, sName);
set(2, sCode);
set(3, jConfig);
set(4, iOrder);
set(5, rCityId);
set(6, isActive);
set(7, zSigma);
set(8, zLanguage);
set(9, zCreateBy);
set(10, zCreateTime);
set(11, zUpdateBy);
set(12, zUpdateTime);
}
}
|
embeddery/stackrox
|
pkg/k8sutil/nsobj_ref.go
|
package k8sutil
// NamespacedObject is the minimal interface for Kubernetes objects with a name and a namespace.
type NamespacedObject interface {
GetNamespace() string
GetName() string
}
// NSObjRef can be used to maintain a reference to a namespaced object in Kubernetes, identified through its namespace
// and name. This type is safe to be used as a key in a map.
// Note that this DOES NOT allow to distinguish between objects with different types but equal names.
type NSObjRef struct {
Namespace, Name string
}
// RefOf obtains a NSObjRef for the given object.
func RefOf(obj NamespacedObject) NSObjRef {
return NSObjRef{
Namespace: obj.GetNamespace(),
Name: obj.GetName(),
}
}
|
EasySimple/fishd-mobile
|
site/mobile/lib/iframe.js
|
<filename>site/mobile/lib/iframe.js
import eventbus from './eventbus'
import { hashHistory } from 'react-router';
let init = false
export default function initIframe () {
if (init) {
return
}
init = true
// 监听路由改变,同步父页面路由
window.addEventListener('hashchange', () => {
window.parent.postMessage(
{
type: 'pathChange',
data: location.hash
},
'*'
)
})
// 监听父路由事件
window.addEventListener('message', (e) => {
const event = e.data || ''
switch (event.type) {
case 'reloadDemo':
eventbus.emit('reloadDemo', event.data)
break
case 'pathChange':
// #/zh-CN/components/button
const arr = event.data.split('/')
const lang = arr[1]
const demo = arr[3] || ''
if (demo) {
hashHistory.replace(`/${lang}/${demo}`)
}
break
}
})
}
|
Heng-Z/mwr
|
models/unet/builder.py
|
<gh_stars>10-100
from IsoNet.models.unet.blocks import conv_blocks
from tensorflow.keras.layers import MaxPooling2D, UpSampling2D, MaxPooling3D, UpSampling3D, AveragePooling3D
from tensorflow.keras.layers import Concatenate
def build_unet(filter_base=32,depth=2,convs_per_depth=2,
kernel=(3,3),
batch_norm=False,
dropout=0.0,
pool=(2,2)):
if len(kernel)==2:
MaxPooling=MaxPooling2D
UpSampling=UpSampling2D
else:
MaxPooling=MaxPooling3D
UpSampling=UpSampling3D
def _func(inputs):
concatenate = []
layer = inputs
for n in range(depth):
for i in range(convs_per_depth):
layer = conv_blocks(filter_base*2**n,kernel,dropout=dropout,
batch_norm=batch_norm,name="down_level_%s_no_%s" % (n, i))(layer)
concatenate.append(layer)
layer = MaxPooling(pool_size=pool)(layer)
for i in range(convs_per_depth -1):
layer = conv_blocks(filter_base*2**depth,kernel,
dropout=dropout,batch_norm = batch_norm,name="middle_%s" % i)(layer)
layer = conv_blocks(filter_base*2**max(0,depth-1),kernel,dropout=dropout,
batch_norm=batch_norm,name="middle_%s" % convs_per_depth)(layer)
for n in reversed(range(depth)):
layer = Concatenate(axis=-1)([UpSampling(pool)(layer),concatenate[n]])
for i in range(convs_per_depth-1):
layer = conv_blocks(filter_base * 2 ** n, kernel, dropout=dropout,
batch_norm=batch_norm,name="up_level_%s_no_%s" % (n, i))(layer)
layer = conv_blocks(filter_base * 2 ** max(0,(n-1)), kernel, dropout=dropout,
batch_norm=batch_norm,name="up_level_%s_no_%s" % (n, convs_per_depth))(layer)
return layer
return _func
|
andraantariksa/PlasmaEngine
|
Source/Lightning/LightningCore/Traits.hpp
|
// MIT Licensed (see LICENSE.md).
#pragma once
#ifndef LIGHTNING_TRAITS_HPP
# define LIGHTNING_TRAITS_HPP
namespace Lightning
{
template <typename T>
class PlasmaSharedTemplate StaticDereference
{
public:
typedef T Type;
};
template <typename T>
class PlasmaSharedTemplate StaticDereference<T*>
{
public:
typedef T Type;
};
// Tells us whether a type is a primitive (built in type)
template <typename T>
class PlasmaSharedTemplate IsPrimitive
{
public:
static const bool Value = false;
typedef void FalseType;
};
// Mark all the basic types that we know of as primtiive
template <>
class PlasmaShared IsPrimitive<bool>
{
public:
static const bool Value = true;
};
template <>
class PlasmaShared IsPrimitive<float>
{
public:
static const bool Value = true;
};
template <>
class PlasmaShared IsPrimitive<double>
{
public:
static const bool Value = true;
};
template <>
class PlasmaShared IsPrimitive<char>
{
public:
static const bool Value = true;
};
template <>
class PlasmaShared IsPrimitive<signed char>
{
public:
static const bool Value = true;
};
template <>
class PlasmaShared IsPrimitive<unsigned char>
{
public:
static const bool Value = true;
};
template <>
class PlasmaShared IsPrimitive<signed short>
{
public:
static const bool Value = true;
};
template <>
class PlasmaShared IsPrimitive<unsigned short>
{
public:
static const bool Value = true;
};
template <>
class PlasmaShared IsPrimitive<signed int>
{
public:
static const bool Value = true;
};
template <>
class PlasmaShared IsPrimitive<unsigned int>
{
public:
static const bool Value = true;
};
template <>
class PlasmaShared IsPrimitive<signed long>
{
public:
static const bool Value = true;
};
template <>
class PlasmaShared IsPrimitive<unsigned long>
{
public:
static const bool Value = true;
};
template <>
class PlasmaShared IsPrimitive<signed long long>
{
public:
static const bool Value = true;
};
template <>
class PlasmaShared IsPrimitive<unsigned long long>
{
public:
static const bool Value = true;
};
} // namespace Lightning
#endif
|
kchanlee/tencentcloud-sdk-nodejs
|
tencentcloud/bmlb/v20180625/models.js
|
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. 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 AbstractModel = require("../../common/abstract_model");
/**
* SetTrafficMirrorHealthSwitch请求参数结构体
* @class
*/
class SetTrafficMirrorHealthSwitchRequest extends AbstractModel {
constructor(){
super();
/**
* 流量镜像实例ID。
* @type {string || null}
*/
this.TrafficMirrorId = null;
/**
* 健康检查开关,0:关闭,1:打开
* @type {number || null}
*/
this.HealthSwitch = null;
/**
* 健康检查判断健康的次数,最小值2,最大值10。
* @type {number || null}
*/
this.HealthNum = null;
/**
* 健康检查判断不健康的次数,最小值2,最大值10。
* @type {number || null}
*/
this.UnhealthNum = null;
/**
* 健康检查间隔,单位:秒,最小值5,最大值300。
* @type {number || null}
*/
this.IntervalTime = null;
/**
* 检查的域名配置。
* @type {string || null}
*/
this.HttpCheckDomain = null;
/**
* 检查的路径配置。
* @type {string || null}
*/
this.HttpCheckPath = null;
/**
* 健康检查中认为健康的HTTP返回码的组合。可选值为1~5的集合,1表示HTTP返回码为1xx认为健康。2表示HTTP返回码为2xx认为健康。3表示HTTP返回码为3xx认为健康。4表示HTTP返回码为4xx认为健康。5表示HTTP返回码为5xx认为健康。
* @type {Array.<number> || null}
*/
this.HttpCodes = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TrafficMirrorId = 'TrafficMirrorId' in params ? params.TrafficMirrorId : null;
this.HealthSwitch = 'HealthSwitch' in params ? params.HealthSwitch : null;
this.HealthNum = 'HealthNum' in params ? params.HealthNum : null;
this.UnhealthNum = 'UnhealthNum' in params ? params.UnhealthNum : null;
this.IntervalTime = 'IntervalTime' in params ? params.IntervalTime : null;
this.HttpCheckDomain = 'HttpCheckDomain' in params ? params.HttpCheckDomain : null;
this.HttpCheckPath = 'HttpCheckPath' in params ? params.HttpCheckPath : null;
this.HttpCodes = 'HttpCodes' in params ? params.HttpCodes : null;
}
}
/**
* SetTrafficMirrorAlias返回参数结构体
* @class
*/
class SetTrafficMirrorAliasResponse extends AbstractModel {
constructor(){
super();
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* DeleteL7Rules请求参数结构体
* @class
*/
class DeleteL7RulesRequest extends AbstractModel {
constructor(){
super();
/**
* 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。
* @type {string || null}
*/
this.LoadBalancerId = null;
/**
* 七层监听器实例ID,可通过接口DescribeL7Listeners查询。
* @type {string || null}
*/
this.ListenerId = null;
/**
* 转发域名实例ID,可通过接口DescribeL7Rules查询。
* @type {string || null}
*/
this.DomainId = null;
/**
* 转发路径实例ID列表,可通过接口DescribeL7Rules查询。
* @type {Array.<string> || null}
*/
this.LocationIds = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
this.ListenerId = 'ListenerId' in params ? params.ListenerId : null;
this.DomainId = 'DomainId' in params ? params.DomainId : null;
this.LocationIds = 'LocationIds' in params ? params.LocationIds : null;
}
}
/**
* DeleteTrafficMirror返回参数结构体
* @class
*/
class DeleteTrafficMirrorResponse extends AbstractModel {
constructor(){
super();
/**
* 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。
* @type {string || null}
*/
this.TaskId = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TaskId = 'TaskId' in params ? params.TaskId : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* ModifyL7BackendPort返回参数结构体
* @class
*/
class ModifyL7BackendPortResponse extends AbstractModel {
constructor(){
super();
/**
* 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。
* @type {string || null}
*/
this.TaskId = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TaskId = 'TaskId' in params ? params.TaskId : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* ModifyL4BackendProbePort返回参数结构体
* @class
*/
class ModifyL4BackendProbePortResponse extends AbstractModel {
constructor(){
super();
/**
* 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。
* @type {string || null}
*/
this.TaskId = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TaskId = 'TaskId' in params ? params.TaskId : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* 待与流量镜像绑定的接收机信息。
* @class
*/
class BindTrafficMirrorReceiver extends AbstractModel {
constructor(){
super();
/**
* 待绑定的主机端口,可选值1~65535。
* @type {number || null}
*/
this.Port = null;
/**
* 待绑定的主机实例ID。
* @type {string || null}
*/
this.InstanceId = null;
/**
* 待绑定的主机权重,可选值0~100。
* @type {number || null}
*/
this.Weight = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.Port = 'Port' in params ? params.Port : null;
this.InstanceId = 'InstanceId' in params ? params.InstanceId : null;
this.Weight = 'Weight' in params ? params.Weight : null;
}
}
/**
* ModifyL4BackendPort返回参数结构体
* @class
*/
class ModifyL4BackendPortResponse extends AbstractModel {
constructor(){
super();
/**
* 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果
* @type {string || null}
*/
this.TaskId = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TaskId = 'TaskId' in params ? params.TaskId : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* ModifyL7Locations返回参数结构体
* @class
*/
class ModifyL7LocationsResponse extends AbstractModel {
constructor(){
super();
/**
* 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。
* @type {string || null}
*/
this.TaskId = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TaskId = 'TaskId' in params ? params.TaskId : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* DescribeTrafficMirrorReceiverHealthStatus请求参数结构体
* @class
*/
class DescribeTrafficMirrorReceiverHealthStatusRequest extends AbstractModel {
constructor(){
super();
/**
* 查询所在的流量镜像ID。
* @type {string || null}
*/
this.TrafficMirrorId = null;
/**
* 流量镜像接收机实例ID和端口数组。
* @type {Array.<DescribeTrafficMirrorReceiver> || null}
*/
this.ReceiverSet = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TrafficMirrorId = 'TrafficMirrorId' in params ? params.TrafficMirrorId : null;
if (params.ReceiverSet) {
this.ReceiverSet = new Array();
for (let z in params.ReceiverSet) {
let obj = new DescribeTrafficMirrorReceiver();
obj.deserialize(params.ReceiverSet[z]);
this.ReceiverSet.push(obj);
}
}
}
}
/**
* 待与四层监听器解绑的物理机主机、虚拟机或半托管主机信息。
* @class
*/
class UnbindL4Backend extends AbstractModel {
constructor(){
super();
/**
* 待解绑的主机端口,可选值1~65535。
* @type {number || null}
*/
this.Port = null;
/**
* 黑石物理机主机ID、虚拟机IP或者是半托管主机ID。
* @type {string || null}
*/
this.InstanceId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.Port = 'Port' in params ? params.Port : null;
this.InstanceId = 'InstanceId' in params ? params.InstanceId : null;
}
}
/**
* ModifyL4Listener返回参数结构体
* @class
*/
class ModifyL4ListenerResponse extends AbstractModel {
constructor(){
super();
/**
* 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。
* @type {string || null}
*/
this.TaskId = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TaskId = 'TaskId' in params ? params.TaskId : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* 获取设备绑定信息时返回的四层监听器信息。
* @class
*/
class DevicesBindInfoL4Listener extends AbstractModel {
constructor(){
super();
/**
* 七层监听器实例ID。
* @type {string || null}
*/
this.ListenerId = null;
/**
* 七层监听器协议类型,可选值:http,https。
* @type {string || null}
*/
this.Protocol = null;
/**
* 七层监听器的监听端口。
* @type {number || null}
*/
this.LoadBalancerPort = null;
/**
* 该转发路径所绑定的主机列表。
* @type {Array.<DevicesBindInfoBackend> || null}
*/
this.BackendSet = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.ListenerId = 'ListenerId' in params ? params.ListenerId : null;
this.Protocol = 'Protocol' in params ? params.Protocol : null;
this.LoadBalancerPort = 'LoadBalancerPort' in params ? params.LoadBalancerPort : null;
if (params.BackendSet) {
this.BackendSet = new Array();
for (let z in params.BackendSet) {
let obj = new DevicesBindInfoBackend();
obj.deserialize(params.BackendSet[z]);
this.BackendSet.push(obj);
}
}
}
}
/**
* DescribeL4ListenerInfo请求参数结构体
* @class
*/
class DescribeL4ListenerInfoRequest extends AbstractModel {
constructor(){
super();
/**
* 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。
* @type {string || null}
*/
this.LoadBalancerId = null;
/**
* 查找的键值,可用于模糊查找该名称的监听器。
* @type {string || null}
*/
this.SearchKey = null;
/**
* 主机ID或虚机IP列表,可用于获取绑定了该主机的监听器。
* @type {Array.<string> || null}
*/
this.InstanceIds = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
this.SearchKey = 'SearchKey' in params ? params.SearchKey : null;
this.InstanceIds = 'InstanceIds' in params ? params.InstanceIds : null;
}
}
/**
* 查询绑定了某主机的四层监听器时返回的四层监听器信息。
* @class
*/
class L4ListenerInfo extends AbstractModel {
constructor(){
super();
/**
* 监听器ID。
* @type {string || null}
*/
this.ListenerId = null;
/**
* 用户自定义的监听器名称。
* @type {string || null}
*/
this.ListenerName = null;
/**
* 负载均衡实例监听器协议类型,可选值tcp,udp。
* @type {string || null}
*/
this.Protocol = null;
/**
* 负载均衡监听器的监听接口,可选值1~65535。
* @type {number || null}
*/
this.LoadBalancerPort = null;
/**
* 用于计费模式为固定带宽计费,指定监听器最大带宽值,可选值:0-1000,单位:Mbps。
* @type {number || null}
*/
this.Bandwidth = null;
/**
* 监听器的类别:L4Listener(四层监听器),L7Listener(七层监听器)。
* @type {string || null}
*/
this.ListenerType = null;
/**
* 会话保持时间。单位:秒
* @type {number || null}
*/
this.SessionExpire = null;
/**
* 是否开启了检查:1(开启)、0(关闭)。
* @type {number || null}
*/
this.HealthSwitch = null;
/**
* 响应超时时间,单位:秒。
* @type {number || null}
*/
this.TimeOut = null;
/**
* 检查间隔,单位:秒。
* @type {number || null}
*/
this.IntervalTime = null;
/**
* 负载均衡监听器健康阈值,默认值:3,表示当连续探测三次健康则表示该转发正常,可选值:2-10,单位:次。
* @type {number || null}
*/
this.HealthNum = null;
/**
* 负载均衡监听器不健康阈值,默认值:3,表示当连续探测三次不健康则表示该转发不正常,可选值:2-10,单位:次。
* @type {number || null}
*/
this.UnhealthNum = null;
/**
* 监听器当前状态(0代表创建中,1代表正常运行,2代表创建失败,3代表删除中,4代表删除失败)。
* @type {number || null}
*/
this.Status = null;
/**
* 创建时间戳。
* @type {string || null}
*/
this.AddTimestamp = null;
/**
* 是否开启自定义健康检查:1(开启)、0(关闭)。默认值0,表示关闭。(该字段在健康检查开启的情况下才生效)
* @type {number || null}
*/
this.CustomHealthSwitch = null;
/**
* 自定义健康探测内容类型,可选值:text(文本)、hexadecimal(十六进制)。
* @type {string || null}
*/
this.InputType = null;
/**
* 探测内容类型为文本方式时,针对请求文本中换行替换方式。可选值:1(替换为LF)、2(替换为CR)、3(替换为LF+CR)。
* @type {number || null}
*/
this.LineSeparatorType = null;
/**
* 自定义探测请求内容。
* @type {string || null}
*/
this.HealthRequest = null;
/**
* 自定义探测返回内容。
* @type {string || null}
*/
this.HealthResponse = null;
/**
* 是否开启toa:1(开启)、0(关闭)。
* @type {number || null}
*/
this.ToaFlag = null;
/**
* 转发后端服务器调度类型。
* @type {string || null}
*/
this.BalanceMode = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.ListenerId = 'ListenerId' in params ? params.ListenerId : null;
this.ListenerName = 'ListenerName' in params ? params.ListenerName : null;
this.Protocol = 'Protocol' in params ? params.Protocol : null;
this.LoadBalancerPort = 'LoadBalancerPort' in params ? params.LoadBalancerPort : null;
this.Bandwidth = 'Bandwidth' in params ? params.Bandwidth : null;
this.ListenerType = 'ListenerType' in params ? params.ListenerType : null;
this.SessionExpire = 'SessionExpire' in params ? params.SessionExpire : null;
this.HealthSwitch = 'HealthSwitch' in params ? params.HealthSwitch : null;
this.TimeOut = 'TimeOut' in params ? params.TimeOut : null;
this.IntervalTime = 'IntervalTime' in params ? params.IntervalTime : null;
this.HealthNum = 'HealthNum' in params ? params.HealthNum : null;
this.UnhealthNum = 'UnhealthNum' in params ? params.UnhealthNum : null;
this.Status = 'Status' in params ? params.Status : null;
this.AddTimestamp = 'AddTimestamp' in params ? params.AddTimestamp : null;
this.CustomHealthSwitch = 'CustomHealthSwitch' in params ? params.CustomHealthSwitch : null;
this.InputType = 'InputType' in params ? params.InputType : null;
this.LineSeparatorType = 'LineSeparatorType' in params ? params.LineSeparatorType : null;
this.HealthRequest = 'HealthRequest' in params ? params.HealthRequest : null;
this.HealthResponse = 'HealthResponse' in params ? params.HealthResponse : null;
this.ToaFlag = 'ToaFlag' in params ? params.ToaFlag : null;
this.BalanceMode = 'BalanceMode' in params ? params.BalanceMode : null;
}
}
/**
* DescribeL7Rules请求参数结构体
* @class
*/
class DescribeL7RulesRequest extends AbstractModel {
constructor(){
super();
/**
* 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。
* @type {string || null}
*/
this.LoadBalancerId = null;
/**
* 七层监听器ID,可通过接口DescribeL7Listeners查询。
* @type {string || null}
*/
this.ListenerId = null;
/**
* 转发域名ID列表,可通过接口DescribeL7Rules查询。
* @type {Array.<string> || null}
*/
this.DomainIds = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
this.ListenerId = 'ListenerId' in params ? params.ListenerId : null;
this.DomainIds = 'DomainIds' in params ? params.DomainIds : null;
}
}
/**
* UnbindL7Backends返回参数结构体
* @class
*/
class UnbindL7BackendsResponse extends AbstractModel {
constructor(){
super();
/**
* 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。
* @type {string || null}
*/
this.TaskId = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TaskId = 'TaskId' in params ? params.TaskId : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* ModifyL4BackendWeight返回参数结构体
* @class
*/
class ModifyL4BackendWeightResponse extends AbstractModel {
constructor(){
super();
/**
* 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。
* @type {string || null}
*/
this.TaskId = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TaskId = 'TaskId' in params ? params.TaskId : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* DeleteL7Domains返回参数结构体
* @class
*/
class DeleteL7DomainsResponse extends AbstractModel {
constructor(){
super();
/**
* 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。
* @type {string || null}
*/
this.TaskId = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TaskId = 'TaskId' in params ? params.TaskId : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* 获取设备绑定信息时返回的所绑定的主机信息。
* @class
*/
class DevicesBindInfoBackend extends AbstractModel {
constructor(){
super();
/**
* 黑石物理机的主机ID、托管主机ID或虚拟机IP。
* @type {string || null}
*/
this.InstanceId = null;
/**
* 主机端口。
* @type {number || null}
*/
this.Port = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.InstanceId = 'InstanceId' in params ? params.InstanceId : null;
this.Port = 'Port' in params ? params.Port : null;
}
}
/**
* UnbindL4Backends请求参数结构体
* @class
*/
class UnbindL4BackendsRequest extends AbstractModel {
constructor(){
super();
/**
* 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。
* @type {string || null}
*/
this.LoadBalancerId = null;
/**
* 负载均衡四层监听器ID,可通过接口DescribeL4Listeners查询。
* @type {string || null}
*/
this.ListenerId = null;
/**
* 待解绑的主机信息。可以绑定多个主机端口。目前一个四层监听器下面最多允许绑定255个主机端口。
* @type {Array.<UnbindL4Backend> || null}
*/
this.BackendSet = null;
/**
* 绑定类型。0:物理机 1:虚拟机 2:半托管机器
* @type {number || null}
*/
this.BindType = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
this.ListenerId = 'ListenerId' in params ? params.ListenerId : null;
if (params.BackendSet) {
this.BackendSet = new Array();
for (let z in params.BackendSet) {
let obj = new UnbindL4Backend();
obj.deserialize(params.BackendSet[z]);
this.BackendSet.push(obj);
}
}
this.BindType = 'BindType' in params ? params.BindType : null;
}
}
/**
* DescribeL7Listeners请求参数结构体
* @class
*/
class DescribeL7ListenersRequest extends AbstractModel {
constructor(){
super();
/**
* 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。
* @type {string || null}
*/
this.LoadBalancerId = null;
/**
* 七层监听器实例ID列表,可通过接口DescribeL7Listeners查询。
* @type {Array.<string> || null}
*/
this.ListenerIds = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
this.ListenerIds = 'ListenerIds' in params ? params.ListenerIds : null;
}
}
/**
* DescribeTrafficMirrorListeners请求参数结构体
* @class
*/
class DescribeTrafficMirrorListenersRequest extends AbstractModel {
constructor(){
super();
/**
* 流量镜像实例ID。
* @type {string || null}
*/
this.TrafficMirrorId = null;
/**
* 分页的偏移量,也即从第几条记录开始查询
* @type {number || null}
*/
this.Offset = null;
/**
* 单次查询返回的条目数,默认值:500。
* @type {number || null}
*/
this.Limit = null;
/**
* 待搜索的负载均衡Id。
* @type {Array.<string> || null}
*/
this.SearchLoadBalancerIds = null;
/**
* 待搜索的负载均衡名称。
* @type {Array.<string> || null}
*/
this.SearchLoadBalancerNames = null;
/**
* 待搜索的Vip。
* @type {Array.<string> || null}
*/
this.SearchVips = null;
/**
* 待搜索的监听器ID。
* @type {Array.<string> || null}
*/
this.SearchListenerIds = null;
/**
* 待搜索的监听器名称。
* @type {Array.<string> || null}
*/
this.SearchListenerNames = null;
/**
* 待搜索的协议名称。
* @type {Array.<string> || null}
*/
this.SearchProtocols = null;
/**
* 待搜索的端口。
* @type {Array.<number> || null}
*/
this.SearchLoadBalancerPorts = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TrafficMirrorId = 'TrafficMirrorId' in params ? params.TrafficMirrorId : null;
this.Offset = 'Offset' in params ? params.Offset : null;
this.Limit = 'Limit' in params ? params.Limit : null;
this.SearchLoadBalancerIds = 'SearchLoadBalancerIds' in params ? params.SearchLoadBalancerIds : null;
this.SearchLoadBalancerNames = 'SearchLoadBalancerNames' in params ? params.SearchLoadBalancerNames : null;
this.SearchVips = 'SearchVips' in params ? params.SearchVips : null;
this.SearchListenerIds = 'SearchListenerIds' in params ? params.SearchListenerIds : null;
this.SearchListenerNames = 'SearchListenerNames' in params ? params.SearchListenerNames : null;
this.SearchProtocols = 'SearchProtocols' in params ? params.SearchProtocols : null;
this.SearchLoadBalancerPorts = 'SearchLoadBalancerPorts' in params ? params.SearchLoadBalancerPorts : null;
}
}
/**
* 待与七层监听器转发规则绑定的物理机主机、虚拟机或半托管主机信息。目前一个七层转发路径下面最多允许绑定255个主机端口。
* @class
*/
class BindL7Backend extends AbstractModel {
constructor(){
super();
/**
* 待绑定的主机端口,可选值1~65535。
* @type {number || null}
*/
this.Port = null;
/**
* 黑石物理机主机ID、虚拟机IP或者是半托管主机ID。
* @type {string || null}
*/
this.InstanceId = null;
/**
* 待绑定的主机权重,可选值0~100。
* @type {number || null}
*/
this.Weight = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.Port = 'Port' in params ? params.Port : null;
this.InstanceId = 'InstanceId' in params ? params.InstanceId : null;
this.Weight = 'Weight' in params ? params.Weight : null;
}
}
/**
* ModifyL7Listener返回参数结构体
* @class
*/
class ModifyL7ListenerResponse extends AbstractModel {
constructor(){
super();
/**
* 任务ID。该接口为异步任务,可根据本参数调用[DescribeLoadBalancerTaskResult](/document/product/386/9308)接口来查询任务操作结果
* @type {string || null}
*/
this.TaskId = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TaskId = 'TaskId' in params ? params.TaskId : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* DescribeLoadBalancerTaskResult请求参数结构体
* @class
*/
class DescribeLoadBalancerTaskResultRequest extends AbstractModel {
constructor(){
super();
/**
* 任务ID。由具体的异步操作接口提供。
* @type {string || null}
*/
this.TaskId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TaskId = 'TaskId' in params ? params.TaskId : null;
}
}
/**
* DescribeL7Rules返回参数结构体
* @class
*/
class DescribeL7RulesResponse extends AbstractModel {
constructor(){
super();
/**
* 返回的转发规则列表。
* @type {Array.<L7Rule> || null}
*/
this.RuleSet = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
if (params.RuleSet) {
this.RuleSet = new Array();
for (let z in params.RuleSet) {
let obj = new L7Rule();
obj.deserialize(params.RuleSet[z]);
this.RuleSet.push(obj);
}
}
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* CreateTrafficMirror返回参数结构体
* @class
*/
class CreateTrafficMirrorResponse extends AbstractModel {
constructor(){
super();
/**
* 流量镜像实例ID
* @type {string || null}
*/
this.TrafficMirrorId = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TrafficMirrorId = 'TrafficMirrorId' in params ? params.TrafficMirrorId : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* DescribeDevicesBindInfo请求参数结构体
* @class
*/
class DescribeDevicesBindInfoRequest extends AbstractModel {
constructor(){
super();
/**
* 黑石私有网络唯一ID。
* @type {string || null}
*/
this.VpcId = null;
/**
* 主机ID或虚机IP列表,可用于获取绑定了该主机的负载均衡列表。
* @type {Array.<string> || null}
*/
this.InstanceIds = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.VpcId = 'VpcId' in params ? params.VpcId : null;
this.InstanceIds = 'InstanceIds' in params ? params.InstanceIds : null;
}
}
/**
* BindL4Backends返回参数结构体
* @class
*/
class BindL4BackendsResponse extends AbstractModel {
constructor(){
super();
/**
* 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。
* @type {string || null}
*/
this.TaskId = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TaskId = 'TaskId' in params ? params.TaskId : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* 获取流量镜像的监听器列表信息时返回的与流量镜像绑定的监听器信息。
* @class
*/
class TrafficMirrorListener extends AbstractModel {
constructor(){
super();
/**
* 监听器ID。
* @type {string || null}
*/
this.ListenerId = null;
/**
* 监听器名称。
* @type {string || null}
*/
this.ListenerName = null;
/**
* 七层监听器协议类型,可选值:http,https。
* @type {string || null}
*/
this.Protocol = null;
/**
* 监听器的监听端口。
* @type {number || null}
*/
this.LoadBalancerPort = null;
/**
* 当前带宽。
* @type {number || null}
*/
this.Bandwidth = null;
/**
* 带宽上限。
* @type {number || null}
*/
this.MaxBandwidth = null;
/**
* 监听器类型。
* @type {string || null}
*/
this.ListenerType = null;
/**
* 认证方式:0(不认证,用于http),1(单向认证,用于https),2(双向认证,用于https)。
* @type {number || null}
*/
this.SslMode = null;
/**
* 服务端证书ID。
* @type {string || null}
*/
this.CertId = null;
/**
* 客户端证书ID。
* @type {string || null}
*/
this.CertCaId = null;
/**
* 添加时间。
* @type {string || null}
*/
this.AddTimestamp = null;
/**
* 负载均衡ID。
* @type {string || null}
*/
this.LoadBalancerId = null;
/**
* 私有网络名称。
* @type {string || null}
*/
this.VpcName = null;
/**
* 私有网络Cidr。
* @type {string || null}
*/
this.VpcCidrBlock = null;
/**
* 负载均衡的VIP。
* @type {Array.<string> || null}
*/
this.LoadBalancerVips = null;
/**
* 负载均衡名称。
* @type {string || null}
*/
this.LoadBalancerName = null;
/**
* 负载均衡的IPV6的VIP。
* @type {Array.<string> || null}
*/
this.LoadBalancerVipv6s = null;
/**
* 支持的IP协议类型。ipv4或者是ipv6。
* @type {string || null}
*/
this.IpProtocolType = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.ListenerId = 'ListenerId' in params ? params.ListenerId : null;
this.ListenerName = 'ListenerName' in params ? params.ListenerName : null;
this.Protocol = 'Protocol' in params ? params.Protocol : null;
this.LoadBalancerPort = 'LoadBalancerPort' in params ? params.LoadBalancerPort : null;
this.Bandwidth = 'Bandwidth' in params ? params.Bandwidth : null;
this.MaxBandwidth = 'MaxBandwidth' in params ? params.MaxBandwidth : null;
this.ListenerType = 'ListenerType' in params ? params.ListenerType : null;
this.SslMode = 'SslMode' in params ? params.SslMode : null;
this.CertId = 'CertId' in params ? params.CertId : null;
this.CertCaId = 'CertCaId' in params ? params.CertCaId : null;
this.AddTimestamp = 'AddTimestamp' in params ? params.AddTimestamp : null;
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
this.VpcName = 'VpcName' in params ? params.VpcName : null;
this.VpcCidrBlock = 'VpcCidrBlock' in params ? params.VpcCidrBlock : null;
this.LoadBalancerVips = 'LoadBalancerVips' in params ? params.LoadBalancerVips : null;
this.LoadBalancerName = 'LoadBalancerName' in params ? params.LoadBalancerName : null;
this.LoadBalancerVipv6s = 'LoadBalancerVipv6s' in params ? params.LoadBalancerVipv6s : null;
this.IpProtocolType = 'IpProtocolType' in params ? params.IpProtocolType : null;
}
}
/**
* DescribeL7ListenersEx返回参数结构体
* @class
*/
class DescribeL7ListenersExResponse extends AbstractModel {
constructor(){
super();
/**
* 此指定VPC中负载均衡的总数。
* @type {number || null}
*/
this.TotalCount = null;
/**
* 符合条件的监听器。
* @type {Array.<L7ExListener> || null}
*/
this.ListenerSet = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TotalCount = 'TotalCount' in params ? params.TotalCount : null;
if (params.ListenerSet) {
this.ListenerSet = new Array();
for (let z in params.ListenerSet) {
let obj = new L7ExListener();
obj.deserialize(params.ListenerSet[z]);
this.ListenerSet.push(obj);
}
}
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* 待与七层监听器转发规则解绑的物理机主机、虚拟机或半托管主机信息。
* @class
*/
class UnbindL7Backend extends AbstractModel {
constructor(){
super();
/**
* 待解绑的主机端口,可选值1~65535。
* @type {number || null}
*/
this.Port = null;
/**
* 黑石物理机主机ID、虚拟机IP或者是半托管主机ID。
* @type {string || null}
*/
this.InstanceId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.Port = 'Port' in params ? params.Port : null;
this.InstanceId = 'InstanceId' in params ? params.InstanceId : null;
}
}
/**
* 获取与流量镜像绑定的接收机信息时返回的接收机信息。
* @class
*/
class TrafficMirrorReceiver extends AbstractModel {
constructor(){
super();
/**
* 接收机实例ID。
* @type {string || null}
*/
this.InstanceId = null;
/**
* 接收机接收端口。
* @type {number || null}
*/
this.Port = null;
/**
* 接收机权重。
* @type {number || null}
*/
this.Weight = null;
/**
* 流量镜像ID。
* @type {string || null}
*/
this.TrafficMirrorId = null;
/**
* 接收机别名。
* @type {string || null}
*/
this.Alias = null;
/**
* 接收机内网IP地址。
* @type {string || null}
*/
this.LanIp = null;
/**
* 接收机所在的子网的ID。
* @type {string || null}
*/
this.SubnetId = null;
/**
* 接收机所在的子网的名称。
* @type {string || null}
*/
this.SubnetName = null;
/**
* 接收机所在的子网的Cidr。
* @type {string || null}
*/
this.SubnetCidrBlock = null;
/**
* 接收机所在的私有网络的ID。
* @type {string || null}
*/
this.VpcId = null;
/**
* 接收机所在的私有网络的名称。
* @type {string || null}
*/
this.VpcName = null;
/**
* 接收机所在的私有网络的Cidr。
* @type {string || null}
*/
this.VpcCidrBlock = null;
/**
* 接收机的健康状态。
* @type {string || null}
*/
this.HealthStatus = null;
/**
* 接收机的可以执行的操作集合。
* @type {Array.<string> || null}
*/
this.Operates = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.InstanceId = 'InstanceId' in params ? params.InstanceId : null;
this.Port = 'Port' in params ? params.Port : null;
this.Weight = 'Weight' in params ? params.Weight : null;
this.TrafficMirrorId = 'TrafficMirrorId' in params ? params.TrafficMirrorId : null;
this.Alias = 'Alias' in params ? params.Alias : null;
this.LanIp = 'LanIp' in params ? params.LanIp : null;
this.SubnetId = 'SubnetId' in params ? params.SubnetId : null;
this.SubnetName = 'SubnetName' in params ? params.SubnetName : null;
this.SubnetCidrBlock = 'SubnetCidrBlock' in params ? params.SubnetCidrBlock : null;
this.VpcId = 'VpcId' in params ? params.VpcId : null;
this.VpcName = 'VpcName' in params ? params.VpcName : null;
this.VpcCidrBlock = 'VpcCidrBlock' in params ? params.VpcCidrBlock : null;
this.HealthStatus = 'HealthStatus' in params ? params.HealthStatus : null;
this.Operates = 'Operates' in params ? params.Operates : null;
}
}
/**
* 流量镜像健康检查返回的接收机的端口及状态信息。
* @class
*/
class TrafficMirrorPortStatus extends AbstractModel {
constructor(){
super();
/**
* 接收机端口。
* @type {number || null}
*/
this.Port = null;
/**
* 状态。
* @type {string || null}
*/
this.Status = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.Port = 'Port' in params ? params.Port : null;
this.Status = 'Status' in params ? params.Status : null;
}
}
/**
* UploadCert返回参数结构体
* @class
*/
class UploadCertResponse extends AbstractModel {
constructor(){
super();
/**
* 新建的证书ID。
* @type {string || null}
*/
this.CertId = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.CertId = 'CertId' in params ? params.CertId : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* DescribeTrafficMirrorReceivers返回参数结构体
* @class
*/
class DescribeTrafficMirrorReceiversResponse extends AbstractModel {
constructor(){
super();
/**
* 接收机列表,具体结构描述如data结构所示。
* @type {Array.<TrafficMirrorReceiver> || null}
*/
this.ReceiverSet = null;
/**
* 接收机总数。
* @type {number || null}
*/
this.TotalCount = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
if (params.ReceiverSet) {
this.ReceiverSet = new Array();
for (let z in params.ReceiverSet) {
let obj = new TrafficMirrorReceiver();
obj.deserialize(params.ReceiverSet[z]);
this.ReceiverSet.push(obj);
}
}
this.TotalCount = 'TotalCount' in params ? params.TotalCount : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* DeleteListeners请求参数结构体
* @class
*/
class DeleteListenersRequest extends AbstractModel {
constructor(){
super();
/**
* 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。
* @type {string || null}
*/
this.LoadBalancerId = null;
/**
* 待删除的负载均衡四层和七层监听器ID列表,可通过接口DescribeL4Listeners和DescribeL7Listeners查询。目前同时只能删除一种类型的监听器,并且删除七层监听器的数量上限为一个。
* @type {Array.<string> || null}
*/
this.ListenerIds = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
this.ListenerIds = 'ListenerIds' in params ? params.ListenerIds : null;
}
}
/**
* ModifyL4BackendProbePort请求参数结构体
* @class
*/
class ModifyL4BackendProbePortRequest extends AbstractModel {
constructor(){
super();
/**
* 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。
* @type {string || null}
*/
this.LoadBalancerId = null;
/**
* 负载均衡四层监听器ID,可通过接口DescribeL7Listeners查询。
* @type {string || null}
*/
this.ListenerId = null;
/**
* 黑石物理机主机ID、虚拟机IP或者是半托管主机ID。
* @type {string || null}
*/
this.InstanceId = null;
/**
* 已绑定的主机端口。
* @type {number || null}
*/
this.Port = null;
/**
* 新的探测端口,可选值1~65535。
* @type {number || null}
*/
this.ProbePort = null;
/**
* 绑定类型。0:物理机 1:虚拟机IP 2:半托管机器
* @type {number || null}
*/
this.BindType = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
this.ListenerId = 'ListenerId' in params ? params.ListenerId : null;
this.InstanceId = 'InstanceId' in params ? params.InstanceId : null;
this.Port = 'Port' in params ? params.Port : null;
this.ProbePort = 'ProbePort' in params ? params.ProbePort : null;
this.BindType = 'BindType' in params ? params.BindType : null;
}
}
/**
* DescribeTrafficMirrors请求参数结构体
* @class
*/
class DescribeTrafficMirrorsRequest extends AbstractModel {
constructor(){
super();
/**
* 流量镜像实例ID的数组,支持批量查询
* @type {Array.<string> || null}
*/
this.TrafficMirrorIds = null;
/**
* 流量镜像实例别名数组。
* @type {Array.<string> || null}
*/
this.Aliases = null;
/**
* 流量镜像实例所属的私有网络ID数组,形如:vpc-xxx。
* @type {Array.<string> || null}
*/
this.VpcIds = null;
/**
* 分页的偏移量,也即从第几条记录开始查询
* @type {number || null}
*/
this.Offset = null;
/**
* 单次查询返回的条目数,默认值:500。
* @type {number || null}
*/
this.Limit = null;
/**
* 排序字段。trafficMirrorId或者createTime。
* @type {string || null}
*/
this.OrderField = null;
/**
* 排序方式,取值:0:增序(默认),1:降序
* @type {number || null}
*/
this.Order = null;
/**
* 模糊匹配trafficMirrorId或者alias字段。
* @type {string || null}
*/
this.SearchKey = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TrafficMirrorIds = 'TrafficMirrorIds' in params ? params.TrafficMirrorIds : null;
this.Aliases = 'Aliases' in params ? params.Aliases : null;
this.VpcIds = 'VpcIds' in params ? params.VpcIds : null;
this.Offset = 'Offset' in params ? params.Offset : null;
this.Limit = 'Limit' in params ? params.Limit : null;
this.OrderField = 'OrderField' in params ? params.OrderField : null;
this.Order = 'Order' in params ? params.Order : null;
this.SearchKey = 'SearchKey' in params ? params.SearchKey : null;
}
}
/**
* UploadCert请求参数结构体
* @class
*/
class UploadCertRequest extends AbstractModel {
constructor(){
super();
/**
* 证书类型,可选值:CA,SVR。
* @type {string || null}
*/
this.CertType = null;
/**
* 证书内容。
* @type {string || null}
*/
this.Cert = null;
/**
* 证书别名。
* @type {string || null}
*/
this.Alias = null;
/**
* 私钥内容,证书类型为SVR时不需要传递。
* @type {string || null}
*/
this.Key = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.CertType = 'CertType' in params ? params.CertType : null;
this.Cert = 'Cert' in params ? params.Cert : null;
this.Alias = 'Alias' in params ? params.Alias : null;
this.Key = 'Key' in params ? params.Key : null;
}
}
/**
* DescribeL4ListenerInfo返回参数结构体
* @class
*/
class DescribeL4ListenerInfoResponse extends AbstractModel {
constructor(){
super();
/**
* 返回的四层监听器列表。
* @type {Array.<L4ListenerInfo> || null}
*/
this.ListenerSet = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
if (params.ListenerSet) {
this.ListenerSet = new Array();
for (let z in params.ListenerSet) {
let obj = new L4ListenerInfo();
obj.deserialize(params.ListenerSet[z]);
this.ListenerSet.push(obj);
}
}
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* BindTrafficMirrorListeners请求参数结构体
* @class
*/
class BindTrafficMirrorListenersRequest extends AbstractModel {
constructor(){
super();
/**
* 流量镜像实例ID。
* @type {string || null}
*/
this.TrafficMirrorId = null;
/**
* 七层监听器实例ID数组,可通过接口DescribeL7Listeners查询。
* @type {Array.<string> || null}
*/
this.ListenerIds = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TrafficMirrorId = 'TrafficMirrorId' in params ? params.TrafficMirrorId : null;
this.ListenerIds = 'ListenerIds' in params ? params.ListenerIds : null;
}
}
/**
* ModifyL7BackendPort请求参数结构体
* @class
*/
class ModifyL7BackendPortRequest extends AbstractModel {
constructor(){
super();
/**
* 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。
* @type {string || null}
*/
this.LoadBalancerId = null;
/**
* 七层监听器实例ID,可通过接口DescribeL7Listeners查询。
* @type {string || null}
*/
this.ListenerId = null;
/**
* 转发域名实例ID,可通过接口DescribeL7Rules查询。
* @type {string || null}
*/
this.DomainId = null;
/**
* 转发路径实例ID,可通过接口DescribeL7Rules查询。
* @type {string || null}
*/
this.LocationId = null;
/**
* 黑石物理机主机ID、虚拟机IP或者是半托管主机ID。
* @type {string || null}
*/
this.InstanceId = null;
/**
* 已绑定的主机端口。
* @type {number || null}
*/
this.Port = null;
/**
* 新的主机端口,可选值1~65535。
* @type {number || null}
*/
this.NewPort = null;
/**
* 绑定类型。0:物理机 1:虚拟机 2:半托管机器
* @type {number || null}
*/
this.BindType = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
this.ListenerId = 'ListenerId' in params ? params.ListenerId : null;
this.DomainId = 'DomainId' in params ? params.DomainId : null;
this.LocationId = 'LocationId' in params ? params.LocationId : null;
this.InstanceId = 'InstanceId' in params ? params.InstanceId : null;
this.Port = 'Port' in params ? params.Port : null;
this.NewPort = 'NewPort' in params ? params.NewPort : null;
this.BindType = 'BindType' in params ? params.BindType : null;
}
}
/**
* ModifyL4BackendPort请求参数结构体
* @class
*/
class ModifyL4BackendPortRequest extends AbstractModel {
constructor(){
super();
/**
* 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。
* @type {string || null}
*/
this.LoadBalancerId = null;
/**
* 负载均衡四层监听器ID,可通过接口DescribeL4Listeners查询。
* @type {string || null}
*/
this.ListenerId = null;
/**
* 黑石物理机主机ID、虚拟机IP或者是半托管主机ID。
* @type {string || null}
*/
this.InstanceId = null;
/**
* 已绑定的主机端口。
* @type {number || null}
*/
this.Port = null;
/**
* 新的主机端口,可选值1~65535。
* @type {number || null}
*/
this.NewPort = null;
/**
* 绑定类型。0:物理机 1:虚拟机 2:半托管机器
* @type {number || null}
*/
this.BindType = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
this.ListenerId = 'ListenerId' in params ? params.ListenerId : null;
this.InstanceId = 'InstanceId' in params ? params.InstanceId : null;
this.Port = 'Port' in params ? params.Port : null;
this.NewPort = 'NewPort' in params ? params.NewPort : null;
this.BindType = 'BindType' in params ? params.BindType : null;
}
}
/**
* DescribeL4Listeners返回参数结构体
* @class
*/
class DescribeL4ListenersResponse extends AbstractModel {
constructor(){
super();
/**
* 监听器信息数组。
* @type {Array.<L4Listener> || null}
*/
this.ListenerSet = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
if (params.ListenerSet) {
this.ListenerSet = new Array();
for (let z in params.ListenerSet) {
let obj = new L4Listener();
obj.deserialize(params.ListenerSet[z]);
this.ListenerSet.push(obj);
}
}
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* ModifyL7Locations请求参数结构体
* @class
*/
class ModifyL7LocationsRequest extends AbstractModel {
constructor(){
super();
/**
* 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。
* @type {string || null}
*/
this.LoadBalancerId = null;
/**
* 七层监听器实例ID,可通过接口DescribeL7Listeners查询。
* @type {string || null}
*/
this.ListenerId = null;
/**
* 待更新的七层转发规则信息数组。
* @type {Array.<ModifyL7LocationRule> || null}
*/
this.RuleSet = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
this.ListenerId = 'ListenerId' in params ? params.ListenerId : null;
if (params.RuleSet) {
this.RuleSet = new Array();
for (let z in params.RuleSet) {
let obj = new ModifyL7LocationRule();
obj.deserialize(params.RuleSet[z]);
this.RuleSet.push(obj);
}
}
}
}
/**
* ModifyLoadBalancer返回参数结构体
* @class
*/
class ModifyLoadBalancerResponse extends AbstractModel {
constructor(){
super();
/**
* 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。
* @type {string || null}
*/
this.TaskId = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TaskId = 'TaskId' in params ? params.TaskId : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* CreateL4Listeners返回参数结构体
* @class
*/
class CreateL4ListenersResponse extends AbstractModel {
constructor(){
super();
/**
* 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果
* @type {string || null}
*/
this.TaskId = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TaskId = 'TaskId' in params ? params.TaskId : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* ModifyL7BackendWeight返回参数结构体
* @class
*/
class ModifyL7BackendWeightResponse extends AbstractModel {
constructor(){
super();
/**
* 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果
* @type {string || null}
*/
this.TaskId = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TaskId = 'TaskId' in params ? params.TaskId : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* DescribeTrafficMirrors返回参数结构体
* @class
*/
class DescribeTrafficMirrorsResponse extends AbstractModel {
constructor(){
super();
/**
* 流量镜像总数。
* @type {number || null}
*/
this.TotalCount = null;
/**
* 对象数组。数组元素为流量镜像信息,具体结构描述如list结构所示。
* @type {Array.<TrafficMirror> || null}
*/
this.TrafficMirrorSet = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TotalCount = 'TotalCount' in params ? params.TotalCount : null;
if (params.TrafficMirrorSet) {
this.TrafficMirrorSet = new Array();
for (let z in params.TrafficMirrorSet) {
let obj = new TrafficMirror();
obj.deserialize(params.TrafficMirrorSet[z]);
this.TrafficMirrorSet.push(obj);
}
}
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* DescribeL7Backends请求参数结构体
* @class
*/
class DescribeL7BackendsRequest extends AbstractModel {
constructor(){
super();
/**
* 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。
* @type {string || null}
*/
this.LoadBalancerId = null;
/**
* 七层监听器实例ID,可通过接口DescribeL7Listeners查询。
* @type {string || null}
*/
this.ListenerId = null;
/**
* 转发域名实例ID,可通过接口DescribeL7Rules查询。
* @type {string || null}
*/
this.DomainId = null;
/**
* 转发路径实例ID,可通过接口DescribeL7Rules查询。
* @type {string || null}
*/
this.LocationId = null;
/**
* 查询条件,传'all'则查询所有与规则绑定的主机信息。如果为all时,DomainId和LocationId参数没有意义不必传入,否则DomainId和LocationId参数必须传入。
* @type {string || null}
*/
this.QueryType = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
this.ListenerId = 'ListenerId' in params ? params.ListenerId : null;
this.DomainId = 'DomainId' in params ? params.DomainId : null;
this.LocationId = 'LocationId' in params ? params.LocationId : null;
this.QueryType = 'QueryType' in params ? params.QueryType : null;
}
}
/**
* 获取黑石负载均衡七层监听器时返回的七层监听器信息。
* @class
*/
class L7Listener extends AbstractModel {
constructor(){
super();
/**
* 七层监听器实例ID。
* @type {string || null}
*/
this.ListenerId = null;
/**
* 七层监听器名称。
* @type {string || null}
*/
this.ListenerName = null;
/**
* 七层监听器协议类型,可选值:http,https。
* @type {string || null}
*/
this.Protocol = null;
/**
* 七层监听器的监听端口。
* @type {number || null}
*/
this.LoadBalancerPort = null;
/**
* 计费模式为按固定带宽方式时监听器的限速值,单位:Mbps。
* @type {number || null}
*/
this.Bandwidth = null;
/**
* 监听器的类别:L4Listener(四层监听器),L7Listener(七层监听器)。
* @type {string || null}
*/
this.ListenerType = null;
/**
* 七层监听器的认证方式:0(不认证,用于http),1(单向认证,用于https),2(双向认证,用于https)。
* @type {number || null}
*/
this.SslMode = null;
/**
* 七层监听器关联的服务端证书ID。
* @type {string || null}
*/
this.CertId = null;
/**
* 七层监听器关联的客户端证书ID。
* @type {string || null}
*/
this.CertCaId = null;
/**
* 监听器当前状态(0代表创建中,1代表正常运行,2代表创建失败,3代表删除中,4代表删除失败)。
* @type {number || null}
*/
this.Status = null;
/**
* 创建时间戳。
* @type {string || null}
*/
this.AddTimestamp = null;
/**
* https转发类型。0:https。1:spdy。2:http2。3:spdy+http2。
* @type {number || null}
*/
this.ForwardProtocol = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.ListenerId = 'ListenerId' in params ? params.ListenerId : null;
this.ListenerName = 'ListenerName' in params ? params.ListenerName : null;
this.Protocol = 'Protocol' in params ? params.Protocol : null;
this.LoadBalancerPort = 'LoadBalancerPort' in params ? params.LoadBalancerPort : null;
this.Bandwidth = 'Bandwidth' in params ? params.Bandwidth : null;
this.ListenerType = 'ListenerType' in params ? params.ListenerType : null;
this.SslMode = 'SslMode' in params ? params.SslMode : null;
this.CertId = 'CertId' in params ? params.CertId : null;
this.CertCaId = 'CertCaId' in params ? params.CertCaId : null;
this.Status = 'Status' in params ? params.Status : null;
this.AddTimestamp = 'AddTimestamp' in params ? params.AddTimestamp : null;
this.ForwardProtocol = 'ForwardProtocol' in params ? params.ForwardProtocol : null;
}
}
/**
* CreateL7Rules请求参数结构体
* @class
*/
class CreateL7RulesRequest extends AbstractModel {
constructor(){
super();
/**
* 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。
* @type {string || null}
*/
this.LoadBalancerId = null;
/**
* 七层监听器实例ID,可通过接口DescribeL7Listeners查询。
* @type {string || null}
*/
this.ListenerId = null;
/**
* 七层转发规则信息数组,可以创建多个七层转发规则。目前一个七层监听器下面最多允许创建50个七层转发域名,而每一个转发域名下最多可以创建100个转发规则。目前只能单条创建,不能批量创建。
* @type {Array.<CreateL7Rule> || null}
*/
this.RuleSet = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
this.ListenerId = 'ListenerId' in params ? params.ListenerId : null;
if (params.RuleSet) {
this.RuleSet = new Array();
for (let z in params.RuleSet) {
let obj = new CreateL7Rule();
obj.deserialize(params.RuleSet[z]);
this.RuleSet.push(obj);
}
}
}
}
/**
* ModifyL7BackendWeight请求参数结构体
* @class
*/
class ModifyL7BackendWeightRequest extends AbstractModel {
constructor(){
super();
/**
* 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。
* @type {string || null}
*/
this.LoadBalancerId = null;
/**
* 七层监听器实例ID,可通过接口DescribeL7Listeners查询。
* @type {string || null}
*/
this.ListenerId = null;
/**
* 转发域名实例ID,可通过接口DescribeL7Rules查询。
* @type {string || null}
*/
this.DomainId = null;
/**
* 转发路径实例ID,可通过接口DescribeL7Rules查询。
* @type {string || null}
*/
this.LocationId = null;
/**
* 黑石物理机主机ID、虚拟机IP或者是半托管主机ID。
* @type {string || null}
*/
this.InstanceId = null;
/**
* 权重信息,可选值0~100。
* @type {number || null}
*/
this.Weight = null;
/**
* 已绑定的主机端口。
* @type {number || null}
*/
this.Port = null;
/**
* 绑定类型。0:物理机 1:虚拟机 2:半托管机器
* @type {number || null}
*/
this.BindType = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
this.ListenerId = 'ListenerId' in params ? params.ListenerId : null;
this.DomainId = 'DomainId' in params ? params.DomainId : null;
this.LocationId = 'LocationId' in params ? params.LocationId : null;
this.InstanceId = 'InstanceId' in params ? params.InstanceId : null;
this.Weight = 'Weight' in params ? params.Weight : null;
this.Port = 'Port' in params ? params.Port : null;
this.BindType = 'BindType' in params ? params.BindType : null;
}
}
/**
* CreateL4Listeners请求参数结构体
* @class
*/
class CreateL4ListenersRequest extends AbstractModel {
constructor(){
super();
/**
* 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。
* @type {string || null}
*/
this.LoadBalancerId = null;
/**
* 监听器信息数组,可以创建多个监听器。目前一个负载均衡下面最多允许创建50个监听器
* @type {Array.<CreateL4Listener> || null}
*/
this.ListenerSet = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
if (params.ListenerSet) {
this.ListenerSet = new Array();
for (let z in params.ListenerSet) {
let obj = new CreateL4Listener();
obj.deserialize(params.ListenerSet[z]);
this.ListenerSet.push(obj);
}
}
}
}
/**
* ReplaceCert请求参数结构体
* @class
*/
class ReplaceCertRequest extends AbstractModel {
constructor(){
super();
/**
* 要被替换的证书ID
* @type {string || null}
*/
this.OldCertId = null;
/**
* 证书内容
* @type {string || null}
*/
this.NewCert = null;
/**
* 证书名称
* @type {string || null}
*/
this.NewAlias = null;
/**
* 私钥内容,证书类型为SVR时不需要传递
* @type {string || null}
*/
this.NewKey = null;
/**
* 是否删除旧证书,0 表示不删除,1 表示删除
* @type {number || null}
*/
this.DeleteOld = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.OldCertId = 'OldCertId' in params ? params.OldCertId : null;
this.NewCert = 'NewCert' in params ? params.NewCert : null;
this.NewAlias = 'NewAlias' in params ? params.NewAlias : null;
this.NewKey = 'NewKey' in params ? params.NewKey : null;
this.DeleteOld = 'DeleteOld' in params ? params.DeleteOld : null;
}
}
/**
* BindL7Backends返回参数结构体
* @class
*/
class BindL7BackendsResponse extends AbstractModel {
constructor(){
super();
/**
* 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。
* @type {string || null}
*/
this.TaskId = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TaskId = 'TaskId' in params ? params.TaskId : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* 获取七层监听器转发规则时返回的转发规则。
* @class
*/
class L7Rule extends AbstractModel {
constructor(){
super();
/**
* 转发域名。
* @type {string || null}
*/
this.Domain = null;
/**
* 转发域名实例ID。
* @type {string || null}
*/
this.DomainId = null;
/**
* 转发路径当前状态(0代表创建中,1代表正常运行,2代表创建失败,3代表删除中,4代表删除失败)。
* @type {number || null}
*/
this.Status = null;
/**
* 创建时间戳。
* @type {string || null}
*/
this.AddTimestamp = null;
/**
* 该转发域名下面的转发路径列表。
* @type {Array.<L7RulesLocation> || null}
*/
this.LocationSet = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.Domain = 'Domain' in params ? params.Domain : null;
this.DomainId = 'DomainId' in params ? params.DomainId : null;
this.Status = 'Status' in params ? params.Status : null;
this.AddTimestamp = 'AddTimestamp' in params ? params.AddTimestamp : null;
if (params.LocationSet) {
this.LocationSet = new Array();
for (let z in params.LocationSet) {
let obj = new L7RulesLocation();
obj.deserialize(params.LocationSet[z]);
this.LocationSet.push(obj);
}
}
}
}
/**
* UnbindTrafficMirrorReceivers返回参数结构体
* @class
*/
class UnbindTrafficMirrorReceiversResponse extends AbstractModel {
constructor(){
super();
/**
* 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。
* @type {string || null}
*/
this.TaskId = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TaskId = 'TaskId' in params ? params.TaskId : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* DeleteL7Domains请求参数结构体
* @class
*/
class DeleteL7DomainsRequest extends AbstractModel {
constructor(){
super();
/**
* 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。
* @type {string || null}
*/
this.LoadBalancerId = null;
/**
* 七层监听器实例ID,可通过接口DescribeL7Listeners查询。
* @type {string || null}
*/
this.ListenerId = null;
/**
* 转发域名实例ID列表,可通过接口DescribeL7Rules查询。
* @type {Array.<string> || null}
*/
this.DomainIds = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
this.ListenerId = 'ListenerId' in params ? params.ListenerId : null;
this.DomainIds = 'DomainIds' in params ? params.DomainIds : null;
}
}
/**
* BindTrafficMirrorReceivers请求参数结构体
* @class
*/
class BindTrafficMirrorReceiversRequest extends AbstractModel {
constructor(){
super();
/**
* 流量镜像实例ID。
* @type {string || null}
*/
this.TrafficMirrorId = null;
/**
* 待绑定的黑石物理机信息数组。
* @type {Array.<BindTrafficMirrorReceiver> || null}
*/
this.ReceiverSet = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TrafficMirrorId = 'TrafficMirrorId' in params ? params.TrafficMirrorId : null;
if (params.ReceiverSet) {
this.ReceiverSet = new Array();
for (let z in params.ReceiverSet) {
let obj = new BindTrafficMirrorReceiver();
obj.deserialize(params.ReceiverSet[z]);
this.ReceiverSet.push(obj);
}
}
}
}
/**
* BindTrafficMirrorListeners返回参数结构体
* @class
*/
class BindTrafficMirrorListenersResponse extends AbstractModel {
constructor(){
super();
/**
* 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。
* @type {string || null}
*/
this.TaskId = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TaskId = 'TaskId' in params ? params.TaskId : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* BindL7Backends请求参数结构体
* @class
*/
class BindL7BackendsRequest extends AbstractModel {
constructor(){
super();
/**
* 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。
* @type {string || null}
*/
this.LoadBalancerId = null;
/**
* 七层监听器实例ID,可通过接口DescribeL7Listeners查询。
* @type {string || null}
*/
this.ListenerId = null;
/**
* 转发域名实例ID,可通过接口DescribeL7Rules查询。
* @type {string || null}
*/
this.DomainId = null;
/**
* 转发路径实例ID,可通过接口DescribeL7Rules查询。
* @type {string || null}
*/
this.LocationId = null;
/**
* 待绑定的主机信息。可以绑定多个主机端口。目前一个七层转发路径下面最多允许绑定255个主机端口。
* @type {Array.<BindL7Backend> || null}
*/
this.BackendSet = null;
/**
* 绑定类型。0:物理机,1:虚拟机 2:半托管机器。
* @type {number || null}
*/
this.BindType = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
this.ListenerId = 'ListenerId' in params ? params.ListenerId : null;
this.DomainId = 'DomainId' in params ? params.DomainId : null;
this.LocationId = 'LocationId' in params ? params.LocationId : null;
if (params.BackendSet) {
this.BackendSet = new Array();
for (let z in params.BackendSet) {
let obj = new BindL7Backend();
obj.deserialize(params.BackendSet[z]);
this.BackendSet.push(obj);
}
}
this.BindType = 'BindType' in params ? params.BindType : null;
}
}
/**
* 待查询四层监听器绑定的主机信息。
* @class
*/
class DescribeL4Backend extends AbstractModel {
constructor(){
super();
/**
* 待绑定的主机端口,可选值1~65535。
* @type {number || null}
*/
this.Port = null;
/**
* 黑石物理机的主机ID。
* @type {string || null}
*/
this.InstanceId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.Port = 'Port' in params ? params.Port : null;
this.InstanceId = 'InstanceId' in params ? params.InstanceId : null;
}
}
/**
* DescribeCertDetail返回参数结构体
* @class
*/
class DescribeCertDetailResponse extends AbstractModel {
constructor(){
super();
/**
* 证书ID。
* @type {string || null}
*/
this.CertId = null;
/**
* 证书名称。
* @type {string || null}
*/
this.CertName = null;
/**
* 证书类型(SVR=服务器证书,CA=客户端证书)。
* @type {string || null}
*/
this.CertType = null;
/**
* 证书内容。
* @type {string || null}
*/
this.CertContent = null;
/**
* 证书主域名。
* @type {string || null}
*/
this.CertDomain = null;
/**
* 证书子域名列表。
* @type {Array.<string> || null}
*/
this.CertSubjectDomain = null;
/**
* 证书上传时间。
* @type {string || null}
*/
this.CertUploadTime = null;
/**
* 证书生效时间。
* @type {string || null}
*/
this.CertBeginTime = null;
/**
* 证书失效时间。
* @type {string || null}
*/
this.CertEndTime = null;
/**
* 该证书关联的黑石负载均衡对象列表。
* @type {Array.<CertDetailLoadBalancer> || null}
*/
this.CertLoadBalancerSet = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.CertId = 'CertId' in params ? params.CertId : null;
this.CertName = 'CertName' in params ? params.CertName : null;
this.CertType = 'CertType' in params ? params.CertType : null;
this.CertContent = 'CertContent' in params ? params.CertContent : null;
this.CertDomain = 'CertDomain' in params ? params.CertDomain : null;
this.CertSubjectDomain = 'CertSubjectDomain' in params ? params.CertSubjectDomain : null;
this.CertUploadTime = 'CertUploadTime' in params ? params.CertUploadTime : null;
this.CertBeginTime = 'CertBeginTime' in params ? params.CertBeginTime : null;
this.CertEndTime = 'CertEndTime' in params ? params.CertEndTime : null;
if (params.CertLoadBalancerSet) {
this.CertLoadBalancerSet = new Array();
for (let z in params.CertLoadBalancerSet) {
let obj = new CertDetailLoadBalancer();
obj.deserialize(params.CertLoadBalancerSet[z]);
this.CertLoadBalancerSet.push(obj);
}
}
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* DescribeL4Backends请求参数结构体
* @class
*/
class DescribeL4BackendsRequest extends AbstractModel {
constructor(){
super();
/**
* 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。
* @type {string || null}
*/
this.LoadBalancerId = null;
/**
* 负载均衡四层监听器ID,可通过接口DescribeL4Listeners查询。
* @type {string || null}
*/
this.ListenerId = null;
/**
* 待查询的主机信息。
* @type {Array.<DescribeL4Backend> || null}
*/
this.BackendSet = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
this.ListenerId = 'ListenerId' in params ? params.ListenerId : null;
if (params.BackendSet) {
this.BackendSet = new Array();
for (let z in params.BackendSet) {
let obj = new DescribeL4Backend();
obj.deserialize(params.BackendSet[z]);
this.BackendSet.push(obj);
}
}
}
}
/**
* DescribeTrafficMirrorReceiverHealthStatus返回参数结构体
* @class
*/
class DescribeTrafficMirrorReceiverHealthStatusResponse extends AbstractModel {
constructor(){
super();
/**
* 内网IP和端口对应的状态。
* @type {Array.<TrafficMirrorReciversStatus> || null}
*/
this.ReceiversStatusSet = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
if (params.ReceiversStatusSet) {
this.ReceiversStatusSet = new Array();
for (let z in params.ReceiversStatusSet) {
let obj = new TrafficMirrorReciversStatus();
obj.deserialize(params.ReceiversStatusSet[z]);
this.ReceiversStatusSet.push(obj);
}
}
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* BindTrafficMirrorReceivers返回参数结构体
* @class
*/
class BindTrafficMirrorReceiversResponse extends AbstractModel {
constructor(){
super();
/**
* 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。
* @type {string || null}
*/
this.TaskId = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TaskId = 'TaskId' in params ? params.TaskId : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* ReplaceCert返回参数结构体
* @class
*/
class ReplaceCertResponse extends AbstractModel {
constructor(){
super();
/**
* 新证书ID。
* @type {string || null}
*/
this.NewCertId = null;
/**
* 旧证书ID。
* @type {string || null}
*/
this.OldCertId = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.NewCertId = 'NewCertId' in params ? params.NewCertId : null;
this.OldCertId = 'OldCertId' in params ? params.OldCertId : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* DescribeLoadBalancerPortInfo请求参数结构体
* @class
*/
class DescribeLoadBalancerPortInfoRequest extends AbstractModel {
constructor(){
super();
/**
* 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。
* @type {string || null}
*/
this.LoadBalancerId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
}
}
/**
* 获取设备绑定信息时返回的设备所绑定的转发路径信息。
* @class
*/
class DevicesBindInfoLocation extends AbstractModel {
constructor(){
super();
/**
* 转发路径。
* @type {string || null}
*/
this.Url = null;
/**
* 转发路径实例ID。
* @type {string || null}
*/
this.LocationId = null;
/**
* 该转发路径所绑定的主机列表。
* @type {Array.<DevicesBindInfoBackend> || null}
*/
this.BackendSet = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.Url = 'Url' in params ? params.Url : null;
this.LocationId = 'LocationId' in params ? params.LocationId : null;
if (params.BackendSet) {
this.BackendSet = new Array();
for (let z in params.BackendSet) {
let obj = new DevicesBindInfoBackend();
obj.deserialize(params.BackendSet[z]);
this.BackendSet.push(obj);
}
}
}
}
/**
* SetTrafficMirrorHealthSwitch返回参数结构体
* @class
*/
class SetTrafficMirrorHealthSwitchResponse extends AbstractModel {
constructor(){
super();
/**
* 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。
* @type {string || null}
*/
this.TaskId = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TaskId = 'TaskId' in params ? params.TaskId : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* DeleteLoadBalancer请求参数结构体
* @class
*/
class DeleteLoadBalancerRequest extends AbstractModel {
constructor(){
super();
/**
* 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。
* @type {string || null}
*/
this.LoadBalancerId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
}
}
/**
* UnbindTrafficMirrorListeners返回参数结构体
* @class
*/
class UnbindTrafficMirrorListenersResponse extends AbstractModel {
constructor(){
super();
/**
* 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。
* @type {string || null}
*/
this.TaskId = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TaskId = 'TaskId' in params ? params.TaskId : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* 用于创建七层监听器的转发规则的信息。目前一个七层监听器下面最多允许创建50个七层转发域名,而每一个转发域名下最多可以创建100个转发规则。
* @class
*/
class CreateL7Rule extends AbstractModel {
constructor(){
super();
/**
* 七层转发规则的转发域名。
* @type {string || null}
*/
this.Domain = null;
/**
* 七层转发规则的转发路径。
* @type {string || null}
*/
this.Url = null;
/**
* 会话保持时间,单位:秒。可选值:30~3600。默认值0,表示不开启会话保持。
* @type {number || null}
*/
this.SessionExpire = null;
/**
* 健康检查开关:1(开启)、0(关闭)。默认值0,表示关闭。
* @type {number || null}
*/
this.HealthSwitch = null;
/**
* 健康检查检查间隔时间,默认值:5,可选值:5-300,单位:秒。
* @type {number || null}
*/
this.IntervalTime = null;
/**
* 健康检查健康阈值,默认值:3,表示当连续探测三次健康则表示该转发正常,可选值:2-10,单位:次。
* @type {number || null}
*/
this.HealthNum = null;
/**
* 健康检查不健康阈值,默认值:5,表示当连续探测五次不健康则表示该转发不正常,可选值:2-10,单位:次。
* @type {number || null}
*/
this.UnhealthNum = null;
/**
* 健康检查中认为健康的HTTP返回码的组合。可选值为1~5的集合,1表示HTTP返回码为1xx认为健康。2表示HTTP返回码为2xx认为健康。3表示HTTP返回码为3xx认为健康。4表示HTTP返回码为4xx认为健康。5表示HTTP返回码为5xx认为健康。
* @type {Array.<number> || null}
*/
this.HttpCodes = null;
/**
* 健康检查检查路径。
* @type {string || null}
*/
this.HttpCheckPath = null;
/**
* 健康检查检查域名。如果创建规则的域名使用通配符或正则表达式,则健康检查检查域名可自定义,否则必须跟健康检查检查域名一样。
* @type {string || null}
*/
this.HttpCheckDomain = null;
/**
* 均衡方式:ip_hash、wrr。默认值wrr。
* @type {string || null}
*/
this.BalanceMode = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.Domain = 'Domain' in params ? params.Domain : null;
this.Url = 'Url' in params ? params.Url : null;
this.SessionExpire = 'SessionExpire' in params ? params.SessionExpire : null;
this.HealthSwitch = 'HealthSwitch' in params ? params.HealthSwitch : null;
this.IntervalTime = 'IntervalTime' in params ? params.IntervalTime : null;
this.HealthNum = 'HealthNum' in params ? params.HealthNum : null;
this.UnhealthNum = 'UnhealthNum' in params ? params.UnhealthNum : null;
this.HttpCodes = 'HttpCodes' in params ? params.HttpCodes : null;
this.HttpCheckPath = 'HttpCheckPath' in params ? params.HttpCheckPath : null;
this.HttpCheckDomain = 'HttpCheckDomain' in params ? params.HttpCheckDomain : null;
this.BalanceMode = 'BalanceMode' in params ? params.BalanceMode : null;
}
}
/**
* CreateL7Rules返回参数结构体
* @class
*/
class CreateL7RulesResponse extends AbstractModel {
constructor(){
super();
/**
* 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。
* @type {string || null}
*/
this.TaskId = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TaskId = 'TaskId' in params ? params.TaskId : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* ModifyL7Listener请求参数结构体
* @class
*/
class ModifyL7ListenerRequest extends AbstractModel {
constructor(){
super();
/**
* 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。
* @type {string || null}
*/
this.LoadBalancerId = null;
/**
* 七层监听器实例ID,可通过接口DescribeL7Listeners查询。
* @type {string || null}
*/
this.ListenerId = null;
/**
* 七层监听器名称。
* @type {string || null}
*/
this.ListenerName = null;
/**
* 认证方式:0(不认证,用于http),1(单向认证,用于https),2(双向认证,用于https)。
* @type {number || null}
*/
this.SslMode = null;
/**
* 服务端证书ID。
* @type {string || null}
*/
this.CertId = null;
/**
* 服务端证书名称。
* @type {string || null}
*/
this.CertName = null;
/**
* 服务端证书内容。
* @type {string || null}
*/
this.CertContent = null;
/**
* 服务端证书密钥。
* @type {string || null}
*/
this.CertKey = null;
/**
* 客户端证书ID。
* @type {string || null}
*/
this.CertCaId = null;
/**
* 客户端证书名称。
* @type {string || null}
*/
this.CertCaName = null;
/**
* 客户端证书内容。
* @type {string || null}
*/
this.CertCaContent = null;
/**
* 计费模式为按固定带宽方式时监听器的限速值,可选值:0-1000,单位:Mbps。
* @type {number || null}
*/
this.Bandwidth = null;
/**
* 转发协议。当监听器Protocol为https时并且SslMode为1或2时,有意义。可选的值为0:https,1:spdy,2:http2,3:spdy+http2。
* @type {number || null}
*/
this.ForwardProtocol = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
this.ListenerId = 'ListenerId' in params ? params.ListenerId : null;
this.ListenerName = 'ListenerName' in params ? params.ListenerName : null;
this.SslMode = 'SslMode' in params ? params.SslMode : null;
this.CertId = 'CertId' in params ? params.CertId : null;
this.CertName = 'CertName' in params ? params.CertName : null;
this.CertContent = 'CertContent' in params ? params.CertContent : null;
this.CertKey = 'CertKey' in params ? params.CertKey : null;
this.CertCaId = 'CertCaId' in params ? params.CertCaId : null;
this.CertCaName = 'CertCaName' in params ? params.CertCaName : null;
this.CertCaContent = 'CertCaContent' in params ? params.CertCaContent : null;
this.Bandwidth = 'Bandwidth' in params ? params.Bandwidth : null;
this.ForwardProtocol = 'ForwardProtocol' in params ? params.ForwardProtocol : null;
}
}
/**
* 流量镜像进行健康检查的接收机信息。
* @class
*/
class DescribeTrafficMirrorReceiver extends AbstractModel {
constructor(){
super();
/**
* 物理机实例ID。
* @type {string || null}
*/
this.InstanceId = null;
/**
* 物理机绑定的端口。
* @type {number || null}
*/
this.Port = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.InstanceId = 'InstanceId' in params ? params.InstanceId : null;
this.Port = 'Port' in params ? params.Port : null;
}
}
/**
* 监听器信息。
* @class
*/
class L7ExListener extends AbstractModel {
constructor(){
super();
/**
* 绑定的监听器唯一ID。
* @type {string || null}
*/
this.ListenerId = null;
/**
* 监听器名称。
* @type {string || null}
*/
this.ListenerName = null;
/**
* 七层监听器协议类型,可选值:http,https。
* @type {string || null}
*/
this.Protocol = null;
/**
* 监听器的监听端口。
* @type {number || null}
*/
this.LoadBalancerPort = null;
/**
* 当前带宽。
* @type {number || null}
*/
this.Bandwidth = null;
/**
* 带宽上限。
* @type {number || null}
*/
this.MaxBandwidth = null;
/**
* 监听器类型。
* @type {string || null}
*/
this.ListenerType = null;
/**
* 认证方式:0(不认证,用于http),1(单向认证,用于https),2(双向认证,用于https)。
* @type {number || null}
*/
this.SslMode = null;
/**
* 服务端证书ID。
* @type {string || null}
*/
this.CertId = null;
/**
* 客户端证书ID。
* @type {string || null}
*/
this.CertCaId = null;
/**
* 添加时间。
* @type {string || null}
*/
this.AddTimestamp = null;
/**
* 负载均衡名ID。
* @type {string || null}
*/
this.LoadBalancerId = null;
/**
* 私有网络名称。
* @type {string || null}
*/
this.VpcName = null;
/**
* 私有网络Cidr。
* @type {string || null}
*/
this.VpcCidrBlock = null;
/**
* 负载均衡的VIP。
* @type {Array.<string> || null}
*/
this.LoadBalancerVips = null;
/**
* 负载均衡名称。
* @type {string || null}
*/
this.LoadBalancerName = null;
/**
* 负载均衡IPV6的VIP。
* @type {Array.<string> || null}
*/
this.LoadBalancerVipv6s = null;
/**
* 支持的IP协议类型。ipv4或者是ipv6。
* @type {string || null}
*/
this.IpProtocolType = null;
/**
* 是否绑定在入参指定的流量镜像中。
* @type {boolean || null}
*/
this.BindTrafficMirror = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.ListenerId = 'ListenerId' in params ? params.ListenerId : null;
this.ListenerName = 'ListenerName' in params ? params.ListenerName : null;
this.Protocol = 'Protocol' in params ? params.Protocol : null;
this.LoadBalancerPort = 'LoadBalancerPort' in params ? params.LoadBalancerPort : null;
this.Bandwidth = 'Bandwidth' in params ? params.Bandwidth : null;
this.MaxBandwidth = 'MaxBandwidth' in params ? params.MaxBandwidth : null;
this.ListenerType = 'ListenerType' in params ? params.ListenerType : null;
this.SslMode = 'SslMode' in params ? params.SslMode : null;
this.CertId = 'CertId' in params ? params.CertId : null;
this.CertCaId = 'CertCaId' in params ? params.CertCaId : null;
this.AddTimestamp = 'AddTimestamp' in params ? params.AddTimestamp : null;
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
this.VpcName = 'VpcName' in params ? params.VpcName : null;
this.VpcCidrBlock = 'VpcCidrBlock' in params ? params.VpcCidrBlock : null;
this.LoadBalancerVips = 'LoadBalancerVips' in params ? params.LoadBalancerVips : null;
this.LoadBalancerName = 'LoadBalancerName' in params ? params.LoadBalancerName : null;
this.LoadBalancerVipv6s = 'LoadBalancerVipv6s' in params ? params.LoadBalancerVipv6s : null;
this.IpProtocolType = 'IpProtocolType' in params ? params.IpProtocolType : null;
this.BindTrafficMirror = 'BindTrafficMirror' in params ? params.BindTrafficMirror : null;
}
}
/**
* 查询绑定了某主机的七层监听器时返回的七层监听器信息。
* @class
*/
class L7ListenerInfo extends AbstractModel {
constructor(){
super();
/**
* 七层监听器实例ID。
* @type {string || null}
*/
this.ListenerId = null;
/**
* 七层监听器名称。
* @type {string || null}
*/
this.ListenerName = null;
/**
* 七层监听器协议类型,可选值:http,https。
* @type {string || null}
*/
this.Protocol = null;
/**
* 七层监听器的监听端口。
* @type {number || null}
*/
this.LoadBalancerPort = null;
/**
* 计费模式为按固定带宽方式时监听器的限速值,单位:Mbps。
* @type {number || null}
*/
this.Bandwidth = null;
/**
* 监听器的类别:L4Listener(四层监听器),L7Listener(七层监听器)。
* @type {string || null}
*/
this.ListenerType = null;
/**
* 七层监听器的认证方式:0(不认证,用于http),1(单向认证,用于https),2(双向认证,用于https)。
* @type {number || null}
*/
this.SslMode = null;
/**
* 七层监听器关联的服务端证书ID。
* @type {string || null}
*/
this.CertId = null;
/**
* 七层监听器关联的客户端证书ID。
* @type {string || null}
*/
this.CertCaId = null;
/**
* 当前绑定关系的健康检查状态(Dead代表不健康,Alive代表健康)。
* @type {number || null}
*/
this.Status = null;
/**
* 创建时间戳。
* @type {string || null}
*/
this.AddTimestamp = null;
/**
* 返回的转发规则列表。
* @type {Array.<L7ListenerInfoRule> || null}
*/
this.RuleSet = null;
/**
* https转发类型。0:https。1:spdy。2:http2。3:spdy+http2。
* @type {number || null}
*/
this.ForwardProtocol = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.ListenerId = 'ListenerId' in params ? params.ListenerId : null;
this.ListenerName = 'ListenerName' in params ? params.ListenerName : null;
this.Protocol = 'Protocol' in params ? params.Protocol : null;
this.LoadBalancerPort = 'LoadBalancerPort' in params ? params.LoadBalancerPort : null;
this.Bandwidth = 'Bandwidth' in params ? params.Bandwidth : null;
this.ListenerType = 'ListenerType' in params ? params.ListenerType : null;
this.SslMode = 'SslMode' in params ? params.SslMode : null;
this.CertId = 'CertId' in params ? params.CertId : null;
this.CertCaId = 'CertCaId' in params ? params.CertCaId : null;
this.Status = 'Status' in params ? params.Status : null;
this.AddTimestamp = 'AddTimestamp' in params ? params.AddTimestamp : null;
if (params.RuleSet) {
this.RuleSet = new Array();
for (let z in params.RuleSet) {
let obj = new L7ListenerInfoRule();
obj.deserialize(params.RuleSet[z]);
this.RuleSet.push(obj);
}
}
this.ForwardProtocol = 'ForwardProtocol' in params ? params.ForwardProtocol : null;
}
}
/**
* 查询绑定了某主机的七层监听器时返回的转发规则。
* @class
*/
class L7ListenerInfoRule extends AbstractModel {
constructor(){
super();
/**
* 转发域名。
* @type {string || null}
*/
this.Domain = null;
/**
* 转发域名实例ID。
* @type {string || null}
*/
this.DomainId = null;
/**
* 当前绑定关系的健康检查状态(Dead代表不健康,Alive代表健康)。
* @type {number || null}
*/
this.Status = null;
/**
* 创建时间戳。
* @type {string || null}
*/
this.AddTimestamp = null;
/**
* 该转发域名下面的转发路径列表。
* @type {Array.<L7ListenerInfoLocation> || null}
*/
this.LocationSet = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.Domain = 'Domain' in params ? params.Domain : null;
this.DomainId = 'DomainId' in params ? params.DomainId : null;
this.Status = 'Status' in params ? params.Status : null;
this.AddTimestamp = 'AddTimestamp' in params ? params.AddTimestamp : null;
if (params.LocationSet) {
this.LocationSet = new Array();
for (let z in params.LocationSet) {
let obj = new L7ListenerInfoLocation();
obj.deserialize(params.LocationSet[z]);
this.LocationSet.push(obj);
}
}
}
}
/**
* DescribeL7Backends返回参数结构体
* @class
*/
class DescribeL7BackendsResponse extends AbstractModel {
constructor(){
super();
/**
* 返回的绑定关系列表。
* @type {Array.<L7Backend> || null}
*/
this.BackendSet = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
if (params.BackendSet) {
this.BackendSet = new Array();
for (let z in params.BackendSet) {
let obj = new L7Backend();
obj.deserialize(params.BackendSet[z]);
this.BackendSet.push(obj);
}
}
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* 过滤器
* @class
*/
class Filter extends AbstractModel {
constructor(){
super();
/**
* 属性名称, 若存在多个Filter时,Filter间的关系为逻辑与(AND)关系。
* @type {string || null}
*/
this.Name = null;
/**
* 属性值, 若同一个Filter存在多个Values,同一Filter下Values间的关系为逻辑或(OR)关系。
* @type {Array.<string> || null}
*/
this.Values = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.Name = 'Name' in params ? params.Name : null;
this.Values = 'Values' in params ? params.Values : null;
}
}
/**
* 获取设备绑定信息时返回的设备所绑定的转发规则信息。
* @class
*/
class DevicesBindInfoRule extends AbstractModel {
constructor(){
super();
/**
* 转发域名。
* @type {string || null}
*/
this.Domain = null;
/**
* 转发域名ID。
* @type {string || null}
*/
this.DomainId = null;
/**
* 转发路径列表。
* @type {Array.<DevicesBindInfoLocation> || null}
*/
this.LocationSet = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.Domain = 'Domain' in params ? params.Domain : null;
this.DomainId = 'DomainId' in params ? params.DomainId : null;
if (params.LocationSet) {
this.LocationSet = new Array();
for (let z in params.LocationSet) {
let obj = new DevicesBindInfoLocation();
obj.deserialize(params.LocationSet[z]);
this.LocationSet.push(obj);
}
}
}
}
/**
* 获取流量镜像实例的列表信息时返回的流量镜像信息。
* @class
*/
class TrafficMirror extends AbstractModel {
constructor(){
super();
/**
* 流量镜像ID。
* @type {string || null}
*/
this.TrafficMirrorId = null;
/**
* 流量镜像名称。
* @type {string || null}
*/
this.Alias = null;
/**
* 流量镜像所在的私有网络ID。
* @type {string || null}
*/
this.VpcId = null;
/**
* 接收机负载均衡方式。wrr,ip_hash,wlc。
* @type {string || null}
*/
this.LoadBalancerType = null;
/**
* 是否开始对接收机的健康检查。0:关闭,非0:开启。
* @type {number || null}
*/
this.HealthSwitch = null;
/**
* 健康阈值。
* @type {number || null}
*/
this.HealthNum = null;
/**
* 不健康阈值。
* @type {number || null}
*/
this.UnhealthNum = null;
/**
* 检查间隔。
* @type {number || null}
*/
this.IntervalTime = null;
/**
* 检查域名。
* @type {string || null}
*/
this.HttpCheckDomain = null;
/**
* 检查目录。
* @type {string || null}
*/
this.HttpCheckPath = null;
/**
* 健康检查返回码。 1:1xx,2:2xx,3:3xx,4:4xx,5:5xx。
* @type {Array.<number> || null}
*/
this.HttpCodes = null;
/**
* 创建时间。
* @type {string || null}
*/
this.CreateTime = null;
/**
* 流量镜像所在私有网络的Cidr。
* @type {string || null}
*/
this.VpcCidrBlock = null;
/**
* 流量镜像所在私有网络的名称。
* @type {string || null}
*/
this.VpcName = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TrafficMirrorId = 'TrafficMirrorId' in params ? params.TrafficMirrorId : null;
this.Alias = 'Alias' in params ? params.Alias : null;
this.VpcId = 'VpcId' in params ? params.VpcId : null;
this.LoadBalancerType = 'LoadBalancerType' in params ? params.LoadBalancerType : null;
this.HealthSwitch = 'HealthSwitch' in params ? params.HealthSwitch : null;
this.HealthNum = 'HealthNum' in params ? params.HealthNum : null;
this.UnhealthNum = 'UnhealthNum' in params ? params.UnhealthNum : null;
this.IntervalTime = 'IntervalTime' in params ? params.IntervalTime : null;
this.HttpCheckDomain = 'HttpCheckDomain' in params ? params.HttpCheckDomain : null;
this.HttpCheckPath = 'HttpCheckPath' in params ? params.HttpCheckPath : null;
this.HttpCodes = 'HttpCodes' in params ? params.HttpCodes : null;
this.CreateTime = 'CreateTime' in params ? params.CreateTime : null;
this.VpcCidrBlock = 'VpcCidrBlock' in params ? params.VpcCidrBlock : null;
this.VpcName = 'VpcName' in params ? params.VpcName : null;
}
}
/**
* DescribeLoadBalancers请求参数结构体
* @class
*/
class DescribeLoadBalancersRequest extends AbstractModel {
constructor(){
super();
/**
* 负载均衡器ID数组
* @type {Array.<string> || null}
*/
this.LoadBalancerIds = null;
/**
* 负载均衡的类型 : open表示公网LB类型,internal表示内网LB类型
* @type {string || null}
*/
this.LoadBalancerType = null;
/**
* 负载均衡器名称
* @type {string || null}
*/
this.LoadBalancerName = null;
/**
* 负载均衡域名。规则:1-60个小写英文字母、数字、点号“.”或连接线“-”。内网类型的负载均衡不能配置该字段
* @type {string || null}
*/
this.Domain = null;
/**
* 负载均衡获得的公网IP地址,支持多个
* @type {Array.<string> || null}
*/
this.LoadBalancerVips = null;
/**
* 数据偏移量,默认为0
* @type {number || null}
*/
this.Offset = null;
/**
* 返回数据长度,默认为20
* @type {number || null}
*/
this.Limit = null;
/**
* 模糊查找名称、域名、VIP
* @type {string || null}
*/
this.SearchKey = null;
/**
* 排序字段,支持:loadBalancerName,createTime,domain,loadBalancerType
* @type {string || null}
*/
this.OrderBy = null;
/**
* 1倒序,0顺序,默认顺序
* @type {number || null}
*/
this.OrderType = null;
/**
* 项目ID
* @type {number || null}
*/
this.ProjectId = null;
/**
* 是否筛选独占集群,0表示非独占集群,1表示四层独占集群,2表示七层独占集群,3表示四层和七层独占集群,4表示共享容灾
* @type {number || null}
*/
this.Exclusive = null;
/**
* 该负载均衡对应的tgw集群(fullnat,tunnel,dnat)
* @type {string || null}
*/
this.TgwSetType = null;
/**
* 该负载均衡对应的所在的私有网络ID
* @type {string || null}
*/
this.VpcId = null;
/**
* 'CONFLIST' 查询带confId的LB列表,'CONFID' 查询某个confId绑定的LB列表
* @type {string || null}
*/
this.QueryType = null;
/**
* 个性化配置ID
* @type {string || null}
*/
this.ConfId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerIds = 'LoadBalancerIds' in params ? params.LoadBalancerIds : null;
this.LoadBalancerType = 'LoadBalancerType' in params ? params.LoadBalancerType : null;
this.LoadBalancerName = 'LoadBalancerName' in params ? params.LoadBalancerName : null;
this.Domain = 'Domain' in params ? params.Domain : null;
this.LoadBalancerVips = 'LoadBalancerVips' in params ? params.LoadBalancerVips : null;
this.Offset = 'Offset' in params ? params.Offset : null;
this.Limit = 'Limit' in params ? params.Limit : null;
this.SearchKey = 'SearchKey' in params ? params.SearchKey : null;
this.OrderBy = 'OrderBy' in params ? params.OrderBy : null;
this.OrderType = 'OrderType' in params ? params.OrderType : null;
this.ProjectId = 'ProjectId' in params ? params.ProjectId : null;
this.Exclusive = 'Exclusive' in params ? params.Exclusive : null;
this.TgwSetType = 'TgwSetType' in params ? params.TgwSetType : null;
this.VpcId = 'VpcId' in params ? params.VpcId : null;
this.QueryType = 'QueryType' in params ? params.QueryType : null;
this.ConfId = 'ConfId' in params ? params.ConfId : null;
}
}
/**
* 获取设备绑定信息时返回的设备被绑定所在的负载均衡信息。
* @class
*/
class DevicesBindInfoLoadBalancer extends AbstractModel {
constructor(){
super();
/**
* 负载均衡实例ID。
* @type {string || null}
*/
this.LoadBalancerId = null;
/**
* 开发商AppId。
* @type {number || null}
*/
this.AppId = null;
/**
* 负载均衡所属的项目ID。
* @type {number || null}
*/
this.ProjectId = null;
/**
* 黑石私有网络唯一ID。
* @type {string || null}
*/
this.VpcId = null;
/**
* 负载均衡的IP地址。
* @type {string || null}
*/
this.Vip = null;
/**
* 负载均衡对应的TGW集群类别,取值为tunnel或fullnat。tunnel表示隧道集群,fullnat表示FULLNAT集群。
* @type {string || null}
*/
this.TgwSetType = null;
/**
* 是否独占TGW集群。
* @type {number || null}
*/
this.Exclusive = null;
/**
* 具有该绑定关系的四层监听器列表。
* @type {Array.<DevicesBindInfoL4Listener> || null}
*/
this.L4ListenerSet = null;
/**
* 具有该绑定关系的七层监听器列表。
* @type {Array.<DevicesBindInfoL7Listener> || null}
*/
this.L7ListenerSet = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
this.AppId = 'AppId' in params ? params.AppId : null;
this.ProjectId = 'ProjectId' in params ? params.ProjectId : null;
this.VpcId = 'VpcId' in params ? params.VpcId : null;
this.Vip = 'Vip' in params ? params.Vip : null;
this.TgwSetType = 'TgwSetType' in params ? params.TgwSetType : null;
this.Exclusive = 'Exclusive' in params ? params.Exclusive : null;
if (params.L4ListenerSet) {
this.L4ListenerSet = new Array();
for (let z in params.L4ListenerSet) {
let obj = new DevicesBindInfoL4Listener();
obj.deserialize(params.L4ListenerSet[z]);
this.L4ListenerSet.push(obj);
}
}
if (params.L7ListenerSet) {
this.L7ListenerSet = new Array();
for (let z in params.L7ListenerSet) {
let obj = new DevicesBindInfoL7Listener();
obj.deserialize(params.L7ListenerSet[z]);
this.L7ListenerSet.push(obj);
}
}
}
}
/**
* 查询四层监听器时返回的四层监听器信息。
* @class
*/
class L4Listener extends AbstractModel {
constructor(){
super();
/**
* 监听器ID。
* @type {string || null}
*/
this.ListenerId = null;
/**
* 用户自定义的监听器名称。
* @type {string || null}
*/
this.ListenerName = null;
/**
* 负载均衡实例监听器协议类型,可选值tcp,udp。
* @type {string || null}
*/
this.Protocol = null;
/**
* 负载均衡监听器的监听接口,可选值1~65535。
* @type {number || null}
*/
this.LoadBalancerPort = null;
/**
* 用于计费模式为固定带宽计费,指定监听器最大带宽值,可选值:0-1000,单位:Mbps。
* @type {number || null}
*/
this.Bandwidth = null;
/**
* 监听器的类别:L4Listener(四层监听器),L7Listener(七层监听器)。
* @type {string || null}
*/
this.ListenerType = null;
/**
* 会话保持时间。单位:秒
* @type {number || null}
*/
this.SessionExpire = null;
/**
* 是否开启了检查:1(开启)、0(关闭)。
* @type {number || null}
*/
this.HealthSwitch = null;
/**
* 响应超时时间,单位:秒。
* @type {number || null}
*/
this.TimeOut = null;
/**
* 检查间隔,单位:秒。
* @type {number || null}
*/
this.IntervalTime = null;
/**
* 负载均衡监听器健康阈值,默认值:3,表示当连续探测三次健康则表示该转发正常,可选值:2-10,单位:次。
* @type {number || null}
*/
this.HealthNum = null;
/**
* 负载均衡监听器不健康阈值,默认值:3,表示当连续探测三次不健康则表示该转发不正常,可选值:2-10,单位:次。
* @type {number || null}
*/
this.UnhealthNum = null;
/**
* 是否开启自定义健康检查:1(开启)、0(关闭)。默认值0,表示关闭。(该字段在健康检查开启的情况下才生效)
* @type {number || null}
*/
this.CustomHealthSwitch = null;
/**
* 自定义健康探测内容类型,可选值:text(文本)、hexadecimal(十六进制)。
* @type {string || null}
*/
this.InputType = null;
/**
* 探测内容类型为文本方式时,针对请求文本中换行替换方式。可选值:1(替换为LF)、2(替换为CR)、3(替换为LF+CR)。
* @type {number || null}
*/
this.LineSeparatorType = null;
/**
* 自定义探测请求内容。
* @type {string || null}
*/
this.HealthRequest = null;
/**
* 自定义探测返回内容。
* @type {string || null}
*/
this.HealthResponse = null;
/**
* 是否开启toa:1(开启)、0(关闭)。
* @type {number || null}
*/
this.ToaFlag = null;
/**
* 监听器当前状态(0代表创建中,1代表正常运行,2代表创建失败,3代表删除中,4代表删除失败)。
* @type {number || null}
*/
this.Status = null;
/**
* 创建时间戳。
* @type {string || null}
*/
this.AddTimestamp = null;
/**
* 转发后端服务器调度类型。
* @type {string || null}
*/
this.BalanceMode = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.ListenerId = 'ListenerId' in params ? params.ListenerId : null;
this.ListenerName = 'ListenerName' in params ? params.ListenerName : null;
this.Protocol = 'Protocol' in params ? params.Protocol : null;
this.LoadBalancerPort = 'LoadBalancerPort' in params ? params.LoadBalancerPort : null;
this.Bandwidth = 'Bandwidth' in params ? params.Bandwidth : null;
this.ListenerType = 'ListenerType' in params ? params.ListenerType : null;
this.SessionExpire = 'SessionExpire' in params ? params.SessionExpire : null;
this.HealthSwitch = 'HealthSwitch' in params ? params.HealthSwitch : null;
this.TimeOut = 'TimeOut' in params ? params.TimeOut : null;
this.IntervalTime = 'IntervalTime' in params ? params.IntervalTime : null;
this.HealthNum = 'HealthNum' in params ? params.HealthNum : null;
this.UnhealthNum = 'UnhealthNum' in params ? params.UnhealthNum : null;
this.CustomHealthSwitch = 'CustomHealthSwitch' in params ? params.CustomHealthSwitch : null;
this.InputType = 'InputType' in params ? params.InputType : null;
this.LineSeparatorType = 'LineSeparatorType' in params ? params.LineSeparatorType : null;
this.HealthRequest = 'HealthRequest' in params ? params.HealthRequest : null;
this.HealthResponse = 'HealthResponse' in params ? params.HealthResponse : null;
this.ToaFlag = 'ToaFlag' in params ? params.ToaFlag : null;
this.Status = 'Status' in params ? params.Status : null;
this.AddTimestamp = 'AddTimestamp' in params ? params.AddTimestamp : null;
this.BalanceMode = 'BalanceMode' in params ? params.BalanceMode : null;
}
}
/**
* 用于创建四层监听器的监听器信息。目前一个负载均衡下面最多允许创建50个七层监听器。
* @class
*/
class CreateL7Listener extends AbstractModel {
constructor(){
super();
/**
* 七层监听器端口,可选值1~65535。
* @type {number || null}
*/
this.LoadBalancerPort = null;
/**
* 七层监听器协议类型,可选值:http,https。
* @type {string || null}
*/
this.Protocol = null;
/**
* 七层监听器名称。
* @type {string || null}
*/
this.ListenerName = null;
/**
* 认证方式:0(不认证,用于http),1(单向认证,用于https),2(双向认证,用于https)。当创建的是https类型的监听器时,此值必选。
* @type {number || null}
*/
this.SslMode = null;
/**
* 服务端证书ID。当创建的是https类型的监听器时,此值必选。
* @type {string || null}
*/
this.CertId = null;
/**
* 服务端证书名称。
* @type {string || null}
*/
this.CertName = null;
/**
* 服务端证书内容。
* @type {string || null}
*/
this.CertContent = null;
/**
* 服务端证书密钥。
* @type {string || null}
*/
this.CertKey = null;
/**
* 客户端证书ID。
* @type {string || null}
*/
this.CertCaId = null;
/**
* 客户端证书名称。
* @type {string || null}
*/
this.CertCaName = null;
/**
* 客户端证书内容。
* @type {string || null}
*/
this.CertCaContent = null;
/**
* 用于计费模式为固定带宽计费,指定监听器最大带宽值,可选值:0-1000,单位:Mbps。
* @type {number || null}
*/
this.Bandwidth = null;
/**
* 转发协议。当Protocol为https时并且SslMode为1或2时,有意义。可选的值为0:https,1:spdy,2:http2,3:spdy+http2。
* @type {number || null}
*/
this.ForwardProtocol = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerPort = 'LoadBalancerPort' in params ? params.LoadBalancerPort : null;
this.Protocol = 'Protocol' in params ? params.Protocol : null;
this.ListenerName = 'ListenerName' in params ? params.ListenerName : null;
this.SslMode = 'SslMode' in params ? params.SslMode : null;
this.CertId = 'CertId' in params ? params.CertId : null;
this.CertName = 'CertName' in params ? params.CertName : null;
this.CertContent = 'CertContent' in params ? params.CertContent : null;
this.CertKey = 'CertKey' in params ? params.CertKey : null;
this.CertCaId = 'CertCaId' in params ? params.CertCaId : null;
this.CertCaName = 'CertCaName' in params ? params.CertCaName : null;
this.CertCaContent = 'CertCaContent' in params ? params.CertCaContent : null;
this.Bandwidth = 'Bandwidth' in params ? params.Bandwidth : null;
this.ForwardProtocol = 'ForwardProtocol' in params ? params.ForwardProtocol : null;
}
}
/**
* DeleteLoadBalancer返回参数结构体
* @class
*/
class DeleteLoadBalancerResponse extends AbstractModel {
constructor(){
super();
/**
* 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。
* @type {string || null}
*/
this.TaskId = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TaskId = 'TaskId' in params ? params.TaskId : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* CreateTrafficMirror请求参数结构体
* @class
*/
class CreateTrafficMirrorRequest extends AbstractModel {
constructor(){
super();
/**
* 流量镜像实例别名。
* @type {string || null}
*/
this.Alias = null;
/**
* 流量镜像实例所属的私有网络ID,形如:vpc-xxx。
* @type {string || null}
*/
this.VpcId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.Alias = 'Alias' in params ? params.Alias : null;
this.VpcId = 'VpcId' in params ? params.VpcId : null;
}
}
/**
* BindL4Backends请求参数结构体
* @class
*/
class BindL4BackendsRequest extends AbstractModel {
constructor(){
super();
/**
* 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。
* @type {string || null}
*/
this.LoadBalancerId = null;
/**
* 四层监听器实例ID,可通过接口DescribeL4Listeners查询。
* @type {string || null}
*/
this.ListenerId = null;
/**
* 待绑定的主机信息。可以绑定多个主机端口。目前一个四层监听器下面最多允许绑定255个主机端口。
* @type {Array.<BindL4Backend> || null}
*/
this.BackendSet = null;
/**
* 绑定类型。0:物理机 1:虚拟机 2:半托管机器
* @type {number || null}
*/
this.BindType = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
this.ListenerId = 'ListenerId' in params ? params.ListenerId : null;
if (params.BackendSet) {
this.BackendSet = new Array();
for (let z in params.BackendSet) {
let obj = new BindL4Backend();
obj.deserialize(params.BackendSet[z]);
this.BackendSet.push(obj);
}
}
this.BindType = 'BindType' in params ? params.BindType : null;
}
}
/**
* DescribeL7ListenerInfo返回参数结构体
* @class
*/
class DescribeL7ListenerInfoResponse extends AbstractModel {
constructor(){
super();
/**
* 返回的七层监听器列表。
* @type {Array.<L7ListenerInfo> || null}
*/
this.ListenerSet = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
if (params.ListenerSet) {
this.ListenerSet = new Array();
for (let z in params.ListenerSet) {
let obj = new L7ListenerInfo();
obj.deserialize(params.ListenerSet[z]);
this.ListenerSet.push(obj);
}
}
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* DescribeL7Listeners返回参数结构体
* @class
*/
class DescribeL7ListenersResponse extends AbstractModel {
constructor(){
super();
/**
* 返回的七层监听器列表。
* @type {Array.<L7Listener> || null}
*/
this.ListenerSet = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
if (params.ListenerSet) {
this.ListenerSet = new Array();
for (let z in params.ListenerSet) {
let obj = new L7Listener();
obj.deserialize(params.ListenerSet[z]);
this.ListenerSet.push(obj);
}
}
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* DeleteListeners返回参数结构体
* @class
*/
class DeleteListenersResponse extends AbstractModel {
constructor(){
super();
/**
* 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。
* @type {string || null}
*/
this.TaskId = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TaskId = 'TaskId' in params ? params.TaskId : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* CreateLoadBalancers返回参数结构体
* @class
*/
class CreateLoadBalancersResponse extends AbstractModel {
constructor(){
super();
/**
* 创建的黑石负载均衡实例ID。
* @type {Array.<string> || null}
*/
this.LoadBalancerIds = null;
/**
* 创建负载均衡的异步任务ID。
* @type {string || null}
*/
this.TaskId = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerIds = 'LoadBalancerIds' in params ? params.LoadBalancerIds : null;
this.TaskId = 'TaskId' in params ? params.TaskId : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* 待与流量镜像解绑的接收机信息。
* @class
*/
class UnbindTrafficMirrorReceiver extends AbstractModel {
constructor(){
super();
/**
* 待解绑的主机端口,可选值1~65535。
* @type {number || null}
*/
this.Port = null;
/**
* 待解绑的主机实例ID。
* @type {string || null}
*/
this.InstanceId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.Port = 'Port' in params ? params.Port : null;
this.InstanceId = 'InstanceId' in params ? params.InstanceId : null;
}
}
/**
* ModifyLoadBalancerChargeMode返回参数结构体
* @class
*/
class ModifyLoadBalancerChargeModeResponse extends AbstractModel {
constructor(){
super();
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* UnbindL7Backends请求参数结构体
* @class
*/
class UnbindL7BackendsRequest extends AbstractModel {
constructor(){
super();
/**
* 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。
* @type {string || null}
*/
this.LoadBalancerId = null;
/**
* 七层监听器实例ID,可通过接口DescribeL7Listeners查询。
* @type {string || null}
*/
this.ListenerId = null;
/**
* 转发域名实例ID,可通过接口DescribeL7Rules查询。
* @type {string || null}
*/
this.DomainId = null;
/**
* 转发路径实例ID,可通过接口DescribeL7Rules查询。
* @type {string || null}
*/
this.LocationId = null;
/**
* 待绑定的主机信息。
* @type {Array.<UnbindL7Backend> || null}
*/
this.BackendSet = null;
/**
* 绑定类型。0:物理机 1:虚拟机 2:半托管机器
* @type {number || null}
*/
this.BindType = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
this.ListenerId = 'ListenerId' in params ? params.ListenerId : null;
this.DomainId = 'DomainId' in params ? params.DomainId : null;
this.LocationId = 'LocationId' in params ? params.LocationId : null;
if (params.BackendSet) {
this.BackendSet = new Array();
for (let z in params.BackendSet) {
let obj = new UnbindL7Backend();
obj.deserialize(params.BackendSet[z]);
this.BackendSet.push(obj);
}
}
this.BindType = 'BindType' in params ? params.BindType : null;
}
}
/**
* 查询绑定了某主机的七层监听器时返回的转发路径。
* @class
*/
class L7ListenerInfoLocation extends AbstractModel {
constructor(){
super();
/**
* 转发路径。
* @type {string || null}
*/
this.Url = null;
/**
* 转发路径实例ID。
* @type {string || null}
*/
this.LocationId = null;
/**
* 会话保持时间。
* @type {number || null}
*/
this.SessionExpire = null;
/**
* 是否开启健康检查。
* @type {number || null}
*/
this.HealthSwitch = null;
/**
* 健康检查检查路径。
* @type {string || null}
*/
this.HttpCheckPath = null;
/**
* 健康检查检查域名。
* @type {string || null}
*/
this.HttpCheckDomain = null;
/**
* 健康检查检查间隔时间。
* @type {number || null}
*/
this.IntervalTime = null;
/**
* 健康检查健康阈值。
* @type {number || null}
*/
this.HealthNum = null;
/**
* 健康检查不健康阈值。
* @type {number || null}
*/
this.UnhealthNum = null;
/**
* 健康检查中认为健康的HTTP返回码的组合。可选值为1~5的集合,1表示HTTP返回码为1xx认为健康。2表示HTTP返回码为2xx认为健康。3表示HTTP返回码为3xx认为健康。4表示HTTP返回码为4xx认为健康。5表示HTTP返回码为5xx认为健康。
* @type {Array.<number> || null}
*/
this.HttpCodes = null;
/**
* 均衡方式。
* @type {string || null}
*/
this.BalanceMode = null;
/**
* 当前绑定关系的健康检查状态(Dead代表不健康,Alive代表健康)。
* @type {number || null}
*/
this.Status = null;
/**
* 创建时间戳。
* @type {string || null}
*/
this.AddTimestamp = null;
/**
* 该转发路径所绑定的主机列表。
* @type {Array.<L7ListenerInfoBackend> || null}
*/
this.BackendSet = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.Url = 'Url' in params ? params.Url : null;
this.LocationId = 'LocationId' in params ? params.LocationId : null;
this.SessionExpire = 'SessionExpire' in params ? params.SessionExpire : null;
this.HealthSwitch = 'HealthSwitch' in params ? params.HealthSwitch : null;
this.HttpCheckPath = 'HttpCheckPath' in params ? params.HttpCheckPath : null;
this.HttpCheckDomain = 'HttpCheckDomain' in params ? params.HttpCheckDomain : null;
this.IntervalTime = 'IntervalTime' in params ? params.IntervalTime : null;
this.HealthNum = 'HealthNum' in params ? params.HealthNum : null;
this.UnhealthNum = 'UnhealthNum' in params ? params.UnhealthNum : null;
this.HttpCodes = 'HttpCodes' in params ? params.HttpCodes : null;
this.BalanceMode = 'BalanceMode' in params ? params.BalanceMode : null;
this.Status = 'Status' in params ? params.Status : null;
this.AddTimestamp = 'AddTimestamp' in params ? params.AddTimestamp : null;
if (params.BackendSet) {
this.BackendSet = new Array();
for (let z in params.BackendSet) {
let obj = new L7ListenerInfoBackend();
obj.deserialize(params.BackendSet[z]);
this.BackendSet.push(obj);
}
}
}
}
/**
* 获取七层转发规则时返回的转发域名下面的转发路径。
* @class
*/
class L7RulesLocation extends AbstractModel {
constructor(){
super();
/**
* 转发路径。
* @type {string || null}
*/
this.Url = null;
/**
* 转发路径实例ID。
* @type {string || null}
*/
this.LocationId = null;
/**
* 会话保持时间。
* @type {number || null}
*/
this.SessionExpire = null;
/**
* 是否开启健康检查。
* @type {number || null}
*/
this.HealthSwitch = null;
/**
* 健康检查检查路径。
* @type {string || null}
*/
this.HttpCheckPath = null;
/**
* 健康检查检查域名。
* @type {string || null}
*/
this.HttpCheckDomain = null;
/**
* 健康检查检查间隔时间。
* @type {number || null}
*/
this.IntervalTime = null;
/**
* 健康检查健康阈值。
* @type {number || null}
*/
this.HealthNum = null;
/**
* 健康检查不健康阈值。
* @type {number || null}
*/
this.UnhealthNum = null;
/**
* 健康检查中认为健康的HTTP返回码的组合。可选值为1~5的集合,1表示HTTP返回码为1xx认为健康。2表示HTTP返回码为2xx认为健康。3表示HTTP返回码为3xx认为健康。4表示HTTP返回码为4xx认为健康。5表示HTTP返回码为5xx认为健康。
* @type {Array.<number> || null}
*/
this.HttpCodes = null;
/**
* 均衡方式。
* @type {string || null}
*/
this.BalanceMode = null;
/**
* 转发路径当前状态(0代表创建中,1代表正常运行,2代表创建失败,3代表删除中,4代表删除失败)。
* @type {number || null}
*/
this.Status = null;
/**
* 创建时间戳。
* @type {string || null}
*/
this.AddTimestamp = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.Url = 'Url' in params ? params.Url : null;
this.LocationId = 'LocationId' in params ? params.LocationId : null;
this.SessionExpire = 'SessionExpire' in params ? params.SessionExpire : null;
this.HealthSwitch = 'HealthSwitch' in params ? params.HealthSwitch : null;
this.HttpCheckPath = 'HttpCheckPath' in params ? params.HttpCheckPath : null;
this.HttpCheckDomain = 'HttpCheckDomain' in params ? params.HttpCheckDomain : null;
this.IntervalTime = 'IntervalTime' in params ? params.IntervalTime : null;
this.HealthNum = 'HealthNum' in params ? params.HealthNum : null;
this.UnhealthNum = 'UnhealthNum' in params ? params.UnhealthNum : null;
this.HttpCodes = 'HttpCodes' in params ? params.HttpCodes : null;
this.BalanceMode = 'BalanceMode' in params ? params.BalanceMode : null;
this.Status = 'Status' in params ? params.Status : null;
this.AddTimestamp = 'AddTimestamp' in params ? params.AddTimestamp : null;
}
}
/**
* 修改负载均衡计费方式的监听器信息。
* @class
*/
class ModifyLoadBalancerChargeModeListener extends AbstractModel {
constructor(){
super();
/**
* 监听器ID。
* @type {string || null}
*/
this.ListenerId = null;
/**
* 协议类型。
* @type {string || null}
*/
this.Protocol = null;
/**
* 带宽。
* @type {number || null}
*/
this.Bandwidth = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.ListenerId = 'ListenerId' in params ? params.ListenerId : null;
this.Protocol = 'Protocol' in params ? params.Protocol : null;
this.Bandwidth = 'Bandwidth' in params ? params.Bandwidth : null;
}
}
/**
* 流量镜像健康检查返回的接收机状态信息。
* @class
*/
class TrafficMirrorReciversStatus extends AbstractModel {
constructor(){
super();
/**
* 内网IP。
* @type {string || null}
*/
this.LanIp = null;
/**
* 端口及对应的状态。
* @type {Array.<TrafficMirrorPortStatus> || null}
*/
this.ReceiversPortStatusSet = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LanIp = 'LanIp' in params ? params.LanIp : null;
if (params.ReceiversPortStatusSet) {
this.ReceiversPortStatusSet = new Array();
for (let z in params.ReceiversPortStatusSet) {
let obj = new TrafficMirrorPortStatus();
obj.deserialize(params.ReceiversPortStatusSet[z]);
this.ReceiversPortStatusSet.push(obj);
}
}
}
}
/**
* CreateLoadBalancers请求参数结构体
* @class
*/
class CreateLoadBalancersRequest extends AbstractModel {
constructor(){
super();
/**
* 黑石负载均衡实例所属的私有网络ID。
* @type {string || null}
*/
this.VpcId = null;
/**
* 负载均衡的类型,取值为open或internal。open表示公网(有日租),internal表示内网。
* @type {string || null}
*/
this.LoadBalancerType = null;
/**
* 在私有网络内购买内网负载均衡实例的时候需要指定子网ID,内网负载均衡实例的VIP将从这个子网中产生。其他情况不用填写该字段。
* @type {string || null}
*/
this.SubnetId = null;
/**
* 负载均衡所属项目ID。不填则属于默认项目。
* @type {number || null}
*/
this.ProjectId = null;
/**
* 购买黑石负载均衡实例的数量。默认值为1, 最大值为20。
* @type {number || null}
*/
this.GoodsNum = null;
/**
* 黑石负载均衡的计费模式,取值为flow和bandwidth,其中flow模式表示流量模式,bandwidth表示带宽模式。默认值为flow。
* @type {string || null}
*/
this.PayMode = null;
/**
* 负载均衡对应的TGW集群类别,取值为tunnel、fullnat或dnat。tunnel表示隧道集群,fullnat表示FULLNAT集群(普通外网负载均衡),dnat表示DNAT集群(增强型外网负载均衡)。默认值为fullnat。如需获取client IP,可以选择 tunnel 模式,fullnat 模式(tcp 通过toa 获取),dnat 模式。
* @type {string || null}
*/
this.TgwSetType = null;
/**
* 负载均衡的独占类别,取值为0表示非独占,1表示四层独占,2表示七层独占,3表示四层和七层独占,4表示共享容灾。
* @type {number || null}
*/
this.Exclusive = null;
/**
* 指定的VIP,如果指定,则数量必须与goodsNum一致。如果不指定,则由后台分配随机VIP。
* @type {Array.<string> || null}
*/
this.SpecifiedVips = null;
/**
* (未全地域开放)保障型负载均衡设定参数,如果类别选择保障型则需传入此参数。
* @type {CreateLoadBalancerBzConf || null}
*/
this.BzConf = null;
/**
* IP协议类型。可取的值为“ipv4”或“ipv6”。
* @type {string || null}
*/
this.IpProtocolType = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.VpcId = 'VpcId' in params ? params.VpcId : null;
this.LoadBalancerType = 'LoadBalancerType' in params ? params.LoadBalancerType : null;
this.SubnetId = 'SubnetId' in params ? params.SubnetId : null;
this.ProjectId = 'ProjectId' in params ? params.ProjectId : null;
this.GoodsNum = 'GoodsNum' in params ? params.GoodsNum : null;
this.PayMode = 'PayMode' in params ? params.PayMode : null;
this.TgwSetType = 'TgwSetType' in params ? params.TgwSetType : null;
this.Exclusive = 'Exclusive' in params ? params.Exclusive : null;
this.SpecifiedVips = 'SpecifiedVips' in params ? params.SpecifiedVips : null;
if (params.BzConf) {
let obj = new CreateLoadBalancerBzConf();
obj.deserialize(params.BzConf)
this.BzConf = obj;
}
this.IpProtocolType = 'IpProtocolType' in params ? params.IpProtocolType : null;
}
}
/**
* DescribeLoadBalancerPortInfo返回参数结构体
* @class
*/
class DescribeLoadBalancerPortInfoResponse extends AbstractModel {
constructor(){
super();
/**
* 返回的监听器列表(四层和七层)。
* @type {Array.<LoadBalancerPortInfoListener> || null}
*/
this.ListenerSet = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
if (params.ListenerSet) {
this.ListenerSet = new Array();
for (let z in params.ListenerSet) {
let obj = new LoadBalancerPortInfoListener();
obj.deserialize(params.ListenerSet[z]);
this.ListenerSet.push(obj);
}
}
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* DescribeL7ListenerInfo请求参数结构体
* @class
*/
class DescribeL7ListenerInfoRequest extends AbstractModel {
constructor(){
super();
/**
* 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。
* @type {string || null}
*/
this.LoadBalancerId = null;
/**
* 查找的键值,可用于模糊查找有该转发域名的监听器。
* @type {string || null}
*/
this.SearchKey = null;
/**
* 主机ID或虚机IP列表,可用于获取绑定了该主机的监听器。
* @type {Array.<string> || null}
*/
this.InstanceIds = null;
/**
* 是否获取转发规则下的主机信息。默认为0,不获取。
* @type {number || null}
*/
this.IfGetBackendInfo = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
this.SearchKey = 'SearchKey' in params ? params.SearchKey : null;
this.InstanceIds = 'InstanceIds' in params ? params.InstanceIds : null;
this.IfGetBackendInfo = 'IfGetBackendInfo' in params ? params.IfGetBackendInfo : null;
}
}
/**
* ModifyL4Listener请求参数结构体
* @class
*/
class ModifyL4ListenerRequest extends AbstractModel {
constructor(){
super();
/**
* 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。
* @type {string || null}
*/
this.LoadBalancerId = null;
/**
* 四层监听器ID。可通过接口DescribeL4Listeners查询。
* @type {string || null}
*/
this.ListenerId = null;
/**
* 四层监听器名称。
* @type {string || null}
*/
this.ListenerName = null;
/**
* 会话保持时间,单位:秒。可选值:900~3600。
* @type {number || null}
*/
this.SessionExpire = null;
/**
* 是否开启健康检查:1(开启)、0(关闭)。默认值0,表示关闭。
* @type {number || null}
*/
this.HealthSwitch = null;
/**
* 健康检查的响应超时时间,可选值:2-60,默认值:2,单位:秒。<br><font color="red">响应超时时间要小于检查间隔时间。</font>
* @type {number || null}
*/
this.TimeOut = null;
/**
* 健康检查间隔,默认值:5,可选值:5-300,单位:秒。
* @type {number || null}
*/
this.IntervalTime = null;
/**
* 健康阈值,默认值:3,表示当连续探测三次健康则表示该转发正常,可选值:2-10,单位:次。
* @type {number || null}
*/
this.HealthNum = null;
/**
* 不健康阈值,默认值:3,表示当连续探测三次不健康则表示该转发不正常,可选值:2-10,单位:次。
* @type {number || null}
*/
this.UnhealthNum = null;
/**
* 监听器最大带宽值,用于计费模式为固定带宽计费。可选值:0-1000,单位:Mbps。
* @type {number || null}
*/
this.Bandwidth = null;
/**
* 是否开启自定义健康检查:1(开启)、0(关闭)。默认值0,表示关闭。(该字段在健康检查开启的情况下才生效)
* @type {number || null}
*/
this.CustomHealthSwitch = null;
/**
* 自定义健康探测内容类型,可选值:text(文本)、hexadecimal(十六进制)。
* @type {string || null}
*/
this.InputType = null;
/**
* 探测内容类型为文本方式时,针对请求文本中换行替换方式。可选值:1(替换为LF)、2(替换为CR)、3(替换为LF+CR)。
* @type {number || null}
*/
this.LineSeparatorType = null;
/**
* 自定义探测请求内容。
* @type {string || null}
*/
this.HealthRequest = null;
/**
* 自定义探测返回内容。
* @type {string || null}
*/
this.HealthResponse = null;
/**
* 是否开启toa。可选值:0(关闭)、1(开启),默认关闭。(该字段在负载均衡为fullnat类型下才生效)
* @type {number || null}
*/
this.ToaFlag = null;
/**
* 四层调度方式。wrr,wlc。
* @type {string || null}
*/
this.BalanceMode = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
this.ListenerId = 'ListenerId' in params ? params.ListenerId : null;
this.ListenerName = 'ListenerName' in params ? params.ListenerName : null;
this.SessionExpire = 'SessionExpire' in params ? params.SessionExpire : null;
this.HealthSwitch = 'HealthSwitch' in params ? params.HealthSwitch : null;
this.TimeOut = 'TimeOut' in params ? params.TimeOut : null;
this.IntervalTime = 'IntervalTime' in params ? params.IntervalTime : null;
this.HealthNum = 'HealthNum' in params ? params.HealthNum : null;
this.UnhealthNum = 'UnhealthNum' in params ? params.UnhealthNum : null;
this.Bandwidth = 'Bandwidth' in params ? params.Bandwidth : null;
this.CustomHealthSwitch = 'CustomHealthSwitch' in params ? params.CustomHealthSwitch : null;
this.InputType = 'InputType' in params ? params.InputType : null;
this.LineSeparatorType = 'LineSeparatorType' in params ? params.LineSeparatorType : null;
this.HealthRequest = 'HealthRequest' in params ? params.HealthRequest : null;
this.HealthResponse = 'HealthResponse' in params ? params.HealthResponse : null;
this.ToaFlag = 'ToaFlag' in params ? params.ToaFlag : null;
this.BalanceMode = 'BalanceMode' in params ? params.BalanceMode : null;
}
}
/**
* 查询四层监听器返回的与监听器绑定关系的主机信息。
* @class
*/
class L4Backend extends AbstractModel {
constructor(){
super();
/**
* 绑定类别(0代表黑石物理机,1代表虚拟机IP)。
* @type {number || null}
*/
this.BindType = null;
/**
* 主机端口。
* @type {number || null}
*/
this.Port = null;
/**
* 权重。
* @type {number || null}
*/
this.Weight = null;
/**
* 当前绑定关系的健康检查状态(Dead代表不健康,Alive代表健康)。
* @type {string || null}
*/
this.Status = null;
/**
* 黑石物理机的主机ID。
* @type {string || null}
*/
this.InstanceId = null;
/**
* 黑石物理机的别名。
* @type {string || null}
*/
this.Alias = null;
/**
* 主机IP。
* @type {string || null}
*/
this.LanIp = null;
/**
* 黑石物理机当前可以执行的操作。
* @type {Array.<string> || null}
*/
this.Operates = null;
/**
* 主机探测端口。
* @type {number || null}
*/
this.ProbePort = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.BindType = 'BindType' in params ? params.BindType : null;
this.Port = 'Port' in params ? params.Port : null;
this.Weight = 'Weight' in params ? params.Weight : null;
this.Status = 'Status' in params ? params.Status : null;
this.InstanceId = 'InstanceId' in params ? params.InstanceId : null;
this.Alias = 'Alias' in params ? params.Alias : null;
this.LanIp = 'LanIp' in params ? params.LanIp : null;
this.Operates = 'Operates' in params ? params.Operates : null;
this.ProbePort = 'ProbePort' in params ? params.ProbePort : null;
}
}
/**
* 获取七层转发路径绑定的主机列表时返回的主机信息。
* @class
*/
class L7Backend extends AbstractModel {
constructor(){
super();
/**
* 绑定类别(0代表黑石物理机,1代表虚拟机IP)。
* @type {number || null}
*/
this.BindType = null;
/**
* 主机端口。
* @type {number || null}
*/
this.Port = null;
/**
* 权重。
* @type {number || null}
*/
this.Weight = null;
/**
* 当前绑定关系的健康检查状态(Dead代表不健康,Alive代表健康)。
* @type {string || null}
*/
this.Status = null;
/**
* 黑石物理机的主机ID。
* @type {string || null}
*/
this.InstanceId = null;
/**
* 黑石物理机的别名。
* @type {string || null}
*/
this.Alias = null;
/**
* 主机IP。
* @type {string || null}
*/
this.LanIp = null;
/**
* 黑石物理机的管理IP。
* @type {string || null}
*/
this.MgtIp = null;
/**
* 黑石物理机当前可以执行的操作。
* @type {Array.<string> || null}
*/
this.Operates = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.BindType = 'BindType' in params ? params.BindType : null;
this.Port = 'Port' in params ? params.Port : null;
this.Weight = 'Weight' in params ? params.Weight : null;
this.Status = 'Status' in params ? params.Status : null;
this.InstanceId = 'InstanceId' in params ? params.InstanceId : null;
this.Alias = 'Alias' in params ? params.Alias : null;
this.LanIp = 'LanIp' in params ? params.LanIp : null;
this.MgtIp = 'MgtIp' in params ? params.MgtIp : null;
this.Operates = 'Operates' in params ? params.Operates : null;
}
}
/**
* 修改黑石负载均衡七层转发路径时待修改的七层转发规则信息。
* @class
*/
class ModifyL7LocationRule extends AbstractModel {
constructor(){
super();
/**
* 转发域名实例ID,可通过接口DescribeL7Rules查询。
* @type {string || null}
*/
this.DomainId = null;
/**
* 转发路径实例ID,可通过接口DescribeL7Rules查询。
* @type {string || null}
*/
this.LocationId = null;
/**
* 转发路径。
* @type {string || null}
*/
this.Url = null;
/**
* 会话保持时间,单位:秒。可选值:30~3600。默认值0,表示不开启会话保持。
* @type {number || null}
*/
this.SessionExpire = null;
/**
* 健康检查开关:1(开启)、0(关闭)。默认值0,表示关闭。
* @type {number || null}
*/
this.HealthSwitch = null;
/**
* 健康检查检查间隔时间,默认值:5,可选值:5-300,单位:秒。
* @type {number || null}
*/
this.IntervalTime = null;
/**
* 健康检查健康阈值,默认值:3,表示当连续探测三次健康则表示该转发正常,可选值:2-10,单位:次。
* @type {number || null}
*/
this.HealthNum = null;
/**
* 健康检查不健康阈值,默认值:5,表示当连续探测五次不健康则表示该转发不正常,可选值:2-10,单位:次。
* @type {number || null}
*/
this.UnhealthNum = null;
/**
* 健康检查中认为健康的HTTP返回码的组合。可选值为1~5的集合,1表示HTTP返回码为1xx认为健康。2表示HTTP返回码为2xx认为健康。3表示HTTP返回码为3xx认为健康。4表示HTTP返回码为4xx认为健康。5表示HTTP返回码为5xx认为健康。
* @type {Array.<number> || null}
*/
this.HttpCodes = null;
/**
* 健康检查检查路径。
* @type {string || null}
*/
this.HttpCheckPath = null;
/**
* 健康检查检查域名。如果规则的域名使用通配符或正则表达式,则健康检查检查域名可自定义,否则必须跟健康检查检查域名一样。不填表示不修改。
* @type {string || null}
*/
this.HttpCheckDomain = null;
/**
* 均衡方式:ip_hash、wrr。默认值wrr。
* @type {string || null}
*/
this.BalanceMode = null;
/**
* 转发域名。
* @type {string || null}
*/
this.Domain = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.DomainId = 'DomainId' in params ? params.DomainId : null;
this.LocationId = 'LocationId' in params ? params.LocationId : null;
this.Url = 'Url' in params ? params.Url : null;
this.SessionExpire = 'SessionExpire' in params ? params.SessionExpire : null;
this.HealthSwitch = 'HealthSwitch' in params ? params.HealthSwitch : null;
this.IntervalTime = 'IntervalTime' in params ? params.IntervalTime : null;
this.HealthNum = 'HealthNum' in params ? params.HealthNum : null;
this.UnhealthNum = 'UnhealthNum' in params ? params.UnhealthNum : null;
this.HttpCodes = 'HttpCodes' in params ? params.HttpCodes : null;
this.HttpCheckPath = 'HttpCheckPath' in params ? params.HttpCheckPath : null;
this.HttpCheckDomain = 'HttpCheckDomain' in params ? params.HttpCheckDomain : null;
this.BalanceMode = 'BalanceMode' in params ? params.BalanceMode : null;
this.Domain = 'Domain' in params ? params.Domain : null;
}
}
/**
* ModifyLoadBalancer请求参数结构体
* @class
*/
class ModifyLoadBalancerRequest extends AbstractModel {
constructor(){
super();
/**
* 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。
* @type {string || null}
*/
this.LoadBalancerId = null;
/**
* 负载均衡器名称,规则:1-20个英文、汉字、数字、连接线“-”或下划线“_”。
* @type {string || null}
*/
this.LoadBalancerName = null;
/**
* 域名前缀,负载均衡的域名由用户输入的域名前缀与配置文件中的域名后缀一起组合而成,保证是唯一的域名。规则:1-20个小写英文字母、数字或连接线“-”。内网类型的负载均衡不能配置该字段。
* @type {string || null}
*/
this.DomainPrefix = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
this.LoadBalancerName = 'LoadBalancerName' in params ? params.LoadBalancerName : null;
this.DomainPrefix = 'DomainPrefix' in params ? params.DomainPrefix : null;
}
}
/**
* 获取设备绑定信息时返回的七层监听器信息。
* @class
*/
class DevicesBindInfoL7Listener extends AbstractModel {
constructor(){
super();
/**
* 七层监听器实例ID。
* @type {string || null}
*/
this.ListenerId = null;
/**
* 七层监听器协议类型,可选值:http,https。
* @type {string || null}
*/
this.Protocol = null;
/**
* 七层监听器的监听端口。
* @type {number || null}
*/
this.LoadBalancerPort = null;
/**
* 返回的转发规则列表。
* @type {Array.<DevicesBindInfoRule> || null}
*/
this.RuleSet = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.ListenerId = 'ListenerId' in params ? params.ListenerId : null;
this.Protocol = 'Protocol' in params ? params.Protocol : null;
this.LoadBalancerPort = 'LoadBalancerPort' in params ? params.LoadBalancerPort : null;
if (params.RuleSet) {
this.RuleSet = new Array();
for (let z in params.RuleSet) {
let obj = new DevicesBindInfoRule();
obj.deserialize(params.RuleSet[z]);
this.RuleSet.push(obj);
}
}
}
}
/**
* DescribeL4Listeners请求参数结构体
* @class
*/
class DescribeL4ListenersRequest extends AbstractModel {
constructor(){
super();
/**
* 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。
* @type {string || null}
*/
this.LoadBalancerId = null;
/**
* 四层监听器实例ID数组,可通过接口DescribeL4Listeners查询。
* @type {Array.<string> || null}
*/
this.ListenerIds = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
this.ListenerIds = 'ListenerIds' in params ? params.ListenerIds : null;
}
}
/**
* CreateL7Listeners返回参数结构体
* @class
*/
class CreateL7ListenersResponse extends AbstractModel {
constructor(){
super();
/**
* 新建的负载均衡七层监听器的唯一ID列表。
* @type {Array.<string> || null}
*/
this.ListenerIds = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.ListenerIds = 'ListenerIds' in params ? params.ListenerIds : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* 用于创建负载均衡的个性化配置。
* @class
*/
class CreateLoadBalancerBzConf extends AbstractModel {
constructor(){
super();
/**
* 按月/按小时计费。
* @type {string || null}
*/
this.BzPayMode = null;
/**
* 四层可选按带宽,连接数衡量。
* @type {string || null}
*/
this.BzL4Metrics = null;
/**
* 七层可选按qps衡量。
* @type {string || null}
*/
this.BzL7Metrics = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.BzPayMode = 'BzPayMode' in params ? params.BzPayMode : null;
this.BzL4Metrics = 'BzL4Metrics' in params ? params.BzL4Metrics : null;
this.BzL7Metrics = 'BzL7Metrics' in params ? params.BzL7Metrics : null;
}
}
/**
* DeleteTrafficMirror请求参数结构体
* @class
*/
class DeleteTrafficMirrorRequest extends AbstractModel {
constructor(){
super();
/**
* 流量镜像实例ID数组,可以批量删除,每次删除上限为20
* @type {Array.<string> || null}
*/
this.TrafficMirrorIds = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TrafficMirrorIds = 'TrafficMirrorIds' in params ? params.TrafficMirrorIds : null;
}
}
/**
* CreateL7Listeners请求参数结构体
* @class
*/
class CreateL7ListenersRequest extends AbstractModel {
constructor(){
super();
/**
* 负载均衡实例ID
* @type {string || null}
*/
this.LoadBalancerId = null;
/**
* 七层监听器信息数组,可以创建多个七层监听器。目前一个负载均衡下面最多允许创建50个七层监听器。
* @type {Array.<CreateL7Listener> || null}
*/
this.ListenerSet = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
if (params.ListenerSet) {
this.ListenerSet = new Array();
for (let z in params.ListenerSet) {
let obj = new CreateL7Listener();
obj.deserialize(params.ListenerSet[z]);
this.ListenerSet.push(obj);
}
}
}
}
/**
* 待与四层监听器绑定的物理机主机、虚拟机或半托管主机信息。目前一个四层监听器下面最多允许绑定255个主机端口。
* @class
*/
class BindL4Backend extends AbstractModel {
constructor(){
super();
/**
* 待绑定的主机端口,可选值1~65535。
* @type {number || null}
*/
this.Port = null;
/**
* 待绑定的黑石物理机主机ID、虚拟机IP或者是半托管主机ID。
* @type {string || null}
*/
this.InstanceId = null;
/**
* 待绑定的主机权重,可选值0~100。
* @type {number || null}
*/
this.Weight = null;
/**
* 自定义探测的主机端口,可选值1~65535。(需要监听器开启自定义健康检查)
* @type {number || null}
*/
this.ProbePort = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.Port = 'Port' in params ? params.Port : null;
this.InstanceId = 'InstanceId' in params ? params.InstanceId : null;
this.Weight = 'Weight' in params ? params.Weight : null;
this.ProbePort = 'ProbePort' in params ? params.ProbePort : null;
}
}
/**
* DescribeL7ListenersEx请求参数结构体
* @class
*/
class DescribeL7ListenersExRequest extends AbstractModel {
constructor(){
super();
/**
* 返回的监听器中标识是否绑定在此流量镜像中。
* @type {string || null}
*/
this.TrafficMirrorId = null;
/**
* 待获取监听器所在的VPC的ID。
* @type {string || null}
*/
this.VpcId = null;
/**
* 此VPC中获取负载均衡的偏移。
* @type {number || null}
*/
this.Offset = null;
/**
* 此VPC中获取负载均衡的数量。
* @type {number || null}
*/
this.Limit = null;
/**
* 过滤条件。
LoadBalancerId - String - (过滤条件)负载均衡ID。
LoadBalancerName - String - (过滤条件)负载均衡名称。
Vip - String - (过滤条件)VIP。
ListenerId - String - (过滤条件)监听器ID。
ListenerName - String - (过滤条件)监听器名称。
Protocol - String - (过滤条件)七层协议。
LoadBalancerPort - String - (过滤条件)监听器端口。
* @type {Array.<Filter> || null}
*/
this.Filters = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TrafficMirrorId = 'TrafficMirrorId' in params ? params.TrafficMirrorId : null;
this.VpcId = 'VpcId' in params ? params.VpcId : null;
this.Offset = 'Offset' in params ? params.Offset : null;
this.Limit = 'Limit' in params ? params.Limit : null;
if (params.Filters) {
this.Filters = new Array();
for (let z in params.Filters) {
let obj = new Filter();
obj.deserialize(params.Filters[z]);
this.Filters.push(obj);
}
}
}
}
/**
* DescribeLoadBalancerTaskResult返回参数结构体
* @class
*/
class DescribeLoadBalancerTaskResultResponse extends AbstractModel {
constructor(){
super();
/**
* 任务当前状态。0:成功,1:失败,2:进行中。
* @type {number || null}
*/
this.Status = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.Status = 'Status' in params ? params.Status : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* UnbindTrafficMirrorReceivers请求参数结构体
* @class
*/
class UnbindTrafficMirrorReceiversRequest extends AbstractModel {
constructor(){
super();
/**
* 流量镜像实例ID。
* @type {string || null}
*/
this.TrafficMirrorId = null;
/**
* 待绑定的主机实例ID和端口数组。
* @type {Array.<UnbindTrafficMirrorReceiver> || null}
*/
this.ReceiverSet = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TrafficMirrorId = 'TrafficMirrorId' in params ? params.TrafficMirrorId : null;
if (params.ReceiverSet) {
this.ReceiverSet = new Array();
for (let z in params.ReceiverSet) {
let obj = new UnbindTrafficMirrorReceiver();
obj.deserialize(params.ReceiverSet[z]);
this.ReceiverSet.push(obj);
}
}
}
}
/**
* UnbindTrafficMirrorListeners请求参数结构体
* @class
*/
class UnbindTrafficMirrorListenersRequest extends AbstractModel {
constructor(){
super();
/**
* 流量镜像实例ID。
* @type {string || null}
*/
this.TrafficMirrorId = null;
/**
* 七层监听器实例ID数组,可通过接口DescribeL7Listeners查询。
* @type {Array.<string> || null}
*/
this.ListenerIds = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TrafficMirrorId = 'TrafficMirrorId' in params ? params.TrafficMirrorId : null;
this.ListenerIds = 'ListenerIds' in params ? params.ListenerIds : null;
}
}
/**
* DescribeCertDetail请求参数结构体
* @class
*/
class DescribeCertDetailRequest extends AbstractModel {
constructor(){
super();
/**
* 证书ID。
* @type {string || null}
*/
this.CertId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.CertId = 'CertId' in params ? params.CertId : null;
}
}
/**
* DescribeDevicesBindInfo返回参数结构体
* @class
*/
class DescribeDevicesBindInfoResponse extends AbstractModel {
constructor(){
super();
/**
* 返回的负载均衡绑定信息。
* @type {Array.<DevicesBindInfoLoadBalancer> || null}
*/
this.LoadBalancerSet = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
if (params.LoadBalancerSet) {
this.LoadBalancerSet = new Array();
for (let z in params.LoadBalancerSet) {
let obj = new DevicesBindInfoLoadBalancer();
obj.deserialize(params.LoadBalancerSet[z]);
this.LoadBalancerSet.push(obj);
}
}
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* 获取黑石负载均衡端口相关信息时返回的监听器信息(四层和七层)。
* @class
*/
class LoadBalancerPortInfoListener extends AbstractModel {
constructor(){
super();
/**
* 负载均衡监听器ID。
* @type {string || null}
*/
this.ListenerId = null;
/**
* 监听器名称。
* @type {string || null}
*/
this.ListenerName = null;
/**
* 监听器协议类型,可选值:http,https,tcp,udp。
* @type {string || null}
*/
this.Protocol = null;
/**
* 监听器的监听端口。
* @type {number || null}
*/
this.LoadBalancerPort = null;
/**
* 计费模式为按固定带宽方式时监听器的限速值,单位:Mbps。
* @type {number || null}
*/
this.Bandwidth = null;
/**
* 监听器当前状态(0代表创建中,1代表正常运行,2代表创建失败,3代表删除中,4代表删除失败)。
* @type {number || null}
*/
this.Status = null;
/**
* 与监听器绑定的主机端口。
* @type {number || null}
*/
this.Port = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.ListenerId = 'ListenerId' in params ? params.ListenerId : null;
this.ListenerName = 'ListenerName' in params ? params.ListenerName : null;
this.Protocol = 'Protocol' in params ? params.Protocol : null;
this.LoadBalancerPort = 'LoadBalancerPort' in params ? params.LoadBalancerPort : null;
this.Bandwidth = 'Bandwidth' in params ? params.Bandwidth : null;
this.Status = 'Status' in params ? params.Status : null;
this.Port = 'Port' in params ? params.Port : null;
}
}
/**
* DescribeL4Backends返回参数结构体
* @class
*/
class DescribeL4BackendsResponse extends AbstractModel {
constructor(){
super();
/**
* 返回的绑定关系列表。
* @type {Array.<L4Backend> || null}
*/
this.BackendSet = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
if (params.BackendSet) {
this.BackendSet = new Array();
for (let z in params.BackendSet) {
let obj = new L4Backend();
obj.deserialize(params.BackendSet[z]);
this.BackendSet.push(obj);
}
}
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* 用于创建四层监听器的监听器信息。目前一个负载均衡下面最多允许创建50个监听器。
* @class
*/
class CreateL4Listener extends AbstractModel {
constructor(){
super();
/**
* 监听器监听端口,可选值1~65535。
* @type {number || null}
*/
this.LoadBalancerPort = null;
/**
* 监听器协议类型,可选值tcp,udp。
* @type {string || null}
*/
this.Protocol = null;
/**
* 监听器名称。
* @type {string || null}
*/
this.ListenerName = null;
/**
* 监听器的会话保持时间,单位:秒。可选值:900~3600,不传表示不开启会话保持。
* @type {number || null}
*/
this.SessionExpire = null;
/**
* 是否开启健康检查:1(开启)、0(关闭)。默认值0,表示关闭。
* @type {number || null}
*/
this.HealthSwitch = null;
/**
* 健康检查的响应超时时间,可选值:2-60,默认值:2,单位:秒。<br><font color="red">响应超时时间要小于检查间隔时间。</font>
* @type {number || null}
*/
this.TimeOut = null;
/**
* 健康检查检查间隔时间,默认值:5,可选值:5-300,单位:秒。
* @type {number || null}
*/
this.IntervalTime = null;
/**
* 健康阈值,默认值:3,表示当连续探测三次健康则表示该转发正常,可选值:2-10,单位:次。
* @type {number || null}
*/
this.HealthNum = null;
/**
* 不健康阈值,默认值:3,表示当连续探测三次不健康则表示该转发不正常,可选值:2-10,单位:次。
* @type {number || null}
*/
this.UnhealthNum = null;
/**
* 监听器最大带宽值,用于计费模式为固定带宽计费,可选值:0-1000,单位:Mbps。
* @type {number || null}
*/
this.Bandwidth = null;
/**
* 是否开启自定义健康检查:1(开启)、0(关闭)。默认值0,表示关闭。(该字段在健康检查开启的情况下才生效)
* @type {number || null}
*/
this.CustomHealthSwitch = null;
/**
* 自定义健康探测内容类型,可选值:text(文本)、hexadecimal(十六进制)。
* @type {string || null}
*/
this.InputType = null;
/**
* 探测内容类型为文本方式时,针对请求文本中换行替换方式。可选值:1(替换为LF)、2(替换为CR)、3(替换为LF+CR)。
* @type {number || null}
*/
this.LineSeparatorType = null;
/**
* 自定义探测请求内容。
* @type {string || null}
*/
this.HealthRequest = null;
/**
* 自定义探测返回内容。
* @type {string || null}
*/
this.HealthResponse = null;
/**
* 是否开启toa。可选值:0(关闭)、1(开启),默认关闭。(该字段在负载均衡为fullnat类型下才生效)
* @type {number || null}
*/
this.ToaFlag = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerPort = 'LoadBalancerPort' in params ? params.LoadBalancerPort : null;
this.Protocol = 'Protocol' in params ? params.Protocol : null;
this.ListenerName = 'ListenerName' in params ? params.ListenerName : null;
this.SessionExpire = 'SessionExpire' in params ? params.SessionExpire : null;
this.HealthSwitch = 'HealthSwitch' in params ? params.HealthSwitch : null;
this.TimeOut = 'TimeOut' in params ? params.TimeOut : null;
this.IntervalTime = 'IntervalTime' in params ? params.IntervalTime : null;
this.HealthNum = 'HealthNum' in params ? params.HealthNum : null;
this.UnhealthNum = 'UnhealthNum' in params ? params.UnhealthNum : null;
this.Bandwidth = 'Bandwidth' in params ? params.Bandwidth : null;
this.CustomHealthSwitch = 'CustomHealthSwitch' in params ? params.CustomHealthSwitch : null;
this.InputType = 'InputType' in params ? params.InputType : null;
this.LineSeparatorType = 'LineSeparatorType' in params ? params.LineSeparatorType : null;
this.HealthRequest = 'HealthRequest' in params ? params.HealthRequest : null;
this.HealthResponse = 'HealthResponse' in params ? params.HealthResponse : null;
this.ToaFlag = 'ToaFlag' in params ? params.ToaFlag : null;
}
}
/**
* DescribeTrafficMirrorListeners返回参数结构体
* @class
*/
class DescribeTrafficMirrorListenersResponse extends AbstractModel {
constructor(){
super();
/**
* 监听器列表。
* @type {Array.<TrafficMirrorListener> || null}
*/
this.ListenerSet = null;
/**
* 监听器总数。
* @type {number || null}
*/
this.TotalCount = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
if (params.ListenerSet) {
this.ListenerSet = new Array();
for (let z in params.ListenerSet) {
let obj = new TrafficMirrorListener();
obj.deserialize(params.ListenerSet[z]);
this.ListenerSet.push(obj);
}
}
this.TotalCount = 'TotalCount' in params ? params.TotalCount : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* DescribeLoadBalancers返回参数结构体
* @class
*/
class DescribeLoadBalancersResponse extends AbstractModel {
constructor(){
super();
/**
* 返回负载均衡信息列表。
* @type {Array.<LoadBalancer> || null}
*/
this.LoadBalancerSet = null;
/**
* 符合条件的负载均衡总数。
* @type {number || null}
*/
this.TotalCount = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
if (params.LoadBalancerSet) {
this.LoadBalancerSet = new Array();
for (let z in params.LoadBalancerSet) {
let obj = new LoadBalancer();
obj.deserialize(params.LoadBalancerSet[z]);
this.LoadBalancerSet.push(obj);
}
}
this.TotalCount = 'TotalCount' in params ? params.TotalCount : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* DeleteL7Rules返回参数结构体
* @class
*/
class DeleteL7RulesResponse extends AbstractModel {
constructor(){
super();
/**
* 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。
* @type {string || null}
*/
this.TaskId = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TaskId = 'TaskId' in params ? params.TaskId : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* 获取证书信息时返回的所用在的负载均衡信息。
* @class
*/
class CertDetailLoadBalancer extends AbstractModel {
constructor(){
super();
/**
* 黑石负载均衡实例ID。
* @type {string || null}
*/
this.LoadBalancerId = null;
/**
* 黑石负载均衡实例名称。
* @type {string || null}
*/
this.LoadBalancerName = null;
/**
* 该黑石负载均衡所在的VpcId。
* @type {string || null}
*/
this.VpcId = null;
/**
* 该黑石负载均衡所在的regionId。
* @type {number || null}
*/
this.RegionId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
this.LoadBalancerName = 'LoadBalancerName' in params ? params.LoadBalancerName : null;
this.VpcId = 'VpcId' in params ? params.VpcId : null;
this.RegionId = 'RegionId' in params ? params.RegionId : null;
}
}
/**
* DescribeTrafficMirrorReceivers请求参数结构体
* @class
*/
class DescribeTrafficMirrorReceiversRequest extends AbstractModel {
constructor(){
super();
/**
* 流量镜像实例ID。
* @type {string || null}
*/
this.TrafficMirrorId = null;
/**
* 接收机黑石物理机实例ID数组。
* @type {Array.<string> || null}
*/
this.InstanceIds = null;
/**
* 接收机接收端口数组。
* @type {Array.<number> || null}
*/
this.Ports = null;
/**
* 接收机实例权重数组。
* @type {Array.<number> || null}
*/
this.Weights = null;
/**
* 分页的偏移量,也即从第几条记录开始查询
* @type {number || null}
*/
this.Offset = null;
/**
* 单次查询返回的条目数,默认值:500。
* @type {number || null}
*/
this.Limit = null;
/**
* 搜索instance或者alias
* @type {string || null}
*/
this.VagueStr = null;
/**
* 搜索IP
* @type {string || null}
*/
this.VagueIp = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TrafficMirrorId = 'TrafficMirrorId' in params ? params.TrafficMirrorId : null;
this.InstanceIds = 'InstanceIds' in params ? params.InstanceIds : null;
this.Ports = 'Ports' in params ? params.Ports : null;
this.Weights = 'Weights' in params ? params.Weights : null;
this.Offset = 'Offset' in params ? params.Offset : null;
this.Limit = 'Limit' in params ? params.Limit : null;
this.VagueStr = 'VagueStr' in params ? params.VagueStr : null;
this.VagueIp = 'VagueIp' in params ? params.VagueIp : null;
}
}
/**
* SetTrafficMirrorAlias请求参数结构体
* @class
*/
class SetTrafficMirrorAliasRequest extends AbstractModel {
constructor(){
super();
/**
* 流量镜像实例ID。
* @type {string || null}
*/
this.TrafficMirrorId = null;
/**
* 流量镜像实例别名。
* @type {string || null}
*/
this.Alias = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TrafficMirrorId = 'TrafficMirrorId' in params ? params.TrafficMirrorId : null;
this.Alias = 'Alias' in params ? params.Alias : null;
}
}
/**
* UnbindL4Backends返回参数结构体
* @class
*/
class UnbindL4BackendsResponse extends AbstractModel {
constructor(){
super();
/**
* 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。
* @type {string || null}
*/
this.TaskId = null;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
* @type {string || null}
*/
this.RequestId = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.TaskId = 'TaskId' in params ? params.TaskId : null;
this.RequestId = 'RequestId' in params ? params.RequestId : null;
}
}
/**
* 查询绑定了某主机七层监听器时返回的与转发路径所绑定的主机信息。
* @class
*/
class L7ListenerInfoBackend extends AbstractModel {
constructor(){
super();
/**
* 绑定类别(0代表黑石物理机,1代表虚拟机IP)。
* @type {number || null}
*/
this.BindType = null;
/**
* 主机端口。
* @type {number || null}
*/
this.Port = null;
/**
* 权重。
* @type {number || null}
*/
this.Weight = null;
/**
* 当前绑定关系的健康检查状态(Dead代表不健康,Alive代表健康)。
* @type {string || null}
*/
this.Status = null;
/**
* 黑石物理机的主机ID。
* @type {string || null}
*/
this.InstanceId = null;
/**
* 黑石物理机的别名。
* @type {string || null}
*/
this.Alias = null;
/**
* 主机IP。
* @type {string || null}
*/
this.LanIp = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.BindType = 'BindType' in params ? params.BindType : null;
this.Port = 'Port' in params ? params.Port : null;
this.Weight = 'Weight' in params ? params.Weight : null;
this.Status = 'Status' in params ? params.Status : null;
this.InstanceId = 'InstanceId' in params ? params.InstanceId : null;
this.Alias = 'Alias' in params ? params.Alias : null;
this.LanIp = 'LanIp' in params ? params.LanIp : null;
}
}
/**
* ModifyLoadBalancerChargeMode请求参数结构体
* @class
*/
class ModifyLoadBalancerChargeModeRequest extends AbstractModel {
constructor(){
super();
/**
* 负载均衡实例ID。
* @type {string || null}
*/
this.LoadBalancerId = null;
/**
* 计费方式。flow或bandwidth。
* @type {string || null}
*/
this.PayMode = null;
/**
* 监听器信息,当计费方式选为 bandwidth 且此负载均衡实例下存在监听器时需填入此字段,可以自定义每个监听器带宽上限。
* @type {Array.<ModifyLoadBalancerChargeModeListener> || null}
*/
this.ListenerSet = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
this.PayMode = 'PayMode' in params ? params.PayMode : null;
if (params.ListenerSet) {
this.ListenerSet = new Array();
for (let z in params.ListenerSet) {
let obj = new ModifyLoadBalancerChargeModeListener();
obj.deserialize(params.ListenerSet[z]);
this.ListenerSet.push(obj);
}
}
}
}
/**
* ModifyL4BackendWeight请求参数结构体
* @class
*/
class ModifyL4BackendWeightRequest extends AbstractModel {
constructor(){
super();
/**
* 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。
* @type {string || null}
*/
this.LoadBalancerId = null;
/**
* 负载均衡四层监听器ID,可通过接口DescribeL4Listeners查询。
* @type {string || null}
*/
this.ListenerId = null;
/**
* 黑石物理机主机ID、虚拟机IP或者是半托管主机ID。
* @type {string || null}
*/
this.InstanceId = null;
/**
* 权重信息,可选值0~100。
* @type {number || null}
*/
this.Weight = null;
/**
* 已绑定的主机端口。
* @type {number || null}
*/
this.Port = null;
/**
* 绑定类型。0:物理机 1:虚拟机 2:半托管机器
* @type {number || null}
*/
this.BindType = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
this.ListenerId = 'ListenerId' in params ? params.ListenerId : null;
this.InstanceId = 'InstanceId' in params ? params.InstanceId : null;
this.Weight = 'Weight' in params ? params.Weight : null;
this.Port = 'Port' in params ? params.Port : null;
this.BindType = 'BindType' in params ? params.BindType : null;
}
}
/**
* 获取负载均衡实例列表时返回的负载均衡信息。
* @class
*/
class LoadBalancer extends AbstractModel {
constructor(){
super();
/**
* 负载均衡器ID
* @type {string || null}
*/
this.LoadBalancerId = null;
/**
* 项目ID,通过v2/DescribeProject 接口获得
* @type {number || null}
*/
this.ProjectId = null;
/**
* 负载均衡器名称
* @type {string || null}
*/
this.LoadBalancerName = null;
/**
* 负载均衡的类型 : open表示公网负载均衡类型,internal表示内网负载均衡类型
* @type {string || null}
*/
this.LoadBalancerType = null;
/**
* 是否筛选独占集群,0表示非独占集群,1表示四层独占集群,2表示七层独占集群,3表示四层和七层独占集群,4表示共享容灾
* @type {number || null}
*/
this.Exclusive = null;
/**
* 该负载均衡对应的tgw集群(fullnat,tunnel,dnat)
* @type {string || null}
*/
this.TgwSetType = null;
/**
* 负载均衡域名。规则:1-60个小写英文字母、数字、点号“.”或连接线“-”。内网类型的负载均衡不能配置该字段
* @type {string || null}
*/
this.Domain = null;
/**
* 该负载均衡对应的所在的VpcId
* @type {string || null}
*/
this.VpcId = null;
/**
* 该负载均衡对应的所在的SubnetId
* @type {string || null}
*/
this.SubnetId = null;
/**
* 无
* @type {number || null}
*/
this.Status = null;
/**
* 无
* @type {string || null}
*/
this.PayMode = null;
/**
* 无
* @type {string || null}
*/
this.LatestPayMode = null;
/**
* 无
* @type {string || null}
*/
this.CreateTime = null;
/**
* 无
* @type {string || null}
*/
this.StatusTime = null;
/**
* 私有网络名称。
* @type {string || null}
*/
this.VpcName = null;
/**
* 私有网络Cidr。
* @type {string || null}
*/
this.VpcCidrBlock = null;
/**
* 负载均衡的IPV4的VIP。
* @type {Array.<string> || null}
*/
this.LoadBalancerVips = null;
/**
* 无
* @type {Array.<string> || null}
*/
this.SupportListenerTypes = null;
/**
* 无
* @type {number || null}
*/
this.Bandwidth = null;
/**
* 负载均衡个性化配置ID
* @type {string || null}
*/
this.ConfId = null;
/**
* 无
* @type {string || null}
*/
this.ConfName = null;
/**
* 负载均衡的IPV6的VIP。
* @type {Array.<string> || null}
*/
this.LoadBalancerVipv6s = null;
/**
* 负载均衡IP协议类型。ipv4或者ipv6。
* @type {string || null}
*/
this.IpProtocolType = null;
/**
* 保障型网关计费形式
* @type {string || null}
*/
this.BzPayMode = null;
/**
* 保障型网关四层计费指标
* @type {string || null}
*/
this.BzL4Metrics = null;
/**
* 保障型网关七层计费指标
* @type {string || null}
*/
this.BzL7Metrics = null;
/**
* 该负载均衡对应的所在的整形类型的VpcId
* @type {number || null}
*/
this.IntVpcId = null;
/**
* 负载均衡的IPV6或者IPV4的VIP。
注意:此字段可能返回 null,表示取不到有效值。
* @type {Array.<string> || null}
*/
this.CurVips = null;
}
/**
* @private
*/
deserialize(params) {
if (!params) {
return;
}
this.LoadBalancerId = 'LoadBalancerId' in params ? params.LoadBalancerId : null;
this.ProjectId = 'ProjectId' in params ? params.ProjectId : null;
this.LoadBalancerName = 'LoadBalancerName' in params ? params.LoadBalancerName : null;
this.LoadBalancerType = 'LoadBalancerType' in params ? params.LoadBalancerType : null;
this.Exclusive = 'Exclusive' in params ? params.Exclusive : null;
this.TgwSetType = 'TgwSetType' in params ? params.TgwSetType : null;
this.Domain = 'Domain' in params ? params.Domain : null;
this.VpcId = 'VpcId' in params ? params.VpcId : null;
this.SubnetId = 'SubnetId' in params ? params.SubnetId : null;
this.Status = 'Status' in params ? params.Status : null;
this.PayMode = 'PayMode' in params ? params.PayMode : null;
this.LatestPayMode = 'LatestPayMode' in params ? params.LatestPayMode : null;
this.CreateTime = 'CreateTime' in params ? params.CreateTime : null;
this.StatusTime = 'StatusTime' in params ? params.StatusTime : null;
this.VpcName = 'VpcName' in params ? params.VpcName : null;
this.VpcCidrBlock = 'VpcCidrBlock' in params ? params.VpcCidrBlock : null;
this.LoadBalancerVips = 'LoadBalancerVips' in params ? params.LoadBalancerVips : null;
this.SupportListenerTypes = 'SupportListenerTypes' in params ? params.SupportListenerTypes : null;
this.Bandwidth = 'Bandwidth' in params ? params.Bandwidth : null;
this.ConfId = 'ConfId' in params ? params.ConfId : null;
this.ConfName = 'ConfName' in params ? params.ConfName : null;
this.LoadBalancerVipv6s = 'LoadBalancerVipv6s' in params ? params.LoadBalancerVipv6s : null;
this.IpProtocolType = 'IpProtocolType' in params ? params.IpProtocolType : null;
this.BzPayMode = 'BzPayMode' in params ? params.BzPayMode : null;
this.BzL4Metrics = 'BzL4Metrics' in params ? params.BzL4Metrics : null;
this.BzL7Metrics = 'BzL7Metrics' in params ? params.BzL7Metrics : null;
this.IntVpcId = 'IntVpcId' in params ? params.IntVpcId : null;
this.CurVips = 'CurVips' in params ? params.CurVips : null;
}
}
module.exports = {
SetTrafficMirrorHealthSwitchRequest: SetTrafficMirrorHealthSwitchRequest,
SetTrafficMirrorAliasResponse: SetTrafficMirrorAliasResponse,
DeleteL7RulesRequest: DeleteL7RulesRequest,
DeleteTrafficMirrorResponse: DeleteTrafficMirrorResponse,
ModifyL7BackendPortResponse: ModifyL7BackendPortResponse,
ModifyL4BackendProbePortResponse: ModifyL4BackendProbePortResponse,
BindTrafficMirrorReceiver: BindTrafficMirrorReceiver,
ModifyL4BackendPortResponse: ModifyL4BackendPortResponse,
ModifyL7LocationsResponse: ModifyL7LocationsResponse,
DescribeTrafficMirrorReceiverHealthStatusRequest: DescribeTrafficMirrorReceiverHealthStatusRequest,
UnbindL4Backend: UnbindL4Backend,
ModifyL4ListenerResponse: ModifyL4ListenerResponse,
DevicesBindInfoL4Listener: DevicesBindInfoL4Listener,
DescribeL4ListenerInfoRequest: DescribeL4ListenerInfoRequest,
L4ListenerInfo: L4ListenerInfo,
DescribeL7RulesRequest: DescribeL7RulesRequest,
UnbindL7BackendsResponse: UnbindL7BackendsResponse,
ModifyL4BackendWeightResponse: ModifyL4BackendWeightResponse,
DeleteL7DomainsResponse: DeleteL7DomainsResponse,
DevicesBindInfoBackend: DevicesBindInfoBackend,
UnbindL4BackendsRequest: UnbindL4BackendsRequest,
DescribeL7ListenersRequest: DescribeL7ListenersRequest,
DescribeTrafficMirrorListenersRequest: DescribeTrafficMirrorListenersRequest,
BindL7Backend: BindL7Backend,
ModifyL7ListenerResponse: ModifyL7ListenerResponse,
DescribeLoadBalancerTaskResultRequest: DescribeLoadBalancerTaskResultRequest,
DescribeL7RulesResponse: DescribeL7RulesResponse,
CreateTrafficMirrorResponse: CreateTrafficMirrorResponse,
DescribeDevicesBindInfoRequest: DescribeDevicesBindInfoRequest,
BindL4BackendsResponse: BindL4BackendsResponse,
TrafficMirrorListener: TrafficMirrorListener,
DescribeL7ListenersExResponse: DescribeL7ListenersExResponse,
UnbindL7Backend: UnbindL7Backend,
TrafficMirrorReceiver: TrafficMirrorReceiver,
TrafficMirrorPortStatus: TrafficMirrorPortStatus,
UploadCertResponse: UploadCertResponse,
DescribeTrafficMirrorReceiversResponse: DescribeTrafficMirrorReceiversResponse,
DeleteListenersRequest: DeleteListenersRequest,
ModifyL4BackendProbePortRequest: ModifyL4BackendProbePortRequest,
DescribeTrafficMirrorsRequest: DescribeTrafficMirrorsRequest,
UploadCertRequest: UploadCertRequest,
DescribeL4ListenerInfoResponse: DescribeL4ListenerInfoResponse,
BindTrafficMirrorListenersRequest: BindTrafficMirrorListenersRequest,
ModifyL7BackendPortRequest: ModifyL7BackendPortRequest,
ModifyL4BackendPortRequest: ModifyL4BackendPortRequest,
DescribeL4ListenersResponse: DescribeL4ListenersResponse,
ModifyL7LocationsRequest: ModifyL7LocationsRequest,
ModifyLoadBalancerResponse: ModifyLoadBalancerResponse,
CreateL4ListenersResponse: CreateL4ListenersResponse,
ModifyL7BackendWeightResponse: ModifyL7BackendWeightResponse,
DescribeTrafficMirrorsResponse: DescribeTrafficMirrorsResponse,
DescribeL7BackendsRequest: DescribeL7BackendsRequest,
L7Listener: L7Listener,
CreateL7RulesRequest: CreateL7RulesRequest,
ModifyL7BackendWeightRequest: ModifyL7BackendWeightRequest,
CreateL4ListenersRequest: CreateL4ListenersRequest,
ReplaceCertRequest: ReplaceCertRequest,
BindL7BackendsResponse: BindL7BackendsResponse,
L7Rule: L7Rule,
UnbindTrafficMirrorReceiversResponse: UnbindTrafficMirrorReceiversResponse,
DeleteL7DomainsRequest: DeleteL7DomainsRequest,
BindTrafficMirrorReceiversRequest: BindTrafficMirrorReceiversRequest,
BindTrafficMirrorListenersResponse: BindTrafficMirrorListenersResponse,
BindL7BackendsRequest: BindL7BackendsRequest,
DescribeL4Backend: DescribeL4Backend,
DescribeCertDetailResponse: DescribeCertDetailResponse,
DescribeL4BackendsRequest: DescribeL4BackendsRequest,
DescribeTrafficMirrorReceiverHealthStatusResponse: DescribeTrafficMirrorReceiverHealthStatusResponse,
BindTrafficMirrorReceiversResponse: BindTrafficMirrorReceiversResponse,
ReplaceCertResponse: ReplaceCertResponse,
DescribeLoadBalancerPortInfoRequest: DescribeLoadBalancerPortInfoRequest,
DevicesBindInfoLocation: DevicesBindInfoLocation,
SetTrafficMirrorHealthSwitchResponse: SetTrafficMirrorHealthSwitchResponse,
DeleteLoadBalancerRequest: DeleteLoadBalancerRequest,
UnbindTrafficMirrorListenersResponse: UnbindTrafficMirrorListenersResponse,
CreateL7Rule: CreateL7Rule,
CreateL7RulesResponse: CreateL7RulesResponse,
ModifyL7ListenerRequest: ModifyL7ListenerRequest,
DescribeTrafficMirrorReceiver: DescribeTrafficMirrorReceiver,
L7ExListener: L7ExListener,
L7ListenerInfo: L7ListenerInfo,
L7ListenerInfoRule: L7ListenerInfoRule,
DescribeL7BackendsResponse: DescribeL7BackendsResponse,
Filter: Filter,
DevicesBindInfoRule: DevicesBindInfoRule,
TrafficMirror: TrafficMirror,
DescribeLoadBalancersRequest: DescribeLoadBalancersRequest,
DevicesBindInfoLoadBalancer: DevicesBindInfoLoadBalancer,
L4Listener: L4Listener,
CreateL7Listener: CreateL7Listener,
DeleteLoadBalancerResponse: DeleteLoadBalancerResponse,
CreateTrafficMirrorRequest: CreateTrafficMirrorRequest,
BindL4BackendsRequest: BindL4BackendsRequest,
DescribeL7ListenerInfoResponse: DescribeL7ListenerInfoResponse,
DescribeL7ListenersResponse: DescribeL7ListenersResponse,
DeleteListenersResponse: DeleteListenersResponse,
CreateLoadBalancersResponse: CreateLoadBalancersResponse,
UnbindTrafficMirrorReceiver: UnbindTrafficMirrorReceiver,
ModifyLoadBalancerChargeModeResponse: ModifyLoadBalancerChargeModeResponse,
UnbindL7BackendsRequest: UnbindL7BackendsRequest,
L7ListenerInfoLocation: L7ListenerInfoLocation,
L7RulesLocation: L7RulesLocation,
ModifyLoadBalancerChargeModeListener: ModifyLoadBalancerChargeModeListener,
TrafficMirrorReciversStatus: TrafficMirrorReciversStatus,
CreateLoadBalancersRequest: CreateLoadBalancersRequest,
DescribeLoadBalancerPortInfoResponse: DescribeLoadBalancerPortInfoResponse,
DescribeL7ListenerInfoRequest: DescribeL7ListenerInfoRequest,
ModifyL4ListenerRequest: ModifyL4ListenerRequest,
L4Backend: L4Backend,
L7Backend: L7Backend,
ModifyL7LocationRule: ModifyL7LocationRule,
ModifyLoadBalancerRequest: ModifyLoadBalancerRequest,
DevicesBindInfoL7Listener: DevicesBindInfoL7Listener,
DescribeL4ListenersRequest: DescribeL4ListenersRequest,
CreateL7ListenersResponse: CreateL7ListenersResponse,
CreateLoadBalancerBzConf: CreateLoadBalancerBzConf,
DeleteTrafficMirrorRequest: DeleteTrafficMirrorRequest,
CreateL7ListenersRequest: CreateL7ListenersRequest,
BindL4Backend: BindL4Backend,
DescribeL7ListenersExRequest: DescribeL7ListenersExRequest,
DescribeLoadBalancerTaskResultResponse: DescribeLoadBalancerTaskResultResponse,
UnbindTrafficMirrorReceiversRequest: UnbindTrafficMirrorReceiversRequest,
UnbindTrafficMirrorListenersRequest: UnbindTrafficMirrorListenersRequest,
DescribeCertDetailRequest: DescribeCertDetailRequest,
DescribeDevicesBindInfoResponse: DescribeDevicesBindInfoResponse,
LoadBalancerPortInfoListener: LoadBalancerPortInfoListener,
DescribeL4BackendsResponse: DescribeL4BackendsResponse,
CreateL4Listener: CreateL4Listener,
DescribeTrafficMirrorListenersResponse: DescribeTrafficMirrorListenersResponse,
DescribeLoadBalancersResponse: DescribeLoadBalancersResponse,
DeleteL7RulesResponse: DeleteL7RulesResponse,
CertDetailLoadBalancer: CertDetailLoadBalancer,
DescribeTrafficMirrorReceiversRequest: DescribeTrafficMirrorReceiversRequest,
SetTrafficMirrorAliasRequest: SetTrafficMirrorAliasRequest,
UnbindL4BackendsResponse: UnbindL4BackendsResponse,
L7ListenerInfoBackend: L7ListenerInfoBackend,
ModifyLoadBalancerChargeModeRequest: ModifyLoadBalancerChargeModeRequest,
ModifyL4BackendWeightRequest: ModifyL4BackendWeightRequest,
LoadBalancer: LoadBalancer,
}
|
JeanMarc-Moly/mugimugi_client_api
|
mugimugi_client_api/get_item_by_id/circle.py
|
from typing import ClassVar
from mugimugi_client_api_entity import Circle
from mugimugi_client_api_entity import GetCircleById as Root
from mugimugi_client_api_entity.enum import ElementPrefix
from .abstract import GetItemById
class GetCircleById(GetItemById):
ROOT: ClassVar[type] = Root
PREFIX: ClassVar[ElementPrefix] = Circle.PREFIX
|
voxmedia/convert-rich-text
|
lib/formats/link.js
|
<reponame>voxmedia/convert-rich-text
module.exports = {
add: function(node, value, dom) {
var link = node.ownerDocument.createElement('a');
dom(node).wrap(link);
node = link;
node.href = value;
var previous = node.previousSibling;
if (previous && previous.tagName === 'A' && previous.href === node.href) {
node = dom(previous).merge(node).get();
}
return node;
}
};
|
TiankunZhou/dials
|
command_line/export_bitmaps.py
|
from __future__ import absolute_import, division, print_function
import os
import sys
from PIL import Image
import iotbx.phil
from dials.algorithms.image.threshold import DispersionThresholdDebug
from dials.array_family import flex
from dials.util import Sorry, show_mail_handle_errors
from dials.util.image_viewer.slip_viewer.tile_generation import (
get_flex_image,
get_flex_image_multipanel,
)
from dials.util.options import OptionParser, flatten_experiments
help_message = """
Export raw diffraction image files as bitmap images, optionally exporting
images from intermediate spot-finding steps (local mean and variance maps,
or sigma_b, sigma_s or threshold-filtered images). Appearance of the images
can be altered via the brightness and colour_scheme parameters, and optionally
binning of pixels can be used to reduce image sizes.
Examples::
dials.export_bitmaps image.cbf
dials.export_bitmaps models.expt
dials.export_bitmaps image.cbf display=variance colour_scheme=inverse_greyscale
"""
phil_scope = iotbx.phil.parse(
"""
binning = 1
.type = int(value_min=1)
brightness = 100
.type = float(value_min=0.0)
colour_scheme = *greyscale rainbow heatmap inverse_greyscale
.type = choice
padding = 4
.type = int(value_min=0)
imageset_index = None
.type = int
.multiple = True
.help = "The index/indices from an imageset to export. The first image of "
"the set is 1."
.expert_level=2
display = *image mean variance dispersion sigma_b \
sigma_s threshold global_threshold
.type = choice
nsigma_b = 6
.type = float(value_min=0)
nsigma_s = 3
.type = float(value_min=0)
global_threshold = 0
.type = float(value_min=0)
kernel_size = 3,3
.type = ints(size=2, value_min=1)
min_local = 2
.type = int
gain = 1
.type = float(value_min=0)
saturation = 0
.type = int
show_mask = False
.type = bool
png {
compress_level = 1
.type = int(value_min=0, value_max=9)
.help = "ZLIB compression level, a number between 0 and 9: 1 gives best "
"speed, 9 gives best compression, 0 gives no compression at all."
}
jpeg {
quality = 75
.type = int(value_min=1, value_max=95)
.help = "The image quality, on a scale from 1 (worst) to 95 (best)"
}
include scope dials.util.options.format_phil_scope
output {
prefix = "image"
.type = str
directory = None
.type = path
file = None
.type = str
.help = "Full name of the output file. Overrides 'prefix' and the default "
"file extension. Only makes sense if a single file is written."
format = jpeg *png tiff
.type = choice
}""",
process_includes=True,
)
colour_schemes = {"greyscale": 0, "rainbow": 1, "heatmap": 2, "inverse_greyscale": 3}
@show_mail_handle_errors()
def run(args=None):
usage = "dials.export_bitmaps [options] models.expt | image.cbf"
parser = OptionParser(
usage=usage,
phil=phil_scope,
read_experiments=True,
read_experiments_from_images=True,
check_format=True,
epilog=help_message,
)
params, options = parser.parse_args(args, show_diff_phil=True)
experiments = flatten_experiments(params.input.experiments)
if len(experiments) == 0:
parser.print_help()
exit(0)
imagesets = experiments.imagesets()
for imageset in imagesets:
imageset_as_bitmaps(imageset, params)
def imageset_as_bitmaps(imageset, params):
brightness = params.brightness / 100
vendortype = "made up"
# check that binning is a power of 2
binning = params.binning
if not (binning > 0 and ((binning & (binning - 1)) == 0)):
raise Sorry("binning must be a power of 2")
output_dir = params.output.directory
if output_dir is None:
output_dir = "."
elif not os.path.exists(output_dir):
os.makedirs(output_dir)
output_files = []
detector = imageset.get_detector()
panel = detector[0]
scan = imageset.get_scan()
# XXX is this inclusive or exclusive?
saturation = panel.get_trusted_range()[1]
if params.saturation:
saturation = params.saturation
if scan is not None and scan.get_oscillation()[1] > 0 and not params.imageset_index:
start, end = scan.get_image_range()
else:
start, end = 1, len(imageset)
# If the user specified an image range index, only export those
image_range = [
i
for i in range(start, end + 1)
if not params.imageset_index or i in params.imageset_index
]
if params.output.file and len(image_range) != 1:
sys.exit("output.file can only be specified if a single image is exported")
for i_image in image_range:
image = imageset.get_raw_data(i_image - start)
mask = imageset.get_mask(i_image - start)
if mask is None:
mask = [p.get_trusted_range_mask(im) for im, p in zip(image, detector)]
if params.show_mask:
for rd, m in zip(image, mask):
rd.set_selected(~m, -2)
image = image_filter(
image,
mask,
display=params.display,
gain_value=params.gain,
nsigma_b=params.nsigma_b,
nsigma_s=params.nsigma_s,
global_threshold=params.global_threshold,
min_local=params.min_local,
kernel_size=params.kernel_size,
)
show_untrusted = params.show_mask
if len(detector) > 1:
# FIXME This doesn't work properly, as flex_image.size2() is incorrect
# also binning doesn't work
flex_image = get_flex_image_multipanel(
brightness=brightness,
panels=detector,
image_data=image,
binning=binning,
beam=imageset.get_beam(),
show_untrusted=show_untrusted,
)
else:
flex_image = get_flex_image(
brightness=brightness,
data=image[0],
binning=binning,
saturation=saturation,
vendortype=vendortype,
show_untrusted=show_untrusted,
)
flex_image.setWindow(0, 0, 1)
flex_image.adjust(color_scheme=colour_schemes.get(params.colour_scheme))
# now export as a bitmap
flex_image.prep_string()
# XXX is size//binning safe here?
pil_img = Image.frombytes(
"RGB", (flex_image.ex_size2(), flex_image.ex_size1()), flex_image.as_bytes()
)
if params.output.file:
path = os.path.join(output_dir, params.output.file)
else:
path = os.path.join(
output_dir,
"{prefix}{image:0{padding}}.{format}".format(
image=i_image,
prefix=params.output.prefix,
padding=params.padding,
format=params.output.format,
),
)
print("Exporting %s" % path)
output_files.append(path)
with open(path, "wb") as tmp_stream:
pil_img.save(
tmp_stream,
format=params.output.format,
compress_level=params.png.compress_level,
quality=params.jpeg.quality,
)
return output_files
def image_filter(
raw_data,
mask,
display,
gain_value,
nsigma_b,
nsigma_s,
global_threshold,
min_local,
kernel_size,
):
if display == "image":
return raw_data
assert gain_value > 0
gain_map = [flex.double(rd.accessor(), gain_value) for rd in raw_data]
kabsch_debug_list = [
DispersionThresholdDebug(
data.as_double(),
mask[i_panel],
gain_map[i_panel],
kernel_size,
nsigma_b,
nsigma_s,
global_threshold,
min_local,
)
for i_panel, data in enumerate(raw_data)
]
if display == "mean":
display_data = [kabsch.mean() for kabsch in kabsch_debug_list]
elif display == "variance":
display_data = [kabsch.variance() for kabsch in kabsch_debug_list]
elif display == "dispersion":
display_data = [kabsch.index_of_dispersion() for kabsch in kabsch_debug_list]
elif display == "sigma_b":
cv = [kabsch.index_of_dispersion() for kabsch in kabsch_debug_list]
display_data = (kabsch.cv_mask() for kabsch in kabsch_debug_list)
display_data = [_mask.as_1d().as_double() for _mask in display_data]
for i, _mask in enumerate(display_data):
_mask.reshape(cv[i].accessor())
elif display == "sigma_s":
cv = [kabsch.index_of_dispersion() for kabsch in kabsch_debug_list]
display_data = (kabsch.value_mask() for kabsch in kabsch_debug_list)
display_data = [_mask.as_1d().as_double() for _mask in display_data]
for i, _mask in enumerate(display_data):
_mask.reshape(cv[i].accessor())
elif display == "global_threshold":
cv = [kabsch.index_of_dispersion() for kabsch in kabsch_debug_list]
display_data = (kabsch.global_mask() for kabsch in kabsch_debug_list)
display_data = [_mask.as_1d().as_double() for _mask in display_data]
for i, _mask in enumerate(display_data):
_mask.reshape(cv[i].accessor())
elif display == "threshold":
cv = [kabsch.index_of_dispersion() for kabsch in kabsch_debug_list]
display_data = (kabsch.final_mask() for kabsch in kabsch_debug_list)
display_data = [_mask.as_1d().as_double() for _mask in display_data]
for i, _mask in enumerate(display_data):
_mask.reshape(cv[i].accessor())
return display_data
if __name__ == "__main__":
run()
|
mattantonelli/ffxiv-collect
|
db/migrate/20210527190101_create_character_records.rb
|
class CreateCharacterRecords < ActiveRecord::Migration[5.2]
def change
create_table :character_records do |t|
t.integer :character_id
t.integer :record_id
t.timestamps
end
add_index :character_records, :character_id
add_index :character_records, :record_id
add_index :character_records, [:character_id, :record_id], unique: true
add_column :characters, :records_count, :integer, default: 0
add_index :characters, :records_count
end
end
|
rickypid/node-redirect-rules
|
libs/middleware.js
|
module.exports = createMiddlewareForRules;
var _ = require('lodash');
var requireDir = require('require-directory');
var matchers = require('./matchers');
var placeholders = require('./placeholders');
var outputters = requireDir(module, './outputters');
var outputTypes = [ 'status', 'headers', 'body' ]; // Place in sequential order
var rules = [];
function createMiddlewareForRules(newRules) {
rules = newRules;
return function(req, res, next) {
var destination = findDestination(rules, req);
if (destination) {
outputTypes
.filter(function(key) { return key in destination; })
.forEach(function(key) {
outputters[key](res, destination[key]);
});
res.end();
} else {
next();
}
};
}
function setRule(newRules) {
rules = newRules;
}
module.exports.setRule = setRule;
function findDestination(rules, req) {
if (!(rules instanceof Array)) {
rules = [rules];
}
for (var i = 0; i < rules.length; i++) {
var destination = attemptRule(rules[i], req);
if (destination) {
return destination;
}
}
}
function attemptRule(rule, req) {
var conditions = rule.from;
if (typeof(conditions) !== 'object' || conditions instanceof RegExp) {
conditions = { url: conditions };
}
var allMatchVars = {};
var allConditionsMatch = Object
.keys(conditions)
.every(function(prop) {
var matcher = matchers[prop];
if (!matcher)
return false;
var matchVars = matcher(req, conditions[prop]);
if (!matchVars)
return false;
_.assign(allMatchVars, matchVars);
return true;
});
if (allConditionsMatch) {
return generateDestination(rule, req, allMatchVars);
}
}
function generateDestination(rule, req, variables) {
var result = {
status: rule.to.status || rule.status || 301,
headers: rule.to.headers || {},
body: rule.to.body
};
if (typeof(rule.to) !== 'object') {
result.headers.location = rule.to;
} else {
result.headers.location = rule.to.url;
}
variables.redirectURL = generateDestinationUrl(result.headers.location, req, variables);
result.headers.location = '{redirectURL}';
return substitutePlaceholders(result, variables, req);
}
var SCHEMALESS_PREFIX = /^\/\//;
var DOUBLE_SLASHES_AFTER_BEGINNING = /([^\/])\/{2,}/g;
var DOUBLE_SLASHES_NOT_FOLLOWING_COLON = /([^:\/]|^)\/{2,}/g;
var DOUBLE_QUESTION_MARKS = /\?{2,}/g;
function generateDestinationUrl(pattern, req, variables) {
var unwantedDoubleSlashes = SCHEMALESS_PREFIX.test(pattern)
? DOUBLE_SLASHES_AFTER_BEGINNING
: DOUBLE_SLASHES_NOT_FOLLOWING_COLON;
return substitutePlaceholders(pattern, variables, req)
// Clean up double slashes, which could result from empty placeholders in the URL
.replace(unwantedDoubleSlashes, '$1/')
// Clean up double question marks, which could result from doing '?{query}'
.replace(DOUBLE_QUESTION_MARKS, '?');
}
var PLACEHOLDERS = /\{([^}]*?)}/g;
function substitutePlaceholders(value, variables, req) {
var type = typeof(value);
if (type === 'object') {
return Object
.keys(value)
.reduce(function(result, prop) {
result[prop] = substitutePlaceholders(value[prop], variables, req);
return result;
}, {});
}
if (type !== 'string')
return value;
return value.replace(PLACEHOLDERS, function(substr, placeholder) {
if (placeholder in variables) {
return variables[placeholder];
}
var parts = placeholder.split('.');
placeholder = parts[0];
var param = parts[1];
if (placeholder in placeholders) {
var result = placeholders[placeholder](req);
return param ? result[param] : result;
}
return '';
});
}
|
JayWenStar/sonic-server-simple
|
src/main/java/com/sonic/simple/controller/FilesController.java
|
<reponame>JayWenStar/sonic-server-simple
package com.sonic.simple.controller;
import com.sonic.simple.config.WebAspect;
import com.sonic.simple.models.http.RespModel;
import com.sonic.simple.tools.FileTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@RestController
@RequestMapping("/api/folder/files")
public class FilesController {
private final Logger logger = LoggerFactory.getLogger(FilesController.class);
private ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
@Autowired
private FileTool fileTool;
/**
* @param day 文件保留天数
* @return com.sonic.common.http.RespModel
* @author ZhouYiXun
* @des 删除本地文件
* @date 2021/8/21 21:47
*/
@WebAspect
@DeleteMapping
public RespModel delete(@RequestParam(name = "day") int day) {
long timeMillis = Calendar.getInstance().getTimeInMillis();
SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
List<String> fileList = Arrays.asList("imageFiles", "recordFiles", "logFiles", "packageFiles");
cachedThreadPool.execute(() -> {
for (String fileType : fileList) {
File[] type = new File(fileType).listFiles();
for (File dateFile : type) {
try {
if (timeMillis - sf.parse(dateFile.getName()).getTime()
> day * 86400000L) {
logger.info("开始清理:" + dateFile.getPath());
fileTool.deleteDir(dateFile);
}
} catch (ParseException e) {
logger.info("文件名出错:" + dateFile.getPath());
logger.error(e.getMessage());
}
}
}
});
return new RespModel(2000, "开始清理!");
}
}
|
giorgos-nikolopoulos/adc-nitro-go
|
resource/config/authentication/authenticationemailaction.go
|
/*
* Copyright (c) 2021 Citrix Systems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package authentication
/**
* Configuration for Email entity resource.
*/
type Authenticationemailaction struct {
/**
* Name for the new email action. Must begin with an ASCII alphanumeric or underscore (_) character, and must contain only ASCII alphanumeric, underscore, hash (#), period (.), space, colon (:), at (@), equals (=), and hyphen (-) characters. Cannot be changed after an action is created.
The following requirement applies only to the Citrix ADC CLI:
If the name includes one or more spaces, enclose the name in double or single quotation marks (for example, "my action" or 'my action').
*/
Name string `json:"name,omitempty"`
/**
* Username/Clientid/EmailID to be used to authenticate to the server.
*/
Username string `json:"username,omitempty"`
/**
* Password/Clientsecret to use when authenticating to the server.
*/
Password string `json:"password,omitempty"`
/**
* Address of the server that delivers the message. It is fully qualified fqdn such as http(s):// or smtp(s):// for http and smtp protocols respectively. For SMTP, the port number is mandatory like smtps://smtp.example.com:25.
*/
Serverurl string `json:"serverurl,omitempty"`
/**
* Content to be delivered to the user. "$code" string within the content will be replaced with the actual one-time-code to be sent.
*/
Content string `json:"content,omitempty"`
/**
* This is the group that is added to user sessions that match current IdP policy. It can be used in policies to identify relying party trust.
*/
Defaultauthenticationgroup string `json:"defaultauthenticationgroup,omitempty"`
/**
* Time after which the code expires.
*/
Timeout int `json:"timeout,omitempty"`
/**
* Type of the email action. Default type is SMTP.
*/
Type string `json:"type,omitempty"`
/**
* An optional expression that yields user's email. When not configured, user's default mail address would be used. When configured, result of this expression is used as destination email address.
*/
Emailaddress string `json:"emailaddress,omitempty"`
}
|
KhodyAzmoon/atdl4j
|
src/main/java/org/atdl4j/fixatdl/layout/ClockT.java
|
<reponame>KhodyAzmoon/atdl4j
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2010.02.24 at 10:55:05 AM CST
//
package org.atdl4j.fixatdl.layout;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
import org.atdl4j.fixatdl.timezones.Timezone;
/**
* <p>Java class for Clock_t complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Clock_t">
* <complexContent>
* <extension base="{http://www.fixprotocol.org/FIXatdl-1-1/Layout}Control_t">
* <attribute name="initValue" type="{http://www.w3.org/2001/XMLSchema}time" />
* <attribute name="initValueMode" default="0">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}int">
* <enumeration value="0"/>
* <enumeration value="1"/>
* </restriction>
* </simpleType>
* </attribute>
* <attribute name="localMktTz" type="{http://www.fixprotocol.org/FIXatdl-1-1/Timezones}LocalMktTz_t" />
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Clock_t")
public class ClockT
extends ControlT
{
@XmlAttribute
@XmlSchemaType(name = "time")
protected XMLGregorianCalendar initValue;
@XmlAttribute
protected Integer initValueMode;
@XmlAttribute
protected Timezone localMktTz;
/**
* Gets the value of the initValue property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getInitValue() {
return initValue;
}
/**
* Sets the value of the initValue property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setInitValue(XMLGregorianCalendar value) {
this.initValue = value;
}
/**
* Gets the value of the initValueMode property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public int getInitValueMode() {
if (initValueMode == null) {
return 0;
} else {
return initValueMode;
}
}
/**
* Sets the value of the initValueMode property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setInitValueMode(Integer value) {
this.initValueMode = value;
}
/**
* Gets the value of the localMktTz property.
*
* @return
* possible object is
* {@link Timezone }
*
*/
public Timezone getLocalMktTz() {
return localMktTz;
}
/**
* Sets the value of the localMktTz property.
*
* @param value
* allowed object is
* {@link Timezone }
*
*/
public void setLocalMktTz(Timezone value) {
this.localMktTz = value;
}
}
|
tonysparks/jslt2
|
src/main/java/jslt2/Jslt2Exception.java
|
<filename>src/main/java/jslt2/Jslt2Exception.java
/*
* see license.txt
*/
package jslt2;
/**
* @author Tony
*
*/
public class Jslt2Exception extends RuntimeException {
/**
* SUID
*/
private static final long serialVersionUID = 4445110898818625900L;
public Jslt2Exception() {
}
/**
* @param message
*/
public Jslt2Exception(String message) {
super(message);
}
/**
* @param cause
*/
public Jslt2Exception(Throwable cause) {
super(cause);
}
/**
* @param message
* @param cause
*/
public Jslt2Exception(String message, Throwable cause) {
super(message, cause);
}
/**
* @param message
* @param cause
* @param enableSuppression
* @param writableStackTrace
*/
public Jslt2Exception(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
|
aphex3k/specter-desktop
|
tests/test_managers_otp.py
|
<reponame>aphex3k/specter-desktop
import os
from cryptoadvance.specter.managers.otp_manager import OtpManager
import time
def test_OtpManager(empty_data_folder):
# A OtpManager manages Otp, one-time-passwords
# via json-files in an empty data folder
otpm = OtpManager(data_folder=empty_data_folder)
assert os.path.isfile(os.path.join(empty_data_folder, "otps.json"))
# initialization will load from the folder but it's empty at first
assert otpm.data == {} # but you shouldn't access data directly anyway
# an otp looks like this:
an_otp = {
"otp": "aOxO42IeM-aRB4WjBIAQRA",
"created_at": 1618491877.546648,
"expiry": 1617495477.546648,
}
otpm.add_new_user_otp(an_otp)
yet_another_otp = {
"otp": "nPfouONJmUgS642MitqPkg",
"created_at": time.time(),
"expiry": time.time() + 60 * 60, # plus 1 h
}
assert otpm.validate_new_user_otp(an_otp["otp"]) == False
otpm.add_new_user_otp(yet_another_otp)
assert otpm.validate_new_user_otp(an_otp["otp"]) == False
assert otpm.validate_new_user_otp(yet_another_otp["otp"]) == True
otpm.remove_new_user_otp(an_otp["otp"])
# If it doesn't exist, False as well
assert otpm.validate_new_user_otp(an_otp["otp"]) == False
# anything gets you False
assert otpm.validate_new_user_otp("anything") == False
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.