repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
physikerwelt/incubator-flink
|
flink-tests/src/test/java/org/apache/flink/test/distributedCache/DistributedCacheTest.java
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.test.distributedCache;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.HashSet;
import java.util.Set;
import org.apache.flink.api.common.Plan;
import org.apache.flink.api.common.cache.DistributedCache.DistributedCacheEntry;
import org.apache.flink.api.java.record.functions.MapFunction;
import org.apache.flink.api.java.record.io.CsvOutputFormat;
import org.apache.flink.api.java.record.io.TextInputFormat;
import org.apache.flink.api.java.record.operators.FileDataSink;
import org.apache.flink.api.java.record.operators.FileDataSource;
import org.apache.flink.api.java.record.operators.MapOperator;
import org.apache.flink.test.testdata.WordCountData;
import org.apache.flink.test.util.RecordAPITestBase;
import org.apache.flink.types.IntValue;
import org.apache.flink.types.Record;
import org.apache.flink.types.StringValue;
import org.apache.flink.util.Collector;
/**
* Test the distributed cache via using the cache file to do a selection on the input
*/
public class DistributedCacheTest extends RecordAPITestBase {
public static final String cacheData = "machen\n" + "zeit\n" + "heerscharen\n" + "keiner\n" + "meine\n"
+ "fuehr\n" + "triumph\n" + "kommst\n" + "frei\n" + "schaffen\n" + "gesinde\n"
+ "langbeinigen\n" + "schalk\n" + "besser\n" + "solang\n" + "meer\n" + "fragst\n"
+ "gabriel\n" + "selbst\n" + "bin\n" + "sich\n" + "du\n" + "sogar\n" + "geht\n"
+ "immer\n" + "mensch\n" + "befestigt\n" + "lebt\n" + "mag\n" + "engeln\n" + "breiten\n"
+ "blitzendes\n" + "tags\n" + "sie\n" + "plagen\n" + "allzu\n" + "meisten\n" + "o\n"
+ "pfade\n" + "kennst\n" + "nichts\n" + "gedanken\n" + "befriedigt\n" + "mich\n" + "s\n"
+ "es\n" + "verneinen\n" + "er\n" + "gleich\n" + "baeumchen\n" + "donnergang\n";
public static final String selectedCounts = "machen 1\n" + "zeit 2\n" + "heerscharen 1\n" + "keiner 2\n" + "meine 3\n"
+ "fuehr 1\n" + "triumph 1\n" + "kommst 1\n" + "frei 1\n" + "schaffen 1\n" + "gesinde 1\n"
+ "langbeinigen 1\n" + "schalk 1\n" + "besser 1\n" + "solang 1\n" + "meer 4\n" + "fragst 1\n"
+ "gabriel 1\n" + "selbst 2\n" + "bin 1\n" + "sich 7\n" + "du 11\n" + "sogar 1\n" + "geht 1\n"
+ "immer 4\n" + "mensch 2\n" + "befestigt 1\n" + "lebt 2\n" + "mag 3\n" + "engeln 2\n" + "breiten 1\n"
+ "blitzendes 1\n" + "tags 1\n" + "sie 2\n" + "plagen 2\n" + "allzu 1\n" + "meisten 1\n" + "o 1\n"
+ "pfade 1\n" + "kennst 1\n" + "nichts 3\n" + "gedanken 1\n" + "befriedigt 1\n" + "mich 6\n" + "s 3\n"
+ "es 8\n" + "verneinen 1\n" + "er 13\n" + "gleich 1\n" + "baeumchen 1\n" + "donnergang 1\n";
protected String textPath;
protected String cachePath;
protected String resultPath;
public static class TokenizeLine extends MapFunction {
private static final long serialVersionUID = 1L;
private Set<String> stringList = new HashSet<String>();
@Override
public void open(org.apache.flink.configuration.Configuration conf) {
File file = getRuntimeContext().getDistributedCache().getFile("cache_test");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String tempString = null;
while ((tempString = reader.readLine()) != null) {
stringList.add(tempString);
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void map(Record record, Collector<Record> collector) {
String line = record.getField(0, StringValue.class).getValue();
String [] element = line.split(" ");
String word = element[0];
int count = Integer.parseInt(element[1]);
if (stringList.contains(word)) {
collector.collect(new Record(new StringValue(word), new IntValue(count)));
}
}
}
public Plan getPlan(int numSubTasks, String dataInput, String output) {
// input is {word, count} pair
FileDataSource source = new FileDataSource(new TextInputFormat(), dataInput, "Input Lines");
//do a selection using cached file
MapOperator mapper = MapOperator.builder(new TokenizeLine())
.input(source)
.name("Tokenize Lines")
.build();
FileDataSink out = new FileDataSink(new CsvOutputFormat(), output, mapper, "Selection");
CsvOutputFormat.configureRecordFormat(out)
.recordDelimiter('\n')
.fieldDelimiter(' ')
.field(StringValue.class, 0)
.field(IntValue.class, 1);
Plan plan = new Plan(out, "Distributed Cache");
plan.setDefaultParallelism(numSubTasks);
return plan;
}
@Override
protected void preSubmit() throws Exception {
textPath = createTempFile("count.txt", WordCountData.COUNTS);
cachePath = createTempFile("cache.txt", cacheData);
resultPath = getTempDirPath("result");
}
@Override
protected Plan getTestJob() {
Plan plan = getPlan(1 , textPath, resultPath);
try {
plan.registerCachedFile("cache_test", new DistributedCacheEntry(cachePath, false));
} catch (IOException ex) {
throw new RuntimeException(ex);
}
return plan;
}
@Override
protected void postSubmit() throws Exception {
// Test results
compareResultsByLinesInMemory(selectedCounts, resultPath);
}
}
|
bphenriques-interview-challenges/get-file-line-api-challenge
|
src/test/scala/com/bphenriques/lineserver/client/input/strategies/LocalFileLinesInputSupplierConfigSpec.scala
|
<reponame>bphenriques-interview-challenges/get-file-line-api-challenge
/*
*
* * © Copyright 2019 <NAME>
*
*
*/
package com.bphenriques.lineserver.client.input.strategies
import java.io.File
import com.bphenriques.helpers.BaseSpec
/**
* Tests [[LocalFileLinesInputSupplierConfig]].
*/
class LocalFileLinesInputSupplierConfigSpec extends BaseSpec {
it must "reject invalid arguments" in {
val rows = Table(
"File",
new File(""), // Home folder.
getResource(".file") // File that does not exist.
)
forAll (rows) { file: File =>
assertThrows[Exception] {
LocalFileLinesInputSupplierConfig(file)
}
}
}
it must "accept valid files" in {
val file = getResource("sample.txt")
LocalFileLinesInputSupplierConfig(file).file shouldEqual file
}
}
|
pmh/elf
|
lib/language/language.js
|
<reponame>pmh/elf
var elf = require ( "../runtime/runtime" )
, Parser = require ( "../parser/parser" )
, ParserDSL = require ( "../parser/dsl" )
, Lexer = require ( "../lexer/lexer" )
, LexerDSL = require ( "../lexer/dsl" )
, fun = require ( "funargs" )
, Language
;
Language = elf.Object.clone(function () {
this.init = function () {
this.parser = Parser.clone();
this.lexer = Lexer.clone();
this.wrapParserAPI()
};
this.wrapParserAPI = function () {
var lexer = this.lexer;
this.parser.wrap("advance", function (old) {
return function (id) {
if (id) lexer.operator(id);
return old.apply(this, arguments);
}
})
this.parser.wrap("parseUntil", function (old) {
return function (id, opts) {
lexer.operator(id);
if (opts && opts.step) lexer.operator(opts.step);
return old.apply(this, arguments);
}
})
}
LexerDSL.slots().forEach(function (slot) {
this[slot] = function () {
this.lexer[slot].apply(this.lexer, arguments);
}
}, this)
ParserDSL.slots().forEach(function (slot) {
this[slot] = function () {
var args = fun(arguments);
var ids = args.strings();
ids.forEach(function (id) {
this.lexer.operator(id);
}, this)
this.parser[slot].apply(this.parser, arguments);
}
}, this);
this.borrow = function (obj) {
var symbols = Array.prototype.slice.call(arguments, 1);
symbols.forEach(function (sym) { this.lexer.operator(sym); }, this)
this.parser.borrow.apply(this.parser, [obj.parser].concat(symbols));
}
this.extend = function () {
var languages = Array.prototype.slice.call(arguments)
, self = this
;
languages.forEach(function (language) {
language.parser.symbol_table.symbols.slots().forEach(function (symbol_name) {
self.parser.symbol_table.symbols[symbol_name] = language.parser.symbol_table.symbols[symbol_name]
}.bind(this));
language.lexer.rules.forEach(function (rule) {
self.lexer.rules.push(rule);
});
if (language.extended) language.extended(self);
});
return this;
}
this.parse = function (input) {
return this.parser.parse(this.lexer.lex(input))
}
});
module.exports = Language;
|
jonesd/st2x
|
src/main/java/info/dgjones/st2x/transform/method/intra/TransformStreamContents.java
|
<gh_stars>0
/**
* The MIT License
* Copyright (c) 2003 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package info.dgjones.st2x.transform.method.intra;
import java.util.List;
import info.dgjones.st2x.JavaMethod;
import info.dgjones.st2x.javatoken.JavaAssignment;
import info.dgjones.st2x.javatoken.JavaBlockStart;
import info.dgjones.st2x.javatoken.JavaCallEnd;
import info.dgjones.st2x.javatoken.JavaCallKeywordStart;
import info.dgjones.st2x.javatoken.JavaCallStart;
import info.dgjones.st2x.javatoken.JavaIdentifier;
import info.dgjones.st2x.javatoken.JavaKeyword;
import info.dgjones.st2x.javatoken.JavaStatementTerminator;
import info.dgjones.st2x.javatoken.JavaType;
import info.dgjones.st2x.transform.method.AbstractMethodBodyTransformation;
import info.dgjones.st2x.transform.tokenmatcher.TokenMatcher;
import info.dgjones.st2x.transform.tokenmatcher.TokenMatcherFactory;
import info.dgjones.st2x.util.ClassHelper;
public class TransformStreamContents extends AbstractMethodBodyTransformation {
public TransformStreamContents() {
super();
}
public TransformStreamContents(TokenMatcherFactory factory) {
super(factory);
}
protected TokenMatcher matchers(TokenMatcherFactory factory) {
return factory.seq(
// factory.token(JavaKeyword.class, "return"),
factory.token(JavaIdentifier.class, "String"),
factory.token(JavaCallKeywordStart.class, "streamContents"),
factory.token(JavaBlockStart.class),
factory.token(JavaType.class, "Object"),
factory.token(JavaIdentifier.class),
factory.token(JavaStatementTerminator.class));
}
protected int transform(JavaMethod javaMethod, List tokens, int i) {
int statementStart = javaMethod.methodBody.findStartOfStatement(i-1);
int blockEnd = javaMethod.methodBody.findEndOfBlockQuietFail(i+2);
if (blockEnd == -1) {
System.out.println("--Failed to find end of block for:"+ClassHelper.getShortName(this.getClass())+" method:"+javaMethod.getQualifiedSignature());
return i;
}
tokens.remove(blockEnd+1);
tokens.remove(blockEnd);
tokens.remove(i+3);
tokens.remove(i+2);
tokens.remove(i+1);
tokens.remove(i+0);
tokens.add(i, new JavaType("StringWriter"));
tokens.add(i+1, new JavaIdentifier("stringWriter"));
tokens.add(i+2, new JavaAssignment());
tokens.add(i+3, new JavaKeyword("new"));
tokens.add(i+4, new JavaCallStart("StringWriter"));
tokens.add(i+5, new JavaCallEnd());
tokens.add(i+6, new JavaStatementTerminator());
tokens.add(i+7, new JavaType("PrintWriter"));
tokens.add(i+9, new JavaAssignment());
tokens.add(i+10, new JavaKeyword("new"));
tokens.add(i+11, new JavaCallKeywordStart("PrintWriter"));
tokens.add(i+12, new JavaIdentifier("stringWriter"));
tokens.add(i+13, new JavaCallEnd());
int newEnd = blockEnd+13-4;
tokens.add(newEnd+0, new JavaIdentifier("stringWriter"));
tokens.add(newEnd+1, new JavaCallStart("toString"));
tokens.add(newEnd+2, new JavaCallEnd());
javaMethod.methodBody.copy(statementStart, i, newEnd);
javaMethod.methodBody.remove(statementStart, i);
return i;
}
}
|
jazzscheme/jazz
|
lib/jazz.stream/foreign/mac/gstreamer/gstreamer/include/gstreamer-1.0/gst/vulkan/vulkan.h
|
/*
* GStreamer
* Copyright (C) 2015 <NAME> <<EMAIL>>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library 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.
*/
#ifndef __GST_VULKAN_H__
#define __GST_VULKAN_H__
#include <gst/gst.h>
#include <gst/vulkan/gstvkapi.h>
#include <gst/vulkan/gstvkdebug.h>
#include <gst/vulkan/gstvkerror.h>
#include <gst/vulkan/gstvkformat.h>
/* vulkan wrapper objects */
#include <gst/vulkan/gstvkinstance.h>
#include <gst/vulkan/gstvkphysicaldevice.h>
#include <gst/vulkan/gstvkdevice.h>
#include <gst/vulkan/gstvkqueue.h>
#include <gst/vulkan/gstvkfence.h>
#include <gst/vulkan/gstvkdisplay.h>
#include <gst/vulkan/gstvkwindow.h>
#include <gst/vulkan/gstvkmemory.h>
#include <gst/vulkan/gstvkbarrier.h>
#include <gst/vulkan/gstvkbuffermemory.h>
#include <gst/vulkan/gstvkimagememory.h>
#include <gst/vulkan/gstvkimageview.h>
#include <gst/vulkan/gstvkbufferpool.h>
#include <gst/vulkan/gstvkimagebufferpool.h>
#include <gst/vulkan/gstvkcommandbuffer.h>
#include <gst/vulkan/gstvkcommandpool.h>
#include <gst/vulkan/gstvkdescriptorset.h>
#include <gst/vulkan/gstvkdescriptorpool.h>
#include <gst/vulkan/gstvkhandle.h>
/* helper elements */
#include <gst/vulkan/gstvkvideofilter.h>
/* helper vulkan objects */
#include <gst/vulkan/gstvkdescriptorcache.h>
#include <gst/vulkan/gstvktrash.h>
#include <gst/vulkan/gstvkswapper.h>
#include <gst/vulkan/gstvkhandlepool.h>
#include <gst/vulkan/gstvkfullscreenquad.h>
#include <gst/vulkan/gstvkutils.h>
#endif /* __GST_VULKAN_H__ */
|
hwu25/edk2-platforms
|
Platform/Intel/Vlv2TbltDevicePkg/Include/Guid/BiosId.h
|
/*++
Copyright (c) 1999 - 2014, Intel Corporation. All rights reserved
SPDX-License-Identifier: BSD-2-Clause-Patent
Module Name:
BiosId.h
Abstract:
GUIDs used for Bios ID.
--*/
#ifndef _BIOS_ID_H_
#define _BIOS_ID_H_
#define EFI_BIOS_ID_GUID \
{ 0xC3E36D09, 0x8294, 0x4b97, 0xA8, 0x57, 0xD5, 0x28, 0x8F, 0xE3, 0x3E, 0x28 }
extern EFI_GUID gEfiBiosIdGuid;
#endif
|
slemjet/problems_and_solutions
|
questions_codility/3.time-complexity/src/test/java/pl/slemjet/kata/tapeequilibrium/FrogJmpTest.java
|
package pl.slemjet.kata.tapeequilibrium;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class FrogJmpTest {
@Test
void jumpsTest() {
assertEquals(3, FrogJmp.jumps(10, 85, 30));
assertEquals(3, FrogJmp.jumps(10, 85, 25));
}
}
|
lguohan/SDKLT
|
src/bcma/cint/core/cint_datatypes.h
|
<gh_stars>1-10
/*
* $Id: cint_datatypes.h,v 1.20 2012/03/02 16:21:39 yaronm Exp $
* Copyright: (c) 2018 Broadcom. All Rights Reserved. "Broadcom" refers to
* Broadcom Limited and/or its subsidiaries.
*
* Broadcom Switch Software License
*
* This license governs the use of the accompanying Broadcom software. Your
* use of the software indicates your acceptance of the terms and conditions
* of this license. If you do not agree to the terms and conditions of this
* license, do not use the software.
* 1. Definitions
* "Licensor" means any person or entity that distributes its Work.
* "Software" means the original work of authorship made available under
* this license.
* "Work" means the Software and any additions to or derivative works of
* the Software that are made available under this license.
* The terms "reproduce," "reproduction," "derivative works," and
* "distribution" have the meaning as provided under U.S. copyright law.
* Works, including the Software, are "made available" under this license
* by including in or with the Work either (a) a copyright notice
* referencing the applicability of this license to the Work, or (b) a copy
* of this license.
* 2. Grant of Copyright License
* Subject to the terms and conditions of this license, each Licensor
* grants to you a perpetual, worldwide, non-exclusive, and royalty-free
* copyright license to reproduce, prepare derivative works of, publicly
* display, publicly perform, sublicense and distribute its Work and any
* resulting derivative works in any form.
* 3. Grant of Patent License
* Subject to the terms and conditions of this license, each Licensor
* grants to you a perpetual, worldwide, non-exclusive, and royalty-free
* patent license to make, have made, use, offer to sell, sell, import, and
* otherwise transfer its Work, in whole or in part. This patent license
* applies only to the patent claims licensable by Licensor that would be
* infringed by Licensor's Work (or portion thereof) individually and
* excluding any combinations with any other materials or technology.
* If you institute patent litigation against any Licensor (including a
* cross-claim or counterclaim in a lawsuit) to enforce any patents that
* you allege are infringed by any Work, then your patent license from such
* Licensor to the Work shall terminate as of the date such litigation is
* filed.
* 4. Redistribution
* You may reproduce or distribute the Work only if (a) you do so under
* this License, (b) you include a complete copy of this License with your
* distribution, and (c) you retain without modification any copyright,
* patent, trademark, or attribution notices that are present in the Work.
* 5. Derivative Works
* You may specify that additional or different terms apply to the use,
* reproduction, and distribution of your derivative works of the Work
* ("Your Terms") only if (a) Your Terms provide that the limitations of
* Section 7 apply to your derivative works, and (b) you identify the
* specific derivative works that are subject to Your Terms.
* Notwithstanding Your Terms, this license (including the redistribution
* requirements in Section 4) will continue to apply to the Work itself.
* 6. Trademarks
* This license does not grant any rights to use any Licensor's or its
* affiliates' names, logos, or trademarks, except as necessary to
* reproduce the notices described in this license.
* 7. Limitations
* Platform. The Work and any derivative works thereof may only be used, or
* intended for use, with a Broadcom switch integrated circuit.
* No Reverse Engineering. You will not use the Work to disassemble,
* reverse engineer, decompile, or attempt to ascertain the underlying
* technology of a Broadcom switch integrated circuit.
* 8. Termination
* If you violate any term of this license, then your rights under this
* license (including the license grants of Sections 2 and 3) will
* terminate immediately.
* 9. Disclaimer of Warranty
* THE WORK IS PROVIDED "AS IS" WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WARRANTIES OR CONDITIONS OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE OR
* NON-INFRINGEMENT. YOU BEAR THE RISK OF UNDERTAKING ANY ACTIVITIES UNDER
* THIS LICENSE. SOME STATES' CONSUMER LAWS DO NOT ALLOW EXCLUSION OF AN
* IMPLIED WARRANTY, SO THIS DISCLAIMER MAY NOT APPLY TO YOU.
* 10. Limitation of Liability
* EXCEPT AS PROHIBITED BY APPLICABLE LAW, IN NO EVENT AND UNDER NO LEGAL
* THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE
* SHALL ANY LICENSOR BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY DIRECT,
* INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF
* OR RELATED TO THIS LICENSE, THE USE OR INABILITY TO USE THE WORK
* (INCLUDING BUT NOT LIMITED TO LOSS OF GOODWILL, BUSINESS INTERRUPTION,
* LOST PROFITS OR DATA, COMPUTER FAILURE OR MALFUNCTION, OR ANY OTHER
* COMMERCIAL DAMAGES OR LOSSES), EVEN IF THE LICENSOR HAS BEEN ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGES.
*
*
*
* File: cint_datatypes.h
* Purpose: CINT datatype interfaces
*/
#ifndef __CINT_DATATYPES_H__
#define __CINT_DATATYPES_H__
#include "cint_ast.h"
#include "cint_types.h"
#include "cint_error.h"
/*
* Generic datatype description structure
*/
#define CINT_DATATYPE_F_ATOMIC 0x1
#define CINT_DATATYPE_F_STRUCT 0x2
#define CINT_DATATYPE_F_ENUM 0x4
#define CINT_DATATYPE_F_FUNC 0x8
#define CINT_DATATYPE_F_CONSTANT 0x10
#define CINT_DATATYPE_F_FUNC_DYNAMIC 0x20
#define CINT_DATATYPE_F_FUNC_POINTER 0x40
#define CINT_DATATYPE_F_TYPEDEF 0x80
#define CINT_DATATYPE_F_ITERATOR 0x100
#define CINT_DATATYPE_F_MACRO 0x200
#define CINT_DATATYPE_F_FUNC_VARARG 0x400
#define CINT_DATATYPE_FLAGS_FUNC (CINT_DATATYPE_F_FUNC | CINT_DATATYPE_F_FUNC_DYNAMIC)
#define CINT_DATATYPE_FLAGS_TYPE (CINT_DATATYPE_F_ATOMIC | CINT_DATATYPE_F_STRUCT | CINT_DATATYPE_F_ENUM | CINT_DATATYPE_F_FUNC_POINTER | CINT_DATATYPE_F_TYPEDEF)
typedef struct cint_datatype_s {
/* Flags for this datatype */
unsigned int flags;
/*
* The description of this datatype
*/
cint_parameter_desc_t desc;
/*
* Pointer to the description of the basetype
*/
union {
cint_atomic_type_t* ap;
cint_struct_type_t* sp;
cint_enum_type_t* ep;
cint_constants_t* cp;
cint_function_t* fp;
cint_function_pointer_t* fpp;
cint_custom_iterator_t* ip;
cint_custom_macro_t* mp;
void* p;
} basetype;
/*
* Original type name. May be different from basetype name based on aliases or typedefs.
* Also used for temporary storage.
*/
char type[CINT_CONFIG_MAX_VARIABLE_NAME];
/*
* Custom print and assignment vectors which can be used with this datatype.
* These are different from the atomic type definition as it this type
* may still be an aggregate and may be treated or referenced as such in
* addition to the custom assignment and print options.
*/
cint_atomic_type_t* cap;
/*
* Used when identifying when custom operations should be used on a type
* defined as an array of another type.
*
* For example, consider an atomic type defined to be a char[6] with custom
* input and output functions. For a variable of this type we could always
* use the custom functions. However, if we represented an array of this
* type we would have to store the custom functions and only use them after
* we dereferenced the entity sufficiently. Storing the dimension count
* (one in this case) of the base type allows us to do this.
*/
int type_num_dimensions;
} cint_datatype_t;
/*
* Use for structures created by hand
*/
#define CINT_STRUCT_TYPE_DEFINE(_struct) \
{ \
#_struct, \
sizeof(_struct), \
__cint_struct_members__##_struct, \
__cint_maddr__##_struct \
}
extern int
cint_datatype_size(const cint_datatype_t* dt);
extern int
cint_datatype_find(const char* basetype, cint_datatype_t* dt);
extern int
cint_datatype_enum_find(const char* enumid, cint_datatype_t* dt, int* value);
typedef int (*cint_datatype_traverse_t)(void* cookie, const cint_datatype_t* dt);
extern int
cint_datatype_traverse(int flags, cint_datatype_traverse_t cb, void* cookie);
extern char*
cint_datatype_format(const cint_datatype_t* dt, int alloc);
extern char*
cint_datatype_format_pd(const cint_parameter_desc_t* pd, int alloc);
extern void cint_datatype_clear(void);
extern int cint_datatype_add_atomics(cint_atomic_type_t* types);
extern int cint_datatype_add_data(cint_data_t* data, void *dlhandle);
extern int cint_datatype_add_function(cint_function_t* f);
extern int cint_datatype_add_structure(cint_struct_type_t* s);
extern int cint_datatype_add_enumeration(cint_enum_type_t* cet);
extern int cint_datatype_constant_find(const char* name, int* c);
extern int cint_datatype_checkall(int print);
extern void cint_datatype_clear_structure(cint_struct_type_t* structure);
extern void cint_datatype_clear_function(cint_function_t* function);
extern void cint_datatype_clear_enumeration(cint_enum_type_t* enumeration);
extern void cint_datatype_delete_function(const char* fname);
extern void cint_datatype_delete_type_cache(const char* fname);
#endif /* __CINT_DATATYPES_H__ */
|
lizwjiang/cgv
|
cgv-core/src/test/java/org/g4/certificate/Test.java
|
<filename>cgv-core/src/test/java/org/g4/certificate/Test.java
package org.g4.certificate;
import org.g4.certificate.facade.CertLogger;
import java.io.UnsupportedEncodingException;
/**
* Created with IntelliJ IDEA.
* User: <NAME>
* Date: 11/6/13
* Time: 5:08 PM
*/
public class Test {
public static void main(String[] args) throws UnsupportedEncodingException {
/* Map m = System.getenv();
for (Iterator it = m.keySet().iterator(); it.hasNext(); ) {
String key = (String) it.next();
String value = (String) m.get(key);
System.out.println(key + " : " + value);
}*/
/* Properties p = System.getProperties();
p.setProperty("file.separator","/");
for ( Iterator it = p.keySet().iterator(); it.hasNext(); ){
String key = (String ) it.next();
String value = (String ) p.get(key);
System.out.println(key +" = " +value);
}*/
/* System.out.println(Test.class.getResource("/").getPath().toString());
String s = "c:\\abc\\123.keystore";
System.out.println(System.getProperty("jre.home"));
String url = Test.class.getProtectionDomain().getCodeSource().getLocation().getFile();
String l = URLDecoder.decode(Test.class.getProtectionDomain().getCodeSource().getLocation().getFile(), "UTF-8");
System.out.println(l);
Reader reader =new InputStreamReader(Test.class.getClassLoader().getResourceAsStream("/a.txt"));*/
/*String currentPath = Test.class.getResource("/").getPath().toString();
System.out.println(currentPath);
FileUtil.createFile(currentPath + "Johnson_test.txt");
try {
//1. Class.getResourceAsStream(String path), if the path doesn't start with /, the path will be started from the package the current class belongs to,
//if starting with /, that means the path will be started from the root of classpath.
//2. Class.getClassLoader.getResourceAsStream(String path), by default, the path is started from the root of classpath, so the path should not start with /
InputStream is = Test.class.getResourceAsStream("/com/hp/servicemanager/certificate/resources/openssl.exe");
if(is == null) System.out.println(" is is null");
FileUtil.createFile(is, "c:/openssl.exe");
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}*/
//System.out.println(FileUtil.getJarCurrentPath());
//CertGen.generateAllCertificates4SMTSO();
/* File f = new File("C:/Program Files (x86)/Java/jre7/lib/security/cacerts");
if(f.exists()) System.out.println("file exists");*/
/*String path = "abcde123/";
path = path.substring(0, path.lastIndexOf("/"));
System.out.println(path);*/
/*
String cmd="D:/Program Files (x86)";
System.out.println(CertUtil.analyzeSpace(cmd));*/
/*String cmd[] = new String[]{
"cmd ", "/c",
"start",
"keytool",
"-genkey"};
CertificateExecutor.execCommand(cmd, new File("C:/Program Files (x86)/Java/jre7/bin"));*/
/* Runtime runtime = Runtime.getRuntime();
NumberFormat format = NumberFormat.getInstance();
StringBuilder sb = new StringBuilder();
long maxMemory = runtime.maxMemory();
long allocatedMemory = runtime.totalMemory();
long freeMemory = runtime.freeMemory();
sb.append("free memory: " + format.format(freeMemory / (1024 * 1024)) + " MB\n");
sb.append("allocated memory: " + format.format(allocatedMemory / (1024 * 1024)) + " MB\n");
sb.append("max memory: " + format.format(maxMemory / (1024 * 1024)) + "MB\n");
sb.append("total free memory: " + format.format((freeMemory + (maxMemory - allocatedMemory)) / (1024 * 1024)) + "MB\n");
System.out.println(sb.toString());*/
/* String path = "E:\\TSO_test\\TSO";
FileUtil.getFileList(path);
Map<String, String> testMap = new HashMap<String, String>();
testMap.put("test1","test1");
testMap.put("test","");
String abc = testMap.get("test");
System.out.println(abc);*/
//KeyToolFacade.getEnvJREPath();
/*
CertLogger logger = CertLogger.getLogger("test");
logger.info("Test");*/
CertLogger logger = CertLogger.getLogger(Test.class.getName());
logger.debug("Johnson testing.........................................................");
}
}
|
renovate-bot/java-gkehub
|
proto-google-cloud-gkehub-v1beta/src/main/java/com/google/cloud/gkehub/multiclusteringress/v1beta/MultiClusterIngressProto.java
|
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/gkehub/v1beta/multiclusteringress/multiclusteringress.proto
package com.google.cloud.gkehub.multiclusteringress.v1beta;
public final class MultiClusterIngressProto {
private MultiClusterIngressProto() {}
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {}
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry);
}
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_gkehub_multiclusteringress_v1beta_FeatureSpec_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_gkehub_multiclusteringress_v1beta_FeatureSpec_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor descriptor;
static {
java.lang.String[] descriptorData = {
"\nHgoogle/cloud/gkehub/v1beta/multicluste"
+ "ringress/multiclusteringress.proto\022.goog"
+ "le.cloud.gkehub.multiclusteringress.v1be"
+ "ta\032\034google/api/annotations.proto\"r\n\013Feat"
+ "ureSpec\022\031\n\021config_membership\030\001 \001(\t\022H\n\007bi"
+ "lling\030\002 \001(\01627.google.cloud.gkehub.multic"
+ "lusteringress.v1beta.Billing*I\n\007Billing\022"
+ "\027\n\023BILLING_UNSPECIFIED\020\000\022\021\n\rPAY_AS_YOU_G"
+ "O\020\001\022\022\n\016ANTHOS_LICENSE\020\002B\312\002\n2com.google.c"
+ "loud.gkehub.multiclusteringress.v1betaB\030"
+ "MultiClusterIngressProtoP\001Zagoogle.golan"
+ "g.org/genproto/googleapis/cloud/gkehub/m"
+ "ulticlusteringress/v1beta;multiclusterin"
+ "gress\252\002.Google.Cloud.GkeHub.MultiCluster"
+ "Ingress.V1Beta\312\002.Google\\Cloud\\GkeHub\\Mul"
+ "tiClusterIngress\\V1beta\352\0022Google::Cloud:"
+ ":GkeHub::MultiClusterIngress::V1betab\006pr"
+ "oto3"
};
descriptor =
com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(
descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
com.google.api.AnnotationsProto.getDescriptor(),
});
internal_static_google_cloud_gkehub_multiclusteringress_v1beta_FeatureSpec_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_google_cloud_gkehub_multiclusteringress_v1beta_FeatureSpec_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_gkehub_multiclusteringress_v1beta_FeatureSpec_descriptor,
new java.lang.String[] {
"ConfigMembership", "Billing",
});
com.google.api.AnnotationsProto.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
|
danr-amz/amazon-ssm-agent
|
agent/plugins/configurepackage/envdetect/constants/constants.go
|
package constants
// PlatformFamily marks a family of similar operating systems
// PlatformFamilyWindows uses Ohai identifier for windows platform family
const PlatformFamilyWindows = "windows"
// PlatformFamilyDarwin uses Ohai identifier for darwin platform family
const PlatformFamilyDarwin = "mac_os_x"
// PlatformFamilyDebian uses Ohai identifier for debian platform family
const PlatformFamilyDebian = "debian"
// PlatformFamilyRhel uses Ohai identifier for rhel platform family
const PlatformFamilyRhel = "rhel"
// PlatformFamilyFedora uses Ohai identifier for fedora platform family
const PlatformFamilyFedora = "fedora"
// PlatformFamilyAlpine uses Ohai identifier for alpine platform family
const PlatformFamilyAlpine = "alpine"
// PlatformFamilySuse uses Ohai identifier for opensuse platform family
const PlatformFamilySuse = "suse"
// PlatformFamilyGentoo uses Ohai identifier for gentoo linux platform family
const PlatformFamilyGentoo = "gentoo"
// PlatformFamilyArch uses Ohai identifier for arch linux platform family
const PlatformFamilyArch = "arch"
// Platform marks a specific operating systems
// PlatformDebian uses Ohai identifier for debian platform
const PlatformDebian = "debian"
// PlatformUbuntu uses Ohai identifier for ubuntu platform
const PlatformUbuntu = "ubuntu"
// PlatformRaspbian uses Ohai identifier for raspbian platform
const PlatformRaspbian = "raspbian"
// PlatformRedhat uses Ohai identifier for redhat platform
const PlatformRedhat = "redhat"
// PlatformOracleLinux uses Ohai identifier for oracle linux platform
const PlatformOracleLinux = "oracle"
// PlatformCentos uses Ohai identifier for centos platform
const PlatformCentos = "centos"
// PlatformFedora uses Ohai identifier for fedora platform
const PlatformFedora = "fedora"
// PlatformAmazon uses Ohai identifier for amazon platform
const PlatformAmazon = "amazon"
// PlatformAlpine uses Ohai identifier for alpine platform
const PlatformAlpine = "alpine"
// PlatformSuse uses Ohai identifier for suse platform
const PlatformSuse = "suse"
// PlatformOpensuse uses Ohai identifier for opensuse platform version < 42
const PlatformOpensuse = "opensuse"
// PlatformOpensuseLeap uses Ohai identifier for amazon platform version >= 42
const PlatformOpensuseLeap = "opensuseleap"
// PlatformGentoo uses Ohai identifier for gentoo platform
const PlatformGentoo = "gentoo"
// PlatformArch uses Ohai identifier for arch platform
const PlatformArch = "arch"
// PlatformWindows uses Ohai identifier for windows platform
const PlatformWindows = "windows"
// PlatformDarwin uses Ohai identifier for darwin platform
const PlatformDarwin = "mac_os_x"
// OperatingSystemSKUs to denote Windows Nano installations
const SKUProductDatacenterNanoServer = "143"
const SKUProductStandardNanoServer = "144"
// Init marks a init system used by the Operating Sysstem
// InitSystemd uses identifier for systemd init system
const InitSystemd = "systemd"
// InitUpstart uses identifier for upstart init system
const InitUpstart = "upstart"
// InitChkconfig uses identifier for chkconfig init system (RHEL)
const InitChkconfig = "chkconfig"
// InitUpdatercd uses Ohai identifier for update-rc.d init system (Debian)
const InitUpdatercd = "updatercd"
// InitOpenrc uses identifier for openrc init system (Gentoo)
const InitOpenrc = "openrc"
// InitService uses identifier for undetected init systems but available
// `service` command to start/stop/restart services
const InitService = "service"
// InitDocker uses docker identifier for systems running inside of docker
// Those systems typically don't use the system init system and instead using a
// shell (bash, sh), a supervisor (runit, supervisord) or just a arbitrary
// command as pid1. Any service control would not work as for systems outside
// of docker.
const InitDocker = "docker"
// InitWindows uses windows identifier for windows init system
const InitWindows = "windows"
// InitLaunchd uses launchd for mac os x init system
const InitLaunchd = "launchd"
// constants for package manager used by the operating system
//
// multiple package manager might be installed but only the main manager for
// the platform is relevant.
//
// Ohai does not detect the package manager so using Ohai identifier does not
// work.
//
// Linux often have a low level package manager (for install, uninstall) and a
// high level package manager (for fetching and dependencies). (dpkg -> apt,
// rpm -> yum, rpm -> dnf, rpm -> zypper, portage -> emerge). Because its easy
// to determine the lower level package manager from the higher level but not
// the other way round we use high level package managers for detection.
// PackageManagerMac is always `mac_os_x` when running on Mac OS X. There are
// multiple competing package formates (.pkg, .dmg, brew, ...) so it depends on
// the use case.
const PackageManagerMac = "mac_os_x"
// PackageManagerWindows is always `windows` when running on Windows systems.
// There are multiple competing package formates (.msi, .exe, chocolatey, ...)
// so it depends on the use case.
const PackageManagerWindows = "windows"
// PackageManagerApt is used on Debian platform families (ubuntu, mate, ...)
const PackageManagerApt = "apt"
// PackageManagerYum is used on RHEL platform families (centos, red hat, amazon, ...)
const PackageManagerYum = "yum"
// PackageManagerPacman is used on ArchLinux
const PackageManagerPacman = "pacman"
// PackageManagerZipper is used on SuSe platform families (OpenSuse, SLES, ...)
const PackageManagerZipper = "zypper"
// PackageManagerAlpine is used on Alpine Linux
const PackageManagerAlpine = "alpine"
// PackageManagerDnf is used on Fedora
const PackageManagerDnf = "dnf"
// PackageManagerEmerge is used on Gentoo platform families (Gentoo, Funtoo, ...)
const PackageManagerEmerge = "emerge"
|
dperl-sol/cctbx_project
|
mmtbx/refinement/real_space/tst_fit_residue_0H.py
|
from __future__ import absolute_import, division, print_function
import time
import mmtbx.refinement.real_space.fit_residues
import mmtbx.refinement.real_space
pdb_answer = """\
CRYST1 15.538 12.841 13.194 90.00 90.00 90.00 P 1 0
SCALE1 0.064358 0.000000 0.000000 0.00000
SCALE2 0.000000 0.077876 0.000000 0.00000
SCALE3 0.000000 0.000000 0.075792 0.00000
ATOM 2006 N MSE B 37 8.282 9.046 6.190 1.00 10.00 N
ATOM 2007 CA MSE B 37 6.863 8.719 6.123 1.00 10.00 C
ATOM 2008 C MSE B 37 6.057 9.906 5.608 1.00 10.00 C
ATOM 2009 O MSE B 37 5.000 9.734 5.000 1.00 10.00 O
ATOM 2010 CB MSE B 37 6.347 8.291 7.498 1.00 10.00 C
ATOM 2011 CG MSE B 37 7.044 7.066 8.067 1.00 10.00 C
ATOM 2012 SE MSE B 37 6.355 6.551 9.817 1.00 10.00 Se
ATOM 2013 CE MSE B 37 7.491 5.000 10.145 1.00 10.00 C
ATOM 0 HA MSE B 37 6.740 7.889 5.427 1.00 10.00 H
ATOM 0 HB2 MSE B 37 6.468 9.121 8.194 1.00 10.00 H
ATOM 0 HB3 MSE B 37 5.279 8.088 7.426 1.00 10.00 H
ATOM 0 HG2 MSE B 37 6.926 6.232 7.375 1.00 10.00 H
ATOM 0 HG3 MSE B 37 8.113 7.265 8.146 1.00 10.00 H
ATOM 0 HE1 MSE B 37 7.241 4.564 11.112 1.00 10.00 H
ATOM 0 HE2 MSE B 37 7.331 4.259 9.361 1.00 10.00 H
ATOM 0 HE3 MSE B 37 8.537 5.308 10.145 1.00 10.00 H
TER
"""
pdb_poor0 = """\
CRYST1 15.538 12.841 13.194 90.00 90.00 90.00 P 1
ATOM 2006 N MSE B 37 8.282 9.046 6.190 1.00 10.00 N
ATOM 2007 CA MSE B 37 6.863 8.719 6.123 1.00 10.00 C
ATOM 2008 C MSE B 37 6.057 9.906 5.608 1.00 10.00 C
ATOM 2009 O MSE B 37 5.000 9.734 5.000 1.00 10.00 O
ATOM 2010 CB MSE B 37 6.347 8.291 7.498 1.00 10.00 C
ATOM 2011 CG MSE B 37 4.889 7.862 7.506 1.00 10.00 C
ATOM 2012 SE MSE B 37 4.305 7.207 9.247 1.00 10.00 Se
ATOM 2013 CE MSE B 37 5.093 5.424 9.180 1.00 10.00 C
ATOM 9 HA MSE B 37 6.740 7.889 5.427 1.00 10.00 H
ATOM 10 HB2 MSE B 37 6.960 7.467 7.864 1.00 10.00 H
ATOM 11 HB3 MSE B 37 6.475 9.118 8.196 1.00 10.00 H
ATOM 12 HG2 MSE B 37 4.265 8.705 7.212 1.00 10.00 H
ATOM 13 HG3 MSE B 37 4.740 7.081 6.760 1.00 10.00 H
ATOM 14 HE1 MSE B 37 4.863 4.890 10.101 1.00 10.00 H
ATOM 15 HE2 MSE B 37 4.682 4.876 8.331 1.00 10.00 H
ATOM 16 HE3 MSE B 37 6.174 5.507 9.069 1.00 10.00 H
TER
"""
def exercise(pdb_poor_str, i_pdb, d_min = 1.0, resolution_factor = 0.1):
"""
Fit one non-standard residue: MSE with H.
"""
#
t = mmtbx.refinement.real_space.setup_test(
pdb_answer = pdb_answer,
pdb_poor = pdb_poor_str,
i_pdb = i_pdb,
d_min = d_min,
residues = ["MSE"],
resolution_factor = resolution_factor)
#
result = mmtbx.refinement.real_space.fit_residues.run(
pdb_hierarchy = t.ph_poor,
vdw_radii = t.vdw,
crystal_symmetry = t.crystal_symmetry,
map_data = t.target_map,
backbone_sample = True,
rotatable_hd = t.rotatable_hd,
rotamer_manager = t.rotamer_manager,
sin_cos_table = t.sin_cos_table,
mon_lib_srv = t.mon_lib_srv)
result.pdb_hierarchy.write_pdb_file(file_name = "refined_%s.pdb"%str(i_pdb))
#
mmtbx.refinement.real_space.check_sites_match(
ph_answer = t.ph_answer,
ph_refined = result.pdb_hierarchy,
tol = 0.5)
if(__name__ == "__main__"):
t0 = time.time()
for i_pdb, pdb_poor_str in enumerate([pdb_poor0,]):
exercise(
pdb_poor_str = pdb_poor_str,
i_pdb = i_pdb)
print("Time: %6.4f"%(time.time()-t0))
|
usenixatc2021/SoftRefresh_Scheduling
|
linsched-linsched-alpha/lib/dynamic_queue_limits.c
|
<gh_stars>0
/*
* Dynamic byte queue limits. See include/linux/dynamic_queue_limits.h
*
* Copyright (c) 2011, <NAME> <<EMAIL>>
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/ctype.h>
#include <linux/kernel.h>
#include <linux/dynamic_queue_limits.h>
#define POSDIFF(A, B) ((A) > (B) ? (A) - (B) : 0)
/* Records completed count and recalculates the queue limit */
void dql_completed(struct dql *dql, unsigned int count)
{
unsigned int inprogress, prev_inprogress, limit;
unsigned int ovlimit, all_prev_completed, completed;
/* Can't complete more than what's in queue */
BUG_ON(count > dql->num_queued - dql->num_completed);
completed = dql->num_completed + count;
limit = dql->limit;
ovlimit = POSDIFF(dql->num_queued - dql->num_completed, limit);
inprogress = dql->num_queued - completed;
prev_inprogress = dql->prev_num_queued - dql->num_completed;
all_prev_completed = POSDIFF(completed, dql->prev_num_queued);
if ((ovlimit && !inprogress) ||
(dql->prev_ovlimit && all_prev_completed)) {
/*
* Queue considered starved if:
* - The queue was over-limit in the last interval,
* and there is no more data in the queue.
* OR
* - The queue was over-limit in the previous interval and
* when enqueuing it was possible that all queued data
* had been consumed. This covers the case when queue
* may have becomes starved between completion processing
* running and next time enqueue was scheduled.
*
* When queue is starved increase the limit by the amount
* of bytes both sent and completed in the last interval,
* plus any previous over-limit.
*/
limit += POSDIFF(completed, dql->prev_num_queued) +
dql->prev_ovlimit;
dql->slack_start_time = jiffies;
dql->lowest_slack = UINT_MAX;
} else if (inprogress && prev_inprogress && !all_prev_completed) {
/*
* Queue was not starved, check if the limit can be decreased.
* A decrease is only considered if the queue has been busy in
* the whole interval (the check above).
*
* If there is slack, the amount of execess data queued above
* the the amount needed to prevent starvation, the queue limit
* can be decreased. To avoid hysteresis we consider the
* minimum amount of slack found over several iterations of the
* completion routine.
*/
unsigned int slack, slack_last_objs;
/*
* Slack is the maximum of
* - The queue limit plus previous over-limit minus twice
* the number of objects completed. Note that two times
* number of completed bytes is a basis for an upper bound
* of the limit.
* - Portion of objects in the last queuing operation that
* was not part of non-zero previous over-limit. That is
* "round down" by non-overlimit portion of the last
* queueing operation.
*/
slack = POSDIFF(limit + dql->prev_ovlimit,
2 * (completed - dql->num_completed));
slack_last_objs = dql->prev_ovlimit ?
POSDIFF(dql->prev_last_obj_cnt, dql->prev_ovlimit) : 0;
slack = max(slack, slack_last_objs);
if (slack < dql->lowest_slack)
dql->lowest_slack = slack;
if (time_after(jiffies,
dql->slack_start_time + dql->slack_hold_time)) {
limit = POSDIFF(limit, dql->lowest_slack);
dql->slack_start_time = jiffies;
dql->lowest_slack = UINT_MAX;
}
}
/* Enforce bounds on limit */
limit = clamp(limit, dql->min_limit, dql->max_limit);
if (limit != dql->limit) {
dql->limit = limit;
ovlimit = 0;
}
dql->adj_limit = limit + completed;
dql->prev_ovlimit = ovlimit;
dql->prev_last_obj_cnt = dql->last_obj_cnt;
dql->num_completed = completed;
dql->prev_num_queued = dql->num_queued;
}
EXPORT_SYMBOL(dql_completed);
void dql_reset(struct dql *dql)
{
/* Reset all dynamic values */
dql->limit = 0;
dql->num_queued = 0;
dql->num_completed = 0;
dql->last_obj_cnt = 0;
dql->prev_num_queued = 0;
dql->prev_last_obj_cnt = 0;
dql->prev_ovlimit = 0;
dql->lowest_slack = UINT_MAX;
dql->slack_start_time = jiffies;
}
EXPORT_SYMBOL(dql_reset);
int dql_init(struct dql *dql, unsigned hold_time)
{
dql->max_limit = DQL_MAX_LIMIT;
dql->min_limit = 0;
dql->slack_hold_time = hold_time;
dql_reset(dql);
return 0;
}
EXPORT_SYMBOL(dql_init);
|
jojochuang/eventwave
|
application/heartbeat/scheduler.cc
|
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <pthread.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>
#include <string>
#include "SysUtil.h"
#include "lib/mace.h"
#include "mlist.h"
#include "RandomUtil.h"
#include "mace-macros.h"
#include <ScopedLock.h>
#include "Event.h"
#include "HierarchicalContextLock.h"
#include "TcpTransport-init.h"
#include "CondorHeartBeat-init.h"
#include "load_protocols.h"
#include "ContextJobNode.h"
//global variables
static bool isClosed = false;
class ContextJobScheduler: public ContextJobNode{
public:
ContextJobScheduler(){
choosePool();
setSchedulerPort();
SysUtil::signal(SIGABRT, &ContextJobScheduler::shutdownHandler);
SysUtil::signal(SIGHUP, &ContextJobScheduler::shutdownHandler);
SysUtil::signal(SIGTERM, &ContextJobScheduler::shutdownHandler);
SysUtil::signal(SIGINT, &ContextJobScheduler::shutdownHandler);
SysUtil::signal(SIGSEGV, &ContextJobScheduler::shutdownHandler);
SysUtil::signal(SIGCHLD, &ContextJobScheduler::shutdownHandler);
SysUtil::signal(SIGQUIT, &ContextJobScheduler::shutdownHandler);
//SysUtil::signal(SIGCONT, &ContextJobScheduler::shutdownHandler);
}
void start(){
ContextJobNode::start();
if( params::get<bool>("norelaunch", 0 ) ){
std::cout<<"will not maintain spared process pool actively"<<std::endl;
}
if( params::containsKey("script") ){
executeScript( );
}else{
createShell();
}
}
private:
void setSchedulerPort(){
/*std::string masterAddr = params::get<std::string>("MACE_AUTO_BOOTSTRAP_PEERS");
size_t i = masterAddr.find(":");
if( i != std::string::npos ){
params::set("MACE_PORT", masterAddr.substr( i+ 1 ) );
}*/
}
void choosePool(){
if( params::containsKey("pool") ){
if( params::get<std::string>("pool") == std::string("cloud") ){
std::cout<<"use cloud machines to run jobs"<<std::endl;
}else if(params::get<std::string>("pool") == std::string("condor") ) {
std::cout<<"use condor machines to run jobs"<<std::endl;
}else if(params::get<std::string>("pool") == std::string("ec2") ) {
std::cout<<"use amazon EC2 machines to run jobs"<<std::endl;
}
}else if( params::containsKey("cloud") ){
std::cout<<"use cloud machines to run jobs"<<std::endl;
}else if( params::containsKey("condor") ){
std::cout<<"use condor machines to run jobs"<<std::endl;
}else if( params::containsKey("ec2") ){
std::cout<<"use amazon EC2 machines to run jobs"<<std::endl;
}else{
while(true){
std::cout<<"Choose 'cloud' or 'condor' to run job?"<<std::endl;
char choicebuf[256];
std::cin.getline(choicebuf, 256);
if( strncmp(choicebuf,"cloud",5)==0 ){
params::set("pool", "cloud");
break;
}else if( strncmp(choicebuf,"condor",6)==0 ){
params::set("pool", "condor");
break;
}else{
}
}
}
}
static void printHelp(){
std::cout<<"'exit' to shutdown job manager."<<std::endl;
std::cout<<"'start _spec_ _input_' to start service.(input file name is optional)"<<std::endl;
std::cout<<"'show job' to view status of running services"<<std::endl;
std::cout<<"'show node' to view status of nodes"<<std::endl;
std::cout<<"'kill all' to terminate all nodes"<<std::endl;
std::cout<<"'kill _number_' to terminate some nodes"<<std::endl;
std::cout<<"'migrate _jobid_ node _number_' to migrate nodes. (injected failure, obsoleted now)"<<std::endl;
std::cout<<"'migrate _jobid_ context _contextid_' to migrate nodes."<<std::endl;
std::cout<<"'migrate _jobid_ rootcontext _contextid_' to migrate nodes."<<std::endl;
std::cout<<"'log _jobid_ _procid_ ' to examine logs of the unit_app process."<<std::endl;
std::cout<<"'hblog _jobid_ _procid_ ' to examine logs of the heartbeat process."<<std::endl;
std::cout<<"'split _jobid_ _nodeid_' to split contexts on node into half."<<std::endl;
std::cout<<"'help' to show help menu."<<std::endl;
}
static int32_t executeCommon(istream& iss, int32_t cmdNo = -1){
char cmdbuf[256];
iss>>cmdbuf;
if( iss.bad() || iss.fail() ){
if( cmdNo != -1 )
std::cerr<<"Can't read command at line "<<cmdNo<<"."<<std::endl;
return -1;
}
std::string atLine;
if( cmdNo != -1 )
atLine = " at line "+boost::lexical_cast<std::string>(cmdNo)+".";
if( strcmp( cmdbuf, "sleep") == 0 ){
int period;
iss>>period;
if( iss.fail() ){
std::cerr<<"failed to read sleep time. (not a number?)"<<std::endl;
}else if( period >= 0 ){
sleep( period );
}else{
std::cerr<<"sleep time less than zero"<<std::endl;
}
}else if( strcmp(cmdbuf, "show") == 0 ){
iss>>cmdbuf;
if( iss.fail() ){
std::cerr<<"can't read properly after 'show'"<<atLine<<std::endl;
}else if( strcmp( cmdbuf, "job") == 0 )
heartbeatApp->showJobStatus();
else if( strcmp( cmdbuf,"node") == 0 )
heartbeatApp->showNodeStatus();
else{
std::cerr<<"Unexpected command parameter"<<atLine<<std::endl;
}
}else if( strcmp( cmdbuf, "migrate") == 0 ){
uint32_t jobID;
iss>>jobID;
if( iss.fail() ){
std::cerr<<"failed to read context name"<<std::endl;
}else{
iss>>cmdbuf;
if( strcmp( cmdbuf, "node" ) == 0 ){
int32_t migrateCount;
iss>>migrateCount;
if( iss.fail() ){
std::cerr<<"failed to read number of migrated nodes. (not a number?)"<<std::endl;
}else if( migrateCount > 0 ){
heartbeatApp->terminateRemote(migrateCount, 1);
}else{
std::cerr<<"invalid number: need to be larger than zero"<<std::endl;
}
}else if( strcmp( cmdbuf, "context" ) == 0 ){
iss>>cmdbuf;
if( iss.fail() ){
std::cerr<<"failed to read context name"<<std::endl;
}else{
MaceAddr nullAddr;
heartbeatApp->migrateContext(jobID, cmdbuf, nullAddr, false );
}
}else if( strcmp( cmdbuf, "rootcontext" ) == 0 ){
iss>>cmdbuf;
if( iss.fail() ){
std::cerr<<"failed to read context name"<<std::endl;
}else{
MaceAddr nullAddr;
heartbeatApp->migrateContext(jobID, cmdbuf, nullAddr, true );
}
}else{ // unexpect command
std::cerr<<"Unexpected command parameter"<<atLine<<std::endl;
}
}
}else if( strcmp( cmdbuf, "split") == 0 ){
uint32_t jobID;
iss>>jobID;
iss>>cmdbuf;
MaceKey nodeKey(ipv4, cmdbuf);
heartbeatApp->splitNodeContext(jobID, nodeKey.getMaceAddr() );
}else if( strcmp( cmdbuf, "launch_heartbeat") == 0 ){
}else if( strcmp( cmdbuf,"start") == 0 ){
char jobspecfile[256];
char jobinputfile[256];
iss>>jobspecfile;
if( iss.eof() ){
heartbeatApp->startService( jobspecfile,"" );
}else{
iss>>jobinputfile;
heartbeatApp->startService( jobspecfile,jobinputfile );
}
}else if( strcmp( cmdbuf, "kill") == 0 ){
iss>>cmdbuf;
if( strcmp( cmdbuf,"all") == 0 ){
heartbeatApp->terminateRemoteAll();
}else{
uint32_t migrateCount;
iss>>migrateCount;
heartbeatApp->terminateRemote(migrateCount, 0);
}
}else if( strcmp( cmdbuf,"print") == 0 ){
iss.getline( cmdbuf, sizeof(cmdbuf) );
std::cout<< cmdbuf << std::endl;
}else if( strcmp( cmdbuf,"log") == 0 ){
if( !params::containsKey("logdir") ){
std::cout<<"parameter 'logdir' undefined"<<atLine<<std::endl;
return 0;
}
char cmdbuf[256];
uint32_t jobid;
uint32_t nodeid;
mace::string nodeHostName;
uint32_t node_unixpid;
uint32_t uniapp_unixpid;
iss>>jobid;
if( iss.eof() ){
std::cout<<"Not enough parameters"<<std::endl;
}
iss>>nodeid;
if( heartbeatApp->getNodeInfo( jobid, nodeid, nodeHostName, node_unixpid, uniapp_unixpid ) ){
sprintf(cmdbuf, "ssh %s \"cat %s/ua/%d/*\" |less", nodeHostName.c_str(),params::get<std::string>("logdir").c_str(), uniapp_unixpid );
int n = system( cmdbuf );
if( n == -1 ){ perror("system"); }
}
}else if( strcmp( cmdbuf,"hblog") == 0 ){
if( !params::containsKey("logdir") ){
std::cout<<"parameter 'logdir' undefined"<<atLine<<std::endl;
return 0;
}
char cmdbuf[256];
uint32_t jobid;
uint32_t nodeid;
mace::string nodeHostName;
uint32_t node_unixpid;
uint32_t uniapp_unixpid;
iss>>jobid>>nodeid;
if( heartbeatApp->getNodeInfo( jobid, nodeid, nodeHostName, node_unixpid, uniapp_unixpid ) ){
sprintf(cmdbuf, "ssh %s \"cat %s/hb/%d/*\" |less", nodeHostName.c_str(),params::get<std::string>("logdir").c_str(), node_unixpid );
int n = system( cmdbuf );
if( n == -1 ){ perror("system"); }
}
}else if( strcmp( cmdbuf,"exit") == 0 ){
isClosed = true;
return -1;
}else if( strcmp( cmdbuf,"?") == 0 || strcmp( cmdbuf,"help") == 0 ){
printHelp();
}else if( strncmp( cmdbuf, "#", 1 ) == 0 ){
return 0;
}else{
std::cerr<<"Unrecognized command: '"<< cmdbuf<<"'"<<atLine<<std::endl;
}
return 0;
}
static void executeScript( ){
mace::string script = params::get<mace::string>("script");
std::fstream fp( script.c_str(), std::fstream::in );
if( fp.is_open() ){
std::cout<<"executing script file '"<< script<< "'"<<std::endl;
}else{
std::cerr<<"Failed to open script file '"<< script <<"'. Ignore it."<<std::endl;
fp.close();
return;
}
char buf[256];
mace::list< mace::string > command;
while( fp.good() ){
fp.getline( buf, 256 );
command.push_back( mace::string(buf) );
}
fp.close();
// execute each line
uint32_t cmdNo=0;
for( mace::list<mace::string >::iterator cmdIt=command.begin(); cmdIt != command.end(); cmdNo++,cmdIt ++){
istringstream iss( *cmdIt );
if( executeCommon( iss, cmdNo ) < 0 ){
break;
}
}
}
static void *schedulerShell(void *threadid){
std::cout<<"For help, type 'help' or '?'"<<std::endl;
std::cin.exceptions( std::ios::badbit | std::ios::eofbit | std::ios::failbit );
while(true){
std::cout<<">>> ";
std::string cmd;
try{
getline(std::cin, cmd);
}catch( std::ios_base::failure& ex ){
std::cout<< ex.what() << std::endl;
break;
}
if( cmd.size() == 0 )continue;
istringstream iss(cmd );
if( ContextJobScheduler::executeCommon( iss ) < 0 ){
break;
}
}
isClosed = true;
pthread_exit(NULL);
return NULL;
}
void createShell(){
pthread_t shellThread;
int rc = pthread_create( &shellThread, NULL, ContextJobScheduler::schedulerShell, (void *)NULL );
if( rc != 0 ){
errno = rc;
perror("pthread_create() failed");
exit(EXIT_FAILURE);
}
void *status;
rc = pthread_join(shellThread, &status);
if( rc != 0 ){
errno = rc;
perror("pthread_join() failed");
exit(EXIT_FAILURE);
}
}
static void shutdownHandler(int signum){
if( signum == SIGINT ){ // ctrl+c pressed
isClosed = true;
}
if( signum == SIGTERM){
isClosed = true;
}
if( signum == SIGHUP ){
isClosed = false; // ignore SIGHUP. this was the bug from Condor
}
}
};
int main(int argc, char* argv[]) {
ADD_SELECTORS("main");
mace::Init(argc, argv);
load_protocols(); // enable service configuration
ContextJobNode* node;
node = new ContextJobScheduler();
params::print(stdout);
node->start();
while( isClosed == false ){
SysUtil::sleepm(100);
}
node->stop();
delete node;
return EXIT_SUCCESS;
}
|
CodeWall-EStudio/SWall
|
client/android/TRA/TRA/src/com/swall/tra/AvailableFrame.java
|
package com.swall.tra;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.swall.tra.adapter.ActivitiesListAdapter;
import com.swall.tra.model.TRAInfo;
import com.swall.tra.network.ActionListener;
import com.swall.tra.network.ServiceManager;
import com.swall.tra.utils.JSONUtils;
import com.swall.tra_demo.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by pxz on 13-12-28.
*/
public class AvailableFrame extends TabFrame implements AdapterView.OnItemClickListener {
private final static int MSG_REFRESH = 0;
private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch(msg.what){
case MSG_REFRESH:
app.doAction(ServiceManager.Constants.ACTION_GET_AVAILABLE_ACTIVITIES, defaultRequestData, listListener);
break;
}
}
};
private int mAutoRetryCount = 0;
private static final int RETRY_MAX = 5;
@Override
public View onCreateView(LayoutInflater inflater) {
mView = inflater.inflate(R.layout.activities_list,null);
// mListView = (ListView)findViewById(R.id.listview);
pullToRefreshListView = (PullToRefreshListView)findViewById(R.id.listview);
pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
@Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
mHandler.sendEmptyMessage(MSG_REFRESH);
}
});
mListView = pullToRefreshListView.getRefreshableView();
mAdapter = new ActivitiesListAdapter(getActivity());
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(this);
listListener = new ActionListener(getActivity()) {
@Override
public void onReceive(int action, Bundle data) {
Activity activity = getActivity();
if(activity == null)return;
pullToRefreshListView.onRefreshComplete();
if(data == null){
// TODO
showEmptyOrShowError();
return;
}
if(getActivity().isFinishing()){
return;
}
String str = data.getString("result");
Log.i("SWall", TAG + " " + str);
try {
JSONObject obj = new JSONObject(str);
JSONObject resultObject = JSONUtils.getJSONObject(obj, "r", new JSONObject());
// JSONArray array = JSONUtils.getJSONArray(resultObject, "activities", new JSONArray());
mAdapter.setJSONData(resultObject);
} catch (JSONException e) {
// DO nothing
e.printStackTrace();
showEmptyOrShowError();
}
}
};
app.doAction(ServiceManager.Constants.ACTION_GET_AVAILABLE_ACTIVITIES, defaultRequestData, listListener);
return mView;
}
private void showEmptyOrShowError() {
Activity activity = getActivity();
if(activity == null || activity.isFinishing()){
return;
}
Toast.makeText(getActivity(),"暂无数据,请稍后下拉刷新...",Toast.LENGTH_LONG).show();
/*
mAutoRetryCount ++;
if(RETRY_MAX > mAutoRetryCount){
Toast.makeText(getActivity(),"暂无数据,5秒后重新刷新...",Toast.LENGTH_SHORT).show();
mHandler.sendEmptyMessageDelayed(MSG_REFRESH,5000);
}else{
//TODO
Toast.makeText(getActivity(),"无数据,请稍候再打开本程序",Toast.LENGTH_SHORT).show();
getActivity().finish();
}
*/
}
@Override
public void onDestroy(){
super.onDestroy();
app.removeObserver(listListener);
mHandler.removeMessages(MSG_REFRESH);
}
private ListView mListView;
private ActivitiesListAdapter mAdapter;
private ActionListener listListener;
private PullToRefreshListView pullToRefreshListView;
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
TRAInfo info = (TRAInfo)adapterView.getAdapter().getItem(position);
Intent i = new Intent(getActivity(),TRAInfoActivity.class);
Bundle bundle = new Bundle();
Log.i("JSON", info.toString());
bundle.putString("result", info.toString());
bundle.putBoolean("joinable", true);
i.putExtras(bundle);
startActivity(i);
}
}
|
valentinvieriu/keyguard-next
|
src/components/RecoveryWordsInputField.js
|
/* global Nimiq */
/* global I18n */
/* global AutoComplete */
/* global AnimationUtils */
class RecoveryWordsInputField extends Nimiq.Observable {
/**
*
* @param {number} index
*/
constructor(index) {
super();
this._index = index;
/** @type {string} */
this._value = '';
this.complete = false;
this.dom = this._createElements();
this._setupAutocomplete();
this._addEvents();
}
/**
* @param {string} paste
*/
fillValueFrom(paste) {
if (paste.indexOf(' ') !== -1) {
this.value = paste.substr(0, paste.indexOf(' '));
this._checkValidity();
this.fire(RecoveryWordsInputField.Events.FOCUS_NEXT, this._index + 1, paste.substr(paste.indexOf(' ') + 1));
} else {
this.value = paste;
this._checkValidity();
}
}
/**
* @returns {{ element: HTMLElement, input: HTMLInputElement, placeholder: HTMLDivElement }}
*/
_createElements() {
const element = document.createElement('div');
element.classList.add('recovery-words-input-field');
const input = document.createElement('input');
input.classList.add('nq-input');
input.setAttribute('type', 'text');
input.setAttribute('autocorrect', 'off');
input.setAttribute('autocapitalize', 'none');
input.setAttribute('spellcheck', 'false');
/** */
const setPlaceholder = () => {
input.placeholder = `${this._index < 9 ? '0' : ''}${this._index + 1}`;
};
I18n.observer.on(I18n.Events.LANGUAGE_CHANGED, setPlaceholder);
setPlaceholder();
const placeholder = document.createElement('div');
placeholder.className = 'placeholder';
placeholder.textContent = (this._index + 1).toString();
element.appendChild(input);
return { element, input, placeholder };
}
_addEvents() {
this.dom.input.addEventListener('keydown', this._onKeydown.bind(this));
this.dom.input.addEventListener('keyup', this._onKeyup.bind(this));
this.dom.input.addEventListener('paste', this._onPaste.bind(this));
this.dom.input.addEventListener('blur', this._onBlur.bind(this));
}
_setupAutocomplete() {
this.autocomplete = new AutoComplete({
selector: this.dom.input,
source: /** @param{string} term @param{function} response */ (term, response) => {
term = term.toLowerCase();
const list = Nimiq.MnemonicUtils.DEFAULT_WORDLIST.filter(word => word.startsWith(term));
response(list);
},
onSelect: this._select.bind(this),
minChars: 3,
delay: 0,
});
}
focus() {
// cf. https://stackoverflow.com/questions/20747591
setTimeout(() => this.dom.input.focus(), 50);
}
get value() {
return this.dom.input.value;
}
set value(value) {
this.dom.input.value = value;
this._value = value;
}
get element() {
return this.dom.element;
}
_onBlur() {
this._checkValidity();
}
/**
* @param {KeyboardEvent} e
*/
_onKeydown(e) {
if (e.keyCode === 32 /* space */
|| e.keyCode === 9 /* tab */) {
e.preventDefault();
}
if (e.keyCode === 32 // space
|| e.keyCode === 13 // enter
|| (e.keyCode === 9 && !e.shiftKey)) { // tab
this._checkValidity(1);
}
if (e.keyCode === 9 && e.shiftKey) { // shift-tab
this._checkValidity(-1);
}
}
_onKeyup() {
this._onValueChanged();
}
/**
* @param {ClipboardEvent} e
*/
_onPaste(e) {
// @ts-ignore (Property 'clipboardData' does not exist on type 'Window'.)
let paste = (e.clipboardData || window.clipboardData).getData('text');
paste = paste.replace(/\s+/g, ' ');
if (paste && paste.split(' ').length > 1) {
e.preventDefault();
e.stopPropagation();
this.fillValueFrom(paste);
}
}
/**
*
* @param {number} [setFocusToNextInputOffset = 0]
*/
_checkValidity(setFocusToNextInputOffset = 0) {
// Do not block tabbing through empty fields
if (!this.dom.input.value) {
if (setFocusToNextInputOffset) {
this._focusNext(setFocusToNextInputOffset);
}
return;
}
if (Nimiq.MnemonicUtils.DEFAULT_WORDLIST.indexOf(this.value.toLowerCase()) >= 0) {
this.complete = true;
this.dom.element.classList.add('complete');
this.fire(RecoveryWordsInputField.Events.VALID, this);
if (setFocusToNextInputOffset) {
this._focusNext(setFocusToNextInputOffset);
}
} else {
this._onInvalid();
}
}
/**
* Callback from AutoComplete
* @param {Event} e - original Event
* @param {string} term - the selected term
* @param {Element} item - the item that held the term
*/
_select(e, term, item) {
item.classList.remove('selected');
this.value = term;
this._focusNext();
}
/**
*
* @param {number} [offset = 1]
*/
_focusNext(offset = 1) {
this.fire(RecoveryWordsInputField.Events.FOCUS_NEXT, this._index + offset);
}
_onInvalid() {
this.dom.input.value = '';
this._onValueChanged();
AnimationUtils.animate('shake', this.dom.input);
}
_onValueChanged() {
if (this.value === this._value) return;
if (this.complete) {
this.complete = false;
this.dom.element.classList.remove('complete');
this.fire(RecoveryWordsInputField.Events.INVALID, this);
}
this._value = this.value;
}
}
/**
* @type {RecoveryWordsInputField | undefined} _revealedWord
*/
RecoveryWordsInputField._revealedWord = undefined;
RecoveryWordsInputField.Events = {
FOCUS_NEXT: 'recovery-words-focus-next',
VALID: 'recovery-word-valid',
INVALID: 'recovery-word-invalid',
};
|
klueless-io/drawio_dsl
|
.builders/generators/02-generate-app.rb
|
<filename>.builders/generators/02-generate-app.rb<gh_stars>0
KManager.action :requires do
action do
shapes_file = k_builder.target_folders.get_filename(:app, 'config/configuration.json')
shapes_configuration = JSON.parse(File.read(shapes_file))
shapes = shapes_configuration['shape']
lookup = shapes['lookup']
elements = shapes['elements']
lines = shapes['lines']
texts = shapes['texts']
# strokes = shapes_configuration['strokes']
KDirector::Dsls::BasicDsl
.init(k_builder,
on_exist: :write, # %i[skip write compare]
on_action: :execute # %i[queue execute]
)
.blueprint(
active: true,
on_exist: :write) do
cd(:lib)
add('schema/_.rb',
template_file: 'schema_require.rb',
elements: elements,
lines: lines,
texts: texts)
elements.each do |element|
add("schema/elements/#{element['key']}.rb",
template_file: 'schema_element.rb',
element: element)
end
lines.each do |line|
add("schema/lines/#{line['key']}.rb",
template_file: 'schema_line.rb',
line: line)
end
texts.each do |text|
add("schema/texts/#{text['key']}.rb",
template_file: 'schema_text.rb',
text: text)
end
add("drawio_shapes.rb" , template_file: 'drawio_shapes.rb' , shapes: lookup, shape_length: lookup.length)
add("dom_builder_shapes.rb" , template_file: 'dom_builder_shapes.rb' , shapes: lookup)
cd(:spec)
# build spec for each shape
elements.each do |element|
add("schema/elements/#{element['key']}_spec.rb",
template_file: 'schema_element_spec.rb',
element: element)
end
lines.each do |line|
add("schema/lines/#{line['key']}_spec.rb",
template_file: 'schema_line_spec.rb',
line: line)
end
texts.each do |text|
add("schema/texts/#{text['key']}_spec.rb",
template_file: 'schema_text_spec.rb',
text: text)
end
cd(:app)
run_command('rubocop -a')
end
end
end
|
Hakerh400/web
|
projects/trait/action.js
|
'use strict';
const assert = require('assert');
const Inspectable = require('./inspectable');
const ctorsPri = require('./ctors-pri');
class Action extends Inspectable{
exec(btn, labs){ O.virtual('exec'); }
*inspectData(){ return []; }
*inspect(){
return new DetailedInfo(`action :: ${this.ctor.name}`,
yield [[this, 'inspectData']],
);
}
*serData(ser){}
*deserData(ser){}
*ser(ser){
yield [[this, 'serCtor'], ser];
yield [[this, 'serData'], ser];
}
static *deser(ser){
const ctor = yield [[Action, 'deserCtor'], ser];
const action = ctor.new();
yield [[action, 'deserData'], ser];
return action;
}
}
class OpenLevel extends Action{
exec(btn, labs){
if(labs.length !== 1) return;
const level = labs[0];
if(!O.has(levels, level)) return;
const {world} = btn;
levels[level](world, btn.ent, level);
}
}
const ctorsArr = [
Action,
OpenLevel,
];
const ctorsObj = ctorsPri(ctorsArr);
module.exports = Object.assign(Action, {
ctorsArr,
...ctorsObj,
});
const Grid = require('./grid');
const Entity = require('./entity');
const Trait = require('./trait');
const levels = require('./levels');
|
gaoxiaojun/minircp
|
Plugins/org.blueberry.ui.qt/src/internal/berryMenuServiceFactory.h
|
/*===================================================================
BlueBerry Platform
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#ifndef BERRYMENUSERVICEFACTORY_H
#define BERRYMENUSERVICEFACTORY_H
#include "berryIServiceFactory.h"
namespace berry {
class MenuServiceFactory : public QObject, public IServiceFactory
{
Q_OBJECT
Q_INTERFACES(berry::IServiceFactory)
public:
Object* Create(const QString& serviceInterface, IServiceLocator* parentLocator,
IServiceLocator* locator) const override;
};
}
#endif // BERRYMENUSERVICEFACTORY_H
|
vill/bemer
|
lib/bemer/asset_matcher.rb
|
<reponame>vill/bemer
# frozen_string_literal: true
module Bemer
class AssetMatcher
def initialize(loose_app_assets)
@loose_app_assets = loose_app_assets
end
def call(logical_path, filename = nil)
filename = Rails.application.assets.resolve(logical_path).to_s if filename.nil?
return if [Bemer.path, *Bemer.asset_paths].detect { |path| filename.start_with?(path.to_s) }
loose_app_assets.call(logical_path, filename) if loose_app_assets.respond_to?(:call)
end
protected
attr_reader :loose_app_assets
end
end
|
acsl-mipt/actor-framework
|
libcaf_core/src/simple_actor_clock.cpp
|
/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2018 <NAME> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#include "caf/detail/simple_actor_clock.hpp"
#include "caf/actor_cast.hpp"
#include "caf/sec.hpp"
#include "caf/system_messages.hpp"
namespace caf {
namespace detail {
bool simple_actor_clock::ordinary_predicate::
operator()(const secondary_map::value_type& x) const noexcept {
auto ptr = get_if<ordinary_timeout>(&x.second->second);
return ptr != nullptr ? ptr->type == type : false;
}
bool simple_actor_clock::request_predicate::
operator()(const secondary_map::value_type& x) const noexcept {
auto ptr = get_if<request_timeout>(&x.second->second);
return ptr != nullptr ? ptr->id == id : false;
}
void simple_actor_clock::visitor::operator()(ordinary_timeout& x) {
CAF_ASSERT(x.self != nullptr);
x.self->get()->eq_impl(make_message_id(), x.self, nullptr,
timeout_msg{x.type, x.id});
ordinary_predicate pred{x.type};
thisptr->drop_lookup(x.self->get(), pred);
}
void simple_actor_clock::visitor::operator()(request_timeout& x) {
CAF_ASSERT(x.self != nullptr);
x.self->get()->eq_impl(x.id, x.self, nullptr, sec::request_timeout);
request_predicate pred{x.id};
thisptr->drop_lookup(x.self->get(), pred);
}
void simple_actor_clock::visitor::operator()(actor_msg& x) {
x.receiver->enqueue(std::move(x.content), nullptr);
}
void simple_actor_clock::visitor::operator()(group_msg& x) {
x.target->eq_impl(make_message_id(), std::move(x.sender), nullptr,
std::move(x.content));
}
void simple_actor_clock::set_ordinary_timeout(time_point t, abstract_actor* self,
atom_value type, uint64_t id) {
ordinary_predicate pred{type};
auto i = lookup(self, pred);
auto sptr = actor_cast<strong_actor_ptr>(self);
ordinary_timeout tmp{std::move(sptr), type, id};
if (i != actor_lookup_.end()) {
schedule_.erase(i->second);
i->second = schedule_.emplace(t, std::move(tmp));
} else {
auto j = schedule_.emplace(t, std::move(tmp));
actor_lookup_.emplace(self, j);
}
}
void simple_actor_clock::set_request_timeout(time_point t, abstract_actor* self,
message_id id) {
request_predicate pred{id};
auto i = lookup(self, pred);
auto sptr = actor_cast<strong_actor_ptr>(self);
request_timeout tmp{std::move(sptr), id};
if (i != actor_lookup_.end()) {
schedule_.erase(i->second);
i->second = schedule_.emplace(t, std::move(tmp));
} else {
auto j = schedule_.emplace(t, std::move(tmp));
actor_lookup_.emplace(self, j);
}
}
void simple_actor_clock::cancel_ordinary_timeout(abstract_actor* self,
atom_value type) {
ordinary_predicate pred{type};
cancel(self, pred);
}
void simple_actor_clock::cancel_request_timeout(abstract_actor* self,
message_id id) {
request_predicate pred{id};
cancel(self, pred);
}
void simple_actor_clock::cancel_timeouts(abstract_actor* self) {
auto range = actor_lookup_.equal_range(self);
if (range.first == range.second)
return;
for (auto i = range.first; i != range.second; ++i)
schedule_.erase(i->second);
actor_lookup_.erase(range.first, range.second);
}
void simple_actor_clock::schedule_message(time_point t,
strong_actor_ptr receiver,
mailbox_element_ptr content) {
schedule_.emplace(t, actor_msg{std::move(receiver), std::move(content)});
}
void simple_actor_clock::schedule_message(time_point t, group target,
strong_actor_ptr sender,
message content) {
schedule_.emplace(
t, group_msg{std::move(target), std::move(sender), std::move(content)});
}
void simple_actor_clock::cancel_all() {
actor_lookup_.clear();
schedule_.clear();
}
} // namespace detail
} // namespace caf
|
RedaMastouri/marvis
|
11 - Extra-- sonos snips voice app/tests/services/node/test_device_discovery_service.py
|
<reponame>RedaMastouri/marvis
import mock
import pytest
import requests
from snipssonos.entities.device import Device
from snipssonos.services.node.device_discovery_service import NodeDeviceDiscoveryService
from snipssonos.exceptions import DeviceParsingException, NoReachableDeviceException
@pytest.fixture
def connected_device():
return Device.from_dict({
'identifier': 'RINCON_7828CA10127001400',
'name': '<NAME>',
'volume': 18
})
@pytest.fixture
def configuration():
return {
'global':{
'node_device_discovery_port' : 5005,
'node_device_discovery_host' : 'localhost'
}
}
def test_device_discovery_service_initialization(configuration):
discovery_service = NodeDeviceDiscoveryService(configuration)
assert discovery_service.PORT == configuration['global']['node_device_discovery_port']
assert discovery_service.HOST == configuration['global']['node_device_discovery_host']
assert discovery_service.PROTOCOL == NodeDeviceDiscoveryService.PROTOCOL
def test_generate_correct_url_query_for_get_method(configuration):
discovery_service = NodeDeviceDiscoveryService(configuration)
expected_query = "http://localhost:5005/zones/"
actual_query = discovery_service.generate_get_query()
assert expected_query == actual_query
def test_parses_correct_device_from_input_json():
discovery_service = NodeDeviceDiscoveryService()
json_response = """[
{
"uuid": "RINCON_7828CA10127001400",
"coordinator": {
"uuid": "RINCON_7828CA10127001400",
"state": {
"volume": 17,
"mute": false,
"equalizer": {
"bass": 0,
"treble": 0,
"loudness": true
},
"currentTrack": {
"artist": "Fatback Band",
"title": "Chillin' Out",
"album": "14 Karat",
"albumArtUri": "/getaa?s=1&u=x-sonos-spotify%3aspotify%253atrack%253a1bAeucHM9U9RJBJM3bPIGU%3fsid%3d9%26flags%3d8224%26sn%3d2",
"duration": 341,
"uri": "x-sonos-spotify:spotify%3atrack%3a1bAeucHM9U9RJBJM3bPIGU?sid=9&flags=8224&sn=2",
"type": "track",
"stationName": "",
"absoluteAlbumArtUri": "http://192.168.173.215:1400/getaa?s=1&u=x-sonos-spotify%3aspotify%253atrack%253a1bAeucHM9U9RJBJM3bPIGU%3fsid%3d9%26flags%3d8224%26sn%3d2"
},
"nextTrack": {
"artist": "",
"title": "",
"album": "",
"albumArtUri": "",
"duration": 0,
"uri": ""
},
"trackNo": 2,
"elapsedTime": 37,
"elapsedTimeFormatted": "00:00:37",
"playbackState": "PAUSED_PLAYBACK",
"playMode": {
"repeat": "none",
"shuffle": false,
"crossfade": false
}
},
"roomName": "Antho Room",
"coordinator": "RINCON_7828CA10127001400",
"groupState": {
"volume": 17,
"mute": false
}
},
"members": [
{
"uuid": "RINCON_7828CA10127001400",
"state": {
"volume": 17,
"mute": false,
"equalizer": {
"bass": 0,
"treble": 0,
"loudness": true
},
"currentTrack": {
"artist": "Fatback Band",
"title": "Chillin' Out",
"album": "14 Karat",
"albumArtUri": "/getaa?s=1&u=x-sonos-spotify%3aspotify%253atrack%253a1bAeucHM9U9RJBJM3bPIGU%3fsid%3d9%26flags%3d8224%26sn%3d2",
"duration": 341,
"uri": "x-sonos-spotify:spotify%3atrack%3a1bAeucHM9U9RJBJM3bPIGU?sid=9&flags=8224&sn=2",
"type": "track",
"stationName": "",
"absoluteAlbumArtUri": "http://192.168.173.215:1400/getaa?s=1&u=x-sonos-spotify%3aspotify%253atrack%253a1bAeucHM9U9RJBJM3bPIGU%3fsid%3d9%26flags%3d8224%26sn%3d2"
},
"nextTrack": {
"artist": "",
"title": "",
"album": "",
"albumArtUri": "",
"duration": 0,
"uri": ""
},
"trackNo": 2,
"elapsedTime": 37,
"elapsedTimeFormatted": "00:00:37",
"playbackState": "PAUSED_PLAYBACK",
"playMode": {
"repeat": "none",
"shuffle": false,
"crossfade": false
}
},
"roomName": "Antho Room",
"coordinator": "RINCON_7828CA10127001400",
"groupState": {
"volume": 17,
"mute": false
}
}
]
}
]"""
devices = discovery_service.parse_devices(json_response)
assert len(devices) == 1
assert devices[0].identifier == "RINCON_7828CA10127001400"
assert devices[0].name == "<NAME>"
assert devices[0].volume == 17
def test_parsing_invalid_json_raises_exception():
discovery_service = NodeDeviceDiscoveryService()
json_response = """[
{
"members": [
{
"uuuid": "RINCON_7828CA10127001400",
"state": {
"volume": 17,
"mute": false,
"equalizer": {
"bass": 0,
"treble": 0,
"loudness": true
},
"currentTrack": {
"artist": "Fatback Band",
"title": "Chillin' Out",
"album": "14 Karat",
"albumArtUri": "/getaa?s=1&u=x-sonos-spotify%3aspotify%253atrack%253a1bAeucHM9U9RJBJM3bPIGU%3fsid%3d9%26flags%3d8224%26sn%3d2",
"duration": 341,
"uri": "x-sonos-spotify:spotify%3atrack%3a1bAeucHM9U9RJBJM3bPIGU?sid=9&flags=8224&sn=2",
"type": "track",
"stationName": "",
"absoluteAlbumArtUri": "http://192.168.173.215:1400/getaa?s=1&u=x-sonos-spotify%3aspotify%253atrack%253a1bAeucHM9U9RJBJM3bPIGU%3fsid%3d9%26flags%3d8224%26sn%3d2"
},
"nextTrack": {
"artist": "",
"title": "",
"album": "",
"albumArtUri": "",
"duration": 0,
"uri": ""
},
"trackNo": 2,
"elapsedTime": 37,
"elapsedTimeFormatted": "00:00:37",
"playbackState": "PAUSED_PLAYBACK",
"playMode": {
"repeat": "none",
"shuffle": false,
"crossfade": false
}
},
"roomName": "<NAME>",
"coordinator": "RINCON_7828CA10127001400",
"groupState": {
"volume": 17,
"mute": false
}
}
]
}
]"""
with pytest.raises(DeviceParsingException):
discovery_service.parse_devices(json_response)
def test_parsing_json_with_empty_members():
discovery_service = NodeDeviceDiscoveryService()
json_response = """[
{"members": []}]"""
devices = discovery_service.parse_devices(json_response)
assert len(devices) == 0
@mock.patch.object(NodeDeviceDiscoveryService, 'get_devices')
def test_get_method_returns_first_occurrence(mocked_get_devices, connected_device):
discovery_service = NodeDeviceDiscoveryService()
mocked_get_devices.return_value = [connected_device]
assert discovery_service.get().name == connected_device.name
assert discovery_service.get().identifier == connected_device.identifier
assert discovery_service.get().volume == connected_device.volume
@mock.patch('snipssonos.services.node.device_discovery_service.requests')
def test_get_method_performs_correct_api_query(mocked_requests):
discovery_device = NodeDeviceDiscoveryService()
discovery_device.execute_query()
actual_query = discovery_device.generate_get_query()
mocked_requests.get.assert_called_with(actual_query)
@mock.patch('snipssonos.services.node.device_discovery_service.requests')
def test_unreachable_device_raises_exception(mocked_requests):
discovery_device = NodeDeviceDiscoveryService()
mocked_response_object = mock.create_autospec(requests.Response)
mocked_response_object.ok = False
mocked_requests.get.return_value = mocked_response_object
with pytest.raises(NoReachableDeviceException):
discovery_device.execute_query()
|
hacfins/spring-boot-2-api
|
edu-db/src/main/java/com/langyastudio/edu/db/model/UmsMessage.java
|
package com.langyastudio.edu.db.model;
import java.time.LocalDateTime;
import com.alibaba.fastjson.annotation.JSONField;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 消息通知
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UmsMessage {
/**
* 机构、教室号、班级、用户
*/
public static final byte TYPE_SCHOOL = 1;
public static final byte TYPE_ROOM = 2;
public static final byte TYPE_CLASSES = 3;
public static final byte TYPE_USER = 4;
/**
* 订阅、评论、点赞、通知
*/
public static final byte QUEUE_SUB = 1;
public static final byte QUEUE_CHAT = 2;
public static final byte QUEUE_UPVOTE = 3;
public static final byte QUEUE_NOTICE = 4;
private Integer id;
/**
* 消息id号
*/
private String msgId;
/**
* 发送消息者id号
*/
private String sendId;
/**
* 发送消息者类型(机构、教室号、班级、用户)
*/
private Integer sendType;
/**
* 接收消息者id号
*/
private String toId;
/**
* 接收消息者(机构、教室号、班级、用户)
*/
private Integer toType;
/**
* 事件id号(消息触发者)
*/
private String eventId;
/**
* 消息类型(订阅、评论、点赞、通知等)
*/
private Integer queue;
/**
* 消息标题
*/
private String msgTitle;
/**
* 消息内容(没有时,为空)
*/
private String msgContent;
/**
* 未读、已读
*/
private Byte status;
/**
* 更新时间
*/
@JSONField(serialize = false)
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
/**
* 删除标记
*/
private LocalDateTime deleteTime;
/**
* 创建时间
*/
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
}
|
shmily1012/linux-zns
|
Linux_Kernel/linux-master/tools/testing/selftests/bpf/benchs/bench_trigger.c
|
<reponame>shmily1012/linux-zns
// SPDX-License-Identifier: GPL-2.0
/* Copyright (c) 2020 Facebook */
#include "bench.h"
#include "trigger_bench.skel.h"
/* BPF triggering benchmarks */
static struct trigger_ctx {
struct trigger_bench *skel;
} ctx;
static struct counter base_hits;
static void trigger_validate()
{
if (env.consumer_cnt != 1) {
fprintf(stderr, "benchmark doesn't support multi-consumer!\n");
exit(1);
}
}
static void *trigger_base_producer(void *input)
{
while (true) {
(void)syscall(__NR_getpgid);
atomic_inc(&base_hits.value);
}
return NULL;
}
static void trigger_base_measure(struct bench_res *res)
{
res->hits = atomic_swap(&base_hits.value, 0);
}
static void *trigger_producer(void *input)
{
while (true)
(void)syscall(__NR_getpgid);
return NULL;
}
static void trigger_measure(struct bench_res *res)
{
res->hits = atomic_swap(&ctx.skel->bss->hits, 0);
}
static void setup_ctx()
{
setup_libbpf();
ctx.skel = trigger_bench__open_and_load();
if (!ctx.skel) {
fprintf(stderr, "failed to open skeleton\n");
exit(1);
}
}
static void attach_bpf(struct bpf_program *prog)
{
struct bpf_link *link;
link = bpf_program__attach(prog);
if (IS_ERR(link)) {
fprintf(stderr, "failed to attach program!\n");
exit(1);
}
}
static void trigger_tp_setup()
{
setup_ctx();
attach_bpf(ctx.skel->progs.bench_trigger_tp);
}
static void trigger_rawtp_setup()
{
setup_ctx();
attach_bpf(ctx.skel->progs.bench_trigger_raw_tp);
}
static void trigger_kprobe_setup()
{
setup_ctx();
attach_bpf(ctx.skel->progs.bench_trigger_kprobe);
}
static void trigger_fentry_setup()
{
setup_ctx();
attach_bpf(ctx.skel->progs.bench_trigger_fentry);
}
static void trigger_fmodret_setup()
{
setup_ctx();
attach_bpf(ctx.skel->progs.bench_trigger_fmodret);
}
static void *trigger_consumer(void *input)
{
return NULL;
}
const struct bench bench_trig_base = {
.name = "trig-base",
.validate = trigger_validate,
.producer_thread = trigger_base_producer,
.consumer_thread = trigger_consumer,
.measure = trigger_base_measure,
.report_progress = hits_drops_report_progress,
.report_final = hits_drops_report_final,
};
const struct bench bench_trig_tp = {
.name = "trig-tp",
.validate = trigger_validate,
.setup = trigger_tp_setup,
.producer_thread = trigger_producer,
.consumer_thread = trigger_consumer,
.measure = trigger_measure,
.report_progress = hits_drops_report_progress,
.report_final = hits_drops_report_final,
};
const struct bench bench_trig_rawtp = {
.name = "trig-rawtp",
.validate = trigger_validate,
.setup = trigger_rawtp_setup,
.producer_thread = trigger_producer,
.consumer_thread = trigger_consumer,
.measure = trigger_measure,
.report_progress = hits_drops_report_progress,
.report_final = hits_drops_report_final,
};
const struct bench bench_trig_kprobe = {
.name = "trig-kprobe",
.validate = trigger_validate,
.setup = trigger_kprobe_setup,
.producer_thread = trigger_producer,
.consumer_thread = trigger_consumer,
.measure = trigger_measure,
.report_progress = hits_drops_report_progress,
.report_final = hits_drops_report_final,
};
const struct bench bench_trig_fentry = {
.name = "trig-fentry",
.validate = trigger_validate,
.setup = trigger_fentry_setup,
.producer_thread = trigger_producer,
.consumer_thread = trigger_consumer,
.measure = trigger_measure,
.report_progress = hits_drops_report_progress,
.report_final = hits_drops_report_final,
};
const struct bench bench_trig_fmodret = {
.name = "trig-fmodret",
.validate = trigger_validate,
.setup = trigger_fmodret_setup,
.producer_thread = trigger_producer,
.consumer_thread = trigger_consumer,
.measure = trigger_measure,
.report_progress = hits_drops_report_progress,
.report_final = hits_drops_report_final,
};
|
uicodefr/postit
|
postit-server/src/main/java/com/uicode/postit/postitserver/service/global/GlobalService.java
|
package com.uicode.postit.postitserver.service.global;
import java.util.Optional;
import com.uicode.postit.postitserver.dto.IdEntityDto;
import com.uicode.postit.postitserver.dto.global.CountLikesDto;
import com.uicode.postit.postitserver.dto.global.GlobalStatusDto;
import com.uicode.postit.postitserver.exception.functionnal.ForbiddenException;
import com.uicode.postit.postitserver.exception.functionnal.NotFoundException;
public interface GlobalService {
GlobalStatusDto getStatus();
void clearCache();
Optional<String> getParameterValue(String parameterName);
String getParameterValueForClient(String parameterName) throws NotFoundException, ForbiddenException;
CountLikesDto countLikes();
IdEntityDto addLike(String clientIp);
}
|
ahakingdom/Rusthon
|
regtests/asm/asm_hello_rust.py
|
'''
rust inline assembly
'''
def test_single_input( a : int ) -> int:
let mut b = 0
with asm( outputs=b, inputs=a, volatile=True, clobber='%ebx', alignstack=True ):
movl %1, %%ebx;
movl %%ebx, %0;
return b
def test_multi_input( a : int, b : int ) -> int:
let mut out = 0
with asm( outputs=out, inputs=(a,b), volatile=True, clobber=('%ebx','memory') ):
movl %1, %%ebx;
addl %2, %%ebx;
movl %%ebx, %0;
return out
def main():
x = test_single_input(999)
print x ## should print 999
y = test_multi_input(400, 20)
print y ## should print 420
|
CNES/resto_client
|
resto_client/functions/aoi_utils.py
|
<filename>resto_client/functions/aoi_utils.py
# -*- coding: utf-8 -*-
"""
.. admonition:: License
Copyright 2019 CNES
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License
is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
or implied. See the License for the specific language governing permissions and
limitations under the License.
"""
from typing import Any, List # @UnusedImport @NoMove
import json
from pathlib import Path
from shapely.geometry import shape
from shapely.geometry.base import BaseGeometry
from shapely.ops import unary_union
from resto_client.base_exceptions import RestoClientUserError
HERE = Path(__file__).parent
PATH_AOI = HERE.parent / 'zones'
class LowerList(list):
"""
Class representing a less restrictive list
"""
def __contains__(self, other: object) -> bool:
"""
other is in my class if this lower is in it
:param other: object whose str representation is to be tested for being in the list.
:returns: boolean response of : is the other.lower in self ?
"""
return super(LowerList, self).__contains__(str(other).lower())
def list_all_geojson() -> List[str]:
"""
List all geojson file in the proper path for aoi
:returns: list of file in lower_case
"""
list_file = [f.stem for f in PATH_AOI.iterdir() if f.suffix == '.geojson']
# prepare test by lower all name
list_file = [element.lower() for element in list_file]
return list_file
def search_file_from_key(key: str) -> Path:
"""
Translate a key to this proper geojson file
:param key: the geojson file
:returns: geojson file associated
"""
if not key.endswith('.geojson'):
key += '.geojson'
return PATH_AOI / key
def str_region_choice() -> str:
"""
str ready to be displayed explaining possible region choices
:returns: str of possible input for region
"""
region_list = sorted(LowerList(list_all_geojson()))
return f'region can be either a Path or from the predefined zones in database : {region_list}'
def geojson_zone_to_bbox(geojson_path: Path) -> BaseGeometry:
"""
Translate a geojson file to a bbox geometry
:param geojson_path: the path to the geojson file
:returns: the bbox geometry of the kml
"""
# will contain all shape of the geojson
shapes = geojson_to_shape(geojson_path)
# translate it for resto into bbox bounds
return shapes_to_bbox(shapes)
def find_sensitive_file(geojson_path: Path) -> Path:
"""
Find the proper file name if the given has not a good sensitive case
:param geojson_path: the geojson file path
:returns: correct path with case taking into account
:raises RestoClientUserError: when the region file is not found.
"""
file_name = geojson_path.name
directory = geojson_path.parent
for name_in_dir in directory.iterdir():
if file_name.lower() == str(name_in_dir.name).lower():
improved_path = directory / name_in_dir
return improved_path
raise RestoClientUserError('No region file found with name {}'.format(geojson_path))
def geojson_to_shape(geojson_file: Path) -> List[BaseGeometry]:
"""
Translate a geojson file to a shape of shapely
:param geojson_file: the path of the geojson file
:returns: list of shape
"""
if not geojson_file.exists():
geojson_file = find_sensitive_file(geojson_file)
with open(geojson_file, 'r') as file:
data = json.load(file)
shapes = []
for feature in data['features']:
shapes.append(shape(feature['geometry']))
return shapes
def shapes_to_bbox(shapes: List[BaseGeometry]) -> BaseGeometry:
"""
Translate shapes to a bbox envelope
:param shapes: list of shapely shape
:returns: bbox of the shapes, rectangular boundaries
"""
# convert to a single shape, union of all
union_mono_shape = unary_union(shapes)
# returns the smallest rectangular polygon
convex_envelope = union_mono_shape.convex_hull
return convex_envelope
|
FreeAllegiance/Allegiance-AZ
|
src/WinTrek/introscreen.cpp
|
#include "pch.h"
#include "regkey.h"
#include "training.h"
//extern bool CheckNetworkDevices(ZString& strDriverURL);
//KGJV test
#define ENABLE3DINTROSCREEN
//////////////////////////////////////////////////////////////////////////////
//
// Intro Screen
//
//////////////////////////////////////////////////////////////////////////////
class IntroScreen :
public Screen,
public TrekClientEventSink,
public EventTargetContainer<IntroScreen>,
public LogonSite,
public PasswordDialogSink
{
private:
TRef<Modeler> m_pmodeler;
TRef<Pane> m_ppane;
TRef<ButtonPane> m_pbuttonPlayLan;
TRef<ButtonPane> m_pbuttonPlayInt;
TRef<ButtonPane> m_pbuttonZoneClub;
//TRef<ButtonPane> m_pbuttonTraining;
TRef<ButtonPane> m_pbuttonTrainingBig;
TRef<ButtonPane> m_pbuttonZoneWeb;
TRef<ButtonPane> m_pbuttonOptions;
TRef<ButtonPane> m_pbuttonIntro;
TRef<ButtonPane> m_pbuttonCredits;
TRef<ButtonPane> m_pbuttonQuickstart;
TRef<ButtonPane> m_pbuttonExit;
TRef<ButtonPane> m_pbuttonHelp;
TRef<IMessageBox> m_pMsgBox;
GUID m_guidSession;
ZString m_strCharacterName;
ZString m_strPassword;
MissionInfo* m_pmissionJoining;
#ifdef ENABLE3DINTROSCREEN
//KGJV
TRef<Number> m_ptime;
TRef<Pane> m_ppaneGeo;
TRef<Camera> m_pcamera;
TRef<Viewport> m_pviewport;
TRef<WrapGeo> m_pwrapGeo;
TRef<WrapImage> m_pwrapImageGeo;
TRef<WrapImage> m_pwrapImage;
TRef<ThingGeo> m_pthing;
#endif
enum
{
hoverNone,
hoverPlayLan,
hoverPlayInt,
hoverZoneClub,
hoverTrain,
hoverZoneWeb,
hoverOptions,
hoverIntro,
hoverCredits,
hoverQuickstart,
hoverExit,
hoverHelp
};
TRef<ModifiableNumber> m_pnumberCurrentHover;
friend class CreditsPopup;
class CreditsPopup : public IPopup, public EventTargetContainer<CreditsPopup>
{
private:
TRef<Pane> m_ppane;
TRef<ButtonPane> m_pbuttonClose;
IntroScreen* m_pparent;
TRef<IKeyboardInput> m_pkeyboardInputOldFocus;
public:
CreditsPopup(TRef<INameSpace> pns, IntroScreen* pparent, Number* ptime)
{
m_pparent = pparent;
TRef<WrapNumber> pcreditsTime;
CastTo(pcreditsTime, pns->FindMember("creditsTime"));
CastTo(m_ppane, pns->FindMember("screen"));
CastTo(m_pbuttonClose, pns->FindMember("closeButtonPane"));
pcreditsTime->SetWrappedValue(Subtract(ptime, new Number(ptime->GetValue())));
AddEventTarget(&IntroScreen::CreditsPopup::OnButtonClose, m_pbuttonClose->GetEventSource());
}
//
// IPopup methods
//
virtual void OnClose()
{
if (m_pkeyboardInputOldFocus)
GetWindow()->SetFocus(m_pkeyboardInputOldFocus);
m_pkeyboardInputOldFocus = NULL;
IPopup::OnClose();
}
virtual void SetContainer(IPopupContainer* pcontainer)
{
// initialize the check boxes
m_pkeyboardInputOldFocus = GetWindow()->GetFocus();
IPopup::SetContainer(pcontainer);
}
Pane* GetPane()
{
return m_ppane;
}
bool OnKey(IInputProvider* pprovider, const KeyState& ks, bool& fForceTranslate)
{
// we need to make sure we get OnChar calls to pass on to the edit box
fForceTranslate = true;
return false;
}
bool OnChar(IInputProvider* pprovider, const KeyState& ks)
{
return true;
}
bool OnButtonClose()
{
m_pcontainer->ClosePopup(this);
return true;
}
};
friend class FindServerPopup;
class FindServerPopup : public IPopup, public EventTargetContainer<FindServerPopup>, public IItemEvent::Sink
{
private:
TRef<Pane> m_ppane;
//TRef<ButtonPane> m_pbuttonFind;
TRef<ButtonPane> m_pbuttonJoin;
TRef<ButtonPane> m_pbuttonCancel;
//TRef<EditPane> m_peditPane;
TRef<ListPane> m_plistPane;
TRef<IItemEvent::Source> m_peventServerList;
TRef<TEvent<ItemID>::Sink> m_psinkServerList;
IntroScreen* m_pparent;
//TRef<IKeyboardInput> m_pkeyboardInputOldFocus;
bool m_bDoBackgroundPolling;
TRef<LANServerInfo> m_pserverSearching;
TRef<IMessageBox> m_pmsgBox;
typedef TListListWrapper<TRef<LANServerInfo> > ServerList;
TRef<ServerList> m_plistServers;
class ServerItemPainter : public ItemPainter
{
int m_nWidth;
int m_nGameNameX;
public:
ServerItemPainter(int nGameNameX, int nWidth)
: m_nWidth(nWidth), m_nGameNameX(nGameNameX) {};
int GetXSize()
{
return m_nWidth;
}
int GetYSize()
{
return 14;
}
void Paint(ItemID pitemArg, Surface* psurface, bool bSelected, bool bFocus)
{
LANServerInfo* serverInfo = (LANServerInfo*)pitemArg;
const int nPlayerWidth = 40;
if (bSelected) {
psurface->FillRect(
WinRect(0, 0, GetXSize(), GetYSize()),
Color(1, 0, 0)
);
}
TRef<IEngineFont> pfont = TrekResources::SmallFont();
Color color = Color::White();
WinRect rectClipOld = psurface->GetClipRect();
psurface->SetClipRect(WinRect(WinPoint(0, 0), WinPoint(GetXSize() - nPlayerWidth, GetYSize()))); // clip name to fit in row
psurface->DrawString(pfont, color, WinPoint(2, 0), serverInfo->strGameName);
psurface->RestoreClipRect(rectClipOld);
if (serverInfo->nMaxPlayers != 0)
{
char cbPlayers[20];
sprintf(cbPlayers, "(%d/%d)", serverInfo->nNumPlayers, serverInfo->nMaxPlayers);
psurface->DrawString(pfont, color, WinPoint(GetXSize() - nPlayerWidth + 2, 0), cbPlayers);
}
}
};
static bool GameNameCompare(ItemID pitem1, ItemID pitem2)
{
LANServerInfo* serverInfo1 = (LANServerInfo*)pitem1;
LANServerInfo* serverInfo2 = (LANServerInfo*)pitem2;
return _stricmp(serverInfo1->strGameName, serverInfo2->strGameName) > 0;
}
public:
FindServerPopup(TRef<INameSpace> pns, IntroScreen* pparent)
{
m_bDoBackgroundPolling = false;
m_pparent = pparent;
Value* pGameNameX;
Value* pListXSize;
CastTo(m_ppane, pns->FindMember("ServerDialog"));
//CastTo(m_pbuttonFind, pns->FindMember("serverFindButtonPane"));
CastTo(m_pbuttonJoin, pns->FindMember("serverJoinButtonPane"));
CastTo(m_pbuttonCancel, pns->FindMember("serverCancelButtonPane"));
//CastTo(m_peditPane, (Pane*)pns->FindMember("serverEditPane"));
CastTo(m_plistPane, (Pane*)pns->FindMember("serverListPane"));
CastTo(pGameNameX, pns->FindMember("serverListGameNameX"));
CastTo(pListXSize, pns->FindMember("serverListWidth"));
//AddEventTarget(OnButtonFind, m_pbuttonFind->GetEventSource());
AddEventTarget(&IntroScreen::FindServerPopup::OnButtonJoin, m_pbuttonJoin->GetEventSource());
AddEventTarget(&IntroScreen::FindServerPopup::OnButtonCancel, m_pbuttonCancel->GetEventSource());
AddEventTarget(&IntroScreen::FindServerPopup::OnButtonJoin, m_plistPane->GetDoubleClickEventSource());
m_peventServerList = m_plistPane->GetSelectionEventSource();
m_peventServerList->AddSink(m_psinkServerList = new IItemEvent::Delegate(this));
m_plistPane->NeedLayout();
m_plistPane->SetItemPainter(new ServerItemPainter(GetNumber(pGameNameX), GetNumber(pListXSize)));
m_plistServers = new ServerList();
m_plistPane->SetList(new SortedList<ItemIDCompareFunction>(m_plistServers, GameNameCompare));
m_pbuttonJoin->SetEnabled(false);
m_pserverSearching = new LANServerInfo(GUID_NULL, "Searching...", 0, 0);
AddEventTarget(&IntroScreen::FindServerPopup::PollForServers, GetWindow(), 1.0f);
}
~FindServerPopup()
{
m_peventServerList->RemoveSink(m_psinkServerList);
}
//
// IPopup methods
//
Pane* GetPane()
{
return m_ppane;
}
virtual void OnClose()
{
//if (m_pkeyboardInputOldFocus)
// GetWindow()->SetFocus(m_pkeyboardInputOldFocus);
//m_pkeyboardInputOldFocus = NULL;
m_bDoBackgroundPolling = false;
IPopup::OnClose();
}
virtual void SetContainer(IPopupContainer* pcontainer)
{
//m_pkeyboardInputOldFocus = GetWindow()->GetFocus();
//GetWindow()->SetFocus(m_peditPane);
m_bDoBackgroundPolling = true;
FindGames("");
IPopup::SetContainer(pcontainer);
}
bool OnKey(IInputProvider* pprovider, const KeyState& ks, bool& fForceTranslate)
{
// we need to make sure we get OnChar calls to pass on to the edit box
fForceTranslate = true;
return false;
}
/*
bool OnChar(IInputProvider* pprovider, const KeyState& ks)
{
if (ks.vk == 13)
{
OnButtonFind();
return true;
}
else
return ((IKeyboardInput*)m_peditPane)->OnChar(pprovider, ks);
}
bool OnButtonFind()
{
FindGames(m_peditPane->GetString());
return true;
}
*/
bool PollForServers()
{
if (m_bDoBackgroundPolling)
FindGames(NULL);
return true;
}
void FindGames(const char* szServerName)
{
// WLP 2005 - turned off the every second search to keep the mouse responding
// added next line to turn off polling
// TE: Commented now that enumeration is done asynchronously
// mmf: LAN mode is still sync so leave this in, otherwise GUI hangs on LAN game select screen
m_bDoBackgroundPolling = false ;
TList<TRef<LANServerInfo> > listResults;
trekClient.FindStandaloneServersByName(szServerName, listResults);
// WLP 2005 - DPLAY8 upgrade addition code
// DPLAY8 EnumHosts returns duplicates in the list
// so we have to strip them out
// How this works =
// destroy all dupes to the first entry
// destroy all dupes to the second entry - etc.
// just keep at it until the end
TList<TRef<LANServerInfo> >::Iterator iterNew(listResults); // Walking list
for( int i = 1 ; i < listResults.GetCount() ; i++ ) // Walk the entire list
{
iterNew.First(); // set on the first one
for ( int j = 1 ; j < i ; j++, iterNew.Next() ) ; // find the starting position
GUID matchGUID = iterNew.Value()->guidSession ; // this is the one to check for dupes
iterNew.Next(); // bump to the next one to start comparing
while (!iterNew.End()) // walk from here to the end checking dupes
{
if (memcmp(&(iterNew.Value()->guidSession), // compare GUID for dupes
&matchGUID, sizeof(GUID)) == 0)
iterNew.Remove();
else iterNew.Next();
}
}
// WLP - 2005 end of add for DPLAY8 upgrade
// add to or update the the server list with the new results
// Note: we have to maintain some degree of consistancy to
// make sure scrolling an selection work, so unfortunately we
// can't just copy.
ServerList::Iterator iterOld(*m_plistServers);
while (!iterOld.End())
{
bool bFound = false;
ZString strOldName = iterOld.Value()->strGameName;
for (TList<TRef<LANServerInfo> >::Iterator iterNew(listResults);
!iterNew.End(); iterNew.Next())
{
ZString strNewName = iterNew.Value()->strGameName;
if (memcmp(&(iterNew.Value()->guidSession),
&(iterOld.Value()->guidSession), sizeof(GUID)) == 0
&& iterNew.Value()->nMaxPlayers > 1
&& iterNew.Value()->nMaxPlayers < 1000)
{
// found it - update it with the new info
bFound = true;
iterOld.Value()->strGameName = iterNew.Value()->strGameName;
iterNew.Remove();
break;
}
}
// didn't find it in the new list, so nuke it.
if (!bFound)
iterOld.Remove();
else
iterOld.Next();
}
// for anything else that's new, just add it to the end.
for (TList<TRef<LANServerInfo> >::Iterator iterNew(listResults);
!iterNew.End(); iterNew.Next())
{
// don't show single player games or zone server games
if (iterNew.Value()->nMaxPlayers > 1
&& iterNew.Value()->nMaxPlayers < 1000)
{
ZString strNewName = iterNew.Value()->strGameName;
m_plistServers->PushEnd(iterNew.Value());
}
}
if (m_plistServers->IsEmpty())
{
// put "Searching..." in the list.
m_plistServers->PushEnd(m_pserverSearching);
}
}
bool OnButtonJoin()
{
//GetWindow()->SetFocus(m_pkeyboardInputOldFocus);
//m_pkeyboardInputOldFocus = NULL;
m_bDoBackgroundPolling = false;
if (m_ppopupOwner) {
m_ppopupOwner->ClosePopup(this);
} else {
m_pcontainer->ClosePopup(this);
}
LANServerInfo* serverInfo = (LANServerInfo*)(m_plistPane->GetSelection());
if (serverInfo != NULL && serverInfo != m_pserverSearching)
m_pparent->OnPickServer(serverInfo->guidSession);
return true;
}
bool OnButtonCancel()
{
//GetWindow()->SetFocus(m_pkeyboardInputOldFocus);
//m_pkeyboardInputOldFocus = NULL;
m_bDoBackgroundPolling = false;
if (m_ppopupOwner) {
m_ppopupOwner->ClosePopup(this);
} else {
m_pcontainer->ClosePopup(this);
}
return true;
}
bool OnEvent(IItemEvent::Source *pevent, ItemID pitem)
{
LANServerInfo* serverInfo = (LANServerInfo*)pitem;
m_pbuttonJoin->SetEnabled(serverInfo != NULL && serverInfo != m_pserverSearching);
return true;
}
};
TRef<CreditsPopup> m_pcreditsPopup;
TRef<FindServerPopup> m_pfindServerPopup;
class CloseTrainWarnSink : public IIntegerEventSink {
public:
IntroScreen* m_pScreen;
TRef<ButtonPane> m_pDontAskMeAgain;
CloseTrainWarnSink(IntroScreen* pScreen, ButtonPane* pDontAskMeAgain)
: m_pScreen (pScreen), m_pDontAskMeAgain (pDontAskMeAgain) {}
bool OnEvent(IIntegerEventSource* pevent, int value)
{
if (value == IDOK) {
m_pScreen->OnButtonTraining ();
}
if (m_pDontAskMeAgain->GetChecked()) {
// here we mark things as if a training mission has been launched
HKEY hKey;
DWORD dwHasRunTraining = 1;
if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE, ALLEGIANCE_REGISTRY_KEY_ROOT, 0, KEY_WRITE, &hKey))
{
RegSetValueExA(hKey, "HasTrained", NULL, REG_DWORD, (const BYTE*) &dwHasRunTraining, sizeof (dwHasRunTraining));
RegCloseKey (hKey);
}
}
return false;
}
};
class URLMessageSink : public IIntegerEventSink {
public:
ZString m_strURL;
URLMessageSink(ZString strURL) :
m_strURL(strURL)
{
}
bool OnEvent(IIntegerEventSource* pevent, int value)
{
if (value == IDOK) {
GetWindow()->ShowWebPage(m_strURL);
}
return false;
}
};
bool CheckNetworkDrivers()
{
/* imago 10/14
ZString strDriverURL;
if (!CheckNetworkDevices(strDriverURL))
{
TRef<IMessageBox> pMsgBox = CreateMessageBox("The drivers of the "
"network card you are using are known not to work with "
"Microsoft Allegiance. Please visit " + strDriverURL
+ " to download updated drivers. Press <OK> to go there now.",
NULL, true, true);
pMsgBox->GetEventSource()->AddSink(new URLMessageSink(strDriverURL));
GetWindow()->GetPopupContainer()->OpenPopup(pMsgBox, false);
return false;
}
else
*/
return true;
}
public:
IntroScreen(Modeler* pmodeler) :
m_pmodeler(pmodeler)
{
trekClient.DisconnectClub();
TRef<INameSpace> pnsIntroScreen = m_pmodeler->CreateNameSpace("introscreendata", m_pmodeler->GetNameSpace("gamepanes"));
pnsIntroScreen->AddMember("hoverNone", new Number(hoverNone ));
pnsIntroScreen->AddMember("hoverPlayLan", new Number(hoverPlayLan ));
pnsIntroScreen->AddMember("hoverPlayInt", new Number(hoverPlayInt) );
pnsIntroScreen->AddMember("hoverZoneClub", new Number(hoverZoneClub ));
pnsIntroScreen->AddMember("hoverZoneWeb", new Number(hoverZoneWeb ));
pnsIntroScreen->AddMember("hoverTrain", new Number(hoverTrain ));
pnsIntroScreen->AddMember("hoverOptions", new Number(hoverOptions ));
pnsIntroScreen->AddMember("hoverIntro", new Number(hoverIntro ));
pnsIntroScreen->AddMember("hoverCredits", new Number(hoverCredits ));
pnsIntroScreen->AddMember("hoverQuickstart", new Number(hoverQuickstart ));
pnsIntroScreen->AddMember("hoverExit", new Number(hoverExit ));
pnsIntroScreen->AddMember("hoverHelp", new Number(hoverHelp ));
pnsIntroScreen->AddMember("CurrentHover", m_pnumberCurrentHover = new ModifiableNumber(hoverNone));
#ifdef ENABLE3DINTROSCREEN
//KGJV
pnsIntroScreen->AddMember("bgImage", (Value*)(m_pwrapImage = new WrapImage(Image::GetEmpty())));
m_pthing = NULL;
#endif
#ifdef USEAZ
TRef<INameSpace> pns = pmodeler->GetNameSpace("introscreen");
#else
TRef<INameSpace> pns = pmodeler->GetNameSpace("introscreen_fz");
#endif
CastTo(m_ppane, pns->FindMember("screen"));
CastTo(m_pbuttonPlayLan, pns->FindMember("playLanButtonPane"));
CastTo(m_pbuttonPlayInt, pns->FindMember("playIntButtonPane"));
CastTo(m_pbuttonZoneClub, pns->FindMember("zoneClubButtonPane" ));
//CastTo(m_pbuttonTraining, pns->FindMember("trainButtonPane"));
CastTo(m_pbuttonTrainingBig,pns->FindMember("trainBigButtonPane"));
CastTo(m_pbuttonZoneWeb, pns->FindMember("zoneWebButtonPane" ));
CastTo(m_pbuttonOptions, pns->FindMember("optionsButtonPane"));
CastTo(m_pbuttonIntro, pns->FindMember("introButtonPane"));
CastTo(m_pbuttonCredits, pns->FindMember("creditsButtonPane"));
CastTo(m_pbuttonQuickstart, pns->FindMember("quickstartButtonPane"));
CastTo(m_pbuttonExit, pns->FindMember("exitButtonPane" ));
CastTo(m_pbuttonHelp, pns->FindMember("helpButtonPane" ));
//AddEventTarget(OnButtonGames, m_pbuttonPlayLan->GetEventSource());
//AddEventTarget(OnButtonTraining, m_pbuttonTraining->GetEventSource());
AddEventTarget(&IntroScreen::OnButtonTraining, m_pbuttonTrainingBig->GetEventSource());
AddEventTarget(&IntroScreen::OnButtonExit, m_pbuttonExit->GetEventSource());
AddEventTarget(&IntroScreen::OnButtonHelp, m_pbuttonHelp->GetEventSource());
AddEventTarget(&IntroScreen::OnButtonZoneClub, m_pbuttonZoneClub->GetEventSource());
AddEventTarget(&IntroScreen::OnButtonInternet, m_pbuttonPlayInt->GetEventSource());
AddEventTarget(&IntroScreen::OnButtonLAN, m_pbuttonPlayLan->GetEventSource());
AddEventTarget(&IntroScreen::OnButtonZoneWeb, m_pbuttonZoneWeb->GetEventSource());
AddEventTarget(&IntroScreen::OnButtonOptions, m_pbuttonOptions->GetEventSource());
AddEventTarget(&IntroScreen::OnButtonCredits, m_pbuttonCredits->GetEventSource());
AddEventTarget(&IntroScreen::OnButtonIntro, m_pbuttonIntro->GetEventSource());
AddEventTarget(&IntroScreen::OnHoverPlayLan, m_pbuttonPlayLan->GetMouseEnterEventSource());
AddEventTarget(&IntroScreen::OnHoverPlayInt, m_pbuttonPlayInt->GetMouseEnterEventSource());
AddEventTarget(&IntroScreen::OnHoverZoneClub, m_pbuttonZoneClub->GetMouseEnterEventSource());
//AddEventTarget(OnHoverTrain, m_pbuttonTraining->GetMouseEnterEventSource());
AddEventTarget(&IntroScreen::OnHoverTrain, m_pbuttonTrainingBig->GetMouseEnterEventSource());
AddEventTarget(&IntroScreen::OnHoverZoneWeb, m_pbuttonZoneWeb->GetMouseEnterEventSource());
AddEventTarget(&IntroScreen::OnHoverOptions, m_pbuttonOptions->GetMouseEnterEventSource());
AddEventTarget(&IntroScreen::OnHoverIntro, m_pbuttonIntro->GetMouseEnterEventSource());
AddEventTarget(&IntroScreen::OnHoverCredits, m_pbuttonCredits->GetMouseEnterEventSource());
AddEventTarget(&IntroScreen::OnHoverQuickstart, m_pbuttonQuickstart->GetMouseEnterEventSource());
AddEventTarget(&IntroScreen::OnHoverExit, m_pbuttonExit->GetMouseEnterEventSource());
AddEventTarget(&IntroScreen::OnHoverHelp, m_pbuttonHelp->GetMouseEnterEventSource());
AddEventTarget(&IntroScreen::OnHoverNone, m_pbuttonPlayLan->GetMouseLeaveEventSource());
AddEventTarget(&IntroScreen::OnHoverNone, m_pbuttonPlayInt->GetMouseLeaveEventSource());
AddEventTarget(&IntroScreen::OnHoverNone, m_pbuttonZoneClub->GetMouseLeaveEventSource());
//AddEventTarget(OnHoverNone, m_pbuttonTraining->GetMouseLeaveEventSource());
AddEventTarget(&IntroScreen::OnHoverNone, m_pbuttonTrainingBig->GetMouseLeaveEventSource());
AddEventTarget(&IntroScreen::OnHoverNone, m_pbuttonZoneWeb->GetMouseLeaveEventSource());
AddEventTarget(&IntroScreen::OnHoverNone, m_pbuttonOptions->GetMouseLeaveEventSource());
AddEventTarget(&IntroScreen::OnHoverNone, m_pbuttonIntro->GetMouseLeaveEventSource());
AddEventTarget(&IntroScreen::OnHoverNone, m_pbuttonCredits->GetMouseLeaveEventSource());
//AddEventTarget(OnHoverNone, m_pbuttonQuickstart->GetMouseLeaveEventSource());
AddEventTarget(&IntroScreen::OnHoverNone, m_pbuttonHelp->GetMouseLeaveEventSource());
AddEventTarget(&IntroScreen::OnHoverNone, m_pbuttonExit->GetMouseLeaveEventSource());
/*m_pbuttonZoneClub->SetEnabled(false);
m_pbuttonPlayLan->SetEnabled(false);*/
// BT - Steam - Hiding these irrelevant buttons for now.
#ifndef USEAZ
m_pbuttonZoneClub->SetHidden(true);
#endif
m_pbuttonPlayLan->SetHidden(true);
m_pbuttonPlayInt->SetEnabled(true); //Imago 9/14
m_pfindServerPopup = new FindServerPopup(pns, this);
pmodeler->UnloadNameSpace(pns);
trekClient.Disconnect();
trekClient.DisconnectLobby();
if (g_bQuickstart || g_bReloaded)
AddEventTarget(&IntroScreen::OnQuickstart, GetWindow(), 0.01f);
// we only do this once per execution, and only if training is installed
static bool bHaveVisited = false;
if (Training::IsInstalled () && !bHaveVisited)
{
// check to see if training has been run before
HKEY hKey;
DWORD dwHasRunTraining = 0;
DWORD dwDataSize = sizeof (dwHasRunTraining);
if (ERROR_SUCCESS == RegOpenKeyEx (HKEY_LOCAL_MACHINE, ALLEGIANCE_REGISTRY_KEY_ROOT, 0, KEY_READ, &hKey))
{
RegQueryValueExA(hKey, "HasTrained", NULL, NULL, (LPBYTE) &dwHasRunTraining, &dwDataSize);
RegCloseKey(hKey);
}
// first time through, show a dialog explaining that users
// really should do the training first
if (!dwHasRunTraining)
{
TRef<IMessageBox> pMsgBox =
CreateMessageBox(
"ALLEGIANCE is a team-based massively-multiplayer space combat game, in which your goal is to conquer the universe.\n\nTraining is strongly recommended before going online, and will take approximately 30 minutes. Press the OK button to begin training now.",
NULL,
true,
true
);
TRef<Surface> psurface = GetModeler()->LoadSurface("btndontaskmeagainbmp", true);
TRef<ButtonPane> pDontAskMeAgain
= CreateTrekButton(CreateButtonFacePane(psurface, ButtonNormalCheckBox), true, mouseclickSound);
pDontAskMeAgain->SetOffset(WinPoint(183, 140));
pMsgBox->GetPane()->InsertAtBottom(pDontAskMeAgain);
pMsgBox->GetEventSource()->AddSink(new CloseTrainWarnSink(this, pDontAskMeAgain));
GetWindow()->GetPopupContainer()->OpenPopup (pMsgBox, false);
}
}
if (g_bAskForCDKey && !bHaveVisited && trekClient.GetCDKey().IsEmpty())
{
TRef<IPopup> ppopupCDKey = CreateCDKeyPopup();
GetWindow()->GetPopupContainer()->OpenPopup(ppopupCDKey, false);
}
// stop us from asking again during this execution
bHaveVisited = true;
trekClient.FlushSessionLostMessage();
#ifdef ENABLE3DINTROSCREEN
// KGJV test
{
m_pwrapImage->SetImage((Image*)(Value *)pns->FindMember("bkImage"));
m_ppaneGeo = CreateGeoPane(Point(800, 528),Point(0, 0)
//pns->FindPoint("geoSize"),
//pns->FindPoint("geoPosition")
);
m_ppaneGeo->SetOffset(WinPoint(0, 0)
//pns->FindWinPoint("geoPosition")
);
m_ppane->InsertAtTop(m_ppaneGeo);
TRef<StringValue> pstring; CastTo(pstring, pns->FindMember("geoModel"));
char *models[] = {
"alleglogo",
"fig03",
"faohbssy",
"fig20",
"quizfig",
"fig30",
"ss01",
"ss101",
"ss27",
"utl95",
"bgrnd57",
"bsg_colrap2"
};
Orientation ors[] = {
Orientation (Vector (0.0f, -1.0f, 0.0f), Vector (0.0f, 0.0f, 1.0f)),
Orientation (Vector (0.1f, 0.0f, 0.0f), Vector (0.0f, 0.0f, 1.0f)),
Orientation (Vector (0.0f, 1.0f, 0.0f), Vector (0.0f, 0.0f, 1.0f)),
Orientation (Vector (0.1f, 0.0f, 0.0f), Vector (0.0f, 0.0f, 1.0f)),
Orientation (Vector (0.1f, 0.0f, 0.0f), Vector (0.0f, 0.0f, 1.0f)),
Orientation (Vector (0.1f, 0.0f, 0.0f), Vector (0.0f, 0.0f, 1.0f)),
Orientation (Vector (0.0f, 1.0f, 0.0f), Vector (0.0f, 0.0f, 1.0f)),
Orientation (Vector (0.0f, 1.0f, 0.0f), Vector (0.0f, 0.0f, 1.0f)),
Orientation (Vector (0.0f, 1.0f, 0.0f), Vector (0.0f, 0.0f, 1.0f)),
Orientation (Vector (0.1f, 0.0f, 0.0f), Vector (0.0f, 0.0f, 1.0f)),
Orientation (Vector (0.0f, 1.0f, 0.0f), Vector (0.0f, 0.0f, 1.0f)),
Orientation (Vector (0.1f, 0.0f, 0.0f), Vector (0.0f, 0.0f, 1.0f))
};
srand(GetTickCount() + (int)time(NULL)); //imago 10/14, apparently this call in ZLib is out of scope.
int sel = randomInt(0, 11);
TRef<INameSpace> pnsgeo = m_pmodeler->GetNameSpace(models[sel]
//pstring->GetValue()
);
if (pnsgeo) {
m_pthing = ThingGeo::Create(m_pmodeler, m_ptime);
m_pthing->LoadMDL(0, pnsgeo, NULL);
if (sel != 0)
m_pthing->SetShadeAlways(true);
//m_pthing->SetTransparentObjects(true);
m_pthing->SetOrientation(ors[sel]);
//m_pthing->SetShowBounds(true);
SetGeo(m_pthing->GetGeo());
}
}
#endif
}
virtual ~IntroScreen()
{
m_pmodeler->UnloadNameSpace("introscreendata");
#ifdef ENABLE3DINTROSCREEN
m_pthing->SetTransparentObjects(false);
m_pthing->SetShowBounds(false);
#endif
}
bool OnQuickstart()
{
#ifdef USEAZ //Imago 7/4/09 #78
OnButtonZoneClub();
#else
OnButtonInternet();
#endif
return false;
}
#ifdef ENABLE3DINTROSCREEN
// KGJV
void SetGeo(Geo* pgeo)
{
m_pwrapGeo->SetGeo(pgeo);
float radius = pgeo->GetRadius(Matrix::GetIdentity());
//m_scaleCone = 0.75f * radius;
m_pcamera->SetPosition(
Vector(
0,
0,
2.4f * radius
)
);
}
// KGJV
TRef<Pane> CreateGeoPane(const Point& size, const Point& offset)
{
m_pcamera = new Camera();
m_pcamera->SetZClip(1, 10000);
m_pcamera->SetFOV(RadiansFromDegrees(55));
Rect rect(Point(0, 0), size);
TRef<RectValue> prect = new RectValue(rect);
m_pviewport = new Viewport(m_pcamera, prect);
m_pwrapGeo = new WrapGeo(Geo::GetEmpty());
m_pwrapImageGeo = new WrapImage(Image::GetEmpty());
m_ptime = GetWindow()->GetTime();
GeoImage* pgeo =
new GeoImage(
new TransformGeo(
new TransformGeo(
m_pwrapGeo,
new AnimateRotateTransform(
new VectorValue(Vector(0, 1, 0)),
Multiply(m_ptime, new Number(1))
)
),
new RotateTransform(Vector(1, 0, 0), pi/8)
),
m_pviewport,
true
);
TRef<Image> pimage =
new GroupImage(
m_pwrapImageGeo,
pgeo,
new TranslateImage(
m_pwrapImage,
Point(-offset.X(), -(600 - size.Y() - offset.Y()))
)
);
//
// Give this guy a zbuffer
//
return
new AnimatedImagePane(
CreatePaneImage(
GetEngine(),
SurfaceType3D() | SurfaceTypeZBuffer(),
false,
new AnimatedImagePane(
pimage,
rect
)
)
);
}
#endif
//////////////////////////////////////////////////////////////////////////////
//
// Event handlers
//
//////////////////////////////////////////////////////////////////////////////
bool OnPickServer(GUID guidSession)
{
assert (!trekClient.LoggedOn());
m_guidSession = guidSession;
//
// pop up the call sign/login dialog
//
TRef<IPopup> plogonPopup = CreateLogonPopup(m_pmodeler, this, LogonLAN,
"Enter a call sign to use for this game.", trekClient.GetSavedCharacterName(), "", false);
GetWindow()->GetPopupContainer()->OpenPopup(plogonPopup, false);
return true;
}
bool OnButtonTraining()
{
if (Training::IsInstalled ())
{
// go train, because we have all the training files installed
trekClient.SetIsLobbied(false);
trekClient.SetIsZoneClub(false);
GetWindow()->screen(ScreenIDTrainScreen);
}
else // wlp 2006 - go straight to lobby
{
// otherwise give the player the option to download the training files
// if they do, then go to the download, and restart allegiance
// otherwise don't do anything
m_pMsgBox = CreateMessageBox ("TRAINING IS NOT INSTALLED.\n\nClick 'OK' to open the Allegiance website, then follow the directions there to download and install training.", NULL, false);
TRef<Surface> psurfaceOKButton = GetModeler ()->LoadImage ("btnokbmp", true)->GetSurface();
TRef<Surface> psurfaceAbortButton = GetModeler ()->LoadImage ("btnabortbmp", true)->GetSurface();
TRef<ButtonPane> pOKButton = CreateButton ( CreateButtonFacePane(psurfaceOKButton, ButtonNormal, 0, psurfaceOKButton->GetSize().X()), false, 0, 1.0);
TRef<ButtonPane> pAbortButton = CreateButton ( CreateButtonFacePane(psurfaceAbortButton, ButtonNormal, 0, psurfaceAbortButton->GetSize().X()), false, 0, 1.0);
pOKButton->SetOffset (WinPoint(100, 170));
pAbortButton->SetOffset (WinPoint(300, 170));
m_pMsgBox->GetPane ()->InsertAtBottom (pOKButton);
m_pMsgBox->GetPane ()->InsertAtBottom (pAbortButton);
AddEventTarget(&IntroScreen::OnButtonBailTraining, pAbortButton->GetEventSource());
AddEventTarget(&IntroScreen::OnButtonDownloadTraining, pOKButton->GetEventSource());
GetWindow()->GetPopupContainer()->OpenPopup (m_pMsgBox, false);
}
return true;
}
bool OnButtonBailTraining ()
{
GetWindow ()->GetPopupContainer ()->ClosePopup (m_pMsgBox);
return true;
}
bool OnButtonDownloadTraining ()
{
// close the dialog window
GetWindow ()->GetPopupContainer ()->ClosePopup (m_pMsgBox);
// start to find the config file
char config_file_name[MAX_PATH];
// get the app build number
ZVersionInfo vi;
ZString strBuild(vi.GetFileBuildNumber());
// start with a default name
Strcpy(config_file_name, "Allegiance");
Strcat(config_file_name, PCC(strBuild));
Strcat(config_file_name, ".cfg");
// then look to see if there is one in the registry we should use instead
HKEY hKey;
if (ERROR_SUCCESS == ::RegOpenKeyEx(HKEY_LOCAL_MACHINE, ALLEGIANCE_REGISTRY_KEY_ROOT, 0, KEY_READ, &hKey))
{
DWORD cbValue = MAX_PATH;
char reg_config_file_name[MAX_PATH] = {0};
// BT - 7/15 - CSS Integration - Enable beta mode
if (g_bBetaMode == true)
::RegQueryValueExA(hKey, "BetaCfgFile", NULL, NULL, (LPBYTE)®_config_file_name, &cbValue);
else
::RegQueryValueExA(hKey, "CfgFile", NULL, NULL, (LPBYTE)®_config_file_name, &cbValue);
// if it didn't succeed, we'll just use the default above
if (strlen (reg_config_file_name) > 0)
Strcpy (config_file_name, reg_config_file_name);
}
// then construct the full path name of the config file
PathString pathEXE(PathString::GetCurrentDirectory());
PathString pathConfig(pathEXE + PathString(PathString(config_file_name).GetFilename()));
// load the config data
CfgInfo cfgInfo;
cfgInfo.Load (pathConfig);
if (cfgInfo.strTrainingURL)
{
// if everything is OK, launch the web page
GetWindow ()->ShowWebPage (cfgInfo.strTrainingURL);
// ... and close our application
GetWindow()->PostMessage(WM_CLOSE);
}
else
{
// if not, we alert the user...
TRef<IMessageBox> pMsgBox = CreateMessageBox ("CAN'T DOWNLOAD TRAINING FILES.\n\nCan't find the download address.", NULL, true);
GetWindow()->GetPopupContainer()->OpenPopup (pMsgBox, false);
}
return true;
}
void OnLogon(const ZString& strName, const ZString& strPassword, BOOL fRememberPW)
{
// remember the character name for next time
trekClient.SaveCharacterName(strName);
m_strCharacterName = strName;
//m_strPassword = "";
// pop up the Connecting... dialog.
GetWindow()->SetWaitCursor();
TRef<IMessageBox> pmsgBox = CreateMessageBox("Connecting...", NULL, false);
GetWindow()->GetPopupContainer()->OpenPopup(pmsgBox, false);
// pause to let the "connecting..." box draw itself
AddEventTarget(&IntroScreen::OnTryLogon, GetWindow(), 0.1f);
}
bool OnTryLogon()
{
trekClient.SetIsLobbied(false);
trekClient.SetIsZoneClub(false);
BaseClient::ConnectInfo ci;
ci.guidSession = m_guidSession;
strcpy(ci.szName, m_strCharacterName);
assert(strlen(m_strPassword) < c_cbGamePassword);
trekClient.ConnectToServer(ci, NA, Time::Now(), m_strPassword, true);
return false;
}
void OnLogonGameServer()
{
// wait for a join message.
GetWindow()->SetWaitCursor();
TRef<IMessageBox> pmsgBox =
CreateMessageBox("Joining mission....", NULL, false, false);
GetWindow()->GetPopupContainer()->OpenPopup(pmsgBox, false);
}
void OnLogonGameServerFailed(bool bRetry, const char* szReason)
{
if (bRetry)
{
// pop up the call sign/login dialog
TRef<IPopup> plogonPopup = CreateLogonPopup(m_pmodeler, this, LogonLAN,
szReason, trekClient.GetSavedCharacterName(), "", false);
GetWindow()->GetPopupContainer()->OpenPopup(plogonPopup, false);
}
else
{
// tell the user why the logon failed
TRef<IMessageBox> pmsgBox = CreateMessageBox(szReason);
GetWindow()->GetPopupContainer()->OpenPopup(pmsgBox, false);
}
}
void OnAddPlayer(MissionInfo* pMissionInfo, SideID sideID, PlayerInfo* pPlayerInfo)
{
if (pMissionInfo && pPlayerInfo == trekClient.MyPlayerInfo())
{
// go to the team lobby...
GetWindow()->screen(ScreenIDTeamScreen);
}
}
void OnDelRequest(MissionInfo* pMissionInfo, SideID sideID, PlayerInfo* pPlayerInfo, DelPositionReqReason reason)
{
if (pPlayerInfo == trekClient.MyPlayerInfo())
{
m_pmissionJoining = pMissionInfo;
// rejected !! Bad password?
if (!GetWindow()->GetPopupContainer()->IsEmpty())
GetWindow()->GetPopupContainer()->ClosePopup(NULL);
GetWindow()->RestoreCursor();
if (reason == DPR_BadPassword)
{
TRef<IPopup> ppopupPassword = CreatePasswordPopup(this, m_strPassword);
GetWindow()->GetPopupContainer()->OpenPopup(ppopupPassword, false);
}
else if (reason == DPR_NoMission)
{
TRef<IMessageBox> pmsgBox = CreateMessageBox("The mission you were trying to join has ended.");
GetWindow()->GetPopupContainer()->OpenPopup(pmsgBox, false);
trekClient.Disconnect();
}
else if (reason == DPR_LobbyLocked)
{
TRef<IMessageBox> pmsgBox = CreateMessageBox("The lobby for this mission is locked.");
GetWindow()->GetPopupContainer()->OpenPopup(pmsgBox, false);
trekClient.Disconnect();
}
else if (reason == DPR_OutOfLives)
{
TRef<IMessageBox> pmsgBox = CreateMessageBox("You have run out of lives in this mission.");
GetWindow()->GetPopupContainer()->OpenPopup(pmsgBox, false);
trekClient.Disconnect();
}
else if (reason == DPR_Banned)
{
TRef<IMessageBox> pmsgBox = CreateMessageBox("You have been removed (i.e. booted) from this game by the commander(s)."); // mmf 09/07 was "You have been banned from this mission."
GetWindow()->GetPopupContainer()->OpenPopup(pmsgBox, false);
trekClient.Disconnect();
}
else if (reason == DPR_GameFull)
{
TRef<IMessageBox> pmsgBox = CreateMessageBox("This server has reached its maximum number of players.");
GetWindow()->GetPopupContainer()->OpenPopup(pmsgBox, false);
trekClient.Disconnect();
}
else if (reason == DPR_PrivateGame)
{
TRef<IMessageBox> pmsgBox = CreateMessageBox("The game you tried to join is private. Your login id does not have access to it.");
GetWindow()->GetPopupContainer()->OpenPopup(pmsgBox, false);
trekClient.Disconnect();
}
else if (reason == DPR_DuplicateLogin)
{
TRef<IMessageBox> pmsgBox = CreateMessageBox("Someone else is already using that name in this game.");
GetWindow()->GetPopupContainer()->OpenPopup(pmsgBox, false);
trekClient.Disconnect();
}
else if (reason == DPR_ServerPaused)
{
TRef<IMessageBox> pmsgBox = CreateMessageBox("The server for this game is shutting down and is not accepting new users.");
GetWindow()->GetPopupContainer()->OpenPopup(pmsgBox, false);
trekClient.Disconnect();
}
else
{
TRef<IMessageBox> pmsgBox = CreateMessageBox("You have not been accepted into the game.");
GetWindow()->GetPopupContainer()->OpenPopup(pmsgBox, false);
trekClient.Disconnect();
}
}
}
virtual void OnCancelPassword()
{
trekClient.Disconnect();
}
virtual void OnPassword(ZString strPassword)
{
// try the new password
m_strPassword = <PASSWORD>;
// pop up the Connecting... dialog.
GetWindow()->SetWaitCursor();
TRef<IMessageBox> pmsgBox = CreateMessageBox("Connecting...", NULL, false);
GetWindow()->GetPopupContainer()->OpenPopup(pmsgBox, false);
// pause to let the "connecting..." box draw itself
AddEventTarget(&IntroScreen::OnTryLogon, GetWindow(), 0.1f);
}
void OnAbort()
{
// user aborted logging on; we don't need to do anything
};
bool OnButtonExit()
{
GetWindow()->StartClose();
return true;
}
bool OnButtonHelp()
{
GetWindow()->OnHelp (true);
return true;
}
bool OnButtonZoneClub()
{
if (CheckNetworkDrivers())
{
trekClient.SetIsZoneClub(true);
GetWindow()->screen(ScreenIDZoneClubScreen);
}
return true;
}
bool OnButtonInternet()
{
if (CheckNetworkDrivers())
{
trekClient.SetIsZoneClub(false);
GetWindow()->screen(ScreenIDZoneClubScreen);
}
return true;
}
bool OnButtonLAN()
{
if (CheckNetworkDrivers())
{
GetWindow()->GetPopupContainer()->OpenPopup(m_pfindServerPopup, false);
}
return true;
}
bool OnButtonZoneWeb()
{
GetWindow()->ShowWebPage();
return true;
}
bool OnButtonOptions()
{
GetWindow()->ShowOptionsMenu();
return true;
}
bool OnButtonCredits()
{
#if (DIRECT3D_VERSION >= 0x0800)
GetModeler()->SetColorKeyHint( true );
#endif
TRef<INameSpace> pnsCredits = GetModeler()->GetNameSpace("creditspane");
m_pcreditsPopup = new CreditsPopup(pnsCredits, this, GetWindow()->GetTime());
GetWindow()->GetPopupContainer()->OpenPopup(m_pcreditsPopup, false);
return true;
}
bool OnButtonIntro()
{
GetWindow()->screen(ScreenIDSplashScreen);
return true;
}
bool OnHoverPlayLan()
{
m_pnumberCurrentHover->SetValue(hoverPlayLan);
return true;
}
bool OnHoverPlayInt()
{
m_pnumberCurrentHover->SetValue(hoverPlayInt);
return true;
}
bool OnHoverZoneClub()
{
m_pnumberCurrentHover->SetValue(hoverZoneClub);
return true;
}
bool OnHoverTrain()
{
m_pnumberCurrentHover->SetValue(hoverTrain);
return true;
}
bool OnHoverZoneWeb()
{
m_pnumberCurrentHover->SetValue(hoverZoneWeb);
return true;
}
bool OnHoverOptions()
{
m_pnumberCurrentHover->SetValue(hoverOptions);
return true;
}
bool OnHoverIntro()
{
m_pnumberCurrentHover->SetValue(hoverIntro);
return true;
}
bool OnHoverCredits()
{
m_pnumberCurrentHover->SetValue(hoverCredits);
return true;
}
bool OnHoverQuickstart()
{
m_pnumberCurrentHover->SetValue(hoverQuickstart);
return true;
}
bool OnHoverHelp()
{
m_pnumberCurrentHover->SetValue(hoverHelp);
return true;
}
bool OnHoverExit()
{
m_pnumberCurrentHover->SetValue(hoverExit);
return true;
}
bool OnHoverNone()
{
m_pnumberCurrentHover->SetValue(hoverNone);
return true;
}
//////////////////////////////////////////////////////////////////////////////
//
// Screen Methods
//
//////////////////////////////////////////////////////////////////////////////
Pane* GetPane()
{
return m_ppane;
}
};
//////////////////////////////////////////////////////////////////////////////
//
// Constructor
//
//////////////////////////////////////////////////////////////////////////////
TRef<Screen> CreateIntroScreen(Modeler* pmodeler)
{
return new IntroScreen(pmodeler);
}
|
TobiasLudwig/boost.simd
|
test/api/algorithm/replace.cpp
|
<reponame>TobiasLudwig/boost.simd<filename>test/api/algorithm/replace.cpp
//==================================================================================================
/*
Copyright 2017 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#include <boost/simd/algorithm/replace.hpp>
#include <numeric>
#include <vector>
#include <simd_test.hpp>
using namespace boost::simd;
using namespace boost::alignment;
STF_CASE_TPL( "Check unary simd::replace", STF_NUMERIC_TYPES )
{
static const int N = pack<T>::static_size;
std::vector<T> values(2*N+3), ref(2*N+3);
std::iota(values.begin(), values.end(),T(1));
std::iota(ref.begin(), ref.end(),T(1));
{
std::replace(ref.begin(), ref.end(), T(1), T(0));
boost::simd::replace(values.data(), values.data()+2*N+3, T(1), T(0));
STF_EQUAL( values, ref );
}
{
std::replace(ref.begin(), ref.end(), T(2*N+2), T(0));
boost::simd::replace(values.data(), values.data()+2*N+3, T(2*N+2), T(0));
STF_EQUAL( values, ref );
}
{
std::replace(ref.begin(), ref.end(), T(2*N+2), T(0));
boost::simd::replace(values.data(), values.data()+2*N+3, T(2*N+2), T(0));
STF_EQUAL( values, ref );
}
}
|
ridi/chromium-aw
|
src/main/java/org/chromium/content/browser/input/ImeAdapterImplJni.java
|
<reponame>ridi/chromium-aw
package org.chromium.content.browser.input;
import android.view.KeyEvent;
import java.lang.CharSequence;
import java.lang.Override;
import java.lang.String;
import javax.annotation.Generated;
import org.chromium.base.JniStaticTestMocker;
import org.chromium.base.NativeLibraryLoadedStatus;
import org.chromium.base.annotations.CheckDiscard;
import org.chromium.base.natives.GEN_JNI;
import org.chromium.content_public.browser.WebContents;
@Generated("org.chromium.jni_generator.JniProcessor")
@CheckDiscard("crbug.com/993421")
final class ImeAdapterImplJni implements ImeAdapterImpl.Natives {
private static ImeAdapterImpl.Natives testInstance;
public static final JniStaticTestMocker<ImeAdapterImpl.Natives> TEST_HOOKS = new org.chromium.base.JniStaticTestMocker<org.chromium.content.browser.input.ImeAdapterImpl.Natives>() {
@java.lang.Override
public void setInstanceForTesting(
org.chromium.content.browser.input.ImeAdapterImpl.Natives instance) {
if (!org.chromium.base.natives.GEN_JNI.TESTING_ENABLED) {
throw new RuntimeException("Tried to set a JNI mock when mocks aren't enabled!");
}
testInstance = instance;
}
};
@Override
public long init(ImeAdapterImpl caller, WebContents webContents) {
return (long)GEN_JNI.org_chromium_content_browser_input_ImeAdapterImpl_init(caller, webContents);
}
@Override
public boolean sendKeyEvent(long nativeImeAdapterAndroid, ImeAdapterImpl caller, KeyEvent event,
int type, int modifiers, long timestampMs, int keyCode, int scanCode, boolean isSystemKey,
int unicodeChar) {
return (boolean)GEN_JNI.org_chromium_content_browser_input_ImeAdapterImpl_sendKeyEvent(nativeImeAdapterAndroid, caller, event, type, modifiers, timestampMs, keyCode, scanCode, isSystemKey, unicodeChar);
}
@Override
public void appendUnderlineSpan(long spanPtr, int start, int end) {
GEN_JNI.org_chromium_content_browser_input_ImeAdapterImpl_appendUnderlineSpan(spanPtr, start, end);
}
@Override
public void appendBackgroundColorSpan(long spanPtr, int start, int end, int backgroundColor) {
GEN_JNI.org_chromium_content_browser_input_ImeAdapterImpl_appendBackgroundColorSpan(spanPtr, start, end, backgroundColor);
}
@Override
public void appendSuggestionSpan(long spanPtr, int start, int end, boolean isMisspelling,
boolean removeOnFinishComposing, int underlineColor, int suggestionHighlightColor,
String[] suggestions) {
GEN_JNI.org_chromium_content_browser_input_ImeAdapterImpl_appendSuggestionSpan(spanPtr, start, end, isMisspelling, removeOnFinishComposing, underlineColor, suggestionHighlightColor, suggestions);
}
@Override
public void setComposingText(long nativeImeAdapterAndroid, ImeAdapterImpl caller,
CharSequence text, String textStr, int newCursorPosition) {
GEN_JNI.org_chromium_content_browser_input_ImeAdapterImpl_setComposingText(nativeImeAdapterAndroid, caller, text, textStr, newCursorPosition);
}
@Override
public void commitText(long nativeImeAdapterAndroid, ImeAdapterImpl caller, CharSequence text,
String textStr, int newCursorPosition) {
GEN_JNI.org_chromium_content_browser_input_ImeAdapterImpl_commitText(nativeImeAdapterAndroid, caller, text, textStr, newCursorPosition);
}
@Override
public void finishComposingText(long nativeImeAdapterAndroid, ImeAdapterImpl caller) {
GEN_JNI.org_chromium_content_browser_input_ImeAdapterImpl_finishComposingText(nativeImeAdapterAndroid, caller);
}
@Override
public void setEditableSelectionOffsets(long nativeImeAdapterAndroid, ImeAdapterImpl caller,
int start, int end) {
GEN_JNI.org_chromium_content_browser_input_ImeAdapterImpl_setEditableSelectionOffsets(nativeImeAdapterAndroid, caller, start, end);
}
@Override
public void setComposingRegion(long nativeImeAdapterAndroid, ImeAdapterImpl caller, int start,
int end) {
GEN_JNI.org_chromium_content_browser_input_ImeAdapterImpl_setComposingRegion(nativeImeAdapterAndroid, caller, start, end);
}
@Override
public void deleteSurroundingText(long nativeImeAdapterAndroid, ImeAdapterImpl caller, int before,
int after) {
GEN_JNI.org_chromium_content_browser_input_ImeAdapterImpl_deleteSurroundingText(nativeImeAdapterAndroid, caller, before, after);
}
@Override
public void deleteSurroundingTextInCodePoints(long nativeImeAdapterAndroid, ImeAdapterImpl caller,
int before, int after) {
GEN_JNI.org_chromium_content_browser_input_ImeAdapterImpl_deleteSurroundingTextInCodePoints(nativeImeAdapterAndroid, caller, before, after);
}
@Override
public boolean requestTextInputStateUpdate(long nativeImeAdapterAndroid, ImeAdapterImpl caller) {
return (boolean)GEN_JNI.org_chromium_content_browser_input_ImeAdapterImpl_requestTextInputStateUpdate(nativeImeAdapterAndroid, caller);
}
@Override
public void requestCursorUpdate(long nativeImeAdapterAndroid, ImeAdapterImpl caller,
boolean immediateRequest, boolean monitorRequest) {
GEN_JNI.org_chromium_content_browser_input_ImeAdapterImpl_requestCursorUpdate(nativeImeAdapterAndroid, caller, immediateRequest, monitorRequest);
}
@Override
public void advanceFocusInForm(long nativeImeAdapterAndroid, ImeAdapterImpl caller,
int focusType) {
GEN_JNI.org_chromium_content_browser_input_ImeAdapterImpl_advanceFocusInForm(nativeImeAdapterAndroid, caller, focusType);
}
public static ImeAdapterImpl.Natives get() {
if (GEN_JNI.TESTING_ENABLED) {
if (testInstance != null) {
return testInstance;
}
if (GEN_JNI.REQUIRE_MOCK) {
throw new UnsupportedOperationException("No mock found for the native implementation for org.chromium.content.browser.input.ImeAdapterImpl.Natives. The current configuration requires all native implementations to have a mock instance.");
}
}
NativeLibraryLoadedStatus.checkLoaded(false);
return new ImeAdapterImplJni();
}
}
|
juliomarcelopicardo/Wolfy2D
|
src/core/material.cc
|
/** Copyright <NAME>. 2017-18, all rights reserved.
*
* @project Wolfy2D - Including JMP scripting language.
* @author <NAME> <<EMAIL>>
*
*/
#include "GL/glew.h"
#include "core/material.h"
#include "core/core.h"
#include "imgui/logger_module.h"
#include <string>
#include <vector>
namespace W2D {
/*******************************************************************************
*** Constructor and destructor ***
*******************************************************************************/
Material::Material() {
uniform_location_ = { 0, 0, 0, 0 };
}
Material::~Material() {
if (glIsProgram(program_id_)) {
glDeleteProgram(program_id_);
}
}
/*******************************************************************************
*** Material methods ***
*******************************************************************************/
void Material::saveShadersCode() {
vertex_shader_code_.clear();
fragment_shader_code_.clear();
vertex_shader_code_ =
"#version 330\n"
"layout(location = 0) in vec3 a_position;\n"
"layout(location = 1) in vec2 a_uv;\n"
"uniform mat4 u_m_matrix;\n"
"uniform mat4 u_p_matrix;\n"
"uniform int u_time;\n"
"out vec3 normal;\n"
"out vec2 uv;\n"
"void main() {\n"
" uv = a_uv;\n"
" gl_Position = u_p_matrix* u_m_matrix * vec4(a_position, 1.0);\n}";
fragment_shader_code_ =
"#version 330\n"
"in vec2 uv;\n"
"uniform sampler2D u_sample;\n"
"out vec4 fragColor;\n"
"void main() {\n"
" fragColor = texture(u_sample, uv);\n"
"}\n";
}
void Material::createProgram() {
program_id_ = glCreateProgram();
}
void Material::createShaders() {
vertex_shader_id_ = glCreateShader(GL_VERTEX_SHADER);
fragment_shader_id_ = glCreateShader(GL_FRAGMENT_SHADER);
}
void Material::compileShaders() {
const GLchar* vertex_shader_code = vertex_shader_code_.c_str();
glShaderSource(vertex_shader_id_, 1, &vertex_shader_code, NULL);
glCompileShader(vertex_shader_id_);
logShaderError(vertex_shader_id_);
const GLchar* fragment_shader_code = fragment_shader_code_.c_str();
glShaderSource(fragment_shader_id_, 1, &fragment_shader_code, NULL);
glCompileShader(fragment_shader_id_);
logShaderError(fragment_shader_id_);
}
void Material::attachShaders() {
glAttachShader(program_id_, vertex_shader_id_);
glAttachShader(program_id_, fragment_shader_id_);
}
void Material::linkProgram() {
glLinkProgram(program_id_);
logProgramError();
}
void Material::detachShaders() {
glDetachShader(program_id_, vertex_shader_id_);
glDetachShader(program_id_, fragment_shader_id_);
}
void Material::deleteShaders() {
glDeleteShader(vertex_shader_id_);
glDeleteShader(fragment_shader_id_);
}
/* Hacemos esto para optimizar, guardando los uniforms en variables evitamos tener
que hacer la llamada glGetUniformLocation en cada frame (ya que es muy costosa).
*/
void Material::saveUniformLocations() {
uint32 program = program_id_;
glUseProgram(program_id_);
// Material Uniforms.
uniform_location_.model_matrix = glGetUniformLocation(program, "u_m_matrix");
uniform_location_.projection_matrix = glGetUniformLocation(program, "u_p_matrix");
uniform_location_.time = glGetUniformLocation(program, "u_time");
uniform_location_.texture = glGetUniformLocation(program, "u_sample");
glUseProgram(0);
}
void Material::render(const float model_matrix[16],
const float projection_matrix[16],
const uint32 texture_id) {
//Estas dos flags son las que van a hacer que todo alpha por debajo
//de 0.01 sea descartado, y sin usar un discard.
glAlphaFunc(GL_GREATER, 0.01f);
glEnable(GL_ALPHA_TEST);
//Estas dos flags son para que primero se pinte lo que se ha de pintar
//primero, y no a la inversa.
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_ALWAYS);
glUseProgram(program_id_);
glUniformMatrix4fv(uniform_location_.model_matrix, 1, GL_FALSE, model_matrix);
glUniformMatrix4fv(uniform_location_.projection_matrix, 1, GL_FALSE, projection_matrix);
glUniform1i(uniform_location_.time, (uint32)Time());
glActiveTexture(GL_TEXTURE0 + 0);
glBindTexture(GL_TEXTURE_2D, texture_id);
glUniform1i(uniform_location_.texture, 0);
}
void Material::init(const char* lua_path) {
saveShadersCode();
createProgram();
createShaders();
compileShaders();
attachShaders();
linkProgram();
detachShaders();
deleteShaders();
saveUniformLocations();
}
/*******************************************************************************
*** Error checkings ***
*******************************************************************************/
void Material::logShaderError(const uint32 shader_id_) {
int32 log_length = 0;
int32 output = 0;
glGetShaderiv(shader_id_, GL_COMPILE_STATUS, &output);
glGetShaderiv(shader_id_, GL_INFO_LOG_LENGTH, &log_length);
if (output == GL_FALSE || log_length > 0) {
std::vector<char> error_message(log_length + 1);
glGetShaderInfoLog(shader_id_, log_length, nullptr, error_message.data());
std::string log_error("Shader ERROR: ");
log_error += error_message.data();
Core::instance().user_interface_.log_.AddLog_E(log_error);
exit(EXIT_FAILURE);
}
}
void Material::logProgramError() {
int32 log_length = 0;
int32 output = 0;
glGetProgramiv(program_id_, GL_LINK_STATUS, &output);
glGetProgramiv(program_id_, GL_INFO_LOG_LENGTH, &log_length);
if (output == GL_FALSE || log_length > 0) {
std::vector<char> error_message(log_length + 1);
glGetProgramInfoLog(program_id_, log_length, nullptr, error_message.data());
std::string log_error("Shader ERROR: ");
log_error += error_message.data();
Core::instance().user_interface_.log_.AddLog_E(log_error);
exit(EXIT_FAILURE);
}
}
};/* W2D */
|
ViBiOh/fibr
|
pkg/exif/aggregate.go
|
<reponame>ViBiOh/fibr<gh_stars>10-100
package exif
import (
"fmt"
"path/filepath"
"time"
"github.com/ViBiOh/fibr/pkg/provider"
)
var (
aggregateRatio = 0.4
levels = []string{"city", "state", "country"}
)
// GetAggregateFor return aggregated value for a given directory
func (a App) GetAggregateFor(item provider.StorageItem) (provider.Aggregate, error) {
if !a.enabled() {
return provider.Aggregate{}, nil
}
if !item.IsDir {
return provider.Aggregate{}, nil
}
aggregate, err := a.loadAggregate(item)
if err != nil {
return aggregate, fmt.Errorf("unable to load aggregate: %s", err)
}
return aggregate, nil
}
func (a App) aggregate(item provider.StorageItem) error {
if !item.IsDir {
file, err := a.getDirOf(item)
if err != nil {
return fmt.Errorf("unable to get directory: %s", err)
}
item = file
}
if err := a.computeAndSaveAggregate(item); err != nil {
return fmt.Errorf("unable to compute aggregate: %s", err)
}
return nil
}
func (a App) computeAndSaveAggregate(dir provider.StorageItem) error {
directoryAggregate := newAggregate()
var minDate, maxDate time.Time
err := a.storageApp.Walk(dir.Pathname, func(item provider.StorageItem, err error) error {
if err != nil {
return err
}
if item.Pathname == dir.Pathname {
return nil
}
if item.IsDir {
return filepath.SkipDir
}
if a.hasExif(item) {
if itemDate, err := a.getDate(item); err == nil {
minDate, maxDate = aggregateDate(minDate, maxDate, itemDate)
}
}
if a.hasGeocode(item) {
data, err := a.loadGeocode(item)
if err != nil {
return fmt.Errorf("unable to get geocode: %s", err)
}
directoryAggregate.ingest(data)
}
return nil
})
if err != nil {
return fmt.Errorf("unable to aggregate: %s", err)
}
return a.saveMetadata(dir, aggregateMetadataFilename, provider.Aggregate{
Location: directoryAggregate.value(),
Start: minDate,
End: maxDate,
})
}
func aggregateDate(min, max, current time.Time) (time.Time, time.Time) {
if min.IsZero() || current.Before(min) {
min = current
}
if max.IsZero() || current.After(max) {
max = current
}
return min, max
}
func (a App) getDirOf(item provider.StorageItem) (provider.StorageItem, error) {
return a.storageApp.Info(item.Dir())
}
|
autoScript964/script
|
app_xy3d/src/main/java/com/script/fairy/TeamTask.java
|
package com.script.fairy;
import com.script.opencvapi.FindResult;
import com.script.opencvapi.LtLog;
import com.script.opencvapi.AtFairyConfig;
import com.script.framework.AtFairyImpl;
/**
* Created by user on 2019/6/3.
*/
public class TeamTask {
public GamePublicFuntion gamePublicFuntion;
public FindResult result;
public AtFairyImpl mFairy;
public SingleTask singleTask;
private int hour;
private int minute;
private int week;
private int activity_type = 1;
private String activity_name;
public boolean bool_genrank_state = false;
private boolean bool_rank = false;
private boolean bool_dairank_state = false;
public AtFairyImpl getmFairy() {
return mFairy;
}
public TeamTask(AtFairyImpl ypFairy) throws Exception {
mFairy = ypFairy;
gamePublicFuntion = new GamePublicFuntion(ypFairy);
singleTask = new SingleTask(ypFairy);
}
private int start_num = 3;
private boolean hanhua = true;
class TeamTask_Content extends TaskContent {
public TeamTask_Content(AtFairyImpl mFairy, String name) throws Exception {
super(mFairy, name);
}
void create() throws Exception {
super.create();
hanhua=true;
if (!AtFairyConfig.getOption("number").equals("")) {
start_num = Integer.parseInt(AtFairyConfig.getOption("number"));
}
}
void init() throws Exception {
gamePublicFuntion.init(1);
setTaskName(1);
}
void inOperation() throws Exception {
gamePublicFuntion.lv();
gamePublicFuntion.skipScene();
gamePublicFuntion.chat();
gamePublicFuntion.deng();
result = mFairy.findPic("ling3.png");
mFairy.onTap(0.8f, result, 1213, 52, 1232, 70, "", 1000);
result = mFairy.findPic(1045, 3, 1265, 50, "nn2.png");
mFairy.onTap(0.85f, result, "跳过教学", 500);
result = mFairy.findPic(962, 562, 1077, 636, "map.png");
mFairy.onTap(0.75f, result, 1123, 67, 1147, 86, "关闭地图界面", 500);
result = mFairy.findPic(331, 478, 597, 527, "rank20.png");
mFairy.onTap(0.85f, result, 780, 514, 801, 530, "同意申请", 500);
if (AtFairyConfig.getOption("jj").equals("1")) {
if (gamePublicFuntion.fb()) {
if (timeMap("jj", 180000, true)) {
mFairy.onTap(1032, 433, 1054, 447, "开始释放绝技", 1000);
mFairy.onTap(1033, 332, 1058, 350, "", 500);
mFairy.onTap(1216, 641, 1234, 662, "", 500);
gamePublicFuntion.close(3);
}
}
}
cancel();
use();
}
void cancel() throws Exception {
result = gamePublicFuntion.qx();
mFairy.onTap(0.8f, result, "取消", 500);
}
void use() throws Exception {
gamePublicFuntion.use();
}//使用
boolean activity_end(FindResult act) throws Exception {
return false;
}
void content_01() throws Exception {
if (timeCount(10, 0)) {
if (frequencyMap("actError", 1)) {
setTaskEnd();
return;
}
}
result = mFairy.findPic("activity.png");
if (result.sim > 0.75f) {
GamePublicFuntion.activity_bool = false;
mFairy.onTap(0.75f, result, "活动按钮", 800);
}
result = mFairy.findPic("activity1.png");
if (result.sim > 0.8f) {
if (oneSecond()) {
gamePublicFuntion.activity_type(activity_type);
result = mFairy.findPic("activity3.png");
if (result.sim > 0.8f) {
for (int i = 0; i < 5; i++) {
result = mFairy.findPic(617, 55, 660, 575, "activity2.png");
mFairy.onTap(0.75f, result, result.x + 30, result.y + 0, result.x + 40, result.y + 1, "领取活跃", 500);
}
}
}
FindResult act = mFairy.findPic(818, 35, 1009, 559, activity_name);
if (act.sim > 0.85f) {
if (activity_end(act)) {
oneSecond = 0;
return;
}
result = mFairy.findPic(act.x + 223, act.y - 30, act.x + 350, act.y + 71, "wan.png");
if (result.sim > 0.8f) {
setTaskEnd();
return;
}
result = mFairy.findPic(act.x + 223, act.y - 10, act.x + 354, act.y + 71, "qian.png");
if (result.sim > 0.8f) {
mFairy.onTap(1221, 37, 1247, 57, "", 500);
oneSecond = 0;
frequencyInit("actError");
bool_rank = false;
setTaskName(2);
return;
}
}
if (GamePublicFuntion.activity_bool == false) {
activitySlide.slideRange(new int[]{3, 5, 6, 7}, 2);
} else {
activitySlide.slideRange(new int[]{3, 5, 6, 7, 8}, 2, 0);
}
}
}//活动
void han() throws Exception {
result = mFairy.findPic("rank19.png");
if (result.sim > 0.8f) {
if (AtFairyConfig.getOption("han1").equals("1")) {
result = mFairy.findPic("han1.png");
mFairy.onTap(0.85f, result, "队伍喊话", 500);
} else {
result = mFairy.findPic("han1.png");
if (result.sim < 0.85f) {
mFairy.onTap(546, 441, 563, 453, "", 500);
}
}
if (AtFairyConfig.getOption("han2").equals("1")) {
result = mFairy.findPic("han2.png");
mFairy.onTap(0.85f, result, "帮派喊话", 500);
} else {
result = mFairy.findPic("han2.png");
if (result.sim < 0.85f) {
mFairy.onTap(675, 442, 687, 450, "", 500);
}
}
if (AtFairyConfig.getOption("han3").equals("1")) {
result = mFairy.findPic("han3.png");
mFairy.onTap(0.85f, result, "当前喊话", 500);
} else {
result = mFairy.findPic("han3.png");
if (result.sim < 0.85f) {
mFairy.onTap(804, 441, 816, 452, "", 500);
}
}
result = mFairy.findPic("han.png");
if(result.sim>0.85f) {
mFairy.onTap(0.85f, result, "一键喊话", 1000);
if(mapCount(0.8f,417,105,876,406,"hanhua.png")){
mFairy.onTap(920,161,937,178,"",500);
hanhua = false;
return;
}else{
result = mFairy.findPic("han.png");
if(result.sim>0.85f) {
mFairy.onTap(920,161,937,178,"",500);
return;
}
}
}
}
}//喊话
void rank(String[] img, String mb_str1,String[] mb_str2) throws Exception {
timeCount(10, 0);
if (bool_rank == false) {
result = mFairy.findPic("rank1.png");
if (result.sim > 0.85f) {
err = 0;
LtLog.e(mFairy.getLineInfo("发现创建队伍 >>> 队伍状态判断成功"));
bool_rank = true;
bool_dairank_state = true;
return;
}
gamePublicFuntion.rank();
if (gamePublicFuntion.mainScene()) {
result = mFairy.findPic(11,390,229,486, "rank8.png");
if (result.sim > 0.8f) {
err = 0;
result = mFairy.findPic(new String[]{"rank2.png", "rank3.png"});
if (result.sim > 0.85f) {
LtLog.e(mFairy.getLineInfo("发现跟随>>>队伍状态判断成功"));
frequencyInit("genRank");
bool_rank = true;
bool_dairank_state = false;
return;
} else {
if (frequencyMap("genRank", 2)) {
LtLog.e(mFairy.getLineInfo("发现自己是队长>>>队伍状态判断成功"));
bool_rank = true;
bool_dairank_state = true;
return;
}
}
}
return;
}
gamePublicFuntion.close(1);
} else {
frequencyInit("genRank");
result = mFairy.findPic("rank12.png");
if (result.sim > 0.8f) {
if (frequencyMap("mbError", 7)) {
mFairy.onTap(1097, 108, 1119, 121, "", 500);
return;
}
result = mFairy.findPic(185, 136, 446, 640, mb_str1);
if (result.sim > 0.85f) {
result = mFairy.findPic(result.x + 90, result.y - 20, result.x + 200, result.y + 43, "mb1.png");
if (result.sim > 0.85f) {
mFairy.onTap(0.85f, result, "点击 str1", 1000);
err = 4;
if (mb_str2 == null) {
err = 0;
result = mFairy.findPic("rank13.png");
mFairy.onTap(0.9f, result, "自动匹配", 500);
mFairy.onTap(969, 581, 1026, 603, "开始匹配", 2000);
return;
}
}
}
if (mb_str2 != null) {
result = mFairy.findPic(181, 132, 433, 681, mb_str2);
if (result.sim > 0.8f) {
err = 0;
mFairy.onTap(0.8f, result, "点击 str2", 1000);
result = mFairy.findPic("rank13.png");
mFairy.onTap(0.9f, result, "自动匹配", 500);
mFairy.onTap(969, 581, 1026, 603, "开始匹配", 500);
return;
}
}
rankmbSlide.slideRange(new int[]{3, 4, 5, 6}, 2, 0);
return;
} else {
frequencyInit("mbError");
}
result = mFairy.findPic(1,1,85,214,"rankScene.png");
LtLog.e(mFairy.getLineInfo("组队场景 sim:"+result.sim));
if (result.sim > 0.85f) {
err = 0;
result = mFairy.findPic(839,585,1078,711,"rank10.png");
if (result.sim > 0.85f) {
mFairy.onTap(0.85f, result, "创建队伍", 500);
bool_dairank_state = true;
}
if (bool_dairank_state == false) {
result = mFairy.findPic("rank5.png");
mFairy.onTap(0.85f, result, "退出队伍", 500);
return;
}
result = mFairy.findPic("yao1.png");
mFairy.onTap(0.85f, result, 1180, 66, 1200, 82, "批准", 500);
han();
result = mFairy.findPic("rank15.png");
if (result.sim > 0.8f) {
for (int i = 0; i < 5; i++) {
result = mFairy.findPic(408, 22, 543, 542, "rank16.png");
mFairy.onTap(0.85f, result, "批准", 500);
}
mFairy.onTap(336, 655, 370, 670, "", 1000);
}
result = mFairy.findPic(190,66,517,165,img);
if (result.sim > 0.8f) {
frequencyInit("rank_mb");
result = mFairy.findPic("rank11.png");
mFairy.onTap(0.85f, result, "自动匹配", 500);
if (gamePublicFuntion.rank_num() >= start_num) {
mFairy.onTap(100,110,141,127, "人数达到要求>>>前往", 500);
setTaskName(3);
return;
}
if (AtFairyConfig.getOption("5307").equals("1") || AtFairyConfig.getOption("5489").equals("1")) {
if (timeMap("han", 15000, true) && hanhua) {
result = mFairy.findPic("rank18.png");
if (result.sim > 0.8f) {
mFairy.onTap(0.8f, result, "喊话", 1000);
return;
}
}
}
result = mFairy.findPic("rank14.png");
mFairy.onTap(0.8f, result, "有人申请队伍", 1000);
} else {
if (frequencyMap("rank_mb", 2)) {
frequencyInit("start_activity");
mFairy.onTap(243,113,258,130, "", 1000);
}
}
if (frequencyMap("errRank_count", 10)) {
gamePublicFuntion.close(3);
bool_rank = false;
return;
}
return;
}
gamePublicFuntion.clickRank();
}
}
}
private boolean zg = false;
private long cb_time = 3600000;
public void zg() throws Exception {
new TeamTask_Content(mFairy, "带队捉鬼") {
void create() throws Exception {
super.create();
activity_type = 1;
activity_name = "zg.png";
if (AtFairyConfig.getOption("zg").equals("2")) {
zg = true;
} else {
zg = false;
}
long i = getTimeStamp(AtFairyConfig.getOption("cb"));
if (i != -1) {
cb_time = i;
}
}
void content_02() throws Exception {
rank(new String[]{"zg1.png"}, "zg6.png", null);
}
boolean activity_end(FindResult act) throws Exception {
if (zg == false) {
result = mFairy.findPic(act.x + 80, act.y + 2, act.x + 180, act.y + 66,
new String[]{"zg11.png", "zg12.png"});
if (result.sim > 0.92f) {
LtLog.e(mFairy.getLineInfo("捉鬼活跃度已满"));
setTaskEnd();
return true;
}
}
return false;
}
void cancel() throws Exception {
FindResult qx = gamePublicFuntion.qx();
if (qx.sim > 0.8f) {
result = mFairy.findPic("zg9.png");
if (result.sim > 0.8f) {
if (zg) {
mFairy.onTap(810, 436, 850, 451, "继续追鬼", 500);
} else {
mFairy.onTap(403, 436, 489, 448, "完成一轮查看活跃", 500);
setTaskName(0);
}
return;
}
result = mFairy.findPic("zg10.png");
if (result.sim > 0.8f) {
mFairy.onTap(585, 436, 684, 447, "追鬼次数已达上限", 500);
setTaskName(0);
return;
}
if (frequencyMap("qx", 1)) {
mFairy.onTap(0.8f, qx, "取消", 500);
}
} else {
frequencyInit("qx");
}
}
void content_03() throws Exception {
timeCount(7, 0);
gamePublicFuntion.task();
gamePublicFuntion.fhs(2);
if (timeMap("cb", cb_time, false)) {
singleTask.chubei();
gamePublicFuntion.close(3);
}
if (timeMap("seeRank", 600000, false)) {
gamePublicFuntion.close(3);
setTaskName(2);
return;
}
result = mFairy.findPic(997, 57, 1152, 523, "zg7.png");
mFairy.onTap(0.8f, result, "追鬼任务", 500);
if (frequencyMap("chat2", 1)) {
gamePublicFuntion.chat2();
}
if (gamePublicFuntion.fb()) {
err = 0;
Thread.sleep(2000);
frequencyInit("fb");
if (oneSecond()) {
gamePublicFuntion.auto();
}
mFairy.initMatTime();
} else {
if (frequencyMap("fb", 2)) {
oneSecond = 0;
gamePublicFuntion.auto1(2);
}
}
if (gamePublicFuntion.mainScene()) {
frequencyInit("chat2");
if (timeMap("jihe", 180000, true)) {
gamePublicFuntion.rank();
result = mFairy.findPic("jihe.png");
mFairy.onTap(0.72f, result, "集合", 500);
mFairy.onTap(0.72f, result, "集合", 500);
}
if (gamePublicFuntion.judgeStop(6, true, 0.85f)) {
FindResult task = mFairy.findPic(7, 127, 74, 396, "zg8.png");
if (task.sim > 0.7f) {
err = 0;
mFairy.onTap(0.7f, task, "taskClick", 500);
mFairy.initMatTime();
return;
}
taskSlide.slideRange(new int[]{3, 4, 5}, 2, 0);
}
}
}
};
}//带队捉鬼
private String ytdg_name = "dg1.png";
private int ytdg_num = 0;
private boolean ytdg_bool = false;
public void ytdg() throws Exception {
new TeamTask_Content(mFairy, "雁塔地宫") {
void create() throws Exception {
super.create();
activity_type = 1;
activity_name = "ytdg.png";
ytdg_name = "dg" + AtFairyConfig.getOption("ytdg") + ".png";
}
void content_02() throws Exception {
rank(new String[]{"ytdg2.png"/*,"j1.png"*/}, "ytdg1.png", null);
ytdg_num = 0;
ytdg_bool = false;
}
void cancel() throws Exception {
FindResult qx = gamePublicFuntion.qx();
if (qx.sim > 0.8f) {
result = mFairy.findPic("ytdg8.png");
if (result.sim > 0.8f) {
mFairy.onTap(811, 434, 850, 452, "人数不足>确定进入副本", 2000);
return;
}
if (frequencyMap("qx", 1)) {
mFairy.onTap(0.8f, qx, "取消", 500);
}
} else {
frequencyInit("qx");
}
}
void content_03() throws Exception {
if (timeCount(10, 0)) {
if (ytdg_bool) {
setTaskEnd();
return;
}
}
if (AtFairyConfig.getOption("fh").equals("1")) {
gamePublicFuntion.fhs(1);
}
result = mFairy.findPic(997, 57, 1152, 523, "ytdg3.png");
mFairy.onTap(0.8f, result, "参加活动", 500);
result = mFairy.findPic(970, 584, 1198, 681, "ytdg5.png");
mFairy.onTap(0.8f, result, "确定选择", 500);
result = mFairy.findPic("ytdg6.png");
if (result.sim > 0.8f) {
err = 0;
result = mFairy.findPic("ytdg9.png");
if (result.sim > 0.95f) {
mFairy.onTap(1153, 86, 1171, 104, "", 500);
setTaskEnd();
return;
}
result = mFairy.findPic(215, 88, 605, 647, ytdg_name);
if (result.sim > 0.8f) {
mFairy.onTap(0.8f, result, "选择怪物", 1000);
long l = mFairy.getColorNum(970, 584, 995, 605, 0.95f, 0, "108,101,90");
if (l > 100) {
setTaskEnd();
return;
}
mFairy.onTap(1002, 585, 1058, 597, "", 2000);
return;
}
ytdg_num++;
if (ytdg_num > 10) {
setTaskEnd();
return;
}
ytdgSlide.slideRange(ytdg_num, new int[]{3, 5, 7, 9}, 2, 0);
return;
} else {
if (gamePublicFuntion.mainScene()) {
if (timeMap("jihe", 180000, true)) {
gamePublicFuntion.rank();
result = mFairy.findPic("jihe.png");
mFairy.onTap(0.72f, result, "集合", 500);
mFairy.onTap(0.72f, result, "集合", 500);
}
if (gamePublicFuntion.judgeStop(6, true, 0.85f)) {
}
}
}
result = mFairy.findPic("ytdg7.png");
if (result.sim > 0.8f) {
err = 0;
if (frequencyMap("ytdg_end", 2)) {
mFairy.onTap(424, 434, 460, 449, "无法获得奖励,end!", 1000);
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
gamePublicFuntion.init(0);
if (gamePublicFuntion.fb() == false) {
Thread.sleep(2000);
break;
}
}
gamePublicFuntion.rank();
result = mFairy.findPic("jihe.png");
mFairy.onTap(0.72f, result, "集合", 500);
mFairy.onTap(0.72f, result, "集合", 500);
setTaskEnd();
return;
}
mFairy.onTap(0.8f, result, 797, 439, 868, 454, "继续下一层", 8000);
}
if (gamePublicFuntion.fb()) {
err = 0;
ytdg_bool = true;
long a = mFairy.getColorNum(329, 24, 516, 36, 0.95f, 0, "250,75,75");
if (a < 40) {
if (gamePublicFuntion.fhs() == false) {
if (frequencyMap("rand", 3)) {
LtLog.e(mFairy.getLineInfo("没有发现目标,滑动>>>"));
mFairy.ranSwipe(199, 608, 199, 373, 5000, (long) 500, 7);
}
}
} else {
frequencyInit("rand");
}
gamePublicFuntion.auto();
mFairy.initMatTime();
}
}
};
}//雁塔地宫
public void ptfb(final int i) throws Exception {
new TeamTask_Content(mFairy, "普通副本") {
void create() throws Exception {
super.create();
activity_type = 1;
activity_name = "ptfb.png";
}
void content_02() throws Exception {
switch (i) {
case 1:
rank(new String[]{"dxmo.png", "fdyy.png"}, "ptfb1.png", new String[]{"dxmo1.png", "fdyy1.png"});
break;
case 2:
rank(new String[]{"xhlz.png", "dhyf.png"}, "ptfb1.png", new String[]{"xhlz1.png", "dhyf1.png"});
break;
}
}
void cancel() throws Exception {
FindResult qx = gamePublicFuntion.qx();
if (qx.sim > 0.8f) {
result = mFairy.findPic(335, 245, 940, 404, "jia1.png");
if(result.sim>0.8f) {
mFairy.onTap(0.8f, result, 805, 435, 864, 449, "是否召回", 500);
return;
}
result = mFairy.findPic(316,263,966,401, "jia4.png");
if(result.sim>0.8f) {
mFairy.onTap(0.8f, result, 808,434,855,453, "确定进入", 500);
return;
}
if (frequencyMap("qx", 1)) {
mFairy.onTap(0.8f, qx, "取消", 500);
}
} else {
frequencyInit("qx");
}
}
void content_03() throws Exception {
timeCount(15, 0);
if (AtFairyConfig.getOption("fh").equals("1")) {
gamePublicFuntion.fhs(1);
}
result = mFairy.findPic("ptfb9.png");
mFairy.onTap(0.8f, result, "继续挂机", 500);
result = mFairy.findPic("ptfb17.png");
if(result.sim>0.8f) {
mFairy.onTap(0.8f, result, "继续开启", 500);
if(mapCount(0.8f,426,149,562,556,"jia3.png")){
setTaskName(2);
gamePublicFuntion.init(0);
return;
}
}
result = mFairy.findPic("ptfb18.png");
mFairy.onTap(0.8f, result, "继续", 500);
result = mFairy.findPic("ptfb13.png");
mFairy.onTap(0.8f, result, "跳过旁白", 500);
result = mFairy.findPic("ptfb14.png");
if (result.sim > 0.8f) {
for (int i = 0; i < 4; i++) {
result = modularLookup(1113, 204, 1191, 300, "shaizi.png");
if (result.sim > 0.8f) {
mFairy.onTap(0.8f, result, "骰子", 500);
modularLookup++;
}
}
modularLookup = 0;
mFairy.onTap(1182, 65, 1202, 83, "", 1000);
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
result = mFairy.findPic("ptfb18.png");
mFairy.onTap(0.8f, result, "继续", 500);
gamePublicFuntion.init(0);
if (gamePublicFuntion.fb() == false) {
Thread.sleep(2000);
break;
}
}
gamePublicFuntion.rank();
result = mFairy.findPic("jihe.png");
mFairy.onTap(0.72f, result, "集合", 500);
mFairy.onTap(0.72f, result, "集合", 500);
setTaskEnd();
return;
}
result = mFairy.findPic("ptfb11.png");
if (result.sim > 0.8f) {
Thread.sleep(5000);
mFairy.onTap(600, 435, 668, 448, "全部战败", 500);
mFairy.onTap(424, 434, 460, 449, "无法获得奖励,end!", 1000);
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
gamePublicFuntion.init(0);
if (gamePublicFuntion.fb() == false) {
Thread.sleep(2000);
break;
}
}
gamePublicFuntion.rank();
result = mFairy.findPic("jihe.png");
mFairy.onTap(0.72f, result, "集合", 500);
mFairy.onTap(0.72f, result, "集合", 500);
setTaskEnd();
return;
}
gamePublicFuntion.errClick();
result = mFairy.findPic("nn1.png");
if (result.sim > 0.8f) {
mFairy.onTap(0.8f, result, "跳过剧情", 800);
mFairy.onTap(412, 435, 483, 450, "", 1000);
err = 0;
}
result = mFairy.findPic("nn10.png");
mFairy.onTap(0.8f, result, "跳过动画", 1000);
if (gamePublicFuntion.fb()) {
err = 0;
gamePublicFuntion.errClick = 0;
gamePublicFuntion.auto();
result = mFairy.findPic(592, 73, 737, 387, "ptfb10.png");
if (result.sim > 0.8f) {
mFairy.ranSwipe(144, 595, 295, 595, 500, (long) 500, 4);
}
result = mFairy.findPic("shou.png");
if (result.sim > 0.8f) {
mFairy.ranSwipe(197, 608, 197, 582, 800, 200);
mFairy.onTap(0.8f, result, "手", 2000);
mFairy.initMatTime();
return;
}
} else {
result = mFairy.findPic(997, 57, 1152, 523, "ptfb2.png");
if (result.sim > 0.8f) {
mFairy.onTap(0.8f, result, "选择副本", 1500);
gamePublicFuntion.errClick = 0;
}
result = mFairy.findPic("ptfb3.png");
if (result.sim > 0.8f) {
gamePublicFuntion.errClick = 0;
err = 0;
FindResult fb;
result = mFairy.findPic("ptfb6.png");
mFairy.onTap(0.8f, result, "普通副本", 1000);
switch (i) {
case 1:
fb = mFairy.findPic(170, 117, 1119, 190, new String[]{"dxmo2.png", "fdyy2.png"});
if (fb.sim > 0.75f) {
result = mFairy.findPic(fb.x - 10, fb.y + 202, fb.x + 156, fb.y + 342, "ptfb15.png");
if (result.sim > 0.8f) {
mFairy.onTap(1134, 81, 1156, 97, "", 500);
setTaskEnd();
return;
}
mFairy.onTap(0.8f, fb, fb.x, fb.y + 200, fb.x + 50, fb.y + 250, "地下魔祸", 3000);
}
break;
case 2:
fb = mFairy.findPic(170, 117, 1119, 190, new String[]{"xhlz2.png", "dhyf2.png"});
if (fb.sim > 0.75f) {
result = mFairy.findPic(fb.x - 10, fb.y + 202, fb.x + 156, fb.y + 342, "ptfb15.png");
if (result.sim > 0.8f) {
mFairy.onTap(1134, 81, 1156, 97, "", 500);
setTaskEnd();
return;
}
mFairy.onTap(0.8f, fb, fb.x, fb.y + 200, fb.x + 50, fb.y + 250, "西海龙战", 3000);
}
break;
}
if (frequencyMap("ran_fb", 3)) {
mFairy.ranSwipe(951, 368, 433, 368, 500, (long) 2000, 3);
return;
}
result = mFairy.findPic("ptfb4.png");
if (result.sim > 0.8f) {
result = mFairy.findPic("ptfb7.png");
if (result.sim > 0.8f) {
mFairy.onTap(1135, 77, 1155, 97, "", 500);
setTaskEnd();
return;
}
mFairy.onTap(962, 603, 1002, 620, "开启", 500);
if(mapCount(0.8f,426,149,562,556,"jia3.png")){
setTaskName(2);
gamePublicFuntion.init(0);
return;
}
}
}
result = mFairy.findPic(535, 2, 704, 42, "ptfb8.png");
if (result.sim > 0.8f) {
err = 0;
gamePublicFuntion.errClick = 0;
}
if (gamePublicFuntion.mainScene()) {
gamePublicFuntion.errClick = 0;
if (timeMap("jihe", 300000, true)) {
gamePublicFuntion.rank();
result = mFairy.findPic("jihe.png");
mFairy.onTap(0.72f, result, "集合", 500);
}
gamePublicFuntion.judgeStop(10, true, 0.85f);
}
}
}
};
}//普通副本 ....未修改
public void knfb(final int i) throws Exception {
new TeamTask_Content(mFairy, "困难副本") {
void create() throws Exception {
super.create();
activity_type = 1;
activity_name = "knfb.png";
}
void content_02() throws Exception {
switch (i) {
case 1:
rank(new String[]{"dxmo.png"}, "knfb1.png", new String[]{"dxmo1.png"});
break;
case 2:
rank(new String[]{"fdyy.png"}, "knfb1.png", new String[]{"fdyy1.png"});
break;
case 3:
rank(new String[]{"xhlz.png"}, "knfb1.png", new String[]{"xhlz1.png"});
break;
case 4:
rank(new String[]{"dhyf.png"}, "knfb1.png", new String[]{"dhyf1.png"});
break;
}
}
void cancel() throws Exception {
FindResult qx = gamePublicFuntion.qx();
if (qx.sim > 0.8f) {
result = mFairy.findPic(335, 245, 940, 404, "jia1.png");
mFairy.onTap(0.8f, result, 805, 435, 864, 449, "是否召回", 500);
if (frequencyMap("qx", 1)) {
mFairy.onTap(0.8f, qx, "取消", 500);
}
} else {
frequencyInit("qx");
}
}
void content_03() throws Exception {
timeCount(15, 0);
if (AtFairyConfig.getOption("fh").equals("1")) {
gamePublicFuntion.fhs(1);
}
result = mFairy.findPic("ptfb9.png");
mFairy.onTap(0.8f, result, "继续挂机", 500);
result = mFairy.findPic("ptfb17.png");
mFairy.onTap(0.8f, result, "继续开启", 500);
result = mFairy.findPic("ptfb13.png");
mFairy.onTap(0.8f, result, "跳过旁白", 500);
result = mFairy.findPic("ptfb14.png");
if (result.sim > 0.8f) {
for (int i = 0; i < 4; i++) {
result = modularLookup(1113, 204, 1191, 300, "shaizi.png");
if (result.sim > 0.8f) {
mFairy.onTap(0.8f, result, "骰子", 500);
modularLookup++;
}
}
modularLookup = 0;
mFairy.onTap(1182, 65, 1202, 83, "", 1000);
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
gamePublicFuntion.init(0);
if (gamePublicFuntion.fb() == false) {
Thread.sleep(2000);
break;
}
}
gamePublicFuntion.rank();
result = mFairy.findPic("jihe.png");
mFairy.onTap(0.72f, result, "集合", 500);
mFairy.onTap(0.72f, result, "集合", 500);
setTaskEnd();
return;
}
result = mFairy.findPic("ptfb11.png");
if (result.sim > 0.8f) {
Thread.sleep(5000);
mFairy.onTap(600, 435, 668, 448, "全部战败", 500);
mFairy.onTap(424, 434, 460, 449, "无法获得奖励,end!", 1000);
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
gamePublicFuntion.init(0);
if (gamePublicFuntion.fb() == false) {
Thread.sleep(2000);
break;
}
}
gamePublicFuntion.rank();
result = mFairy.findPic("jihe.png");
mFairy.onTap(0.72f, result, "集合", 500);
mFairy.onTap(0.72f, result, "集合", 500);
setTaskEnd();
return;
}
if (gamePublicFuntion.fb()) {
err = 0;
gamePublicFuntion.auto();
result = mFairy.findPic(592, 73, 737, 387, "ptfb10.png");
if (result.sim > 0.8f) {
mFairy.ranSwipe(144, 595, 295, 595, 500, (long) 500, 4);
}
result = mFairy.findPic("shou.png");
if (result.sim > 0.8f) {
mFairy.ranSwipe(197, 608, 197, 582, 800, 200);
mFairy.onTap(0.8f, result, "手", 2000);
mFairy.initMatTime();
return;
}
} else {
result = mFairy.findPic(997, 57, 1152, 523, "ptfb2.png");
mFairy.onTap(0.8f, result, "选择副本", 500);
result = mFairy.findPic("ptfb3.png");
if (result.sim > 0.8f) {
err = 0;
FindResult fb = null;
result = mFairy.findPic("knfb2.png");
mFairy.onTap(0.8f, result, "困难副本", 1000);
switch (i) {
case 1:
fb = mFairy.findPic(170, 117, 1119, 190, "dxmo2.png");
if (fb.sim > 0.8f) {
result = mFairy.findPic(fb.x - 10, fb.y + 202, fb.x + 156, fb.y + 342, "ptfb15.png");
if (result.sim > 0.8f) {
mFairy.onTap(1134, 81, 1156, 97, "", 500);
setTaskEnd();
return;
}
mFairy.onTap(0.8f, fb, fb.x, fb.y + 200, fb.x + 50, fb.y + 250, "地下魔祸", 1500);
}
break;
case 2:
fb = mFairy.findPic(170, 117, 1119, 190, "fdyy2.png");
if (fb.sim > 0.8f) {
result = mFairy.findPic(fb.x - 10, fb.y + 202, fb.x + 156, fb.y + 342, "ptfb15.png");
if (result.sim > 0.8f) {
mFairy.onTap(1134, 81, 1156, 97, "", 500);
setTaskEnd();
return;
}
mFairy.onTap(0.8f, fb, fb.x, fb.y + 200, fb.x + 50, fb.y + 250, "分定阴阳", 1500);
}
break;
case 3:
fb = mFairy.findPic(170, 117, 1119, 190, "xhlz2.png");
if (fb.sim > 0.8f) {
result = mFairy.findPic(fb.x - 10, fb.y + 202, fb.x + 156, fb.y + 342, "ptfb15.png");
if (result.sim > 0.8f) {
mFairy.onTap(1134, 81, 1156, 97, "", 500);
setTaskEnd();
return;
}
mFairy.onTap(0.8f, fb, fb.x, fb.y + 200, fb.x + 50, fb.y + 250, "西海龙战", 1500);
}
break;
case 4:
fb = mFairy.findPic(170, 117, 1119, 190, "dhyf2.png");
if (fb.sim > 0.8f) {
result = mFairy.findPic(fb.x - 10, fb.y + 202, fb.x + 156, fb.y + 342, "ptfb15.png");
if (result.sim > 0.8f) {
mFairy.onTap(1134, 81, 1156, 97, "", 500);
setTaskEnd();
return;
}
mFairy.onTap(0.8f, fb, fb.x, fb.y + 200, fb.x + 50, fb.y + 250, "东海妖风", 1500);
}
break;
}
if (frequencyMap("ran_fb", 3)) {
mFairy.ranSwipe(951, 368, 433, 368, 500, (long) 1000, 3);
return;
}
result = mFairy.findPic("ptfb4.png");
if (result.sim > 0.8f) {
result = mFairy.findPic("ptfb7.png");
if (result.sim > 0.8f) {
mFairy.onTap(1135, 77, 1155, 97, "", 500);
setTaskEnd();
return;
}
mFairy.onTap(962, 603, 1002, 620, "开启", 2000);
}
}
result = mFairy.findPic(535, 2, 704, 42, "ptfb8.png");
if (result.sim > 0.8f) {
err = 0;
}
if (gamePublicFuntion.mainScene()) {
if (timeMap("jihe", 300000, true)) {
gamePublicFuntion.rank();
result = mFairy.findPic("jihe.png");
mFairy.onTap(0.72f, result, "集合", 500);
}
gamePublicFuntion.judgeStop(10, true, 0.85f);
}
}
}
};
}//困难副本....未修改
public void yb() throws Exception {
new TeamTask_Content(mFairy, "组队运镖") {
void create() throws Exception {
super.create();
activity_type = 2;
activity_name = "yb.png";
}
void content_02() throws Exception {
rank(new String[]{"yb7.png"}, "sf.png", new String[]{"yb6.png"});
}
void cancel() throws Exception {
FindResult qx = gamePublicFuntion.qx();
if (qx.sim > 0.8f) {
result = mFairy.findPic("yb2.png");
mFairy.onTap(0.8f, result, 814, 436, 860, 450, "离镖车太远 - 同意", 500);
result = mFairy.findPic(335, 245, 940, 404, "jia1.png");
mFairy.onTap(0.8f, result, 805, 435, 864, 449, "是否召回", 500);
if (frequencyMap("qx", 1)) {
mFairy.onTap(0.8f, qx, "取消", 500);
}
} else {
frequencyInit("qx");
}
}
void content_03() throws Exception {
timeCount(5, 0);
result = mFairy.findPic("chat2.png");
if (result.sim > 0.8f) {
err = 0;
}
result = mFairy.findPic("yb11.png");
if(result.sim>0.8f){
mFairy.onTap(0.8f, result, "活跃不足", 500);
setTaskEnd();
return;
}
result = mFairy.findPic("yb10.png");
if (result.sim > 0.8f) {
mFairy.onTap(1084, 591, 1119, 623, "", 500);
setTaskName(2);
return;
} else {
result = mFairy.findPic(966, 197, 1186, 600, "yb3.png");
if (result.sim > 0.8f) {
mFairy.onTap(0.8f, result, "确定前往下一镖", 2000);
return;
}
switch (AtFairyConfig.getOption("zdyb")) {
case "1":
result = mFairy.findPic(966, 197, 1186, 600, "yb8.png");
if (result.sim > 0.8f) {
frequencyInit("chat2");
mFairy.onTap(0.8f, result, "风雨镖", 500);
return;
}
break;
case "2":
result = mFairy.findPic(966, 197, 1186, 600, "yb9.png");
if (result.sim > 0.8f) {
frequencyInit("chat2");
mFairy.onTap(0.8f, result, "天险镖", 500);
return;
}
break;
}
if (frequencyMap("chat2", 2)) {
gamePublicFuntion.chat2();
}
}
result = mFairy.findPic("yb4.png");
if (result.sim > 0.8f) {
Thread.sleep(2000);
err = 0;
}
if (gamePublicFuntion.fb()) {
gamePublicFuntion.auto();
mFairy.initMatTime();
}
gamePublicFuntion.task();
if (gamePublicFuntion.mainScene()) {
frequencyInit("chat2");
if (timeMap("jihe", 180000, true)) {
gamePublicFuntion.rank();
result = mFairy.findPic("jihe.png");
mFairy.onTap(0.72f, result, "集合", 500);
mFairy.onTap(0.72f, result, "集合", 500);
}
if (gamePublicFuntion.judgeStop(6, true, 0.85f)) {
FindResult task = mFairy.findPic(17, 117, 83, 398, "yb5.png");
if (task.sim > 0.7f) {
mFairy.onTap(0.7f, task, "taskClick", 2000);
mFairy.initMatTime();
return;
}
taskSlide.slideRange(new int[]{2, 4}, 2, 0);
}
}
}
};
}//组队运镖
/**
* 限时任务
*/
public void hgfz() throws Exception {
new TeamTask_Content(mFairy, "皇宫飞贼") {
void create() throws Exception {
super.create();
activity_type = 3;
activity_name = "hgfz.png";
}
void content_02() throws Exception {
rank(new String[]{"hgfz2.png"}, "hgfz1.png", null);
}
void cancel() throws Exception {
FindResult qx = gamePublicFuntion.qx();
if (qx.sim > 0.8f) {
result = mFairy.findPic(335, 245, 940, 404, "jia1.png");
mFairy.onTap(0.8f, result, 805, 435, 864, 449, "是否召回", 500);
if (frequencyMap("qx", 1)) {
mFairy.onTap(0.8f, qx, "取消", 500);
}
} else {
frequencyInit("qx");
}
}
void content_03() throws Exception {
timeCount(6, 0);
gamePublicFuntion.fhs(2);
gamePublicFuntion.task();
result = mFairy.findPic(943, 27, 1219, 537, new String[]{"hgfz3.png", "hgfz4.png"});
mFairy.onTap(0.8f, result, "让我来!", 500);
result = mFairy.findPic("hgfz5.png");
if (result.sim > 0.8f) {
err = 0;
result = mFairy.findPic(724, 115, 1117, 171, "hgfz6.png");
if (result.sim > 0.85f) {
mFairy.onTap(result.x + 1, result.y - 25, result.x + 2, result.y - 23, "抓贼", 1000);
for (int i = 0; i < 3; i++) {
result = mFairy.findPic(208, 109, 1125, 630, "hgfz7.png");
mFairy.onTap(0.8f, result, "选择贼", 500);
}
gamePublicFuntion.close(3);
} else {
mFairy.onTap(754, 106, 768, 123, "", 500);
}
if (frequencyMap("fzError", 8)) {
gamePublicFuntion.close(3);
return;
}
} else {
frequencyInit("fzError");
}
if (gamePublicFuntion.fb()) {
err = 0;
if (gamePublicFuntion.lv() == false) {
gamePublicFuntion.auto();
Thread.sleep(3000);
}
}
if (gamePublicFuntion.mainScene()) {
if (timeMap("jihe", 180000, true)) {
gamePublicFuntion.rank();
result = mFairy.findPic("jihe.png");
mFairy.onTap(0.72f, result, "集合", 500);
mFairy.onTap(0.72f, result, "集合", 500);
}
if (gamePublicFuntion.judgeStop(5, true, 0.85f)) {
result = mFairy.findPic(5, 119, 69, 426, "hgfz8.png");
if (result.sim > 0.7f) {
err = 0;
mFairy.onTap(0.7f, result, "皇宫飞贼", 3000);
mFairy.initMatTime();
return;
}
taskSlide.slideRange(new int[]{3, 4, 5}, 2, 0);
}
}
}
};
}//皇宫飞贼
public void qzsm() throws Exception {
new TeamTask_Content(mFairy, "勤政事民") {
void create() throws Exception {
super.create();
activity_type = 3;
activity_name = "qzsm.png";
}
void content_02() throws Exception {
rank(new String[]{"qzsm2.png"}, "jjzz1.png", new String[]{"qzsm1.png"});
}
void cancel() throws Exception {
FindResult qx = gamePublicFuntion.qx();
if (qx.sim > 0.8f) {
result = mFairy.findPic(335, 245, 940, 404, "jia1.png");
mFairy.onTap(0.8f, result, 805, 435, 864, 449, "是否召回", 500);
if (frequencyMap("qx", 1)) {
mFairy.onTap(0.8f, qx, "取消", 500);
}
} else {
frequencyInit("qx");
}
}
void content_03() throws Exception {
timeCount(10, 0);
gamePublicFuntion.fhs(2);
gamePublicFuntion.task();
result = mFairy.findPic("qzsm3.png");
if (result.sim > 0.8f) {
err = 0;
result = mFairy.findPic("qzsm4.png");
if (result.sim > 0.8f) {
mFairy.onTap(1214,48,1236,72,"",500);
return;
}
mFairy.onTap(597,591,674,607,"",200);
mFairy.onTap(280,591,350,610,"",300);
if(mapCount(0.8f,379,136,914,480,"qzsm6.png")){
singleTask.li_rank();
setTaskName(0);
return;
}
}else{
result = mFairy.findPic(new String[]{"chat1.png", "nn11.png"});
if (result.sim > 0.8f) {
err = 0;
mFairy.onTap(1053, 458, 1111, 475, "chat", 500);
return;
}
}
if(frequencyMap("chat",3)){
gamePublicFuntion.chat2();
}
if (gamePublicFuntion.fb()) {
err = 0;
if (gamePublicFuntion.lv() == false) {
gamePublicFuntion.auto();
Thread.sleep(3000);
}
}
if (gamePublicFuntion.mainScene()) {
frequencyInit("chat2");
if (timeMap("jihe", 180000, true)) {
gamePublicFuntion.rank();
result = mFairy.findPic("jihe.png");
mFairy.onTap(0.72f, result, "集合", 500);
mFairy.onTap(0.72f, result, "集合", 500);
}
if (gamePublicFuntion.judgeStop(5, true, 0.85f)) {
result = mFairy.findPic(5, 119, 69, 426, "qzsm5.png");
if (result.sim > 0.7f) {
err = 0;
mFairy.onTap(0.7f, result, "官职", 3000);
mFairy.initMatTime();
return;
}
taskSlide.slideRange(new int[]{3, 4, 5}, 2, 0);
}
}
}
};
}//勤政事民
private boolean xycm = false;
public void xycm() throws Exception {
new TeamTask_Content(mFairy, "降妖除魔") {
void create() throws Exception {
super.create();
activity_type = 3;
activity_name = "xycm.png";
xycm = false;
}
void content_02() throws Exception {
if (xycm) {
xycm = false;
setTaskName(3);
err = 2;
return;
}
rank(new String[]{"xycm3.png"}, "xycm1.png", new String[]{"xycm2.png"});
}
void cancel() throws Exception {
FindResult qx = gamePublicFuntion.qx();
if (qx.sim > 0.8f) {
result = mFairy.findPic(335, 245, 940, 404, "jia1.png");
mFairy.onTap(0.8f, result, 805, 435, 864, 449, "是否召回", 500);
if (frequencyMap("qx", 1)) {
mFairy.onTap(0.8f, qx, "取消", 500);
}
} else {
frequencyInit("qx");
}
}
void content_03() throws Exception {
timeCount(10, 0);
gamePublicFuntion.fhs(2);
gamePublicFuntion.task();
result = mFairy.findPic(943, 27, 1219, 537, "xycm4.png");
if (result.sim > 0.8f) {
mFairy.onTap(0.8f, result, "降妖除魔", 500);
err = 0;
}
if (gamePublicFuntion.fb()) {
err = 0;
xycm = true;
Thread.sleep(2000);
frequencyInit("fb");
if (oneSecond()) {
gamePublicFuntion.auto();
}
mFairy.initMatTime();
} else {
if (frequencyMap("fb", 2)) {
oneSecond = 0;
gamePublicFuntion.auto1(2);
if (xycm) {
setTaskName(1);
}
return;
}
}
if (gamePublicFuntion.mainScene()) {
if (timeMap("jihe", 180000, true)) {
gamePublicFuntion.rank();
result = mFairy.findPic("jihe.png");
mFairy.onTap(0.72f, result, "集合", 500);
mFairy.onTap(0.72f, result, "集合", 500);
}
if (gamePublicFuntion.judgeStop(5, true, 0.85f)) {
result = mFairy.findPic(3, 122, 108, 418, "xycm5.png");
if (result.sim > 0.7f) {
err = 0;
mFairy.onTap(0.7f, result, "降妖除魔", 3000);
mFairy.initMatTime();
return;
}
taskSlide.slideRange(new int[]{4, 6, 8}, 2, 0);
}
}
}
};
gamePublicFuntion.init(0);
mFairy.ranSwipe(212, 508, 228, 508, 500, (long) 500, 1);
}//降妖除魔....未修改
class GenContent extends TaskContent {
public GenContent(AtFairyImpl mFairy, String name) throws Exception {
super(mFairy, name);
}
void init() throws Exception {
gamePublicFuntion.init(1);
setTaskName(1);
oneSecond = 0;
bool_rank = false;
}
boolean activity_end(FindResult act) throws Exception {
return false;
}
void content_01() throws Exception {
if (timeCount(10, 0)) {
if (frequencyMap("actError", 1)) {
setTaskEnd();
return;
}
}
result = mFairy.findPic("activity.png");
if (result.sim > 0.75f) {
GamePublicFuntion.activity_bool = false;
mFairy.onTap(0.75f, result, "活动按钮", 800);
}
result = mFairy.findPic("activity1.png");
if (result.sim > 0.8f) {
if (oneSecond()) {
gamePublicFuntion.activity_type(activity_type);
result = mFairy.findPic("activity3.png");
if (result.sim > 0.8f) {
for (int i = 0; i < 5; i++) {
result = mFairy.findPic(617, 55, 660, 575, "activity2.png");
mFairy.onTap(0.75f, result, result.x + 30, result.y + 0, result.x + 40, result.y + 1, "领取活跃", 500);
}
}
}
FindResult act = mFairy.findPic(818, 35, 1009, 559, activity_name);
if (act.sim > 0.85f) {
if (activity_end(act)) {
oneSecond = 0;
return;
}
result = mFairy.findPic(act.x + 223, act.y - 30, act.x + 350, act.y + 71, "wan.png");
if (result.sim > 0.8f) {
setTaskEnd();
return;
}
result = mFairy.findPic(act.x + 223, act.y - 10, act.x + 354, act.y + 71, "qian.png");
if (result.sim > 0.8f) {
mFairy.onTap(1221, 37, 1247, 57, "", 500);
oneSecond = 0;
frequencyInit("actError");
setTaskName(2);
return;
}
}
if (GamePublicFuntion.activity_bool == false) {
activitySlide.slideRange(new int[]{3, 5, 6, 7}, 2);
} else {
activitySlide.slideRange(new int[]{3, 5, 6, 7, 8}, 2, 0);
}
}
}//活动
void inOperation() throws Exception {
gamePublicFuntion.lv();
gamePublicFuntion.skipScene();
gamePublicFuntion.chat();
gamePublicFuntion.deng();
gamePublicFuntion.fhs(2);
gamePublicFuntion.rank();
cancel();
use();
result = mFairy.findPic("ling3.png");
mFairy.onTap(0.8f, result, 1213, 52, 1232, 70, "", 1000);
result = mFairy.findPic(1045, 3, 1265, 50, "nn2.png");
mFairy.onTap(0.85f, result, "跳过教学", 500);
result = mFairy.findPic(962, 562, 1077, 636, "map.png");
mFairy.onTap(0.75f, result, 1123, 67, 1147, 86, "", 500);
result = mFairy.findPic("rank3.png");
mFairy.onTap(0.85f, result, "跟随", 500);
result = mFairy.findPic(1000, 588, 1198, 702, "gen2.png");
mFairy.onTap(0.8f, result, "同意进入副本1", 500);
result = mFairy.findPic(774, 108, 941, 261, "gen3.png");
mFairy.onTap(0.8f, result, "同意进入副本2", 500);
result = mFairy.findPic(577, 275, 683, 649, "ok.png");
mFairy.onTap(0.8f, result, "ok", 500);
if (AtFairyConfig.getOption("jj").equals("1")) {
if (gamePublicFuntion.fb()) {
if (timeMap("jj", 180000, true)) {
mFairy.onTap(1032, 433, 1054, 447, "开始释放绝技", 1000);
mFairy.onTap(1033, 332, 1058, 350, "", 500);
mFairy.onTap(1216, 641, 1234, 662, "", 500);
gamePublicFuntion.close(3);
}
}
}
}
void cancel() throws Exception {
result = gamePublicFuntion.qx();
mFairy.onTap(0.8f, result, "取消", 500);
}
void use() throws Exception {
gamePublicFuntion.use();
}//使用
void rank(String[] img, String mb_str1, String[] mb_str2) throws Exception {
timeCount(10, 0);
if (bool_rank == false) {
frequencyInit("errRank_count");
result = mFairy.findPic("rank1.png");
if (result.sim > 0.85f) {
err = 0;
LtLog.e(mFairy.getLineInfo("发现创建队伍 >>> 队伍状态判断成功"));
bool_rank = true;
bool_genrank_state = false;
return;
}
gamePublicFuntion.rank();
gamePublicFuntion.close(1);
if (gamePublicFuntion.mainScene()) {
result = mFairy.findPic(13, 427, 52, 470, "rank8.png");
if (result.sim > 0.8f) {
err = 0;
result = mFairy.findPic(new String[]{"rank2.png", "rank3.png"});
if (result.sim > 0.85f) {
LtLog.e(mFairy.getLineInfo("发现跟随>>>队伍状态判断成功"));
frequencyInit("genRank");
bool_rank = true;
bool_genrank_state = true;
return;
} else {
if (frequencyMap("genRank", 2)) {
LtLog.e(mFairy.getLineInfo("发现是队长>>>队伍状态判断成功"));
bool_rank = true;
bool_genrank_state = false;
return;
}
}
}
result = mFairy.findPic(1, 124, 40, 178, "rank23.png");
if (result.sim > 0.75f) {
err = 0;
if (timeMap("ppRank", 300000, false)) {
LtLog.e(mFairy.getLineInfo("匹配超时>>>"));
bool_rank = true;
bool_genrank_state = true;
return;
}
}
return;
}
gamePublicFuntion.close(1);
} else {
frequencyInit("genRank");
result = mFairy.findPic("rank7.png");
if (result.sim > 0.8f) {
frequencyInit("errRank_count");
if (frequencyMap("mbError", 7)) {
mFairy.onTap(1092, 99, 1115, 121, "", 500);
return;
}
result = mFairy.findPic(181, 177, 445, 632, mb_str1);
if (result.sim > 0.85f) {
result = mFairy.findPic(result.x + 50, result.y - 20, result.x + 200, result.y + 43, "mb1.png");
if (result.sim > 0.85f) {
mFairy.onTap(0.85f, result, "点击 str1", 1000);
err = 4;
if (mb_str2 == null) {
err = 0;
for (int i = 0; i < 3; i++) {
result = mFairy.findPic(957, 175, 1083, 560, "rank22.png");
mFairy.onTap(0.9f, result, "申请", 500);
}
result = mFairy.findPic("rank21.png");
mFairy.onTap(0.9f, result, "开始匹配", 3000);
gamePublicFuntion.close(3);
bool_rank = false;
return;
}
}
}
if (mb_str2 != null) {
result = mFairy.findPic(181, 177, 445, 632, mb_str2);
if (result.sim > 0.8f) {
mFairy.onTap(0.8f, result, "str2", 1000);
err = 0;
for (int i = 0; i < 3; i++) {
result = mFairy.findPic(957, 175, 1083, 560, "rank22.png");
mFairy.onTap(0.9f, result, "申请", 500);
}
result = mFairy.findPic("rank21.png");
mFairy.onTap(0.9f, result, "开始匹配", 3000);
gamePublicFuntion.close(3);
bool_rank = false;
return;
}
}
rankmbSlide.slideRange(new int[]{3, 4, 5, 6}, 2, 0);
return;
} else {
frequencyInit("mbError");
}
result = mFairy.findPic(1,1,85,214,"rankScene.png");
LtLog.e(mFairy.getLineInfo("组队场景 sim:"+result.sim));
if (result.sim > 0.85f) {
err = 0;
result = mFairy.findPic("yao1.png");
mFairy.onTap(0.85f, result, 1180, 66, 1200, 82, "批准", 500);
result = mFairy.findPic(617,519,1256,681,"rank6.png");
if (result.sim > 0.85f) {
mFairy.onTap(0.85f, result, "便捷组队", 500);
bool_genrank_state = true;
return;
}
if (bool_genrank_state == false) {
result = mFairy.findPic("rank5.png");
mFairy.onTap(0.85f, result, "退出队伍", 500);
return;
}
if (mFairy.findPic(190,66,517,165,img).sim > 0.8f || mFairy.findPic("rank24.png").sim > 0.8f) {
mFairy.onTap(1214, 36, 1231, 52, "", 500);
setTaskName(3);
return;
}
if (frequencyMap("errRank_count", 10)) {
gamePublicFuntion.close(3);
bool_rank = false;
return;
}
return;
}
gamePublicFuntion.clickRank();
}
}
boolean exceptional_case() throws Exception {
return false;
}
void content_03() throws Exception {
timeCount(20, 0);
Thread.sleep(1000);
gamePublicFuntion.close(1);
result = mFairy.findPic("ptfb9.png");
mFairy.onTap(0.8f, result, "继续挂机", 500);
result = mFairy.findPic("ptfb18.png");
mFairy.onTap(0.8f, result, "继续", 500);
result = mFairy.findPic("ptfb13.png");
mFairy.onTap(0.8f, result, "跳过旁白", 500);
result = mFairy.findPic(535, 2, 704, 42, "ptfb8.png");
if (result.sim > 0.8f) {
err = 0;
}
result = mFairy.findPic("rank1.png");
if (result.sim > 0.85f) {
LtLog.e(mFairy.getLineInfo("发现创建队伍 >>> 跳转"));
gamePublicFuntion.init(1);
setTaskName(1);
bool_rank = true;
bool_genrank_state = false;
return;
}
if (gamePublicFuntion.mainScene()) {
result = mFairy.findPic(13, 427, 52, 470, "rank8.png");
if (result.sim > 0.8f) {
result = mFairy.findPic(new String[]{"rank2.png", "rank3.png"});
if (result.sim > 0.85f) {
frequencyInit("genRank");
} else {
if (frequencyMap("genRank", 3)) {
LtLog.e(mFairy.getLineInfo("跟随长时间未发现 >>> 跳转"));
gamePublicFuntion.init(1);
setTaskName(1);
bool_rank = true;
bool_genrank_state = false;
return;
}
}
}
if (gamePublicFuntion.fb()) {
err = 0;
if (gamePublicFuntion.judgeBattle()) {
mFairy.initMatTime();
}
}
result = mFairy.findPic("shengddian.png");
if (result.sim > 0.75f) {
Thread.sleep(2000);
return;
} else {
if (gamePublicFuntion.judgeStop(480, false, 0.85f)) {
LtLog.e(mFairy.getLineInfo("长时间发呆 >>> 跳转"));
mFairy.initMatTime();
if (exceptional_case()) {
return;
}
gamePublicFuntion.init(1);
setTaskName(1);
bool_rank = true;
bool_genrank_state = false;
return;
}
}
}
}
}
public void gen_ptfb(final int i) throws Exception {
new GenContent(mFairy, "跟队-普通副本") {
void create() throws Exception {
super.create();
activity_type = 1;
activity_name = "ptfb.png";
}
void content_02() throws Exception {
switch (i) {
case 1:
rank(new String[]{"dxmo.png", "fdyy.png"}, "ptfb16.png", new String[]{"dxmo3.png", "fdyy3.png"});
break;
case 2:
rank(new String[]{"xhlz.png", "dhyf.png"}, "ptfb16.png", new String[]{"xhlz3.png", "dhyf3.png"});
break;
}
}
void content_03() throws Exception {
super.content_03();
result = mFairy.findPic("ptfb14.png");
if (result.sim > 0.8f) {
for (int i = 0; i < 4; i++) {
result = modularLookup(1113, 204, 1191, 300, "shaizi.png");
if (result.sim > 0.8f) {
mFairy.onTap(0.8f, result, "骰子", 500);
modularLookup++;
}
}
modularLookup = 0;
mFairy.onTap(1182, 65, 1202, 83, "", 1000);
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
gamePublicFuntion.init(0);
if (gamePublicFuntion.fb() == false) {
Thread.sleep(2000);
break;
}
}
setTaskEnd();
return;
}
}
};
}//跟队-普通副本....未修改
public void gen_knfb(final int i) throws Exception {
new GenContent(mFairy, "跟队-困难副本") {
void create() throws Exception {
super.create();
activity_type = 1;
activity_name = "knfb.png";
}
void content_02() throws Exception {
switch (i) {
case 1:
rank(new String[]{"dxmo.png"}, "knfb3.png", new String[]{"dxmo3.png"});
break;
case 2:
rank(new String[]{"fdyy.png"}, "knfb3.png", new String[]{"fdyy3.png"});
break;
case 3:
rank(new String[]{"xhlz.png"}, "knfb3.png", new String[]{"xhlz3.png"});
break;
case 4:
rank(new String[]{"dhyf.png"}, "knfb3.png", new String[]{"dhyf3.png"});
break;
}
}
void content_03() throws Exception {
super.content_03();
result = mFairy.findPic("ptfb14.png");
if (result.sim > 0.8f) {
for (int i = 0; i < 4; i++) {
result = modularLookup(1113, 204, 1191, 300, "shaizi.png");
if (result.sim > 0.8f) {
mFairy.onTap(0.8f, result, "骰子", 500);
modularLookup++;
}
}
modularLookup = 0;
mFairy.onTap(1182, 65, 1202, 83, "", 1000);
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
gamePublicFuntion.init(0);
if (gamePublicFuntion.fb() == false) {
Thread.sleep(2000);
break;
}
}
setTaskEnd();
return;
}
}
};
}//跟队-困难副本....未修改
public void gen_zg() throws Exception {
new GenContent(mFairy, "跟队-捉鬼") {
void init() throws Exception {
gamePublicFuntion.init(1);
if (zg) {
setTaskName(2);
} else {
setTaskName(1);
}
oneSecond = 0;
bool_rank = false;
}
void create() throws Exception {
super.create();
activity_type = 1;
activity_name = "zg.png";
if (AtFairyConfig.getOption("zg").equals("2")) {
zg = true;
} else {
zg = false;
}
long i = getTimeStamp(AtFairyConfig.getOption("cb"));
if (i != -1) {
cb_time = i;
}
}
boolean activity_end(FindResult act) throws Exception {
if (zg == false) {
result = mFairy.findPic(act.x + 80, act.y + 2, act.x + 180, act.y + 66,
new String[]{"zg11.png", "zg12.png"});
if (result.sim > 0.92f) {
LtLog.e(mFairy.getLineInfo("捉鬼活跃度已满"));
setTaskEnd();
return true;
}
}
return false;
}
void content_02() throws Exception {
rank(new String[]{"zg1.png"}, "zg2.png", null);
}
boolean exceptional_case() throws Exception {
if (zg) {
setTaskName(2);
gamePublicFuntion.init(1);
bool_rank = true;
bool_genrank_state = false;
return true;
}
return false;
}
void content_03() throws Exception {
super.content_03();
if (timeMap("cb", cb_time, false)) {
singleTask.chubei();
gamePublicFuntion.close(3);
}
if (zg == false && timeMap("huoyue", 600000, false)) {
setTaskName(0);
return;
}
}
};
}
private boolean gen_ywz = true;
public boolean gen_ywz() throws Exception {
gen_ywz = true;
new GenContent(mFairy, "妖王战") {
void create() throws Exception {
super.create();
activity_type = 1;
activity_name = "ywz.png";
}
void inOperation() throws Exception {
super.inOperation();
minute = mFairy.dateMinute();
if ((minute > 10 && minute < 30) || (minute > 40 && minute < 59)) {
if (gamePublicFuntion.fb() == false) {
if (frequencyMap("end_time", 2)) {
setTaskEnd();
gen_ywz = false;
return;
}
}
}
}
void content_02() throws Exception {
rank(new String[]{"ywz2.png"}, "fy5.png", new String[]{"ywz7.png"});
}
void content_03() throws Exception {
super.content_03();
result = mFairy.findPic("ptfb14.png");
if (result.sim > 0.8f) {
for (int i = 0; i < 4; i++) {
result = modularLookup(1113, 204, 1191, 300, "shaizi.png");
if (result.sim > 0.8f) {
mFairy.onTap(0.8f, result, "骰子", 500);
modularLookup++;
}
}
modularLookup = 0;
mFairy.onTap(1182, 65, 1202, 83, "", 1000);
}
}
};
return gen_ywz;
}//妖王战
private boolean gen_xs = true;
public boolean gen_xs() throws Exception {
gen_xs = true;
new GenContent(mFairy, "二十八星宿") {
void create() throws Exception {
super.create();
activity_type = 1;
activity_name = "xs.png";
}
void inOperation() throws Exception {
super.inOperation();
minute = mFairy.dateMinute();
if (minute > 40) {
if (gamePublicFuntion.fb() == false) {
if (frequencyMap("end_time", 2)) {
setTaskEnd();
gen_xs = false;
return;
}
}
}
}
void content_02() throws Exception {
rank(new String[]{"xs3.png"}, "xs1.png", new String[]{"xs2.png"});
}
};
return gen_xs;
}//二十八星宿
public void gen_jjzz() throws Exception {
new GenContent(mFairy, "加急奏章") {
void create() throws Exception {
super.create();
activity_type = 3;
activity_name = "jjzz.png";
}
void inOperation() throws Exception {
super.inOperation();
minute = mFairy.dateMinute();
if (minute > 30) {
if (gamePublicFuntion.fb() == false) {
if (frequencyMap("end_time", 2)) {
setTaskEnd();
return;
}
}
}
}
void content_02() throws Exception {
rank(new String[]{"jjzz3.png"}, "jjzz1.png", new String[]{"jjzz2.png"});
}
void content_03() throws Exception {
super.content_03();
}
};
}//加急奏章
public void gen() throws Exception {
new TaskContent(mFairy, "固定队跟队") {
void init() throws Exception {
gamePublicFuntion.init(0);
setTaskName(1);
}
void content_01() throws Exception {
timeCount(30, 0);
FindResult qx = gamePublicFuntion.qx();
if (qx.sim > 0.8f) {
result = mFairy.findPic("ytdg7.png");
if (result.sim > 0.8f) {
mFairy.onTap(0.8f, result, 797, 439, 868, 454, "继续下一层", 8000);
return;
}
result = mFairy.findPic("ptfb9.png");
if (result.sim > 0.8f) {
mFairy.onTap(0.8f, result, "继续挂机", 500);
return;
}
result = mFairy.findPic("ptfb18.png");
if (result.sim > 0.8f) {
mFairy.onTap(0.8f, result, "继续", 500);
return;
}
if (frequencyMap("qx", 3)) {
mFairy.onTap(0.8f, qx, "取消", 500);
}
} else {
frequencyInit("qx");
}
if (gamePublicFuntion.fb()) {
err = 0;
if (AtFairyConfig.getOption("jj").equals("1")) {
if (timeMap("jj", 180000, true)) {
mFairy.onTap(1032, 433, 1054, 447, "开始释放绝技", 1000);
mFairy.onTap(1033, 332, 1058, 350, "", 500);
mFairy.onTap(1216, 641, 1234, 662, "", 500);
gamePublicFuntion.close(3);
}
}
}
gamePublicFuntion.rank();
gamePublicFuntion.fhs(2);
result = mFairy.findPic("rank3.png");
mFairy.onTap(0.85f, result, "跟随", 500);
result = mFairy.findPic(338, 477, 683, 530, "gen4.png");
mFairy.onTap(0.72f, result, 782, 518, 801, 537, "确定跟随", 500);
result = mFairy.findPic("ling3.png");
mFairy.onTap(0.8f, result, 1213, 52, 1232, 70, "", 1000);
result = mFairy.findPic(1000, 588, 1198, 702, "gen2.png");
mFairy.onTap(0.8f, result, "同意进入副本1", 500);
result = mFairy.findPic(774, 108, 941, 261, "gen3.png");
mFairy.onTap(0.8f, result, "同意进入副本2", 500);
result = mFairy.findPic(577, 275, 683, 649, "ok.png");
mFairy.onTap(0.8f, result, "ok", 500);
result = mFairy.findPic(1045, 3, 1265, 50, "nn2.png");
mFairy.onTap(0.85f, result, "跳过教学", 500);
result = mFairy.findPic("ptfb13.png");
mFairy.onTap(0.8f, result, "跳过旁白", 500);
result = mFairy.findPic("hgfz5.png");
if (result.sim > 0.8f) {
result = mFairy.findPic(724, 115, 1117, 171, "hgfz6.png");
if (result.sim > 0.85f) {
mFairy.onTap(result.x + 1, result.y - 25, result.x + 2, result.y - 23, "抓贼", 1000);
for (int i = 0; i < 3; i++) {
result = mFairy.findPic(208, 109, 1125, 630, "hgfz7.png");
mFairy.onTap(0.8f, result, "选择贼", 500);
}
gamePublicFuntion.close(3);
} else {
mFairy.onTap(754, 106, 768, 123, "", 500);
}
}
if (gamePublicFuntion.mainScene()) {
if (gamePublicFuntion.judgeStop(10, true, 0.85f)) {
}
}
}
};
}//跟
/**
* other
*/
private int go1, go2, go3, go4, go5 = 0,go6 = 0,go7 = 0,go8 =0,go9 = 0;
public void xianshi() throws Exception{
new TaskContent(mFairy, "限时任务") {
void init() throws Exception {
gamePublicFuntion.init(0);
setTaskName(1);
}
void content_01() throws Exception {
timeCount(10, 0);
if (gamePublicFuntion.mainScene()) {
err = 0;
}
result = gamePublicFuntion.qx();
mFairy.onTap(0.8f, result, "取消", 500);
result = mFairy.findPic("ptfb14.png");
if (result.sim > 0.8f) {
for (int i = 0; i < 4; i++) {
result = modularLookup(1113, 204, 1191, 300, "shaizi.png");
if (result.sim > 0.8f) {
mFairy.onTap(0.8f, result, "骰子", 500);
modularLookup++;
}
}
modularLookup = 0;
mFairy.onTap(1182, 65, 1202, 83, "", 1000);
}
if (xs()) {
setTaskName(0);
return;
}
}
boolean xs() throws Exception {
boolean bool = false;
while (mFairy.condit()) {
week = mFairy.week();
hour = mFairy.dateHour();
minute = mFairy.dateMinute();
if (hour == 0 || hour == 24) {
go1 = 0;
go2 = 0;
go3 = 0;
go4 = 0;
go5 = 0;
go6 = 0;
go7 = 0;
go8 = 0;
go9 = 0;
}
if (AtFairyConfig.getOption("hgfz").equals("1") && go1 == 0) {
if ((hour == 12 && minute > 30) || (hour > 12 && hour < 24)) {
hgfz();
go1 = 1;
bool = true;
continue;
}
}
if (AtFairyConfig.getOption("xycm").equals("1") && go2 == 0) {
if ((week == 6 || week == 7) && hour >= 14) {
xycm();
go2 = 1;
bool = true;
continue;
}
}
if (AtFairyConfig.getOption("jjzz").equals("1") && go6 == 0) {
if (hour == 19 && minute<30) {
gen_jjzz();
go6 = 1;
bool = true;
continue;
}
}
if (AtFairyConfig.getOption("bpyx").equals("1") && go7 == 0) {
if (hour == 20 && minute>10 && minute<25) {
singleTask.li_rank();
singleTask.bpyx();
go7 = 1;
bool = true;
continue;
}
}
if (AtFairyConfig.getOption("jzhs").equals("1") && go8 == 0) {
if ((week == 1 || week ==3 || week==5)
&&((hour == 20 && minute>30) || (hour ==21 && minute<30))) {
singleTask.li_rank();
singleTask.jzhs();
go8 = 1;
bool = true;
continue;
}
}
if (AtFairyConfig.getOption("qzsm").equals("1") && go9 == 0) {
if (hour >= 12) {
qzsm();
go9 = 1;
bool = true;
continue;
}
}
if (AtFairyConfig.getOption("ywz").equals("1") && go3 == 0) {
if (hour >= 12 && ((minute >= 0 && minute <= 10) || (minute >= 30 && minute <= 40))) {
if (gen_ywz()) {
singleTask.li_rank();
go3 = 1;
bool = true;
continue;
}
}
}
if (AtFairyConfig.getOption("xs").equals("1") && go4 == 0) {
if ((hour >= 12 && hour < 23) && (minute > 20 && minute < 40)) {
if (gen_xs()) {
singleTask.li_rank();
go4 = 1;
bool = true;
continue;
}
}
}
if (AtFairyConfig.getOption("kjxs").equals("1") && go5 == 0) {
if (week != 7 && hour >= 11) {
singleTask.kjxs();
singleTask.li_rank();
go5 = 1;
bool = true;
continue;
}
}
break;
}
return bool;
}
};
}//限时任务
}
|
Space-Crew/SpaceCraft
|
client/3d/water/FlowCube.spec.js
|
<filename>client/3d/water/FlowCube.spec.js
import {expect} from 'chai'
import {FlowCube} from './FlowCube'
describe('FlowCube', () => {
/*************
* Volume
*************/
describe('maxVolumeOfParents', () => {
const source1 = new FlowCube({x: 0, y: 0, z: 3}, true)
const source2 = new FlowCube({x: 0, y: 2, z: 0}, true)
const child = source1
.createChildAt({x: 0, y: 0, z: 2})
.createChildAt({x: 0, y: 0, z: 1})
.createChildAt({x: 0, y: 0, z: 0})
source2.createChildAt({x: 0, y: 1, z: 0}).linkChild(child)
it('works', () => {
expect(child.maxVolumeOfParents).to.equal(4)
})
})
describe('volume and findVolumeBasedOnParents and hasVolumeToFlowTo', () => {
it('works horizontally', () => {
const source = new FlowCube({x: 0, y: -64, z: 0}, true)
const child = source
.createChildAt({x: 0, y: -64, z: -1})
.createChildAt({x: 0, y: -64, z: -2})
.createChildAt({x: 0, y: -64, z: -3})
expect(child.volume).to.equal(1)
expect(child.hasVolumeToFlowTo({x: 0, y: -64, z: -4})).to.equal(false)
})
it('works vertically', () => {
const source = new FlowCube({x: 0, y: -63, z: 0}, true)
const child = source
.createChildAt({x: 0, y: -63, z: -1})
.createChildAt({x: 0, y: -63, z: -2})
.createChildAt({x: 0, y: -63, z: -3})
expect(child.hasVolumeToFlowTo({x: 0, y: -64, z: -3})).to.equal(true)
const child2 = source.createChildAt({x: 0, y: -64, z: 0})
expect(child2.volume).to.equal(4)
})
})
/*****************
* Public methods
*****************/
describe('createChildAt and linkChild', () => {
let source
let child
beforeEach(() => {
source = new FlowCube({x: 0, y: 0, z: 0}, true)
child = source.createChildAt({x: 0, y: 0, z: 1})
})
it('sets child position', () => {
expect(child.position).to.include({x: 0, y: 0, z: 1})
})
it('does not make child a source', () => {
expect(child.isSource).to.equal(false)
})
it('keeps its parent', () => {
expect(child.parents).to.have.property('0,0,0')
})
})
describe('linkChild', () => {
let source
let child
let otherSource
beforeEach(() => {
source = new FlowCube({x: 0, y: 0, z: 0}, true)
otherSource = new FlowCube({x: 0, y: 1, z: 2}, true)
child = source
.createChildAt({x: 0, y: 0, z: 1})
.createChildAt({x: 0, y: 0, z: 2})
})
it('resets the volume of the child', () => {
let targetVolume = source.volume - 2
expect(child.volume).to.equal(targetVolume)
otherSource.linkChild(child)
expect(child.volume).to.equal(otherSource.volume)
})
})
describe('unlinkChild', () => {
let source
let child
beforeEach(() => {
source = new FlowCube({x: 0, y: 0, z: 0}, true)
child = source.createChildAt({x: 1, y: 0, z: 0})
source.unlinkChild(child)
})
it('removes the child form the parent', () => {
expect(source.children).to.be.empty
})
it('removes the parent form the child', () => {
expect(child.parents).to.be.empty
})
})
describe('unlinkParents', () => {
let child
let parent1
let parent2
beforeEach(() => {
parent1 = new FlowCube({x: 0, y: 0, z: 0})
parent2 = new FlowCube({x: 1, y: 1, z: 0})
child = new FlowCube({x: 1, y: 0, z: 0})
parent1.linkChild(child)
parent2.linkChild(child)
expect(parent1.children).to.have.property('1,0,0')
expect(parent2.children).to.have.property('1,0,0')
})
it('unlinks the cube from its parents', () => {
child.unlinkParents()
expect(parent1.children).to.not.have.property('1,0,0')
expect(parent2.children).to.not.have.property('1,0,0')
})
})
describe('up', () => {
const source = new FlowCube({x: 0, y: -62, z: 0}, true)
it('returns the position above this one', () => {
expect(source.up).to.deep.equal({x: 0, y: -61, z: 0})
})
})
describe('neighbors', () => {
let source
let neighbors
before(() => {
source = new FlowCube({x: 0, y: -62, z: 0}, true)
neighbors = source.neighbors
})
it('gets adjacent positions on the xy plane', () => {
expect(neighbors).to.deep.equal([
{x: 0, y: -62, z: 1},
{x: 1, y: -62, z: 0},
{x: 0, y: -62, z: -1},
{x: -1, y: -62, z: 0},
{x: 0, y: -63, z: 0}
])
})
})
/*****************
* Private methods
*****************/
describe('down', () => {
const source = new FlowCube({x: 0, y: -62, z: 0}, true)
it('returns the position below this one', () => {
expect(source.down).to.deep.equal({x: 0, y: -63, z: 0})
})
})
describe('clonePosition', () => {
let source
let clone
before(() => {
source = new FlowCube({x: 0, y: -62, z: 0}, true)
clone = source.clonePosition()
})
it('creates a new object with same position', () => {
expect(clone).to.deep.equal(source.position)
expect(clone).to.not.equal(source.position)
})
})
describe('flatNeighbors', () => {
let source
let flatNeighbors
before(() => {
source = new FlowCube({x: 0, y: -62, z: 0}, true)
flatNeighbors = source.flatNeighbors
})
it('gets adjacent positions on the xy plane', () => {
expect(flatNeighbors).to.deep.equal([
{x: 0, y: -62, z: 1},
{x: 1, y: -62, z: 0},
{x: 0, y: -62, z: -1},
{x: -1, y: -62, z: 0}
])
})
})
describe('isFlowingDown', () => {
let source
let childDown
let childSide
before(() => {
source = new FlowCube({x: 0, y: 0, z: 0}, true)
childDown = source.createChildAt({x: 0, y: -1, z: 0})
childSide = new FlowCube({x: 20, y: 0, z: 0})
})
it('returns true if parent is above', () => {
expect(childDown.isFlowingDown()).to.be.true
})
it('returns false if parent is not above', () => {
expect(childSide.isFlowingDown()).to.be.false
})
})
describe('becameBigger', () => {
let otherCube
let source
let child
beforeEach(() => {
source = new FlowCube({x: 0, y: -64, z: 0}, true)
child = source
.createChildAt({x: 1, y: -64, z: 0})
.createChildAt({x: 2, y: -64, z: 0})
.createChildAt({x: 3, y: -64, z: 0})
otherCube = new FlowCube({x: 0, y: -64, z: 0}, true)
})
it('returns true if does', () => {
const oldVolume = child.volume
otherCube.linkChild(child)
expect(child.becameBigger(oldVolume)).to.be.true
})
it("returns false if doesn't", () => {
const oldVolume = otherCube.volume
child.linkChild(otherCube)
expect(otherCube.becameBigger(oldVolume)).to.be.false
})
})
})
|
Git-liuxiaoyu/cloud-hospital-parent
|
cloud-hospital-parent/cloud-hospital-nacos-parent/drug-service/src/main/java/com/example/drugservice/service/instock/InStockDrugCommand.java
|
<gh_stars>0
package com.example.drugservice.service.instock;
import com.example.drugservice.util.ApplicationContextHolder;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.ToString;
import javax.xml.transform.Source;
import java.math.BigDecimal;
import java.util.Date;
@Data
@AllArgsConstructor
@ToString
public class InStockDrugCommand {
private String no;
private String name;
private Integer typeId;
private Integer num;
private BigDecimal costprice;
private BigDecimal saleprice;
private String location;
private Date productiontime;
private Date expirationtime;
@ApiModelProperty(hidden = true)
private IInStockDrugCommandHandle handle;
public InStockDrugCommand(){
this.handle= ApplicationContextHolder
.getApplicationContext()
.getBean(IInStockDrugCommandHandle.class);
}
public InStockDrugCommand(String name, Integer typeId, Integer num, BigDecimal costprice, BigDecimal saleprice, String location, Date productiontime, Date expirationtime) {
this();
this.name = name;
this.typeId = typeId;
this.num = num;
this.costprice = costprice;
this.saleprice = saleprice;
this.location = location;
this.productiontime = productiontime;
this.expirationtime = expirationtime;
}
public void execute(){
InStockDrugCommand drug = handle.getDrugByNameAndByLocation(this.name, this.location);
if (drug==null){
//添加药品
handle.addDrug(this);
}else {
//修改库存 根据no
this.no = drug.getNo();
handle.updateDrug(this);
}
}
}
|
wyaadarsh/LeetCode-Solutions
|
Python3/0635-Design-Log-Storage-System/soln.py
|
ass LogSystem:
def __init__(self):
self.gra_d = {'Year' : 4,
'Month' : 7,
'Day' : 10,
'Hour' : 13,
'Minute' : 16,
'Second' : 19}
self.logs = []
def put(self, id, timestamp):
"""
:type id: int
:type timestamp: str
:rtype: void
"""
self.logs.append((id, timestamp))
def retrieve(self, s, e, gra):
"""
:type s: str
:type e: str
:type gra: str
:rtype: List[int]
"""
print(self.logs)
idx = self.gra_d[gra]
s = s[:idx]
e = e[:idx]
return [i for i, stamp in self.logs if s <= stamp[:idx] <= e]
# Your LogSystem object will be instantiated and called as such:
# obj = LogSystem()
# obj.put(id,timestamp)
# param_2 = obj.retrieve(s,e,gra)
|
santosfamilyfoundation/RuinaMain
|
reducers/PassengerReducer.js
|
var uuid = require('react-native-uuid');
const initialState = {
data: []
}
let updatedState;
export default function passengerReducer (state=initialState, action) {
switch (action.type) {
case 'ADDPASSENGER':
console.log("add passenger " + action.payload.id);
return {
...state,
data: state.data.concat([{id: action.payload.id, vehicle: action.payload.vehicleID}])
}
case 'UPDATEPASSENGER':
const { id, question, selection } = action.payload
updatedState = state.data;
let selectedPassenger = updatedState.find(passenger => passenger.id == id)
if(selectedPassenger.response == undefined) {
selectedPassenger.response = {}
}
selectedPassenger.response[question] = selection;
return {
...state,
data: updatedState
}
case 'DELETEPASSENGER':
const {passengerID} = action.payload
console.log("delete passenger " + passengerID);
updatedState = state.data;
return {
...state,
data: updatedState.filter(passenger => passenger.id != passengerID)
}
case 'RESETPASSENGER':
console.log("RESET PASSENGER!");
state = initialState;
return {
...state,
}
default:
return state;
}
}
|
MicrohexHQ/liboqs
|
src/sig/picnic/external/lowmc_pars.h
|
<reponame>MicrohexHQ/liboqs
/*
* This file is part of the optimized implementation of the Picnic signature scheme.
* See the accompanying documentation for complete details.
*
* The code is provided under the MIT license, see LICENSE for
* more details.
* SPDX-License-Identifier: MIT
*/
#ifndef LOWMC_PARS_H
#define LOWMC_PARS_H
#include <stddef.h>
#include "mzd_additional.h"
typedef mzd_local_t lowmc_key_t;
/**
* Masks for 10 S-boxes.
*/
#define MASK_X0I UINT64_C(0x2492492400000000)
#define MASK_X1I UINT64_C(0x4924924800000000)
#define MASK_X2I UINT64_C(0x9249249000000000)
#define MASK_MASK UINT64_C(0x00000003ffffffff)
/**
* Masks for 1 S-box.
*/
#define MASK_X0I_1 UINT64_C(0x2000000000000000)
#define MASK_X1I_1 UINT64_C(0x4000000000000000)
#define MASK_X2I_1 UINT64_C(0x8000000000000000)
#define MASK_MASK_1 UINT64_C(0x1fffffffffffffff)
/**
* LowMC instances
*/
#define LOWMC_L1_N 128
#define LOWMC_L1_M 10
#define LOWMC_L1_K LOWMC_L1_N
#define LOWMC_L1_R 20
#define LOWMC_L3_N 192
#define LOWMC_L3_M 10
#define LOWMC_L3_K LOWMC_L3_N
#define LOWMC_L3_R 30
#define LOWMC_L5_N 256
#define LOWMC_L5_M 10
#define LOWMC_L5_K LOWMC_L5_N
#define LOWMC_L5_R 38
#define LOWMC_L1_1_N 128
#define LOWMC_L1_1_M 1
#define LOWMC_L1_1_K LOWMC_L1_1_N
#define LOWMC_L1_1_R 182
#define LOWMC_L3_1_N 192
#define LOWMC_L3_1_M 1
#define LOWMC_L3_1_K LOWMC_L3_1_N
#define LOWMC_L3_1_R 284
#define LOWMC_L5_1_N 256
#define LOWMC_L5_1_M 1
#define LOWMC_L5_1_K LOWMC_L5_1_N
#define LOWMC_L5_1_R 363
typedef struct {
#if !defined(REDUCED_ROUND_KEY_COMPUTATION)
const mzd_local_t* k_matrix;
#endif
#if !defined(OPTIMIZED_LINEAR_LAYER_EVALUATION)
const mzd_local_t* l_matrix;
#else
const mzd_local_t* z_matrix;
const mzd_local_t* r_matrix;
const word r_mask;
#endif
#if !defined(REDUCED_ROUND_KEY_COMPUTATION)
const mzd_local_t* constant;
#endif
#if defined(MUL_M4RI)
#if !defined(REDUCED_ROUND_KEY_COMPUTATION)
mzd_local_t* k_lookup;
#endif
mzd_local_t* l_lookup;
#endif
} lowmc_round_t;
/**
* LowMC definition
*/
typedef struct {
uint32_t m;
uint32_t n;
uint32_t r;
uint32_t k;
const mzd_local_t* k0_matrix; // K_0 or K_0 + precomputed if reduced_linear_layer is set
#if defined(OPTIMIZED_LINEAR_LAYER_EVALUATION)
const mzd_local_t* zr_matrix; // combined linear layers
#endif
#if defined(MUL_M4RI)
mzd_local_t* k0_lookup;
#endif
#if defined(MUL_M4RI)
lowmc_round_t* rounds;
#else
const lowmc_round_t* rounds;
#endif
#if defined(REDUCED_ROUND_KEY_COMPUTATION)
const mzd_local_t* precomputed_non_linear_part_matrix;
#if defined(MUL_M4RI)
mzd_local_t* precomputed_non_linear_part_lookup;
#endif
const mzd_local_t* precomputed_constant_linear;
const mzd_local_t* precomputed_constant_non_linear;
#endif
} lowmc_t;
#if defined(MUL_M4RI)
/**
* Initiaizes lookup tables of a LowMC instance
*
* \return parameters defining a LowMC instance
*/
bool lowmc_init(lowmc_t* lowmc);
#endif
/**
* Clears the allocated LowMC parameters
*
* \param lowmc the LowMC parameters to be cleared
*/
void lowmc_clear(lowmc_t* lowmc);
#endif
|
ogii-test/ddp-study-server
|
pepper-apis/src/main/java/org/broadinstitute/ddp/util/StudyDataLoader.java
|
<reponame>ogii-test/ddp-study-server
package org.broadinstitute.ddp.util;
import static java.util.stream.Collectors.toList;
import static org.apache.commons.lang.time.DateUtils.MILLIS_PER_SECOND;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import com.auth0.json.mgmt.users.User;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.typesafe.config.Config;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.broadinstitute.ddp.client.Auth0ManagementClient;
import org.broadinstitute.ddp.constants.ConfigFile;
import org.broadinstitute.ddp.constants.SqlConstants.MedicalProviderTable;
import org.broadinstitute.ddp.db.DBUtils;
import org.broadinstitute.ddp.db.dao.ActivityInstanceDao;
import org.broadinstitute.ddp.db.dao.ActivityInstanceStatusDao;
import org.broadinstitute.ddp.db.dao.AnswerDao;
import org.broadinstitute.ddp.db.dao.DsmKitRequestDao;
import org.broadinstitute.ddp.db.dao.JdbiActivity;
import org.broadinstitute.ddp.db.dao.JdbiActivityInstance;
import org.broadinstitute.ddp.db.dao.JdbiClient;
import org.broadinstitute.ddp.db.dao.JdbiCompositeAnswer;
import org.broadinstitute.ddp.db.dao.JdbiCountrySubnationalDivision;
import org.broadinstitute.ddp.db.dao.JdbiInstitutionType;
import org.broadinstitute.ddp.db.dao.JdbiLanguageCode;
import org.broadinstitute.ddp.db.dao.JdbiMailAddress;
import org.broadinstitute.ddp.db.dao.JdbiMailingList;
import org.broadinstitute.ddp.db.dao.JdbiMedicalProvider;
import org.broadinstitute.ddp.db.dao.JdbiUser;
import org.broadinstitute.ddp.db.dao.JdbiUserStudyEnrollment;
import org.broadinstitute.ddp.db.dao.JdbiUserStudyLegacyData;
import org.broadinstitute.ddp.db.dao.KitTypeDao;
import org.broadinstitute.ddp.db.dao.MedicalProviderDao;
import org.broadinstitute.ddp.db.dao.UserProfileDao;
import org.broadinstitute.ddp.db.dto.ActivityInstanceDto;
import org.broadinstitute.ddp.db.dto.ClientDto;
import org.broadinstitute.ddp.db.dto.MedicalProviderDto;
import org.broadinstitute.ddp.db.dto.StudyDto;
import org.broadinstitute.ddp.db.dto.UserDto;
import org.broadinstitute.ddp.exception.AddressVerificationException;
import org.broadinstitute.ddp.exception.DDPException;
import org.broadinstitute.ddp.model.activity.instance.answer.AgreementAnswer;
import org.broadinstitute.ddp.model.activity.instance.answer.Answer;
import org.broadinstitute.ddp.model.activity.instance.answer.BoolAnswer;
import org.broadinstitute.ddp.model.activity.instance.answer.CompositeAnswer;
import org.broadinstitute.ddp.model.activity.instance.answer.DateAnswer;
import org.broadinstitute.ddp.model.activity.instance.answer.DateValue;
import org.broadinstitute.ddp.model.activity.instance.answer.PicklistAnswer;
import org.broadinstitute.ddp.model.activity.instance.answer.SelectedPicklistOption;
import org.broadinstitute.ddp.model.activity.instance.answer.TextAnswer;
import org.broadinstitute.ddp.model.activity.types.InstanceStatusType;
import org.broadinstitute.ddp.model.activity.types.InstitutionType;
import org.broadinstitute.ddp.model.address.MailAddress;
import org.broadinstitute.ddp.model.migration.BaseSurvey;
import org.broadinstitute.ddp.model.migration.SurveyAddress;
import org.broadinstitute.ddp.model.user.EnrollmentStatusType;
import org.broadinstitute.ddp.model.user.UserProfile;
import org.broadinstitute.ddp.service.AddressService;
import org.broadinstitute.ddp.service.DsmAddressValidationStatus;
import org.broadinstitute.ddp.service.OLCService;
import org.jdbi.v3.core.Handle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StudyDataLoader {
public static final String OTHER = "OTHER";
//public static final String NED = "NED";
public static final String YES = "YES";
public static final String NO = "NO";
public static final String DK = "DK";
private static final Logger LOG = LoggerFactory.getLogger(StudyDataLoader.class);
private static final String DEFAULT_PREFERRED_LANGUAGE_CODE = "en";
private static final String DATSTAT_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
private static final int DSM_DEFAULT_ON_DEMAND_TRIGGER_ID = -2;
Map<String, List<String>> sourceDataSurveyQs;
Map<String, String> altNames;
Map<String, String> dkAltNames;
Map<Integer, String> yesNoDkLookup;
Map<Integer, Boolean> booleanValueLookup;
Auth0ManagementClient mgmtClient;
Map<String, List<String>> datStatEnumLookup;
Auth0Util auth0Util;
String auth0Domain;
String mgmtToken;
private Long defaultKitCreationEpoch = null;
public StudyDataLoader(Config cfg) {
Config auth0Config = cfg.getConfig(ConfigFile.AUTH0);
auth0Domain = auth0Config.getString(ConfigFile.DOMAIN);
auth0Util = new Auth0Util(auth0Domain);
mgmtClient = new Auth0ManagementClient(
auth0Domain,
auth0Config.getString("managementApiClientId"),
auth0Config.getString("managementApiSecret"));
mgmtToken = mgmtClient.getToken();
sourceDataSurveyQs = new HashMap<>();
//some lookup codes/values
yesNoDkLookup = new HashMap<>();
yesNoDkLookup.put(0, "NO");
yesNoDkLookup.put(1, "YES");
yesNoDkLookup.put(2, "DK");
booleanValueLookup = new HashMap<>();
booleanValueLookup.put(0, false);
booleanValueLookup.put(1, true);
dkAltNames = new HashMap<>();
dkAltNames.put("dk", "Don't know");
// altNames maps from the name in the mapping to the name in the export file
altNames = new HashMap<>();
altNames.put("SOUTH_EAST_ASIAN", "southeast_asian_indian");
altNames.put("BLACK", "black_african_american");
altNames.put("PREFER_NOT_ANSWER", "prefer_no_answer");
altNames.put("NATIVE_HAWAIIAN", "hawaiian");
//MPC THERAPIES options entries
altNames.put("xtandi", "xtandi_enzalutamide");
altNames.put("zytiga", "zytiga_abiraterone");
altNames.put("docetaxel", "docetaxel_taxotere");
altNames.put("taxol", "paclitaxel_taxol");
altNames.put("jevtana", "jevtana_cabazitaxel");
altNames.put("opdivo", "opdivo_nivolumab");
altNames.put("yervoy", "yervoy_ipilumimab");
altNames.put("tecentriq", "tecentriq_aztezolizumab");
altNames.put("lynparza", "lynparza_olaparib");
altNames.put("rubraca", "rubraca_rucaparib");
altNames.put("TAXOTERE", "docetaxel_taxotere");
altNames.put("PARAPLATIN", "carboplatin");
altNames.put("ETOPOPHOS", "etoposide");
altNames.put("NOVANTRONE", "mitoxantrone");
altNames.put("EMCYT", "estramustine");
altNames.put("FIRMAGON", "degareliz");
altNames.put("OTHER_YES", "other_therapy");
altNames.put("CLINICAL_TRIAL", "exp_clinical_trial");
altNames.put("affected", "effected");
//index is value in export file and element is stable id
datStatEnumLookup = new HashMap<>();
//Independently consent
List<String> optionList = new ArrayList<>(2);
optionList.add(0, "prion_consent_s7_INDEPENDENT_NO");
optionList.add(1, "prion_consent_s7_INDEPENDENT_YES");
datStatEnumLookup.put("independently_consent", optionList);
//Participant gender
optionList = new ArrayList<>(4);
optionList.add(0, null);
optionList.add(1, "FEMALE");
optionList.add(2, "MALE");
optionList.add(3, "PREFER_NOT");
datStatEnumLookup.put("participant_gender", optionList);
//Current status
optionList = new ArrayList<>(4);
optionList.add(0, null);
optionList.add(1, "SYMPTOMATIC");
optionList.add(2, "AT_RISK");
optionList.add(3, "CONTROL");
datStatEnumLookup.put("current_status", optionList);
//Doctor diagnosed
optionList = new ArrayList<>(2);
optionList.add(0, "DIAGNOSED_NO");
optionList.add(1, "DIAGNOSED_YES");
datStatEnumLookup.put("doctor_diagnosed", optionList);
//Prion subtype
optionList = new ArrayList<>(9);
optionList.add(0, null);
optionList.add(1, "CJD");
optionList.add(2, "FFI");
optionList.add(3, "GSS");
optionList.add(4, "VPSPr");
optionList.add(5, "PSA");
optionList.add(6, "KURU");
optionList.add(7, "vCJD");
optionList.add(8, "sFI");
datStatEnumLookup.put("prion_subtype", optionList);
//Genetic testing
optionList = new ArrayList<>(4);
optionList.add(0, null);
optionList.add(1, "WAITING");
optionList.add(2, "KNOWN");
optionList.add(3, "NO");
datStatEnumLookup.put("genetic_testing", optionList);
//Move ability
optionList = new ArrayList<>(4);
optionList.add(0, null);
optionList.add(1, "ASSIST");
optionList.add(2, "IND");
optionList.add(3, "BED");
datStatEnumLookup.put("move_ability", optionList);
//Cognitive ability
optionList = new ArrayList<>(4);
optionList.add(0, null);
optionList.add(1, "IMP");
optionList.add(2, "NORM");
optionList.add(3, "SEV");
datStatEnumLookup.put("cognitive_ability", optionList);
//Eat ability
optionList = new ArrayList<>(4);
optionList.add(0, null);
optionList.add(1, "ASSIST");
optionList.add(2, "NORM");
optionList.add(3, "TUBE");
datStatEnumLookup.put("eat_ability", optionList);
//Travel ability
optionList = new ArrayList<>(4);
optionList.add(0, null);
optionList.add(1, "ASSIST");
optionList.add(2, "YES");
optionList.add(3, "NO");
datStatEnumLookup.put("travel_ability", optionList);
//participant disease risk
optionList = new ArrayList<>(7);
optionList.add(0, null);
optionList.add(1, "SUSPECTED_EXPOSED");
optionList.add(2, "MEDICAL_INFORMED");
optionList.add(3, "RELATIVE_UNTESTED");
optionList.add(4, "RELATIVE_TESTED");
optionList.add(5, "PARTICIPANT_TESTED");
optionList.add(6, "OTHER");
datStatEnumLookup.put("participant_disease_risk", optionList);
//medical procedure risk
optionList = new ArrayList<>(6);
optionList.add(0, null);
optionList.add(1, "MEDICAL_PROCEDURE_TRANSFUSION");
optionList.add(2, "MEDICAL_PROCEDURE_INSTRUMENTS");
optionList.add(3, "MEDICAL_PROCEDURE_TRANSPLANT");
optionList.add(4, "MEDICAL_PROCEDURE_HGH");
optionList.add(5, "MEDICAL_PROCEDURE_OTHER");
datStatEnumLookup.put("medical_procedure_risk", optionList);
//know_which_mutation
optionList = new ArrayList<>(2);
optionList.add(0, "KNOWN_MUTATION_NO");
optionList.add(1, "KNOWN_MUTATION_YES");
datStatEnumLookup.put("know_which_mutation", optionList);
//earliest_symptom_estimated
optionList = new ArrayList<>(2);
optionList.add(0, null);
optionList.add(1, "ESTIMATED_DATE");
datStatEnumLookup.put("earliest_symptom_estimated", optionList);
//diagnosis_date_estimated
optionList = new ArrayList<>(2);
optionList.add(0, null);
optionList.add(1, "YES");
datStatEnumLookup.put("diagnosis_date_estimated", optionList);
}
void loadMailingListData(Handle handle, JsonElement data, String studyCode) {
LOG.info("loading: {} mailinglist", studyCode);
JdbiMailingList dao = handle.attach(JdbiMailingList.class);
JsonArray dataArray = data.getAsJsonArray();
Long dateCreatedMillis = null;
JsonElement dateCreatedEl;
String firstName;
String lastName;
String email;
for (JsonElement thisEl : dataArray) {
dateCreatedEl = thisEl.getAsJsonObject().get("datecreated");
if (dateCreatedEl != null && !dateCreatedEl.isJsonNull()) {
dateCreatedMillis = dateCreatedEl.getAsNumber().longValue();
}
firstName = getStringValueFromElement(thisEl, "firstname");
lastName = getStringValueFromElement(thisEl, "lastname");
email = getStringValueFromElement(thisEl, "email");
if (StringUtils.isBlank(firstName)) {
firstName = "";
}
if (StringUtils.isBlank(lastName)) {
lastName = "";
}
dao.insertByStudyGuidIfNotStoredAlready(firstName, lastName, email, studyCode, null, dateCreatedMillis);
}
}
public Map<String, String> verifyAuth0Users(Set<String> emailList) {
//make auth0 call
Map<String, String> auth0EmailMap = auth0Util.getAuth0UsersByEmails(emailList, mgmtToken);
return auth0EmailMap;
}
public String loadParticipantData(Handle handle, JsonElement datstatData, JsonElement mappingData, String phoneNumber,
StudyDto studyDto, ClientDto clientDto, MailAddress address, OLCService olcService,
AddressService addressService, boolean useExistingAuth0Users) throws Exception {
//load data
JdbiUser jdbiUser = handle.attach(JdbiUser.class);
String altpid = datstatData.getAsJsonObject().get("datstat_altpid").getAsString();
String userGuid = jdbiUser.getUserGuidByAltpid(altpid);
if (userGuid != null) {
LOG.warn("Looks like Participant data already loaded: " + userGuid);
return userGuid;
//watch out.. early return
}
//get default kit creation date
String defaultKitCreationDate = mappingData.getAsJsonArray().get(2).getAsJsonObject()
.get("default_kit_creation_date").getAsString();
userGuid = DBUtils.uniqueUserGuid(handle);
String userHruid = DBUtils.uniqueUserHruid(handle);
JdbiUser userDao = handle.attach(JdbiUser.class);
JdbiClient clientDao = handle.attach(JdbiClient.class);
UserDto pepperUser = createLegacyPepperUser(userDao, clientDao, datstatData, userGuid, userHruid, clientDto,
useExistingAuth0Users);
JdbiLanguageCode jdbiLanguageCode = handle.attach(JdbiLanguageCode.class);
UserProfileDao profileDao = handle.attach(UserProfileDao.class);
addUserProfile(pepperUser, datstatData, jdbiLanguageCode, profileDao);
JdbiMailAddress jdbiMailAddress = handle.attach(JdbiMailAddress.class);
MailAddress createdAddress = addUserAddress(handle, pepperUser,
datstatData,
phoneNumber, address,
jdbiMailAddress,
olcService, addressService);
String kitRequestId = getStringValueFromElement(datstatData, "ddp_spit_kit_request_id");
if (kitRequestId != null) {
KitTypeDao kitTypeDao = handle.attach(KitTypeDao.class);
DsmKitRequestDao dsmKitRequestDao = handle.attach(DsmKitRequestDao.class);
addKitDetails(dsmKitRequestDao,
kitTypeDao,
pepperUser.getUserId(),
createdAddress.getId(),
kitRequestId,
studyDto.getGuid(),
defaultKitCreationDate);
}
String ddpCreated = getStringValueFromElement(datstatData, "ddp_created");
Long ddpCreatedAt = null;
boolean couldNotParse = false;
try {
if (ddpCreated != null) {
Instant instant = Instant.parse(ddpCreated);
if (instant != null) {
ddpCreatedAt = instant.toEpochMilli();
}
}
} catch (DateTimeParseException e) {
couldNotParse = true;
}
if (couldNotParse || ddpCreatedAt == null) {
throw new RuntimeException("Could not figure out registration date for user: " + userGuid);
}
handle.attach(JdbiUserStudyEnrollment.class)
.changeUserStudyEnrollmentStatus(userGuid, studyDto.getGuid(), EnrollmentStatusType.REGISTERED, ddpCreatedAt);
LOG.info("user guid: " + pepperUser.getUserGuid());
processLegacyFields(handle, datstatData, mappingData.getAsJsonArray().get(1),
studyDto.getId(), pepperUser.getUserId(), null);
return pepperUser.getUserGuid();
}
public ActivityInstanceDto createPrequal(Handle handle, String participantGuid, long studyId, String ddpCreated,
JdbiActivity jdbiActivity,
ActivityInstanceDao activityInstanceDao,
ActivityInstanceStatusDao activityInstanceStatusDao,
AnswerDao answerDao) throws Exception {
Long studyActivityId = jdbiActivity.findIdByStudyIdAndCode(studyId, "PREQUAL").get();
Instant instant;
try {
instant = Instant.parse(ddpCreated);
} catch (DateTimeParseException e) {
throw new Exception("Could not parse required createdAt value for prequal, value is " + ddpCreated);
}
long ddpCreatedAt = instant.toEpochMilli();
ActivityInstanceDto dto = activityInstanceDao
.insertInstance(studyActivityId, participantGuid, participantGuid, InstanceStatusType.CREATED,
true,
ddpCreatedAt,
null, null, null);
//populate PREQUAL answers
UserProfileDao profileDao = handle.attach(UserProfileDao.class);
UserProfile profile = profileDao.findProfileByUserGuid(participantGuid)
.orElseThrow(() -> new DDPException("Could not find profile for use with guid " + participantGuid));
answerTextQuestion("PREQUAL_FIRST_NAME", participantGuid, dto.getGuid(),
profile.getFirstName(), answerDao);
answerTextQuestion("PREQUAL_LAST_NAME", participantGuid, dto.getGuid(),
profile.getLastName(), answerDao);
List<SelectedPicklistOption> options = new ArrayList<>();
options.add(new SelectedPicklistOption("DIAGNOSED"));
answerPickListQuestion("PREQUAL_SELF_DESCRIBE", participantGuid, dto.getGuid(),
options, answerDao);
//add 30seconds to created_date and populate complete status
activityInstanceStatusDao
.insertStatus(dto.getId(), InstanceStatusType.COMPLETE, ddpCreatedAt + 30000, participantGuid);
return dto;
}
public ActivityInstanceDto createActivityInstance(JsonElement surveyData, String participantGuid,
long studyId, String activityCode, String createdAt,
JdbiActivity jdbiActivity,
ActivityInstanceDao activityInstanceDao,
ActivityInstanceStatusDao activityInstanceStatusDao,
JdbiActivityInstance jdbiActivityInstance) throws Exception {
BaseSurvey baseSurvey = getBaseSurvey(surveyData);
if (baseSurvey.getDdpCreated() == null) {
LOG.warn("No createdAt for survey: {} participant guid: {} . using participant data created_at ",
activityCode, participantGuid);
baseSurvey.setDdpCreated(createdAt);
}
Long submissionId = baseSurvey.getDatstatSubmissionId();
String sessionId = baseSurvey.getDatstatSessionId();
String ddpCreated = baseSurvey.getDdpCreated();
String ddpCompleted = baseSurvey.getDdpFirstCompleted();
String ddpLastUpdated = baseSurvey.getDdpLastUpdated();
String activityVersion = baseSurvey.getActivityVersion();
if (StringUtils.isEmpty(activityVersion)) {
activityVersion = baseSurvey.getSurveyVersion();
}
Integer submissionStatus = baseSurvey.getDatstatSubmissionStatus();
Long studyActivityId = jdbiActivity.findIdByStudyIdAndCode(studyId, activityCode).get();
Long ddpLastUpdatedAt;
Long ddpCreatedAt;
Long ddpCompletedAt = null;
if (ddpCreated != null) {
Instant instant;
try {
instant = Instant.parse(ddpCreated);
} catch (DateTimeParseException e) {
throw new Exception("Could not parse required createdAt value for " + activityCode + " survey, value is " + ddpCreated);
}
ddpCreatedAt = instant.toEpochMilli();
} else {
throw new Exception("Missing required createdAt value for " + activityCode + " survey");
}
if (ddpLastUpdated != null) {
Instant instant;
try {
instant = Instant.parse(ddpLastUpdated);
} catch (DateTimeParseException e) {
throw new Exception("Could not parse required lastUpdated value for " + activityCode
+ " survey, value is " + ddpLastUpdated);
}
ddpLastUpdatedAt = instant.toEpochMilli();
} else {
throw new Exception("Missing required lastUpdated value for " + activityCode + " survey");
}
if (ddpCompleted != null) {
Instant instant;
try {
instant = Instant.parse(ddpCompleted);
} catch (DateTimeParseException e) {
throw new Exception("Could not parse required completedAt value for " + activityCode
+ " survey, value is " + ddpCompleted);
}
ddpCompletedAt = instant.toEpochMilli();
if (ddpCompletedAt < ddpCreatedAt) {
throw new Exception("Invalid ddpCreatedAt - ddpCompletedAt dates. created date : " + ddpCreated
+ " is greater than ddpCompleted/Submitted date:: " + ddpCompleted + " in activity: " + activityCode
+ " userguid: " + participantGuid);
}
}
if (ddpLastUpdatedAt < ddpCreatedAt) {
throw new Exception("Invalid ddpCreatedAt - ddpLastUpdated dates. created date : " + ddpCreated
+ " is greater than last updated date: " + ddpLastUpdated + " in activity: " + activityCode
+ " userguid: " + participantGuid);
}
String surveyStatus = baseSurvey.getSurveyStatus();
InstanceStatusType instanceCurrentStatus = null;
if (StringUtils.isNotEmpty(surveyStatus)) {
instanceCurrentStatus = InstanceStatusType.valueOf(surveyStatus);
if ("CREATED".equalsIgnoreCase(instanceCurrentStatus.name()) && ddpCreatedAt.compareTo(ddpLastUpdatedAt) != 0) {
throw new Exception("Passed survey status as CREATED but lastUpdated date: " + ddpLastUpdated
+ " is not same as created date: " + createdAt);
}
} else {
instanceCurrentStatus = getActivityInstanceStatus(submissionStatus, ddpCreatedAt, ddpLastUpdatedAt, ddpCompletedAt);
}
// Read only is always undefined for things that aren't consent- we rely on the user being terminated to show read only activities
boolean itIsCompletedConsent = (activityCode == "CONSENT" || activityCode == "TISSUECONSENT"
|| activityCode == "BLOODCONSENT" || activityCode == "FOLLOWUPCONSENT")
&& instanceCurrentStatus == InstanceStatusType.COMPLETE;
Boolean isReadonly = itIsCompletedConsent ? true : null;
ActivityInstanceDto dto = activityInstanceDao
.insertInstance(studyActivityId, participantGuid, participantGuid, InstanceStatusType.CREATED,
isReadonly,
ddpCreatedAt,
submissionId, sessionId, activityVersion);
LOG.info("Created activity instance {} for activity {} and user {}",
dto.getGuid(), activityCode, participantGuid);
long activityInstanceId = dto.getId();
if (InstanceStatusType.IN_PROGRESS == instanceCurrentStatus) {
activityInstanceStatusDao
.insertStatus(activityInstanceId, InstanceStatusType.IN_PROGRESS, ddpLastUpdatedAt, participantGuid);
//reload activityInstance to get updated status
dto = jdbiActivityInstance.getByActivityInstanceId(dto.getId()).get();
} else if (InstanceStatusType.COMPLETE == instanceCurrentStatus) {
if (ddpCompletedAt == null) {
//ddpCompletedAt = ddpLastUpdatedAt;
throw new Exception("No completed/submitted date value passed for " + activityCode
+ " survey with status COMPLETE. user guid: " + participantGuid);
}
activityInstanceStatusDao.insertStatus(activityInstanceId, InstanceStatusType.COMPLETE, ddpCompletedAt, participantGuid);
if (ddpLastUpdatedAt > ddpCompletedAt) {
activityInstanceStatusDao
.insertStatus(activityInstanceId, InstanceStatusType.COMPLETE, ddpLastUpdatedAt, participantGuid);
}
dto = jdbiActivityInstance.getByActivityInstanceId(dto.getId()).get();
} else {
//CREATED
activityInstanceStatusDao.insertStatus(activityInstanceId, InstanceStatusType.CREATED, ddpCreatedAt, participantGuid);
}
return dto;
}
public void loadAboutYouSurveyData(Handle handle,
JsonElement surveyData,
JsonElement mappingData,
StudyDto studyDto,
UserDto userDto,
ActivityInstanceDto instanceDto,
AnswerDao answerDao) throws Exception {
LOG.info("Populating AboutYou Survey...");
if (surveyData == null || surveyData.isJsonNull()) {
LOG.warn("NO AboutYou Survey !");
return;
}
processSurveyData(handle, "aboutyousurvey", surveyData, mappingData,
studyDto, userDto, instanceDto, answerDao);
}
private InstanceStatusType getActivityInstanceStatus(Integer submissionStatusCode, Long createdAt,
Long lastUpdatedAt, Long completedAt) throws Exception {
//submissionStatusCode: Completed = 1 ; In Progress = 2; Terminated = 5
//mbc gets instance status passed.really don't need to determine status.. May be for future studies
InstanceStatusType statusType;
if (completedAt != null) {
if (submissionStatusCode != null && submissionStatusCode != 1 && submissionStatusCode != 5) {
throw new Exception("The survey has a completedAt value, but claims to not be completed!");
}
statusType = InstanceStatusType.COMPLETE;
} else if (createdAt != null && !createdAt.equals(lastUpdatedAt)) {
if (submissionStatusCode != null && submissionStatusCode != 2 && submissionStatusCode != 5) {
throw new Exception("The survey has a different createdAt/lastUpdatedAt values, but claims to not be in progress!");
}
statusType = InstanceStatusType.IN_PROGRESS;
} else {
if (submissionStatusCode != null && submissionStatusCode != 2 && submissionStatusCode != 5) {
throw new Exception("The survey has the same createdAt/lastUpdatedAt values, but claims to not be in progress!");
}
statusType = InstanceStatusType.CREATED;
}
//if no status code passed try by timestamps/dates passed
if (statusType == null) {
//figure out different way
if (completedAt != null) {
statusType = InstanceStatusType.COMPLETE;
} else if (lastUpdatedAt != null) {
statusType = InstanceStatusType.IN_PROGRESS;
} else {
//if we got this far.. its created
statusType = InstanceStatusType.CREATED;
}
}
return statusType;
}
private void addLegacySurveyAddress(Handle handle, StudyDto studyDto, UserDto userDto, ActivityInstanceDto instanceDto,
JsonElement data, String surveyName) {
String street1 = getStringValueFromElement(data, "street1");
String street2 = getStringValueFromElement(data, "street2");
String city = getStringValueFromElement(data, "city");
String country = getStringValueFromElement(data, "country");
String postalCode = getStringValueFromElement(data, "postal_code");
String state = getStringValueFromElement(data, "state");
String fullName = getStringValueFromElement(data, "fullname");
String phoneNumber = getStringValueFromElement(data, "phone_number");
SurveyAddress userLegacyAddress = new SurveyAddress(fullName, street1, street2,
city, state, country, postalCode, phoneNumber);
String fieldName = "legacy_".concat(surveyName).concat("_address");
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.serializeNulls().create();
String addressJsonStr = gson.toJson(userLegacyAddress);
handle.attach(JdbiUserStudyLegacyData.class).insert(userDto.getUserId(), studyDto.getId(), instanceDto.getId(),
fieldName, addressJsonStr);
}
public void loadReleaseSurveyData(Handle handle,
JsonElement surveyData,
JsonElement mappingData,
StudyDto studyDto,
UserDto userDto,
ActivityInstanceDto instanceDto,
AnswerDao answerDao) throws Exception {
LOG.info("Populating Release Survey...");
if (surveyData == null || surveyData.isJsonNull()) {
LOG.warn("NO Release Survey !");
return;
}
processSurveyData(handle, "releasesurvey", surveyData, mappingData,
studyDto, userDto, instanceDto, answerDao);
//add physicians
processInstitutions(handle, surveyData, userDto, studyDto,
"physician_list", InstitutionType.PHYSICIAN, "releasesurvey");
//load initialbiopsy instiution
addBiopsyInstitutions(handle, surveyData, userDto, studyDto);
//add institutions
processInstitutions(handle, surveyData, userDto, studyDto,
"institution_list", InstitutionType.INSTITUTION, "releasesurvey");
updateUserStudyEnrollment(handle, surveyData, userDto.getUserGuid(), studyDto.getGuid());
}
public void loadBloodReleaseSurveyData(Handle handle,
JsonElement surveyData,
JsonElement mappingData,
StudyDto studyDto,
UserDto userDto,
ActivityInstanceDto instanceDto,
AnswerDao answerDao) throws Exception {
LOG.info("Populating Blood Release Survey...");
if (surveyData == null || surveyData.isJsonNull()) {
LOG.warn("NO Release Survey !");
return;
}
processSurveyData(handle, "bdreleasesurvey", surveyData, mappingData,
studyDto, userDto, instanceDto, answerDao);
//handle agreement
String surveyStatus = surveyData.getAsJsonObject().get("survey_status").getAsString();
if (surveyStatus.equalsIgnoreCase("COMPLETE")) {
answerAgreementQuestion("BLOODRELEASE_AGREEMENT", userDto.getUserGuid(),
instanceDto.getGuid(), Boolean.TRUE, answerDao);
}
//Special case for MBC.
//MBC might have dup physicians because physician list comes in both release and bdrelease surveys
processPhysicianList(handle, surveyData, userDto, studyDto,
"physician_list", InstitutionType.PHYSICIAN, "bdreleasesurvey", instanceDto);
updateUserStudyEnrollment(handle, surveyData, userDto.getUserGuid(), studyDto.getGuid());
}
private void updateUserStudyEnrollment(Handle handle, JsonElement surveyData, String userGuid, String studyGuid) throws Exception {
BaseSurvey baseSurvey = getBaseSurvey(surveyData);
if (InstanceStatusType.COMPLETE.name().equalsIgnoreCase(baseSurvey.getSurveyStatus())) {
long updatedAt;
if (baseSurvey.getDdpFirstCompleted() != null) {
Instant instant;
try {
instant = Instant.parse(baseSurvey.getDdpFirstCompleted());
} catch (DateTimeParseException e) {
throw new Exception("Could not parse required completedAt value:" + baseSurvey.getDdpFirstCompleted());
}
updatedAt = instant.toEpochMilli();
} else {
Instant instant;
try {
instant = Instant.parse(baseSurvey.getDdpLastUpdated());
} catch (DateTimeParseException e) {
throw new Exception("Could not parse required lastUpdated value:" + baseSurvey.getDdpLastUpdated());
}
updatedAt = instant.toEpochMilli();
}
handle.attach(JdbiUserStudyEnrollment.class).changeUserStudyEnrollmentStatus(userGuid, studyGuid,
EnrollmentStatusType.ENROLLED, updatedAt);
}
}
String getMedicalProviderGuid(Handle handle) {
return DBUtils.uniqueStandardGuid(handle,
MedicalProviderTable.TABLE_NAME, MedicalProviderTable.MEDICAL_PROVIDER_GUID);
}
public void loadConsentSurveyData(Handle handle,
JsonElement surveyData,
JsonElement mappingData,
StudyDto studyDto,
UserDto userDto,
ActivityInstanceDto instanceDto,
AnswerDao answerDao) throws Exception {
LOG.info("Populating Consent Survey...");
if (surveyData == null || surveyData.isJsonNull()) {
LOG.warn("NO Consent Survey !");
return;
}
processSurveyData(handle, "consentsurvey", surveyData, mappingData,
studyDto, userDto, instanceDto, answerDao);
}
public void loadMedicalSurveyData(Handle handle,
JsonElement surveyData,
JsonElement mappingData,
StudyDto studyDto,
UserDto userDto,
ActivityInstanceDto instanceDto,
AnswerDao answerDao) throws Exception {
LOG.info("Populating Medical Survey...");
if (surveyData == null || surveyData.isJsonNull()) {
LOG.warn("NO Medical Survey !");
return;
}
processSurveyData(handle, "medicalsurvey", surveyData, mappingData,
studyDto, userDto, instanceDto, answerDao);
}
public void loadTissueConsentSurveyData(Handle handle,
JsonElement surveyData,
JsonElement mappingData,
StudyDto studyDto,
UserDto userDto,
ActivityInstanceDto instanceDto,
AnswerDao answerDao) throws Exception {
LOG.info("Populating Tissue Consent Survey...");
if (surveyData == null || surveyData.isJsonNull()) {
LOG.warn("NO Tissue Consent Survey !");
return;
}
//for mbc tissueconsentsurvey data comes as consent
processSurveyData(handle, "consentsurvey", surveyData, mappingData,
studyDto, userDto, instanceDto, answerDao);
}
public void loadBloodConsentSurveyData(Handle handle,
JsonElement surveyData,
JsonElement mappingData,
StudyDto studyDto,
UserDto userDto,
ActivityInstanceDto instanceDto,
AnswerDao answerDao) throws Exception {
LOG.info("Populating Blood Consent Survey...");
if (surveyData == null || surveyData.isJsonNull()) {
LOG.warn("NO Blood Consent Survey !");
return;
}
processSurveyData(handle, "bdconsentsurvey", surveyData, mappingData,
studyDto, userDto, instanceDto, answerDao);
String street1 = getStringValueFromElement(surveyData, "street1");
String street2 = getStringValueFromElement(surveyData, "street2");
String city = getStringValueFromElement(surveyData, "city");
String postalCode = getStringValueFromElement(surveyData, "postal_code");
String state = getStringValueFromElement(surveyData, "state");
String phoneNumber = getStringValueFromElement(surveyData, "phone_number");
String bdConsentAddress =
Stream.of(street1, street2, city, state, postalCode)
.filter(s -> s != null && !s.isEmpty())
.collect(Collectors.joining(", "));
if (StringUtils.isNotBlank(bdConsentAddress)) {
answerTextQuestion("BLOODCONSENT_ADDRESS", userDto.getUserGuid(), instanceDto.getGuid(),
bdConsentAddress, answerDao);
}
if (StringUtils.isNotBlank(phoneNumber)) {
answerTextQuestion("BLOODCONSENT_PHONE", userDto.getUserGuid(), instanceDto.getGuid(),
phoneNumber, answerDao);
}
//addLegacySurveyAddress(handle, studyDto, userDto, instanceDto, surveyData, "bloodconsent");
}
public void loadFollowupSurveyData(Handle handle,
JsonElement surveyData,
JsonElement mappingData,
StudyDto studyDto,
UserDto userDto,
ActivityInstanceDto instanceDto,
JdbiActivityInstance activityInstanceDao,
AnswerDao answerDao) throws Exception {
LOG.info("Populating Followup Survey...");
if (surveyData == null || surveyData.isJsonNull()) {
LOG.warn("NO Followup Survey !");
return;
}
String status = getStringValueFromElement(surveyData, "survey_status");
if (status.equalsIgnoreCase("CREATED")) {
LOG.warn("Created followup survey instance but no data ");
return;
}
processSurveyData(handle, "followupsurvey", surveyData, mappingData,
studyDto, userDto, instanceDto, answerDao);
Integer dsmTriggerId = getIntegerValueFromElement(surveyData, "ddp_dsmtriggerid");
activityInstanceDao.updateOndemandTriggerId(userDto.getUserId(), instanceDto.getId(),
dsmTriggerId == null ? DSM_DEFAULT_ON_DEMAND_TRIGGER_ID : dsmTriggerId.intValue());
}
public void loadFollowupConsentSurveyData(Handle handle,
JsonElement surveyData,
JsonElement mappingData,
StudyDto studyDto,
UserDto userDto,
ActivityInstanceDto instanceDto,
JdbiActivityInstance activityInstanceDao,
AnswerDao answerDao) throws Exception {
LOG.info("Populating FollowupConsent Survey...");
if (surveyData == null || surveyData.isJsonNull()) {
LOG.warn("NO Followup Survey !");
return;
}
processSurveyData(handle, "followupconsentsurvey", surveyData, mappingData,
studyDto, userDto, instanceDto, answerDao);
Integer dsmTriggerId = getIntegerValueFromElement(surveyData, "ddp_dsmtriggerid");
activityInstanceDao.updateOndemandTriggerId(userDto.getUserId(), instanceDto.getId(),
dsmTriggerId == null ? DSM_DEFAULT_ON_DEMAND_TRIGGER_ID : dsmTriggerId.intValue());
}
public String answerDateQuestion(String pepperQuestionStableId, String participantGuid, String instanceGuid,
DateValue value, AnswerDao answerDao) {
Answer answer = new DateAnswer(null, pepperQuestionStableId, null, null, null, null);
if (value != null) {
answer = new DateAnswer(null, pepperQuestionStableId, null,
value.getYear(),
value.getMonth(),
value.getDay());
}
return answerDao.createAnswer(participantGuid, instanceGuid, answer).getAnswerGuid();
}
public String answerTextQuestion(String pepperQuestionStableId,
String participantGuid,
String instanceGuid,
String value, AnswerDao answerDao) {
String guid = null;
if (value != null) {
Answer answer = new TextAnswer(null, pepperQuestionStableId, null, value);
guid = answerDao.createAnswer(participantGuid, instanceGuid, answer).getAnswerGuid();
}
return guid;
}
public String answerBooleanQuestion(String pepperQuestionStableId,
String participantGuid,
String instanceGuid,
Boolean value, AnswerDao answerDao) throws Exception {
if (value != null) {
Answer answer = new BoolAnswer(null, pepperQuestionStableId, null, value);
return answerDao.createAnswer(participantGuid, instanceGuid, answer).getAnswerGuid();
}
return null;
}
public String answerAgreementQuestion(String pepperQuestionStableId,
String participantGuid,
String instanceGuid,
Boolean value, AnswerDao answerDao) throws Exception {
if (value != null) {
Answer answer = new AgreementAnswer(null, pepperQuestionStableId, null, value);
return answerDao.createAnswer(participantGuid, instanceGuid, answer).getAnswerGuid();
}
return null;
}
public String answerPickListQuestion(String questionStableId, String participantGuid, String instanceGuid,
List<SelectedPicklistOption> selectedPicklistOptions, AnswerDao answerDao) {
Answer answer = new PicklistAnswer(null, questionStableId, null, selectedPicklistOptions);
return answerDao.createAnswer(participantGuid, instanceGuid, answer).getAnswerGuid();
}
public String answerCompositeQuestion(Handle handle,
String pepperQuestionStableId,
String participantGuid,
String instanceGuid,
List<String> nestedGuids, List<Integer> compositeAnswerOrders, AnswerDao answerDao) {
Answer parentAnswer = answerDao.createAnswer(participantGuid, instanceGuid,
new CompositeAnswer(null, pepperQuestionStableId, null));
List<Long> childrenAnswerIds = new ArrayList<>();
var jdbiCompositeAnswer = handle.attach(JdbiCompositeAnswer.class);
if (CollectionUtils.isNotEmpty(nestedGuids)) {
for (String childGuid : nestedGuids) {
if (childGuid != null) {
childrenAnswerIds.add(answerDao.getAnswerSql().findDtoByGuid(childGuid).get().getId());
}
}
jdbiCompositeAnswer.insertChildAnswerItems(parentAnswer.getAnswerId(), childrenAnswerIds, compositeAnswerOrders);
}
return parentAnswer.getAnswerGuid();
}
public boolean isExistingAuth0User(JsonElement datStatData) throws Exception {
String emailAddress = datStatData.getAsJsonObject().get("datstat_email").getAsString();
List<User> auth0UsersByEmail = auth0Util.getAuth0UsersByEmail(emailAddress, mgmtToken);
return auth0UsersByEmail != null && auth0UsersByEmail.size() > 0;
}
public UserDto createLegacyPepperUser(JdbiUser userDao, JdbiClient clientDao,
JsonElement data, String userGuid, String userHruid, ClientDto clientDto,
boolean useExistingAuth0Users) throws Exception {
String emailAddress = data.getAsJsonObject().get("datstat_email").getAsString();
String userAction = "created";
User newAuth0User = null;
//If configured to use existing Auth0 users, first check to see if there's already an Auth0 user we should use
if (useExistingAuth0Users) {
List<User> auth0UsersByEmail = auth0Util.getAuth0UsersByEmail(emailAddress, mgmtToken);
if (auth0UsersByEmail != null && auth0UsersByEmail.size() > 0) {
userAction = "found";
newAuth0User = auth0UsersByEmail.get(0);
LOG.info("Using existing Auth0 user");
}
}
if (newAuth0User == null) {
// Create a user for the given domain
if (useExistingAuth0Users) {
LOG.info("User not found: creating with random password");
}
String randomPass = <PASSWORD>();
newAuth0User = auth0Util.createAuth0User(emailAddress, randomPass, mgmtToken);
}
String auth0UserId = newAuth0User.getId();
String userCreatedAt = getStringValueFromElement(data, "ddp_created");
LocalDateTime createdAtDate = LocalDateTime.parse(userCreatedAt, DateTimeFormatter.ofPattern(DATSTAT_DATE_FORMAT));
String lastModifiedStr = getStringValueFromElement(data, "ddp_last_updated");
LocalDateTime lastModifiedDate = createdAtDate;
if (lastModifiedStr != null && !lastModifiedStr.isEmpty()) {
lastModifiedDate = LocalDateTime.parse(lastModifiedStr);
}
long createdAtMillis = createdAtDate.toInstant(ZoneOffset.UTC).toEpochMilli();
long updatedAtMillis = lastModifiedDate.toInstant(ZoneOffset.UTC).toEpochMilli();
String shortId = data.getAsJsonObject().get("ddp_participant_shortid").getAsString();
String altpid = data.getAsJsonObject().get("datstat_altpid").getAsString();
long userId = userDao.insertMigrationUser(auth0UserId, userGuid, clientDto.getId(), userHruid,
altpid, shortId, createdAtMillis, updatedAtMillis);
UserDto newUser = new UserDto(userId, auth0UserId, userGuid, userHruid, altpid,
shortId, createdAtMillis, updatedAtMillis);
mgmtClient.setUserGuidForAuth0User(auth0UserId, clientDto.getAuth0ClientId(), newUser.getUserGuid());
LOG.info("User " + userAction + ": Auth0UserId = " + auth0UserId + ", GUID = " + userGuid + ", HRUID = " + userHruid
+ ", " + "ALTPID = " + altpid);
return newUser;
}
private String generateRandomPassword() {
Random rnd = new Random();
int passLength = 128;
StringBuilder stringBuilder = new StringBuilder(passLength);
IntStream.range(0, passLength)
.forEach(i -> stringBuilder.append(Character.toChars(rnd.nextInt(26) + 'a')));
stringBuilder.replace(50, 54, "91_A<");
return stringBuilder.toString();
}
UserProfile addUserProfile(UserDto user,
JsonElement data,
JdbiLanguageCode jdbiLanguageCode,
UserProfileDao profileDao) {
Boolean isDoNotContact = getBooleanValueFromElement(data, "ddp_do_not_contact");
Long languageCodeId = jdbiLanguageCode.getLanguageCodeId(DEFAULT_PREFERRED_LANGUAGE_CODE);
UserProfile profile = new UserProfile.Builder(user.getUserId())
.setFirstName(StringUtils.trim(data.getAsJsonObject().get("datstat_firstname").getAsString()))
.setLastName(StringUtils.trim(data.getAsJsonObject().get("datstat_lastname").getAsString()))
.setPreferredLangId(languageCodeId)
.setDoNotContact(isDoNotContact)
.build();
profileDao.createProfile(profile);
return profile;
}
MailAddress getUserAddress(Handle handle, JsonElement data,
String phoneNumber,
OLCService olcService, AddressService addressService) {
String street1 = getStringValueFromElement(data, "ddp_street1");
String street2 = getStringValueFromElement(data, "ddp_street2");
String city = getStringValueFromElement(data, "ddp_city");
String country = getStringValueFromElement(data, "ddp_country");
String postalCode = getStringValueFromElement(data, "ddp_postal_code");
String state = getStringValueFromElement(data, "ddp_state");
String firstName = getStringValueFromElement(data, "datstat_firstname");
String lastName = getStringValueFromElement(data, "datstat_lastname");
String fullName = firstName.trim().concat(" ").concat(lastName.trim());
if (StringUtils.isNotBlank(state) && StringUtils.isNotBlank(country)) {
String stateCode = getStateCode(handle, state, country);
if (StringUtils.isNotBlank(stateCode)) {
state = stateCode;
}
}
MailAddress mailAddress = new MailAddress(fullName,
street1, street2, city, state, country,
postalCode, phoneNumber, null, null, null, true);
//no addressvalid flag in MBC.
//if kit exists consider address as valid else validate address
String kitRequestId = getStringValueFromElement(data, "ddp_spit_kit_request_id");
if (StringUtils.isNotBlank(kitRequestId)) {
mailAddress.setValidationStatus(DsmAddressValidationStatus.DSM_VALID_ADDRESS_STATUS);
mailAddress.setPlusCode(olcService.calculatePlusCodeWithPrecision(mailAddress, OLCService.DEFAULT_OLC_PRECISION));
} else {
try {
mailAddress = addressService.verifyAddress(mailAddress);
mailAddress.setValidationStatus(DsmAddressValidationStatus.DSM_EASYPOST_SUGGESTED_ADDRESS_STATUS);
} catch (AddressVerificationException e) {
//LOG.warn("Exception while verifying address for user: {} error: {} ", user.getUserGuid(), e);
mailAddress.setValidationStatus(DsmAddressValidationStatus.DSM_INVALID_ADDRESS_STATUS);
}
}
return mailAddress;
}
MailAddress addUserAddress(Handle handle, UserDto user,
JsonElement data,
String phoneNumber, MailAddress mailAddress,
JdbiMailAddress jdbiMailAddress,
OLCService olcService, AddressService addressService) {
if (mailAddress == null) {
mailAddress = getUserAddress(handle, data, phoneNumber, olcService, addressService);
}
String ddpCreated = getStringValueFromElement(data, "ddp_created");
long ddpCreatedAt = Instant.now().getEpochSecond();
//use DDP_CREATED time for MailAddress creation time.
if (ddpCreated != null) {
Instant instant = Instant.parse(ddpCreated);
if (instant != null) {
ddpCreatedAt = instant.getEpochSecond();
}
}
MailAddress address = jdbiMailAddress.insertLegacyAddress(mailAddress, user.getUserGuid(), user.getUserGuid(), ddpCreatedAt);
jdbiMailAddress.setDefaultAddressForParticipant(address.getGuid());
LOG.info("Inserted address id: {}...createdTime: {}", address.getGuid(), ddpCreatedAt);
return mailAddress;
}
private String getStateCode(Handle handle, String ddpState, String ddpCountry) {
String stateCode = null;
JdbiCountrySubnationalDivision subnationDao = handle.attach(JdbiCountrySubnationalDivision.class);
List<String> stateCodeList = subnationDao.getStateCode(ddpState.trim());
if (stateCodeList.size() == 1) {
stateCode = stateCodeList.get(0);
} else if (stateCodeList.size() > 1) {
//search and narrow down by country
stateCode = subnationDao.getStateCode(ddpState.trim(), ddpCountry.trim());
}
return stateCode;
}
private BaseSurvey getBaseSurvey(JsonElement surveyData) {
Integer datstatSubmissionIdNum = getIntegerValueFromElement(surveyData, "datstat.submissionid");
Long datstatSubmissionId = null;
if (datstatSubmissionIdNum != null) {
datstatSubmissionId = datstatSubmissionIdNum.longValue();
}
String datstatSessionId = getStringValueFromElement(surveyData, "datstat.sessionid");
String ddpCreated = getStringValueFromElement(surveyData, "ddp_created");
String ddpFirstCompleted = getStringValueFromElement(surveyData, "ddp_firstcompleted");
String ddpLastSubmitted = getStringValueFromElement(surveyData, "ddp_lastsubmitted");
String ddpLastUpdated = getStringValueFromElement(surveyData, "ddp_lastupdated");
String surveyVersion = getStringValueFromElement(surveyData, "surveyversion");
String activityVersion = getStringValueFromElement(surveyData, "consent_version");
String surveyStatus = getStringValueFromElement(surveyData, "survey_status");
Integer datstatSubmissionStatus = getIntegerValueFromElement(surveyData, "datstat.submissionstatus");
if (ddpFirstCompleted == null) {
ddpFirstCompleted = ddpLastSubmitted;
}
BaseSurvey baseSurvey = new BaseSurvey(datstatSubmissionId, datstatSessionId, ddpCreated, ddpFirstCompleted,
ddpLastUpdated, surveyVersion, activityVersion, surveyStatus, datstatSubmissionStatus);
return baseSurvey;
}
private String getStringValueFromElement(JsonElement element, String key) {
String value = null;
JsonElement keyEl = element.getAsJsonObject().get(key);
if (keyEl != null && !keyEl.isJsonNull()) {
value = keyEl.getAsString();
}
return value;
}
private Boolean getBooleanValueFromElement(JsonElement element, String key) {
Boolean value = null;
JsonElement keyEl = element.getAsJsonObject().get(key);
if (keyEl != null && !keyEl.isJsonNull()) {
value = keyEl.getAsBoolean();
}
return value;
}
private Integer getIntegerValueFromElement(JsonElement element, String key) {
Integer value = null;
JsonElement keyEl = element.getAsJsonObject().get(key);
if (keyEl != null && !keyEl.isJsonNull()) {
value = keyEl.getAsInt();
}
return value;
}
Long addKitDetails(DsmKitRequestDao dsmKitRequestDao,
KitTypeDao kitTypeDao,
Long pepperUserId,
Long addressid,
String kitRequestId,
String studyGuid,
String defaultKitCreationDate) {
if (defaultKitCreationEpoch == null) {
ZoneId zoneId = ZoneId.of("UTC");
defaultKitCreationEpoch = LocalDate.parse(defaultKitCreationDate,
DateTimeFormatter.ofPattern("MM/dd/yyyy")).atStartOfDay(zoneId).toEpochSecond();
}
long kitTypeId = kitTypeDao.getSalivaKitType().getId();
long kitId = dsmKitRequestDao.createKitRequest(kitRequestId, studyGuid, addressid, kitTypeId,
pepperUserId, defaultKitCreationEpoch, false);
LOG.info("Created kit ID: " + kitId);
return kitId;
}
void addUserStudyExit(Handle handle, String ddpExited,
String participantGuid,
String studyGuid) {
LocalDateTime exitAt;
if (ddpExited != null && !ddpExited.isEmpty()) {
exitAt = LocalDateTime.parse(ddpExited, DateTimeFormatter.ofPattern(DATSTAT_DATE_FORMAT));
handle.attach(JdbiUserStudyEnrollment.class).terminateStudyEnrollment(participantGuid, studyGuid,
exitAt.toEpochSecond(ZoneOffset.UTC) * MILLIS_PER_SECOND);
}
}
private void processSurveyData(Handle handle, String surveyName, JsonElement sourceData, JsonElement mappingData, StudyDto studyDto,
UserDto userDto, ActivityInstanceDto instanceDto, AnswerDao answerDao) throws Exception {
//if survey is null.. just return
if (sourceData == null || sourceData.isJsonNull()) {
LOG.warn("no source data for survey: {}", surveyName);
return;
}
String participantGuid = userDto.getUserGuid();
String instanceGuid = instanceDto.getGuid();
sourceDataSurveyQs.put(surveyName, new ArrayList<>());
//iterate through mappingData and try to retrieve sourceData for each element
//iterate through each question_stable_mapping
JsonArray questionStableArray = mappingData.getAsJsonObject().getAsJsonArray("question_answer_stables");
for (JsonElement thisMap : questionStableArray) {
String questionName = getStringValueFromElement(thisMap, "name");
String questionType = getStringValueFromElement(thisMap, "type");
String stableId = getStringValueFromElement(thisMap, "stable_id");
if (StringUtils.isEmpty(stableId)) {
//non question-answer-stable elements.. continue to next element
sourceDataSurveyQs.get(surveyName).add(questionName);
continue;
}
//Now try to get source data for this question
//check type and act accordingly
switch (questionType) {
case "Date":
processDateQuestion(thisMap, sourceData, surveyName, participantGuid, instanceGuid, answerDao);
break;
case "string":
processTextQuestion(thisMap, sourceData, surveyName, participantGuid, instanceGuid, answerDao);
break;
case "Picklist":
processPicklistQuestion(thisMap, sourceData, surveyName, participantGuid, instanceGuid, answerDao);
break;
case "PicklistGroup":
processPicklistGroupQuestion(thisMap, sourceData, surveyName, participantGuid, instanceGuid, answerDao);
break;
//case "YesNoDkPicklist":
// processYesNoDkPicklistQuestion(handle, thisMap, sourceData, surveyName, participantGuid, instanceGuid, answerDao);
// break; //todo
case "Boolean":
processBooleanQuestion(thisMap, sourceData, surveyName, participantGuid, instanceGuid, answerDao);
break;
case "BooleanSpecialPL":
processBooleanSpecialPLQuestion(handle, thisMap, sourceData, surveyName, participantGuid, instanceGuid, answerDao);
break;
case "Agreement":
processAgreementQuestion(thisMap, sourceData, surveyName, participantGuid, instanceGuid, answerDao);
break;
case "Composite":
processCompositeQuestion(handle, thisMap, sourceData, surveyName,
participantGuid, instanceGuid, answerDao);
break;
case "CompositeMedList":
processMedListCompositeQuestion(handle, thisMap, sourceData, surveyName,
participantGuid, instanceGuid, answerDao);
break;
default:
LOG.warn(" Default .. Q name: {} .. type: {} ", questionName, questionType);
}
}
processLegacyFields(handle, sourceData, mappingData, studyDto.getId(), userDto.getUserId(), instanceDto.getId());
}
private void processLegacyFields(Handle handle, JsonElement sourceData, JsonElement mappingData,
long studyId, long participantId, Long instanceId) {
JsonElement legacyFieldsJsonEl = mappingData.getAsJsonObject().get("legacy_fields");
if (legacyFieldsJsonEl == null || legacyFieldsJsonEl.isJsonNull()) {
return;
}
JsonArray legacyFields = legacyFieldsJsonEl.getAsJsonArray();
for (JsonElement field : legacyFields) {
populateUserStudyLegacyData(handle, sourceData, field.getAsString(), studyId, participantId, instanceId);
}
}
private void populateUserStudyLegacyData(Handle handle, JsonElement sourceData, String fieldName,
long studyId, long participantId, Long instanceId) {
JsonElement valueEl = sourceData.getAsJsonObject().get(fieldName);
if (valueEl != null && !valueEl.isJsonNull() && StringUtils.isNotEmpty(valueEl.getAsString())) {
LOG.debug(" study: {} .. userguid: {} actinstanceguid: {} fieldName: {} fieldValue: {} ",
studyId, participantId, instanceId, fieldName, valueEl.getAsString());
handle.attach(JdbiUserStudyLegacyData.class).insert(participantId, studyId, instanceId,
fieldName, valueEl.getAsString());
}
}
private String processPicklistGroupQuestion(JsonElement mapElement, JsonElement sourceDataElement, String surveyName,
String participantGuid, String instanceGuid, AnswerDao answerDao) {
String answerGuid = null;
String stableId = getStringValueFromElement(mapElement, "stable_id");
if (mapElement.getAsJsonObject().get("groups") == null || mapElement.getAsJsonObject().get("groups").isJsonNull()) {
return null;
}
//iterate through groups
JsonArray groupEls = mapElement.getAsJsonObject().get("groups").getAsJsonArray();
List<SelectedPicklistOption> selectedPicklistOptions = new ArrayList<>();
for (JsonElement group: groupEls) {
String groupName = getStringValueFromElement(group, "name");
//get selected picklists options
selectedPicklistOptions.addAll(getSelectedPicklistOptions(group, sourceDataElement, groupName, surveyName));
}
if (CollectionUtils.isNotEmpty(selectedPicklistOptions)) {
answerGuid = answerPickListQuestion(stableId, participantGuid, instanceGuid, selectedPicklistOptions, answerDao);
}
return answerGuid;
}
private String processPicklistQuestion(JsonElement mapElement, JsonElement sourceDataElement, String surveyName,
String participantGuid, String instanceGuid, AnswerDao answerDao) {
String answerGuid = null;
String questionName = getStringValueFromElement(mapElement, "name");
String sourceType = getStringValueFromElement(mapElement, "source_type");
//handle options
String stableId = getStringValueFromElement(mapElement, "stable_id");
List<SelectedPicklistOption> selectedPicklistOptions = new ArrayList<>();
if (mapElement.getAsJsonObject().get("options") == null || mapElement.getAsJsonObject().get("options").isJsonNull()) {
//this will handle "country" : "US"
String value = getStringValueFromElement(sourceDataElement, questionName);
if (StringUtils.isNotEmpty(value)) {
selectedPicklistOptions.add(new SelectedPicklistOption(value));
}
sourceDataSurveyQs.get(surveyName).add(questionName);
} else if (StringUtils.isNotEmpty(sourceType)) {
//as of now only one data type integer other than string
switch (sourceType) {
case "string":
selectedPicklistOptions = getPicklistOptionsForSourceStrs(mapElement, sourceDataElement, questionName, surveyName);
break;
case "integer":
//"currently_medicated": 1 //0/1/2 for N/Y/Dk
selectedPicklistOptions = getPicklistOptionsForSourceNumbers(mapElement, sourceDataElement, questionName, surveyName);
break;
default:
LOG.warn("source type: {} not supported", sourceType, questionName);
}
} else {
selectedPicklistOptions = getSelectedPicklistOptions(mapElement, sourceDataElement, questionName, surveyName);
}
if (CollectionUtils.isNotEmpty(selectedPicklistOptions)) {
answerGuid = answerPickListQuestion(stableId, participantGuid, instanceGuid, selectedPicklistOptions, answerDao);
}
return answerGuid;
}
private List<SelectedPicklistOption> getPicklistOptionsForSourceNumbers(JsonElement mapElement, JsonElement sourceDataElement,
String questionName, String surveyName) {
List<SelectedPicklistOption> selectedPicklistOptions = new ArrayList<>();
JsonElement value = null;
sourceDataSurveyQs.get(surveyName).add(questionName);
if (sourceDataElement != null && !sourceDataElement.getAsJsonObject().get(questionName).isJsonNull()) {
value = sourceDataElement.getAsJsonObject().get(questionName);
}
if (value == null || value.isJsonNull()) {
return selectedPicklistOptions;
}
//Get the option value using either datStatEnumLookup or yesNoDkLookup
boolean foundValue = false;
String val = null;
if (("medicalsurvey".equals(surveyName) || "consentsurvey".equals(surveyName))
&& datStatEnumLookup.get(questionName) != null && datStatEnumLookup.get(questionName).get(value.getAsInt()) != null) {
foundValue = true;
val = datStatEnumLookup.get(questionName).get(value.getAsInt());
} else if (yesNoDkLookup.get(value.getAsInt()) != null) {
foundValue = true;
val = yesNoDkLookup.get(value.getAsInt());
}
//If we found the value, add a SelectedPicklistOption with the value to selectedPicklistOptions
if (foundValue) {
//Check for a specify field associated with the selected option
boolean foundSpecify = false;
JsonArray options = mapElement.getAsJsonObject().getAsJsonArray("options");
for (JsonElement option : options) {
JsonObject optionObject = option.getAsJsonObject();
JsonElement optionNameEl = optionObject.get("stable_id");
//Find out if this is the selected option
if (optionNameEl != null && optionNameEl.getAsString() != null
&& !optionNameEl.getAsString().isEmpty() && val.equals(optionNameEl.getAsString())) {
JsonElement specifyKeyElement = optionObject.get("text");
//If we find the specify field, set foundSpecify to true and include the specify value
if (specifyKeyElement != null && !specifyKeyElement.isJsonNull()
&& StringUtils.isNotEmpty(specifyKeyElement.getAsString())) {
foundSpecify = true;
String otherTextKey;
if ("medicalsurvey".equals(surveyName)) {
//For medical survey, text contains the full name of the key, so don't concatenate
otherTextKey = specifyKeyElement.getAsString();
} else {
//Otherwise, the name of the key is [optionName].[valueAssociatedWithTextInMapping]
otherTextKey = questionName + "." + optionNameEl.getAsString() + "." + specifyKeyElement.getAsString();
}
selectedPicklistOptions.add(new SelectedPicklistOption(val,
getStringValueFromElement(sourceDataElement, otherTextKey)));
}
//Now that we've found the selected option and checked for specify, done looking through options
break;
}
}
// If we didn't find a specify field, don't include one
if (!foundSpecify) {
selectedPicklistOptions.add(new SelectedPicklistOption(val));
}
}
return selectedPicklistOptions;
}
private List<SelectedPicklistOption> getPicklistOptionsForSourceStrs(JsonElement mapElement, JsonElement sourceDataElement,
String questionName, String surveyName) {
List<SelectedPicklistOption> selectedPicklistOptions = new ArrayList<>();
JsonElement value = null;
sourceDataSurveyQs.get(surveyName).add(questionName);
//check if source data does not have options. try for a match
if (sourceDataElement != null && !sourceDataElement.getAsJsonObject().get(questionName).isJsonNull()) {
value = sourceDataElement.getAsJsonObject().get(questionName);
}
if (value == null || value.isJsonNull()) {
return selectedPicklistOptions;
}
//RACE has multiple values selected.
//ex:- "American Indian or Native American, Japanese, Other, something else not on the list"
//"something else not on the list" is other text / other details.
//parse by `,` and check each value ..
String[] optValues = value.getAsString().split(",");
List<String> optValuesList = new ArrayList<>();
optValuesList.addAll(Arrays.asList(optValues));
optValuesList.replaceAll(String::trim);
List<String> pepperPLOptions = new ArrayList<>();
JsonArray options = mapElement.getAsJsonObject().getAsJsonArray("options");
for (JsonElement option : options) {
JsonObject optionObject = option.getAsJsonObject();
JsonElement optionNameEl = optionObject.get("name");
String optionName = optionNameEl.getAsString();
if (altNames.get(optionName) != null) {
optionName = altNames.get(optionName);
} else if (dkAltNames.get(optionName) != null) {
optionName = dkAltNames.get(optionName);
}
pepperPLOptions.add(optionName.toUpperCase());
final String optName = optionName;
if (optionName.equalsIgnoreCase(value.getAsString())
|| optValuesList.stream().anyMatch(x -> x.equalsIgnoreCase(optName))) {
//If specify text was exported as a separate key/value pair, make sure it gets passed through
if (optionObject.get("text") != null && ("medicalsurvey".equals(surveyName) || "consentsurvey".equals(surveyName))) {
String otherTextKey;
if ("medicalsurvey".equals(surveyName)) {
//For medical survey, text contains full name of key, so don't concatenate
otherTextKey = optionObject.get("text").getAsString();
} else {
//Otherwise, the name of the key is [optionName].[valueAssociatedWithTextInMapping]
otherTextKey = questionName.concat(".").concat(optionName).concat(".").concat(
optionObject.get("text").getAsString());
}
String otherText = getStringValueFromElement(sourceDataElement, otherTextKey);
selectedPicklistOptions.add(new SelectedPicklistOption(optionName.toUpperCase(), otherText));
} else if (!optionName.equalsIgnoreCase("Other")) {
selectedPicklistOptions.add(new SelectedPicklistOption(optionNameEl.getAsString().toUpperCase()));
} else {
//currently only RACE has Other however Gen2 MBC has other details without user selecting "Other"
//hence MBC Other is taken care below as special case..
//after MBC below code should help
//just select everything after Other (substr)
/*String sourceValue = value.getAsString();
String detailText = sourceValue.substring(sourceValue.lastIndexOf("Other") + 6);
selectedPicklistOptions.add(new SelectedPicklistOption(optionNameEl.getAsString().toUpperCase(), detailText));*/
}
}
}
if ("RACE".equalsIgnoreCase(questionName)) {
//Gen2 MBC has other details without user selecting "Other"
//handle others by adding everything that doesn't match pepper options
List<String> otherText = optValuesList.stream().filter(opt -> !pepperPLOptions.contains(opt.toUpperCase())).collect(toList());
otherText.remove("Other");
String otherDetails = otherText.stream().collect(Collectors.joining(","));
if (StringUtils.isNotBlank(otherDetails)) {
selectedPicklistOptions.add(new SelectedPicklistOption(OTHER, otherDetails));
} else if (optValuesList.contains("Other")) {
selectedPicklistOptions.add(new SelectedPicklistOption(OTHER));
}
}
return selectedPicklistOptions;
}
private List<SelectedPicklistOption> getSelectedPicklistOptions(JsonElement mapElement, JsonElement sourceDataElement,
String questionName, String surveyName) {
List<SelectedPicklistOption> selectedPicklistOptions = new ArrayList<>();
JsonArray options = mapElement.getAsJsonObject().getAsJsonArray("options");
for (JsonElement option : options) {
JsonElement value = null;
JsonElement optionName = option.getAsJsonObject().get("name");
String key;
String optName = null;
if (optionName != null && !optionName.isJsonNull()) {
optName = optionName.getAsString();
if (altNames.get(optName) != null) {
optName = altNames.get(optName);
}
key = questionName + "." + optName;
} else {
key = questionName;
}
JsonElement sourceDataOptEl = sourceDataElement.getAsJsonObject().get(key);
if (sourceDataOptEl != null && !sourceDataOptEl.isJsonNull()) {
value = sourceDataElement.getAsJsonObject().get(key);
sourceDataSurveyQs.get(surveyName).add(key);
}
if (value != null && value.getAsInt() == 1) { //option checked
if (option.getAsJsonObject().get("text") != null) {
//other text details
//For medical survey, the "text" attribute in the mapping contains the full name of the key
if ("medicalsurvey".equals(surveyName)) {
String otherTextKey = option.getAsJsonObject().get("text").getAsString();
String otherText = getStringValueFromElement(sourceDataElement, otherTextKey);
selectedPicklistOptions.add(new SelectedPicklistOption(optionName.getAsString().toUpperCase(), otherText));
} else { //Otherwise, append the "text" attribute value to the key of the question
String otherText = getTextDetails(sourceDataElement, option, key);
selectedPicklistOptions.add(new SelectedPicklistOption(optionName.getAsString().toUpperCase(), otherText));
}
} else {
selectedPicklistOptions.add(new SelectedPicklistOption(optionName.getAsString().toUpperCase()));
}
} else if ("Other".equalsIgnoreCase(optName) && option.getAsJsonObject().get("text") != null) {
//additional check to handle scenarios where:
//Other is NOT checked but other_text details are entered
String otherText = getTextDetails(sourceDataElement, option, key);
if (StringUtils.isNotBlank(otherText)) {
//other text details
selectedPicklistOptions.add(new SelectedPicklistOption(optionName.getAsString().toUpperCase(), otherText));
}
}
}
return selectedPicklistOptions;
}
private String getTextDetails(JsonElement sourceDataElement, JsonElement option, String key) {
String otherTextKey = key.concat(".").concat(option.getAsJsonObject().get("text").getAsString());
JsonElement otherTextEl = sourceDataElement.getAsJsonObject().get(otherTextKey);
String otherText = null;
if (otherTextEl != null && !otherTextEl.isJsonNull()) {
otherText = otherTextEl.getAsString();
}
return otherText;
}
private String processDateQuestion(JsonElement mapElement, JsonElement sourceDataElement, String surveyName,
String participantGuid, String instanceGuid, AnswerDao answerDao) throws Exception {
String answerGuid = null;
JsonElement valueEl;
String questionName = mapElement.getAsJsonObject().get("name").getAsString();
String stableId = getStringValueFromElement(mapElement, "stable_id");
LOG.info("Processing date question: " + questionName + " with stable_id " + stableId);
//check if question has subelements, nullable
if (mapElement.getAsJsonObject().get("subelements") == null) {
valueEl = sourceDataElement.getAsJsonObject().get(questionName);
String sourceType = getStringValueFromElement(mapElement, "source_type");
sourceDataSurveyQs.get(surveyName).add(questionName);
//todo.. revisit below to handle month/day in addition to year for future studies !!
if (valueEl != null && !valueEl.isJsonNull() && !StringUtils.isEmpty(valueEl.getAsString())) {
if (sourceType != null && sourceType.equals("string")) {
String valueStr = valueEl.getAsString();
int valueInt = Integer.parseInt(valueStr);
DateValue dateValue = new DateValue(valueInt, null, null);
answerGuid = answerDateQuestion(stableId, participantGuid, instanceGuid, dateValue, answerDao);
} else {
String dateFormat = mapElement.getAsJsonObject().get("format").getAsString();
DateValue dateValue = parseDate(valueEl.getAsString(), dateFormat);
answerGuid = answerDateQuestion(stableId, participantGuid, instanceGuid, dateValue, answerDao);
}
}
} else {
//handle subelements
JsonArray subelements = mapElement.getAsJsonObject().getAsJsonArray("subelements");
Map<String, JsonElement> dateSubelements = new HashMap<>();
for (JsonElement subelement : subelements) {
String subelementName = subelement.getAsJsonObject().get("name").getAsString();
String key = questionName + "_" + subelementName;
if (altNames.containsKey(key)) {
key = altNames.get(key);
}
valueEl = sourceDataElement.getAsJsonObject().get(key);
dateSubelements.put(subelementName, valueEl);
sourceDataSurveyQs.get(surveyName).add(key);
}
//build date
Integer year = null;
Integer month = null;
Integer day = null;
JsonElement yearEl = dateSubelements.get("year");
JsonElement monthEl = dateSubelements.get("month");
JsonElement dayEl = dateSubelements.get("day");
if (yearEl != null && !yearEl.isJsonNull() && !yearEl.getAsString().isEmpty()) {
year = yearEl.getAsInt();
}
if (monthEl != null && !monthEl.isJsonNull() && !monthEl.getAsString().isEmpty()) {
month = monthEl.getAsInt();
}
if (dayEl != null && !dayEl.isJsonNull() && !dayEl.getAsString().isEmpty()) {
day = dayEl.getAsInt();
}
DateValue dateValue = new DateValue(year, month, day);
answerGuid = answerDateQuestion(stableId, participantGuid, instanceGuid, dateValue, answerDao);
}
return answerGuid;
}
private String processTextQuestion(JsonElement mapElement, JsonElement sourceDataElement, String surveyName,
String participantGuid, String instanceGuid, AnswerDao answerDao) throws Exception {
String answerGuid = null;
JsonElement valueEl;
String questionName = mapElement.getAsJsonObject().get("name").getAsString();
valueEl = sourceDataElement.getAsJsonObject().get(questionName);
String stableId = getStringValueFromElement(mapElement, "stable_id");
LOG.info("Processing text question " + questionName + " with stable id " + stableId);
if (valueEl != null && !valueEl.isJsonNull()) {
answerGuid = answerTextQuestion(stableId, participantGuid, instanceGuid, valueEl.getAsString(), answerDao);
}
sourceDataSurveyQs.get(surveyName).add(questionName);
return answerGuid;
}
private String processAgreementQuestion(JsonElement mapElement, JsonElement sourceDataElement, String surveyName,
String participantGuid, String instanceGuid, AnswerDao answerDao) throws Exception {
String answerGuid;
String questionName = mapElement.getAsJsonObject().get("name").getAsString();
JsonElement valueEl = sourceDataElement.getAsJsonObject().get(questionName);
if (valueEl == null || valueEl.isJsonNull()) {
return null;
}
String stableId = getStringValueFromElement(mapElement, "stable_id");
LOG.info("Processing agreement question " + questionName + " with stable id " + stableId);
if (stableId == null) {
return null;
}
boolean agreed = valueEl.getAsBoolean();
String sourceType = getStringValueFromElement(mapElement, "source_type");
if (StringUtils.isNotBlank(sourceType) && sourceType.equalsIgnoreCase("integer")) {
agreed = (valueEl.getAsInt() == 1);
}
sourceDataSurveyQs.get(surveyName).add(questionName);
answerGuid = answerAgreementQuestion(stableId, participantGuid, instanceGuid, agreed, answerDao);
return answerGuid;
}
private String processCompositeQuestion(Handle handle, JsonElement mapElement, JsonElement sourceDataElement, String surveyName,
String participantGuid, String instanceGuid, AnswerDao answerDao) throws Exception {
String answerGuid = null;
String questionName = mapElement.getAsJsonObject().get("name").getAsString();
sourceDataSurveyQs.get(surveyName).add(questionName);
//handle composite options (nested answers)
String stableId = getStringValueFromElement(mapElement, "stable_id");
LOG.info("Processing composite question " + questionName + " with stable_id " + stableId);
//handle children/nestedQA
JsonArray children = mapElement.getAsJsonObject().getAsJsonArray("children");
List<String> nestedQAGuids = new ArrayList<>();
List<Integer> nestedAnsOrders = new ArrayList<>();
//todo.. This composite type does not handle array/list of answers. make it handle array for future study proof
for (JsonElement childEl : children) {
String childGuid = null;
if (childEl != null && !childEl.isJsonNull()) {
String nestedQuestionType = getStringValueFromElement(childEl, "type");
switch (nestedQuestionType) {
case "Date":
childGuid = processDateQuestion(childEl, sourceDataElement, surveyName, participantGuid,
instanceGuid, answerDao);
break;
case "string":
childGuid = processTextQuestion(childEl, sourceDataElement, surveyName,
participantGuid, instanceGuid, answerDao);
break;
case "Picklist":
childGuid = processPicklistQuestion(childEl, sourceDataElement, surveyName,
participantGuid, instanceGuid, answerDao);
break;
case "Boolean":
childGuid = processBooleanQuestion(childEl, sourceDataElement, surveyName,
participantGuid, instanceGuid, answerDao);
break;
case "BooleanSpecialPL":
childGuid = processBooleanSpecialPLQuestion(handle, childEl, sourceDataElement, surveyName,
participantGuid, instanceGuid, answerDao);
break;
case "Agreement":
childGuid = processAgreementQuestion(childEl, sourceDataElement, surveyName,
participantGuid, instanceGuid, answerDao);
break;
case "ClinicalTrialPicklist":
//todo .. revisit and make it generic
String childStableId = childEl.getAsJsonObject().get("stable_id").getAsString();
JsonElement thisDataArrayEl = sourceDataElement.getAsJsonObject().get(questionName);
if (thisDataArrayEl != null && !thisDataArrayEl.isJsonNull()) {
Boolean isClinicalTrial = getBooleanValueFromElement(thisDataArrayEl, "clinicaltrial");
if (isClinicalTrial) {
List<SelectedPicklistOption> selectedPicklistOptions = new ArrayList<>();
selectedPicklistOptions.add(new SelectedPicklistOption("IS_CLINICAL_TRIAL"));
childGuid = answerPickListQuestion(childStableId, participantGuid,
instanceGuid, selectedPicklistOptions, answerDao);
}
}
break;
default:
LOG.warn(" Default ..Composite nested Q name: {} .. type: {} not supported", questionName,
nestedQuestionType);
}
if (StringUtils.isNotBlank(childGuid)) {
nestedQAGuids.add(childGuid);
nestedAnsOrders.add(0);
}
}
}
if (CollectionUtils.isNotEmpty(nestedQAGuids)) {
answerGuid = answerCompositeQuestion(handle, stableId, participantGuid, instanceGuid,
nestedQAGuids, nestedAnsOrders, answerDao);
}
return answerGuid;
}
private String processMedListCompositeQuestion(Handle handle, JsonElement mapElement, JsonElement sourceDataElement, String surveyName,
String participantGuid, String instanceGuid, AnswerDao answerDao) throws Exception {
//todo .. with some work processCompositeQuestion can be used to handle this question.
//this handles composite question with list/array
String answerGuid = null;
String questionName = mapElement.getAsJsonObject().get("name").getAsString();
sourceDataSurveyQs.get(surveyName).add(questionName);
String stableId = null;
JsonElement stableIdElement = mapElement.getAsJsonObject().get("stable_id");
if (!stableIdElement.isJsonNull()) {
stableId = stableIdElement.getAsString();
}
//source data has array of composite data
JsonElement dataArrayEl = sourceDataElement.getAsJsonObject().get(questionName);
if (dataArrayEl != null && !dataArrayEl.isJsonNull()) {
int compositeAnswerOrder = -1;
List<String> nestedQAGuids = new ArrayList<>();
List<Integer> nestedAnsOrders = new ArrayList<>();
for (JsonElement thisDataEl : dataArrayEl.getAsJsonArray()) {
compositeAnswerOrder++;
//handle children/nestedQA
JsonArray children = mapElement.getAsJsonObject().getAsJsonArray("children");
for (JsonElement childEl : children) {
String childGuid = null;
if (childEl != null && !childEl.isJsonNull()) {
String nestedQuestionType = getStringValueFromElement(childEl, "type");
switch (nestedQuestionType) {
case "Date":
childGuid = processDateQuestion(childEl, thisDataEl, surveyName, participantGuid,
instanceGuid, answerDao);
break;
case "string":
childGuid = processTextQuestion(childEl, thisDataEl, surveyName,
participantGuid, instanceGuid, answerDao);
break;
case "Picklist":
childGuid = processPicklistQuestion(childEl, thisDataEl, surveyName,
participantGuid, instanceGuid, answerDao);
break;
case "Boolean":
childGuid = processBooleanQuestion(childEl, thisDataEl, surveyName,
participantGuid, instanceGuid, answerDao);
break;
case "Agreement":
childGuid = processAgreementQuestion(childEl, thisDataEl, surveyName,
participantGuid, instanceGuid, answerDao);
break;
case "ClinicalTrialPicklist":
//todo .. revisit and make it generic
String childStableId = childEl.getAsJsonObject().get("stable_id").getAsString();
Boolean isClinicalTrial = thisDataEl.getAsJsonObject().get("clinicaltrial").getAsBoolean();
if (isClinicalTrial) {
List<SelectedPicklistOption> selectedPicklistOptions = new ArrayList<>();
selectedPicklistOptions.add(new SelectedPicklistOption("IS_CLINICAL_TRIAL"));
childGuid = answerPickListQuestion(childStableId, participantGuid,
instanceGuid, selectedPicklistOptions, answerDao);
}
break;
default:
LOG.warn(" Default ..Composite nested Q name: {} .. type: {} ", questionName,
nestedQuestionType);
}
if (StringUtils.isNotBlank(childGuid)) {
nestedQAGuids.add(childGuid);
nestedAnsOrders.add(compositeAnswerOrder);
}
}
}
}
if (CollectionUtils.isNotEmpty(nestedQAGuids)) {
answerGuid = answerCompositeQuestion(handle, stableId, participantGuid, instanceGuid, nestedQAGuids,
nestedAnsOrders, answerDao);
}
}
return answerGuid;
}
private String processBooleanSpecialPLQuestion(Handle handle, JsonElement mapElement, JsonElement sourceDataElement, String surveyName,
String participantGuid, String instanceGuid, AnswerDao answerDao) throws Exception {
//in reality a Boolean question but ended up as a Picklist with just one option 'YES'
//reason: boolean question does not support rendering as a checkbox
//ex: "current_medication_names.dk": 0 ; "previous_medication_names.dk": 0,
String answerGuid = null;
String stableId = getStringValueFromElement(mapElement, "stable_id");
String questionName = mapElement.getAsJsonObject().get("name").getAsString();
LOG.info("Processing boolean special picklist question " + questionName + " with stable id " + stableId);
JsonElement valueEl = sourceDataElement.getAsJsonObject().get(questionName);
if (valueEl == null || valueEl.isJsonNull()) {
return null;
}
sourceDataSurveyQs.get(surveyName).add(questionName);
int valueInt = valueEl.getAsInt();
List<SelectedPicklistOption> selectedOptions = new ArrayList<>();
if (valueInt == 1) {
if (datStatEnumLookup.containsKey(questionName)) {
selectedOptions.add(new SelectedPicklistOption(datStatEnumLookup.get(questionName).get(1)));
} else {
selectedOptions.add(new SelectedPicklistOption("YES"));
}
}
//answerGuid = answerBooleanQuestion(handle, stableId, participantGuid, instanceGuid, value, answerDao);
answerGuid = answerPickListQuestion(stableId, participantGuid, instanceGuid, selectedOptions, answerDao);
return answerGuid;
}
private String processBooleanQuestion(JsonElement mapElement, JsonElement sourceDataElement, String surveyName,
String participantGuid, String instanceGuid, AnswerDao answerDao) throws Exception {
String answerGuid = null;
String stableId = getStringValueFromElement(mapElement, "stable_id");
String questionName = getStringValueFromElement(mapElement, "name");
LOG.info("Processing boolean question " + questionName + " with stable id " + stableId);
JsonElement valueEl = sourceDataElement.getAsJsonObject().get(questionName);
if (valueEl == null || valueEl.isJsonNull()) {
return null;
}
sourceDataSurveyQs.get(surveyName).add(questionName);
String sourceType = getStringValueFromElement(mapElement, "source_type");
Boolean value = null;
//below code needed to handle different variations of picklist boolean data
//#1: "clinicaltrial": false
//#2:"previous_medication_names.dk": 0,
if (StringUtils.isNotEmpty(sourceType)) {
//as of now only one data type integer other than string
if (sourceType.equals("integer")) {
value = booleanValueLookup.get(valueEl.getAsInt());
} else {
value = valueEl.getAsBoolean();
}
} else {
LOG.error("NO source type for Boolean Q: {} ", stableId);
}
answerGuid = answerBooleanQuestion(stableId, participantGuid, instanceGuid, value, answerDao);
return answerGuid;
}
private void processPhysicianList(Handle handle, JsonElement sourceDataElement,
UserDto userDto, StudyDto studyDto,
String elementName, InstitutionType type, String surveyName,
ActivityInstanceDto instanceDto) {
MedicalProviderDao medicalProviderDao = handle.attach(MedicalProviderDao.class);
sourceDataSurveyQs.get(surveyName).add(elementName);
JsonElement medicalProviderDataEl = sourceDataElement.getAsJsonObject().get(elementName);
if (medicalProviderDataEl == null || medicalProviderDataEl.isJsonNull()) {
return;
}
long institutionTypeId = handle.attach(JdbiInstitutionType.class).findByType(InstitutionType.PHYSICIAN);
List<MedicalProviderDto> dbPhysicianList = handle.attach(JdbiMedicalProvider.class)
.getAllByUserGuidStudyGuidAndInstitutionTypeId(userDto.getUserGuid(), studyDto.getGuid(), institutionTypeId);
JsonArray medicalProviderDataArray = medicalProviderDataEl.getAsJsonArray();
for (JsonElement physicianEl : medicalProviderDataArray) {
String physicianId = getStringValueFromElement(physicianEl, "physicianid");
String name = getStringValueFromElement(physicianEl, "name");
String institution = getStringValueFromElement(physicianEl, "institution");
String city = getStringValueFromElement(physicianEl, "city");
String state = getStringValueFromElement(physicianEl, "state");
String postalCode = getStringValueFromElement(physicianEl, "zipcode");
String phoneNumber = getStringValueFromElement(physicianEl, "phonenumber");
String streetAddress = getStringValueFromElement(physicianEl, "streetaddress");
//check if this physician already exists in DB.. probably populated by release survey for same ptp
List<MedicalProviderDto> matchedPhysicianList = dbPhysicianList.stream().filter(physician ->
(physician.getInstitutionName() != null && physician.getInstitutionName().equalsIgnoreCase(institution))
&& (physician.getPhysicianName() != null && physician.getPhysicianName().equalsIgnoreCase(name))
&& (physician.getCity() != null && physician.getCity().equalsIgnoreCase(city))
&& (physician.getState() != null && physician.getState().equalsIgnoreCase(state))
&& (physician.getPhone() != null && physician.getPhone().equalsIgnoreCase(phoneNumber))
&& (physician.getStreet() != null && physician.getStreet().equalsIgnoreCase(streetAddress)))
.collect(Collectors.toList());
if (matchedPhysicianList.isEmpty()) {
String guid = getMedicalProviderGuid(handle);
medicalProviderDao.insert(new MedicalProviderDto(
null,
guid,
userDto.getUserId(),
studyDto.getId(),
type,
institution,
name,
city,
state,
postalCode,
phoneNumber,
physicianId,
streetAddress
));
} else {
LOG.warn("skipping duplicate physician: {} for participant: {}", physicianId, userDto.getUserGuid());
}
}
}
private void addBiopsyInstitutions(Handle handle, JsonElement sourceDataElement, UserDto userDto, StudyDto studyDto) {
MedicalProviderDao medicalProviderDao = handle.attach(MedicalProviderDao.class);
//sourceDataSurveyQs.get("releasesurvey").add("initialbiopsy");
String instName = getStringValueFromElement(sourceDataElement, "initial_biopsy_institution");
String instCity = getStringValueFromElement(sourceDataElement, "initial_biopsy_city");
String instState = getStringValueFromElement(sourceDataElement, "initial_biopsy_state");
if (StringUtils.isNotBlank(instName)) {
String guid = getMedicalProviderGuid(handle);
medicalProviderDao.insert(new MedicalProviderDto(
null,
guid, userDto.getUserId(), studyDto.getId(),
InstitutionType.INITIAL_BIOPSY, instName, null, instCity, instState,
null, null, null, null));
}
}
private void processInstitutions(Handle handle, JsonElement sourceDataElement, UserDto userDto, StudyDto studyDto,
String elementName, InstitutionType type, String surveyName) {
MedicalProviderDao medicalProviderDao = handle.attach(MedicalProviderDao.class);
sourceDataSurveyQs.get(surveyName).add(elementName);
JsonElement medicalProviderDataEl = sourceDataElement.getAsJsonObject().get(elementName);
if (medicalProviderDataEl == null || medicalProviderDataEl.isJsonNull()) {
return;
}
JsonArray medicalProviderDataArray = medicalProviderDataEl.getAsJsonArray();
for (JsonElement physicianEl : medicalProviderDataArray) {
String physicianId = getStringValueFromElement(physicianEl, "physicianid");
String institutionId = getStringValueFromElement(physicianEl, "institutionid");
String name = getStringValueFromElement(physicianEl, "name");
String institution = getStringValueFromElement(physicianEl, "institution");
String city = getStringValueFromElement(physicianEl, "city");
String state = getStringValueFromElement(physicianEl, "state");
String postalCode = getStringValueFromElement(physicianEl, "zipcode");
String phoneNumber = getStringValueFromElement(physicianEl, "phonenumber");
String streetAddress = getStringValueFromElement(physicianEl, "streetaddress");
String guid = getMedicalProviderGuid(handle);
String legacyGuid;
if (InstitutionType.PHYSICIAN.equals(type)) {
legacyGuid = physicianId;
} else {
legacyGuid = institutionId;
}
medicalProviderDao.insert(new MedicalProviderDto(
null,
guid,
userDto.getUserId(),
studyDto.getId(),
type,
institution,
name,
city,
state,
postalCode,
phoneNumber,
legacyGuid,
streetAddress
));
}
}
public void verifySourceQsLookedAt(String surveyName, JsonElement sourceDataEl) {
List<String> mappingQuestions = sourceDataSurveyQs.get(surveyName);
List<String> exportDataQs = new ArrayList<>();
if (sourceDataEl == null || sourceDataEl.isJsonNull()) {
LOG.warn(" Survey : {} null ", surveyName);
return;
}
int actualQsCount = sourceDataEl.getAsJsonObject().entrySet().size();
Set<Map.Entry<String, JsonElement>> actualQs = sourceDataEl.getAsJsonObject().entrySet();
LOG.info("survey Name: {} .. Qs looked at count: {} ... Actual source Qs: {} ", surveyName,
mappingQuestions.size(), actualQsCount);
for (String question : mappingQuestions) {
LOG.debug(" Mapping Question: {} ", question);
}
for (Map.Entry<String, JsonElement> entry : actualQs) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
if (!mappingQuestions.contains(entry.getKey())) {
LOG.warn("*Question : \"{}\" missing from Mapping File", entry.getKey());
}
exportDataQs.add(entry.getKey());
}
for (String question : mappingQuestions) {
if (!exportDataQs.contains(question)) {
LOG.warn("*Mapping Question : \"{}\" not in source data ", question);
}
}
}
private DateValue parseDate(String dateValue, String fmt) throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat(fmt);
Date consentDOB = dateFormat.parse(dateValue);
GregorianCalendar gregorianCalendar = new GregorianCalendar();
gregorianCalendar.setTime(consentDOB);
return new DateValue(gregorianCalendar.get(Calendar.YEAR),
gregorianCalendar.get(Calendar.MONTH) + 1, // GregorianCalendar months are 0 indexed
gregorianCalendar.get(Calendar.DAY_OF_MONTH));
}
class UserExistsException extends Exception {
UserExistsException(String msg) {
super(msg);
}
}
}
|
peniakoff/commercetools-sync-java
|
src/main/java/com/commercetools/sync/commons/helpers/CustomReferenceResolver.java
|
package com.commercetools.sync.commons.helpers;
import static io.sphere.sdk.types.CustomFieldsDraft.ofTypeIdAndJson;
import static io.sphere.sdk.utils.CompletableFutureUtils.exceptionallyCompletedFuture;
import static java.lang.String.format;
import static java.util.concurrent.CompletableFuture.completedFuture;
import com.commercetools.sync.commons.BaseSyncOptions;
import com.commercetools.sync.commons.exceptions.ReferenceResolutionException;
import com.commercetools.sync.services.TypeService;
import com.fasterxml.jackson.databind.JsonNode;
import io.sphere.sdk.categories.CategoryDraft;
import io.sphere.sdk.models.Builder;
import io.sphere.sdk.models.ResourceIdentifier;
import io.sphere.sdk.types.CustomFieldsDraft;
import io.sphere.sdk.types.Type;
import java.util.Map;
import java.util.concurrent.CompletionStage;
import java.util.function.BiFunction;
import java.util.function.Function;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* This class is responsible for providing an abstract implementation of reference resolution on
* Custom CTP resources for example (Categories, inventories and resource with a custom field). For
* concrete reference resolution implementation of the CTP resources, this class should be extended.
*
* @param <D> the resource draft type for which reference resolution has to be done on.
* @param <B> the resource draft builder where resolved values should be set. The builder type
* should correspond the {@code D} type.
* @param <S> a subclass implementation of {@link BaseSyncOptions} that is used to allow/deny some
* specific options, specified by the user, on reference resolution.
*/
public abstract class CustomReferenceResolver<
D, B extends Builder<? extends D>, S extends BaseSyncOptions>
extends BaseReferenceResolver<D, S> {
public static final String TYPE_DOES_NOT_EXIST = "Type with key '%s' doesn't exist.";
private final TypeService typeService;
protected CustomReferenceResolver(
@Nonnull final S options, @Nonnull final TypeService typeService) {
super(options);
this.typeService = typeService;
}
/**
* Given a draft of {@code D} (e.g. {@link CategoryDraft}) this method attempts to resolve it's
* custom type reference to return {@link CompletionStage} which contains a new instance of the
* draft with the resolved custom type reference.
*
* <p>The method then tries to fetch the key of the custom type, optimistically from a cache. If
* the key is is not found, the resultant draft would remain exactly the same as the passed draft
* (without a custom type reference resolution).
*
* @param draftBuilder the draft builder to resolve it's references.
* @return a {@link CompletionStage} that contains as a result a new draft instance with resolved
* custom type references or, in case an error occurs during reference resolution, a {@link
* ReferenceResolutionException}.
*/
protected abstract CompletionStage<B> resolveCustomTypeReference(@Nonnull B draftBuilder);
/**
* Given a draft of {@code D} (e.g. {@link CategoryDraft}) this method attempts to resolve it's
* custom type reference to return {@link CompletionStage} which contains a new instance of the
* draft with the resolved custom type reference.
*
* <p>The method then tries to fetch the key of the custom type, optimistically from a cache. If
* the key is is not found, the resultant draft would remain exactly the same as the passed draft
* (without a custom type reference resolution).
*
* <p>Note: If the id field is set, then it is an evidence of resource existence on commercetools,
* so we can issue an update/create API request right away without reference resolution.
*
* @param draftBuilder the draft builder to resolve it's references.
* @param customGetter a function to return the CustomFieldsDraft instance of the draft builder.
* @param customSetter a function to set the CustomFieldsDraft instance of the builder and return
* this builder.
* @param errorMessage the error message to inject in the {@link ReferenceResolutionException} if
* it occurs.
* @return a {@link CompletionStage} that contains as a result a new draft instance with resolved
* custom type references or, in case an error occurs during reference resolution, a {@link
* ReferenceResolutionException}.
*/
@Nonnull
protected CompletionStage<B> resolveCustomTypeReference(
@Nonnull final B draftBuilder,
@Nonnull final Function<B, CustomFieldsDraft> customGetter,
@Nonnull final BiFunction<B, CustomFieldsDraft, B> customSetter,
@Nonnull final String errorMessage) {
final CustomFieldsDraft custom = customGetter.apply(draftBuilder);
if (custom != null) {
final ResourceIdentifier<Type> customType = custom.getType();
if (customType.getId() == null) {
String customTypeKey;
try {
customTypeKey = getCustomTypeKey(customType, errorMessage);
} catch (ReferenceResolutionException referenceResolutionException) {
return exceptionallyCompletedFuture(referenceResolutionException);
}
return fetchAndResolveTypeReference(
draftBuilder, customSetter, custom.getFields(), customTypeKey, errorMessage);
}
}
return completedFuture(draftBuilder);
}
/**
* Given a custom fields object this method fetches the custom type reference id.
*
* @param customType the custom fields' Type.
* @param referenceResolutionErrorMessage the message containing the information about the draft
* to attach to the {@link ReferenceResolutionException} in case it occurs.
* @return a {@link CompletionStage} that contains as a result an optional which either contains
* the custom type id if it exists or empty if it doesn't.
*/
private String getCustomTypeKey(
@Nonnull final ResourceIdentifier<Type> customType,
@Nonnull final String referenceResolutionErrorMessage)
throws ReferenceResolutionException {
try {
return getKeyFromResourceIdentifier(customType);
} catch (ReferenceResolutionException exception) {
final String errorMessage =
format("%s Reason: %s", referenceResolutionErrorMessage, exception.getMessage());
throw new ReferenceResolutionException(errorMessage, exception);
}
}
@Nonnull
private CompletionStage<B> fetchAndResolveTypeReference(
@Nonnull final B draftBuilder,
@Nonnull final BiFunction<B, CustomFieldsDraft, B> customSetter,
@Nullable final Map<String, JsonNode> customFields,
@Nonnull final String typeKey,
@Nonnull final String referenceResolutionErrorMessage) {
return typeService
.fetchCachedTypeId(typeKey)
.thenCompose(
resolvedTypeIdOptional ->
resolvedTypeIdOptional
.map(
resolvedTypeId ->
completedFuture(
customSetter.apply(
draftBuilder, ofTypeIdAndJson(resolvedTypeId, customFields))))
.orElseGet(
() -> {
final String errorMessage =
format(
"%s Reason: %s",
referenceResolutionErrorMessage,
format(TYPE_DOES_NOT_EXIST, typeKey));
return exceptionallyCompletedFuture(
new ReferenceResolutionException(errorMessage));
}));
}
}
|
zhouchong90/OpenStudio
|
openstudiocore/src/model/PumpVariableSpeed.cpp
|
<reponame>zhouchong90/OpenStudio
/**********************************************************************
* Copyright (c) 2008-2014, Alliance for Sustainable Energy.
* All rights reserved.
*
* 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 Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#include "PumpVariableSpeed.hpp"
#include "PumpVariableSpeed_Impl.hpp"
#include "Schedule.hpp"
#include "Schedule_Impl.hpp"
#include "Node.hpp"
#include "Node_Impl.hpp"
#include "Curve.hpp"
#include "Curve_Impl.hpp"
#include "CurveLinear.hpp"
#include "CurveLinear_Impl.hpp"
#include "CurveQuadratic.hpp"
#include "CurveQuadratic_Impl.hpp"
#include "CurveCubic.hpp"
#include "CurveCubic_Impl.hpp"
#include "CurveQuartic.hpp"
#include "CurveQuartic_Impl.hpp"
#include <utilities/idd/IddFactory.hxx>
#include <utilities/idd/OS_Pump_VariableSpeed_FieldEnums.hxx>
#include "../utilities/core/Assert.hpp"
namespace openstudio {
namespace model {
namespace detail {
PumpVariableSpeed_Impl::PumpVariableSpeed_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle)
: StraightComponent_Impl(idfObject,model,keepHandle)
{
OS_ASSERT(idfObject.iddObject().type() == PumpVariableSpeed::iddObjectType());
}
PumpVariableSpeed_Impl::PumpVariableSpeed_Impl(const openstudio::detail::WorkspaceObject_Impl& other,
Model_Impl* model,
bool keepHandle)
: StraightComponent_Impl(other,model,keepHandle)
{
OS_ASSERT(other.iddObject().type() == PumpVariableSpeed::iddObjectType());
}
PumpVariableSpeed_Impl::PumpVariableSpeed_Impl(const PumpVariableSpeed_Impl& other,
Model_Impl* model,
bool keepHandle)
: StraightComponent_Impl(other,model,keepHandle)
{}
const std::vector<std::string>& PumpVariableSpeed_Impl::outputVariableNames() const
{
static std::vector<std::string> result;
if (result.empty()){
}
return result;
}
std::vector<ScheduleTypeKey> PumpVariableSpeed_Impl::getScheduleTypeKeys(const Schedule& schedule) const
{
std::vector<ScheduleTypeKey> result;
UnsignedVector fieldIndices = getSourceIndices(schedule.handle());
UnsignedVector::const_iterator b(fieldIndices.begin()), e(fieldIndices.end());
if (std::find(b,e,OS_Pump_VariableSpeedFields::PumpFlowRateScheduleName) != e)
{
result.push_back(ScheduleTypeKey("PumpVariableSpeed","Pump Flow Rate"));
}
if (std::find(b,e,OS_Pump_VariableSpeedFields::PumprpmScheduleName) != e)
{
result.push_back(ScheduleTypeKey("PumpVariableSpeed","Pump RPM"));
}
if (std::find(b,e,OS_Pump_VariableSpeedFields::MinimumPressureSchedule) != e)
{
result.push_back(ScheduleTypeKey("PumpVariableSpeed","Minimum Pressure"));
}
if (std::find(b,e,OS_Pump_VariableSpeedFields::MaximumPressureSchedule) != e)
{
result.push_back(ScheduleTypeKey("PumpVariableSpeed","Maximum Pressure"));
}
if (std::find(b,e,OS_Pump_VariableSpeedFields::MinimumRPMSchedule) != e)
{
result.push_back(ScheduleTypeKey("PumpVariableSpeed","Minimum RPM"));
}
if (std::find(b,e,OS_Pump_VariableSpeedFields::MaximumRPMSchedule) != e)
{
result.push_back(ScheduleTypeKey("PumpVariableSpeed","Maximum RPM"));
}
return result;
}
IddObjectType PumpVariableSpeed_Impl::iddObjectType() const {
return PumpVariableSpeed::iddObjectType();
}
std::vector<ModelObject> PumpVariableSpeed_Impl::children() const {
ModelObjectVector result;
if (OptionalCurve curve = pumpCurve()) {
result.push_back(*curve);
}
return result;
}
unsigned PumpVariableSpeed_Impl::inletPort()
{
return OS_Pump_VariableSpeedFields::InletNodeName;
}
unsigned PumpVariableSpeed_Impl::outletPort()
{
return OS_Pump_VariableSpeedFields::OutletNodeName;
}
boost::optional<double> PumpVariableSpeed_Impl::ratedFlowRate() const {
return getDouble(OS_Pump_VariableSpeedFields::RatedFlowRate,true);
}
OSOptionalQuantity PumpVariableSpeed_Impl::getRatedFlowRate(bool returnIP) const {
OptionalDouble value = ratedFlowRate();
return getQuantityFromDouble(OS_Pump_VariableSpeedFields::RatedFlowRate, value, returnIP);
}
bool PumpVariableSpeed_Impl::isRatedFlowRateDefaulted() const {
return isEmpty(OS_Pump_VariableSpeedFields::RatedFlowRate);
}
bool PumpVariableSpeed_Impl::isRatedFlowRateAutosized() const {
bool result = false;
boost::optional<std::string> value = getString(OS_Pump_VariableSpeedFields::RatedFlowRate, true);
if (value) {
result = openstudio::istringEqual(value.get(), "autosize");
}
return result;
}
double PumpVariableSpeed_Impl::ratedPumpHead() const {
boost::optional<double> value = getDouble(OS_Pump_VariableSpeedFields::RatedPumpHead,true);
OS_ASSERT(value);
return value.get();
}
Quantity PumpVariableSpeed_Impl::getRatedPumpHead(bool returnIP) const {
OptionalDouble value = ratedPumpHead();
OSOptionalQuantity result = getQuantityFromDouble(OS_Pump_VariableSpeedFields::RatedPumpHead, value, returnIP);
OS_ASSERT(result.isSet());
return result.get();
}
bool PumpVariableSpeed_Impl::isRatedPumpHeadDefaulted() const {
return isEmpty(OS_Pump_VariableSpeedFields::RatedPumpHead);
}
boost::optional<double> PumpVariableSpeed_Impl::ratedPowerConsumption() const {
return getDouble(OS_Pump_VariableSpeedFields::RatedPowerConsumption,true);
}
OSOptionalQuantity PumpVariableSpeed_Impl::getRatedPowerConsumption(bool returnIP) const {
OptionalDouble value = ratedPowerConsumption();
return getQuantityFromDouble(OS_Pump_VariableSpeedFields::RatedPowerConsumption, value, returnIP);
}
bool PumpVariableSpeed_Impl::isRatedPowerConsumptionDefaulted() const {
return isEmpty(OS_Pump_VariableSpeedFields::RatedPowerConsumption);
}
bool PumpVariableSpeed_Impl::isRatedPowerConsumptionAutosized() const {
bool result = false;
boost::optional<std::string> value = getString(OS_Pump_VariableSpeedFields::RatedPowerConsumption, true);
if (value) {
result = openstudio::istringEqual(value.get(), "autosize");
}
return result;
}
double PumpVariableSpeed_Impl::motorEfficiency() const {
boost::optional<double> value = getDouble(OS_Pump_VariableSpeedFields::MotorEfficiency,true);
OS_ASSERT(value);
return value.get();
}
Quantity PumpVariableSpeed_Impl::getMotorEfficiency(bool returnIP) const {
OptionalDouble value = motorEfficiency();
OSOptionalQuantity result = getQuantityFromDouble(OS_Pump_VariableSpeedFields::MotorEfficiency, value, returnIP);
OS_ASSERT(result.isSet());
return result.get();
}
bool PumpVariableSpeed_Impl::isMotorEfficiencyDefaulted() const {
return isEmpty(OS_Pump_VariableSpeedFields::MotorEfficiency);
}
double PumpVariableSpeed_Impl::fractionofMotorInefficienciestoFluidStream() const {
boost::optional<double> value = getDouble(OS_Pump_VariableSpeedFields::FractionofMotorInefficienciestoFluidStream,true);
OS_ASSERT(value);
return value.get();
}
Quantity PumpVariableSpeed_Impl::getFractionofMotorInefficienciestoFluidStream(bool returnIP) const {
OptionalDouble value = fractionofMotorInefficienciestoFluidStream();
OSOptionalQuantity result = getQuantityFromDouble(OS_Pump_VariableSpeedFields::FractionofMotorInefficienciestoFluidStream, value, returnIP);
OS_ASSERT(result.isSet());
return result.get();
}
bool PumpVariableSpeed_Impl::isFractionofMotorInefficienciestoFluidStreamDefaulted() const {
return isEmpty(OS_Pump_VariableSpeedFields::FractionofMotorInefficienciestoFluidStream);
}
double PumpVariableSpeed_Impl::coefficient1ofthePartLoadPerformanceCurve() const {
boost::optional<double> value = getDouble(OS_Pump_VariableSpeedFields::Coefficient1ofthePartLoadPerformanceCurve,true);
OS_ASSERT(value);
return value.get();
}
Quantity PumpVariableSpeed_Impl::getCoefficient1ofthePartLoadPerformanceCurve(bool returnIP) const {
OptionalDouble value = coefficient1ofthePartLoadPerformanceCurve();
OSOptionalQuantity result = getQuantityFromDouble(OS_Pump_VariableSpeedFields::Coefficient1ofthePartLoadPerformanceCurve, value, returnIP);
OS_ASSERT(result.isSet());
return result.get();
}
bool PumpVariableSpeed_Impl::isCoefficient1ofthePartLoadPerformanceCurveDefaulted() const {
return isEmpty(OS_Pump_VariableSpeedFields::Coefficient1ofthePartLoadPerformanceCurve);
}
double PumpVariableSpeed_Impl::coefficient2ofthePartLoadPerformanceCurve() const {
boost::optional<double> value = getDouble(OS_Pump_VariableSpeedFields::Coefficient2ofthePartLoadPerformanceCurve,true);
OS_ASSERT(value);
return value.get();
}
Quantity PumpVariableSpeed_Impl::getCoefficient2ofthePartLoadPerformanceCurve(bool returnIP) const {
OptionalDouble value = coefficient2ofthePartLoadPerformanceCurve();
OSOptionalQuantity result = getQuantityFromDouble(OS_Pump_VariableSpeedFields::Coefficient2ofthePartLoadPerformanceCurve, value, returnIP);
OS_ASSERT(result.isSet());
return result.get();
}
bool PumpVariableSpeed_Impl::isCoefficient2ofthePartLoadPerformanceCurveDefaulted() const {
return isEmpty(OS_Pump_VariableSpeedFields::Coefficient2ofthePartLoadPerformanceCurve);
}
double PumpVariableSpeed_Impl::coefficient3ofthePartLoadPerformanceCurve() const {
boost::optional<double> value = getDouble(OS_Pump_VariableSpeedFields::Coefficient3ofthePartLoadPerformanceCurve,true);
OS_ASSERT(value);
return value.get();
}
Quantity PumpVariableSpeed_Impl::getCoefficient3ofthePartLoadPerformanceCurve(bool returnIP) const {
OptionalDouble value = coefficient3ofthePartLoadPerformanceCurve();
OSOptionalQuantity result = getQuantityFromDouble(OS_Pump_VariableSpeedFields::Coefficient3ofthePartLoadPerformanceCurve, value, returnIP);
OS_ASSERT(result.isSet());
return result.get();
}
bool PumpVariableSpeed_Impl::isCoefficient3ofthePartLoadPerformanceCurveDefaulted() const {
return isEmpty(OS_Pump_VariableSpeedFields::Coefficient3ofthePartLoadPerformanceCurve);
}
double PumpVariableSpeed_Impl::coefficient4ofthePartLoadPerformanceCurve() const {
boost::optional<double> value = getDouble(OS_Pump_VariableSpeedFields::Coefficient4ofthePartLoadPerformanceCurve,true);
OS_ASSERT(value);
return value.get();
}
Quantity PumpVariableSpeed_Impl::getCoefficient4ofthePartLoadPerformanceCurve(bool returnIP) const {
OptionalDouble value = coefficient4ofthePartLoadPerformanceCurve();
OSOptionalQuantity result = getQuantityFromDouble(OS_Pump_VariableSpeedFields::Coefficient4ofthePartLoadPerformanceCurve, value, returnIP);
OS_ASSERT(result.isSet());
return result.get();
}
bool PumpVariableSpeed_Impl::isCoefficient4ofthePartLoadPerformanceCurveDefaulted() const {
return isEmpty(OS_Pump_VariableSpeedFields::Coefficient4ofthePartLoadPerformanceCurve);
}
double PumpVariableSpeed_Impl::minimumFlowRate() const {
boost::optional<double> value = getDouble(OS_Pump_VariableSpeedFields::MinimumFlowRate,true);
OS_ASSERT(value);
return value.get();
}
Quantity PumpVariableSpeed_Impl::getMinimumFlowRate(bool returnIP) const {
OptionalDouble value = minimumFlowRate();
OSOptionalQuantity result = getQuantityFromDouble(OS_Pump_VariableSpeedFields::MinimumFlowRate, value, returnIP);
OS_ASSERT(result.isSet());
return result.get();
}
bool PumpVariableSpeed_Impl::isMinimumFlowRateDefaulted() const {
return isEmpty(OS_Pump_VariableSpeedFields::MinimumFlowRate);
}
std::string PumpVariableSpeed_Impl::pumpControlType() const {
boost::optional<std::string> value = getString(OS_Pump_VariableSpeedFields::PumpControlType,true);
OS_ASSERT(value);
return value.get();
}
bool PumpVariableSpeed_Impl::isPumpControlTypeDefaulted() const {
return isEmpty(OS_Pump_VariableSpeedFields::PumpControlType);
}
boost::optional<Schedule> PumpVariableSpeed_Impl::pumpFlowRateSchedule() const {
return getObject<ModelObject>().getModelObjectTarget<Schedule>(OS_Pump_VariableSpeedFields::PumpFlowRateScheduleName);
}
boost::optional<Curve> PumpVariableSpeed_Impl::pumpCurve() const {
return getObject<PumpVariableSpeed>().getModelObjectTarget<Curve>(OS_Pump_VariableSpeedFields::PumpCurveName);
}
boost::optional<double> PumpVariableSpeed_Impl::impellerDiameter() const {
return getDouble(OS_Pump_VariableSpeedFields::ImpellerDiameter,true);
}
OSOptionalQuantity PumpVariableSpeed_Impl::getImpellerDiameter(bool returnIP) const {
OptionalDouble value = impellerDiameter();
return getQuantityFromDouble(OS_Pump_VariableSpeedFields::ImpellerDiameter, value, returnIP);
}
boost::optional<std::string> PumpVariableSpeed_Impl::vFDControlType() const {
return getString(OS_Pump_VariableSpeedFields::VFDControlType,true);
}
boost::optional<Schedule> PumpVariableSpeed_Impl::pumpRPMSchedule() const {
return getObject<PumpVariableSpeed>().getModelObjectTarget<Schedule>(OS_Pump_VariableSpeedFields::PumprpmScheduleName);
}
boost::optional<Schedule> PumpVariableSpeed_Impl::minimumPressureSchedule() const {
return getObject<PumpVariableSpeed>().getModelObjectTarget<Schedule>(OS_Pump_VariableSpeedFields::MinimumPressureSchedule);
}
boost::optional<Schedule> PumpVariableSpeed_Impl::maximumPressureSchedule() const {
return getObject<PumpVariableSpeed>().getModelObjectTarget<Schedule>(OS_Pump_VariableSpeedFields::MaximumPressureSchedule);
}
boost::optional<Schedule> PumpVariableSpeed_Impl::minimumRPMSchedule() const {
return getObject<PumpVariableSpeed>().getModelObjectTarget<Schedule>(OS_Pump_VariableSpeedFields::MinimumRPMSchedule);
}
boost::optional<Schedule> PumpVariableSpeed_Impl::maximumRPMSchedule() const {
return getObject<PumpVariableSpeed>().getModelObjectTarget<Schedule>(OS_Pump_VariableSpeedFields::MaximumRPMSchedule);
}
void PumpVariableSpeed_Impl::setRatedFlowRate(boost::optional<double> ratedFlowRate) {
bool result(false);
if (ratedFlowRate) {
result = setDouble(OS_Pump_VariableSpeedFields::RatedFlowRate, ratedFlowRate.get());
}
else {
resetRatedFlowRate();
result = true;
}
OS_ASSERT(result);
}
bool PumpVariableSpeed_Impl::setRatedFlowRate(const OSOptionalQuantity& ratedFlowRate) {
bool result(false);
OptionalDouble value;
if (ratedFlowRate.isSet()) {
value = getDoubleFromQuantity(OS_Pump_VariableSpeedFields::RatedFlowRate,ratedFlowRate.get());
if (value) {
setRatedFlowRate(value);
result = true;
}
}
else {
setRatedFlowRate(value);
result = true;
}
return result;
}
void PumpVariableSpeed_Impl::resetRatedFlowRate() {
bool result = setString(OS_Pump_VariableSpeedFields::RatedFlowRate, "");
OS_ASSERT(result);
}
void PumpVariableSpeed_Impl::autosizeRatedFlowRate() {
bool result = setString(OS_Pump_VariableSpeedFields::RatedFlowRate, "autosize");
OS_ASSERT(result);
}
void PumpVariableSpeed_Impl::setRatedPumpHead(double ratedPumpHead) {
bool result = setDouble(OS_Pump_VariableSpeedFields::RatedPumpHead, ratedPumpHead);
OS_ASSERT(result);
}
bool PumpVariableSpeed_Impl::setRatedPumpHead(const Quantity& ratedPumpHead) {
OptionalDouble value = getDoubleFromQuantity(OS_Pump_VariableSpeedFields::RatedPumpHead,ratedPumpHead);
if (!value) {
return false;
}
setRatedPumpHead(value.get());
return true;
}
void PumpVariableSpeed_Impl::resetRatedPumpHead() {
bool result = setString(OS_Pump_VariableSpeedFields::RatedPumpHead, "");
OS_ASSERT(result);
}
void PumpVariableSpeed_Impl::setRatedPowerConsumption(boost::optional<double> ratedPowerConsumption) {
bool result(false);
if (ratedPowerConsumption) {
result = setDouble(OS_Pump_VariableSpeedFields::RatedPowerConsumption, ratedPowerConsumption.get());
}
else {
resetRatedPowerConsumption();
result = true;
}
OS_ASSERT(result);
}
bool PumpVariableSpeed_Impl::setRatedPowerConsumption(const OSOptionalQuantity& ratedPowerConsumption) {
bool result(false);
OptionalDouble value;
if (ratedPowerConsumption.isSet()) {
value = getDoubleFromQuantity(OS_Pump_VariableSpeedFields::RatedPowerConsumption,ratedPowerConsumption.get());
if (value) {
setRatedPowerConsumption(value);
result = true;
}
}
else {
setRatedPowerConsumption(value);
result = true;
}
return result;
}
void PumpVariableSpeed_Impl::resetRatedPowerConsumption() {
bool result = setString(OS_Pump_VariableSpeedFields::RatedPowerConsumption, "");
OS_ASSERT(result);
}
void PumpVariableSpeed_Impl::autosizeRatedPowerConsumption() {
bool result = setString(OS_Pump_VariableSpeedFields::RatedPowerConsumption, "autosize");
OS_ASSERT(result);
}
bool PumpVariableSpeed_Impl::setMotorEfficiency(double motorEfficiency) {
bool result = setDouble(OS_Pump_VariableSpeedFields::MotorEfficiency, motorEfficiency);
return result;
}
bool PumpVariableSpeed_Impl::setMotorEfficiency(const Quantity& motorEfficiency) {
OptionalDouble value = getDoubleFromQuantity(OS_Pump_VariableSpeedFields::MotorEfficiency,motorEfficiency);
if (!value) {
return false;
}
return setMotorEfficiency(value.get());
}
void PumpVariableSpeed_Impl::resetMotorEfficiency() {
bool result = setString(OS_Pump_VariableSpeedFields::MotorEfficiency, "");
OS_ASSERT(result);
}
bool PumpVariableSpeed_Impl::setFractionofMotorInefficienciestoFluidStream(double fractionofMotorInefficienciestoFluidStream) {
bool result = setDouble(OS_Pump_VariableSpeedFields::FractionofMotorInefficienciestoFluidStream, fractionofMotorInefficienciestoFluidStream);
return result;
}
bool PumpVariableSpeed_Impl::setFractionofMotorInefficienciestoFluidStream(const Quantity& fractionofMotorInefficienciestoFluidStream) {
OptionalDouble value = getDoubleFromQuantity(OS_Pump_VariableSpeedFields::FractionofMotorInefficienciestoFluidStream,fractionofMotorInefficienciestoFluidStream);
if (!value) {
return false;
}
return setFractionofMotorInefficienciestoFluidStream(value.get());
}
void PumpVariableSpeed_Impl::resetFractionofMotorInefficienciestoFluidStream() {
bool result = setString(OS_Pump_VariableSpeedFields::FractionofMotorInefficienciestoFluidStream, "");
OS_ASSERT(result);
}
void PumpVariableSpeed_Impl::setCoefficient1ofthePartLoadPerformanceCurve(double coefficient1ofthePartLoadPerformanceCurve) {
bool result = setDouble(OS_Pump_VariableSpeedFields::Coefficient1ofthePartLoadPerformanceCurve, coefficient1ofthePartLoadPerformanceCurve);
OS_ASSERT(result);
}
bool PumpVariableSpeed_Impl::setCoefficient1ofthePartLoadPerformanceCurve(const Quantity& coefficient1ofthePartLoadPerformanceCurve) {
OptionalDouble value = getDoubleFromQuantity(OS_Pump_VariableSpeedFields::Coefficient1ofthePartLoadPerformanceCurve,coefficient1ofthePartLoadPerformanceCurve);
if (!value) {
return false;
}
setCoefficient1ofthePartLoadPerformanceCurve(value.get());
return true;
}
void PumpVariableSpeed_Impl::resetCoefficient1ofthePartLoadPerformanceCurve() {
bool result = setString(OS_Pump_VariableSpeedFields::Coefficient1ofthePartLoadPerformanceCurve, "");
OS_ASSERT(result);
}
void PumpVariableSpeed_Impl::setCoefficient2ofthePartLoadPerformanceCurve(double coefficient2ofthePartLoadPerformanceCurve) {
bool result = setDouble(OS_Pump_VariableSpeedFields::Coefficient2ofthePartLoadPerformanceCurve, coefficient2ofthePartLoadPerformanceCurve);
OS_ASSERT(result);
}
bool PumpVariableSpeed_Impl::setCoefficient2ofthePartLoadPerformanceCurve(const Quantity& coefficient2ofthePartLoadPerformanceCurve) {
OptionalDouble value = getDoubleFromQuantity(OS_Pump_VariableSpeedFields::Coefficient2ofthePartLoadPerformanceCurve,coefficient2ofthePartLoadPerformanceCurve);
if (!value) {
return false;
}
setCoefficient2ofthePartLoadPerformanceCurve(value.get());
return true;
}
void PumpVariableSpeed_Impl::resetCoefficient2ofthePartLoadPerformanceCurve() {
bool result = setString(OS_Pump_VariableSpeedFields::Coefficient2ofthePartLoadPerformanceCurve, "");
OS_ASSERT(result);
}
void PumpVariableSpeed_Impl::setCoefficient3ofthePartLoadPerformanceCurve(double coefficient3ofthePartLoadPerformanceCurve) {
bool result = setDouble(OS_Pump_VariableSpeedFields::Coefficient3ofthePartLoadPerformanceCurve, coefficient3ofthePartLoadPerformanceCurve);
OS_ASSERT(result);
}
bool PumpVariableSpeed_Impl::setCoefficient3ofthePartLoadPerformanceCurve(const Quantity& coefficient3ofthePartLoadPerformanceCurve) {
OptionalDouble value = getDoubleFromQuantity(OS_Pump_VariableSpeedFields::Coefficient3ofthePartLoadPerformanceCurve,coefficient3ofthePartLoadPerformanceCurve);
if (!value) {
return false;
}
setCoefficient3ofthePartLoadPerformanceCurve(value.get());
return true;
}
void PumpVariableSpeed_Impl::resetCoefficient3ofthePartLoadPerformanceCurve() {
bool result = setString(OS_Pump_VariableSpeedFields::Coefficient3ofthePartLoadPerformanceCurve, "");
OS_ASSERT(result);
}
void PumpVariableSpeed_Impl::setCoefficient4ofthePartLoadPerformanceCurve(double coefficient4ofthePartLoadPerformanceCurve) {
bool result = setDouble(OS_Pump_VariableSpeedFields::Coefficient4ofthePartLoadPerformanceCurve, coefficient4ofthePartLoadPerformanceCurve);
OS_ASSERT(result);
}
bool PumpVariableSpeed_Impl::setCoefficient4ofthePartLoadPerformanceCurve(const Quantity& coefficient4ofthePartLoadPerformanceCurve) {
OptionalDouble value = getDoubleFromQuantity(OS_Pump_VariableSpeedFields::Coefficient4ofthePartLoadPerformanceCurve,coefficient4ofthePartLoadPerformanceCurve);
if (!value) {
return false;
}
setCoefficient4ofthePartLoadPerformanceCurve(value.get());
return true;
}
void PumpVariableSpeed_Impl::resetCoefficient4ofthePartLoadPerformanceCurve() {
bool result = setString(OS_Pump_VariableSpeedFields::Coefficient4ofthePartLoadPerformanceCurve, "");
OS_ASSERT(result);
}
void PumpVariableSpeed_Impl::setMinimumFlowRate(double minimumFlowRate) {
bool result = setDouble(OS_Pump_VariableSpeedFields::MinimumFlowRate, minimumFlowRate);
OS_ASSERT(result);
}
bool PumpVariableSpeed_Impl::setMinimumFlowRate(const Quantity& minimumFlowRate) {
OptionalDouble value = getDoubleFromQuantity(OS_Pump_VariableSpeedFields::MinimumFlowRate,minimumFlowRate);
if (!value) {
return false;
}
setMinimumFlowRate(value.get());
return true;
}
void PumpVariableSpeed_Impl::resetMinimumFlowRate() {
bool result = setString(OS_Pump_VariableSpeedFields::MinimumFlowRate, "");
OS_ASSERT(result);
}
bool PumpVariableSpeed_Impl::setPumpControlType(std::string pumpControlType) {
bool result = setString(OS_Pump_VariableSpeedFields::PumpControlType, pumpControlType);
return result;
}
void PumpVariableSpeed_Impl::resetPumpControlType() {
bool result = setString(OS_Pump_VariableSpeedFields::PumpControlType, "");
OS_ASSERT(result);
}
bool PumpVariableSpeed_Impl::setPumpFlowRateSchedule(Schedule& schedule) {
bool result = setSchedule(OS_Pump_VariableSpeedFields::PumpFlowRateScheduleName,
"PumpVariableSpeed",
"Pump Flow Rate",
schedule);
return result;
}
void PumpVariableSpeed_Impl::resetPumpFlowRateSchedule() {
bool result = setString(OS_Pump_VariableSpeedFields::PumpFlowRateScheduleName, "");
OS_ASSERT(result);
}
bool PumpVariableSpeed_Impl::setPumpCurve(const Curve& curve) {
if (curve.optionalCast<CurveLinear>() ||
curve.optionalCast<CurveQuadratic>() ||
curve.optionalCast<CurveCubic>() ||
curve.optionalCast<CurveQuartic>())
{
Curve wcurve = curve;
if (wcurve.parent()) {
wcurve = curve.clone().cast<Curve>();
}
bool ok = setPointer(OS_Pump_VariableSpeedFields::PumpCurveName,wcurve.handle());
OS_ASSERT(ok);
return true;
}
return false;
}
void PumpVariableSpeed_Impl::resetPumpCurve() {
bool ok = setString(OS_Pump_VariableSpeedFields::PumpCurveName,"");
OS_ASSERT(ok);
}
void PumpVariableSpeed_Impl::setImpellerDiameter(boost::optional<double> impellerDiameter) {
bool result(false);
if (impellerDiameter) {
result = setDouble(OS_Pump_VariableSpeedFields::ImpellerDiameter, impellerDiameter.get());
}
else {
resetImpellerDiameter();
result = true;
}
OS_ASSERT(result);
}
bool PumpVariableSpeed_Impl::setImpellerDiameter(const OSOptionalQuantity& impellerDiameter) {
bool result(false);
OptionalDouble value;
if (impellerDiameter.isSet()) {
value = getDoubleFromQuantity(OS_Pump_VariableSpeedFields::ImpellerDiameter,impellerDiameter.get());
if (value) {
setImpellerDiameter(value);
result = true;
}
}
else {
setImpellerDiameter(value);
result = true;
}
return result;
}
void PumpVariableSpeed_Impl::resetImpellerDiameter() {
bool result = setString(OS_Pump_VariableSpeedFields::ImpellerDiameter, "");
OS_ASSERT(result);
}
bool PumpVariableSpeed_Impl::setVFDControlType(boost::optional<std::string> vFDControlType) {
bool result(false);
if (vFDControlType) {
result = setString(OS_Pump_VariableSpeedFields::VFDControlType, vFDControlType.get());
}
else {
resetVFDControlType();
result = true;
}
return result;
}
void PumpVariableSpeed_Impl::resetVFDControlType() {
bool result = setString(OS_Pump_VariableSpeedFields::VFDControlType, "");
OS_ASSERT(result);
}
bool PumpVariableSpeed_Impl::setPumpRPMSchedule(Schedule& schedule) {
bool result = setSchedule(OS_Pump_VariableSpeedFields::PumprpmScheduleName,
"PumpVariableSpeed",
"Pump RPM",
schedule);
return result;
}
void PumpVariableSpeed_Impl::resetPumpRPMSchedule() {
bool result = setString(OS_Pump_VariableSpeedFields::PumprpmScheduleName, "");
OS_ASSERT(result);
}
bool PumpVariableSpeed_Impl::setMinimumPressureSchedule(Schedule& schedule) {
bool result = setSchedule(OS_Pump_VariableSpeedFields::MinimumPressureSchedule,
"PumpVariableSpeed",
"Minimum Pressure",
schedule);
return result;
}
void PumpVariableSpeed_Impl::resetMinimumPressureSchedule() {
bool result = setString(OS_Pump_VariableSpeedFields::MinimumPressureSchedule, "");
OS_ASSERT(result);
}
bool PumpVariableSpeed_Impl::setMaximumPressureSchedule(Schedule& schedule) {
bool result = setSchedule(OS_Pump_VariableSpeedFields::MaximumPressureSchedule,
"PumpVariableSpeed",
"Maximum Pressure",
schedule);
return result;
}
void PumpVariableSpeed_Impl::resetMaximumPressureSchedule() {
bool result = setString(OS_Pump_VariableSpeedFields::MaximumPressureSchedule, "");
OS_ASSERT(result);
}
bool PumpVariableSpeed_Impl::setMinimumRPMSchedule(Schedule& schedule) {
bool result = setSchedule(OS_Pump_VariableSpeedFields::MinimumRPMSchedule,
"PumpVariableSpeed",
"Minimum RPM",
schedule);
return result;
}
void PumpVariableSpeed_Impl::resetMinimumRPMSchedule() {
bool result = setString(OS_Pump_VariableSpeedFields::MinimumRPMSchedule, "");
OS_ASSERT(result);
}
bool PumpVariableSpeed_Impl::setMaximumRPMSchedule(Schedule& schedule) {
bool result = setSchedule(OS_Pump_VariableSpeedFields::MaximumRPMSchedule,
"PumpVariableSpeed",
"Maximum RPM",
schedule);
return result;
}
void PumpVariableSpeed_Impl::resetMaximumRPMSchedule() {
bool result = setString(OS_Pump_VariableSpeedFields::MaximumRPMSchedule, "");
OS_ASSERT(result);
}
bool PumpVariableSpeed_Impl::addToNode(Node & node)
{
if( boost::optional<PlantLoop> plant = node.plantLoop() )
{
return StraightComponent_Impl::addToNode(node);
}
return false;
}
openstudio::OSOptionalQuantity PumpVariableSpeed_Impl::ratedFlowRate_SI() const {
return getRatedFlowRate(false);
}
openstudio::OSOptionalQuantity PumpVariableSpeed_Impl::ratedFlowRate_IP() const {
return getRatedFlowRate(true);
}
openstudio::Quantity PumpVariableSpeed_Impl::ratedPumpHead_SI() const {
return getRatedPumpHead(false);
}
openstudio::Quantity PumpVariableSpeed_Impl::ratedPumpHead_IP() const {
return getRatedPumpHead(true);
}
openstudio::OSOptionalQuantity PumpVariableSpeed_Impl::ratedPowerConsumption_SI() const {
return getRatedPowerConsumption(false);
}
openstudio::OSOptionalQuantity PumpVariableSpeed_Impl::ratedPowerConsumption_IP() const {
return getRatedPowerConsumption(true);
}
openstudio::Quantity PumpVariableSpeed_Impl::motorEfficiency_SI() const {
return getMotorEfficiency(false);
}
openstudio::Quantity PumpVariableSpeed_Impl::motorEfficiency_IP() const {
return getMotorEfficiency(true);
}
openstudio::Quantity PumpVariableSpeed_Impl::fractionofMotorInefficienciestoFluidStream_SI() const {
return getFractionofMotorInefficienciestoFluidStream(false);
}
openstudio::Quantity PumpVariableSpeed_Impl::fractionofMotorInefficienciestoFluidStream_IP() const {
return getFractionofMotorInefficienciestoFluidStream(true);
}
openstudio::Quantity PumpVariableSpeed_Impl::coefficient1ofthePartLoadPerformanceCurve_SI() const {
return getCoefficient1ofthePartLoadPerformanceCurve(false);
}
openstudio::Quantity PumpVariableSpeed_Impl::coefficient1ofthePartLoadPerformanceCurve_IP() const {
return getCoefficient1ofthePartLoadPerformanceCurve(true);
}
openstudio::Quantity PumpVariableSpeed_Impl::coefficient2ofthePartLoadPerformanceCurve_SI() const {
return getCoefficient2ofthePartLoadPerformanceCurve(false);
}
openstudio::Quantity PumpVariableSpeed_Impl::coefficient2ofthePartLoadPerformanceCurve_IP() const {
return getCoefficient2ofthePartLoadPerformanceCurve(true);
}
openstudio::Quantity PumpVariableSpeed_Impl::coefficient3ofthePartLoadPerformanceCurve_SI() const {
return getCoefficient3ofthePartLoadPerformanceCurve(false);
}
openstudio::Quantity PumpVariableSpeed_Impl::coefficient3ofthePartLoadPerformanceCurve_IP() const {
return getCoefficient3ofthePartLoadPerformanceCurve(true);
}
openstudio::Quantity PumpVariableSpeed_Impl::coefficient4ofthePartLoadPerformanceCurve_SI() const {
return getCoefficient4ofthePartLoadPerformanceCurve(false);
}
openstudio::Quantity PumpVariableSpeed_Impl::coefficient4ofthePartLoadPerformanceCurve_IP() const {
return getCoefficient4ofthePartLoadPerformanceCurve(true);
}
openstudio::Quantity PumpVariableSpeed_Impl::minimumFlowRate_SI() const {
return getMinimumFlowRate(false);
}
openstudio::Quantity PumpVariableSpeed_Impl::minimumFlowRate_IP() const {
return getMinimumFlowRate(true);
}
std::vector<std::string> PumpVariableSpeed_Impl::pumpControlTypeValues() const {
return PumpVariableSpeed::pumpControlTypeValues();
}
openstudio::OSOptionalQuantity PumpVariableSpeed_Impl::impellerDiameter_SI() const {
return getImpellerDiameter(false);
}
openstudio::OSOptionalQuantity PumpVariableSpeed_Impl::impellerDiameter_IP() const {
return getImpellerDiameter(true);
}
std::vector<std::string> PumpVariableSpeed_Impl::vfdControlTypeValues() const {
return PumpVariableSpeed::vfdControlTypeValues();
}
boost::optional<ModelObject> PumpVariableSpeed_Impl::pumpFlowRateScheduleAsModelObject() const {
OptionalModelObject result;
OptionalSchedule intermediate = pumpFlowRateSchedule();
if (intermediate) {
result = *intermediate;
}
return result;
}
boost::optional<ModelObject> PumpVariableSpeed_Impl::pumpCurveAsModelObject() const {
OptionalModelObject result;
OptionalCurve intermediate = pumpCurve();
if (intermediate) {
result = *intermediate;
}
return result;
}
boost::optional<ModelObject> PumpVariableSpeed_Impl::pumpRPMScheduleAsModelObject() const {
OptionalModelObject result;
OptionalSchedule intermediate = pumpRPMSchedule();
if (intermediate) {
result = *intermediate;
}
return result;
}
boost::optional<ModelObject> PumpVariableSpeed_Impl::minimumPressureScheduleAsModelObject() const {
OptionalModelObject result;
OptionalSchedule intermediate = minimumPressureSchedule();
if (intermediate) {
result = *intermediate;
}
return result;
}
boost::optional<ModelObject> PumpVariableSpeed_Impl::maximumPressureScheduleAsModelObject() const {
OptionalModelObject result;
OptionalSchedule intermediate = maximumPressureSchedule();
if (intermediate) {
result = *intermediate;
}
return result;
}
boost::optional<ModelObject> PumpVariableSpeed_Impl::minimumRPMScheduleAsModelObject() const {
OptionalModelObject result;
OptionalSchedule intermediate = minimumRPMSchedule();
if (intermediate) {
result = *intermediate;
}
return result;
}
boost::optional<ModelObject> PumpVariableSpeed_Impl::maximumRPMScheduleAsModelObject() const {
OptionalModelObject result;
OptionalSchedule intermediate = maximumRPMSchedule();
if (intermediate) {
result = *intermediate;
}
return result;
}
bool PumpVariableSpeed_Impl::setPumpFlowRateScheduleAsModelObject(const boost::optional<ModelObject>& modelObject) {
if (modelObject) {
OptionalSchedule intermediate = modelObject->optionalCast<Schedule>();
if (intermediate) {
Schedule schedule(*intermediate);
return setPumpFlowRateSchedule(schedule);
}
else {
return false;
}
}
else {
resetPumpFlowRateSchedule();
}
return true;
}
bool PumpVariableSpeed_Impl::setPumpCurveAsModelObject(const boost::optional<ModelObject>& modelObject) {
if (modelObject) {
OptionalCurve intermediate = modelObject->optionalCast<Curve>();
if (intermediate) {
return setPumpCurve(*intermediate);
}
else {
return false;
}
}
else {
resetPumpCurve();
}
return true;
}
bool PumpVariableSpeed_Impl::setPumpRPMScheduleAsModelObject(const boost::optional<ModelObject>& modelObject) {
if (modelObject) {
OptionalSchedule intermediate = modelObject->optionalCast<Schedule>();
if (intermediate) {
Schedule schedule(*intermediate);
return setPumpRPMSchedule(schedule);
}
else {
return false;
}
}
else {
resetPumpRPMSchedule();
}
return true;
}
bool PumpVariableSpeed_Impl::setMinimumPressureScheduleAsModelObject(const boost::optional<ModelObject>& modelObject) {
if (modelObject) {
OptionalSchedule intermediate = modelObject->optionalCast<Schedule>();
if (intermediate) {
Schedule schedule(*intermediate);
return setMinimumPressureSchedule(schedule);
}
else {
return false;
}
}
else {
resetMinimumPressureSchedule();
}
return true;
}
bool PumpVariableSpeed_Impl::setMaximumPressureScheduleAsModelObject(const boost::optional<ModelObject>& modelObject) {
if (modelObject) {
OptionalSchedule intermediate = modelObject->optionalCast<Schedule>();
if (intermediate) {
Schedule schedule(*intermediate);
return setMaximumPressureSchedule(schedule);
}
else {
return false;
}
}
else {
resetMaximumPressureSchedule();
}
return true;
}
bool PumpVariableSpeed_Impl::setMinimumRPMScheduleAsModelObject(const boost::optional<ModelObject>& modelObject) {
if (modelObject) {
OptionalSchedule intermediate = modelObject->optionalCast<Schedule>();
if (intermediate) {
Schedule schedule(*intermediate);
return setMinimumRPMSchedule(schedule);
}
else {
return false;
}
}
else {
resetMinimumRPMSchedule();
}
return true;
}
bool PumpVariableSpeed_Impl::setMaximumRPMScheduleAsModelObject(const boost::optional<ModelObject>& modelObject) {
if (modelObject) {
OptionalSchedule intermediate = modelObject->optionalCast<Schedule>();
if (intermediate) {
Schedule schedule(*intermediate);
return setMaximumRPMSchedule(schedule);
}
else {
return false;
}
}
else {
resetMaximumRPMSchedule();
}
return true;
}
} // detail
PumpVariableSpeed::PumpVariableSpeed(const Model& model)
: StraightComponent(PumpVariableSpeed::iddObjectType(),model)
{
OS_ASSERT(getImpl<detail::PumpVariableSpeed_Impl>());
setPumpControlType("Intermittent");
}
IddObjectType PumpVariableSpeed::iddObjectType() {
IddObjectType result(IddObjectType::OS_Pump_VariableSpeed);
return result;
}
std::vector<std::string> PumpVariableSpeed::pumpControlTypeValues() {
return getIddKeyNames(IddFactory::instance().getObject(iddObjectType()).get(),
OS_Pump_VariableSpeedFields::PumpControlType);
}
std::vector<std::string> PumpVariableSpeed::validPumpControlTypeValues() {
return PumpVariableSpeed::pumpControlTypeValues();
}
std::vector<std::string> PumpVariableSpeed::vfdControlTypeValues() {
return getIddKeyNames(IddFactory::instance().getObject(iddObjectType()).get(),
OS_Pump_VariableSpeedFields::VFDControlType);
}
boost::optional<double> PumpVariableSpeed::ratedFlowRate() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->ratedFlowRate();
}
OSOptionalQuantity PumpVariableSpeed::getRatedFlowRate(bool returnIP) const {
return getImpl<detail::PumpVariableSpeed_Impl>()->getRatedFlowRate(returnIP);
}
bool PumpVariableSpeed::isRatedFlowRateDefaulted() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->isRatedFlowRateDefaulted();
}
bool PumpVariableSpeed::isRatedFlowRateAutosized() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->isRatedFlowRateAutosized();
}
double PumpVariableSpeed::ratedPumpHead() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->ratedPumpHead();
}
Quantity PumpVariableSpeed::getRatedPumpHead(bool returnIP) const {
return getImpl<detail::PumpVariableSpeed_Impl>()->getRatedPumpHead(returnIP);
}
bool PumpVariableSpeed::isRatedPumpHeadDefaulted() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->isRatedPumpHeadDefaulted();
}
boost::optional<double> PumpVariableSpeed::ratedPowerConsumption() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->ratedPowerConsumption();
}
OSOptionalQuantity PumpVariableSpeed::getRatedPowerConsumption(bool returnIP) const {
return getImpl<detail::PumpVariableSpeed_Impl>()->getRatedPowerConsumption(returnIP);
}
bool PumpVariableSpeed::isRatedPowerConsumptionDefaulted() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->isRatedPowerConsumptionDefaulted();
}
bool PumpVariableSpeed::isRatedPowerConsumptionAutosized() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->isRatedPowerConsumptionAutosized();
}
double PumpVariableSpeed::motorEfficiency() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->motorEfficiency();
}
Quantity PumpVariableSpeed::getMotorEfficiency(bool returnIP) const {
return getImpl<detail::PumpVariableSpeed_Impl>()->getMotorEfficiency(returnIP);
}
bool PumpVariableSpeed::isMotorEfficiencyDefaulted() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->isMotorEfficiencyDefaulted();
}
double PumpVariableSpeed::fractionofMotorInefficienciestoFluidStream() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->fractionofMotorInefficienciestoFluidStream();
}
Quantity PumpVariableSpeed::getFractionofMotorInefficienciestoFluidStream(bool returnIP) const {
return getImpl<detail::PumpVariableSpeed_Impl>()->getFractionofMotorInefficienciestoFluidStream(returnIP);
}
bool PumpVariableSpeed::isFractionofMotorInefficienciestoFluidStreamDefaulted() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->isFractionofMotorInefficienciestoFluidStreamDefaulted();
}
double PumpVariableSpeed::coefficient1ofthePartLoadPerformanceCurve() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->coefficient1ofthePartLoadPerformanceCurve();
}
Quantity PumpVariableSpeed::getCoefficient1ofthePartLoadPerformanceCurve(bool returnIP) const {
return getImpl<detail::PumpVariableSpeed_Impl>()->getCoefficient1ofthePartLoadPerformanceCurve(returnIP);
}
bool PumpVariableSpeed::isCoefficient1ofthePartLoadPerformanceCurveDefaulted() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->isCoefficient1ofthePartLoadPerformanceCurveDefaulted();
}
double PumpVariableSpeed::coefficient2ofthePartLoadPerformanceCurve() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->coefficient2ofthePartLoadPerformanceCurve();
}
Quantity PumpVariableSpeed::getCoefficient2ofthePartLoadPerformanceCurve(bool returnIP) const {
return getImpl<detail::PumpVariableSpeed_Impl>()->getCoefficient2ofthePartLoadPerformanceCurve(returnIP);
}
bool PumpVariableSpeed::isCoefficient2ofthePartLoadPerformanceCurveDefaulted() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->isCoefficient2ofthePartLoadPerformanceCurveDefaulted();
}
double PumpVariableSpeed::coefficient3ofthePartLoadPerformanceCurve() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->coefficient3ofthePartLoadPerformanceCurve();
}
Quantity PumpVariableSpeed::getCoefficient3ofthePartLoadPerformanceCurve(bool returnIP) const {
return getImpl<detail::PumpVariableSpeed_Impl>()->getCoefficient3ofthePartLoadPerformanceCurve(returnIP);
}
bool PumpVariableSpeed::isCoefficient3ofthePartLoadPerformanceCurveDefaulted() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->isCoefficient3ofthePartLoadPerformanceCurveDefaulted();
}
double PumpVariableSpeed::coefficient4ofthePartLoadPerformanceCurve() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->coefficient4ofthePartLoadPerformanceCurve();
}
Quantity PumpVariableSpeed::getCoefficient4ofthePartLoadPerformanceCurve(bool returnIP) const {
return getImpl<detail::PumpVariableSpeed_Impl>()->getCoefficient4ofthePartLoadPerformanceCurve(returnIP);
}
bool PumpVariableSpeed::isCoefficient4ofthePartLoadPerformanceCurveDefaulted() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->isCoefficient4ofthePartLoadPerformanceCurveDefaulted();
}
double PumpVariableSpeed::minimumFlowRate() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->minimumFlowRate();
}
Quantity PumpVariableSpeed::getMinimumFlowRate(bool returnIP) const {
return getImpl<detail::PumpVariableSpeed_Impl>()->getMinimumFlowRate(returnIP);
}
bool PumpVariableSpeed::isMinimumFlowRateDefaulted() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->isMinimumFlowRateDefaulted();
}
std::string PumpVariableSpeed::pumpControlType() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->pumpControlType();
}
bool PumpVariableSpeed::isPumpControlTypeDefaulted() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->isPumpControlTypeDefaulted();
}
boost::optional<Schedule> PumpVariableSpeed::pumpFlowRateSchedule() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->pumpFlowRateSchedule();
}
boost::optional<Curve> PumpVariableSpeed::pumpCurve() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->pumpCurve();
}
boost::optional<double> PumpVariableSpeed::impellerDiameter() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->impellerDiameter();
}
OSOptionalQuantity PumpVariableSpeed::getImpellerDiameter(bool returnIP) const {
return getImpl<detail::PumpVariableSpeed_Impl>()->getImpellerDiameter(returnIP);
}
boost::optional<std::string> PumpVariableSpeed::vFDControlType() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->vFDControlType();
}
boost::optional<Schedule> PumpVariableSpeed::pumpRPMSchedule() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->pumpRPMSchedule();
}
boost::optional<Schedule> PumpVariableSpeed::minimumPressureSchedule() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->minimumPressureSchedule();
}
boost::optional<Schedule> PumpVariableSpeed::maximumPressureSchedule() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->maximumPressureSchedule();
}
boost::optional<Schedule> PumpVariableSpeed::minimumRPMSchedule() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->minimumRPMSchedule();
}
boost::optional<Schedule> PumpVariableSpeed::maximumRPMSchedule() const {
return getImpl<detail::PumpVariableSpeed_Impl>()->maximumRPMSchedule();
}
void PumpVariableSpeed::setRatedFlowRate(double ratedFlowRate) {
getImpl<detail::PumpVariableSpeed_Impl>()->setRatedFlowRate(ratedFlowRate);
}
bool PumpVariableSpeed::setRatedFlowRate(const Quantity& ratedFlowRate) {
return getImpl<detail::PumpVariableSpeed_Impl>()->setRatedFlowRate(ratedFlowRate);
}
void PumpVariableSpeed::resetRatedFlowRate() {
getImpl<detail::PumpVariableSpeed_Impl>()->resetRatedFlowRate();
}
void PumpVariableSpeed::autosizeRatedFlowRate() {
getImpl<detail::PumpVariableSpeed_Impl>()->autosizeRatedFlowRate();
}
void PumpVariableSpeed::setRatedPumpHead(double ratedPumpHead) {
getImpl<detail::PumpVariableSpeed_Impl>()->setRatedPumpHead(ratedPumpHead);
}
bool PumpVariableSpeed::setRatedPumpHead(const Quantity& ratedPumpHead) {
return getImpl<detail::PumpVariableSpeed_Impl>()->setRatedPumpHead(ratedPumpHead);
}
void PumpVariableSpeed::resetRatedPumpHead() {
getImpl<detail::PumpVariableSpeed_Impl>()->resetRatedPumpHead();
}
void PumpVariableSpeed::setRatedPowerConsumption(double ratedPowerConsumption) {
getImpl<detail::PumpVariableSpeed_Impl>()->setRatedPowerConsumption(ratedPowerConsumption);
}
bool PumpVariableSpeed::setRatedPowerConsumption(const Quantity& ratedPowerConsumption) {
return getImpl<detail::PumpVariableSpeed_Impl>()->setRatedPowerConsumption(ratedPowerConsumption);
}
void PumpVariableSpeed::resetRatedPowerConsumption() {
getImpl<detail::PumpVariableSpeed_Impl>()->resetRatedPowerConsumption();
}
void PumpVariableSpeed::autosizeRatedPowerConsumption() {
getImpl<detail::PumpVariableSpeed_Impl>()->autosizeRatedPowerConsumption();
}
bool PumpVariableSpeed::setMotorEfficiency(double motorEfficiency) {
return getImpl<detail::PumpVariableSpeed_Impl>()->setMotorEfficiency(motorEfficiency);
}
bool PumpVariableSpeed::setMotorEfficiency(const Quantity& motorEfficiency) {
return getImpl<detail::PumpVariableSpeed_Impl>()->setMotorEfficiency(motorEfficiency);
}
void PumpVariableSpeed::resetMotorEfficiency() {
getImpl<detail::PumpVariableSpeed_Impl>()->resetMotorEfficiency();
}
bool PumpVariableSpeed::setFractionofMotorInefficienciestoFluidStream(double fractionofMotorInefficienciestoFluidStream) {
return getImpl<detail::PumpVariableSpeed_Impl>()->setFractionofMotorInefficienciestoFluidStream(fractionofMotorInefficienciestoFluidStream);
}
bool PumpVariableSpeed::setFractionofMotorInefficienciestoFluidStream(const Quantity& fractionofMotorInefficienciestoFluidStream) {
return getImpl<detail::PumpVariableSpeed_Impl>()->setFractionofMotorInefficienciestoFluidStream(fractionofMotorInefficienciestoFluidStream);
}
void PumpVariableSpeed::resetFractionofMotorInefficienciestoFluidStream() {
getImpl<detail::PumpVariableSpeed_Impl>()->resetFractionofMotorInefficienciestoFluidStream();
}
void PumpVariableSpeed::setCoefficient1ofthePartLoadPerformanceCurve(double coefficient1ofthePartLoadPerformanceCurve) {
getImpl<detail::PumpVariableSpeed_Impl>()->setCoefficient1ofthePartLoadPerformanceCurve(coefficient1ofthePartLoadPerformanceCurve);
}
bool PumpVariableSpeed::setCoefficient1ofthePartLoadPerformanceCurve(const Quantity& coefficient1ofthePartLoadPerformanceCurve) {
return getImpl<detail::PumpVariableSpeed_Impl>()->setCoefficient1ofthePartLoadPerformanceCurve(coefficient1ofthePartLoadPerformanceCurve);
}
void PumpVariableSpeed::resetCoefficient1ofthePartLoadPerformanceCurve() {
getImpl<detail::PumpVariableSpeed_Impl>()->resetCoefficient1ofthePartLoadPerformanceCurve();
}
void PumpVariableSpeed::setCoefficient2ofthePartLoadPerformanceCurve(double coefficient2ofthePartLoadPerformanceCurve) {
getImpl<detail::PumpVariableSpeed_Impl>()->setCoefficient2ofthePartLoadPerformanceCurve(coefficient2ofthePartLoadPerformanceCurve);
}
bool PumpVariableSpeed::setCoefficient2ofthePartLoadPerformanceCurve(const Quantity& coefficient2ofthePartLoadPerformanceCurve) {
return getImpl<detail::PumpVariableSpeed_Impl>()->setCoefficient2ofthePartLoadPerformanceCurve(coefficient2ofthePartLoadPerformanceCurve);
}
void PumpVariableSpeed::resetCoefficient2ofthePartLoadPerformanceCurve() {
getImpl<detail::PumpVariableSpeed_Impl>()->resetCoefficient2ofthePartLoadPerformanceCurve();
}
void PumpVariableSpeed::setCoefficient3ofthePartLoadPerformanceCurve(double coefficient3ofthePartLoadPerformanceCurve) {
getImpl<detail::PumpVariableSpeed_Impl>()->setCoefficient3ofthePartLoadPerformanceCurve(coefficient3ofthePartLoadPerformanceCurve);
}
bool PumpVariableSpeed::setCoefficient3ofthePartLoadPerformanceCurve(const Quantity& coefficient3ofthePartLoadPerformanceCurve) {
return getImpl<detail::PumpVariableSpeed_Impl>()->setCoefficient3ofthePartLoadPerformanceCurve(coefficient3ofthePartLoadPerformanceCurve);
}
void PumpVariableSpeed::resetCoefficient3ofthePartLoadPerformanceCurve() {
getImpl<detail::PumpVariableSpeed_Impl>()->resetCoefficient3ofthePartLoadPerformanceCurve();
}
void PumpVariableSpeed::setCoefficient4ofthePartLoadPerformanceCurve(double coefficient4ofthePartLoadPerformanceCurve) {
getImpl<detail::PumpVariableSpeed_Impl>()->setCoefficient4ofthePartLoadPerformanceCurve(coefficient4ofthePartLoadPerformanceCurve);
}
bool PumpVariableSpeed::setCoefficient4ofthePartLoadPerformanceCurve(const Quantity& coefficient4ofthePartLoadPerformanceCurve) {
return getImpl<detail::PumpVariableSpeed_Impl>()->setCoefficient4ofthePartLoadPerformanceCurve(coefficient4ofthePartLoadPerformanceCurve);
}
void PumpVariableSpeed::resetCoefficient4ofthePartLoadPerformanceCurve() {
getImpl<detail::PumpVariableSpeed_Impl>()->resetCoefficient4ofthePartLoadPerformanceCurve();
}
void PumpVariableSpeed::setMinimumFlowRate(double minimumFlowRate) {
getImpl<detail::PumpVariableSpeed_Impl>()->setMinimumFlowRate(minimumFlowRate);
}
bool PumpVariableSpeed::setMinimumFlowRate(const Quantity& minimumFlowRate) {
return getImpl<detail::PumpVariableSpeed_Impl>()->setMinimumFlowRate(minimumFlowRate);
}
void PumpVariableSpeed::resetMinimumFlowRate() {
getImpl<detail::PumpVariableSpeed_Impl>()->resetMinimumFlowRate();
}
bool PumpVariableSpeed::setPumpControlType(std::string pumpControlType) {
return getImpl<detail::PumpVariableSpeed_Impl>()->setPumpControlType(pumpControlType);
}
void PumpVariableSpeed::resetPumpControlType() {
getImpl<detail::PumpVariableSpeed_Impl>()->resetPumpControlType();
}
bool PumpVariableSpeed::setPumpFlowRateSchedule(Schedule& schedule) {
return getImpl<detail::PumpVariableSpeed_Impl>()->setPumpFlowRateSchedule(schedule);
}
void PumpVariableSpeed::resetPumpFlowRateSchedule() {
getImpl<detail::PumpVariableSpeed_Impl>()->resetPumpFlowRateSchedule();
}
bool PumpVariableSpeed::setPumpCurve(const Curve& curve) {
return getImpl<detail::PumpVariableSpeed_Impl>()->setPumpCurve(curve);
}
void PumpVariableSpeed::resetPumpCurve() {
getImpl<detail::PumpVariableSpeed_Impl>()->resetPumpCurve();
}
void PumpVariableSpeed::setImpellerDiameter(double impellerDiameter) {
getImpl<detail::PumpVariableSpeed_Impl>()->setImpellerDiameter(impellerDiameter);
}
bool PumpVariableSpeed::setImpellerDiameter(const Quantity& impellerDiameter) {
return getImpl<detail::PumpVariableSpeed_Impl>()->setImpellerDiameter(impellerDiameter);
}
void PumpVariableSpeed::resetImpellerDiameter() {
getImpl<detail::PumpVariableSpeed_Impl>()->resetImpellerDiameter();
}
bool PumpVariableSpeed::setVFDControlType(std::string vFDControlType) {
return getImpl<detail::PumpVariableSpeed_Impl>()->setVFDControlType(vFDControlType);
}
void PumpVariableSpeed::resetVFDControlType() {
getImpl<detail::PumpVariableSpeed_Impl>()->resetVFDControlType();
}
bool PumpVariableSpeed::setPumpRPMSchedule(Schedule& schedule) {
return getImpl<detail::PumpVariableSpeed_Impl>()->setPumpRPMSchedule(schedule);
}
void PumpVariableSpeed::resetPumpRPMSchedule() {
getImpl<detail::PumpVariableSpeed_Impl>()->resetPumpRPMSchedule();
}
bool PumpVariableSpeed::setMinimumPressureSchedule(Schedule& schedule) {
return getImpl<detail::PumpVariableSpeed_Impl>()->setMinimumPressureSchedule(schedule);
}
void PumpVariableSpeed::resetMinimumPressureSchedule() {
getImpl<detail::PumpVariableSpeed_Impl>()->resetMinimumPressureSchedule();
}
bool PumpVariableSpeed::setMaximumPressureSchedule(Schedule& schedule) {
return getImpl<detail::PumpVariableSpeed_Impl>()->setMaximumPressureSchedule(schedule);
}
void PumpVariableSpeed::resetMaximumPressureSchedule() {
getImpl<detail::PumpVariableSpeed_Impl>()->resetMaximumPressureSchedule();
}
bool PumpVariableSpeed::setMinimumRPMSchedule(Schedule& schedule) {
return getImpl<detail::PumpVariableSpeed_Impl>()->setMinimumRPMSchedule(schedule);
}
void PumpVariableSpeed::resetMinimumRPMSchedule() {
getImpl<detail::PumpVariableSpeed_Impl>()->resetMinimumRPMSchedule();
}
bool PumpVariableSpeed::setMaximumRPMSchedule(Schedule& schedule) {
return getImpl<detail::PumpVariableSpeed_Impl>()->setMaximumRPMSchedule(schedule);
}
void PumpVariableSpeed::resetMaximumRPMSchedule() {
getImpl<detail::PumpVariableSpeed_Impl>()->resetMaximumRPMSchedule();
}
/// @cond
PumpVariableSpeed::PumpVariableSpeed(std::shared_ptr<detail::PumpVariableSpeed_Impl> impl)
: StraightComponent(impl)
{}
/// @endcond
} // model
} // openstudio
|
christopherhein/manager
|
apis/cloudformation/v1alpha1/stack_types.go
|
/*
Copyright © 2019 AWS Controller authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1alpha1
import (
metav1alpha1 "go.awsctrl.io/manager/apis/meta/v1alpha1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// StackSpec defines the desired state of Stack
type StackSpec struct {
metav1alpha1.CloudFormationMeta `json:",inline"`
// Parameters A list of Parameter structures that specify input parameters for
// the stack. For more information, see the Parameter data type.
Parameters map[string]string `json:"parameters"`
// ClientRequestToken A unique identifier for this CreateStack request.
// Specify this token if you plan to retry requests so that AWS CloudFormation
// knows that you're not attempting to create a stack with the same name. You
// might retry CreateStack requests to ensure that AWS CloudFormation
// successfully received them.
// +optional
ClientRequestToken string `json:"clientRequestToken,omitempty"`
// TemplateBody Structure containing the template body with a minimum length
// of 1 byte and a maximum length of 51,200 bytes.
TemplateBody string `json:"templateBody"`
}
// StackStatus defines the observed state of Stack
type StackStatus struct {
metav1alpha1.StatusMeta `json:",inline"`
}
// +kubebuilder:object:root=true
// +kubebuilder:subresource:status
// +kubebuilder:resource:categories=aws;all;cloudformation
// +kubebuilder:printcolumn:JSONPath=.status.status,description="status of the stack",name=Status,priority=1,type=string
// Stack is the Schema for the Stacks API
type Stack struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec StackSpec `json:"spec,omitempty"`
Status StackStatus `json:"status,omitempty"`
}
// +kubebuilder:object:root=true
// StackList contains a list of Stack
type StackList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []Stack `json:"items"`
}
func init() {
SchemeBuilder.Register(&Stack{}, &StackList{})
}
// GetNotificationARNs is an autogenerated deepcopy function, will return notifications for stack
func (in *Stack) GetNotificationARNs() []string {
notifcations := []string{}
for _, notifarn := range in.Spec.CloudFormationMeta.NotificationARNs {
notifcations = append(notifcations, *notifarn)
}
return notifcations
}
|
linbolun-525/GoSword-Admin
|
app/admin/apis/job.go
|
package apis
import (
"project/app/admin/models/dto"
"project/app/admin/service"
"project/common/api"
"project/utils"
"project/utils/app"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
"go.uber.org/zap"
)
// InsertMenuHandler 查询岗位
// @Summary 查询岗位
// @Description Author:JiaKunLi 2021/02/1
// @Tags 系统:岗位管理 job Controller
// @Accept application/json
// @Produce application/json
// @Param object query dto.GetJobList false "查询参数"
// @Security ApiKeyAuth
// @Success 200 {object} models._ResponseGetJobList
// @Router /api/job [get]
func GetJobList(c *gin.Context) {
p := new(dto.GetJobList)
//获取上下文中信息
user, err := api.GetUserMessage(c)
if err != nil {
c.Error(err)
zap.L().Error("GetUserMessage failed", zap.Error(err))
return
}
if err := c.ShouldBindQuery(p); err != nil {
// 请求参数有误, 直接返回响应
zap.L().Error("job bind params failed", zap.String("Username", user.Username), zap.Error(err))
c.Error(err)
_, ok := err.(validator.ValidationErrors)
if !ok {
app.ResponseError(c, app.CodeParamIsInvalid)
return
}
app.ResponseError(c, app.CodeParamNotComplete)
return
}
//业务逻辑处理
s := new(service.Job)
res, err := s.GetJobList(p)
if err != nil {
c.Error(err)
zap.L().Error("get job list failed", zap.String("Username", user.Username), zap.Error(err))
app.ResponseError(c, app.CodeSelectOperationFail)
return
}
// 返回响应
app.ResponseSuccess(c, res)
}
// DelJobById 删除岗位
// @Summary 删除岗位
// @Description Author:JiaKunLi 2021/02/1
// @Tags 系统:岗位管理 job Controller
// @Accept application/json
// @Produce application/json
// @Param object body []int false "查询参数"
// @Security ApiKeyAuth
// @Success 200 {object} models._ResponseInsertMenu
// @Router /api/job [delete]
func DelJobById(c *gin.Context) {
var ids []int
//获取上下文中信息
user, err := api.GetUserMessage(c)
if err != nil {
c.Error(err)
zap.L().Error("GetUserMessage failed", zap.Error(err))
return
}
if err := c.ShouldBindJSON(&ids); err != nil {
// 请求参数有误, 直接返回响应
zap.L().Error("del job bind ids failed", zap.String("Username", user.Username), zap.Error(err))
c.Error(err)
_, ok := err.(validator.ValidationErrors)
if !ok {
app.ResponseError(c, app.CodeParamIsInvalid)
return
}
app.ResponseError(c, app.CodeParamNotComplete)
return
}
if len(ids) == 0 {
app.ResponseError(c, app.CodeParamIsBlank)
return
}
job := new(service.Job)
count, err := job.DelJobById(user.UserId, &ids)
if err != nil {
c.Error(err)
zap.L().Error("delete job service failed", zap.String("Username", user.Username), zap.Error(err))
app.ResponseError(c, app.CodeDeleteOperationFail)
return
}
if *count > 0 {
app.ResponseErrorWithMsg(c, app.CodeOperationFail, "请解除该岗位用户关联后再试!")
return
}
app.ResponseSuccess(c, nil)
}
// AddJob 新增岗位
// @Summary 新增岗位
// @Description Author:JiaKunLi 2021/02/1
// @Tags 系统:岗位管理 job Controller
// @Accept application/json
// @Produce application/json
// @Param object body dto.AddJob false "查询参数"
// @Security ApiKeyAuth
// @Success 200 {object} models._ResponseInsertMenu
// @Router /api/job [post]
func AddJob(c *gin.Context) {
p := new(dto.AddJob)
//获取上下文中信息
user, err := api.GetUserMessage(c)
if err != nil {
c.Error(err)
zap.L().Error("GetUserMessage failed", zap.Error(err))
return
}
if err := c.ShouldBindJSON(p); err != nil {
// 请求参数有误, 直接返回响应
zap.L().Error("del job bind ids failed", zap.String("Username", user.Username), zap.Error(err))
c.Error(err)
_, ok := err.(validator.ValidationErrors)
if !ok {
app.ResponseError(c, app.CodeParamIsInvalid)
return
}
app.ResponseError(c, app.CodeParamNotComplete)
return
}
job := new(service.Job)
if err := job.AddJob(user.UserId, p); err != nil {
c.Error(err)
zap.L().Error("add job service failed", zap.String("Username", user.Username), zap.Error(err))
app.ResponseError(c, app.CodeInsertOperationFail)
return
}
app.ResponseSuccess(c, nil)
}
// UpdateJob 修改岗位
// @Summary 修改岗位
// @Description Author:JiaKunLi 2021/02/1
// @Tags 系统:岗位管理 job Controller
// @Accept application/json
// @Produce application/json
// @Param object body dto.UpdateJob false "查询参数"
// @Security ApiKeyAuth
// @Success 200 {object} models._ResponseInsertMenu
// @Router /api/job [put]
func UpdateJob(c *gin.Context) {
p := new(dto.UpdateJob)
//获取上下文中信息
user, err := api.GetUserMessage(c)
if err != nil {
c.Error(err)
zap.L().Error("GetUserMessage failed", zap.Error(err))
return
}
if err := c.ShouldBindJSON(p); err != nil {
// 请求参数有误, 直接返回响应
zap.L().Error("update job bind body failed", zap.String("Username", user.Username), zap.Error(err))
c.Error(err)
_, ok := err.(validator.ValidationErrors)
if !ok {
app.ResponseError(c, app.CodeParamIsInvalid)
return
}
app.ResponseError(c, app.CodeParamNotComplete)
return
}
job := new(service.Job)
if err = job.Update(user.UserId, p); err != nil {
c.Error(err)
zap.L().Error("update job failed", zap.String("Username", user.Username), zap.Error(err))
app.ResponseError(c, app.CodeUpdateOperationFail)
return
}
app.ResponseSuccess(c, nil)
}
// JobDownload 导出岗位数据
// @Summary 导出岗位数据
// @Description Author:JiaKunLi 2021/02/1
// @Tags 系统:岗位管理 job Controller
// @Accept application/json
// @Produce application/json
// @Param object query dto.GetJobList false "查询参数"
// @Security ApiKeyAuth
// @Success 200
// @Router /api/job/download [get]
func JobDownload(c *gin.Context) {
p := new(dto.GetJobList)
//获取上下文中信息
user, err := api.GetUserMessage(c)
if err != nil {
c.Error(err)
zap.L().Error("GetUserMessage failed", zap.Error(err))
return
}
if err := c.ShouldBindQuery(p); err != nil {
// 请求参数有误, 直接返回响应
zap.L().Error("JobDownload bind params failed", zap.String("Username", user.Username), zap.Error(err))
c.Error(err)
_, ok := err.(validator.ValidationErrors)
if !ok {
app.ResponseError(c, app.CodeParamIsInvalid)
return
}
app.ResponseError(c, app.CodeParamNotComplete)
return
}
//业务逻辑处理
s := new(service.Job)
res, err := s.JobListDownload(p)
if err != nil {
c.Error(err)
zap.L().Error("JobDownload service failed", zap.String("Username", user.Username), zap.Error(err))
app.ResponseError(c, app.CodeSelectOperationFail)
return
}
utils.ResponseXls(c, res, `岗位数据`)
}
|
Kinjeiro/front-core
|
src/modules/module-auth/server/subModule/users/user-representation.js
|
// https://www.keycloak.org/docs-api/7.0/rest-api/index.html#_userrepresentation
export const USER_REPRESENTATION_FIELDS = [
'id',
'createdTimestamp',
'username',
'enabled',
'totp',
'emailVerified',
'firstName',
'lastName',
'email',
'disableableCredentialTypes',
'requiredActions',
'notBefore',
'access',
'attributes',
];
|
theofficialgman/lwjgl3
|
modules/lwjgl/vulkan/src/generated/java/org/lwjgl/vulkan/VkViewport.java
|
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.vulkan;
import javax.annotation.*;
import java.nio.*;
import org.lwjgl.*;
import org.lwjgl.system.*;
import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.MemoryStack.*;
/**
* Structure specifying a viewport.
*
* <h5>Description</h5>
*
* <div style="margin-left: 26px; border-left: 1px solid gray; padding-left: 14px;"><h5>Note</h5>
*
* <p>Despite their names, {@code minDepth} <b>can</b> be less than, equal to, or greater than {@code maxDepth}.</p>
* </div>
*
* <p>The framebuffer depth coordinate <code>z<sub>f</sub></code> <b>may</b> be represented using either a fixed-point or floating-point representation. However, a floating-point representation <b>must</b> be used if the depth/stencil attachment has a floating-point depth component. If an <code>m</code>-bit fixed-point representation is used, we assume that it represents each value <code>k / (2<sup>m</sup> - 1)</code>, where <code>k ∈ { 0, 1, …, 2<sup>m</sup>-1 }</code>, as <code>k</code> (e.g. 1.0 is represented in binary as a string of all ones).</p>
*
* <p>The viewport parameters shown in the above equations are found from these values as</p>
*
* <dl>
* <dd><code>o<sub>x</sub> = x + width / 2</code></dd>
* <dd><code>o<sub>y</sub> = y + height / 2</code></dd>
* <dd><code>o<sub>z</sub> = minDepth</code></dd>
* <dd><code>p<sub>x</sub> = width</code></dd>
* <dd><code>p<sub>y</sub> = height</code></dd>
* <dd><code>p<sub>z</sub> = maxDepth - minDepth</code>.</dd>
* </dl>
*
* <p>If a render pass transform is enabled, the values <code>(p<sub>x</sub>,p<sub>y</sub>)</code> and <code>(o<sub>x</sub>, o<sub>y</sub>)</code> defining the viewport are transformed as described in <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#vertexpostproc-renderpass-transform">render pass transform</a> before participating in the viewport transform.</p>
*
* <p>The application <b>can</b> specify a negative term for {@code height}, which has the effect of negating the y coordinate in clip space before performing the transform. When using a negative {@code height}, the application <b>should</b> also adjust the {@code y} value to point to the lower left corner of the viewport instead of the upper left corner. Using the negative {@code height} allows the application to avoid having to negate the y component of the {@code Position} output from the last <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#pipeline-graphics-subsets-pre-rasterization">pre-rasterization shader stage</a>.</p>
*
* <p>The width and height of the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#limits-maxViewportDimensions">implementation-dependent maximum viewport dimensions</a> <b>must</b> be greater than or equal to the width and height of the largest image which <b>can</b> be created and attached to a framebuffer.</p>
*
* <p>The floating-point viewport bounds are represented with an <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#limits-viewportSubPixelBits">implementation-dependent precision</a>.</p>
*
* <h5>Valid Usage</h5>
*
* <ul>
* <li>{@code width} <b>must</b> be greater than {@code 0.0}</li>
* <li>{@code width} <b>must</b> be less than or equal to {@link VkPhysicalDeviceLimits}{@code ::maxViewportDimensions}[0]</li>
* <li>The absolute value of {@code height} <b>must</b> be less than or equal to {@link VkPhysicalDeviceLimits}{@code ::maxViewportDimensions}[1]</li>
* <li>{@code x} <b>must</b> be greater than or equal to {@code viewportBoundsRange}[0]</li>
* <li><code>(x + width)</code> <b>must</b> be less than or equal to {@code viewportBoundsRange}[1]</li>
* <li>{@code y} <b>must</b> be greater than or equal to {@code viewportBoundsRange}[0]</li>
* <li>{@code y} <b>must</b> be less than or equal to {@code viewportBoundsRange}[1]</li>
* <li><code>(y + height)</code> <b>must</b> be greater than or equal to {@code viewportBoundsRange}[0]</li>
* <li><code>(y + height)</code> <b>must</b> be less than or equal to {@code viewportBoundsRange}[1]</li>
* <li>Unless {@link EXTDepthRangeUnrestricted VK_EXT_depth_range_unrestricted} extension is enabled {@code minDepth} <b>must</b> be between {@code 0.0} and {@code 1.0}, inclusive</li>
* <li>Unless {@link EXTDepthRangeUnrestricted VK_EXT_depth_range_unrestricted} extension is enabled {@code maxDepth} <b>must</b> be between {@code 0.0} and {@code 1.0}, inclusive</li>
* </ul>
*
* <h5>See Also</h5>
*
* <p>{@link VkCommandBufferInheritanceViewportScissorInfoNV}, {@link VkPipelineViewportStateCreateInfo}, {@link VK10#vkCmdSetViewport CmdSetViewport}, {@link EXTExtendedDynamicState#vkCmdSetViewportWithCountEXT CmdSetViewportWithCountEXT}</p>
*
* <h3>Layout</h3>
*
* <pre><code>
* struct VkViewport {
* float {@link #x};
* float {@link #y};
* float {@link #width};
* float {@link #height};
* float {@link #minDepth};
* float {@link #maxDepth};
* }</code></pre>
*/
public class VkViewport extends Struct implements NativeResource {
/** The struct size in bytes. */
public static final int SIZEOF;
/** The struct alignment in bytes. */
public static final int ALIGNOF;
/** The struct member offsets. */
public static final int
X,
Y,
WIDTH,
HEIGHT,
MINDEPTH,
MAXDEPTH;
static {
Layout layout = __struct(
__member(4),
__member(4),
__member(4),
__member(4),
__member(4),
__member(4)
);
SIZEOF = layout.getSize();
ALIGNOF = layout.getAlignment();
X = layout.offsetof(0);
Y = layout.offsetof(1);
WIDTH = layout.offsetof(2);
HEIGHT = layout.offsetof(3);
MINDEPTH = layout.offsetof(4);
MAXDEPTH = layout.offsetof(5);
}
/**
* Creates a {@code VkViewport} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
* visible to the struct instance and vice versa.
*
* <p>The created instance holds a strong reference to the container object.</p>
*/
public VkViewport(ByteBuffer container) {
super(memAddress(container), __checkContainer(container, SIZEOF));
}
@Override
public int sizeof() { return SIZEOF; }
/** {@code x} and {@code y} are the viewport’s upper left corner <code>(x,y)</code>. */
public float x() { return nx(address()); }
/** see {@code x} */
public float y() { return ny(address()); }
/** {@code width} and {@code height} are the viewport’s width and height, respectively. */
public float width() { return nwidth(address()); }
/** see {@code width} */
public float height() { return nheight(address()); }
/** {@code minDepth} and {@code maxDepth} are the depth range for the viewport. */
public float minDepth() { return nminDepth(address()); }
/** see {@code minDepth} */
public float maxDepth() { return nmaxDepth(address()); }
/** Sets the specified value to the {@link #x} field. */
public VkViewport x(float value) { nx(address(), value); return this; }
/** Sets the specified value to the {@link #y} field. */
public VkViewport y(float value) { ny(address(), value); return this; }
/** Sets the specified value to the {@link #width} field. */
public VkViewport width(float value) { nwidth(address(), value); return this; }
/** Sets the specified value to the {@link #height} field. */
public VkViewport height(float value) { nheight(address(), value); return this; }
/** Sets the specified value to the {@link #minDepth} field. */
public VkViewport minDepth(float value) { nminDepth(address(), value); return this; }
/** Sets the specified value to the {@link #maxDepth} field. */
public VkViewport maxDepth(float value) { nmaxDepth(address(), value); return this; }
/** Initializes this struct with the specified values. */
public VkViewport set(
float x,
float y,
float width,
float height,
float minDepth,
float maxDepth
) {
x(x);
y(y);
width(width);
height(height);
minDepth(minDepth);
maxDepth(maxDepth);
return this;
}
/**
* Copies the specified struct data to this struct.
*
* @param src the source struct
*
* @return this struct
*/
public VkViewport set(VkViewport src) {
memCopy(src.address(), address(), SIZEOF);
return this;
}
// -----------------------------------
/** Returns a new {@code VkViewport} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */
public static VkViewport malloc() {
return wrap(VkViewport.class, nmemAllocChecked(SIZEOF));
}
/** Returns a new {@code VkViewport} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */
public static VkViewport calloc() {
return wrap(VkViewport.class, nmemCallocChecked(1, SIZEOF));
}
/** Returns a new {@code VkViewport} instance allocated with {@link BufferUtils}. */
public static VkViewport create() {
ByteBuffer container = BufferUtils.createByteBuffer(SIZEOF);
return wrap(VkViewport.class, memAddress(container), container);
}
/** Returns a new {@code VkViewport} instance for the specified memory address. */
public static VkViewport create(long address) {
return wrap(VkViewport.class, address);
}
/** Like {@link #create(long) create}, but returns {@code null} if {@code address} is {@code NULL}. */
@Nullable
public static VkViewport createSafe(long address) {
return address == NULL ? null : wrap(VkViewport.class, address);
}
/**
* Returns a new {@link VkViewport.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed.
*
* @param capacity the buffer capacity
*/
public static VkViewport.Buffer malloc(int capacity) {
return wrap(Buffer.class, nmemAllocChecked(__checkMalloc(capacity, SIZEOF)), capacity);
}
/**
* Returns a new {@link VkViewport.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed.
*
* @param capacity the buffer capacity
*/
public static VkViewport.Buffer calloc(int capacity) {
return wrap(Buffer.class, nmemCallocChecked(capacity, SIZEOF), capacity);
}
/**
* Returns a new {@link VkViewport.Buffer} instance allocated with {@link BufferUtils}.
*
* @param capacity the buffer capacity
*/
public static VkViewport.Buffer create(int capacity) {
ByteBuffer container = __create(capacity, SIZEOF);
return wrap(Buffer.class, memAddress(container), capacity, container);
}
/**
* Create a {@link VkViewport.Buffer} instance at the specified memory.
*
* @param address the memory address
* @param capacity the buffer capacity
*/
public static VkViewport.Buffer create(long address, int capacity) {
return wrap(Buffer.class, address, capacity);
}
/** Like {@link #create(long, int) create}, but returns {@code null} if {@code address} is {@code NULL}. */
@Nullable
public static VkViewport.Buffer createSafe(long address, int capacity) {
return address == NULL ? null : wrap(Buffer.class, address, capacity);
}
// -----------------------------------
/** Returns a new {@code VkViewport} instance allocated on the thread-local {@link MemoryStack}. */
public static VkViewport mallocStack() {
return mallocStack(stackGet());
}
/** Returns a new {@code VkViewport} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero. */
public static VkViewport callocStack() {
return callocStack(stackGet());
}
/**
* Returns a new {@code VkViewport} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
*/
public static VkViewport mallocStack(MemoryStack stack) {
return wrap(VkViewport.class, stack.nmalloc(ALIGNOF, SIZEOF));
}
/**
* Returns a new {@code VkViewport} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
*/
public static VkViewport callocStack(MemoryStack stack) {
return wrap(VkViewport.class, stack.ncalloc(ALIGNOF, 1, SIZEOF));
}
/**
* Returns a new {@link VkViewport.Buffer} instance allocated on the thread-local {@link MemoryStack}.
*
* @param capacity the buffer capacity
*/
public static VkViewport.Buffer mallocStack(int capacity) {
return mallocStack(capacity, stackGet());
}
/**
* Returns a new {@link VkViewport.Buffer} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero.
*
* @param capacity the buffer capacity
*/
public static VkViewport.Buffer callocStack(int capacity) {
return callocStack(capacity, stackGet());
}
/**
* Returns a new {@link VkViewport.Buffer} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
* @param capacity the buffer capacity
*/
public static VkViewport.Buffer mallocStack(int capacity, MemoryStack stack) {
return wrap(Buffer.class, stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity);
}
/**
* Returns a new {@link VkViewport.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
* @param capacity the buffer capacity
*/
public static VkViewport.Buffer callocStack(int capacity, MemoryStack stack) {
return wrap(Buffer.class, stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity);
}
// -----------------------------------
/** Unsafe version of {@link #x}. */
public static float nx(long struct) { return UNSAFE.getFloat(null, struct + VkViewport.X); }
/** Unsafe version of {@link #y}. */
public static float ny(long struct) { return UNSAFE.getFloat(null, struct + VkViewport.Y); }
/** Unsafe version of {@link #width}. */
public static float nwidth(long struct) { return UNSAFE.getFloat(null, struct + VkViewport.WIDTH); }
/** Unsafe version of {@link #height}. */
public static float nheight(long struct) { return UNSAFE.getFloat(null, struct + VkViewport.HEIGHT); }
/** Unsafe version of {@link #minDepth}. */
public static float nminDepth(long struct) { return UNSAFE.getFloat(null, struct + VkViewport.MINDEPTH); }
/** Unsafe version of {@link #maxDepth}. */
public static float nmaxDepth(long struct) { return UNSAFE.getFloat(null, struct + VkViewport.MAXDEPTH); }
/** Unsafe version of {@link #x(float) x}. */
public static void nx(long struct, float value) { UNSAFE.putFloat(null, struct + VkViewport.X, value); }
/** Unsafe version of {@link #y(float) y}. */
public static void ny(long struct, float value) { UNSAFE.putFloat(null, struct + VkViewport.Y, value); }
/** Unsafe version of {@link #width(float) width}. */
public static void nwidth(long struct, float value) { UNSAFE.putFloat(null, struct + VkViewport.WIDTH, value); }
/** Unsafe version of {@link #height(float) height}. */
public static void nheight(long struct, float value) { UNSAFE.putFloat(null, struct + VkViewport.HEIGHT, value); }
/** Unsafe version of {@link #minDepth(float) minDepth}. */
public static void nminDepth(long struct, float value) { UNSAFE.putFloat(null, struct + VkViewport.MINDEPTH, value); }
/** Unsafe version of {@link #maxDepth(float) maxDepth}. */
public static void nmaxDepth(long struct, float value) { UNSAFE.putFloat(null, struct + VkViewport.MAXDEPTH, value); }
// -----------------------------------
/** An array of {@link VkViewport} structs. */
public static class Buffer extends StructBuffer<VkViewport, Buffer> implements NativeResource {
private static final VkViewport ELEMENT_FACTORY = VkViewport.create(-1L);
/**
* Creates a new {@code VkViewport.Buffer} instance backed by the specified container.
*
* Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
* will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
* by {@link VkViewport#SIZEOF}, and its mark will be undefined.
*
* <p>The created buffer instance holds a strong reference to the container object.</p>
*/
public Buffer(ByteBuffer container) {
super(container, container.remaining() / SIZEOF);
}
public Buffer(long address, int cap) {
super(address, null, -1, 0, cap, cap);
}
Buffer(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) {
super(address, container, mark, pos, lim, cap);
}
@Override
protected Buffer self() {
return this;
}
@Override
protected VkViewport getElementFactory() {
return ELEMENT_FACTORY;
}
/** @return the value of the {@link VkViewport#x} field. */
public float x() { return VkViewport.nx(address()); }
/** @return the value of the {@link VkViewport#y} field. */
public float y() { return VkViewport.ny(address()); }
/** @return the value of the {@link VkViewport#width} field. */
public float width() { return VkViewport.nwidth(address()); }
/** @return the value of the {@link VkViewport#height} field. */
public float height() { return VkViewport.nheight(address()); }
/** @return the value of the {@link VkViewport#minDepth} field. */
public float minDepth() { return VkViewport.nminDepth(address()); }
/** @return the value of the {@link VkViewport#maxDepth} field. */
public float maxDepth() { return VkViewport.nmaxDepth(address()); }
/** Sets the specified value to the {@link VkViewport#x} field. */
public VkViewport.Buffer x(float value) { VkViewport.nx(address(), value); return this; }
/** Sets the specified value to the {@link VkViewport#y} field. */
public VkViewport.Buffer y(float value) { VkViewport.ny(address(), value); return this; }
/** Sets the specified value to the {@link VkViewport#width} field. */
public VkViewport.Buffer width(float value) { VkViewport.nwidth(address(), value); return this; }
/** Sets the specified value to the {@link VkViewport#height} field. */
public VkViewport.Buffer height(float value) { VkViewport.nheight(address(), value); return this; }
/** Sets the specified value to the {@link VkViewport#minDepth} field. */
public VkViewport.Buffer minDepth(float value) { VkViewport.nminDepth(address(), value); return this; }
/** Sets the specified value to the {@link VkViewport#maxDepth} field. */
public VkViewport.Buffer maxDepth(float value) { VkViewport.nmaxDepth(address(), value); return this; }
}
}
|
L-VE/knooppuntnet
|
server/src/main/scala/kpn/api/common/LocationPage.scala
|
package kpn.api.common
import kpn.api.common.common.Ref
case class LocationPage(routeRefs: Seq[Ref])
|
wangzmgit/go-danmu
|
controller/CollectionController.go
|
package controller
import (
"strconv"
"github.com/gin-gonic/gin"
"kuukaa.fun/danmu-v4/dto"
"kuukaa.fun/danmu-v4/response"
"kuukaa.fun/danmu-v4/service"
)
/*********************************************************
** 函数功能: 创建合集
** 日 期: 2021年11月19日14:48:29
** 版 本: 3.6.0
**********************************************************/
func CreateCollection(ctx *gin.Context) {
var request dto.CreateCollectionDto
err := ctx.Bind(&request)
if err != nil {
response.Fail(ctx, nil, response.RequestError)
return
}
title := request.Title
cover := request.Cover
uid, _ := ctx.Get("id")
//验证数据
if len(title) == 0 {
response.CheckFail(ctx, nil, response.TitleCheck)
return
}
if len(cover) == 0 {
response.CheckFail(ctx, nil, response.CoverCheck)
return
}
res := service.CreateCollectionService(request, uid)
response.HandleResponse(ctx, res)
}
/*********************************************************
** 函数功能: 修改合集信息
** 日 期: 2021年11月19日14:48:29
** 版 本: 3.6.0
**********************************************************/
func ModifyCollection(ctx *gin.Context) {
var request dto.ModifyCollectionDto
err := ctx.Bind(&request)
if err != nil {
response.Fail(ctx, nil, response.RequestError)
return
}
title := request.Title
cover := request.Cover
uid, _ := ctx.Get("id")
//验证数据
if len(title) == 0 {
response.CheckFail(ctx, nil, response.TitleCheck)
return
}
if len(cover) == 0 {
response.CheckFail(ctx, nil, response.CoverCheck)
return
}
res := service.ModifyCollectionService(request, uid)
response.HandleResponse(ctx, res)
}
/*********************************************************
** 函数功能: 获取自己创建的合集
** 日 期: 2021年11月19日19:58:43
** 版 本: 3.6.0
**********************************************************/
func GetCreateCollectionList(ctx *gin.Context) {
uid, _ := ctx.Get("id")
page, _ := strconv.Atoi(ctx.Query("page"))
pageSize, _ := strconv.Atoi(ctx.Query("page_size"))
if page <= 0 || pageSize <= 0 {
response.CheckFail(ctx, nil, response.PageOrSizeError)
return
}
if pageSize >= 30 {
response.CheckFail(ctx, nil, response.TooManyRequests)
return
}
res := service.GetCreateCollectionListService(page, pageSize, uid)
response.HandleResponse(ctx, res)
}
/*********************************************************
** 函数功能: 获取合集内容
** 日 期: 2021年11月19日20:01:08
** 版 本: 3.6.0
**********************************************************/
func GetCollectionContent(ctx *gin.Context) {
cid, _ := strconv.Atoi(ctx.Query("cid"))
page, _ := strconv.Atoi(ctx.Query("page"))
pageSize, _ := strconv.Atoi(ctx.Query("page_size"))
if cid <= 0 {
response.CheckFail(ctx, nil, response.CollectionNotExist)
return
}
if page <= 0 || pageSize <= 0 {
response.CheckFail(ctx, nil, response.PageOrSizeError)
return
}
if pageSize >= 30 {
response.CheckFail(ctx, nil, response.TooManyRequests)
return
}
res := service.GetCollectionContentService(cid, page, pageSize)
response.HandleResponse(ctx, res)
}
/*********************************************************
** 函数功能: 获取合集信息
** 日 期: 2021年11月20日16:23:57
** 版 本: 3.6.0
**********************************************************/
func GetCollectionByID(ctx *gin.Context) {
id, _ := strconv.Atoi(ctx.Query("id"))
if id <= 0 {
response.CheckFail(ctx, nil, response.CollectionNotExist)
return
}
res := service.GetCollectionByIDService(id)
response.HandleResponse(ctx, res)
}
/*********************************************************
** 函数功能: 删除合集
** 日 期: 2021年11月20日16:55:39
** 版 本: 3.6.0
**********************************************************/
func DeleteCollection(ctx *gin.Context) {
//获取参数
var collection dto.DeleteCollectionDto
err := ctx.Bind(&collection)
if err != nil {
response.Fail(ctx, nil, response.RequestError)
return
}
id := collection.ID
uid, _ := ctx.Get("id")
//数据验证
if id == 0 {
response.CheckFail(ctx, nil, response.CollectionNotExist)
return
}
//删除合集
res := service.DeleteCollectionService(id, uid)
response.HandleResponse(ctx, res)
}
/*********************************************************
** 函数功能: 获取可以添加的视频列表
** 日 期: 2021年11月20日20:38:13
** 版 本: 3.6.0
**********************************************************/
func GetCanAddVideo(ctx *gin.Context) {
//获取参数
uid, _ := ctx.Get("id")
id, _ := strconv.Atoi(ctx.Query("id"))
page, _ := strconv.Atoi(ctx.Query("page"))
pageSize, _ := strconv.Atoi(ctx.Query("page_size"))
if page <= 0 || pageSize <= 0 {
response.CheckFail(ctx, nil, response.PageOrSizeError)
return
}
if pageSize >= 30 {
response.CheckFail(ctx, nil, response.TooManyRequests)
return
}
if id <= 0 {
response.CheckFail(ctx, nil, response.CollectionNotExist)
return
}
//删除合集
res := service.GetCanAddVideoService(id, uid, page, pageSize)
response.HandleResponse(ctx, res)
}
/*********************************************************
** 函数功能: 向合集内添加视频
** 日 期: 2021年11月21日09:31:09
** 版 本: 3.6.0
**********************************************************/
func AddVideoToCollection(ctx *gin.Context) {
//获取参数
var video dto.AddVideoDto
err := ctx.Bind(&video)
if err != nil {
response.Fail(ctx, nil, response.RequestError)
return
}
vid := video.Vid
cid := video.Cid
uid, _ := ctx.Get("id")
//数据验证
if vid == 0 || cid == 0 {
response.CheckFail(ctx, nil, response.CollectionOrVideoNotExist)
return
}
//添加合集
res := service.AddVideoToCollectionService(vid, cid, uid)
response.HandleResponse(ctx, res)
}
/*********************************************************
** 函数功能: 删除合集内的视频
** 日 期: 2021年11月21日13:32:59
** 版 本: 3.6.0
**********************************************************/
func DeleteCollectionVideo(ctx *gin.Context) {
//获取参数
var video dto.DeleteVideoDto
err := ctx.Bind(&video)
if err != nil {
response.Fail(ctx, nil, response.RequestError)
return
}
vid := video.Vid
cid := video.Cid
uid, _ := ctx.Get("id")
//数据验证
if vid == 0 || cid == 0 {
response.CheckFail(ctx, nil, response.CollectionOrVideoNotExist)
return
}
//添加合集
res := service.DeleteCollectionVideoService(vid, cid, uid)
response.HandleResponse(ctx, res)
}
/*********************************************************
** 函数功能: 获取合集列表
** 日 期: 2021年11月21日14:53:56
** 版 本: 3.6.0
**********************************************************/
func GetCollectionList(ctx *gin.Context) {
page, _ := strconv.Atoi(ctx.Query("page"))
pageSize, _ := strconv.Atoi(ctx.Query("page_size"))
if page <= 0 || pageSize <= 0 {
response.CheckFail(ctx, nil, response.PageOrSizeError)
return
}
if pageSize >= 30 {
response.CheckFail(ctx, nil, response.TooManyRequests)
return
}
res := service.GetCollectionListService(page, pageSize)
response.HandleResponse(ctx, res)
}
|
godmonth/godmonth-status2
|
builder/src/main/java/com/godmonth/status2/builder/binding/BindingListBuilder.java
|
<reponame>godmonth/godmonth-status2<filename>builder/src/main/java/com/godmonth/status2/builder/binding/BindingListBuilder.java
package com.godmonth.status2.builder.binding;
import com.godmonth.status2.analysis.impl.BindingKeyUtils;
import com.godmonth.status2.annotations.binding.ModelBinding;
import com.google.common.collect.ImmutableSet;
import com.google.common.reflect.ClassPath;
import lombok.Builder;
import lombok.NonNull;
import lombok.Singular;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.core.annotation.AnnotationUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
/**
* <p></p >
*
* @author shenyue
*/
@Slf4j
public class BindingListBuilder {
/**
* @param classLoader
* @param packageNames
* @param enableAnnotationClass
* @param ancestorClass
* @param modelClass
* @param predicate
* @param bindingKeyFunction
* @param autowireCapableBeanFactory
* @param <T> 推进器类
* @return Object是路由key
* @throws IOException
* @throws ClassNotFoundException
*/
@Builder
private static <T> List<Pair<Object, T>> build(ClassLoader classLoader, @NonNull @Singular Set<String> packageNames, Class enableAnnotationClass, Class ancestorClass, Class modelClass, Predicate<Class> predicate, Function<Class, Object[]> bindingKeyFunction, @NonNull AutowireCapableBeanFactory autowireCapableBeanFactory) throws IOException, ClassNotFoundException {
Validate.notEmpty(packageNames, "packageNames is empty");
bindingKeyFunction = bindingKeyFunction != null ? bindingKeyFunction : BindingKeyUtils::getBindingKey;
List<Pair<Object, T>> list = new ArrayList<>();
ClassPath classPath = ClassPath.from(classLoader != null ? classLoader : ClassLoader.getSystemClassLoader());
for (String packageName : packageNames) {
ImmutableSet<ClassPath.ClassInfo> topLevelClasses = classPath.getTopLevelClassesRecursive(packageName);
for (ClassPath.ClassInfo topLevelClass : topLevelClasses) {
Class<?> aClass = Class.forName(topLevelClass.getName());
//检查激活标志
if (enableAnnotationClass != null && AnnotationUtils.findAnnotation(aClass, enableAnnotationClass) == null) {
continue;
}
//检查父类
if (ancestorClass != null && !ancestorClass.isAssignableFrom(aClass)) {
continue;
}
//匹配模型
if (modelClass != null) {
ModelBinding modelBinding = AnnotationUtils.findAnnotation(aClass, ModelBinding.class);
if (modelBinding != null && !modelClass.equals(modelBinding.value())) {
continue;
}
}
//过滤断言
if (predicate != null && !predicate.test(aClass)) {
continue;
}
final List<Pair<Object, T>> byAnnotation = createByAnnotation(aClass, autowireCapableBeanFactory, bindingKeyFunction);
if (byAnnotation != null) {
list.addAll(byAnnotation);
}
}
}
log.debug("binding list:{}", list);
return list;
}
public static <T> List<Pair<Object, T>> createByAnnotation(Class aClass, AutowireCapableBeanFactory autowireCapableBeanFactory, Function<Class, Object[]> bindingKeyFunction) {
Object[] keys = bindingKeyFunction.apply(aClass);
List<Pair<Object, T>> pairs = new ArrayList<>();
if (keys != null) {
T component = (T) autowireCapableBeanFactory.autowire(aClass, AutowireCapableBeanFactory.AUTOWIRE_NO, false);
for (int i = 0; i < keys.length; i++) {
Object key = keys[i];
if (component != null) {
final Pair<Object, T> of = Pair.of(key, component);
pairs.add(of);
}
}
}
return pairs;
}
}
|
clayne/fast_io
|
include/fast_io_core_impl/concepts/parse_code.h
|
#pragma once
namespace fast_io
{
enum class parse_code
{
ok = 0,
end_of_file = 1,
partial = 2,
invalid = 3,
overflow = 4
};
template<typename Iter>
struct parse_result
{
using iterator = Iter;
iterator iter;
parse_code code;
};
}
|
uyaki/uyaki-cloud
|
uyaki-cloud-microservices/uyaki-cloud-microservices-auth/src/main/java/com/uyaki/cloud/microservices/auth/mapper/om/RoleMapper.java
|
<filename>uyaki-cloud-microservices/uyaki-cloud-microservices-auth/src/main/java/com/uyaki/cloud/microservices/auth/mapper/om/RoleMapper.java<gh_stars>1-10
package com.uyaki.cloud.microservices.auth.mapper.om;
import com.uyaki.cloud.microservices.auth.model.om.Role;
public interface RoleMapper {
int deleteByPrimaryKey(Long id);
int insert(Role record);
int insertSelective(Role record);
Role selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(Role record);
int updateByPrimaryKey(Role record);
}
|
HumphreyHCB/SOMns-vscode
|
server/org.eclipse.lsp4j-gen/org/eclipse/lsp4j/LocationLink.java
|
<filename>server/org.eclipse.lsp4j-gen/org/eclipse/lsp4j/LocationLink.java
/**
* Copyright (c) 2016-2018 TypeFox and others.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0,
* or the Eclipse Distribution License v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.lsp4j;
import org.eclipse.lsp4j.Range;
import org.eclipse.lsp4j.jsonrpc.validation.NonNull;
import org.eclipse.lsp4j.util.Preconditions;
import org.eclipse.xtext.xbase.lib.Pure;
import org.eclipse.xtext.xbase.lib.util.ToStringBuilder;
/**
* Represents a link between a source and a target location.
*/
@SuppressWarnings("all")
public class LocationLink {
/**
* Span of the origin of this link.
* <p>
* Used as the underlined span for mouse interaction. Defaults to the word range at
* the mouse position.
*/
private Range originSelectionRange;
/**
* The target resource identifier of this link.
*/
@NonNull
private String targetUri;
/**
* The full target range of this link. If the target for example is a symbol then target range is the
* range enclosing this symbol not including leading/trailing whitespace but everything else
* like comments. This information is typically used to highlight the range in the editor.
*/
@NonNull
private Range targetRange;
/**
* The range that should be selected and revealed when this link is being followed, e.g the name of a function.
* Must be contained by the the {@link #targetRange}. See also {@link DocumentSymbol#range}
*/
@NonNull
private Range targetSelectionRange;
public LocationLink() {
}
public LocationLink(@NonNull final String targetUri, @NonNull final Range targetRange, @NonNull final Range targetSelectionRange) {
this.targetUri = Preconditions.<String>checkNotNull(targetUri, "targetUri");
this.targetRange = Preconditions.<Range>checkNotNull(targetRange, "targetRange");
this.targetSelectionRange = Preconditions.<Range>checkNotNull(targetSelectionRange, "targetSelectionRange");
}
public LocationLink(@NonNull final String targetUri, @NonNull final Range targetRange, @NonNull final Range targetSelectionRange, final Range originSelectionRange) {
this(targetUri, targetRange, targetSelectionRange);
this.originSelectionRange = originSelectionRange;
}
/**
* Span of the origin of this link.
* <p>
* Used as the underlined span for mouse interaction. Defaults to the word range at
* the mouse position.
*/
@Pure
public Range getOriginSelectionRange() {
return this.originSelectionRange;
}
/**
* Span of the origin of this link.
* <p>
* Used as the underlined span for mouse interaction. Defaults to the word range at
* the mouse position.
*/
public void setOriginSelectionRange(final Range originSelectionRange) {
this.originSelectionRange = originSelectionRange;
}
/**
* The target resource identifier of this link.
*/
@Pure
@NonNull
public String getTargetUri() {
return this.targetUri;
}
/**
* The target resource identifier of this link.
*/
public void setTargetUri(@NonNull final String targetUri) {
this.targetUri = Preconditions.checkNotNull(targetUri, "targetUri");
}
/**
* The full target range of this link. If the target for example is a symbol then target range is the
* range enclosing this symbol not including leading/trailing whitespace but everything else
* like comments. This information is typically used to highlight the range in the editor.
*/
@Pure
@NonNull
public Range getTargetRange() {
return this.targetRange;
}
/**
* The full target range of this link. If the target for example is a symbol then target range is the
* range enclosing this symbol not including leading/trailing whitespace but everything else
* like comments. This information is typically used to highlight the range in the editor.
*/
public void setTargetRange(@NonNull final Range targetRange) {
this.targetRange = Preconditions.checkNotNull(targetRange, "targetRange");
}
/**
* The range that should be selected and revealed when this link is being followed, e.g the name of a function.
* Must be contained by the the {@link #targetRange}. See also {@link DocumentSymbol#range}
*/
@Pure
@NonNull
public Range getTargetSelectionRange() {
return this.targetSelectionRange;
}
/**
* The range that should be selected and revealed when this link is being followed, e.g the name of a function.
* Must be contained by the the {@link #targetRange}. See also {@link DocumentSymbol#range}
*/
public void setTargetSelectionRange(@NonNull final Range targetSelectionRange) {
this.targetSelectionRange = Preconditions.checkNotNull(targetSelectionRange, "targetSelectionRange");
}
@Override
@Pure
public String toString() {
ToStringBuilder b = new ToStringBuilder(this);
b.add("originSelectionRange", this.originSelectionRange);
b.add("targetUri", this.targetUri);
b.add("targetRange", this.targetRange);
b.add("targetSelectionRange", this.targetSelectionRange);
return b.toString();
}
@Override
@Pure
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
LocationLink other = (LocationLink) obj;
if (this.originSelectionRange == null) {
if (other.originSelectionRange != null)
return false;
} else if (!this.originSelectionRange.equals(other.originSelectionRange))
return false;
if (this.targetUri == null) {
if (other.targetUri != null)
return false;
} else if (!this.targetUri.equals(other.targetUri))
return false;
if (this.targetRange == null) {
if (other.targetRange != null)
return false;
} else if (!this.targetRange.equals(other.targetRange))
return false;
if (this.targetSelectionRange == null) {
if (other.targetSelectionRange != null)
return false;
} else if (!this.targetSelectionRange.equals(other.targetSelectionRange))
return false;
return true;
}
@Override
@Pure
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.originSelectionRange== null) ? 0 : this.originSelectionRange.hashCode());
result = prime * result + ((this.targetUri== null) ? 0 : this.targetUri.hashCode());
result = prime * result + ((this.targetRange== null) ? 0 : this.targetRange.hashCode());
return prime * result + ((this.targetSelectionRange== null) ? 0 : this.targetSelectionRange.hashCode());
}
}
|
Omnicrola/voxel-cascade
|
src/main/java/com/omnicrola/voxel/entities/control/fx/ParticleEffectControlFactory.java
|
<filename>src/main/java/com/omnicrola/voxel/entities/control/fx/ParticleEffectControlFactory.java
package com.omnicrola.voxel.entities.control.fx;
import com.jme3.math.Vector3f;
import com.jme3.scene.Spatial;
import com.omnicrola.voxel.data.units.UnitDefinitionRepository;
import com.omnicrola.voxel.entities.Effect;
import com.omnicrola.voxel.entities.control.EntityControlAdapter;
import com.omnicrola.voxel.entities.control.IControlFactory;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Created by omnic on 3/13/2016.
*/
@XmlRootElement(name = "particle-effect")
public class ParticleEffectControlFactory implements IControlFactory {
public ParticleEffectControlFactory() {
}
@Override
public void build(Spatial spatial, UnitDefinitionRepository unitDefinitionRepository, EntityControlAdapter entityControlAdapter) {
Effect effect = entityControlAdapter.getParticleBuilder().cubicHarvest();
Vector3f offset = new Vector3f(0f, 0f, 0f);
ParticleAttachmentControl particleAttachmentControl = new ParticleAttachmentControl(effect, entityControlAdapter, offset);
spatial.addControl(particleAttachmentControl);
}
}
|
Andreas237/AndroidPolicyAutomation
|
ExtractedJars/RT_News_com.rt.mobile.english/javafiles/com/google/android/gms/internal/ads/zzasv.java
|
// Decompiled by Jad v1.5.8g. Copyright 2001 <NAME>.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.google.android.gms.internal.ads;
import android.graphics.Canvas;
import android.view.MotionEvent;
import android.webkit.ValueCallback;
import com.google.android.gms.ads.internal.zzbv;
import java.util.concurrent.Executor;
// Referenced classes of package com.google.android.gms.internal.ads:
// zzass, zzajm, zzakb, zzaoe,
// zzasw, zzash, zzasu
public class zzasv extends zzass
{
public zzasv(zzash zzash)
{
super(zzash);
// 0 0:aload_0
// 1 1:aload_1
// 2 2:invokespecial #16 <Method void zzass(zzash)>
zzbv.zzeo().zzqe();
// 3 5:invokestatic #22 <Method zzajm zzbv.zzeo()>
// 4 8:invokevirtual #28 <Method void zzajm.zzqe()>
// 5 11:return
}
private final void zzqf()
{
this;
// 0 0:aload_0
JVM INSTR monitorenter ;
// 1 1:monitorenter
if(!zzdfi)
//* 2 2:aload_0
//* 3 3:getfield #32 <Field boolean zzdfi>
//* 4 6:ifne 20
{
zzdfi = true;
// 5 9:aload_0
// 6 10:iconst_1
// 7 11:putfield #32 <Field boolean zzdfi>
zzbv.zzeo().zzqf();
// 8 14:invokestatic #22 <Method zzajm zzbv.zzeo()>
// 9 17:invokevirtual #34 <Method void zzajm.zzqf()>
}
this;
// 10 20:aload_0
JVM INSTR monitorexit ;
// 11 21:monitorexit
return;
// 12 22:return
Exception exception;
exception;
// 13 23:astore_1
//* 14 24:aload_0
throw exception;
// 15 25:monitorexit
// 16 26:aload_1
// 17 27:athrow
}
public void destroy()
{
this;
// 0 0:aload_0
JVM INSTR monitorenter ;
// 1 1:monitorenter
boolean flag = zzdfh;
// 2 2:aload_0
// 3 3:getfield #39 <Field boolean zzdfh>
// 4 6:istore_1
if(!flag)
break MISSING_BLOCK_LABEL_14;
// 5 7:iload_1
// 6 8:ifeq 14
this;
// 7 11:aload_0
JVM INSTR monitorexit ;
// 8 12:monitorexit
return;
// 9 13:return
zzdfh = true;
// 10 14:aload_0
// 11 15:iconst_1
// 12 16:putfield #39 <Field boolean zzdfh>
zzam(false);
// 13 19:aload_0
// 14 20:iconst_0
// 15 21:invokevirtual #43 <Method void zzam(boolean)>
zzakb.v("Initiating WebView self destruct sequence in 3...");
// 16 24:ldc1 #45 <String "Initiating WebView self destruct sequence in 3...">
// 17 26:invokestatic #51 <Method void zzakb.v(String)>
zzakb.v("Loading blank page in WebView, 2...");
// 18 29:ldc1 #53 <String "Loading blank page in WebView, 2...">
// 19 31:invokestatic #51 <Method void zzakb.v(String)>
super.loadUrl("about:blank");
// 20 34:aload_0
// 21 35:ldc1 #55 <String "about:blank">
// 22 37:invokespecial #58 <Method void zzass.loadUrl(String)>
this;
// 23 40:aload_0
JVM INSTR monitorexit ;
// 24 41:monitorexit
return;
// 25 42:return
Object obj;
obj;
// 26 43:astore_2
zzbv.zzeo().zza(((Throwable) (obj)), "AdWebViewImpl.loadUrlUnsafe");
// 27 44:invokestatic #22 <Method zzajm zzbv.zzeo()>
// 28 47:aload_2
// 29 48:ldc1 #60 <String "AdWebViewImpl.loadUrlUnsafe">
// 30 50:invokevirtual #64 <Method void zzajm.zza(Throwable, String)>
zzakb.zzd("#007 Could not call remote method.", ((Throwable) (obj)));
// 31 53:ldc1 #66 <String "#007 Could not call remote method.">
// 32 55:aload_2
// 33 56:invokestatic #70 <Method void zzakb.zzd(String, Throwable)>
this;
// 34 59:aload_0
JVM INSTR monitorexit ;
// 35 60:monitorexit
return;
// 36 61:return
obj;
// 37 62:astore_2
//* 38 63:aload_0
throw obj;
// 39 64:monitorexit
// 40 65:aload_2
// 41 66:athrow
}
public void evaluateJavascript(String s, ValueCallback valuecallback)
{
this;
// 0 0:aload_0
JVM INSTR monitorenter ;
// 1 1:monitorenter
if(!isDestroyed())
break MISSING_BLOCK_LABEL_28;
// 2 2:aload_0
// 3 3:invokevirtual #78 <Method boolean isDestroyed()>
// 4 6:ifeq 28
zzakb.zzdk("#004 The webview is destroyed. Ignoring action.");
// 5 9:ldc1 #80 <String "#004 The webview is destroyed. Ignoring action.">
// 6 11:invokestatic #83 <Method void zzakb.zzdk(String)>
if(valuecallback == null)
break MISSING_BLOCK_LABEL_25;
// 7 14:aload_2
// 8 15:ifnull 25
valuecallback.onReceiveValue(((Object) (null)));
// 9 18:aload_2
// 10 19:aconst_null
// 11 20:invokeinterface #89 <Method void ValueCallback.onReceiveValue(Object)>
this;
// 12 25:aload_0
JVM INSTR monitorexit ;
// 13 26:monitorexit
return;
// 14 27:return
super.evaluateJavascript(s, valuecallback);
// 15 28:aload_0
// 16 29:aload_1
// 17 30:aload_2
// 18 31:invokespecial #91 <Method void zzass.evaluateJavascript(String, ValueCallback)>
this;
// 19 34:aload_0
JVM INSTR monitorexit ;
// 20 35:monitorexit
return;
// 21 36:return
s;
// 22 37:astore_1
//* 23 38:aload_0
throw s;
// 24 39:monitorexit
// 25 40:aload_1
// 26 41:athrow
}
protected void finalize()
throws Throwable
{
this;
// 0 0:aload_0
JVM INSTR monitorenter ;
// 1 1:monitorenter
if(!isDestroyed())
//* 2 2:aload_0
//* 3 3:invokevirtual #78 <Method boolean isDestroyed()>
//* 4 6:ifne 14
zzam(true);
// 5 9:aload_0
// 6 10:iconst_1
// 7 11:invokevirtual #43 <Method void zzam(boolean)>
zzqf();
// 8 14:aload_0
// 9 15:invokespecial #98 <Method void zzqf()>
this;
// 10 18:aload_0
JVM INSTR monitorexit ;
// 11 19:monitorexit
((Object)this).finalize();
// 12 20:aload_0
// 13 21:invokespecial #102 <Method void Object.finalize()>
return;
// 14 24:return
Exception exception;
exception;
// 15 25:astore_1
this;
// 16 26:aload_0
JVM INSTR monitorexit ;
// 17 27:monitorexit
throw exception;
// 18 28:aload_1
// 19 29:athrow
exception;
// 20 30:astore_1
((Object)this).finalize();
// 21 31:aload_0
// 22 32:invokespecial #102 <Method void Object.finalize()>
throw exception;
// 23 35:aload_1
// 24 36:athrow
}
public final boolean isDestroyed()
{
this;
// 0 0:aload_0
JVM INSTR monitorenter ;
// 1 1:monitorenter
boolean flag = zzdfh;
// 2 2:aload_0
// 3 3:getfield #39 <Field boolean zzdfh>
// 4 6:istore_1
this;
// 5 7:aload_0
JVM INSTR monitorexit ;
// 6 8:monitorexit
return flag;
// 7 9:iload_1
// 8 10:ireturn
Exception exception;
exception;
// 9 11:astore_2
//* 10 12:aload_0
throw exception;
// 11 13:monitorexit
// 12 14:aload_2
// 13 15:athrow
}
public void loadData(String s, String s1, String s2)
{
this;
// 0 0:aload_0
JVM INSTR monitorenter ;
// 1 1:monitorenter
if(isDestroyed())
break MISSING_BLOCK_LABEL_19;
// 2 2:aload_0
// 3 3:invokevirtual #78 <Method boolean isDestroyed()>
// 4 6:ifne 19
super.loadData(s, s1, s2);
// 5 9:aload_0
// 6 10:aload_1
// 7 11:aload_2
// 8 12:aload_3
// 9 13:invokespecial #107 <Method void zzass.loadData(String, String, String)>
this;
// 10 16:aload_0
JVM INSTR monitorexit ;
// 11 17:monitorexit
return;
// 12 18:return
zzakb.zzdk("#004 The webview is destroyed. Ignoring action.");
// 13 19:ldc1 #80 <String "#004 The webview is destroyed. Ignoring action.">
// 14 21:invokestatic #83 <Method void zzakb.zzdk(String)>
this;
// 15 24:aload_0
JVM INSTR monitorexit ;
// 16 25:monitorexit
return;
// 17 26:return
s;
// 18 27:astore_1
//* 19 28:aload_0
throw s;
// 20 29:monitorexit
// 21 30:aload_1
// 22 31:athrow
}
public void loadDataWithBaseURL(String s, String s1, String s2, String s3, String s4)
{
this;
// 0 0:aload_0
JVM INSTR monitorenter ;
// 1 1:monitorenter
if(isDestroyed())
break MISSING_BLOCK_LABEL_23;
// 2 2:aload_0
// 3 3:invokevirtual #78 <Method boolean isDestroyed()>
// 4 6:ifne 23
super.loadDataWithBaseURL(s, s1, s2, s3, s4);
// 5 9:aload_0
// 6 10:aload_1
// 7 11:aload_2
// 8 12:aload_3
// 9 13:aload 4
// 10 15:aload 5
// 11 17:invokespecial #111 <Method void zzass.loadDataWithBaseURL(String, String, String, String, String)>
this;
// 12 20:aload_0
JVM INSTR monitorexit ;
// 13 21:monitorexit
return;
// 14 22:return
zzakb.zzdk("#004 The webview is destroyed. Ignoring action.");
// 15 23:ldc1 #80 <String "#004 The webview is destroyed. Ignoring action.">
// 16 25:invokestatic #83 <Method void zzakb.zzdk(String)>
this;
// 17 28:aload_0
JVM INSTR monitorexit ;
// 18 29:monitorexit
return;
// 19 30:return
s;
// 20 31:astore_1
//* 21 32:aload_0
throw s;
// 22 33:monitorexit
// 23 34:aload_1
// 24 35:athrow
}
public void loadUrl(String s)
{
this;
// 0 0:aload_0
JVM INSTR monitorenter ;
// 1 1:monitorenter
if(isDestroyed())
break MISSING_BLOCK_LABEL_17;
// 2 2:aload_0
// 3 3:invokevirtual #78 <Method boolean isDestroyed()>
// 4 6:ifne 17
super.loadUrl(s);
// 5 9:aload_0
// 6 10:aload_1
// 7 11:invokespecial #58 <Method void zzass.loadUrl(String)>
this;
// 8 14:aload_0
JVM INSTR monitorexit ;
// 9 15:monitorexit
return;
// 10 16:return
zzakb.zzdk("#004 The webview is destroyed. Ignoring action.");
// 11 17:ldc1 #80 <String "#004 The webview is destroyed. Ignoring action.">
// 12 19:invokestatic #83 <Method void zzakb.zzdk(String)>
this;
// 13 22:aload_0
JVM INSTR monitorexit ;
// 14 23:monitorexit
return;
// 15 24:return
s;
// 16 25:astore_1
//* 17 26:aload_0
throw s;
// 18 27:monitorexit
// 19 28:aload_1
// 20 29:athrow
}
protected void onDraw(Canvas canvas)
{
if(isDestroyed())
//* 0 0:aload_0
//* 1 1:invokevirtual #78 <Method boolean isDestroyed()>
//* 2 4:ifeq 8
{
return;
// 3 7:return
} else
{
super.onDraw(canvas);
// 4 8:aload_0
// 5 9:aload_1
// 6 10:invokespecial #116 <Method void zzass.onDraw(Canvas)>
return;
// 7 13:return
}
}
public void onPause()
{
if(isDestroyed())
//* 0 0:aload_0
//* 1 1:invokevirtual #78 <Method boolean isDestroyed()>
//* 2 4:ifeq 8
{
return;
// 3 7:return
} else
{
super.onPause();
// 4 8:aload_0
// 5 9:invokespecial #119 <Method void zzass.onPause()>
return;
// 6 12:return
}
}
public void onResume()
{
if(isDestroyed())
//* 0 0:aload_0
//* 1 1:invokevirtual #78 <Method boolean isDestroyed()>
//* 2 4:ifeq 8
{
return;
// 3 7:return
} else
{
super.onResume();
// 4 8:aload_0
// 5 9:invokespecial #122 <Method void zzass.onResume()>
return;
// 6 12:return
}
}
public boolean onTouchEvent(MotionEvent motionevent)
{
return !isDestroyed() && super.onTouchEvent(motionevent);
// 0 0:aload_0
// 1 1:invokevirtual #78 <Method boolean isDestroyed()>
// 2 4:ifne 17
// 3 7:aload_0
// 4 8:aload_1
// 5 9:invokespecial #126 <Method boolean zzass.onTouchEvent(MotionEvent)>
// 6 12:ifeq 17
// 7 15:iconst_1
// 8 16:ireturn
// 9 17:iconst_0
// 10 18:ireturn
}
public void stopLoading()
{
if(isDestroyed())
//* 0 0:aload_0
//* 1 1:invokevirtual #78 <Method boolean isDestroyed()>
//* 2 4:ifeq 8
{
return;
// 3 7:return
} else
{
super.stopLoading();
// 4 8:aload_0
// 5 9:invokespecial #129 <Method void zzass.stopLoading()>
return;
// 6 12:return
}
}
protected void zzam(boolean flag)
{
// 0 0:return
}
public final void zzc(zzasu zzasu)
{
this;
// 0 0:aload_0
JVM INSTR monitorenter ;
// 1 1:monitorenter
if(!isDestroyed())
break MISSING_BLOCK_LABEL_21;
// 2 2:aload_0
// 3 3:invokevirtual #78 <Method boolean isDestroyed()>
// 4 6:ifeq 21
zzakb.v("Blank page loaded, 1...");
// 5 9:ldc1 #133 <String "Blank page loaded, 1...">
// 6 11:invokestatic #51 <Method void zzakb.v(String)>
zzuk();
// 7 14:aload_0
// 8 15:invokevirtual #136 <Method void zzuk()>
this;
// 9 18:aload_0
JVM INSTR monitorexit ;
// 10 19:monitorexit
return;
// 11 20:return
super.zzc(zzasu);
// 12 21:aload_0
// 13 22:aload_1
// 14 23:invokespecial #138 <Method void zzass.zzc(zzasu)>
this;
// 15 26:aload_0
JVM INSTR monitorexit ;
// 16 27:monitorexit
return;
// 17 28:return
zzasu;
// 18 29:astore_1
//* 19 30:aload_0
throw zzasu;
// 20 31:monitorexit
// 21 32:aload_1
// 22 33:athrow
}
public final void zzuk()
{
this;
// 0 0:aload_0
JVM INSTR monitorenter ;
// 1 1:monitorenter
zzakb.v("Destroying WebView!");
// 2 2:ldc1 #140 <String "Destroying WebView!">
// 3 4:invokestatic #51 <Method void zzakb.v(String)>
zzqf();
// 4 7:aload_0
// 5 8:invokespecial #98 <Method void zzqf()>
zzaoe.zzcvy.execute(((Runnable) (new zzasw(this))));
// 6 11:getstatic #146 <Field Executor zzaoe.zzcvy>
// 7 14:new #148 <Class zzasw>
// 8 17:dup
// 9 18:aload_0
// 10 19:invokespecial #151 <Method void zzasw(zzasv)>
// 11 22:invokeinterface #157 <Method void Executor.execute(Runnable)>
this;
// 12 27:aload_0
JVM INSTR monitorexit ;
// 13 28:monitorexit
return;
// 14 29:return
Exception exception;
exception;
// 15 30:astore_1
//* 16 31:aload_0
throw exception;
// 17 32:monitorexit
// 18 33:aload_1
// 19 34:athrow
}
final void zzvw()
{
super.destroy();
// 0 0:aload_0
// 1 1:invokespecial #160 <Method void zzass.destroy()>
// 2 4:return
}
private boolean zzdfh;
private boolean zzdfi;
}
|
CRamsan/auraxiscontrolcenter
|
app/src/main/java/com/cesarandres/ps2link/fragments/FragmentMainMenu.java
|
<gh_stars>1-10
package com.cesarandres.ps2link.fragments;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.Toast;
import com.android.vending.billing.IInAppBillingService;
import com.cesarandres.ps2link.ApplicationPS2Link;
import com.cesarandres.ps2link.ApplicationPS2Link.ActivityMode;
import com.cesarandres.ps2link.R;
import com.cesarandres.ps2link.base.BaseFragment;
import com.cesarandres.ps2link.dbg.DBGCensus.Namespace;
import com.cesarandres.ps2link.module.BitmapWorkerTask;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import android.support.v4.content.*;
import android.*;
import android.content.pm.*;
import android.support.v4.app.*;
/**
* This fragment is very static, it has all the buttons for most of the main
* fragments. It will also display the Preferred Character and Preferred Outfit
* buttons if those have been set.
*/
public class FragmentMainMenu extends BaseFragment {
private static IInAppBillingService mService;
private ServiceConnection mServiceConn;
/*
* (non-Javadoc)
*
* @see com.cesarandres.ps2link.base.BaseFragment#onCreateView(android.view.
* LayoutInflater, android.view.ViewGroup, android.os.Bundle)
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main_menu, container, false);
}
/*
* (non-Javadoc)
*
* @see
* com.cesarandres.ps2link.base.BaseFragment#onActivityCreated(android.os
* .Bundle)
*/
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this.fragmentTitle.setText(getString(R.string.app_name_capital));
Button buttonCharacters = (Button) getActivity().findViewById(R.id.buttonCharacters);
Button buttonServers = (Button) getActivity().findViewById(R.id.buttonServers);
Button buttonOutfit = (Button) getActivity().findViewById(R.id.buttonOutfit);
Button buttonNews = (Button) getActivity().findViewById(R.id.buttonNews);
Button buttonTwitter = (Button) getActivity().findViewById(R.id.buttonTwitter);
Button buttonReddit = (Button) getActivity().findViewById(R.id.buttonRedditFragment);
Button buttonDonate = (Button) getActivity().findViewById(R.id.buttonDonate);
Button buttonAbout = (Button) getActivity().findViewById(R.id.buttonAbout);
Button buttonSettings = (Button) getActivity().findViewById(R.id.buttonSettings);
buttonCharacters.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mCallbacks.onItemSelected(ActivityMode.ACTIVITY_PROFILE_LIST.toString(), null);
}
});
buttonServers.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mCallbacks.onItemSelected(ActivityMode.ACTIVITY_SERVER_LIST.toString(), null);
}
});
buttonOutfit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mCallbacks.onItemSelected(ActivityMode.ACTIVITY_OUTFIT_LIST.toString(), null);
}
});
buttonNews.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mCallbacks.onItemSelected(ActivityMode.ACTIVITY_LINK_MENU.toString(), null);
}
});
buttonTwitter.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mCallbacks.onItemSelected(ActivityMode.ACTIVITY_TWITTER.toString(), null);
}
});
buttonReddit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mCallbacks.onItemSelected(ActivityMode.ACTIVITY_REDDIT.toString(), null);
}
});
buttonAbout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mCallbacks.onItemSelected(ActivityMode.ACTIVITY_ABOUT.toString(), null);
}
});
buttonDonate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (mService != null) {
DownloadDonationsTask task = new DownloadDonationsTask();
setCurrentTask(task);
task.execute();
}
}
});
buttonSettings.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
mCallbacks.onItemSelected(ActivityMode.ACTIVITY_SETTINGS.toString(), null);
}
});
final ImageButton buttonPS2Background = (ImageButton) getActivity().findViewById(R.id.buttonPS2);
buttonPS2Background.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ImageView background = ((ImageView) getActivity().findViewById(R.id.imageViewBackground));
background.setImageResource(R.drawable.ps2_activity_background);
background.setScaleType(ScaleType.FIT_START);
SharedPreferences settings = getActivity().getSharedPreferences("PREFERENCES", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("preferedWallpaper", ApplicationPS2Link.WallPaperMode.PS2.toString());
editor.commit();
}
});
final ImageButton buttonNCBackground = (ImageButton) getActivity().findViewById(R.id.buttonNC);
buttonNCBackground.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
promptForPermissions();
BitmapWorkerTask task = new BitmapWorkerTask((ImageView) (getActivity().findViewById(R.id.imageViewBackground)), getActivity());
task.execute("nc_wallpaper.jpg");
SharedPreferences settings = getActivity().getSharedPreferences("PREFERENCES", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("preferedWallpaper", ApplicationPS2Link.WallPaperMode.NC.toString());
editor.commit();
}
});
final ImageButton buttonTRBackground = (ImageButton) getActivity().findViewById(R.id.buttonTR);
buttonTRBackground.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
promptForPermissions();
BitmapWorkerTask task = new BitmapWorkerTask((ImageView) (getActivity().findViewById(R.id.imageViewBackground)), getActivity());
task.execute("tr_wallpaper.jpg");
SharedPreferences settings = getActivity().getSharedPreferences("PREFERENCES", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("preferedWallpaper", ApplicationPS2Link.WallPaperMode.TR.toString());
editor.commit();
}
});
final ImageButton buttonVSBackground = (ImageButton) getActivity().findViewById(R.id.buttonVS);
buttonVSBackground.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
promptForPermissions();
BitmapWorkerTask task = new BitmapWorkerTask((ImageView) (getActivity().findViewById(R.id.imageViewBackground)), getActivity());
task.execute("vs_wallpaper.jpg");
SharedPreferences settings = getActivity().getSharedPreferences("PREFERENCES", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("preferedWallpaper", ApplicationPS2Link.WallPaperMode.VS.toString());
editor.commit();
}
});
mServiceConn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
@Override
public void onServiceConnected(ComponentName name,
IBinder service) {
mService = IInAppBillingService.Stub.asInterface(service);
}
};
Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
serviceIntent.setPackage("com.android.vending");
getActivity().bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
}
/*
* (non-Javadoc)
*
* @see com.cesarandres.ps2link.base.BaseFragment#onResume()
*/
@Override
public void onResume() {
super.onResume();
checkPreferedButtons();
}
/**
* This function will check the preferences to see if any profile or outfit
* has been set as preferred. If any has been set then the respective button
* will be displayed, they will be hidden otherwise.
*/
public void checkPreferedButtons() {
SharedPreferences settings = getActivity().getSharedPreferences("PREFERENCES", 0);
String preferedProfileId = settings.getString("preferedProfile", "");
String preferedProfileName = settings.getString("preferedProfileName", "");
final Button buttonPreferedProfile = (Button) getActivity().findViewById(R.id.buttonPreferedProfile);
if (!preferedProfileId.equals("")) {
buttonPreferedProfile.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SharedPreferences settings = getActivity().getSharedPreferences("PREFERENCES", 0);
mCallbacks.onItemSelected(ApplicationPS2Link.ActivityMode.ACTIVITY_PROFILE.toString(),
new String[]{settings.getString("preferedProfile", ""),
settings.getString("preferedProfileNamespace", Namespace.PS2PC.name())});
}
});
buttonPreferedProfile.setText(preferedProfileName);
buttonPreferedProfile.setVisibility(View.VISIBLE);
} else {
buttonPreferedProfile.setVisibility(View.GONE);
}
String preferedOutfitId = settings.getString("preferedOutfit", "");
String preferedOutfitName = settings.getString("preferedOutfitName", "");
final Button buttonPreferedOutfit = (Button) getActivity().findViewById(R.id.buttonPreferedOutfit);
if (!preferedOutfitId.equals("")) {
buttonPreferedOutfit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SharedPreferences settings = getActivity().getSharedPreferences("PREFERENCES", 0);
mCallbacks.onItemSelected(ApplicationPS2Link.ActivityMode.ACTIVITY_MEMBER_LIST.toString(),
new String[]{settings.getString("preferedOutfit", ""),
settings.getString("preferedOutfitNamespace", Namespace.PS2PC.name())});
}
});
buttonPreferedOutfit.setVisibility(View.VISIBLE);
buttonPreferedOutfit.setText(preferedOutfitName);
} else {
buttonPreferedOutfit.setVisibility(View.GONE);
}
}
/* (non-Javadoc)
* @see com.cesarandres.ps2link.base.BaseFragment#onDestroy()
*/
@Override
public void onDestroy() {
super.onDestroy();
if (mService != null) {
getActivity().unbindService(mServiceConn);
}
}
public void promptForPermissions() {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
0);
}
}
/**
* @author cramsan
*/
private class DownloadDonationsTask extends AsyncTask<Void, Void, ArrayList<String>> {
/* (non-Javadoc)
* @see android.os.AsyncTask#doInBackground(java.lang.Object[])
*/
@Override
protected ArrayList<String> doInBackground(Void... params) {
int response = -1;
Bundle ownedItems;
try {
ownedItems = mService.getPurchases(3, getActivity().getPackageName(), "inapp", null);
response = ownedItems.getInt("RESPONSE_CODE");
} catch (RemoteException e1) {
e1.printStackTrace();
return null;
}
if (response == 0) {
ArrayList<String> purchaseDataList = ownedItems.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
for (int i = 0; i < purchaseDataList.size(); ++i) {
String purchaseData = purchaseDataList.get(i);
try {
JSONObject ownedObject;
ownedObject = new JSONObject(purchaseData);
String token = ownedObject.getString("purchaseToken");
response = mService.consumePurchase(3, getActivity().getPackageName(), token);
} catch (JSONException e) {
e.printStackTrace();
return null;
} catch (RemoteException e) {
e.printStackTrace();
return null;
}
}
}
ArrayList<String> skuList = new ArrayList<String>();
skuList.add("item_donation_1");
skuList.add("item_donation_2");
skuList.add("item_donation_3");
skuList.add("item_donation_4");
Bundle querySkus = new Bundle();
querySkus.putStringArrayList("ITEM_ID_LIST", skuList);
Bundle skuDetails;
try {
skuDetails = mService.getSkuDetails(3, getActivity().getPackageName(), "inapp", querySkus);
response = skuDetails.getInt("RESPONSE_CODE");
if (response == 0) {
return skuDetails.getStringArrayList("DETAILS_LIST");
} else {
return null;
}
} catch (RemoteException e) {
e.printStackTrace();
return null;
}
}
/* (non-Javadoc)
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
protected void onPostExecute(ArrayList<String> result) {
if (result != null) {
if (result.size() > 0) {
DonationsDialogFragment newFragment = new DonationsDialogFragment();
if (!newFragment.setResponseList(result)) {
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.toast_error_server_error), Toast.LENGTH_LONG).show();
return;
}
FragmentManager manager = getActivity().getSupportFragmentManager();
if (manager != null) {
newFragment.show(manager, "donations");
} else {
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.toast_error_empty_response), Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.toast_error_empty_response), Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.toast_error_response_error), Toast.LENGTH_LONG).show();
}
}
}
public static class DonationsDialogFragment extends DialogFragment {
private ArrayList<String> responseList;
private CharSequence[] displayData;
public DonationsDialogFragment(){
super();
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.text_choose_donation)
.setItems(displayData, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int index) {
String thisResponse = responseList.get(index);
JSONObject object;
try {
object = new JSONObject(thisResponse);
String sku = object.getString("productId");
Bundle buyIntentBundle = mService.getBuyIntent(3, getActivity().getPackageName(), sku, "inapp", "");
PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
getActivity().startIntentSenderForResult(pendingIntent.getIntentSender(),
1001, new Intent(), Integer.valueOf(0), Integer.valueOf(0),
Integer.valueOf(0));
return;
} catch (JSONException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
} catch (SendIntentException e) {
e.printStackTrace();
}
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.toast_error_error_sending), Toast.LENGTH_LONG).show();
return;
}
});
setRetainInstance(true);
return builder.create();
}
public boolean setResponseList(ArrayList<String> responseList) {
this.displayData = new String[responseList.size()];
for (int i = 0; i < responseList.size(); i++) {
String thisResponse = responseList.get(i);
try {
JSONObject object = new JSONObject(thisResponse);
String sku = object.getString("title");
displayData[i] = sku;
} catch (JSONException e) {
e.printStackTrace();
return false;
}
}
this.responseList = responseList;
return true;
}
}
}
|
miguel567/nftgallery
|
node_modules/@walletconnect/browser-utils/dist/cjs/index.js
|
<reponame>miguel567/nftgallery
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
tslib_1.__exportStar(require("./browser"), exports);
tslib_1.__exportStar(require("./json"), exports);
tslib_1.__exportStar(require("./local"), exports);
tslib_1.__exportStar(require("./mobile"), exports);
tslib_1.__exportStar(require("./registry"), exports);
//# sourceMappingURL=index.js.map
|
HarshaNalluru/gdg
|
node_modules/assertions/test/assert.expresso.js
|
//asserters.expresso.js
var asserters = require('../')
, assert = require('assert')
var deleted_a = {a: true}
delete deleted_a.a
var a,b,c,d,e
var examples =
{ ok : {
pass : [[1], [2], [-1], ['sadf'], [true], [[]], [{}]]
, fail : [[0],[false],[null],[undefined]]
}
, equal : {
pass : [ [1,1], [2,2.0], [-1,-1], ['sadf','sadf'], [true,1]
, [a = [], a], [b = {}, b]]
, fail : [ [0,1], [[],[]] ]
}
, isTypeof : {
pass : [ [1, 'number']
, [NaN, 'number']
, ['', 'string']
, [{}, 'object']
, [null,'object']
, [undefined, 'undefined'] ]
, fail : [ [0, 'string'] ]
}
, isString : {
pass : [ ['uoeaueu'] ]
, fail : [ [0], [/aoeuaoeu/], [{}], [[]], [true] ]
}
, isNumber: {
pass : [ [10], [0], [-1], [NaN], [-1.7976931348623157E+1030], , [1.7976931348623157E+1030] ]
, fail : [ [/aoeuaoeu/], [{}], [[]], [true], [undefined] ]
}
, isBoolean: {
pass : [ [true], [false]]
, fail : [ ['true'], ['false'], [0], [1], [null], [undefined] ]
}
, isUndefined: {
pass : [ [undefined]]
, fail : [ ['true'], ['false'], [0], [1], [null], [true], [false] ]
}
, isNull: {
pass : [ [null]]
, fail : [ ['true'], ['false'], [0], [1], [undefined], [true], [false] ]
}
, isInstanceof : {
pass : [ [{}, Object], [[], Object], [[], Array]
, [new Error, Error], [function (){}, Function]]
, fail : [ [{}, Array] ]
}
, has : {// has basicially checks if expected is a sub tree of actual.
pass : [ [{a: 1}, {a: 1}]
, [{a: 1, b: 2}, {a: 1}]
, [{a: 1}, {a: assert.ok}] //also, it applies functions in expected
]
, fail : [ [{a: 1}, {a: 1, b: 2}]
, [{a: 1}, {a: {}}]
, [{}, {a: {}}]
, [{a: false}, {a: assert.ok}]
]
}
, every : {
pass : [ [[1,2,3,4,5],assert.ok] ]
, fail : [ [[1,2,3,4,5,false],assert.ok] ]
}
, primitive : {
pass : [ [1], [2], [3], ['sadgsdf'] [true], [false], [undefined] ]
, fail : [ [null], [[]], [{}], [new Error], [function (){}] ]
}
, complex : {
pass : [ [null], [[]], [{}], [new Error], [function (){}] ]
, fail : [ [1], [2], [3], ['sadgsdf'] [true], [false], [undefined] ]
}
, isFunction : {
pass : [ [function(){}], [Error], [({}).constructor] ]
, fail : [ [1], [2], [3], ['sadgsdf'] [true], [false], [undefined] ]
}
, matches : {
pass : [ ['hello', /\w+/] , ['asdgsadg', /[a|s|d|g]+/] ]
, fail : [ ['sgfg-', /^\w+$/] ]
}
//like (actual,expected,{case:boolean,whitespace:boolean,quotes:boolean}) //all default to on.
, like : {
pass :
[ ['hello\n', 'hello']
, ['asdgsadg', 'ASDGSADG']
, ['"quoted"', "'quoted'"]
, ['1234', '1\n2\n3\n4\n']
]
, fail :
[ ['hello\n', 'hello', {whitespace: true}]
, ['asdgsadg', 'ASDGSADG', {case: true}]
, ['"quoted"', "'quoted'", {quotes: true}]
]
}
, property : {
pass : [ [{a:true}, 'a'], [[],'length',0], ['hello','length', 5], [{a:1}, 'a', assert.ok ], [{a:null}, 'a', function (actual){assert.equal(actual,null)} ] ]
, fail : [ [{}, 'a'], [deleted_a, 'a'], [{a:undefined}, 'a'], ['hello','length', 7] ,[{a:false}, 'a', assert.ok]]
}
, lessThan: {
pass: [ [1, 2], [0, 1], [-1, 0] ]
, fail: [ [1, 0], [0, 0] ]
}
, greaterThan: {
pass: [ [1, 0] ]
, fail: [ [1, 2], [0, 1], [-1, 0], [0, 0] ]
}
, lessThanOrEqual: {
pass: [ [1, 2], [0, 1], [-1, 0], [0, 0] ]
, fail: [ [1, 0] ]
}
, greaterThanOrEqual: {
pass: [ [1, 0], [0, 0] ]
, fail: [ [1, 2], [0, 1], [-1, 0] ]
}
, between: {
pass: [ [1, 0, 2], [0, -1, 1] ]
, fail: [ [1, 2, 3], [0, 0, 1], [-1, 0] ]
}
, betweenOrEqual: {
pass: [ [1, 1, 2], [0, -1, 1], [0, 0, 0] ]
, fail: [ [1, 2, 3], [0, 0.1, 1], [-1, 0] ]
}
, isValidDate: {
pass: [ [new Date().toString()], [Date.now()], ['2009-06-29T11:11:55Z'] , [1], [null]]
, fail: [ [{}], ['euthoeu'] ]
}
, contains: {
pass: [ [[1,2,3], 1], [[1,2,3], 2], [['a', 'b', 'c'], 'c'], ['hello there' , 'hell']]
, fail: [ [[], 1], ['euthoeu', 'x'] ]
}
, includes: {
pass: [ [2, [1,2,3]], [3, [1,2,3]], ['c', ['a', 'b', 'c']], ['the', 'hello there']]
, fail: [ [1, []], ['x', 'euthoeu'] ]
}
, isArray: {
pass: [ [[]] ]
, fail: [ [{}], ['euthoeu'], [/ouoeu/], [42], [null], [true] ]
}
, isEmpty: {
pass: [ [[]] ]
, fail: [ [ [1,2] ], [ 2 ], [true] ]
}
}
exports ['check examples'] = function (){
// check('ok')
for(i in examples){
check(i)
}
}
function check(name){
//check passes
examples[name].pass.forEach(function (e,k){
asserters[name].apply(null,e)
})
//check fails
examples[name].fail.forEach(function (e){
try {
asserters[name].apply(null,e)
} catch (err){
// if(!(err instanceof assert.AssertionError))
// throw err
return
}
assert.ok(false,"expected " + name + "(" + e.join() + ") to fail")
})
}
exports ['every'] = function (){
asserters.every([1,2,3,4,5,6],function (x){
assert.ok('number' == typeof x)
})
assert.throws(function(){
asserters.every([1,2,'asda',4,5,6],function (x){
assert.ok('number' == typeof x)
})
})
}
/*
the node js behaviour here is annoying, and not consistant with my higher order assertions.
*/
/*
exports ['throws can check what object is thrown'] = function (){
var called = 0
, err = new Error("HELLO")
var examples =
[ [ function () {throw err}
, function (thrown) { called ++; assert.equal(thrown, err) } ]
, [ function () {throw err} ]
]
examples.forEach(function (c){
asserters.throws.apply(null,c)
})
assert.equal(1, called)
}
*/
exports ['every intercepts error, records item errored at'] = function (){
var examples =
[ [ [1,2,3,4,5,null], assert.ok, 5]
, [ [null,'sadf','sadfg'], assert.ok, 0]
, [ [null,null,null,1], assert.ifError, 3]
]
// asserters.every([null,null,null,1], assert.ifError)
examples.forEach(function (e){
try {
asserters.every(e[0],e[1])
} catch (err) {
return
}
assert.ok(false, "expected 'every' to fail")
})
}
exports ['has intercepts error, records path item errored at'] = function (){
var examples =
[ [ {a: null}, {a: assert.ok}, ['a']]
, [ {'a-b-c': {0: {x: false } } }, {'a-b-c': {0 : {x:assert.ok}}}, ['a-b-c',0,'x']]
, [ {a:{}},{a:{b: 1}}, ['a','b']]
]
examples.forEach(function (e){
try {
asserters.has(e[0],e[1])
} catch (err) {
return
}
assert.ok(false,"expected has to throw error at path " + inspect(e[2]))
})
}
|
ice1000/la-clojure-devkt
|
src/org/jetbrains/plugin/devkt/clojure/psi/stubs/api/ClNsStub.java
|
package org.jetbrains.plugin.devkt.clojure.psi.stubs.api;
import org.jetbrains.kotlin.com.intellij.psi.stubs.IStubElementType;
import org.jetbrains.kotlin.com.intellij.psi.stubs.NamedStub;
import org.jetbrains.kotlin.com.intellij.psi.stubs.StubBase;
import org.jetbrains.kotlin.com.intellij.psi.stubs.StubElement;
import org.jetbrains.kotlin.com.intellij.util.io.StringRef;
import org.jetbrains.plugin.devkt.clojure.psi.api.ns.ClNs;
/**
* @author ilyas
*/
public class ClNsStub extends StubBase<ClNs> implements NamedStub<ClNs> {
private final StringRef myName;
private final int myTextOffset;
public ClNsStub(StubElement parent, StringRef name, final IStubElementType elementType, int textOffset) {
super(parent, elementType);
myName = name;
myTextOffset = textOffset;
}
public int getTextOffset() {
return myTextOffset;
}
public String getName() {
return StringRef.toString(myName);
}
}
|
kaczmarj/grand-challenge.org
|
app/grandchallenge/components/migrations/0008_alter_componentinterfacevalue_file.py
|
<gh_stars>100-1000
# Generated by Django 3.2.9 on 2021-11-26 13:45
from django.db import migrations, models
import grandchallenge.components.models
import grandchallenge.core.storage
import grandchallenge.core.validators
class Migration(migrations.Migration):
dependencies = [("components", "0007_auto_20211116_0906")]
operations = [
migrations.AlterField(
model_name="componentinterfacevalue",
name="file",
field=models.FileField(
blank=True,
null=True,
storage=grandchallenge.core.storage.ProtectedS3Storage(),
upload_to=grandchallenge.components.models.component_interface_value_path,
validators=[
grandchallenge.core.validators.ExtensionValidator(
allowed_extensions=(
".json",
".zip",
".csv",
".png",
".jpg",
".jpeg",
".pdf",
".sqreg",
)
),
grandchallenge.core.validators.MimeTypeValidator(
allowed_types=(
"application/json",
"application/zip",
"text/plain",
"application/csv",
"application/pdf",
"image/png",
"image/jpeg",
"application/octet-stream",
"application/x-sqlite3",
"application/vnd.sqlite3",
)
),
],
),
)
]
|
kmuellerjones/ohNetGenerated
|
OpenHome/Net/Bindings/Cpp/Device/Providers/DvAvOpenhomeOrgTime1Std.cpp
|
#include "DvAvOpenhomeOrgTime1.h"
#include <OpenHome/Types.h>
#include <OpenHome/Net/Private/DviService.h>
#include <OpenHome/Net/Private/Service.h>
#include <OpenHome/Net/Private/FunctorDviInvocation.h>
#include <OpenHome/Net/Cpp/DvInvocation.h>
#include <OpenHome/Net/Private/DviStack.h>
using namespace OpenHome;
using namespace OpenHome::Net;
bool DvProviderAvOpenhomeOrgTime1Cpp::SetPropertyTrackCount(uint32_t aValue)
{
ASSERT(iPropertyTrackCount != NULL);
return SetPropertyUint(*iPropertyTrackCount, aValue);
}
void DvProviderAvOpenhomeOrgTime1Cpp::GetPropertyTrackCount(uint32_t& aValue)
{
ASSERT(iPropertyTrackCount != NULL);
aValue = iPropertyTrackCount->Value();
}
bool DvProviderAvOpenhomeOrgTime1Cpp::SetPropertyDuration(uint32_t aValue)
{
ASSERT(iPropertyDuration != NULL);
return SetPropertyUint(*iPropertyDuration, aValue);
}
void DvProviderAvOpenhomeOrgTime1Cpp::GetPropertyDuration(uint32_t& aValue)
{
ASSERT(iPropertyDuration != NULL);
aValue = iPropertyDuration->Value();
}
bool DvProviderAvOpenhomeOrgTime1Cpp::SetPropertySeconds(uint32_t aValue)
{
ASSERT(iPropertySeconds != NULL);
return SetPropertyUint(*iPropertySeconds, aValue);
}
void DvProviderAvOpenhomeOrgTime1Cpp::GetPropertySeconds(uint32_t& aValue)
{
ASSERT(iPropertySeconds != NULL);
aValue = iPropertySeconds->Value();
}
DvProviderAvOpenhomeOrgTime1Cpp::DvProviderAvOpenhomeOrgTime1Cpp(DvDeviceStd& aDevice)
: DvProvider(aDevice.Device(), "av.openhome.org", "Time", 1)
{
iPropertyTrackCount = NULL;
iPropertyDuration = NULL;
iPropertySeconds = NULL;
}
void DvProviderAvOpenhomeOrgTime1Cpp::EnablePropertyTrackCount()
{
iPropertyTrackCount = new PropertyUint(new ParameterUint("TrackCount"));
iService->AddProperty(iPropertyTrackCount); // passes ownership
}
void DvProviderAvOpenhomeOrgTime1Cpp::EnablePropertyDuration()
{
iPropertyDuration = new PropertyUint(new ParameterUint("Duration"));
iService->AddProperty(iPropertyDuration); // passes ownership
}
void DvProviderAvOpenhomeOrgTime1Cpp::EnablePropertySeconds()
{
iPropertySeconds = new PropertyUint(new ParameterUint("Seconds"));
iService->AddProperty(iPropertySeconds); // passes ownership
}
void DvProviderAvOpenhomeOrgTime1Cpp::EnableActionTime()
{
OpenHome::Net::Action* action = new OpenHome::Net::Action("Time");
action->AddOutputParameter(new ParameterRelated("TrackCount", *iPropertyTrackCount));
action->AddOutputParameter(new ParameterRelated("Duration", *iPropertyDuration));
action->AddOutputParameter(new ParameterRelated("Seconds", *iPropertySeconds));
FunctorDviInvocation functor = MakeFunctorDviInvocation(*this, &DvProviderAvOpenhomeOrgTime1Cpp::DoTime);
iService->AddAction(action, functor);
}
void DvProviderAvOpenhomeOrgTime1Cpp::DoTime(IDviInvocation& aInvocation)
{
aInvocation.InvocationReadStart();
aInvocation.InvocationReadEnd();
uint32_t respTrackCount;
uint32_t respDuration;
uint32_t respSeconds;
DvInvocationStd invocation(aInvocation);
Time(invocation, respTrackCount, respDuration, respSeconds);
aInvocation.InvocationWriteStart();
DviInvocationResponseUint respWriterTrackCount(aInvocation, "TrackCount");
respWriterTrackCount.Write(respTrackCount);
DviInvocationResponseUint respWriterDuration(aInvocation, "Duration");
respWriterDuration.Write(respDuration);
DviInvocationResponseUint respWriterSeconds(aInvocation, "Seconds");
respWriterSeconds.Write(respSeconds);
aInvocation.InvocationWriteEnd();
}
void DvProviderAvOpenhomeOrgTime1Cpp::Time(IDvInvocationStd& /*aInvocation*/, uint32_t& /*aTrackCount*/, uint32_t& /*aDuration*/, uint32_t& /*aSeconds*/)
{
ASSERTS();
}
|
Jorgelig/hoshinplan
|
config/initializers/decimal_validator.rb
|
class DecimalValidator < Apipie::Validator::BaseValidator
def validate(value)
self.class.validate(value)
end
def self.build(param_description, argument, options, block)
if argument == :decimal
self.new(param_description)
end
end
def description
"Must be a decimal number."
end
def self.validate(value)
value.to_s =~ /\A[0-9]+([,.][0-9]+)?\Z$/
end
end
|
McLeodMoores/starling
|
projects/engine/src/test/java/com/opengamma/engine/value/ComputedValueTest.java
|
<reponame>McLeodMoores/starling
/**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.engine.value;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import org.fudgemsg.FudgeContext;
import org.fudgemsg.FudgeMsg;
import org.fudgemsg.FudgeMsgEnvelope;
import org.testng.annotations.Test;
import com.opengamma.engine.ComputationTargetSpecification;
import com.opengamma.engine.target.ComputationTargetType;
import com.opengamma.id.UniqueId;
import com.opengamma.util.fudgemsg.OpenGammaFudgeContext;
import com.opengamma.util.test.TestGroup;
/**
* Test ComputedValue.
*/
@Test(groups = TestGroup.UNIT)
public class ComputedValueTest {
private static final FudgeContext FUDGE_CONTEXT = OpenGammaFudgeContext.getInstance();
public void test_constructor_Object_Portfolio() {
final ValueSpecification vspec = ValueSpecification.of("DATA", ComputationTargetType.SECURITY, UniqueId.of("Foo", "Bar"),
ValueProperties.with(ValuePropertyNames.FUNCTION, "mockFunctionid").get());
final ComputedValue test = new ComputedValue(vspec, "HELLO");
assertEquals("HELLO", test.getValue());
assertEquals(vspec, test.getSpecification());
}
public static class ComplexValue {
private final double _i;
private final double _j;
public ComplexValue(final double i, final double j) {
_i = i;
_j = j;
}
public double getI() {
return _i;
}
public double getJ() {
return _j;
}
public static ComplexValue fromFudgeMsg(final FudgeMsg msg) {
return new ComplexValue(msg.getDouble("i"), msg.getDouble("j"));
}
@Override
public boolean equals(final Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof ComplexValue) {
final ComplexValue other = (ComplexValue) obj;
return other._i == _i && other._j == _j;
}
return false;
}
}
private void cycleComputedValue(final ComputedValue value) {
final FudgeMsgEnvelope fme = FUDGE_CONTEXT.toFudgeMsg(value);
assertNotNull(fme);
final FudgeMsg msg = fme.getMessage();
assertNotNull(msg);
final ComputedValue cycledValue = FUDGE_CONTEXT.fromFudgeMsg(ComputedValue.class, msg);
assertNotNull(cycledValue);
assertEquals(value, cycledValue);
}
private ValueSpecification createValueSpecification() {
return new ValueSpecification("test", ComputationTargetSpecification.of(UniqueId.of("foo", "bar")),
ValueProperties.with(ValuePropertyNames.FUNCTION, "mockFunctionId").get());
}
public void testDouble() {
cycleComputedValue(new ComputedValue(createValueSpecification(), 3.1412d));
}
public void testInteger() {
cycleComputedValue(new ComputedValue(createValueSpecification(), 12345678));
}
@Test
public void testSubMessage() {
cycleComputedValue(new ComputedValue(createValueSpecification(), new ComplexValue(1d, 2d)));
}
}
|
lorint/duty_free
|
spec/test_app/config/initializers/duty_free.rb
|
<reponame>lorint/duty_free
# frozen_string_literal: true
::ActiveSupport::Deprecation.silence do
# ::DutyFree.config.track_associations = true
end
|
sksingh329/automationCoders
|
src/test/java/apps/web/herokuapp/NewWindowTest.java
|
<gh_stars>1-10
package apps.web.herokuapp;
import flows.web.herokuapp.FrameFlow;
import flows.web.herokuapp.WindowFlow;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import utils.HandlePropertiesFile;
import utils.assertions.TestValidations;
import java.util.Properties;
@Listeners(reports.listeners.TestNGListener.class)
public class NewWindowTest {
public Properties env;
WindowFlow windowFlow;
TestValidations validate;
@BeforeMethod
public void getHerokuApp(){
env = HandlePropertiesFile.loadProperties("src/test/resources/env/", "ENV_WEB_APP_HEROKUAPP.properties");
validate = new TestValidations();
windowFlow = new WindowFlow(env.getProperty("browser"),env.getProperty("appUrl"));
}
@Test
public void validateNewWindowTitle(){
String expectedTitle = "New Window";
String actualTitle = windowFlow.getNewWindowTitle();
validate.checkEquals("Validate new window title",actualTitle,expectedTitle);
}
@Test
public void validateParentWindowTitle(){
String expectedTitle = "The Internet";
String actualTitle = windowFlow.getParentWindowTitle();
validate.checkEquals("Validate parent window title",actualTitle,expectedTitle);
}
@AfterMethod
public void quitBrowser(){
windowFlow.quitBrowser();
}
}
|
laik/liqo
|
pkg/liqonet/overlay/doc.go
|
// Package overlay contains the overlays implementations supported in liqo.
package overlay
|
vinodronold/fivefrets-next-ui
|
src/app/constants/routes.js
|
export const home = {
href: () => '/',
as: () => '/'
}
export const play = {
href: id => `/play?id=${id}`,
as: id => `/p/${id}`
}
export const browse = {
href: start => `/browse?start=${start}`,
as: start => `/b/${start}`
}
export const login = {
href: () => '/login',
as: () => '/l'
}
|
hefen1/chromium
|
content/browser/indexed_db/indexed_db_transaction.cc
|
<reponame>hefen1/chromium<filename>content/browser/indexed_db/indexed_db_transaction.cc
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/indexed_db/indexed_db_transaction.h"
#include "base/bind.h"
#include "base/logging.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/utf_string_conversions.h"
#include "content/browser/indexed_db/indexed_db_backing_store.h"
#include "content/browser/indexed_db/indexed_db_cursor.h"
#include "content/browser/indexed_db/indexed_db_database.h"
#include "content/browser/indexed_db/indexed_db_database_callbacks.h"
#include "content/browser/indexed_db/indexed_db_tracing.h"
#include "content/browser/indexed_db/indexed_db_transaction_coordinator.h"
#include "third_party/WebKit/public/platform/WebIDBDatabaseException.h"
#include "third_party/leveldatabase/env_chromium.h"
namespace content {
const int64 kInactivityTimeoutPeriodSeconds = 60;
IndexedDBTransaction::TaskQueue::TaskQueue() {}
IndexedDBTransaction::TaskQueue::~TaskQueue() { clear(); }
void IndexedDBTransaction::TaskQueue::clear() {
while (!queue_.empty())
queue_.pop();
}
IndexedDBTransaction::Operation IndexedDBTransaction::TaskQueue::pop() {
DCHECK(!queue_.empty());
Operation task(queue_.front());
queue_.pop();
return task;
}
IndexedDBTransaction::TaskStack::TaskStack() {}
IndexedDBTransaction::TaskStack::~TaskStack() { clear(); }
void IndexedDBTransaction::TaskStack::clear() {
while (!stack_.empty())
stack_.pop();
}
IndexedDBTransaction::Operation IndexedDBTransaction::TaskStack::pop() {
DCHECK(!stack_.empty());
Operation task(stack_.top());
stack_.pop();
return task;
}
IndexedDBTransaction::IndexedDBTransaction(
int64 id,
scoped_refptr<IndexedDBDatabaseCallbacks> callbacks,
const std::set<int64>& object_store_ids,
blink::WebIDBTransactionMode mode,
IndexedDBDatabase* database,
IndexedDBBackingStore::Transaction* backing_store_transaction)
: id_(id),
object_store_ids_(object_store_ids),
mode_(mode),
used_(false),
state_(CREATED),
commit_pending_(false),
callbacks_(callbacks),
database_(database),
transaction_(backing_store_transaction),
backing_store_transaction_begun_(false),
should_process_queue_(false),
pending_preemptive_events_(0) {
database_->transaction_coordinator().DidCreateTransaction(this);
diagnostics_.tasks_scheduled = 0;
diagnostics_.tasks_completed = 0;
diagnostics_.creation_time = base::Time::Now();
}
IndexedDBTransaction::~IndexedDBTransaction() {
// It shouldn't be possible for this object to get deleted until it's either
// complete or aborted.
DCHECK_EQ(state_, FINISHED);
DCHECK(preemptive_task_queue_.empty());
DCHECK_EQ(pending_preemptive_events_, 0);
DCHECK(task_queue_.empty());
DCHECK(abort_task_stack_.empty());
}
void IndexedDBTransaction::ScheduleTask(blink::WebIDBTaskType type,
Operation task) {
DCHECK_NE(state_, COMMITTING);
if (state_ == FINISHED)
return;
timeout_timer_.Stop();
used_ = true;
if (type == blink::WebIDBTaskTypeNormal) {
task_queue_.push(task);
++diagnostics_.tasks_scheduled;
} else {
preemptive_task_queue_.push(task);
}
RunTasksIfStarted();
}
void IndexedDBTransaction::ScheduleAbortTask(Operation abort_task) {
DCHECK_NE(FINISHED, state_);
DCHECK(used_);
abort_task_stack_.push(abort_task);
}
void IndexedDBTransaction::RunTasksIfStarted() {
DCHECK(used_);
// Not started by the coordinator yet.
if (state_ != STARTED)
return;
// A task is already posted.
if (should_process_queue_)
return;
should_process_queue_ = true;
base::MessageLoop::current()->PostTask(
FROM_HERE, base::Bind(&IndexedDBTransaction::ProcessTaskQueue, this));
}
void IndexedDBTransaction::Abort() {
Abort(IndexedDBDatabaseError(blink::WebIDBDatabaseExceptionUnknownError,
"Internal error (unknown cause)"));
}
void IndexedDBTransaction::Abort(const IndexedDBDatabaseError& error) {
IDB_TRACE1("IndexedDBTransaction::Abort", "txn.id", id());
if (state_ == FINISHED)
return;
// The last reference to this object may be released while performing the
// abort steps below. We therefore take a self reference to keep ourselves
// alive while executing this method.
scoped_refptr<IndexedDBTransaction> protect(this);
timeout_timer_.Stop();
state_ = FINISHED;
should_process_queue_ = false;
if (backing_store_transaction_begun_)
transaction_->Rollback();
// Run the abort tasks, if any.
while (!abort_task_stack_.empty())
abort_task_stack_.pop().Run(NULL);
preemptive_task_queue_.clear();
pending_preemptive_events_ = 0;
task_queue_.clear();
// Backing store resources (held via cursors) must be released
// before script callbacks are fired, as the script callbacks may
// release references and allow the backing store itself to be
// released, and order is critical.
CloseOpenCursors();
transaction_->Reset();
// Transactions must also be marked as completed before the
// front-end is notified, as the transaction completion unblocks
// operations like closing connections.
database_->transaction_coordinator().DidFinishTransaction(this);
#ifndef NDEBUG
DCHECK(!database_->transaction_coordinator().IsActive(this));
#endif
if (callbacks_.get())
callbacks_->OnAbort(id_, error);
database_->TransactionFinished(this, false);
database_ = NULL;
}
bool IndexedDBTransaction::IsTaskQueueEmpty() const {
return preemptive_task_queue_.empty() && task_queue_.empty();
}
bool IndexedDBTransaction::HasPendingTasks() const {
return pending_preemptive_events_ || !IsTaskQueueEmpty();
}
void IndexedDBTransaction::RegisterOpenCursor(IndexedDBCursor* cursor) {
open_cursors_.insert(cursor);
}
void IndexedDBTransaction::UnregisterOpenCursor(IndexedDBCursor* cursor) {
open_cursors_.erase(cursor);
}
void IndexedDBTransaction::Start() {
// TransactionCoordinator has started this transaction.
DCHECK_EQ(CREATED, state_);
state_ = STARTED;
diagnostics_.start_time = base::Time::Now();
if (!used_)
return;
RunTasksIfStarted();
}
class BlobWriteCallbackImpl : public IndexedDBBackingStore::BlobWriteCallback {
public:
explicit BlobWriteCallbackImpl(
scoped_refptr<IndexedDBTransaction> transaction)
: transaction_(transaction) {}
void Run(bool succeeded) override {
transaction_->BlobWriteComplete(succeeded);
}
protected:
~BlobWriteCallbackImpl() override {}
private:
scoped_refptr<IndexedDBTransaction> transaction_;
};
void IndexedDBTransaction::BlobWriteComplete(bool success) {
IDB_TRACE("IndexedDBTransaction::BlobWriteComplete");
if (state_ == FINISHED) // aborted
return;
DCHECK_EQ(state_, COMMITTING);
if (success)
CommitPhaseTwo();
else
Abort(IndexedDBDatabaseError(blink::WebIDBDatabaseExceptionDataError,
"Failed to write blobs."));
}
leveldb::Status IndexedDBTransaction::Commit() {
IDB_TRACE1("IndexedDBTransaction::Commit", "txn.id", id());
timeout_timer_.Stop();
// In multiprocess ports, front-end may have requested a commit but
// an abort has already been initiated asynchronously by the
// back-end.
if (state_ == FINISHED)
return leveldb::Status::OK();
DCHECK_NE(state_, COMMITTING);
DCHECK(!used_ || state_ == STARTED);
commit_pending_ = true;
// Front-end has requested a commit, but there may be tasks like
// create_index which are considered synchronous by the front-end
// but are processed asynchronously.
if (HasPendingTasks())
return leveldb::Status::OK();
state_ = COMMITTING;
leveldb::Status s;
if (!used_) {
s = CommitPhaseTwo();
} else {
scoped_refptr<IndexedDBBackingStore::BlobWriteCallback> callback(
new BlobWriteCallbackImpl(this));
// CommitPhaseOne will call the callback synchronously if there are no blobs
// to write.
s = transaction_->CommitPhaseOne(callback);
if (!s.ok())
Abort(IndexedDBDatabaseError(blink::WebIDBDatabaseExceptionDataError,
"Error processing blob journal."));
}
return s;
}
leveldb::Status IndexedDBTransaction::CommitPhaseTwo() {
// Abort may have been called just as the blob write completed.
if (state_ == FINISHED)
return leveldb::Status::OK();
DCHECK_EQ(state_, COMMITTING);
// The last reference to this object may be released while performing the
// commit steps below. We therefore take a self reference to keep ourselves
// alive while executing this method.
scoped_refptr<IndexedDBTransaction> protect(this);
state_ = FINISHED;
leveldb::Status s;
bool committed;
if (!used_) {
committed = true;
} else {
s = transaction_->CommitPhaseTwo();
committed = s.ok();
}
// Backing store resources (held via cursors) must be released
// before script callbacks are fired, as the script callbacks may
// release references and allow the backing store itself to be
// released, and order is critical.
CloseOpenCursors();
transaction_->Reset();
// Transactions must also be marked as completed before the
// front-end is notified, as the transaction completion unblocks
// operations like closing connections.
database_->transaction_coordinator().DidFinishTransaction(this);
if (committed) {
abort_task_stack_.clear();
callbacks_->OnComplete(id_);
database_->TransactionFinished(this, true);
} else {
while (!abort_task_stack_.empty())
abort_task_stack_.pop().Run(NULL);
IndexedDBDatabaseError error;
if (leveldb_env::IndicatesDiskFull(s)) {
error = IndexedDBDatabaseError(
blink::WebIDBDatabaseExceptionQuotaError,
"Encountered disk full while committing transaction.");
} else {
error = IndexedDBDatabaseError(blink::WebIDBDatabaseExceptionUnknownError,
"Internal error committing transaction.");
}
callbacks_->OnAbort(id_, error);
database_->TransactionFinished(this, false);
database_->TransactionCommitFailed(s);
}
database_ = NULL;
return s;
}
void IndexedDBTransaction::ProcessTaskQueue() {
IDB_TRACE1("IndexedDBTransaction::ProcessTaskQueue", "txn.id", id());
// May have been aborted.
if (!should_process_queue_)
return;
DCHECK(!IsTaskQueueEmpty());
should_process_queue_ = false;
if (!backing_store_transaction_begun_) {
transaction_->Begin();
backing_store_transaction_begun_ = true;
}
// The last reference to this object may be released while performing the
// tasks. Take take a self reference to keep this object alive so that
// the loop termination conditions can be checked.
scoped_refptr<IndexedDBTransaction> protect(this);
TaskQueue* task_queue =
pending_preemptive_events_ ? &preemptive_task_queue_ : &task_queue_;
while (!task_queue->empty() && state_ != FINISHED) {
DCHECK_EQ(state_, STARTED);
Operation task(task_queue->pop());
task.Run(this);
if (!pending_preemptive_events_) {
DCHECK(diagnostics_.tasks_completed < diagnostics_.tasks_scheduled);
++diagnostics_.tasks_completed;
}
// Event itself may change which queue should be processed next.
task_queue =
pending_preemptive_events_ ? &preemptive_task_queue_ : &task_queue_;
}
// If there are no pending tasks, we haven't already committed/aborted,
// and the front-end requested a commit, it is now safe to do so.
if (!HasPendingTasks() && state_ != FINISHED && commit_pending_) {
Commit();
return;
}
// The transaction may have been aborted while processing tasks.
if (state_ == FINISHED)
return;
DCHECK(state_ == STARTED);
// Otherwise, start a timer in case the front-end gets wedged and
// never requests further activity. Read-only transactions don't
// block other transactions, so don't time those out.
if (mode_ != blink::WebIDBTransactionModeReadOnly) {
timeout_timer_.Start(
FROM_HERE,
base::TimeDelta::FromSeconds(kInactivityTimeoutPeriodSeconds),
base::Bind(&IndexedDBTransaction::Timeout, this));
}
}
void IndexedDBTransaction::Timeout() {
Abort(IndexedDBDatabaseError(
blink::WebIDBDatabaseExceptionTimeoutError,
base::ASCIIToUTF16("Transaction timed out due to inactivity.")));
}
void IndexedDBTransaction::CloseOpenCursors() {
for (auto* cursor : open_cursors_)
cursor->Close();
open_cursors_.clear();
}
} // namespace content
|
fmoraw/NS
|
main/source/mod/AvHBaseBuildable.cpp
|
//======== (C) Copyright 2001 <NAME> All rights reserved. =========
//
// The copyright to the contents herein is the property of <NAME>.
// The contents may be used and/or copied only with the written permission of
// <NAME>, or in accordance with the terms and conditions stipulated in
// the agreement/contract under which the contents have been supplied.
//
// Purpose:
//
// $Workfile: AvHBaseBuildable.cpp$
// $Date: 2002/11/22 21:28:15 $
//
//-------------------------------------------------------------------------------
// $Log: AvHBaseBuildable.cpp,v $
// Revision 1.19 2002/11/22 21:28:15 Flayra
// - mp_consistency changes
//
// Revision 1.18 2002/11/15 04:47:11 Flayra
// - Regenerate now returns bool if healed or not, for def chamber tweak
//
// Revision 1.17 2002/11/12 02:22:35 Flayra
// - Removed draw damage from public build
// - Don't allow +use to speed research
//
// Revision 1.16 2002/11/06 01:38:24 Flayra
// - Added ability for buildings to be enabled and disabled, for turrets to be shut down
// - Damage refactoring (TakeDamage assumes caller has already adjusted for friendly fire, etc.)
//
// Revision 1.15 2002/10/24 21:21:49 Flayra
// - Added code to award attacker a frag when destroying a building but thought better of it
//
// Revision 1.14 2002/10/16 00:49:35 Flayra
// - Reworked build times so they are real numbers
//
// Revision 1.13 2002/10/03 18:38:56 Flayra
// - Fixed problem where regenerating builders via healing spray wasn't updating health ring
// - Allow buildings to play custom damage alerts (for towers)
//
// Revision 1.12 2002/09/23 22:10:14 Flayra
// - Removed progress bar when building
// - Removed vestiges of fading building as building
// - Changed point costs
//
// Revision 1.11 2002/09/09 19:49:09 Flayra
// - Buildables now play animations better, without interrupting previous anims
//
// Revision 1.10 2002/08/31 18:01:00 Flayra
// - Work at VALVe
//
// Revision 1.9 2002/08/16 02:32:45 Flayra
// - Added damage types
// - Added visual health for commander and marines
//
// Revision 1.8 2002/08/02 22:02:09 Flayra
// - New alert system
//
// Revision 1.7 2002/07/26 23:03:56 Flayra
// - Don't play "hurt/wound" sounds when we don't actually take damage (GetCanEntityDoDamageTo)
// - Generate numerical feedback for damage events
//
// Revision 1.6 2002/07/23 16:58:38 Flayra
// - Auto-build can't happen before game starts
//
// Revision 1.5 2002/07/01 21:15:46 Flayra
// - Added auto-build capability
//
// Revision 1.4 2002/06/25 17:31:24 Flayra
// - Regular update, don't assume anything about player building, renamed arsenal to armory
//
// Revision 1.3 2002/06/03 16:27:59 Flayra
// - Allow alien buildings to regenerate, renamed weapons factory and armory
//
// Revision 1.2 2002/05/28 17:37:27 Flayra
// - Added building recycling, mark mapper placed buildables so they aren't destroyed at the end of the round
//
// Revision 1.1 2002/05/23 02:34:00 Flayra
// - Post-crash checkin. Restored @Backup from around 4/16. Contains changes for last four weeks of development.
//
//===============================================================================
#include "AvHBaseBuildable.h"
#include "AvHGamerules.h"
#include "AvHSharedUtil.h"
#include "AvHServerUtil.h"
#include "AvHServerVariables.h"
#include "AvHParticleConstants.h"
#include "AvHMarineEquipmentConstants.h"
#include "AvHSoundListManager.h"
#include "AvHAlienEquipmentConstants.h"
#include "AvHPlayerUpgrade.h"
#include "../dlls/animation.h"
#include "AvHMovementUtil.h"
const int kBaseBuildableSpawnAnimation = 0;
const int kBaseBuildableDeployAnimation = 1;
const int kBaseBuildableIdle1Animation = 2;
const int kBaseBuildableIdle2Animation = 3;
const int kBaseBuildableResearchingAnimation = 4;
const int kBaseBuildableActiveAnimation = 5;
const int kBaseBuildableFireAnimation = 6;
const int kBaseBuildableTakeDamageAnimation = 7;
const int kBaseBuildableDieForwardAnimation = 8;
const int kBaseBuildableDieLeftAnimation = 9;
const int kBaseBuildableDieBackwardAnimation = 10;
const int kBaseBuildableDieRightAnimation = 11;
const int kBaseBuildableSpecialAnimation = 12;
extern int gRegenerationEventID;
extern AvHSoundListManager gSoundListManager;
AvHBaseBuildable::AvHBaseBuildable(AvHTechID inTechID, AvHMessageID inMessageID, char* inClassName, int inUser3) : AvHBuildable(inTechID), kStartAlpha(128), mAverageUseSoundLength(.5f)
{
this->mClassName = inClassName;
this->mMessageID = inMessageID;
this->mBaseHealth = GetGameRules()->GetBaseHealthForMessageID(inMessageID);
char* theModelName = AvHSHUGetBuildTechModelName(inMessageID);
ASSERT(theModelName);
this->mModelName = theModelName;
this->mSelectID = inUser3;
this->mTimeToConstruct = GetGameRules()->GetBuildTimeForMessageID(inMessageID);
// Very important that this doesn't go in Init(), else mapper-placed structures disappear on map-reset
this->mPersistent = false;
this->Init();
}
void AvHBaseBuildable::Init()
{
if(this->pev)
{
InitializeBuildable(this->pev->iuser3, this->pev->iuser4, this->pev->fuser1, this->mSelectID);
}
this->mTimeAnimationDone = 0;
this->mLastAnimationPlayed = -1;
this->mIsResearching = false;
this->mTimeOfLastAutoHeal = -1;
this->mInternalSetConstructionComplete = false;
this->mKilled = false;
this->mTimeOfLastDamageEffect = -1;
this->mTimeOfLastDamageUpdate = -1;
this->mTimeRecycleStarted = -1;
this->mTimeRecycleDone = -1;
this->mTimeOfLastDCRegeneration = -1;
SetThink(NULL);
}
const float kAnimateThinkTime = .1f;
void AvHBaseBuildable::AnimateThink()
{
int theSequence = this->GetResearchAnimation();
if(!this->mIsResearching)
{
// Play a random idle animation
theSequence = this->GetIdleAnimation();
}
else
{
int a = 0;
}
this->PlayAnimationAtIndex(theSequence);
// Set our next think
float theUpdateTime = this->GetTimeForAnimation(theSequence);
this->pev->nextthink = gpGlobals->time + theUpdateTime;
}
int AvHBaseBuildable::BloodColor( void )
{
int theBloodColor = DONT_BLEED;
if(this->GetIsOrganic())
{
theBloodColor = BLOOD_COLOR_GREEN;
}
return theBloodColor;
}
void AvHBaseBuildable::BuildableTouch(CBaseEntity* inEntity)
{
if(inEntity->pev->team != this->pev->team)
{
this->Uncloak();
// GHOSTBUILDING: Destroy and return res.
if (this->mGhost && inEntity->IsAlive() && inEntity->IsPlayer())
{
this->TakeDamage(inEntity->pev, this->pev, 80000, DMG_GENERIC);
AvHTeam* theTeam = GetGameRules()->GetTeam(AvHTeamNumber(this->pev->team));
if (theTeam)
{
float thePercentage = .8f;
float thePointsBack = GetGameRules()->GetCostForMessageID(this->mMessageID) * thePercentage;
theTeam->SetTeamResources(theTeam->GetTeamResources() + thePointsBack);
AvHSUPlayNumericEventAboveStructure(thePointsBack, this);
}
// Uncloak the player
AvHCloakable *theCloakable=dynamic_cast<AvHCloakable *>(inEntity);
if ( theCloakable ) {
theCloakable->Uncloak();
}
}
}
}
void AvHBaseBuildable::CheckEnabledState()
{
}
void AvHBaseBuildable::ConstructUse( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value )
{
bool theSuccess = false;
bool theIsBuilding = false;
bool theIsResearching = false;
float thePercentage = 0.0f;
AvHSHUGetBuildResearchState(this->pev->iuser3, this->pev->iuser4, this->pev->fuser1, theIsBuilding, theIsResearching, thePercentage);
// Only allow players to help along building, not researching
if(theIsBuilding)
{
// Only allow users from same team as turret deployer
float thePercentage = this->GetNormalizedBuildPercentage();
if(pActivator->pev->team == this->pev->team && (thePercentage < 1.0f))
{
AvHPlayer* thePlayer = dynamic_cast<AvHPlayer*>(pActivator);
ASSERT(thePlayer);
// Only soldiers and builders can build
if(thePlayer->GetIsAbleToAct() && ((thePlayer->pev->iuser3 == AVH_USER3_MARINE_PLAYER) || (thePlayer->pev->iuser3 == AVH_USER3_ALIEN_PLAYER2)))
{
AvHBasePlayerWeapon* theWeapon = dynamic_cast<AvHBasePlayerWeapon*>(thePlayer->m_pActiveItem);
if(!theWeapon || theWeapon->CanHolster())
{
thePlayer->PlayerConstructUse();
bool thePlaySound = false;
// Ensure that buildings are never absolutely painful to create
int theBuildTime = max(GetGameRules()->GetBuildTimeForMessageID(this->mMessageID), 1);
if((GetGameRules()->GetIsTesting() || GetGameRules()->GetCheatsEnabled()) && !GetGameRules()->GetIsCheatEnabled(kcSlowResearch))
{
theBuildTime = 2;
}
// Make non-frame-rate dependent
const float kDefaultInterval = .1f;
float theTimeOfLastConstructUse = thePlayer->GetTimeOfLastConstructUse();
float theInterval = min(max(gpGlobals->time - theTimeOfLastConstructUse, 0.0f), kDefaultInterval);
thePercentage += (theInterval/(float)theBuildTime);
thePlayer->SetTimeOfLastConstructUse(gpGlobals->time);
if(gpGlobals->time > (this->mLastTimePlayedSound + this->mAverageUseSoundLength))
{
AvHSUPlayRandomConstructionEffect(thePlayer, this);
this->mLastTimePlayedSound = gpGlobals->time;
}
// Given the number of constructors, what's chance of starting a new sound?
float theChanceForNewSound = (gpGlobals->frametime/(this->mAverageUseSoundLength));// /2.0f));
float theRandomFloat = RANDOM_FLOAT(0.0f, 1.0f);
if(theRandomFloat < theChanceForNewSound)
{
AvHSUPlayRandomConstructionEffect(thePlayer, this);
}
//if(RANDOM_LONG(0, 20) == 0)
//{
// char theMessage[128];
// sprintf(theMessage, "Time passed: %f, ticks: %d, rate: %f\n", theTimePassed, this->mPreThinkTicks, this->mPreThinkFrameRate);
// UTIL_SayText(theMessage, this);
//}
this->SetNormalizedBuildPercentage(thePercentage);
theSuccess = true;
// GHOSTBUILD: Manifest structure.
pev->renderamt = 255;
pev->rendermode = kRenderNormal;
pev->solid = SOLID_BBOX;
this->mGhost = false;
}
}
}
}
// Clear out +use sound when ineffective
if(!theSuccess)
{
EMIT_SOUND(pActivator->edict(), CHAN_ITEM, "common/null.wav", 1.0, ATTN_NORM);
}
}
bool AvHBaseBuildable::Energize(float inEnergyAmount)
{
return false;
}
int AvHBaseBuildable::GetBaseHealth() const
{
return this->mBaseHealth;
}
char* AvHBaseBuildable::GetClassName() const
{
return this->mClassName;
}
int AvHBaseBuildable::GetIdleAnimation() const
{
int theAnimation = this->GetIdle1Animation();
if(RANDOM_LONG(0, 1))
{
theAnimation = this->GetIdle2Animation();
}
return theAnimation;
}
char* AvHBaseBuildable::GetDeploySound() const
{
return NULL;
}
bool AvHBaseBuildable::GetIsBuilt() const
{
return this->mInternalSetConstructionComplete;
}
bool AvHBaseBuildable::GetIsOrganic() const
{
return false;
}
char* AvHBaseBuildable::GetKilledSound() const
{
return NULL;
}
float AvHBaseBuildable::GetNormalizedBuildPercentage() const
{
//return this->pev->fuser1/kNormalizationNetworkFactor;
bool theIsBuilding;
bool theIsResearching;
float thePercentage;
AvHSHUGetBuildResearchState(this->pev->iuser3, this->pev->iuser4, this->pev->fuser1, theIsBuilding, theIsResearching, thePercentage);
// Check for energy special case
if(theIsBuilding && theIsResearching)
{
thePercentage = 1.0f;
}
return thePercentage;
}
float AvHBaseBuildable::GetTimeForAnimation(int inIndex) const
{
return GetSequenceDuration(GET_MODEL_PTR(ENT(pev)), this->pev);
}
int AvHBaseBuildable::GetStartAlpha() const
{
return kStartAlpha;
}
void AvHBaseBuildable::FireDeathTarget() const
{
if(this->mTargetOnDeath != "")
{
FireTargets(this->mTargetOnDeath.c_str(), NULL, NULL, USE_TOGGLE, 0.0f);
}
}
void AvHBaseBuildable::FireSpawnTarget() const
{
if(this->mTargetOnSpawn != "")
{
FireTargets(this->mTargetOnSpawn.c_str(), NULL, NULL, USE_TOGGLE, 0.0f);
}
}
void AvHBaseBuildable::KeyValue(KeyValueData* pkvd)
{
// Any entity placed by the mapper is persistent
this->SetPersistent();
if(FStrEq(pkvd->szKeyName, "targetonspawn"))
{
this->mTargetOnSpawn = pkvd->szValue;
pkvd->fHandled = TRUE;
}
else if(FStrEq(pkvd->szKeyName, "targetondeath"))
{
this->mTargetOnDeath = pkvd->szValue;
pkvd->fHandled = TRUE;
}
else if(FStrEq(pkvd->szKeyName, "teamchoice"))
{
//this->mTeam = (AvHTeamNumber)(atoi(pkvd->szValue));
this->pev->team = (AvHTeamNumber)(atoi(pkvd->szValue));
pkvd->fHandled = TRUE;
}
else if(FStrEq(pkvd->szKeyName, "angles"))
{
// TODO: Insert code here
//pkvd->fHandled = TRUE;
int a = 0;
}
else
{
CBaseAnimating::KeyValue(pkvd);
}
}
void AvHBaseBuildable::PlayAnimationAtIndex(int inIndex, bool inForce, float inFrameRate)
{
// Only play animations on buildings that we have artwork for
bool thePlayAnim = false;
if(inIndex >= 0)
{
switch(this->mMessageID)
{
case BUILD_RESOURCES:
case BUILD_ARMSLAB:
case BUILD_COMMANDSTATION:
case BUILD_INFANTRYPORTAL:
case BUILD_TURRET_FACTORY:
case TURRET_FACTORY_UPGRADE:
case BUILD_ARMORY:
case ARMORY_UPGRADE:
case BUILD_OBSERVATORY:
case BUILD_TURRET:
case BUILD_SIEGE:
case BUILD_PROTOTYPE_LAB:
case ALIEN_BUILD_HIVE:
case ALIEN_BUILD_RESOURCES:
case ALIEN_BUILD_OFFENSE_CHAMBER:
case ALIEN_BUILD_DEFENSE_CHAMBER:
case ALIEN_BUILD_SENSORY_CHAMBER:
case ALIEN_BUILD_MOVEMENT_CHAMBER:
thePlayAnim = true;
}
}
// Make sure we're not interrupting another animation
if(thePlayAnim)
{
// Allow forcing of new animation, but it's better to complete current animation then interrupt it and play it again
float theCurrentTime = gpGlobals->time;
if((theCurrentTime >= this->mTimeAnimationDone) || (inForce && (inIndex != this->mLastAnimationPlayed)))
{
this->pev->sequence = inIndex;
this->pev->frame = 0;
ResetSequenceInfo();
this->pev->framerate = inFrameRate;
// Set to last frame to play backwards
if(this->pev->framerate < 0)
{
this->pev->frame = 255;
}
this->mLastAnimationPlayed = inIndex;
float theTimeForAnim = this->GetTimeForAnimation(inIndex);
this->mTimeAnimationDone = theCurrentTime + theTimeForAnim;
// Recalculate size
//Vector theMinSize, theMaxSize;
//this->ExtractBbox(this->pev->sequence, (float*)&theMinSize, (float*)&theMaxSize);
//UTIL_SetSize(this->pev, theMinSize, theMaxSize);
}
}
}
void AvHBaseBuildable::SetNormalizedBuildPercentage(float inPercentage, bool inForceIfComplete)
{
// Get previous build percentage so we can add hitpoints as structure is building. This means that structures that are hurt while building finish hurt.
bool theIsBuilding, theIsResearching;
float theNormalizedBuildPercentage = 0.0f;
AvHSHUGetBuildResearchState(this->pev->iuser3, this->pev->iuser4, this->pev->fuser1, theIsBuilding, theIsResearching, theNormalizedBuildPercentage);
float theDiff = inPercentage - theNormalizedBuildPercentage;
if(theDiff > 0)
{
this->pev->health += theDiff*(1.0f - kBaseHealthPercentage)*this->mBaseHealth;
this->pev->health = min(max(0.0f, this->pev->health), (float)this->mBaseHealth);
}
else
{
int a = 0;
}
// Set new build state
AvHSHUSetBuildResearchState(this->pev->iuser3, this->pev->iuser4, this->pev->fuser1, true, inPercentage);
if(inPercentage >= 1.0f)
{
this->InternalSetConstructionComplete(inForceIfComplete);
}
this->HealthChanged();
}
void AvHBaseBuildable::UpdateOnRecycle()
{
// empty, override to add events on recycle for buildings
}
Vector AvHBaseBuildable::EyePosition( ) {
if ( this->pev->iuser3 == AVH_USER3_HIVE )
return CBaseEntity::EyePosition();
vec3_t position=AvHSHUGetRealLocation(this->pev->origin, this->pev->mins, this->pev->maxs);
position[2]+=10;
return position;
}
void AvHBaseBuildable::StartRecycle()
{
if(!GetHasUpgrade(this->pev->iuser4, MASK_RECYCLING))
{
int theRecycleTime = (GetGameRules()->GetCheatsEnabled() && !GetGameRules()->GetIsCheatEnabled(kcSlowResearch)) ? 2 : BALANCE_VAR(kRecycleTime);
// Play recycle animation in reverse (would like to play them slower according to recycle time, but it doesn't work for all structures, seems dependent on # of keyframes)
int theAnimation = this->GetRecycleAnimation();
float theTimeForAnim = this->GetTimeForAnimation(theAnimation);
float theFrameRate = -1;//-theTimeForAnim/theRecycleTime;
this->PlayAnimationAtIndex(theAnimation, true, theFrameRate);
// Schedule time to give points back
SetThink(&AvHBaseBuildable::RecycleComplete);
this->mTimeRecycleStarted = gpGlobals->time;
this->mTimeRecycleDone = gpGlobals->time + theRecycleTime;
this->pev->nextthink = this->mTimeRecycleDone;
float theVolume = .5f;
EMIT_SOUND(this->edict(), CHAN_AUTO, kBuildableRecycleSound, theVolume, ATTN_NORM);
SetUpgradeMask(&this->pev->iuser4, MASK_RECYCLING);
// run any events for this class on recycling the structure
this->UpdateOnRecycle();
// Remove tech immediately, so research or building isn't started using this tech
this->TriggerRemoveTech();
}
}
bool AvHBaseBuildable::GetIsRecycling() const
{
return GetHasUpgrade(this->pev->iuser4, MASK_RECYCLING);
}
bool AvHBaseBuildable::GetIsTechActive() const
{
bool theIsActive = false;
if(this->GetIsBuilt() && (this->pev->health > 0) && !GetHasUpgrade(this->pev->iuser4, MASK_RECYCLING))
{
theIsActive = true;
}
return theIsActive;
}
int AvHBaseBuildable::GetActiveAnimation() const
{
return kBaseBuildableActiveAnimation;
}
CBaseEntity* AvHBaseBuildable::GetAttacker()
{
CBaseEntity* theAttacker = this;
AvHBuildable* theBuildable = dynamic_cast<AvHBuildable*>(this);
if(theBuildable)
{
int theBuilderIndex = theBuildable->GetBuilder();
CBaseEntity* theBuilderEntity = CBaseEntity::Instance(g_engfuncs.pfnPEntityOfEntIndex(theBuilderIndex));
if(theBuilderEntity)
{
theAttacker = theBuilderEntity;
}
}
return theAttacker;
}
int AvHBaseBuildable::GetDeployAnimation() const
{
return kBaseBuildableDeployAnimation;
}
int AvHBaseBuildable::GetIdle1Animation() const
{
return kBaseBuildableIdle1Animation;
}
int AvHBaseBuildable::GetIdle2Animation() const
{
return kBaseBuildableIdle2Animation;
}
int AvHBaseBuildable::GetKilledAnimation() const
{
return kBaseBuildableDieForwardAnimation;
}
AvHMessageID AvHBaseBuildable::GetMessageID() const
{
return this->mMessageID;
}
int AvHBaseBuildable::GetMoveType() const
{
return MOVETYPE_TOSS;
}
bool AvHBaseBuildable::GetTriggerAlertOnDamage() const
{
return true;
}
float AvHBaseBuildable::GetTimeAnimationDone() const
{
return this->mTimeAnimationDone;
}
int AvHBaseBuildable::GetResearchAnimation() const
{
return kBaseBuildableResearchingAnimation;
}
// Play deploy animation backwards
int AvHBaseBuildable::GetRecycleAnimation() const
{
int theAnimation = -1;
if(this->GetIsBuilt())
{
theAnimation = this->GetDeployAnimation();
}
return theAnimation;
}
char* AvHBaseBuildable::GetModelName() const
{
return this->mModelName;
}
int AvHBaseBuildable::GetSpawnAnimation() const
{
return kBaseBuildableSpawnAnimation;
}
int AvHBaseBuildable::GetTakeDamageAnimation() const
{
int theAnimation = -1;
if(this->GetIsBuilt())
{
theAnimation = kBaseBuildableTakeDamageAnimation;
}
return theAnimation;
}
AvHTeamNumber AvHBaseBuildable::GetTeamNumber() const
{
AvHTeamNumber ret=TEAM_IND;
if ( this->pev )
ret=(AvHTeamNumber)this->pev->team;
return ret;
}
void AvHBaseBuildable::Killed(entvars_t* pevAttacker, int iGib)
{
bool theInReset = GetGameRules()->GetIsGameInReset();
AvHBaseBuildable::SetHasBeenKilled();
GetGameRules()->RemoveEntityUnderAttack( this->entindex() );
this->mKilled = true;
this->mInternalSetConstructionComplete = false;
this->mTimeOfLastAutoHeal = -1;
if (!theInReset)
{
// : 980
// Less smoke for recycled buildings
this->TriggerDeathAudioVisuals(iGib == GIB_RECYCLED);
if(!this->GetIsOrganic())
{
// More sparks for recycled buildings
int numSparks = ( iGib == GIB_RECYCLED ) ? 7 : 3;
for ( int i=0; i < numSparks; i++ ) {
Vector vecSrc = Vector( (float)RANDOM_FLOAT( pev->absmin.x, pev->absmax.x ), (float)RANDOM_FLOAT( pev->absmin.y, pev->absmax.y ), (float)0 );
vecSrc = vecSrc + Vector( (float)0, (float)0, (float)RANDOM_FLOAT( pev->origin.z, pev->absmax.z ) );
UTIL_Sparks(vecSrc);
}
}
// :
}
this->TriggerRemoveTech();
AvHSURemoveEntityFromHotgroupsAndSelection(this->entindex());
if(pevAttacker)
{
const char* theClassName = STRING(this->pev->classname);
AvHPlayer* inPlayer = dynamic_cast<AvHPlayer*>(CBaseEntity::Instance(ENT(pevAttacker)));
if(inPlayer && theClassName)
{
inPlayer->LogPlayerAction("structure_destroyed", theClassName);
GetGameRules()->RewardPlayerForKill(inPlayer, this);
}
}
if(this->GetIsPersistent())
{
this->SetInactive();
}
else
{
CBaseAnimating::Killed(pevAttacker, iGib);
}
}
void AvHBaseBuildable::SetActive()
{
this->pev->effects &= ~EF_NODRAW;
}
void AvHBaseBuildable::SetInactive()
{
this->pev->health = 0;
this->pev->effects |= EF_NODRAW;
this->pev->solid = SOLID_NOT;
this->pev->takedamage = DAMAGE_NO;
SetUpgradeMask(&this->pev->iuser4, MASK_PARASITED, false);//: remove parasite flag to prevent phantom parasites.
//this->pev->deadflag = DEAD_DEAD;
SetThink(NULL);
}
int AvHBaseBuildable::ObjectCaps(void)
{
return FCAP_CONTINUOUS_USE;
}
void AvHBaseBuildable::Precache(void)
{
CBaseAnimating::Precache();
char* theDeploySound = this->GetDeploySound();
if(theDeploySound)
{
PRECACHE_UNMODIFIED_SOUND(theDeploySound);
}
char* theKilledSound = this->GetKilledSound();
if(theKilledSound)
{
PRECACHE_UNMODIFIED_SOUND(theKilledSound);
}
PRECACHE_UNMODIFIED_MODEL(this->mModelName);
PRECACHE_UNMODIFIED_SOUND(kBuildableRecycleSound);
//PRECACHE_UNMODIFIED_SOUND(kBuildableHurt1Sound);
//PRECACHE_UNMODIFIED_SOUND(kBuildableHurt2Sound);
this->mElectricalSprite = PRECACHE_UNMODIFIED_MODEL(kElectricalSprite);
}
void AvHBaseBuildable::RecycleComplete()
{
// Look at whether it has been built and health to determine how many points to give back
float thePercentage = BALANCE_VAR(kRecycleResourcePercentage);
if(!this->GetIsBuilt())
{
thePercentage = .8f;
}
// Make sure the building is still alive, can't get points back if it's dead
if(this->pev->health <= 0)
{
thePercentage = 0.0f;
}
// Look up team
AvHTeam* theTeam = GetGameRules()->GetTeam((AvHTeamNumber)this->pev->team);
if(theTeam)
{
bool theIsEnergyTech = AvHSHUGetDoesTechCostEnergy(this->mMessageID);
ASSERT(!theIsEnergyTech);
float thePointsBack = GetGameRules()->GetCostForMessageID(this->mMessageID)*thePercentage;
theTeam->SetTeamResources(theTeam->GetTeamResources() + thePointsBack);
// Play "+ resources" event
AvHSUPlayNumericEventAboveStructure(thePointsBack, this);
// : 980
// Less smoke and more sparks for recycled buildings
this->Killed(this->pev, GIB_RECYCLED);
// :
}
}
// Sets the template iuser3 for this buildable. This is stored outside of the actual iuser3 because sometimes the pev isn't allocated yet.
void AvHBaseBuildable::SetSelectID(int inSelectID)
{
this->mSelectID = inSelectID;
}
bool AvHBaseBuildable::Regenerate(float inRegenerationAmount, bool inPlaySound, bool dcHealing)
{
bool theDidHeal = false;
if ( gpGlobals->time > this->mTimeOfLastDCRegeneration + BALANCE_VAR(kDefenseChamberThinkInterval) - 0.05f || (dcHealing == false)) {
if ( dcHealing )
this->mTimeOfLastDCRegeneration = gpGlobals->time;
float theMaxHealth = this->mBaseHealth;
if(!this->GetIsBuilt())
{
float theNormalizedBuildPercentage = this->GetNormalizedBuildPercentage();
theMaxHealth = (kBaseHealthPercentage + theNormalizedBuildPercentage*(1.0f - kBaseHealthPercentage))*this->mBaseHealth;
}
// If we aren't at full health, heal health
if(this->pev->health < theMaxHealth)
{
this->pev->health = min(theMaxHealth, this->pev->health + inRegenerationAmount);
this->HealthChanged();
theDidHeal = true;
}
// Play regen event
if(theDidHeal)
{
if(inPlaySound)
{
// Play regeneration event
PLAYBACK_EVENT_FULL(0, this->edict(), gRegenerationEventID, 0, this->pev->origin, (float *)&g_vecZero, 1.0f, 0.0, /*theWeaponIndex*/ 0, 0, 0, 0 );
}
}
}
return theDidHeal;
}
void AvHBaseBuildable::ResetEntity()
{
CBaseAnimating::ResetEntity();
this->Init();
this->Materialize();
this->pev->effects = 0;
// Build it if marked as starting built
if(this->pev->spawnflags & 1)
this->SetConstructionComplete(true);
this->mKilled = false;
}
void AvHBaseBuildable::InternalSetConstructionComplete(bool inForce)
{
if(!this->mInternalSetConstructionComplete || inForce)
{
// Fully built items are no longer marked as buildable
SetUpgradeMask(&this->pev->iuser4, MASK_BUILDABLE, false);
this->pev->rendermode = kRenderNormal;
this->pev->renderamt = 255;
// GHOSTBUILD: Ensure that finished buildings aren't ghosted.
this->mGhost = false;
this->pev->solid = SOLID_BBOX;
this->SetHasBeenBuilt();
this->SetActive();
this->mInternalSetConstructionComplete = true;
this->TriggerAddTech();
char* theDeploySound = this->GetDeploySound();
if(theDeploySound)
{
EMIT_SOUND(ENT(this->pev), CHAN_WEAPON, theDeploySound, 1, ATTN_NORM);
}
int theDeployAnimation = this->GetDeployAnimation();
this->PlayAnimationAtIndex(theDeployAnimation, true);
}
}
void AvHBaseBuildable::SetConstructionComplete(bool inForce)
{
this->SetNormalizedBuildPercentage(1.0f, inForce);
}
void AvHBaseBuildable::SetAverageUseSoundLength(float inLength)
{
this->mAverageUseSoundLength = inLength;
}
void AvHBaseBuildable::SetResearching(bool inState)
{
int theSequence = this->GetResearchAnimation();
if(!inState)
{
theSequence = this->GetIdleAnimation();
}
this->PlayAnimationAtIndex(theSequence, true);
this->mIsResearching = inState;
}
// Requires mSelectID and mMessageID to be set
// Sets the pev user variables, mBaseHealth, pev->health and pev->armorvalue
void AvHBaseBuildable::InternalInitializeBuildable()
{
// Always buildable
InitializeBuildable(this->pev->iuser3, this->pev->iuser4, this->pev->fuser1, this->mSelectID);
this->mBaseHealth = GetGameRules()->GetBaseHealthForMessageID(this->mMessageID);
this->pev->health = this->mBaseHealth*kBaseHealthPercentage;
this->pev->max_health = this->mBaseHealth;
// Store max health in armorvalue
//this->pev->armorvalue = GetGameRules()->GetBaseHealthForMessageID(this->mMessageID);
}
const float kFallThinkInterval = .1f;
void AvHBaseBuildable::Spawn()
{
this->Precache();
CBaseAnimating::Spawn();
// Get building size in standard way
SET_MODEL(ENT(this->pev), this->mModelName);
pev->movetype = this->GetMoveType();
pev->solid = SOLID_BBOX;
UTIL_SetOrigin( pev, pev->origin );
this->Materialize();
SetTouch(&AvHBaseBuildable::BuildableTouch);
if(this->pev->spawnflags & 1)
this->SetConstructionComplete(true);
// GHOSTBUILD: Mark as unmanifested if it's a marine structure.
if (!this->GetIsOrganic())
{
pev->renderamt = 170;
pev->rendermode = kRenderTransTexture;
this->mGhost = true;
}
}
void AvHBaseBuildable::FallThink()
{
pev->nextthink = gpGlobals->time + kFallThinkInterval;
if ( pev->flags & FL_ONGROUND )
{
this->Materialize();
// Start animating
SetThink(&AvHBaseBuildable::AnimateThink);
this->pev->nextthink = gpGlobals->time + kAnimateThinkTime;
}
}
int AvHBaseBuildable::GetSequenceForBoundingBox() const
{
return 0;
}
void AvHBaseBuildable::Materialize()
{
this->pev->solid = SOLID_BBOX;
this->pev->movetype = this->GetMoveType();
this->pev->classname = MAKE_STRING(this->mClassName);
this->pev->takedamage = DAMAGE_YES;
SetBits(this->pev->flags, FL_MONSTER);
// Always buildable
this->InternalInitializeBuildable();
this->SetNormalizedBuildPercentage(0.0f);
// NOTE: fuser2 is used for repairing structures
Vector theMinSize, theMaxSize;
//int theSequence = this->GetSequenceForBoundingBox();
// Get height needed for model
//this->ExtractBbox(theSequence, (float*)&theMinSize, (float*)&theMaxSize);
//float theHeight = theMaxSize.z - theMinSize.z;
AvHSHUGetSizeForTech(this->GetMessageID(), theMinSize, theMaxSize);
UTIL_SetSize(pev, theMinSize, theMaxSize);
this->PlayAnimationAtIndex(this->GetSpawnAnimation(), true);
SetUse(&AvHBaseBuildable::ConstructUse);
}
int AvHBaseBuildable::TakeDamage(entvars_t* inInflictor, entvars_t* inAttacker, float inDamage, int inBitsDamageType)
{
if(GetGameRules()->GetIsCheatEnabled(kcHighDamage))
{
inDamage *= 50;
}
if(!inAttacker)
{
inAttacker = inInflictor;
}
if(!inInflictor)
{
inInflictor = inAttacker;
}
// Take into account handicap
AvHTeam* theTeam = GetGameRules()->GetTeam(AvHTeamNumber(inAttacker->team));
if(theTeam)
{
float theHandicap = theTeam->GetHandicap();
inDamage *= theHandicap;
}
CBaseEntity* inInflictorEntity = CBaseEntity::Instance(inInflictor);
float theDamage = 0;
// Take half damage from piercing
if(inBitsDamageType & NS_DMG_PIERCING)
{
inDamage /= 2.0f;
}
// Take double damage from blast
if(inBitsDamageType & NS_DMG_BLAST)
{
inDamage *= 2.0f;
}
if((inBitsDamageType & NS_DMG_ORGANIC) && !this->GetIsOrganic())
{
inDamage = 0.0f;
}
theDamage = AvHPlayerUpgrade::CalculateDamageLessArmor((AvHUser3)this->pev->iuser3, this->pev->iuser4, inDamage, this->pev->armorvalue, inBitsDamageType, GetGameRules()->GetNumActiveHives((AvHTeamNumber)this->pev->team));
if(theDamage > 0)
{
int theAnimationIndex = this->GetTakeDamageAnimation();
if(theAnimationIndex >= 0)
{
this->PlayAnimationAtIndex(theAnimationIndex, true);
}
// Award experience to attacker
CBaseEntity* theEntity = CBaseEntity::Instance(ENT(inAttacker));
AvHPlayer* inAttacker = dynamic_cast<AvHPlayer*>(theEntity);
if(inAttacker && (inAttacker->pev->team != this->pev->team))
{
inAttacker->AwardExperienceForObjective(theDamage, this->GetMessageID());
}
}
int theReturnValue = 0;
if(theDamage > 0.0f)
{
if(this->GetTriggerAlertOnDamage())
GetGameRules()->TriggerAlert((AvHTeamNumber)this->pev->team, ALERT_UNDER_ATTACK, this->entindex());
theDamage = CBaseAnimating::TakeDamage(inInflictor, inAttacker, inDamage, inBitsDamageType);
bool theDrawDamage = (ns_cvar_float(&avh_drawdamage) > 0);
if(theDrawDamage)
{
Vector theMinSize;
Vector theMaxSize;
AvHSHUGetSizeForTech(this->GetMessageID(), theMinSize, theMaxSize);
Vector theStartPos = this->pev->origin;
theStartPos.z += theMaxSize.z;
// Draw for everyone (team is 0 after inDamage parameter)
AvHSUPlayNumericEvent(-inDamage, this->edict(), theStartPos, 0, kNumericalInfoHealthEvent, 0);
}
}
// Structures uncloak when damaged
this->Uncloak();
this->HealthChanged();
return theDamage;
}
void AvHBaseBuildable::TechnologyBuilt(AvHMessageID inMessageID)
{
}
void AvHBaseBuildable::WorldUpdate()
{
this->UpdateTechSlots();
// Organic buildings heal themselves
if(this->GetIsOrganic())
{
this->UpdateAutoHeal();
}
else
{
//this->UpdateDamageEffects();
}
// If we're electrified, set render mode
if(GetHasUpgrade(this->pev->iuser4, MASK_UPGRADE_11))
{
// Base marine building
const int kElectrifyRenderMode = kRenderFxGlowShell;
const int kElectrifyRenderAmount = 40;
this->pev->renderfx = kElectrifyRenderMode;
this->pev->renderamt = kElectrifyRenderAmount;
this->pev->rendercolor.x = kTeamColors[this->pev->team][0];
this->pev->rendercolor.y = kTeamColors[this->pev->team][1];
this->pev->rendercolor.z = kTeamColors[this->pev->team][2];
// Check for enemy players/structures nearby
CBaseEntity* theBaseEntity = NULL;
int theNumEntsDamaged = 0;
while(((theBaseEntity = UTIL_FindEntityInSphere(theBaseEntity, this->pev->origin, BALANCE_VAR(kElectricalRange))) != NULL) && (theNumEntsDamaged < BALANCE_VAR(kElectricalMaxTargets)))
{
// When "electric" cheat is enabled, shock all non-self entities, else shock enemies
if((GetGameRules()->GetIsCheatEnabled(kcElectric) && (theBaseEntity != this)) || ((theBaseEntity->pev->team != this->pev->team) && theBaseEntity->IsAlive()))
{
// Make sure it's not blocked
TraceResult theTraceResult;
UTIL_TraceLine(this->pev->origin, theBaseEntity->pev->origin, ignore_monsters, dont_ignore_glass, this->edict(), &theTraceResult);
if(theTraceResult.flFraction == 1.0f)
{
CBaseEntity* theAttacker = this->GetAttacker();
ASSERT(theAttacker);
if(theBaseEntity->TakeDamage(this->pev, theAttacker->pev, BALANCE_VAR(kElectricalDamage), DMG_GENERIC) > 0)
{
MESSAGE_BEGIN( MSG_BROADCAST, SVC_TEMPENTITY );
WRITE_BYTE(TE_BEAMENTPOINT);
WRITE_SHORT(theBaseEntity->entindex());
WRITE_COORD( this->pev->origin.x);
WRITE_COORD( this->pev->origin.y);
WRITE_COORD( this->pev->origin.z);
WRITE_SHORT( this->mElectricalSprite );
WRITE_BYTE( 0 ); // framestart
WRITE_BYTE( (int)15); // framerate
WRITE_BYTE( (int)(2) ); // life
WRITE_BYTE( 60 ); // width
WRITE_BYTE( 15 ); // noise
WRITE_BYTE( (int)this->pev->rendercolor.x ); // r, g, b
WRITE_BYTE( (int)this->pev->rendercolor.y ); // r, g, b
WRITE_BYTE( (int)this->pev->rendercolor.z ); // r, g, b
WRITE_BYTE( 200 ); // brightness
WRITE_BYTE( 10 ); // speed
MESSAGE_END();
gSoundListManager.PlaySoundInList(kElectricSparkSoundList, this, CHAN_AUTO, .7f);
UTIL_Sparks(theBaseEntity->pev->origin);
theNumEntsDamaged++;
}
}
}
}
}
}
bool AvHBaseBuildable::GetHasBeenKilled() const
{
return this->mKilled;
}
bool AvHBaseBuildable::GetIsTechnologyAvailable(AvHMessageID inMessageID) const
{
bool theTechnologyAvailable = false;
const AvHTeam* theTeam = GetGameRules()->GetTeam((AvHTeamNumber)this->pev->team);
if(theTeam)
{
// Don't allow electrical upgrade if we're already electrified
if((inMessageID != RESEARCH_ELECTRICAL) || !GetHasUpgrade(this->pev->iuser4, MASK_UPGRADE_11))
{
theTechnologyAvailable = (theTeam->GetIsTechnologyAvailable(inMessageID) && this->GetIsBuilt() && !GetHasUpgrade(this->pev->iuser4, MASK_RECYCLING));
// Enable recycle button for unbuilt structures
if(!this->GetIsBuilt() && (inMessageID == BUILD_RECYCLE))
{
theTechnologyAvailable = true;
}
}
}
return theTechnologyAvailable;
}
void AvHBaseBuildable::UpdateTechSlots()
{
// Get tech slot for this structure
AvHGamerules* theGameRules = GetGameRules();
const AvHTeam* theTeam = theGameRules->GetTeam((AvHTeamNumber)this->pev->team);
if(theTeam)
{
// Update tech slots
AvHTechSlots theTechSlots;
if(theTeam->GetTechSlotManager().GetTechSlotList((AvHUser3)this->pev->iuser3, theTechSlots))
{
// Clear the existing slots
int theMasks[kNumTechSlots] = {MASK_UPGRADE_1, MASK_UPGRADE_2, MASK_UPGRADE_3, MASK_UPGRADE_4, MASK_UPGRADE_5, MASK_UPGRADE_6, MASK_UPGRADE_7, MASK_UPGRADE_8};
// Each slot if we technology is available
for(int i = 0; i < kNumTechSlots; i++)
{
int theCurrentMask = theMasks[i];
this->pev->iuser4 &= ~theCurrentMask;
AvHMessageID theMessage = theTechSlots.mTechSlots[i];
if(theMessage != MESSAGE_NULL)
{
if(this->GetIsTechnologyAvailable(theMessage))
{
this->pev->iuser4 |= theCurrentMask;
}
}
}
}
// Update recycling status bar
if(GetHasUpgrade(this->pev->iuser4, MASK_RECYCLING))
{
float theNormalizedRecyclingFactor = (gpGlobals->time - this->mTimeRecycleStarted)/(this->mTimeRecycleDone - this->mTimeRecycleStarted);
theNormalizedRecyclingFactor = min(max(theNormalizedRecyclingFactor, 0.0f), 1.0f);
//theResearchEntity->pev->fuser1 = (kResearchFuser1Base + theNormalizedResearchFactor)*kNormalizationNetworkFactor;
AvHSHUSetBuildResearchState(this->pev->iuser3, this->pev->iuser4, this->pev->fuser1, false, theNormalizedRecyclingFactor);
}
}
}
void AvHBaseBuildable::TriggerDeathAudioVisuals(bool isRecycled)
{
AvHClassType theTeamType = AVH_CLASS_TYPE_UNDEFINED;
AvHTeam* theTeam = GetGameRules()->GetTeam((AvHTeamNumber)this->pev->team);
if(theTeam)
{
theTeamType = theTeam->GetTeamType();
}
switch(theTeamType)
{
case AVH_CLASS_TYPE_ALIEN:
AvHSUPlayParticleEvent(kpsChamberDeath, this->edict(), this->pev->origin);
break;
case AVH_CLASS_TYPE_MARINE:
// lots of smoke
// : 980
// Less smoke for recycled buildings
int smokeScale = isRecycled ? 15 : 25;
MESSAGE_BEGIN( MSG_BROADCAST, SVC_TEMPENTITY );
WRITE_BYTE( TE_SMOKE );
WRITE_COORD( RANDOM_FLOAT( pev->absmin.x, pev->absmax.x ) );
WRITE_COORD( RANDOM_FLOAT( pev->absmin.y, pev->absmax.y ) );
WRITE_COORD( RANDOM_FLOAT( pev->absmin.z, pev->absmax.z ) );
WRITE_SHORT( g_sModelIndexSmoke );
WRITE_BYTE( smokeScale ); // scale * 10
WRITE_BYTE( 10 ); // framerate
MESSAGE_END();
break;
}
char* theKilledSound = this->GetKilledSound();
if(theKilledSound)
{
EMIT_SOUND(ENT(this->pev), CHAN_AUTO, theKilledSound, 1.0, ATTN_IDLE);
}
}
void AvHBaseBuildable::UpdateAutoBuild(float inTimePassed)
{
if(GetGameRules()->GetGameStarted())
{
// TF2 snippet for making sure players don't get stuck in buildings
if(this->pev->solid == SOLID_NOT)
{
//trace_t tr;
//UTIL_TraceHull(this->pev->origin, this->pev->origin, this->pev->mins, this->pev->maxs, this->pev, &tr);
//if(!tr.startsolid && !tr.allsolid )
//if(AvHSHUGetIsAreaFree(this->pev->origin, this->pev->mins, this->pev->maxs, this->edict()))
// Check point contents for corner points
float theMinX = this->pev->origin.x + this->pev->mins.x;
float theMinY = this->pev->origin.y + this->pev->mins.y;
float theMinZ = this->pev->origin.z + this->pev->mins.z;
float theMaxX = this->pev->origin.x + this->pev->maxs.x;
float theMaxY = this->pev->origin.y + this->pev->maxs.y;
float theMaxZ = this->pev->origin.z + this->pev->maxs.z;
// Do tracelines between the corners, to make sure there's no geometry inside the box
Vector theMinVector(theMinX, theMinY, theMinZ);
Vector theMaxVector(theMaxX, theMaxY, theMaxZ);
if(AvHSHUTraceLineIsAreaFree(theMinVector, theMaxVector, this->edict()))
{
theMinVector = Vector(theMaxX, theMinY, theMinZ);
theMaxVector = Vector(theMinX, theMaxY, theMaxZ);
if(AvHSHUTraceLineIsAreaFree(theMinVector, theMaxVector, this->edict()))
{
theMinVector = Vector(theMaxX, theMaxY, theMinZ);
theMaxVector = Vector(theMinX, theMinY, theMaxZ);
if(AvHSHUTraceLineIsAreaFree(theMinVector, theMaxVector, this->edict()))
{
this->pev->solid = SOLID_BBOX;
// Relink into world (not sure if this is necessary)
UTIL_SetOrigin(this->pev, this->pev->origin);
}
}
}
}
else
{
// If it's not fully built, build more
bool theIsBuilding, theIsResearching;
float thePercentage;
AvHSHUGetBuildResearchState(this->pev->iuser3, this->pev->iuser4, this->pev->fuser1, theIsBuilding, theIsResearching, thePercentage);
float theBuildTime = GetGameRules()->GetBuildTimeForMessageID(this->GetMessageID());
float theBuildPercentage = inTimePassed/theBuildTime;
float theNewPercentage = min(thePercentage + theBuildPercentage, 1.0f);
this->SetNormalizedBuildPercentage(theNewPercentage);
// // Increase built time if not fully built
// if(!this->GetHasBeenBuilt() && (theNewPercentage >= 1.0f))
// {
// this->SetConstructionComplete();
// }
//// else
//// {
//// this->pev->rendermode = kRenderTransTexture;
//// int theStartAlpha = this->GetStartAlpha();
//// this->pev->renderamt = theStartAlpha + theNewPercentage*(255 - theStartAlpha);
//// }
//
// AvHSHUSetBuildResearchState(this->pev->iuser3, this->pev->iuser4, this->pev->fuser1, true, theNewPercentage);
// TODO: Heal self?
// TODO: Play ambient sounds?
}
}
}
void AvHBaseBuildable::UpdateAutoHeal()
{
if(GetGameRules()->GetGameStarted() && this->GetIsBuilt())
{
if((this->mTimeOfLastAutoHeal != -1) && (gpGlobals->time > this->mTimeOfLastAutoHeal))
{
float theMaxHealth = GetGameRules()->GetBaseHealthForMessageID(this->GetMessageID());
if(this->pev->health < theMaxHealth)
{
float theTimePassed = (gpGlobals->time - this->mTimeOfLastAutoHeal);
float theHitPointsToGain = theTimePassed*BALANCE_VAR(kOrganicStructureHealRate);
this->pev->health += theHitPointsToGain;
this->pev->health = min(this->pev->health, theMaxHealth);
this->HealthChanged();
}
}
this->mTimeOfLastAutoHeal = gpGlobals->time;
}
}
void AvHBaseBuildable::UpdateDamageEffects()
{
if(GetGameRules()->GetGameStarted() && this->GetIsBuilt())
{
// Add special effects for structures that are hurt or almost dead
float theMaxHealth = GetGameRules()->GetBaseHealthForMessageID(this->GetMessageID());
float theHealthScalar = this->pev->health/theMaxHealth;
float theTimeInterval = max(gpGlobals->time - this->mTimeOfLastDamageUpdate, .1f);
const float kParticleSystemLifetime = 5.0f;
int theAverageSoundInterval = -1;
// If we're at 25% health or less, emit black smoke
if(gpGlobals->time > (this->mTimeOfLastDamageEffect + kParticleSystemLifetime))
{
if(theHealthScalar < .25f)
{
AvHSUPlayParticleEvent(kpsBuildableLightDamage, this->edict(), this->pev->origin);
this->mTimeOfLastDamageEffect = gpGlobals->time;
theAverageSoundInterval = 3;
}
// If we're at 50% health or less, emit light smoke
else if(theHealthScalar < .5f)
{
AvHSUPlayParticleEvent(kpsBuildableLightDamage, this->edict(), this->pev->origin);
this->mTimeOfLastDamageEffect = gpGlobals->time;
theAverageSoundInterval = 5;
}
}
// If we're at less then 75% health, spark occasionally
if(theHealthScalar < .75f)
{
int theRandomChance = RANDOM_LONG(0, (float)8/theTimeInterval);
if(theRandomChance == 0)
{
UTIL_Sparks(this->pev->origin);
UTIL_Sparks(this->pev->origin);
const char* theHurtSoundToPlay = kBuildableHurt1Sound;
if(RANDOM_LONG(0, 1) == 1)
{
theHurtSoundToPlay = kBuildableHurt2Sound;
}
float theVolume = .3f;
EMIT_SOUND(this->edict(), CHAN_AUTO, theHurtSoundToPlay, theVolume, ATTN_NORM);
}
}
this->mTimeOfLastDamageUpdate = gpGlobals->time;
}
}
void AvHBaseBuildable::HealthChanged()
{
int theMaxHealth = this->mBaseHealth;//this->pev->armorvalue;
int theCurrentHealth = this->pev->health;
float theNewHealthPercentage = (float)theCurrentHealth/theMaxHealth;
this->pev->fuser2 = theNewHealthPercentage*kNormalizationNetworkFactor;
}
bool AvHBaseBuildable::GetIsPersistent() const
{
return this->mPersistent;
}
void AvHBaseBuildable::SetPersistent()
{
this->mPersistent = true;
}
|
awslabs/aws-soter
|
src/com/amazon/soter/checker/search/DFS.java
|
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazon.soter.checker.search;
import com.amazon.soter.checker.SearchConfiguration;
import com.amazon.soter.checker.Strategy;
import com.amazon.soter.checker.tasks.Task;
import com.amazon.soter.checker.strategies.Generator;
import java.util.Stack;
import java.util.concurrent.Callable;
import java.util.logging.Logger;
/** Implementation of DFS. */
public class DFS<T> extends Searcher<T> {
private final Logger logger = Logger.getLogger(Searcher.class.getName());
/** Stack of previously-made scheduling choices */
private SchedulingChoices<Task> taskChoices = new SchedulingChoices<>();
/** Stack of previously-made int choices */
private SchedulingChoices<Integer> intChoices = new SchedulingChoices<>();
/** Stack of previously-made bool choices */
private SchedulingChoices<Boolean> boolChoices = new SchedulingChoices<>();
/** DFS has finished exhaustively searching all scheduling choices */
private boolean isFullyExploredChoices = false;
/** DFS has finished exhaustively searching all int choices */
private boolean isFullyExploredIntChoices = false;
/** DFS has finished exhaustively searching all boolean choices */
private boolean isFullyExploredBoolChoices = false;
/** Scheduling choice made by DFS */
private class SchedulingChoice<U> {
/** Scheduling choice made that should be repeated next iteration */
private U repeat;
/** Generator representing backtrack set */
private Generator<U> backtrack;
}
/** Scheduling choices made by DFS */
private class SchedulingChoices<U> extends Stack<SchedulingChoice<U>> {
private boolean clearEmpty() {
while (!isEmpty() && !peek().backtrack.hasNext()) {
pop();
}
if (!isEmpty()) {
peek().repeat = null;
}
return isEmpty();
}
U getNextChoice(int depth, Callable<Generator<U>> nextGenerator) {
SchedulingChoice<U> sc;
if (depth < size()) {
sc = get(depth);
} else {
sc = new SchedulingChoice<>();
try {
sc.backtrack = nextGenerator.call();
} catch (Exception e) {
e.printStackTrace();
}
push(sc);
}
if (sc.repeat == null) {
sc.repeat = sc.backtrack.getNext();
}
return sc.repeat;
}
}
/** Load configuration, if necessary. */
public void updateConfiguration(SearchConfiguration searchConfiguration) { }
/** Make a new exhaustive DFS.
*
* @param strat The search strategy to use
*/
public DFS(Strategy strat) {
super(strat);
}
@Override
boolean hasNext() {
return getNext() != null;
}
@Override
int getNextIntegerChoice(int bound) {
return intChoices.getNextChoice(getIntChoiceDepth(), () -> getStrat().getIntInstance(bound));
}
@Override
boolean getNextBooleanChoice() {
return boolChoices.getNextChoice(getBoolChoiceDepth(), () -> getStrat().getBoolInstance());
}
@Override
Task getNext() {
return taskChoices.getNextChoice(getDepth(), () -> getStrat().getTaskInstance(getChecker().getEnabled()));
}
@Override
void runNext(Task t) {
// Need to lookup to update the task to the current iteration's version
t = getChecker().lookupByID(t);
logger.fine("Choice " + getDepth() + ": " + t.getTaskId());
getChecker().run(t);
}
@Override
void prepareForNextIteration() {
isFullyExploredIntChoices = intChoices.clearEmpty();
if (isFullyExploredIntChoices) {
isFullyExploredBoolChoices = boolChoices.clearEmpty();
isFullyExploredIntChoices = false; // reset ints
if (isFullyExploredBoolChoices) {
isFullyExploredChoices = taskChoices.clearEmpty();
isFullyExploredBoolChoices = false; // reset bools
}
}
}
@Override
boolean isDone() {
return super.isDone() || isFullyExploredChoices;
}
}
|
ArriolaHarold2001/addedlamps
|
build/tmp/expandedArchives/forge-1.17.1-37.0.58_mapped_official_1.17.1-sources.jar_461b1baaba5fdaecf94c73039d52c00b/com/mojang/math/Vector3d.java
|
<filename>build/tmp/expandedArchives/forge-1.17.1-37.0.58_mapped_official_1.17.1-sources.jar_461b1baaba5fdaecf94c73039d52c00b/com/mojang/math/Vector3d.java
package com.mojang.math;
public class Vector3d {
public double x;
public double y;
public double z;
public Vector3d(double p_86218_, double p_86219_, double p_86220_) {
this.x = p_86218_;
this.y = p_86219_;
this.z = p_86220_;
}
public void set(Vector3d p_176290_) {
this.x = p_176290_.x;
this.y = p_176290_.y;
this.z = p_176290_.z;
}
public void set(double p_176286_, double p_176287_, double p_176288_) {
this.x = p_176286_;
this.y = p_176287_;
this.z = p_176288_;
}
public void scale(double p_176284_) {
this.x *= p_176284_;
this.y *= p_176284_;
this.z *= p_176284_;
}
public void add(Vector3d p_176292_) {
this.x += p_176292_.x;
this.y += p_176292_.y;
this.z += p_176292_.z;
}
}
|
densogiaichned/serenity
|
Userland/Libraries/LibWeb/Bindings/AudioConstructor.cpp
|
<reponame>densogiaichned/serenity<gh_stars>1-10
/*
* Copyright (c) 2022, <NAME> <<EMAIL>>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibWeb/Bindings/AudioConstructor.h>
#include <LibWeb/Bindings/HTMLAudioElementPrototype.h>
#include <LibWeb/Bindings/HTMLAudioElementWrapper.h>
#include <LibWeb/Bindings/NodeWrapperFactory.h>
#include <LibWeb/DOM/ElementFactory.h>
#include <LibWeb/HTML/Window.h>
#include <LibWeb/Namespace.h>
namespace Web::Bindings {
AudioConstructor::AudioConstructor(JS::GlobalObject& global_object)
: NativeFunction(*global_object.function_prototype())
{
}
void AudioConstructor::initialize(JS::GlobalObject& global_object)
{
auto& vm = this->vm();
auto& window = static_cast<WindowObject&>(global_object);
NativeFunction::initialize(global_object);
define_direct_property(vm.names.prototype, &window.ensure_web_prototype<HTMLAudioElementPrototype>("HTMLAudioElement"), 0);
define_direct_property(vm.names.length, JS::Value(0), JS::Attribute::Configurable);
}
JS::ThrowCompletionOr<JS::Value> AudioConstructor::call()
{
return vm().throw_completion<JS::TypeError>(global_object(), JS::ErrorType::ConstructorWithoutNew, "Audio");
}
// https://html.spec.whatwg.org/multipage/media.html#dom-audio
JS::ThrowCompletionOr<JS::Object*> AudioConstructor::construct(FunctionObject&)
{
// 1. Let document be the current global object's associated Document.
auto& window = static_cast<WindowObject&>(HTML::current_global_object());
auto& document = window.impl().associated_document();
// 2. Let audio be the result of creating an element given document, audio, and the HTML namespace.
auto audio = DOM::create_element(document, HTML::TagNames::audio, Namespace::HTML);
// 3. Set an attribute value for audio using "preload" and "auto".
audio->set_attribute(HTML::AttributeNames::preload, "auto"sv);
auto src_value = vm().argument(0);
// 4. If src is given, then set an attribute value for audio using "src" and src.
// (This will cause the user agent to invoke the object's resource selection algorithm before returning.)
if (!src_value.is_undefined()) {
auto src = TRY(src_value.to_string(global_object()));
audio->set_attribute(HTML::AttributeNames::src, move(src));
}
// 5. Return audio.
return wrap(global_object(), audio);
}
}
|
HanumantappaBudihal/LeetCode-Solutions
|
3.Topicwise Questions/9. Palindrome Number.cpp
|
<gh_stars>0
class Solution {
public:
bool isPalindrome(int x) {
int input=x;
long reverseNumber=0;
while(x>0)
{
reverseNumber=(reverseNumber*10)+(x%10);
x=x/10;
cout<<x<<" ";
}
if(input!=reverseNumber)
return false;
cout<<input<< " "<<reverseNumber;
return true;
}
};
|
itzg/tsdb-cassandra
|
src/main/java/com/rackspace/ceres/app/model/TsdbQueryRequest.java
|
package com.rackspace.ceres.app.model;
import java.util.List;
import lombok.Data;
@Data
public class TsdbQueryRequest {
String metric;
String downsample;
List<TsdbFilter> filters;
}
|
gdky005/KaiDunPro
|
app/src/main/java/com/kaidun/pro/bean/CourseSchedule.java
|
package com.kaidun.pro.bean;
import java.util.List;
/**
* Created by Administrator on 2018/2/5.
*/
public class CourseSchedule {
/**
* message : 成功
* result : [{"bookCode":"4","courseSortName":"ABC","listingRate":"0%","readingRate":"0%","speakingRate":"0%","writingRate":"0%"}]
* statusCode : 100
* ver : 1
*/
private String message;
private int statusCode;
private int ver;
private List<ResultBean> result;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
public int getVer() {
return ver;
}
public void setVer(int ver) {
this.ver = ver;
}
public List<ResultBean> getResult() {
return result;
}
public void setResult(List<ResultBean> result) {
this.result = result;
}
public static class ResultBean {
/**
* bookCode : 4
* courseSortName : ABC
* listingRate : 0%
* readingRate : 0%
* speakingRate : 0%
* writingRate : 0%
*/
private String bookCode;
private String courseSortName;
private String listingRate;
private String readingRate;
private String speakingRate;
private String writingRate;
public String getBookCode() {
return bookCode;
}
public void setBookCode(String bookCode) {
this.bookCode = bookCode;
}
public String getCourseSortName() {
return courseSortName;
}
public void setCourseSortName(String courseSortName) {
this.courseSortName = courseSortName;
}
public String getListingRate() {
return listingRate;
}
public void setListingRate(String listingRate) {
this.listingRate = listingRate;
}
public String getReadingRate() {
return readingRate;
}
public void setReadingRate(String readingRate) {
this.readingRate = readingRate;
}
public String getSpeakingRate() {
return speakingRate;
}
public void setSpeakingRate(String speakingRate) {
this.speakingRate = speakingRate;
}
public String getWritingRate() {
return writingRate;
}
public void setWritingRate(String writingRate) {
this.writingRate = writingRate;
}
}
}
|
suluner/tencentcloud-sdk-cpp
|
thpc/include/tencentcloud/thpc/v20211109/ThpcClient.h
|
<reponame>suluner/tencentcloud-sdk-cpp
/*
* Copyright (c) 2017-2019 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.
*/
#ifndef TENCENTCLOUD_THPC_V20211109_THPCCLIENT_H_
#define TENCENTCLOUD_THPC_V20211109_THPCCLIENT_H_
#include <functional>
#include <future>
#include <tencentcloud/core/AbstractClient.h>
#include <tencentcloud/core/Credential.h>
#include <tencentcloud/core/profile/ClientProfile.h>
#include <tencentcloud/core/AsyncCallerContext.h>
#include <tencentcloud/thpc/v20211109/model/BindAutoScalingGroupRequest.h>
#include <tencentcloud/thpc/v20211109/model/BindAutoScalingGroupResponse.h>
#include <tencentcloud/thpc/v20211109/model/CreateClusterRequest.h>
#include <tencentcloud/thpc/v20211109/model/CreateClusterResponse.h>
#include <tencentcloud/thpc/v20211109/model/DeleteClusterRequest.h>
#include <tencentcloud/thpc/v20211109/model/DeleteClusterResponse.h>
#include <tencentcloud/thpc/v20211109/model/DescribeClustersRequest.h>
#include <tencentcloud/thpc/v20211109/model/DescribeClustersResponse.h>
namespace TencentCloud
{
namespace Thpc
{
namespace V20211109
{
class ThpcClient : public AbstractClient
{
public:
ThpcClient(const Credential &credential, const std::string ®ion);
ThpcClient(const Credential &credential, const std::string ®ion, const ClientProfile &profile);
typedef Outcome<Core::Error, Model::BindAutoScalingGroupResponse> BindAutoScalingGroupOutcome;
typedef std::future<BindAutoScalingGroupOutcome> BindAutoScalingGroupOutcomeCallable;
typedef std::function<void(const ThpcClient*, const Model::BindAutoScalingGroupRequest&, BindAutoScalingGroupOutcome, const std::shared_ptr<const AsyncCallerContext>&)> BindAutoScalingGroupAsyncHandler;
typedef Outcome<Core::Error, Model::CreateClusterResponse> CreateClusterOutcome;
typedef std::future<CreateClusterOutcome> CreateClusterOutcomeCallable;
typedef std::function<void(const ThpcClient*, const Model::CreateClusterRequest&, CreateClusterOutcome, const std::shared_ptr<const AsyncCallerContext>&)> CreateClusterAsyncHandler;
typedef Outcome<Core::Error, Model::DeleteClusterResponse> DeleteClusterOutcome;
typedef std::future<DeleteClusterOutcome> DeleteClusterOutcomeCallable;
typedef std::function<void(const ThpcClient*, const Model::DeleteClusterRequest&, DeleteClusterOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DeleteClusterAsyncHandler;
typedef Outcome<Core::Error, Model::DescribeClustersResponse> DescribeClustersOutcome;
typedef std::future<DescribeClustersOutcome> DescribeClustersOutcomeCallable;
typedef std::function<void(const ThpcClient*, const Model::DescribeClustersRequest&, DescribeClustersOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeClustersAsyncHandler;
/**
*本接口(BindAutoScalingGroup)用于为集群队列绑定弹性伸缩组
* @param req BindAutoScalingGroupRequest
* @return BindAutoScalingGroupOutcome
*/
BindAutoScalingGroupOutcome BindAutoScalingGroup(const Model::BindAutoScalingGroupRequest &request);
void BindAutoScalingGroupAsync(const Model::BindAutoScalingGroupRequest& request, const BindAutoScalingGroupAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr);
BindAutoScalingGroupOutcomeCallable BindAutoScalingGroupCallable(const Model::BindAutoScalingGroupRequest& request);
/**
*本接口 (CreateCluster) 用于创建并启动集群。
* @param req CreateClusterRequest
* @return CreateClusterOutcome
*/
CreateClusterOutcome CreateCluster(const Model::CreateClusterRequest &request);
void CreateClusterAsync(const Model::CreateClusterRequest& request, const CreateClusterAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr);
CreateClusterOutcomeCallable CreateClusterCallable(const Model::CreateClusterRequest& request);
/**
*本接口(DeleteCluster)用于删除一个指定的集群。
* @param req DeleteClusterRequest
* @return DeleteClusterOutcome
*/
DeleteClusterOutcome DeleteCluster(const Model::DeleteClusterRequest &request);
void DeleteClusterAsync(const Model::DeleteClusterRequest& request, const DeleteClusterAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr);
DeleteClusterOutcomeCallable DeleteClusterCallable(const Model::DeleteClusterRequest& request);
/**
*本接口(DescribeClusters)用于查询集群列表。
* @param req DescribeClustersRequest
* @return DescribeClustersOutcome
*/
DescribeClustersOutcome DescribeClusters(const Model::DescribeClustersRequest &request);
void DescribeClustersAsync(const Model::DescribeClustersRequest& request, const DescribeClustersAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr);
DescribeClustersOutcomeCallable DescribeClustersCallable(const Model::DescribeClustersRequest& request);
};
}
}
}
#endif // !TENCENTCLOUD_THPC_V20211109_THPCCLIENT_H_
|
lattwood/datadog-agent
|
pkg/collector/corechecks/system/winproc/winproc_windows.go
|
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-present Datadog, Inc.
//go:build windows
// +build windows
package winproc
import (
"github.com/DataDog/datadog-agent/pkg/aggregator"
"github.com/DataDog/datadog-agent/pkg/autodiscovery/integration"
"github.com/DataDog/datadog-agent/pkg/collector/check"
core "github.com/DataDog/datadog-agent/pkg/collector/corechecks"
"github.com/DataDog/datadog-agent/pkg/util/winutil/pdhutil"
)
const winprocCheckName = "winproc"
type processChk struct {
core.CheckBase
numprocs *pdhutil.PdhSingleInstanceCounterSet
pql *pdhutil.PdhSingleInstanceCounterSet
}
// Run executes the check
func (c *processChk) Run() error {
sender, err := aggregator.GetSender(c.ID())
if err != nil {
return err
}
procQueueLength, _ := c.pql.GetValue()
procCount, _ := c.numprocs.GetValue()
sender.Gauge("system.proc.queue_length", procQueueLength, "", nil)
sender.Gauge("system.proc.count", procCount, "", nil)
sender.Commit()
return nil
}
func (c *processChk) Configure(data integration.Data, initConfig integration.Data, source string) error {
err := c.CommonConfigure(data, source)
if err != nil {
return err
}
c.numprocs, err = pdhutil.GetSingleInstanceCounter("System", "Processes")
if err != nil {
return err
}
c.pql, err = pdhutil.GetSingleInstanceCounter("System", "Processor Queue Length")
return err
}
func processCheckFactory() check.Check {
return &processChk{
CheckBase: core.NewCheckBase(winprocCheckName),
}
}
func init() {
core.RegisterCheck(winprocCheckName, processCheckFactory)
}
|
debashish05/competitive_programming
|
codeforces/109-A-33848292.cpp
|
<filename>codeforces/109-A-33848292.cpp
#include<bits/stdc++.h>
#define ll long long int
#define loop(k) for(i=0;i<k;++i)
#define loop2(k,l) for(j=k;j<l;++j)
#define mod 1000000007
using namespace std;
int main()
{
std::ios_base::sync_with_stdio(false);cin.tie(NULL);
ll t=1,i=0,j=0,k=0;
//cin>>t;
while(t--){
ll n;
cin>>n;
for(i=0;(4*i+7*j)<=n;++i){
for(j=0;(4*i+7*j)<=n;++j){
//cout<<4*i+7*j<<"\n";
if(4*i+7*j==n)break;
}
if(4*i+7*j==n)break;
j=0;
}
//cout<<4*i+7*j;
if(4*i+7*j==n){
for(k=0;k<i;++k)cout<<"4";
for(k=0;k<j;++k)cout<<"7";
}
else cout<<"-1";
cout<<"\n";
}
return 0;
}
|
dudetheduck/curso-web-moderno
|
array/exercicios/ex05.js
|
// Crie uma função que receba dois números e retorne se o primeiro é maior ou igual ao segundo.
function maiorOuIgual(n1, n2) {
if (typeof n1 != typeof n2) {
return false
} else {
return n1 >= n2
}
}
console.log(maiorOuIgual(0, 0))
console.log(maiorOuIgual(0, "0"))
console.log(maiorOuIgual(5, 1))
|
MarkG/java-oss-lib
|
src/test/java/com/trendrr/oss/tests/TimeAmountTests.java
|
/**
*
*/
package com.trendrr.oss.tests;
import java.io.UnsupportedEncodingException;
import junit.framework.Assert;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import com.trendrr.oss.TimeAmount;
import com.trendrr.oss.Timeframe;
import com.trendrr.oss.exceptions.TrendrrParseException;
/**
* @author <NAME>
* @created Apr 11, 2012
*
*/
public class TimeAmountTests {
protected static Log log = LogFactory.getLog(TimeAmountTests.class);
@Test
public void test() throws UnsupportedEncodingException, TrendrrParseException {
test("10 minutes", Timeframe.MINUTES, 10);
test("15m", Timeframe.MINUTES, 15);
test("24h", Timeframe.HOURS, 24);
}
@Test
public void testAbbrev() throws TrendrrParseException {
TimeAmount amt = TimeAmount.instance("10 min");
TimeAmount amt2 = TimeAmount.instance(amt.abbreviation());
Assert.assertEquals(amt.toString(), amt2.toString());
amt = TimeAmount.instance("10 months");
amt2 = TimeAmount.instance(amt.abbreviation());
Assert.assertEquals(amt.toString(), amt2.toString());
amt = TimeAmount.instance("10 millis");
amt2 = TimeAmount.instance(amt.abbreviation());
Assert.assertEquals(amt.toString(), amt2.toString());
amt = TimeAmount.instance("10 secs");
amt2 = TimeAmount.instance(amt.abbreviation());
Assert.assertEquals(amt.toString(), amt2.toString());
amt = TimeAmount.instance("10 hours");
amt2 = TimeAmount.instance(amt.abbreviation());
Assert.assertEquals(amt.toString(), amt2.toString());
amt = TimeAmount.instance("10 years");
amt2 = TimeAmount.instance(amt.abbreviation());
Assert.assertEquals(amt.toString(), amt2.toString());
}
private void test(String str, Timeframe frame, int amount) throws TrendrrParseException {
TimeAmount amt = TimeAmount.instance(str);
Assert.assertNotNull(amt);
Assert.assertEquals(frame, amt.getTimeframe());
Assert.assertEquals(amount, amt.getAmount());
}
}
|
Runnable/api-client
|
test/unit-route.js
|
'use strict';
var expect = require('chai').expect;
var sinon = require('sinon');
var User = require('../lib/models/user');
var Route = require('../lib/models/user/route');
var mockClient = {
post: sinon.spy(),
patch: sinon.spy(),
del: sinon.spy()
};
var userContentDomain = 'runnableapp.com';
var modelOpts = {
client: mockClient,
userContentDomain: userContentDomain
};
describe('route', function () {
var ctx;
beforeEach(function (done) {
ctx = {};
done();
});
describe('constructor', function () {
it('should have the right path', function(done) {
var user = new User({}, modelOpts);
var srcHostname = 'hello.runnableapp.com';
var route = user.newRoute({ srcHostname: srcHostname }, modelOpts);
expect(route.path()).to.equal('users/me/routes/'+encodeURIComponent(srcHostname));
done();
});
});
});
|
OpenEstate/OpenEstate-IS24-REST
|
Core/src/main/jaxb/org/openestate/is24/restapi/xml/common/FacilityType.java
|
package org.openestate.is24.restapi.xml.common;
import javax.annotation.Generated;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for FacilityType.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="FacilityType">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="ASSISTED_LIVING"/>
* <enumeration value="RESIDENCE"/>
* <enumeration value="SENIOR_PARK"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "FacilityType")
@XmlEnum
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-07T09:44:49+02:00", comments = "JAXB RI v2.3.0")
public enum FacilityType {
/**
* Seniorenwohnen
*
*/
ASSISTED_LIVING,
/**
* Residenz
*
*/
RESIDENCE,
/**
* Seniorenwohnpark
*
*/
SENIOR_PARK;
public String value() {
return name();
}
public static FacilityType fromValue(String v) {
return valueOf(v);
}
}
|
pja35/LogicGates-Last
|
newdoc/html/search/all_14.js
|
<gh_stars>1-10
var searchData=
[
['xor',['XOR',['../class_x_o_r.html',1,'']]]
];
|
atombrella/Dawa
|
packages/server/apiSpecification/ejerlav/sqlModel.js
|
<filename>packages/server/apiSpecification/ejerlav/sqlModel.js
"use strict";
const nameAndKey = require('./nameAndKey');
const sqlParameterImpl = require('../common/sql/sqlParameterImpl');
const parameters = require('./parameters');
const sqlUtil = require('../common/sql/sqlUtil');
const assembleSqlModel = sqlUtil.assembleSqlModel;
const dbapi = require('../../dbapi');
const postgisSqlUtil = require('../common/sql/postgisSqlUtil');
const columns = Object.assign({
kode: {
column: 'ejerlav.kode'
},
navn: {
column: 'ejerlav.navn'
},
tsv: {
column: 'ejerlav.tsv'
},
geom_json: {
select: function (sqlParts, sqlModel, params) {
const sridAlias = dbapi.addSqlParameter(sqlParts, params.srid || 4326);
return postgisSqlUtil.geojsonColumn(params.srid || 4326, sridAlias, 'ejerlav.geom');
}
},
}, postgisSqlUtil.bboxVisualCenterColumns());
const parameterImpls = [
sqlParameterImpl.simplePropertyFilter(parameters.propertyFilter, columns),
sqlParameterImpl.reverseGeocodingWithin(),
sqlParameterImpl.geomWithin(),
sqlParameterImpl.search(columns, ['navn']),
sqlParameterImpl.paging(columns, nameAndKey.key)
];
const baseQuery = function() {
return {
select: [],
from: ['ejerlav'],
whereClauses: [],
groupBy: '',
orderClauses: [],
sqlParams: []
};
};
module.exports = assembleSqlModel(columns, parameterImpls, baseQuery);
const registry = require('../registry');
registry.add('ejerlav', 'sqlModel', undefined, module.exports);
|
Dr-Turtle/DRG_ModPresetManager
|
Source/FSDEngine/Public/SDFRandomizeTransform.h
|
<reponame>Dr-Turtle/DRG_ModPresetManager<filename>Source/FSDEngine/Public/SDFRandomizeTransform.h<gh_stars>1-10
#pragma once
#include "CoreMinimal.h"
#include "SDFSingleChildBase.h"
#include "SDFRandomizeTransformProperties.h"
#include "SDFRandomizeTransform.generated.h"
UCLASS(BlueprintType)
class USDFRandomizeTransform : public USDFSingleChildBase {
GENERATED_BODY()
public:
UPROPERTY(BlueprintReadWrite, EditAnywhere)
FSDFRandomizeTransformProperties Properties;
USDFRandomizeTransform();
};
|
makeitrealcamp/top-v12
|
node/express-sequelize/sequelize/index.js
|
const { Sequelize } = require('sequelize');
const { applyExtraSetup } = require('./extra-setup');
// In a real app, you should keep the database connection URL as an environment variable.
// But for this example, we will just use a local SQLite database.
// const sequelize = new Sequelize(process.env.DB_CONNECTION_URL);
/**
* Examples
* "postgres": {
"username": "postgres",
"password": "<PASSWORD>",
"database": "groceries",
"host": "127.0.0.1",
"dialect": "postgres"
},
"mysql": {
"username": "root",
"password": <PASSWORD>,
"database": "database_test",
"host": "127.0.0.1",
"dialect": "mysql"
},
*/
const sequelize = new Sequelize({
dialect: 'sqlite',
storage: 'sqlite-example-database/example-db.sqlite',
logQueryParameters: true,
benchmark: true
});
const modelDefiners = [
require('./models/user.model'),
require('./models/instrument.model'),
require('./models/orchestra.model'),
// Add more models here...
// require('./models/item'),
];
// We define all models according to their files.
for (const modelDefiner of modelDefiners) {
modelDefiner(sequelize);
}
// We execute any extra setup after the models are defined, such as adding associations.
applyExtraSetup(sequelize);
// We export the sequelize connection instance to be used around our app.
module.exports = sequelize;
|
zhangchuanchuan/DesignMode
|
com/stream/visitor/common/Element.java
|
<gh_stars>0
public abstract class Element {
public abstract void accept(Visitor v);
}
|
wayxzz/leet-code-questions
|
test/623_add-one-row-to-tree.test.js
|
/*
*
* 给定一个二叉树,根节点为第1层,深度为 1。在其第 d 层追加一行值为 v 的节点。
*
* 添加规则:给定一个深度值 d (正整数),针对深度为 d-1 层的每一非空节点 N,为 N 创建两个值为 v 的左子树和右子树。
*
* 将 N 原先的左子树,连接为新节点 v 的左子树;将 N 原先的右子树,连接为新节点 v 的右子树。
*
* 如果 d 的值为 1,深度 d - 1 不存在,则创建一个新的根节点 v,原先的整棵树将作为 v 的左子树。
*
* 示例 1:
*
*
* 输入:
* 二叉树如下所示:
* 4
* / \
* 2 6
* / \ /
* 3 1 5
*
* v = 1
*
* d = 2
*
* 输出:
* 4
* / \
* 1 1
* / \
* 2 6
* / \ /
* 3 1 5
*
*
*
* 示例 2:
*
*
* 输入:
* 二叉树如下所示:
* 4
* /
* 2
* / \
* 3 1
*
* v = 1
*
* d = 3
*
* 输出:
* 4
* /
* 2
* / \
* 1 1
* / \
* 3 1
*
*
* 注意:
*
*
* 输入的深度值 d 的范围是:[1,二叉树最大深度 + 1]。
* 输入的二叉树至少有一个节点。
*
*
*
*/
|
vitorbaraujo/libpitaya
|
src/pc_mutex.h
|
<filename>src/pc_mutex.h
/**
* Copyright (c) 2014,2015 NetEase, Inc. and other Pomelo contributors
* MIT Licensed.
*/
#ifndef PC_MUTEX_H
#define PC_MUTEX_H
#include <assert.h>
/*
* pc_mutex_t is recursive
*/
#ifdef _WIN32
#include <windows.h>
typedef CRITICAL_SECTION pc_mutex_t;
static __inline void pc_mutex_init(pc_mutex_t* mutex)
{
InitializeCriticalSection(mutex);
}
static __inline void pc_mutex_lock(pc_mutex_t* mutex)
{
EnterCriticalSection(mutex);
}
static __inline void pc_mutex_unlock(pc_mutex_t* mutex)
{
LeaveCriticalSection(mutex);
}
static __inline void pc_mutex_destroy(pc_mutex_t* mutex)
{
DeleteCriticalSection(mutex);
}
#else
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
typedef pthread_mutex_t pc_mutex_t;
static inline void pc_mutex_init(pc_mutex_t* mutex)
{
pthread_mutexattr_t attr;
int ret;
pthread_mutexattr_init(&attr);
#ifdef __linux__
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP);
#else
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
#endif
ret = pthread_mutex_init(mutex, &attr);
assert(!ret);
}
static inline void pc_mutex_lock(pc_mutex_t* mutex)
{
int ret;
ret = pthread_mutex_lock(mutex);
assert(!ret);
}
static inline void pc_mutex_unlock(pc_mutex_t* mutex)
{
int ret;
ret = pthread_mutex_unlock(mutex);
assert(!ret);
}
static inline void pc_mutex_destroy(pc_mutex_t* mutex)
{
int ret;
ret = pthread_mutex_destroy(mutex);
assert(!ret);
}
#endif
#endif /* PC_MUTEX_H */
|
aagatsapkota/alexa-skill
|
src/js-utils/display.js
|
<gh_stars>0
import moment from 'moment-timezone'
import { zdColorWhite } from '@zendeskgarden/css-variables'
const semver = require('semver')
const equals = require('fast-deep-equal')
// LOCAL FUNCTIONS
const dateStartsWith = (value, comparison) => {
return stringStartsWith(
[
moment(value).format('MDYY'),
moment(value).format('M/D/YY'),
moment(value).format('MDYYYY'),
moment(value).format('M/D/YYYY'),
moment(value).format('MMDDYYYY'),
moment(value).format('MM/DD/YYYY'),
moment(value).format('DDMMYYYY')
],
comparison
)
}
const prepareFetchResponse = response => {
return response.text().then(body => {
let json = {};
if (body !== '') {
json = JSON.parse(body);
}
if (!response.ok) {
const error = JSON.parse(body);
json = { errors: [error] };
}
return {
status: response.status,
ok: response.ok,
json
};
});
}
const priceStartsWith = (values, comparison) => {
return stringStartsWith(
ensureArray(values).map(value => ensureString(value).replace(/\D/g, '')),
ensureString(comparison).replace(/\D/g, '')
)
}
const recase = (string, replacement = '') => !string
? ''
: string
.replace(/[^a-zA-Z0-9]+/g, replacement)
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')
.replace(/([a-z])([A-Z])/g, '$1-$2')
.replace(/([0-9])([^0-9])/g, '$1-$2')
.replace(/([^0-9])([0-9])/g, '$1-$2')
.replace(/[-_]+/g, replacement)
.toLowerCase()
const stringIncludes = (values, comparison) => {
return ensureArray(values).some(
value =>
(value && typeof value !== 'object' && includes(value, comparison)) ||
false
)
}
const stringStartsWith = (values, comparison) => {
return ensureArray(values).some(
value =>
(value &&
typeof value !== 'object' &&
ensureString(value).toLowerCase().startsWith(ensureString(comparison).toLowerCase())) ||
false
)
}
// EXPORTED FUNCTIONS
export const isWhite = color => {
return (
color === 'white' ||
color === '#fff' ||
color === '#ffffff' ||
color === 'rgb(255, 255, 255)' ||
color === zdColorWhite
)
}
export const formatTimelineEventDate = date => {
return `${moment(date).format('ll')} ${moment(date).format('LT')}`;
}
export const trimStatus = paymentStatus => {
switch (paymentStatus) {
case 'refunded':
return 'refund'
case 'authorized':
return 'auth'
default:
return paymentStatus
}
}
export const hashAddress = address => {
return hashCode(
`${address.line_1 || ''}${address.line_2 || ''}${address.city ||
''}${address.county || ''}${address.postcode || ''}${address.country ||
''}`
)
}
export const convertStoreAddress = store => {
return {
name: store.name,
firstName: '',
lastName: '',
line1: store.address,
line2: '',
city: store.city,
region: store.state,
country: '',
postCode: store.zip,
phone: store.phone,
email: store.email
}
}
// TODO: bring in address name field in general to address form?
export const toCommerceAddress = (
line1,
line2,
city,
state,
zip,
firstName = '',
lastName = '',
country = 'US'
// eslint-disable-next-line max-params
) => ({
first_name: firstName,
last_name: lastName,
line_1: line1,
line_2: line2,
city: city,
county: state,
postcode: zip,
country: country
})
export const fromCommerceAddress = (address = {}) => ({
name: address.company_name,
firstName: address.first_name,
lastName: address.last_name,
line1: address.line_1,
line2: address.line_2,
city: address.city,
region: address.county,
country: address.country,
postCode: address.postcode,
phone: address.phone || '',
email: address.email || ''
})
export const wrapKeyData = (keyData, keyType = 'RSA PRIVATE') => {
return `-----BEGIN ${keyType} KEY-----${
keyData.replace( /"/g, '')
}-----END ${keyType} KEY-----\n`.replace(/\\n/g, '\n')
}
export const arrayEmpty = (array) => {
// eslint-disable-next-line eqeqeq
return !array || !array.length || array[0] == undefined
}
export const arraysEqual = (array1, array2) => {
return (
array1 &&
array2 &&
array1.length === array2.length &&
array1.sort().every((value, index) => {
return value === array2.sort()[index];
})
);
}
export const arrayNotEmpty = (array) => {
// eslint-disable-next-line eqeqeq
return !arrayEmpty(array) && array[0] != undefined
}
export const camelcase = string => {
return !string
? ''
: string.replace(
/\w\S*/g,
word => `${uppercase(word.charAt(0))}${word.substr(1).toLowerCase()}`
);
}
export const clean = string => {
return string ? string.replace(/\W/g, '') : string;
}
export const cleanObject = object => {
return !object
? object
: Object.entries(object)
.filter(([key, value]) => {
// eslint-disable-next-line eqeqeq
return value && value != undefined;
}) // Remove undef. and null.
.reduce(
(cleanedObject, [key, value]) =>
typeof value === 'object'
? { ...cleanedObject, [key]: cleanObject(value) } // Recurse.
: { ...cleanedObject, [key]: value }, // Copy value.
{}
);
}
export const cloneObject = object => {
return JSON.parse(JSON.stringify(object));
}
export const compareDate = (date1, date2) => {
return -moment.utc(date1).diff(moment.utc(date2))
}
export const compareNumber = (number1, number2) => {
return number1 - number2
}
export const compareString = (string1, string2) => {
return ensureString(string1).localeCompare(string2)
}
export const convertSpaces = string => {
return string ? string.replace(/ /g, '\u00a0') : string;
}
export const dashcase = string => {
return recase(string, '-');
}
export const deepEqual = (object1, object2) => {
return object1 &&
object2 &&
typeof object1 === 'object' &&
typeof object2 === 'object'
? equals(object1, object2)
: object1 === object2;
}
export const delay = (time) => {
return new Promise((res) => {
return setTimeout(() => {
return res()
}, time)
})
}
export const endsWithAny = (string, suffixes = []) => {
return suffixes.some(suffix => {
return string.endsWith(suffix);
});
}
/**
* Helper to escape unsafe characters in HTML, including &, <, >, ", ', `, =
* @param {String} str String to be escaped
* @return {String} escaped string
*/
export const escapeSpecialChars = str => {
if (typeof str !== 'string')
throw new TypeError(
'escapeSpecialChars function expects input in type String'
);
const escaped = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'`': '`',
'=': '='
};
return str.replace(/[&<>"'`=]/g, function(m) {
return escaped[m];
});
}
export const ensureNumeric = (string) => Number(ensureString(string).replace(/[^0-9.]/gi, ''))
export const ensureArray = (array = []) => {
return !array ? [] : Array.isArray(array) ? array : [array]
}
export const ensureObject = (object) => {
return object || {}
}
export const ensureString = (string) => {
return string ? `${string}` : ''
}
export const splitString = (splitting, index = splitting.length) => {
const string = ensureString(splitting)
return [string.slice(0, index), string.slice(index)]
}
export const capitalize = (string) => {
const parts = splitString(string, 1)
return `${uppercase(parts[0])}${parts[1]}`
}
export const uppercase = string => {
return ensureString(string).toUpperCase();
}
export const isTrue = (value) => {
const string = ensureString(value)
return !['','false'].includes(string)
}
export const isType = (value, type) => {
return value && typeof value === type
}
export const formatPhone = phoneNumber => {
return phoneNumber
? phoneNumber
.replace(/[^\d]/g, '')
.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3')
: '';
}
export const getHash = unhashed => {
return clean(unhashed);
}
export const getPagedData = (
data,
selectedPage,
pageSize,
sortComparator,
sortField,
sortDirection
// eslint-disable-next-line max-params
) => {
const sortedData = sortField && sortDirection
? data.sort((a, b) => {
const aValue = traverse(sortField, a);
const bValue = traverse(sortField, b);
const sortComparison = sortComparator(aValue, bValue);
return sortDirection === 'asc' ? sortComparison : -sortComparison;
})
: data;
return sortedData.slice((selectedPage - 1) * pageSize, selectedPage * pageSize);
}
export const handleFetchResponse = (response) => {
return prepareFetchResponse(response).then((responseObj) => {
if (responseObj.ok) {
return responseObj.json
}
let errorMsg = responseObj
if (typeof responseObj === 'object') {
errorMsg = JSON.stringify(responseObj)
}
return Promise.reject(safeParse(errorMsg))
})
}
export const hashCode = (object) => {
const key = object ? JSON.stringify(object) : null
return key
? Array.from(key).reduce((s, c) => {
return (Math.imul(31, s) + c.charCodeAt(0)) | 0
}, 0)
: null
}
export const includes = (original, comparison) => {
const formattedOriginal = ensureString(original)
.replace(/ /g, '')
.toLowerCase();
const formattedComparison = ensureString(comparison)
.replace(/ /g, '')
.toLowerCase();
return formattedOriginal.includes(formattedComparison);
}
export const isNumeric = string => {
return string && !isNaN(parseFloat(string)) && isFinite(string);
}
export const isAlpha = string => {
return string && /^[a-zA-Z]*$/.test(string);
}
export const lowercase = (string) => {
return !string ? '' : string.toLowerCase()
}
export const mergeArraysByKey = (ary1, ary2, key) => {
return ensureArray(ary1).map(item1 => {
const matchingItem = ensureArray(ary2).find(item2 => {
return item2[key] === item1[key] && item2;
});
return {
...item1,
...matchingItem
};
});
}
export const nextRandom = (max = 100, min = 1) => {
let randomNumber;
do {
randomNumber = random(max, min);
} while (randomNumber === nextRandom.last);
nextRandom.last = randomNumber;
return randomNumber;
}
export const nullable = object => {
return !object || object === 'null' || object === undefined || object === null
? null
: object;
}
export const objectEmpty = (object) => {
return !object || !Object.keys(object).length
}
// TODO investigate if there is already a utility for this purpose
export const objectContainsAnyValue = (object) => {
return Object.values(object).some(value => nullable(value))
}
export const objectMatchers = {
stringIncludes,
stringStartsWith,
priceStartsWith,
dateStartsWith
};
export const objectMatchesFilter = (
object = {},
matchers = {},
filter = ''
) => {
return Object.entries(matchers).some(
([fieldKey, match = stringIncludes]) => {
const value = traverse(fieldKey, object);
return match(value, filter);
}
);
}
export const objectNotEmpty = (object) => {
return !objectEmpty(object)
}
export const objectToFormData = (object, formData = [], previousKey = '') => {
object = safeParse(object);
if (object && typeof object === 'object') {
Object.keys(object).forEach(key => {
objectToFormData(
object[key],
formData,
previousKey === '' ? key : `${previousKey}[${key}]`
);
});
} else if (previousKey !== '') {
formData.push(`${encodeURIComponent(previousKey)}=${encodeURIComponent(object)}`)
}
return formData.join('&');
}
export const objectToQuerystring = (object) => {
object = safeParse(object)
return object
? Object.keys(object)
.map((property) => {
const value = object[property]
return `${encodeURIComponent(property)}=${
typeof value === 'object'
? objectToQuerystring(value)
: encodeURIComponent(value)
}`
})
.join('&')
: ''
}
export const prepareRegex = (string) => {
return (
string
// TODO!!: test out with: .replace(/[-[\]{}()*+!<=:?./\\^$|#\s,]/g, '\\$&')
// eslint-disable-next-line no-useless-escape
.replace(/[-[\]{}()*+!<=:?.\/\\^$|#\s,]/g, '\\$&')
.replace('\\*', '.+')
)
}
export const toRegexArray = (csv) => {
return (csv || '')
.replace(/, /g, ',')
.split(',')
.map(value => new RegExp(`^${prepareRegex(value)}$`))
}
export const querystringToObject = queryString => {
const hashes = queryString.split('&');
return hashes.reduce((params, hash) => {
const split = hash.indexOf('=');
const key = hash.slice(0, split);
const val = hash.slice(split + 1);
return Object.assign(params, { [key]: decodeURIComponent(val) });
}, {});
}
export const random = (max = 100, min = 1) => {
const floor = Math.min(max, min)
return Math.floor(Math.random() * (max - floor + 1)) + floor
}
export const reverseTruncate = (value, length, prefix) => {
if (!value || !length) return value || '';
const truncated = ensureString(value).slice(value.length - length);
return value.length <= length
? value
: prefix
? `${prefix}${truncated}`
: truncated;
}
export const safeTrim = (object) => {
if (object
&& typeof object === 'string'
) {
object = object.trim(object)
}
return object
}
export const safeParse = (object, trim) => {
if (object
&& typeof object === 'string'
) {
if (trim) {
object = safeTrim(object)
}
if (object.startsWith('{') || object.startsWith('[')) {
object = JSON.parse(object)
}
}
return object
}
export const safeStringify = object => {
if (object && typeof object === 'object') {
object = JSON.stringify(object);
}
return object;
}
export const snakecase = string => {
return recase(string, '_');
}
export const splitName = (fullName = '') => {
fullName = fullName || '';
const firstName = fullName
.split(' ')
.slice(0, -1)
.join(' ');
const lastName = fullName.split(' ').slice(-1)[0];
return { firstName, lastName };
}
/**
* Helper to render a dataset using the same template function
* @param {Array} set dataset
* @param {Function} getTemplate function to generate template
* @param {String} initialValue any template string prepended
* @return {String} final template
*/
export const templatingLoop = (set, getTemplate, initialValue = '') => {
return set.reduce((accumulator, item, index) => {
return `${accumulator}${getTemplate(item, index)}`;
}, initialValue);
}
export const toName = (nameable) => {
return !nameable ? '' : Object.keys(nameable)[0]
}
// eslint-disable-next-line no-restricted-globals
export const traverse = (selector, obj = self, separator = '.') => {
const properties = Array.isArray(selector)
? selector
: ensureString(selector).split(separator);
return properties.reduce((prev, curr) => prev && prev[curr], obj);
}
export const compareVersion = (version1, version2) =>
version1 === version2 ? 0 : semver.gt(version1, version2) ? -1 : 1
export const removeLeadingSlash = string => ensureString(string).replace(/^\//, "")
export const removeTrailingSlash = string => ensureString(string).replace(/\/$/, "")
export const removeLeadingTrailingSlash = string =>
removeTrailingSlash(removeLeadingSlash(string))
export const ensureLeadingSlash = string => `/${removeLeadingSlash(string)}`
export const getNavigationItem = (text, item) => {
const { frontmatter, path } = item || {}
const { title } = frontmatter || {}
return {
...frontmatter,
text: text || title,
path,
}
}
export const getNavigationLinks = ({
path: currentPath,
subPaths = [],
labels = ['Previous', 'Next'],
maxItems = 2,
}) => {
const currentIndex = subPaths.findIndex(
({ path: subPath }) => subPath === currentPath
)
const items = Math.max(2, maxItems)
const previousCount = Math.ceil(items / 2)
const nextCount = items - previousCount
const firstIndex = Math.max(0, currentIndex - previousCount)
const lastIndex =
currentIndex < 0
? 0
: Math.min(subPaths.length, currentIndex + 1 + nextCount)
return [
...(currentIndex === 0 ? [null] : []),
...subPaths.slice(firstIndex, currentIndex),
...subPaths.slice(currentIndex + 1, lastIndex),
...(currentIndex === subPaths.length - 1 ? [null] : []),
].map((navigationItem, index) =>
getNavigationItem(labels[index] || index, navigationItem)
)
}
export const scrollTo = hash => {
if (hash && document.querySelector(hash)) {
document.querySelector(hash).scrollIntoView({
behavior: 'smooth',
block: 'start',
})
}
}
export const formatNumber = (number, locale = 'en') => Number(number).toLocaleString(locale)
export const formatDate = (value) => {
return value
? moment(value).format('lll')
: null
}
export const formatTimestamps = ({ created_at = moment(), updated_at = moment() } = {}) => ({
created_at: moment(created_at).format('YYYY-MM-DD HH:mm:ss'),
updated_at: moment(updated_at).format('YYYY-MM-DD HH:mm:ss'),
})
export const getOrigin = (origin, referer) => {
const subOrigin = referer ? referer.match(/\?origin=([^?&]+)/) : null
if (subOrigin) {
origin = decodeURIComponent(subOrigin[1])
}
return origin || referer
}
export const handleError = response => {
return new Promise((resolve, reject) => {
if (response && response.error) {
console.error(
`handleError, response.error: ${JSON.stringify(response.error)}`
)
reject(response.error)
} else {
resolve(response)
}
})
}
export const getProvidersLabel = providersName => {
// 'commerceProvider
return providersName.replace('Provider', '') // 'commerce', 'shipping'
}
export const getProviderInfo = (providers, providerType) => {
return objectEmpty(providers) || !providerType
? null
: providers[providerType].getInfo()
}
|
orzjs/koa-blog
|
server/routes/blog/index.js
|
const apiBlog = require('./controller');
const path = require('path');
const fs = require('fs-extra');
const multer = require('koa-multer');
const config = require('../../config/config');
const Settings = require('../../models').settings;
const uploadPath = config.uploadPath;
const storageImages = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, uploadPath);
},
filename: (req, file, cb) => {
const u = req.body.uuid;
fs.mkdirp(path.join(uploadPath, 'blog-images', u), (err) => {
if (err) {
cb(err);
} else {
cb(null, `blog-images/${u}/${file.originalname}`);
}
});
}
});
const uploadImages = multer({ storage: storageImages });
const storageCover = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, uploadPath);
},
filename: (req, file, cb) => {
fs.mkdirp(path.join(uploadPath, 'cover'), (err) => {
if (err) {
cb(err);
} else {
cb(null, `cover/${file.originalname}`);
}
});
}
});
const uploadCover = multer({ storage: storageCover });
function routeBlog(router) {
router.get('/', blog);
router.get('/blog/(.*)', blog);
router.get('/api/blog', apiBlog.getList);
// 删除博客
router.delete('/api/blog', apiBlog.deleteBlog);
router.post('/api/publish', apiBlog.publishBlog);
router.put('/api/publish', apiBlog.updateBlog);
router.post('/api/uploadFile', uploadImages.single('file'), apiBlog.uploadFile);
router.post('/api/uploadCover', uploadCover.single('cover'), apiBlog.uploadCover);
async function blog(ctx) {
// switch(ctx.path) {
// // 必须登录才能发表
// case '/blog/publish'
// case '/blog/publish':
// case '/blog/update':
// if (ctx.isUnauthenticated()) {
// ctx.redirect('/login');
// } else {
// await ctx.render('../../client/public/views/blog/blog.ejs', {userInfo: ctx.state.user});
// }
// break;
// default:
// await ctx.render('../../client/public/views/blog/blog.ejs', {userInfo: ctx.state.user});
// break;
// }
if (ctx.isUnauthenticated()) {
ctx.redirect('/login');
} else {
const user = ctx.state.user.dataValues;
const userId = user.id;
const setting = await Settings.findOne({ where: { user_id: userId, } });
user.setting = setting.dataValues;
await ctx.render('../../client/public/views/blog/blog.ejs', { userInfo: user });
}
}
}
module.exports = routeBlog;
|
78182648/blibli-go
|
app/admin/ep/marthe/dao/mysql_bugly_version.go
|
package dao
import (
"database/sql"
"fmt"
"go-common/app/admin/ep/marthe/model"
"go-common/library/ecode"
pkgerr "github.com/pkg/errors"
)
const (
_versionInnerJoinProjectSql = "select a.id,a.version,a.bugly_project_id,a.action,a.task_status,a.update_by,a.ctime,a.mtime,b.project_name,b.exception_type from bugly_versions as a inner join bugly_projects as b on a.bugly_project_id = b.id"
_versionInnerJoinProjectSqlCount = "select count(-1) as totalCount from bugly_versions as a inner join bugly_projects as b on a.bugly_project_id = b.id"
_where = "WHERE"
_and = "AND"
)
// InsertBuglyVersion Insert Bugly Version.
func (d *Dao) InsertBuglyVersion(buglyVersion *model.BuglyVersion) error {
return pkgerr.WithStack(d.db.Create(buglyVersion).Error)
}
// UpdateBuglyVersion Update Bugly Version.
func (d *Dao) UpdateBuglyVersion(buglyVersion *model.BuglyVersion) error {
return pkgerr.WithStack(d.db.Model(&model.BuglyVersion{}).Updates(buglyVersion).Error)
}
// QueryBuglyVersionByVersion Query Bugly Version By Version.
func (d *Dao) QueryBuglyVersionByVersion(version string) (buglyVersion *model.BuglyVersion, err error) {
buglyVersion = &model.BuglyVersion{}
if err = d.db.Where("version = ?", version).First(buglyVersion).Error; err != nil {
if err == ecode.NothingFound {
err = nil
} else {
err = pkgerr.WithStack(err)
}
}
return
}
// QueryBuglyVersion Query Bugly Version .
func (d *Dao) QueryBuglyVersion(id int64) (buglyVersion *model.BuglyVersion, err error) {
buglyVersion = &model.BuglyVersion{}
if err = d.db.Where("id = ?", id).First(buglyVersion).Error; err != nil {
if err == ecode.NothingFound {
err = nil
} else {
err = pkgerr.WithStack(err)
}
}
return
}
// QueryBuglyVersionList Query Bugly Version List.
func (d *Dao) QueryBuglyVersionList() (versionList []string, err error) {
var (
rows *sql.Rows
)
sql := "select DISTINCT version from bugly_versions"
if rows, err = d.db.Raw(sql).Rows(); err != nil {
return
}
defer rows.Close()
for rows.Next() {
var ver string
if err = rows.Scan(&ver); err != nil {
return
}
versionList = append(versionList, ver)
}
return
}
// FindBuglyProjectVersions Find Bugly Project Versions.
func (d *Dao) FindBuglyProjectVersions(req *model.QueryBuglyVersionRequest) (total int64, buglyProjectVersions []*model.BuglyProjectVersion, err error) {
var (
qSQL = _versionInnerJoinProjectSql
cSQL = _versionInnerJoinProjectSqlCount
rows *sql.Rows
)
if req.UpdateBy != "" || req.ProjectName != "" || req.Action > 0 || req.Version != "" {
var (
partSql string
logicalWord = _where
)
if req.UpdateBy != "" {
partSql = fmt.Sprintf("%s %s a.update_by = '%s'", partSql, logicalWord, req.UpdateBy)
logicalWord = _and
}
if req.ProjectName != "" {
partSql = fmt.Sprintf("%s %s b.project_name like '%s'", partSql, logicalWord, _wildcards+req.ProjectName+_wildcards)
logicalWord = _and
}
if req.Action > 0 {
partSql = fmt.Sprintf("%s %s a.action = %d", partSql, logicalWord, req.Action)
logicalWord = _and
}
if req.Version != "" {
partSql = fmt.Sprintf("%s %s a.version like '%s'", partSql, logicalWord, _wildcards+req.Version+_wildcards)
logicalWord = _and
}
qSQL = qSQL + partSql
cSQL = cSQL + partSql
}
cDB := d.db.Raw(cSQL)
if err = pkgerr.WithStack(cDB.Count(&total).Error); err != nil {
return
}
gDB := d.db.Raw(qSQL)
if rows, err = gDB.Order("a.ctime DESC").Offset((req.PageNum - 1) * req.PageSize).Limit(req.PageSize).Rows(); err != nil {
return
}
defer rows.Close()
for rows.Next() {
pv := &model.BuglyProjectVersion{}
if err = rows.Scan(&pv.ID, &pv.Version, &pv.BuglyProjectID, &pv.Action, &pv.TaskStatus, &pv.UpdateBy, &pv.CTime, &pv.MTime, &pv.ProjectName, &pv.ExceptionType); err != nil {
return
}
buglyProjectVersions = append(buglyProjectVersions, pv)
}
return
}
// FindEnableAndReadyVersions Find Enable And Ready Versions.
func (d *Dao) FindEnableAndReadyVersions() (buglyVersions []*model.BuglyVersion, err error) {
err = pkgerr.WithStack(d.db.Where("action = ? and task_status = ?", model.BuglyVersionActionEnable, model.BuglyVersionTaskStatusReady).Find(&buglyVersions).Error)
return
}
|
Freddan-67/V3DLib
|
Lib/Source/Functions.h
|
#ifndef _V3DLIB_SOURCE_FUNCTIONS_H_
#define _V3DLIB_SOURCE_FUNCTIONS_H_
#include "Int.h"
#include "Float.h"
#include "StmtStack.h" // StackCallback
namespace V3DLib {
namespace functions {
// These exposed for unit tests
void Return(Int const &val);
void Return(Float const &val);
IntExpr create_function_snippet(StackCallback f);
FloatExpr create_float_function_snippet(StackCallback f);
IntExpr two_complement(IntExpr a);
IntExpr abs(IntExpr a);
IntExpr topmost_bit(IntExpr in_a);
void integer_division(Int "ient, Int &remainder, IntExpr in_a, IntExpr in_b);
inline IntExpr operator-(IntExpr a) { return two_complement(a); }
float cos(float x_in, bool extra_precision = false) noexcept;
float sin(float x_in, bool extra_precision = false) noexcept;
FloatExpr cos(FloatExpr x_in, bool extra_precision = false);
FloatExpr sin(FloatExpr x_in, bool extra_precision = false);
FloatExpr sin_v3d(FloatExpr x_in);
FloatExpr cos_v3d(FloatExpr x_in);
FloatExpr ffloor(FloatExpr x);
FloatExpr fabs(FloatExpr x);
} // namespace functions
void rotate_sum(Int &input, Int &result);
void rotate_sum(Float &input, Float &result);
void set_at(Int &dst, Int n, Int const &src);
void set_at(Float &dst, Int n, Float const &src);
void sync_qpus(Int::Ptr signal);
} // namespace V3DLib
#endif // _V3DLIB_SOURCE_FUNCTIONS_H_
|
thyhero/alpha
|
alpha-db/alpha-db-es6/src/main/java/com/geektcp/alpha/db/es6/dao/EsSearchDao.java
|
<gh_stars>1-10
package com.geektcp.alpha.db.es6.dao;
import com.geektcp.alpha.db.es6.bean.StoreURL;
import com.geektcp.alpha.db.es6.model.EsQuery;
import com.geektcp.alpha.db.es6.model.EsQueryResult;
import java.util.List;
/**
* @author tanghaiyang on 2019/5/7.
*/
public interface EsSearchDao {
EsQueryResult search(StoreURL storeURL, EsQuery esQuery);
EsQueryResult searchByIds(StoreURL storeURL, EsQuery esQuery);
EsQueryResult searchByFields(StoreURL storeURL, EsQuery esQuery);
List<EsQueryResult> multiSearch(StoreURL storeURL, List<EsQuery> list);
EsQueryResult searchByDSL(StoreURL storeURL, String queryDSL);
}
|
CasualPokePlayer/ares
|
hiro/windows/sizable.hpp
|
<filename>hiro/windows/sizable.hpp<gh_stars>100-1000
#if defined(Hiro_Sizable)
namespace hiro {
struct pSizable : pObject {
Declare(Sizable, Object)
virtual auto minimumSize() const -> Size;
virtual auto setCollapsible(bool collapsible) -> void;
virtual auto setGeometry(Geometry geometry) -> void;
};
}
#endif
|
Robbbert/messui
|
src/mame/drivers/monon_color.cpp
|
<filename>src/mame/drivers/monon_color.cpp
// license:BSD-3-Clause
// copyright-holders:<NAME>
/***************************************************************************
Monon Color - Chinese handheld
see
https://gbatemp.net/threads/the-monon-color-a-new-video-game-console-from-china.467788/
https://twitter.com/Splatoon2weird/status/1072182093206052864
uses AX208 CPU (custom 8051 @ 96Mhz with single cycle instructions, extended '16 bit' opcodes + integrated video, jpeg decoder etc.)
https://docplayer.net/52724058-Ax208-product-specification.html
***************************************************************************/
#include "emu.h"
#include "cpu/mcs51/axc51-core.h"
#include "emupal.h"
#include "screen.h"
#include "speaker.h"
#include "bus/generic/slot.h"
#include "bus/generic/carts.h"
class monon_color_state : public driver_device
{
public:
monon_color_state(const machine_config &mconfig, device_type type, const char *tag)
: driver_device(mconfig, type, tag),
m_cart(*this, "cartslot"),
m_maincpu(*this, "maincpu"),
m_screen(*this, "screen"),
m_palette(*this, "palette"),
m_mainram(*this, "mainram"),
m_otherram(*this, "otherram"),
m_bootcopy(0)
{ }
void monon_color(machine_config &config);
protected:
// driver_device overrides
virtual void machine_start() override;
virtual void machine_reset() override;
virtual void video_start() override;
// screen updates
uint32_t screen_update(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
private:
required_device<generic_slot_device> m_cart;
required_device<cpu_device> m_maincpu;
required_device<screen_device> m_screen;
required_device<palette_device> m_palette;
required_shared_ptr<uint8_t> m_mainram;
required_shared_ptr<uint8_t> m_otherram;
DECLARE_DEVICE_IMAGE_LOAD_MEMBER(cart_load);
void monon_color_map(address_map &map);
int m_bootcopy;
};
void monon_color_state::machine_start()
{
uint8_t* flash = memregion("flash")->base();
uint8_t* maincpu = &m_mainram[0];
memcpy(maincpu, flash+0x200, 0x1e00); // 0x4000-0x5dff fixed code?
}
void monon_color_state::machine_reset()
{
m_maincpu->set_state_int(MCS51_PC, 0x4000);
uint8_t* flash = memregion("flash")->base();
uint8_t* maincpu = &m_mainram[0];
memset(maincpu + 0x1e00, 0x00, 0x1000);
switch (m_bootcopy)
{
// there are a whole bunch of blocks that map at 0x5e00 (boot code jumps straight to 0x5e00)
case 0x0: memcpy(maincpu + 0x1e00, flash + 0x2000, 0x1000); break; // BANK0 - clears RAM, sets up stack etc. but then jumps to 0x9xxx where we have nothing (probably the correct initial block tho)
case 0x1: memcpy(maincpu + 0x1e00, flash + 0x4200, 0x0a00); break; // BANK1 - just set register + a jump (to function that writes to UART)
case 0x2: memcpy(maincpu + 0x1e00, flash + 0x4c00, 0x0a00); break; // BANK2
case 0x3: memcpy(maincpu + 0x1e00, flash + 0x5600, 0x0a00); break; // BANK3
case 0x4: memcpy(maincpu + 0x1e00, flash + 0x6000, 0x0a00); break; // BANK4 - ends up reting with nothing on the stack
case 0x5: memcpy(maincpu + 0x1e00, flash + 0x6a00, 0x0a00); break; // BANK5
case 0x6: memcpy(maincpu + 0x1e00, flash + 0x7400, 0x0a00); break; // BANK6
case 0x7: memcpy(maincpu + 0x1e00, flash + 0x7e00, 0x0a00); break; // BANK7
case 0x8: memcpy(maincpu + 0x1e00, flash + 0x8800, 0x0a00); break; // BANK8
case 0x9: memcpy(maincpu + 0x1e00, flash + 0x9200, 0x0a00); break; // BANK9
}
m_bootcopy++;
if (m_bootcopy == 0xa) m_bootcopy = 0x0;
/* block starting at e000 in flash is not code? (or encrypted?)
no code to map at 0x9000 in address space (possible BIOS?)
no code in flash ROM past the first 64kb(?) which is basically the same on all games, must be some kind of script interpreter? J2ME maybe?
there are 5 different 'versions' of the code in the dumped ROMs, where the code is the same the roms match up until 0x50000 after which the game specific data starts
by game number:
103alt (earliest? doesn't have bank9)
101,102,103,104,105 (1st revision)
106,107 (2nd revision)
201 (3rd revision)
202,203,204,205,301,302,303,304 (4th revision)
*/
}
void monon_color_state::video_start()
{
}
uint32_t monon_color_state::screen_update(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect)
{
return 0;
}
static INPUT_PORTS_START( monon_color )
INPUT_PORTS_END
void monon_color_state::monon_color_map(address_map &map)
{
map(0x4000, 0x6fff).ram().share("mainram");
map(0x9000, 0x9fff).ram().share("otherram"); // lots of jumps to here, is there some kind of BIOS? none of the code appears to map here?
}
void monon_color_state::monon_color(machine_config &config)
{
/* basic machine hardware */
AX208(config, m_maincpu, 96000000); // (8051 / MCS51 derived) incomplete core!
m_maincpu->set_addrmap(AS_PROGRAM, &monon_color_state::monon_color_map);
/* video hardware */
SCREEN(config, m_screen, SCREEN_TYPE_RASTER);
m_screen->set_refresh_hz(60);
m_screen->set_vblank_time(ATTOSECONDS_IN_USEC(2500));
m_screen->set_screen_update(FUNC(monon_color_state::screen_update));
m_screen->set_size(32*8, 32*8);
m_screen->set_visarea(0*8, 32*8-1, 2*8, 30*8-1);
m_screen->set_palette(m_palette);
PALETTE(config, m_palette).set_entries(256);
/* sound hardware */
SPEAKER(config, "mono").front_center();
generic_cartslot_device &cartslot(GENERIC_CARTSLOT(config, "cartslot", generic_plain_slot, "monon_color_cart", "bin"));
cartslot.set_width(GENERIC_ROM8_WIDTH);
cartslot.set_device_load(FUNC(monon_color_state::cart_load));
cartslot.set_must_be_loaded(true);
/* software lists */
SOFTWARE_LIST(config, "cart_list").set_original("monon_color");
}
DEVICE_IMAGE_LOAD_MEMBER( monon_color_state::cart_load )
{
uint32_t size = m_cart->common_get_size("rom");
std::vector<uint8_t> temp;
temp.resize(size);
m_cart->rom_alloc(size, GENERIC_ROM8_WIDTH, ENDIANNESS_LITTLE);
m_cart->common_load_rom(&temp[0], size, "rom");
memcpy(memregion("flash")->base(), &temp[0], size);
return image_init_result::PASS;
}
ROM_START( mononcol )
ROM_REGION( 0x1000000, "flash", ROMREGION_ERASE00 )
ROM_END
CONS( 2011, mononcol, 0, 0, monon_color, monon_color, monon_color_state, empty_init, "M&D", "Monon Color", MACHINE_IS_SKELETON )
|
kanaabe/force
|
src/desktop/apps/artsy_primer/server.js
|
<reponame>kanaabe/force<gh_stars>0
import * as routes from './routes'
import express from 'express'
import path from 'path'
import { resize, crop } from '../../components/resizer'
import { toSentence } from 'underscore.string'
const app = express()
app.set('views', path.resolve(__dirname, 'templates'))
app.set('view engine', 'jade')
app.locals.resize = resize
app.locals.crop = crop
app.locals.toSentence = toSentence
app.get('/artsy-primer/:id', routes.article)
app.get('/primer-digest/:id', routes.article)
app.get('/artsy-primer-personalize*', routes.personalize)
app.post('/artsy-primer/set-sailthru', routes.setSailthruData)
export default app
|
thundergolfer/uni
|
machine_learning/applications/spam/a_plan_for_spam/mail_server.py
|
<filename>machine_learning/applications/spam/a_plan_for_spam/mail_server.py
"""
This is the 'main' SMTP mail server that will interact with a Spam-detection
API to detect Spam email and filter it out of client's inboxes.
"""
import asyncore
import email
import email.errors
import email.header
import email.policy
import email.utils
import hashlib
import http
import json
import logging
import smtpd
import smtplib
import time
import urllib.request
import config
import events
from typing import Optional, Tuple
ServerAddr = Tuple[str, int]
logging.basicConfig(format=config.logging_format_str)
logging.getLogger().setLevel(logging.DEBUG)
logging.info("Building mail-server event publisher.")
emit_event_func = events.build_event_emitter(
to_console=True,
to_file=True,
log_root_path=config.logging_file_path_root,
)
event_publisher = events.MailServerEventPublisher(
emit_event=emit_event_func, time_of_day_clock_fn=lambda: time.time_ns()
)
def hash_email_contents(email: bytes) -> str:
return hashlib.sha256(email).hexdigest().upper()
def extract_email_header_field(*, email_bytes: bytes, field_name: str) -> Optional[str]:
e_msg = email.message_from_bytes(email_bytes, policy=email.policy.SMTPUTF8)
return e_msg.get(field_name)
def extract_email_msg_id(email_bytes: bytes) -> Optional[str]:
try:
return extract_email_header_field(
email_bytes=email_bytes, field_name="Message-ID"
)
except (email.errors.HeaderParseError, IndexError):
# A few dozen emails in the dataset(s) have busted Message-IDs.
# There are 3 '<<EMAIL>>' IDs, for example, which are in an invalid format,
# and obviously not unique.
# Ref: https://en.wikipedia.org/wiki/Message-ID
logging.warning("Failed to parse 'Message-ID' from email.")
return None
class AntiSpamServer(smtpd.SMTPServer):
def __init__(self, localaddr, remoteaddr, **kwargs):
super(AntiSpamServer, self).__init__(localaddr, remoteaddr, **kwargs)
def process_message(self, peer, mailfrom, rcpttos, data, **kwargs):
try:
logging.info("Call fraud API ---")
is_spam = self.check_for_spam(email_bytes=data)
except http.client.HTTPException as err:
breakpoint()
e_msg = self.add_anti_spam_headers(is_spam=is_spam, data=data)
# I don't call smtpd.PureProxy's process_message() method because it's
# janky. If I pass bytes for `data` it breaks because it tries to split
# those bytes using '\n', a string. If I pass a string, it passes that
# string to smtplib.sendmail which can only handle ascii strings, and the
# enron dataset emails aren't ascii.
s = smtplib.SMTP()
s.connect(self._remoteaddr[0], self._remoteaddr[1])
try:
s.send_message(msg=e_msg, from_addr=mailfrom, to_addrs=rcpttos)
finally:
s.quit()
@staticmethod
def add_anti_spam_headers(is_spam: bool, data: bytes) -> email.message.Message:
"""
Applying Anti-spam email headers like Microsoft Outlook does.
Ref: https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/anti-spam-message-headers?view=o365-worldwide
"""
e_msg = email.message_from_bytes(data, policy=email.policy.SMTPUTF8)
email_id = extract_email_msg_id(email_bytes=data)
if not email_id:
raise RuntimeError("Should not fail to get Message-ID.")
anti_spam_header_key = "X-Thundergolfer-AntiSpam"
e_msg.add_header(anti_spam_header_key, "SPAM" if is_spam else "HAM")
event_publisher.emit_email_headers_modified(
email_id=email_id,
headers=[anti_spam_header_key],
)
return e_msg
@staticmethod
def check_for_spam(email_bytes: bytes) -> bool:
email_id = extract_email_msg_id(email_bytes=email_bytes)
if not email_id:
raise RuntimeError("Should not fail to get Message-ID.")
body = {"email": email_bytes.decode("latin-1")}
spam_detect_api_url = ":".join(
[str(component) for component in config.spam_detect_api_addr]
)
req = urllib.request.Request(f"http://{spam_detect_api_url}")
req.add_header("Content-Type", "application/json; charset=utf-8")
data = json.dumps(body)
data_b = data.encode("utf-8")
req.add_header("Content-Length", str(len(data_b)))
response = urllib.request.urlopen(req, data_b)
response_data = json.loads(response.read())
return response_data["label"]
def serve() -> None:
logging.info("Starting (spam-detecting) mail server.")
localaddr: ServerAddr = config.mail_server_addr
remoteaddr: ServerAddr = config.mail_receiver_addr
_server = AntiSpamServer(
localaddr=localaddr, remoteaddr=remoteaddr, enable_SMTPUTF8=True
)
asyncore.loop()
if __name__ == "__main__":
serve()
|
guoxiangran/main
|
src/com/tspeiz/modules/util/weixin/GetWxOrderno.java
|
<reponame>guoxiangran/main
package com.tspeiz.modules.util.weixin;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import org.apache.http.impl.client.DefaultHttpClient;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import com.tspeiz.modules.util.weixin.http.HttpClientConnectionManager;
public class GetWxOrderno
{
public static DefaultHttpClient httpclient;
static
{
httpclient = new DefaultHttpClient();
httpclient = (DefaultHttpClient)HttpClientConnectionManager.getSSLInstance(httpclient);
}
public static String getPayNo(String _url,String xmlParam){
StringBuffer buffer = new StringBuffer();
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(_url);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url
.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod("POST");
if ("GET".equalsIgnoreCase("POST"))
httpUrlConn.connect();
// 当有数据需要提交时
if (null != xmlParam) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(xmlParam.getBytes("UTF-8"));
outputStream.close();
}
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
System.out.println("=====返回==="+buffer.toString());
} catch (ConnectException ce) {
} catch (Exception e) {
}
return buffer.toString();
}
/**
* 解析xml,返回第一级元素键值对。如果第一级元素有子节点,则此节点的值是子节点的xml数据。
* @param strxml
* @return
* @throws JDOMException
* @throws IOException
*/
public static Map doXMLParse(String strxml) throws Exception {
if(null == strxml || "".equals(strxml)) {
return null;
}
Map m = new HashMap();
InputStream in = String2Inputstream(strxml);
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(in);
Element root = doc.getRootElement();
List list = root.getChildren();
Iterator it = list.iterator();
while(it.hasNext()) {
Element e = (Element) it.next();
String k = e.getName();
String v = "";
List children = e.getChildren();
if(children.isEmpty()) {
v = e.getTextNormalize();
} else {
v = getChildrenText(children);
}
m.put(k, v);
}
//关闭流
in.close();
return m;
}
/**
* 获取子结点的xml
* @param children
* @return String
*/
public static String getChildrenText(List children) {
StringBuffer sb = new StringBuffer();
if(!children.isEmpty()) {
Iterator it = children.iterator();
while(it.hasNext()) {
Element e = (Element) it.next();
String name = e.getName();
String value = e.getTextNormalize();
List list = e.getChildren();
sb.append("<" + name + ">");
if(!list.isEmpty()) {
sb.append(getChildrenText(list));
}
sb.append(value);
sb.append("</" + name + ">");
}
}
return sb.toString();
}
public static InputStream String2Inputstream(String str) {
return new ByteArrayInputStream(str.getBytes());
}
}
|
BoniLindsley/pymap
|
test/server/test_admin_auth.py
|
from collections.abc import Mapping
import pytest
from grpclib.testing import ChannelFor
from pymapadmin.grpc.admin_grpc import SystemStub, UserStub
from pymapadmin.grpc.admin_pb2 import SUCCESS, FAILURE, UserData, \
LoginRequest, GetUserRequest, SetUserRequest, DeleteUserRequest
from pymap.admin.handlers.system import SystemHandlers
from pymap.admin.handlers.user import UserHandlers
from .base import TestBase
pytestmark = pytest.mark.asyncio
class TestAdminAuth(TestBase):
admin_token = '<KEY>' \
'<KEY>' \
'<KEY>'
@pytest.fixture
def overrides(self):
return {'admin_key': b'testadmintoken'}
async def test_token(self, backend) -> None:
token = await self._login(backend, 'testuser', 'testpass')
await self._get_user(backend, token, 'testuser')
await self._set_user(backend, token, 'testuser', '<PASSWORD>pass')
await self._delete_user(backend, token, 'testuser')
await self._get_user(backend, token, 'testuser',
failure_key='InvalidAuth')
await self._get_user(backend, self.admin_token, 'testuser',
failure_key='UserNotFound')
async def test_authorization(self, backend) -> None:
await self._set_user(backend, self.admin_token, 'newuser', 'newpass')
token1 = await self._login(backend, 'testuser', 'testpass')
token2 = await self._login(backend, 'newuser', 'newpass')
await self._get_user(backend, token1, 'newuser',
failure_key='AuthorizationFailure')
await self._get_user(backend, token2, 'newuser')
await self._set_user(backend, token1, 'newuser', '<PASSWORD>',
failure_key='AuthorizationFailure')
await self._set_user(backend, token2, 'newuser', '<PASSWORD>')
await self._delete_user(backend, token1, 'newuser',
failure_key='AuthorizationFailure')
await self._delete_user(backend, token2, 'newuser')
async def test_admin_role(self, backend) -> None:
token = await self._login(backend, 'testuser', '<PASSWORD>')
await self._set_user(backend, token, 'testuser', 'testpass',
params={'role': 'admin'},
failure_key='NotAllowedError')
await self._set_user(backend, self.admin_token, 'testuser', '<PASSWORD>pass',
params={'role': 'admin'})
await self._set_user(backend, token, 'testuser', '<PASSWORD>',
params={'role': 'admin'})
await self._set_user(backend, token, 'newuser', 'newpass')
await self._delete_user(backend, token, 'newuser')
async def _login(self, backend, authcid: str, secret: str) -> str:
handlers = SystemHandlers(backend)
request = LoginRequest(authcid=authcid, secret=secret)
async with ChannelFor([handlers]) as channel:
stub = SystemStub(channel)
response = await stub.Login(request)
assert SUCCESS == response.result.code
return response.bearer_token
async def _get_user(self, backend, token: str, user: str, *,
failure_key: str = None) -> None:
handlers = UserHandlers(backend)
request = GetUserRequest(user=user)
metadata = {'auth-token': token}
async with ChannelFor([handlers]) as channel:
stub = UserStub(channel)
response = await stub.GetUser(request, metadata=metadata)
if failure_key is None:
assert SUCCESS == response.result.code
assert user == response.username
else:
assert FAILURE == response.result.code
assert failure_key == response.result.key
async def _set_user(self, backend, token: str, user: str, password: str, *,
params: Mapping[str, str] = {},
failure_key: str = None) -> None:
handlers = UserHandlers(backend)
data = UserData(password=password, params=params)
request = SetUserRequest(user=user, data=data)
metadata = {'auth-token': token}
async with ChannelFor([handlers]) as channel:
stub = UserStub(channel)
response = await stub.SetUser(request, metadata=metadata)
if failure_key is None:
assert SUCCESS == response.result.code
assert user == response.username
else:
assert FAILURE == response.result.code
assert failure_key == response.result.key
async def _delete_user(self, backend, token: str, user: str, *,
failure_key: str = None) -> None:
handlers = UserHandlers(backend)
request = DeleteUserRequest(user=user)
metadata = {'auth-token': token}
async with ChannelFor([handlers]) as channel:
stub = UserStub(channel)
response = await stub.DeleteUser(request, metadata=metadata)
if failure_key is None:
assert SUCCESS == response.result.code
assert user == response.username
else:
assert FAILURE == response.result.code
assert failure_key == response.result.key
|
gaoweibupt/PaddleDTX
|
crypto/core/machine_learning/logic_regression/mpc_vertical/regression.go
|
<filename>crypto/core/machine_learning/logic_regression/mpc_vertical/regression.go
// Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package mpc_vertical
import (
"log"
"math"
"math/big"
"strconv"
"github.com/PaddlePaddle/PaddleDTX/crypto/common/math/homomorphism/paillier"
"github.com/PaddlePaddle/PaddleDTX/crypto/common/math/rand"
"github.com/PaddlePaddle/PaddleDTX/crypto/core/machine_learning/common"
)
// 纵向联合学习,基于半同态加密方案的多元逻辑回归算法
// PHE Multiple Variable Logic Regression Model based on Gradient Descent method
// LocalGradAndCostPart 迭代的中间参数,包含未加密的和同态加密参数,用于计算梯度和损失
type LocalGradAndCostPart struct {
EncPart *EncLocalGradAndCostPart // 加密参数
RawPart *RawLocalGradAndCostPart // 原始参数
}
// EncLocalGradAndCostPart 迭代的中间同态加密参数,用于计算梯度和损失
type EncLocalGradAndCostPart struct {
EncPart1 map[int]*big.Int // 对每一条数据(ID编号),有标签方:计算y - 0.5,无标签方: 计算preValA; 并使用公钥pubKey-B进行同态加密;
EncPart2 map[int]*big.Int // 对每一条数据(ID编号),有标签方:计算(y - 0.5)*preValB,无标签方:计算preValA^2/8; 并使用公钥pubKey-B进行同态加密
EncPart3 map[int]*big.Int // 对每一条数据(ID编号),有标签方:计算preValB^2/8,并使用公钥pubKey-B进行同态加密
EncPart4 map[int]*big.Int // 对每一条数据(ID编号),有标签方:计算preValB/4,并使用公钥pubKey-B进行同态加密
EncPart5 map[int]*big.Int // 对每一条数据(ID编号),有标签方:计算0.5 + preValB/4 - y,并使用公钥pubKey-B进行同态加密
EncRegCost *big.Int // 正则化损失,被同态加密
}
// RawLocalGradAndCostPart 迭代中间同态加密参数,用于计算梯度和损失
type RawLocalGradAndCostPart struct {
RawPart1 map[int]*big.Int // 对每一条数据(ID编号),有标签方:计算y - 0.5, 无标签方: 计算preValA
RawPart2 map[int]*big.Int // 对每一条数据(ID编号),有标签方:计算(y - 0.5)*preValB, 无标签方: 计算preValA^2/8
RawPart3 map[int]*big.Int // 对每一条数据(ID编号),有标签方:计算preValB^2/8
RawPart4 map[int]*big.Int // 对每一条数据(ID编号),有标签方:计算preValB/4
RawPart5 map[int]*big.Int // 对每一条数据(ID编号),有标签方:计算0.5 + preValB/4 - y
RawRegCost *big.Int // 正则化损失
}
// ---------------------- 纵向联合学习的模型训练原理相关 start ----------------------
//
// 我们回忆一下,logic regression的损失函数和梯度
//
// ---------- 损失的计算 ----------
//
// 在多元逻辑回归中,我们改用交叉熵(Cross Entropy),来作为损失函数。原因在于,我们在模型中引入了Sigmoid函数。
// Sigmoid函数:1/(1+e^-x),也就是说,最终模型为:1/(1+e^-(w*x)) = 1/(1+e^-(θ(0) + θ(1)*x(1) + θ(2)*x(2) + ... + θ(n)*x(n)))
// Sigmoid函数的特性是函数输出为0和1之间。 我们利用该特性来解决二分类问题。
// 但是,引入该函数后,如果继续使用MSE来作为损失函数,该函数不是一个凹函数或者凸函数。
// 也就是说,存在大量的局部最优点,导致难以使用梯度下降方法来寻找到全局最优点,进而确定模型的最佳参数。
//
// 交叉熵损失函数:
// 总特征数量n, 总样本数量m
// J(θ)=-1/m*CostSum(hθ(x(j)),y(j))
//
// for j:=0; j++; j<m
// {
// CostSum += y(j)*log(hθ(x(j)) + (1-y(j))*log(1-hθ(x(j)))
// }
// 其中,y的值总是为0或者为1
//
// hθ(x(j)) = 1/(1+e^-(w'x)) = 1/(1+e^-(θ(0) + θ(1)*x(1) + θ(2)*x(2) + ... + θ(n)*x(n)))
//
// 参数集合w = [θ(1),θ(2),...,θ(n)]
// 整个模型的参数集合w' = (w, θ(0)) = [θ(0),θ(1),θ(2),...,θ(n)]
//
// 如果要完成去中心化计算损失函数,核心是通过同态和随机mask,完成log(hθ(x(j))和log(1-hθ(x(j))的计算,而y(j)和(1-y(j))由标签方掌握,可以基于同态做明文*密文的运算。
// 问题是,我们可以通过同态和随机mask完成线性方程式的计算,log函数并不支持我们修改过的同态函数,hθ函数中的e^x也不支持同态
// 因此,需要把核心函数log(hθ(x(j))和log(1-hθ(x(j))进行泰勒展开。预估泰勒展开到二次项可以满足精度要求。
//
// 把hθ(x(j)的多元变量考虑成1个x(这不会影响泰勒展开求导),用Sigmoid函数:1/(1+e^-x)来表示。然后对log(hθ(x(j))和log(1-hθ(x(j))来做泰勒展开到二次项。
//
// log(hθ) = ln(1/(1+e^-x)),求导:
// 1阶导数为:f'(x) = (ln(1+e^-x)^-1)' = (-1*ln(1+e^-x))' = -(ln(1+e^-x))' = -(-1 * e^-x)/(1+e^-x) = e^-x/(1+e^-x)
// 2阶导数为:f''(x) = (e^-x * (1+e^-x)^-1)' = (e^-x)' * (1+e^-x)^-1 + (e^-x) * ((1+e^-x)^-1)'
// = -e^-x / (1+e^-x) + e^-x * e^-x / (1+e^-x)^2
// f(0)=ln(0.5), f'(0)=0.5, f''(0)=-1/4
// 所以,log(hθ) = ln(1/(1+e^-x))进行泰勒展开到二次项,结果为:f(x)=f(0)+f'(0)(x)+f''(0)(x^2)/2! = ln(0.5) + x/2 - x^2/8
//
// log(1-hθ) = ln(1 - 1/(1+e^-x)),求导:
// 1阶导数为:f'(x) = (ln(1 - 1/(1+e^-x)))' = (ln(e^-x / (1+e^-x)))' = (1+e^-x)/e^-x * (e^-x / (1+e^-x))' = -1/(1+e^-x)
// 2阶导数为:f''(x) = (-1/(1+e^-x))' = -((1+e^-x)^-1)' = -1 * -1 * (1+e^-x)^-2 * -1 * e^-x = -e^-x / (1+e^-x)^2
// f(0)=ln(0.5), f'(0)=-0.5, f''(0)=-1/4
// 所以,log(1-hθ) = ln(1 - 1/(1+e^-x))进行泰勒展开到二次项,结果为:f(x)=f(0)+f'(0)(x)+f''(0)(x^2)/2! = ln(0.5) - x/2 - x^2/8
//
// 此外,在计算x^2时, (predictValue(j-A) + predictValue(j-B))^2
// = (A(j) + B(j))^2
// = A(j)^2 + B(j)^2 + 2*A(j)*B(j)
//
// 综上,考虑两方场景,也就是无标签方A(部分特征)和有标签方B(部分特征+标签)
//
// 损失函数:
// J(θ)=-1/m*CostSum(hθ(x(j)),y(j))
//
// for j:=0; j++; j<m
// {
// CostSum += y(j)*log(hθ(x(j)) + (1-y(j))*log(1-hθ(x(j))
// }
// 其中,y的值总是为0或者为1
//
// 那么,Cost = y*log(hθ(x) + (1-y)*log(1-hθ(x)) = y*(ln(0.5) + x/2 - x^2/8) + (1-y)*(ln(0.5) - x/2 - x^2/8)
// = ln(0.5) + (y - 0.5)*x - x^2/8 = ln(0.5) + (y - 0.5)*(preValA + preValB) - (preValA + preValB)^2/8
// = ln(0.5) + (y - 0.5)*preValA + (y - 0.5)*preValB - preValA^2/8 - preValB^2/8 - preValA*preValB/4
//
// 无标签方A(部分特征)通过损失函数评估损失时:
// step 1. B用自己的同态公钥加密数据,获得encByB(y - 0.5)、encByB((y - 0.5)*preValB)、encByB(preValB^2/8)、encByB(preValB/4),将加密数据发送给A
// step 2. A用B的公钥执行同态运算:ln(0.5) + encByB(y - 0.5)*preValA + encByB((y - 0.5)*preValB) - preValA^2/8
// - encByB(preValB^2/8) - preValA*encByB(preValB/4) + ranNumA
// step 3. A将同态运算结果发给B
// step 4. B使用自己的私钥解密同态运算结果,将解密结果发给A
// step 5. A从解密结果中移除ranNumA,获得真正结果,用来更新xAj的梯度graAj
//
// 有标签方B(部分特征+标签)通过损失函数评估损失时:
// step 1. A用自己的同态公钥加密数据,获得encByA(preValA)、encByA(preValA^2/8),将加密数据发送给B
// step 2. B用A的公钥执行同态运算:ln(0.5) + (y - 0.5)*encByA(preValA) + (y - 0.5)*preValB - encByA(preValA^2/8)
// - preValB^2/8 - encByA(preValA)*preValB/4 + ranNumB
// step 3. B将同态运算结果发给A
// step 4. A使用自己的私钥解密同态运算结果,将解密结果发给B
// step 5. B从解密结果中移除ranNumB,获得真正结果,用来更新xBj的梯度graBj
//
// 根据最近两次损失函数的差值评估整荡幅度是否符合目标要求,是否可以结束梯度下降的收敛计算
//
// 特别提醒:
// 在上面计算时,需要考虑精度,同态加密(仅支持整数),所以加密前放大指定精度,乘法运算的常数项又放大了指定精度。所以,加法算式中的每一项需要放大(精度*精度),最后在计算结束后,进行缩小。
//
// ---------- 梯度的计算 ----------
//
// 根据上文计算损失函数时的介绍
// 计算出w' = (w, θ(0)) = [θ(0),θ(1),θ(2),...,θ(n)]中的每个θ(i),来得到模型w'
// for i:=0; i++; i<n
// {
// // 计算第i个特征的参数θ(i):
// θ(i) = θ(i) − α*Grad(i)
// }
//
// 第i个特征的Grad(i):
// for j:=0; j++; i<m
// {
// Grad(i) += (predictValue(j) - realValue(j))*trainSet[j][i]
// }
//
// predictValue(j) = hθ(x(j)) = 1/(1+e^-(w'x)) = 1/(1+e^-(θ(0) + θ(1)*x(1) + θ(2)*x(2) + ... + θ(n)*x(n)))
//
// Grad(i) = Grad(i)/m
//
// 同样的,predictValue(j)的计算,需要多方合作完成。
//
// 如果要完成去中心化计算梯度,核心是通过同态和随机mask,完成hθ(x(j))的计算,而y(j)由标签方掌握,可以基于同态做明文*密文的运算。
// 问题是,我们可以通过同态和随机mask完成线性方程式的计算,以e为底数的指数函数e^x并不支持同态
// 因此,需要把核心函数hθ(x(j))进行泰勒展开。预估泰勒展开到二次项可以满足精度要求。
//
// hθ(x) = 1/(1+e^-x)),求导:
// 1阶导数为:f'(x) = ((1+e^-x)^-1)' = -1 * (1+e^-x)^-2 * e^-x * -1 = e^-x / (1+e^-x)^2
// 2阶导数为:f''(x) = (e^-x * (1+e^-x)^-2)' = (e^-x)' * (1+e^-x)^-2 + (e^-x) * ((1+e^-x)^-2)'
// = -e^-x / (1+e^-x)^2 + 2 * e^-x * e^-x / (1+e^-x)^3
// f(0)=0.5, f'(0)=1/4, f''(0)=0
// 所以,hθ(x) = 1/(1+e^-x)进行泰勒展开到二次项,结果为:f(x)=f(0)+f'(0)(x)+f''(0)(x^2)/2! = 0.5 + x/4
//
// 那么,梯度的计算:Grad(i) = (predictValue(j) - realValue(j))*trainSet[j][i]
// = (0.5 + x/4 - y)*x(i) = (0.5 + (preValA + preValB)/4 - y)*x(i)
// = (0.5 + preValA/4 + (preValB/4 - y))*x(i)
// = x(i)*preValA/4 + x(i)*(0.5 + preValB/4 - y)
//
// 无标签方A(部分特征)计算本地特征的梯度时:
// step 1. B用自己的同态公钥加密数据,获得encByB(0.5 + preValB/4 - y),将加密数据发送给A
// step 2. A用B的公钥执行同态运算:x(i)*preValA/4 + x(i)*encByB(0.5 + preValB/4 - y) + ranNumA
// step 3. A将同态运算结果发给B
// step 4. B使用自己的私钥解密同态运算结果,将解密结果发给A
// step 5. A从解密结果中移除ranNumA,获得真正结果,用来更新xAj的梯度graAj
//
// 有标签方B(部分特征+标签)计算本地特征的梯度时:
// step 1. A用自己的同态公钥加密数据,获得encByA(preValA/4),将加密数据发送给B
// step 2. B用A的公钥执行同态运算:x(i)*encByA(preValA/4) + x(i)*(0.5 + preValB/4 - y) + ranNumB
// step 3. B将同态运算结果发给A
// step 4. A使用自己的私钥解密同态运算结果,将解密结果发给B
// step 5. B从解密结果中移除ranNumB,获得真正结果,用来更新xBj的梯度graBj
//
// ---------------------- 纵向联合学习的模型训练原理相关 end ----------------------
// StandardizeDataSet 将样本数据集合进行标准化处理,将均值变为0,标准差变为1
// Z-score Normalization
// x' = (x - avgerage(x)) / standard_deviation(x)
// 特别注意:对于逻辑回归,标签值不做标准化处理
func StandardizeDataSet(sourceDataSet *common.DataSet, label string) *common.StandardizedDataSet {
// Calculate the means and standard deviations for each feature
// 特征的均值
xbarParams := make(map[string]float64)
// 特征的标准差
sigmaParams := make(map[string]float64)
for _, feature := range sourceDataSet.Features {
var sum float64 = 0 // 样本总值
var sigmaSum float64 = 0 // 每个样本值与全体样本值的平均数之差的平方值之和
// 计算总值
for _, value := range feature.Sets {
sum += value
}
// 计算均值
xbars := sum / float64(len(feature.Sets))
// 计算每个样本值与全体样本值的平均数之差的平方值之和
for _, value := range feature.Sets {
sigmaSum += math.Pow(value-xbars, 2)
}
// 计算方差: 每个样本值与全体样本值的平均数之差的平方值的平均数
variance := sigmaSum / float64(len(feature.Sets))
// 计算标准差: 方差的平方根
sigmas := math.Sqrt(variance)
xbarParams[feature.FeatureName] = xbars
sigmaParams[feature.FeatureName] = sigmas
}
// 遍历各个特征维度的特征值集合,根据均值和标准差进行标准化处理
var newFeatures []*common.DataFeature
for _, feature := range sourceDataSet.Features {
// 先获得该特征维度的名称
var newDataFeature common.DataFeature
newDataFeature.FeatureName = feature.FeatureName
// 声明该特征维度的经过标准化处理后的特征值集合
newSets := make(map[int]float64)
// 如果是目标维度
if feature.FeatureName == label {
// 直接赋值,不执行标准化操作
for key, value := range feature.Sets {
newSets[key] = value
}
} else {
xbars := xbarParams[feature.FeatureName]
sigmas := sigmaParams[feature.FeatureName]
// 对特征值进行标准化处理,对数据集的每一条数据的每个特征的减去该特征均值后除以特征标准差。
for key, value := range feature.Sets {
newValue := (value - xbars) / sigmas
newSets[key] = newValue
}
}
newDataFeature.Sets = newSets
newFeatures = append(newFeatures, &newDataFeature)
}
var standardizedDataSet common.StandardizedDataSet
standardizedDataSet.Features = newFeatures
standardizedDataSet.XbarParams = xbarParams
standardizedDataSet.SigmaParams = sigmaParams
standardizedDataSet.OriginalFeatures = sourceDataSet.Features
return &standardizedDataSet
}
// PreProcessDataSet 预处理标签方的标准化数据集
// 将样本数据集转化为一个m*(n+2)的矩阵, 其中每行对应一个样本,每行的第一列为编号ID,第二列为1(截距intercept),其它列分别对应一种特征的值
func PreProcessDataSet(sourceDataSet *common.StandardizedDataSet, label string) *common.TrainDataSet {
var featureNames []string
// 特征数量 - 有多少个特征维度
featureNum := len(sourceDataSet.Features)
// 样本数量 - 取某一个特征的的样本数量
sampleNum := len(sourceDataSet.Features[0].Sets)
// 将样本数据集转化为一个m*(n+2)的矩阵, 其中每行对应一个样本,每行的第一列为编号ID,第二列为1(截距intercept),其它列分别对应一种特征的值
trainSet := make([][]float64, sampleNum)
originalTrainSet := make([][]float64, sampleNum)
for i := 0; i < sampleNum; i++ {
trainSet[i] = make([]float64, featureNum+2)
originalTrainSet[i] = make([]float64, featureNum+2)
}
i := 0 // i表示遍历到第i个样本
for key, _ := range sourceDataSet.Features[0].Sets {
trainSet[key][0] = float64(key)
originalTrainSet[key][0] = float64(key)
// 每个样本的第2列为1
trainSet[key][1] = 1
originalTrainSet[key][1] = 1
i++
}
// 遍历所有的特征维度
i = 1 // i表示遍历到第i个特征维度
for _, feature := range sourceDataSet.Features {
// 遍历每个特征维度的每个样本
// 如果是目标维度
if feature.FeatureName == label {
// 遍历某个特征维度的所有样本
for key, value := range feature.Sets {
// 把值放在训练样本的最后一列
trainSet[key][featureNum+1] = value
}
} else { // 如果不是目标维度
for key, value := range feature.Sets {
trainSet[key][i+1] = value
}
i++
featureNames = append(featureNames, feature.FeatureName)
}
}
// 遍历所有的特征维度
i = 1 // i表示遍历到第i个特征维度
for _, feature := range sourceDataSet.OriginalFeatures {
// 遍历每个特征维度的每个样本
// 如果是目标维度
if feature.FeatureName == label {
// 遍历某个特征维度的所有样本
for key, value := range feature.Sets {
// 把值放在训练样本的最后一列
originalTrainSet[key][featureNum+1] = value
}
} else { // 如果不是目标维度
for key, value := range feature.Sets {
originalTrainSet[key][i+1] = value
}
i++
}
}
if len(label) != 0 {
featureNames = append(featureNames, label)
}
dataSet := &common.TrainDataSet{
FeatureNames: featureNames, // 特征名称的集合
TrainSet: trainSet, // 特征集合
XbarParams: sourceDataSet.XbarParams, // 特征的均值
SigmaParams: sourceDataSet.SigmaParams, // 特征的标准差
OriginalTrainSet: originalTrainSet, // 原始特征集合
}
return dataSet
}
// PreProcessDataSetNoTag 预处理非标签方的标准化训练数据集
// 将样本数据集转化为一个m*(n+1)的矩阵, 其中每行对应一个样本,每行的第一列为编号ID,其它列分别对应一种特征的值
func PreProcessDataSetNoTag(sourceDataSet *common.StandardizedDataSet) *common.TrainDataSet {
var featureNames []string
// 特征数量 - 有多少个特征维度
featureNum := len(sourceDataSet.Features)
// 样本数量 - 取某一个特征的的样本数量
sampleNum := len(sourceDataSet.Features[0].Sets)
// 将样本数据集转化为一个m*(n+2)的矩阵, 其中每行对应一个样本,每行的第一列为编号ID,第二列为1(截距intercept),其它列分别对应一种特征的值
trainSet := make([][]float64, sampleNum)
originalTrainSet := make([][]float64, sampleNum)
for i := 0; i < sampleNum; i++ {
trainSet[i] = make([]float64, featureNum+1)
originalTrainSet[i] = make([]float64, featureNum+1)
}
i := 0 // i表示遍历到第i个样本
for key, _ := range sourceDataSet.Features[0].Sets {
// 每个样本的第1列为编号ID
trainSet[key][0] = float64(key)
originalTrainSet[key][0] = float64(key)
i++
}
// 遍历所有的特征维度
i = 1 // i表示遍历到第i个特征维度
for _, feature := range sourceDataSet.Features {
// 遍历每个特征维度的每个样本
for key, value := range feature.Sets {
trainSet[key][i] = value
}
i++
featureNames = append(featureNames, feature.FeatureName)
}
// 遍历所有的特征维度
i = 1 // i表示遍历到第i个特征维度
for _, feature := range sourceDataSet.OriginalFeatures {
// 遍历每个特征维度的每个样本
for key, value := range feature.Sets {
originalTrainSet[key][i] = value
}
i++
}
dataSet := &common.TrainDataSet{
FeatureNames: featureNames, // 特征名称的集合
TrainSet: trainSet, // 特征集合
XbarParams: sourceDataSet.XbarParams, // 特征的均值
SigmaParams: sourceDataSet.SigmaParams, // 特征的标准差
OriginalTrainSet: originalTrainSet, // 原始特征集合
}
return dataSet
}
// CalLocalGradAndCostTagPart 标签方为计算本地模型中,每个特征的参数做准备,计算本地同态加密结果
// 对每一条数据(ID编号j),计算y - 0.5,(y - 0.5)*preValB,preValB^2/8,preValB/4,并对它们分别使用公钥pubKey-B进行同态加密
// 注意:高性能的同态运算仅能处理整数,对于浮点数有精度损失,所以必须在参数中指定精度来进行处理
//
// - thetas 上一轮训练得到的模型参数
// - trainSet 预处理过的训练数据
// - accuracy 同态加解密精确到小数点后的位数
// - regMode 正则模式
// - regParam 正则参数
// - publicKey 标签方同态公钥
func CalLocalGradAndCostTagPart(thetas []float64, trainSet [][]float64, accuracy int, regMode int, regParam float64, publicKey *paillier.PublicKey) (*LocalGradAndCostPart, error) {
// 对每一条数据(ID编号),计算y - 0.5
rawPart1 := make(map[int]*big.Int)
// 对每一条数据(ID编号),计算(y - 0.5)*preValB
rawPart2 := make(map[int]*big.Int)
// 对每一条数据(ID编号),计算preValB^2/8
rawPart3 := make(map[int]*big.Int)
// 对每一条数据(ID编号),计算preValB/4
rawPart4 := make(map[int]*big.Int)
// 对每一条数据(ID编号),计算0.5 + preValB/4 - y
rawPart5 := make(map[int]*big.Int)
// 对每一条数据(ID编号),计算y - 0.5,并使用公钥pubKey-B进行同态加密
encPart1 := make(map[int]*big.Int)
// 对每一条数据(ID编号),计算(y - 0.5)*preValB,并使用公钥pubKey-B进行同态加密
encPart2 := make(map[int]*big.Int)
// 对每一条数据(ID编号),计算preValB^2/8,并使用公钥pubKey-B进行同态加密
encPart3 := make(map[int]*big.Int)
// 对每一条数据(ID编号),计算preValB/4,并使用公钥pubKey-B进行同态加密
encPart4 := make(map[int]*big.Int)
// 对每一条数据(ID编号),计算0.5 + preValB/4 - y,并使用公钥pubKey-B进行同态加密
encPart5 := make(map[int]*big.Int)
// 遍历样本的每一行
for i := 0; i < len(trainSet); i++ {
id, predictValue := predict(thetas, trainSet[i])
// 计算y - 0.5
rawPart1Value := trainSet[i][len(trainSet[i])-1] - 0.5
// 精度处理转int后,才可以使用同态加密和同态运算
rawPart1ValueInt := big.NewInt(int64(math.Round(rawPart1Value * math.Pow(10, float64(accuracy)))))
rawPart1[id] = rawPart1ValueInt
// encByB(y - 0.5)
// 使用同态公钥加密数据
encPart1Value, err := publicKey.EncryptSupNegNum(rawPart1ValueInt)
if err != nil {
log.Printf("Paillier Encrypt err is %v", err)
return nil, err
}
encPart1[id] = encPart1Value
// 计算(y - 0.5)*preValB
rawPart2Value := rawPart1Value * predictValue
// 精度处理转int后,才可以使用同态加密和同态运算
rawPart2ValueInt := big.NewInt(int64(math.Round(rawPart2Value * math.Pow(10, float64(accuracy)))))
rawPart2[id] = rawPart2ValueInt
// encByB((y - 0.5)*preValB)
// 使用同态公钥加密数据
encPart2Value, err := publicKey.EncryptSupNegNum(rawPart2ValueInt)
if err != nil {
log.Printf("Paillier Encrypt err is %v", err)
return nil, err
}
encPart2[id] = encPart2Value
// 计算preValB^2/8
rawPart3Value := math.Pow(predictValue, 2) / 8
// 精度处理转int后,才可以使用同态加密和同态运算
rawPart3ValueInt := big.NewInt(int64(math.Round(rawPart3Value * math.Pow(10, float64(accuracy)))))
rawPart3[id] = rawPart3ValueInt
// encByB(preValB^2/8)
// 使用同态公钥加密数据
encPart3Value, err := publicKey.EncryptSupNegNum(rawPart3ValueInt)
if err != nil {
log.Printf("Paillier Encrypt err is %v", err)
return nil, err
}
encPart3[id] = encPart3Value
// 计算preValB/4
rawPart4Value := predictValue / 4
// 精度处理转int后,才可以使用同态加密和同态运算
rawPart4ValueInt := big.NewInt(int64(math.Round(rawPart4Value * math.Pow(10, float64(accuracy)))))
rawPart4[id] = rawPart4ValueInt
// encByB(preValB/4)
// 使用同态公钥加密数据
encPart4Value, err := publicKey.EncryptSupNegNum(rawPart4ValueInt)
if err != nil {
log.Printf("Paillier Encrypt err is %v", err)
return nil, err
}
encPart4[id] = encPart4Value
// 计算0.5 + preValB/4 - y
rawPart5Value := 0.5 + predictValue*0.25 - trainSet[i][len(trainSet[i])-1]
// 精度处理转int后,才可以使用同态加密和同态运算
rawPart5ValueInt := big.NewInt(int64(math.Round(rawPart5Value * math.Pow(10, float64(accuracy)))))
rawPart5[id] = rawPart5ValueInt
// encByB(0.5 + preValB/4 - y)
// 使用同态公钥加密数据
encPart5Value, err := publicKey.EncryptSupNegNum(rawPart5ValueInt)
encPart5[id] = encPart5Value
}
regCost := 0.0
switch regMode {
case common.RegLasso:
regCost = CalLassoRegCost(thetas, len(trainSet), regParam)
case common.RegRidge:
regCost = CalRidgeRegCost(thetas, len(trainSet), regParam)
default:
}
// 精度处理转int后,才可以使用同态加密和同态运算
rawRegCost := big.NewInt(int64(math.Round(regCost * math.Pow(10, float64(accuracy)))))
// 使用同态公钥加密数据
encRegCost, err := publicKey.EncryptSupNegNum(rawRegCost)
if err != nil {
log.Printf("Paillier Encrypt err is %v", err)
return nil, err
}
// 生成标签方的中间原始参数,用于计算梯度和损失
rawPart := &RawLocalGradAndCostPart{
RawPart1: rawPart1,
RawPart2: rawPart2,
RawPart3: rawPart3,
RawPart4: rawPart4,
RawPart5: rawPart5,
RawRegCost: rawRegCost,
}
// 生成标签方的中间同态加密参数,用于计算梯度和损失
encPart := &EncLocalGradAndCostPart{
EncPart1: encPart1,
EncPart2: encPart2,
EncPart3: encPart3,
EncPart4: encPart4,
EncPart5: encPart5,
EncRegCost: encRegCost,
}
// 生成标签方的中间同态加密参数,用于计算梯度和损失
localGradAndCostTagPart := &LocalGradAndCostPart{
RawPart: rawPart,
EncPart: encPart,
}
return localGradAndCostTagPart, nil
}
// CalLocalGradAndCostPart 非标签方为计算本地模型中,每个特征的参数做准备,计算本地同态加密结果
// 对于梯度:A计算preValA/4,再用自己的同态公钥加密数据,获得encByA(preValA/4),将加密数据发送给B
// 对于损失:A计算preValA、preValA^2/8,再用自己的同态公钥加密数据,获得encByA(preValA)、encByA(preValA^2/8),将加密数据发送给B
//
// - thetas 上一轮训练得到的模型参数
// - trainSet 预处理过的训练数据
// - accuracy 同态加解密精确到小数点后的位数
// - regMode 正则模式
// - regParam 正则参数
// - publicKey 非标签方同态公钥
func CalLocalGradAndCostPart(thetas []float64, trainSet [][]float64, accuracy int, regMode int, regParam float64, publicKey *paillier.PublicKey) (*LocalGradAndCostPart, error) {
// 对每一条数据(ID编号),计preValA
rawPart1 := make(map[int]*big.Int)
// 对每一条数据(ID编号),计算preValA^2/8
rawPart2 := make(map[int]*big.Int)
// 对每一条数据(ID编号),计算preValA/4
// 对每一条数据(ID编号),计preValA,并使用公钥pubKey-A进行同态加密
encPart1 := make(map[int]*big.Int)
// 对每一条数据(ID编号),计算preValA^2/8,并使用公钥pubKey-A进行同态加密
encPart2 := make(map[int]*big.Int)
// 对每一条数据(ID编号),计算preValA/4,并使用公钥pubKey-A进行同态加密
// 遍历样本的每一行
for i := 0; i < len(trainSet); i++ {
id, predictValue := predictNoTag(thetas, trainSet[i])
// 精度处理转int后,才可以使用同态加密和同态运算,放大1个精度
predictValueInt := big.NewInt(int64(math.Round(predictValue * math.Pow(10, float64(accuracy)))))
// 使用同态公钥加密数据
encPredictValue, err := publicKey.EncryptSupNegNum(predictValueInt)
if err != nil {
log.Printf("Paillier Encrypt err is %v", err)
return nil, err
}
// 计算preValA^2/8,放大1个精度
predictValue2 := math.Pow(predictValue, 2) / 8
predictValue2Int := big.NewInt(int64(math.Round(predictValue2 * math.Pow(10, float64(accuracy)))))
// 使用同态公钥加密数据
encPredictValue2, err := publicKey.EncryptSupNegNum(predictValue2Int)
if err != nil {
log.Printf("Paillier Encrypt err is %v", err)
return nil, err
}
rawPart1[id] = predictValueInt
rawPart2[id] = predictValue2Int
encPart1[id] = encPredictValue
encPart2[id] = encPredictValue2
}
regCost := 0.0
switch regMode {
case common.RegLasso:
regCost = CalLassoRegCost(thetas, len(trainSet), regParam)
case common.RegRidge:
regCost = CalRidgeRegCost(thetas, len(trainSet), regParam)
default:
}
// 精度处理转int后,才可以使用同态加密和同态运算
rawRegCost := big.NewInt(int64(math.Round(regCost * math.Pow(10, float64(accuracy)))))
// 使用同态公钥加密数据
encRegCost, err := publicKey.EncryptSupNegNum(rawRegCost)
if err != nil {
log.Printf("Paillier Encrypt err is %v", err)
return nil, err
}
// 生成非标签方的中间原始参数,用于计算梯度和损失
rawPart := &RawLocalGradAndCostPart{
RawPart1: rawPart1,
RawPart2: rawPart2,
RawRegCost: rawRegCost,
}
// 生成非标签方的中间同态加密参数,用于计算梯度和损失
encPart := &EncLocalGradAndCostPart{
EncPart1: encPart1,
EncPart2: encPart2,
EncRegCost: encRegCost,
}
// 生成费标签方的中间同态加密参数,用于计算梯度和损失
localGradAndCostPart := &LocalGradAndCostPart{
RawPart: rawPart,
EncPart: encPart,
}
return localGradAndCostPart, nil
}
// CalLassoRegCost 计算使用L1 Lasso进行正则化后的损失函数,来评估当前模型的损失
// 定义总特征数量n,总样本数量m,正则项系数λ(用来权衡正则项与原始损失函数项的比重)
// L1 = λ/m * (|θ(0)| + |θ(1)| + ... + |θ(n)|),其中,|θ|表示θ的绝对值
//
// - thetas 当前的模型参数
// - trainSetSize 训练样本个数
// - regParam 正则参数
func CalLassoRegCost(thetas []float64, trainSetSize int, regParam float64) float64 {
lassoRegCost := 0.0
// 遍历特征的每一行
for i := 0; i < len(thetas); i++ {
thetasCost := math.Abs(thetas[i])
lassoRegCost += thetasCost
}
lassoRegCost = regParam * lassoRegCost / float64(trainSetSize)
return lassoRegCost
}
// CalRidgeRegCost 计算使用L2 Ridge进行正则化后的损失函数,来评估当前模型的损失
// 定义总特征数量n,总样本数量m,正则项系数λ(用来权衡正则项与原始损失函数项的比重)
// L2 = λ/2m * (θ(0)^2 + θ(1)^2 + ... + θ(n)^2)
//
// - thetas 当前的模型参数
// - trainSetSize 训练样本个数
// - regParam 正则参数
func CalRidgeRegCost(thetas []float64, trainSetSize int, regParam float64) float64 {
ridgeRegCost := 0.0
// 遍历特征的每一行
for i := 0; i < len(thetas); i++ {
thetasCost := math.Pow(thetas[i], 2)
ridgeRegCost += thetasCost
}
ridgeRegCost = regParam * ridgeRegCost / (2 * float64(trainSetSize))
return ridgeRegCost
}
// CalEncLocalGradient 非标签方聚合双方的中间加密参数,为本地特征计算模型参数
// 计算本地加密梯度,并提交随机数干扰
// 参与方A执行同态运算
// 梯度的计算:Grad(i) = (predictValue(j) - realValue(j))*trainSet[j][i]
// = (0.5 + x/4 - y)*x(i) = (0.5 + (preValA + preValB)/4 - y)*x(i)
// = (0.5 + preValA/4 + (preValB/4 - y))*x(i)
// = x(i)*preValA/4 + x(i)*(0.5 + preValB/4 - y)
//
// - localPart 非标签方本地的明文梯度数据
// - tagPart 标签方的加密梯度数据
// - trainSet 非标签方训练样本集合
// - featureIndex 指定特征的索引
// - accuracy 同态加解密精度
// - publicKey 标签方同态公钥
func CalEncLocalGradient(localPart *RawLocalGradAndCostPart, tagPart *EncLocalGradAndCostPart, trainSet [][]float64, featureIndex, accuracy int, publicKey *paillier.PublicKey) (*common.EncLocalGradient, error) {
encGradMap := make(map[int]*big.Int)
// 生成 RanNumA,用于梯度值的混淆
randomBytes, err := rand.GenerateSeedWithStrengthAndKeyLen(rand.KeyStrengthHard, rand.KeyLengthInt64)
if err != nil {
return nil, err
}
ranNum := big.NewInt(0).SetBytes(randomBytes)
// 遍历样本的每一行
for i := 0; i < len(trainSet); i++ {
// 获取该行数据的id
// TODO: 后续优化下数据结构,来提升性能
id := int(math.Floor(trainSet[i][0] + 0.5))
// 计算x(i)/4*scale精度
scaleFactor := big.NewInt(int64(math.Round(trainSet[i][featureIndex+1] * 0.25 * math.Pow(10, float64(accuracy)))))
// 计算x(i)*preValA/4,1个精度的明文*scale精度
rawValue1 := new(big.Int).Mul(localPart.RawPart1[id], scaleFactor)
// 计算x(i)*scale精度
scaleFactor = big.NewInt(int64(math.Round(trainSet[i][featureIndex+1] * math.Pow(10, float64(accuracy)))))
// 计算x(i)*encByB(0.5 + preValB/4 - y),1个精度的密文*scale精度
encValue2 := publicKey.CypherPlainMultiply(tagPart.EncPart5[id], scaleFactor)
// 计算 x(i)*preValA/4 + x(i)*encByB(0.5 + preValB/4 - y) + ranNumA
// 密文与原文的同态加法
addResult := publicKey.CypherPlainsAdd(encValue2, rawValue1, ranNum)
encGradMap[id] = addResult
}
encLocalGradient := &common.EncLocalGradient{
EncGrad: encGradMap,
RandomNoise: ranNum,
}
return encLocalGradient, nil
}
// CalEncLocalGradientTagPart 标签方聚合双方的中间加密参数,为本地特征计算模型参数
// 计算本地加密梯度,并提交随机数干扰
// 参与方B计算加密梯度信息
// 梯度的计算:Grad(i) = (predictValue(j) - realValue(j))*trainSet[j][i]
// = (0.5 + x/4 - y)*x(i) = (0.5 + (preValA + preValB)/4 - y)*x(i)
// = (0.5 + preValA/4 + (preValB/4 - y))*x(i)
// = x(i)*preValA/4 + x(i)*(0.5 + preValB/4 - y)
//
// - localPart 标签方本地的明文梯度数据
// - otherPart 非标签方的加密梯度数据
// - trainSet 标签方训练样本集合
// - featureIndex 指定特征的索引
// - accuracy 同态加解密精度
// - publicKey 非标签方同态公钥
func CalEncLocalGradientTagPart(tagPart *RawLocalGradAndCostPart, otherPart *EncLocalGradAndCostPart, trainSet [][]float64, featureIndex, accuracy int, publicKey *paillier.PublicKey) (*common.EncLocalGradient, error) {
encGradMap := make(map[int]*big.Int)
// 生成 RanNumB,用于梯度值的混淆
randomBytes, err := rand.GenerateSeedWithStrengthAndKeyLen(rand.KeyStrengthHard, rand.KeyLengthInt64)
if err != nil {
return nil, err
}
ranNum := big.NewInt(0).SetBytes(randomBytes)
// 遍历样本的每一行
for i := 0; i < len(trainSet); i++ {
// 获取该行数据的id
// TODO: 后续优化下数据结构,来提升性能
id := int(math.Floor(trainSet[i][0] + 0.5))
// 计算x(i)/4*scale精度
scaleFactor := big.NewInt(int64(math.Round(trainSet[i][featureIndex+1] * 0.25 * math.Pow(10, float64(accuracy)))))
// 计算x(i)*encByA(preValA)/4,1个精度的密文*scale精度
encValue1 := publicKey.CypherPlainMultiply(otherPart.EncPart1[id], scaleFactor)
// 计算x(i)*scale精度
scaleFactor = big.NewInt(int64(math.Round(trainSet[i][featureIndex+1] * math.Pow(10, float64(accuracy)))))
// 计算x(i)*(0.5 + preValB/4 - y),1个精度的密文*scale精度
rawValue2 := new(big.Int).Mul(tagPart.RawPart5[id], scaleFactor)
// 计算 x(i)*encByA(preValA)/4 + x(i)*(0.5 + preValB/4 - y) + ranNumB
// 密文与原文的同态加法
addResult := publicKey.CypherPlainsAdd(encValue1, rawValue2, ranNum)
encGradMap[id] = addResult
}
encLocalGradient := &common.EncLocalGradient{
EncGrad: encGradMap,
RandomNoise: ranNum,
}
return encLocalGradient, nil
}
// DecryptGradient 为另一参与方解密加密的梯度
// - encGradMap 加密的梯度信息
// - privateKey 己方同态私钥
func DecryptGradient(encGradMap map[int]*big.Int, privateKey *paillier.PrivateKey) map[int]*big.Int {
// 解密后的梯度信息
gradMap := make(map[int]*big.Int)
for id, encGrad := range encGradMap {
rawGrad := privateKey.DecryptSupNegNum(encGrad)
gradMap[id] = rawGrad
}
return gradMap
}
// RetrieveRealGradient 从解密后的梯度信息中,移除随机数噪音,还原己方真实的梯度数据
// - decGradMap 解密的梯度信息
// - accuracy 同态加解密精度
// - randomInt 己方梯度的噪音值
func RetrieveRealGradient(decGradMap map[int]*big.Int, accuracy int, randomInt *big.Int) map[int]float64 {
// 解密后的梯度信息(含随机数噪声)
gradMap := make(map[int]float64)
for id, decGrad := range decGradMap {
minusRandomInt := new(big.Int).Mul(big.NewInt(-1), randomInt)
rawGrad := new(big.Int).Add(decGrad, minusRandomInt)
rawGradStr := rawGrad.String()
rawGradFloat64, _ := strconv.ParseFloat(rawGradStr, 64)
rawGradFloat64 = rawGradFloat64 / math.Pow(10, float64(accuracy)*2)
gradMap[id] = rawGradFloat64
}
return gradMap
}
// CalGradient 根据还原的明文梯度数据计算梯度值
func CalGradient(gradMap map[int]float64) float64 {
var decGradSum float64 = 0
for _, decGrad := range gradMap {
decGradSum += decGrad
}
gradient := decGradSum / float64(len(gradMap))
return gradient
}
// CalGradientWithLassoReg 使用L1正则(Lasso)计算梯度
// 定义总特征数量n,总样本数量m,正则项系数λ(用来权衡正则项与原始损失函数项的比重)
// Grad_new(i) = (Grad_new(i) + λ*sgn(θ(i)))/m
// 其中,trainSet[j][i] 表示第j个样本的的第i个特征的值
func CalGradientWithLassoReg(thetas []float64, gradMap map[int]float64, featureIndex int, regParam float64) float64 {
gradient := CalGradient(gradMap)
// get sgn(θ(i)
sgnTheta := 0.0
switch {
case thetas[featureIndex] > 0:
sgnTheta = 1
case thetas[featureIndex] < 0:
sgnTheta = -1
default: // θ(i)=0
sgnTheta = 0
}
// λ*sgn(θ(i)))/m
lassoReg := regParam * sgnTheta / float64(len(gradMap))
gradientWithLassoReg := gradient + lassoReg
return gradientWithLassoReg
}
// CalGradientWithRidgeReg 使用L2正则(Ridge)计算梯度
// 定义总特征数量n,总样本数量m,正则项系数λ(用来权衡正则项与原始损失函数项的比重)
// Grad_new(i) = (Grad_new(i) + λ*θ(i))/m
// 其中,trainSet[j][i] 表示第j个样本的的第i个特征的值
func CalGradientWithRidgeReg(thetas []float64, gradMap map[int]float64, featureIndex int, regParam float64) float64 {
gradient := CalGradient(gradMap)
// λ*θ(i))/m
ridgeReg := regParam * thetas[featureIndex] / float64(len(gradMap))
gradientWithRidgeReg := gradient + ridgeReg
return gradientWithRidgeReg
}
// EvaluateEncLocalCost 非标签方根据损失函数来评估当前模型的损失,衡量模型是否已经收敛
// TODO 增加泛化支持:
// L1 = λ/m * (|θ(0)| + |θ(1)| + ... + |θ(n)|),其中,|θ|表示θ的绝对值
// L2 = λ/2m * (θ(0)^2 + θ(1)^2 + ... + θ(n)^2)
//
// 参与方A执行同态运算ln(0.5) + encByB(y - 0.5)*preValA + encByB((y - 0.5)*preValB) - preValA^2/8
// - encByB(preValB^2/8) - preValA*encByB(preValB/4) + ranNumA
//
// - localPart 本地的明文损失数据
// - tagPart 标签方的加密损失数据
// - trainSet 非标签方训练样本集合
// - accuracy 同态加解密精度
// - publicKey 标签方同态公钥
func EvaluateEncLocalCost(localPart *RawLocalGradAndCostPart, tagPart *EncLocalGradAndCostPart, trainSet [][]float64, accuracy int, publicKey *paillier.PublicKey) (*common.EncLocalCost, error) {
costSum := make(map[int]*big.Int)
// 生成 RanNumA,用于损失值的混淆
randomBytes, err := rand.GenerateSeedWithStrengthAndKeyLen(rand.KeyStrengthHard, rand.KeyLengthInt64)
if err != nil {
return nil, err
}
ranNum := big.NewInt(0).SetBytes(randomBytes)
// 计算ln(0.5)
lnHalf := math.Log(0.5)
// 2个精度的明文
lnHalfValueInt := big.NewInt(int64(math.Round(lnHalf * math.Pow(10, 2*float64(accuracy)))))
// 遍历样本的每一行
for i := 0; i < len(trainSet); i++ {
// 获取该行数据的id
// TODO: 后续优化下数据结构,来提升性能
id := int(math.Floor(trainSet[i][0] + 0.5))
// 计算encByB(y - 0.5)*preValA,2个精度的密文
encValue1 := publicKey.CypherPlainMultiply(tagPart.EncPart1[id], localPart.RawPart1[id])
// 计算encByB((y - 0.5)*preValB),1个精度的密文*scale精度
scaleFactor := big.NewInt(int64(math.Round(math.Pow(10, float64(accuracy)))))
encValue2 := publicKey.CypherPlainMultiply(tagPart.EncPart2[id], scaleFactor)
// 计算preValA^2/8,1个精度的原文*scale精度
rawValue3 := new(big.Int).Mul(localPart.RawPart2[id], scaleFactor)
// 计算-preValA^2/8
rawValue3 = new(big.Int).Mul(rawValue3, big.NewInt(-1))
// 计算encByB(preValB^2/8),1个精度的密文*scale精度
encValue4 := publicKey.CypherPlainMultiply(tagPart.EncPart3[id], scaleFactor)
// 计算-encByB(preValB^2/8)
encValue4 = publicKey.CypherPlainMultiply(encValue4, big.NewInt(-1))
// 计算preValA*encByB(preValB/4),2个精度的密文
encValue5 := publicKey.CypherPlainMultiply(tagPart.EncPart4[id], localPart.RawPart1[id])
// 计算-preValA*encByB(preValB/4)
encValue5 = publicKey.CypherPlainMultiply(encValue5, big.NewInt(-1))
// 计算 ln(0.5) + encByB(y - 0.5)*preValA + encByB((y - 0.5)*preValB) - preValA^2/8
// - encByB(preValB^2/8) - preValA*encByB(preValB/4) + ranNumA
// 密文同态加法
addResult := publicKey.CyphersAdd(encValue1, encValue2, encValue4, encValue5)
// 密文与原文的同态加法
addResult = publicKey.CypherPlainsAdd(addResult, lnHalfValueInt, rawValue3, ranNum)
costSum[id] = addResult
}
encLocalCost := &common.EncLocalCost{
EncCost: costSum,
RandomNoise: ranNum,
}
return encLocalCost, nil
}
// EvaluateEncLocalCostTag 标签方使用同态运算,根据损失函数来计算当前模型的加密损失
// TODO 增加泛化支持:
// 参与方B执行同态运算encCostForB = ln(0.5) + (y - 0.5)*encByA(preValA) + (y - 0.5)*preValB - encByA(preValA^2/8)
// - preValB^2/8 - encByA(preValA)*preValB/4 + ranNumB
//
// - localPart 本地的明文损失数据
// - otherPart 非标签方的加密损失数据
// - trainSet 标签方训练样本集合
// - accuracy 同态加解密精度
// - publicKey 非标签方同态公钥
func EvaluateEncLocalCostTag(localPart *RawLocalGradAndCostPart, otherPart *EncLocalGradAndCostPart, trainSet [][]float64, accuracy int, publicKey *paillier.PublicKey) (*common.EncLocalCost, error) {
costSum := make(map[int]*big.Int)
// 生成 RanNumB,用于损失值的混淆
randomBytes, err := rand.GenerateSeedWithStrengthAndKeyLen(rand.KeyStrengthHard, rand.KeyLengthInt64)
if err != nil {
return nil, err
}
ranNum := big.NewInt(0).SetBytes(randomBytes)
// 计算ln(0.5)
lnHalf := math.Log(0.5)
// 2个精度的明文
lnHalfValueInt := big.NewInt(int64(math.Round(lnHalf * math.Pow(10, 2*float64(accuracy)))))
// 遍历样本的每一行
for i := 0; i < len(trainSet); i++ {
// 获取该行数据的id
// TODO: 后续优化下数据结构,来提升性能
id := int(math.Floor(trainSet[i][0] + 0.5))
// 计算(y - 0.5)*encByA(preValA),2个精度的密文
encValue1 := publicKey.CypherPlainMultiply(otherPart.EncPart1[id], localPart.RawPart1[id])
// 计算(y - 0.5)*preValB,1个精度的原文*scale精度
scaleFactor := big.NewInt(int64(math.Round(math.Pow(10, float64(accuracy)))))
rawValue2 := new(big.Int).Mul(localPart.RawPart2[id], scaleFactor)
// 计算encByA(preValA^2/8),1个精度的密文*scale精度
encValue3 := publicKey.CypherPlainMultiply(otherPart.EncPart2[id], scaleFactor)
// 计算-encByA(preValA^2/8)
encValue3 = publicKey.CypherPlainMultiply(encValue3, big.NewInt(-1))
// 计算preValB^2/8,1个精度的密文*scale精度
rawValue4 := new(big.Int).Mul(localPart.RawPart3[id], scaleFactor)
// 计算 -preValB^2/8
rawValue4 = new(big.Int).Mul(rawValue4, big.NewInt(-1))
// 计算encByA(preValA)*preValB/4,2个精度的密文
encValue5 := publicKey.CypherPlainMultiply(otherPart.EncPart1[id], localPart.RawPart4[id])
// 计算-encByA(preValA)*preValB/4
encValue5 = publicKey.CypherPlainMultiply(encValue5, big.NewInt(-1))
// 计算 ln(0.5) + (y - 0.5)*encByA(preValA) + (y - 0.5)*preValB - encByA(preValA^2/8)
// - preValB^2/8 - encByA(preValA)*preValB/4 + ranNumB
// 密文同态加法
addResult := publicKey.CyphersAdd(encValue1, encValue3, encValue5)
// 密文与原文的同态加法
addResult = publicKey.CypherPlainsAdd(addResult, lnHalfValueInt, rawValue2, rawValue4, ranNum)
costSum[id] = addResult
}
encLocalCost := &common.EncLocalCost{
EncCost: costSum,
RandomNoise: ranNum,
}
return encLocalCost, nil
}
// DecryptCost 为其他方解密带噪音的损失
// - encCostMap 加密的损失信息
// - privateKey 己方同态私钥
func DecryptCost(encCostMap map[int]*big.Int, privateKey *paillier.PrivateKey) map[int]*big.Int {
// 解密后的梯度信息
costMap := make(map[int]*big.Int)
for id, encCost := range encCostMap {
rawCost := privateKey.DecryptSupNegNum(encCost)
costMap[id] = rawCost
}
return costMap
}
// RetrieveRealCost 从解密后的梯度信息中,移除随机数噪音,恢复真实损失
// - decCostMap 解密的损失信息
// - accuracy 同态加解密精度
// - randomInt 损失的噪音值
func RetrieveRealCost(decCostMap map[int]*big.Int, accuracy int, randomInt *big.Int) map[int]float64 {
// 解密后的梯度信息(含随机数噪声)
costMap := make(map[int]float64)
for id, decCost := range decCostMap {
minusRandomInt := new(big.Int).Mul(big.NewInt(-1), randomInt)
rawCost := new(big.Int).Add(decCost, minusRandomInt)
rawCostStr := rawCost.String()
rawCostFloat64, _ := strconv.ParseFloat(rawCostStr, 64)
rawCostFloat64 = rawCostFloat64 / math.Pow(10, 2*float64(accuracy))
costMap[id] = rawCostFloat64
}
return costMap
}
// CalCost 根据还原的损失信息计算损失值
func CalCost(costMap map[int]float64) float64 {
var decCostSum float64 = 0
for _, decCost := range costMap {
decCostSum += decCost
}
cost := decCostSum / (-1 * float64(len(costMap)))
return cost
}
// predict 标签方用训练得到的模型对样本做预测计算
// thetas example: const, feature1_theta, feature2_theta
// sample example: id, 1, feature1, feature2...
func predict(thetas []float64, sample []float64) (int, float64) {
var predictValue = thetas[0]
for i := 1; i < len(thetas); i++ {
predictValue += thetas[i] * sample[i+1]
}
// TODO: 后续优化下数据结构,来提升性能
id := int(math.Floor(sample[0] + 0.5))
return id, predictValue
}
// predictNoTag 非标签方用训练得到的模型对样本做预测计算
// thetas example: feature1_theta, feature2_theta
// sample example: id, feature1, feature2
func predictNoTag(thetas []float64, sample []float64) (int, float64) {
var predictValue = 0.0
for i := 0; i < len(thetas); i++ {
predictValue += thetas[i] * sample[i+1]
}
// TODO: 后续优化下数据结构,来提升性能
id := int(math.Floor(sample[0] + 0.5))
return id, predictValue
}
// PredictLocalPartNoTag 非标签方使用经过标准化处理的本地数据进行预测
// - thetas feature_name->feature_theta
// - standardizedInput feature_name->value
func PredictLocalPartNoTag(thetas, standardizedInput map[string]float64) float64 {
var predictValue = 0.0
for key, _ := range thetas {
predictValue += thetas[key] * standardizedInput[key]
}
return predictValue
}
// PredictLocalPartTag 标签方使用经过标准化处理的本地数据进行预测
// - thetas feature_name->feature_theta,包含"Intercept"
// - standardizedInput feature_name->value
func PredictLocalPartTag(thetas, standardizedInput map[string]float64) float64 {
var predictValue = thetas["Intercept"]
for key, _ := range standardizedInput {
predictValue += thetas[key] * standardizedInput[key]
}
return predictValue
}
// StandardizeLocalInput 各参与方使用之前训练集合的标准化参数对本地的要进行预测的数据进行标准化处理
// - xbars feature_name->样本均值
// - sigmas feature_name->样本标准差
// - input feature_name->样本值
func StandardizeLocalInput(xbars, sigmas, input map[string]float64) map[string]float64 {
standardizedInput := make(map[string]float64)
for key, _ := range input {
standardizedInput[key] = (input[key] - xbars[key]) / sigmas[key]
}
return standardizedInput
}
|
danielgarm/C-Bash-Projects
|
Shared/Tests/3hilo.c
|
#define MAX_BUF 3
#define PROD 1000
sem_t elementos;
sem_t huecos;
int buffer[MAX_BUF];
int cons, prod = 0;
void main(void){
pthread_t th1, th2, th3;
sem_init(&elementos, 0, 0);
sem_init(&huecos, 0, MAX_buffer);
sem_init(&elementos, 0, 0);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.