repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
lagerdata/unit-test_templates
|
cc3235sf/ti_sdk/simplelink_cc32xx_sdk_4_10_00_07/source/ti/net/mqtt/server/server_core.h
|
/*
* Copyright (C) 2016-2018, Texas Instruments Incorporated
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Texas Instruments Incorporated nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**@file server_core.h
The MQTT server daemon, a task, provisions the high level abstractions for the
smart applications. This is an intelligent layer that utilizes the services
of the MQTT Server Packet Library and is responsible for the functions of the
topic management, the client management and support of multiple server
applications.
The light-weight server enables the services of the MQTT protocol for an
application to either extend and / or control the existing functions to suit
the deployment specific scenario. These applications in practice are the
plug-ins / add-ons to the core server functionalities. Specifically,
these applications, among others capabilities, can be used for analyzing and
approving the credentials of the remote clients, acting as a bridge between
a MQTT external client and the server, and a snooper to learn about all the
data transactions to / from the server.
The server is targeted to conform to MQTT 3.1.1 specification.
The services of the server are multi-task safe. Platform specific atomicity
constructs are used, through abstractions, by the server to maintain data
coherency and synchronization.
The server offers the following compile line configurable parameters (-D opt)
- <b> CFG_SR_MAX_MQP_TX_LEN: </b> the constant buffer length allocated for a TX.
\n\n
- <b> CFG_SR_MAX_SUBTOP_LEN: </b> the maximum buffer size to hold a sub-topic.
For e.g., in the topic /x/y/z, the phrase /x, /y and z are sub-topics.
\n\n
- <b> CFG_SR_MAX_TOPIC_NODE: </b> the maximum number of topic nodes in server.
For e.g., in the topic /x/y/z, there are three nodes (/x, /y and z).
\n\n
- <b> CFG_SR_MAX_CL_ID_SIZE: </b> the maximum length of the client-id string.
\n\n
- <b> CFG_SR_MAX_NUM_CLIENT: </b> the maximum number of clients to be managed.
Note this is different from the maximum number of 'contexts'. A large number
of clients can be managed using fewer number of 'contexts' (connections).
\n\n
@note Any future extensions & development must follow the following guidelines.
A new API or an extension to the existing API
a) must be rudimentary
b) must not imply a rule or policy (including a state machine)
b) must ensure simple design and implementation
*/
#ifndef ti_net_mqtt_server_MQTTServerCore__include
#define ti_net_mqtt_server_MQTTServerCore__include
#include "server_pkts.h"
#ifdef __cplusplus
extern "C" {
#endif
/** @defgroup server_daemon The Server Daemon API(s)
@{
*/
typedef struct _MQTTServerCore_AppCBs_t_
{
/** Connection request from remote client - assess credentials.
This routine presents, to the application, the information about the
credentials of the remote client that is trying to establish a MQTT
connection with the server. The application shall utilize these data
in conjunction with its policy to either allow or deny connection to
the server.
Should the application choose to allow the remote client to establish
a MQTT connection, then it must provide in 'app-user' (place-holder),
a handle that refers to the user of this connection. The server will
provide this handle in follow-up routines to enable the application
to refer to the associated connection in its implementation.
@param[in] clientID UTF8 based ID of the remote client - is set to
NULL to indicate a zero-length client id.
@param[in] userName UTF8 based user-name provided by the remote
client. It is set to NULL if the client did not provide an user name
@param[in] password UTF8 based pass-word provided by the remote
client. It is set to NULL if the client did not provide a pass-word
@param[out] appUsr place-holder for application to provide a handle
to the user of this specific connection / client.
@return 16bit value for the variable header in the CONNACK message.
The MSB in the return value refers to the 8bit parameter of the
acknowledge flags and must be set 0. The LSB in the return value
refers to the 8bit 'return code' parameter in the CONNACK message
and must be set accordingly.
*/
uint16_t (*connect)(const MQTT_UTF8String_t *clientID,
const MQTT_UTF8String_t *userName,
const MQTT_UTF8String_t *password,
void **appUsr);
/** Indicate a PUBLISH message from the network.
This routine presents, to the application, the topic and the related
data along with other qualifiers published by one of the clients
associated with this server. The application must enroll with the
server the particular topic for which the data should be notified.
@param[in] topic UTF8 topic Name for which data has been published
@param[in] dataBuf the published binary data for the topic
@param[in] dataLen the length of the binary data
@param[in] dup is this a duplicate data from remote client?
@param[in] qos quality of service of the message / data
@param[in] retain should the server retain the data?
@return none
*/
void (*publish)(const MQTT_UTF8String_t *topic,
const uint8_t *payload, uint32_t payLen,
bool dup, uint8_t qos, bool retain);
/** Notify disconnection to the remote client.
This routine is invoked by the server to declare to the application
to a particular client has been terminated and follow-up, if needed,
can now commence. This routine aids the application by indicating if
an error condition had caused the disconnection.
@param[in] appUsr handle to refer to the user of the connection in
the application
@param[in] due2err has the connection been closed due to an error?
@return none
*/
void (*disconn)(const void *appUsr, bool due2err);
}MQTTServerCore_AppCBs_t;
/** Configuration for the applications that utilize the MQTT Server Daemon.
At the moment this configuration is not used and has been incorporated
to support forward compatibility (future use)
*/
typedef struct _MQTTServerCore_AppCfg_t_
{
void *placeHolder; /**< Dummy, not used as of now */
}MQTTServerCore_AppCfg_t;
//*****************************************************************************
// function prototypes
//*****************************************************************************
/** Enroll with server to receive data for a topic
This routine registers with the server, the specified topic for which the
application should receive any published data from the network. Whenever,
any of the remote clients that are connected to the server or applications,
this or other, publishes data for the specified topic, the server will
present the published information to this application.
As part of the enrollment, the application should provide the maxmimum QoS
with which the server should provide the published data. If the topic data
received by the server bears a QoS higher than the one specified by the
application, the server shall lower it to the QoS level preferred by the
application. Otherwise, the QoS of the data shall be presented 'as-is'. In
other words, the application should expect a published data with a lower QoS.
@param[in] app_hnd handle to the application context in the server. This
handle is provided by server @ref MQTTServerCore_appRegister()
@param[in] topic UTF8 based string for which the application needs to start
getting the published data
@param[in] qos the maximum QoS the application intends to receive data for
this particular topic
@return 0 on success, otherwise a negative value on error.
*/
int32_t MQTTServerCore_topicEnroll(const void *app_hnd,
const MQTT_UTF8String_t *topic, MQTT_QOS qos);
/** Cancel previous enrollment to receive data for a topic
This routines terminates the previous registration, if any, made by the
application to receive any published data for the specified topic. Once,
the enrollment is removed, the application, there after, will not receive
any data for this topic from the server.
@param[in] app_hnd handle to the application context in the server. This
handle is provided by server @ref MQTTServerCore_appRegister()
@param[in] topic UTF8 based string for which the application needs to stop
getting the published data
@return 0 on success, otherwise a negative value on error.
*/
int32_t MQTTServerCore_topicDisenroll(const void *app_hnd,
const MQTT_UTF8String_t *topic);
/** Send data to network for a topic
This routine offers the binary data along-with associated properties for a
specific topic to the server. The server, based on the subscriptions from the
remote clients and the enrollments made by the local applications for this
topic, will send the binary data and its qualifiers, adjusted for the maximum
subscribed or enrolled QoS, to the remote clients and the local applications.
@param[in] topic UTF8 topic Name for which data has been published
@param[in] dataBuf the published binary data for the topic
@param[in] dataLen the length of the binary data
@param[in] qos quality of service of the message / data
@param[in] retain should the server retain the data?
@return on success, the length of data sent, otherwise -1 on error.
*/
int32_t MQTTServerCore_pubSend(const MQTT_UTF8String_t *topic,
const uint8_t *dataBuf, uint32_t dataLen,
MQTT_QOS qos, bool retain);
/** Register an application with the server.
This routine makes known to the server about an application identified by
its name and creates a context / reference for the application in the
server.
An application intending to utilize the services of the MQTT server must be
first registered with the server.
@param[in] cbs callback routines from the application to be invoked by the
server
@param[in] name refers to the name of the application. The application must
retain the memory used by the 'name' after the function call. The server
does not copy the name into its internal buffers.
@return a valid handle to context of application in the server, othewise
NULL on error
*/
void *MQTTServerCore_appRegister(const MQTTServerCore_AppCBs_t *cbs,
const char *name);
/** Initialize the MQTT Server (Task / Daemon).
This routine initializes the server implementation and sets it up using
the provided configuration. The server implementation must be initialized
prior to invoking of any other routine or service.
This routine should be invoked as part of the platform initialization.
@note This routine must be invoked only once in an run of the system. This
routine internally invokes the @ref MQTTServerPkts_libInit( ) and therefore,
there is no need to invoke the @ref MQTTServerPkts_libInit( ) explicitly.
The server needs to be in a state to listen to incoming MQTT connection
requests. Therefore, the platform sequence after provisioning the buffer
using the API @ref MQTTServerPkts_registerNetSvc, must invoke the API @ref
MQTTServerPkts_run, in an infinite loop, to keep the server daemon active.
@param[in] libCfg configuration information for the MQTT server packet
library.
@param[in] appCfg configuration information for the server applications.
@return 0 on success, otherwise -1 on error
*/
int32_t MQTTServerCore_init(const MQTTServerPkts_LibCfg_t *libCfg,
const MQTTServerCore_AppCfg_t *appCfg);
void MQTTServerCore_topicNodeExit(void);
/** @} */ /* End of server_daemon */
#ifdef __cplusplus
}
#endif
#endif
|
nattyco/fermatold
|
fermat-api/src/main/java/com/bitdubai/fermat_api/layer/all_definition/license/LicenseSubsystem.java
|
package com.bitdubai.fermat_api.layer.all_definition.license;
import com.bitdubai.fermat_api.Addon;
/**
* Created by ciencias on 21.01.15.
*/
public interface LicenseSubsystem {
public void start () throws CantStartSubsystemException;
public Addon getAddon();
}
|
starao520/sign-set-admin
|
ams-tools/src/main/java/com/aisino/entity/QiniuContent.java
|
<reponame>starao520/sign-set-admin
package com.aisino.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.IdType;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.EqualsAndHashCode;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import java.io.Serializable;
import java.util.Date;
/**
* @author rxx
* @date 2020-09-27
*/
@Getter
@Setter
@NoArgsConstructor
@EqualsAndHashCode(callSuper = false)
@TableName("tool_qiniu_content")
public class QiniuContent implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "ID")
@TableId(value = "content_id", type= IdType.AUTO)
private Long id;
@ApiModelProperty(value = "Bucket 识别符")
private String bucket;
@ApiModelProperty(value = "文件名称")
@TableField(value = "name")
private String name;
@ApiModelProperty(value = "真实名称")
@TableField(value = "real_name")
private String realName;
@ApiModelProperty(value = "文件大小")
private String size;
@ApiModelProperty(value = "文件类型:私有或公开")
private String type = "公开";
@ApiModelProperty(value = "文件url")
private String url;
@ApiModelProperty(value = "文件后缀")
private String suffix;
@ApiModelProperty(value = "上传者ID")
@TableField(value = "create_user_id")
private Long createUserId;
@ApiModelProperty(value = "点赞次数")
@TableField(value = "praise_count")
private Long praiseCount;
@ApiModelProperty(value = "收藏次数")
@TableField(value = "collect_count")
private Long collectCount;
@ApiModelProperty(value = "作用域(1.书签 2.头像)")
private String scope;
@ApiModelProperty(value = "上传或同步的时间")
@TableField(fill= FieldFill.INSERT_UPDATE)
private Date createTime;
public void copyFrom(QiniuContent source){
BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
}
}
|
ktrzeciaknubisa/jxcore-binary-packaging
|
deps/mozjs/src/jsweakcache.h
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=8 sts=4 et sw=4 tw=99:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef jsweakcache_h
#define jsweakcache_h
#include "jscntxt.h"
#include "gc/Marking.h"
#include "js/HashTable.h"
#include "vm/Runtime.h"
namespace js {
// A WeakCache is used to map a key to a value similar to an HashMap except
// that its entries are garbage collected. An entry is kept as long as
// both the key and value are marked.
//
// No mark function is provided with this weak container. However, this weak
// container should take part in the sweep phase.
template <class Key, class Value,
class HashPolicy = DefaultHasher<Key>,
class AllocPolicy = RuntimeAllocPolicy>
class WeakCache : public HashMap<Key, Value, HashPolicy, AllocPolicy> {
private:
typedef HashMap<Key, Value, HashPolicy, AllocPolicy> Base;
typedef typename Base::Range Range;
typedef typename Base::Enum Enum;
public:
explicit WeakCache(JSRuntime *rt) : Base(rt) { }
explicit WeakCache(JSContext *cx) : Base(cx->runtime()) { }
public:
// Sweep all entries which have unmarked key or value.
void sweep(FreeOp *fop) {
// Remove all entries whose keys/values remain unmarked.
for (Enum e(*this); !e.empty(); e.popFront()) {
// Checking IsMarked() may update the location of the Key (or Value).
// Pass in a stack local, then manually update the backing heap store.
Key k(e.front().key);
bool isKeyDying = gc::IsAboutToBeFinalized(&k);
if (isKeyDying || gc::IsAboutToBeFinalized(e.front().value)) {
e.removeFront();
} else {
// Potentially update the location of the Key.
// The Value had its heap addresses correctly passed to IsMarked(),
// and therefore has already been updated if necessary.
// e.rekeyFront(k);
}
}
#if DEBUG
// Once we've swept, all remaining edges should stay within the
// known-live part of the graph.
for (Range r = Base::all(); !r.empty(); r.popFront()) {
Key k(r.front().key);
JS_ASSERT(!gc::IsAboutToBeFinalized(&k));
JS_ASSERT(!gc::IsAboutToBeFinalized(r.front().value));
// Assert that IsMarked() did not perform relocation.
JS_ASSERT(k == r.front().key);
}
#endif
}
};
// A WeakValueCache is similar to a WeakCache, except keys are never marked.
// This is useful for weak maps where the keys are primitive values such as uint32_t.
template <class Key, class Value,
class HashPolicy = DefaultHasher<Key>,
class AllocPolicy = RuntimeAllocPolicy>
class WeakValueCache : public HashMap<Key, Value, HashPolicy, AllocPolicy>
{
public:
typedef HashMap<Key, Value, HashPolicy, AllocPolicy> Base;
typedef typename Base::Range Range;
typedef typename Base::Enum Enum;
explicit WeakValueCache(JSRuntime *rt) : Base(rt) { }
explicit WeakValueCache(JSContext *cx) : Base(cx->runtime()) { }
public:
// Sweep all entries which have unmarked key or value.
void sweep(FreeOp *fop) {
// Remove all entries whose values remain unmarked.
for (Enum e(*this); !e.empty(); e.popFront()) {
if (gc::IsAboutToBeFinalized(e.front().value()))
e.removeFront();
}
#if DEBUG
// Once we've swept, all remaining edges should stay within the
// known-live part of the graph.
for (Range r = Base::all(); !r.empty(); r.popFront())
JS_ASSERT(!gc::IsAboutToBeFinalized(r.front().value()));
#endif
}
};
} // namespace js
#endif /* jsweakcache_h */
|
yuuki0xff/goapptrace
|
tracer/logger/retrysender.go
|
<reponame>yuuki0xff/goapptrace
package logger
import (
"log"
"time"
"github.com/yuuki0xff/goapptrace/tracer/types"
)
// RetrySender is automatically retry to all operations.
type RetrySender struct {
Sender Sender
MaxRetry int
RetryInterval time.Duration
}
func (s *RetrySender) Open() error {
return s.retry("Open", s.Sender.Open)
}
func (s *RetrySender) Close() error {
return s.retry("Close", s.Sender.Close)
}
func (s *RetrySender) SendSymbols(data *types.SymbolsData) error {
return s.retrySend("SendSymbols", func() error {
// try to send
return s.Sender.SendSymbols(data)
})
}
// SendLog sends a RawFuncLog.
// if occur the any error, retry to send after re-open.
func (s *RetrySender) SendLog(raw *types.RawFuncLog) error {
return s.retrySend("SendLog", func() error {
return s.Sender.SendLog(raw)
})
}
// retry is automatically retry until reached to retry limit or fn() is succeed.
func (s *RetrySender) retry(funcName string, fn func() error) error {
var err error
for i := 0; i < s.maxRetry(); i++ {
err = fn()
if err == nil {
return nil
}
log.Printf("failed to Sender.%s() on RetrySender.%s(): %s", funcName, funcName, err)
s.sleep(i)
}
return err
}
// retrySend is automatically retry until reached to retry limit or send() is succeed.
// When send() is not succeed, it will reopen the sender.
func (s *RetrySender) retrySend(funcName string, send func() error) error {
var senderr error
for i := 0; i < s.maxRetry(); i++ {
senderr = send()
if senderr == nil {
return nil
}
log.Printf("failed to RetrySender.%s(): %s", funcName, senderr)
// try to close.
// if occurs any error, we print of logging message.
closeerr := s.Close()
if closeerr != nil {
log.Printf("failed to Sender.Close() on RetrySender.%s(): %s", funcName, closeerr)
}
// try to re-open.
openerr := s.Open()
if openerr != nil {
log.Panicf("failed to Sender.Open() on RetrySender.%s(): %s", funcName, openerr)
return openerr
}
s.sleep(i)
}
return senderr
}
func (s *RetrySender) maxRetry() int {
if s.MaxRetry < 0 {
log.Panicf("invalid MaxRetry: %d >= 0", s.MaxRetry)
}
if s.MaxRetry == 0 {
return defaultMaxRetry
}
return s.MaxRetry
}
func (s *RetrySender) sleep(retryCount int) time.Duration {
if s.RetryInterval < 0 {
log.Panicf("invalid RetryInterval: %d >= 0", s.MaxRetry)
}
if s.RetryInterval == 0 {
return defaultRetryInterval
}
return s.RetryInterval
}
|
legioner9/Node_Way_source_2
|
Store/myNpm/st_doc1/nodejs.org_DOCS.v.2/Console/_/#TSH/Copy_learn/JavaScript/3-prompt.js
|
<filename>Store/myNpm/st_doc1/nodejs.org_DOCS.v.2/Console/_/#TSH/Copy_learn/JavaScript/3-prompt.js
'use strict';
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
prompt: '> ',
});
rl.prompt();
const commands = {
help() {
console.log('Commands:', Object.keys(commands).join(', '));
},
hello() {
console.log('Hello there!');
},
exit() {
rl.close();
}
};
rl.on('line', line => {
line = line.trim();
const command = commands[line];
if (command) command();
else console.log('Unknown command');
rl.prompt();
}).on('close', () => {
console.log('Bye!');
process.exit(0);
});
|
biemo8/bbs-cloud
|
app-biz/biemo-bbs/biemo-bbs-api/src/main/java/com/biemo/cloud/bbs/api/BArticleApi.java
|
<filename>app-biz/biemo-bbs/biemo-bbs-api/src/main/java/com/biemo/cloud/bbs/api/BArticleApi.java
package com.biemo.cloud.bbs.api;
import com.biemo.cloud.bbs.api.vo.BArticleVo;
import com.biemo.cloud.kernel.model.response.ResponseData;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
@FeignClient(value = "biemo-bbs-app",contextId = "BArticleApi")
public interface BArticleApi {
@RequestMapping(value = "/{id}",method = RequestMethod.GET)
ResponseData detail(@PathVariable("id") Long id);
@GetMapping("/articles")
ResponseData articles();
@GetMapping("/nearly/{id}")
ResponseData nearly(@PathVariable("id") Long id);
@GetMapping("/related/{id}")
ResponseData related(@PathVariable("id") Long id);
@RequestMapping("/favorite/{id}")
ResponseData userFavorite(@PathVariable("id") Long id);
@RequestMapping("/tag/articles")
ResponseData tagArticles(Long tagId);
@GetMapping("/user/articles")
ResponseData userArticles(BArticleVo bArticle);
@PostMapping("/create")
ResponseData articleCreate(@RequestParam(value = "id",required = false) Long id,String captchaId,String captchaCode ,String title,String content,String tags) throws Exception;
@RequestMapping("/edit/{id}")
public ResponseData editArticle(@PathVariable("id") Long id);
}
|
gdumond/apim-cli
|
modules/apis/src/test/java/com/axway/apim/changeAction/ChangeTestAction.java
|
package com.axway.apim.changeAction;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.axway.apim.APIExportApp;
import com.axway.apim.lib.CoreParameters;
import com.axway.apim.lib.CoreParameters.Mode;
import com.consol.citrus.actions.AbstractTestAction;
import com.consol.citrus.context.TestContext;
import com.consol.citrus.exceptions.CitrusRuntimeException;
import com.consol.citrus.exceptions.ValidationException;
public class ChangeTestAction extends AbstractTestAction {
private static Logger LOG = LoggerFactory.getLogger(ChangeTestAction.class);
File testDir = null;
@Override
public void doExecute(TestContext context) {
String stage = null;
boolean useEnvironmentOnly = false;
try {
stage = context.getVariable("stage");
} catch (CitrusRuntimeException ignore) {};
LOG.info("API-Manager import is using user: '"+context.replaceDynamicContentInString("${oadminUsername1}")+"'");
int expectedReturnCode = 0;
try {
expectedReturnCode = Integer.parseInt(context.getVariable("expectedReturnCode"));
} catch (Exception ignore) {};
try {
useEnvironmentOnly = Boolean.parseBoolean(context.getVariable("useEnvironmentOnly"));
} catch (Exception ignore) {};
boolean enforce = false;
boolean ignoreQuotas = false;
boolean ignoreAdminAccount = false;
boolean ignoreCache = false;
String allowOrgAdminsToPublish = "true";
boolean changeOrganization = false;
String clientOrgsMode = null;
String clientAppsMode = null;
String quotaMode = null;
String newBackend = null;
String oldBackend = null;
String name = null;
try {
enforce = Boolean.parseBoolean(context.getVariable("enforce"));
} catch (Exception ignore) {};
try {
ignoreQuotas = Boolean.parseBoolean(context.getVariable("ignoreQuotas"));
} catch (Exception ignore) {};
try {
quotaMode = context.getVariable("quotaMode");
} catch (Exception ignore) {};
try {
clientOrgsMode = context.getVariable("clientOrgsMode");
} catch (Exception ignore) {};
try {
clientAppsMode = context.getVariable("clientAppsMode");
} catch (Exception ignore) {};
try {
ignoreAdminAccount = Boolean.parseBoolean(context.getVariable("ignoreAdminAccount"));
} catch (Exception ignore) {};
try {
allowOrgAdminsToPublish = context.getVariable("allowOrgAdminsToPublish");
} catch (Exception ignore) {};
try {
changeOrganization = Boolean.parseBoolean(context.getVariable("changeOrganization"));
} catch (Exception ignore) {};
try {
ignoreCache = Boolean.parseBoolean(context.getVariable("ignoreCache"));
} catch (Exception ignore) {};
try {
name = context.getVariable("name");
} catch (Exception ignore) {};
try {
newBackend = context.getVariable("newBackend");
} catch (Exception ignore) {};
try {
oldBackend = context.getVariable("oldBackend");
} catch (Exception ignore) {};
if(stage==null) {
stage = "NOT_SET";
}
List<String> args = new ArrayList<String>();
if(useEnvironmentOnly) {
args.add("-s");
args.add(stage);
} else {
args.add("-h");
args.add(context.replaceDynamicContentInString("${apiManagerHost}"));
args.add("-u");
args.add(context.replaceDynamicContentInString("${oadminUsername1}"));
args.add("-p");
args.add(context.replaceDynamicContentInString("${oadminPassword1}"));
args.add("-s");
args.add(stage);
if(quotaMode!=null) {
args.add("-quotaMode");
args.add(quotaMode);
}
if(clientOrgsMode!=null) {
args.add("-clientOrgsMode");
args.add(clientOrgsMode);
}
if(clientAppsMode!=null) {
args.add("-clientAppsMode");
args.add(clientAppsMode);
}
args.add("-allowOrgAdminsToPublish");
args.add(allowOrgAdminsToPublish);
if(newBackend!=null) {
args.add("-newBackend");
args.add(newBackend);
}
if(name!=null) {
args.add("-name");
args.add(name);
}
if(oldBackend!=null) {
args.add("-oldBackend");
args.add(oldBackend);
}
if(changeOrganization) args.add("-changeOrganization");
if(enforce) args.add("-force");
if(ignoreQuotas) args.add("-ignoreQuotas");
if(ignoreCache) args.add("-ignoreCache");
if(ignoreAdminAccount) args.add("-ignoreAdminAccount");
}
LOG.info(args.toString());
int rc = APIExportApp.change(args.toArray(new String[args.size()]));
if(expectedReturnCode!=rc) {
throw new ValidationException("Expected RC was: " + expectedReturnCode + " but got: " + rc);
}
}
}
|
DavidSlayback/rlpyt
|
rlpyt/envs/bsuiteenv/bsuite_env.py
|
import bsuite
from dm_env import specs
from bsuite.utils.wrappers import RewardNoise, RewardScale
from rlpyt.envs.base import Env, EnvStep, EnvInfo
from rlpyt.spaces.int_box import IntBox
from rlpyt.spaces.float_box import FloatBox
from rlpyt.utils.logging.context import LOG_DIR, osp # Base log directory
VALID_ENV_SWEEP_IDS = bsuite.sweep.SWEEP
VALID_ENV_IDS = list(bsuite.bsuite.EXPERIMENT_NAME_TO_ENVIRONMENT.keys())
"""
Environments: Bandit, Cartpole, Cartpole Swingup, Catch, deep_sea, discounting_chain, memory_len, memory_size, mnist, mountain_car, umbrella. All 10k episodes
- Bandit: 11 actions/arms, linspace of rewards 0-1 (determined by mapping_seed). Mapping seed applied before "seed" from wrappers
- Cartpole: Basic cartpole (keep pole balanced), lots of parameters, but wouldn't touch anything except seed
- CartpoleSwingup: As above, but pole begins downward, must be swung upward to see reward. Agent pays "move_cost" on action. Only touch seed.
- Catch: Agent catches balls falling from in columnsxrows (10x5) grid. Obs are binary grid (1 for ball, paddle; 0 otherwise). rows, columns, seed. Episode ends on missing or catching ball
- DeepSea: sizexsize grid, deterministic=False for 1/N chance of 'right' action failure. At each state, one action is 'left', one 'right' (randomized across states by mapping_seed). Action always results in agent dropping one row. Far right corner is reward
obs is size*size grid, but with 1 where agent is. Rewards are move_cost and taking right action at rightmost column. seed for nondeterministic
- DiscountingChain: Observation is two pixels: (context, time_to_live). Context will only be -1 in the first step, then equal to the action selected in
the first step. For all future decisions the agent is in a "chain" for that action. Reward of +1 come at one of: 1, 3, 10, 30, 100
However, depending on the seed, one of these chains has a 10% bonus. mapping_seed
- MemoryChain: Obs is (context, ttl). Context is 0 except at first step ( +-1 bitstring). seed. memory_length for length of episode. num_bits for size of "context"
- MNISTBandit: fraction is set of training set to keep. seed for index of image. +1 for correct label, -1 for wrong (10 labels). Terminates episode
- MountainCar: max_steps (1000 default) and seed (for position). -1 per timestep
- UmbrellaChain: obs is (need_umbrella, have_umbrella, ttl, n_distractor...). Only first action (pickup or not) matters. chain_length is length of episode, n_distractor is size of distractors, seed
Noise (bandit, cartpole, catch, mnist, mountain_car): Wrap environment with RewardNoise wrapper. noise_scale is stddev of gaussian on reward. Also takes "seed"
Scale (bandit, cartpole, catch, mnist, mountain_car): Wrap environment with RewardScale wrapper. reward_scale is factor by which reward is multiplied
Auto reset
"""
class BSuiteEnv(Env):
""" DeepMind bsuite environment in rlpyt-compatible format
Args:
id: Id of bsuite environment (str). Must be listed in bsuite.sweep.SWEEP
exp_kwargs: Experiment kwargs for bsuite (dict or None). If None, id must be sweep id. Else, must be valud args for specified environment
external_logging: Type of bsuite logging to use (str). bsuite has logging methods built into its environments,
either 'sqlite' or 'csv'. Defaults to 'none' (use rlpyt logging). Only applies to SWEEP IDs
save_path: Path to save data too (on top of base rlpyt data directory) (str).
overrite: Overwrite
"""
def __init__(self,
id: str,
exp_kwargs: dict = None,
external_logging: str = 'none',
save_path: str = '',
overwrite: bool = True):
assert (id in VALID_ENV_SWEEP_IDS) or (id in VALID_ENV_IDS and exp_kwargs is not None) # Either using one of presets or using base experiment with other settings
aug_path = osp.join(LOG_DIR, save_path) # LOG_DIR + save_path
if id in VALID_ENV_SWEEP_IDS: # Pre-parameterized experiments
if external_logging == 'none':
env = bsuite.load_from_id(id) # No recording
else:
env = bsuite.load_and_record(id, aug_path, external_logging, overwrite=overwrite) # Record in sql or csv. same sql for each id
self.num_episodes = env.bsuite_num_episodes
else:
noise_scale = exp_kwargs.pop('noise_scale', 0.)
noise_scale_seed = exp_kwargs.pop('noise_scale_seed', 0.)
reward_scale = exp_kwargs.pop('reward_scale', 0.)
env = bsuite.load(id, **exp_kwargs)
if noise_scale: env = RewardNoise(env, noise_scale, noise_scale_seed)
if reward_scale: env = RewardScale(env, reward_scale)
self.num_episodes = 1e4 # Default
self.env = env
self._action_space = IntBox(low=0, high=self.env.action_spec().num_values)
o_spec = self.env.observation_spec()
if isinstance(o_spec, specs.BoundedArray):
self._observation_space = FloatBox(low=o_spec.minimum.item(),
high=o_spec.maximum.item(),
shape=o_spec.shape,
dtype=o_spec.dtype)
else:
self._observation_space = FloatBox(low=-float('inf'),
high=float('inf'),
shape=o_spec.shape,
dtype=o_spec.dtype)
self._last_observation = None
self.game_over = False,
self.viewer = None
def reset(self):
self.game_over = False
timestep = self.env.reset()
self._last_observation = timestep.observation
return timestep.observation
def step(self, action):
timestep = self.env.step(action)
self._last_observation = timestep.observation
reward = timestep.reward or 0.
if timestep.last():
self.game_over = True
return EnvStep(timestep.observation, reward, timestep.last(), EnvInfo())
def render(self, mode: str = 'rgb_array'):
if self._last_observation is None:
raise ValueError('Environment not ready to render. Call reset() first.')
if mode == 'rgb_array':
return self._last_observation
if mode == 'human':
if self.viewer is None:
# pylint: disable=import-outside-toplevel
# pylint: disable=g-import-not-at-top
from gym.envs.classic_control import rendering
self.viewer = rendering.SimpleImageViewer()
self.viewer.imshow(self._last_observation)
return self.viewer.isopen
if __name__ == "__main__":
for env in VALID_ENV_SWEEP_IDS:
test = BSuiteEnv(env)
testo = test.reset()
print(test.observation_space.shape)
test = BSuiteEnv('bandit/0')
testo = test.reset()
testa = test.step(test.action_space.sample())
|
pakpoomton/CellmodellerShadow
|
html/namespace_cell_modeller_1_1_integration_1_1_c_l_euler_integrator.js
|
<gh_stars>0
var namespace_cell_modeller_1_1_integration_1_1_c_l_euler_integrator =
[
[ "CLEulerIntegrator", "class_cell_modeller_1_1_integration_1_1_c_l_euler_integrator_1_1_c_l_euler_integrator.html", "class_cell_modeller_1_1_integration_1_1_c_l_euler_integrator_1_1_c_l_euler_integrator" ]
];
|
phoolhbti/mi17
|
rpgm/rpgm/src/main/java/org/yarlithub/yschool/web/setting/settingsGradesDivisionsBean.java
|
package org.yarlithub.yschool.web.setting;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import javax.faces.bean.ManagedBean;
/**
* Created with IntelliJ IDEA.
* User: Pirinthapan
* Date: 4/8/14
* Time: 11:17 PM
* To change this template use File | Settings | File Templates.
*/
@ManagedBean
@Scope(value = "session")
@Controller
public class settingsGradesDivisionsBean {
private boolean gradeEditMode = false;
private boolean divisionEditMode = false;
private String gradeDescription = "Grade 6";
private String divisionDescription = "Division A";
private boolean gradeUnEditMode = true;
private boolean divisionUnEditMode = true;
private String grade = "6";
private String division = "A";
private boolean gradeEditMode1 = false;
private boolean divisionEditMode1 = false;
private String gradeDescription1 = "Grade 7";
private String divisionDescription1 = "Division B";
private boolean gradeUnEditMode1 = true;
private boolean divisionUnEditMode1 = true;
private String grade1 = "7";
private String division1 = "B";
public String getGradeDescription() {
return gradeDescription;
}
public void setGradeDescription(String gradeDescription) {
this.gradeDescription = gradeDescription;
}
public String getDivisionDescription() {
return divisionDescription;
}
public void setDivisionDescription(String divisionDescription) {
this.divisionDescription = divisionDescription;
}
public boolean isDivisionEditMode() {
return divisionEditMode;
}
public void setDivisionEditMode(boolean divisionEditMode) {
this.divisionEditMode = divisionEditMode;
}
public boolean isDivisionUnEditMode() {
return divisionUnEditMode;
}
public void setDivisionUnEditMode(boolean divisionUnEditMode) {
this.divisionUnEditMode = divisionUnEditMode;
}
public String getDivision() {
return division;
}
public void setDivision(String division) {
this.division = division;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public settingsGradesDivisionsBean(){
gradeUnEditMode = true;
gradeEditMode = false;
}
public boolean isGradeEditMode() {
return gradeEditMode;
}
public void setGradeEditMode(boolean gradeEditMode) {
this.gradeEditMode = gradeEditMode;
}
public boolean isGradeUnEditMode() {
return gradeUnEditMode;
}
public void setGradeUnEditMode(boolean gradeUnEditMode) {
this.gradeUnEditMode = gradeUnEditMode;
}
public void gradeChangeToEditMode(){
gradeEditMode = true;
gradeUnEditMode = false;
}
public void gradeCompleteEditMode(){
gradeEditMode = false;
gradeUnEditMode = true;
}
public void gradeCancelEditMode(){
gradeEditMode = false;
gradeUnEditMode = true;
}
public void gradeDeleteEditMode(){
gradeEditMode = false;
gradeUnEditMode = true;
}
public void divisionChangeToEditMode(){
divisionEditMode = true;
divisionUnEditMode = false;
}
public void divisionCompleteEditMode(){
divisionEditMode = false;
divisionUnEditMode = true;
}
public void divisionCancelEditMode(){
divisionEditMode = false;
divisionUnEditMode = true;
}
public void divisionDeleteEditMode(){
divisionEditMode = false;
divisionUnEditMode = true;
}
public void gradeChangeToEditMode1(){
gradeEditMode1 = true;
gradeUnEditMode1 = false;
}
public void gradeCompleteEditMode1(){
gradeEditMode1 = false;
gradeUnEditMode1 = true;
}
public void gradeCancelEditMode1(){
gradeEditMode1 = false;
gradeUnEditMode1 = true;
}
public void gradeDeleteEditMode1(){
gradeEditMode1 = false;
gradeUnEditMode1 = true;
}
public void divisionChangeToEditMode1(){
divisionEditMode1 = true;
divisionUnEditMode1 = false;
}
public void divisionCompleteEditMode1(){
divisionEditMode1 = false;
divisionUnEditMode1 = true;
}
public void divisionCancelEditMode1(){
divisionEditMode1 = false;
divisionUnEditMode1 = true;
}
public void divisionDeleteEditMode1(){
divisionEditMode1 = false;
divisionUnEditMode1 = true;
}
public boolean isGradeEditMode1() {
return gradeEditMode1;
}
public void setGradeEditMode1(boolean gradeEditMode1) {
this.gradeEditMode1 = gradeEditMode1;
}
public boolean isDivisionEditMode1() {
return divisionEditMode1;
}
public void setDivisionEditMode1(boolean divisionEditMode1) {
this.divisionEditMode1 = divisionEditMode1;
}
public String getGradeDescription1() {
return gradeDescription1;
}
public void setGradeDescription1(String gradeDescription1) {
this.gradeDescription1 = gradeDescription1;
}
public String getDivisionDescription1() {
return divisionDescription1;
}
public void setDivisionDescription1(String divisionDescription1) {
this.divisionDescription1 = divisionDescription1;
}
public boolean isGradeUnEditMode1() {
return gradeUnEditMode1;
}
public void setGradeUnEditMode1(boolean gradeUnEditMode1) {
this.gradeUnEditMode1 = gradeUnEditMode1;
}
public boolean isDivisionUnEditMode1() {
return divisionUnEditMode1;
}
public void setDivisionUnEditMode1(boolean divisionUnEditMode1) {
this.divisionUnEditMode1 = divisionUnEditMode1;
}
public String getGrade1() {
return grade1;
}
public void setGrade1(String grade1) {
this.grade1 = grade1;
}
public String getDivision1() {
return division1;
}
public void setDivision1(String division1) {
this.division1 = division1;
}
}
|
latotty/meteor-sweeper
|
.storybook/config.js
|
<reponame>latotty/meteor-sweeper
import React from 'react';
import { configure, addDecorator } from '@kadira/storybook';
import { withKnobs } from '@kadira/storybook-addon-knobs';
import { setStubbingMode } from 'react-komposer';
import { ThemeProvider } from 'styled-components';
import { MemoryRouter } from 'react-router'
import Alert from 'react-s-alert';
// Enable react-komposer stubbing.
setStubbingMode(true);
import theme from '../imports/ui/components/themes/default';
import './main.scss';
import 'react-s-alert/dist/s-alert-default.css';
import 'react-s-alert/dist/s-alert-css-effects/slide.css';
const req = require.context('../imports/ui', true, /.stories.js$/);
function loadStories() {
req.keys().forEach(filename => req(filename));
};
addDecorator(withKnobs);
addDecorator(story => (
<div>
<MemoryRouter>
<ThemeProvider theme={theme}>
{story()}
</ThemeProvider>
</MemoryRouter>
<Alert stack={{ limit: 3 }} />
</div>
));
configure(loadStories, module);
|
Colbys/smartactors-core
|
CoreFeatures/Database-in-memory-plugins/PluginInMemoryDatabase/src/main/java/info/smart_tools/smartactors/database_in_memory_plugins/in_memory_database_plugin/PluginInMemoryDatabase.java
|
package info.smart_tools.smartactors.database_in_memory_plugins.in_memory_database_plugin;
import info.smart_tools.smartactors.feature_loading_system.bootstrap_item.BootstrapItem;
import info.smart_tools.smartactors.base.interfaces.iaction.exception.ActionExecuteException;
import info.smart_tools.smartactors.feature_loading_system.interfaces.ibootstrap.IBootstrap;
import info.smart_tools.smartactors.feature_loading_system.interfaces.ibootstrap_item.IBootstrapItem;
import info.smart_tools.smartactors.database_in_memory.in_memory_database.InMemoryDatabaseIOCInitializer;
import info.smart_tools.smartactors.base.exception.invalid_argument_exception.InvalidArgumentException;
import info.smart_tools.smartactors.feature_loading_system.interfaces.iplugin.IPlugin;
import info.smart_tools.smartactors.feature_loading_system.interfaces.iplugin.exception.PluginException;
/**
* Plugin for in memory database
*/
public class PluginInMemoryDatabase implements IPlugin {
private final IBootstrap<IBootstrapItem<String>> bootstrap;
/**
* Constructor
*
* @param bootstrap bootstrap element
*/
public PluginInMemoryDatabase(final IBootstrap<IBootstrapItem<String>> bootstrap) {
this.bootstrap = bootstrap;
}
@Override
public void load() throws PluginException {
try {
BootstrapItem item = new BootstrapItem("InMemoryDatabase");
item
// .after("IOC")
// .after("IFieldNamePlugin")
.process(() -> {
try {
InMemoryDatabaseIOCInitializer.init();
} catch (Exception e) {
throw new ActionExecuteException("Failed to load plugin \"NestedFieldName\"", e);
}
}
);
bootstrap.add(item);
} catch (InvalidArgumentException e) {
throw new PluginException(e);
}
}
}
|
mensfeld/rhodes
|
neon/Helium/HeliumForWindows/Implementation/Plugins/PB_DeviceApplication_PLG/HourglassModule.h
|
/**
* \file HourglassModule.h
* \brief Hourglass Plug-in module interface.
* File to house the CHourglassModule class and all related includes / defines
* to interface between Browser core and the Hourglass functionality.
* The Hourglass will be shown automatically during page navigates and also
* when told to. The Hourglass will not be shown if the request originates from
* a module which does not have focus.
*/
#pragma once
#include "../../common/Public/PBPlugin.h"
#include "HourglassAnimation.h"
/**
* Class to define the interface between the core and the CHourglassAnimation
* functionality.
* Inherits from PBModule to align with the Plug-in design. Actions meta tags
* to perform the appropriate Hourglass behaviour.
*/
class CHourglassModule: public PBModule
{
public:
/**
* This Function is inherited from PBModule::onInit.
* Please see that function for further definition.
* Copies the Module name into the Module and registers for OnAppFocus
* events.
*/
BOOL onInit(PPBSTRUCT pPBStructure);
/**
* This Function is inherited from PBModule::onDeInit.
* Please see that function for further definition.
* Deregisters for OnAppFocus events.
*/
void onDeInit(PPBSTRUCT pPBStructure);
/**
* This Function is inherited from PBModule::onAttachInstance.
* Please see that function for further definition.
* Creates instance data for the new Object. Stores a reference to
* the instance data in the pInstStruct, associating it with the newly
* created instance.
*/
BOOL onAttachInstance(PPBSTRUCT pPBStructure, PPBINSTSTRUCT pInstStruct);
/**
* This Function is inherited from PBModule::onReleaseInstance.
* Please see that function for further definition.
* Deletes the instance data associated with the instance being
* released.
*/
BOOL onReleaseInstance(PPBSTRUCT pPBStructure, PPBINSTSTRUCT pInstStruct);
/**
* This Function is inherited from PBModule::onAppFocus.
* Please see that function for further definition.
* Receive change of application focus notifications, inform the old and
* new IDs whether they have lost / gained focus
*/
BOOL onAppFocus(int iOldID, int iNewID);
/**
* This Function is inherited from PBModule::onBeforeNavigate.
* Please see that function for further definition.
* Displays the Hourglass if this application is in the foreground.
*/
BOOL onBeforeNavigate (int iInstID);
/**
* This Function is inherited from PBModule::onDocumentComplete.
* Please see that function for further definition.
* Hides the Hourglass once navigation has completed.
*/
BOOL onDocumentComplete (int iInstID);
/**
* This Function is inherited from PBModule::MetaProc.
* Please see that function for further definition.
* Accepts 'Meta tags' associated with the Hourglass module and actions
* them appropriately.
*/
BOOL MetaProc(PBMetaStruct *pbMetaStructure, PPBSTRUCT pPBStructure, void *pParam);
/**
* Function to retrieve the 'WaitCursorEnabled' configuration setting.
* \param iInstance Application instance to retrieve the setting for
* \param value [out] Value of the configuration setting
* \return Whether or not the value was successfully read from the
* configuration.
*/
bool RetrieveNoWaitConfigValue(int iInstance, BOOL* input);
/**
* Function to retrieve the 'WaitCursorLeft' configuration setting.
* \param iInstance Application instance to retrieve the setting for
* \param value [out] Value of the configuration setting
* \return Whether or not the value was successfully read from the
* configuration.
*/
bool RetrieveHourglassDefaultLeft(int iInstance, DWORD* value);
/**
* Function to retrieve the 'WaitCursorTop' configuration setting.
* \param iInstance Application instance to retrieve the setting for
* \param value [out] Value of the configuration setting
* \return Whether or not the value was successfully read from the
* configuration.
*/
bool RetrieveHourglassDefaultTop(int iInstance, DWORD* value);
/**
* This function is inherited from PBModule::onRhoAppFocus.
* Please see that function for further definition.
*/
BOOL onRhoAppFocus(bool bActivate, int iInstID);
private:
HANDLE m_hWindowInitialisedEvent;
};
|
Danial41/-
|
public_html/plugins/joomlaquiz/truefalse/js/next/truefalse.js
|
case '3': //true-false
if (!jq_Check_selectRadio('quest_choice', 'quest_form'+questions[n].cur_quest_id)) {
try{ ScrollToElement(jq_getObj('quest_div'+questions[n].cur_quest_id));} catch(e) {}
ShowMessage('error_messagebox_quest'+questions[n].cur_quest_id, 1, mes_complete_this_part);
return false;
}
break;
|
alipay/antchain-openapi-prod-sdk
|
yunqing/java/src/main/java/com/antgroup/antchain/openapi/yunqing/models/NodeExecutionLog.java
|
// This file is auto-generated, don't edit it. Thanks.
package com.antgroup.antchain.openapi.yunqing.models;
import com.aliyun.tea.*;
public class NodeExecutionLog extends TeaModel {
// 当前节点的动作
@NameInMap("node_action")
@Validation(required = true)
public String nodeAction;
// 当前节点的执行日志信息
@NameInMap("message")
@Validation(required = true)
public String message;
public static NodeExecutionLog build(java.util.Map<String, ?> map) throws Exception {
NodeExecutionLog self = new NodeExecutionLog();
return TeaModel.build(map, self);
}
public NodeExecutionLog setNodeAction(String nodeAction) {
this.nodeAction = nodeAction;
return this;
}
public String getNodeAction() {
return this.nodeAction;
}
public NodeExecutionLog setMessage(String message) {
this.message = message;
return this;
}
public String getMessage() {
return this.message;
}
}
|
CyberQueenMara/baseband-research
|
okl4_kernel/okl4_2.1.1-patch.9/tools/magpie/test/fullsystem/pistachio/kernel/include/arch/ia64/ar.h
|
/*********************************************************************
*
* Copyright (C) 2002, 2003, Karlsruhe University
*
* File path: arch/ia64/ar.h
* Description: IA64 application registers
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: ar.h,v 1.6.4.1 2003/09/24 19:12:15 skoglund Exp $
*
********************************************************************/
#ifndef __ARCH__IA64__AR_H__
#define __ARCH__IA64__AR_H__
#define FRAME_MARKER(input, local, output) \
(((input + local) << 7) + (input + local + output))
#if !defined(ASSEMBLY)
class ar_pfs_t
{
public:
union {
struct {
word_t sof : 7;
word_t sol : 7;
word_t sor : 4;
word_t rrb_gr : 7;
word_t rrb_fr : 7;
word_t rrb_pr : 6;
word_t __rv1 : 14;
word_t previous_ec : 6;
word_t __rv2 : 4;
word_t previous_priv : 2;
};
u64_t raw;
};
word_t locals (void)
{ return sol; }
word_t outputs (void)
{ return sof - sol; }
word_t framesize (void)
{ return sof; }
};
class ar_fpsr_t
{
public:
union {
struct {
word_t traps_vd : 1;
word_t traps_dd : 1;
word_t traps_zd : 1;
word_t traps_od : 1;
word_t traps_ud : 1;
word_t traps_id : 1;
word_t sf0 : 13;
word_t sf1 : 13;
word_t sf2 : 13;
word_t sf3 : 13;
word_t __rv : 6;
};
u64_t raw;
};
enum ctrl_e {
ftz = (1 << 0),
wre = (1 << 1),
pc_0 = (0 << 2),
pc_1 = (1 << 2),
pc_2 = (2 << 2),
pc_3 = (3 << 2),
rc_zero = (0 << 4),
rc_up = (1 << 4),
rc_down = (2 << 4),
rc_nearest = (2 << 4),
td = (1 << 6)
};
enum flags_e {
v = (1 << 7),
d = (1 << 8),
z = (1 << 9),
o = (1 << 10),
u = (1 << 11),
i = (1 << 12)
};
void enable_all_traps (void)
{
traps_vd = traps_dd = traps_zd = traps_od =
traps_ud = traps_id = 0;
}
void disable_all_traps (void)
{
traps_vd = traps_dd = traps_zd = traps_od =
traps_ud = traps_id = 1;
}
void set_sf0 (word_t sf) { sf0 = sf; }
void set_sf1 (word_t sf) { sf1 = sf; }
void set_sf2 (word_t sf) { sf2 = sf; }
void set_sf3 (word_t sf) { sf3 = sf; }
};
INLINE word_t ar_get_itc (void)
{
word_t itc;
__asm__ __volatile__ ("mov %0 = ar.itc" :"=r" (itc));
return itc;
}
INLINE void ar_set_itc (word_t count)
{
__asm__ __volatile__ ("mov ar.itc = %0" ::"r" (count));
}
#endif /* !ASSEMBLY */
#endif /* !__ARCH__IA64__AR_H__ */
|
fpriyatna/mappingpedia-engine-dataset
|
src/main/scala/es/upm/fi/dia/oeg/mappingpedia/utility/MappingPediaUtility.scala
|
<gh_stars>1-10
package es.upm.fi.dia.oeg.mappingpedia.utility
import java.io._
import java.nio.channels.FileChannel
import java.security.MessageDigest
import java.util.UUID
import es.upm.fi.dia.oeg.mappingpedia.model.result.ListResult
import es.upm.fi.dia.oeg.mappingpedia.model.{Dataset, Distribution, OntologyClass}
import es.upm.fi.dia.oeg.mappingpedia.{MappingPediaConstant, MappingPediaEngine, MappingPediaProperties}
import org.apache.jena.graph.{Node, NodeFactory, Triple}
import org.apache.jena.query.QuerySolution
import org.apache.jena.rdf.model._
import org.apache.jena.util.FileManager
import org.slf4j.{Logger, LoggerFactory}
import org.springframework.web.multipart.MultipartFile
import scala.collection.JavaConversions._
import org.apache.commons.io.FileUtils
import org.apache.jena.ontology.OntClass
import scala.io.Source
/**
* Created by freddy on 10/08/2017.
*/
object MappingPediaUtility {
val logger: Logger = LoggerFactory.getLogger(this.getClass);
/*
def getVirtuosoGraph(virtuosoJDBC : String, virtuosoUser : String, virtuosoPwd : String
, virtuosoGraphName : String) : VirtGraph = {
logger.info("Connecting to Virtuoso Graph...");
logger.info(s"virtuosoGraphName = $virtuosoGraphName");
val virtGraph : VirtGraph = new VirtGraph (
virtuosoGraphName, virtuosoJDBC, virtuosoUser, virtuosoPwd);
logger.info("Connected to Virtuoso Graph...");
return virtGraph;
}
*/
def getFirstPropertyObjectValueLiteral(resource:Resource, property:Property): Literal = {
val it = resource.listProperties(property);
var result: Literal = null;
if(it != null && it.hasNext()) {
val statement = it.next();
val objectNode = statement.getObject();
result = objectNode.asLiteral()
}
return result;
}
def collectBlankNodes(triples:List[Triple]) : Set[Node] = {
val blankNodes:Set[Node] = if(triples.isEmpty) {
Set.empty;
} else {
val blankNodesHead:Set[Node] = this.collectBlankNode(triples.head);
val blankNodesTail:Set[Node] = this.collectBlankNodes(triples.tail);
blankNodesHead ++ blankNodesTail;
}
blankNodes;
}
def collectBlankNode(tp:Triple) : Set[Node] = {
val tpSubject = tp.getSubject;
val tpObject = tp.getObject;
var blankNodes:Set[Node] = Set.empty;
if(tpSubject.isBlank()) {
blankNodes = blankNodes + tpSubject;
}
if(tpObject.isBlank()) {
blankNodes = blankNodes + tpObject;
}
blankNodes;
}
def skolemizeTriples(triples:List[Triple], baseURI:String) : List[Triple] = {
val blankNodes = this.collectBlankNodes(triples);
val mapNewNodes = this.skolemizeBlankNodes(blankNodes, baseURI);
val newTriples = this.replaceBlankNodesInTriples(triples, mapNewNodes);
newTriples;
}
def replaceBlankNodesInTriples(triples:List[Triple], mapNewNodes:Map[Node, Node]) : List[Triple] = {
val newTriples = triples.map(x => {this.replaceBlankNodesInTriple(x, mapNewNodes)});
newTriples;
}
def replaceBlankNodesInTriple(tp:Triple, mapNewNodes:Map[Node, Node]) : Triple = {
val tpSubject = tp.getSubject;
val tpObject = tp.getObject;
val tpSubjectNew:Node = if(tpSubject.isBlank()) { mapNewNodes.get(tpSubject).get } else { tpSubject; }
val tpObjectNew:Node = if(tpObject.isBlank()) { mapNewNodes.get(tpObject).get } else { tpObject; }
val newTriple = new Triple(tpSubjectNew, tp.getPredicate, tpObjectNew);
newTriple;
}
def skolemizeBlankNodes(blankNodes:Set[Node], baseURI:String) : Map[Node, Node] = {
val mapNewNodes = blankNodes.map(x => {(x -> this.skolemizeBlankNode(x, baseURI))}).toMap;
mapNewNodes;
}
def skolemizeBlankNode(blankNode:Node, baseURI:String) : Node = {
//val absoluteBaseURI = if(baseURI.endsWith("/")) { baseURI } else { baseURI + "/" }
val newNodeURI = baseURI + ".well-known/genid/" + blankNode.getBlankNodeLabel;
val newNode = NodeFactory.createURI(newNodeURI);
newNode;
}
def toTriples(model:Model) : List[Triple] = {
val statements = model.listStatements();
//val statementList = statements.toList();
var triples:List[Triple] = List.empty;
if(statements != null) {
while(statements.hasNext()) {
val statement = statements.nextStatement();
val triple = statement.asTriple();
triples = triples ::: List(triple);
}
}
triples;
}
def replaceBaseURI(lines:Iterator[String], pNewBaseURI:String) : Iterator[String] = {
var newBaseURI = pNewBaseURI;
if(!pNewBaseURI.startsWith("<")) {
newBaseURI = "<" + newBaseURI;
}
if(!pNewBaseURI.endsWith(">")) {
newBaseURI = newBaseURI + ">";
}
val newLines = lines.map(oneLine => {
val line = oneLine.trim;
if(line.startsWith("@base")) {
"@base " + newBaseURI + " . ";
} else { line }
}
)
newLines;
}
@throws(classOf[IOException])
def materializeFileInputStream(source: FileInputStream, dest: File) {
var sourceChannel: FileChannel = null
var destChannel: FileChannel = null
val fos: FileOutputStream = new FileOutputStream(dest)
try {
sourceChannel = source.getChannel
destChannel = fos.getChannel
destChannel.transferFrom(sourceChannel, 0, sourceChannel.size)
} finally {
sourceChannel.close
destChannel.close
fos.close
}
}
@throws(classOf[IOException])
def materializeFileInputStream(source: FileInputStream, uuidDirectoryName: String, fileName: String): File = {
val uploadDirectoryPath: String = MappingPediaConstant.DEFAULT_UPLOAD_DIRECTORY;
val outputDirectory: File = new File(uploadDirectoryPath)
if (!outputDirectory.exists) {
outputDirectory.mkdirs
}
val uuidDirectoryPath: String = uploadDirectoryPath + "/" + uuidDirectoryName
//logger.info("upload directory path = " + uuidDirectoryPath)
val uuidDirectory: File = new File(uuidDirectoryPath)
if (!uuidDirectory.exists) {
uuidDirectory.mkdirs
}
val uploadedFilePath: String = uuidDirectory + "/" + fileName
val dest: File = new File(uploadedFilePath)
dest.createNewFile
this.materializeFileInputStream(source, dest)
return dest
}
def pushContentToGitHub(file:File) = {
}
def multipartFileToFile(fileRef:MultipartFile) : File = {
// Path where the uploaded files will be stored.
val uuid = UUID.randomUUID().toString();
val file = this.multipartFileToFile(fileRef, uuid);
file;
}
def multipartFileToFile(fileRef:MultipartFile, uuid:String) : File = {
// Create the input stream to uploaded files to read data from it.
val fis:FileInputStream = try {
if(fileRef != null) {
val inputStreamAux = fileRef.getInputStream().asInstanceOf[FileInputStream];
inputStreamAux;
} else {
val errorMessage = "can't process the uploaded file, fileRef is null";
throw new Exception(errorMessage);
}
} catch {
case e:Exception => {
e.printStackTrace();
throw e;
}
}
// Get the name of uploaded files.
val fileName = fileRef.getOriginalFilename();
val file = MappingPediaUtility.materializeFileInputStream(fis, uuid, fileName);
file;
}
def readFromResourcesDirectory(filePath:String) : String = {
//var lines: String = Source.fromResource(templateFilePath).getLines.mkString("\n");
val is: InputStream = getClass.getResourceAsStream("/" + filePath)
val lines= scala.io.Source.fromInputStream(is).getLines.mkString("\n");
lines;
}
def getStringOrElse(qs:QuerySolution, varName:String, obj:String) : String = {
val result = qs.get(varName);
if(result == null) {
obj
} else {
result.toString;
}
}
def getOptionString(qs:QuerySolution, varName:String) : Option[String] = {
val result = qs.get(varName);
if(result == null) {
None
} else {
Some(result.toString);
}
}
def getClassesLocalNames(listOfClasses:List[OntClass]) : List[String] = {
val result = listOfClasses.map(ontClass => ontClass.getLocalName);
result;
}
def getClassesURIs(listOfClasses:List[OntClass]) : List[String] = {
val result = listOfClasses.map(ontClass => ontClass.getURI);
result;
}
def calculateHash(dataset:Dataset) : String = {
val distributions = dataset.getDistributions;
logger.info(s"{distributions.length = ${distributions.length}")
this.calculateHash(distributions);
}
def calculateHash(distributions:List[Distribution]) : String = {
val datasetHashValue = distributions.foldLeft(0)((acc, distribution) => {
val distributionHashValue = MappingPediaUtility.calculateHash(
distribution.dcatDownloadURL, distribution.encoding);
logger.info(s"distributionHashValue = ${distributionHashValue}")
acc + distributionHashValue.toInt
})
logger.debug(s"datasetHashValue = ${datasetHashValue}")
datasetHashValue.toString
}
def calculateHash(downloadURL:String) : String = {
this.calculateHash(downloadURL, null);
}
def calculateHash(downloadURL:String, pEncoding:String) : String = {
logger.debug(s"calculating hash value of ${downloadURL}");
val encoding = if(pEncoding == null) { "UTF-8" } else { pEncoding }
val hashValue = try {
if (downloadURL != null) {
val downloadURLContent = scala.io.Source.fromURL(downloadURL, encoding).mkString
//logger.info(s"downloadURLContent ${downloadURLContent}");
//val downloadURLContentBase64 = GitHubUtility.encodeToBase64(downloadURLContent);
//logger.info(s"downloadURLContentBase64 ${downloadURLContentBase64}");
//MessageDigest.getInstance("SHA").digest(downloadURLContentBase64.getBytes).toString
downloadURLContent.hashCode.toString;
} else {
null
}
} catch {
case e:Exception => {
e.printStackTrace()
null
}
}
logger.debug(s"hash value of of ${downloadURL} = ${hashValue}");
hashValue
}
def getFileNameAndContent(file: File, downloadURL:String, encoding:String) = {
val (fileName:String, fileContent:String) = {
if(file != null) {
val fileAbsolutePath = file.getAbsolutePath;
logger.info(s"fileAbsolutePath = $fileAbsolutePath");
val fileContent = Source.fromFile(file.getAbsolutePath, encoding)
logger.info(s"encoding = $encoding");
val fileContentLines = fileContent.getLines;
val fileContentString = fileContentLines.mkString("\n")
(file.getName, fileContentString)
} else if(downloadURL!= null) {
val downloadURLFilename = downloadURL.substring(
downloadURL.lastIndexOf('/') + 1, downloadURL.length)
val downloadURLContent = scala.io.Source.fromURL(downloadURL, encoding)
val downloadURLContentString = downloadURLContent.mkString
(downloadURLFilename, downloadURLContentString);
} else {
val errorMessage = "No file or download url has been provided"
logger.info(errorMessage);
throw new Exception(errorMessage);
}
}
(fileName:String, fileContent:String);
}
def normalizeTerm(originalTerm:String) : List[String] = {
if(originalTerm != null) {
val normalizedTermSingular = originalTerm.toLowerCase.replaceAll(" ", "");
val normalizedTermPlural1 = normalizedTermSingular + "s"
val normalizedTermPlural2 = normalizedTermSingular + "es"
val normalizedTermPlural3 = if(normalizedTermSingular.endsWith("y")) {
val plural = normalizedTermSingular.substring(0, normalizedTermSingular.length-1) + "ies"
//logger.info(s"$normalizedTermSingular -- $plural")
plural
} else { normalizedTermSingular }
List(normalizedTermSingular, normalizedTermPlural1, normalizedTermPlural2, normalizedTermPlural3)
} else {
Nil
}
}
def getClassURI(pClass:String) : String = {
this.getClassURI(pClass, "http://schema.org/")
}
def getClassURI(pClass:String, defaultNamespace:String) : String = {
val isLocalName = if(pClass.contains("/")) { false } else { true }
val classIRI = if(isLocalName) {
if(defaultNamespace.endsWith("/")) {
defaultNamespace + pClass
} else {
defaultNamespace + "/" + pClass
}
} else {
pClass
}
classIRI
}
/* def stringToBoolean(aString:String) : Boolean = {
if(aString != null) {
if(aString.equalsIgnoreCase("true") || aString.equalsIgnoreCase("yes")) {
true;
} else {
false
}
} else {
false
}
}*/
def stringToBoolean(inputString:String) : Boolean = {
try {
val listOfTrueString = List("true", "yes");
val result = if(inputString == null) {
false
} else {
if(listOfTrueString.contains(inputString)) {
true
} else {
false
}
}
result
} catch {
case e:Exception => {
e.printStackTrace()
false
}
}
}
}
|
pvmoore/ts-warp
|
src/warp/ast/decl/Declaration.java
|
package warp.ast.decl;
import warp.ast.stmt.Statement;
public abstract class Declaration extends Statement {
/** true if preceded by 'declare' keyword */
public boolean isAmbient;
}
|
amazoyer/ml-ranking-module
|
src/test/java/com/datafari/ranking/config/AbstractTest.java
|
package com.datafari.ranking.config;
import javax.inject.Inject;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import com.datafari.ranking.configuration.ConfigProperties;
import com.datafari.ranking.configuration.ResourceLoadingUtils;
import com.datafari.ranking.trainer.MLTrainer;
@ContextConfiguration(classes = LocalSolrTestConfig.class)
public class AbstractTest {
@Inject
protected ResourceLoadingUtils resourceLoadingUtils;
@Inject
protected MLTrainer mlTrainer;
}
|
xiabee/BIT-CS
|
C语言程序设计基础/心形2.c
|
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#define I 20
#define R 340
int main()
{
int i,j,e;
int a;
for(i=1,a=I;i<I/2;i++,a--){
for(j=(int) ( I-sqrt(I*I-(a-i)*(a-i)) );j>0;j--)
printf(" ");
for(e=1;e<=2*sqrt(I*I-(a-i)*(a-i));e++)
printf("\3");
for(j=(int) ( 2*( I-sqrt(I*I-(a-i)*(a-i)) ) );j>0;j--)
printf(" ");
for(e=1;e<=2*sqrt(I*I-(a-i)*(a-i));e++)
printf("\3");
printf("\n");
}
for(i=1;i<80;i++)
{
if(i==25){
printf(" ZT,I LOVE YOU!Happy New Year!");
i+=30;
}
printf("\3");
}
printf("\n");
for(i=1;i<=R/2;i++){
if(i%2||i%3)continue;
for(j=(int) ( R-sqrt(R*R-i*i) );j>0;j--)
printf(" ");
for(e=1;e<=2*( sqrt(R*R-i*i) - (R-2*I) );e++)
printf("\3");
printf("\n");
}
long time;
for(; ;)
{
system("color a");
for(time=0;time<99999999;time++);
system("color b");
for(time=0;time<99999999;time++);
system("color c");
for(time=0;time<99999999;time++);
system("color d");
for(time=0;time<99999999;time++);
system("color e");
for(time=0;time<99999999;time++);
system("color f");
for(time=0;time<99999999;time++);
system("color 0");
for(time=0;time<99999999;time++);
system("color 1");
for(time=0;time<99999999;time++);
system("color 2");
for(time=0;time<99999999;time++);
system("color 3");
for(time=0;time<99999999;time++);
system("color 4");
for(time=0;time<99999999;time++);
system("color 5");
for(time=0;time<99999999;time++);
system("color 6");
for(time=0;time<99999999;time++);
system("color 7");
for(time=0;time<99999999;time++);
system("color 8");
for(time=0;time<99999999;time++);
system("color 9");
for(time=0;time<99999999;time++);
system("color ab");
for(time=0;time<99999999;time++);
system("color ac");
for(time=0;time<99999999;time++);
system("color ad");
for(time=0;time<99999999;time++);
system("color ae");
for(time=0;time<99999999;time++);
system("color af");
for(time=0;time<99999999;time++);
}
return 0;
}
|
charlesbjohnson/super_happy_interview_time
|
rb/lib/ctci/ctci_c2_p1.rb
|
# frozen_string_literal: true
module CTCI
module C2
module P1
# Write code to remove duplicates from an unsorted linked list.
# FOLLOW UP
# How would you solve this problem if a temporary buffer is not allowed?
def remove_dup!
dups = count_dup
cursor = @head
until cursor == @tail
data = cursor.next.data
is_a_dup = dups.key?(data)
if is_a_dup
times_seen = dups[data]
if times_seen.positive?
# deleting the next node has the side effect of
# incrementing cursor.next, repeat this iteration
# so that we don't jump over it accidentally
delete_next(cursor)
next
end
dups[data] += 1
end
cursor = cursor.next
end
end
private
def count_dup
counts = Hash.new(0)
cursor = @head.next
while cursor
counts[cursor.data] += 1
cursor = cursor.next
end
dups = counts.select { |_, v| v > 1 }
dups.each_key { |k| dups[k] = 0 }
end
def delete_next(cursor)
doomed = cursor.next
cursor.next = doomed.next
@tail = cursor if doomed == @tail
end
end
end
end
|
vassik/ThingMLTesting
|
language/thingml/src/org/thingml/xtext/StringLitValueConverter.java
|
<reponame>vassik/ThingMLTesting
/**
* 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.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*/
package org.thingml.xtext;
import org.eclipse.xtext.conversion.ValueConverterException;
import org.eclipse.xtext.conversion.impl.AbstractLexerBasedConverter;
import org.eclipse.xtext.nodemodel.INode;
public class StringLitValueConverter extends AbstractLexerBasedConverter<String> {
@Override
public String toValue(String string, INode node) throws ValueConverterException {
if(string != null && string.length() >= 2 && string.startsWith("\"") && string.endsWith("\"")) {
return string.substring(1, string.length()-1);
}
return string;
}
@Override
public String toString(String value) {
return "\"" + value + "\"";
}
}
|
homer0/jimpex
|
src/middlewares/utils/versionValidator.js
|
const ObjectUtils = require('wootils/shared/objectUtils');
const { code: statuses } = require('statuses');
const { middlewareCreator } = require('../../utils/wrappers');
/**
* @typedef {import('../../types').ExpressMiddleware} ExpressMiddleware
* @typedef {import('../../types').ExpressRequest} ExpressRequest
* @typedef {import('../../services/http/responsesBuilder').ResponsesBuilder} ResponsesBuilder
* @prettierignore
*/
/**
* @typedef {import('../../types').MiddlewareCreator<O>} MiddlewareCreator<O>
* @template O
*/
/**
* The options for how the middleware should behave if the requested version is `latest`.
*
* @typedef {Object} VersionValidatorLatestOptions
* @property {boolean} allow Whether or not the middleware should validate the _"latest
* version"_.
* Default `true`.
* @property {string} name The name of the _"latest version"_. Basically,
* `req.params.version`
* must match with this property in order to be consider
* "latest".
* Default `'latest'`.
* @parent module:middlewares
*/
/**
* The options for how to detect if the request comes from a popup and how to compose the
* post message the middleware will use to respond.
*
* @typedef {Object} VersionValidatorPopupOptions
* @property {string} variable The name of the query string variable the middleware will
* check in order to indentify whether the request comes from
* a popup or not.
* The variable must have `'true'` as its value. Default
* `'popup'`.
* @property {string} title The title of the page that will be generated to respond in
* case the versions don't match. Default `'Conflict'`.
* @property {string} message The contents of the post message the generated page will
* send if the versions don't match. Default
* `'vesion:conflict'`.
* @parent module:middlewares
*/
/**
* The options used to customize a {@link VersionValidator} instance.
*
* @typedef {Object} VersionValidatorOptions
* @property {string} error The error message to show when the
* version is invalid.
* @property {VersionValidatorLatestOptions} latest The options for how the middleware
* should behave if the requested
* version is `latest`.
* @property {VersionValidatorPopupOptions} popup The options for how to detect if the
* request comes from a popup and how
* to compose the post message the
* middleware will use to respond.
* @property {string | number} version The version used to validate the
* requests.
* On the {@link VersionValidator}
* constructor, if specified via
* parameter,
* the class will take care of
* automatically add it to the options.
* @parent module:middlewares
*/
/**
* This is the handler for the middleware/controller that validates the app version.
* This is useful in cases where you want to restrict the access to the app to specific
* versions,
* for example: you have a frontend app which needs to be aligned with the "current"
* version of the app, since the frontend won't realize a new version was released, the
* validator can be used to let the frontend know.
* Also, it can be configured to handle requests from popups, in which case, instead of
* generating an error message, it will send a post message.
*
* @parent module:middlewares
*/
class VersionValidator {
/**
* @param {?(string | ?number)} version
* The current version of the app. The reason this is nullable is because this comes
* directly from the app configuration, but you may want to re use this to validate
* "another version", so you can use the custom shorthand and send the version using the
* `options` parameter.
* @param {ResponsesBuilder} responsesBuilder
* To generate post message responses for popups.
* @param {ClassAppError} AppError
* To generate the error in case the version is invalid.
* @param {Partial<VersionValidatorOptions>} [options={}]
* Custom options to modify the middleware behavior.
* @throws {Error}
* If the version is `null` and the `options` don't include one either.
*/
constructor(version, responsesBuilder, AppError, options = {}) {
/**
* A local reference for the `responsesBuilder` service.
*
* @type {ResponsesBuilder}
* @access protected
* @ignore
*/
this._responsesBuilder = responsesBuilder;
/**
* A local reference for the class the app uses to generate errors.
*
* @type {ClassAppError}
* @access protected
* @ignore
*/
this._AppError = AppError;
/**
* These are the "settings" the middleware will use in order to validate the requests.
*
* @type {VersionValidatorOptions}
* @access protected
* @ignore
*/
this._options = ObjectUtils.merge(
{
error: "The application version doesn't match",
latest: {
allow: true,
name: 'latest',
},
popup: {
variable: 'popup',
title: 'Conflict',
message: 'vesion:conflict',
},
version,
},
options,
);
if (!this._options.version) {
throw new Error('You need to supply a version');
}
}
/**
* Returns the Express middleware that will validate the `version` parameter.
*
* @returns {ExpressMiddleware}
*/
middleware() {
return (req, res, next) => {
// Get the `version` parameter from the request.
const { version } = req.params;
if (!version) {
// If no version is present, move on to the next middleware.
next();
} else if (version === this._options.version || this._validateLatest(version)) {
/**
* If the version matches the one on the options, or the requested version is "latest"
* (and the option is enabled), move on to the next middleware.
*/
next();
} else if (this._isPopup(req)) {
/**
* If it doesn't match and the request is comming from a popup, send a response with a
* post message.
*/
this._responsesBuilder.htmlPostMessage(
res,
this._options.popup.title,
this._options.popup.message,
statuses.conflict,
);
} else {
// Finally, if it doesn't match and is not from a popup, move to the error handler.
next(
new this._AppError(this._options.error, {
status: statuses.conflict,
response: {
validation: true,
},
}),
);
}
};
}
/**
* The options used to customize the middleware behavior.
*
* @returns {VersionValidatorOptions}
*/
get options() {
return this._options;
}
/**
* Helper method that checks if the incoming request is from a popup.
*
* @param {ExpressRequest} req The request information.
* @returns {boolean}
* @access protected
* @ignore
*/
_isPopup(req) {
const popup = req.query[this._options.popup.variable];
return !!(popup && popup.toLowerCase() === 'true');
}
/**
* Helper method that checks if the "latest version" is enabled and if the given version
* is "the latest" (comparing it with the option name).
*
* @param {string | number} version The version to validate.
* @returns {boolean}
* @access protected
* @ignore
*/
_validateLatest(version) {
return this._options.latest.allow && version === this._options.latest.name;
}
}
/**
* A middleware that will validate a `version` request parameter against the app version
* and generate an error if they don't match.
* This is a "middleware/controller" is because the wrappers for both are the same, the
* difference is that, for controllers, Jimpex sends a second parameter with the route
* where they are mounted.
* By validating the route parameter, the function can know whether the implementation is
* going to use the middleware by itself or as a route middleware.
* If used as middleware, it will just return the result of
* {@link VersionValidator#middleware};
* but if used as controller, it will mount it on `[route]/:version/*`.
*
* @type {MiddlewareCreator<VersionValidatorOptions>}
* @parent module:middlewares
*/
const versionValidator = middlewareCreator((options = {}) => (app, route) => {
// Get the middleware function.
const middlewareValidator = new VersionValidator(
app.get('appConfiguration').get('version'),
app.get('responsesBuilder'),
app.get('AppError'),
options,
).middleware();
// Set the variable to be returned.
let result;
if (route) {
// If the implementation will use it as a router, get the `router` service and mount it.
const router = app.get('router');
// Set the array of "routes" as the return value.
result = [router.all('/:version/*', middlewareValidator)];
} else {
// If the implementation will use it stand alone, just set the function to be returned.
result = middlewareValidator;
}
// Return the route or the middleware.
return result;
});
module.exports.VersionValidator = VersionValidator;
module.exports.versionValidator = versionValidator;
|
adrienlachaize/dezede
|
libretto/migrations/0029_add_auteur_ensemble_and_constraints.py
|
from django.db import models, migrations
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('libretto', '0028_auto_20150526_0012'),
]
operations = [
migrations.AddField(
model_name='auteur',
name='ensemble',
field=models.ForeignKey(related_name='auteurs', on_delete=django.db.models.deletion.PROTECT, verbose_name='ensemble', blank=True, to='libretto.Ensemble', null=True),
preserve_default=True,
),
migrations.AlterField(
model_name='auteur',
name='individu',
field=models.ForeignKey(related_name='auteurs', on_delete=django.db.models.deletion.PROTECT, verbose_name='individu', blank=True, to='libretto.Individu', null=True),
preserve_default=True,
),
migrations.AlterField(
model_name='oeuvre',
name='ict',
field=models.CharField(help_text='Indice de Catalogue Th\xe9matique. Exemple\xa0: \xab\xa0RV\xa042\xa0\xbb, \xab\xa0K.\xa0299d\xa0\xbb ou encore \xab\xa0Hob.\xa0XVI:24\xa0\xbb.', max_length=25, verbose_name='ICT', db_index=True, blank=True),
preserve_default=True,
),
migrations.RunSQL("""
ALTER TABLE libretto_elementdedistribution
ADD CONSTRAINT evenement_xor_elementdeprogramme
CHECK (evenement_id IS NOT NULL <> element_de_programme_id IS NOT NULL);
ALTER TABLE libretto_elementdedistribution
ADD CONSTRAINT not_partie_and_profession
CHECK (NOT (partie_id IS NOT NULL AND profession_id IS NOT NULL));
ALTER TABLE libretto_auteur
ADD CONSTRAINT oeuvre_xor_source
CHECK (oeuvre_id IS NOT NULL <> source_id IS NOT NULL);
ALTER TABLE libretto_auteur
ADD CONSTRAINT individu_xor_ensemble
CHECK (individu_id IS NOT NULL <> ensemble_id IS NOT NULL);
""", """
ALTER TABLE libretto_elementdedistribution
DROP CONSTRAINT evenement_xor_elementdeprogramme;
ALTER TABLE libretto_elementdedistribution
DROP CONSTRAINT not_partie_and_profession;
ALTER TABLE libretto_auteur
DROP CONSTRAINT oeuvre_xor_source;
ALTER TABLE libretto_auteur
DROP CONSTRAINT individu_xor_ensemble;
"""),
]
|
nowimwrok/zd_devpro
|
src/main/java/com/thinkgem/jeesite/modules/wlpt/web/activity/ActivityWxgiftController.java
|
/**
*
*/
package com.thinkgem.jeesite.modules.wlpt.web.activity;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.IdGen;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.Tools;
import com.thinkgem.jeesite.modules.wlpt.entity.activity.ActivityWxgift;
import com.thinkgem.jeesite.modules.wlpt.service.activity.ActivityWxgiftService;
/**
* 奖品列表Controller
* @author 曾煜佳
* @version 2016-08-04
*/
@Controller
@RequestMapping(value = "${adminPath}/wlpt/activity/activityWxgift")
public class ActivityWxgiftController extends BaseController {
@Autowired
private ActivityWxgiftService activityWxgiftService;
@ModelAttribute
public ActivityWxgift get(@RequestParam(required=false) String id) {
ActivityWxgift entity = null;
if (StringUtils.isNotBlank(id)){
entity = activityWxgiftService.get(id);
}
if (entity == null){
entity = new ActivityWxgift();
}
return entity;
}
@RequiresPermissions("wlpt:activity:activityWxgift:view")
@RequestMapping(value = {"list", ""})
public String list(ActivityWxgift activityWxgift, HttpServletRequest request, HttpServletResponse response, Model model) {
Page<ActivityWxgift> page = activityWxgiftService.findPage(new Page<ActivityWxgift>(request, response), activityWxgift);
model.addAttribute("page", page);
return "modules/wlpt/activity/activityWxgiftList";
}
@RequiresPermissions("wlpt:activity:activityWxgift:view")
@RequestMapping(value = "form")
public String form(ActivityWxgift activityWxgift, Model model) {
model.addAttribute("activityWxgift", activityWxgift);
return "modules/wlpt/activity/activityWxgiftForm";
}
@RequiresPermissions("wlpt:activity:activityWxgift:edit")
@RequestMapping(value = "save")
public String save(ActivityWxgift activityWxgift, Model model, RedirectAttributes redirectAttributes) {
if (!beanValidator(model, activityWxgift)){
return form(activityWxgift, model);
}
//判断当前奖品是添加或是修改
if(Tools.IsNullOrWhiteSpace(activityWxgift.getId())){
activityWxgift.setId(IdGen.uuid());
activityWxgift.setIsNewRecord(true);
activityWxgift.setUpdatetime(new Date());
activityWxgift.setCreatetime(new Date());
activityWxgift.setSurplusnum(activityWxgift.getGiftnum());
}else {
activityWxgift.setUpdateDate(new Date());
}
activityWxgiftService.save(activityWxgift);
addMessage(redirectAttributes, "保存奖品成功");
//判断上一个页面是否是活动信息列表
if(activityWxgift.getPagetype().equals("info")){
return "redirect:"+Global.getAdminPath()+"/wlpt/activity/activityWxinfo/?repage";
}
return "redirect:"+Global.getAdminPath()+"/wlpt/activity/activityWxgift/?repage";
}
@RequiresPermissions("wlpt:activity:activityWxgift:edit")
@RequestMapping(value = "delete")
public String delete(ActivityWxgift activityWxgift, RedirectAttributes redirectAttributes) {
activityWxgiftService.delete(activityWxgift);
addMessage(redirectAttributes, "删除奖品成功");
return "redirect:"+Global.getAdminPath()+"/wlpt/activity/activityWxgift/?repage";
}
}
|
DmitriiEskov/deskov
|
problems/src/test/java/frog/FrogTest.java
|
package frog;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
/**
* This class is for testing the Frog class.
*
* @author <NAME> (<EMAIL>)
* @since 17.07.2019
*/
public class FrogTest {
private HashSet<String> firstTest = new HashSet<>();
private HashSet<String> secondTest = new HashSet<>();
public FrogTest() {
try (BufferedReader reader1 = new BufferedReader(new FileReader(getClass().getClassLoader().getResource("firstTest.txt").getFile()));
BufferedReader reader2 = new BufferedReader(new FileReader(getClass().getClassLoader().getResource("secondTest.txt").getFile()))) {
while (reader1.ready()) {
this.firstTest.add(reader1.readLine());
}
while (reader2.ready()) {
this.secondTest.add(reader2.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void whenMoveAndMeetTreesThenSuccess() {
int[] start = {7, 11};
int[] finish = {10, 9};
int[] tree = {9, 14};
int[] tree2 = {8, 5};
HashSet<String> result = new Frog().move(start, finish, 2, tree, tree2);
assertThat(result, is(this.firstTest));
}
@Test
public void whenMoveWithoutTreesThenSuccess() {
int[] start = {7, 11};
int[] finish = {3, 3};
HashSet<String> result = new Frog().move(start, finish, 0, new int[0], new int[0]);
assertThat(result, is(this.secondTest));
}
@Test
public void whenImpossibleToFindWay() {
int[] start = {7, 11};
int[] finish = {10, 9};
int[] tree1 = {10, 8};
int[] tree2 = {9, 8};
int[] tree3 = {9, 9};
int[] tree4 = {9, 10};
int[] tree5 = {10, 10};
HashSet<String> result = new Frog().move(start, finish, 5, tree1, tree2, tree3, tree4, tree5);
assertThat(true, is(result.isEmpty()));
}
}
|
jarocho105/pre2
|
erp_desktop_all/src_cartera/com/bydan/erp/cartera/presentation/swing/jinternalframes/TipoBienJInternalFrame.java
|
<gh_stars>1-10
/*
*AVISO LEGAL
© Copyright
*Este programa esta protegido por la ley de derechos de autor.
*La reproduccion o distribucion ilicita de este programa o de cualquiera de
*sus partes esta penado por la ley con severas sanciones civiles y penales,
*y seran objeto de todas las sanciones legales que correspondan.
*Su contenido no puede copiarse para fines comerciales o de otras,
*ni puede mostrarse, incluso en una version modificada, en otros sitios Web.
Solo esta permitido colocar hipervinculos al sitio web.
*/
package com.bydan.erp.cartera.presentation.swing.jinternalframes;
import com.bydan.erp.seguridad.presentation.swing.jinternalframes.*;
import com.bydan.erp.cartera.presentation.web.jsf.sessionbean.*;//;
import com.bydan.erp.cartera.presentation.swing.jinternalframes.*;
import com.bydan.erp.cartera.presentation.swing.jinternalframes.auxiliar.*;
import com.bydan.erp.seguridad.presentation.web.jsf.sessionbean.*;
import com.bydan.erp.seguridad.business.entity.*;
//import com.bydan.erp.cartera.presentation.report.source.*;
import com.bydan.framework.erp.business.entity.Reporte;
import com.bydan.erp.seguridad.business.entity.Modulo;
import com.bydan.erp.seguridad.business.entity.Opcion;
import com.bydan.erp.seguridad.business.entity.Usuario;
import com.bydan.erp.seguridad.business.entity.ResumenUsuario;
import com.bydan.erp.seguridad.business.entity.ParametroGeneralSg;
import com.bydan.erp.seguridad.business.entity.ParametroGeneralUsuario;
import com.bydan.erp.seguridad.util.SistemaParameterReturnGeneral;
import com.bydan.erp.cartera.business.entity.*;
import com.bydan.erp.cartera.util.TipoBienConstantesFunciones;
import com.bydan.erp.cartera.business.logic.*;
import com.bydan.framework.erp.business.entity.DatoGeneral;
import com.bydan.framework.erp.business.entity.OrderBy;
import com.bydan.framework.erp.business.entity.Mensajes;
import com.bydan.framework.erp.business.entity.Classe;
import com.bydan.framework.erp.business.logic.*;
import com.bydan.framework.erp.presentation.desktop.swing.DateConverter;
import com.bydan.framework.erp.presentation.desktop.swing.DateConverterFromDate;
import com.bydan.framework.erp.presentation.desktop.swing.FuncionesSwing;
import com.bydan.framework.erp.presentation.desktop.swing.JInternalFrameBase;
import com.bydan.framework.erp.presentation.desktop.swing.*;
import com.bydan.framework.erp.util.*;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.sql.*;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRRuntimeException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.j2ee.servlets.BaseHttpServlet;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.data.JRBeanArrayDataSource;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import javax.swing.*;
import java.awt.*;
import javax.swing.border.EtchedBorder;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.table.TableColumn;
import com.toedter.calendar.JDateChooser;
@SuppressWarnings("unused")
public class TipoBienJInternalFrame extends TipoBienBeanSwingJInternalFrameAdditional {
private static final long serialVersionUID = 1L;
//protected Usuario usuarioActual=null;
public JToolBar jTtoolBarTipoBien;
protected JMenuBar jmenuBarTipoBien;
protected JMenu jmenuTipoBien;
protected JMenu jmenuDatosTipoBien;
protected JMenu jmenuArchivoTipoBien;
protected JMenu jmenuAccionesTipoBien;
protected JPanel jContentPane = null;
protected JPanel jPanelBusquedasParametrosTipoBien = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
protected GridBagLayout gridaBagLayoutTipoBien;
protected GridBagConstraints gridBagConstraintsTipoBien;
//protected JInternalFrameBase jInternalFrameParent;
public TipoBienDetalleFormJInternalFrame jInternalFrameDetalleFormTipoBien;
protected ReporteDinamicoJInternalFrame jInternalFrameReporteDinamicoTipoBien;
protected ImportacionJInternalFrame jInternalFrameImportacionTipoBien;
//VENTANAS PARA ACTUALIZAR Y BUSCAR FK
protected EmpresaBeanSwingJInternalFrame empresaBeanSwingJInternalFrame;
public String sFinalQueryGeneral_empresa="";
public TipoBienSessionBean tipobienSessionBean;
public EmpresaSessionBean empresaSessionBean;
//protected JDesktopPane jDesktopPane;
public List<TipoBien> tipobiens;
public List<TipoBien> tipobiensEliminados;
public List<TipoBien> tipobiensAux;
protected OrderByJInternalFrame jInternalFrameOrderByTipoBien;
protected JButton jButtonAbrirOrderByTipoBien;
//protected JPanel jPanelOrderByTipoBien;
//public JScrollPane jScrollPanelOrderByTipoBien;
//protected JButton jButtonCerrarOrderByTipoBien;
public ArrayList<OrderBy> arrOrderBy= new ArrayList<OrderBy>();
public TipoBienLogic tipobienLogic;
public JScrollPane jScrollPanelDatosTipoBien;
public JScrollPane jScrollPanelDatosEdicionTipoBien;
public JScrollPane jScrollPanelDatosGeneralTipoBien;
//public JScrollPane jScrollPanelDatosTipoBienOrderBy;
//public JScrollPane jScrollPanelReporteDinamicoTipoBien;
//public JScrollPane jScrollPanelImportacionTipoBien;
protected JPanel jPanelAccionesTipoBien;
protected JPanel jPanelPaginacionTipoBien;
protected JPanel jPanelParametrosReportesTipoBien;
protected JPanel jPanelParametrosReportesAccionesTipoBien;
;
protected JPanel jPanelParametrosAuxiliar1TipoBien;
protected JPanel jPanelParametrosAuxiliar2TipoBien;
protected JPanel jPanelParametrosAuxiliar3TipoBien;
protected JPanel jPanelParametrosAuxiliar4TipoBien;
//protected JPanel jPanelParametrosAuxiliar5TipoBien;
//protected JPanel jPanelReporteDinamicoTipoBien;
//protected JPanel jPanelImportacionTipoBien;
public JTable jTableDatosTipoBien;
//public JTable jTableDatosTipoBienOrderBy;
//ELEMENTOS TABLAS PARAMETOS
//ELEMENTOS TABLAS PARAMETOS_FIN
protected JButton jButtonNuevoTipoBien;
protected JButton jButtonDuplicarTipoBien;
protected JButton jButtonCopiarTipoBien;
protected JButton jButtonVerFormTipoBien;
protected JButton jButtonNuevoRelacionesTipoBien;
protected JButton jButtonModificarTipoBien;
protected JButton jButtonGuardarCambiosTablaTipoBien;
protected JButton jButtonCerrarTipoBien;
protected JButton jButtonRecargarInformacionTipoBien;
protected JButton jButtonProcesarInformacionTipoBien;
protected JButton jButtonAnterioresTipoBien;
protected JButton jButtonSiguientesTipoBien;
protected JButton jButtonNuevoGuardarCambiosTipoBien;
//protected JButton jButtonGenerarReporteDinamicoTipoBien;
//protected JButton jButtonCerrarReporteDinamicoTipoBien;
//protected JButton jButtonGenerarExcelReporteDinamicoTipoBien;
//protected JButton jButtonAbrirImportacionTipoBien;
//protected JButton jButtonGenerarImportacionTipoBien;
//protected JButton jButtonCerrarImportacionTipoBien;
//protected JFileChooser jFileChooserImportacionTipoBien;
//protected File fileImportacionTipoBien;
//TOOLBAR
protected JButton jButtonNuevoToolBarTipoBien;
protected JButton jButtonDuplicarToolBarTipoBien;
protected JButton jButtonNuevoRelacionesToolBarTipoBien;
public JButton jButtonGuardarCambiosToolBarTipoBien;
protected JButton jButtonCopiarToolBarTipoBien;
protected JButton jButtonVerFormToolBarTipoBien;
public JButton jButtonGuardarCambiosTablaToolBarTipoBien;
protected JButton jButtonMostrarOcultarTablaToolBarTipoBien;
protected JButton jButtonCerrarToolBarTipoBien;
protected JButton jButtonRecargarInformacionToolBarTipoBien;
protected JButton jButtonProcesarInformacionToolBarTipoBien;
protected JButton jButtonAnterioresToolBarTipoBien;
protected JButton jButtonSiguientesToolBarTipoBien;
protected JButton jButtonNuevoGuardarCambiosToolBarTipoBien;
protected JButton jButtonAbrirOrderByToolBarTipoBien;
//TOOLBAR
//MENU
protected JMenuItem jMenuItemNuevoTipoBien;
protected JMenuItem jMenuItemDuplicarTipoBien;
protected JMenuItem jMenuItemNuevoRelacionesTipoBien;
protected JMenuItem jMenuItemGuardarCambiosTipoBien;
protected JMenuItem jMenuItemCopiarTipoBien;
protected JMenuItem jMenuItemVerFormTipoBien;
protected JMenuItem jMenuItemGuardarCambiosTablaTipoBien;
protected JMenuItem jMenuItemCerrarTipoBien;
protected JMenuItem jMenuItemDetalleCerrarTipoBien;
protected JMenuItem jMenuItemDetalleAbrirOrderByTipoBien;
protected JMenuItem jMenuItemDetalleMostarOcultarTipoBien;
protected JMenuItem jMenuItemRecargarInformacionTipoBien;
protected JMenuItem jMenuItemProcesarInformacionTipoBien;
protected JMenuItem jMenuItemAnterioresTipoBien;
protected JMenuItem jMenuItemSiguientesTipoBien;
protected JMenuItem jMenuItemNuevoGuardarCambiosTipoBien;
protected JMenuItem jMenuItemAbrirOrderByTipoBien;
protected JMenuItem jMenuItemMostrarOcultarTipoBien;
//MENU
protected JLabel jLabelAccionesTipoBien;
protected JCheckBox jCheckBoxSeleccionarTodosTipoBien;
protected JCheckBox jCheckBoxSeleccionadosTipoBien;
protected JCheckBox jCheckBoxConAltoMaximoTablaTipoBien;
protected JCheckBox jCheckBoxConGraficoReporteTipoBien;
@SuppressWarnings("rawtypes")
protected JComboBox jComboBoxTiposArchivosReportesTipoBien;
@SuppressWarnings("rawtypes")
protected JComboBox jComboBoxTiposReportesTipoBien;
//@SuppressWarnings("rawtypes")
//protected JComboBox jComboBoxTiposArchivosReportesDinamicoTipoBien;
//@SuppressWarnings("rawtypes")
//protected JComboBox jComboBoxTiposReportesDinamicoTipoBien;
@SuppressWarnings("rawtypes")
protected JComboBox jComboBoxTiposGraficosReportesTipoBien;
@SuppressWarnings("rawtypes")
protected JComboBox jComboBoxTiposPaginacionTipoBien;
@SuppressWarnings("rawtypes")
protected JComboBox jComboBoxTiposRelacionesTipoBien;
@SuppressWarnings("rawtypes")
protected JComboBox jComboBoxTiposAccionesTipoBien;
@SuppressWarnings("rawtypes")
protected JComboBox jComboBoxTiposSeleccionarTipoBien;
protected JTextField jTextFieldValorCampoGeneralTipoBien;
//REPORTE DINAMICO
//@SuppressWarnings("rawtypes")
//public JLabel jLabelColumnasSelectReporteTipoBien;
//public JList<Reporte> jListColumnasSelectReporteTipoBien;
//public JScrollPane jScrollColumnasSelectReporteTipoBien;
//public JLabel jLabelRelacionesSelectReporteTipoBien;
//public JList<Reporte> jListRelacionesSelectReporteTipoBien;
//public JScrollPane jScrollRelacionesSelectReporteTipoBien;
//public JLabel jLabelConGraficoDinamicoTipoBien;
//protected JCheckBox jCheckBoxConGraficoDinamicoTipoBien;
//public JLabel jLabelGenerarExcelReporteDinamicoTipoBien;
//public JLabel jLabelTiposArchivoReporteDinamicoTipoBien;
//public JLabel jLabelArchivoImportacionTipoBien;
//public JLabel jLabelPathArchivoImportacionTipoBien;
//protected JTextField jTextFieldPathArchivoImportacionTipoBien;
//public JLabel jLabelColumnaCategoriaGraficoTipoBien;
//@SuppressWarnings("rawtypes")
//protected JComboBox jComboBoxColumnaCategoriaGraficoTipoBien;
//public JLabel jLabelColumnaCategoriaValorTipoBien;
//@SuppressWarnings("rawtypes")
//protected JComboBox jComboBoxColumnaCategoriaValorTipoBien;
//public JLabel jLabelColumnasValoresGraficoTipoBien;
//public JList<Reporte> jListColumnasValoresGraficoTipoBien;
//public JScrollPane jScrollColumnasValoresGraficoTipoBien;
//public JLabel jLabelTiposGraficosReportesDinamicoTipoBien;
//@SuppressWarnings("rawtypes")
//protected JComboBox jComboBoxTiposGraficosReportesDinamicoTipoBien;
protected Boolean conMaximoRelaciones=true;
protected Boolean conFuncionalidadRelaciones=true;
public Boolean conCargarMinimo=false;
public Boolean cargarRelaciones=false;
public Boolean conMostrarAccionesCampo=false;
public Boolean permiteRecargarForm=false;//PARA NUEVO PREPARAR Y MANEJO DE EVENTOS, EVITAR QUE SE EJECUTE AL CARGAR VENTANA O LOAD
public Boolean conCargarFormDetalle=false;
//BYDAN_BUSQUEDAS
public JTabbedPane jTabbedPaneBusquedasTipoBien;
//ELEMENTOS TABLAS PARAMETOS
//ELEMENTOS TABLAS PARAMETOS_FIN
public static int openFrameCount = 0;
public static final int xOffset = 10, yOffset = 35;
//LOS DATOS DE NUEVO Y EDICION ACTUAL APARECEN EN OTRA VENTANA(true) O NO(false)
public static Boolean CON_DATOS_FRAME=true;
public static Boolean ISBINDING_MANUAL=true;
public static Boolean ISLOAD_FKLOTE=true;
public static Boolean ISBINDING_MANUAL_TABLA=true;
public static Boolean CON_CARGAR_MEMORIA_INICIAL=true;
//Al final no se utilizan, se inicializan desde JInternalFrameBase, desde ParametroGeneralUsuario
public static String STIPO_TAMANIO_GENERAL="NORMAL";
public static String STIPO_TAMANIO_GENERAL_TABLA="NORMAL";
public static Boolean CONTIPO_TAMANIO_MANUAL=false;
public static Boolean CON_LLAMADA_SIMPLE=true;
public static Boolean CON_LLAMADA_SIMPLE_TOTAL=true;
public static Boolean ESTA_CARGADO_PORPARTE=false;
public int iWidthScroll=0;//(screenSize.width-screenSize.width/2)+(250*0);
public int iHeightScroll=0;//(screenSize.height-screenSize.height/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ALTO);
//public int iWidthFormulario=450;//(screenSize.width-screenSize.width/2)+(250*0);
//public int iHeightFormulario=418;//(screenSize.height-screenSize.height/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ALTO);
//Esto va en DetalleForm
//public int iHeightFormularioMaximo=0;
//public int iWidthFormularioMaximo=0;
public int iWidthTableDefinicion=0;
public double dStart = 0;
public double dEnd = 0;
public double dDif = 0;
/*
double start=(double)System.currentTimeMillis();
double end=0;
double dif=0;
end=(double)System.currentTimeMillis();
dif=end - start;
start=(double)System.currentTimeMillis();
System.out.println("Tiempo(ms) Carga TEST 1_2 DetalleMovimientoInventario: " + dif);
*/
public SistemaParameterReturnGeneral sistemaReturnGeneral;
public List<Opcion> opcionsRelacionadas=new ArrayList<Opcion>();
//ES AUXILIAR PARA WINDOWS FORMS
public TipoBienJInternalFrame() throws Exception {
super(PaginaTipo.PRINCIPAL);
//super("TipoBien No " + (++openFrameCount),true, /*resizable*/true, /*closable*/true, /*maximizable*/true);//iconifiable
try {
//Boolean cargarRelaciones=false;
initialize(null,false,false,false/*cargarRelaciones*/,null,null,null,null,null,null,PaginaTipo.PRINCIPAL);
} catch(Exception e) {
FuncionesSwing.manageException(this, e, null);
}
}
public TipoBienJInternalFrame(Boolean cargarRelaciones,PaginaTipo paginaTipo) throws Exception {
super(paginaTipo);
//super("TipoBien No " + (++openFrameCount),true, /*resizable*/true, /*closable*/true, /*maximizable*/true);//iconifiable
try {
initialize(null,false,false,cargarRelaciones,null,null,null,null,null,null,paginaTipo);
} catch(Exception e) {
FuncionesSwing.manageException(this, e, null);
}
}
public TipoBienJInternalFrame(Boolean conGuardarRelaciones,Boolean esGuardarRelacionado,Boolean cargarRelaciones,PaginaTipo paginaTipo) throws Exception {
super(paginaTipo);
//super("TipoBien No " + (++openFrameCount),true, /*resizable*/true, /*closable*/true, /*maximizable*/true);//iconifiable
try {
initialize(null,conGuardarRelaciones,esGuardarRelacionado,cargarRelaciones,null,null,null,null,null,null,paginaTipo);
} catch(Exception e) {
FuncionesSwing.manageException(this, e, null);
}
}
public TipoBienJInternalFrame(JDesktopPane jdesktopPane,Boolean conGuardarRelaciones,Boolean esGuardarRelacionado,Boolean cargarRelaciones,Usuario usuarioActual,ResumenUsuario resumenUsuarioActual,Modulo moduloActual,Opcion opcionActual,ParametroGeneralSg parametroGeneralSg,ParametroGeneralUsuario parametroGeneralUsuario,PaginaTipo paginaTipo) throws Exception {
super(paginaTipo);//,jdesktopPane
this.jDesktopPane=jdesktopPane;
this.dStart=(double)System.currentTimeMillis();
//super("TipoBien No " + (++openFrameCount),true, /*resizable*/true, /*closable*/true, /*maximizable*/true);//iconifiable
try {
long start_time=0;
long end_time=0;
if(Constantes2.ISDEVELOPING2) {
start_time = System.currentTimeMillis();
}
initialize(jdesktopPane,conGuardarRelaciones,esGuardarRelacionado,cargarRelaciones,usuarioActual,resumenUsuarioActual,moduloActual,opcionActual,parametroGeneralSg,parametroGeneralUsuario,paginaTipo);
if(Constantes2.ISDEVELOPING2) {
end_time = System.currentTimeMillis();
String sTipo="Clase Padre Ventana";
Funciones2.getMensajeTiempoEjecucion(start_time, end_time, sTipo,false);
}
} catch(Exception e) {
FuncionesSwing.manageException(this, e, null);
}
}
public JInternalFrameBase getJInternalFrameParent() {
return jInternalFrameParent;
}
public void setJInternalFrameParent(JInternalFrameBase internalFrameParent) {
jInternalFrameParent = internalFrameParent;
}
public void setjButtonRecargarInformacion(JButton jButtonRecargarInformacionTipoBien) {
this.jButtonRecargarInformacionTipoBien = jButtonRecargarInformacionTipoBien;
}
public JButton getjButtonProcesarInformacionTipoBien() {
return this.jButtonProcesarInformacionTipoBien;
}
public void setjButtonProcesarInformacion(JButton jButtonProcesarInformacionTipoBien) {
this.jButtonProcesarInformacionTipoBien = jButtonProcesarInformacionTipoBien;
}
public JButton getjButtonRecargarInformacionTipoBien() {
return this.jButtonRecargarInformacionTipoBien;
}
public List<TipoBien> gettipobiens() {
return this.tipobiens;
}
public void settipobiens(List<TipoBien> tipobiens) {
this.tipobiens = tipobiens;
}
public List<TipoBien> gettipobiensAux() {
return this.tipobiensAux;
}
public void settipobiensAux(List<TipoBien> tipobiensAux) {
this.tipobiensAux = tipobiensAux;
}
public List<TipoBien> gettipobiensEliminados() {
return this.tipobiensEliminados;
}
public void setTipoBiensEliminados(List<TipoBien> tipobiensEliminados) {
this.tipobiensEliminados = tipobiensEliminados;
}
@SuppressWarnings("rawtypes")
public JComboBox getjComboBoxTiposSeleccionarTipoBien() {
return jComboBoxTiposSeleccionarTipoBien;
}
@SuppressWarnings("rawtypes")
public void setjComboBoxTiposSeleccionarTipoBien(
JComboBox jComboBoxTiposSeleccionarTipoBien) {
this.jComboBoxTiposSeleccionarTipoBien = jComboBoxTiposSeleccionarTipoBien;
}
public void setBorderResaltarTiposSeleccionarTipoBien() {
Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
this.jTtoolBarTipoBien.setBorder(borderResaltar);
this.jComboBoxTiposSeleccionarTipoBien .setBorder(borderResaltar);
}
public JTextField getjTextFieldValorCampoGeneralTipoBien() {
return jTextFieldValorCampoGeneralTipoBien;
}
public void setjTextFieldValorCampoGeneralTipoBien(
JTextField jTextFieldValorCampoGeneralTipoBien) {
this.jTextFieldValorCampoGeneralTipoBien = jTextFieldValorCampoGeneralTipoBien;
}
public void setBorderResaltarValorCampoGeneralTipoBien() {
Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
this.jTtoolBarTipoBien.setBorder(borderResaltar);
this.jTextFieldValorCampoGeneralTipoBien .setBorder(borderResaltar);
}
public JCheckBox getjCheckBoxSeleccionarTodosTipoBien() {
return this.jCheckBoxSeleccionarTodosTipoBien;
}
public void setjCheckBoxSeleccionarTodosTipoBien(
JCheckBox jCheckBoxSeleccionarTodosTipoBien) {
this.jCheckBoxSeleccionarTodosTipoBien = jCheckBoxSeleccionarTodosTipoBien;
}
public void setBorderResaltarSeleccionarTodosTipoBien() {
Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
this.jTtoolBarTipoBien.setBorder(borderResaltar);
this.jCheckBoxSeleccionarTodosTipoBien .setBorder(borderResaltar);
}
public JCheckBox getjCheckBoxSeleccionadosTipoBien() {
return this.jCheckBoxSeleccionadosTipoBien;
}
public void setjCheckBoxSeleccionadosTipoBien(
JCheckBox jCheckBoxSeleccionadosTipoBien) {
this.jCheckBoxSeleccionadosTipoBien = jCheckBoxSeleccionadosTipoBien;
}
public void setBorderResaltarSeleccionadosTipoBien() {
Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
this.jTtoolBarTipoBien.setBorder(borderResaltar);
this.jCheckBoxSeleccionadosTipoBien .setBorder(borderResaltar);
}
@SuppressWarnings("rawtypes")
public JComboBox getjComboBoxTiposArchivosReportesTipoBien() {
return this.jComboBoxTiposArchivosReportesTipoBien;
}
@SuppressWarnings("rawtypes")
public void setjComboBoxTiposArchivosReportesTipoBien(
JComboBox jComboBoxTiposArchivosReportesTipoBien) {
this.jComboBoxTiposArchivosReportesTipoBien = jComboBoxTiposArchivosReportesTipoBien;
}
public void setBorderResaltarTiposArchivosReportesTipoBien() {
Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
this.jTtoolBarTipoBien.setBorder(borderResaltar);
this.jComboBoxTiposArchivosReportesTipoBien .setBorder(borderResaltar);
}
@SuppressWarnings("rawtypes")
public JComboBox getjComboBoxTiposReportesTipoBien() {
return this.jComboBoxTiposReportesTipoBien;
}
@SuppressWarnings("rawtypes")
public void setjComboBoxTiposReportesTipoBien(
JComboBox jComboBoxTiposReportesTipoBien) {
this.jComboBoxTiposReportesTipoBien = jComboBoxTiposReportesTipoBien;
}
//@SuppressWarnings("rawtypes")
//public JComboBox getjComboBoxTiposReportesDinamicoTipoBien() {
// return jComboBoxTiposReportesDinamicoTipoBien;
//}
//@SuppressWarnings("rawtypes")
//public void setjComboBoxTiposReportesDinamicoTipoBien(
// JComboBox jComboBoxTiposReportesDinamicoTipoBien) {
// this.jComboBoxTiposReportesDinamicoTipoBien = jComboBoxTiposReportesDinamicoTipoBien;
//}
//@SuppressWarnings("rawtypes")
//public JComboBox getjComboBoxTiposArchivosReportesDinamicoTipoBien() {
// return jComboBoxTiposArchivosReportesDinamicoTipoBien;
//}
//@SuppressWarnings("rawtypes")
//public void setjComboBoxTiposArchivosReportesDinamicoTipoBien(
// JComboBox jComboBoxTiposArchivosReportesDinamicoTipoBien) {
// this.jComboBoxTiposArchivosReportesDinamicoTipoBien = jComboBoxTiposArchivosReportesDinamicoTipoBien;
//}
public void setBorderResaltarTiposReportesTipoBien() {
Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
this.jTtoolBarTipoBien.setBorder(borderResaltar);
this.jComboBoxTiposReportesTipoBien .setBorder(borderResaltar);
}
@SuppressWarnings("rawtypes")
public JComboBox getjComboBoxTiposGraficosReportesTipoBien() {
return this.jComboBoxTiposGraficosReportesTipoBien;
}
@SuppressWarnings("rawtypes")
public void setjComboBoxTiposGraficosReportesTipoBien(
JComboBox jComboBoxTiposGraficosReportesTipoBien) {
this.jComboBoxTiposGraficosReportesTipoBien = jComboBoxTiposGraficosReportesTipoBien;
}
public void setBorderResaltarTiposGraficosReportesTipoBien() {
Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
this.jTtoolBarTipoBien.setBorder(borderResaltar);
this.jComboBoxTiposGraficosReportesTipoBien .setBorder(borderResaltar);
}
@SuppressWarnings("rawtypes")
public JComboBox getjComboBoxTiposPaginacionTipoBien() {
return this.jComboBoxTiposPaginacionTipoBien;
}
@SuppressWarnings("rawtypes")
public void setjComboBoxTiposPaginacionTipoBien(
JComboBox jComboBoxTiposPaginacionTipoBien) {
this.jComboBoxTiposPaginacionTipoBien = jComboBoxTiposPaginacionTipoBien;
}
public void setBorderResaltarTiposPaginacionTipoBien() {
Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
this.jTtoolBarTipoBien.setBorder(borderResaltar);
this.jComboBoxTiposPaginacionTipoBien .setBorder(borderResaltar);
}
@SuppressWarnings("rawtypes")
public JComboBox getjComboBoxTiposRelacionesTipoBien() {
return this.jComboBoxTiposRelacionesTipoBien;
}
@SuppressWarnings("rawtypes")
public JComboBox getjComboBoxTiposAccionesTipoBien() {
return this.jComboBoxTiposAccionesTipoBien;
}
@SuppressWarnings("rawtypes")
public void setjComboBoxTiposRelacionesTipoBien(
JComboBox jComboBoxTiposRelacionesTipoBien) {
this.jComboBoxTiposRelacionesTipoBien = jComboBoxTiposRelacionesTipoBien;
}
@SuppressWarnings("rawtypes")
public void setjComboBoxTiposAccionesTipoBien(
JComboBox jComboBoxTiposAccionesTipoBien) {
this.jComboBoxTiposAccionesTipoBien = jComboBoxTiposAccionesTipoBien;
}
public void setBorderResaltarTiposRelacionesTipoBien() {
Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
this.jTtoolBarTipoBien.setBorder(borderResaltar);
this.jComboBoxTiposRelacionesTipoBien .setBorder(borderResaltar);
}
public void setBorderResaltarTiposAccionesTipoBien() {
Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
this.jTtoolBarTipoBien.setBorder(borderResaltar);
this.jComboBoxTiposAccionesTipoBien .setBorder(borderResaltar);
}
//public JCheckBox getjCheckBoxConGraficoDinamicoTipoBien() {
// return jCheckBoxConGraficoDinamicoTipoBien;
//}
//public void setjCheckBoxConGraficoDinamicoTipoBien(
// JCheckBox jCheckBoxConGraficoDinamicoTipoBien) {
// this.jCheckBoxConGraficoDinamicoTipoBien = jCheckBoxConGraficoDinamicoTipoBien;
//}
//public void setBorderResaltarConGraficoDinamicoTipoBien() {
// Border borderResaltar=Funciones2.getBorderResaltar(this.getParametroGeneralUsuario(),"PARAMETRO");
// this.jTtoolBarTipoBien.setBorder(borderResaltar);
// this.jCheckBoxConGraficoDinamicoTipoBien .setBorder(borderResaltar);
//}
/*
public JDesktopPane getJDesktopPane() {
return jDesktopPane;
}
public void setJDesktopPane(JDesktopPane desktopPane) {
jDesktopPane = desktopPane;
}
*/
private void initialize(JDesktopPane jdesktopPane,Boolean conGuardarRelaciones,Boolean esGuardarRelacionado,Boolean cargarRelaciones,Usuario usuarioActual,ResumenUsuario resumenUsuarioActual,Modulo moduloActual,Opcion opcionActual,ParametroGeneralSg parametroGeneralSg,ParametroGeneralUsuario parametroGeneralUsuario,PaginaTipo paginaTipo) throws Exception {
this.tipobienSessionBean=new TipoBienSessionBean();
this.tipobienSessionBean.setConGuardarRelaciones(conGuardarRelaciones);
this.tipobienSessionBean.setEsGuardarRelacionado(esGuardarRelacionado);
this.conCargarMinimo=this.tipobienSessionBean.getEsGuardarRelacionado();
this.cargarRelaciones=cargarRelaciones;
if(!this.conCargarMinimo) {
}
//this.sTipoTamanioGeneral=TipoBienJInternalFrame.STIPO_TAMANIO_GENERAL;
//this.sTipoTamanioGeneralTabla=TipoBienJInternalFrame.STIPO_TAMANIO_GENERAL_TABLA;
this.sTipoTamanioGeneral=FuncionesSwing.getTipoTamanioGeneral(this,parametroGeneralUsuario,conGuardarRelaciones,esGuardarRelacionado);
this.sTipoTamanioGeneralTabla=FuncionesSwing.getTipoTamanioGeneralTabla(this,parametroGeneralUsuario,conGuardarRelaciones,esGuardarRelacionado);
this.conTipoTamanioManual=FuncionesSwing.getConTipoTamanioManual(this,parametroGeneralUsuario,conGuardarRelaciones,esGuardarRelacionado);
this.conTipoTamanioTodo=FuncionesSwing.getConTipoTamanioTodo(this,parametroGeneralUsuario,conGuardarRelaciones,esGuardarRelacionado);
TipoBienJInternalFrame.STIPO_TAMANIO_GENERAL=this.sTipoTamanioGeneral;
TipoBienJInternalFrame.STIPO_TAMANIO_GENERAL_TABLA=this.sTipoTamanioGeneralTabla;
TipoBienJInternalFrame.CONTIPO_TAMANIO_MANUAL=this.conTipoTamanioManual;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int iWidth=(screenSize.width-screenSize.width/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ANCHO);
int iHeight=(screenSize.height-screenSize.height/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ALTO);
//this.setTitle(Funciones.GetTituloSistema(this.parametroGeneralSg,this.moduloActual,this.opcionActual,this.usuarioActual,"Tipo Bien MANTENIMIENTO"));
if(iWidth > 650) {
iWidth=650;
}
if(iHeight > 1110) {
iHeight=1110;
}
this.setSize(iWidth,iHeight);
this.setFrameIcon(new ImageIcon(FuncionesSwing.getImagenBackground(Constantes2.S_ICON_IMAGE)));
this.setContentPane(this.getJContentPane(iWidth,iHeight,jdesktopPane,cargarRelaciones,usuarioActual,resumenUsuarioActual,moduloActual,opcionActual,parametroGeneralSg,parametroGeneralUsuario,paginaTipo));
if(!this.tipobienSessionBean.getEsGuardarRelacionado()) {
this.setResizable(true);
this.setClosable(true);
this.setMaximizable(true);
this.iconable=true;
setLocation(xOffset*openFrameCount, yOffset*openFrameCount);
if(Constantes.CON_VARIAS_VENTANAS) {
openFrameCount++;
if(openFrameCount==Constantes.INUM_MAX_VENTANAS) {
openFrameCount=0;
}
}
}
TipoBienJInternalFrame.ESTA_CARGADO_PORPARTE=true;
//super("TipoBien No " + (++openFrameCount),true, /*resizable*/true, /*closable*/true, /*maximizable*/true);//iconifiable
//SwingUtilities.updateComponentTreeUI(this);
}
public void inicializarToolBar() {
this.jTtoolBarTipoBien= new JToolBar("MENU PRINCIPAL");
//TOOLBAR
//PRINCIPAL
this.jButtonNuevoToolBarTipoBien=FuncionesSwing.getButtonToolBarGeneral(this.jButtonNuevoToolBarTipoBien,this.jTtoolBarTipoBien,
"nuevo","nuevo","Nuevo"+" "+TipoBienConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("NUEVO"),"Nuevo",false);
this.jButtonNuevoGuardarCambiosToolBarTipoBien=FuncionesSwing.getButtonToolBarGeneral(this.jButtonNuevoGuardarCambiosToolBarTipoBien,this.jTtoolBarTipoBien,
"nuevoguardarcambios","nuevoguardarcambios","Nuevo" + FuncionesSwing.getKeyMensaje("NUEVO_TABLA"),"Nuevo",false);
this.jButtonGuardarCambiosTablaToolBarTipoBien=FuncionesSwing.getButtonToolBarGeneral(this.jButtonGuardarCambiosTablaToolBarTipoBien,this.jTtoolBarTipoBien,
"guardarcambiostabla","guardarcambiostabla","Guardar"+" "+TipoBienConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("GUARDAR_CAMBIOS"),"Guardar",false);
this.jButtonDuplicarToolBarTipoBien=FuncionesSwing.getButtonToolBarGeneral(this.jButtonDuplicarToolBarTipoBien,this.jTtoolBarTipoBien,
"duplicar","duplicar","Duplicar"+" "+TipoBienConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("DUPLICAR"),"Duplicar",false);
this.jButtonCopiarToolBarTipoBien=FuncionesSwing.getButtonToolBarGeneral(this.jButtonCopiarToolBarTipoBien,this.jTtoolBarTipoBien,
"copiar","copiar","Copiar"+" "+TipoBienConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("COPIAR"),"Copiar",false);
this.jButtonVerFormToolBarTipoBien=FuncionesSwing.getButtonToolBarGeneral(this.jButtonVerFormToolBarTipoBien,this.jTtoolBarTipoBien,
"ver_form","ver_form","Ver"+" "+TipoBienConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("VER_FORM"),"Ver",false);
this.jButtonRecargarInformacionToolBarTipoBien=FuncionesSwing.getButtonToolBarGeneral(this.jButtonRecargarInformacionToolBarTipoBien,this.jTtoolBarTipoBien,
"recargar","recargar","Recargar"+" "+TipoBienConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("RECARGAR"),"Recargar",false);
this.jButtonAnterioresToolBarTipoBien=FuncionesSwing.getButtonToolBarGeneral(this.jButtonRecargarInformacionToolBarTipoBien,this.jTtoolBarTipoBien,
"anteriores","anteriores","Anteriores Datos" + FuncionesSwing.getKeyMensaje("ANTERIORES"),"<<",false);
this.jButtonSiguientesToolBarTipoBien=FuncionesSwing.getButtonToolBarGeneral(this.jButtonRecargarInformacionToolBarTipoBien,this.jTtoolBarTipoBien,
"siguientes","siguientes","Siguientes Datos" + FuncionesSwing.getKeyMensaje("SIGUIENTES"),">>",false);
this.jButtonAbrirOrderByToolBarTipoBien=FuncionesSwing.getButtonToolBarGeneral(this.jButtonAbrirOrderByToolBarTipoBien,this.jTtoolBarTipoBien,
"orden","orden","Orden" + FuncionesSwing.getKeyMensaje("ORDEN"),"Orden",false);
this.jButtonNuevoRelacionesToolBarTipoBien=FuncionesSwing.getButtonToolBarGeneral(this.jButtonNuevoRelacionesToolBarTipoBien,this.jTtoolBarTipoBien,
"nuevo_relaciones","nuevo_relaciones","NUEVO RELACIONES" + FuncionesSwing.getKeyMensaje("NUEVO_RELACIONES"),"NUEVO RELACIONES",false);
this.jButtonMostrarOcultarTablaToolBarTipoBien=FuncionesSwing.getButtonToolBarGeneral(this.jButtonMostrarOcultarTablaToolBarTipoBien,this.jTtoolBarTipoBien,
"mostrar_ocultar","mostrar_ocultar","Mostrar Ocultar"+" "+TipoBienConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("MOSTRAR_OCULTAR"),"Mostrar Ocultar",false);
this.jButtonCerrarToolBarTipoBien=FuncionesSwing.getButtonToolBarGeneral(this.jButtonCerrarToolBarTipoBien,this.jTtoolBarTipoBien,
"cerrar","cerrar","Salir"+" "+TipoBienConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("CERRAR"),"Salir",false);
//this.jButtonNuevoRelacionesToolBarTipoBien=new JButtonMe();
//protected JButton jButtonNuevoRelacionesToolBarTipoBien;
this.jButtonProcesarInformacionToolBarTipoBien=new JButtonMe();
//protected JButton jButtonProcesarInformacionToolBarTipoBien;
//protected JButton jButtonModificarToolBarTipoBien;
//PRINCIPAL
//DETALLE
//DETALLE_FIN
}
public void cargarMenus() {
this.jmenuBarTipoBien=new JMenuBarMe();
//PRINCIPAL
this.jmenuTipoBien=new JMenuMe("General");
this.jmenuArchivoTipoBien=new JMenuMe("Archivo");
this.jmenuAccionesTipoBien=new JMenuMe("Acciones");
this.jmenuDatosTipoBien=new JMenuMe("Datos");
//PRINCIPAL_FIN
//DETALLE
//DETALLE_FIN
this.jMenuItemNuevoTipoBien= new JMenuItem("Nuevo" + FuncionesSwing.getKeyMensaje("NUEVO"));
this.jMenuItemNuevoTipoBien.setActionCommand("Nuevo");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemNuevoTipoBien,"nuevo_button","Nuevo");
FuncionesSwing.setBoldMenuItem(this.jMenuItemNuevoTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemDuplicarTipoBien= new JMenuItem("Duplicar" + FuncionesSwing.getKeyMensaje("DUPLICAR"));
this.jMenuItemDuplicarTipoBien.setActionCommand("Duplicar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemDuplicarTipoBien,"duplicar_button","Duplicar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemDuplicarTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemNuevoRelacionesTipoBien= new JMenuItem("Nuevo Rel" + FuncionesSwing.getKeyMensaje("NUEVO_TABLA"));
this.jMenuItemNuevoRelacionesTipoBien.setActionCommand("Nuevo Rel");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemNuevoRelacionesTipoBien,"nuevorelaciones_button","Nuevo Rel");
FuncionesSwing.setBoldMenuItem(this.jMenuItemNuevoRelacionesTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemGuardarCambiosTipoBien= new JMenuItem("Guardar" + FuncionesSwing.getKeyMensaje("GUARDAR_CAMBIOS"));
this.jMenuItemGuardarCambiosTipoBien.setActionCommand("Guardar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemGuardarCambiosTipoBien,"guardarcambios_button","Guardar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemGuardarCambiosTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemCopiarTipoBien= new JMenuItem("Copiar" + FuncionesSwing.getKeyMensaje("COPIAR"));
this.jMenuItemCopiarTipoBien.setActionCommand("Copiar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemCopiarTipoBien,"copiar_button","Copiar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemCopiarTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemVerFormTipoBien= new JMenuItem("Ver" + FuncionesSwing.getKeyMensaje("VER_FORM"));
this.jMenuItemVerFormTipoBien.setActionCommand("Ver");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemVerFormTipoBien,"ver_form_button","Ver");
FuncionesSwing.setBoldMenuItem(this.jMenuItemVerFormTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemGuardarCambiosTablaTipoBien= new JMenuItem("Guardar Tabla" + FuncionesSwing.getKeyMensaje("GUARDAR_CAMBIOS"));
this.jMenuItemGuardarCambiosTablaTipoBien.setActionCommand("Guardar Tabla");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemGuardarCambiosTablaTipoBien,"guardarcambiostabla_button","Guardar Tabla");
FuncionesSwing.setBoldMenuItem(this.jMenuItemGuardarCambiosTablaTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemCerrarTipoBien= new JMenuItem("Salir" + FuncionesSwing.getKeyMensaje("CERRAR"));
this.jMenuItemCerrarTipoBien.setActionCommand("Cerrar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemCerrarTipoBien,"cerrar_button","Salir");
FuncionesSwing.setBoldMenuItem(this.jMenuItemCerrarTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemRecargarInformacionTipoBien= new JMenuItem("Recargar" + FuncionesSwing.getKeyMensaje("RECARGAR"));
this.jMenuItemRecargarInformacionTipoBien.setActionCommand("Recargar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemRecargarInformacionTipoBien,"recargar_button","Recargar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemRecargarInformacionTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemProcesarInformacionTipoBien= new JMenuItem("Procesar Informacion");
this.jMenuItemProcesarInformacionTipoBien.setActionCommand("Procesar Informacion");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemProcesarInformacionTipoBien,"procesar_button","Procesar Informacion");
this.jMenuItemAnterioresTipoBien= new JMenuItem("Anteriores" + FuncionesSwing.getKeyMensaje("ANTERIORES"));
this.jMenuItemAnterioresTipoBien.setActionCommand("Anteriores");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemAnterioresTipoBien,"anteriores_button","Anteriores");
FuncionesSwing.setBoldMenuItem(this.jMenuItemAnterioresTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemSiguientesTipoBien= new JMenuItem("Siguientes" + FuncionesSwing.getKeyMensaje("SIGUIENTES"));
this.jMenuItemSiguientesTipoBien.setActionCommand("Siguientes");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemSiguientesTipoBien,"siguientes_button","Siguientes");
FuncionesSwing.setBoldMenuItem(this.jMenuItemSiguientesTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemAbrirOrderByTipoBien= new JMenuItem("Orden" + FuncionesSwing.getKeyMensaje("ORDEN"));
this.jMenuItemAbrirOrderByTipoBien.setActionCommand("Orden");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemAbrirOrderByTipoBien,"orden_button","Orden");
FuncionesSwing.setBoldMenuItem(this.jMenuItemAbrirOrderByTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemMostrarOcultarTipoBien= new JMenuItem("Mostrar Ocultar" + FuncionesSwing.getKeyMensaje("MOSTRAR_OCULTAR"));
this.jMenuItemMostrarOcultarTipoBien.setActionCommand("Mostrar Ocultar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemMostrarOcultarTipoBien,"mostrar_ocultar_button","Mostrar Ocultar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemMostrarOcultarTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemDetalleAbrirOrderByTipoBien= new JMenuItem("Orden" + FuncionesSwing.getKeyMensaje("ORDEN"));
this.jMenuItemDetalleAbrirOrderByTipoBien.setActionCommand("Orden");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemDetalleAbrirOrderByTipoBien,"orden_button","Orden");
FuncionesSwing.setBoldMenuItem(this.jMenuItemDetalleAbrirOrderByTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemDetalleMostarOcultarTipoBien= new JMenuItem("Mostrar Ocultar" + FuncionesSwing.getKeyMensaje("MOSTRAR_OCULTAR"));
this.jMenuItemDetalleMostarOcultarTipoBien.setActionCommand("Mostrar Ocultar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemDetalleMostarOcultarTipoBien,"mostrar_ocultar_button","Mostrar Ocultar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemDetalleMostarOcultarTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemNuevoGuardarCambiosTipoBien= new JMenuItem("Nuevo Tabla" + FuncionesSwing.getKeyMensaje("NUEVO_TABLA"));
this.jMenuItemNuevoGuardarCambiosTipoBien.setActionCommand("Nuevo Tabla");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemNuevoGuardarCambiosTipoBien,"nuevoguardarcambios_button","Nuevo");
FuncionesSwing.setBoldMenuItem(this.jMenuItemNuevoGuardarCambiosTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);
//PRINCIPAL
if(!this.conCargarMinimo) {
this.jmenuArchivoTipoBien.add(this.jMenuItemCerrarTipoBien);
this.jmenuAccionesTipoBien.add(this.jMenuItemNuevoTipoBien);
this.jmenuAccionesTipoBien.add(this.jMenuItemNuevoGuardarCambiosTipoBien);
this.jmenuAccionesTipoBien.add(this.jMenuItemNuevoRelacionesTipoBien);
this.jmenuAccionesTipoBien.add(this.jMenuItemGuardarCambiosTablaTipoBien);
this.jmenuAccionesTipoBien.add(this.jMenuItemDuplicarTipoBien);
this.jmenuAccionesTipoBien.add(this.jMenuItemCopiarTipoBien);
this.jmenuAccionesTipoBien.add(this.jMenuItemVerFormTipoBien);
this.jmenuDatosTipoBien.add(this.jMenuItemRecargarInformacionTipoBien);
this.jmenuDatosTipoBien.add(this.jMenuItemAnterioresTipoBien);
this.jmenuDatosTipoBien.add(this.jMenuItemSiguientesTipoBien);
this.jmenuDatosTipoBien.add(this.jMenuItemAbrirOrderByTipoBien);
this.jmenuDatosTipoBien.add(this.jMenuItemMostrarOcultarTipoBien);
}
//PRINCIPAL_FIN
//DETALLE
//this.jmenuDetalleAccionesTipoBien.add(this.jMenuItemGuardarCambiosTipoBien);
//DETALLE_FIN
//RELACIONES
//RELACIONES
//PRINCIPAL
if(!this.conCargarMinimo) {
FuncionesSwing.setBoldMenu(this.jmenuArchivoTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldMenu(this.jmenuAccionesTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldMenu(this.jmenuDatosTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);
this.jmenuBarTipoBien.add(this.jmenuArchivoTipoBien);
this.jmenuBarTipoBien.add(this.jmenuAccionesTipoBien);
this.jmenuBarTipoBien.add(this.jmenuDatosTipoBien);
}
//PRINCIPAL_FIN
//DETALLE
//DETALLE_FIN
//AGREGA MENU A PANTALLA
if(!this.conCargarMinimo) {
this.setJMenuBar(this.jmenuBarTipoBien);
}
//AGREGA MENU DETALLE A PANTALLA
}
public void inicializarElementosBusquedasTipoBien() {
//BYDAN_BUSQUEDAS
//INDICES BUSQUEDA
this.jTabbedPaneBusquedasTipoBien=new JTabbedPane();
this.jTabbedPaneBusquedasTipoBien.setMinimumSize(new Dimension(this.getWidth(),Constantes.ISWING_ALTO_TABPANE_BUSQUEDA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_TABPANE_BUSQUEDA,25)));
this.jTabbedPaneBusquedasTipoBien.setMaximumSize(new Dimension(this.getWidth(),Constantes.ISWING_ALTO_TABPANE_BUSQUEDA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_TABPANE_BUSQUEDA,25)));
this.jTabbedPaneBusquedasTipoBien.setPreferredSize(new Dimension(this.getWidth(),Constantes.ISWING_ALTO_TABPANE_BUSQUEDA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_TABPANE_BUSQUEDA,25)));
//this.jTabbedPaneBusquedasTipoBien.setBorder(javax.swing.BorderFactory.createTitledBorder("Busqueda"));
this.jTabbedPaneBusquedasTipoBien.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
FuncionesSwing.setBoldTabbedPane(this.jTabbedPaneBusquedasTipoBien,STIPO_TAMANIO_GENERAL,false,true,this);
//INDICES BUSQUEDA_FIN
}
//JPanel
//@SuppressWarnings({"unchecked" })//"rawtypes"
public JScrollPane getJContentPane(int iWidth,int iHeight,JDesktopPane jDesktopPane,Boolean cargarRelaciones,Usuario usuarioActual,ResumenUsuario resumenUsuarioActual,Modulo moduloActual,Opcion opcionActual,ParametroGeneralSg parametroGeneralSg,ParametroGeneralUsuario parametroGeneralUsuario,PaginaTipo paginaTipo) throws Exception {
//PARA TABLA PARAMETROS
String sKeyStrokeName="";
KeyStroke keyStrokeControl=null;
this.jContentPane = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
this.usuarioActual=usuarioActual;
this.resumenUsuarioActual=resumenUsuarioActual;
this.opcionActual=opcionActual;
this.moduloActual=moduloActual;
this.parametroGeneralSg=parametroGeneralSg;
this.parametroGeneralUsuario=parametroGeneralUsuario;
this.jDesktopPane=jDesktopPane;
this.conFuncionalidadRelaciones=parametroGeneralUsuario.getcon_guardar_relaciones();
int iGridyPrincipal=0;
this.inicializarToolBar();
//CARGAR MENUS
if(this.conCargarFormDetalle) { //true) {
//this.jInternalFrameDetalleTipoBien = new TipoBienDetalleJInternalFrame(paginaTipo);//JInternalFrameBase("Tipo Bien DATOS");
this.jInternalFrameDetalleFormTipoBien = new TipoBienDetalleFormJInternalFrame(jDesktopPane,this.tipobienSessionBean.getConGuardarRelaciones(),this.tipobienSessionBean.getEsGuardarRelacionado(),cargarRelaciones,usuarioActual,resumenUsuarioActual,moduloActual,opcionActual,parametroGeneralSg,parametroGeneralUsuario,paginaTipo);
} else {
this.jInternalFrameDetalleFormTipoBien = null;//new TipoBienDetalleFormJInternalFrame("MINIMO");
}
this.cargarMenus();
this.gridaBagLayoutTipoBien= new GridBagLayout();
this.jTableDatosTipoBien = new JTableMe();
String sToolTipTipoBien="";
sToolTipTipoBien=TipoBienConstantesFunciones.SCLASSWEBTITULO;
if(Constantes.ISDEVELOPING) {
sToolTipTipoBien+="(Cartera.TipoBien)";
}
if(!this.tipobienSessionBean.getEsGuardarRelacionado()) {
sToolTipTipoBien+="_"+this.opcionActual.getId();
}
this.jTableDatosTipoBien.setToolTipText(sToolTipTipoBien);
//SE DEFINE EN DETALLE
//FuncionesSwing.setBoldLabelTable(this.jTableDatosTipoBien);
this.jTableDatosTipoBien.setAutoCreateRowSorter(true);
this.jTableDatosTipoBien.setRowHeight(Constantes.ISWING_ALTO_FILA_TABLA + Constantes.ISWING_ALTO_FILA_TABLA_EXTRA_FECHA);
//MULTIPLE SELECTION
this.jTableDatosTipoBien.setRowSelectionAllowed(true);
this.jTableDatosTipoBien.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
FuncionesSwing.setBoldTable(jTableDatosTipoBien,STIPO_TAMANIO_GENERAL,false,true,this);
this.jButtonNuevoTipoBien = new JButtonMe();
this.jButtonDuplicarTipoBien = new JButtonMe();
this.jButtonCopiarTipoBien = new JButtonMe();
this.jButtonVerFormTipoBien = new JButtonMe();
this.jButtonNuevoRelacionesTipoBien = new JButtonMe();
this.jButtonGuardarCambiosTablaTipoBien = new JButtonMe();
this.jButtonCerrarTipoBien = new JButtonMe();
this.jScrollPanelDatosTipoBien = new JScrollPane();
this.jScrollPanelDatosGeneralTipoBien = new JScrollPane();
this.jPanelAccionesTipoBien = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);
//if(!this.conCargarMinimo) {
;
//}
this.sPath=" <---> Acceso: Tipo Bien";
if(!this.tipobienSessionBean.getEsGuardarRelacionado()) {
this.jScrollPanelDatosTipoBien.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos Tipo Bienes" + this.sPath));
} else {
this.jScrollPanelDatosTipoBien.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
}
this.jScrollPanelDatosGeneralTipoBien.setBorder(javax.swing.BorderFactory.createTitledBorder("Edicion Datos"));
this.jPanelAccionesTipoBien.setBorder(javax.swing.BorderFactory.createTitledBorder("Acciones"));
this.jPanelAccionesTipoBien.setToolTipText("Acciones");
this.jPanelAccionesTipoBien.setName("Acciones");
FuncionesSwing.setBoldScrollPanel(this.jScrollPanelDatosGeneralTipoBien, STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldScrollPanel(this.jScrollPanelDatosTipoBien, STIPO_TAMANIO_GENERAL,false,false,this);
//if(!this.conCargarMinimo) {
;
//}
//ELEMENTOS TABLAS PARAMETOS
if(!this.conCargarMinimo) {
}
//ELEMENTOS TABLAS PARAMETOS_FIN
if(!this.conCargarMinimo) {
//REPORTE DINAMICO
//NO CARGAR INICIALMENTE, EN BOTON AL ABRIR
//this.jInternalFrameReporteDinamicoTipoBien=new ReporteDinamicoJInternalFrame(TipoBienConstantesFunciones.SCLASSWEBTITULO,this);
//this.cargarReporteDinamicoTipoBien();
//IMPORTACION
//NO CARGAR INICIALMENTE, EN BOTON AL ABRIR
//this.jInternalFrameImportacionTipoBien=new ImportacionJInternalFrame(TipoBienConstantesFunciones.SCLASSWEBTITULO,this);
//this.cargarImportacionTipoBien();
}
String sMapKey = "";
InputMap inputMap =null;
this.jButtonAbrirOrderByTipoBien = new JButtonMe();
this.jButtonAbrirOrderByTipoBien.setText("Orden");
this.jButtonAbrirOrderByTipoBien.setToolTipText("Orden"+FuncionesSwing.getKeyMensaje("ORDEN"));
FuncionesSwing.addImagenButtonGeneral(this.jButtonAbrirOrderByTipoBien,"orden_button","Orden");
FuncionesSwing.setBoldButton(this.jButtonAbrirOrderByTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);;
sMapKey = "AbrirOrderBySistema";
inputMap = this.jButtonAbrirOrderByTipoBien.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("ORDEN") , FuncionesSwing.getMaskKey("ORDEN")), sMapKey);
this.jButtonAbrirOrderByTipoBien.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"AbrirOrderBySistema"));
if(!this.conCargarMinimo) {
//NO CARGAR INICIALMENTE, EN BOTON AL ABRIR
//this.jInternalFrameOrderByTipoBien=new OrderByJInternalFrame(STIPO_TAMANIO_GENERAL,this.jButtonAbrirOrderByTipoBien,false,this);
//this.cargarOrderByTipoBien(false);
} else {
//NO CARGAR INICIALMENTE, EN BOTON AL ABRIR
//this.jInternalFrameOrderByTipoBien=new OrderByJInternalFrame(STIPO_TAMANIO_GENERAL,this.jButtonAbrirOrderByTipoBien,true,this);
//this.cargarOrderByTipoBien(true);
}
//VALORES PARA DISENO
/*
this.jTableDatosTipoBien.setMinimumSize(new Dimension(400,50));//430
this.jTableDatosTipoBien.setMaximumSize(new Dimension(400,50));//430
this.jTableDatosTipoBien.setPreferredSize(new Dimension(400,50));//430
this.jScrollPanelDatosTipoBien.setMinimumSize(new Dimension(400,50));
this.jScrollPanelDatosTipoBien.setMaximumSize(new Dimension(400,50));
this.jScrollPanelDatosTipoBien.setPreferredSize(new Dimension(400,50));
*/
this.jButtonNuevoTipoBien.setText("Nuevo");
this.jButtonDuplicarTipoBien.setText("Duplicar");
this.jButtonCopiarTipoBien.setText("Copiar");
this.jButtonVerFormTipoBien.setText("Ver");
this.jButtonNuevoRelacionesTipoBien.setText("Nuevo Rel");
this.jButtonGuardarCambiosTablaTipoBien.setText("Guardar");
this.jButtonCerrarTipoBien.setText("Salir");
FuncionesSwing.addImagenButtonGeneral(this.jButtonNuevoTipoBien,"nuevo_button","Nuevo",this.tipobienSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonDuplicarTipoBien,"duplicar_button","Duplicar",this.tipobienSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonCopiarTipoBien,"copiar_button","Copiar",this.tipobienSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonVerFormTipoBien,"ver_form","Ver",this.tipobienSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonNuevoRelacionesTipoBien,"nuevorelaciones_button","Nuevo Rel",this.tipobienSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonGuardarCambiosTablaTipoBien,"guardarcambiostabla_button","Guardar",this.tipobienSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonCerrarTipoBien,"cerrar_button","Salir",this.tipobienSessionBean.getEsGuardarRelacionado());
FuncionesSwing.setBoldButton(this.jButtonNuevoTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonDuplicarTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonCopiarTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonVerFormTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonNuevoRelacionesTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonGuardarCambiosTablaTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonCerrarTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);
this.jButtonNuevoTipoBien.setToolTipText("Nuevo"+" "+TipoBienConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("NUEVO"));
this.jButtonDuplicarTipoBien.setToolTipText("Duplicar"+" "+TipoBienConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("DUPLICAR"));
this.jButtonCopiarTipoBien.setToolTipText("Copiar"+" "+TipoBienConstantesFunciones.SCLASSWEBTITULO+ FuncionesSwing.getKeyMensaje("COPIAR"));
this.jButtonVerFormTipoBien.setToolTipText("Ver"+" "+TipoBienConstantesFunciones.SCLASSWEBTITULO+ FuncionesSwing.getKeyMensaje("VER_FORM"));
this.jButtonNuevoRelacionesTipoBien.setToolTipText("Nuevo Rel"+" "+TipoBienConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("NUEVO_RELACIONES"));
this.jButtonGuardarCambiosTablaTipoBien.setToolTipText("Guardar"+" "+TipoBienConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("GUARDAR_CAMBIOS"));
this.jButtonCerrarTipoBien.setToolTipText("Salir"+" "+TipoBienConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("CERRAR"));
//HOT KEYS
/*
N->Nuevo
N->Alt + Nuevo Relaciones (ANTES R)
A->Actualizar
E->Eliminar
S->Cerrar
C->->Mayus + Cancelar (ANTES Q->Quit)
G->Guardar Cambios
D->Duplicar
C->Alt + Cop?ar
O->Orden
N->Nuevo Tabla
R->Recargar Informacion Inicial (ANTES I)
Alt + Pag.Down->Siguientes
Alt + Pag.Up->Anteriores
NO UTILIZADOS
M->Modificar
*/
//String sMapKey = "";
//InputMap inputMap =null;
//NUEVO
sMapKey = "NuevoTipoBien";
inputMap = this.jButtonNuevoTipoBien.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("NUEVO") , FuncionesSwing.getMaskKey("NUEVO")), sMapKey);
this.jButtonNuevoTipoBien.getActionMap().put(sMapKey, new ButtonAbstractAction(this,"NuevoTipoBien"));
//DUPLICAR
sMapKey = "DuplicarTipoBien";
inputMap = this.jButtonDuplicarTipoBien.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("DUPLICAR") , FuncionesSwing.getMaskKey("DUPLICAR")), sMapKey);
this.jButtonDuplicarTipoBien.getActionMap().put(sMapKey, new ButtonAbstractAction(this,"DuplicarTipoBien"));
//COPIAR
sMapKey = "CopiarTipoBien";
inputMap = this.jButtonCopiarTipoBien.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("COPIAR") , FuncionesSwing.getMaskKey("COPIAR")), sMapKey);
this.jButtonCopiarTipoBien.getActionMap().put(sMapKey, new ButtonAbstractAction(this,"CopiarTipoBien"));
//VEr FORM
sMapKey = "VerFormTipoBien";
inputMap = this.jButtonVerFormTipoBien.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("VER_FORM") , FuncionesSwing.getMaskKey("VER_FORM")), sMapKey);
this.jButtonVerFormTipoBien.getActionMap().put(sMapKey, new ButtonAbstractAction(this,"VerFormTipoBien"));
//NUEVO RELACIONES
sMapKey = "NuevoRelacionesTipoBien";
inputMap = this.jButtonNuevoRelacionesTipoBien.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("NUEVO_RELACIONES") , FuncionesSwing.getMaskKey("NUEVO_RELACIONES")), sMapKey);
this.jButtonNuevoRelacionesTipoBien.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"NuevoRelacionesTipoBien"));
//MODIFICAR
/*
sMapKey = "ModificarTipoBien";
inputMap = this.jButtonModificarTipoBien.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("MODIFICAR") , FuncionesSwing.getMaskKey("MODIFICAR")), sMapKey);
this.jButtonModificarTipoBien.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"ModificarTipoBien"));
*/
//CERRAR
sMapKey = "CerrarTipoBien";
inputMap = this.jButtonCerrarTipoBien.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("CERRAR") , FuncionesSwing.getMaskKey("CERRAR")), sMapKey);
this.jButtonCerrarTipoBien.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"CerrarTipoBien"));
//GUARDAR CAMBIOS
sMapKey = "GuardarCambiosTablaTipoBien";
inputMap = this.jButtonGuardarCambiosTablaTipoBien.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("GUARDAR_CAMBIOS") , FuncionesSwing.getMaskKey("GUARDAR_CAMBIOS")), sMapKey);
this.jButtonGuardarCambiosTablaTipoBien.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"GuardarCambiosTablaTipoBien"));
//ABRIR ORDER BY
if(!this.conCargarMinimo) {
}
//HOT KEYS
this.jPanelParametrosReportesTipoBien = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
this.jPanelParametrosReportesAccionesTipoBien = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
this.jPanelPaginacionTipoBien = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
this.jPanelParametrosAuxiliar1TipoBien= new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
this.jPanelParametrosAuxiliar2TipoBien= new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
this.jPanelParametrosAuxiliar3TipoBien= new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
this.jPanelParametrosAuxiliar4TipoBien= new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
//this.jPanelParametrosAuxiliar5TipoBien= new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
this.jPanelParametrosReportesTipoBien.setBorder(javax.swing.BorderFactory.createTitledBorder("Parametros Reportes-Acciones"));
this.jPanelParametrosReportesTipoBien.setName("jPanelParametrosReportesTipoBien");
this.jPanelParametrosReportesAccionesTipoBien.setBorder(javax.swing.BorderFactory.createTitledBorder("Parametros Acciones"));
//this.jPanelParametrosReportesAccionesTipoBien.setBorder(javax.swing.BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
this.jPanelParametrosReportesAccionesTipoBien.setName("jPanelParametrosReportesAccionesTipoBien");
FuncionesSwing.setBoldPanel(this.jPanelParametrosReportesTipoBien, STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldPanel(this.jPanelParametrosReportesAccionesTipoBien, STIPO_TAMANIO_GENERAL,false,false,this);
this.jButtonRecargarInformacionTipoBien = new JButtonMe();
this.jButtonRecargarInformacionTipoBien.setText("Recargar");
this.jButtonRecargarInformacionTipoBien.setToolTipText("Recargar"+" "+TipoBienConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("RECARGAR"));
FuncionesSwing.addImagenButtonGeneral(this.jButtonRecargarInformacionTipoBien,"recargar_button","Recargar");
this.jButtonProcesarInformacionTipoBien = new JButtonMe();
this.jButtonProcesarInformacionTipoBien.setText("Procesar");
this.jButtonProcesarInformacionTipoBien.setToolTipText("Procesar"+" "+TipoBienConstantesFunciones.SCLASSWEBTITULO);
this.jButtonProcesarInformacionTipoBien.setVisible(false);
this.jButtonProcesarInformacionTipoBien.setMinimumSize(new Dimension(185,25));
this.jButtonProcesarInformacionTipoBien.setMaximumSize(new Dimension(185,25));
this.jButtonProcesarInformacionTipoBien.setPreferredSize(new Dimension(185,25));
this.jComboBoxTiposArchivosReportesTipoBien = new JComboBoxMe();
//this.jComboBoxTiposArchivosReportesTipoBien.setText("TIPO");
this.jComboBoxTiposArchivosReportesTipoBien.setToolTipText("Tipos De Archivo");
this.jComboBoxTiposReportesTipoBien = new JComboBoxMe();
//this.jComboBoxTiposArchivosReportesTipoBien.setText("TIPO");
this.jComboBoxTiposReportesTipoBien.setToolTipText("Tipos De Reporte");
this.jComboBoxTiposGraficosReportesTipoBien = new JComboBoxMe();
//this.jComboBoxTiposArchivosReportesTipoBien.setText("TIPO");
this.jComboBoxTiposGraficosReportesTipoBien.setToolTipText("Tipos De Reporte");
this.jComboBoxTiposPaginacionTipoBien = new JComboBoxMe();
//this.jComboBoxTiposPaginacionTipoBien.setText("Paginacion");
this.jComboBoxTiposPaginacionTipoBien.setToolTipText("Tipos De Paginacion");
this.jComboBoxTiposRelacionesTipoBien = new JComboBoxMe();
//this.jComboBoxTiposRelacionesTipoBien.setText("Accion");
this.jComboBoxTiposRelacionesTipoBien.setToolTipText("Tipos de Relaciones");
this.jComboBoxTiposAccionesTipoBien = new JComboBoxMe();
//this.jComboBoxTiposAccionesTipoBien.setText("Accion");
this.jComboBoxTiposAccionesTipoBien.setToolTipText("Tipos de Acciones");
this.jComboBoxTiposSeleccionarTipoBien = new JComboBoxMe();
//this.jComboBoxTiposSeleccionarTipoBien.setText("Accion");
this.jComboBoxTiposSeleccionarTipoBien.setToolTipText("Tipos de Seleccion");
this.jTextFieldValorCampoGeneralTipoBien=new JTextFieldMe();
this.jTextFieldValorCampoGeneralTipoBien.setMinimumSize(new Dimension(100,Constantes.ISWING_ALTO_CONTROL));
this.jTextFieldValorCampoGeneralTipoBien.setMaximumSize(new Dimension(100,Constantes.ISWING_ALTO_CONTROL));
this.jTextFieldValorCampoGeneralTipoBien.setPreferredSize(new Dimension(100,Constantes.ISWING_ALTO_CONTROL));
this.jLabelAccionesTipoBien = new JLabelMe();
this.jLabelAccionesTipoBien.setText("Acciones");
this.jLabelAccionesTipoBien.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelAccionesTipoBien.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelAccionesTipoBien.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jCheckBoxSeleccionarTodosTipoBien = new JCheckBoxMe();
this.jCheckBoxSeleccionarTodosTipoBien.setText("Sel. Todos");
this.jCheckBoxSeleccionarTodosTipoBien.setToolTipText("Sel. Todos");
this.jCheckBoxSeleccionadosTipoBien = new JCheckBoxMe();
//this.jCheckBoxSeleccionadosTipoBien.setText("Seleccionados");
this.jCheckBoxSeleccionadosTipoBien.setToolTipText("SELECCIONAR SELECCIONADOS");
this.jCheckBoxConAltoMaximoTablaTipoBien = new JCheckBoxMe();
//this.jCheckBoxConAltoMaximoTablaTipoBien.setText("Con Maximo Alto Tabla");
this.jCheckBoxConAltoMaximoTablaTipoBien.setToolTipText("Con Maximo Alto Tabla");
this.jCheckBoxConGraficoReporteTipoBien = new JCheckBoxMe();
this.jCheckBoxConGraficoReporteTipoBien.setText("Graf.");
this.jCheckBoxConGraficoReporteTipoBien.setToolTipText("Con Grafico");
this.jButtonAnterioresTipoBien = new JButtonMe();
//this.jButtonAnterioresTipoBien.setText("<<");
this.jButtonAnterioresTipoBien.setToolTipText("Anteriores Datos" + FuncionesSwing.getKeyMensaje("ANTERIORES"));
FuncionesSwing.addImagenButtonGeneral(this.jButtonAnterioresTipoBien,"anteriores_button","<<");
FuncionesSwing.setBoldButton(this.jButtonAnterioresTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);
this.jButtonSiguientesTipoBien = new JButtonMe();
//this.jButtonSiguientesTipoBien.setText(">>");
this.jButtonSiguientesTipoBien.setToolTipText("Siguientes Datos" + FuncionesSwing.getKeyMensaje("SIGUIENTES"));
FuncionesSwing.addImagenButtonGeneral(this.jButtonSiguientesTipoBien,"siguientes_button",">>");
FuncionesSwing.setBoldButton(this.jButtonSiguientesTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);
this.jButtonNuevoGuardarCambiosTipoBien = new JButtonMe();
this.jButtonNuevoGuardarCambiosTipoBien.setText("Nue");
this.jButtonNuevoGuardarCambiosTipoBien.setToolTipText("Nuevo" + FuncionesSwing.getKeyMensaje("NUEVO_TABLA"));
FuncionesSwing.addImagenButtonGeneral(this.jButtonNuevoGuardarCambiosTipoBien,"nuevoguardarcambios_button","Nue",this.tipobienSessionBean.getEsGuardarRelacionado());
FuncionesSwing.setBoldButton(this.jButtonNuevoGuardarCambiosTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);
//HOT KEYS2
/*
T->Nuevo Tabla
*/
//NUEVO GUARDAR CAMBIOS O NUEVO TABLA
sMapKey = "NuevoGuardarCambiosTipoBien";
inputMap = this.jButtonNuevoGuardarCambiosTipoBien.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("NUEVO_TABLA") , FuncionesSwing.getMaskKey("NUEVO_TABLA")), sMapKey);
this.jButtonNuevoGuardarCambiosTipoBien.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"NuevoGuardarCambiosTipoBien"));
//RECARGAR
sMapKey = "RecargarInformacionTipoBien";
inputMap = this.jButtonRecargarInformacionTipoBien.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("RECARGAR") , FuncionesSwing.getMaskKey("RECARGAR")), sMapKey);
this.jButtonRecargarInformacionTipoBien.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"RecargarInformacionTipoBien"));
//SIGUIENTES
sMapKey = "SiguientesTipoBien";
inputMap = this.jButtonSiguientesTipoBien.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("SIGUIENTES") , FuncionesSwing.getMaskKey("SIGUIENTES")), sMapKey);
this.jButtonSiguientesTipoBien.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"SiguientesTipoBien"));
//ANTERIORES
sMapKey = "AnterioresTipoBien";
inputMap = this.jButtonAnterioresTipoBien.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("ANTERIORES") , FuncionesSwing.getMaskKey("ANTERIORES")), sMapKey);
this.jButtonAnterioresTipoBien.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"AnterioresTipoBien"));
//HOT KEYS2
//DETALLE
//TOOLBAR
//INDICES BUSQUEDA
//INDICES BUSQUEDA_FIN
//INDICES BUSQUEDA
if(!this.conCargarMinimo) {
this.inicializarElementosBusquedasTipoBien();
}
//INDICES BUSQUEDA_FIN
//ELEMENTOS TABLAS PARAMETOS
if(!this.conCargarMinimo) {
}
//ELEMENTOS TABLAS PARAMETOS_FIN
//ELEMENTOS TABLAS PARAMETOS_FIN
//ESTA EN BEAN
/*
this.jTabbedPaneRelacionesTipoBien.setMinimumSize(new Dimension(this.getWidth(),TipoBienBean.ALTO_TABPANE_RELACIONES + FuncionesSwing.getValorProporcion(TipoBienBean.ALTO_TABPANE_RELACIONES,0)));
this.jTabbedPaneRelacionesTipoBien.setMaximumSize(new Dimension(this.getWidth(),TipoBienBean.ALTO_TABPANE_RELACIONES + FuncionesSwing.getValorProporcion(TipoBienBean.ALTO_TABPANE_RELACIONES,0)));
this.jTabbedPaneRelacionesTipoBien.setPreferredSize(new Dimension(this.getWidth(),TipoBienBean.ALTO_TABPANE_RELACIONES + FuncionesSwing.getValorProporcion(TipoBienBean.ALTO_TABPANE_RELACIONES,0)));
*/
int iPosXAccionPaginacion=0;
GridBagLayout gridaBagLayoutPaginacionTipoBien = new GridBagLayout();
this.jPanelPaginacionTipoBien.setLayout(gridaBagLayoutPaginacionTipoBien);
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.anchor = GridBagConstraints.EAST;
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsTipoBien.gridy = 0;
this.gridBagConstraintsTipoBien.gridx = iPosXAccionPaginacion++;
this.jPanelPaginacionTipoBien.add(this.jButtonAnterioresTipoBien, this.gridBagConstraintsTipoBien);
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.gridx = iPosXAccionPaginacion++;
this.gridBagConstraintsTipoBien.gridy = 0;
this.jPanelPaginacionTipoBien.add(this.jButtonNuevoGuardarCambiosTipoBien, this.gridBagConstraintsTipoBien);
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsTipoBien.gridx = iPosXAccionPaginacion++;
this.gridBagConstraintsTipoBien.gridy = 0;
this.jPanelPaginacionTipoBien.add(this.jButtonSiguientesTipoBien, this.gridBagConstraintsTipoBien);
iPosXAccionPaginacion=0;
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsTipoBien.gridy = 1;
this.gridBagConstraintsTipoBien.gridx = iPosXAccionPaginacion++;
this.jPanelPaginacionTipoBien.add(this.jButtonNuevoTipoBien, this.gridBagConstraintsTipoBien);
if(this.conFuncionalidadRelaciones) {
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsTipoBien.gridy = 1;
this.gridBagConstraintsTipoBien.gridx = iPosXAccionPaginacion++;
this.jPanelPaginacionTipoBien.add(this.jButtonNuevoRelacionesTipoBien, this.gridBagConstraintsTipoBien);
}
if(!this.tipobienSessionBean.getEsGuardarRelacionado()
&& !this.conCargarMinimo) {
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsTipoBien.gridy = 1;
this.gridBagConstraintsTipoBien.gridx = iPosXAccionPaginacion++;
this.jPanelPaginacionTipoBien.add(this.jButtonGuardarCambiosTablaTipoBien, this.gridBagConstraintsTipoBien);
}
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsTipoBien.gridy = 1;
this.gridBagConstraintsTipoBien.gridx = iPosXAccionPaginacion++;
this.jPanelPaginacionTipoBien.add(this.jButtonDuplicarTipoBien, this.gridBagConstraintsTipoBien);
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsTipoBien.gridy = 1;
this.gridBagConstraintsTipoBien.gridx = iPosXAccionPaginacion++;
this.jPanelPaginacionTipoBien.add(this.jButtonCopiarTipoBien, this.gridBagConstraintsTipoBien);
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsTipoBien.gridy = 1;
this.gridBagConstraintsTipoBien.gridx = iPosXAccionPaginacion++;
this.jPanelPaginacionTipoBien.add(this.jButtonVerFormTipoBien, this.gridBagConstraintsTipoBien);
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsTipoBien.gridy = 1;
this.gridBagConstraintsTipoBien.gridx = iPosXAccionPaginacion++;
this.jPanelPaginacionTipoBien.add(this.jButtonCerrarTipoBien, this.gridBagConstraintsTipoBien);
this.jButtonRecargarInformacionTipoBien.setMinimumSize(new Dimension(95,25));
this.jButtonRecargarInformacionTipoBien.setMaximumSize(new Dimension(95,25));
this.jButtonRecargarInformacionTipoBien.setPreferredSize(new Dimension(95,25));
FuncionesSwing.setBoldButton(this.jButtonRecargarInformacionTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);
this.jComboBoxTiposArchivosReportesTipoBien.setMinimumSize(new Dimension(105,20));
this.jComboBoxTiposArchivosReportesTipoBien.setMaximumSize(new Dimension(105,20));
this.jComboBoxTiposArchivosReportesTipoBien.setPreferredSize(new Dimension(105,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposArchivosReportesTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jComboBoxTiposReportesTipoBien.setMinimumSize(new Dimension(100,20));
this.jComboBoxTiposReportesTipoBien.setMaximumSize(new Dimension(100,20));
this.jComboBoxTiposReportesTipoBien.setPreferredSize(new Dimension(100,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposReportesTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jComboBoxTiposGraficosReportesTipoBien.setMinimumSize(new Dimension(80,20));
this.jComboBoxTiposGraficosReportesTipoBien.setMaximumSize(new Dimension(80,20));
this.jComboBoxTiposGraficosReportesTipoBien.setPreferredSize(new Dimension(80,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposGraficosReportesTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jComboBoxTiposPaginacionTipoBien.setMinimumSize(new Dimension(80,20));
this.jComboBoxTiposPaginacionTipoBien.setMaximumSize(new Dimension(80,20));
this.jComboBoxTiposPaginacionTipoBien.setPreferredSize(new Dimension(80,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposPaginacionTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jComboBoxTiposRelacionesTipoBien.setMinimumSize(new Dimension(145,20));
this.jComboBoxTiposRelacionesTipoBien.setMaximumSize(new Dimension(145,20));
this.jComboBoxTiposRelacionesTipoBien.setPreferredSize(new Dimension(145,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposRelacionesTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jComboBoxTiposAccionesTipoBien.setMinimumSize(new Dimension(145,20));
this.jComboBoxTiposAccionesTipoBien.setMaximumSize(new Dimension(145,20));
this.jComboBoxTiposAccionesTipoBien.setPreferredSize(new Dimension(145,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposAccionesTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jComboBoxTiposSeleccionarTipoBien.setMinimumSize(new Dimension(145,20));
this.jComboBoxTiposSeleccionarTipoBien.setMaximumSize(new Dimension(145,20));
this.jComboBoxTiposSeleccionarTipoBien.setPreferredSize(new Dimension(145,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposSeleccionarTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jCheckBoxConAltoMaximoTablaTipoBien.setMinimumSize(new Dimension(20,20));
this.jCheckBoxConAltoMaximoTablaTipoBien.setMaximumSize(new Dimension(20,20));
this.jCheckBoxConAltoMaximoTablaTipoBien.setPreferredSize(new Dimension(20,20));
FuncionesSwing.setBoldCheckBox(this.jCheckBoxConAltoMaximoTablaTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jCheckBoxConGraficoReporteTipoBien.setMinimumSize(new Dimension(60,20));
this.jCheckBoxConGraficoReporteTipoBien.setMaximumSize(new Dimension(60,20));
this.jCheckBoxConGraficoReporteTipoBien.setPreferredSize(new Dimension(60,20));
FuncionesSwing.setBoldCheckBox(this.jCheckBoxConGraficoReporteTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);
this.jCheckBoxSeleccionarTodosTipoBien.setMinimumSize(new Dimension(100,20));
this.jCheckBoxSeleccionarTodosTipoBien.setMaximumSize(new Dimension(100,20));
this.jCheckBoxSeleccionarTodosTipoBien.setPreferredSize(new Dimension(100,20));
FuncionesSwing.setBoldCheckBox(this.jCheckBoxSeleccionarTodosTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jCheckBoxSeleccionadosTipoBien.setMinimumSize(new Dimension(20,20));
this.jCheckBoxSeleccionadosTipoBien.setMaximumSize(new Dimension(20,20));
this.jCheckBoxSeleccionadosTipoBien.setPreferredSize(new Dimension(20,20));
FuncionesSwing.setBoldCheckBox(this.jCheckBoxSeleccionadosTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);;
GridBagLayout gridaBagParametrosReportesTipoBien = new GridBagLayout();
GridBagLayout gridaBagParametrosReportesAccionesTipoBien = new GridBagLayout();
GridBagLayout gridaBagParametrosAuxiliar1TipoBien = new GridBagLayout();
GridBagLayout gridaBagParametrosAuxiliar2TipoBien = new GridBagLayout();
GridBagLayout gridaBagParametrosAuxiliar3TipoBien = new GridBagLayout();
GridBagLayout gridaBagParametrosAuxiliar4TipoBien = new GridBagLayout();
int iGridxParametrosReportes=0;
int iGridyParametrosReportes=0;
int iGridxParametrosAuxiliar=0;
int iGridyParametrosAuxiliar=0;
this.jPanelParametrosReportesTipoBien.setLayout(gridaBagParametrosReportesTipoBien);
this.jPanelParametrosReportesAccionesTipoBien.setLayout(gridaBagParametrosReportesAccionesTipoBien);
this.jPanelParametrosAuxiliar1TipoBien.setLayout(gridaBagParametrosAuxiliar1TipoBien);
this.jPanelParametrosAuxiliar2TipoBien.setLayout(gridaBagParametrosAuxiliar2TipoBien);
this.jPanelParametrosAuxiliar3TipoBien.setLayout(gridaBagParametrosAuxiliar3TipoBien);
this.jPanelParametrosAuxiliar4TipoBien.setLayout(gridaBagParametrosAuxiliar4TipoBien);
//this.jPanelParametrosAuxiliar5TipoBien.setLayout(gridaBagParametrosAuxiliar2TipoBien);
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsTipoBien.gridy = iGridyParametrosReportes;
this.gridBagConstraintsTipoBien.gridx = iGridxParametrosReportes++;
this.jPanelParametrosReportesTipoBien.add(this.jButtonRecargarInformacionTipoBien, this.gridBagConstraintsTipoBien);
//PAGINACION
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsTipoBien.gridy = iGridyParametrosAuxiliar;//iGridyParametrosReportes;
this.gridBagConstraintsTipoBien.gridx = iGridxParametrosAuxiliar++;//iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosAuxiliar1TipoBien.add(this.jComboBoxTiposPaginacionTipoBien, this.gridBagConstraintsTipoBien);
//CON ALTO MAXIMO TABLA
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsTipoBien.gridy = iGridyParametrosAuxiliar;//iGridyParametrosReportes;
this.gridBagConstraintsTipoBien.gridx = iGridxParametrosAuxiliar++;//iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosAuxiliar1TipoBien.add(this.jCheckBoxConAltoMaximoTablaTipoBien, this.gridBagConstraintsTipoBien);
//TIPOS ARCHIVOS REPORTES
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsTipoBien.gridy = iGridyParametrosAuxiliar;//iGridyParametrosReportes;
this.gridBagConstraintsTipoBien.gridx = iGridxParametrosAuxiliar++;//iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosAuxiliar1TipoBien.add(this.jComboBoxTiposArchivosReportesTipoBien, this.gridBagConstraintsTipoBien);
//USANDO AUXILIAR
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsTipoBien.gridy = iGridyParametrosReportes;
this.gridBagConstraintsTipoBien.gridx = iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosReportesTipoBien.add(this.jPanelParametrosAuxiliar1TipoBien, this.gridBagConstraintsTipoBien);
//USANDO AUXILIAR FIN
//AUXILIAR4 TIPOS REPORTES Y TIPOS GRAFICOS REPORTES
iGridxParametrosAuxiliar=0;
iGridyParametrosAuxiliar=0;
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsTipoBien.gridy =iGridxParametrosAuxiliar;//iGridyParametrosReportes;
this.gridBagConstraintsTipoBien.gridx =iGridyParametrosAuxiliar++;//iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosAuxiliar4TipoBien.add(this.jComboBoxTiposReportesTipoBien, this.gridBagConstraintsTipoBien);
//AUXILIAR4 TIPOS REPORTES Y TIPOS GRAFICOS REPORTES
//USANDO AUXILIAR 4
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsTipoBien.gridy = iGridyParametrosReportes;
this.gridBagConstraintsTipoBien.gridx = iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosReportesTipoBien.add(this.jPanelParametrosAuxiliar4TipoBien, this.gridBagConstraintsTipoBien);
//USANDO AUXILIAR 4 FIN
//TIPOS REPORTES
/*
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsTipoBien.gridy = iGridyParametrosReportes;//iGridyParametrosReportes;
this.gridBagConstraintsTipoBien.gridx = iGridxParametrosReportes++;//iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosReportesTipoBien.add(this.jComboBoxTiposReportesTipoBien, this.gridBagConstraintsTipoBien);
*/
//GENERAR REPORTE (jCheckBoxExportar)
/*
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsTipoBien.gridy = iGridyParametrosReportes;
this.gridBagConstraintsTipoBien.gridx = iGridxParametrosReportes++;
this.jPanelParametrosReportesTipoBien.add(this.jCheckBoxGenerarReporteTipoBien, this.gridBagConstraintsTipoBien);
*/
iGridxParametrosAuxiliar=0;
iGridyParametrosAuxiliar=0;
//USANDO AUXILIAR
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsTipoBien.gridy = iGridyParametrosReportes;
this.gridBagConstraintsTipoBien.gridx = iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosReportesTipoBien.add(this.jPanelParametrosAuxiliar2TipoBien, this.gridBagConstraintsTipoBien);
//USANDO AUXILIAR FIN
//PARAMETROS ACCIONES
//iGridxParametrosReportes=1;
iGridxParametrosReportes=0;
iGridyParametrosReportes=1;
/*
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsTipoBien.gridy = iGridyParametrosReportes;
this.gridBagConstraintsTipoBien.gridx =iGridxParametrosReportes++;
this.jPanelParametrosReportesTipoBien.add(this.jLabelAccionesTipoBien, this.gridBagConstraintsTipoBien);
*/
//PARAMETROS_ACCIONES-PARAMETROS_REPORTES
//ORDER BY
if(!this.conCargarMinimo) {
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsTipoBien.gridy = iGridyParametrosReportes;
this.gridBagConstraintsTipoBien.gridx = iGridxParametrosReportes++;
this.jPanelParametrosReportesTipoBien.add(this.jButtonAbrirOrderByTipoBien, this.gridBagConstraintsTipoBien);
}
//PARAMETROS_ACCIONES-PARAMETROS_REPORTES
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsTipoBien.gridy = iGridyParametrosReportes;
this.gridBagConstraintsTipoBien.gridx = iGridxParametrosReportes++;
this.jPanelParametrosReportesTipoBien.add(this.jComboBoxTiposSeleccionarTipoBien, this.gridBagConstraintsTipoBien);
/*
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsTipoBien.gridy = iGridyParametrosReportes;
this.gridBagConstraintsTipoBien.gridx =iGridxParametrosReportes++;
this.jPanelParametrosReportesTipoBien.add(this.jCheckBoxSeleccionarTodosTipoBien, this.gridBagConstraintsTipoBien);
*/
iGridxParametrosAuxiliar=0;
iGridyParametrosAuxiliar=0;
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsTipoBien.gridy =iGridxParametrosAuxiliar;//iGridyParametrosReportes;
this.gridBagConstraintsTipoBien.gridx =iGridyParametrosAuxiliar++;//iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosAuxiliar3TipoBien.add(this.jCheckBoxSeleccionarTodosTipoBien, this.gridBagConstraintsTipoBien);
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsTipoBien.gridy =iGridxParametrosAuxiliar;//iGridyParametrosReportes;
this.gridBagConstraintsTipoBien.gridx =iGridyParametrosAuxiliar++;//iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosAuxiliar3TipoBien.add(this.jCheckBoxSeleccionadosTipoBien, this.gridBagConstraintsTipoBien);
//USANDO AUXILIAR3
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsTipoBien.gridy = iGridyParametrosReportes;
this.gridBagConstraintsTipoBien.gridx = iGridxParametrosReportes++;
//this.jPanelParametrosReportes
this.jPanelParametrosReportesTipoBien.add(this.jPanelParametrosAuxiliar3TipoBien, this.gridBagConstraintsTipoBien);
//USANDO AUXILIAR3 FIN
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.gridy = iGridyParametrosReportes;
this.gridBagConstraintsTipoBien.gridx = iGridxParametrosReportes++;
this.jPanelParametrosReportesTipoBien.add(this.jComboBoxTiposRelacionesTipoBien, this.gridBagConstraintsTipoBien);
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.gridy = iGridyParametrosReportes;
this.gridBagConstraintsTipoBien.gridx = iGridxParametrosReportes++;
this.jPanelParametrosReportesTipoBien.add(this.jComboBoxTiposAccionesTipoBien, this.gridBagConstraintsTipoBien);
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.gridy = iGridyParametrosReportes;
this.gridBagConstraintsTipoBien.gridx = iGridxParametrosReportes++;
this.jPanelParametrosReportesTipoBien.add(this.jTextFieldValorCampoGeneralTipoBien, this.gridBagConstraintsTipoBien);
;
//ELEMENTOS TABLAS PARAMETOS
//SUBPANELES POR CAMPO
if(!this.conCargarMinimo) {
//SUBPANELES EN PANEL CAMPOS
}
//ELEMENTOS TABLAS PARAMETOS_FIN
/*
GridBagLayout gridaBagLayoutDatosTipoBien = new GridBagLayout();
this.jScrollPanelDatosTipoBien.setLayout(gridaBagLayoutDatosTipoBien);
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsTipoBien.gridy = 0;
this.gridBagConstraintsTipoBien.gridx = 0;
this.jScrollPanelDatosTipoBien.add(this.jTableDatosTipoBien, this.gridBagConstraintsTipoBien);
*/
this.redimensionarTablaDatos(-1);
this.jScrollPanelDatosTipoBien.setViewportView(this.jTableDatosTipoBien);
this.jTableDatosTipoBien.setFillsViewportHeight(true);
this.jTableDatosTipoBien.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
Integer iGridXParametrosAccionesFormulario=0;
Integer iGridYParametrosAccionesFormulario=0;
GridBagLayout gridaBagLayoutAccionesTipoBien= new GridBagLayout();
this.jPanelAccionesTipoBien.setLayout(gridaBagLayoutAccionesTipoBien);
/*
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsTipoBien.gridy = 0;
this.gridBagConstraintsTipoBien.gridx = 0;
this.jPanelAccionesTipoBien.add(this.jButtonNuevoTipoBien, this.gridBagConstraintsTipoBien);
*/
int iPosXAccion=0;
if(!this.conCargarMinimo) {
//BYDAN_BUSQUEDAS
}
//this.setJProgressBarToJPanel();
GridBagLayout gridaBagLayoutTipoBien = new GridBagLayout();
this.jContentPane.setLayout(gridaBagLayoutTipoBien);
if(this.parametroGeneralUsuario.getcon_botones_tool_bar() && !this.tipobienSessionBean.getEsGuardarRelacionado()) {
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.gridy = iGridyPrincipal++;
this.gridBagConstraintsTipoBien.gridx = 0;
//this.gridBagConstraintsTipoBien.fill =GridBagConstraints.VERTICAL;
this.gridBagConstraintsTipoBien.anchor = GridBagConstraints.CENTER;//.CENTER;NORTH
this.gridBagConstraintsTipoBien.ipadx = 100;
this.jContentPane.add(this.jTtoolBarTipoBien, this.gridBagConstraintsTipoBien);
}
//PROCESANDO EN OTRA PANTALLA
/*
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.gridy = iGridyPrincipal++;
this.gridBagConstraintsTipoBien.gridx = 0;
//this.gridBagConstraintsTipoBien.fill =GridBagConstraints.VERTICAL;
this.gridBagConstraintsTipoBien.anchor = GridBagConstraints.CENTER;
this.gridBagConstraintsTipoBien.ipadx = 100;
this.jContentPane.add(this.jPanelProgressProcess, this.gridBagConstraintsTipoBien);
*/
int iGridxBusquedasParametros=0;
//PARAMETROS TABLAS PARAMETROS
if(!this.conCargarMinimo) {
}
//PARAMETROS TABLAS PARAMETROS_FIN
//PARAMETROS REPORTES
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.gridy = iGridyPrincipal++;
this.gridBagConstraintsTipoBien.gridx = 0;
this.jContentPane.add(this.jPanelParametrosReportesTipoBien, this.gridBagConstraintsTipoBien);
/*
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.gridy = iGridyPrincipal++;
this.gridBagConstraintsTipoBien.gridx = 0;
this.jContentPane.add(this.jPanelParametrosReportesAccionesTipoBien, this.gridBagConstraintsTipoBien);
*/
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.gridy =iGridyPrincipal++;
this.gridBagConstraintsTipoBien.gridx =0;
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.BOTH;
//this.gridBagConstraintsTipoBien.ipady =150;
this.jContentPane.add(this.jScrollPanelDatosTipoBien, this.gridBagConstraintsTipoBien);
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.gridy = iGridyPrincipal++;
this.gridBagConstraintsTipoBien.gridx = 0;
this.jContentPane.add(this.jPanelPaginacionTipoBien, this.gridBagConstraintsTipoBien);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
iWidthScroll=(screenSize.width-screenSize.width/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ANCHO_RELSCROLL)+(250*0);
iHeightScroll=(screenSize.height-screenSize.height/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ALTO_RELSCROLL);
//iWidthFormulario=iWidthScroll;
//iHeightFormulario=iHeightScroll;
if(TipoBienJInternalFrame.CON_DATOS_FRAME) {
this.jPanelBusquedasParametrosTipoBien= new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
int iGridyRelaciones=0;
GridBagLayout gridaBagLayoutBusquedasParametrosTipoBien = new GridBagLayout();
this.jPanelBusquedasParametrosTipoBien.setLayout(gridaBagLayoutBusquedasParametrosTipoBien);
if(this.parametroGeneralUsuario.getcon_botones_tool_bar()) {
}
this.jScrollPanelDatosGeneralTipoBien= new JScrollPane(jContentPane,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
this.jScrollPanelDatosGeneralTipoBien.setMinimumSize(new Dimension(iWidthScroll,iHeightScroll));
this.jScrollPanelDatosGeneralTipoBien.setMaximumSize(new Dimension(iWidthScroll,iHeightScroll));
this.jScrollPanelDatosGeneralTipoBien.setPreferredSize(new Dimension(iWidthScroll,iHeightScroll));
this.gridBagConstraintsTipoBien = new GridBagConstraints();
//if(!this.conCargarMinimo) {
//}
this.conMaximoRelaciones=true;
if(this.parametroGeneralUsuario.getcon_cargar_por_parte()) {
}
Boolean tieneColumnasOcultas=false;
tieneColumnasOcultas=true;
if(!Constantes.ISDEVELOPING) {
} else {
if(tieneColumnasOcultas) {
}
}
} else {
//DISENO_DETALLE COMENTAR Y
//DISENO_DETALLE(Solo Descomentar Seccion Inferior)
//NOTA-DISENO_DETALLE(Si cambia lo de abajo, cambiar lo comentado, Al final no es lo mismo)
}
//DISENO_DETALLE-(Descomentar)
/*
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.gridy = iGridyPrincipal++;
this.gridBagConstraintsTipoBien.gridx = 0;
this.jContentPane.add(this.jPanelCamposTipoBien, this.gridBagConstraintsTipoBien);
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.gridy = iGridyPrincipal++;
this.gridBagConstraintsTipoBien.gridx = 0;
this.jContentPane.add(this.jPanelCamposOcultosTipoBien, this.gridBagConstraintsTipoBien);
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.gridy =iGridyPrincipal++;
this.gridBagConstraintsTipoBien.gridx =0;
this.jContentPane.add(this.jPanelAccionesTipoBien, this.gridBagConstraintsTipoBien);
*/
//pack();
return this.jScrollPanelDatosGeneralTipoBien;//jContentPane;
}
/*
public void cargarReporteDinamicoTipoBien() throws Exception {
int iWidthReporteDinamico=350;
int iHeightReporteDinamico=450;//250;400;
int iPosXReporteDinamico=0;
int iPosYReporteDinamico=0;
GridBagLayout gridaBagLayoutReporteDinamicoTipoBien = new GridBagLayout();
//PANEL
this.jPanelReporteDinamicoTipoBien = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);
this.jPanelReporteDinamicoTipoBien.setBorder(javax.swing.BorderFactory.createTitledBorder("Campos"));
this.jPanelReporteDinamicoTipoBien.setName("jPanelReporteDinamicoTipoBien");
this.jPanelReporteDinamicoTipoBien.setMinimumSize(new Dimension(iWidthReporteDinamico,iHeightReporteDinamico));
this.jPanelReporteDinamicoTipoBien.setMaximumSize(new Dimension(iWidthReporteDinamico,iHeightReporteDinamico));
this.jPanelReporteDinamicoTipoBien.setPreferredSize(new Dimension(iWidthReporteDinamico,iHeightReporteDinamico));
this.jPanelReporteDinamicoTipoBien.setLayout(gridaBagLayoutReporteDinamicoTipoBien);
this.jInternalFrameReporteDinamicoTipoBien= new ReporteDinamicoJInternalFrame();
this.jScrollPanelReporteDinamicoTipoBien = new JScrollPane();
//PANEL_CONTROLES
//this.jScrollColumnasSelectReporteTipoBien= new JScrollPane();
//JINTERNAL FRAME
this.jInternalFrameReporteDinamicoTipoBien.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
this.jInternalFrameReporteDinamicoTipoBien.setjInternalFrameParent(this);
this.jInternalFrameReporteDinamicoTipoBien.setTitle("REPORTE DINAMICO");
this.jInternalFrameReporteDinamicoTipoBien.setSize(iWidthReporteDinamico+70,iHeightReporteDinamico+100);
this.jInternalFrameReporteDinamicoTipoBien.setLocation(xOffset*(openFrameCount + Constantes.INUM_MAX_VENTANAS_DET_X), yOffset*(openFrameCount+Constantes.INUM_MAX_VENTANAS_DET_Y));
this.jInternalFrameReporteDinamicoTipoBien.setResizable(true);
this.jInternalFrameReporteDinamicoTipoBien.setClosable(true);
this.jInternalFrameReporteDinamicoTipoBien.setMaximizable(true);
//SCROLL PANEL
//this.jScrollPanelReporteDinamicoTipoBien.setMinimumSize(new Dimension(iWidthReporteDinamico,iHeightReporteDinamico));
//this.jScrollPanelReporteDinamicoTipoBien.setMaximumSize(new Dimension(iWidthReporteDinamico,iHeightReporteDinamico));
//this.jScrollPanelReporteDinamicoTipoBien.setPreferredSize(new Dimension(iWidthReporteDinamico,iHeightReporteDinamico));
//this.jScrollPanelReporteDinamicoTipoBien.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos Tipo Bienes"));
//CONTROLES-ELEMENTOS
//LABEL SELECT COLUMNAS
this.jLabelColumnasSelectReporteTipoBien = new JLabelMe();
this.jLabelColumnasSelectReporteTipoBien.setText("Columnas Seleccion");
this.jLabelColumnasSelectReporteTipoBien.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelColumnasSelectReporteTipoBien.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelColumnasSelectReporteTipoBien.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
iPosXReporteDinamico=0;
iPosYReporteDinamico=0;
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsTipoBien.gridy = iPosYReporteDinamico;
this.gridBagConstraintsTipoBien.gridx = iPosXReporteDinamico++;
this.jPanelReporteDinamicoTipoBien.add(this.jLabelColumnasSelectReporteTipoBien, this.gridBagConstraintsTipoBien);
//LISTA SELECT COLUMNAS
this.jListColumnasSelectReporteTipoBien = new JList<Reporte>();
this.jListColumnasSelectReporteTipoBien.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
this.jListColumnasSelectReporteTipoBien.setToolTipText("Tipos de Seleccion");
this.jListColumnasSelectReporteTipoBien.setMinimumSize(new Dimension(145,300));
this.jListColumnasSelectReporteTipoBien.setMaximumSize(new Dimension(145,300));
this.jListColumnasSelectReporteTipoBien.setPreferredSize(new Dimension(145,300));
//SCROLL_PANEL_CONTROL
this.jScrollColumnasSelectReporteTipoBien=new JScrollPane(this.jListColumnasSelectReporteTipoBien);
this.jScrollColumnasSelectReporteTipoBien.setMinimumSize(new Dimension(180,150));
this.jScrollColumnasSelectReporteTipoBien.setMaximumSize(new Dimension(180,150));
this.jScrollColumnasSelectReporteTipoBien.setPreferredSize(new Dimension(180,150));
this.jScrollColumnasSelectReporteTipoBien.setBorder(javax.swing.BorderFactory.createTitledBorder("COLUMNAS"));
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsTipoBien.gridy = iPosYReporteDinamico;
this.gridBagConstraintsTipoBien.gridx = iPosXReporteDinamico++;
//this.jPanelReporteDinamicoTipoBien.add(this.jListColumnasSelectReporteTipoBien, this.gridBagConstraintsTipoBien);
this.jPanelReporteDinamicoTipoBien.add(this.jScrollColumnasSelectReporteTipoBien, this.gridBagConstraintsTipoBien);
//LABEL SELECT RELACIONES
this.jLabelRelacionesSelectReporteTipoBien = new JLabelMe();
this.jLabelRelacionesSelectReporteTipoBien.setText("Relaciones Seleccion");
this.jLabelRelacionesSelectReporteTipoBien.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelRelacionesSelectReporteTipoBien.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelRelacionesSelectReporteTipoBien.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
iPosXReporteDinamico=0;
iPosYReporteDinamico++;
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsTipoBien.gridy = iPosYReporteDinamico;
this.gridBagConstraintsTipoBien.gridx = iPosXReporteDinamico++;
this.jPanelReporteDinamicoTipoBien.add(this.jLabelRelacionesSelectReporteTipoBien, this.gridBagConstraintsTipoBien);
//LABEL SELECT RELACIONES_FIN
//LISTA SELECT RELACIONES
this.jListRelacionesSelectReporteTipoBien = new JList<Reporte>();
this.jListRelacionesSelectReporteTipoBien.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
this.jListRelacionesSelectReporteTipoBien.setToolTipText("Tipos de Seleccion");
this.jListRelacionesSelectReporteTipoBien.setMinimumSize(new Dimension(145,300));
this.jListRelacionesSelectReporteTipoBien.setMaximumSize(new Dimension(145,300));
this.jListRelacionesSelectReporteTipoBien.setPreferredSize(new Dimension(145,300));
//SCROLL_PANEL_CONTROL
this.jScrollRelacionesSelectReporteTipoBien=new JScrollPane(this.jListRelacionesSelectReporteTipoBien);
this.jScrollRelacionesSelectReporteTipoBien.setMinimumSize(new Dimension(180,120));
this.jScrollRelacionesSelectReporteTipoBien.setMaximumSize(new Dimension(180,120));
this.jScrollRelacionesSelectReporteTipoBien.setPreferredSize(new Dimension(180,120));
this.jScrollRelacionesSelectReporteTipoBien.setBorder(javax.swing.BorderFactory.createTitledBorder("RELACIONES"));
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsTipoBien.gridy = iPosYReporteDinamico;
this.gridBagConstraintsTipoBien.gridx = iPosXReporteDinamico++;
//this.jPanelReporteDinamicoTipoBien.add(this.jListRelacionesSelectReporteTipoBien, this.gridBagConstraintsTipoBien);
this.jPanelReporteDinamicoTipoBien.add(this.jScrollRelacionesSelectReporteTipoBien, this.gridBagConstraintsTipoBien);
//LISTA SELECT RELACIONES_FIN
this.jCheckBoxConGraficoDinamicoTipoBien = new JCheckBoxMe();
this.jComboBoxColumnaCategoriaGraficoTipoBien = new JComboBoxMe();
this.jListColumnasValoresGraficoTipoBien = new JList<Reporte>();
//COMBO TIPOS REPORTES
this.jComboBoxTiposReportesDinamicoTipoBien = new JComboBoxMe();
this.jComboBoxTiposReportesDinamicoTipoBien.setToolTipText("Tipos De Reporte");
this.jComboBoxTiposReportesDinamicoTipoBien.setMinimumSize(new Dimension(100,20));
this.jComboBoxTiposReportesDinamicoTipoBien.setMaximumSize(new Dimension(100,20));
this.jComboBoxTiposReportesDinamicoTipoBien.setPreferredSize(new Dimension(100,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposReportesDinamicoTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);;
//COMBO TIPOS REPORTES
//COMBO TIPOS ARCHIVOS
this.jComboBoxTiposArchivosReportesDinamicoTipoBien = new JComboBoxMe();
this.jComboBoxTiposArchivosReportesDinamicoTipoBien.setToolTipText("Tipos Archivos");
this.jComboBoxTiposArchivosReportesDinamicoTipoBien.setMinimumSize(new Dimension(100,20));
this.jComboBoxTiposArchivosReportesDinamicoTipoBien.setMaximumSize(new Dimension(100,20));
this.jComboBoxTiposArchivosReportesDinamicoTipoBien.setPreferredSize(new Dimension(100,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposArchivosReportesDinamicoTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);;
//COMBO TIPOS ARCHIVOS
//LABEL GENERAR EXCEL
this.jLabelGenerarExcelReporteDinamicoTipoBien = new JLabelMe();
this.jLabelGenerarExcelReporteDinamicoTipoBien.setText("Tipos de Reporte");
this.jLabelGenerarExcelReporteDinamicoTipoBien.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelGenerarExcelReporteDinamicoTipoBien.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelGenerarExcelReporteDinamicoTipoBien.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
iPosXReporteDinamico=0;
iPosYReporteDinamico++;
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsTipoBien.gridy = iPosYReporteDinamico;
this.gridBagConstraintsTipoBien.gridx = iPosXReporteDinamico++;
this.jPanelReporteDinamicoTipoBien.add(this.jLabelGenerarExcelReporteDinamicoTipoBien, this.gridBagConstraintsTipoBien);
//BOTON GENERAR EXCEL
this.jButtonGenerarExcelReporteDinamicoTipoBien = new JButtonMe();
this.jButtonGenerarExcelReporteDinamicoTipoBien.setText("Generar Excel");
FuncionesSwing.addImagenButtonGeneral(this.jButtonGenerarExcelReporteDinamicoTipoBien,"generar_excel_reporte_dinamico_button","Generar EXCEL");
this.jButtonGenerarExcelReporteDinamicoTipoBien.setToolTipText("Generar EXCEL"+" "+TipoBienConstantesFunciones.SCLASSWEBTITULO);
//this.gridBagConstraintsTipoBien = new GridBagConstraints();
//this.gridBagConstraintsTipoBien.fill = GridBagConstraints.VERTICAL;
//this.gridBagConstraintsTipoBien.gridy = iPosYReporteDinamico;
//this.gridBagConstraintsTipoBien.gridx = iPosXReporteDinamico++;
//this.jPanelReporteDinamicoTipoBien.add(this.jButtonGenerarExcelReporteDinamicoTipoBien, this.gridBagConstraintsTipoBien);
//COMBO TIPOS REPORTES
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsTipoBien.gridy = iPosYReporteDinamico;
this.gridBagConstraintsTipoBien.gridx = iPosXReporteDinamico++;
this.jPanelReporteDinamicoTipoBien.add(this.jComboBoxTiposReportesDinamicoTipoBien, this.gridBagConstraintsTipoBien);
//LABEL TIPOS DE ARCHIVO
this.jLabelTiposArchivoReporteDinamicoTipoBien = new JLabelMe();
this.jLabelTiposArchivoReporteDinamicoTipoBien.setText("Tipos de Archivo");
this.jLabelTiposArchivoReporteDinamicoTipoBien.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelTiposArchivoReporteDinamicoTipoBien.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelTiposArchivoReporteDinamicoTipoBien.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
iPosXReporteDinamico=0;
iPosYReporteDinamico++;
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsTipoBien.gridy = iPosYReporteDinamico;
this.gridBagConstraintsTipoBien.gridx = iPosXReporteDinamico++;
this.jPanelReporteDinamicoTipoBien.add(this.jLabelTiposArchivoReporteDinamicoTipoBien, this.gridBagConstraintsTipoBien);
//COMBO TIPOS ARCHIVOS
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsTipoBien.gridy = iPosYReporteDinamico;
this.gridBagConstraintsTipoBien.gridx = iPosXReporteDinamico++;
this.jPanelReporteDinamicoTipoBien.add(this.jComboBoxTiposArchivosReportesDinamicoTipoBien, this.gridBagConstraintsTipoBien);
//BOTON GENERAR
this.jButtonGenerarReporteDinamicoTipoBien = new JButtonMe();
this.jButtonGenerarReporteDinamicoTipoBien.setText("Generar");
FuncionesSwing.addImagenButtonGeneral(this.jButtonGenerarReporteDinamicoTipoBien,"generar_reporte_dinamico_button","Generar");
this.jButtonGenerarReporteDinamicoTipoBien.setToolTipText("Generar"+" "+TipoBienConstantesFunciones.SCLASSWEBTITULO);
iPosXReporteDinamico=0;
iPosYReporteDinamico++;
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsTipoBien.gridy = iPosYReporteDinamico;
this.gridBagConstraintsTipoBien.gridx = iPosXReporteDinamico++;
this.jPanelReporteDinamicoTipoBien.add(this.jButtonGenerarReporteDinamicoTipoBien, this.gridBagConstraintsTipoBien);
//BOTON CERRAR
this.jButtonCerrarReporteDinamicoTipoBien = new JButtonMe();
this.jButtonCerrarReporteDinamicoTipoBien.setText("Cancelar");
FuncionesSwing.addImagenButtonGeneral(this.jButtonCerrarReporteDinamicoTipoBien,"cerrar_reporte_dinamico_button","Cancelar");
this.jButtonCerrarReporteDinamicoTipoBien.setToolTipText("Cancelar"+" "+TipoBienConstantesFunciones.SCLASSWEBTITULO);
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsTipoBien.gridy = iPosYReporteDinamico;
this.gridBagConstraintsTipoBien.gridx = iPosXReporteDinamico++;
this.jPanelReporteDinamicoTipoBien.add(this.jButtonCerrarReporteDinamicoTipoBien, this.gridBagConstraintsTipoBien);
//GLOBAL AGREGAR PANELES
GridBagLayout gridaBagLayoutReporteDinamicoPrincipalTipoBien = new GridBagLayout();
this.jScrollPanelReporteDinamicoTipoBien= new JScrollPane(jPanelReporteDinamicoTipoBien,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
this.jScrollPanelReporteDinamicoTipoBien.setMinimumSize(new Dimension(iWidthReporteDinamico+90,iHeightReporteDinamico+90));
this.jScrollPanelReporteDinamicoTipoBien.setMaximumSize(new Dimension(iWidthReporteDinamico+90,iHeightReporteDinamico+90));
this.jScrollPanelReporteDinamicoTipoBien.setPreferredSize(new Dimension(iWidthReporteDinamico+90,iHeightReporteDinamico+90));
this.jScrollPanelReporteDinamicoTipoBien.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos Tipo Bienes"));
iPosXReporteDinamico=0;
iPosYReporteDinamico=0;
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.gridy =iPosYReporteDinamico;
this.gridBagConstraintsTipoBien.gridx =iPosXReporteDinamico;
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.BOTH;
this.jInternalFrameReporteDinamicoTipoBien.setContentPane(new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true));
this.jInternalFrameReporteDinamicoTipoBien.getContentPane().setLayout(gridaBagLayoutReporteDinamicoPrincipalTipoBien);
this.jInternalFrameReporteDinamicoTipoBien.getContentPane().add(this.jScrollPanelReporteDinamicoTipoBien, this.gridBagConstraintsTipoBien);
}
*/
/*
public void cargarImportacionTipoBien() throws Exception {
int iWidthImportacion=350;
int iHeightImportacion=250;//400;
int iPosXImportacion=0;
int iPosYImportacion=0;
GridBagLayout gridaBagLayoutImportacionTipoBien = new GridBagLayout();
//PANEL
this.jPanelImportacionTipoBien = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);
this.jPanelImportacionTipoBien.setBorder(javax.swing.BorderFactory.createTitledBorder("Campos"));
this.jPanelImportacionTipoBien.setName("jPanelImportacionTipoBien");
this.jPanelImportacionTipoBien.setMinimumSize(new Dimension(iWidthImportacion,iHeightImportacion));
this.jPanelImportacionTipoBien.setMaximumSize(new Dimension(iWidthImportacion,iHeightImportacion));
this.jPanelImportacionTipoBien.setPreferredSize(new Dimension(iWidthImportacion,iHeightImportacion));
this.jPanelImportacionTipoBien.setLayout(gridaBagLayoutImportacionTipoBien);
this.jInternalFrameImportacionTipoBien= new ImportacionJInternalFrame();
//this.jInternalFrameImportacionTipoBien= new ImportacionJInternalFrame();
this.jScrollPanelImportacionTipoBien = new JScrollPane();
//PANEL_CONTROLES
//this.jScrollColumnasSelectReporteTipoBien= new JScrollPane();
//JINTERNAL FRAME
this.jInternalFrameImportacionTipoBien.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
this.jInternalFrameImportacionTipoBien.setjInternalFrameParent(this);
this.jInternalFrameImportacionTipoBien.setTitle("REPORTE DINAMICO");
this.jInternalFrameImportacionTipoBien.setSize(iWidthImportacion+70,iHeightImportacion+100);
this.jInternalFrameImportacionTipoBien.setLocation(xOffset*(openFrameCount + Constantes.INUM_MAX_VENTANAS_DET_X), yOffset*(openFrameCount+Constantes.INUM_MAX_VENTANAS_DET_Y));
this.jInternalFrameImportacionTipoBien.setResizable(true);
this.jInternalFrameImportacionTipoBien.setClosable(true);
this.jInternalFrameImportacionTipoBien.setMaximizable(true);
//JINTERNAL FRAME IMPORTACION
this.jInternalFrameImportacionTipoBien.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
this.jInternalFrameImportacionTipoBien.setjInternalFrameParent(this);
this.jInternalFrameImportacionTipoBien.setTitle("IMPORTACION");
this.jInternalFrameImportacionTipoBien.setSize(iWidthImportacion+70,iHeightImportacion+100);
this.jInternalFrameImportacionTipoBien.setLocation(xOffset*(openFrameCount + Constantes.INUM_MAX_VENTANAS_DET_X), yOffset*(openFrameCount+Constantes.INUM_MAX_VENTANAS_DET_Y));
this.jInternalFrameImportacionTipoBien.setResizable(true);
this.jInternalFrameImportacionTipoBien.setClosable(true);
this.jInternalFrameImportacionTipoBien.setMaximizable(true);
//SCROLL PANEL
this.jScrollPanelImportacionTipoBien.setMinimumSize(new Dimension(iWidthImportacion,iHeightImportacion));
this.jScrollPanelImportacionTipoBien.setMaximumSize(new Dimension(iWidthImportacion,iHeightImportacion));
this.jScrollPanelImportacionTipoBien.setPreferredSize(new Dimension(iWidthImportacion,iHeightImportacion));
this.jScrollPanelImportacionTipoBien.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos Tipo Bienes"));
//LABEL ARCHIVO IMPORTACION
this.jLabelArchivoImportacionTipoBien = new JLabelMe();
this.jLabelArchivoImportacionTipoBien.setText("ARCHIVO IMPORTACION");
this.jLabelArchivoImportacionTipoBien.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelArchivoImportacionTipoBien.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelArchivoImportacionTipoBien.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
iPosXImportacion=0;
iPosYImportacion++;
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsTipoBien.gridy = iPosYImportacion;
this.gridBagConstraintsTipoBien.gridx = iPosXImportacion++;
this.jPanelImportacionTipoBien.add(this.jLabelArchivoImportacionTipoBien, this.gridBagConstraintsTipoBien);
//BOTON ABRIR IMPORTACION
this.jFileChooserImportacionTipoBien = new JFileChooser();
this.jFileChooserImportacionTipoBien.setToolTipText("ESCOGER ARCHIVO"+" "+TipoBienConstantesFunciones.SCLASSWEBTITULO);
this.jButtonAbrirImportacionTipoBien = new JButtonMe();
this.jButtonAbrirImportacionTipoBien.setText("ESCOGER");
FuncionesSwing.addImagenButtonGeneral(this.jButtonAbrirImportacionTipoBien,"generar_importacion_button","ESCOGER");
this.jButtonAbrirImportacionTipoBien.setToolTipText("Generar"+" "+TipoBienConstantesFunciones.SCLASSWEBTITULO);
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsTipoBien.gridy = iPosYImportacion;
this.gridBagConstraintsTipoBien.gridx = iPosXImportacion++;
this.jPanelImportacionTipoBien.add(this.jButtonAbrirImportacionTipoBien, this.gridBagConstraintsTipoBien);
//LABEL PATH IMPORTACION
this.jLabelPathArchivoImportacionTipoBien = new JLabelMe();
this.jLabelPathArchivoImportacionTipoBien.setText("PATH ARCHIVO");
this.jLabelPathArchivoImportacionTipoBien.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelPathArchivoImportacionTipoBien.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelPathArchivoImportacionTipoBien.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
iPosXImportacion=0;
iPosYImportacion++;
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsTipoBien.gridy = iPosYImportacion;
this.gridBagConstraintsTipoBien.gridx = iPosXImportacion++;
this.jPanelImportacionTipoBien.add(this.jLabelPathArchivoImportacionTipoBien, this.gridBagConstraintsTipoBien);
//PATH IMPORTACION
this.jTextFieldPathArchivoImportacionTipoBien=new JTextFieldMe();
this.jTextFieldPathArchivoImportacionTipoBien.setMinimumSize(new Dimension(150,Constantes.ISWING_ALTO_CONTROL));
this.jTextFieldPathArchivoImportacionTipoBien.setMaximumSize(new Dimension(150,Constantes.ISWING_ALTO_CONTROL));
this.jTextFieldPathArchivoImportacionTipoBien.setPreferredSize(new Dimension(150,Constantes.ISWING_ALTO_CONTROL));
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsTipoBien.gridy = iPosYImportacion;
this.gridBagConstraintsTipoBien.gridx = iPosXImportacion++;
this.jPanelImportacionTipoBien.add(this.jTextFieldPathArchivoImportacionTipoBien, this.gridBagConstraintsTipoBien);
//BOTON IMPORTACION
this.jButtonGenerarImportacionTipoBien = new JButtonMe();
this.jButtonGenerarImportacionTipoBien.setText("IMPORTAR");
FuncionesSwing.addImagenButtonGeneral(this.jButtonGenerarImportacionTipoBien,"generar_importacion_button","IMPORTAR");
this.jButtonGenerarImportacionTipoBien.setToolTipText("Generar"+" "+TipoBienConstantesFunciones.SCLASSWEBTITULO);
iPosXImportacion=0;
iPosYImportacion++;
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsTipoBien.gridy = iPosYImportacion;
this.gridBagConstraintsTipoBien.gridx = iPosXImportacion++;
this.jPanelImportacionTipoBien.add(this.jButtonGenerarImportacionTipoBien, this.gridBagConstraintsTipoBien);
//BOTON CERRAR
this.jButtonCerrarImportacionTipoBien = new JButtonMe();
this.jButtonCerrarImportacionTipoBien.setText("Cancelar");
FuncionesSwing.addImagenButtonGeneral(this.jButtonCerrarImportacionTipoBien,"cerrar_reporte_dinamico_button","Cancelar");
this.jButtonCerrarImportacionTipoBien.setToolTipText("Cancelar"+" "+TipoBienConstantesFunciones.SCLASSWEBTITULO);
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsTipoBien.gridy = iPosYImportacion;
this.gridBagConstraintsTipoBien.gridx = iPosXImportacion++;
this.jPanelImportacionTipoBien.add(this.jButtonCerrarImportacionTipoBien, this.gridBagConstraintsTipoBien);
//GLOBAL AGREGAR PANELES
GridBagLayout gridaBagLayoutImportacionPrincipalTipoBien = new GridBagLayout();
this.jScrollPanelImportacionTipoBien= new JScrollPane(jPanelImportacionTipoBien,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
iPosXImportacion=0;
iPosYImportacion=0;
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.gridy =iPosYImportacion;
this.gridBagConstraintsTipoBien.gridx =iPosXImportacion;
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.BOTH;
this.jInternalFrameImportacionTipoBien.setContentPane(new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true));
this.jInternalFrameImportacionTipoBien.getContentPane().setLayout(gridaBagLayoutImportacionPrincipalTipoBien);
this.jInternalFrameImportacionTipoBien.getContentPane().add(this.jScrollPanelImportacionTipoBien, this.gridBagConstraintsTipoBien);
}
*/
/*
public void cargarOrderByTipoBien(Boolean cargaMinima) throws Exception {
String sMapKey = "";
InputMap inputMap =null;
int iWidthOrderBy=350;
int iHeightOrderBy=300;//400;
int iPosXOrderBy=0;
int iPosYOrderBy=0;
if(!cargaMinima) {
this.jButtonAbrirOrderByTipoBien = new JButtonMe();
this.jButtonAbrirOrderByTipoBien.setText("Orden");
this.jButtonAbrirOrderByTipoBien.setToolTipText("Orden"+FuncionesSwing.getKeyMensaje("ORDEN"));
FuncionesSwing.addImagenButtonGeneral(this.jButtonAbrirOrderByTipoBien,"orden_button","Orden");
FuncionesSwing.setBoldButton(this.jButtonAbrirOrderByTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);;
sMapKey = "AbrirOrderByTipoBien";
inputMap = this.jButtonAbrirOrderByTipoBien.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("ORDEN") , FuncionesSwing.getMaskKey("ORDEN")), sMapKey);
this.jButtonAbrirOrderByTipoBien.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"AbrirOrderByTipoBien"));
GridBagLayout gridaBagLayoutOrderByTipoBien = new GridBagLayout();
//PANEL
this.jPanelOrderByTipoBien = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);
this.jPanelOrderByTipoBien.setBorder(javax.swing.BorderFactory.createTitledBorder("Campos"));
this.jPanelOrderByTipoBien.setName("jPanelOrderByTipoBien");
this.jPanelOrderByTipoBien.setMinimumSize(new Dimension(iWidthOrderBy,iHeightOrderBy));
this.jPanelOrderByTipoBien.setMaximumSize(new Dimension(iWidthOrderBy,iHeightOrderBy));
this.jPanelOrderByTipoBien.setPreferredSize(new Dimension(iWidthOrderBy,iHeightOrderBy));
FuncionesSwing.setBoldPanel(this.jPanelOrderByTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jPanelOrderByTipoBien.setLayout(gridaBagLayoutOrderByTipoBien);
this.jTableDatosTipoBienOrderBy = new JTableMe();
this.jTableDatosTipoBienOrderBy.setAutoCreateRowSorter(true);
FuncionesSwing.setBoldTable(jTableDatosTipoBienOrderBy,STIPO_TAMANIO_GENERAL,false,true,this);
this.jScrollPanelDatosTipoBienOrderBy = new JScrollPane();
this.jScrollPanelDatosTipoBienOrderBy.setBorder(javax.swing.BorderFactory.createTitledBorder("Orden"));
this.jScrollPanelDatosTipoBienOrderBy.setViewportView(this.jTableDatosTipoBienOrderBy);
this.jTableDatosTipoBienOrderBy.setFillsViewportHeight(true);
this.jTableDatosTipoBienOrderBy.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
this.jInternalFrameOrderByTipoBien= new OrderByJInternalFrame();
this.jInternalFrameOrderByTipoBien= new OrderByJInternalFrame();
this.jScrollPanelOrderByTipoBien = new JScrollPane();
//PANEL_CONTROLES
//this.jScrollColumnasSelectReporteTipoBien= new JScrollPane();
//JINTERNAL FRAME OrderBy
this.jInternalFrameOrderByTipoBien.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
this.jInternalFrameOrderByTipoBien.setjInternalFrameParent(this);
this.jInternalFrameOrderByTipoBien.setTitle("Orden");
this.jInternalFrameOrderByTipoBien.setSize(iWidthOrderBy+70,iHeightOrderBy+100);
this.jInternalFrameOrderByTipoBien.setLocation(xOffset*(openFrameCount + Constantes.INUM_MAX_VENTANAS_DET_X), yOffset*(openFrameCount+Constantes.INUM_MAX_VENTANAS_DET_Y));
this.jInternalFrameOrderByTipoBien.setResizable(true);
this.jInternalFrameOrderByTipoBien.setClosable(true);
this.jInternalFrameOrderByTipoBien.setMaximizable(true);
//FuncionesSwing.setBoldPanel(this.jInternalFrameOrderByTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);;
//SCROLL PANEL
this.jScrollPanelOrderByTipoBien.setMinimumSize(new Dimension(iWidthOrderBy,iHeightOrderBy));
this.jScrollPanelOrderByTipoBien.setMaximumSize(new Dimension(iWidthOrderBy,iHeightOrderBy));
this.jScrollPanelOrderByTipoBien.setPreferredSize(new Dimension(iWidthOrderBy,iHeightOrderBy));
FuncionesSwing.setBoldScrollPanel(this.jScrollPanelOrderByTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jScrollPanelOrderByTipoBien.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos Tipo Bienes"));
//DATOS TOTALES
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.gridy =iPosYOrderBy++;
this.gridBagConstraintsTipoBien.gridx =iPosXOrderBy;
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.BOTH;
//this.gridBagConstraintsTipoBien.ipady =150;
this.jPanelOrderByTipoBien.add(jScrollPanelDatosTipoBienOrderBy, this.gridBagConstraintsTipoBien);//this.jTableDatosTipoBienTotales
//BOTON CERRAR
this.jButtonCerrarOrderByTipoBien = new JButtonMe();
this.jButtonCerrarOrderByTipoBien.setText("Salir");
FuncionesSwing.addImagenButtonGeneral(this.jButtonCerrarOrderByTipoBien,"cerrar","Salir");//cerrar_reporte_dinamico_button
this.jButtonCerrarOrderByTipoBien.setToolTipText("Cancelar"+" "+TipoBienConstantesFunciones.SCLASSWEBTITULO);
FuncionesSwing.setBoldButton(this.jButtonCerrarOrderByTipoBien, STIPO_TAMANIO_GENERAL,false,true,this);;
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsTipoBien.gridy = iPosYOrderBy++;
this.gridBagConstraintsTipoBien.gridx = iPosXOrderBy;
this.jPanelOrderByTipoBien.add(this.jButtonCerrarOrderByTipoBien, this.gridBagConstraintsTipoBien);
//GLOBAL AGREGAR PANELES
GridBagLayout gridaBagLayoutOrderByPrincipalTipoBien = new GridBagLayout();
this.jScrollPanelOrderByTipoBien= new JScrollPane(jPanelOrderByTipoBien,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
iPosXOrderBy=0;
iPosYOrderBy=0;
this.gridBagConstraintsTipoBien = new GridBagConstraints();
this.gridBagConstraintsTipoBien.gridy =iPosYOrderBy;
this.gridBagConstraintsTipoBien.gridx =iPosXOrderBy;
this.gridBagConstraintsTipoBien.fill = GridBagConstraints.BOTH;
this.jInternalFrameOrderByTipoBien.setContentPane(new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true));
this.jInternalFrameOrderByTipoBien.getContentPane().setLayout(gridaBagLayoutOrderByPrincipalTipoBien);
this.jInternalFrameOrderByTipoBien.getContentPane().add(this.jScrollPanelOrderByTipoBien, this.gridBagConstraintsTipoBien);
} else {
this.jButtonAbrirOrderByTipoBien = new JButtonMe();
}
}
*/
public void redimensionarTablaDatos(int iNumFilas) {
this.redimensionarTablaDatos(iNumFilas,0);
}
public void redimensionarTablaDatos(int iNumFilas,int iTamanioFilaTabla) {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int iWidthTable=screenSize.width*2;//screenSize.width - (screenSize.width/8);
int iWidthTableScroll=screenSize.width - (screenSize.width/8);
int iWidthTableCalculado=0;//930
int iHeightTable=0;//screenSize.height/3;
int iHeightTableTotal=0;
//ANCHO COLUMNAS SIMPLES
iWidthTableCalculado+=430;
//ANCHO COLUMNAS OCULTAS
if(Constantes.ISDEVELOPING) {
iWidthTableCalculado+=400;
}
//ANCHO COLUMNAS RELACIONES
iWidthTableCalculado+=100;
//ESPACION PARA SELECT RELACIONES
if(this.conMaximoRelaciones
&& this.tipobienSessionBean.getConGuardarRelaciones()
) {
if(this.conFuncionalidadRelaciones) {
iWidthTableCalculado+=Constantes.ISWING_ANCHO_COLUMNA;
}
}
//SI CALCULADO ES MENOR QUE MAXIMO
/*
if(iWidthTableCalculado<=iWidthTable) {
iWidthTable=iWidthTableCalculado;
}
*/
//SI TABLA ES MENOR QUE SCROLL
if(iWidthTableCalculado<=iWidthTableScroll) {
iWidthTableScroll=iWidthTableCalculado;
}
//NO VALE SIEMPRE PONE TAMANIO COLUMNA 200
/*
int iTotalWidth=0;
int iWidthColumn=0;
int iCountColumns=this.jTableDatosTipoBien.getColumnModel().getColumnCount();
if(iCountColumns>0) {
for(int i = 0; i < this.jTableDatosTipoBien.getColumnModel().getColumnCount(); i++) {
TableColumn column = this.jTableDatosTipoBien.getColumnModel().getColumn(i);
iWidthColumn=column.getWidth();
iTotalWidth+=iWidthColumn;
}
//iWidthTableCalculado=iTotalWidth;
}
*/
if(iTamanioFilaTabla<=0) {
iTamanioFilaTabla=this.jTableDatosTipoBien.getRowHeight();//TipoBienConstantesFunciones.ITAMANIOFILATABLA;
}
if(iNumFilas>0) {
iHeightTable=(iNumFilas * iTamanioFilaTabla);
} else {
iHeightTable=iTamanioFilaTabla;
}
iHeightTableTotal=iHeightTable;
if(!this.tipobienSessionBean.getEsGuardarRelacionado()) {
if(iHeightTable > TipoBienConstantesFunciones.TAMANIO_ALTO_MAXIMO_TABLADATOS) { //Constantes.ISWING_TAMANIOMAXIMO_TABLADATOS) {
//SI SE SELECCIONA MAXIMO TABLA SE AMPLIA A ALTO MAXIMO DE SCROLL, PARA QUE SCROLL NO SEA TAN PEQUE?O
if(!this.jCheckBoxConAltoMaximoTablaTipoBien.isSelected()) {
iHeightTable=TipoBienConstantesFunciones.TAMANIO_ALTO_MAXIMO_TABLADATOS; //Constantes.ISWING_TAMANIOMAXIMO_TABLADATOS;
} else {
iHeightTable=iHeightTableTotal + FuncionesSwing.getValorProporcion(iHeightTableTotal,30);
}
} else {
if(iHeightTable < TipoBienConstantesFunciones.TAMANIO_ALTO_MINIMO_TABLADATOS) {//Constantes.ISWING_TAMANIOMINIMO_TABLADATOS) {
iHeightTable=TipoBienConstantesFunciones.TAMANIO_ALTO_MINIMO_TABLADATOS; //Constantes.ISWING_TAMANIOMINIMO_TABLADATOS;
}
}
} else {
if(iHeightTable > TipoBienConstantesFunciones.TAMANIO_ALTO_MAXIMO_TABLADATOSREL) { //Constantes.ISWING_TAMANIOMAXIMO_TABLADATOS) {
//SI SE SELECCIONA MAXIMO TABLA SE AMPLIA A ALTO MAXIMO DE SCROLL, PARA QUE SCROLL NO SEA TAN PEQUE?O
if(!this.jCheckBoxConAltoMaximoTablaTipoBien.isSelected()) {
iHeightTable=TipoBienConstantesFunciones.TAMANIO_ALTO_MAXIMO_TABLADATOSREL; //Constantes.ISWING_TAMANIOMAXIMO_TABLADATOS;
} else {
iHeightTable=iHeightTableTotal + FuncionesSwing.getValorProporcion(iHeightTableTotal,30);
}
} else {
if(iHeightTable < TipoBienConstantesFunciones.TAMANIO_ALTO_MINIMO_TABLADATOSREL) {//Constantes.ISWING_TAMANIOMINIMO_TABLADATOS) {
iHeightTable=TipoBienConstantesFunciones.TAMANIO_ALTO_MINIMO_TABLADATOSREL; //Constantes.ISWING_TAMANIOMINIMO_TABLADATOS;
}
}
}
//OJO:SE DESHABILITA CALCULADO
//NO SE UTILIZA CALCULADO SI POR DEFINICION
if(iWidthTableDefinicion>0) {
iWidthTableCalculado=iWidthTableDefinicion;
}
this.jTableDatosTipoBien.setMinimumSize(new Dimension(iWidthTableCalculado,iHeightTableTotal));
this.jTableDatosTipoBien.setMaximumSize(new Dimension(iWidthTableCalculado,iHeightTableTotal));
this.jTableDatosTipoBien.setPreferredSize(new Dimension(iWidthTableCalculado,iHeightTableTotal));//iWidthTable
this.jScrollPanelDatosTipoBien.setMinimumSize(new Dimension(iWidthTableScroll,iHeightTable));
this.jScrollPanelDatosTipoBien.setMaximumSize(new Dimension(iWidthTableScroll,iHeightTable));
this.jScrollPanelDatosTipoBien.setPreferredSize(new Dimension(iWidthTableScroll,iHeightTable));
//ORDER BY
//OrderBy
int iHeightTableOrderBy=0;
int iNumFilasOrderBy=this.arrOrderBy.size();
int iTamanioFilaTablaOrderBy=0;
if(this.jInternalFrameOrderByTipoBien!=null && this.jInternalFrameOrderByTipoBien.getjTableDatosOrderBy()!=null) {
//if(!this.tipobienSessionBean.getEsGuardarRelacionado()) {
iTamanioFilaTablaOrderBy=this.jInternalFrameOrderByTipoBien.getjTableDatosOrderBy().getRowHeight();
if(iNumFilasOrderBy>0) {
iHeightTableOrderBy=iNumFilasOrderBy * iTamanioFilaTablaOrderBy;
} else {
iHeightTableOrderBy=iTamanioFilaTablaOrderBy;
}
this.jInternalFrameOrderByTipoBien.getjTableDatosOrderBy().setMinimumSize(new Dimension(Constantes2.ISWING_TAMANIO_ANCHO_TABLADATOS_ORDERBY,iHeightTableOrderBy));//iWidthTableCalculado/4
this.jInternalFrameOrderByTipoBien.getjTableDatosOrderBy().setMaximumSize(new Dimension(Constantes2.ISWING_TAMANIO_ANCHO_TABLADATOS_ORDERBY,iHeightTableOrderBy));
this.jInternalFrameOrderByTipoBien.getjTableDatosOrderBy().setPreferredSize(new Dimension(Constantes2.ISWING_TAMANIO_ANCHO_TABLADATOS_ORDERBY,iHeightTableOrderBy));//iWidthTable
this.jInternalFrameOrderByTipoBien.getjScrollPanelDatosOrderBy().setMinimumSize(new Dimension(Constantes2.ISWING_TAMANIO_ANCHO_TABLADATOS_ORDERBY+30,Constantes2.ISWING_TAMANIO_ALTO_TABLADATOS_ORDERBY));//iHeightTableOrderBy,iWidthTableScroll
this.jInternalFrameOrderByTipoBien.getjScrollPanelDatosOrderBy().setMaximumSize(new Dimension(Constantes2.ISWING_TAMANIO_ANCHO_TABLADATOS_ORDERBY+30,Constantes2.ISWING_TAMANIO_ALTO_TABLADATOS_ORDERBY));
this.jInternalFrameOrderByTipoBien.getjScrollPanelDatosOrderBy().setPreferredSize(new Dimension(Constantes2.ISWING_TAMANIO_ANCHO_TABLADATOS_ORDERBY+30,Constantes2.ISWING_TAMANIO_ALTO_TABLADATOS_ORDERBY));
}
//ORDER BY
//this.jScrollPanelDatosTipoBien.setMinimumSize(new Dimension(iWidthTableScroll,iHeightTable));
//this.jScrollPanelDatosTipoBien.setMaximumSize(new Dimension(iWidthTableScroll,iHeightTable));
//this.jScrollPanelDatosTipoBien.setPreferredSize(new Dimension(iWidthTableScroll,iHeightTable));
//VERSION 0
/*
//SI CALCULADO ES MENOR QUE MAXIMO
if(iWidthTableCalculado<=iWidthTable) {
iWidthTable=iWidthTableCalculado;
}
//SI TABLA ES MENOR QUE SCROLL
if(iWidthTable<=iWidthTableScroll) {
iWidthTableScroll=iWidthTable;
}
*/
}
public void redimensionarTablaDatosConTamanio(int iTamanioFilaTabla) throws Exception {
int iSizeTabla=0;
//ARCHITECTURE
if(Constantes.ISUSAEJBLOGICLAYER) {
iSizeTabla=tipobienLogic.getTipoBiens().size();
} else if(Constantes.ISUSAEJBREMOTE || Constantes.ISUSAEJBHOME) {
iSizeTabla=tipobiens.size();
}
//ARCHITECTURE
this.redimensionarTablaDatos(iSizeTabla,iTamanioFilaTabla);
}
//PARA REPORTES
public static List<TipoBien> TraerTipoBienBeans(List<TipoBien> tipobiens,ArrayList<Classe> classes)throws Exception {
try {
for(TipoBien tipobien:tipobiens) {
if(!(TipoBienConstantesFunciones.S_TIPOREPORTE_EXTRA.equals(Constantes2.S_REPORTE_EXTRA_GROUP_GENERICO)
|| TipoBienConstantesFunciones.S_TIPOREPORTE_EXTRA.equals(Constantes2.S_REPORTE_EXTRA_GROUP_TOTALES_GENERICO))
) {
tipobien.setsDetalleGeneralEntityReporte(TipoBienConstantesFunciones.getTipoBienDescripcion(tipobien));
if(tipobien.getBiens()!=null && Funciones.existeClass(classes,Bien.class)) {
try{tipobien.setbiensDescripcionReporte(new JRBeanCollectionDataSource(BienJInternalFrame.TraerBienBeans(tipobien.getBiens(),classes)));}catch(Exception e){e.printStackTrace();}
}
} else {
//tipobien.setsDetalleGeneralEntityReporte(tipobien.getsDetalleGeneralEntityReporte());
}
//tipobienbeans.add(tipobienbean);
}
} catch(Exception ex) {
throw ex;
}
return tipobiens;
}
//PARA REPORTES FIN
}
|
AgoraIO-Community/RTC-Innovation-Challenge-2020
|
SDKChallengeProject/powerOperation/app/src/main/java/com/xiaoyang/poweroperation/ui/activity/MainActivity.java
|
<gh_stars>10-100
package com.xiaoyang.poweroperation.ui.activity;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.xiaoyang.poweroperation.R;
import com.xiaoyang.poweroperation.data.Constants;
import com.xiaoyang.poweroperation.di.component.DaggerMainComponent;
import com.xiaoyang.poweroperation.main.ChartFragment;
import com.xiaoyang.poweroperation.main.HomeFragment;
import com.xiaoyang.poweroperation.main.MineFragment;
import com.xiaoyang.poweroperation.main.WorkTabFragment;
import com.xiaoyang.poweroperation.ui.contract.MainContract;
import com.xiaoyang.poweroperation.ui.presenter.MainPresenter;
import com.xylib.base.utils.StatusBarUtil;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Locale;
import butterknife.BindView;
import static com.jess.arms.utils.Preconditions.checkNotNull;
/**
* Package:
* ClassName: MainActivity
* Author: xiaoyangyan
* CreateDate: 2019-12-12 16:18
* Description: 主页
*/
public class MainActivity extends BaseActivity<MainPresenter> implements MainContract.View {
private static final int REQUEST_PERMISSION_LOCATION = 2020;
@BindView(R.id.fake_status_bar)
View fakeStatusBar;
@BindView(R.id.fragment_group)
FrameLayout fragmentGroup;
@BindView(R.id.bottom_navigation_view)
BottomNavigationView mBottomNavigationView;
private ArrayList<BaseFragment> mFragments;
private HomeFragment homeFragment;
private MineFragment mineFragment;
private ChartFragment chartFragment;
private WorkTabFragment workTabFragment;
private int mLastFgIndex;
@Override
public void setupActivityComponent(@NonNull AppComponent appComponent) {
DaggerMainComponent //如找不到该类,请编译一下项目
.builder()
.appComponent(appComponent)
.view(this)
.build()
.inject(this);
}
@Override
public int initView(@Nullable Bundle savedInstanceState) {
return R.layout.activity_main; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
}
@Override
public void initData(@Nullable Bundle savedInstanceState) {
initStatusBar();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_PERMISSION_LOCATION);
}
}
mFragments = new ArrayList<>();
initFragments();
mBottomNavigationView.setSelectedItemId(R.id.tab_home);
initPager(true, Constants.TAB_HOME);
initBottomNavigationView();
// sHA1(this);
}
public static String sHA1(Context context) {
try {
PackageInfo info = context.getPackageManager().getPackageInfo(
context.getPackageName(), PackageManager.GET_SIGNATURES);
byte[] cert = info.signatures[0].toByteArray();
MessageDigest md = MessageDigest.getInstance("SHA1");
byte[] publicKey = md.digest(cert);
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < publicKey.length; i++) {
String appendString = Integer.toHexString(0xFF & publicKey[i])
.toUpperCase(Locale.US);
if (appendString.length() == 1)
hexString.append("0");
hexString.append(appendString);
hexString.append(":");
}
String result = hexString.toString();
Log.v("yxy", "sHA1==>" + result.substring(0, result.length() - 1));
return result.substring(0, result.length() - 1);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
private void initPager(boolean isRecreate, int position) {
homeFragment = HomeFragment.newInstance();
mFragments.add(homeFragment);
initFragments();
initBottomNavigationView();
switchFragment(position);
}
private void initStatusBar() {
int color = getResources().getColor(R.color.white);
StatusBarUtil.setColor(this, color, 0);
StatusBarUtil.setLightMode(this);
StatusBarUtil.setPadding(MainActivity.this, fragmentGroup);
}
private void initBottomNavigationView() {
mBottomNavigationView.setOnNavigationItemSelectedListener(item -> {
switch (item.getItemId()) {
case R.id.tab_home:
loadPager(getString(R.string.bottom_home), 0,
homeFragment, Constants.TAB_HOME);
break;
case R.id.tab_chart:
loadPager(getString(R.string.bottom_chart), 1,
chartFragment, Constants.TAB_CHART);
break;
// case R.id.tab_work:
// loadPager(getString(R.string.bottom_work), 2,
// workTabFragment, Constants.TAB_WORK);
// break;
case R.id.tab_mine:
loadPager(getString(R.string.bottom_mine), 2,
mineFragment, Constants.TAB_MINE);
break;
default:
break;
}
return true;
});
}
/**
* 切换fragment
*
* @param position 要显示的fragment的下标
*/
private void switchFragment(int position) {
if (position >= mFragments.size()) {
return;
}
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment targetFg = mFragments.get(position);
Fragment lastFg = mFragments.get(mLastFgIndex);
mLastFgIndex = position;
ft.hide(lastFg);
if (!targetFg.isAdded()) {
getSupportFragmentManager().beginTransaction().remove(targetFg).commitAllowingStateLoss();
ft.add(R.id.fragment_group, targetFg);
}
ft.show(targetFg);
ft.commitAllowingStateLoss();
}
private void loadPager(String title, int position, BaseFragment mFragment, int pagerType) {
switchFragment(position);
}
private void initFragments() {
homeFragment = HomeFragment.newInstance();
mineFragment = MineFragment.newInstance();
chartFragment = ChartFragment.newInstance();
// workTabFragment=WorkTabFragment.newInstance();
mFragments.add(homeFragment);
mFragments.add(chartFragment);
// mFragments.add(workTabFragment);
mFragments.add(mineFragment);
}
@Override
public void showLoading() {
}
@Override
public void hideLoading() {
}
@Override
public void showMessage(@NonNull String message) {
checkNotNull(message);
ArmsUtils.snackbarText(message);
}
@Override
public void launchActivity(@NonNull Intent intent) {
checkNotNull(intent);
ArmsUtils.startActivity(intent);
}
@Override
public void killMyself() {
finish();
}
}
|
sopra-fs-20-group-15/server
|
src/main/java/ch/uzh/ifi/seal/soprafs20/Entities/GameEntity.java
|
<reponame>sopra-fs-20-group-15/server<filename>src/main/java/ch/uzh/ifi/seal/soprafs20/Entities/GameEntity.java
package ch.uzh.ifi.seal.soprafs20.Entities;
import ch.uzh.ifi.seal.soprafs20.GameLogic.*;
import ch.uzh.ifi.seal.soprafs20.exceptions.ConflictException;
import ch.uzh.ifi.seal.soprafs20.service.State;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
@Entity
//Even though there is a red line beneath "GAME", it should still work
@Table(name = "GAME")
public class GameEntity {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@Column(nullable = true)
private Long activeCardId;
@Column(nullable = true)
private String activeMysteryWord;
@Column(nullable = true)
private Long wordId;
@Column(nullable = true)
private Long activePlayerId;
@ElementCollection
List<PlayerEntity> players;
@ElementCollection
private List<Angel> angels;
@ElementCollection
private List<Devil> devils;
@ElementCollection
List<Long> passivePlayerIds;
@ElementCollection
List<Long> CardIds;
/**PlayerToken / Clue*/
@ElementCollection
Map<String, String> clueMap;
@ElementCollection
Map<String,String> validClues;
@ElementCollection
Map<String,Integer> analyzedClues;
@Embedded
private Scoreboard scoreboard;
@Embedded
private HandlerForLeavingPlayers handlerForLeavingPlayers=new HandlerForLeavingPlayers();
@Column
private String Guess;
@Column
private boolean isValidGuess;
@Column
private State stateForLogicService;
public State getStateForLogicService() {
return stateForLogicService;
}
public void setStateForLogicService(State stateForLogicService) {
this.stateForLogicService = stateForLogicService;
}
private Long timeStart;
@Column
private Boolean hasEnded;
public Long getWordId() {
return wordId;
}
public void setWordId(Long wordId) {
this.wordId = wordId;
}
public HandlerForLeavingPlayers getHandlerForLeavingPlayers(){
return handlerForLeavingPlayers;
}
public void setTimeStart(Long timeStart) {
this.timeStart = timeStart;
}
public Long getTimeStart() {
return timeStart;
}
public Map<String, Integer> getAnalyzedClues() {
return analyzedClues;
}
public void setAnalyzedClues(Map<String, Integer> analyzedClues) {
this.analyzedClues = analyzedClues;
}
public void setValidClues(Map<String, String> validClues) {
this.validClues = validClues;
}
public Map<String, String> getValidClues() {
return validClues;
}
public void setClueMap(Map<String, String> clueList) {
this.clueMap = clueList;
}
public Map<String, String> getClueMap() {
return clueMap;
}
public List<PlayerEntity> getPlayers() {
return players;
}
public void setPlayers(List<PlayerEntity> players) {
this.players = players;
}
public void setHandlerForLeavingPlayers(HandlerForLeavingPlayers handlerForLeavingPlayers) {
this.handlerForLeavingPlayers = handlerForLeavingPlayers;
}
public boolean isValidGuess() {
return isValidGuess;
}
public void setValidGuess(boolean validGuess) {
isValidGuess = validGuess;
}
public Long getActiveCardId() {
return activeCardId;
}
public void setActiveCardId(Long cardId) {
this.activeCardId = cardId;
}
public String getActiveMysteryWord() {
return activeMysteryWord;
}
public void setActiveMysteryWord(String activeMysteryWord) {
this.activeMysteryWord = activeMysteryWord;
}
public Long getActivePlayerId() {
return activePlayerId;
}
public Long getId() {
return id;
}
public void setScoreboard(Scoreboard scoreboard) {
this.scoreboard = scoreboard;
}
public List<Long> getCardIds() {
return CardIds;
}
public List<Long> getPassivePlayerIds() {
return passivePlayerIds;
}
public void setActivePlayerId(Long activePlayerId) {
this.activePlayerId = activePlayerId;
}
public void setId(Long id) {
this.id = id;
}
public Scoreboard getScoreboard() {
return scoreboard;
}
public void setAngels(List<Angel> angels) {
this.angels = angels;
}
public List<Angel> getAngels() {
return angels;
}
public void setDevils(List<Devil> devils) {
this.devils = devils;
}
public List<Devil> getDevils() {
return devils;
}
public int getNumOfBots(){
return devils.size()+angels.size();
}
public String getGuess() {
return Guess;
}
public void setGuess(String guess) {
Guess = guess;
}
public void setCardIds(List<Long> cardIds) {
CardIds = cardIds;
}
public void setIsValidGuess(boolean validGuess) {
isValidGuess = validGuess;
}
public boolean getIsValidGuess(){
return this.isValidGuess;
}
public Boolean getHasEnded() {
return hasEnded;
}
public void setHasEnded(Boolean hasEnded) {
this.hasEnded = hasEnded;
}
public List<Bot> getBots(){
List<Bot> bots = new ArrayList<>();
bots.addAll(angels);
bots.addAll(devils);
return bots;
}
public void setPassivePlayerIds(List<Long> passivePlayerIds) {
this.passivePlayerIds = passivePlayerIds;
}
/**Draws card from stack and sets it as the current active card
*@Param: GameEntity
*@Returns: GameEntity
*@Throws: 409: Empty stack
* */
public GameEntity drawCardFromStack(){
if (this.getCardIds().size() > 0){
List<Long> cardIds = this.getCardIds();
this.setActiveCardId(cardIds.remove(cardIds.size()-1));
return this;
}
else{
throw new ConflictException("The CardStack is empty! The game should have ended already!");
}
}
}
|
stackql/stackql
|
internal/test/stackqltestutil/locator.go
|
package stackqltestutil
import (
"fmt"
"io/ioutil"
"github.com/stackql/stackql/internal/stackql/dto"
"github.com/stackql/stackql/internal/stackql/entryutil"
"github.com/stackql/stackql/internal/stackql/sqlengine"
"github.com/stackql/stackql/internal/stackql/util"
)
func GetRuntimeCtx(providerStr string, outputFmtStr string, testName string) (*dto.RuntimeCtx, error) {
saKeyPath, err := util.GetFilePathFromRepositoryRoot("test/assets/credentials/dummy/google/dummy-sa-key.json")
if err != nil {
return nil, fmt.Errorf("test failed on %s: %v", saKeyPath, err)
}
oktaSaKeyPath, err := util.GetFilePathFromRepositoryRoot("test/assets/credentials/dummy/okta/api-key.txt")
if err != nil {
return nil, fmt.Errorf("test failed on %s: %v", saKeyPath, err)
}
appRoot, err := util.GetFilePathFromRepositoryRoot("test/.stackql")
if err != nil {
return nil, fmt.Errorf("test failed: %v", err)
}
dbInitFilePath, err := util.GetFilePathFromRepositoryRoot("test/db/setup.sql")
if err != nil {
return nil, fmt.Errorf("test failed on %s: %v", dbInitFilePath, err)
}
registryRoot, err := util.GetForwardSlashFilePathFromRepositoryRoot("test/registry")
if err != nil {
return nil, fmt.Errorf("test failed on %s: %v", dbInitFilePath, err)
}
return &dto.RuntimeCtx{
Delimiter: ",",
ProviderStr: providerStr,
LogLevelStr: "warn",
ApplicationFilesRootPath: appRoot,
AuthRaw: fmt.Sprintf(`{ "google": { "credentialsfilepath": "%s" }, "okta": { "credentialsfilepath": "%s", "type": "api_key" } }`, saKeyPath, oktaSaKeyPath),
RegistryRaw: fmt.Sprintf(`{ "url": "file://%s", "useEmbedded": false }`, registryRoot),
OutputFormat: outputFmtStr,
DbFilePath: fmt.Sprintf("file:%s?mode=memory&cache=shared", testName),
DbInitFilePath: dbInitFilePath,
}, nil
}
func getBytesFromLocalPath(path string) ([]byte, error) {
fullPath, err := util.GetFilePathFromRepositoryRoot(path)
if err != nil {
return nil, err
}
return ioutil.ReadFile(fullPath)
}
func BuildSQLEngine(runtimeCtx dto.RuntimeCtx) (sqlengine.SQLEngine, error) {
sqlEng, err := entryutil.BuildSQLEngine(runtimeCtx)
if err != nil {
return nil, err
}
googleRootDiscoveryBytes, err := getBytesFromLocalPath("test/db/google._root_.json")
if err != nil {
return nil, err
}
googleComputeDiscoveryBytes, err := getBytesFromLocalPath("test/db/google.compute.json")
if err != nil {
return nil, err
}
googleContainerDiscoveryBytes, err := getBytesFromLocalPath("test/db/google.container.json")
if err != nil {
return nil, err
}
googleCloudResourceManagerDiscoveryBytes, err := getBytesFromLocalPath("test/db/google.cloudresourcemanager.json")
if err != nil {
return nil, err
}
googleBQDiscoveryBytes, err := getBytesFromLocalPath("test/db/google.bigquery.json")
if err != nil {
return nil, err
}
sqlEng.Exec(`INSERT INTO "__iql__.cache.key_val"(k, v) VALUES(?, ?)`, "https://www.googleapis.com/discovery/v1/apis", googleRootDiscoveryBytes)
if err != nil {
return nil, err
}
sqlEng.Exec(`INSERT INTO "__iql__.cache.key_val"(k, v) VALUES(?, ?)`, "https://www.googleapis.com/discovery/v1/apis/compute/v1/rest", googleComputeDiscoveryBytes)
if err != nil {
return nil, err
}
sqlEng.Exec(`INSERT INTO "__iql__.cache.key_val"(k, v) VALUES(?, ?)`, "https://container.googleapis.com/$discovery/rest?version=v1", googleContainerDiscoveryBytes)
if err != nil {
return nil, err
}
sqlEng.Exec(`INSERT INTO "__iql__.cache.key_val"(k, v) VALUES(?, ?)`, "https://cloudresourcemanager.googleapis.com/$discovery/rest?version=v3", googleCloudResourceManagerDiscoveryBytes)
if err != nil {
return nil, err
}
sqlEng.Exec(`INSERT INTO "__iql__.cache.key_val"(k, v) VALUES(?, ?)`, "https://bigquery.googleapis.com/$discovery/rest?version=v2", googleBQDiscoveryBytes)
if err != nil {
return nil, err
}
return sqlEng, nil
}
|
maciejg-git/vue-bootstrap-icons
|
dist-mdi/mdi/head-remove.js
|
import { h } from 'vue'
export default {
name: "HeadRemove",
vendor: "Mdi",
type: "",
tags: ["head","remove"],
render() {
return h(
"svg",
{"xmlns":"http://www.w3.org/2000/svg","width":"24","height":"24","viewBox":"0 0 24 24","class":"v-icon","fill":"currentColor","data-name":"mdi-head-remove","innerHTML":"<path d='M13 3C9.2 3 6.2 5.9 6 9.7L4.1 12.2C3.9 12.5 4.1 13 4.5 13H6V16C6 17.1 6.9 18 8 18H9V21H16V16.3C18.4 15.2 20 12.8 20 10C20 6.1 16.9 3 13 3M15.1 12.5L13 10.4L10.9 12.5L9.5 11.1L11.6 9L9.5 6.9L10.9 5.5L13 7.6L15.1 5.5L16.5 6.9L14.4 9L16.5 11.1L15.1 12.5Z' />"},
)
}
}
|
alphagov-mirror/pay-ledger
|
src/main/java/uk/gov/pay/ledger/transaction/model/TransactionFactory.java
|
package uk.gov.pay.ledger.transaction.model;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.gov.pay.ledger.transaction.entity.TransactionEntity;
import uk.gov.pay.ledger.transaction.search.model.SettlementSummary;
import uk.gov.pay.ledger.transaction.search.model.RefundSummary;
import uk.gov.pay.ledger.transaction.search.model.PaymentSettlementSummary;
import java.io.IOException;
import java.util.Map;
import java.util.Optional;
import static uk.gov.pay.ledger.util.JsonParser.safeGetAsBoolean;
import static uk.gov.pay.ledger.util.JsonParser.safeGetAsDate;
import static uk.gov.pay.ledger.util.JsonParser.safeGetAsLong;
import static uk.gov.pay.ledger.util.JsonParser.safeGetAsString;
public class TransactionFactory {
private static final Logger LOGGER = LoggerFactory.getLogger(TransactionFactory.class);
private ObjectMapper objectMapper;
@Inject
public TransactionFactory(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
public Transaction createTransactionEntity(TransactionEntity entity) {
if ("REFUND".equals(entity.getTransactionType())) {
return createRefund(entity);
}
return createPayment(entity);
}
private Transaction createPayment(TransactionEntity entity) {
try {
JsonNode transactionDetails = objectMapper.readTree(Optional.ofNullable(entity.getTransactionDetails()).orElse("{}"));
Address billingAddress = Address.from(
safeGetAsString(transactionDetails, "address_line1"),
safeGetAsString(transactionDetails, "address_line2"),
safeGetAsString(transactionDetails, "address_postcode"),
safeGetAsString(transactionDetails, "address_city"),
safeGetAsString(transactionDetails, "address_county"),
safeGetAsString(transactionDetails, "address_country")
);
String cardBrand = safeGetAsString(transactionDetails, "card_brand_label");
CardType cardType = CardType.fromString(safeGetAsString(transactionDetails, "card_type"));
CardDetails cardDetails = CardDetails.from(entity.getCardholderName(), billingAddress, cardBrand,
entity.getLastDigitsCardNumber(), entity.getFirstDigitsCardNumber(),
safeGetAsString(transactionDetails, "expiry_date"), cardType);
Map<String, Object> metadata = null;
if (transactionDetails.has("external_metadata")) {
metadata = objectMapper.readValue(
objectMapper.treeAsTokens(transactionDetails.get("external_metadata")),
new TypeReference<>() {
});
}
RefundSummary refundSummary = RefundSummary.from(entity);
PaymentSettlementSummary paymentSettlementSummary = new PaymentSettlementSummary(
safeGetAsDate(transactionDetails, "capture_submitted_date"),
safeGetAsDate(transactionDetails, "captured_date"),
entity.getPayoutEntity().map(payoutEntity -> payoutEntity.getPaidOutDate()).orElse(null)
);
return new Payment.Builder()
.withGatewayAccountId(entity.getGatewayAccountId())
.withAmount(entity.getAmount())
.withReference(entity.getReference())
.withDescription(entity.getDescription())
.withState(entity.getState())
.withLanguage(safeGetAsString(transactionDetails, "language"))
.withExternalId(entity.getExternalId())
.withReturnUrl(safeGetAsString(transactionDetails, "return_url"))
.withEmail(entity.getEmail())
.withPaymentProvider(safeGetAsString(transactionDetails, "payment_provider"))
.withCreatedDate(entity.getCreatedDate())
.withCardDetails(cardDetails)
.withDelayedCapture(safeGetAsBoolean(transactionDetails, "delayed_capture", false))
.withExternalMetadata(metadata)
.withEventCount(entity.getEventCount())
.withGatewayTransactionId(safeGetAsString(transactionDetails, "gateway_transaction_id"))
.withCorporateCardSurcharge(safeGetAsLong(transactionDetails, "corporate_surcharge"))
.withFee(entity.getFee())
.withNetAmount(entity.getNetAmount())
.withRefundSummary(refundSummary)
.withTotalAmount(entity.getTotalAmount())
.withSettlementSummary(paymentSettlementSummary)
.withMoto(entity.isMoto())
.withLive(entity.isLive())
.withSource(entity.getSource())
.withWalletType(safeGetAsString(transactionDetails, "wallet"))
.withGatewayPayoutId(entity.getGatewayPayoutId())
.build();
} catch (IOException e) {
LOGGER.error("Error during the parsing transaction entity data [{}] [errorMessage={}]", entity.getExternalId(), e.getMessage());
}
return null;
}
private Transaction createRefund(TransactionEntity entity) {
try {
JsonNode transactionDetails = objectMapper.readTree(Optional.ofNullable(entity.getTransactionDetails()).orElse("{}"));
JsonNode refundPaymentDetails = transactionDetails.get("payment_details");
CardType cardType = CardType.fromString(safeGetAsString(refundPaymentDetails, "card_type"));
CardDetails cardDetails = CardDetails.from(entity.getCardholderName(), null,
safeGetAsString(refundPaymentDetails, "card_brand_label"), entity.getLastDigitsCardNumber(),
entity.getFirstDigitsCardNumber(), safeGetAsString(refundPaymentDetails, "expiry_date"), cardType);
Payment paymentDetails = new Payment.Builder()
.withReference(entity.getReference())
.withDescription(entity.getDescription())
.withEmail(entity.getEmail())
.withCardDetails(cardDetails)
.withWalletType(safeGetAsString(refundPaymentDetails, "wallet"))
.build();
SettlementSummary refundSettlementSummary = new SettlementSummary(
entity.getPayoutEntity().map(payoutEntity -> payoutEntity.getPaidOutDate()).orElse(null)
);
return new Refund.Builder()
.withGatewayAccountId(entity.getGatewayAccountId())
.withAmount(entity.getAmount())
.withGatewayTransactionId(entity.getGatewayTransactionId())
.withState(entity.getState())
.withExternalId(entity.getExternalId())
.withCreatedDate(entity.getCreatedDate())
.withEventCount(entity.getEventCount())
.withRefundedBy(safeGetAsString(transactionDetails, "refunded_by"))
.withRefundedByUserEmail(safeGetAsString(transactionDetails, "user_email"))
.withParentExternalId(entity.getParentExternalId())
.withGatewayPayoutId(entity.getGatewayPayoutId())
.withPaymentDetails(paymentDetails)
.withSettlementSummary(refundSettlementSummary)
.build();
} catch (IOException e) {
LOGGER.error("Error during the parsing transaction entity data [{}] [errorMessage={}]", entity.getExternalId(), e.getMessage());
}
return null;
}
}
|
elifesciences/elife-xpub
|
test/pageObjects/demographic.js
|
<filename>test/pageObjects/demographic.js
import config from 'config'
import { Selector } from 'testcafe'
const demographic = {
url: new RegExp(
`${config.get('pubsweet-server.baseUrl')}/survey/[a-f0-9-]{36}`,
),
question1: Selector('[data-test-id=survey-question-1]'),
question2: Selector('[data-test-id=survey-question-2]'),
question3: Selector('[data-test-id=survey-question-3]'),
submit: Selector('[data-test-id=submit]'),
}
export default demographic
|
Fippe94/openEtG
|
views/Upgrade.js
|
<filename>views/Upgrade.js
"use strict";
var px = require("../px");
var gfx = require("../gfx");
var sock = require("../sock");
var Cards = require("../Cards");
var etgutil = require("../etgutil");
var userutil = require("../userutil");
module.exports = function() {
function upgradeCard(card) {
if (!card.isFree()) {
if (card.upped) return "You cannot upgrade upgraded cards.";
var use = card.rarity != -1 ? 6 : 1;
if (cardpool[card.code] >= use) {
sock.userExec("upgrade", { card: card.code });
}
else return "You need at least " + use + " copies to be able to upgrade this card!";
}
else if (sock.user.gold >= 50) {
sock.userExec("uppillar", { c: card.code });
goldcount.text = sock.user.gold + "$";
}
else return "You need 50$ to afford an upgraded pillar!";
}
function unupgradeCard(card) {
if (card.rarity || (card.shiny && card.upped)) {
if (!card.upped) return "You cannot unupgrade unupgraded cards.";
sock.userExec("unupgrade", { card: card.code });
}
else return "You cannot unupgrade pillars; sell it instead."
}
function polishCard(card) {
if (!card.isFree()) {
if (card.shiny) return "You cannot polish shiny cards.";
if (card.rarity == 5) return "You cannot polish Nymphs.";
var use = card.rarity != -1 ? 6 : 2;
if (cardpool[card.code] >= use) {
sock.userExec("polish", { card: card.code });
}
else return "You need at least " + use + " copies to be able to polish this card!";
}
else if (sock.user.gold >= 50) {
sock.userExec("shpillar", { c: card.code });
goldcount.text = sock.user.gold + "$";
}
else return "You need 50$ to afford a shiny pillar!";
}
function unpolishCard(card) {
if (card.rarity || (card.shiny && card.upped)) {
if (!card.shiny) return "You cannot unpolish non-shiny cards.";
if (!card.rarity == 5) return "You cannot unpolish Nymphs.";
sock.userExec("unpolish", { card: card.code });
}
else return "You cannot unpolish pillars; sell them instead.";
}
function sellCard(card) {
if (card.rarity == -1) return "You really don't want to sell that, trust me.";
else if (card.isFree()){
if (sock.user.gold >= 300){
sock.userExec("upshpillar", {c: card.code});
goldcount.text = sock.user.gold + "$";
}else return "You need 300$ to afford a shiny upgraded pillar!";
}else{
var codecount = etgutil.count(sock.user.pool, card.code);
if (codecount) {
sock.userExec("sellcard", { card: card.code });
goldcount.text = sock.user.gold + "$";
}
else return "This card is bound to your account; you cannot sell it.";
}
}
function eventWrap(func){
return function(){
var error = selectedCard ? func(Cards.Codes[selectedCard]) : "Pick a card, any card.";
if (error) twarning.text = error;
else adjustdeck();
}
}
function autoCards(){
sock.userExec("upshall");
adjustdeck();
}
function adjustdeck() {
cardpool = etgutil.deck2pool(sock.user.pool);
cardsel.cardpool = cardpool = etgutil.deck2pool(sock.user.accountbound, cardpool);
}
var cardpool, selectedCard;
var upgradeui = px.mkView(function(){
if (selectedCard) cardArt.texture = gfx.getArt(etgutil.asUpped(selectedCard, true));
});
var stage = {view:upgradeui,
bexit: [5, 50, ["Exit", require("./MainMenu")]],
bupgrade: [150, 50, ["Upgrade", eventWrap(upgradeCard)]],
bpolish: [150, 95, ["Polish", eventWrap(polishCard), function() { if (selectedCard) cardArt.texture = gfx.getArt(etgutil.asShiny(selectedCard, true)) }]],
bunupgrade:[150, 50, ["Unupgrade", eventWrap(unupgradeCard)]],
bunpolish:[150, 95, ["Unpolish", eventWrap(unpolishCard), function() { if (selectedCard) cardArt.texture = gfx.getArt(etgutil.asShiny(selectedCard, false)) }]],
bsell:[150, 140, ["Sell", eventWrap(sellCard)]],
bauto:[5, 140, ["Autoconvert", autoCards]],
};
var goldcount = px.domText(sock.user.gold + "$");
var tinfo = px.domText("");
var tinfo2 = px.domText("");
var tinfo3 = px.domText("");
var twarning = px.domText("");
stage.domtext = [
[5, 240, goldcount],
[250, 50, tinfo],
[250, 140, tinfo2],
[250, 95, tinfo3],
[100, 170, twarning],
];
var cardArt = new PIXI.Sprite(gfx.nopic);
cardArt.position.set(734, 8);
upgradeui.addChild(cardArt);
var selectedCardArt = new PIXI.Sprite(gfx.nopic);
selectedCardArt.position.set(534, 8);
upgradeui.addChild(selectedCardArt);
var cardsel = new px.CardSelector(stage.domtext, null,
function(code){
var card = Cards.Codes[code];
selectedCardArt.texture = gfx.getArt(code);
cardArt.texture = gfx.getArt(etgutil.asUpped(code, true));
selectedCard = code;
if (card.upped) {
px.setDomVis("bupgrade", false);
px.setDomVis("bunupgrade", true);
tinfo.text = card.isFree() ? "" : card.rarity != -1 ? "Convert into an 6 unupgraded copies." : "Convert into an unupgraded version.";
}else{
tinfo.text = card.isFree() ? "50$ to upgrade" : card.rarity != -1 ? "Convert 6 into an upgraded version." : "Convert into an upgraded version.";
px.setDomVis("bupgrade", true);
px.setDomVis("bunupgrade", false);
}
if (card.rarity == 5) {
px.setDomVis("bpolish", false);
px.setDomVis("bunpolish", false);
tinfo3.text = "This card cannot be " + (card.shiny ? "un" : "") + "polished.";
}
else if (card.shiny){
px.setDomVis("bpolish", false);
px.setDomVis("bunpolish", true);
tinfo3.text = card.isFree() ? "" : card.rarity != -1 ? "Convert into 6 non-shiny copies." : "Convert into 2 non-shiny copies.";
}else{
tinfo3.text = card.isFree() ? "50$ to polish" : card.rarity == 5 ? "This card cannot be polished." : card.rarity != -1 ? "Convert 6 into a shiny version." : "Convert 2 into a shiny version.";
px.setDomVis("bpolish", true);
px.setDomVis("bunpolish", false);
}
px.setDomVis("bsell", ~card.rarity);
document.getElementById("bsell").value = card.isFree() ? "Polgrade" : "Sell";
tinfo2.text = card.rarity == -1 ? "" : card.isFree() ? "300$ to upgrade & polish" :
"Sell for " + userutil.sellValues[card.rarity] * (card.upped ? 6 : 1) * (card.shiny ? 6 : 1) + "$";
twarning.text = "";
}, true
);
upgradeui.addChild(cardsel);
cardsel.cardminus = {};
adjustdeck();
px.refreshRenderer(stage);
px.setDomVis("bupgrade", false);
px.setDomVis("bpolish", false);
px.setDomVis("bsell", false);
px.setDomVis("bunupgrade", false);
px.setDomVis("bunpolish", false);
}
|
TianyiChen/rdcpp-data
|
data/581.cpp
|
<gh_stars>0
int IOJFcxH,X2SzN,M ,IMz//
, /*n1h*/Gx0,
nrs
, hT
, x,XCFN8l ,
EJj ,CjRy7B ,tP3M ,KQdZ
, rGkz ,Qw ,
Bm3td, rwv,
isAv,ht , H,Nt , WoL,/*of*/ WC,q1g
, Rpvm ,
jY,
hgC,CN ,/*B4qP*/uf//9G
,
f8kMXAK/**/
, LZ ,//eT
oeqVC,GX,//K
/*2TwaX*/ w//ixdO
,
h1E46 , Y7,//jx
UYgs , tnW
,RC,ROXe ,e ,
Y8,
pQVZ2T, Pz3,Sdu, sn
//5
,XdTt,
WC1,
HR3
,OUnNfT,
wcxXW /*z*/,oS9v
,W1X ,zA ,
ZNmi ; //Cu9g
void f_f0
(){volatile int extHJ
,
d51B ,Lqa49
/*zWo0*/,/*GQqh*/n,nQh,
o7h
,tbD8
,AHBtc5D
, /**/
F
,
//lYZ
BqYa5,q
;ZNmi= q +
extHJ /*f*/+
d51B+ Lqa49 //nB6F9
+n ;if
(true )return
; else{
for(int i=1; i< 1
;++i )
//
{int I68;volatile int/*J*/ HWc2V,/*JZ*/y5iX3
, /*mueF*/j8d, mCrqE
; ;//oSl
{{{{ }} }} I68=mCrqE+HWc2V + y5iX3 + j8d
;}for
(int /*7*/i=1;i<2//W
;++i){;{ volatile int lL6 ,
gi7D,oLb ,d3gDL ; for (int
i=1; i<3 ;++i ) if(
true ) { }
else
if(
true )
IOJFcxH=d3gDL+lL6
+ gi7D +
oLb
; else{ {}if(true) for/*QD*/ (int i=1 ;i<
4 ;++i)
{ } else {
;
; }} {}
{} return ; for
(int /*kM*/
i=1 ; i< 5
;++i ) ;}
} /*SEH*/{{
return ;}/*hvq*/ ;}{ ; if( true )
{volatile int pB8,
tb
;//F4v
X2SzN =tb/*6*/+pB8 ;
}else{int
I4b ;volatile int//UtV
t7//KHt
,OW3,/*0zJA*/j ;
I4b=j +t7 + OW3
;return ; }
} {volatile int
Ci
,
/*9*/
OT,f3eT
;if (
/*oG*/true
)
if( true ) {volatile int mF ,Pgnn
, ov;//2iycg
if ( true )
/*rC*/{ volatile int /**//*kr2Sc*/ FG; ;
;M
= FG ;}else
IMz=
ov
+mF/*5*/+Pgnn ; } else for(int i=1//iX
;
i< //i5
6;++i)
{
{ { }{} }}
else if
(true)
return ; else
{
;} //Q
Gx0
=
f3eT +Ci + OT;
}}if (
true )
{{ return ;for(int
i=1/**/
;
i< 7 ;++i) ; return
;} for (int i=1;
i< 8 ;++i ){ volatile int yX4w
,WwLoT, Z5,f1Y; if ( true )if(true) nrs= f1Y
+ yX4w +WwLoT + Z5
;//uLr
else for
(int i=1 ;i<
9 ;++i) { /*oQ9*/return ;;} else {
return ;
}return ;{{
}} }return ;
for(int i=1;
i</*48pn*/10 ;++i
){
/*24*/{
return ;/*yY*/for
(int i=1
;
i<
11
;++i){; }}
{{} } { int
fG ; //
volatile int PUq, Sb, //IIoB2A
y;for(int i=1
; i<
12
;++i
){ }
fG =
y
+
PUq+Sb ;{
return ;
{
}
{ }/*SD*/}{} /*x*/
}
{//Fr
{
; { return
; }}} }return ;
}else { int nSU
; volatile int xtW
,
v6Mh
, cUc, J7xw
,//Xp
gt
,nF7W, CxP,B3
,
W
,/*Zn*/ BzqE; {
{
{
}}
{//uNeE
{ volatile int YC;hT/*8*/=/*kNe*/YC
;} } } nSU =
BzqE+ xtW
+ v6Mh
+ cUc ; for (int
i=1; i<13;++i) if (
true) {;return ; {;}}else x=J7xw +gt+
nF7W//3n8He
+
CxP+ B3 +W;
{ return
;{ {
{
}
{}
}}} {
volatile int fAVX ,
Y7i
, jFm
//G
,Wwn ,dY85M;return
; XCFN8l= dY85M + fAVX
+
Y7i
+ jFm +
Wwn
;{
if//0M
( true)
for(int i=1; i< 14
;++i )
{} else
{volatile int
GW;EJj= GW
;}{}
return ;{{
for
(int /*yyw*/
i=1
; i<15;++i
) return
;
}
if
(true
){
//Cl
}
else
{} {
} {{
//7J
} {}}}{ {} return ; } }{for(int
i=1;i<16 ;++i /**/){
}/*5*/}return ;/*5m*/ }
}{int XB/**/;volatile int p ,ji,
pz , //CHDY
pDTL , Sx;{
{; }if ( true){{ {}}
}
//R
else{ {{
} }{ }} }{ {
volatile int IjA//lG
//r5VZ
,
FZq,b /*c50*/; for(int
i=1 ;
i<17
;++i )
if
(
true)
{}else for(int i=1;i<18
;++i//NW
/*6be*/)for(int
i=1;
i< 19
;++i)//J
{}
/*eG8J*/if
(//4B
true
)
for(int i=1 ; i<20/*a1r*/;++i )
{}else{
for(int i=1 ;
i<21 ;++i ){ }}if ( true ) CjRy7B = b+
IjA +FZq
;else
{
for
(int
i=1 ; i<
22;++i ) ;}//UT
} return ; { {{volatile int gN0z ;{
}
tP3M= gN0z ;} }/*2Uw*///C9
{{
}}//U
{int fZc; //E
volatile int G2B
,mReJ ;
fZc
=mReJ+/*V*/G2B
;}}{ {/*xre*/} {
}
{
/*ze*/{ }//SUB
} return
; /*B*/
{return ;} //k
}} /*I*/ { for (int
i=1;i<
23 ;++i ) ;if ( true) return ;/**/ else {int dmU ; volatile int vZe
,Ko
,
Ys , uYp
,
HT2;for(int
i=1;
i<24;++i ) return
; ; if (true ) {{ }/*R00*/} else
if//L2n
( true
)
dmU = HT2 +vZe//C
+ Ko
+Ys/*VHr*/+uYp;else ; }{/*I7*/volatile int kkrSz,
Ry
,i5f/*UEr*/,FNd; //e8n1
{
if(
/*AtU*//*9*/
true )//
{//gU
//f
} else
{ } return
; {{
}{
}
}}{
volatile int aT3tX,/*DAA*/DS;if (true )KQdZ =//0mf
DS+ aT3tX;else ;}
{ }rGkz =
FNd + kkrSz//
+
Ry
+
i5f;
}}/*R*/{int
f; volatile int
lt ,
vc ,
suu
/*u*/,
/*Ry9*/V4E ;{{}if (true );else/*76*/ if
(true
)
{/*VwL*/ { {
} }
} else { } }
{volatile int Vd , Tff
;
Qw=
Tff + //iw
Vd
;}/*cTU*/for (int i=1 ; i<25 //
;++i )
;
f
=
V4E+ lt+ vc+
/**/suu;/**/for
(int i=1
;/*bYG*/ i< 26;++i
)for(int i=1 ; i<27;++i) {for (int i=1
;
i<28;++i
) for(int i=1 ; i<
29 ;++i ) {/*p6m*/{
}/*e*/} for
(int i=1
;/*Ij9*/
i<30 ;++i ){ for(int i=1//v
;
i<31;++i//H
) {volatile int Z,
I6GJ
, Zfke ; if(true
)for(int
i=1/*C*/;i< 32
;++i
)
{
}
else {} Bm3td=
Zfke+
Z +
I6GJ; }
} }
}if (true
)XB=/*O*/ Sx
+ p
+ji +pz+
pDTL
;else { if (true ){ {}
}else {{if(true
){ if(true
) {}else for(int i=1/*Kyn*/; i<
33 ;++i/*FlX*/ ){}{}/*OK*/
}else
{}{}{}} {{
{ }} if (
/*z*/ true ){//cun
}else for(int i=1
;i< 34;++i
) {} }}{/**/ {
}
{ }
}} return//C9D
;
if(true)/*Z3*/{int m6; volatile int
Me
, ewVBs ,
XN4
, PR1
; return //P
; m6 =
PR1+
Me +
ewVBs+ XN4; { ; }}
else
for (int i=1 ; i<35 //l
;++i/*q0X*/)return ;{
{
{{} }} {volatile int//DK3
u2 //Kv
, S
, ec7 ;
rwv //FC
=
ec7+ u2//tGf4ju
+
S
;/*sw2*/{ //MK
if( true){} else ;
}{return ;}
}}
} isAv
/*MQV*/=//rx
nQh
+
o7h + tbD8 +AHBtc5D +F //R
+
BqYa5;return ;return ;}
void f_f1 (){volatile int uNVzjO ,
i1s
, Ktj
,
PFEA7/**/,ORd
,itS;{
for(int
//A
i=1
;i<
36 //X
;++i);
;{
int cuhR
; volatile int kjR, Lo,
nS
,TvL
,fDQ ;
for(int
i=1
; i< //5OB
37
;++i
)if
(
true) if
(true) cuhR //r
=fDQ +
kjR+ Lo+ nS + TvL
;
else if
( true ){if (
true); else ; }
else{//L5B
{
} }
else
if (
true
)
{ if/*B*/( true
)
return ;else{
;//x
} {{ }}}
else{
{ {}
if
( /*Bj*/true){} else{ } return ; }
{{
;{
}}}}
return ;for (int i=1
; i<38 ;++i) //zQ6i
{;
} }
;;
}{ volatile int
ZLx
,
F0gLjB, rfr ,
I3Z;if(true )
if/*iu*/(true )return ;else
{
{ //oOTaM
{
return ;
for (int
i=1; i<39//Od
;++i ) {}/*1Qo*/}}
{; }
}else{{
{for (int i=1
;i<40
;++i )if(/**/
true//c
) {}else
{
}
;if
(true) { }/*9*///
else{ }} { } }
{{ }for(int
i=1 ;i< 41;++i) return ;{
int Ea
; volatile int
wr8;Ea =wr8;; } }
{
{ {}/**/{}} //yMX
if( true
/**/ )
for /*4d*/ (int
i=1 ;
i<
42;++i
){for/*0Cl*/(int i=1;
i< 43 ;++i)
; { }
}//ZbNS
else ;{} }}/*c*/ht
=/*HW*/I3Z+ZLx/*Md*/+ F0gLjB+rfr;return
; {volatile int s3, zhQ,SCahC;;; {return ;
} if (//
true)H//X
= SCahC
+ s3+ zhQ; else if(
true) if
(//ce
true)
{
{
{ } }
return ;
}
else
{volatile int
Q3Ke,
J;
Nt =J+Q3Ke;}else for
(int i=1;
i</**/44
;++i )
for (int i=1 ; i< 45
;++i
){ //I
{;{}for (int i=1 ; i< 46/*WG*/;++i){} } } } { { {
int cW
//3
;
volatile int zGXK
,KaoO2e
//Vnf
,
c5 ;for (int i=1; /*6DZ*/ i<47
;++i
)cW =c5
+ zGXK+ KaoO2e
;
}
}return ;
} } { { volatile int Y
/*Bs*/, iomsx,JOG , CXa/*otur2*/ , kJSw, AJC,
G//qH
/*O*/; {
volatile int
qhKB
,
GZ ;{
volatile int
yZ
,
w0hnD;
WoL= w0hnD+ yZ
;}
/*PO*/{
} WC
=GZ
+ qhKB;}
for (int i=1 ;i<48;++i )
for/*fY5e*/ //H
(int
i=1;
i< 49 ;++i ) q1g= G +//uxKw
Y+
iomsx
;
Rpvm
=JOG +CXa//k
+kJSw + AJC; } ;
{{
/*lW*/return ;;{
}
{
return
//wq1W
; } }{for (int i=1 ; i< 50;++i )
;} } }//N
{
{ volatile int ez2
,
kQ,fN
,hVxT;if(//n
true)/*QTI*///8
{{
}for(int i=1; /**/i<
51;++i
) for/*lM*/(int i=1;i<52
;++i) for
(int /*F*/ i=1
; i<
53 ;++i)
for (int
i=1 ;i<54
;++i
)
{}//zj7
}else {if
( true )return/*2m5b*/ ;/**/else
return
; if(true ) {/**/volatile int
qiv,l6A;
jY
=
l6A +qiv ;/*7qci*/ } else { {
} {} }}
hgC =hVxT+
ez2 +
kQ+fN
; return ; }{ ;
{
{volatile int Mm,nPn;/*u3CQO6*/
CN= nPn+Mm
;; }//Lm
return ;
} }
{
{{
}
{//FT
; ; }
{}} ;/*z*/return ; }return
;
return ;}
if(true)
uf
=
itS+uNVzjO +/*3l*/
//
i1s
+ Ktj/**/+PFEA7+
ORd; else { int
z6
; volatile int K4L//iR
/*rK*/ , vEa1n
,gv /*nh*/,
Wzs,IYppx
, VhO ,YU //llbt
,K,
Bb2;{; {//7A4
for/*gFiTE*/
/*PHkC*/(int i=1; i<55;++i ){ }/*li*/
{}; if
(
true){ }
else/*ulZd*/ return
; } }/*fD*/
{ volatile int
rVt
,U3P0e
, vgp ,/*j*/
pj ;{{//KlR
}
{
{volatile int
NAQ ;f8kMXAK=NAQ; }
}} LZ
/*Z*/ =
pj+
rVt+U3P0e
+ //UoBt
vgp
;
}/*qh*/ z6=Bb2+
K4L
+ vEa1n
+gv ; {{{
for
(int
i=1; i<
56;++i/*p*/){} }
}
{return ; {for/*Y*/(int i=1//Y
;
i< 57
;++i
)return ; } /*B*/{
return ;
}
} { {
for(int
i=1; i< 58
;++i){}
{} {{}} } }
} /*m7Eu*/oeqVC
=Wzs
+IYppx+VhO+ YU
+K; }
return/*e0WhH*/ ;
}void /*2N*/ f_f2()
{
{return ;{ int eAhv;volatile int
Qbs,
mp,
QiS ; return
/*6v*/ ;eAhv =QiS+ Qbs +
mp ; {{volatile int WFO4
, s60Uj,m8Ov ;
{}if ( true
)
GX = m8Ov + WFO4 + s60Uj ;//Q
else if (true) return ;else { } {
} }{ //0BE
return ;
}
//
}
}{
volatile int /*WAuI*/ a4RZV , m,//Gv
Z4 ,
aU//ZoRD
,blo8CJ
, viE, YZ
; if( true )if (/*5K1*/true/*IR0h*/ ) w
= YZ
+
a4RZV+
m;else
{ volatile int I2,
vv//D
, zEX6v;
{int c
; //c
volatile int wS245 , OL
/**/;
c
//C7smdv
=
OL+wS245 ; {{}//li
}
}for
(int /*MPc*/ i=1
;
i< 59;++i ) for//L
(int /*r*/
i=1
;i<
60
;++i )h1E46= zEX6v
+//2
I2 +vv; }//X
else{/*4*/ ;{
volatile int KOt,
vWl5; {
;
}//4l
if(
true//xF
)return
//dpH
;else Y7 =
vWl5
+ KOt
;
{} }
; }if/*ZWR*/ (
true)
{
return ;{ ; }//9X
}else{
{ { } ; }
for(int i=1 ;
i< //rB9y
61;++i )
{ volatile int wE ,ZA8l ;//QpV7lT
UYgs =
ZA8l+ wE; { /**/} }
}
tnW
=
Z4+
aU + blo8CJ+viE
;}{int Xxqh ; volatile int
L
,O6hI
,
Losi,qi,
vdqh ;{return ;
{ if(true ) return/*H*/ ; else{/*2Vz*/}}{ }} Xxqh=vdqh
+L+
O6hI+
Losi+
qi ;for(int i=1;i<
62 ;++i ){{
{ }
}//pE
}}}return//9w
;
if(//3
true )if
( true) {{ return
;return ; return
;/*8*/ {
for(int i=1
;
i< 63;++i
)
{
}} } {return ; ; {return ;{
{} return
;
{}
} if /**/( /*w*/ true /*GgL84H*/) { }
else
{ }for (int i=1 ;
i<
64;++i) {{ /*a*/
}{}
}} }
if
( true)
{for(int i=1/*mzA*/;i<65;++i//Ydj
) {
{/*9cp*/volatile int
v , iVC
,
ZS7bl /*W7v*/ ,
qr2W , JzrM ;
//
RC = JzrM+v/*A*/;ROXe =
iVC+ ZS7bl+qr2W; { }
} for (int i=1; i<66 ;++i )return ;}
{ { for (int i=1 ;i<67 ;++i )
{
}; /*D*/ }
{} } }else {return ;;} {{ {/**/volatile int
Dj//KZ
, sn2 , tQJ,XM , QS;e =QS
+Dj +
/*tW*/sn2
; Y8 = tQJ
+ XM/*C*/
; { } }
}{{
return ;
}
{ {
}}}}} //cg
else ;else {
volatile int Wh7j ,//7X
Xp4C,//wj
kfi
,
HW, pMIEaw ;for
(int i=1
;i<68;++i
) return ;return
; for(int
i=1;i< 69
;++i)pQVZ2T =
pMIEaw +Wh7j//XQ
+
Xp4C+ kfi+ HW; }
{
int
qEFW, wZ/*1*/;
volatile int/*fsd*/
Eu
,
Jivo,//A8hk
T5,Fb4 ,
nMU,
YE ,ja14, X ,Ic; return ; wZ=Ic+
Eu+ Jivo+T5; qEFW = Fb4+nMU /*d7*/+
YE+ ja14+
X
;
for
(int i=1
//o6
;
i<70;++i) //k8
return ;
}{
volatile int
nx , qRpY, NB,
vmsb;//RV
Pz3 = vmsb
/**/
+ nx+
qRpY+NB ; {{{
} /*i*/}
{ { } }} {{return
; {//zq6py
} } for (int i=1
;
i<
71;++i
)
{ {}/*t*/
return ;;
}{
{ //Xcs
{
}{ }}}} for(int i=1;i<72;++i)//bb
/**/
return
;}return
; }
int main()
{volatile int tB4n, ch5Ofj
, rgjR , //N8p
z8KVC , LgL , bxV ,bKc
,cSucT; {{{ for
(int i=1; i<73
;++i)for (int i=1;i< 74
;++i/*0s*/) { {} { {}{
}
}
}{{
} }} {/*jm*/
{
}for(int
i=1 ;
i<75
;++i
) {/*dG2n*/ }
}
}/*rvla*/for(int i=1 ;i<76
;++i)
;
{ {{volatile int Xf8r
;
Sdu= Xf8r; {}
}/*e66*/
}return 340560788 ; for
(int
i=1
;i< 77
;++i ){ {
} } {
volatile int RV2, LQWY,
JE ,
WX ,
vA0;sn= vA0+ RV2+LQWY ; XdTt/*Njv*/=
JE +WX;}
//8
} ;if (true ) { { { { }} } if (//DI
true) ;else
for(int
i=1
;i< 78
;++i )
{{} {{ }}}}/*y*/else{ {{ }
return
941441209 ;
}
{
volatile int n3 ,ekD , Fth ;
for//K
(int
i=1;
i< 79;++i)
WC1=Fth
+n3
+ekD ;{
{}}}{ { if(
true){//
{//
}
{ {}/*uwG*/
}{ }} else/*u*/ { }
{
}}
{}//l
}} }{volatile int WR , C, lvH,
jM1vk
;{int//8
Ac;volatile int bEzu ,SSw//
, vK3o;
{
{ {
} {}}
return
1894454630 ;}{/*6F5*/if( //v
true
)
{volatile int tB6s3a ;/*5yVB*/{}HR3 =
tB6s3a
;}
else//aPj
{{}{if
(
true )return 1413749301 ;
else{ /*2i*/}} }{}
{//R
volatile int
hl2z,zj8WrpV//vJZ
;for (int
i=1
;i<
80/*ka*/ ;++i
)
{} OUnNfT =//v5k
zj8WrpV/*cHm*/+
hl2z;}
}{ for
(int
//BJed
i=1 ; i<
81
;++i )
{
{ }} }
Ac
= vK3o +
bEzu + SSw ;
} wcxXW = jM1vk +
WR+ //S
C +//qdY
lvH ; for (int
i=1 ; i< 82
;++i ){
return 1417371685 ;
;return 665516139 ; } { int R3h
;//2
volatile int pQ, Ssg
,
VISZ, qd ;;{ int
T3;volatile int Jx0Z9
, /*kEv*/easp0
, gRgm ;
{ for(int i=1
; i< 83 ;++i )
for (int i=1;i< 84;++i )//GMC
//XQ58
{ } }for (int
i=1 ;i<85 ;++i)//yQ
if/*6m5t*/( true) ; else T3= gRgm/*j*/+ Jx0Z9
+ easp0
/*1*/ ;}
for(int
i=1
; i< 86
;++i) if(true) for(int i=1 ;
i<//i
87;++i )R3h=qd+ pQ
+
Ssg+ VISZ ;//FxV
else if(
true ) {
if( true//O3
){} else {
int NIJ6; volatile int
fk30I
,
mArr; ;//
{for
(int //T
i=1 ;i<
88
;++i )
for
(int
i=1; i< 89 ;++i
)
{ }}NIJ6= mArr+ fk30I;//
}{ return
811621349; {/*yWY8*/ }}}
else{volatile int lDU
,
DI;for
(int
i=1 ; i<90;++i)//m
oS9v = DI+
lDU//sJL
//y5
; }} {{ if (
true) {{
{
} }
;
{ {}
} }/*c*//*lxb*/ else//FQ
{volatile int sBI,zARO7
;W1X
= zARO7+
sBI
;
}{ {}
}
} { { }}return/*7*/ 64241114 ; {
{ } { //FM
}
} } }
zA
=
cSucT
+
tB4n +ch5Ofj+ rgjR +z8KVC+LgL
+
bxV+ bKc
;//n
{
//MOG
;{
return 405410265
;/*TD*/;return 199411882 ;
} {{int
F59NiD
; volatile int M0u, yBnBo//lu
, T2
;/*Bu*/
F59NiD= T2+M0u +
yBnBo
;/*aSM*/
return //3
1848282205;
if
(
true
){
}else{{} if ( true
) {} else ;if//4PXX
(true)if(
true)
{} else ;
else for (int i=1; i<
91
;++i){} {
{//MBW
}}} }return 550816137/**/;{ for
(int i=1 ;
i< 92//d
;++i) {for (int /*n*/i=1;
i< 93;++i )if( true //Cl
){; }
else for(int i=1
;i<94 ;++i ){} ; }for(int i=1;
i< 95;++i
) {}//d
{
} }//le
} ;} }
|
AghLearning/Lemoncode_JS_Bootcamp
|
Modulo_03/03_Laboratorio/app.js
|
console.log("Modulo 3: Laboratorio");
console.log("======================");
const product = { count: 3, price: 12.55, type: "ropa" };
const empleado = {
bruto: 35000,
hijos: 2,
pagas: 14
}
function getVat(product) {
switch (product.type) {
case "ropa":
return 10/100;
break;
case "alimentacion":
return 4/100;
break;
default:
return 21/100;
break;
}
}
function getTotalVat(product) {
return product.count > 0 ? product.price * getVat(product) : 0;
}
let precioTotal = 0;
const cantidad = (product.count <= 0) ? 0 : product.count;
if (cantidad > 0) {
precioTotal = product.count * product.price;
}
console.log("Precio Total: " + precioTotal);
const precioTotalNuevo = (product.count <= 0) ? 0 : product.count * product.price;
console.log("Precio Total: " + precioTotalNuevo);
let iva = 0;
switch (product.type) {
case "ropa":
iva = 10/100;
break;
case "alimentacion":
iva = 4/100;
break;
default:
iva = 21/100;
break;
}
const importeIvaUnidad = product.price * iva;
console.log("Importe de IVA ("+ (iva*100) + " %): " + importeIvaUnidad);
console.log("Modulo 3: Laboratorio - Extra");
console.log("=============================");
let retencion = 0
if (empleado.bruto < 12000) {
retencion = 0;
} else if (empleado.bruto >= 12000 && empleado.bruto < 24000) {
retencion = 8;
} else if (empleado.bruto >= 24000 && empleado.bruto < 34000) {
retencion = 16;
} else {
retencion = 30;
}
let bonificacionHijos = 0;
if (retencion > 0 && empleado.hijos>0) {
bonificacionHijos = retencion -2
}
const nominaNetaAnual = empleado.bruto - (empleado.bruto * (retencion/100));
const nominaNetaMensual = nominaNetaAnual / empleado.pagas
console.log("El empleado cobra " + nominaNetaAnual + "€ anuales netos, esto es: " + nominaNetaMensual + "€/mes");
console.log("Modulo 3: Laboratorio - Avanzado");
console.log("=============================");
const importeIvaFuncion = getTotalVat(product);
console.log("La función devuelve un IVA por unidad de: " + importeIvaFuncion + "€");
|
JoaoCostaIFG/MNUM
|
Pratical/Class10/tercos-aurea.py
|
#!/usr/bin/env python3
# These methods won't be on the 2nd mini test (no algorithm implementation)
# so I will verify if they are correct after the test
# (should at least be really close to correct)
from math import sin, sqrt
limm = 1e-5
def f(x):
return sin(x) ** 2
def const_search(xi, xf, h):
print("const_search")
# change direc if necessary
if (f(xi) < f(xi + h)):
h = -h
while f(xi) > f(xi + h):
xi += h
print("xi:", xi, "h:", h)
return xi
def inc_search(xi, xf, h):
print("inc_search")
# change direc if necessary
if (f(xi) < f(xi + h)):
h = -h
while f(xi) > f(xi + h):
h *= 2
xi += h
print("xi:", xi, "h:", h)
return xi
def adjust(xi, xf, xm):
# Adjust 3 points to parabola
result = xf + ((xm - xf) * (f(xi) - f(xm))) / \
(2 * (f(xm) - 2 * f(xf) + f(xi)))
print(result)
return result
def tercos(xi, xf):
# doing 10 iterations cause it seems OK for this problem
print("Tercos:")
lastx = 0
for i in range(10):
h = (xf - xi) / 3
x3 = xi + h
x4 = xf - h
if f(x4) < f(x3):
xi = x3
lastx = x4
elif f(x3) <= f(x4):
# TODO caso do ==
# podemos abandonar ambos os extremos do intervalo
xf = x4
lastx = x3
print("xi:", xi, "xf:", xf)
print("fi:", f(xi), "ff:", f(xf))
return (xi, xf, lastx)
def aurea(xi, xf):
# doing 10 iterations cause it seems OK for this problem
print("Aurea:")
B = (sqrt(5) - 1) / 2 # golden ratio
A = B ** 2
lastx = 0
x3 = xi + A * (xf - xi)
x4 = xi + B * (xf - xi)
for i in range(10):
if f(x4) < f(x3):
xi = x3
lastx = x3 = x4
x4 = x3 + B * (xf - x3)
elif f(x3) <= f(x4):
xf = x4
lastx = x4 = x3
x3 = xi + B * (xf - xi)
print("xi:", xi, "xf:", xf)
print("fi:", f(xi), "ff:", f(xf))
return (xi, xf, lastx)
# f is convex from -1 to 1
xi = -1
xf = 1
h = 0.1
# tercos
xi = const_search(xi, xf, h)
points = tercos(xi, xf)
result = adjust(*points) # the star (*) unpacks the sequence
# f is convex from -1 to 1
xi = -1
xf = 1
h = 0.1
# aurea
xi = const_search(xi, xf, h)
points = aurea(xi, xf)
result = adjust(*points) # the star (*) unpacks the sequence
|
Bluscream/scs-sdk-plugin
|
docs/search/keywords/00740065006c.js
|
NDSearch.OnPrefixDataLoaded(
"tel",
["Variable", "Function", "Delegate", "Property"],
[
[
"Telemetry",
,
[
[
"SCSSdkClient.Demo.SCSSdkClientDemo",
,
,
,
0,
"File2:SCSSdkClient.Demo/SCSSdkClientDemo.cs:SCSSdkClient.Demo.SCSSdkClientDemo.Telemetry",
"CSharpClass:SCSSdkClient.Demo.SCSSdkClientDemo:Telemetry",
],
],
],
[
"telemetry_configuration",
,
[[, , , , 1, "File3:src/scs_telemetry.cpp:telemetry_configuration"]],
],
[
"Telemetry_Data",
,
[
[
"SCSSdkClient.Demo.SCSSdkClientDemo",
,
,
,
1,
"File2:SCSSdkClient.Demo/SCSSdkClientDemo.cs:SCSSdkClient.Demo.SCSSdkClientDemo.Telemetry_Data",
"CSharpClass:SCSSdkClient.Demo.SCSSdkClientDemo:Telemetry_Data",
],
],
],
[
"telemetry_frame_start",
,
[[, , , , 1, "File3:src/scs_telemetry.cpp:telemetry_frame_start"]],
],
[
"telemetry_pause",
,
[[, , , , 1, "File3:src/scs_telemetry.cpp:telemetry_pause"]],
],
[
"TelemetryData",
,
[
[
"SCSSdkClient",
,
,
,
2,
"File:SCSSdkTelemetry.cs:SCSSdkClient.TelemetryData",
],
],
],
[
"TelemetryFerry",
,
[
[
"SCSSdkClient.Demo.SCSSdkClientDemo",
,
,
,
1,
"File2:SCSSdkClient.Demo/SCSSdkClientDemo.cs:SCSSdkClient.Demo.SCSSdkClientDemo.TelemetryFerry",
"CSharpClass:SCSSdkClient.Demo.SCSSdkClientDemo:TelemetryFerry",
],
],
],
[
"TelemetryFined",
,
[
[
"SCSSdkClient.Demo.SCSSdkClientDemo",
,
,
,
1,
"File2:SCSSdkClient.Demo/SCSSdkClientDemo.cs:SCSSdkClient.Demo.SCSSdkClientDemo.TelemetryFined",
"CSharpClass:SCSSdkClient.Demo.SCSSdkClientDemo:TelemetryFined",
],
],
],
[
"TelemetryJobCancelled",
,
[
[
"SCSSdkClient.Demo.SCSSdkClientDemo",
,
,
,
1,
"File2:SCSSdkClient.Demo/SCSSdkClientDemo.cs:SCSSdkClient.Demo.SCSSdkClientDemo.TelemetryJobCancelled",
"CSharpClass:SCSSdkClient.Demo.SCSSdkClientDemo:TelemetryJobCancelled",
],
],
],
[
"TelemetryJobDelivered",
,
[
[
"SCSSdkClient.Demo.SCSSdkClientDemo",
,
,
,
1,
"File2:SCSSdkClient.Demo/SCSSdkClientDemo.cs:SCSSdkClient.Demo.SCSSdkClientDemo.TelemetryJobDelivered",
"CSharpClass:SCSSdkClient.Demo.SCSSdkClientDemo:TelemetryJobDelivered",
],
],
],
[
"TelemetryOnJobFinished",
,
[
[
"SCSSdkClient.Demo.SCSSdkClientDemo",
,
,
,
1,
"File2:SCSSdkClient.Demo/SCSSdkClientDemo.cs:SCSSdkClient.Demo.SCSSdkClientDemo.TelemetryOnJobFinished",
"CSharpClass:SCSSdkClient.Demo.SCSSdkClientDemo:TelemetryOnJobFinished",
],
],
],
[
"TelemetryOnJobStarted",
,
[
[
"SCSSdkClient.Demo.SCSSdkClientDemo",
,
,
,
1,
"File2:SCSSdkClient.Demo/SCSSdkClientDemo.cs:SCSSdkClient.Demo.SCSSdkClientDemo.TelemetryOnJobStarted",
"CSharpClass:SCSSdkClient.Demo.SCSSdkClientDemo:TelemetryOnJobStarted",
],
],
],
[
"TelemetryTollgate",
,
[
[
"SCSSdkClient.Demo.SCSSdkClientDemo",
,
,
,
1,
"File2:SCSSdkClient.Demo/SCSSdkClientDemo.cs:SCSSdkClient.Demo.SCSSdkClientDemo.TelemetryTollgate",
"CSharpClass:SCSSdkClient.Demo.SCSSdkClientDemo:TelemetryTollgate",
],
],
],
[
"TelemetryTrain",
,
[
[
"SCSSdkClient.Demo.SCSSdkClientDemo",
,
,
,
1,
"File2:SCSSdkClient.Demo/SCSSdkClientDemo.cs:SCSSdkClient.Demo.SCSSdkClientDemo.TelemetryTrain",
"CSharpClass:SCSSdkClient.Demo.SCSSdkClientDemo:TelemetryTrain",
],
],
],
[
"TelemetryVersion",
,
[
[
"SCSSdkClient.Object.SCSTelemetry",
,
,
,
3,
"File:Object/SCSTelemetry.cs:SCSSdkClient.Object.SCSTelemetry.TelemetryVersion",
"CSharpClass:SCSSdkClient.Object.SCSTelemetry:TelemetryVersion",
],
],
],
]
);
|
mdvx/TimeBase
|
java/quantserver/snmpagent/src/main/java/deltix/snmp/mibc/Env.java
|
<gh_stars>0
package deltix.snmp.mibc;
import deltix.snmp.mibc.errors.*;
import deltix.util.parsers.Location;
import java.util.*;
/**
*
*/
class Env <T extends CompiledEntity> {
private Map <String, T> env =
new HashMap <String, T> ();
public final Collection <T> values () {
return (env.values ());
}
public final void register (T e) {
register (Location.NONE, e);
}
public final void register (long location, T e) {
String id = e.getId ();
if (env.containsKey (id))
throw new DuplicateIdException (location, id);
env.put (id, e);
}
public final T resolve (String id) {
return (resolve (Location.NONE, id));
}
public final T resolve (long location, String id) {
T e = env.get (id);
if (e == null)
throw new UnresolvedIdException (location, id);
return (e);
}
}
|
jasonrudolph/stratify
|
lib/stratify.rb
|
require_dependency 'stratify/activity'
require_dependency 'stratify/collector'
require_dependency 'stratify/collector_coordinator'
|
sharplook/tencentcloud-sdk-java-test
|
src/main/java/com/tencentcloudapi/sqlserver/v20180328/models/CreateBackupMigrationRequest.java
|
/*
* Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencentcloudapi.sqlserver.v20180328.models;
import com.tencentcloudapi.common.AbstractModel;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import java.util.HashMap;
public class CreateBackupMigrationRequest extends AbstractModel{
/**
* 导入目标实例ID
*/
@SerializedName("InstanceId")
@Expose
private String InstanceId;
/**
* 迁移任务恢复类型,FULL-全量备份恢复,FULL_LOG-全量备份+事务日志恢复,FULL_DIFF-全量备份+差异备份恢复
*/
@SerializedName("RecoveryType")
@Expose
private String RecoveryType;
/**
* 备份上传类型,COS_URL-备份放在用户的对象存储上,提供URL。COS_UPLOAD-备份放在业务的对象存储上,需要用户上传。
*/
@SerializedName("UploadType")
@Expose
private String UploadType;
/**
* 任务名称
*/
@SerializedName("MigrationName")
@Expose
private String MigrationName;
/**
* UploadType是COS_URL时这里填URL,COS_UPLOAD这里填备份文件的名字。只支持1个备份文件,但1个备份文件内可包含多个库
*/
@SerializedName("BackupFiles")
@Expose
private String [] BackupFiles;
/**
* Get 导入目标实例ID
* @return InstanceId 导入目标实例ID
*/
public String getInstanceId() {
return this.InstanceId;
}
/**
* Set 导入目标实例ID
* @param InstanceId 导入目标实例ID
*/
public void setInstanceId(String InstanceId) {
this.InstanceId = InstanceId;
}
/**
* Get 迁移任务恢复类型,FULL-全量备份恢复,FULL_LOG-全量备份+事务日志恢复,FULL_DIFF-全量备份+差异备份恢复
* @return RecoveryType 迁移任务恢复类型,FULL-全量备份恢复,FULL_LOG-全量备份+事务日志恢复,FULL_DIFF-全量备份+差异备份恢复
*/
public String getRecoveryType() {
return this.RecoveryType;
}
/**
* Set 迁移任务恢复类型,FULL-全量备份恢复,FULL_LOG-全量备份+事务日志恢复,FULL_DIFF-全量备份+差异备份恢复
* @param RecoveryType 迁移任务恢复类型,FULL-全量备份恢复,FULL_LOG-全量备份+事务日志恢复,FULL_DIFF-全量备份+差异备份恢复
*/
public void setRecoveryType(String RecoveryType) {
this.RecoveryType = RecoveryType;
}
/**
* Get 备份上传类型,COS_URL-备份放在用户的对象存储上,提供URL。COS_UPLOAD-备份放在业务的对象存储上,需要用户上传。
* @return UploadType 备份上传类型,COS_URL-备份放在用户的对象存储上,提供URL。COS_UPLOAD-备份放在业务的对象存储上,需要用户上传。
*/
public String getUploadType() {
return this.UploadType;
}
/**
* Set 备份上传类型,COS_URL-备份放在用户的对象存储上,提供URL。COS_UPLOAD-备份放在业务的对象存储上,需要用户上传。
* @param UploadType 备份上传类型,COS_URL-备份放在用户的对象存储上,提供URL。COS_UPLOAD-备份放在业务的对象存储上,需要用户上传。
*/
public void setUploadType(String UploadType) {
this.UploadType = UploadType;
}
/**
* Get 任务名称
* @return MigrationName 任务名称
*/
public String getMigrationName() {
return this.MigrationName;
}
/**
* Set 任务名称
* @param MigrationName 任务名称
*/
public void setMigrationName(String MigrationName) {
this.MigrationName = MigrationName;
}
/**
* Get UploadType是COS_URL时这里填URL,COS_UPLOAD这里填备份文件的名字。只支持1个备份文件,但1个备份文件内可包含多个库
* @return BackupFiles UploadType是COS_URL时这里填URL,COS_UPLOAD这里填备份文件的名字。只支持1个备份文件,但1个备份文件内可包含多个库
*/
public String [] getBackupFiles() {
return this.BackupFiles;
}
/**
* Set UploadType是COS_URL时这里填URL,COS_UPLOAD这里填备份文件的名字。只支持1个备份文件,但1个备份文件内可包含多个库
* @param BackupFiles UploadType是COS_URL时这里填URL,COS_UPLOAD这里填备份文件的名字。只支持1个备份文件,但1个备份文件内可包含多个库
*/
public void setBackupFiles(String [] BackupFiles) {
this.BackupFiles = BackupFiles;
}
/**
* Internal implementation, normal users should not use it.
*/
public void toMap(HashMap<String, String> map, String prefix) {
this.setParamSimple(map, prefix + "InstanceId", this.InstanceId);
this.setParamSimple(map, prefix + "RecoveryType", this.RecoveryType);
this.setParamSimple(map, prefix + "UploadType", this.UploadType);
this.setParamSimple(map, prefix + "MigrationName", this.MigrationName);
this.setParamArraySimple(map, prefix + "BackupFiles.", this.BackupFiles);
}
}
|
ushakov-av/engocab
|
core/src/main/java/ru/mipt/engocab/core/model/WordKey.java
|
package ru.mipt.engocab.core.model;
/**
* @author <NAME>
*/
public class WordKey implements Comparable<WordKey> {
private final String word;
private final PartOfSpeech partOfSpeech;
private final int number;
private String transcription;
public WordKey(String word, PartOfSpeech partOfSpeech, int number) {
this(word, partOfSpeech, number, null);
}
public WordKey(String word, PartOfSpeech partOfSpeech, int number, String transcription) {
this.word = word;
this.partOfSpeech = partOfSpeech;
this.number = number;
this.transcription = transcription;
}
public String getWord() {
return word;
}
public PartOfSpeech getPartOfSpeech() {
return partOfSpeech;
}
public int getNumber() {
return number;
}
public String getTranscription() {
return transcription;
}
public void setTranscription(String transcription) {
this.transcription = transcription;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
WordKey that = (WordKey) o;
return compareTo(that) == 0;
}
@Override
public int hashCode() {
int result = word.hashCode();
result = 31 * result + PartOfSpeech.getHashCode(partOfSpeech);
result = 31 * result + number;
return result;
}
@Override
public int compareTo(WordKey that) {
if (!word.equals(that.word)) {
return word.compareTo(that.word);
}
if (partOfSpeech != that.partOfSpeech) {
return Integer.compare(PartOfSpeech.getHashCode(partOfSpeech), PartOfSpeech.getHashCode(that.partOfSpeech));
}
return Integer.compare(number, that.number);
}
@Override
public String toString() {
return "WordKey{" +
"word='" + word + '\'' +
", partOfSpeech=" + partOfSpeech +
", number=" + number +
", transcription='" + transcription + '\'' +
'}';
}
}
|
nobodysshadow/edX_MITx_6.00.1x
|
week5/lecture9/exampleClasses.py
|
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 9 08:24:52 2016
@author: WELG
"""
class Animal(object):
def __init__(self, age):
self.age = age
self.name = None
def get_age(self):
return self.age
def get_name(self):
return self.name
def set_age(self, newage):
self.age = newage
def set_name(self, newname=""):
self.name = newname
def __str__(self):
return "animal:"+str(self.name)+":"+str(self.age)
class Cat(Animal):
def speak(self):
print("meow”)
def __str__(self):
return "cat:"+str(self.name)+":"+str(self.age)
class Person(Animal):
def __init__(self, name, age):
Animal.__init__(self, age)
Animal.set_name(self, name)
self.friends = []
def get_friends(self):
return self.friends
def add_friend(self, fname):
if fname not in self.friends:
self.friends.append(fname)
def speak(self):
print("hello”)
def age_diff(self, other):
# alternate way: diff = self.age - other.age
diff = self.get_age() - other.get_age()
if self.age > other.age:
print(self.name, "is", diff, "years older than", other.name)
else:
print(self.name, "is", -diff, "years younger than", other.name)
def __str__(self):
return "person:"+str(self.name)+":"+str(self.age)
import random
class Student(Person):
def __init__(self, name, age, major=None):
Person.__init__(self, name, age)
self.major = major
def change_major(self, major):
self.major = major
def speak(self):
r = random.random()
if r < 0.25:
print("i have homework”)
elif 0.25 <= r < 0.5:
print("i need sleep”)
elif 0.5 <= r < 0.75:
print("i should eat”)
else:
print("i am watching tv”)
def __str__(self):
return "student:"+str(self.name)+":"+str(self.age)+":"+str(self.major)
class Rabbit(Animal):
tag = 1
def __init__(self, age, parent1=None, parent2=None):
Animal.__init__(self, age)
self.parent1 = parent1
self.parent2 = parent2
self.rid = Rabbit.tag
Rabbit.tag += 1
|
dimitriho/protoc-bridge
|
bridge/src/test/scala/protocbridge/ProtocCacheSpec.scala
|
package protocbridge
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.must.Matchers
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import java.io.File
import scala.concurrent.duration.Duration
import java.nio.file.Files
import scala.concurrent.Await
import java.util.concurrent.atomic.AtomicInteger
import org.scalatest.OneInstancePerTest
import scala.concurrent.Promise
class ProtocCacheSpec
extends AnyFlatSpec
with Matchers
with OneInstancePerTest {
val cacheDir = Files.createTempDirectory("protocache").toFile()
val cache =
new protocbridge.FileCache[String](cacheDir, downloadFile, v => v + ".exe")
val callCount = new AtomicInteger(0)
val p = Promise[Unit]() // used to unsuspend the downloader
val existing = {
new File(cacheDir, "existing.exe.complete").createNewFile()
val f = new File(cacheDir, "existing.exe")
f.createNewFile()
f
}
def downloadFile(tmpDir: File, v: String): Future[File] = {
callCount.incrementAndGet()
p.future.map { _ =>
if (v == "error") throw new RuntimeException("error!")
else {
val out = new File(tmpDir, v + ".tmp")
out.createNewFile()
out
}
}
}
"cache" should "immediately return an existing file and make it executable" in {
val c = Await.result(cache.get("existing"), Duration.Inf)
c.canExecute() must be(true)
c must be(existing)
callCount.get must be(0)
}
"cache" should "make exactly one concurrent request" in {
val fs = (0 to 20).map(_ => cache.get("somever"))
p.success(())
val res = Await.result(Future.sequence(fs), Duration.Inf)
callCount.get must be(1)
}
"cache" should "make exactly one concurrent request per key" in {
val fs = (0 to 50).map(i => cache.get(s"somever${i % 3}"))
p.success(())
val res = Await.result(Future.sequence(fs), Duration.Inf)
callCount.get must be(3)
new File(cacheDir, "somever0.exe").canExecute() must be(true)
new File(cacheDir, "somever1.exe").canExecute() must be(true)
new File(cacheDir, "somever2.exe").canExecute() must be(true)
new File(cacheDir, "somever3.exe").canExecute() must be(false)
Await.result(cache.get("somever1"), Duration.Inf).canExecute() must be(true)
callCount.get must be(3)
Await.result(cache.get("somever3"), Duration.Inf).canExecute() must be(true)
callCount.get must be(4)
}
"cache" should "make exactly one concurrent request per key on errors" in {
val fs = (0 to 50).map(_ => cache.get(s"error"))
p.success(())
fs.foreach { f =>
intercept[RuntimeException](Await.result(f, Duration.Inf))
.getMessage() must be("error!")
}
callCount.get must be(1)
// The next call should trigger another download: misses are not remembered.
intercept[RuntimeException](Await.result(cache.get(s"error"), Duration.Inf))
callCount.get must be(2)
}
}
|
Spacc-Inc/MultiMC5-Cracked
|
libraries/katabasis/src/Reply.cpp
|
<filename>libraries/katabasis/src/Reply.cpp
#include <QTimer>
#include <QNetworkReply>
#include "katabasis/Reply.h"
namespace Katabasis {
Reply::Reply(QNetworkReply *r, int timeOut, QObject *parent): QTimer(parent), reply(r) {
setSingleShot(true);
connect(this, &Reply::timeout, this, &Reply::onTimeOut, Qt::QueuedConnection);
start(timeOut);
}
void Reply::onTimeOut() {
timedOut = true;
reply->abort();
}
// ----------------------------
ReplyList::~ReplyList() {
foreach (Reply *timedReply, replies_) {
delete timedReply;
}
}
void ReplyList::add(QNetworkReply *reply, int timeOut) {
if (reply && ignoreSslErrors()) {
reply->ignoreSslErrors();
}
add(new Reply(reply, timeOut));
}
void ReplyList::add(Reply *reply) {
replies_.append(reply);
}
void ReplyList::remove(QNetworkReply *reply) {
Reply *o2Reply = find(reply);
if (o2Reply) {
o2Reply->stop();
(void)replies_.removeOne(o2Reply);
}
}
Reply *ReplyList::find(QNetworkReply *reply) {
foreach (Reply *timedReply, replies_) {
if (timedReply->reply == reply) {
return timedReply;
}
}
return 0;
}
bool ReplyList::ignoreSslErrors()
{
return ignoreSslErrors_;
}
void ReplyList::setIgnoreSslErrors(bool ignoreSslErrors)
{
ignoreSslErrors_ = ignoreSslErrors;
}
}
|
mgoyal2-atl/atlassian-slack-integration-server
|
bitbucket-slack-server-integration-plugin/src/main/java/com/atlassian/bitbucket/plugins/slack/notification/RepositoryNotificationTypes.java
|
<gh_stars>10-100
package com.atlassian.bitbucket.plugins.slack.notification;
import com.atlassian.bitbucket.event.branch.BranchCreatedEvent;
import com.atlassian.bitbucket.event.branch.BranchDeletedEvent;
import com.atlassian.bitbucket.event.commit.CommitDiscussionCommentAddedEvent;
import com.atlassian.bitbucket.event.commit.CommitDiscussionCommentDeletedEvent;
import com.atlassian.bitbucket.event.commit.CommitDiscussionCommentEditedEvent;
import com.atlassian.bitbucket.event.commit.CommitDiscussionCommentRepliedEvent;
import com.atlassian.bitbucket.event.repository.RepositoryEvent;
import com.atlassian.bitbucket.event.repository.RepositoryForkedEvent;
import com.atlassian.bitbucket.event.repository.RepositoryPushEvent;
import com.atlassian.bitbucket.event.tag.TagCreatedEvent;
import com.atlassian.bitbucket.event.tag.TagDeletedEvent;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
import java.util.Optional;
public enum RepositoryNotificationTypes {
PUSHED("CommitPushed"),
TAG_CREATED("TagCreated"),
TAG_DELETED("TagDeleted"),
BRANCH_CREATED("BranchCreated"),
BRANCH_DELETED("BranchDeleted"),
FORKED("Forked"),
COMMENT_ADDED("CommitComment"),
COMMENT_EDITED("CommitCommentEdited"),
COMMENT_REPLIED("CommitCommentReplied"),
COMMENT_DELETED("CommitCommentDeleted");
private static final Map<Class<? extends RepositoryEvent>, RepositoryNotificationTypes> byEventClass =
ImmutableMap.<Class<? extends RepositoryEvent>, RepositoryNotificationTypes>builder()
.put(RepositoryForkedEvent.class, RepositoryNotificationTypes.FORKED)
.put(RepositoryPushEvent.class, RepositoryNotificationTypes.PUSHED)
.put(TagCreatedEvent.class, RepositoryNotificationTypes.TAG_CREATED)
.put(TagDeletedEvent.class, RepositoryNotificationTypes.TAG_DELETED)
.put(BranchCreatedEvent.class, RepositoryNotificationTypes.BRANCH_CREATED)
.put(BranchDeletedEvent.class, RepositoryNotificationTypes.BRANCH_DELETED)
.put(CommitDiscussionCommentAddedEvent.class, RepositoryNotificationTypes.COMMENT_ADDED)
.put(CommitDiscussionCommentEditedEvent.class, RepositoryNotificationTypes.COMMENT_EDITED)
.put(CommitDiscussionCommentRepliedEvent.class, RepositoryNotificationTypes.COMMENT_REPLIED)
.put(CommitDiscussionCommentDeletedEvent.class, RepositoryNotificationTypes.COMMENT_DELETED)
.build();
private final String key;
RepositoryNotificationTypes(final String key) {
this.key = key;
}
public String getKey() {
return key;
}
public static Optional<RepositoryNotificationTypes> byEventClass(final Class<?> clazz) {
if (RepositoryEvent.class.isAssignableFrom(clazz)) {
return byEventClass.entrySet().stream()
.filter(e -> e.getKey().isAssignableFrom(clazz))
.map(Map.Entry::getValue)
.findAny();
}
return Optional.empty();
}
}
|
mweber03/quarkus
|
core/runtime/src/main/java/io/quarkus/runtime/logging/CategoryBuildTimeConfig.java
|
package io.quarkus.runtime.logging;
import io.quarkus.runtime.annotations.ConfigGroup;
import io.quarkus.runtime.annotations.ConfigItem;
@ConfigGroup
public class CategoryBuildTimeConfig {
/**
* The minimum log level for this category.
* By default all categories are configured with <code>DEBUG</code> minimum level.
*
* To get runtime logging below <code>DEBUG</code>, e.g. <code>TRACE</code>,
* the minimum level has to be adjusted at build time, the right log level needs to be provided at runtime.
*
* As an example, to get <code>TRACE</code> logging,
* minimum level needs to be at <code>TRACE</code> and the runtime log level needs to match that.
*/
@ConfigItem(defaultValue = "inherit")
public InheritableLevel minLevel;
}
|
vidkidz/crossbridge
|
llvm-gcc-4.2-2.9/gcc/testsuite/gcc.dg/compat/struct-by-value-22_y.c
|
<reponame>vidkidz/crossbridge
#include <stdarg.h>
#include "compat-common.h"
#include "mixed-struct-defs.h"
#include "mixed-struct-check.h"
#ifdef SKIP_VA
const int test_va = 0;
#else
const int test_va = 1;
#endif
#define T(NAME, FIELDS, TYPE, FIELDINIT, FIELDTEST) \
void \
testva##NAME (int n, ...) \
{ \
va_list ap; \
if (test_va) \
{ \
struct S { FIELDS TYPE a[n]; } s; \
int fail = 0, i, j; \
\
va_start (ap, n); \
for (j = 0; j < 2; ++j) \
{ \
s = va_arg (ap, struct S); \
for (i = 0; i < n; ++i) \
if (s.a[i] != 12 + n - i) \
++fail; \
if (fail) \
{ DEBUG_FAIL; } \
if (!j && va_arg (ap, int) != n) \
{ DEBUG_FAIL; } \
FIELDTEST; \
} \
va_end (ap); \
} \
}
#include "struct-by-value-22_x.c"
|
bianapis/sd-branch-location-operations-v3
|
src/main/java/org/bian/dto/CRBranchLocationAdministrativePlanGrantOutputModel.java
|
<gh_stars>0
package org.bian.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.bian.dto.CRBranchLocationAdministrativePlanGrantOutputModelGrantRequestResponseRecord;
import javax.validation.Valid;
/**
* CRBranchLocationAdministrativePlanGrantOutputModel
*/
public class CRBranchLocationAdministrativePlanGrantOutputModel {
private String branchLocationAdministrativePlanBudgetType = null;
private String branchLocationAdministrativePlanAssignment = null;
private String branchLocationAdministrativePlanPlan = null;
private String branchLocationAdministrativePlanGrantActionTaskReference = null;
private Object branchLocationAdministrativePlanGrantActionTaskRecord = null;
private String grantRequestRecordReference = null;
private CRBranchLocationAdministrativePlanGrantOutputModelGrantRequestResponseRecord grantRequestResponseRecord = null;
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: A Classification value that distinguishes between Budgets within Branch Location Administrative Plan according to the type of resource and/or activity that is budgetted
* @return branchLocationAdministrativePlanBudgetType
**/
public String getBranchLocationAdministrativePlanBudgetType() {
return branchLocationAdministrativePlanBudgetType;
}
public void setBranchLocationAdministrativePlanBudgetType(String branchLocationAdministrativePlanBudgetType) {
this.branchLocationAdministrativePlanBudgetType = branchLocationAdministrativePlanBudgetType;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: The allocation of someone or something which is specified for Branch Location Administrative Plan
* @return branchLocationAdministrativePlanAssignment
**/
public String getBranchLocationAdministrativePlanAssignment() {
return branchLocationAdministrativePlanAssignment;
}
public void setBranchLocationAdministrativePlanAssignment(String branchLocationAdministrativePlanAssignment) {
this.branchLocationAdministrativePlanAssignment = branchLocationAdministrativePlanAssignment;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: A plan that defines clerical support for BranchLocation
* @return branchLocationAdministrativePlanPlan
**/
public String getBranchLocationAdministrativePlanPlan() {
return branchLocationAdministrativePlanPlan;
}
public void setBranchLocationAdministrativePlanPlan(String branchLocationAdministrativePlanPlan) {
this.branchLocationAdministrativePlanPlan = branchLocationAdministrativePlanPlan;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to a Branch Location Administrative Plan instance grant service call
* @return branchLocationAdministrativePlanGrantActionTaskReference
**/
public String getBranchLocationAdministrativePlanGrantActionTaskReference() {
return branchLocationAdministrativePlanGrantActionTaskReference;
}
public void setBranchLocationAdministrativePlanGrantActionTaskReference(String branchLocationAdministrativePlanGrantActionTaskReference) {
this.branchLocationAdministrativePlanGrantActionTaskReference = branchLocationAdministrativePlanGrantActionTaskReference;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The grant service call consolidated processing record
* @return branchLocationAdministrativePlanGrantActionTaskRecord
**/
public Object getBranchLocationAdministrativePlanGrantActionTaskRecord() {
return branchLocationAdministrativePlanGrantActionTaskRecord;
}
public void setBranchLocationAdministrativePlanGrantActionTaskRecord(Object branchLocationAdministrativePlanGrantActionTaskRecord) {
this.branchLocationAdministrativePlanGrantActionTaskRecord = branchLocationAdministrativePlanGrantActionTaskRecord;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to the grant request record
* @return grantRequestRecordReference
**/
public String getGrantRequestRecordReference() {
return grantRequestRecordReference;
}
public void setGrantRequestRecordReference(String grantRequestRecordReference) {
this.grantRequestRecordReference = grantRequestRecordReference;
}
/**
* Get grantRequestResponseRecord
* @return grantRequestResponseRecord
**/
public CRBranchLocationAdministrativePlanGrantOutputModelGrantRequestResponseRecord getGrantRequestResponseRecord() {
return grantRequestResponseRecord;
}
public void setGrantRequestResponseRecord(CRBranchLocationAdministrativePlanGrantOutputModelGrantRequestResponseRecord grantRequestResponseRecord) {
this.grantRequestResponseRecord = grantRequestResponseRecord;
}
}
|
pvalls/ray-tracer
|
src/shapes/shape.cpp
|
<filename>src/shapes/shape.cpp
#include "shape.h"
Shape::Shape(const Matrix4x4 &t_, Material *material_)
{
objectToWorld = t_;
objectToWorld.inverse(worldToObject);
material = material_;
}
const Material& Shape::getMaterial() const
{
return *material;
}
|
dsiroky/rewofs
|
src/rewofs/client/transport.hpp
|
/// Client side transport.
///
/// @file
#pragma once
#ifndef TRANSPORT_HPP__WALU1VCO
#define TRANSPORT_HPP__WALU1VCO
#include <thread>
#include "rewofs/client/config.hpp"
#include "rewofs/transport.hpp"
//==========================================================================
namespace rewofs::client {
//==========================================================================
class Transport
{
public:
Transport(Serializer& serializer, Deserializer& deserializer,
Distributor& distributor);
void set_endpoint(const std::string& endpoint);
void start();
void stop();
void wait();
private:
void run_reader();
void run_writer();
Serializer& m_serializer;
Deserializer& m_deserializer;
Distributor& m_distributor;
int m_socket{-1};
std::thread m_reader{};
std::thread m_writer{};
std::atomic<bool> m_quit{false};
};
//==========================================================================
/// Channel for single commands/responses.
class SingleComm
{
public:
SingleComm(Serializer& serializer, Deserializer& deserializer);
template<typename _Result, typename _Command>
Deserializer::Result<_Result>
single_command(flatbuffers::FlatBufferBuilder& fbb,
const flatbuffers::Offset<_Command> command,
const std::chrono::milliseconds timeout = TIMEOUT);
private:
Serializer& m_serializer;
Deserializer& m_deserializer;
};
//--------------------------------------------------------------------------
template<typename _Result, typename _Command>
Deserializer::Result<_Result>
SingleComm::single_command(flatbuffers::FlatBufferBuilder& fbb,
const flatbuffers::Offset<_Command> command,
const std::chrono::milliseconds timeout)
{
auto queue = m_serializer.new_queue(Serializer::PRIORITY_DEFAULT);
const auto mid = m_serializer.add_command(queue, fbb, command);
log_trace("mid:{}", strong::value_of(mid));
const auto res = m_deserializer.wait_for_result<_Result>(mid, timeout);
if (not res.is_valid())
{
throw std::system_error{EHOSTUNREACH, std::generic_category()};
}
return res;
}
//==========================================================================
} // namespace rewofs::client
#endif /* include guard */
|
rodrigogs/github-metrics
|
src/controllers/v1/feed.v1.controller.js
|
const debug = require('debug')('github-metrics:controllers:v1:feed');
const FeedService = require('../../services/v1/feed.v1.service');
const FeedController = {
/**
* @api {post} /update Github webhook
* @apiVersion 1
* @apiName Github
* @apiGroup Webhook
* @apiPermission any
*
* @apiDescription Github webhook.
*/
update: async (req, res, next) => {
debug('executing update action');
const code = req.headers['x-delivery'];
const type = req.headers['x-event'];
const delivery = req.body;
try {
await FeedService.update(code, type, delivery);
res.sendStatus(200);
} catch (err) {
next(err);
}
},
/**
* @api {post} /github Github webhook
* @apiVersion 1
* @apiName Github
* @apiGroup Webhook
* @apiPermission any
*
* @apiDescription Github webhook.
*
* @apiExample Example usage:
* curl -X POST http://localhost:3000/github
*/
github: async (req, res, next) => {
debug('executing github action');
const delivery = req.headers['x-github-delivery'];
const type = req.headers['x-github-event'];
const payload = req.body;
try {
await FeedService.schedule('github', delivery, type, payload);
res.sendStatus(200);
} catch (err) {
next(err);
}
},
};
module.exports = FeedController;
|
Liquid-Zhangliquan/zen-3d
|
src/core/objects/fog/FogExp2.js
|
import { FOG_TYPE } from '../../const.js';
import { Color3 } from '../../math/Color3.js';
/**
* Exp2 fog.
* @memberof zen3d
* @constructor
* @param {number} [color=0x000000] - The color of the fog.
* @param {number} [density=0.00025] - The density of the exp2 fog.
*/
function FogExp2(color, density) {
this.fogType = FOG_TYPE.EXP2;
/**
* The color of the fog.
* @member {zen3d.Color3}
* @default zen3d.Color3(0x000000)
*/
this.color = new Color3((color !== undefined) ? color : 0x000000);
/**
* The density of the exp2 fog.
* @member {number}
* @default 0.00025
*/
this.density = (density !== undefined) ? density : 0.00025;
}
export { FogExp2 };
|
ufoscout/jpattern
|
gwt/src/main/java/com/jpattern/gwt/client/presenter/NullPresenter.java
|
<gh_stars>0
package com.jpattern.gwt.client.presenter;
import java.util.List;
import java.util.Map;
import com.google.gwt.user.client.ui.HasWidgets;
import com.jpattern.gwt.client.IApplicationProvider;
import com.jpattern.gwt.client.navigationevent.INavigationEvent;
import com.jpattern.gwt.client.navigationevent.INavigationEventCallback;
import com.jpattern.gwt.client.navigationevent.INavigationEventData;
import com.jpattern.gwt.client.navigationevent.INavigationEventWrapper;
import com.jpattern.gwt.client.navigationevent.NullNavigationEvent;
import com.jpattern.gwt.client.navigationevent.NullNavigationEventData;
import com.jpattern.gwt.client.view.IView;
import com.jpattern.gwt.client.view.NullView;
import com.jpattern.shared.result.IErrorMessage;
/**
*
* @author <NAME>'
*
*/
public class NullPresenter implements IPresenter {
private IApplicationProvider provider;
public NullPresenter(IApplicationProvider provider) {
this.provider = provider;
}
@Override
public void onEventError(List<IErrorMessage> errorMessages) {
}
@Override
public void onEventStart() {
}
@Override
public void onEventEnd() {
}
@Override
public void initPresenter() {
}
@Override
public void hierarchy(List<String> hierarchyResult) {
}
@Override
public IView getView() {
return new NullView();
}
@Override
public void registerNavigationEvent(INavigationEvent navigationEvent, HasWidgets eventTarget, INavigationEventCallback navigationEventCallback) {
}
@Override
public INavigationEventData getNavigationEventData(String navigationEventName) {
return new NullNavigationEventData();
}
@Override
public void launchNavigationEvent(String navigationEventName, boolean registerHistory) {
}
@Override
public INavigationEvent getNavigationEvent() {
return new NullNavigationEvent();
}
@Override
public void setParent(IPresenter parentPresenter) {
}
@Override
public boolean isInitialized() {
return false;
}
@Override
public String getName() {
return "";
}
@Override
public void launchNavigationEvent(String navigationEventName, boolean registerHistory, Map<String, String> queryStringValues) {
}
@Override
public void registerNavigationEvent(
INavigationEventWrapper navigationEventWrapper,
HasWidgets eventTarget,
INavigationEventCallback navigationEventCallback) {
}
@Override
public void onUnload() {
}
@Override
public void launchNavigationEvent(String[] navigationEventsName,
boolean registerHistory, Map<String, String> queryStringValues) {
}
@Override
public void launchNavigationEvent(String[] navigationEventsName,
boolean registerHistory) {
}
@Override
public void setProvider(IApplicationProvider provider) {
this.provider = provider;
}
@Override
public void launchNavigationEvent(String[] navigationEventsName,
boolean registerHistory, Map<String, String> queryStringValues,
boolean onlyIfTargetNotUsed) {
}
@Override
public String[] getAllowedRole() {
return new String[0];
}
@Override
public boolean isUserAuthorized() {
return false;
}
@Override
public IApplicationProvider getProvider() {
return provider;
}
}
|
MontiCore/monticore
|
monticore-test/02.experiments/scopes/src/test/java/GlobalScopeTest.java
|
<filename>monticore-test/02.experiments/scopes/src/test/java/GlobalScopeTest.java
/* (c) https://github.com/MontiCore/monticore */
import automata.AutomataMill;
import automata._symboltable.IAutomataGlobalScope;
import automata._symboltable.MyStateDeSer;
import automata._symboltable.MyStateResolver;
import de.monticore.io.paths.MCPath;
import org.junit.Test;
import java.nio.file.Paths;
public class GlobalScopeTest {
@Test
public void testGS() {
// tests availability of the configuration methods
IAutomataGlobalScope gs = AutomataMill.globalScope();
gs.setSymbolPath(new MCPath(Paths.get("src/models")));
gs.setFileExt("autsym");
gs.addAdaptedStateSymbolResolver(new MyStateResolver());
gs.putSymbolDeSer("automata._symboltable.StateSymbol",
new MyStateDeSer());
}
}
|
amcclead7336/Enterprise_Data_Science_Final
|
venv/lib/python3.8/site-packages/vsts/git/v4_0/models/git_fork_ref.py
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from .git_ref import GitRef
class GitForkRef(GitRef):
"""GitForkRef.
:param _links:
:type _links: :class:`ReferenceLinks <git.v4_0.models.ReferenceLinks>`
:param is_locked:
:type is_locked: bool
:param is_locked_by:
:type is_locked_by: :class:`IdentityRef <git.v4_0.models.IdentityRef>`
:param name:
:type name: str
:param object_id:
:type object_id: str
:param peeled_object_id:
:type peeled_object_id: str
:param statuses:
:type statuses: list of :class:`GitStatus <git.v4_0.models.GitStatus>`
:param url:
:type url: str
:param repository:
:type repository: :class:`GitRepository <git.v4_0.models.GitRepository>`
"""
_attribute_map = {
'_links': {'key': '_links', 'type': 'ReferenceLinks'},
'is_locked': {'key': 'isLocked', 'type': 'bool'},
'is_locked_by': {'key': 'isLockedBy', 'type': 'IdentityRef'},
'name': {'key': 'name', 'type': 'str'},
'object_id': {'key': 'objectId', 'type': 'str'},
'peeled_object_id': {'key': 'peeledObjectId', 'type': 'str'},
'statuses': {'key': 'statuses', 'type': '[GitStatus]'},
'url': {'key': 'url', 'type': 'str'},
'repository': {'key': 'repository', 'type': 'GitRepository'}
}
def __init__(self, _links=None, is_locked=None, is_locked_by=None, name=None, object_id=None, peeled_object_id=None, statuses=None, url=None, repository=None):
super(GitForkRef, self).__init__(_links=_links, is_locked=is_locked, is_locked_by=is_locked_by, name=name, object_id=object_id, peeled_object_id=peeled_object_id, statuses=statuses, url=url)
self.repository = repository
|
ModeenF/UltraDV
|
UltraDV/Source/AVINodes/Shared/Headers/TMSRLECodec.h
|
//---------------------------------------------------------------------
//
// File: TMSRLECodec.cpp
//
// Author: <NAME>
//
// Date: 09.18.98
//
// Desc: Microsoft RLE Codec
//
// Copyright ©1998 mediapede Software
//
//---------------------------------------------------------------------
#ifndef __TMSRLECODEC_H__
#define __TMSRLECODEC_H__
// Microsoft RLE Codec
class TMSRLECodec : public TVideoCodec
{
public:
TMSRLECodec(TRIFFReader *reader);
~TMSRLECodec();
bool GetDescription(char *descText);
bool DecodeFrame(AVIVideoFrame *theFrame, void *dstBuffer, uint16 dstDepth);
private:
void Init();
bool DecodeMicrosoftRLE(uint32 width, uint32 height, void *buffer, int32 bufSize, void *dstBuffer);
protected:
};
#endif
|
mkbrv/tda
|
src/main/java/com/pironet/tda/MainMenu.java
|
<reponame>mkbrv/tda
/*
* MainMenu.java
*
* This file is part of TDA - Thread Dump Analysis Tool.
*
* TDA is free software; you can redistribute it and/or modify
* it under the terms of the Lesser GNU General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* TDA 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
* Lesser GNU General Public License for more details.
*
* TDA should have received a copy of the Lesser GNU General Public License
* along with Foobar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* $Id: MainMenu.java,v 1.38 2008-09-18 14:44:10 irockel Exp $
*/
package com.pironet.tda;
import com.pironet.tda.utils.PrefManager;
import com.pironet.tda.utils.ResourceManager;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
/**
* provides instances of the main menu (though there is typically only one).
*
* @author irockel
*/
public class MainMenu extends JMenuBar {
private JMenuItem closeMenuItem;
private JMenuItem longMenuItem;
private JMenuItem recentFilesMenu;
private JMenuItem recentSessionsMenu;
private JMenuItem closeAllMenuItem;
private JMenuItem expandAllMenuItem;
private JMenuItem collapseAllMenuItem;
private TDA listener;
private JToolBar toolBar;
private JButton closeToolBarButton;
private JMenuItem saveSessionMenuItem;
private JButton findLRThreadsButton;
private JButton expandButton;
private JButton collapseButton;
/**
* Creates a new instance of the MainMenu
*/
public MainMenu(TDA listener) {
this.listener = listener;
createMenuBar();
}
/**
* get the close file menu item
*/
public JMenuItem getCloseMenuItem() {
return (closeMenuItem);
}
/**
* get the close file menu item
*/
public JButton getCloseToolBarButton() {
return (closeToolBarButton);
}
/**
* get the close file menu item
*/
public JButton getExpandButton() {
return (expandButton);
}
/**
* get the close file menu item
*/
public JButton getCollapseButton() {
return (collapseButton);
}
/**
* get the close file menu item
*/
public JButton getFindLRThreadsToolBarButton() {
return (findLRThreadsButton);
}
/**
* get the close all file menu item
*/
public JMenuItem getCloseAllMenuItem() {
return (closeAllMenuItem);
}
public JMenuItem getLongMenuItem() {
return (longMenuItem);
}
/**
* get the close all file menu item
*/
public JMenuItem getExpandAllMenuItem() {
return (expandAllMenuItem);
}
public JMenuItem getCollapseAllMenuItem() {
return (collapseAllMenuItem);
}
public JMenuItem getSaveSessionMenuItem() {
return (saveSessionMenuItem);
}
/**
* create the top level menu bar
*/
private void createMenuBar() {
add(createFileMenu());
add(createViewMenu());
add(createToolsMenu());
add(createHelpMenu());
}
private JMenu createFileMenu() {
JMenuItem menuItem;
JMenu menu;
//Build the first menu.
menu = new JMenu(ResourceManager.translate("file.menu"));
menu.setMnemonic(KeyStroke.getKeyStroke(ResourceManager.translate("file.menu.mnem")).getKeyCode());
menu.getAccessibleContext().setAccessibleDescription(ResourceManager.translate("file.menu.description"));
menu.addMenuListener(listener);
//a group of JMenuItems
menuItem = new JMenuItem(ResourceManager.translate("file.open"),
KeyStroke.getKeyStroke(ResourceManager.translate("file.open.mnem")).getKeyCode());
menuItem.setIcon(TDA.createImageIcon("FileOpen.gif"));
menuItem.setAccelerator(KeyStroke.getKeyStroke(
ResourceManager.translate("file.open.accel")));
menuItem.getAccessibleContext().setAccessibleDescription(
ResourceManager.translate("file.open.description"));
menuItem.addActionListener(listener);
menu.add(menuItem);
closeMenuItem = new JMenuItem(ResourceManager.translate("file.close"),
KeyStroke.getKeyStroke(ResourceManager.translate("file.close.mnem")).getKeyCode());
closeMenuItem.setIcon(TDA.createImageIcon("CloseFile.gif"));
closeMenuItem.getAccessibleContext().setAccessibleDescription(
ResourceManager.translate("file.open.description"));
closeMenuItem.addActionListener(listener);
closeMenuItem.setEnabled(false);
menu.add(closeMenuItem);
closeAllMenuItem = new JMenuItem(ResourceManager.translate("file.closeall"),
KeyStroke.getKeyStroke(ResourceManager.translate("file.closeall.mnem")).getKeyCode());
closeAllMenuItem.getAccessibleContext().setAccessibleDescription(
ResourceManager.translate("file.closeall.description"));
closeAllMenuItem.addActionListener(listener);
closeAllMenuItem.setEnabled(false);
menu.add(closeAllMenuItem);
createRecentFileMenu();
menu.add(recentFilesMenu);
menu.addSeparator();
menuItem = new JMenuItem(ResourceManager.translate("file.getfromclipboard"),
KeyStroke.getKeyStroke(ResourceManager.translate("file.getfromclipboard.mnem")).getKeyCode());
menuItem.setIcon(TDA.createImageIcon("Empty.gif"));
menuItem.getAccessibleContext().setAccessibleDescription(
ResourceManager.translate("file.getfromclipboard.description"));
menuItem.setAccelerator(KeyStroke.getKeyStroke(
ResourceManager.translate("file.getfromclipboard.accel")));
menuItem.addActionListener(listener);
menu.add(menuItem);
menu.addSeparator();
saveSessionMenuItem = new JMenuItem(ResourceManager.translate("file.savesession"),
KeyStroke.getKeyStroke(ResourceManager.translate("file.savesession.mnem")).getKeyCode());
saveSessionMenuItem.getAccessibleContext().setAccessibleDescription(
ResourceManager.translate("file.savesession.description"));
saveSessionMenuItem.addActionListener(listener);
menu.add(saveSessionMenuItem);
saveSessionMenuItem.setEnabled(false);
menuItem = new JMenuItem(ResourceManager.translate("file.opensession"),
KeyStroke.getKeyStroke(ResourceManager.translate("file.opensession.mnem")).getKeyCode());
menuItem.getAccessibleContext().setAccessibleDescription(
ResourceManager.translate("file.opensession.description"));
menuItem.addActionListener(listener);
menu.add(menuItem);
createRecentSessionsMenu();
menu.add(recentSessionsMenu);
menu.addSeparator();
menuItem = new JMenuItem(ResourceManager.translate("file.exit"),
KeyStroke.getKeyStroke(ResourceManager.translate("file.exit.mnem")).getKeyCode());
menuItem.setAccelerator(KeyStroke.getKeyStroke(
ResourceManager.translate("file.exit.accel")));
menuItem.getAccessibleContext().setAccessibleDescription(
ResourceManager.translate("file.exit.description"));
menuItem.addActionListener(listener);
menu.add(menuItem);
return (menu);
}
/**
* Build tools menu in the menu bar.
*/
private JMenu createViewMenu() {
JMenuItem menuItem;
JMenu menu;
menu = new JMenu(ResourceManager.translate("view.menu"));
menu.setMnemonic(KeyStroke.getKeyStroke(ResourceManager.translate("view.menu.mnem")).getKeyCode());
menu.getAccessibleContext().setAccessibleDescription(ResourceManager.translate("view.menu.description"));
add(menu);
expandAllMenuItem = new JMenuItem(ResourceManager.translate("view.expand"),
KeyStroke.getKeyStroke(ResourceManager.translate("view.expand.mnem")).getKeyCode());
expandAllMenuItem.setIcon(TDA.createImageIcon("Expanded.gif"));
expandAllMenuItem.setAccelerator(KeyStroke.getKeyStroke(
ResourceManager.translate("view.expand.accel")));
expandAllMenuItem.getAccessibleContext().setAccessibleDescription(
ResourceManager.translate("view.expand.description"));
expandAllMenuItem.addActionListener(listener);
expandAllMenuItem.setEnabled(false);
menu.add(expandAllMenuItem);
collapseAllMenuItem = new JMenuItem(ResourceManager.translate("view.collapse"),
KeyStroke.getKeyStroke(ResourceManager.translate("view.collapse.mnem")).getKeyCode());
collapseAllMenuItem.setIcon(TDA.createImageIcon("Collapsed.gif"));
collapseAllMenuItem.setAccelerator(KeyStroke.getKeyStroke(
ResourceManager.translate("view.collapse.accel")));
collapseAllMenuItem.getAccessibleContext().setAccessibleDescription(
ResourceManager.translate("view.collapse.description"));
collapseAllMenuItem.setEnabled(false);
collapseAllMenuItem.addActionListener(listener);
menu.add(collapseAllMenuItem);
menu.addSeparator();
menuItem = new JCheckBoxMenuItem(ResourceManager.translate("view.showtoolbar"), PrefManager.get().getShowToolbar());
menuItem.setMnemonic(KeyStroke.getKeyStroke(ResourceManager.translate("view.showtoolbar.mnem")).getKeyCode());
menuItem.addActionListener(listener);
menuItem.setIcon(TDA.createImageIcon("Empty.gif"));
menu.add(menuItem);
return (menu);
}
/**
* Build tools menu in the menu bar.
*/
private JMenu createToolsMenu() {
JMenuItem menuItem;
JMenu menu;
menu = new JMenu(ResourceManager.translate("tools.menu"));
menu.setMnemonic(KeyStroke.getKeyStroke(ResourceManager.translate("tools.menu.mnem")).getKeyCode());
menu.getAccessibleContext().setAccessibleDescription(ResourceManager.translate("tools.menu.description"));
add(menu);
longMenuItem = new JMenuItem(ResourceManager.translate("tools.longrunning"),
KeyStroke.getKeyStroke(ResourceManager.translate("tools.longrunning.mnem")).getKeyCode());
longMenuItem.setIcon(TDA.createImageIcon("FindLRThreads.gif"));
longMenuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_L, ActionEvent.ALT_MASK));
longMenuItem.getAccessibleContext().setAccessibleDescription(
"Find long running threads...");
longMenuItem.addActionListener(listener);
longMenuItem.setEnabled(false);
menu.add(longMenuItem);
menu.addSeparator();
menuItem = new JMenuItem("Filters",
KeyEvent.VK_F);
menuItem.setIcon(TDA.createImageIcon("Filters.gif"));
menuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_F, ActionEvent.ALT_MASK));
menuItem.getAccessibleContext().setAccessibleDescription(
"Setup Filter");
menuItem.addActionListener(listener);
menu.add(menuItem);
menuItem = new JMenuItem("Categories",
KeyEvent.VK_F);
menuItem.setIcon(TDA.createImageIcon("CustomCat.gif"));
menuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_G, ActionEvent.ALT_MASK));
menuItem.getAccessibleContext().setAccessibleDescription(
"Setup Categories");
menuItem.addActionListener(listener);
menu.add(menuItem);
menu.addSeparator();
menuItem = new JMenuItem(ResourceManager.translate("file.preferences"),
KeyStroke.getKeyStroke(ResourceManager.translate("file.preferences.mnem")).getKeyCode());
menuItem.setIcon(TDA.createImageIcon("Preferences.gif"));
menuItem.getAccessibleContext().setAccessibleDescription(
ResourceManager.translate("file.preferences.description"));
menuItem.addActionListener(listener);
menu.add(menuItem);
/*menu.addSeparator();
menuItem = new JMenuItem("Load Configuration Set...",
KeyEvent.VK_F);
menuItem.setIcon(TDA.createImageIcon("Empty.gif"));
menuItem.getAccessibleContext().setAccessibleDescription(
"Load Configuration Set");
menuItem.addActionListener(listener);
menu.add(menuItem);*/
return (menu);
}
/**
* Build help menu in the menu bar.
*/
private JMenu createHelpMenu() {
JMenuItem menuItem;
JMenu menu;
menu = new JMenu(ResourceManager.translate("help.menu"));
menu.setMnemonic(KeyStroke.getKeyStroke(ResourceManager.translate("help.menu.mnem")).getKeyCode());
menu.getAccessibleContext().setAccessibleDescription(
ResourceManager.translate("help.menu.description"));
menuItem = new JMenuItem(ResourceManager.translate("help.contents"),
KeyStroke.getKeyStroke(ResourceManager.translate("help.contents.mnem")).getKeyCode());
menuItem.setIcon(TDA.createImageIcon("Help.gif"));
menuItem.getAccessibleContext().setAccessibleDescription(
ResourceManager.translate("help.contents.description"));
menuItem.setAccelerator(KeyStroke.getKeyStroke(
ResourceManager.translate("help.contents.accel")));
menuItem.addActionListener(listener);
menu.add(menuItem);
menuItem = new JMenuItem("Release Notes", null);
menuItem.getAccessibleContext().setAccessibleDescription(
"Release Notes");
menuItem.addActionListener(listener);
menu.add(menuItem);
menuItem = new JMenuItem("License", null);
menuItem.getAccessibleContext().setAccessibleDescription(
"TDA Distribution License");
menuItem.addActionListener(listener);
menu.add(menuItem);
menu.addSeparator();
menuItem = new JMenuItem("Forum", null);
menuItem.getAccessibleContext().setAccessibleDescription(
"Online TDA Forum");
menuItem.addActionListener(listener);
menu.add(menuItem);
menu.addSeparator();
menuItem = new JMenuItem("About TDA",
KeyEvent.VK_A);
menuItem.setIcon(TDA.createImageIcon("About.gif"));
menuItem.getAccessibleContext().setAccessibleDescription(
"About Thread Dump Analyzer");
menuItem.addActionListener(listener);
menu.add(menuItem);
return (menu);
}
/**
* create the menu for opening recently selected files.
*/
private void createRecentFileMenu() {
String[] recentFiles = PrefManager.get().getRecentFiles();
recentFilesMenu = new JMenu(ResourceManager.translate("file.recentfiles"));
recentFilesMenu.setMnemonic(KeyStroke.getKeyStroke(ResourceManager.translate("file.recentfiles.mnem")).getKeyCode());
if (recentFiles.length > 1) {
for (int i = 1; i < recentFiles.length; i++) {
if (!recentFiles[i].equals("")) {
JMenuItem item = new JMenuItem(recentFiles[i]);
((JMenu) recentFilesMenu).add(item);
item.addActionListener(listener);
}
}
} else {
recentFilesMenu.setEnabled(false);
}
}
/**
* create the menu for opening recently selected files.
*/
private void createRecentSessionsMenu() {
String[] recentFiles = PrefManager.get().getRecentSessions();
recentSessionsMenu = new JMenu(ResourceManager.translate("file.recentsessions"));
recentSessionsMenu.setMnemonic(KeyStroke.getKeyStroke(ResourceManager.translate("file.recentsessions.mnem")).getKeyCode());
if (recentFiles.length > 1) {
for (int i = 1; i < recentFiles.length; i++) {
if (!recentFiles[i].equals("")) {
JMenuItem item = new JMenuItem(recentFiles[i]);
((JMenu) recentSessionsMenu).add(item);
item.addActionListener(listener);
}
}
} else {
recentSessionsMenu.setEnabled(false);
}
}
/**
* creates and returns a toolbar for the main menu with most
* important entries.
*
* @return toolbar instance, is created on demand.
*/
public JToolBar getToolBar() {
if (toolBar == null) {
createToolBar();
}
return toolBar;
}
/**
* create a toolbar showing the most important main menu entries.
*/
private void createToolBar() {
toolBar = new JToolBar("TDA Toolbar");
if (listener.runningAsJConsolePlugin || listener.runningAsVisualVMPlugin) {
toolBar.add(createToolBarButton("Request a Thread Dump", "FileOpen.gif"));
toolBar.setFloatable(false);
} else {
toolBar.add(createToolBarButton("Open Logfile", "FileOpen.gif"));
closeToolBarButton = createToolBarButton("Close selected Logfile", "CloseFile.gif");
closeToolBarButton.setEnabled(false);
toolBar.add(closeToolBarButton);
}
toolBar.addSeparator();
toolBar.add(createToolBarButton("Preferences", "Preferences.gif"));
toolBar.addSeparator();
expandButton = createToolBarButton("Expand all nodes", "Expanded.gif");
expandButton.setEnabled(false);
toolBar.add(expandButton);
collapseButton = createToolBarButton("Collapse all nodes", "Collapsed.gif");
collapseButton.setEnabled(false);
toolBar.add(collapseButton);
toolBar.addSeparator();
findLRThreadsButton = createToolBarButton("Find long running threads", "FindLRThreads.gif");
findLRThreadsButton.setEnabled(false);
toolBar.add(findLRThreadsButton);
toolBar.add(createToolBarButton("Filters", "Filters.gif"));
toolBar.add(createToolBarButton("Custom Categories", "CustomCat.gif"));
toolBar.addSeparator();
toolBar.add(createToolBarButton("Help", "Help.gif"));
}
/**
* create a toolbar button with tooltip and given icon.
*
* @param text tooltip text
* @param fileName filename for the icon to load
* @return toolbar button
*/
private JButton createToolBarButton(String text, String fileName) {
JButton toolbarButton = new JButton(TDA.createImageIcon(fileName));
if (text != null) {
toolbarButton.setToolTipText(text);
}
toolbarButton.addActionListener(listener);
toolbarButton.setFocusable(false);
return (toolbarButton);
}
}
|
a-ilin/wwaneric
|
gsmmanager/Modem.h
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2017 by <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.
*/
#ifndef MODEM_H
#define MODEM_H
#include "PortController.h"
#include <QMap>
#include <QReadWriteLock>
#include <QStringList>
QStringList parseAnswerLine(const QString &line, const QString &command);
class Modem;
// data that passed to conversation handler
struct RequestArgs
{
virtual ~RequestArgs() {}
};
// data that passed from conversation handler
struct AnswerData
{
virtual ~AnswerData() {}
};
class ModemReply
{
public:
ModemReply();
~ModemReply();
QString handlerName() const;
int type() const;
bool status() const;
AnswerData* data() const;
private:
// hadler name
QString m_handlerName;
// inner reply handler type, usually equals to request type,
// but may differs in case of processing unexpected data
int m_type;
// success (true) or failure(false)
bool m_status;
// reply data
AnswerData * m_data;
friend class Modem;
};
Q_DECLARE_METATYPE(ModemReply)
Q_DECLARE_METATYPE(ModemReply*)
Q_DECLARE_METATYPE(ModemReply**)
class ModemRequest
{
public:
~ModemRequest();
enum Status
{
SuccessCompleted,
SuccessNeedMoreData,
Failure
};
int type() const;
RequestArgs* args() const;
int stage() const;
void setStage(int stage);
Modem* modem() const;
private:
// inner request handler type
int m_type;
// arguments to handler
RequestArgs *m_args;
// stage
int m_stage;
// retry count in case of error, if 0 request will not be processed
int m_retry;
// base type offset for conversation handler
int m_baseOffset;
// modem
Modem * m_modem;
friend class Modem;
};
Q_DECLARE_METATYPE(ModemRequest)
Q_DECLARE_METATYPE(ModemRequest*)
Q_DECLARE_METATYPE(ModemRequest**)
class ConversationHandler
{
public:
ConversationHandler() {}
virtual ~ConversationHandler() {}
// processes conversation (answer) for specified request
// Args:
// [in, out] request - current request in queue (can be modified in this method)
// [in] c - modem answer
// [out] status - set to corresponding status after request processing
// [out] answerData - pointer that must be initialized by answer data or set to NULL
virtual void processConversation(ModemRequest *request,
const Conversation &c,
ModemRequest::Status &status,
AnswerData* &answerData) const
{
Q_UNUSED(request);
Q_UNUSED(c);
Q_UNUSED(answerData);
status = ModemRequest::Failure;
}
// processes unexpected data from modem
// if request processed successful should return true, otherwise false
// Args:
// [in] data - data received by modem
// [out] replyType - should set to reply type if can recognize the data
// [out] answerData - pointer that must be initialized by answer data or set to NULL
virtual bool processUnexpectedData(const QByteArray& data,
int &replyType,
AnswerData* &answerData) const
{
Q_UNUSED(data);
Q_UNUSED(replyType);
Q_UNUSED(answerData);
return false;
}
// returns the data that should be sent to port for specified request
virtual QByteArray requestData(const ModemRequest *request) const
{
Q_UNUSED(request);
return QByteArray();
}
// returns the number of request types that can be processed by this handler
virtual int requestTypesCount() const
{
return 0;
}
// returns the name for this handler (for internal purposes)
virtual QString name() const = 0;
// returns the request args for specified request type
virtual RequestArgs* requestArgs(int type) const
{
Q_UNUSED(type);
return NULL;
}
};
class InitConversationHandler;
class QTimer;
class Modem : public PortController
{
Q_OBJECT
public:
Modem();
~Modem();
void registerConversationHandler(ConversationHandler * handler);
void unregisterConversationHandler(ConversationHandler * handler);
// creates modem request with specified type to passed handler name
// and specified retry count on errors
ModemRequest * createRequest(const QString &handlerName, int type, int retries);
public slots:
// appends request to modem queue,
// after processing modem will delete the ModemRequest object
void appendRequest(ModemRequest *request);
signals:
void replyReceived(ModemReply * reply);
protected:
bool processConversation(Conversation c);
bool processUnexpectedData(const QByteArray& data);
QByteArray requestData() const;
void modemDetected(bool status);
protected slots:
void onInitTimeout();
void onPingTimeout();
private:
QLinkedList<ModemRequest*> m_requests;
// baseOffset ; handler
QMap<int, ConversationHandler*> m_conversationHandlers;
// handler name ; baseOffset
QMap<QString, int> m_conversationHandlersNames;
// is modem initialization sequence finished
bool m_modemInited;
// handler that processes modem initialization
InitConversationHandler * m_initHandler;
// init timeout timer
QTimer * m_initTimer;
// timer checks modem availability
QTimer * m_pingTimer;
bool m_pingReceived;
mutable QReadWriteLock m_rwlock;
Q_DISABLE_COPY(Modem)
};
Q_DECLARE_METATYPE(Modem*)
Q_DECLARE_METATYPE(Modem**)
#endif // MODEM_H
|
AsyncVoid/CustomEnchants
|
src/me/async/customenchants/effect/armour/HazyEffect.java
|
package me.async.customenchants.effect.armour;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.scheduler.BukkitRunnable;
import me.async.customenchants.Main;
import me.async.customenchants.effect.IEffect;
import me.async.customenchants.utils.CloneUtil;
import net.minecraft.server.v1_8_R3.PacketPlayOutEntityDestroy;
public class HazyEffect extends IEffect
{
@Override
public void handleDamageEvent(final EntityDamageByEntityEvent ev, int level)
{
if(ev.getDamager() instanceof Player && ev.getEntity() instanceof Player)
{
if(getRandom().nextInt(10) < level)
{
final int id = CloneUtil.CloneHuman((Player)ev.getEntity(), (Player)ev.getDamager());
new BukkitRunnable()
{
@Override
public void run() {
PacketPlayOutEntityDestroy destroy = new PacketPlayOutEntityDestroy(id);
((CraftPlayer) ev.getDamager()).getHandle().playerConnection.sendPacket(destroy);
}
}.runTaskLaterAsynchronously(Main.plugin, 60);
}
}
}
}
|
chaoxyCode/mbg
|
generator-mybatis-generator-1.4.0/core/mybatis-generator-core/src/main/java/org/mybatis/generator/api/dom/java/render/InnerClassRenderer.java
|
/**
* Copyright 2006-2020 the original author or authors.
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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.mybatis.generator.api.dom.java.render;
import org.mybatis.generator.api.dom.java.CompilationUnit;
import org.mybatis.generator.api.dom.java.InnerClass;
import org.mybatis.generator.api.dom.java.JavaDomUtils;
import org.mybatis.generator.internal.util.CustomCollectors;
import java.util.ArrayList;
import java.util.List;
public class InnerClassRenderer {
public List<String> render(InnerClass innerClass, CompilationUnit compilationUnit) {
List<String> lines = new ArrayList<>();
lines.addAll(innerClass.getJavaDocLines());
lines.addAll(innerClass.getAnnotations());
lines.add(renderFirstLine(innerClass, compilationUnit));
lines.addAll(RenderingUtilities.renderFields(innerClass.getFields(), compilationUnit));
lines.addAll(
RenderingUtilities.renderInitializationBlocks(
innerClass.getInitializationBlocks()));
lines.addAll(
RenderingUtilities.renderClassOrEnumMethods(
innerClass.getMethods(), compilationUnit));
lines.addAll(
RenderingUtilities.renderInnerClasses(
innerClass.getInnerClasses(), compilationUnit));
lines.addAll(
RenderingUtilities.renderInnerInterfaces(
innerClass.getInnerInterfaces(), compilationUnit));
lines.addAll(
RenderingUtilities.renderInnerEnums(innerClass.getInnerEnums(), compilationUnit));
lines = RenderingUtilities.removeLastEmptyLine(lines);
lines.add("}"); // $NON-NLS-1$
return lines;
}
private String renderFirstLine(InnerClass innerClass, CompilationUnit compilationUnit) {
StringBuilder sb = new StringBuilder();
sb.append(innerClass.getVisibility().getValue());
if (innerClass.isAbstract()) {
sb.append("abstract "); // $NON-NLS-1$
}
if (innerClass.isStatic()) {
sb.append("static "); // $NON-NLS-1$
}
if (innerClass.isFinal()) {
sb.append("final "); // $NON-NLS-1$
}
sb.append("class "); // $NON-NLS-1$
sb.append(innerClass.getType().getShortName());
sb.append(
RenderingUtilities.renderTypeParameters(
innerClass.getTypeParameters(), compilationUnit));
sb.append(renderSuperClass(innerClass, compilationUnit));
sb.append(renderSuperInterfaces(innerClass, compilationUnit));
sb.append(" {"); // $NON-NLS-1$
return sb.toString();
}
private String renderSuperClass(InnerClass innerClass, CompilationUnit compilationUnit) {
return innerClass
.getSuperClass()
.map(
sc ->
" extends "
+ JavaDomUtils.calculateTypeName(
compilationUnit, sc)) // $NON-NLS-1$
.orElse(""); // $NON-NLS-1$
}
// should return an empty string if no super interfaces
private String renderSuperInterfaces(InnerClass innerClass, CompilationUnit compilationUnit) {
return innerClass.getSuperInterfaceTypes().stream()
.map(tp -> JavaDomUtils.calculateTypeName(compilationUnit, tp))
.collect(
CustomCollectors.joining(
", ",
" implements ",
"")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
}
|
mgdigital/Chromaprint.scala
|
src/core/test/scala/chromaprint/TestHelperSpec.scala
|
<filename>src/core/test/scala/chromaprint/TestHelperSpec.scala
package chromaprint
import spire.math.UInt
class TestHelperSpec extends AbstractSpec {
behavior of "TestHelper"
it should "count set bits 32" in {
TestHelper.countSetBits(UInt(0x00)) should equal (0)
TestHelper.countSetBits(UInt(0xFF)) should equal (8)
TestHelper.countSetBits(UInt(0xFFFF)) should equal (16)
TestHelper.countSetBits(UInt(0xFFFFFF)) should equal (24)
TestHelper.countSetBits(UInt(0xFFFFFFFF)) should equal (32)
TestHelper.countSetBits(UInt(0x01010101)) should equal (4)
}
}
|
mcmellawatt/geode-native
|
cppcache/src/CacheableEnum.cpp
|
<filename>cppcache/src/CacheableEnum.cpp
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <geode/CacheableEnum.hpp>
#include <geode/internal/functional.hpp>
#include "Utils.hpp"
#include "PdxHelper.hpp"
#include "GeodeTypeIdsImpl.hpp"
#include "EnumInfo.hpp"
#include "CacheRegionHelper.hpp"
namespace apache {
namespace geode {
namespace client {
CacheableEnum::CacheableEnum()
: m_enumClassName(nullptr),
m_enumName(nullptr),
m_ordinal(-1),
m_hashcode(0) {}
CacheableEnum::CacheableEnum(std::string enumClassName, std::string enumName,
int32_t ordinal)
: m_enumClassName(std::move(enumClassName)),
m_enumName(std::move(enumName)),
m_ordinal(ordinal),
m_hashcode(0) {}
void CacheableEnum::toData(apache::geode::client::DataOutput& output) const {
int enumVal = PdxHelper::getEnumValue(
m_enumClassName.c_str(), m_enumName.c_str(), m_ordinal,
CacheRegionHelper::getCacheImpl(output.getCache())->getPdxTypeRegistry());
output.write(static_cast<int8_t>(GeodeTypeIds::CacheableEnum));
output.write(int8_t(enumVal >> 24));
output.writeArrayLen(enumVal & 0xFFFFFF);
}
void CacheableEnum::fromData(apache::geode::client::DataInput& input) {
auto dsId = input.read();
int32_t arrLen = input.readArrayLength();
int enumId = (dsId << 24) | (arrLen & 0xFFFFFF);
auto enumVal = PdxHelper::getEnum(
enumId,
CacheRegionHelper::getCacheImpl(input.getCache())->getPdxTypeRegistry());
m_enumClassName = enumVal->getEnumClassName()->toString();
m_enumName = enumVal->getEnumName()->toString();
m_ordinal = enumVal->getEnumOrdinal();
calculateHashcode();
}
void CacheableEnum::calculateHashcode() {
m_hashcode = 1;
const int32_t prime = 31;
m_hashcode = prime * m_hashcode + geode_hash<std::string>{}(m_enumClassName);
m_hashcode = prime * m_hashcode + geode_hash<std::string>{}(m_enumName);
}
bool CacheableEnum::operator==(const CacheableKey& other) const {
if (other.typeId() != typeId()) {
return false;
}
auto&& otherEnum = dynamic_cast<const CacheableEnum*>(&other);
if (otherEnum == nullptr) {
return false;
}
if (m_ordinal != otherEnum->m_ordinal) {
return false;
}
if (m_enumClassName != otherEnum->m_enumClassName) {
return false;
}
if (m_enumName != otherEnum->m_enumName) {
return false;
}
return true;
}
} // namespace client
} // namespace geode
} // namespace apache
|
45258E9F/IntPTI
|
src/org/sosy_lab/cpachecker/pcc/strategy/partitioning/PartitionChecker.java
|
<reponame>45258E9F/IntPTI
/*
* IntPTI: integer error fixing by proper-type inference
* Copyright (c) 2017.
*
* Open-source component:
*
* CPAchecker
* Copyright (C) 2007-2014 <NAME>
*
* Guava: Google Core Libraries for Java
* Copyright (C) 2010-2006 Google
*
*
*/
package org.sosy_lab.cpachecker.pcc.strategy.partitioning;
import com.google.common.base.Preconditions;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import org.sosy_lab.common.ShutdownNotifier;
import org.sosy_lab.common.log.LogManager;
import org.sosy_lab.cpachecker.cfa.model.CFANode;
import org.sosy_lab.cpachecker.core.interfaces.AbstractState;
import org.sosy_lab.cpachecker.core.interfaces.Precision;
import org.sosy_lab.cpachecker.core.interfaces.StopOperator;
import org.sosy_lab.cpachecker.core.interfaces.TransferRelation;
import org.sosy_lab.cpachecker.core.interfaces.pcc.PartitioningCheckingHelper;
import org.sosy_lab.cpachecker.exceptions.CPAException;
import org.sosy_lab.cpachecker.exceptions.CPATransferException;
import org.sosy_lab.cpachecker.util.AbstractStates;
import org.sosy_lab.cpachecker.util.Pair;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.logging.Level;
public class PartitionChecker {
private final Multimap<CFANode, AbstractState> partitionParts = HashMultimap.create();
private final List<AbstractState> certificatePart = new ArrayList<>();
private final Collection<AbstractState> mustBeInCertificate = new HashSet<>();
private final PartitioningCheckingHelper partitionHelper;
private final PartitioningIOHelper ioHelper;
private final Precision initPrec;
private final StopOperator stop;
private final TransferRelation transfer;
private final ShutdownNotifier shutdownNotifier;
private final LogManager logger;
public PartitionChecker(
final Precision pInitPrecision, final StopOperator pStop, final TransferRelation pTransfer,
final PartitioningIOHelper pIOHelper, final PartitioningCheckingHelper pHelperInfo,
final ShutdownNotifier pShutdownNotifier, final LogManager pLogger) {
initPrec = pInitPrecision;
stop = pStop;
transfer = pTransfer;
ioHelper = pIOHelper;
partitionHelper = pHelperInfo;
shutdownNotifier = pShutdownNotifier;
logger = pLogger;
}
public void checkPartition(int pIndex) {
Multimap<CFANode, AbstractState> statesPerLocation = HashMultimap.create();
Pair<AbstractState[], AbstractState[]> partition = ioHelper.getPartition(pIndex);
Preconditions.checkNotNull(partition);
// add nodes of partition
for (AbstractState internalNode : partition.getFirst()) {
addElement(internalNode, true, statesPerLocation);
}
// add adjacent nodes of other partition
for (AbstractState adjacentNode : partition.getSecond()) {
addElement(adjacentNode, false, statesPerLocation);
}
AbstractState checkedState;
CFANode loc;
Collection<? extends AbstractState> successors;
int nextPos = 0;
while (nextPos < certificatePart.size()) {
if (shutdownNotifier.shouldShutdown()) {
partitionHelper.abortCheckingPreparation();
return;
}
if (certificatePart.size() + partitionHelper.getCurrentCertificateSize() > ioHelper
.getSavedReachedSetSize()) {
logger.log(Level.SEVERE,
"Checking failed, recomputed certificate bigger than original reached set.");
partitionHelper.abortCheckingPreparation();
return;
}
checkedState = certificatePart.get(nextPos++);
// compute successors
try {
successors = transfer.getAbstractSuccessors(checkedState,
Lists.<AbstractState>newArrayList(), initPrec);
for (AbstractState successor : successors) {
// check if covered
loc = AbstractStates.extractLocation(successor);
if (!stop.stop(successor, statesPerLocation.get(loc), initPrec)) {
certificatePart.add(successor);
}
}
} catch (CPATransferException | InterruptedException e) {
logger.log(Level.SEVERE, "Checking failed, successor computation failed");
partitionHelper.abortCheckingPreparation();
return;
} catch (CPAException e) {
logger.log(Level.SEVERE, "Checking failed, checking successor coverage failed");
partitionHelper.abortCheckingPreparation();
return;
}
}
}
public void addCertificatePartsToCertificate(final Collection<AbstractState> pCertificate) {
pCertificate.addAll(certificatePart);
}
public void addElementsCheckedInOtherPartitions(final Collection<AbstractState> pStatesMustBeInCertificate) {
pStatesMustBeInCertificate.addAll(mustBeInCertificate);
}
public void addPartitionElements(final Multimap<CFANode, AbstractState> pPartitionElements) {
pPartitionElements.putAll(partitionParts);
}
public void clearPartitionElementsSavedForInspection() {
certificatePart.clear();
}
public void clearAllSavedPartitioningElements() {
certificatePart.clear();
partitionParts.clear();
mustBeInCertificate.clear();
}
private void addElement(
final AbstractState element, final boolean inCertificate,
final Multimap<CFANode, AbstractState> pStatesPerLocation) {
CFANode node = AbstractStates.extractLocation(element);
pStatesPerLocation.put(node, element);
if (inCertificate) {
partitionParts.put(node, element);
certificatePart.add(element);
} else {
mustBeInCertificate.add(element);
}
}
}
|
AdrianaDinca/training
|
assignment-properties-done/src/main/java/com/crossover/trial/properties/source/URLConfigLoader.java
|
package com.crossover.trial.properties.source;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import com.crossover.trial.properties.ConfigException;
public class URLConfigLoader extends StringPairStreamLoader {
@Override
public boolean canLoad(String location) {
return location.startsWith("https:") || location.startsWith("http:");
}
@Override
protected InputStream openStream(String location) {
try {
URL url = new URL(location);
return url.openStream();
} catch (IOException e) {
throw new ConfigException("Cannot open config file from URL: " + location,e);
}
}
}
|
psykulsk/contrail-operator
|
pkg/certificates/signer_ca_test.go
|
<filename>pkg/certificates/signer_ca_test.go
package certificates
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
core "k8s.io/api/core/v1"
meta "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
)
func TestCertificateSigning(t *testing.T) {
const (
testOwnerName = "testName"
testOwnerUID = "testUID"
testOwnerNamespace = "testNamespace"
)
scheme := runtime.NewScheme()
require.NoError(t, core.SchemeBuilder.AddToScheme(scheme))
cl := fake.NewFakeClientWithScheme(scheme)
owner := &core.Pod{
ObjectMeta: meta.ObjectMeta{
Name: testOwnerName,
UID: testOwnerUID,
Namespace: testOwnerNamespace,
},
}
caCertificate := NewCACertificate(cl, scheme, owner, "ownerType")
assert.NoError(t, caCertificate.EnsureExists())
certPrivKey, _ := rsa.GenerateKey(rand.Reader, 2048)
notBefore := time.Now()
notAfter := notBefore.Add(10 * 365 * 24 * time.Hour)
certificateTemplate := x509.Certificate{
SerialNumber: big.NewInt(2),
Subject: pkix.Name{
CommonName: "testname",
},
DNSNames: []string{"testname"},
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
}
certSigner := signer{cl, owner}
certBytes, err := certSigner.SignCertificate(certificateTemplate, *certPrivKey)
assert.NoError(t, err)
pemBlock, restData := pem.Decode(certBytes)
assert.Equal(t, len(restData), 0)
caCert, err := x509.ParseCertificate(pemBlock.Bytes)
assert.NoError(t, err)
assert.Equal(t, caCert.KeyUsage, x509.KeyUsageKeyEncipherment|x509.KeyUsageDigitalSignature)
assert.Equal(t, caCert.ExtKeyUsage, []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth})
dur := caCert.NotAfter.Sub(caCert.NotBefore)
assert.GreaterOrEqual(t, dur.Hours(), caCertValidityPeriod.Hours())
assert.Equal(t, caCert.Issuer.CommonName, "contrail-signer")
}
|
wkoszycki/constellation
|
src/main/scala/org/constellation/primitives/NodeData.scala
|
package org.constellation.primitives
import java.net.InetSocketAddress
import java.security.KeyPair
import akka.actor.ActorRef
import constellation._
import org.constellation.crypto.KeyUtils
import org.constellation.p2p.PeerRegistrationRequest
import org.constellation.primitives.Schema.NodeState.NodeState
import org.constellation.primitives.Schema._
import org.constellation.util.Metrics
trait NodeData {
// var dbActor : SwayDBDatastore = _
var peerManager: ActorRef = _
var metrics: Metrics = _
@volatile var downloadMode: Boolean = true
@volatile var downloadInProgress: Boolean = false
@volatile var generateRandomTX: Boolean = false
var heartbeatEnabled: Boolean = true
var lastConfirmationUpdateTime: Long = System.currentTimeMillis()
@volatile implicit var keyPair: KeyPair = _
def publicKeyHash: Int = keyPair.getPublic.hashCode()
def id: Id = keyPair.getPublic.toId
def selfAddressStr: String = id.address
val dummyAddress: String = KeyUtils.makeKeyPair().getPublic.toId.address
@volatile var nodeState: NodeState = NodeState.PendingDownload
def setNodeState(
nodeState_ : NodeState
): Unit = {
nodeState = nodeState_
metrics.updateMetric("nodeState", nodeState.toString)
}
var externalHostString: String = "127.0.0.1"
var externlPeerHTTPPort: Int = 9001
def peerRegistrationRequest = PeerRegistrationRequest(externalHostString, externlPeerHTTPPort, id)
@volatile var externalAddress: Option[InetSocketAddress] = None
@volatile var apiAddress: Option[InetSocketAddress] = None
@volatile var tcpAddress: Option[InetSocketAddress] = None
var remotes: Seq[InetSocketAddress] = Seq()
def updateKeyPair(kp: KeyPair): Unit = {
keyPair = kp
}
}
|
99002562/jasmine_1
|
src/test/java/com/gk/test/RunWebAppSuite.java
|
<filename>src/test/java/com/gk/test/RunWebAppSuite.java
package com.gk.test;
import cucumber.api.CucumberOptions;
import cucumber.api.testng.AbstractTestNGCucumberTests;
@CucumberOptions(features = "target/test-classes", tags = {"@mobile"}, monochrome = true, plugin = {
"pretty", "html:target/cucumber-report/webapp",
"json:target/cucumber-report/webapp/cucumber.json",
"rerun:target/cucumber-report/webapp/rerun.txt"},
glue = "com.gk.test.step_definitions.webapp")
public class RunWebAppSuite extends AbstractTestNGCucumberTests {
}
|
gv2011/quarry
|
bits/src/main/java/com/github/gv2011/jsplit/Splitter.java
|
package com.github.gv2011.jsplit;
import java.io.InputStream;
import java.io.OutputStream;
import com.github.gv2011.quarry.util.Hash;
public interface Splitter {
Hash split(InputStream in, SliceWriter sliceSink);
void join(Hash ref, SliceReader sliceSource, OutputStream out);
}
|
fmidev/smartmet-library-grid-files
|
src/grib2/definition/MatrixDataRepresentation.h
|
<reponame>fmidev/smartmet-library-grid-files
// ***********************************************************************
// DO NOT EDIT THIS FILE !!!
// ***********************************************************************
// This file is automatically generated from the grib_api templates. All
// changes will be overridden. If you want to do permanent changes then
// you should write them into the 'MatrixDataRepresentationImpl.*' files.
// ***********************************************************************
#pragma once
#include "../../common/AttributeList.h"
#include "../../common/DataWriter.h"
#include "../../common/MemoryReader.h"
#include "../../grid/Typedefs.h"
#include "../RepresentationDefinition.h"
#include "PackingSettings.h"
namespace SmartMet {
namespace GRIB2 {
/*! \brief The class is automatically created from the template (5.1).*/
class MatrixDataRepresentation : public RepresentationDefinition {
public:
MatrixDataRepresentation();
virtual ~MatrixDataRepresentation();
virtual uint getTemplateNumber() const;
virtual RepresentationDefinition *createRepresentationDefinition() const;
virtual void read(MemoryReader &memoryReader);
virtual void write(DataWriter &dataWriter);
virtual void getAttributeList(const std::string &prefix, T::AttributeList &attributeList) const;
virtual bool getAttributeValue(const char *attributeName, std::string &attributeValue) const;
virtual bool hasAttributeValue(const char *attributeName, const char *attributeValue) const;
virtual void print(std::ostream &stream, uint level, uint optionFlags) const;
virtual T::Hash countHash() const;
PackingSettings *getPacking() const;
void setPacking(PackingSettings &packing);
const T::UInt8_opt &getMatrixBitmapsPresent() const;
void setMatrixBitmapsPresent(T::UInt8_opt matrixBitmapsPresent);
const T::UInt32_opt &getNumberOfCodedValues() const;
void setNumberOfCodedValues(T::UInt32_opt numberOfCodedValues);
const T::UInt16_opt &getFirstDimension() const;
void setFirstDimension(T::UInt16_opt firstDimension);
const T::UInt16_opt &getSecondDimension() const;
void setSecondDimension(T::UInt16_opt secondDimension);
const T::UInt8_opt &getFirstDimensionCoordinateValueDefinition() const;
void setFirstDimensionCoordinateValueDefinition(T::UInt8_opt firstDimensionCoordinateValueDefinition);
const T::UInt8_opt &getNC1() const;
void setNC1(T::UInt8_opt nC1);
const T::UInt8_opt &getSecondDimensionCoordinateValueDefinition() const;
void setSecondDimensionCoordinateValueDefinition(T::UInt8_opt secondDimensionCoordinateValueDefinition);
const T::UInt8_opt &getNC2() const;
void setNC2(T::UInt8_opt nC2);
const T::UInt8_opt &getFirstDimensionPhysicalSignificance() const;
void setFirstDimensionPhysicalSignificance(T::UInt8_opt firstDimensionPhysicalSignificance);
const T::UInt8_opt &getSecondDimensionPhysicalSignificance() const;
void setSecondDimensionPhysicalSignificance(T::UInt8_opt secondDimensionPhysicalSignificance);
float getCoefsFirst() const;
void setCoefsFirst(float coefsFirst);
float getCoefsSecond() const;
void setCoefsSecond(float coefsSecond);
protected:
// # Copyright 2005-2019 ECMWF.
//
// # TEMPLATE 5.1, Matrix values at grid point -simple packing
//
// include "grib2/template.5.packing.def";
mutable PackingSettings mPacking;
//
// unsigned[1] matrixBitmapsPresent ;
T::UInt8_opt mMatrixBitmapsPresent;
// # same as in edition 1
// alias secondaryBitmapPresent=matrixBitmapsPresent;
//
// # Number of data values encoded in Section 7
// unsigned[4] numberOfCodedValues ;
T::UInt32_opt mNumberOfCodedValues;
//
// # NR - first dimension
// # (rows)
// unsigned[2] firstDimension ;
T::UInt16_opt mFirstDimension;
//
// alias NR = firstDimension;
// # NC - second dimension
// # (columns)
// unsigned[2] secondDimension ;
T::UInt16_opt mSecondDimension;
//
// alias NC = secondDimension;
// # First dimension coordinate value definition
// # (Code Table 5.2)
// unsigned[1] firstDimensionCoordinateValueDefinition ;
T::UInt8_opt mFirstDimensionCoordinateValueDefinition;
//
// # NC1 - number of coefficients or values used to specify first dimension coordinate function
// unsigned[1] NC1 : dump ;
T::UInt8_opt mNC1;
// alias numberOfCoefficientsOrValuesUsedToSpecifyFirstDimensionCoordinateFunction=NC1;
//
// # Second dimension coordinate value definition
// # (Code Table 5.2)
// unsigned[1] secondDimensionCoordinateValueDefinition ;
T::UInt8_opt mSecondDimensionCoordinateValueDefinition;
//
// # NC2 - number of coefficients or values used to specify second dimension coordinate function
// unsigned[1] NC2 : dump ;
T::UInt8_opt mNC2;
// alias numberOfCoefficientsOrValuesUsedToSpecifySecondDimensionCoordinateFunction = NC2;
//
// # First dimension physical significance
// # (Code Table 5.3)
// unsigned[1] firstDimensionPhysicalSignificance ;
T::UInt8_opt mFirstDimensionPhysicalSignificance;
//
// # Second dimension physical significance
// # (Code Table 5.3)
// unsigned[1] secondDimensionPhysicalSignificance ;
T::UInt8_opt mSecondDimensionPhysicalSignificance;
//
// ieeefloat coefsFirst[NC1]; # TODO: find proper names
float mCoefsFirst;
// ieeefloat coefsSecond[NC2];# TODO: find proper names
float mCoefsSecond;
//
// alias data.coefsFirst = coefsFirst;
// alias data.coefsSecond=coefsSecond;
//
// if(matrixBitmapsPresent == 1)
// {
//
// constant datumSize = NC*NR;
// constant secondaryBitmapsCount = numberOfValues + 0; #
// constant secondaryBitmapsSize = secondaryBitmapsCount/8;
//
// transient numberOfDataMatrices = numberOfDataPoints/datumSize;
//
// position offsetBBitmap;
// meta secondaryBitmaps g2bitmap(
// dummy,
// missingValue,
// offsetBSection5,
// section5Length,
// numberOfCodedValues ,
// dummy) : read_only
// ;
//
// meta bitmap data_g2secondary_bitmap(primaryBitmap,
// secondaryBitmaps,
// missingValue,datumSize,numberOfDataPoints) : read_only;
//
// }
};
} // namespace GRIB2
} // namespace SmartMet
|
mmghasemi/Vega
|
platform/com.subgraph.vega.html/src/org/w3c/dom/html2/HTMLObjectElement.java
|
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package org.w3c.dom.html2;
import org.w3c.dom.Document;
/**
* Generic embedded object.In principle, all properties on the object element
* are read-write but in some environments some properties may be read-only
* once the underlying object is instantiated. See the OBJECT element
* definition in [<a href='http://www.w3.org/TR/1999/REC-html401-19991224'>HTML 4.01</a>].
* <p>See also the <a href='http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109'>Document Object Model (DOM) Level 2 HTML Specification</a>.
*/
public interface HTMLObjectElement extends HTMLElement {
/**
* Returns the <code>FORM</code> element containing this control. Returns
* <code>null</code> if this control is not within the context of a
* form.
*/
public HTMLFormElement getForm();
/**
* Applet class file. See the <code>code</code> attribute for
* HTMLAppletElement.
*/
public String getCode();
/**
* Applet class file. See the <code>code</code> attribute for
* HTMLAppletElement.
*/
public void setCode(String code);
/**
* Aligns this object (vertically or horizontally) with respect to its
* surrounding text. See the align attribute definition in HTML 4.01.
* This attribute is deprecated in HTML 4.01.
*/
public String getAlign();
/**
* Aligns this object (vertically or horizontally) with respect to its
* surrounding text. See the align attribute definition in HTML 4.01.
* This attribute is deprecated in HTML 4.01.
*/
public void setAlign(String align);
/**
* Space-separated list of archives. See the archive attribute definition
* in HTML 4.01.
*/
public String getArchive();
/**
* Space-separated list of archives. See the archive attribute definition
* in HTML 4.01.
*/
public void setArchive(String archive);
/**
* Width of border around the object. See the border attribute definition
* in HTML 4.01. This attribute is deprecated in HTML 4.01.
*/
public String getBorder();
/**
* Width of border around the object. See the border attribute definition
* in HTML 4.01. This attribute is deprecated in HTML 4.01.
*/
public void setBorder(String border);
/**
* Base URI [<a href='http://www.ietf.org/rfc/rfc2396.txt'>IETF RFC 2396</a>] for <code>classid</code>, <code>data</code>, and
* <code>archive</code> attributes. See the codebase attribute definition
* in HTML 4.01.
*/
public String getCodeBase();
/**
* Base URI [<a href='http://www.ietf.org/rfc/rfc2396.txt'>IETF RFC 2396</a>] for <code>classid</code>, <code>data</code>, and
* <code>archive</code> attributes. See the codebase attribute definition
* in HTML 4.01.
*/
public void setCodeBase(String codeBase);
/**
* Content type for data downloaded via <code>classid</code> attribute.
* See the codetype attribute definition in HTML 4.01.
*/
public String getCodeType();
/**
* Content type for data downloaded via <code>classid</code> attribute.
* See the codetype attribute definition in HTML 4.01.
*/
public void setCodeType(String codeType);
/**
* A URI [<a href='http://www.ietf.org/rfc/rfc2396.txt'>IETF RFC 2396</a>] specifying the location of the object's data. See the data
* attribute definition in HTML 4.01.
*/
public String getData();
/**
* A URI [<a href='http://www.ietf.org/rfc/rfc2396.txt'>IETF RFC 2396</a>] specifying the location of the object's data. See the data
* attribute definition in HTML 4.01.
*/
public void setData(String data);
/**
* Declare (for future reference), but do not instantiate, this object.
* See the declare attribute definition in HTML 4.01.
*/
public boolean getDeclare();
/**
* Declare (for future reference), but do not instantiate, this object.
* See the declare attribute definition in HTML 4.01.
*/
public void setDeclare(boolean declare);
/**
* Override height. See the height attribute definition in HTML 4.01.
*/
public String getHeight();
/**
* Override height. See the height attribute definition in HTML 4.01.
*/
public void setHeight(String height);
/**
* Horizontal space, in pixels, to the left and right of this image,
* applet, or object. See the hspace attribute definition in HTML 4.01.
* This attribute is deprecated in HTML 4.01.
*/
public int getHspace();
/**
* Horizontal space, in pixels, to the left and right of this image,
* applet, or object. See the hspace attribute definition in HTML 4.01.
* This attribute is deprecated in HTML 4.01.
*/
public void setHspace(int hspace);
/**
* Form control or object name when submitted with a form. See the name
* attribute definition in HTML 4.01.
*/
public String getName();
/**
* Form control or object name when submitted with a form. See the name
* attribute definition in HTML 4.01.
*/
public void setName(String name);
/**
* Message to render while loading the object. See the standby attribute
* definition in HTML 4.01.
*/
public String getStandby();
/**
* Message to render while loading the object. See the standby attribute
* definition in HTML 4.01.
*/
public void setStandby(String standby);
/**
* Index that represents the element's position in the tabbing order. See
* the tabindex attribute definition in HTML 4.01.
*/
public int getTabIndex();
/**
* Index that represents the element's position in the tabbing order. See
* the tabindex attribute definition in HTML 4.01.
*/
public void setTabIndex(int tabIndex);
/**
* Content type for data downloaded via <code>data</code> attribute. See
* the type attribute definition in HTML 4.01.
*/
public String getType();
/**
* Content type for data downloaded via <code>data</code> attribute. See
* the type attribute definition in HTML 4.01.
*/
public void setType(String type);
/**
* Use client-side image map. See the usemap attribute definition in HTML
* 4.01.
*/
public String getUseMap();
/**
* Use client-side image map. See the usemap attribute definition in HTML
* 4.01.
*/
public void setUseMap(String useMap);
/**
* Vertical space, in pixels, above and below this image, applet, or
* object. See the vspace attribute definition in HTML 4.01. This
* attribute is deprecated in HTML 4.01.
*/
public int getVspace();
/**
* Vertical space, in pixels, above and below this image, applet, or
* object. See the vspace attribute definition in HTML 4.01. This
* attribute is deprecated in HTML 4.01.
*/
public void setVspace(int vspace);
/**
* Override width. See the width attribute definition in HTML 4.01.
*/
public String getWidth();
/**
* Override width. See the width attribute definition in HTML 4.01.
*/
public void setWidth(String width);
/**
* The document this object contains, if there is any and it is available,
* or <code>null</code> otherwise.
* @since DOM Level 2
*/
public Document getContentDocument();
}
|
danieljurek/Sia-EventUI
|
src/services/signalRService.js
|
<reponame>danieljurek/Sia-EventUI<gh_stars>1-10
import * as signalR from '@aspnet/signalr'
import { getEventActionSet } from 'actions/eventActions'
import * as signalRActions from 'actions/signalRActions'
import config from 'config'
import { getToken } from 'services/authNService'
const defaultBasePath = config.baseUrl
const defaultScopes = [config.clientId]
let signalRConnectionSingleton
let appliedFilterSingleton
export const getSignalRConnection = (dispatch) => signalRConnectionSingleton
? Promise.resolve(signalRConnectionSingleton)
: resetSignalRConnection(dispatch)
export const resetSignalRConnection = (dispatch) => {
return signalReduxConnection(dispatch)
.then(connection => {
signalRConnectionSingleton = connection
return signalRConnectionSingleton
})
}
const signalReduxConnection = (dispatch) => configureConnection(dispatch)
.then(connection => startConnection(connection, dispatch))
const configureConnection = (dispatch) => getToken(defaultScopes)
.then(token => {
const hubAndHttpOptions = {
accessTokenFactory: () => token,
transport: signalR.TransportType.WebSockets
}
let connection = new signalR.HubConnection(defaultBasePath + 'events/live', hubAndHttpOptions)
connection.on('Send', (event) => {
const eventObject = JSON.parse(event)
dispatch(signalRActions.receiveMessage())
dispatch(getEventActionSet(eventObject.id).succeed(eventObject))
})
connection.closedCallbacks = connection.closedCallbacks.concat((error) => dispatch(signalRActions.connectionClosed(error ? error.message : 'No Error Message', error ? error.stack : 'No Stack Trace')))
return connection
})
const startConnection = (connection, dispatch) => {
dispatch(signalRActions.tryEstablishConnection())
return connection
.start()
.then(() => {
if (appliedFilterSingleton) {
connection.invoke('updateFilter', appliedFilterSingleton)
} else {
connection.invoke('clearFilter')
}
})
.then(() => {
dispatch(signalRActions.succeedEstablishConnection())
return connection
},
(error) => {
dispatch(signalRActions.failEstablishConnection(error ? error.message : 'No error message', error ? error.stack : 'No stack trace provided'))
return connection
}
)
}
export const updateEventFilter = (eventFilter, dispatch) => {
appliedFilterSingleton = eventFilter
getSignalRConnection(dispatch)
.then(connection => connection.invoke('updateFilter', eventFilter))
}
export const clearEventFilter = (dispatch) => {
appliedFilterSingleton = null
getSignalRConnection(dispatch)
.then(connection => connection.invoke('clearFilter'))
}
export const getEchoConnectionForTesting = () => { // Do not use in prod
const callHistory = []
signalRConnectionSingleton = {
invoke: (...args) => callHistory.push([...args])
}
return callHistory
}
export default getSignalRConnection
|
drypot/sobeaut
|
server/about/about-all.js
|
'use strict';
var init = require('../base/init');
var expb = require('../express/express-base');
init.add(function (done) {
expb.core.get('/about/site', function (req, res, done) {
res.render('about/about-site');
});
expb.core.get('/about/company', function (req, res, done) {
res.render('about/about-company');
});
expb.core.get('/about/ad', function (req, res, done) {
res.render('about/about-ad');
});
expb.core.get('/about/privacy', function (req, res, done) {
res.render('about/about-privacy');
});
expb.core.get('/about/help', function (req, res, done) {
res.render('about/about-help');
});
done();
});
|
giadram/twisted
|
src/twisted/positioning/test/test_nmea.py
|
<filename>src/twisted/positioning/test/test_nmea.py
# Copyright (c) 2009-2011 Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Test cases for using NMEA sentences.
"""
import datetime
from operator import attrgetter
from zope.interface import implementer
from twisted.positioning import base, nmea, ipositioning
from twisted.positioning.test.receiver import MockPositioningReceiver
from twisted.trial.unittest import TestCase
from twisted.positioning.base import Angles
# Sample sentences
GPGGA = b"$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47"
GPRMC = b"$GPRMC,123519,A,4807.038,N,01131.000,E,022.4,084.4,230394,003.1,W*6A"
GPGSA = b"$GPGSA,A,3,19,28,14,18,27,22,31,39,,,,,1.7,1.0,1.3*34"
GPHDT = b"$GPHDT,038.005,T*3B"
GPGLL = b"$GPGLL,4916.45,N,12311.12,W,225444,A*31"
GPGLL_PARTIAL = b"$GPGLL,3751.65,S,14507.36,E*77"
GPGSV_SINGLE = b"$GPGSV,1,1,11,03,03,111,00,04,15,270,00,06,01,010,00,,,,*4b"
GPGSV_EMPTY_MIDDLE = b"$GPGSV,1,1,11,03,03,111,00,,,,,,,,,13,06,292,00*75"
GPGSV_SEQ = (
GPGSV_FIRST,
GPGSV_MIDDLE,
GPGSV_LAST,
) = b"""
$GPGSV,3,1,11,03,03,111,00,04,15,270,00,06,01,010,00,13,06,292,00*74
$GPGSV,3,2,11,14,25,170,00,16,57,208,39,18,67,296,40,19,40,246,00*74
$GPGSV,3,3,11,22,42,067,42,24,14,311,43,27,05,244,00,,,,*4D
""".split()
@implementer(ipositioning.INMEAReceiver)
class NMEATestReceiver:
"""
An NMEA receiver for testing.
Remembers the last sentence it has received.
"""
def __init__(self):
self.clear()
def clear(self):
"""
Forgets the received sentence (if any), by setting
C{self.receivedSentence} to L{None}.
"""
self.receivedSentence = None
def sentenceReceived(self, sentence):
self.receivedSentence = sentence
class CallbackTests(TestCase):
"""
Tests if the NMEA protocol correctly calls its sentence callback.
@ivar protocol: The NMEA protocol under test.
@type protocol: L{nmea.NMEAProtocol}
@ivar sentenceTypes: The set of sentence types of all sentences the test's
sentence callback function has been called with.
@type sentenceTypes: C{set}
"""
def setUp(self):
receiver = NMEATestReceiver()
self.protocol = nmea.NMEAProtocol(receiver, self._sentenceCallback)
self.sentenceTypes = set()
def _sentenceCallback(self, sentence):
"""
Remembers that a sentence of this type was fired.
"""
self.sentenceTypes.add(sentence.type)
def test_callbacksCalled(self):
"""
The correct callbacks fire, and that *only* those fire.
"""
sentencesByType = {
"GPGGA": [b"$GPGGA*56"],
"GPGLL": [b"$GPGLL*50"],
"GPGSA": [b"$GPGSA*42"],
"GPGSV": [b"$GPGSV*55"],
"GPHDT": [b"$GPHDT*4f"],
"GPRMC": [b"$GPRMC*4b"],
}
for sentenceType, sentences in sentencesByType.items():
for sentence in sentences:
self.protocol.lineReceived(sentence)
self.assertEqual(self.sentenceTypes, {sentenceType})
self.sentenceTypes.clear()
class BrokenSentenceCallbackTests(TestCase):
"""
Tests for broken NMEA sentence callbacks.
"""
def setUp(self):
receiver = NMEATestReceiver()
self.protocol = nmea.NMEAProtocol(receiver, self._sentenceCallback)
def _sentenceCallback(self, sentence):
"""
Raises C{AttributeError}.
"""
raise AttributeError("ERROR!!!")
def test_dontSwallowCallbackExceptions(self):
"""
An C{AttributeError} in the sentence callback of an C{NMEAProtocol}
doesn't get swallowed.
"""
lineReceived = self.protocol.lineReceived
self.assertRaises(AttributeError, lineReceived, b"$GPGGA*56")
class SplitTests(TestCase):
"""
Checks splitting of NMEA sentences.
"""
def test_withChecksum(self):
"""
An NMEA sentence with a checksum gets split correctly.
"""
splitSentence = nmea._split(b"$GPGGA,spam,eggs*00")
self.assertEqual(splitSentence, [b"GPGGA", b"spam", b"eggs"])
def test_noCheckum(self):
"""
An NMEA sentence without a checksum gets split correctly.
"""
splitSentence = nmea._split(b"$GPGGA,spam,eggs*")
self.assertEqual(splitSentence, [b"GPGGA", b"spam", b"eggs"])
class ChecksumTests(TestCase):
"""
NMEA sentence checksum verification tests.
"""
def test_valid(self):
"""
Sentences with valid checksums get validated.
"""
nmea._validateChecksum(GPGGA)
def test_missing(self):
"""
Sentences with missing checksums get validated.
"""
nmea._validateChecksum(GPGGA[:-2])
def test_invalid(self):
"""
Sentences with a bad checksum raise L{base.InvalidChecksum} when
attempting to validate them.
"""
validate = nmea._validateChecksum
bareSentence, checksum = GPGGA.split(b"*")
badChecksum = b"%d" % (int(checksum, 16) + 1,)
sentences = [bareSentence + b"*" + badChecksum]
for s in sentences:
self.assertRaises(base.InvalidChecksum, validate, s)
class NMEAReceiverSetup:
"""
A mixin for tests that need an NMEA receiver (and a protocol attached to
it).
@ivar receiver: An NMEA receiver that remembers the last sentence.
@type receiver: L{NMEATestReceiver}
@ivar protocol: An NMEA protocol attached to the receiver.
@type protocol: L{twisted.positioning.nmea.NMEAProtocol}
"""
def setUp(self):
"""
Sets up an NMEA receiver.
"""
self.receiver = NMEATestReceiver()
self.protocol = nmea.NMEAProtocol(self.receiver)
class GSVSequenceTests(NMEAReceiverSetup, TestCase):
"""
Tests for the interpretation of GSV sequences.
"""
def test_firstSentence(self):
"""
The first sentence in a GSV sequence is correctly identified.
"""
self.protocol.lineReceived(GPGSV_FIRST)
sentence = self.receiver.receivedSentence
self.assertTrue(sentence._isFirstGSVSentence())
self.assertFalse(sentence._isLastGSVSentence())
def test_middleSentence(self):
"""
A sentence in the middle of a GSV sequence is correctly
identified (as being neither the last nor the first).
"""
self.protocol.lineReceived(GPGSV_MIDDLE)
sentence = self.receiver.receivedSentence
self.assertFalse(sentence._isFirstGSVSentence())
self.assertFalse(sentence._isLastGSVSentence())
def test_lastSentence(self):
"""
The last sentence in a GSV sequence is correctly identified.
"""
self.protocol.lineReceived(GPGSV_LAST)
sentence = self.receiver.receivedSentence
self.assertFalse(sentence._isFirstGSVSentence())
self.assertTrue(sentence._isLastGSVSentence())
class BogusSentenceTests(NMEAReceiverSetup, TestCase):
"""
Tests for verifying predictable failure for bogus NMEA sentences.
"""
def assertRaisesOnSentence(self, exceptionClass, sentence):
"""
Asserts that the protocol raises C{exceptionClass} when it receives
C{sentence}.
@param exceptionClass: The exception class expected to be raised.
@type exceptionClass: C{Exception} subclass
@param sentence: The (bogus) NMEA sentence.
@type sentence: C{str}
"""
self.assertRaises(exceptionClass, self.protocol.lineReceived, sentence)
def test_raiseOnUnknownSentenceType(self):
"""
Receiving a well-formed sentence of unknown type raises
C{ValueError}.
"""
self.assertRaisesOnSentence(ValueError, b"$GPBOGUS*5b")
def test_raiseOnMalformedSentences(self):
"""
Receiving a malformed sentence raises L{base.InvalidSentence}.
"""
self.assertRaisesOnSentence(base.InvalidSentence, "GPBOGUS")
class NMEASentenceTests(NMEAReceiverSetup, TestCase):
"""
Tests for L{nmea.NMEASentence} objects.
"""
def test_repr(self):
"""
The C{repr} of L{nmea.NMEASentence} objects is correct.
"""
sentencesWithExpectedRepr = [
(
GPGSA,
"<NMEASentence (GPGSA) {"
"dataMode: A, "
"fixType: 3, "
"horizontalDilutionOfPrecision: 1.0, "
"positionDilutionOfPrecision: 1.7, "
"usedSatellitePRN_0: 19, "
"usedSatellitePRN_1: 28, "
"usedSatellitePRN_2: 14, "
"usedSatellitePRN_3: 18, "
"usedSatellitePRN_4: 27, "
"usedSatellitePRN_5: 22, "
"usedSatellitePRN_6: 31, "
"usedSatellitePRN_7: 39, "
"verticalDilutionOfPrecision: 1.3"
"}>",
),
]
for sentence, expectedRepr in sentencesWithExpectedRepr:
self.protocol.lineReceived(sentence)
received = self.receiver.receivedSentence
self.assertEqual(repr(received), expectedRepr)
class ParsingTests(NMEAReceiverSetup, TestCase):
"""
Tests if raw NMEA sentences get parsed correctly.
This doesn't really involve any interpretation, just turning ugly raw NMEA
representations into objects that are more pleasant to work with.
"""
def _parserTest(self, sentence, expected):
"""
Passes a sentence to the protocol and gets the parsed sentence from
the receiver. Then verifies that the parsed sentence contains the
expected data.
"""
self.protocol.lineReceived(sentence)
received = self.receiver.receivedSentence
self.assertEqual(expected, received._sentenceData)
def test_fullRMC(self):
"""
A full RMC sentence is correctly parsed.
"""
expected = {
"type": "GPRMC",
"latitudeFloat": "4807.038",
"latitudeHemisphere": "N",
"longitudeFloat": "01131.000",
"longitudeHemisphere": "E",
"magneticVariation": "003.1",
"magneticVariationDirection": "W",
"speedInKnots": "022.4",
"timestamp": "123519",
"datestamp": "230394",
"trueHeading": "084.4",
"dataMode": "A",
}
self._parserTest(GPRMC, expected)
def test_fullGGA(self):
"""
A full GGA sentence is correctly parsed.
"""
expected = {
"type": "GPGGA",
"altitude": "545.4",
"altitudeUnits": "M",
"heightOfGeoidAboveWGS84": "46.9",
"heightOfGeoidAboveWGS84Units": "M",
"horizontalDilutionOfPrecision": "0.9",
"latitudeFloat": "4807.038",
"latitudeHemisphere": "N",
"longitudeFloat": "01131.000",
"longitudeHemisphere": "E",
"numberOfSatellitesSeen": "08",
"timestamp": "123519",
"fixQuality": "1",
}
self._parserTest(GPGGA, expected)
def test_fullGLL(self):
"""
A full GLL sentence is correctly parsed.
"""
expected = {
"type": "GPGLL",
"latitudeFloat": "4916.45",
"latitudeHemisphere": "N",
"longitudeFloat": "12311.12",
"longitudeHemisphere": "W",
"timestamp": "225444",
"dataMode": "A",
}
self._parserTest(GPGLL, expected)
def test_partialGLL(self):
"""
A partial GLL sentence is correctly parsed.
"""
expected = {
"type": "GPGLL",
"latitudeFloat": "3751.65",
"latitudeHemisphere": "S",
"longitudeFloat": "14507.36",
"longitudeHemisphere": "E",
}
self._parserTest(GPGLL_PARTIAL, expected)
def test_fullGSV(self):
"""
A full GSV sentence is correctly parsed.
"""
expected = {
"type": "GPGSV",
"GSVSentenceIndex": "1",
"numberOfGSVSentences": "3",
"numberOfSatellitesSeen": "11",
"azimuth_0": "111",
"azimuth_1": "270",
"azimuth_2": "010",
"azimuth_3": "292",
"elevation_0": "03",
"elevation_1": "15",
"elevation_2": "01",
"elevation_3": "06",
"satellitePRN_0": "03",
"satellitePRN_1": "04",
"satellitePRN_2": "06",
"satellitePRN_3": "13",
"signalToNoiseRatio_0": "00",
"signalToNoiseRatio_1": "00",
"signalToNoiseRatio_2": "00",
"signalToNoiseRatio_3": "00",
}
self._parserTest(GPGSV_FIRST, expected)
def test_partialGSV(self):
"""
A partial GSV sentence is correctly parsed.
"""
expected = {
"type": "GPGSV",
"GSVSentenceIndex": "3",
"numberOfGSVSentences": "3",
"numberOfSatellitesSeen": "11",
"azimuth_0": "067",
"azimuth_1": "311",
"azimuth_2": "244",
"elevation_0": "42",
"elevation_1": "14",
"elevation_2": "05",
"satellitePRN_0": "22",
"satellitePRN_1": "24",
"satellitePRN_2": "27",
"signalToNoiseRatio_0": "42",
"signalToNoiseRatio_1": "43",
"signalToNoiseRatio_2": "00",
}
self._parserTest(GPGSV_LAST, expected)
def test_fullHDT(self):
"""
A full HDT sentence is correctly parsed.
"""
expected = {
"type": "GPHDT",
"trueHeading": "038.005",
}
self._parserTest(GPHDT, expected)
def test_typicalGSA(self):
"""
A typical GSA sentence is correctly parsed.
"""
expected = {
"type": "GPGSA",
"dataMode": "A",
"fixType": "3",
"usedSatellitePRN_0": "19",
"usedSatellitePRN_1": "28",
"usedSatellitePRN_2": "14",
"usedSatellitePRN_3": "18",
"usedSatellitePRN_4": "27",
"usedSatellitePRN_5": "22",
"usedSatellitePRN_6": "31",
"usedSatellitePRN_7": "39",
"positionDilutionOfPrecision": "1.7",
"horizontalDilutionOfPrecision": "1.0",
"verticalDilutionOfPrecision": "1.3",
}
self._parserTest(GPGSA, expected)
class FixUnitsTests(TestCase):
"""
Tests for the generic unit fixing method, L{nmea.NMEAAdapter._fixUnits}.
@ivar adapter: The NMEA adapter.
@type adapter: L{nmea.NMEAAdapter}
"""
def setUp(self):
self.adapter = nmea.NMEAAdapter(base.BasePositioningReceiver())
def test_noValueKey(self):
"""
Tests that when no C{valueKey} is provided, C{unitKey} is used, minus
C{"Units"} at the end.
"""
class FakeSentence:
"""
A fake sentence that just has a "foo" attribute.
"""
def __init__(self):
self.foo = 1
self.adapter.currentSentence = FakeSentence()
self.adapter._fixUnits(unitKey="fooUnits", unit="N")
self.assertNotEqual(self.adapter._sentenceData["foo"], 1)
def test_unitKeyButNoUnit(self):
"""
Tests that if a unit key is provided but the unit isn't, the unit is
automatically determined from the unit key.
"""
class FakeSentence:
"""
A fake sentence that just has "foo" and "fooUnits" attributes.
"""
def __init__(self):
self.foo = 1
self.fooUnits = "N"
self.adapter.currentSentence = FakeSentence()
self.adapter._fixUnits(unitKey="fooUnits")
self.assertNotEqual(self.adapter._sentenceData["foo"], 1)
def test_noValueKeyAndNoUnitKey(self):
"""
Tests that when a unit is specified but neither C{valueKey} nor
C{unitKey} is provided, C{ValueError} is raised.
"""
self.assertRaises(ValueError, self.adapter._fixUnits, unit="K")
class FixerTestMixin:
"""
Mixin for tests for the fixers on L{nmea.NMEAAdapter} that adapt
from NMEA-specific notations to generic Python objects.
@ivar adapter: The NMEA adapter.
@type adapter: L{nmea.NMEAAdapter}
"""
def setUp(self):
self.adapter = nmea.NMEAAdapter(base.BasePositioningReceiver())
def _fixerTest(self, sentenceData, expected=None, exceptionClass=None):
"""
A generic adapter fixer test.
Creates a sentence from the C{sentenceData} and sends that to the
adapter. If C{exceptionClass} is not passed, this is assumed to work,
and C{expected} is compared with the adapter's internal state.
Otherwise, passing the sentence to the adapter is checked to raise
C{exceptionClass}.
@param sentenceData: Raw sentence content.
@type sentenceData: C{dict} mapping C{str} to C{str}
@param expected: The expected state of the adapter.
@type expected: C{dict} or L{None}
@param exceptionClass: The exception to be raised by the adapter.
@type exceptionClass: subclass of C{Exception}
"""
sentence = nmea.NMEASentence(sentenceData)
def receiveSentence():
self.adapter.sentenceReceived(sentence)
if exceptionClass is None:
receiveSentence()
self.assertEqual(self.adapter._state, expected)
else:
self.assertRaises(exceptionClass, receiveSentence)
self.adapter.clear()
class TimestampFixerTests(FixerTestMixin, TestCase):
"""
Tests conversion from NMEA timestamps to C{datetime.time} objects.
"""
def test_simple(self):
"""
A simple timestamp is converted correctly.
"""
data = {"timestamp": "123456"} # 12:34:56Z
expected = {"_time": datetime.time(12, 34, 56)}
self._fixerTest(data, expected)
def test_broken(self):
"""
A broken timestamp raises C{ValueError}.
"""
badTimestamps = "993456", "129956", "123499"
for t in badTimestamps:
self._fixerTest({"timestamp": t}, exceptionClass=ValueError)
class DatestampFixerTests(FixerTestMixin, TestCase):
def test_defaultYearThreshold(self):
"""
The default year threshold is 1980.
"""
self.assertEqual(self.adapter.yearThreshold, 1980)
def test_beforeThreshold(self):
"""
Dates before the threshold are interpreted as being in the century
after the threshold. (Since the threshold is the earliest possible
date.)
"""
datestring, date = "010115", datetime.date(2015, 1, 1)
self._fixerTest({"datestamp": datestring}, {"_date": date})
def test_afterThreshold(self):
"""
Dates after the threshold are interpreted as being in the same century
as the threshold.
"""
datestring, date = "010195", datetime.date(1995, 1, 1)
self._fixerTest({"datestamp": datestring}, {"_date": date})
def test_invalidMonth(self):
"""
A datestring with an invalid month (> 12) raises C{ValueError}.
"""
self._fixerTest({"datestamp": "011301"}, exceptionClass=ValueError)
def test_invalidDay(self):
"""
A datestring with an invalid day (more days than there are in that
month) raises C{ValueError}.
"""
self._fixerTest({"datestamp": "320101"}, exceptionClass=ValueError)
self._fixerTest({"datestamp": "300201"}, exceptionClass=ValueError)
def _nmeaFloat(degrees, minutes):
"""
Builds an NMEA float representation for a given angle in degrees and
decimal minutes.
@param degrees: The integer degrees for this angle.
@type degrees: C{int}
@param minutes: The decimal minutes value for this angle.
@type minutes: C{float}
@return: The NMEA float representation for this angle.
@rtype: C{str}
"""
return "%i%0.3f" % (degrees, minutes)
def _coordinateSign(hemisphere):
"""
Return the sign of a coordinate.
This is C{1} if the coordinate is in the northern or eastern hemispheres,
C{-1} otherwise.
@param hemisphere: NMEA shorthand for the hemisphere. One of "NESW".
@type hemisphere: C{str}
@return: The sign of the coordinate value.
@rtype: C{int}
"""
return 1 if hemisphere in "NE" else -1
def _coordinateType(hemisphere):
"""
Return the type of a coordinate.
This is L{Angles.LATITUDE} if the coordinate is in the northern or
southern hemispheres, L{Angles.LONGITUDE} otherwise.
@param hemisphere: NMEA shorthand for the hemisphere. One of "NESW".
@type hemisphere: C{str}
@return: The type of the coordinate (L{Angles.LATITUDE} or
L{Angles.LONGITUDE})
"""
return Angles.LATITUDE if hemisphere in "NS" else Angles.LONGITUDE
class CoordinateFixerTests(FixerTestMixin, TestCase):
"""
Tests turning NMEA coordinate notations into something more pleasant.
"""
def test_north(self):
"""
NMEA coordinate representations in the northern hemisphere
convert correctly.
"""
sentenceData = {"latitudeFloat": "1030.000", "latitudeHemisphere": "N"}
state = {"latitude": base.Coordinate(10.5, Angles.LATITUDE)}
self._fixerTest(sentenceData, state)
def test_south(self):
"""
NMEA coordinate representations in the southern hemisphere
convert correctly.
"""
sentenceData = {"latitudeFloat": "1030.000", "latitudeHemisphere": "S"}
state = {"latitude": base.Coordinate(-10.5, Angles.LATITUDE)}
self._fixerTest(sentenceData, state)
def test_east(self):
"""
NMEA coordinate representations in the eastern hemisphere
convert correctly.
"""
sentenceData = {"longitudeFloat": "1030.000", "longitudeHemisphere": "E"}
state = {"longitude": base.Coordinate(10.5, Angles.LONGITUDE)}
self._fixerTest(sentenceData, state)
def test_west(self):
"""
NMEA coordinate representations in the western hemisphere
convert correctly.
"""
sentenceData = {"longitudeFloat": "1030.000", "longitudeHemisphere": "W"}
state = {"longitude": base.Coordinate(-10.5, Angles.LONGITUDE)}
self._fixerTest(sentenceData, state)
def test_badHemisphere(self):
"""
NMEA coordinate representations for nonexistent hemispheres
raise C{ValueError} when you attempt to parse them.
"""
sentenceData = {"longitudeHemisphere": "Q"}
self._fixerTest(sentenceData, exceptionClass=ValueError)
def test_badHemisphereSign(self):
"""
NMEA coordinate repesentation parsing fails predictably
when you pass nonexistent coordinate types (not latitude or
longitude).
"""
getSign = lambda: self.adapter._getHemisphereSign("BOGUS_VALUE")
self.assertRaises(ValueError, getSign)
class AltitudeFixerTests(FixerTestMixin, TestCase):
"""
Tests that NMEA representations of altitudes are correctly converted.
"""
def test_fixAltitude(self):
"""
The NMEA representation of an altitude (above mean sea level)
is correctly converted.
"""
key, value = "altitude", "545.4"
altitude = base.Altitude(float(value))
self._fixerTest({key: value}, {key: altitude})
def test_heightOfGeoidAboveWGS84(self):
"""
The NMEA representation of an altitude of the geoid (above the
WGS84 reference level) is correctly converted.
"""
key, value = "heightOfGeoidAboveWGS84", "46.9"
altitude = base.Altitude(float(value))
self._fixerTest({key: value}, {key: altitude})
class SpeedFixerTests(FixerTestMixin, TestCase):
"""
Tests that NMEA representations of speeds are correctly converted.
"""
def test_speedInKnots(self):
"""
Speeds reported in knots correctly get converted to meters per
second.
"""
key, value, targetKey = "speedInKnots", "10", "speed"
speed = base.Speed(float(value) * base.MPS_PER_KNOT)
self._fixerTest({key: value}, {targetKey: speed})
class VariationFixerTests(FixerTestMixin, TestCase):
"""
Tests if the absolute values of magnetic variations on the heading
and their sign get combined correctly, and if that value gets
combined with a heading correctly.
"""
def test_west(self):
"""
Tests westward (negative) magnetic variation.
"""
variation, direction = "1.34", "W"
heading = base.Heading.fromFloats(variationValue=-1 * float(variation))
sentenceData = {
"magneticVariation": variation,
"magneticVariationDirection": direction,
}
self._fixerTest(sentenceData, {"heading": heading})
def test_east(self):
"""
Tests eastward (positive) magnetic variation.
"""
variation, direction = "1.34", "E"
heading = base.Heading.fromFloats(variationValue=float(variation))
sentenceData = {
"magneticVariation": variation,
"magneticVariationDirection": direction,
}
self._fixerTest(sentenceData, {"heading": heading})
def test_withHeading(self):
"""
Variation values get combined with headings correctly.
"""
trueHeading, variation, direction = "123.12", "1.34", "E"
sentenceData = {
"trueHeading": trueHeading,
"magneticVariation": variation,
"magneticVariationDirection": direction,
}
heading = base.Heading.fromFloats(
float(trueHeading), variationValue=float(variation)
)
self._fixerTest(sentenceData, {"heading": heading})
class PositionErrorFixerTests(FixerTestMixin, TestCase):
"""
Position errors in NMEA are passed as dilutions of precision (DOP). This
is a measure relative to some specified value of the GPS device as its
"reference" precision. Unfortunately, there are very few ways of figuring
this out from just the device (sans manual).
There are two basic DOP values: vertical and horizontal. HDOP tells you
how precise your location is on the face of the earth (pretending it's
flat, at least locally). VDOP tells you how precise your altitude is
known. PDOP (position DOP) is a dependent value defined as the Euclidean
norm of those two, and gives you a more generic "goodness of fix" value.
"""
def test_simple(self):
self._fixerTest(
{"horizontalDilutionOfPrecision": "11"},
{"positionError": base.PositionError(hdop=11.0)},
)
def test_mixing(self):
pdop, hdop, vdop = "1", "1", "1"
positionError = base.PositionError(
pdop=float(pdop), hdop=float(hdop), vdop=float(vdop)
)
sentenceData = {
"positionDilutionOfPrecision": pdop,
"horizontalDilutionOfPrecision": hdop,
"verticalDilutionOfPrecision": vdop,
}
self._fixerTest(sentenceData, {"positionError": positionError})
class ValidFixTests(FixerTestMixin, TestCase):
"""
Tests that data reported from a valid fix is used.
"""
def test_GGA(self):
"""
GGA data with a valid fix is used.
"""
sentenceData = {
"type": "GPGGA",
"altitude": "545.4",
"fixQuality": nmea.GPGGAFixQualities.GPS_FIX,
}
expectedState = {"altitude": base.Altitude(545.4)}
self._fixerTest(sentenceData, expectedState)
def test_GLL(self):
"""
GLL data with a valid data mode is used.
"""
sentenceData = {
"type": "GPGLL",
"altitude": "545.4",
"dataMode": nmea.GPGLLGPRMCFixQualities.ACTIVE,
}
expectedState = {"altitude": base.Altitude(545.4)}
self._fixerTest(sentenceData, expectedState)
class InvalidFixTests(FixerTestMixin, TestCase):
"""
Tests that data being reported from a bad or incomplete fix isn't
used. Although the specification dictates that GPSes shouldn't produce
NMEA sentences with real-looking values for altitude or position in them
unless they have at least some semblance of a GPS fix, this is widely
ignored.
"""
def _invalidFixTest(self, sentenceData):
"""
Sentences with an invalid fix or data mode result in empty
state (ie, the data isn't used).
"""
self._fixerTest(sentenceData, {})
def test_GGA(self):
"""
GGA sentence data is unused when there is no fix.
"""
sentenceData = {
"type": "GPGGA",
"altitude": "545.4",
"fixQuality": nmea.GPGGAFixQualities.INVALID_FIX,
}
self._invalidFixTest(sentenceData)
def test_GLL(self):
"""
GLL sentence data is unused when the data is flagged as void.
"""
sentenceData = {
"type": "GPGLL",
"altitude": "545.4",
"dataMode": nmea.GPGLLGPRMCFixQualities.VOID,
}
self._invalidFixTest(sentenceData)
def test_badGSADataMode(self):
"""
GSA sentence data is not used when there is no GPS fix, but
the data mode claims the data is "active". Some GPSes do
this, unfortunately, and that means you shouldn't use the
data.
"""
sentenceData = {
"type": "GPGSA",
"altitude": "545.4",
"dataMode": nmea.GPGLLGPRMCFixQualities.ACTIVE,
"fixType": nmea.GPGSAFixTypes.GSA_NO_FIX,
}
self._invalidFixTest(sentenceData)
def test_badGSAFixType(self):
"""
GSA sentence data is not used when the fix claims to be valid
(albeit only 2D), but the data mode says the data is void.
Some GPSes do this, unfortunately, and that means you
shouldn't use the data.
"""
sentenceData = {
"type": "GPGSA",
"altitude": "545.4",
"dataMode": nmea.GPGLLGPRMCFixQualities.VOID,
"fixType": nmea.GPGSAFixTypes.GSA_2D_FIX,
}
self._invalidFixTest(sentenceData)
def test_badGSADataModeAndFixType(self):
"""
GSA sentence data is not use when neither the fix nor the data
mode is any good.
"""
sentenceData = {
"type": "GPGSA",
"altitude": "545.4",
"dataMode": nmea.GPGLLGPRMCFixQualities.VOID,
"fixType": nmea.GPGSAFixTypes.GSA_NO_FIX,
}
self._invalidFixTest(sentenceData)
class NMEAReceiverTests(TestCase):
"""
Tests for the NMEA receiver.
"""
def setUp(self):
self.receiver = MockPositioningReceiver()
self.adapter = nmea.NMEAAdapter(self.receiver)
self.protocol = nmea.NMEAProtocol(self.adapter)
def test_onlyFireWhenCurrentSentenceHasNewInformation(self):
"""
If the current sentence does not contain any new fields for a
particular callback, that callback is not called; even if all
necessary information is still in the state from one or more
previous messages.
"""
self.protocol.lineReceived(GPGGA)
gpggaCallbacks = {
"positionReceived",
"positionErrorReceived",
"altitudeReceived",
}
self.assertEqual(set(self.receiver.called.keys()), gpggaCallbacks)
self.receiver.clear()
self.assertNotEqual(self.adapter._state, {})
# GPHDT contains heading information but not position,
# altitude or anything like that; but that information is
# still in the state.
self.protocol.lineReceived(GPHDT)
gphdtCallbacks = {"headingReceived"}
self.assertEqual(set(self.receiver.called.keys()), gphdtCallbacks)
def _receiverTest(self, sentences, expectedFired=(), extraTest=None):
"""
A generic test for NMEA receiver behavior.
@param sentences: The sequence of sentences to simulate receiving.
@type sentences: iterable of C{str}
@param expectedFired: The names of the callbacks expected to fire.
@type expectedFired: iterable of C{str}
@param extraTest: An optional extra test hook.
@type extraTest: nullary callable
"""
for sentence in sentences:
self.protocol.lineReceived(sentence)
actuallyFired = self.receiver.called.keys()
self.assertEqual(set(actuallyFired), set(expectedFired))
if extraTest is not None:
extraTest()
self.receiver.clear()
self.adapter.clear()
def test_positionErrorUpdateAcrossStates(self):
"""
The positioning error is updated across multiple states.
"""
sentences = [GPGSA] + GPGSV_SEQ
callbacksFired = ["positionErrorReceived", "beaconInformationReceived"]
def _getIdentifiers(beacons):
return sorted(map(attrgetter("identifier"), beacons))
def checkBeaconInformation():
beaconInformation = self.adapter._state["beaconInformation"]
seenIdentifiers = _getIdentifiers(beaconInformation.seenBeacons)
expected = [3, 4, 6, 13, 14, 16, 18, 19, 22, 24, 27]
self.assertEqual(seenIdentifiers, expected)
usedIdentifiers = _getIdentifiers(beaconInformation.usedBeacons)
# These are not actually all the PRNs in the sample GPGSA:
# only the ones also reported by the GPGSV sequence. This
# is just because the sample data doesn't come from the
# same reporting cycle of a GPS device.
self.assertEqual(usedIdentifiers, [14, 18, 19, 22, 27])
self._receiverTest(sentences, callbacksFired, checkBeaconInformation)
def test_emptyMiddleGSV(self):
"""
A GSV sentence with empty entries in any position does not mean that
entries in subsequent positions of the same GSV sentence are ignored.
"""
sentences = [GPGSV_EMPTY_MIDDLE]
callbacksFired = ["beaconInformationReceived"]
def checkBeaconInformation():
beaconInformation = self.adapter._state["beaconInformation"]
seenBeacons = beaconInformation.seenBeacons
self.assertEqual(len(seenBeacons), 2)
self.assertIn(13, [b.identifier for b in seenBeacons])
self._receiverTest(sentences, callbacksFired, checkBeaconInformation)
def test_GGASentences(self):
"""
A sequence of GGA sentences fires C{positionReceived},
C{positionErrorReceived} and C{altitudeReceived}.
"""
sentences = [GPGGA]
callbacksFired = [
"positionReceived",
"positionErrorReceived",
"altitudeReceived",
]
self._receiverTest(sentences, callbacksFired)
def test_GGAWithDateInState(self):
"""
When receiving a GPGGA sentence and a date was already in the
state, the new time (from the GPGGA sentence) is combined with
that date.
"""
self.adapter._state["_date"] = datetime.date(2014, 1, 1)
sentences = [GPGGA]
callbacksFired = [
"positionReceived",
"positionErrorReceived",
"altitudeReceived",
"timeReceived",
]
self._receiverTest(sentences, callbacksFired)
def test_RMCSentences(self):
"""
A sequence of RMC sentences fires C{positionReceived},
C{speedReceived}, C{headingReceived} and C{timeReceived}.
"""
sentences = [GPRMC]
callbacksFired = [
"headingReceived",
"speedReceived",
"positionReceived",
"timeReceived",
]
self._receiverTest(sentences, callbacksFired)
def test_GSVSentences(self):
"""
A complete sequence of GSV sentences fires
C{beaconInformationReceived}.
"""
sentences = [GPGSV_FIRST, GPGSV_MIDDLE, GPGSV_LAST]
callbacksFired = ["beaconInformationReceived"]
def checkPartialInformation():
self.assertNotIn("_partialBeaconInformation", self.adapter._state)
self._receiverTest(sentences, callbacksFired, checkPartialInformation)
def test_emptyMiddleEntriesGSVSequence(self):
"""
A complete sequence of GSV sentences with empty entries in the
middle still fires C{beaconInformationReceived}.
"""
sentences = [GPGSV_EMPTY_MIDDLE]
self._receiverTest(sentences, ["beaconInformationReceived"])
def test_incompleteGSVSequence(self):
"""
An incomplete sequence of GSV sentences does not fire any callbacks.
"""
sentences = [GPGSV_FIRST]
self._receiverTest(sentences)
def test_singleSentenceGSVSequence(self):
"""
The parser does not fail badly when the sequence consists of
only one sentence (but is otherwise complete).
"""
sentences = [GPGSV_SINGLE]
self._receiverTest(sentences, ["beaconInformationReceived"])
def test_GLLSentences(self):
"""
GLL sentences fire C{positionReceived}.
"""
sentences = [GPGLL_PARTIAL, GPGLL]
self._receiverTest(sentences, ["positionReceived"])
def test_HDTSentences(self):
"""
HDT sentences fire C{headingReceived}.
"""
sentences = [GPHDT]
self._receiverTest(sentences, ["headingReceived"])
def test_mixedSentences(self):
"""
A mix of sentences fires the correct callbacks.
"""
sentences = [GPRMC, GPGGA]
callbacksFired = [
"altitudeReceived",
"speedReceived",
"positionReceived",
"positionErrorReceived",
"timeReceived",
"headingReceived",
]
def checkTime():
expectedDateTime = datetime.datetime(1994, 3, 23, 12, 35, 19)
self.assertEqual(self.adapter._state["time"], expectedDateTime)
self._receiverTest(sentences, callbacksFired, checkTime)
def test_lotsOfMixedSentences(self):
"""
Sends an entire gamut of sentences and verifies the
appropriate callbacks fire. These are more than you'd expect
from your average consumer GPS device. They have most of the
important information, including beacon information and
visibility.
"""
sentences = [GPGSA] + GPGSV_SEQ + [GPRMC, GPGGA, GPGLL]
callbacksFired = [
"headingReceived",
"beaconInformationReceived",
"speedReceived",
"positionReceived",
"timeReceived",
"altitudeReceived",
"positionErrorReceived",
]
self._receiverTest(sentences, callbacksFired)
|
sphairas/sphairas-desktop
|
sphairas-admin-libs/admin-container/src/org/thespheres/betula/admincontainer/action/StudentAction.java
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.thespheres.betula.admincontainer.action;
import java.util.HashMap;
import java.util.Map;
import org.thespheres.betula.StudentId;
import org.thespheres.betula.assess.Grade;
import org.thespheres.betula.document.DocumentId;
import org.thespheres.betula.document.Timestamp;
import org.thespheres.betula.services.scheme.spi.Term;
import org.thespheres.betula.xmlimport.ImportTargetsItem;
/**
*
* @author boris.heithecker
*/
class StudentAction {
private final Map<DocumentId, Grade[]> updates = new HashMap<>();
private final StudentId student;
private final ImportTargetsItem item;
StudentAction(StudentId student, final ImportTargetsItem iti) {
this.item = iti;
this.student = student;
}
StudentId getStudent() {
return student;
}
void addUpdate(DocumentId d, Term term, Grade delete, Grade update) {
final Timestamp gradeTime = new Timestamp(term.getBegin());
item.submit(student, term.getScheduledItemId(), update, gradeTime);
updates.put(d, new Grade[]{delete, update});
}
}
|
moutainhigh/taotao-cloud-parent
|
taotao-cloud-uc/taotao-cloud-uc-api/src/main/java/com/taotao/cloud/uc/api/dto/role/RoleDTO.java
|
package com.taotao.cloud.uc.api.dto.role;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import java.io.Serializable;
/**
* 角色DTO
*
* @author dengtao
* @date 2020/5/14 10:44
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(value = "角色DTO")
public class RoleDTO implements Serializable {
private static final long serialVersionUID = -1972549738577159538L;
@NotBlank(message = "角色名称不能超过为空")
@Length(max = 20, message = "角色名称不能超过20个字符")
@ApiModelProperty(value = "角色名称")
private String name;
@NotBlank(message = "角色标识不能超过为空")
@Length(max = 20, message = "角色标识不能超过20个字符")
@ApiModelProperty(value = "角色标识")
@Pattern(regexp = "^[0-9a-zA-Z_]+$", message = "角色标识格式错误:最多20字符,只能包含字母或者下划线")
private String code;
@ApiModelProperty(value = "备注")
private String remark;
}
|
lipengliang0705/epeins
|
src/app/pages/resoures-groups/add/add.controller.js
|
<filename>src/app/pages/resoures-groups/add/add.controller.js
(function () {
'use strict';
/**
* @ 新增仪表盘
* Author:Veiss Date:2019/6/21
* */
var app = angular.module('LoginsightUiApp.page.resoures-groups');
app.controller("resouresGroupsAddController", resouresGroupsAddController);
resouresGroupsAddController.$inject = ['$uibModalInstance', 'newDashboardService', 'toastr', '$rootScope', 'EventRule', 'mainTreeData','ResouresGroupsService'];
function resouresGroupsAddController($uibModalInstance, newDashboardService, toastr, $rootScope, EventRule, mainTreeData,ResouresGroupsService) {
var vm = this;
vm.data = {
name: '',
desc:'',
info:[]
}
vm.appList = [];
vm.method = {
submit: submit,
cancel: cancel
}
vm.mainTreeData = [];
vm.mainTreeBasicConfig = {
core: {
multiple: true,
check_callback: true,
worker: true
},
'types': {
'folder': {
'icon': 'ion-ios-folder'
},
'default': {
'icon': 'ion-document-text'
}
},
'plugins': ['checkbox', 'types'],
'version': 1
};
vm.basicConfig = {
core: {
multiple: false,
check_callback: function (chk, obj, par, pos, more) {
if (chk == 'move_node') {
// console.log(obj, par);
// //移动节点只能平级移动 一级只能移动到一级,二级只能移动到二级,没有三级
if ((obj.original.parent == '#' && par.parent == null) || (obj.original.parent != '#' && par.parent == '#')) {
return true;
}
return false;
} else {
return true;
}
},
worker: true
},
'types': {
'folder': {
'icon': 'ion-ios-folder'
},
'default': {
'icon': 'ion-document-text'
}
},
'plugins': ['types', 'contextmenu', 'dnd'], //'sort'
// 'sort': function(a,b){
// console.log(a,b, this.get_node(a).original, this.get_node(b).original);
// if (this.get_node(b).original.position < this.get_node(a).original.position) {
// return 1;
// }
// return -1;
// },
'version': 1
};
loadAll();
function loadAll() {
getCategoryList(mainTreeData);
}
vm.selectnodeCB = function (nodes, selected, event) {
selected.event.preventDefault();
var menuData = angular.copy(vm.mainTreeData);
if (selected.node.parent == '#') {//选中的为父节点
//先添加父节点,再根据父节点获取子节点添加
var parentflag = _.find(vm.data.info, {'id': selected.node.id});
if (!parentflag) {
vm.data.info.push(selected.node.original);
}
;
var items = _.filter(menuData, {'parent': selected.node.id});
_.forEach(items, function (item) {
var node = _.find(vm.data.info, {'id': item.id});
if (!node) {
vm.data.info.push(item);
}
});
} else { //选中的为子节点
//先查看是否已添加此子节点的父节点,先添加父节点再添加子节点
var parentflag = _.find(vm.data.info, {'id': selected.node.parent});
if (!parentflag) {
var parent = _.find(menuData, {'id': selected.node.parent});
if (parent) {
vm.data.info.push(parent);
}
;
}
vm.data.info.push(selected.node.original);
}
}
vm.deselectnodeCB = function (nodes, selected, event) {
if (selected.node.parent == '#') {
_.remove(vm.data.info, {'id': selected.node.id});
_.remove(vm.data.info, {'parent': selected.node.id});
} else {
_.remove(vm.data.info, {'id': selected.node.id});
var items = _.filter(vm.data.info, {'parent': selected.node.parent});
if (items.length == 0) {
_.remove(vm.data.info, {'id': selected.node.parent});
}
}
}
//获取业务列表
function getCategoryList(mainTreeData) {
var appList = mainTreeData.map(function (d, index) {
var item = d;
return {
id: index+'',
text: item.title,
title: item.description,
"state": {"opened": true},
"level": 0,
"parent": "#",
"icon": "",
"__uiNodeId": 1,
name: item.name
}
})
vm.mainTreeData = _.uniqBy(appList, 'name');
};
function submit() {
var params = {
name: vm.data.name,
description: vm.data.desc,
treeData: vm.data.info,
}
vm.data.info=JSON.stringify(vm.data.info);
console.log(vm.data);
ResouresGroupsService.save(vm.data,function (data) {
console.log(data);
toastr.success('用户分组新建成功!','成功提示');
$rootScope.$broadcast('resouresGroupsAddSuccess', vm.data);
// 关闭
cancel();
},function (err) {
toastr.error(err.data.message,'错误提示');
});
}
function cancel() {
$uibModalInstance.dismiss('cancel');
}
}
})();
|
muaddibco/hrrs
|
serializer-base64/src/main/java/com/vlkan/hrrs/serializer/base64/guava/GuavaBase64Decoder.java
|
package com.vlkan.hrrs.serializer.base64.guava;
import com.vlkan.hrrs.serializer.base64.Base64Decoder;
import static com.google.common.base.Preconditions.checkNotNull;
public class GuavaBase64Decoder implements Base64Decoder {
private static final GuavaBase64Decoder INSTANCE = new GuavaBase64Decoder();
private GuavaBase64Decoder() {
// Do nothing.
}
public static GuavaBase64Decoder getInstance() {
return INSTANCE;
}
@Override
public byte[] decode(String encodedBytes) {
checkNotNull(encodedBytes, "encodedBytes");
return GuavaBase64.BASE_ENCODING.decode(encodedBytes);
}
}
|
coinninjadev/dropbit-android
|
app/src/main/java/com/coinninja/coinkeeper/ui/dropbit/me/verified/DisabledDropbitMeDialog.java
|
package com.coinninja.coinkeeper.ui.dropbit.me.verified;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.widget.Button;
import androidx.appcompat.content.res.AppCompatResources;
import com.coinninja.coinkeeper.R;
import com.coinninja.coinkeeper.ui.dropbit.me.DropBitMeDialog;
import com.coinninja.coinkeeper.util.DropbitIntents;
import com.coinninja.coinkeeper.util.android.LocalBroadCastUtil;
import com.coinninja.coinkeeper.util.android.ServiceWorkUtil;
import com.coinninja.coinkeeper.util.android.activity.ActivityNavigationUtil;
import javax.inject.Inject;
public class DisabledDropbitMeDialog extends DropBitMeDialog {
@Inject
LocalBroadCastUtil localBroadCastUtil;
@Inject
ServiceWorkUtil serviceWorkUtil;
@Inject
ActivityNavigationUtil activityNavigationUtil;
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DropbitIntents.ACTION_DROPBIT_ME_ACCOUNT_ENABLED.equals(intent.getAction())) {
renderAccount();
}
}
};
IntentFilter intentFilter = new IntentFilter(DropbitIntents.ACTION_DROPBIT_ME_ACCOUNT_ENABLED);
public static DropBitMeDialog newInstance() {
return new DisabledDropbitMeDialog();
}
@Override
public void onResume() {
super.onResume();
localBroadCastUtil.registerReceiver(receiver, intentFilter);
}
@Override
protected int getContentViewLayoutId() {
return R.layout.dialog_disabled_dropbit_me;
}
@Override
protected void configurePrimaryCallToAction(Button button) {
Drawable drawable = AppCompatResources.getDrawable(getContext(), R.drawable.cta_button);
button.setBackground(drawable);
button.setText(R.string.dropbit_me_enable_account_button_label);
button.setOnClickListener(v -> serviceWorkUtil.enableDropBitMe());
}
@Override
protected void configureSecondaryButton(Button button) {
button.setText(getString(R.string.dropbit_me_learn_more));
button.setOnClickListener(v -> activityNavigationUtil.learnMoreAboutDropbitMe(getActivity()));
}
@Override
public void onPause() {
super.onPause();
localBroadCastUtil.unregisterReceiver(receiver);
}
}
|
Dachshund77/FlaskEwatson
|
model/SensorModel.py
|
from model.PressureModel import PressureModel
from model.HumidityModel import HumidityModel
from model.CO2Model import CO2Model
from model.TemperatureModel import TemperatureModel
import logging
logging.getLogger(__name__)
class SensorModel():
def __init__(self,pressures,humidities,co2,temperatures):
self.pressures = pressures
self.humidities = humidities
self.co2 = co2
self.temperatures = temperatures
# Used if container is filled with arrays
def to_json_array(self):
# Init
pressureJsonArray = []
humidityJsonArray = []
co2JsonArray = []
temperatureJsonArray = []
# Converting to json
for press in self.pressures:
pressureJsonArray.append(press.to_json())
for hum in self.humidities:
humidityJsonArray.append(hum.to_json())
for c in self.co2:
co2JsonArray.append(c.to_json())
for temp in self.temperatures:
temperatureJsonArray.append(temp.to_json())
# Return data
data = {
'type': 'All sensor readings',
'attributes': {
'pressures': pressureJsonArray,
'humidities': humidityJsonArray,
'co2': co2JsonArray,
'temperatures': temperatureJsonArray
}
}
return data
# Used if variables are only one value
def to_single_json(self):
# Init
pressureJson = self.pressures.to_json()
humidityJson = self.humidities.to_json()
co2Json = self.co2.to_json()
temperatureJson = self.temperatures.to_json()
# Return data
logging.debug("Formatting SensorModel to json")
data = {
'type': 'All sensor readings',
'attributes': {
'pressure': pressureJson,
'humidity': humidityJson,
'co2': co2Json,
'temperature': temperatureJson
}
}
return data
def to_average_json(self):
logging.debug("Formatting SensorModel to average json")
json = {
'type': 'All sensor average',
'attributes': {
'pressure': PressureModel.average_json(self.pressures),
'humidity': HumidityModel.average_json(self.humidities),
'co2': CO2Model.average_json(self.co2),
'temperature': TemperatureModel.average_json(self.temperatures)
}
}
return json
# The nuclear option, sending an entire database via json
@staticmethod
def get_all():
# init
foundPressure = []
foundHumidities = []
foundCo2 = []
foundTemperatures = []
# Execution (4 connection, could be more effecient but query time is hardly an issue)
foundPressure = PressureModel.get_all()
foundHumidities = HumidityModel.get_all()
foundCo2 = CO2Model.get_all()
foundTemperatures = TemperatureModel.get_all()
# Build object
returnObj = SensorModel(foundPressure, foundHumidities, foundCo2, foundTemperatures)
# Clean and return
return returnObj
@staticmethod
def get_by_search(start,end):
# init
foundPressure = []
foundHumidities = []
foundCo2 = []
foundTemperatures = []
# Execution (4 connection, could be more effecient but query time is hardly an issue)
foundPressure = PressureModel.get_by_search(start,end)
foundHumidities = HumidityModel.get_by_search(start,end)
foundCo2 = CO2Model.get_by_search(start,end)
foundTemperatures = TemperatureModel.get_by_search(start,end)
# Build object
returnObj = SensorModel(foundPressure, foundHumidities, foundCo2, foundTemperatures)
# Clean and return
return returnObj
def get_oldest():
# init
foundPressure = None
foundHumidities = None
foundCo2 = None
foundTemperatures = None
# Execution (4 connection, could be more effecient but query time is hardly an issue)
foundPressure = PressureModel.get_oldest()
foundHumidities = HumidityModel.get_oldest()
foundCo2 = CO2Model.get_oldest()
foundTemperatures = TemperatureModel.get_oldest()
# Build object
returnObj = SensorModel(foundPressure, foundHumidities, foundCo2, foundTemperatures)
# Clean and return
return returnObj
def get_newest():
# init
foundPressure = None
foundHumidities = None
foundCo2 = None
foundTemperatures = None
# Execution (4 connection, could be more effecient but query time is hardly an issue)
foundPressure = PressureModel.get_newest()
foundHumidities = HumidityModel.get_newest()
foundCo2 = CO2Model.get_newest()
foundTemperatures = TemperatureModel.get_newest()
# Build object
returnObj = SensorModel(foundPressure, foundHumidities, foundCo2, foundTemperatures)
# Clean and return
return returnObj
def get_average():
# init
foundPressure = None
foundHumidities = None
foundCo2 = None
foundTemperatures = None
# Execution (4 connection, could be more effecient but query time is hardly an issue)
foundPressure = PressureModel.get_average()
foundHumidities = HumidityModel.get_average()
foundCo2 = CO2Model.get_average()
foundTemperatures = TemperatureModel.get_average()
# Build object
returnObj = SensorModel(foundPressure, foundHumidities, foundCo2, foundTemperatures)
# Clean and return
return returnObj
def get_average_by_range(start,end):
# init
foundPressure = None
foundHumidities = None
foundCo2 = None
foundTemperatures = None
# Execution (4 connection, could be more effecient but query time is hardly an issue)
foundPressure = PressureModel.get_average_by_range(start,end)
foundHumidities = HumidityModel.get_average_by_range(start,end)
foundCo2 = CO2Model.get_average_by_range(start,end)
foundTemperatures = TemperatureModel.get_average_by_range(start,end)
# Build object
returnObj = SensorModel(foundPressure, foundHumidities, foundCo2, foundTemperatures)
# Clean and return
return returnObj
@staticmethod
def delete_all():
# Init
returnValue = True
# Execution
PressureModel.delete_all()
HumidityModel.delete_all()
CO2Model.delete_all()
TemperatureModel.delete_all()
# Clean and return
return returnValue
@staticmethod
def delete_by_range(start,end):
# Init
returnValue = True
# Execution
PressureModel.delte_by_range(start,end)
HumidityModel.delte_by_range(start,end)
CO2Model.delete_by_range(start,end)
TemperatureModel.delete_by_range(start,end)
# Clean and return
return returnValue
|
ScalablyTyped/SlinkyTyped
|
m/maxim_mazurok__gapi_dot_client_dot_docs/src/main/scala/typingsSlinky/maximMazurokGapiClientDocs/gapi/client/docs/InlineObjectElement.scala
|
<filename>m/maxim_mazurok__gapi_dot_client_dot_docs/src/main/scala/typingsSlinky/maximMazurokGapiClientDocs/gapi/client/docs/InlineObjectElement.scala<gh_stars>10-100
package typingsSlinky.maximMazurokGapiClientDocs.gapi.client.docs
import org.scalablytyped.runtime.TopLevel
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait InlineObjectElement extends StObject {
/** The ID of the InlineObject this element contains. */
var inlineObjectId: js.UndefOr[String] = js.native
/** The suggested deletion IDs. If empty, then there are no suggested deletions of this content. */
var suggestedDeletionIds: js.UndefOr[js.Array[String]] = js.native
/** The suggested insertion IDs. An InlineObjectElement may have multiple insertion IDs if it is a nested suggested change. If empty, then this is not a suggested insertion. */
var suggestedInsertionIds: js.UndefOr[js.Array[String]] = js.native
/** The suggested text style changes to this InlineObject, keyed by suggestion ID. */
var suggestedTextStyleChanges: js.UndefOr[
/* import warning: importer.ImportType#apply c Unsupported type mapping:
{[ P in string ]: @maxim_mazurok/gapi.client.docs.gapi.client.docs.SuggestedTextStyle}
*/ typingsSlinky.maximMazurokGapiClientDocs.maximMazurokGapiClientDocsStrings.InlineObjectElement with TopLevel[js.Any]
] = js.native
/**
* The text style of this InlineObjectElement. Similar to text content, like text runs and footnote references, the text style of an inline object element can affect content layout as
* well as the styling of text inserted adjacent to it.
*/
var textStyle: js.UndefOr[TextStyle] = js.native
}
object InlineObjectElement {
@scala.inline
def apply(): InlineObjectElement = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[InlineObjectElement]
}
@scala.inline
implicit class InlineObjectElementMutableBuilder[Self <: InlineObjectElement] (val x: Self) extends AnyVal {
@scala.inline
def setInlineObjectId(value: String): Self = StObject.set(x, "inlineObjectId", value.asInstanceOf[js.Any])
@scala.inline
def setInlineObjectIdUndefined: Self = StObject.set(x, "inlineObjectId", js.undefined)
@scala.inline
def setSuggestedDeletionIds(value: js.Array[String]): Self = StObject.set(x, "suggestedDeletionIds", value.asInstanceOf[js.Any])
@scala.inline
def setSuggestedDeletionIdsUndefined: Self = StObject.set(x, "suggestedDeletionIds", js.undefined)
@scala.inline
def setSuggestedDeletionIdsVarargs(value: String*): Self = StObject.set(x, "suggestedDeletionIds", js.Array(value :_*))
@scala.inline
def setSuggestedInsertionIds(value: js.Array[String]): Self = StObject.set(x, "suggestedInsertionIds", value.asInstanceOf[js.Any])
@scala.inline
def setSuggestedInsertionIdsUndefined: Self = StObject.set(x, "suggestedInsertionIds", js.undefined)
@scala.inline
def setSuggestedInsertionIdsVarargs(value: String*): Self = StObject.set(x, "suggestedInsertionIds", js.Array(value :_*))
@scala.inline
def setSuggestedTextStyleChanges(
value: /* import warning: importer.ImportType#apply c Unsupported type mapping:
{[ P in string ]: @maxim_mazurok/gapi.client.docs.gapi.client.docs.SuggestedTextStyle}
*/ typingsSlinky.maximMazurokGapiClientDocs.maximMazurokGapiClientDocsStrings.InlineObjectElement with TopLevel[js.Any]
): Self = StObject.set(x, "suggestedTextStyleChanges", value.asInstanceOf[js.Any])
@scala.inline
def setSuggestedTextStyleChangesUndefined: Self = StObject.set(x, "suggestedTextStyleChanges", js.undefined)
@scala.inline
def setTextStyle(value: TextStyle): Self = StObject.set(x, "textStyle", value.asInstanceOf[js.Any])
@scala.inline
def setTextStyleUndefined: Self = StObject.set(x, "textStyle", js.undefined)
}
}
|
dobroslav-atanasov/JavaScript-Fundamentals
|
09.ArraysAndMatrices-Lab/04.Find-Element/solution.js
|
function solve() {
let searchedElement = Number(document.getElementById('num').value);
let array = JSON.parse(document.getElementById('arr').value);
let result = [];
findElement(searchedElement, array);
document.getElementById('result').textContent = result.join(',');
function findElement(searchedElement, array) {
for (let item of array) {
if (item.includes(searchedElement)) {
result.push(`true -> ${item.indexOf(searchedElement)}`);
} else {
result.push(`false -> ${item.indexOf(searchedElement)}`)
}
}
}
}
|
edawson/parliament2
|
resources/home/dnanexus/root/include/TCernLib.h
|
// @(#)root/table:$Id$
// Author: <NAME>(<EMAIL>) 25/09/99
/*************************************************************************
* Copyright (C) 1995-2000, <NAME> and <NAME>. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_TCernLib
#define ROOT_TCernLib
#include "Rtypes.h"
#include <string.h>
// https://cern-tex.web.cern.ch/cern-tex/shortwrupsdir/f110/top.html
///////////////////////////////////////////////////////////////////////////////////////
// //
// The routines of MXPACK compute the product of two matrices or the product of //
// their transposed matrices and may add or subtract to the resultant matrix //
// a third one, add or subtract one matrix from another, or transfer a matrix, //
// its negative, or a multiple of it, transpose a given matrix, build up a unit //
// matrix, multiply a matrix by a diagonal (from left or from right) and may //
// add the result to another matrix, add to square matrix the multiple of a diagonal //
// matrix, compute the products X=ABA' (A' denotes the transpose of A) and X=A'BA. //
// It is assumed that matrices are <B>row-wise without gaps</B>, contrary to the //
// Fortran convention. //
// //
///////////////////////////////////////////////////////////////////////////////////////
class TArrayD;
class TCL {
public:
virtual ~TCL() { }
static int *ucopy(const int *a, int *b, int n);
static float *ucopy(const float *a, float *b, int n);
static double *ucopy(const float *a, double *b, int n);
static float *ucopy(const double *a, float *b, int n);
static double *ucopy(const double *a, double *b, int n);
static void **ucopy(const void **a, void **b, int n);
static float *vzero(float *a, int n2);
static double *vzero(double *a, int n2);
static void **vzero(void **a, int n2);
static float *vadd(const float *b, const float *c, float *a, int n);
static double *vadd(const double *b, const double *c, double *a, int n);
static float *vadd(const float *b, const double *c, float *a, int n);
static double *vadd(const double *b, const float *c,double *a, int n);
static float vdot(const float *b, const float *a, int n);
static double vdot(const double *b, const double *a, int n);
static float *vsub(const float *a, const float *b, float *x, int n);
static double *vsub(const double *a, const double *b, double *x, int n);
static float *vsub(const float *b, const double *c, float *a, int n);
static double *vsub(const double *b, const float *c, double *a, int n);
static float *vcopyn(const float *a, float *x, int n);
static double *vcopyn(const double *a, double *x, int n);
static float *vscale(const float *a, float scale, float *b, int n);
static double *vscale(const double *a, double scale, double *b, int n);
static float *vlinco(const float *a, float fa, const float *b, float fb,float *x, int n);
static double *vlinco(const double *a, double fa, const double *b, double fb,double *x, int n);
static float *vmatl(const float *g, const float *c, float *x, int n=3,int m=3);
static double *vmatl(const double *g, const double *c, double *x, int n=3,int m=3);
static float *vmatr(const float *c, const float *g, float *x, int n=3,int m=3);
static double *vmatr(const double *c, const double *g, double *x, int n=3,int m=3);
static float *mxmad_0_(int n, const float *a, const float *b, float *c, int i, int j, int k);
static float *mxmad( const float *a, const float *b, float *c, int i, int j, int k);
static float *mxmad1(const float *a, const float *b, float *c, int i, int j, int k);
static float *mxmad2(const float *a, const float *b, float *c, int i, int j, int k);
static float *mxmad3(const float *a, const float *b, float *c, int i, int j, int k);
static float *mxmpy( const float *a, const float *b, float *c, int i, int j, int k);
static float *mxmpy1(const float *a, const float *b, float *c, int i, int j, int k);
static float *mxmpy2(const float *a, const float *b, float *c, int i, int j, int k);
static float *mxmpy3(const float *a, const float *b, float *c, int i, int j, int k);
static float *mxmub( const float *a, const float *b, float *c, int i, int j, int k);
static float *mxmub1(const float *a, const float *b, float *c, int i, int j, int k);
static float *mxmub2(const float *a, const float *b, float *c, int i, int j, int k);
static float *mxmub3(const float *a, const float *b, float *c, int i, int j, int k);
static float *mxmlrt_0_(int n__, const float *a, const float *b, float *c, int ni,int nj);
static float *mxmlrt(const float *a, const float *b, float *c, int ni, int nj);
static float *mxmltr(const float *a, const float *b, float *c, int ni, int nj);
static float *mxtrp(const float *a, float *b, int i, int j);
static double *mxmad_0_(int n, const double *a, const double *b, double *c, int i, int j, int k);
static double *mxmad (const double *a, const double *b, double *c, int i, int j, int k);
static double *mxmad1(const double *a, const double *b, double *c, int i, int j, int k);
static double *mxmad2(const double *a, const double *b, double *c, int i, int j, int k);
static double *mxmad3(const double *a, const double *b, double *c, int i, int j, int k);
static double *mxmpy (const double *a, const double *b, double *c, int i, int j, int k);
static double *mxmpy1(const double *a, const double *b, double *c, int i, int j, int k);
static double *mxmpy2(const double *a, const double *b, double *c, int i, int j, int k);
static double *mxmpy3(const double *a, const double *b, double *c, int i, int j, int k);
static double *mxmub (const double *a, const double *b, double *c, int i, int j, int k);
static double *mxmub1(const double *a, const double *b, double *c, int i, int j, int k);
static double *mxmub2(const double *a, const double *b, double *c, int i, int j, int k);
static double *mxmub3(const double *a, const double *b, double *c, int i, int j, int k);
static double *mxmlrt_0_(int n__, const double *a, const double *b, double *c, int ni,int nj);
static double *mxmlrt(const double *a, const double *b, double *c, int ni, int nj);
static double *mxmltr(const double *a, const double *b, double *c, int ni, int nj);
static double *mxtrp(const double *a, double *b, int i, int j);
// * TR pack
static float *traat(const float *a, float *s, int m, int n);
static float *tral(const float *a, const float *u, float *b, int m, int n);
static float *tralt(const float *a, const float *u, float *b, int m, int n);
static float *tras(const float *a, const float *s, float *b, int m, int n);
static float *trasat(const float *a, const float *s, float *r, int m, int n);
static float *trasat(const double *a, const float *s, float *r, int m, int n);
static float *trata(const float *a, float *r, int m, int n);
static float *trats(const float *a, const float *s, float *b, int m, int n);
static float *tratsa(const float *a, const float *s, float *r, int m, int n);
static float *trchlu(const float *a, float *b, int n);
static float *trchul(const float *a, float *b, int n);
static float *trinv(const float *t, float *s, int n);
static float *trla(const float *u, const float *a, float *b, int m, int n);
static float *trlta(const float *u, const float *a, float *b, int m, int n);
static float *trpck(const float *s, float *u, int n);
static float *trqsq(const float *q, const float *s, float *r, int m);
static float *trsa(const float *s, const float *a, float *b, int m, int n);
static float *trsinv(const float *g, float *gi, int n);
static float *trsmlu(const float *u, float *s, int n);
static float *trsmul(const float *g, float *gi, int n);
static float *trupck(const float *u, float *s, int m);
static float *trsat(const float *s, const float *a, float *b, int m, int n);
// <NAME> addition:
static float *trsequ(float *smx, int m=3, float *b=0, int n=1);
// --- double version
static double *traat (const double *a, double *s, int m, int n);
static double *tral (const double *a, const double *u, double *b, int m, int n);
static double *tralt (const double *a, const double *u, double *b, int m, int n);
static double *tras (const double *a, const double *s, double *b, int m, int n);
static double *trasat(const double *a, const double *s, double *r, int m, int n);
static double *trata (const double *a, double *r, int m, int n);
static double *trats (const double *a, const double *s, double *b, int m, int n);
static double *tratsa(const double *a, const double *s, double *r, int m, int n);
static double *trchlu(const double *a, double *b, int n);
static double *trchul(const double *a, double *b, int n);
static double *trinv (const double *t, double *s, int n);
static double *trla (const double *u, const double *a, double *b, int m, int n);
static double *trlta (const double *u, const double *a, double *b, int m, int n);
static double *trpck (const double *s, double *u, int n);
static double *trqsq (const double *q, const double *s, double *r, int m);
static double *trsa (const double *s, const double *a, double *b, int m, int n);
static double *trsinv(const double *g, double *gi, int n);
static double *trsmlu(const double *u, double *s, int n);
static double *trsmul(const double *g, double *gi, int n);
static double *trupck(const double *u, double *s, int m);
static double *trsat (const double *s, const double *a, double *b, int m, int n);
// <NAME> addition:
static double *trsequ(double *smx, int m=3, double *b=0, int n=1);
ClassDef(TCL,0) //C++ replacement for CERNLIB matrix / triangle matrix packages: F110 and F112
};
//___________________________________________________________________________
inline float *TCL::mxmad(const float *a, const float *b, float *c, int i, int j, int k)
{
return mxmad_0_(0, a, b, c, i, j, k); }
//___________________________________________________________________________
inline float *TCL::mxmad1(const float *a, const float *q, float *c, int i, int j, int k)
{
return mxmad_0_(1, a, q, c, i, j, k); }
//___________________________________________________________________________
inline float *TCL::mxmad2(const float *p, const float *b, float *c, int i, int j, int k)
{
return mxmad_0_(2, p, b, c, i, j, k); }
//___________________________________________________________________________
inline float *TCL::mxmad3(const float *p, const float *q, float *c, int i, int j, int k)
{
return mxmad_0_(3, p, q, c, i, j, k); }
//___________________________________________________________________________
inline float *TCL::mxmpy(const float *a, const float *b, float *c, int i, int j, int k)
{
return mxmad_0_(4, a, b, c, i, j, k); }
//___________________________________________________________________________
inline float *TCL::mxmpy1(const float *a, const float *q, float *c, int i, int j, int k)
{
return mxmad_0_(5, a, q, c, i, j, k); }
//___________________________________________________________________________
inline float *TCL::mxmpy2(const float *p, const float *b, float *c, int i, int j, int k)
{
return mxmad_0_(6, p, b, c, i, j, k); }
//___________________________________________________________________________
inline float *TCL::mxmpy3(const float *p, const float *q, float *c, int i, int j, int k)
{
return mxmad_0_(7, p, q, c, i, j, k); }
//___________________________________________________________________________
inline float *TCL::mxmub(const float *a, const float *b, float *c, int i, int j, int k)
{
return mxmad_0_(8, a, b, c, i, j, k); }
//___________________________________________________________________________
inline float *TCL::mxmub1(const float *a, const float *q, float *c, int i, int j, int k)
{
return mxmad_0_(9, a, q, c, i, j, k); }
//___________________________________________________________________________
inline float *TCL::mxmub2(const float *p, const float *b, float *c, int i, int j, int k)
{
return mxmad_0_(10, p, b, c, i, j, k); }
//___________________________________________________________________________
inline float *TCL::mxmub3(const float *p, const float *q, float *c, int i, int j, int k)
{
return mxmad_0_(11, p, q, c, i, j, k); }
//___________________________________________________________________________
inline float *TCL::mxmlrt(const float *a, const float *b, float *x, int ni, int nj)
{
return mxmlrt_0_(0, a, b, x, ni, nj); }
//___________________________________________________________________________
inline float *TCL::mxmltr(const float *a, const float *b, float *x, int ni, int nj)
{
return mxmlrt_0_(1, a, b, x, ni, nj); }
//-- double version --
//___________________________________________________________________________
inline double *TCL::mxmad(const double *a, const double *b, double *c, int i, int j, int k)
{
return mxmad_0_(0, a, b, c, i, j, k); }
//___________________________________________________________________________
inline double *TCL:: mxmad1(const double *a, const double *b, double *c, int i, int j, int k)
{
return mxmad_0_(1, a, b, c, i, j, k); }
//___________________________________________________________________________
inline double *TCL::mxmad2(const double *a, const double *b, double *c, int i, int j, int k)
{
return mxmad_0_(2, a, b, c, i, j, k); }
//___________________________________________________________________________
inline double *TCL::mxmad3(const double *a, const double *b, double *c, int i, int j, int k)
{
return mxmad_0_(3, a, b, c, i, j, k); }
//___________________________________________________________________________
inline double *TCL::mxmpy(const double *a, const double *b, double *c, int i, int j, int k)
{
return mxmad_0_(4, a, b, c, i, j, k); }
//___________________________________________________________________________
inline double *TCL::mxmpy1(const double *a, const double *b, double *c, int i, int j, int k)
{
return mxmad_0_(5, a, b, c, i, j, k); }
//___________________________________________________________________________
inline double *TCL::mxmpy2(const double *a, const double *b, double *c, int i, int j, int k)
{
return mxmad_0_(6, a, b, c, i, j, k); }
//___________________________________________________________________________
inline double *TCL::mxmpy3(const double *a, const double *b, double *c, int i, int j, int k)
{
return mxmad_0_(7, a, b, c, i, j, k); }
//___________________________________________________________________________
inline double *TCL::mxmub(const double *a, const double *b, double *c, int i, int j, int k)
{
return mxmad_0_(8, a, b, c, i, j, k); }
//___________________________________________________________________________
inline double *TCL::mxmub1(const double *a, const double *b, double *c, int i, int j, int k)
{
return mxmad_0_(9, a, b, c, i, j, k); }
//___________________________________________________________________________
inline double *TCL::mxmub2(const double *a, const double *b, double *c, int i, int j, int k)
{
return mxmad_0_(10, a, b, c, i, j, k); }
//___________________________________________________________________________
inline double *TCL::mxmub3(const double *a, const double *b, double *c, int i, int j, int k)
{
return mxmad_0_(11, a, b, c, i, j, k); }
//___________________________________________________________________________
inline double *TCL::mxmlrt(const double *a, const double *b, double *c, int ni, int nj)
{
return mxmlrt_0_(0, a, b, c, ni, nj); }
//___________________________________________________________________________
inline double *TCL::mxmltr(const double *a, const double *b, double *c, int ni, int nj)
{
return mxmlrt_0_(1, a, b, c, ni, nj); }
// ----
//________________________________________________________
inline int *TCL::ucopy(const int *b, int *a, int n)
{
//to be documented
if (n <= 0) return 0;
memcpy(a,b,n*sizeof(int));
return a;
}
//________________________________________________________
inline float *TCL::ucopy(const float *b, float *a, int n)
{
//to be documented
if (n <= 0) return 0;
memcpy(a,b,n*sizeof(float));
return a;
}
//________________________________________________________
inline float *TCL::ucopy(const double *b, float *a, int n)
{
//to be documented
if (n <= 0) return 0;
for (int i=0;i<n;i++,a++,b++) *a = float(*b);
return a;
}
//________________________________________________________
inline double *TCL::ucopy(const float *b, double *a, int n)
{
//to be documented
if (n <= 0) return 0;
for (int i=0;i<n;i++,a++,b++) *a = double(*b);
return a;
}
//________________________________________________________
inline double *TCL::ucopy(const double *b, double *a, int n)
{
//to be documented
if (n <= 0) return 0;
memcpy(a,b,n*sizeof(double));
return a;
}
//________________________________________________________
inline void **TCL::ucopy(const void **b, void **a, int n)
{
//to be documented
if (n <= 0) return 0;
memcpy(a,b,n*sizeof(void *));
return a;
}
//________________________________________________________
inline float *TCL::vadd(const float *b, const float *c, float *a, int n)
{
//to be documented
if (n <= 0) return 0;
for (int i=0;i<n;i++) a[i] = b[i] + c[i];
return a;
}
//________________________________________________________
inline double *TCL::vadd(const double *b, const double *c, double *a, int n)
{
//to be documented
if (n <= 0) return 0;
for (int i=0;i<n;i++) a[i] = b[i] + c[i];
return a;
}
//________________________________________________________
inline float *TCL::vadd(const float *b, const double *c, float *a, int n)
{
//to be documented
if (n <= 0) return 0;
for (int i=0;i<n;i++) a[i] = b[i] + c[i];
return a;
}
//________________________________________________________
inline double *TCL::vadd(const double *b, const float *c, double *a, int n)
{
//to be documented
if (n <= 0) return 0;
for (int i=0;i<n;i++) a[i] = b[i] + c[i];
return a;
}
//________________________________________________________
inline float TCL::vdot(const float *b, const float *a, int n)
{
//to be documented
float x=0;
if (n>0)
for (int i=0;i<n;i++,a++,b++) x += (*a) * (*b);
return x;
}
//________________________________________________________
inline double TCL::vdot(const double *b, const double *a, int n)
{
//to be documented
double x=0;
if (n>0)
for (int i=0;i<n;i++,a++,b++) x += (*a) * (*b);
return x;
}
//________________________________________________________
inline float *TCL::vsub(const float *a, const float *b, float *x, int n)
{
//to be documented
if (n <= 0) return 0;
for (int i=0;i<n;i++) x[i] = a[i]-b[i];
return x;
}
//________________________________________________________
inline double *TCL::vsub(const double *a, const double *b, double *x, int n)
{
//to be documented
if (n <= 0) return 0;
for (int i=0;i<n;i++) x[i] = a[i]-b[i];
return x;
}
//________________________________________________________
inline float *TCL::vsub(const float *b, const double *c, float *a, int n)
{
//to be documented
if (n <= 0) return 0;
for (int i=0;i<n;i++) a[i] = b[i] - c[i];
return a;
}
//________________________________________________________
inline double *TCL::vsub(const double *b, const float *c, double *a, int n)
{
//to be documented
if (n <= 0) return 0;
for (int i=0;i<n;i++) a[i] = b[i] - c[i];
return a;
}
//________________________________________________________
inline float *TCL::vcopyn(const float *a, float *x, int n)
{
//to be documented
if (n <= 0) return 0;
for (int i=0;i<n;i++) x[i] = -a[i];
return x;
}
//________________________________________________________
inline double *TCL::vcopyn(const double *a, double *x, int n)
{
//to be documented
if (n <= 0) return 0;
for (int i=0;i<n;i++) x[i] = -a[i];
return x;
}
//________________________________________________________
inline float *TCL::vzero(float *a, int n1)
{
//to be documented
if (n1 <= 0) return 0;
return (float *)memset(a,0,n1*sizeof(float));
}
//________________________________________________________
inline double *TCL::vzero(double *a, int n1)
{
//to be documented
if (n1 <= 0) return 0;
return (double *)memset(a,0,n1*sizeof(double));
}
//________________________________________________________
inline void **TCL::vzero(void **a, int n1)
{
//to be documented
if (n1 <= 0) return 0;
return (void **)memset(a,0,n1*sizeof(void *));
}
//________________________________________________________
inline float *TCL::vscale(const float *a, float scale, float *b, int n)
{
//to be documented
for (int i=0;i<n;i++) b[i]=scale*a[i];
return b;
}
//________________________________________________________
inline double *TCL::vscale(const double *a, double scale, double *b, int n)
{
//to be documented
for (int i=0;i<n;i++) b[i]=scale*a[i];
return b;
}
//________________________________________________________
inline float *TCL::vlinco(const float *a, float fa, const float *b, float fb, float *x, int n)
{
//to be documented
for (int i=0;i<n;i++){x[i]=a[i]*fa+b[i]*fb;};
return x;
}
//________________________________________________________
inline double *TCL::vlinco(const double *a, double fa, const double *b, double fb,double *x, int n)
{
//to be documented
for (int i=0;i<n;i++) x[i]=a[i]*fa+b[i]*fb;
return x;
}
//_____________________________________________________________________________
inline float *TCL::vmatl(const float *G, const float *c, float *x, int n,int m)
{
// x = G*c
for (int i=0; i<n; i++) {
double sum = 0;
for (int j=0; j<m; j++) sum += G[j + m*i]*c[j];
x[i] = sum;
}
return x;
}
//_____________________________________________________________________________
inline double *TCL::vmatl(const double *G, const double *c, double *x, int n,int m)
{
// x = G*c
for (int i=0; i<n; i++) {
double sum = 0;
for (int j=0; j<m; j++) sum += G[j + m*i]*c[j];
x[i] = sum;
}
return x;
}
//_____________________________________________________________________________
inline float *TCL::vmatr(const float *c, const float *G, float *x, int n,int m)
{
// x = c*G
for (int j=0; j<m; j++) {
double sum = 0;
for (int i=0; i<n; i++) sum += G[j + n*i]*c[i];
x[j] = sum;
}
return x;
}
//_____________________________________________________________________________
inline double *TCL::vmatr(const double *c, const double *G, double *x, int n,int m)
{
// x = c*G
for (int j=0; j<m; j++) {
double sum = 0;
for (int i=0; i<n; i++) sum += G[j + n*i]*c[i];
x[j] = sum;
}
return x;
}
#endif
|
mobius-software-ltd/iotbroker.cloud-ios-client
|
iotbroker.cloud-client/Classes/IBStringUtils.h
|
//
// IBStringUtils.h
// iotbroker.cloud-client
//
// Created by MacOS on 05.10.2018.
// Copyright © 2018 MobiusSoftware. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface IBStringUtils : NSObject
+ (NSString *)toHexString:(NSInteger)number;
@end
NS_ASSUME_NONNULL_END
|
BlackLight/platypush
|
platypush/config/__init__.py
|
import datetime
import importlib
import inspect
import logging
import os
import pathlib
import pkgutil
import re
import socket
import sys
from typing import Optional
import yaml
from platypush.utils import get_hash, is_functional_procedure, is_functional_hook, is_functional_cron
""" Config singleton instance """
_default_config_instance = None
class Config(object):
"""
Configuration base class
Usage:
- Initialize config from one of the default paths:
Config.init()
- Initialize config from a custom path
Config.init(config_file_path)
- Get a value
Config.get('foo')
"""
"""
Default config file locations:
- $HOME/.config/platypush/config.yaml
- /etc/platypush/config.yaml
"""
_cfgfile_locations = [
os.path.join(os.path.expanduser('~'), '.config', 'platypush', 'config.yaml'),
os.path.join(os.sep, 'etc', 'platypush', 'config.yaml'),
]
_default_constants = {
'today': datetime.date.today,
'now': datetime.datetime.now,
}
_workdir_location = os.path.join(os.path.expanduser('~'), '.local', 'share', 'platypush')
_included_files = set()
def __init__(self, cfgfile=None):
"""
Constructor. Always use the class as a singleton (i.e. through
Config.init), you won't probably need to call the constructor directly
Params:
cfgfile -- Config file path (default: retrieve the first
available location in _cfgfile_locations)
"""
if cfgfile is None:
cfgfile = self._get_default_cfgfile()
if cfgfile is None:
raise RuntimeError('No config file specified and nothing found in {}'
.format(self._cfgfile_locations))
self._cfgfile = os.path.abspath(os.path.expanduser(cfgfile))
self._config = self._read_config_file(self._cfgfile)
if 'token' in self._config:
self._config['token'] = self._config['token']
self._config['token_hash'] = get_hash(self._config['token'])
if 'workdir' not in self._config:
self._config['workdir'] = self._workdir_location
os.makedirs(self._config['workdir'], exist_ok=True)
if 'scripts_dir' not in self._config:
self._config['scripts_dir'] = os.path.join(os.path.dirname(cfgfile), 'scripts')
os.makedirs(self._config['scripts_dir'], mode=0o755, exist_ok=True)
if 'dashboards_dir' not in self._config:
self._config['dashboards_dir'] = os.path.join(os.path.dirname(cfgfile), 'dashboards')
os.makedirs(self._config['dashboards_dir'], mode=0o755, exist_ok=True)
init_py = os.path.join(self._config['scripts_dir'], '__init__.py')
if not os.path.isfile(init_py):
with open(init_py, 'w') as f:
f.write('# Auto-generated __init__.py - do not remove\n')
# Include scripts_dir parent in sys.path so members can be imported in scripts
# through the `scripts` package
scripts_parent_dir = str(pathlib.Path(self._config['scripts_dir']).absolute().parent)
sys.path = [scripts_parent_dir] + sys.path
self._config['db'] = self._config.get('main.db', {
'engine': 'sqlite:///' + os.path.join(
os.path.expanduser('~'), '.local', 'share', 'platypush', 'main.db')
})
logging_config = {
'level': logging.INFO,
'stream': sys.stdout,
'format': '%(asctime)-15s|%(levelname)5s|%(name)s|%(message)s',
}
if 'logging' in self._config:
for (k, v) in self._config['logging'].items():
if k == 'filename':
logfile = os.path.expanduser(v)
logdir = os.path.dirname(logfile)
try:
os.makedirs(logdir, exist_ok=True)
except Exception as e:
print('Unable to create logs directory {}: {}'.format(
logdir, str(e)))
v = logfile
del logging_config['stream']
elif k == 'level':
try:
v = int(v)
except ValueError:
v = getattr(logging, v.upper())
logging_config[k] = v
self._config['logging'] = logging_config
if 'device_id' not in self._config:
self._config['device_id'] = socket.gethostname()
if 'environment' in self._config:
for k, v in self._config['environment'].items():
os.environ[k] = str(v)
self.backends = {}
self.plugins = {}
self.event_hooks = {}
self.procedures = {}
self.constants = {}
self.cronjobs = {}
self.dashboards = {}
self._plugin_manifests = {}
self._backend_manifests = {}
self._init_manifests()
self._init_constants()
self._load_scripts()
self._init_components()
self._init_dashboards(self._config['dashboards_dir'])
def _read_config_file(self, cfgfile):
cfgfile_dir = os.path.dirname(os.path.abspath(
os.path.expanduser(cfgfile)))
config = {}
with open(cfgfile, 'r') as fp:
file_config = yaml.safe_load(fp)
if not file_config:
return config
for section in file_config:
if section == 'include':
include_files = file_config[section] \
if isinstance(file_config[section], list) \
else [file_config[section]]
for include_file in include_files:
if not os.path.isabs(include_file):
include_file = os.path.join(cfgfile_dir, include_file)
self._included_files.add(include_file)
included_config = self._read_config_file(include_file)
for incl_section in included_config.keys():
config[incl_section] = included_config[incl_section]
elif section == 'scripts_dir':
assert isinstance(file_config[section], str)
config['scripts_dir'] = os.path.abspath(os.path.expanduser(file_config[section]))
elif 'disabled' not in file_config[section] \
or file_config[section]['disabled'] is False:
config[section] = file_config[section]
return config
def _load_module(self, modname: str, prefix: Optional[str] = None):
try:
module = importlib.import_module(modname)
except Exception as e:
print('Unhandled exception while importing module {}: {}'.format(modname, str(e)))
return
prefix = modname + '.' if prefix is None else prefix
self.procedures.update(**{
prefix + name: obj
for name, obj in inspect.getmembers(module)
if is_functional_procedure(obj)
})
self.event_hooks.update(**{
prefix + name: obj
for name, obj in inspect.getmembers(module)
if is_functional_hook(obj)
})
self.cronjobs.update(**{
prefix + name: obj
for name, obj in inspect.getmembers(module)
if is_functional_cron(obj)
})
def _load_scripts(self):
scripts_dir = self._config['scripts_dir']
sys_path = sys.path.copy()
sys.path = [scripts_dir] + sys.path
scripts_modname = os.path.basename(scripts_dir)
self._load_module(scripts_modname, prefix='')
for _, modname, _ in pkgutil.walk_packages(path=[scripts_dir], onerror=lambda x: None):
self._load_module(modname)
sys.path = sys_path
def _init_components(self):
for key in self._config.keys():
if key.startswith('backend.') and '.'.join(key.split('.')[1:]) in self._backend_manifests:
backend_name = '.'.join(key.split('.')[1:])
self.backends[backend_name] = self._config[key]
elif key.startswith('event.hook.'):
hook_name = '.'.join(key.split('.')[2:])
self.event_hooks[hook_name] = self._config[key]
elif key.startswith('cron.'):
cron_name = '.'.join(key.split('.')[1:])
self.cronjobs[cron_name] = self._config[key]
elif key.startswith('procedure.'):
tokens = key.split('.')
_async = True if len(tokens) > 2 and tokens[1] == 'async' else False
procedure_name = '.'.join(tokens[2:] if len(tokens) > 2 else tokens[1:])
args = []
m = re.match(r'^([^(]+)\(([^)]+)\)\s*', procedure_name)
if m:
procedure_name = m.group(1).strip()
args = [
arg.strip()
for arg in m.group(2).strip().split(',')
if arg.strip()
]
self.procedures[procedure_name] = {
'_async': _async,
'actions': self._config[key],
'args': args,
}
elif key in self._plugin_manifests:
self.plugins[key] = self._config[key]
def _init_manifests(self, base_dir: Optional[str] = None):
if not base_dir:
base_dir = os.path.abspath(os.path.join(__file__, '..', '..'))
plugins_dir = os.path.join(base_dir, 'plugins')
backends_dir = os.path.join(base_dir, 'backend')
self._init_manifests(plugins_dir)
self._init_manifests(backends_dir)
else:
manifests_map = self._plugin_manifests if base_dir.endswith('plugins') else self._backend_manifests
for mf in pathlib.Path(base_dir).rglob('manifest.yaml'):
with open(mf, 'r') as f:
manifest = yaml.safe_load(f)['manifest']
comp_name = '.'.join(manifest['package'].split('.')[2:])
manifests_map[comp_name] = manifest
def _init_constants(self):
if 'constants' in self._config:
self.constants = self._config['constants']
for (key, value) in self._default_constants.items():
self.constants[key] = value
@staticmethod
def get_dashboard(name: str, dashboards_dir: Optional[str] = None) -> Optional[str]:
global _default_config_instance
# noinspection PyProtectedMember,PyProtectedMember,PyUnresolvedReferences
dashboards_dir = dashboards_dir or _default_config_instance._config['dashboards_dir']
abspath = os.path.join(dashboards_dir, name + '.xml')
if not os.path.isfile(abspath):
return
with open(abspath, 'r') as fp:
return fp.read()
@classmethod
def get_dashboards(cls, dashboards_dir: Optional[str] = None) -> dict:
global _default_config_instance
dashboards = {}
# noinspection PyProtectedMember,PyProtectedMember,PyUnresolvedReferences
dashboards_dir = dashboards_dir or _default_config_instance._config['dashboards_dir']
for f in os.listdir(dashboards_dir):
abspath = os.path.join(dashboards_dir, f)
if not os.path.isfile(abspath) or not abspath.endswith('.xml'):
continue
name = f.split('.xml')[0]
dashboards[name] = cls.get_dashboard(name, dashboards_dir)
return dashboards
def _init_dashboards(self, dashboards_dir: str):
self.dashboards = self.get_dashboards(dashboards_dir)
@staticmethod
def get_backends():
global _default_config_instance
if _default_config_instance is None:
_default_config_instance = Config()
return _default_config_instance.backends
@staticmethod
def get_plugins():
global _default_config_instance
if _default_config_instance is None:
_default_config_instance = Config()
return _default_config_instance.plugins
@staticmethod
def get_event_hooks():
global _default_config_instance
if _default_config_instance is None:
_default_config_instance = Config()
return _default_config_instance.event_hooks
@staticmethod
def get_procedures():
global _default_config_instance
if _default_config_instance is None:
_default_config_instance = Config()
return _default_config_instance.procedures
@staticmethod
def get_constants():
global _default_config_instance
if _default_config_instance is None:
_default_config_instance = Config()
constants = {}
for name in _default_config_instance.constants.keys():
constants[name] = Config.get_constant(name)
return constants
@staticmethod
def get_constant(name):
global _default_config_instance
if _default_config_instance is None:
_default_config_instance = Config()
if name not in _default_config_instance.constants:
return None
value = _default_config_instance.constants[name]
return value() if callable(value) else value
@staticmethod
def get_cronjobs():
global _default_config_instance
if _default_config_instance is None:
_default_config_instance = Config()
return _default_config_instance.cronjobs
@classmethod
def _get_default_cfgfile(cls):
for location in cls._cfgfile_locations:
if os.path.isfile(location):
return location
@staticmethod
def init(cfgfile=None):
"""
Initializes the config object singleton
Params:
cfgfile -- path to the config file - default: _cfgfile_locations
"""
global _default_config_instance
_default_config_instance = Config(cfgfile)
@staticmethod
def get(key: Optional[str] = None):
"""
Get a config value or the whole configuration object.
:param key: Configuration entry to get (default: all entries).
"""
global _default_config_instance
if _default_config_instance is None:
_default_config_instance = Config()
if key:
return _default_config_instance._config.get(key)
return _default_config_instance._config
# vim:sw=4:ts=4:et:
|
huanxiongs/easyagent
|
internal/server/rpc/fake_server.go
|
<reponame>huanxiongs/easyagent
package rpc
import (
"easyagent/internal/proto"
"golang.org/x/net/context"
)
type fakeRpcServer struct{}
func (rpc *fakeRpcServer) RegisterSidecar(ctx context.Context, request *proto.RegisterRequest) (*proto.RegisterResponse, error) {
return &proto.RegisterResponse{}, nil
}
func (rpc *fakeRpcServer) ReadyForControl(request *proto.ControlRequest, stream proto.EasyAgentService_ReadyForControlServer) error {
return nil
}
func (rpc *fakeRpcServer) ReportEvent(ctx context.Context, event *proto.Event) (*proto.EmptyResponse, error) {
return &proto.EmptyResponse{}, nil
}
|
kelkka/RemoteVR
|
Server/src/Render/D3DShader.h
|
#pragma once
#include <d3d11.h>
struct D3DShader
{
public:
D3DShader();
~D3DShader();
static HRESULT CompileShader(const wchar_t* path, const char* type, ID3DBlob** shaderBlob);
ID3D11VertexShader* VS = nullptr;
ID3D11PixelShader* PS = nullptr;
ID3D11InputLayout* InputLayout = nullptr;
private:
};
|
angryLid/campus-mall
|
src/main/java/io/github/angrylid/mall/api/annotation/ClientController.java
|
package io.github.angrylid.mall.api.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@RestController
@RequestMapping
public @interface ClientController {
@AliasFor(annotation = RequestMapping.class)
String name() default "";
@AliasFor(annotation = RequestMapping.class)
String[] value() default {};
@AliasFor(annotation = RequestMapping.class)
String[] path() default {};
}
|
felixhamel/ift287_tp4
|
src/main/java/ligueBaseball/models/MatchModel.java
|
<gh_stars>0
package ligueBaseball.models;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
import ligueBaseball.entities.DatabaseEntity;
import ligueBaseball.entities.Match;
import ligueBaseball.entities.Official;
import ligueBaseball.exceptions.FailedToRetrieveMatchException;
import ligueBaseball.exceptions.FailedToRetrievePlayersOfTeamException;
import ligueBaseball.exceptions.NotInstanceOfClassException;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
@XmlRootElement
@JsonSerialize(include = Inclusion.NON_NULL)
public class MatchModel
{
private int id = 0;
private String date;
private String time;
private int localTeamScore = 0;
private int visitorTeamScore = 0;
private FieldModel field;
private TeamModel localTeam;
private TeamModel visitorTeam;
private List<OfficialModel> officials = new ArrayList<>();
public MatchModel() {
}
public MatchModel(Match match) throws FailedToRetrieveMatchException, FailedToRetrievePlayersOfTeamException {
this.createFromEntity(match);
}
public int getId()
{
return id;
}
public String getDate()
{
return date;
}
public void setDate(String date)
{
this.date = date;
}
public String getTime()
{
return time;
}
public void setTime(String t)
{
this.time = t;
}
public int getLocalTeamScore()
{
return localTeamScore;
}
public void setLocalTeamScore(int score)
{
this.localTeamScore = score;
}
public int getVisitorTeamScore()
{
return visitorTeamScore;
}
public void setVisitorTeamScore(int score)
{
this.visitorTeamScore = score;
}
public TeamModel getLocalTeam()
{
return localTeam;
}
public TeamModel getVisitorTeam()
{
return visitorTeam;
}
public FieldModel getField()
{
return field;
}
public List<OfficialModel> getOfficials()
{
return officials;
}
public void createFromEntity(DatabaseEntity entity) throws FailedToRetrieveMatchException, FailedToRetrievePlayersOfTeamException
{
if (!(entity instanceof Match)) {
throw new NotInstanceOfClassException(Match.class);
}
Match match = (Match) entity;
this.id = match.getId();
this.setTime(match.getTime().toString());
this.setDate(match.getDate().toString());
this.setLocalTeamScore(match.getLocalTeamScore());
this.setVisitorTeamScore(match.getVisitorTeamScore());
this.localTeam = new TeamModel(match.getLocalTeam());
this.visitorTeam = new TeamModel(match.getVisitorTeam());
this.field = new FieldModel(match.getField());
// Add officials
for (Official official : match.getOfficials()) {
this.officials.add(new OfficialModel(official));
}
}
}
|
karmaresearch/takco
|
takco/evaluate/triples.py
|
<filename>takco/evaluate/triples.py
from rdflib import URIRef, Literal
TYPE = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"
LABEL = "http://www.w3.org/2000/01/rdf-schema#label"
def triple_hash(s, p, v):
vnode = Literal(**v) if isinstance(v, dict) else URIRef(v)
return hash((URIRef(s), URIRef(p), vnode))
def yield_triples(table, include_type=True, include_label=True):
gold = table.get("gold", {})
# if fields are set but empty, the table is annotated but has no correct prediction
hasgold = bool(gold)
if "rows" in table:
rows = table["rows"]
else:
rows = [[c.get("text", "") for c in r] for r in table.get("tableData", [])]
# Yield gold and predicted triples
if include_label:
for ri, cells in enumerate(rows):
for ci, cell in enumerate(cells):
predents = table.get("entities", {}).get(str(ci), {}).get(str(ri), {})
goldents = gold.get("entities", {}).get(str(ci), {}).get(str(ri), {})
for e, escore in list(predents.items()) + list(goldents.items()):
v = {"lexical_or_value": str(cell)}
isgold = e in goldents
ispred = e in predents
yield {
"kind": "label",
"s": str(e),
"p": str(LABEL),
"o": v,
"s_score": escore,
"col": int(ci),
"row": int(ri),
"gold": isgold if hasgold else None,
"pred": ispred,
"hash": triple_hash(e, LABEL, v),
}
if include_type:
for ci, predclss in table.get("classes", {}).items():
goldclss = gold.get("classes", {}).get(ci, {})
for cls, cls_score in list(predclss.items()) + list(goldclss.items()):
for ri, predents in table.get("entities", {}).get(ci, {}).items():
goldents = gold.get("entities", {}).get(ci, {}).get(ri, {})
for e, escore in list(predents.items()) + list(goldents.items()):
isgold = (e in goldents) and (cls in goldclss)
ispred = (e in predents) and (cls in predclss)
if isgold or ispred:
yield {
"kind": "class",
"s": str(e),
"p": str(TYPE),
"o": str(cls),
"s_score": escore,
"o_score": cls_score,
"col": int(ci),
"row": int(ri),
"gold": isgold if hasgold else None,
"pred": ispred,
"hash": triple_hash(e, TYPE, cls),
}
# TODO: structure qualifiers
for fromci, toci_props in table.get("properties", {}).items():
for toci, predprops in toci_props.items():
goldprops = gold.get("properties", {}).get(fromci, {}).get(toci, {})
ri_toents = table.get("entities", {}).get(toci, {})
isentityprop = bool(ri_toents)
for p, p_score in list(predprops.items()) + list(goldprops.items()):
for ri, predents in table.get("entities", {}).get(fromci, {}).items():
goldents = gold.get("entities", {}).get(fromci, {}).get(ri, {})
for s, s_score in list(predents.items()) + list(goldents.items()):
isgold = (s in goldents) and (p in goldprops)
ispred = (s in predents) and (p in predprops)
if isgold or ispred:
sp = {
"kind": "property",
"s": str(s),
"p": str(p),
"s_score": s_score,
"p_score": p_score,
"col": int(toci),
"row": int(ri),
"gold": isgold if hasgold else None,
"pred": ispred,
}
if isentityprop:
for o, o_score in ri_toents.get(ri, {}).items():
yield {
**sp,
"o": str(o),
"o_score": o_score,
"hash": triple_hash(s, p, o),
}
else:
try:
cell = rows[int(ri)][int(toci)]
except:
cell = ""
if cell:
tocls = table.get("classes", {}).get(toci, {})
if tocls:
for cls, cls_score in tocls.items():
v = {
"lexical_or_value": str(cell),
"datatype": str(cls),
}
yield {
**sp,
"o": v,
"o_score": cls_score,
"hash": triple_hash(s, p, v),
}
else:
v = {"lexical_or_value": str(cell)}
yield {
**sp,
"o": v,
"hash": triple_hash(s, p, v),
}
|
mgadagin/PythonClass
|
instructors/lessons/numbers/examples/ex2_decimal.py
|
"""
This is from: https://docs.python.org/2/library/decimal.html#module-decimal
"""
import decimal
D = decimal.Decimal # Optional / from FAQ https://docs.python.org/2/library/decimal.html#decimal-faq
D_prec = 6 # Lets start with a precision of 6
print
print "Set precision to 6 decimals."
decimal.getcontext().prec = D_prec
# Take advantage of our shortened syntax above.
x = D(1)
y = D(7)
# We need to use quantize for non-integer multiplication and division.
print "divide x/y:", (x/y).quantize(D(10)**-D_prec), " - type:", type(x/y)
print
TWOPLACES = D(10) ** -2
print "divide x/y, two-digit quantize:", (x/y).quantize(TWOPLACES), " - type:", type(x/y)
print
print "reset to default precision, 28 decimals."
D_prec = 28
decimal.getcontext().prec = D_prec
# quantize again. It is a method of any Decimal type number.
print "divide x/y:", (x/y).quantize(D(10)**-D_prec), " - type:", type(x/y)
print
|
TolgaKara/prodai
|
src/team/views.py
|
from django.shortcuts import render
# Create your views here.
def team(request):
if request.user.is_authenticated:
# This is the access point
return render(request, 'auth/team/index.html')
else:
return redirect('homepage')
|
werdes72/control-plane
|
components/kyma-metrics-collector/pkg/gardener/shoot/client_test.go
|
package shoot
import (
"context"
"testing"
kmctesting "github.com/kyma-project/control-plane/components/kyma-metrics-collector/pkg/testing"
"github.com/prometheus/client_golang/prometheus/testutil"
"github.com/onsi/gomega"
k8sErrors "k8s.io/apimachinery/pkg/api/errors"
gardenerv1beta1 "github.com/gardener/gardener/pkg/apis/core/v1beta1"
gardenercommons "github.com/kyma-project/control-plane/components/kyma-metrics-collector/pkg/gardener/commons"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/dynamic"
dynamicfake "k8s.io/client-go/dynamic/fake"
)
func TestGet(t *testing.T) {
g := gomega.NewGomegaWithT(t)
ctx := context.Background()
existingShoot := "foo-shoot"
shoot := kmctesting.GetShoot(existingShoot, kmctesting.WithVMSpecs)
nsResourceClient, err := NewFakeClient(shoot)
g.Expect(err).Should(gomega.BeNil())
client := Client{ResourceClient: nsResourceClient}
gotShoot, err := client.Get(ctx, existingShoot)
g.Expect(err).Should(gomega.BeNil())
g.Expect(*gotShoot).To(gomega.Equal(*shoot))
// Tests metric
metricName := "kmc_gardener_calls_total"
g.Expect(testutil.CollectAndCount(gardenercommons.TotalCalls, metricName)).Should(gomega.Equal(1))
callsSuccess, err := gardenercommons.TotalCalls.GetMetricWithLabelValues(gardenercommons.SuccessStatusLabel, existingShoot, gardenercommons.SuccessGettingShootLabel)
g.Expect(err).Should(gomega.BeNil())
g.Expect(testutil.ToFloat64(callsSuccess)).Should(gomega.Equal(float64(1)))
nonexistentShoot := "doesnotexist-shoot"
_, err = client.Get(ctx, nonexistentShoot)
g.Expect(err).ShouldNot(gomega.BeNil())
g.Expect(k8sErrors.IsNotFound(err)).To(gomega.BeTrue())
// Test metric
g.Expect(testutil.CollectAndCount(gardenercommons.TotalCalls, metricName)).Should(gomega.Equal(2))
callsFailure, err := gardenercommons.TotalCalls.GetMetricWithLabelValues(gardenercommons.FailureStatusLabel, nonexistentShoot, gardenercommons.FailedGettingShootLabel)
g.Expect(err).Should(gomega.BeNil())
g.Expect(testutil.ToFloat64(callsFailure)).Should(gomega.Equal(float64(1)))
}
func NewFakeClient(shoot *gardenerv1beta1.Shoot) (dynamic.ResourceInterface, error) {
scheme, err := gardenercommons.SetupSchemeOrDie()
if err != nil {
return nil, err
}
unstructuredMap, err := runtime.DefaultUnstructuredConverter.ToUnstructured(shoot)
if err != nil {
return nil, err
}
shootUnstructured := &unstructured.Unstructured{Object: unstructuredMap}
shootUnstructured.SetGroupVersionKind(GroupVersionKind())
dynamicClient := dynamicfake.NewSimpleDynamicClient(scheme, shootUnstructured)
nsResourceClient := dynamicClient.Resource(GroupVersionResource()).Namespace("default")
return nsResourceClient, nil
}
|
zdtjss/wform
|
src/test/java/com/nway/wform/FreemarkerTest.java
|
package com.nway.wform;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import freemarker.template.Configuration;
import freemarker.template.Template;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "/spring.xml" })
public class FreemarkerTest {
@Autowired
@Qualifier("freemarkerConfiguration")
private Configuration freemarker;
@Test
public void out() throws Exception {
Template template = freemarker.getTemplate("/test.ftl");
Map<String, Object> dataModel = new HashMap<String, Object>();
dataModel.put("name", "哈哈");
Writer out = new PrintWriter(System.out);
template.process(dataModel, out);
}
}
|
racoq/TESRAC
|
parent/client/src/main/java/org/kanonizo/framework/objects/ClassUnderTest.java
|
<filename>parent/client/src/main/java/org/kanonizo/framework/objects/ClassUnderTest.java
package org.kanonizo.framework.objects;
import java.util.Set;
import org.kanonizo.Framework;
import org.kanonizo.framework.ClassStore;
import org.kanonizo.util.Util;
public class ClassUnderTest {
private Class<?> cut;
private int id;
private static int count = 0;
private SystemUnderTest parent;
private Set<Line> lines;
private Set<Branch> branches;
public ClassUnderTest(Class<?> cut) {
this.cut = cut;
this.id = ++count;
this.lines = Framework.getInstance().getInstrumenter().getLines(this);
this.branches = Framework.getInstance().getInstrumenter().getBranches(this);
ClassStore.add(cut.getName(), this);
}
private Line findLine(int lineNumber){
return lines.stream().filter(line -> line.getLineNumber() == lineNumber).findFirst().get();
}
public void setParent(SystemUnderTest parent){
this.parent = parent;
}
public int getId(){
return id;
}
public Class<?> getCUT() {
return cut;
}
public void setCUT(Class<?> cut) {
this.cut = cut;
}
public Set<Line> getLines(){
return lines;
}
public Set<Branch> getBranches() { return branches; }
public ClassUnderTest clone() {
return ClassStore.get(cut.getName());
}
@Override
public String toString() {
return Util.getName(cut);
}
public int size() {
return Framework.getInstance().getInstrumenter().getTotalLines(this);
}
public boolean equals(Object other){
if(this == other){
return true;
}
if (other == null){
return false;
}
if (getClass() != other.getClass()){
return false;
}
ClassUnderTest oc = (ClassUnderTest) other;
return oc.cut == cut && oc.id == id;
}
public int hashCode(){
int prime = 37;
int result = prime * ((Integer)id).hashCode();
result *= toString().hashCode();
return result;
}
public static void resetCount(){
count = 0;
}
}
|
syscoin/syscoin-fusion
|
app/utils/helpers/go-to-block-detail.js
|
<gh_stars>1-10
// @flow
import openInBrowser from './open-link-in-browser'
export default (blockhash: string) => openInBrowser(process.env.EXPLORER_BLOCK_PATH + blockhash)
|
bio-nim/pbbam
|
include/pbbam/Accuracy.h
|
#ifndef PBBAM_ACCURACY_H
#define PBBAM_ACCURACY_H
#include <pbbam/Config.h>
#include <pbcopper/data/Accuracy.h>
namespace PacBio {
namespace BAM {
using Accuracy PBBAM_DEPRECATED = Data::Accuracy;
} // namespace BAM
} // namespace PacBio
#endif // PBBAM_ACCURACY_H
|
abbymapes/step43-2020
|
portfolio/src/main/java/com/google/sps/utils/TimeUtils.java
|
/*
* Copyright 2019 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.sps.utils;
import com.google.protobuf.Value;
import com.google.sps.data.Pair;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TimeUtils {
private static Logger log = LoggerFactory.getLogger(TimeUtils.class);
/**
* Converts a string representation ("yyyy-MM-dd'T'HH:mm:ssXXX") of date into a Date object.
*
* @param dateString String representation of date in the form "yyyy-MM-dd'T'HH:mm:ssXXX"
* @param return Date object equivalent to the date represented in the string input.
*/
public static Date stringToDate(String dateString) throws ParseException {
SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX", Locale.ENGLISH);
Date parsed = parser.parse(dateString);
return parsed;
}
/**
* Converts a long representing ms since 1970 into a date string.
*
* @param milliseconds long representing milliseconds since 1970
* @param return String representing the input time as a formatted date string.
*/
public static String secondsToDateString(long milliseconds) throws ParseException {
Date date = new Date(milliseconds);
SimpleDateFormat parser = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.ENGLISH);
return parser.format(date);
}
/**
* Converts an integer in seconds into a string of hours, minutes, and seconds
*
* @param duration An int representing the number of seconds.
* @param return A string containing the input integer converted into "HH hours, MM minutes, and
* SS seconds"
*/
public static String secondsToHMSString(int duration) throws IllegalArgumentException {
if (duration < 1) {
throw new IllegalArgumentException("Duration input cannot be less than 1 second.");
} else if (duration == 1) {
return "1 second";
} else if (duration < 60) {
return String.valueOf(duration) + " seconds";
} else if (duration == 60) {
return "1 minute";
} else if (duration < 3600) {
return String.valueOf(duration / 60)
+ " minutes and "
+ String.valueOf(duration % 60)
+ " seconds";
} else if (duration == 3600) {
return "1 hour";
} else {
String remainder;
try {
remainder = secondsToHMSString(duration % 3600);
if (!remainder.contains("and")) {
remainder = "and " + remainder;
} else {
remainder = " " + remainder;
}
} catch (IllegalArgumentException e) {
remainder = "";
}
return String.valueOf(duration / 3600) + " hours" + remainder;
}
}
/**
* Converts an integer in seconds into a string of "HH:MM:SS"
*
* @param duration An int representing the number of seconds.
* @param return A string containing the input integer converted into "HH:MM:SS"
*/
public static String makeClockDisplay(int duration) {
int hours = duration / 3600;
int min = (duration - hours * 3600) / 60;
int sec = duration - hours * 3600 - min * 60;
if (hours == 0) {
return String.valueOf(min) + ":" + doubleDigitString(sec);
} else {
return String.valueOf(hours) + ":" + doubleDigitString(min) + ":" + doubleDigitString(sec);
}
}
/**
* Converts a single-digit integer into a double-digit number by adding a 0 to the front
*
* @param num input integer
* @return a number that is at least two digits
*/
public static String doubleDigitString(int num) {
if (num >= 10) {
return String.valueOf(num);
} else {
return "0" + String.valueOf(num);
}
}
/**
* Unpacks date object from "date-time-enhanced" entity to retrieve a start and end pair that
* represents the length of time that the user specified.
*
* @param dateObject Value from dialogflow's retrieved parameters
* @return Pair where key represents start time of duration and value represents end time
*/
public static Pair<Long, Long> getTimeRange(Value dateObject) throws ParseException {
String startDateString;
String endDateString;
Value dateTimeObject = dateObject.getStructValue().getFieldsMap().get("date-time");
if (dateTimeObject.hasStructValue()) {
Map<String, Value> durationMap = dateTimeObject.getStructValue().getFieldsMap();
if (durationMap.get("date-time") != null) {
// Case where user specifies a specific date and time (should return a 10 min period
// centered around the time)
Date dateTime = stringToDate(durationMap.get("date-time").getStringValue());
return new Pair(dateTime.getTime() - 300000, dateTime.getTime() + 300000);
}
// Case where user specifies a time duration.
startDateString = durationMap.get("startDate").getStringValue();
endDateString = durationMap.get("endDate").getStringValue();
} else {
// Case where user asks for a date but no time (should return a full day period)
String dateString = dateTimeObject.getStringValue();
startDateString = dateString.replaceAll("T([0-9]{2}:){2}[0-9]{2}", "T00:00:00");
endDateString = dateString.replaceAll("T([0-9]{2}:){2}[0-9]{2}", "T23:59:59");
}
Date start = stringToDate(startDateString);
Date end = stringToDate(endDateString);
return new Pair(start.getTime(), end.getTime());
}
}
|
npocmaka/Windows-Server-2003
|
inetcore/mshtml/src/dxt/msft/src/colormanagement.h
|
<filename>inetcore/mshtml/src/dxt/msft/src/colormanagement.h<gh_stars>10-100
//+-----------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation, 1999
//
// FileName: colormanagement.h
//
// Description: Color management filter transform.
//
// Change History:
//
// 2000/02/06 mcalkins Created. Ported code from an old filter.
//
//------------------------------------------------------------------------------
#ifndef __COLORMANAGEMENT_H_
#define __COLORMANAGEMENT_H_
#include "resource.h"
class ATL_NO_VTABLE CDXTICMFilter :
public CDXBaseNTo1,
public CComCoClass<CDXTICMFilter, &CLSID_DXTICMFilter>,
public CComPropertySupport<CDXTICMFilter>,
public IDispatchImpl<IDXTICMFilter, &IID_IDXTICMFilter, &LIBID_DXTMSFTLib,
DXTMSFT_TLB_MAJOR_VER, DXTMSFT_TLB_MINOR_VER>,
public IObjectSafetyImpl2<CDXTICMFilter>,
public IPersistStorageImpl<CDXTICMFilter>,
public ISpecifyPropertyPagesImpl<CDXTICMFilter>,
public IPersistPropertyBagImpl<CDXTICMFilter>
{
private:
CComPtr<IUnknown> m_spUnkMarshaler;
LOGCOLORSPACE m_LogColorSpace;
BSTR m_bstrColorSpace;
static const TCHAR * s_strSRGBColorSpace;
// m_fWin95 True if we're on Windows 95 specifically. In ths case
// we need to have some special treatment of the color
// space directories.
unsigned m_fWin95 : 1;
public:
CDXTICMFilter();
DECLARE_POLY_AGGREGATABLE(CDXTICMFilter)
DECLARE_REGISTER_DX_IMAGE_AUTHOR_TRANS(IDR_DXTICMFILTER)
DECLARE_GET_CONTROLLING_UNKNOWN()
BEGIN_COM_MAP(CDXTICMFilter)
COM_INTERFACE_ENTRY(IDXTICMFilter)
COM_INTERFACE_ENTRY(IDispatch)
COM_INTERFACE_ENTRY_AGGREGATE(IID_IMarshal, m_spUnkMarshaler.p)
COM_INTERFACE_ENTRY_IID(IID_IObjectSafety, IObjectSafetyImpl2<CDXTICMFilter>)
COM_INTERFACE_ENTRY_IMPL(IPersistPropertyBag)
COM_INTERFACE_ENTRY_IMPL(IPersistStorage)
COM_INTERFACE_ENTRY_IMPL(ISpecifyPropertyPages)
COM_INTERFACE_ENTRY_CHAIN(CDXBaseNTo1)
END_COM_MAP()
BEGIN_PROPERTY_MAP(CDXTICMFilter)
PROP_ENTRY("colorspace", DISPID_DXTICMFILTER_COLORSPACE, CLSID_DXTICMFilterPP)
PROP_ENTRY("intent", DISPID_DXTICMFILTER_INTENT, CLSID_DXTICMFilterPP)
PROP_PAGE(CLSID_DXTICMFilterPP)
END_PROPERTY_MAP()
// CComObjectRootEx overrides.
HRESULT FinalConstruct();
// CDXBaseNTo1 overrides.
HRESULT WorkProc(const CDXTWorkInfoNTo1 & WI, BOOL * pfContinueProcessing);
//HRESULT OnSetup(DWORD dwFlags);
// IDXTICMFilter methods.
STDMETHOD(get_ColorSpace)(BSTR * pbstrColorSpace);
STDMETHOD(put_ColorSpace)(BSTR bstrColorSpace);
STDMETHOD(get_Intent)(short * pnIntent);
STDMETHOD(put_Intent)(short nIntent);
};
#endif // __COLORMANAGEMENT_H_
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.