code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 4
991
| language
stringclasses 9
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ro.nextreports.server.aop;
import java.util.List;
import org.aspectj.lang.annotation.Pointcut;
/**
* @author Decebal Suiu
*/
public abstract class EntitiesRemoveAdvice {
@Pointcut("target(ro.nextreports.server.service.StorageService)")
public void inStorageService() {
}
@Pointcut("execution(* removeEntity(..))")
public void isRemoveEntity() {
}
@Pointcut("args(path, ..)")
public void withPath(String path) {
}
@Pointcut("inStorageService() && isRemoveEntity() && withPath(path)")
public void removeEntity(String path) {
}
@Pointcut("execution(* removeEntityById(..))")
public void isRemoveEntityById() {
}
@Pointcut("args(id, ..)")
public void withId(String id) {
}
@Pointcut("inStorageService() && isRemoveEntityById() && withId(id)")
public void removeEntityById(String id) {
}
@Pointcut("execution(* removeEntitiesById(..))")
public void isRemoveEntitiesById() {
}
@Pointcut("args(ids, ..)")
public void withIds(List<String> ids) {
}
@Pointcut("inStorageService() && isRemoveEntitiesById() && withIds(ids)")
public void removeEntitiesById(List<String> ids) {
}
}
|
nextreports/nextreports-server
|
src/ro/nextreports/server/aop/EntitiesRemoveAdvice.java
|
Java
|
apache-2.0
| 1,930 |
/*
* Copyright 2015-2018 G-Labs. All Rights Reserved.
* https://zuixjs.github.io/zuix
*
* 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.
*/
/*
*
* This file is part of
* zUIx, Javascript library for component-based development.
* https://zuixjs.github.io/zuix
*
* @author Generoso Martello <generoso@martello.com>
*/
const baseFolder = process.cwd();
// Commons
const fs = require('fs');
const path = require('path');
const recursive = require('fs-readdir-recursive');
// logging
const tlog = require(path.join(baseFolder, 'src/lib/logger'));
// ESLint
const linter = require('eslint').linter;
const lintConfig = require(path.join(baseFolder, '.eslintrc.json'));
const sourceFolder = path.join(baseFolder, 'src/js/');
const stats = {
error: 0,
warning: 0
};
function lint(callback) {
recursive(sourceFolder).map((f, i) => {
if (f.endsWith('.js')) {
tlog.info('^B%s^R', f);
const code = fs.readFileSync(sourceFolder + f, 'utf8');
const issues = linter.verify(code, lintConfig, sourceFolder + f);
issues.map((m, i)=>{
if (m.fatal || m.severity > 1) {
stats.error++;
tlog.error(' ^RError^: %s ^R(^Y%s^w:^Y%s^R)', m.message, m.line, m.column);
} else {
stats.warning++;
tlog.warn(' ^YWarning^: %s ^R(^Y%s^w:^Y%s^R)', m.message, m.line, m.column);
}
});
if (issues.length === 0) tlog.info(' ^G\u2713^: OK');
tlog.br();
}
});
tlog.info('Linting completed ^G-^: Errors ^R%s^: ^G-^: Warnings ^Y%s^:\n\n', stats.error, stats.warning);
//process.exit(stats.error);
if (callback) callback(stats);
}
module.exports = {
lint: lint
};
|
genielabs/zuix
|
build/scripts/lint.js
|
JavaScript
|
apache-2.0
| 2,327 |
$: << File.join(File.dirname(__FILE__), "/../lib" )
require 'rubygems'
require 'spec'
require 'dynomite'
|
chef/ruby-dynomite
|
spec/spec_helper.rb
|
Ruby
|
apache-2.0
| 106 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.wss4j.stax.validate;
import org.apache.commons.codec.binary.Base64;
import org.apache.wss4j.binding.wss10.AttributedString;
import org.apache.wss4j.binding.wss10.EncodedString;
import org.apache.wss4j.binding.wss10.PasswordString;
import org.apache.wss4j.binding.wss10.UsernameTokenType;
import org.apache.wss4j.binding.wsu10.AttributedDateTime;
import org.apache.wss4j.common.ext.WSPasswordCallback;
import org.apache.wss4j.common.ext.WSSecurityException;
import org.apache.wss4j.stax.ext.WSSConstants;
import org.apache.wss4j.stax.securityToken.UsernameSecurityToken;
import org.apache.wss4j.stax.securityToken.WSSecurityTokenConstants;
import org.apache.wss4j.stax.utils.WSSUtils;
import org.apache.wss4j.stax.impl.securityToken.UsernameSecurityTokenImpl;
import org.apache.xml.security.stax.ext.XMLSecurityUtils;
import org.apache.xml.security.stax.securityToken.InboundSecurityToken;
public class UsernameTokenValidatorImpl implements UsernameTokenValidator {
private static final transient org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(UsernameTokenValidatorImpl.class);
@Override
public <T extends UsernameSecurityToken & InboundSecurityToken> T validate(
UsernameTokenType usernameTokenType, TokenContext tokenContext) throws WSSecurityException {
// If the UsernameToken is to be used for key derivation, the (1.1)
// spec says that it cannot contain a password, and it must contain
// an Iteration element
final byte[] salt = XMLSecurityUtils.getQNameType(usernameTokenType.getAny(), WSSConstants.TAG_WSSE11_SALT);
PasswordString passwordType = XMLSecurityUtils.getQNameType(usernameTokenType.getAny(), WSSConstants.TAG_WSSE_PASSWORD);
final Long iteration = XMLSecurityUtils.getQNameType(usernameTokenType.getAny(), WSSConstants.TAG_WSSE11_ITERATION);
if (salt != null && (passwordType != null || iteration == null)) {
throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN, "badTokenType01");
}
boolean handleCustomPasswordTypes = tokenContext.getWssSecurityProperties().getHandleCustomPasswordTypes();
boolean allowUsernameTokenNoPassword =
tokenContext.getWssSecurityProperties().isAllowUsernameTokenNoPassword()
|| Boolean.parseBoolean((String)tokenContext.getWsSecurityContext().get(WSSConstants.PROP_ALLOW_USERNAMETOKEN_NOPASSWORD));
// Check received password type against required type
WSSConstants.UsernameTokenPasswordType requiredPasswordType =
tokenContext.getWssSecurityProperties().getUsernameTokenPasswordType();
if (requiredPasswordType != null) {
if (passwordType == null || passwordType.getType() == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Authentication failed as the received password type does not "
+ "match the required password type of: " + requiredPasswordType);
}
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
}
WSSConstants.UsernameTokenPasswordType usernameTokenPasswordType =
WSSConstants.UsernameTokenPasswordType.getUsernameTokenPasswordType(passwordType.getType());
if (requiredPasswordType != usernameTokenPasswordType) {
if (LOG.isDebugEnabled()) {
LOG.debug("Authentication failed as the received password type does not "
+ "match the required password type of: " + requiredPasswordType);
}
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
}
}
WSSConstants.UsernameTokenPasswordType usernameTokenPasswordType = WSSConstants.UsernameTokenPasswordType.PASSWORD_NONE;
if (passwordType != null && passwordType.getType() != null) {
usernameTokenPasswordType = WSSConstants.UsernameTokenPasswordType.getUsernameTokenPasswordType(passwordType.getType());
}
final AttributedString username = usernameTokenType.getUsername();
if (username == null) {
throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN, "badTokenType01");
}
final EncodedString encodedNonce =
XMLSecurityUtils.getQNameType(usernameTokenType.getAny(), WSSConstants.TAG_WSSE_NONCE);
byte[] nonceVal = null;
if (encodedNonce != null && encodedNonce.getValue() != null) {
nonceVal = Base64.decodeBase64(encodedNonce.getValue());
}
final AttributedDateTime attributedDateTimeCreated =
XMLSecurityUtils.getQNameType(usernameTokenType.getAny(), WSSConstants.TAG_WSU_CREATED);
String created = null;
if (attributedDateTimeCreated != null) {
created = attributedDateTimeCreated.getValue();
}
if (usernameTokenPasswordType == WSSConstants.UsernameTokenPasswordType.PASSWORD_DIGEST) {
if (encodedNonce == null || attributedDateTimeCreated == null) {
throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN, "badTokenType01");
}
if (!WSSConstants.SOAPMESSAGE_NS10_BASE64_ENCODING.equals(encodedNonce.getEncodingType())) {
throw new WSSecurityException(WSSecurityException.ErrorCode.UNSUPPORTED_SECURITY_TOKEN, "badTokenType01");
}
verifyDigestPassword(username.getValue(), passwordType, nonceVal, created, tokenContext);
} else if (usernameTokenPasswordType == WSSConstants.UsernameTokenPasswordType.PASSWORD_TEXT
|| passwordType != null && passwordType.getValue() != null
&& usernameTokenPasswordType == WSSConstants.UsernameTokenPasswordType.PASSWORD_NONE) {
verifyPlaintextPassword(username.getValue(), passwordType, tokenContext);
} else if (passwordType != null && passwordType.getValue() != null) {
if (!handleCustomPasswordTypes) {
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
}
verifyCustomPassword(username.getValue(), passwordType, tokenContext);
} else {
if (!allowUsernameTokenNoPassword) {
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
}
}
final String password;
if (passwordType != null) {
password = passwordType.getValue();
} else if (salt != null) {
WSPasswordCallback pwCb = new WSPasswordCallback(username.getValue(),
WSPasswordCallback.USERNAME_TOKEN);
try {
WSSUtils.doPasswordCallback(tokenContext.getWssSecurityProperties().getCallbackHandler(), pwCb);
} catch (WSSecurityException e) {
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION, e);
}
password = pwCb.getPassword();
} else {
password = null;
}
UsernameSecurityTokenImpl usernameSecurityToken = new UsernameSecurityTokenImpl(
usernameTokenPasswordType, username.getValue(), password, created,
nonceVal, salt, iteration,
tokenContext.getWsSecurityContext(), usernameTokenType.getId(),
WSSecurityTokenConstants.KEYIDENTIFIER_SECURITY_TOKEN_DIRECT_REFERENCE);
usernameSecurityToken.setElementPath(tokenContext.getElementPath());
usernameSecurityToken.setXMLSecEvent(tokenContext.getFirstXMLSecEvent());
@SuppressWarnings("unchecked")
T token = (T)usernameSecurityToken;
return token;
}
/**
* Verify a UsernameToken containing a password digest.
*/
protected void verifyDigestPassword(
String username,
PasswordString passwordType,
byte[] nonceVal,
String created,
TokenContext tokenContext
) throws WSSecurityException {
WSPasswordCallback pwCb = new WSPasswordCallback(username,
null,
passwordType.getType(),
WSPasswordCallback.USERNAME_TOKEN);
try {
WSSUtils.doPasswordCallback(tokenContext.getWssSecurityProperties().getCallbackHandler(), pwCb);
} catch (WSSecurityException e) {
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION, e);
}
if (pwCb.getPassword() == null) {
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
}
String passDigest = WSSUtils.doPasswordDigest(nonceVal, created, pwCb.getPassword());
if (!passwordType.getValue().equals(passDigest)) {
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
}
passwordType.setValue(pwCb.getPassword());
}
/**
* Verify a UsernameToken containing a plaintext password.
*/
protected void verifyPlaintextPassword(
String username,
PasswordString passwordType,
TokenContext tokenContext
) throws WSSecurityException {
WSPasswordCallback pwCb = new WSPasswordCallback(username,
null,
passwordType.getType(),
WSPasswordCallback.USERNAME_TOKEN);
try {
WSSUtils.doPasswordCallback(tokenContext.getWssSecurityProperties().getCallbackHandler(), pwCb);
} catch (WSSecurityException e) {
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION, e);
}
if (pwCb.getPassword() == null) {
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
}
if (!passwordType.getValue().equals(pwCb.getPassword())) {
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
}
passwordType.setValue(pwCb.getPassword());
}
/**
* Verify a UsernameToken containing a password of some unknown (but specified) password
* type.
*/
protected void verifyCustomPassword(
String username,
PasswordString passwordType,
TokenContext tokenContext
) throws WSSecurityException {
verifyPlaintextPassword(username, passwordType, tokenContext);
}
}
|
clibois/wss4j
|
ws-security-stax/src/main/java/org/apache/wss4j/stax/validate/UsernameTokenValidatorImpl.java
|
Java
|
apache-2.0
| 11,364 |
import {firestore} from '../../utils/firestore';
const HOOK_COLLECTION_NAME = 'github-event-deliveries';
export const HOOK_MAX_AGE = 60 * 1000;
class HooksModel {
/**
* This method may be called multiple times in quick succession resulting
* in a the doc already existing.
*/
async logHook(hookDelivery: string): Promise<boolean> {
const hookDocRef =
await firestore().collection(HOOK_COLLECTION_NAME).doc(hookDelivery);
return firestore().runTransaction(async (transaction) => {
const hookDoc = await transaction.get(hookDocRef);
if (hookDoc.exists) {
return false;
}
await transaction.set(
hookDocRef, {received: true, timestamp: Date.now()});
return true;
});
}
async cleanHooks() {
const querySnapshot =
await firestore()
.collection(HOOK_COLLECTION_NAME)
.where('timestamp', '<', Date.now() - HOOK_MAX_AGE)
.get();
const batch = firestore().batch();
querySnapshot.forEach((doc) => {
batch.delete(doc.ref);
});
await batch.commit();
}
async deleteHook(hookDelivery: string) {
await firestore()
.collection(HOOK_COLLECTION_NAME)
.doc(hookDelivery)
.delete();
}
}
export const hooksModel = new HooksModel();
|
PolymerLabs/project-health
|
src/server/models/hooksModel.ts
|
TypeScript
|
apache-2.0
| 1,305 |
package com.ycsoft.report.query.daq;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.ycsoft.commons.exception.ReportException;
import com.ycsoft.commons.helper.LoggerHelper;
import com.ycsoft.report.db.ConnContainer;
/**
* 数据库提取数据
*/
public class DBAcquisition implements DataReader {
private Connection conn = null;
private Statement stmt = null;
private ResultSet rs = null;
private String database =null;
private String sql=null;
public DBAcquisition(String sql,String database){
this.sql=sql;
this.database=database;
}
public void close() throws ReportException {
try {
if (rs != null){
rs.close();
rs=null;
}
} catch (Exception e) {
}
try {
if (stmt != null){
stmt.close();
stmt=null;
}
} catch (Exception e) {
}
try {
if (conn != null){
conn.close();
conn=null;
}
} catch (Exception e) {
}
}
public Object getObject(int i) throws ReportException {
try {
return rs.getObject(i);
} catch (SQLException e) {
throw new ReportException(e);
}
}
public String getString(int i) throws ReportException {
try {
return rs.getString(i);
} catch (SQLException e) {
throw new ReportException(e);
}
}
public boolean next() throws ReportException {
try {
return rs.next();
} catch (SQLException e) {
throw new ReportException(e);
}
}
public void open() throws ReportException {
try {
conn = ConnContainer.getConn(database);
stmt = conn.createStatement();
stmt.setFetchSize(1000);
LoggerHelper.debug(this.getClass(),sql);
rs = stmt.executeQuery(sql);
} catch (SQLException e) {
throw new ReportException(e,e.getSQLState());
}
}
}
|
leopardoooo/cambodia
|
boss-report/src/main/java/com/ycsoft/report/query/daq/DBAcquisition.java
|
Java
|
apache-2.0
| 1,854 |
package org.aws4j.data.dynamo.attribute.converter;
import java.lang.reflect.Type;
import java.util.Set;
import org.aws4j.core.exception.NotImplementedException;
import org.aws4j.core.util.JacksonUtil;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonConverter<V> implements AttributeValueConverter<V> {
private Type parameterType;
private ObjectMapper mapper;
public JsonConverter(Type parameterType) {
this.parameterType = parameterType;
this.mapper = new ObjectMapper();
};
// TODO Util
private String toJsonString(V value) {
try {
return mapper.writeValueAsString(value);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException(e);
}
}
private V toValue(String json) {
try {
return mapper.readValue(json,
JacksonUtil.getJavaType(parameterType));
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
@Override
public AttributeValue convert(V value) {
return new AttributeValue().withS(toJsonString(value));
}
@Override
public AttributeValue convertFromSet(Set<V> values) {
throw new NotImplementedException();
}
@Override
public V deconvert(AttributeValue attrValue) {
// TODO Auto-generated method stub
return toValue(attrValue.getS());
}
@Override
public Set<V> deconvertToSet(AttributeValue attrValue) {
throw new NotImplementedException();
}
}
|
aws4j/dynamo-mapper
|
src/main/java/org/aws4j/data/dynamo/attribute/converter/JsonConverter.java
|
Java
|
apache-2.0
| 1,500 |
package ee.jiss.commons.json.convert;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormatter;
import java.io.IOException;
import static ee.jiss.commons.lang.CheckUtils.isEmptyString;
import static org.joda.time.format.DateTimeFormat.forPattern;
public class LocalDateParser
extends StdScalarDeserializer<LocalDate> {
private static final DateTimeFormatter FORMATTER = forPattern("dd.MM.yyyy");
public LocalDateParser() {
super(LocalDate.class);
}
@Override
public LocalDate deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException {
final String text = jp.getText();
return isEmptyString(text) ? null : FORMATTER.parseLocalDate(text);
}
}
|
jiss-software/jiss-commons
|
commons-json/src/main/java/ee/jiss/commons/json/convert/LocalDateParser.java
|
Java
|
apache-2.0
| 935 |
/*
* Copyright 2004-2015 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is 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.
*/
#define EXTERN
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#include "driver.h"
#include "arg.h"
#include "chpl.h"
#include "commonFlags.h"
#include "config.h"
#include "countTokens.h"
#include "docsDriver.h"
#include "files.h"
#include "ipe.h"
#include "log.h"
#include "misc.h"
#include "mysystem.h"
#include "PhaseTracker.h"
#include "primitive.h"
#include "runpasses.h"
#include "stmt.h"
#include "stringutil.h"
#include "symbol.h"
#include "timer.h"
#include "version.h"
#include <inttypes.h>
#include <string>
#include <sstream>
char CHPL_HOME[FILENAME_MAX+1] = "";
const char* CHPL_HOST_PLATFORM = NULL;
const char* CHPL_HOST_COMPILER = NULL;
const char* CHPL_TARGET_PLATFORM = NULL;
const char* CHPL_TARGET_COMPILER = NULL;
const char* CHPL_TARGET_ARCH = NULL;
const char* CHPL_LOCALE_MODEL = NULL;
const char* CHPL_COMM = NULL;
const char* CHPL_COMM_SUBSTRATE = NULL;
const char* CHPL_GASNET_SEGMENT = NULL;
const char* CHPL_TASKS = NULL;
const char* CHPL_THREADS = NULL;
const char* CHPL_LAUNCHER = NULL;
const char* CHPL_TIMERS = NULL;
const char* CHPL_MEM = NULL;
const char* CHPL_MAKE = NULL;
const char* CHPL_ATOMICS = NULL;
const char* CHPL_NETWORK_ATOMICS = NULL;
const char* CHPL_GMP = NULL;
const char* CHPL_HWLOC = NULL;
const char* CHPL_REGEXP = NULL;
const char* CHPL_WIDE_POINTERS = NULL;
const char* CHPL_LLVM = NULL;
const char* CHPL_AUX_FILESYS = NULL;
// quick and dirty
#define MAX_CHPL_ENV_VARS 50
int num_chpl_env_vars = 0;
const char *chpl_env_vars[MAX_CHPL_ENV_VARS];
const char *chpl_env_var_names[MAX_CHPL_ENV_VARS];
bool widePointersStruct;
static char makeArgument[256] = "";
static char libraryFilename[FILENAME_MAX] = "";
static char incFilename[FILENAME_MAX] = "";
static char moduleSearchPath[FILENAME_MAX] = "";
static char log_flags[512] = "";
bool fLibraryCompile = false;
bool no_codegen = false;
int debugParserLevel = 0;
bool fVerify = false;
bool ignore_errors = false;
bool ignore_errors_for_pass = false;
bool ignore_warnings = false;
int fcg = 0;
static bool fBaseline = false;
bool fCacheRemote = false;
bool fFastFlag = false;
int fConditionalDynamicDispatchLimit = 0;
bool fUseNoinit = true;
bool fNoCopyPropagation = false;
bool fNoDeadCodeElimination = false;
bool fNoRemoveWrapRecords = false;
bool fNoScalarReplacement = false;
bool fNoTupleCopyOpt = false;
bool fNoRemoteValueForwarding = false;
bool fNoRemoveCopyCalls = false;
bool fNoOptimizeLoopIterators = false;
bool fNoVectorize = true;
bool fNoGlobalConstOpt = false;
bool fNoFastFollowers = false;
bool fNoInlineIterators = false;
bool fNoLiveAnalysis = false;
bool fNoBoundsChecks = false;
bool fNoLocalChecks = false;
bool fNoNilChecks = false;
bool fNoStackChecks = false;
bool fNoCastChecks = false;
bool fMungeUserIdents = true;
bool fEnableTaskTracking = false;
bool printPasses = false;
FILE* printPassesFile = NULL;
// flag for llvmWideOpt
bool fLLVMWideOpt = false;
bool fWarnConstLoops = true;
// Enable all extra special warnings
static bool fNoWarnSpecial = true;
static bool fNoWarnDomainLiteral = true;
static bool fNoWarnTupleIteration = true;
bool fNoloopInvariantCodeMotion = false;
bool fNoChecks = false;
bool fNoInline = false;
bool fNoPrivatization = false;
bool fNoOptimizeOnClauses = false;
bool fNoRemoveEmptyRecords = true;
bool fRemoveUnreachableBlocks = true;
bool fMinimalModules = false;
bool fUseIPE = false;
int optimize_on_clause_limit = 20;
int scalar_replace_limit = 8;
int tuple_copy_limit = scalar_replace_limit;
bool fGenIDS = false;
int fLinkStyle = LS_DEFAULT; // use backend compiler's default
bool fLocal; // initialized in setupOrderedGlobals() below
bool fIgnoreLocalClasses = false;
bool fHeterogeneous = false; // re-initialized in setupOrderedGlobals() below
bool fieeefloat = false;
int ffloatOpt = 0; // 0 -> backend default; -1 -> strict; 1 -> opt
bool report_inlining = false;
char fExplainCall[256] = "";
int explainCallID = -1;
int breakOnResolveID = -1;
char fExplainInstantiation[256] = "";
bool fExplainVerbose = false;
bool fPrintCallStackOnError = false;
bool fPrintIDonError = false;
bool fPrintModuleResolution = false;
bool fCLineNumbers = false;
bool fPrintEmittedCodeSize = false;
char fPrintStatistics[256] = "";
bool fPrintDispatch = false;
bool fReportOptimizedLoopIterators = false;
bool fReportOrderIndependentLoops = false;
bool fReportOptimizedOn = false;
bool fReportPromotion = false;
bool fReportScalarReplace = false;
bool fReportDeadBlocks = false;
bool fReportDeadModules = false;
bool printCppLineno = false;
bool userSetCppLineno = false;
int num_constants_per_variable = 1;
char defaultDist[256] = "DefaultDist";
int instantiation_limit = 256;
char mainModuleName[256] = "";
bool printSearchDirs = false;
bool printModuleFiles = false;
bool llvmCodegen = false;
#ifdef HAVE_LLVM
bool externC = true;
#else
bool externC = false;
#endif
char breakOnCodegenCname[256] = "";
bool debugCCode = false;
bool optimizeCCode = false;
bool specializeCCode = false;
bool fNoMemoryFrees = false;
int numGlobalsOnHeap = 0;
bool preserveInlinedLineNumbers = false;
const char* compileCommand = NULL;
char compileVersion[64];
/* Note -- LLVM provides a way to get the path to the executable...
// This function isn't referenced outside its translation unit, but it
// can't use the "static" keyword because its address is used for
// GetMainExecutable (since some platforms don't support taking the
// address of main, and some platforms can't implement GetMainExecutable
// without being given the address of a function in the main executable).
llvm::sys::Path GetExecutablePath(const char *Argv0) {
// This just needs to be some symbol in the binary; C++ doesn't
// allow taking the address of ::main however.
void *MainAddr = (void*) (intptr_t) GetExecutablePath;
return llvm::sys::Path::GetMainExecutable(Argv0, MainAddr);
}
*/
static bool isMaybeChplHome(const char* path)
{
bool ret = false;
char* real = dirHasFile(path, "util/chplenv");
if (real)
ret = true;
free(real);
return ret;
}
static void setupChplHome(const char* argv0) {
const char* chpl_home = getenv("CHPL_HOME");
char* guess = NULL;
// Get the executable path.
guess = findProgramPath(argv0);
if (guess) {
// Determine CHPL_HOME based on the exe path.
// Determined exe path, but don't have a env var set
// Look for ../../../util/chplenv
// Remove the /bin/some-platform/chpl part
// from the path.
if( guess[0] ) {
int j = strlen(guess) - 5; // /bin and '\0'
for( ; j >= 0; j-- ) {
if( guess[j] == '/' &&
guess[j+1] == 'b' &&
guess[j+2] == 'i' &&
guess[j+3] == 'n' ) {
guess[j] = '\0';
break;
}
}
}
if( isMaybeChplHome(guess) ) {
// OK!
} else {
// Maybe we are in e.g. /usr/bin.
free(guess);
guess = NULL;
}
}
if( chpl_home ) {
if( strlen(chpl_home) > FILENAME_MAX )
USR_FATAL("$CHPL_HOME=%s path too long", chpl_home);
if( guess == NULL ) {
// Could not find exe path, but have a env var set
strncpy(CHPL_HOME, chpl_home, FILENAME_MAX);
} else {
// We have env var and found exe path.
// Check that they match and emit a warning if not.
if( ! isSameFile(chpl_home, guess) ) {
// Not the same. Emit warning.
USR_WARN("$CHPL_HOME=%s mismatched with executable home=%s",
chpl_home, guess);
}
// Since we have an enviro var, always use that.
strncpy(CHPL_HOME, chpl_home, FILENAME_MAX);
}
} else {
if( guess == NULL ) {
// Could not find enviro var, and could not
// guess at exe's path name.
USR_FATAL("$CHPL_HOME must be set to run chpl");
} else {
int rc;
if( strlen(guess) > FILENAME_MAX )
USR_FATAL("chpl guessed home %s too long", guess);
// Determined exe path, but don't have a env var set
strncpy(CHPL_HOME, guess, FILENAME_MAX);
// Also need to setenv in this case.
rc = setenv("CHPL_HOME", guess, 0);
if( rc ) USR_FATAL("Could not setenv CHPL_HOME");
}
}
// Check that the resulting path is a Chapel distribution.
if( ! isMaybeChplHome(CHPL_HOME) ) {
// Bad enviro var.
USR_WARN("CHPL_HOME=%s is not a Chapel distribution", CHPL_HOME);
}
if( guess )
free(guess);
parseCmdLineConfig("CHPL_HOME", astr("\"", CHPL_HOME, "\""));
}
static void setupEnvVar(std::istringstream& iss, const char** var, const char* varname) {
std::string line;
std::string value;
std::getline(iss, line);
if (!iss.good() || line.find(varname) == std::string::npos) {
INT_FATAL(astr("Parsing ", varname));
}
value = line.substr(line.find('=')+1, std::string::npos);
*var = astr(value.c_str()); // astr call is to canonicalize
parseCmdLineConfig(varname, astr("\"", *var, "\""));
}
#define SETUP_ENV_VAR(varname) \
INT_ASSERT(num_chpl_env_vars < MAX_CHPL_ENV_VARS); \
setupEnvVar(iss, &varname, #varname); \
chpl_env_var_names[num_chpl_env_vars] = #varname; \
chpl_env_vars[num_chpl_env_vars] = varname; \
num_chpl_env_vars++;
static void setupEnvVars() {
std::string vars = runUtilScript("printchplenv --simple");
std::istringstream iss(vars);
SETUP_ENV_VAR(CHPL_HOST_PLATFORM);
SETUP_ENV_VAR(CHPL_HOST_COMPILER);
SETUP_ENV_VAR(CHPL_TARGET_PLATFORM);
SETUP_ENV_VAR(CHPL_TARGET_COMPILER);
SETUP_ENV_VAR(CHPL_TARGET_ARCH);
SETUP_ENV_VAR(CHPL_LOCALE_MODEL);
SETUP_ENV_VAR(CHPL_COMM);
SETUP_ENV_VAR(CHPL_COMM_SUBSTRATE);
SETUP_ENV_VAR(CHPL_GASNET_SEGMENT);
SETUP_ENV_VAR(CHPL_TASKS);
SETUP_ENV_VAR(CHPL_THREADS);
SETUP_ENV_VAR(CHPL_LAUNCHER);
SETUP_ENV_VAR(CHPL_TIMERS);
SETUP_ENV_VAR(CHPL_MEM);
SETUP_ENV_VAR(CHPL_MAKE);
SETUP_ENV_VAR(CHPL_ATOMICS);
SETUP_ENV_VAR(CHPL_NETWORK_ATOMICS);
SETUP_ENV_VAR(CHPL_GMP);
SETUP_ENV_VAR(CHPL_HWLOC);
SETUP_ENV_VAR(CHPL_REGEXP);
SETUP_ENV_VAR(CHPL_WIDE_POINTERS);
SETUP_ENV_VAR(CHPL_LLVM);
SETUP_ENV_VAR(CHPL_AUX_FILESYS);
}
//
// Can't rely on a variable initialization order for globals, so any
// variables that need to be initialized in a particular order go here
//
static void setupOrderedGlobals(const char* argv0) {
// Set up CHPL_HOME first
setupChplHome(argv0);
// Then CHPL_* variables
setupEnvVars();
// These depend on the environment variables being set
fLocal = !strcmp(CHPL_COMM, "none");
bool gotPGI = !strcmp(CHPL_TARGET_COMPILER, "pgi")
|| !strcmp(CHPL_TARGET_COMPILER, "cray-prgenv-pgi");
// conservatively how much is needed for the current PGI compiler
if (gotPGI) fMaxCIdentLen = 1020;
if( 0 == strcmp(CHPL_WIDE_POINTERS, "struct") ) {
widePointersStruct = true;
} else {
widePointersStruct = false;
}
}
// NOTE: We are leaking memory here by dropping astr() results on the ground.
static void recordCodeGenStrings(int argc, char* argv[]) {
compileCommand = astr("chpl ");
// WARNING: This does not handle arbitrary sequences of escaped characters
// in string arguments
for (int i = 1; i < argc; i++) {
char *arg = argv[i];
// Handle " and \" in strings
while (char *dq = strchr(arg, '"')) {
char targ[strlen(argv[i])+4];
memcpy(targ, arg, dq-arg);
if ((dq==argv[i]) || ((dq!=argv[i]) && (*(dq-1)!='\\'))) {
targ[dq-arg] = '\\';
targ[dq-arg+1] = '"';
targ[dq-arg+2] = '\0';
} else {
targ[dq-arg] = '"';
targ[dq-arg+1] = '\0';
}
arg = dq+1;
compileCommand = astr(compileCommand, targ);
if (arg == NULL) break;
}
if (arg)
compileCommand = astr(compileCommand, arg, " ");
}
get_version(compileVersion);
}
static void setStaticLink(const ArgumentState* state, const char* arg_unused) {
if (strcmp(CHPL_TARGET_PLATFORM, "darwin") == 0) {
USR_WARN("Static compilation is not supported on OS X, ignoring flag.");
fLinkStyle = LS_DEFAULT;
} else {
fLinkStyle = LS_STATIC;
}
}
static void setDynamicLink(const ArgumentState* state, const char* arg_unused) {
fLinkStyle = LS_DYNAMIC;
}
static void setChapelDebug(const ArgumentState* state, const char* arg_unused) {
printCppLineno = true;
}
// In order to handle accumulating ccflags arguments, the argument
// processing calls this function. This function appends the flags
// to the ccflags variable, so that multiple --ccflags arguments
// all end up together in the ccflags variable (and will end up
// being passed to the backend C compiler).
static void setCCFlags(const ArgumentState* state, const char* arg) {
// Append arg to the end of ccflags.
int curlen = strlen(ccflags);
int space = sizeof(ccflags) - curlen - 1 - 1; // room for ' ' and \0
int arglen = strlen(arg);
if( arglen <= space ) {
// add a space if there are already arguments here
if( curlen != 0 ) ccflags[curlen++] = ' ';
memcpy(&ccflags[curlen], arg, arglen);
} else {
USR_FATAL("ccflags argument too long");
}
}
static void handleLibrary(const ArgumentState* state, const char* arg_unused) {
addLibInfo(astr("-l", libraryFilename));
}
static void handleLibPath(const ArgumentState* state, const char* arg_unused) {
addLibInfo(astr("-L", libraryFilename));
}
static void handleMake(const ArgumentState* state, const char* arg_unused) {
CHPL_MAKE = makeArgument;
}
static void handleIncDir(const ArgumentState* state, const char* arg_unused) {
addIncInfo(incFilename);
}
static void runCompilerInGDB(int argc, char* argv[]) {
const char* gdbCommandFilename = createDebuggerFile("gdb", argc, argv);
const char* command = astr("gdb -q ", argv[0]," -x ", gdbCommandFilename);
int status = mysystem(command, "running gdb", false);
clean_exit(status);
}
static void runCompilerInLLDB(int argc, char* argv[]) {
const char* lldbCommandFilename = createDebuggerFile("lldb", argc, argv);
const char* command = astr("lldb -s ", lldbCommandFilename, " ", argv[0]);
int status = mysystem(command, "running lldb", false);
clean_exit(status);
}
static void readConfig(const ArgumentState* state, const char* arg_unused) {
// Expect arg_unused to be a string of either of these forms:
// 1. name=value -- set the config param "name" to "value"
// 2. name -- set the boolean config param "name" to NOT("name")
// if name is not type bool, set it to 0.
char *name = strdup(arg_unused);
char *value;
value = strstr(name, "=");
if (value) {
*value = '\0';
value++;
if (value[0]) {
// arg_unused was name=value
parseCmdLineConfig(name, value);
} else {
// arg_unused was name= <blank>
USR_FATAL("Missing config param value");
}
} else {
// arg_unused was just name
parseCmdLineConfig(name, "");
}
}
static void addModulePath(const ArgumentState* state, const char* newpath) {
addFlagModulePath(newpath);
}
static void noteCppLinesSet(const ArgumentState* state, const char* unused) {
userSetCppLineno = true;
}
static void verifySaveCDir(const ArgumentState* state, const char* unused) {
if (saveCDir[0] == '-') {
USR_FATAL("--savec takes a directory name as its argument\n"
" (you specified '%s', assumed to be another flag)",
saveCDir);
}
}
static void turnOffChecks(const ArgumentState* state, const char* unused) {
fNoNilChecks = true;
fNoBoundsChecks = true;
fNoLocalChecks = true;
fNoStackChecks = true;
fNoCastChecks = true;
}
static void handleStackCheck(const ArgumentState* state, const char* unused) {
if (!fNoStackChecks && strcmp(CHPL_TASKS, "massivethreads") == 0) {
USR_WARN("CHPL_TASKS=%s cannot do stack checks.", CHPL_TASKS);
}
}
static void handleTaskTracking(const ArgumentState* state, const char* unused) {
if (fEnableTaskTracking && strcmp(CHPL_TASKS, "fifo") != 0) {
USR_WARN("Enabling task tracking with CHPL_TASKS=%s has no effect other than to slow down compilation", CHPL_TASKS);
}
}
static void setFastFlag(const ArgumentState* state, const char* unused) {
//
// Enable all compiler optimizations, disable all runtime checks
//
fBaseline = false;
// don't set fieeefloat since it can change program behavior.
// instead, we rely on the backend C compiler to choose
// an appropriate level of optimization.
fNoCopyPropagation = false;
fNoDeadCodeElimination = false;
fNoRemoveWrapRecords = false;
fNoFastFollowers = false;
fNoloopInvariantCodeMotion= false;
fNoInline = false;
fNoInlineIterators = false;
fNoOptimizeLoopIterators = false;
fNoVectorize = false;
fNoLiveAnalysis = false;
fNoRemoteValueForwarding = false;
fNoRemoveCopyCalls = false;
fNoScalarReplacement = false;
fNoTupleCopyOpt = false;
fNoPrivatization = false;
fNoChecks = true;
fNoBoundsChecks = true;
fNoLocalChecks = true;
fIgnoreLocalClasses = false;
fNoNilChecks = true;
fNoStackChecks = true;
fNoCastChecks = true;
fNoOptimizeOnClauses = false;
optimizeCCode = true;
specializeCCode = true;
}
static void setFloatOptFlag(const ArgumentState* state, const char* unused) {
// It would be nicer if arg.cpp could handle
// 3-value variables like this (set to false, set to true, not set)
// But if this is the only such case, having a set function is an OK plan.
// ffloatOpt defaults to 0 -> backend default
if( fieeefloat ) {
// IEEE strict
ffloatOpt = -1;
} else {
// lax IEEE, optimize
ffloatOpt = 1;
}
}
static void setBaselineFlag(const ArgumentState* state, const char* unused) {
//
// disable all chapel compiler optimizations
//
fBaseline = true;
fNoCopyPropagation = true;
fNoDeadCodeElimination = true;
fNoRemoveWrapRecords = true;
fNoFastFollowers = true;
fNoloopInvariantCodeMotion = true;
fNoInline = true;
fNoInlineIterators = true;
fNoLiveAnalysis = true;
fNoOptimizeLoopIterators = true;
fNoVectorize = true;
fNoRemoteValueForwarding = true;
fNoRemoveCopyCalls = true;
fNoScalarReplacement = true;
fNoTupleCopyOpt = true;
fNoPrivatization = true;
fNoOptimizeOnClauses = true;
fIgnoreLocalClasses = true;
fConditionalDynamicDispatchLimit = 0;
}
static void setCacheEnable(const ArgumentState* state, const char* unused) {
const char *val = fCacheRemote ? "true" : "false";
parseCmdLineConfig("CHPL_CACHE_REMOTE", val);
}
static void setHtmlUser(const ArgumentState* state, const char* unused) {
fdump_html = true;
fdump_html_include_system_modules = false;
}
static void setWarnTupleIteration(const ArgumentState* state, const char* unused) {
const char *val = fNoWarnTupleIteration ? "false" : "true";
parseCmdLineConfig("CHPL_WARN_TUPLE_ITERATION", astr("\"", val, "\""));
}
static void setWarnDomainLiteral(const ArgumentState* state, const char* unused) {
const char *val = fNoWarnDomainLiteral ? "false" : "true";
parseCmdLineConfig("CHPL_WARN_DOMAIN_LITERAL", astr("\"", val, "\""));
}
static void setWarnSpecial(const ArgumentState* state, const char* unused) {
fNoWarnSpecial = false;
fNoWarnDomainLiteral = false;
setWarnDomainLiteral(state, unused);
fNoWarnTupleIteration = false;
setWarnTupleIteration(state, unused);
}
static void setPrintPassesFile(const ArgumentState* state, const char* fileName) {
printPassesFile = fopen(fileName, "w");
if(printPassesFile == NULL) {
USR_WARN("Error opening printPassesFile: %s.", fileName);
}
}
/*
Flag types:
I = int
P = path
S = string
D = double
f = set to false
F = set to true
+ = increment
T = toggle
L = int64 (long)
N = --no-... flag, --no version sets to false
n = --no-... flag, --no version sets to true
Record components:
{"long option" (or "" for separators), 'short option', "description of option argument(s), if any", "option description", "option type", &affectedVariable, "environment variable name", setter_function},
*/
static ArgumentDescription arg_desc[] = {
{"", ' ', NULL, "Module Processing Options", NULL, NULL, NULL, NULL},
{"count-tokens", ' ', NULL, "[Don't] count tokens in main modules", "N", &countTokens, "CHPL_COUNT_TOKENS", NULL},
{"main-module", ' ', "<module>", "Specify entry point module", "S256", mainModuleName, NULL, NULL},
{"module-dir", 'M', "<directory>", "Add directory to module search path", "P", moduleSearchPath, NULL, addModulePath},
{"print-code-size", ' ', NULL, "[Don't] print code size of main modules", "N", &printTokens, "CHPL_PRINT_TOKENS", NULL},
{"print-module-files", ' ', NULL, "Print module file locations", "F", &printModuleFiles, NULL, NULL},
{"print-search-dirs", ' ', NULL, "[Don't] print module search path", "N", &printSearchDirs, "CHPL_PRINT_SEARCH_DIRS", NULL},
{"", ' ', NULL, "Parallelism Control Options", NULL, NULL, NULL, NULL},
{"local", ' ', NULL, "Target one [many] locale[s]", "N", &fLocal, "CHPL_LOCAL", NULL},
{"", ' ', NULL, "Optimization Control Options", NULL, NULL, NULL, NULL},
{"baseline", ' ', NULL, "Disable all Chapel optimizations", "F", &fBaseline, "CHPL_BASELINE", setBaselineFlag},
{"cache-remote", ' ', NULL, "Enable cache for remote data (must be enabled specifically)", "F", &fCacheRemote, "CHPL_CACHE_REMOTE", setCacheEnable},
{"conditional-dynamic-dispatch-limit", ' ', "<limit>", "Set limit on # of inline conditionals used for dynamic dispatch", "I", &fConditionalDynamicDispatchLimit, "CHPL_CONDITIONAL_DYNAMIC_DISPATCH_LIMIT", NULL},
{"copy-propagation", ' ', NULL, "Enable [disable] copy propagation", "n", &fNoCopyPropagation, "CHPL_DISABLE_COPY_PROPAGATION", NULL},
{"dead-code-elimination", ' ', NULL, "Enable [disable] dead code elimination", "n", &fNoDeadCodeElimination, "CHPL_DISABLE_DEAD_CODE_ELIMINATION", NULL},
{"fast", ' ', NULL, "Use fast default settings", "F", &fFastFlag, "CHPL_FAST", setFastFlag},
{"fast-followers", ' ', NULL, "Enable [disable] fast followers", "n", &fNoFastFollowers, "CHPL_DISABLE_FAST_FOLLOWERS", NULL},
{"ieee-float", ' ', NULL, "Generate code that is strict [lax] with respect to IEEE compliance", "N", &fieeefloat, "CHPL_IEEE_FLOAT", setFloatOptFlag},
{"ignore-local-classes", ' ', NULL, "Disable [enable] local classes", "N", &fIgnoreLocalClasses, NULL, NULL},
{"inline", ' ', NULL, "Enable [disable] function inlining", "n", &fNoInline, NULL, NULL},
{"inline-iterators", ' ', NULL, "Enable [disable] iterator inlining", "n", &fNoInlineIterators, "CHPL_DISABLE_INLINE_ITERATORS", NULL},
{"live-analysis", ' ', NULL, "Enable [disable] live variable analysis", "n", &fNoLiveAnalysis, "CHPL_DISABLE_LIVE_ANALYSIS", NULL},
{"loop-invariant-code-motion", ' ', NULL, "Enable [disable] loop invariant code motion", "n", &fNoloopInvariantCodeMotion, NULL, NULL},
{"optimize-loop-iterators", ' ', NULL, "Enable [disable] optimization of iterators composed of a single loop", "n", &fNoOptimizeLoopIterators, "CHPL_DISABLE_OPTIMIZE_LOOP_ITERATORS", NULL},
{"optimize-on-clauses", ' ', NULL, "Enable [disable] optimization of on clauses", "n", &fNoOptimizeOnClauses, "CHPL_DISABLE_OPTIMIZE_ON_CLAUSES", NULL},
{"optimize-on-clause-limit", ' ', "<limit>", "Limit recursion depth of on clause optimization search", "I", &optimize_on_clause_limit, "CHPL_OPTIMIZE_ON_CLAUSE_LIMIT", NULL},
{"privatization", ' ', NULL, "Enable [disable] privatization of distributed arrays and domains", "n", &fNoPrivatization, "CHPL_DISABLE_PRIVATIZATION", NULL},
{"remote-value-forwarding", ' ', NULL, "Enable [disable] remote value forwarding", "n", &fNoRemoteValueForwarding, "CHPL_DISABLE_REMOTE_VALUE_FORWARDING", NULL},
{"remove-copy-calls", ' ', NULL, "Enable [disable] remove copy calls", "n", &fNoRemoveCopyCalls, "CHPL_DISABLE_REMOVE_COPY_CALLS", NULL},
{"remove-wrap-records", ' ', NULL, "Enable [disable] wrap record removal", "n", &fNoRemoveWrapRecords, "CHPL_REMOVE_WRAP_RECORDS", NULL},
{"scalar-replacement", ' ', NULL, "Enable [disable] scalar replacement", "n", &fNoScalarReplacement, "CHPL_DISABLE_SCALAR_REPLACEMENT", NULL},
{"scalar-replace-limit", ' ', "<limit>", "Limit on the size of tuples being replaced during scalar replacement", "I", &scalar_replace_limit, "CHPL_SCALAR_REPLACE_TUPLE_LIMIT", NULL},
{"tuple-copy-opt", ' ', NULL, "Enable [disable] tuple (memcpy) optimization", "n", &fNoTupleCopyOpt, "CHPL_DISABLE_TUPLE_COPY_OPT", NULL},
{"tuple-copy-limit", ' ', "<limit>", "Limit on the size of tuples considered for optimization", "I", &tuple_copy_limit, "CHPL_TUPLE_COPY_LIMIT", NULL},
{"use-noinit", ' ', NULL, "Enable [disable] ability to skip default initialization through the keyword noinit", "N", &fUseNoinit, NULL, NULL},
{"vectorize", ' ', NULL, "Enable [disable] generation of vectorization hints", "n", &fNoVectorize, "CHPL_DISABLE_VECTORIZATION", NULL},
{"", ' ', NULL, "Run-time Semantic Check Options", NULL, NULL, NULL, NULL},
{"no-checks", ' ', NULL, "Disable all following run-time checks", "F", &fNoChecks, "CHPL_NO_CHECKS", turnOffChecks},
{"bounds-checks", ' ', NULL, "Enable [disable] bounds checking", "n", &fNoBoundsChecks, "CHPL_NO_BOUNDS_CHECKING", NULL},
{"local-checks", ' ', NULL, "Enable [disable] local block checking", "n", &fNoLocalChecks, NULL, NULL},
{"nil-checks", ' ', NULL, "Enable [disable] nil checking", "n", &fNoNilChecks, "CHPL_NO_NIL_CHECKS", NULL},
{"stack-checks", ' ', NULL, "Enable [disable] stack overflow checking", "n", &fNoStackChecks, "CHPL_STACK_CHECKS", handleStackCheck},
{"cast-checks", ' ', NULL, "Enable [disable] checks in safeCast calls", "n", &fNoCastChecks, NULL, NULL},
{"", ' ', NULL, "C Code Generation Options", NULL, NULL, NULL, NULL},
{"codegen", ' ', NULL, "[Don't] Do code generation", "n", &no_codegen, "CHPL_NO_CODEGEN", NULL},
{"cpp-lines", ' ', NULL, "[Don't] Generate #line annotations", "N", &printCppLineno, "CHPL_CG_CPP_LINES", noteCppLinesSet},
{"max-c-ident-len", ' ', NULL, "Maximum length of identifiers in generated code, 0 for unlimited", "I", &fMaxCIdentLen, "CHPL_MAX_C_IDENT_LEN", NULL},
{"munge-user-idents", ' ', NULL, "[Don't] Munge user identifiers to avoid naming conflicts with external code", "N", &fMungeUserIdents, "CHPL_MUNGE_USER_IDENTS"},
{"savec", ' ', "<directory>", "Save generated C code in directory", "P", saveCDir, "CHPL_SAVEC_DIR", verifySaveCDir},
{"", ' ', NULL, "C Code Compilation Options", NULL, NULL, NULL, NULL},
{"ccflags", ' ', "<flags>", "Back-end C compiler flags", "S", NULL, "CHPL_CC_FLAGS", setCCFlags},
{"debug", 'g', NULL, "[Don't] Support debugging of generated C code", "N", &debugCCode, "CHPL_DEBUG", setChapelDebug},
{"dynamic", ' ', NULL, "Generate a dynamically linked binary", "F", &fLinkStyle, NULL, setDynamicLink},
{"hdr-search-path", 'I', "<directory>", "C header search path", "P", incFilename, NULL, handleIncDir},
{"ldflags", ' ', "<flags>", "Back-end C linker flags", "S256", ldflags, "CHPL_LD_FLAGS", NULL},
{"lib-linkage", 'l', "<library>", "C library linkage", "P", libraryFilename, "CHPL_LIB_NAME", handleLibrary},
{"lib-search-path", 'L', "<directory>", "C library search path", "P", libraryFilename, "CHPL_LIB_PATH", handleLibPath},
{"make", ' ', "<make utility>", "Make utility for generated code", "S256", makeArgument, "CHPL_MAKE", handleMake},
{"optimize", 'O', NULL, "[Don't] Optimize generated C code", "N", &optimizeCCode, "CHPL_OPTIMIZE", NULL},
{"specialize", ' ', NULL, "[Don't] Specialize generated C code for CHPL_TARGET_ARCH", "N", &specializeCCode, "CHPL_SPECIALIZE", NULL},
{"output", 'o', "<filename>", "Name output executable", "P", executableFilename, "CHPL_EXE_NAME", NULL},
{"static", ' ', NULL, "Generate a statically linked binary", "F", &fLinkStyle, NULL, setStaticLink},
{"", ' ', NULL, "LLVM Code Generation Options", NULL, NULL, NULL, NULL},
{"llvm", ' ', NULL, "[Don't] use the LLVM code generator", "N", &llvmCodegen, "CHPL_LLVM_CODEGEN", NULL},
{"llvm-wide-opt", ' ', NULL, "Enable [disable] LLVM wide pointer optimizations", "N", &fLLVMWideOpt, "CHPL_LLVM_WIDE_OPTS", NULL},
{"", ' ', NULL, "Compilation Trace Options", NULL, NULL, NULL, NULL},
{"print-commands", ' ', NULL, "[Don't] print system commands", "N", &printSystemCommands, "CHPL_PRINT_COMMANDS", NULL},
{"print-passes", ' ', NULL, "[Don't] print compiler passes", "N", &printPasses, "CHPL_PRINT_PASSES", NULL},
{"print-passes-file", ' ', "<filename>", "Print compiler passes to <filename>", "S", NULL, "CHPL_PRINT_PASSES_FILE", setPrintPassesFile},
{"", ' ', NULL, "Miscellaneous Options", NULL, NULL, NULL, NULL},
// Support for extern { c-code-here } blocks could be toggled with this
// flag, but instead we just leave it on if the compiler can do it.
// {"extern-c", ' ', NULL, "Enable [disable] extern C block support", "f", &externC, "CHPL_EXTERN_C", NULL},
DRIVER_ARG_DEVELOPER,
{"explain-call", ' ', "<call>[:<module>][:<line>]", "Explain resolution of call", "S256", fExplainCall, NULL, NULL},
{"explain-instantiation", ' ', "<function|type>[:<module>][:<line>]", "Explain instantiation of type", "S256", fExplainInstantiation, NULL, NULL},
{"explain-verbose", ' ', NULL, "Enable [disable] tracing of disambiguation with 'explain' options", "N", &fExplainVerbose, "CHPL_EXPLAIN_VERBOSE", NULL},
{"instantiate-max", ' ', "<max>", "Limit number of instantiations", "I", &instantiation_limit, "CHPL_INSTANTIATION_LIMIT", NULL},
{"print-callstack-on-error", ' ', NULL, "print the Chapel call stack leading to each error or warning", "N", &fPrintCallStackOnError, "CHPL_PRINT_CALLSTACK_ON_ERROR", NULL},
{"set", 's', "<name>[=<value>]", "Set config param value", "S", NULL, NULL, readConfig},
{"task-tracking", ' ', NULL, "Enable [disable] runtime task tracking", "N", &fEnableTaskTracking, "CHPL_TASK_TRACKING", handleTaskTracking},
{"warn-const-loops", ' ', NULL, "Enable [disable] warnings for some 'while' loops with constant conditions", "N", &fWarnConstLoops, "CHPL_WARN_CONST_LOOPS", NULL},
{"warn-special", ' ', NULL, "Enable [disable] special warnings", "n", &fNoWarnSpecial, "CHPL_WARN_SPECIAL", setWarnSpecial},
{"warn-domain-literal", ' ', NULL, "Enable [disable] old domain literal syntax warnings", "n", &fNoWarnDomainLiteral, "CHPL_WARN_DOMAIN_LITERAL", setWarnDomainLiteral},
{"warn-tuple-iteration", ' ', NULL, "Enable [disable] warnings for tuple iteration", "n", &fNoWarnTupleIteration, "CHPL_WARN_TUPLE_ITERATION", setWarnTupleIteration},
{"no-warnings", ' ', NULL, "Disable output of warnings", "F", &ignore_warnings, "CHPL_DISABLE_WARNINGS", NULL},
{"", ' ', NULL, "Compiler Information Options", NULL, NULL, NULL, NULL},
DRIVER_ARG_COPYRIGHT,
DRIVER_ARG_HELP,
DRIVER_ARG_HELP_ENV,
DRIVER_ARG_HELP_SETTINGS,
DRIVER_ARG_LICENSE,
DRIVER_ARG_VERSION,
{"", ' ', NULL, "Developer Flags -- Debug Output", NULL, NULL, NULL, NULL},
{"cc-warnings", ' ', NULL, "[Don't] Give warnings for generated code", "N", &ccwarnings, "CHPL_CC_WARNINGS", NULL},
{"c-line-numbers", ' ', NULL, "Use C code line numbers and filenames", "F", &fCLineNumbers, NULL, NULL},
{"gen-ids", ' ', NULL, "[Don't] pepper generated code with BaseAST::ids", "N", &fGenIDS, "CHPL_GEN_IDS", NULL},
{"html", 't', NULL, "Dump IR in HTML format (toggle)", "T", &fdump_html, "CHPL_HTML", NULL},
{"html-user", ' ', NULL, "Dump IR in HTML for user module(s) only (toggle)", "T", &fdump_html, "CHPL_HTML_USER", setHtmlUser},
{"html-wrap-lines", ' ', NULL, "[Don't] allow wrapping lines in HTML dumps", "N", &fdump_html_wrap_lines, "CHPL_HTML_WRAP_LINES", NULL},
{"html-print-block-ids", ' ', NULL, "[Don't] print block IDs in HTML dumps", "N", &fdump_html_print_block_IDs, "CHPL_HTML_PRINT_BLOCK_IDS", NULL},
{"html-chpl-home", ' ', NULL, "Path to use instead of CHPL_HOME in HTML dumps", "P", fdump_html_chpl_home, "CHPL_HTML_CHPL_HOME", NULL},
{"log", 'd', "<letters>", "Dump IR in text format. See runpasses.cpp for definition of <letters>. Empty argument (\"-d=\" or \"--log=\") means \"log all passes\"", "S512", log_flags, "CHPL_LOG_FLAGS", log_flags_arg},
{"log-dir", ' ', "<path>", "Specify log directory", "P", log_dir, "CHPL_LOG_DIR", NULL},
{"log-ids", ' ', NULL, "[Don't] include BaseAST::ids in log files", "N", &fLogIds, "CHPL_LOG_IDS", NULL},
{"log-module", ' ', "<module-name>", "Restrict IR dump to the named module", "S256", log_module, "CHPL_LOG_MODULE", NULL},
// {"log-symbol", ' ', "<symbol-name>", "Restrict IR dump to the named symbol(s)", "S256", log_symbol, "CHPL_LOG_SYMBOL", NULL}, // This doesn't work yet.
{"verify", ' ', NULL, "Run consistency checks during compilation", "N", &fVerify, "CHPL_VERIFY", NULL},
{"parser-debug", 'D', NULL, "Set parser debug level", "+", &debugParserLevel, "CHPL_PARSER_DEBUG", NULL},
{"debug-short-loc", ' ', NULL, "Display long [short] location in certain debug outputs", "N", &debugShortLoc, "CHPL_DEBUG_SHORT_LOC", NULL},
{"print-emitted-code-size", ' ', NULL, "Print emitted code size", "F", &fPrintEmittedCodeSize, NULL, NULL},
{"print-module-resolution", ' ', NULL, "Print name of module being resolved", "F", &fPrintModuleResolution, "CHPL_PRINT_MODULE_RESOLUTION", NULL},
{"print-dispatch", ' ', NULL, "Print dynamic dispatch table", "F", &fPrintDispatch, NULL, NULL},
{"print-statistics", ' ', "[n|k|t]", "Print AST statistics", "S256", fPrintStatistics, NULL, NULL},
{"report-inlining", ' ', NULL, "Print inlined functions", "F", &report_inlining, NULL, NULL},
{"report-dead-blocks", ' ', NULL, "Print dead block removal stats", "F", &fReportDeadBlocks, NULL, NULL},
{"report-dead-modules", ' ', NULL, "Print dead module removal stats", "F", &fReportDeadModules, NULL, NULL},
{"report-optimized-loop-iterators", ' ', NULL, "Print stats on optimized single loop iterators", "F", &fReportOptimizedLoopIterators, NULL, NULL},
{"report-order-independent-loops", ' ', NULL, "Print stats on order independent loops", "F", &fReportOrderIndependentLoops, NULL, NULL},
{"report-optimized-on", ' ', NULL, "Print information about on clauses that have been optimized for potential fast remote fork operation", "F", &fReportOptimizedOn, NULL, NULL},
{"report-promotion", ' ', NULL, "Print information about scalar promotion", "F", &fReportPromotion, NULL, NULL},
{"report-scalar-replace", ' ', NULL, "Print scalar replacement stats", "F", &fReportScalarReplace, NULL, NULL},
{"", ' ', NULL, "Developer Flags -- Miscellaneous", NULL, NULL, NULL, NULL},
{"break-on-id", ' ', NULL, "Break when AST id is created", "I", &breakOnID, "CHPL_BREAK_ON_ID", NULL},
{"break-on-delete-id", ' ', NULL, "Break when AST id is deleted", "I", &breakOnDeleteID, "CHPL_BREAK_ON_DELETE_ID", NULL},
{"break-on-codegen", ' ', NULL, "Break when function cname is code generated", "S256", &breakOnCodegenCname, "CHPL_BREAK_ON_CODEGEN", NULL},
{"default-dist", ' ', "<distribution>", "Change the default distribution", "S256", defaultDist, "CHPL_DEFAULT_DIST", NULL},
{"explain-call-id", ' ', "<call-id>", "Explain resolution of call by ID", "I", &explainCallID, NULL, NULL},
{"break-on-resolve-id", ' ', NULL, "Break when function call with AST id is resolved", "I", &breakOnResolveID, "CHPL_BREAK_ON_RESOLVE_ID", NULL},
DRIVER_ARG_DEBUGGERS,
{"heterogeneous", ' ', NULL, "Compile for heterogeneous nodes", "F", &fHeterogeneous, "", NULL},
{"ignore-errors", ' ', NULL, "[Don't] attempt to ignore errors", "N", &ignore_errors, "CHPL_IGNORE_ERRORS", NULL},
{"ignore-errors-for-pass", ' ', NULL, "[Don't] attempt to ignore errors until the end of the pass in which they occur", "N", &ignore_errors_for_pass, "CHPL_IGNORE_ERRORS_FOR_PASS", NULL},
{"library", ' ', NULL, "Generate a Chapel library file", "F", &fLibraryCompile, NULL, NULL},
{"localize-global-consts", ' ', NULL, "Enable [disable] optimization of global constants", "n", &fNoGlobalConstOpt, "CHPL_DISABLE_GLOBAL_CONST_OPT", NULL},
{"local-temp-names", ' ', NULL, "[Don't] Generate locally-unique temp names", "N", &localTempNames, "CHPL_LOCAL_TEMP_NAMES", NULL},
{"log-deleted-ids-to", ' ', "<filename>", "Log AST id and memory address of each deleted node to the specified file", "P", deletedIdFilename, "CHPL_DELETED_ID_FILENAME", NULL},
{"memory-frees", ' ', NULL, "Enable [disable] memory frees in the generated code", "n", &fNoMemoryFrees, "CHPL_DISABLE_MEMORY_FREES", NULL},
{"preserve-inlined-line-numbers", ' ', NULL, "[Don't] Preserve file names/line numbers in inlined code", "N", &preserveInlinedLineNumbers, "CHPL_PRESERVE_INLINED_LINE_NUMBERS", NULL},
{"print-id-on-error", ' ', NULL, "[Don't] print AST id in error messages", "N", &fPrintIDonError, "CHPL_PRINT_ID_ON_ERROR", NULL},
{"remove-empty-records", ' ', NULL, "Enable [disable] empty record removal", "n", &fNoRemoveEmptyRecords, "CHPL_DISABLE_REMOVE_EMPTY_RECORDS", NULL},
{"remove-unreachable-blocks", ' ', NULL, "[Don't] remove unreachable blocks after resolution", "N", &fRemoveUnreachableBlocks, "CHPL_REMOVE_UNREACHABLE_BLOCKS", NULL},
{"minimal-modules", ' ', NULL, "Enable [disable] using minimal modules", "N", &fMinimalModules, "CHPL_MINIMAL_MODULES", NULL},
DRIVER_ARG_PRINT_CHPL_HOME,
DRIVER_ARG_LAST
};
static ArgumentState sArgState = {
0,
0,
"program",
"path",
NULL
};
static void setupDependentVars() {
if (developer && !userSetCppLineno) {
printCppLineno = false;
}
#ifndef HAVE_LLVM
if (llvmCodegen)
USR_FATAL("This compiler was built without LLVM support");
#endif
if (specializeCCode && (strcmp(CHPL_TARGET_ARCH, "unknown") == 0)) {
USR_WARN("--specialize was set, but CHPL_TARGET_ARCH is 'unknown'. If "
"you want any specialization to occur please set CHPL_TARGET_ARCH "
"to a proper value.");
}
}
static void printStuff(const char* argv0) {
bool shouldExit = false;
bool printedSomething = false;
if (fPrintVersion) {
fprintf(stdout, "%s Version %s\n", sArgState.program_name, compileVersion);
fPrintCopyright = true;
printedSomething = true;
shouldExit = true;
}
if (fPrintLicense) {
fprintf(stdout,
#include "LICENSE"
);
fPrintCopyright = false;
shouldExit = true;
printedSomething = true;
}
if (fPrintCopyright) {
fprintf(stdout,
#include "COPYRIGHT"
);
printedSomething = true;
}
if( fPrintChplHome ) {
char* guess = findProgramPath(argv0);
printf("%s\t%s\n", CHPL_HOME, guess);
free(guess);
printedSomething = true;
}
if (fPrintHelp || (!printedSomething && sArgState.nfile_arguments < 1)) {
if (printedSomething) printf("\n");
usage(&sArgState, !fPrintHelp, fPrintEnvHelp, fPrintSettingsHelp);
shouldExit = true;
printedSomething = true;
}
if (printedSomething && sArgState.nfile_arguments < 1) {
shouldExit = true;
}
if (shouldExit) {
clean_exit(0);
}
}
int main(int argc, char* argv[]) {
PhaseTracker tracker;
startCatchingSignals();
{
astlocMarker markAstLoc(0, "<internal>");
tracker.StartPhase("init");
init_args(&sArgState, argv[0]);
fDocs = (strcmp(sArgState.program_name, "chpldoc") == 0) ? true : false;
fUseIPE = (strcmp(sArgState.program_name, "chpl-ipe") == 0) ? true : false;
// Initialize the arguments for argument state. If chpldoc, use the docs
// specific arguments. Otherwise, use the regular arguments.
if (fDocs) {
init_arg_desc(&sArgState, docs_arg_desc);
} else {
init_arg_desc(&sArgState, arg_desc);
}
initFlags();
initRootModule();
initPrimitive();
initPrimitiveTypes();
DefExpr* objectClass = defineObjectClass();
initChplProgram(objectClass);
initStringLiteralModule();
setupOrderedGlobals(argv[0]);
process_args(&sArgState, argc, argv);
initCompilerGlobals(); // must follow argument parsing
setupDependentVars();
setupModulePaths();
recordCodeGenStrings(argc, argv);
} // astlocMarker scope
if (fUseIPE == false)
printStuff(argv[0]);
if (fRungdb)
runCompilerInGDB(argc, argv);
if (fRunlldb)
runCompilerInLLDB(argc, argv);
addSourceFiles(sArgState.nfile_arguments, sArgState.file_argument);
if (fUseIPE == false) {
runPasses(tracker, fDocs);
} else {
ipeRun();
}
tracker.StartPhase("driverCleanup");
free_args(&sArgState);
tracker.Stop();
if (printPasses == true || printPassesFile != NULL) {
tracker.ReportPass();
tracker.ReportTotal();
tracker.ReportRollup();
}
if (printPassesFile != NULL) {
fclose(printPassesFile);
}
clean_exit(0);
return 0;
}
|
hildeth/chapel
|
compiler/main/driver.cpp
|
C++
|
apache-2.0
| 41,155 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.io.hfile;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hbase.ByteBufferCell;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellComparator;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.KeyValueUtil;
import org.apache.hadoop.hbase.CellComparator.MetaCellComparator;
import org.apache.yetus.audience.InterfaceAudience;
import org.apache.hadoop.hbase.io.compress.Compression;
import org.apache.hadoop.hbase.io.crypto.Encryption;
import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding;
import org.apache.hadoop.hbase.io.hfile.HFile.FileInfo;
import org.apache.hadoop.hbase.io.hfile.HFileBlock.BlockWritable;
import org.apache.hadoop.hbase.security.EncryptionUtil;
import org.apache.hadoop.hbase.security.User;
import org.apache.hadoop.hbase.util.BloomFilterWriter;
import org.apache.hadoop.hbase.util.ByteBufferUtils;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.FSUtils;
import org.apache.hadoop.io.Writable;
/**
* Common functionality needed by all versions of {@link HFile} writers.
*/
@InterfaceAudience.Private
public class HFileWriterImpl implements HFile.Writer {
private static final Log LOG = LogFactory.getLog(HFileWriterImpl.class);
private static final long UNSET = -1;
/** if this feature is enabled, preCalculate encoded data size before real encoding happens*/
public static final String UNIFIED_ENCODED_BLOCKSIZE_RATIO = "hbase.writer.unified.encoded.blocksize.ratio";
/** Block size limit after encoding, used to unify encoded block Cache entry size*/
private final int encodedBlockSizeLimit;
/** The Cell previously appended. Becomes the last cell in the file.*/
protected Cell lastCell = null;
/** FileSystem stream to write into. */
protected FSDataOutputStream outputStream;
/** True if we opened the <code>outputStream</code> (and so will close it). */
protected final boolean closeOutputStream;
/** A "file info" block: a key-value map of file-wide metadata. */
protected FileInfo fileInfo = new HFile.FileInfo();
/** Total # of key/value entries, i.e. how many times add() was called. */
protected long entryCount = 0;
/** Used for calculating the average key length. */
protected long totalKeyLength = 0;
/** Used for calculating the average value length. */
protected long totalValueLength = 0;
/** Total uncompressed bytes, maybe calculate a compression ratio later. */
protected long totalUncompressedBytes = 0;
/** Key comparator. Used to ensure we write in order. */
protected final CellComparator comparator;
/** Meta block names. */
protected List<byte[]> metaNames = new ArrayList<>();
/** {@link Writable}s representing meta block data. */
protected List<Writable> metaData = new ArrayList<>();
/**
* First cell in a block.
* This reference should be short-lived since we write hfiles in a burst.
*/
protected Cell firstCellInBlock = null;
/** May be null if we were passed a stream. */
protected final Path path;
/** Cache configuration for caching data on write. */
protected final CacheConfig cacheConf;
/**
* Name for this object used when logging or in toString. Is either
* the result of a toString on stream or else name of passed file Path.
*/
protected final String name;
/**
* The data block encoding which will be used.
* {@link NoOpDataBlockEncoder#INSTANCE} if there is no encoding.
*/
protected final HFileDataBlockEncoder blockEncoder;
protected final HFileContext hFileContext;
private int maxTagsLength = 0;
/** KeyValue version in FileInfo */
public static final byte [] KEY_VALUE_VERSION = Bytes.toBytes("KEY_VALUE_VERSION");
/** Version for KeyValue which includes memstore timestamp */
public static final int KEY_VALUE_VER_WITH_MEMSTORE = 1;
/** Inline block writers for multi-level block index and compound Blooms. */
private List<InlineBlockWriter> inlineBlockWriters = new ArrayList<>();
/** block writer */
protected HFileBlock.Writer blockWriter;
private HFileBlockIndex.BlockIndexWriter dataBlockIndexWriter;
private HFileBlockIndex.BlockIndexWriter metaBlockIndexWriter;
/** The offset of the first data block or -1 if the file is empty. */
private long firstDataBlockOffset = UNSET;
/** The offset of the last data block or 0 if the file is empty. */
protected long lastDataBlockOffset = UNSET;
/**
* The last(stop) Cell of the previous data block.
* This reference should be short-lived since we write hfiles in a burst.
*/
private Cell lastCellOfPreviousBlock = null;
/** Additional data items to be written to the "load-on-open" section. */
private List<BlockWritable> additionalLoadOnOpenData = new ArrayList<>();
protected long maxMemstoreTS = 0;
public HFileWriterImpl(final Configuration conf, CacheConfig cacheConf, Path path,
FSDataOutputStream outputStream,
CellComparator comparator, HFileContext fileContext) {
this.outputStream = outputStream;
this.path = path;
this.name = path != null ? path.getName() : outputStream.toString();
this.hFileContext = fileContext;
DataBlockEncoding encoding = hFileContext.getDataBlockEncoding();
if (encoding != DataBlockEncoding.NONE) {
this.blockEncoder = new HFileDataBlockEncoderImpl(encoding);
} else {
this.blockEncoder = NoOpDataBlockEncoder.INSTANCE;
}
this.comparator = comparator != null? comparator: CellComparator.COMPARATOR;
closeOutputStream = path != null;
this.cacheConf = cacheConf;
float encodeBlockSizeRatio = conf.getFloat(UNIFIED_ENCODED_BLOCKSIZE_RATIO, 1f);
this.encodedBlockSizeLimit = (int)(hFileContext.getBlocksize() * encodeBlockSizeRatio);
finishInit(conf);
if (LOG.isTraceEnabled()) {
LOG.trace("Writer" + (path != null ? " for " + path : "") +
" initialized with cacheConf: " + cacheConf +
" comparator: " + comparator.getClass().getSimpleName() +
" fileContext: " + fileContext);
}
}
/**
* Add to the file info. All added key/value pairs can be obtained using
* {@link HFile.Reader#loadFileInfo()}.
*
* @param k Key
* @param v Value
* @throws IOException in case the key or the value are invalid
*/
@Override
public void appendFileInfo(final byte[] k, final byte[] v)
throws IOException {
fileInfo.append(k, v, true);
}
/**
* Sets the file info offset in the trailer, finishes up populating fields in
* the file info, and writes the file info into the given data output. The
* reason the data output is not always {@link #outputStream} is that we store
* file info as a block in version 2.
*
* @param trailer fixed file trailer
* @param out the data output to write the file info to
* @throws IOException
*/
protected final void writeFileInfo(FixedFileTrailer trailer, DataOutputStream out)
throws IOException {
trailer.setFileInfoOffset(outputStream.getPos());
finishFileInfo();
long startTime = System.currentTimeMillis();
fileInfo.write(out);
HFile.updateWriteLatency(System.currentTimeMillis() - startTime);
}
/**
* Checks that the given Cell's key does not violate the key order.
*
* @param cell Cell whose key to check.
* @return true if the key is duplicate
* @throws IOException if the key or the key order is wrong
*/
protected boolean checkKey(final Cell cell) throws IOException {
boolean isDuplicateKey = false;
if (cell == null) {
throw new IOException("Key cannot be null or empty");
}
if (lastCell != null) {
int keyComp = comparator.compareKeyIgnoresMvcc(lastCell, cell);
if (keyComp > 0) {
throw new IOException("Added a key not lexically larger than"
+ " previous. Current cell = " + cell + ", lastCell = " + lastCell);
} else if (keyComp == 0) {
isDuplicateKey = true;
}
}
return isDuplicateKey;
}
/** Checks the given value for validity. */
protected void checkValue(final byte[] value, final int offset,
final int length) throws IOException {
if (value == null) {
throw new IOException("Value cannot be null");
}
}
/**
* @return Path or null if we were passed a stream rather than a Path.
*/
@Override
public Path getPath() {
return path;
}
@Override
public String toString() {
return "writer=" + (path != null ? path.toString() : null) + ", name="
+ name + ", compression=" + hFileContext.getCompression().getName();
}
public static Compression.Algorithm compressionByName(String algoName) {
if (algoName == null)
return HFile.DEFAULT_COMPRESSION_ALGORITHM;
return Compression.getCompressionAlgorithmByName(algoName);
}
/** A helper method to create HFile output streams in constructors */
protected static FSDataOutputStream createOutputStream(Configuration conf,
FileSystem fs, Path path, InetSocketAddress[] favoredNodes) throws IOException {
FsPermission perms = FSUtils.getFilePermissions(fs, conf,
HConstants.DATA_FILE_UMASK_KEY);
return FSUtils.create(conf, fs, path, perms, favoredNodes);
}
/** Additional initialization steps */
protected void finishInit(final Configuration conf) {
if (blockWriter != null) {
throw new IllegalStateException("finishInit called twice");
}
blockWriter = new HFileBlock.Writer(blockEncoder, hFileContext);
// Data block index writer
boolean cacheIndexesOnWrite = cacheConf.shouldCacheIndexesOnWrite();
dataBlockIndexWriter = new HFileBlockIndex.BlockIndexWriter(blockWriter,
cacheIndexesOnWrite ? cacheConf : null,
cacheIndexesOnWrite ? name : null);
dataBlockIndexWriter.setMaxChunkSize(
HFileBlockIndex.getMaxChunkSize(conf));
dataBlockIndexWriter.setMinIndexNumEntries(
HFileBlockIndex.getMinIndexNumEntries(conf));
inlineBlockWriters.add(dataBlockIndexWriter);
// Meta data block index writer
metaBlockIndexWriter = new HFileBlockIndex.BlockIndexWriter();
if (LOG.isTraceEnabled()) LOG.trace("Initialized with " + cacheConf);
}
/**
* At a block boundary, write all the inline blocks and opens new block.
*
* @throws IOException
*/
protected void checkBlockBoundary() throws IOException {
//for encoder like prefixTree, encoded size is not available, so we have to compare both encoded size
//and unencoded size to blocksize limit.
if (blockWriter.encodedBlockSizeWritten() >= encodedBlockSizeLimit
|| blockWriter.blockSizeWritten() >= hFileContext.getBlocksize()) {
finishBlock();
writeInlineBlocks(false);
newBlock();
}
}
/** Clean up the data block that is currently being written.*/
private void finishBlock() throws IOException {
if (!blockWriter.isWriting() || blockWriter.blockSizeWritten() == 0) return;
// Update the first data block offset if UNSET; used scanning.
if (firstDataBlockOffset == UNSET) {
firstDataBlockOffset = outputStream.getPos();
}
// Update the last data block offset each time through here.
lastDataBlockOffset = outputStream.getPos();
blockWriter.writeHeaderAndData(outputStream);
int onDiskSize = blockWriter.getOnDiskSizeWithHeader();
Cell indexEntry =
getMidpoint(this.comparator, lastCellOfPreviousBlock, firstCellInBlock);
dataBlockIndexWriter.addEntry(CellUtil.getCellKeySerializedAsKeyValueKey(indexEntry),
lastDataBlockOffset, onDiskSize);
totalUncompressedBytes += blockWriter.getUncompressedSizeWithHeader();
if (cacheConf.shouldCacheDataOnWrite()) {
doCacheOnWrite(lastDataBlockOffset);
}
}
/**
* Try to return a Cell that falls between <code>left</code> and
* <code>right</code> but that is shorter; i.e. takes up less space. This
* trick is used building HFile block index. Its an optimization. It does not
* always work. In this case we'll just return the <code>right</code> cell.
*
* @param comparator
* Comparator to use.
* @param left
* @param right
* @return A cell that sorts between <code>left</code> and <code>right</code>.
*/
public static Cell getMidpoint(final CellComparator comparator, final Cell left,
final Cell right) {
// TODO: Redo so only a single pass over the arrays rather than one to
// compare and then a second composing midpoint.
if (right == null) {
throw new IllegalArgumentException("right cell can not be null");
}
if (left == null) {
return right;
}
// If Cells from meta table, don't mess around. meta table Cells have schema
// (table,startrow,hash) so can't be treated as plain byte arrays. Just skip
// out without trying to do this optimization.
if (comparator instanceof MetaCellComparator) {
return right;
}
int diff = comparator.compareRows(left, right);
if (diff > 0) {
throw new IllegalArgumentException("Left row sorts after right row; left="
+ CellUtil.getCellKeyAsString(left) + ", right=" + CellUtil.getCellKeyAsString(right));
}
byte[] midRow;
boolean bufferBacked = left instanceof ByteBufferCell && right instanceof ByteBufferCell;
if (diff < 0) {
// Left row is < right row.
if (bufferBacked) {
midRow = getMinimumMidpointArray(((ByteBufferCell) left).getRowByteBuffer(),
((ByteBufferCell) left).getRowPosition(), left.getRowLength(),
((ByteBufferCell) right).getRowByteBuffer(),
((ByteBufferCell) right).getRowPosition(), right.getRowLength());
} else {
midRow = getMinimumMidpointArray(left.getRowArray(), left.getRowOffset(),
left.getRowLength(), right.getRowArray(), right.getRowOffset(), right.getRowLength());
}
// If midRow is null, just return 'right'. Can't do optimization.
if (midRow == null) return right;
return CellUtil.createFirstOnRow(midRow);
}
// Rows are same. Compare on families.
diff = CellComparator.compareFamilies(left, right);
if (diff > 0) {
throw new IllegalArgumentException("Left family sorts after right family; left="
+ CellUtil.getCellKeyAsString(left) + ", right=" + CellUtil.getCellKeyAsString(right));
}
if (diff < 0) {
if (bufferBacked) {
midRow = getMinimumMidpointArray(((ByteBufferCell) left).getFamilyByteBuffer(),
((ByteBufferCell) left).getFamilyPosition(), left.getFamilyLength(),
((ByteBufferCell) right).getFamilyByteBuffer(),
((ByteBufferCell) right).getFamilyPosition(), right.getFamilyLength());
} else {
midRow = getMinimumMidpointArray(left.getFamilyArray(), left.getFamilyOffset(),
left.getFamilyLength(), right.getFamilyArray(), right.getFamilyOffset(),
right.getFamilyLength());
}
// If midRow is null, just return 'right'. Can't do optimization.
if (midRow == null) return right;
// Return new Cell where we use right row and then a mid sort family.
return CellUtil.createFirstOnRowFamily(right, midRow, 0, midRow.length);
}
// Families are same. Compare on qualifiers.
diff = CellComparator.compareQualifiers(left, right);
if (diff > 0) {
throw new IllegalArgumentException("Left qualifier sorts after right qualifier; left="
+ CellUtil.getCellKeyAsString(left) + ", right=" + CellUtil.getCellKeyAsString(right));
}
if (diff < 0) {
if (bufferBacked) {
midRow = getMinimumMidpointArray(((ByteBufferCell) left).getQualifierByteBuffer(),
((ByteBufferCell) left).getQualifierPosition(), left.getQualifierLength(),
((ByteBufferCell) right).getQualifierByteBuffer(),
((ByteBufferCell) right).getQualifierPosition(), right.getQualifierLength());
} else {
midRow = getMinimumMidpointArray(left.getQualifierArray(), left.getQualifierOffset(),
left.getQualifierLength(), right.getQualifierArray(), right.getQualifierOffset(),
right.getQualifierLength());
}
// If midRow is null, just return 'right'. Can't do optimization.
if (midRow == null) return right;
// Return new Cell where we use right row and family and then a mid sort qualifier.
return CellUtil.createFirstOnRowCol(right, midRow, 0, midRow.length);
}
// No opportunity for optimization. Just return right key.
return right;
}
/**
* @param leftArray
* @param leftOffset
* @param leftLength
* @param rightArray
* @param rightOffset
* @param rightLength
* @return Return a new array that is between left and right and minimally
* sized else just return null as indicator that we could not create a
* mid point.
*/
private static byte[] getMinimumMidpointArray(final byte[] leftArray, final int leftOffset,
final int leftLength, final byte[] rightArray, final int rightOffset, final int rightLength) {
// rows are different
int minLength = leftLength < rightLength ? leftLength : rightLength;
int diffIdx = 0;
while (diffIdx < minLength
&& leftArray[leftOffset + diffIdx] == rightArray[rightOffset + diffIdx]) {
diffIdx++;
}
byte[] minimumMidpointArray = null;
if (diffIdx >= minLength) {
// leftKey's row is prefix of rightKey's.
minimumMidpointArray = new byte[diffIdx + 1];
System.arraycopy(rightArray, rightOffset, minimumMidpointArray, 0, diffIdx + 1);
} else {
int diffByte = leftArray[leftOffset + diffIdx];
if ((0xff & diffByte) < 0xff && (diffByte + 1) < (rightArray[rightOffset + diffIdx] & 0xff)) {
minimumMidpointArray = new byte[diffIdx + 1];
System.arraycopy(leftArray, leftOffset, minimumMidpointArray, 0, diffIdx);
minimumMidpointArray[diffIdx] = (byte) (diffByte + 1);
} else {
minimumMidpointArray = new byte[diffIdx + 1];
System.arraycopy(rightArray, rightOffset, minimumMidpointArray, 0, diffIdx + 1);
}
}
return minimumMidpointArray;
}
private static byte[] getMinimumMidpointArray(ByteBuffer left, int leftOffset, int leftLength,
ByteBuffer right, int rightOffset, int rightLength) {
// rows are different
int minLength = leftLength < rightLength ? leftLength : rightLength;
int diffIdx = 0;
while (diffIdx < minLength && ByteBufferUtils.toByte(left,
leftOffset + diffIdx) == ByteBufferUtils.toByte(right, rightOffset + diffIdx)) {
diffIdx++;
}
byte[] minMidpoint = null;
if (diffIdx >= minLength) {
// leftKey's row is prefix of rightKey's.
minMidpoint = new byte[diffIdx + 1];
ByteBufferUtils.copyFromBufferToArray(minMidpoint, right, rightOffset, 0, diffIdx + 1);
} else {
int diffByte = ByteBufferUtils.toByte(left, leftOffset + diffIdx);
if ((0xff & diffByte) < 0xff
&& (diffByte + 1) < (ByteBufferUtils.toByte(right, rightOffset + diffIdx) & 0xff)) {
minMidpoint = new byte[diffIdx + 1];
ByteBufferUtils.copyFromBufferToArray(minMidpoint, left, leftOffset, 0, diffIdx);
minMidpoint[diffIdx] = (byte) (diffByte + 1);
} else {
minMidpoint = new byte[diffIdx + 1];
ByteBufferUtils.copyFromBufferToArray(minMidpoint, right, rightOffset, 0, diffIdx + 1);
}
}
return minMidpoint;
}
/** Gives inline block writers an opportunity to contribute blocks. */
private void writeInlineBlocks(boolean closing) throws IOException {
for (InlineBlockWriter ibw : inlineBlockWriters) {
while (ibw.shouldWriteBlock(closing)) {
long offset = outputStream.getPos();
boolean cacheThisBlock = ibw.getCacheOnWrite();
ibw.writeInlineBlock(blockWriter.startWriting(
ibw.getInlineBlockType()));
blockWriter.writeHeaderAndData(outputStream);
ibw.blockWritten(offset, blockWriter.getOnDiskSizeWithHeader(),
blockWriter.getUncompressedSizeWithoutHeader());
totalUncompressedBytes += blockWriter.getUncompressedSizeWithHeader();
if (cacheThisBlock) {
doCacheOnWrite(offset);
}
}
}
}
/**
* Caches the last written HFile block.
* @param offset the offset of the block we want to cache. Used to determine
* the cache key.
*/
private void doCacheOnWrite(long offset) {
HFileBlock cacheFormatBlock = blockWriter.getBlockForCaching(cacheConf);
cacheConf.getBlockCache().cacheBlock(
new BlockCacheKey(name, offset, true, cacheFormatBlock.getBlockType()),
cacheFormatBlock);
}
/**
* Ready a new block for writing.
*
* @throws IOException
*/
protected void newBlock() throws IOException {
// This is where the next block begins.
blockWriter.startWriting(BlockType.DATA);
firstCellInBlock = null;
if (lastCell != null) {
lastCellOfPreviousBlock = lastCell;
}
}
/**
* Add a meta block to the end of the file. Call before close(). Metadata
* blocks are expensive. Fill one with a bunch of serialized data rather than
* do a metadata block per metadata instance. If metadata is small, consider
* adding to file info using {@link #appendFileInfo(byte[], byte[])}
*
* @param metaBlockName
* name of the block
* @param content
* will call readFields to get data later (DO NOT REUSE)
*/
@Override
public void appendMetaBlock(String metaBlockName, Writable content) {
byte[] key = Bytes.toBytes(metaBlockName);
int i;
for (i = 0; i < metaNames.size(); ++i) {
// stop when the current key is greater than our own
byte[] cur = metaNames.get(i);
if (Bytes.BYTES_RAWCOMPARATOR.compare(cur, 0, cur.length, key, 0,
key.length) > 0) {
break;
}
}
metaNames.add(i, key);
metaData.add(i, content);
}
@Override
public void close() throws IOException {
if (outputStream == null) {
return;
}
// Save data block encoder metadata in the file info.
blockEncoder.saveMetadata(this);
// Write out the end of the data blocks, then write meta data blocks.
// followed by fileinfo, data block index and meta block index.
finishBlock();
writeInlineBlocks(true);
FixedFileTrailer trailer = new FixedFileTrailer(getMajorVersion(), getMinorVersion());
// Write out the metadata blocks if any.
if (!metaNames.isEmpty()) {
for (int i = 0; i < metaNames.size(); ++i) {
// store the beginning offset
long offset = outputStream.getPos();
// write the metadata content
DataOutputStream dos = blockWriter.startWriting(BlockType.META);
metaData.get(i).write(dos);
blockWriter.writeHeaderAndData(outputStream);
totalUncompressedBytes += blockWriter.getUncompressedSizeWithHeader();
// Add the new meta block to the meta index.
metaBlockIndexWriter.addEntry(metaNames.get(i), offset,
blockWriter.getOnDiskSizeWithHeader());
}
}
// Load-on-open section.
// Data block index.
//
// In version 2, this section of the file starts with the root level data
// block index. We call a function that writes intermediate-level blocks
// first, then root level, and returns the offset of the root level block
// index.
long rootIndexOffset = dataBlockIndexWriter.writeIndexBlocks(outputStream);
trailer.setLoadOnOpenOffset(rootIndexOffset);
// Meta block index.
metaBlockIndexWriter.writeSingleLevelIndex(blockWriter.startWriting(
BlockType.ROOT_INDEX), "meta");
blockWriter.writeHeaderAndData(outputStream);
totalUncompressedBytes += blockWriter.getUncompressedSizeWithHeader();
if (this.hFileContext.isIncludesMvcc()) {
appendFileInfo(MAX_MEMSTORE_TS_KEY, Bytes.toBytes(maxMemstoreTS));
appendFileInfo(KEY_VALUE_VERSION, Bytes.toBytes(KEY_VALUE_VER_WITH_MEMSTORE));
}
// File info
writeFileInfo(trailer, blockWriter.startWriting(BlockType.FILE_INFO));
blockWriter.writeHeaderAndData(outputStream);
totalUncompressedBytes += blockWriter.getUncompressedSizeWithHeader();
// Load-on-open data supplied by higher levels, e.g. Bloom filters.
for (BlockWritable w : additionalLoadOnOpenData){
blockWriter.writeBlock(w, outputStream);
totalUncompressedBytes += blockWriter.getUncompressedSizeWithHeader();
}
// Now finish off the trailer.
trailer.setNumDataIndexLevels(dataBlockIndexWriter.getNumLevels());
trailer.setUncompressedDataIndexSize(
dataBlockIndexWriter.getTotalUncompressedSize());
trailer.setFirstDataBlockOffset(firstDataBlockOffset);
trailer.setLastDataBlockOffset(lastDataBlockOffset);
trailer.setComparatorClass(comparator.getClass());
trailer.setDataIndexCount(dataBlockIndexWriter.getNumRootEntries());
finishClose(trailer);
blockWriter.release();
}
@Override
public void addInlineBlockWriter(InlineBlockWriter ibw) {
inlineBlockWriters.add(ibw);
}
@Override
public void addGeneralBloomFilter(final BloomFilterWriter bfw) {
this.addBloomFilter(bfw, BlockType.GENERAL_BLOOM_META);
}
@Override
public void addDeleteFamilyBloomFilter(final BloomFilterWriter bfw) {
this.addBloomFilter(bfw, BlockType.DELETE_FAMILY_BLOOM_META);
}
private void addBloomFilter(final BloomFilterWriter bfw,
final BlockType blockType) {
if (bfw.getKeyCount() <= 0)
return;
if (blockType != BlockType.GENERAL_BLOOM_META &&
blockType != BlockType.DELETE_FAMILY_BLOOM_META) {
throw new RuntimeException("Block Type: " + blockType.toString() +
"is not supported");
}
additionalLoadOnOpenData.add(new BlockWritable() {
@Override
public BlockType getBlockType() {
return blockType;
}
@Override
public void writeToBlock(DataOutput out) throws IOException {
bfw.getMetaWriter().write(out);
Writable dataWriter = bfw.getDataWriter();
if (dataWriter != null)
dataWriter.write(out);
}
});
}
@Override
public HFileContext getFileContext() {
return hFileContext;
}
/**
* Add key/value to file. Keys must be added in an order that agrees with the
* Comparator passed on construction.
*
* @param cell
* Cell to add. Cannot be empty nor null.
* @throws IOException
*/
@Override
public void append(final Cell cell) throws IOException {
// checkKey uses comparator to check we are writing in order.
boolean dupKey = checkKey(cell);
if (!dupKey) {
checkBlockBoundary();
}
if (!blockWriter.isWriting()) {
newBlock();
}
blockWriter.write(cell);
totalKeyLength += CellUtil.estimatedSerializedSizeOfKey(cell);
totalValueLength += cell.getValueLength();
// Are we the first key in this block?
if (firstCellInBlock == null) {
// If cell is big, block will be closed and this firstCellInBlock reference will only last
// a short while.
firstCellInBlock = cell;
}
// TODO: What if cell is 10MB and we write infrequently? We hold on to cell here indefinitely?
lastCell = cell;
entryCount++;
this.maxMemstoreTS = Math.max(this.maxMemstoreTS, cell.getSequenceId());
int tagsLength = cell.getTagsLength();
if (tagsLength > this.maxTagsLength) {
this.maxTagsLength = tagsLength;
}
}
@Override
public void beforeShipped() throws IOException {
// Add clone methods for every cell
if (this.lastCell != null) {
this.lastCell = KeyValueUtil.toNewKeyCell(this.lastCell);
}
if (this.firstCellInBlock != null) {
this.firstCellInBlock = KeyValueUtil.toNewKeyCell(this.firstCellInBlock);
}
if (this.lastCellOfPreviousBlock != null) {
this.lastCellOfPreviousBlock = KeyValueUtil.toNewKeyCell(this.lastCellOfPreviousBlock);
}
}
protected void finishFileInfo() throws IOException {
if (lastCell != null) {
// Make a copy. The copy is stuffed into our fileinfo map. Needs a clean
// byte buffer. Won't take a tuple.
byte [] lastKey = CellUtil.getCellKeySerializedAsKeyValueKey(this.lastCell);
fileInfo.append(FileInfo.LASTKEY, lastKey, false);
}
// Average key length.
int avgKeyLen =
entryCount == 0 ? 0 : (int) (totalKeyLength / entryCount);
fileInfo.append(FileInfo.AVG_KEY_LEN, Bytes.toBytes(avgKeyLen), false);
fileInfo.append(FileInfo.CREATE_TIME_TS, Bytes.toBytes(hFileContext.getFileCreateTime()),
false);
// Average value length.
int avgValueLen =
entryCount == 0 ? 0 : (int) (totalValueLength / entryCount);
fileInfo.append(FileInfo.AVG_VALUE_LEN, Bytes.toBytes(avgValueLen), false);
if (hFileContext.getDataBlockEncoding() == DataBlockEncoding.PREFIX_TREE) {
// In case of Prefix Tree encoding, we always write tags information into HFiles even if all
// KVs are having no tags.
fileInfo.append(FileInfo.MAX_TAGS_LEN, Bytes.toBytes(this.maxTagsLength), false);
} else if (hFileContext.isIncludesTags()) {
// When tags are not being written in this file, MAX_TAGS_LEN is excluded
// from the FileInfo
fileInfo.append(FileInfo.MAX_TAGS_LEN, Bytes.toBytes(this.maxTagsLength), false);
boolean tagsCompressed = (hFileContext.getDataBlockEncoding() != DataBlockEncoding.NONE)
&& hFileContext.isCompressTags();
fileInfo.append(FileInfo.TAGS_COMPRESSED, Bytes.toBytes(tagsCompressed), false);
}
}
protected int getMajorVersion() {
return 3;
}
protected int getMinorVersion() {
return HFileReaderImpl.MAX_MINOR_VERSION;
}
protected void finishClose(FixedFileTrailer trailer) throws IOException {
// Write out encryption metadata before finalizing if we have a valid crypto context
Encryption.Context cryptoContext = hFileContext.getEncryptionContext();
if (cryptoContext != Encryption.Context.NONE) {
// Wrap the context's key and write it as the encryption metadata, the wrapper includes
// all information needed for decryption
trailer.setEncryptionKey(EncryptionUtil.wrapKey(cryptoContext.getConf(),
cryptoContext.getConf().get(HConstants.CRYPTO_MASTERKEY_NAME_CONF_KEY,
User.getCurrent().getShortName()),
cryptoContext.getKey()));
}
// Now we can finish the close
trailer.setMetaIndexCount(metaNames.size());
trailer.setTotalUncompressedBytes(totalUncompressedBytes+ trailer.getTrailerSize());
trailer.setEntryCount(entryCount);
trailer.setCompressionCodec(hFileContext.getCompression());
long startTime = System.currentTimeMillis();
trailer.serialize(outputStream);
HFile.updateWriteLatency(System.currentTimeMillis() - startTime);
if (closeOutputStream) {
outputStream.close();
outputStream = null;
}
}
}
|
JingchengDu/hbase
|
hbase-server/src/main/java/org/apache/hadoop/hbase/io/hfile/HFileWriterImpl.java
|
Java
|
apache-2.0
| 32,336 |
export * from './dynamic-date.module';
export * from './dynamic-date.pipe';
|
our-city-app/oca-backend
|
embedded-apps/projects/shared/src/lib/dynamic-date/index.ts
|
TypeScript
|
apache-2.0
| 76 |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
namespace Game.Event
{
public class Event : MonoBehaviour
{
#region Fields
[SerializeField]
private UnityEvent _startList;
[SerializeField]
private UnityEvent _endList;
#endregion Fields
#region Event
public virtual void StartEvent()
{
Debug.Log(string.Format("Start Event: {0}", this.gameObject.name));
this._startList.Invoke();
}
public virtual void EndEvent()
{
Debug.Log(string.Format("End Event: {0}", this.gameObject.name));
this._endList.Invoke();
}
#endregion Event
}
}
|
hilllo/HaloLandsAR
|
HaloLands/Assets/Scripts/EventSystem/Event.cs
|
C#
|
apache-2.0
| 779 |
var schema = require("./schema.js");
var xml = require("./xml.js");
module.exports.createBuilder = schema.createBuilder;
module.exports.parse = xml.parse;
module.exports.parseXml = xml.parse;
|
pagi-org/pagijs
|
src/js/schema/index.js
|
JavaScript
|
apache-2.0
| 193 |
#if TEXTURE_EXPOSE == TEXTURE_NAMES
#elif TEXTURE_EXPOSE == TEXTURE_BUILDER_NAME
builArmchair,
#elif TEXTURE_EXPOSE == TEXTURE_FILE
__FILE__,
#elif TEXTURE_EXPOSE == TEXTURE_BUILDER_BODY
void builArmchair()
{
Channel t;
t.Cells(100);
Channel r = t; r.Scale(53.f/255.f, 83.f/255.f);
Channel g = t; g.Scale(32.f/255.f, 54.f/255.f);
Channel b = t; b.Scale(27.f/245.f, 50.f/255.f);
queueTextureRGB(armchair,
r, g, b,
GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR,
true, GL_REPEAT, false);
t.Random();
t.GaussianBlur();
t.Scale(0., 0.25f);
buildAndQueueBumpMapFromHeightMap(armchairBump, t, true);
}
#endif // TEXTURE_EXPOSE
|
laurentlb/Ctrl-Alt-Test
|
F/data/textures/armchair.cc
|
C++
|
apache-2.0
| 678 |
package echo;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
/**
* Created by Administrator on 2014/12/30.
*/
public class EchoServer {
private int port;
public EchoServer(int port) {
this.port = port;
}
public void run() throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup)
.localAddress(port)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new EchoServerHandler());
}
});
ChannelFuture cf = bootstrap.bind().sync();
cf.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
int port;
if (args.length > 0) {
port = Integer.parseInt(args[0]);
} else {
port = 8080;
}
new EchoServer(port).run();
}
}
|
edgar615/javase-study
|
netty-study/src/main/java/echo/EchoServer.java
|
Java
|
apache-2.0
| 1,712 |
package br.edu.fema.sacheti.intercept;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import br.edu.fema.sacheti.model.Cliente;
import br.edu.fema.sacheti.model.Usuario;
@SessionScoped
@Named
public class ClienteInfo implements Serializable{
private static final long serialVersionUID = 6078821766905465970L;
private Cliente cliente;
private Usuario usuario;
public void login(Cliente cliente){
this.cliente = cliente;
this.usuario = cliente.getUsuario();
}
public void logout(){
this.usuario = null;
}
public Usuario getUsuario() {
return usuario;
}
public Cliente getCliente(){
return cliente;
}
}
|
jpsacheti/limasoftware-java-suporte
|
src/main/java/br/edu/fema/sacheti/intercept/ClienteInfo.java
|
Java
|
apache-2.0
| 691 |
package com.gushikustudios.common;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.scenes.scene2d.ui.Align;
import com.badlogic.gdx.scenes.scene2d.ui.Button;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;
public class TextEntry extends Button
{
public TextEntry(String string,Color textColor,Color bgColor,boolean center)
{
super(Assets.mSkin.getStyle("default-round-white", ButtonStyle.class));
Label label;
this.touchable = false;
this.color.set(bgColor);
this.add(label = new Label(string,Assets.mSkin.getStyle("default-white",LabelStyle.class))).fill().expandX();
label.setWrap(true);
if (center)
{
label.setAlignment(Align.CENTER);
}
label.setColor(textColor);
}
public TextEntry(String [] string,Color [] textColor,Color bgColor,boolean center)
{
super(Assets.mSkin.getStyle("default-round-white", ButtonStyle.class));
Label label;
this.touchable = false;
this.color.set(bgColor);
for (int j = 0; j < string.length; j++)
{
this.row();
this.add(label = new Label(string[j],Assets.mSkin.getStyle("default-white",LabelStyle.class))).fill().expandX();
label.setWrap(true);
if (center)
{
label.setAlignment(Align.CENTER);
}
label.setColor(textColor[j]);
}
}
}
|
minthubk/tankz
|
gushiku-common/src/com/gushikustudios/common/TextEntry.java
|
Java
|
apache-2.0
| 1,449 |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Generated code. DO NOT EDIT!
#
# Snippet for UpdateTensorboard
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-aiplatform
# [START aiplatform_generated_aiplatform_v1_TensorboardService_UpdateTensorboard_async]
from google.cloud import aiplatform_v1
async def sample_update_tensorboard():
# Create a client
client = aiplatform_v1.TensorboardServiceAsyncClient()
# Initialize request argument(s)
tensorboard = aiplatform_v1.Tensorboard()
tensorboard.display_name = "display_name_value"
request = aiplatform_v1.UpdateTensorboardRequest(
tensorboard=tensorboard,
)
# Make the request
operation = client.update_tensorboard(request=request)
print("Waiting for operation to complete...")
response = await operation.result()
# Handle the response
print(response)
# [END aiplatform_generated_aiplatform_v1_TensorboardService_UpdateTensorboard_async]
|
googleapis/python-aiplatform
|
samples/generated_samples/aiplatform_generated_aiplatform_v1_tensorboard_service_update_tensorboard_async.py
|
Python
|
apache-2.0
| 1,730 |
//===--- DiagnosticConsumer.cpp - Diagnostic Consumer Impl ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the DiagnosticConsumer class.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "swift-basic"
#include "swift/Basic/DiagnosticConsumer.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
using namespace swift;
DiagnosticConsumer::~DiagnosticConsumer() { }
void NullDiagnosticConsumer::handleDiagnostic(SourceManager &SM,
SourceLoc Loc,
DiagnosticKind Kind,
StringRef Text,
const DiagnosticInfo &Info) {
DEBUG(llvm::dbgs() << "NullDiagnosticConsumer received diagnostic: "
<< Text << "\n");
}
|
ben-ng/swift
|
lib/Basic/DiagnosticConsumer.cpp
|
C++
|
apache-2.0
| 1,355 |
import React, {Component} from 'react';
import {withRouter} from 'react-router';
import EUCookie from "area51-eucookie";
import Navigation from '../Navigation';
class About extends Component {
render() {
return (<div>
<Navigation page="contactUs"/>
<EUCookie/>
<div className="App-header">
<h1>Contact Us</h1>
</div>
<div className="App-intro">
<p>A contact form will appear here in the near future.</p>
<p>Currently you can contact us via:</p>
<ul>
<li>Twitter:
<ul>
<li><a href="http://twitter.com/TrainWatch">@Trainwatch</a></li>
<li><a href="http://twitter.com/peter_mount">@Peter_Mount</a></li>
</ul>
</li>
</ul>
<p>
Any issues can be reported on <a
href="https://github.com/peter-mount/departureboards/issues">GitHub</a>.
</p>
</div>
</div>);
}
}
export default withRouter(About);
|
peter-mount/departureboards
|
src/contactUs/ContactUs.js
|
JavaScript
|
apache-2.0
| 1,184 |
<?php
session_start();
// include "check-user.php";
include "connection.php";
if (isset($_REQUEST['quiz_id'])) {
$quiz_id = $_REQUEST['quiz_id'];
}else{
$quiz_id = 1;
}
$sql = "SELECT COUNT(*) FROM questions WHERE quiz_id=$quiz_id";
$result = mysqli_query($link, $sql);
if(mysqli_num_rows($result) == 0) {
mysqli_close($link);
exit;
}else{
$amount = 3;
}
?>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Quiz</title>
<!-- Bootstrap Core CSS -->
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css">
<!--Custom CSS-->
<link rel="stylesheet" href="css/quiz2.css" type="text/css">
</head>
<body>
<div class="container-fluid">
<div class="row top">
<?php
$begin = 1; //แถวเริ่มต้นในการอ่านข้อมูล
if($_GET['begin']) {
$begin = $_GET['begin'];
}
$length = 1; //จำนวนคำถามในการอ่านข้อมูลแต่ละช่วง
if($_GET['length']) {
$length = $_GET['length'];
}
if($begin==1){
$_SESSION[score] = 0;
// echo $_SESSION['score'];
}
$begin--; //ลำดับแถวใน MySQL เริ่มจาก 0
$sql = "SELECT * FROM questions WHERE quiz_id = $quiz_id LIMIT $begin, $length";
$result = mysqli_query($link, $sql);
$num = $begin + 1;
while($data = mysqli_fetch_array($result)) {
$question_text = $data['content'];
$question_id = $data['question_id'];
$sql = "SELECT * FROM choices WHERE question_id = $question_id ORDER BY choice_id ASC";
$r = mysqli_query($link, $sql);
echo "<div class='col-xs-1 col-md-2 header'>Q".$num."/".$amount."</div>";
echo "<div class='col-xs-10 col-md-8' id='question'>".$question_text."</div>";
echo "<div class='col-xs-1 col-md-2 header'>".$_SESSION['score']."</div>";
echo '</div>';
while($ch = mysqli_fetch_array($r)) {
if(isset($_SESSION['user_id'])) {
$user_id = $_SESSION['user_id'];
$sql = "SELECT choice_id FROM choices WHERE question_id = $question_id"; //AND subject_id = $subject_id
$choose = mysqli_query($link, $sql);
$row = mysqli_fetch_array($choose);
$id = $row[0];
}
// echo "<div class=\"choice\">{$ch['content']}</div><br>";
echo "<div class='bottom'><button class='row choice' onclick='nextques({$ch['content']})'>{$ch['content']}</button></div>";
}
$num++;
}
$ansSQL = "SELECT content FROM choices WHERE is_correct=1 AND question_id=$question_id";
$rs3 = mysqli_query($link,$ansSQL);
$correctAns = mysqli_fetch_array($rs3);
?>
<script>
function nextques(selected){
// alert("yay");
var url = "quiz2.php?quiz_id=" + <?php echo $quiz_id; ?>;
var begin = <?php echo $begin; ?>;
begin += 2;
url = url + "&begin=" + begin + "&length=1";
var correct = <?php echo $correctAns[0]; ?>;
var amount = <?php echo $amount; ?>;
var endgame = <?php echo $begin; ?>;
if(selected==correct){
$.ajax({
type: "POST",
url: "updatescore.php",
data: {}
}).done(function( msg ) {
// alert( "Update: " + msg );
// alert(msg);
});
}else{
alert("CORRECT answer is " + correct);
}
if((endgame+1)==amount){
url = "quizresult.php";
}
location.href = url;
}
</script>
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>
|
Kunnapat/chowtime
|
quiz2.php
|
PHP
|
apache-2.0
| 4,848 |
# This file is for dev branch
|
umitmertcakmak/PySpyder
|
scrappers/devTest.py
|
Python
|
apache-2.0
| 31 |
/*
* Copyright (C) 2012 ENTERTAILION LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.entertailion.android.launcher.widget;
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.graphics.Typeface;
import android.os.Handler;
import android.text.format.DateUtils;
import android.util.AttributeSet;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.entertailion.android.launcher.R;
/**
* Clock widget. Displays current time with minute accuracy.
*
* @author leon_nicholls
*
*/
public class Clock extends LinearLayout {
private static String LOG_TAG = "Clock";
private Timer timer;
private Handler handler = new Handler();
private TextView timeView;
private String lastTime;
public Clock(Context context, AttributeSet attrs) {
super(context, attrs);
addView(inflate(context, R.layout.clock_widget, null));
timeView = (TextView) findViewById(R.id.time);
if (!isInEditMode()) { // support IDE editor
Typeface typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Condensed.ttf");
timeView.setTypeface(typeface);
}
start();
}
/**
* Thread to update clock every second
*/
public void start() {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
final String time = DateUtils.formatDateTime(getContext(), System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME);
if (!time.equals(lastTime)) {
handler.post(new Runnable() {
public void run() {
timeView.setText(time);
}
});
lastTime = time;
}
}
}, 0, 1000); // every second
}
/**
* Stop the update thread
*/
public void stop() {
timer.cancel();
}
}
|
entertailion/Open-Launcher-for-GTV
|
src/com/entertailion/android/launcher/widget/Clock.java
|
Java
|
apache-2.0
| 2,261 |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[AddComponentMenu("RPG and MMO UI/Tooltip/Tooltip")]
public class RnMUI_Tooltip : MonoBehaviour
{
public class AttributeInfo
{
public string value;
public string text;
public bool singleColumnRow;
public RectOffset margin;
}
public enum AnchorPoint : int
{
BottomLeft = 0,
TopLeft = 1,
TopRight = 2,
BottomRight = 3,
}
private static RnMUI_Tooltip mInstance;
public Camera uiCamera;
public UILabel title;
public UILabel description;
public UISprite background;
public UIWidget container;
public float fadeDuration = 0.3f;
public Color attrValueColor = new Color(0.357f, 0.369f, 0.431f, 1f);
public Color attrTextColor = new Color(0.357f, 0.369f, 0.431f, 1f);
public GameObject attributesRowPrefab;
public int attributesMarginTop = 0;
public int attributesMarginBottom = 0;
public RnMUI_TooltipAnchor tooltipAnchor;
private UIWidget anchorPositionTo;
private Vector3 targetPosition;
private List<AttributeInfo> mAttributes = new List<AttributeInfo>();
private List<GameObject> mInstancedAttributesRows = new List<GameObject>();
private bool mIsVisible = false;
public bool IsVisible { get { return this.mIsVisible; } }
/// <summary>
/// Whether the tooltip is currently visible.
/// </summary>
static public bool isVisible { get { return (mInstance != null && mInstance.IsVisible); } }
void Awake()
{
mInstance = this;
}
void OnDestroy()
{
mInstance = null;
}
protected virtual void Start()
{
this.SetAlpha(0f);
if (this.uiCamera == null) this.uiCamera = NGUITools.FindCameraForLayer(this.gameObject.layer);
if (this.uiCamera == null) this.uiCamera = Camera.main;
if (this.uiCamera == null)
{
Debug.LogWarning(this.GetType() + " requires a camera in order to work.", this);
this.enabled = false;
return;
}
if (this.container == null)
{
Debug.LogWarning(this.GetType() + " requires a container to be define in order to work.", this);
this.enabled = false;
return;
}
if (this.background == null)
{
Debug.LogWarning(this.GetType() + " requires a background sprite in order to work.", this);
this.enabled = false;
return;
}
}
protected virtual void Update()
{
if (this.currentAlpha > 0f)
this.UpdatePosition();
}
/// <summary>
/// Updates the position of the tooltip.
/// </summary>
private void UpdatePosition()
{
AnchorPoint anchorPosition = AnchorPoint.BottomLeft;
if (this.anchorPositionTo != null)
{
// Set the world position to the top right corner of the target
this.transform.position = this.anchorPositionTo.worldCorners[(int)AnchorPoint.TopRight];
}
else
{
// Set the world position to the target position
this.transform.position = targetPosition;
}
// Now move the position up based on the background height
this.transform.localPosition = this.transform.localPosition + new Vector3(0f, this.background.height, 0f);
// Check if the tooltip is going outside the viewport to the left
if (this.uiCamera.WorldToScreenPoint(this.background.worldCorners[2]).x > Screen.width)
{
// move to the left
this.transform.localPosition = this.transform.localPosition + new Vector3(-(this.background.width + (this.anchorPositionTo != null ? this.anchorPositionTo.width : 0)), 0f, 0f);
// Update the anchor variable
anchorPosition = AnchorPoint.BottomRight;
}
// Check if the tooltip is going outside the viewport to the top
if (this.uiCamera.WorldToScreenPoint(this.background.worldCorners[1]).y > Screen.height)
{
// move to the bottom
this.transform.localPosition = this.transform.localPosition + new Vector3(0f, -(this.background.height + (this.anchorPositionTo != null ? this.anchorPositionTo.height : 0)), 0f);
// Update the anchor variable
anchorPosition = (anchorPosition == AnchorPoint.BottomLeft) ? AnchorPoint.TopLeft : AnchorPoint.TopRight;
}
if (this.tooltipAnchor != null)
this.tooltipAnchor.SetAnchorPosition(anchorPosition, this.background.width, this.background.height);
}
private void _SetTitle(string tooltipTitle)
{
if (this.title != null)
this.title.text = tooltipTitle;
}
private void _SetDescription(string tooltipDescription)
{
if (this.description != null)
{
if (string.IsNullOrEmpty(tooltipDescription))
this.description.enabled = false;
else
this.description.enabled = true;
this.description.text = tooltipDescription;
}
}
/// <summary>
/// Sets the title of the tooltip.
/// </summary>
/// <param name="tooltipTitle">Tooltip title.</param>
public static void SetTitle(string tooltipTitle)
{
if (mInstance != null)
mInstance._SetTitle(tooltipTitle);
}
/// <summary>
/// Sets the description of the tooltip, the description will be disabled if set to null or empty.
/// </summary>
/// <param name="tooltipDescription">Tooltip description.</param>
public static void SetDescription(string tooltipDescription)
{
if (mInstance != null)
mInstance._SetDescription(tooltipDescription);
}
private void _AddAttribute(string value, string text, bool singleColumnRow, RectOffset margin)
{
// Create new attribute info
AttributeInfo info = new AttributeInfo();
info.value = "[" + NGUIText.EncodeColor(this.attrValueColor) + "]" + value + "[-]";
info.text = "[" + NGUIText.EncodeColor(this.attrTextColor) + "]" + text + "[-]";
info.singleColumnRow = singleColumnRow;
info.margin = margin;
// Add it to the attribute list
this.mAttributes.Add(info);
}
/// <summary>
/// Adds an attribute to the tooltip, the align is auto based on the order of attributes.
/// </summary>
/// <param name="value">Value.</param>
/// <param name="text">Text.</param>
public static void AddAttribute(string value, string text)
{
if (mInstance != null)
mInstance._AddAttribute(value, text, false, new RectOffset());
}
/// <summary>
/// Adds an attribute to the tooltip on a row with a single column.
/// </summary>
/// <param name="value">Value.</param>
/// <param name="text">Text.</param>
public static void AddAttribute_SingleColumn(string value, string text)
{
if (mInstance != null)
mInstance._AddAttribute(value, text, true, new RectOffset());
}
/// <summary>
/// Adds an attribute to the tooltip on a row with a single column.
/// </summary>
/// <param name="value">Value.</param>
/// <param name="text">Text.</param>
/// <param name="margin">Margin.</param>
public static void AddAttribute_SingleColumn(string value, string text, RectOffset margin)
{
if (mInstance != null)
mInstance._AddAttribute(value, text, true, margin);
}
private void _SetPosition(UIWidget target)
{
if (target == null)
return;
// Save the target and make the calculations after the show call
this.anchorPositionTo = target;
}
/// <summary>
/// Sets the position of the tooltip anchored to the given widget.
/// </summary>
/// <param name="target">Target.</param>
public static void SetPosition(UIWidget target)
{
if (mInstance != null)
mInstance._SetPosition(target);
}
private void _Show()
{
// Cleanup any attributes left, if any at all
this.Cleanup();
// Bring the tooltip forward
NGUITools.BringForward(this.gameObject);
// Save the position where the tooltip should appear
this.targetPosition = uiCamera.ScreenToWorldPoint(Input.mousePosition);
// Prepare the attributes
if (this.mAttributes.Count > 0 && this.attributesRowPrefab != null)
{
bool isLeft = true;
RnMUI_Tooltip_AttributeRow lastAttrRow = null;
int lastDepth = this.title.depth;
// Loop the attributes
foreach (AttributeInfo info in this.mAttributes)
{
// Force left column in case it's a signle column row
if (info.singleColumnRow)
isLeft = true;
if (isLeft)
{
// Instantiate a prefab
GameObject obj = (GameObject)Instantiate(this.attributesRowPrefab);
// Apply parent
obj.transform.parent = this.container.transform;
// Fix position and scale
obj.transform.localScale = Vector3.one;
obj.transform.localPosition = Vector3.zero;
obj.transform.localRotation = Quaternion.identity;
// Increase the depth
lastDepth = lastDepth + 1;
// Apply the new depth
UIWidget wgt = obj.GetComponent<UIWidget>();
if (wgt != null)
wgt.depth = lastDepth;
// Get the attribute row script referrence
lastAttrRow = obj.GetComponent<RnMUI_Tooltip_AttributeRow>();
// Make some changes if it's a single column row
if (info.singleColumnRow)
{
// Destroy the right column
NGUITools.Destroy(lastAttrRow.rightLabel.gameObject);
// Double the size of the label
lastAttrRow.leftLabel.width *= 2;
}
// Check if we can set margin to the row
UITable_ItemMargin margins = obj.GetComponent<UITable_ItemMargin>();
// If the row does not have the component add it
if (margins == null)
margins = obj.AddComponent<UITable_ItemMargin>();
if (margins != null)
{
margins.left = info.margin.left;
margins.right = info.margin.right;
margins.top = info.margin.top;
margins.bottom = info.margin.bottom;
// If this is the first or last row, apply the global attr margins
if (this.mInstancedAttributesRows.Count == 0)
margins.top += this.attributesMarginTop;
else if (this.mInstancedAttributesRows.Count == (Mathf.RoundToInt((float)this.mAttributes.Count / 2f) - 1))
margins.bottom += this.attributesMarginBottom;
}
// Add it to the instanced objects list
this.mInstancedAttributesRows.Add(obj);
}
// Check if we have a row object to work with
if (lastAttrRow != null)
{
UILabel label = (isLeft) ? lastAttrRow.leftLabel : lastAttrRow.rightLabel;
// Check if we have the label
if (label != null)
{
// Set the label alpha
label.alpha = 0f;
// Set the label text
label.text = info.value + info.text;
// Flip is left
if (!info.singleColumnRow)
isLeft = !isLeft;
}
// Update the row size and depth
lastAttrRow.UpdateSizeAndDepth();
}
}
// Clear the attributes list, we no longer need it
this.mAttributes.Clear();
// Apply greater depth to the description
if (this.description != null)
this.description.depth = (lastDepth + 1);
}
// Update the tooltip table
if (this.container != null)
{
UITableExtended contTable = this.container.GetComponent<UITableExtended>();
if (contTable != null)
contTable.Reposition();
}
// Fade In
this.StopCoroutine("FadeOut");
this.StartCoroutine("FadeIn");
}
private void _Hide()
{
// Target alpha
this.StopCoroutine("FadeIn");
this.StartCoroutine("FadeOut");
}
private void OnFadeOut()
{
//Destroy the instanced attributes and empty the list
this.Cleanup();
// Clear the anchor to
this.anchorPositionTo = null;
}
private void Cleanup()
{
//Destroy the attributes
foreach (GameObject obj in this.mInstancedAttributesRows)
{
if (obj != null)
DestroyImmediate(obj);
}
// Clear the list
this.mInstancedAttributesRows.Clear();
}
/// <summary>
/// Show the tooltip.
/// </summary>
public static void Show()
{
if (mInstance != null)
mInstance._Show();
}
/// <summary>
/// Hide the tooltip.
/// </summary>
public static void Hide()
{
if (mInstance != null)
mInstance._Hide();
}
/// <summary>
/// Set the alpha of all widgets.
/// </summary>
private void SetAlpha(float val)
{
UIWidget[] widgets = this.GetComponentsInChildren<UIWidget>();
for (int i = 0, imax = widgets.Length; i < imax; ++i)
{
UIWidget w = widgets[i];
Color c = w.color;
c.a = val;
w.color = c;
}
}
private float currentAlpha { get { return this.background.alpha; } }
// Show / Hide fade animation coroutine
private IEnumerator FadeIn()
{
this.mIsVisible = true;
// Get the timestamp
float startTime = Time.time;
// Calculate the time we need to fade in from the current alpha
float internalDuration = (this.fadeDuration * (1f - this.currentAlpha));
// Update the start time
startTime -= (this.fadeDuration - internalDuration);
// Fade In
while (Time.time < (startTime + this.fadeDuration))
{
float RemainingTime = (startTime + this.fadeDuration) - Time.time;
float ElapsedTime = this.fadeDuration - RemainingTime;
// Update the alpha by the percentage of the time elapsed
this.SetAlpha(ElapsedTime / this.fadeDuration);
yield return 0;
}
// Make sure it's 1
this.SetAlpha(1.0f);
}
// Show / Hide fade animation coroutine
private IEnumerator FadeOut()
{
if (!this.IsVisible)
yield break;
// Get the timestamp
float startTime = Time.time;
// Calculate the time we need to fade out from the current alpha
float internalDuration = (this.fadeDuration * this.currentAlpha);
// Update the start time
startTime -= (this.fadeDuration - internalDuration);
// Fade In
while (Time.time < (startTime + this.fadeDuration))
{
float RemainingTime = (startTime + this.fadeDuration) - Time.time;
// Update the alpha by the percentage of the time elapsed
this.SetAlpha(RemainingTime / this.fadeDuration);
yield return 0;
}
// Make sure it's 0
this.SetAlpha(0f);
this.mIsVisible = false;
this.OnFadeOut();
}
}
|
zhulangen/unity3d-test
|
Assets/Bison/RnM UI for NGUI/Scripts/UI/RnMUI_Tooltip.cs
|
C#
|
apache-2.0
| 13,438 |
/**
* Copyright (C) 2015 Agro-Know, Deutsches Forschungszentrum für Künstliche Intelligenz, iMinds,
* Institut für Angewandte Informatik e. V. an der Universität Leipzig,
* Istituto Superiore Mario Boella, Tilde, Vistatec, WRIPL (http://freme-project.eu)
*
* 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 eu.freme.broker.tools;
import java.util.HashMap;
import eu.freme.common.conversion.rdf.RDFConstants;
@SuppressWarnings("serial")
public class RDFELinkSerializationFormats extends HashMap<String, RDFConstants.RDFSerialization>{
public RDFELinkSerializationFormats(){
super();
put("text/turtle", RDFConstants.RDFSerialization.TURTLE);
put("application/x-turtle", RDFConstants.RDFSerialization.TURTLE);
put("turtle", RDFConstants.RDFSerialization.TURTLE);
put("application/json+ld",RDFConstants.RDFSerialization.JSON_LD);
put("json-ld", RDFConstants.RDFSerialization.JSON_LD);
put("application/n-triples",RDFConstants.RDFSerialization.N_TRIPLES);
put("ntriples", RDFConstants.RDFSerialization.N_TRIPLES);
put("application/rdf+xml", RDFConstants.RDFSerialization.RDF_XML);
put("rdf-xml", RDFConstants.RDFSerialization.RDF_XML);
put("text/n3",RDFConstants.RDFSerialization.N3);
put("n3",RDFConstants.RDFSerialization.N3);
put("application/json", RDFConstants.RDFSerialization.JSON);
put("json", RDFConstants.RDFSerialization.JSON);
}
}
|
freme-project/Broker
|
src/main/java/eu/freme/broker/tools/RDFELinkSerializationFormats.java
|
Java
|
apache-2.0
| 1,982 |
using System;
using System.Linq;
using Ductus.FluentDocker.Commands;
using Ductus.FluentDocker.Services;
using Ductus.FluentDocker.Tests.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Ductus.FluentDocker.Tests
{
public abstract class FluentDockerTestBase
{
protected IHostService DockerHost;
private bool _createdHost;
[TestInitialize]
public void Initialize()
{
EnsureDockerHost();
}
[TestCleanup]
public void Teardown()
{
if (_createdHost)
{
"test-machine".Delete(true /*force*/);
}
}
private void EnsureDockerHost()
{
if (DockerHost?.State == ServiceRunningState.Running)
{
return;
}
var hosts = new Hosts().Discover();
DockerHost = hosts.FirstOrDefault(x => x.IsNative) ?? hosts.FirstOrDefault(x => x.Name == "default");
if (null != DockerHost)
{
if (DockerHost.State != ServiceRunningState.Running)
{
DockerHost.Start();
DockerHost.Host.LinuxMode(DockerHost.Certificates);
}
return;
}
if (hosts.Count > 0)
{
DockerHost = hosts.First();
}
if (null != DockerHost)
{
return;
}
if (_createdHost)
{
throw new Exception("Failed to initialize the test class, tried to create a docker host but failed");
}
var res = "test-machine".Create(1024, 20000, 1);
Assert.AreEqual(true, res.Success);
var start = "test-machine".Start();
Assert.AreEqual(true, start.Success);
_createdHost = true;
EnsureDockerHost();
}
}
}
|
mariotoffia/FluentDocker
|
Ductus.FluentDocker.Tests/FluentDockerTestBase.cs
|
C#
|
apache-2.0
| 1,664 |
package fr.javatronic.blog.massive.annotation1.sub1;
import fr.javatronic.blog.processor.Annotation_001;
@Annotation_001
public class Class_6400 {
}
|
lesaint/experimenting-annotation-processing
|
experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_6400.java
|
Java
|
apache-2.0
| 151 |
package io.cattle.platform.core.addon.metadata;
import io.cattle.platform.core.constants.NetworkConstants;
import io.cattle.platform.core.model.Network;
import io.cattle.platform.object.util.DataAccessor;
import io.github.ibuildthecloud.gdapi.annotation.Field;
import java.util.Map;
public class NetworkInfo implements MetadataObject {
Long id;
String name;
String uuid;
String kind;
String environmentUuid;
boolean hostPorts;
Map<String, Object> metadata;
String defaultPolicyAction;
Object policy;
public NetworkInfo(Network network) {
this.defaultPolicyAction = DataAccessor.fieldString(network, NetworkConstants.FIELD_DEFAULT_POLICY_ACTION);
this.id = network.getId();
this.kind = network.getKind();
this.metadata = DataAccessor.fieldMap(network, NetworkConstants.FIELD_METADATA);
this.name = network.getName();
this.policy = DataAccessor.fieldObject(network, NetworkConstants.FIELD_POLICY);
this.uuid = network.getUuid();
this.hostPorts = DataAccessor.fieldBool(network, NetworkConstants.FIELD_HOST_PORTS);
}
public String getKind() {
return kind;
}
@Field(typeString = "reference[network]")
public Long getInfoTypeId() {
return id;
}
public Long getId() {
return id;
}
@Override
public String getEnvironmentUuid() {
return environmentUuid;
}
@Override
public String getInfoType() {
return "network";
}
@Override
public void setEnvironmentUuid(String environmentUuid) {
this.environmentUuid = environmentUuid;
}
public String getName() {
return name;
}
@Override
public String getUuid() {
return uuid;
}
public boolean isHostPorts() {
return hostPorts;
}
public Map<String, Object> getMetadata() {
return metadata;
}
public String getDefaultPolicyAction() {
return defaultPolicyAction;
}
public Object getPolicy() {
return policy;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
NetworkInfo that = (NetworkInfo) o;
if (hostPorts != that.hostPorts) return false;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
if (name != null ? !name.equals(that.name) : that.name != null) return false;
if (uuid != null ? !uuid.equals(that.uuid) : that.uuid != null) return false;
if (kind != null ? !kind.equals(that.kind) : that.kind != null) return false;
if (environmentUuid != null ? !environmentUuid.equals(that.environmentUuid) : that.environmentUuid != null)
return false;
if (metadata != null ? !metadata.equals(that.metadata) : that.metadata != null) return false;
if (defaultPolicyAction != null ? !defaultPolicyAction.equals(that.defaultPolicyAction) : that.defaultPolicyAction != null)
return false;
return policy != null ? policy.equals(that.policy) : that.policy == null;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (uuid != null ? uuid.hashCode() : 0);
result = 31 * result + (kind != null ? kind.hashCode() : 0);
result = 31 * result + (environmentUuid != null ? environmentUuid.hashCode() : 0);
result = 31 * result + (hostPorts ? 1 : 0);
result = 31 * result + (metadata != null ? metadata.hashCode() : 0);
result = 31 * result + (defaultPolicyAction != null ? defaultPolicyAction.hashCode() : 0);
result = 31 * result + (policy != null ? policy.hashCode() : 0);
return result;
}
}
|
cjellick/cattle
|
modules/model/src/main/java/io/cattle/platform/core/addon/metadata/NetworkInfo.java
|
Java
|
apache-2.0
| 3,884 |
using FluentAssertions;
using NFugue.Integration.MusicXml;
using NFugue.Staccato;
using System.IO;
using Xunit;
namespace NFugue.Tests.Integration
{
public class MusicXmlParserTests
{
private readonly MusicXmlParser xmlParser = new MusicXmlParser();
[Fact]
public void Hello_world_part_wise()
{
ParseMusicXmlFile("Data/HelloWorldPartWise.xml").Should().Be("V0 C4w |");
}
[Fact]
public void Hello_world_time_wise()
{
ParseMusicXmlFile("Data/HelloWorldTimeWise.xml").Should().Be("V0 C4w |");
}
[Fact]
public void Schumann_frage_beginning()
{
ParseMusicXmlFile("Data/Frage.xml").Should().Be(
"V0 KEY:Ebmaj G4q 'Warst | F4q. 'du Eb4i 'nicht, Eb4q 'heil Bb4i 'ger G4i |");
}
private string ParseMusicXmlFile(string path)
{
string xml = File.ReadAllText(path);
var patternBuilder = new StaccatoPatternBuilder(xmlParser);
xmlParser.Parse(xml);
return patternBuilder.Pattern.ToString();
}
}
}
|
mdileep/NFugue
|
tests/NFugue.Tests/Integration/MusicXmlParserTests.cs
|
C#
|
apache-2.0
| 1,134 |
/*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { SearchBoxComponent } from './search-box.component';
import { IconModule } from '../icon/icon.module';
import { ButtonModule } from '../button/button.module';
import { CommonModule } from '@angular/common';
import { InputResetModule } from '../../directives/input-reset/input-reset.module';
@NgModule({
declarations: [SearchBoxComponent],
imports: [FormsModule, IconModule, ButtonModule, CommonModule, InputResetModule],
exports: [SearchBoxComponent],
})
export class SearchBoxModule {}
|
google/web-prototyping-tool
|
projects/cd-common/src/lib/components/search-box/search-box.module.ts
|
TypeScript
|
apache-2.0
| 1,186 |
/*
Copyright 1996-2008 Ariba, 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.
$Id: //ariba/platform/ui/aribaweb/ariba/ui/aribaweb/util/Parameters.java#3 $
*/
package ariba.ui.aribaweb.util;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import ariba.util.core.Assert;
import ariba.util.core.DebugState;
import ariba.util.core.ListUtil;
import ariba.util.core.MapUtil;
/**
Servlet style parameters from URL or CGI or RFC822 and friends
The parameter names are case insensitive.
We use the java.util classes because the Servlet API requires it.
@aribaapi private
*/
public class Parameters implements Externalizable, DebugState
{
public static final String ClassName = "ariba.ui.aribaweb.util.Parameters";
/**
List of original case names
*/
private java.util.Vector names = new java.util.Vector();
/**
Mapping from case-insensitive names to values
*/
private Hashtable hashtable = new Hashtable();
/**
Any class that implements Externalizable must have
a constructor with no arguments.
*/
public Parameters()
{
}
public Parameters(Map hashtable)
{
Iterator k = hashtable.keySet().iterator();
Iterator e = hashtable.values().iterator();
while (k.hasNext()) {
putParameter((String)k.next(), (String)e.next());
}
}
private Parameters(Hashtable hashtable)
{
}
public void putParameter (String name, String value)
{
String original = name;
name = name.toUpperCase();
if (hashtable.containsKey(name)) {
List vector = (List)hashtable.get(name);
vector.add(value);
return;
}
List vector = ListUtil.list(value);
hashtable.put(name, vector);
names.add(original);
}
public String getParameter (String name)
{
name = name.toUpperCase();
List vector = (List)hashtable.get(name);
if (vector == null) {
return null;
}
Assert.that(vector.size() == 1,
"asked for a multi-valued parameter %s singularly, %s",
name, vector.toString());
return (String)ListUtil.firstElement(vector);
}
public int getParameterCount ()
{
return hashtable.size();
}
public String[] getParameterValues (String name)
{
name = name.toUpperCase();
List vector = (List)hashtable.get(name);
return VectorToStringArray(vector);
}
public Iterator getParameterValuesIterator (String name)
{
name = name.toUpperCase();
List vector = (List)hashtable.get(name);
if (vector == null) {
return null;
}
return vector.iterator();
}
private String[] VectorToStringArray (List vector)
{
if (vector == null) {
return null;
}
int length = vector.size();
String[] strings = new String[length];
vector.toArray(strings);
return strings;
}
public Iterator getParameterNames ()
{
return names.iterator();
}
public String removeParameter (String name)
{
name = name.toUpperCase();
List vector = (List)hashtable.remove(name);
if (vector == null) {
return null;
}
removeName(name);
return (String)ListUtil.firstElement(vector);
}
public String[] removeParameterValues (String name)
{
name = name.toUpperCase();
List vector = (List)hashtable.remove(name);
removeName(name);
return VectorToStringArray(vector);
}
private void removeName (String name)
{
for (int i = 0, s = names.size(); i < s ; i++) {
String string = (String)names.get(i);
if (string.equalsIgnoreCase(name)) {
names.remove(i);
return;
}
}
}
/**
Convenience method which removes the given parameter if it exists,
then puts the new parameter value. Returns the previous parameter
value.
*/
public String replaceParameter (String name, String value)
{
String result = removeParameter(name);
putParameter(name, value);
return result;
}
/**
Implementation of the Externalizable interface
@aribaapi private
*/
public void writeExternal (ObjectOutput output) throws IOException
{
output.writeObject(hashtable);
}
/**
Implementation of the Externalizable interface
@aribaapi private
*/
public void readExternal (ObjectInput input)
throws IOException, ClassNotFoundException
{
hashtable = (Hashtable)input.readObject();
}
public String toString ()
{
return hashtable.toString();
}
public Object debugState ()
{
return MapUtil.map(hashtable);
}
public void clear ()
{
hashtable.clear();
names.clear();
}
}
|
pascalrobert/aribaweb
|
src/aribaweb/src/main/java/ariba/ui/aribaweb/util/Parameters.java
|
Java
|
apache-2.0
| 5,756 |
/*
* Copyright (C) 2010-2013 The SINA WEIBO Open Source Project
*
* 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.joy.library.share.weibo.openapi.legacy;
import android.content.Context;
import android.text.TextUtils;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.net.RequestListener;
import com.sina.weibo.sdk.net.WeiboParameters;
import com.joy.library.share.weibo.openapi.AbsOpenAPI;
/**
* 此类封装了账号的接口,详情见<a href="http://t.cn/8F1Egjs">账号接口</a>
*
* @author SINA
* @date 2014-03-03
*/
public class AccountAPI extends AbsOpenAPI {
/** 学校类型,1:大学、2:高中、3:中专技校、4:初中、5:小学,默认为1。 */
public static final int SCHOOL_TYPE_COLLEGE = 1;
public static final int SCHOOL_TYPE_SENIOR = 2;
public static final int SCHOOL_TYPE_TECHNICAL = 3;
public static final int SCHOOL_TYPE_JUNIOR = 4;
public static final int SCHOOL_TYPE_PRIMARY = 5;
/** 学校首字母,默认为A。 */
public enum CAPITAL {
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z
}
private static final String SERVER_URL_PRIX = API_SERVER + "/account";
public AccountAPI(Context context, String appKey, Oauth2AccessToken accessToken) {
super(context, appKey, accessToken);
}
/**
* 获取当前登录用户的隐私设置。
*
* @param listener 异步请求回调接口
*/
public void getPrivacy(RequestListener listener) {
requestAsync(SERVER_URL_PRIX + "/get_privacy.json", new WeiboParameters(mAppKey), HTTPMETHOD_GET, listener);
}
/**
* 获取所有的学校列表。
* NOTE:参数keyword与capital二者必选其一,且只能选其一 按首字母capital查询时,必须提供province参数
*
* @param province 省份范围,省份ID
* @param city 城市范围,城市ID
* @param area 区域范围,区ID
* @param schoolType 学校类型,可为以下几种: 1:大学,2:高中,3:中专技校,4:初中,5:小学
* <li> {@link #SCHOOL_TYPE_COLLEGE}
* <li> {@link #SCHOOL_TYPE_SENIOR}
* <li> {@link #SCHOOL_TYPE_TECHNICAL}
* <li> {@link #SCHOOL_TYPE_JUNIOR}
* <li> {@link #SCHOOL_TYPE_PRIMARY}
* @param capital 学校首字母,默认为A
* @param keyword 学校名称关键字
* @param count 返回的记录条数,默认为10
* @param listener 异步请求回调接口
*/
public void schoolList(int province, int city, int area, int schoolType, CAPITAL capital, String keyword,
int count, RequestListener listener) {
WeiboParameters params = new WeiboParameters(mAppKey);
params.put("province", province);
params.put("city", city);
params.put("area", area);
params.put("type", schoolType);
if (!TextUtils.isEmpty(capital.name())) {
params.put("capital", capital.name());
} else if (!TextUtils.isEmpty(keyword)) {
params.put("keyword", keyword);
}
params.put("count", count);
requestAsync(SERVER_URL_PRIX + "/profile/school_list.json", params, HTTPMETHOD_GET, listener);
}
/**
* 获取当前登录用户的API访问频率限制情况。
*
* @param listener 异步请求回调接口
*/
public void rateLimitStatus(RequestListener listener) {
requestAsync(SERVER_URL_PRIX + "/rate_limit_status.json", new WeiboParameters(mAppKey), HTTPMETHOD_GET, listener);
}
/**
* OAuth授权之后,获取授权用户的UID。
*
* @param listener 异步请求回调接口
*/
public void getUid(RequestListener listener) {
requestAsync(SERVER_URL_PRIX + "/get_uid.json", new WeiboParameters(mAppKey), HTTPMETHOD_GET, listener);
}
/**
* 退出登录。
*
* @param listener 异步请求回调接口
*/
public void endSession(RequestListener listener) {
requestAsync(SERVER_URL_PRIX + "/end_session.json", new WeiboParameters(mAppKey), HTTPMETHOD_POST, listener);
}
}
|
joy-inc/joy-library
|
library-joy/src/main/java/com/joy/library/share/weibo/openapi/legacy/AccountAPI.java
|
Java
|
apache-2.0
| 4,811 |
@extends('emails.layout')
{{--
This is an email blade for resetting password
The following view data is required:
$contentHeader The callout/header of the email's body
$firstName The name of the recipient.
$link The password reset link.
$code The reset code.
$instanceName Name of the DreamFactory Instance.
--}}
@section('contentBody')
<div style="padding: 10px;">
<p>
Hi {{ $firstName }},
</p>
<div>
You have been invited to the DreamFactory Instance of {{ $instanceName }}. Go to the following url, enter the code below, and set your password to confirm your account.<br/>
<br/>
{{ $link }}
<br/><br/>
Confirmation Code: {{ $code }}<br/>
</div>
<p>
<cite>-- The Dream Team</cite>
</p>
</div>
@stop
|
merhawifissehaye/dreamfactory-configured
|
resources/views/emails/invite.blade.php
|
PHP
|
apache-2.0
| 912 |
/*******************************************************************************
* In the Hi-WAY project we propose a novel approach of executing scientific
* workflows processing Big Data, as found in NGS applications, on distributed
* computational infrastructures. The Hi-WAY software stack comprises the func-
* tional workflow language Cuneiform as well as the Hi-WAY ApplicationMaster
* for Apache Hadoop 2.x (YARN).
*
* List of Contributors:
*
* Jörgen Brandt (HU Berlin)
* Marc Bux (HU Berlin)
* Ulf Leser (HU Berlin)
*
* Jörgen Brandt is funded by the European Commission through the BiobankCloud
* project. Marc Bux is funded by the Deutsche Forschungsgemeinschaft through
* research training group SOAMED (GRK 1651).
*
* Copyright 2014 Humboldt-Universität zu Berlin
*
* 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 de.huberlin.wbi.cuneiform.core.cre;
import java.util.UUID;
import de.huberlin.wbi.cuneiform.core.actormodel.Actor;
import de.huberlin.wbi.cuneiform.core.actormodel.Message;
import de.huberlin.wbi.cuneiform.core.semanticmodel.Ticket;
public class TicketReadyMsg extends Message {
private final UUID queryId;
private final Ticket ticket;
public TicketReadyMsg( Actor sender, UUID queryId, Ticket ticket ) {
super( sender );
if( ticket == null )
throw new NullPointerException( "Ticket set must not be null." );
if( queryId == null )
throw new NullPointerException( "Run ID must not be null." );
this.queryId = queryId;
this.ticket = ticket;
}
public UUID getQueryId() {
return queryId;
}
public Ticket getTicket() {
return ticket;
}
@Override
public String toString() {
return "{ ticketReady, \""+queryId+"\", "+ticket.getTicketId()+", \""+ticket.toString().replace( '\n', ' ' )+"\" }";
}
}
|
mackeprm/cuneiform
|
cuneiform-core/src/main/java/de/huberlin/wbi/cuneiform/core/cre/TicketReadyMsg.java
|
Java
|
apache-2.0
| 2,394 |
export { default } from "./tab-title";
|
Sage/carbon
|
src/components/tabs/__internal__/tab-title/index.d.ts
|
TypeScript
|
apache-2.0
| 39 |
package psidev.psi.mi.jami.datasource;
import psidev.psi.mi.jami.model.InteractionEvidence;
/**
* A Data source of interaction evidences.
* It gives full access to all the interactions using Iterator or the full collection.
* It can also give information about the size of the dataSource
*
* @author Marine Dumousseau (marine@ebi.ac.uk)
* @version $Id$
* @since <pre>08/11/13</pre>
*/
public interface InteractionEvidenceSource<T extends InteractionEvidence> extends InteractionEvidenceStream<T>, InteractionSource<T> {
}
|
MICommunity/psi-jami
|
jami-core/src/main/java/psidev/psi/mi/jami/datasource/InteractionEvidenceSource.java
|
Java
|
apache-2.0
| 532 |
package com.bigbug.android.pp.sync;
import android.content.Context;
import com.bigbug.android.pp.Config;
import java.util.List;
import static com.bigbug.android.pp.util.LogUtils.makeLogTag;
public class EventFeedbackApi {
private static final String TAG = makeLogTag(EventFeedbackApi.class);
private static final String PARAMETER_EVENT_CODE = "code";
private static final String PARAMETER_API_KEY = "apikey";
private static final String PARAMETER_SESSION_ID = "objectid";
private static final String PARAMETER_SURVEY_ID = "surveyId";
private static final String PARAMETER_REGISTRANT_ID = "registrantKey";
private final Context mContext;
private final String mUrl;
public EventFeedbackApi(Context context) {
mContext = context;
mUrl = Config.FEEDBACK_URL;
}
/**
* Posts a session to the event server.
*
* @param sessionId The ID of the session that was reviewed.
* @return whether or not updating succeeded
*/
public boolean sendSessionToServer(String sessionId, List<String> questions) {
// BasicHttpClient httpClient = new BasicHttpClient();
// httpClient.addHeader(PARAMETER_EVENT_CODE, Config.FEEDBACK_API_CODE);
// httpClient.addHeader(PARAMETER_API_KEY, Config.FEEDBACK_API_KEY);
//
// ParameterMap parameterMap = httpClient.newParams();
// parameterMap.add(PARAMETER_SESSION_ID, sessionId);
// parameterMap.add(PARAMETER_SURVEY_ID, Config.FEEDBACK_SURVEY_ID);
// parameterMap.add(PARAMETER_REGISTRANT_ID, Config.FEEDBACK_DUMMY_REGISTRANT_ID);
// int i = 1;
// for (String question : questions) {
// parameterMap.add("q" + i, question);
// i++;
// }
//
// HttpResponse response = httpClient.get(mUrl, parameterMap);
//
// if (response != null && response.getStatus() == HttpURLConnection.HTTP_OK) {
// LOGD(TAG, "Server returned HTTP_OK, so session posting was successful.");
// return true;
// } else {
// LOGE(TAG, "Error posting session: HTTP status " + response.getStatus());
// return false;
// }
return false;
}
}
|
bigbugbb/PrayerPartner
|
app/src/main/java/com/bigbug/android/pp/sync/EventFeedbackApi.java
|
Java
|
apache-2.0
| 2,202 |
/*
* 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.
*/
Ext.namespace('OPF.core.validation');
Ext.define('OPF.core.validation.MessageLevel', {
constructor: function(level, css, cfg) {
cfg = cfg || {};
OPF.core.validation.MessageLevel.superclass.constructor.call(this, cfg);
this.level = level;
this.css = css;
},
getLevel: function() {
return this.level;
},
getCSS: function() {
return this.css;
}
});
OPF.core.validation.MessageLevel.TRACE = new OPF.core.validation.MessageLevel('TRACE', 'msg-trace');
OPF.core.validation.MessageLevel.DEBUG = new OPF.core.validation.MessageLevel('DEBUG', 'msg-debug');
OPF.core.validation.MessageLevel.INFO = new OPF.core.validation.MessageLevel('INFO', 'msg-info');
OPF.core.validation.MessageLevel.WARN = new OPF.core.validation.MessageLevel('WARN', 'msg-warn');
OPF.core.validation.MessageLevel.ERROR = new OPF.core.validation.MessageLevel('ERROR', 'msg-error');
OPF.core.validation.MessageLevel.FATAL = new OPF.core.validation.MessageLevel('FATAL', 'msg-fatal');
|
firejack-open/Firejack-Platform
|
platform/src/main/webapp/js/net/firejack/platform/core/validation/MessageLevel.js
|
JavaScript
|
apache-2.0
| 1,875 |
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.uberfire.ext.wires.shared.preferences.bean;
import org.uberfire.preferences.shared.PropertyFormType;
import org.uberfire.preferences.shared.annotations.Property;
import org.uberfire.preferences.shared.annotations.WorkbenchPreference;
import org.uberfire.preferences.shared.bean.BasePreference;
@WorkbenchPreference(identifier = "MyPreference",
bundleKey = "MyPreference.Label")
public class MyPreference implements BasePreference<MyPreference> {
@Property(bundleKey = "MyPreference.Text")
String text;
@Property(formType = PropertyFormType.BOOLEAN, bundleKey = "MyPreference.SendReports")
boolean sendReports;
@Property(formType = PropertyFormType.COLOR, bundleKey = "MyPreference.BackgroundColor")
String backgroundColor;
@Property(formType = PropertyFormType.NATURAL_NUMBER, bundleKey = "MyPreference.Age")
int age;
@Property(formType = PropertyFormType.SECRET_TEXT, bundleKey = "MyPreference.Password")
String password;
@Property(bundleKey = "MyPreference.MyInnerPreference")
MyInnerPreference myInnerPreference;
@Property(shared = true, bundleKey = "MyPreference.MySharedPreference")
MySharedPreference mySharedPreference;
@Override
public MyPreference defaultValue(final MyPreference defaultValue) {
defaultValue.text = "text";
defaultValue.sendReports = true;
defaultValue.backgroundColor = "ABCDEF";
defaultValue.age = 27;
defaultValue.password = "password";
defaultValue.myInnerPreference.text = "text";
defaultValue.mySharedPreference.text = "text";
return defaultValue;
}
}
|
ederign/uberfire
|
uberfire-extensions/uberfire-wires/uberfire-wires-webapp/src/main/java/org/uberfire/ext/wires/shared/preferences/bean/MyPreference.java
|
Java
|
apache-2.0
| 2,269 |
package com.github.simy4.xpath;
import com.github.simy4.xpath.fixtures.FixtureAccessor;
import com.google.gson.JsonObject;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
import javax.xml.xpath.XPathExpressionException;
@BenchmarkMode(Mode.Throughput)
@State(Scope.Benchmark)
public class GsonJsonBuilderBenchmark {
@Param({ "attr", "simple", "special" })
public String fixtureName;
private FixtureAccessor fixtureAccessor;
@Setup
public void setUp() {
fixtureAccessor = new FixtureAccessor(fixtureName, "json");
}
@Benchmark
public void shouldBuildDocumentFromSetOfXPaths(Blackhole blackhole) throws XPathExpressionException {
var xmlProperties = fixtureAccessor.getXmlProperties();
blackhole.consume(new XmlBuilder()
.putAll(xmlProperties.keySet())
.build(new JsonObject()));
}
}
|
SimY4/xpath-to-xml
|
xpath-to-json-gson/src/jmh/java/com/github/simy4/xpath/GsonJsonBuilderBenchmark.java
|
Java
|
apache-2.0
| 1,179 |
require 'schedule_serializer'
class Payment < ActiveRecord::Base
include IceCube
self.inheritance_column = nil
belongs_to :category
PAYMENT_TYPES = %w[Spend Receive].freeze
PAYMENT_PERIODS = %w[Day Week Month].freeze
validates :name, presence: true
validates :category, presence: true
validates :amount, presence: true
validates :schedule, presence: true
validates :type, presence: true, inclusion: { in: PAYMENT_TYPES }
delegate :name, :type, to: :category, prefix: true
serialize :schedule, ScheduleSerializer.new
end
|
dotledger/dotledger
|
app/models/payment.rb
|
Ruby
|
apache-2.0
| 556 |
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
require "rspec"
RSpec.describe "Google::Apis::MonitoringV1" do
# Minimal test just to ensure no syntax errors in generated code
it "should load" do
expect do
require "google/apis/monitoring_v1"
end.not_to raise_error
expect do
Google::Apis::MonitoringV1::MonitoringService.new
end.not_to raise_error
end
end
|
googleapis/google-api-ruby-client
|
generated/google-apis-monitoring_v1/spec/generated_spec.rb
|
Ruby
|
apache-2.0
| 919 |
package com.frameworkset.platform.menu;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.jsp.PageContext;
import org.apache.log4j.Logger;
import com.frameworkset.platform.config.ConfigManager;
import com.frameworkset.platform.framework.Framework;
import com.frameworkset.platform.framework.FrameworkServlet;
import com.frameworkset.platform.framework.Item;
import com.frameworkset.platform.framework.ItemQueue;
import com.frameworkset.platform.framework.MenuHelper;
import com.frameworkset.platform.framework.MenuItem;
import com.frameworkset.platform.framework.Module;
import com.frameworkset.platform.framework.ModuleQueue;
import com.frameworkset.common.tag.tree.COMTree;
import com.frameworkset.common.tag.tree.itf.ITreeNode;
import com.frameworkset.util.StringUtil;
/**
* <p>Title: BaseColumnTree</p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2006</p>
*
* <p>Company: 三一集团</p>
*
* @author biaoping.yin
* @version 1.0
*/
public class BaseColumnTree extends COMTree implements Serializable{
private static final Logger log = Logger.getLogger(BaseColumnTree.class);
private MenuHelper menuHelper;
private String subsystem;
public void setPageContext(PageContext context)
{
super.setPageContext(context);
subsystem = FrameworkServlet.getSubSystem(this.request,this.response,this.accessControl.getUserAccount());
if(menuHelper == null )
menuHelper = new MenuHelper(subsystem,accessControl);
else
menuHelper.resetControl(accessControl);
}
public boolean hasSon(ITreeNode father) {
String path = father.getId();
boolean hasson = false;
int idx = path.indexOf("::");
if(idx == -1) path = subsystem + "::" + path;
Framework framework = Framework.getInstance(subsystem);
if(father.isRoot() && path.equals(Framework.getSuperMenu(subsystem)))
{
ModuleQueue queue = null;
ItemQueue iqueue = null;
if(ConfigManager.getInstance().securityEnabled())
{
queue = this.menuHelper.getModules();
iqueue = this.menuHelper.getItems();
}
else
{
queue = framework.getModules();
iqueue = framework.getItems();
}
for(int i = 0; i < queue.size(); i ++)
{
MenuItem item = queue.getModule(i);
if(item.isUsed())
{
return hasson = true;
}
}
for(int i = 0; i < iqueue.size(); i ++)
{
MenuItem item = iqueue.getItem(i);
if(item.isUsed())
{
return hasson = true;
}
}
}
else
{
MenuItem menuItem = framework.getMenu(path);
if(menuItem instanceof Item)
{
return hasson = false;
}
else if(menuItem instanceof Module)
{
Module module = (Module)menuItem;
ItemQueue iqueue = null;
ModuleQueue mqueue = null;
if(ConfigManager.getInstance().securityEnabled())
{
iqueue = this.menuHelper.getSubItems(module.getPath());
mqueue = this.menuHelper.getSubModules(module.getPath());
}
else
{
iqueue = module.getItems();
mqueue = module.getSubModules();
}
for(int i = 0; i < iqueue.size(); i ++)
{
if(iqueue.getItem(i).isUsed())
return true;
}
for(int i = 0; i < mqueue.size(); i ++)
{
if(mqueue.getModule(i).isUsed())
return true;
}
}
}
return hasson;
}
public boolean setSon(ITreeNode father, int curLevel) {
String parentPath = father.getId();
ModuleQueue submodules = null;
ItemQueue items = null;
int idx = parentPath.indexOf("::");
if(idx == -1) parentPath = subsystem + "::" + parentPath;
Framework framework = Framework.getInstance(subsystem);
if(father.isRoot() && parentPath.equals(Framework.getSuperMenu(subsystem)))
{
if(ConfigManager.getInstance().securityEnabled())
{
submodules = this.menuHelper.getModules();
items = this.menuHelper.getItems();
}
else
{
submodules = framework.getModules();
items = framework.getItems();
}
}
else
{
if(ConfigManager.getInstance().securityEnabled())
{
items = this.menuHelper.getSubItems(parentPath);
submodules = this.menuHelper.getSubModules(parentPath);
}
else
{
Module module = framework.getModule(parentPath);
items = module.getItems();
submodules = module.getSubModules();
}
}
String treeid = "";
String treeName = "";
String moduleType = "module";
String itemType = "item";
boolean showHref = true;
String memo = null;
String radioValue = null;
String checkboxValue = null;
String path = "";
String nodeLink = null;
for(int i = 0; i < submodules.size(); i ++)
{
Map params = new HashMap();
Module submodule = submodules.getModule(i);
if(!submodule.isUsed())
continue;
treeid = submodule.getPath();
treeName = submodule.getName(request);
path = submodule.getPath();
showHref = false;
addNode(father, treeid, treeName, moduleType, showHref, curLevel, memo,
radioValue, checkboxValue, params);
}
for(int i = 0; i < items.size(); i ++)
{
Map params = new HashMap();
Item subitem = (Item)items.getItem(i);
if(!subitem.isUsed())
continue;
treeid = subitem.getPath();
treeName = subitem.getName(request);
path = subitem.getPath();
showHref = true;
nodeLink = getNodeLink(subitem,null);
//通过参数动态设置节点链接,nodeLink为树型结构中的保留的参数名称,其他应用不能覆盖或使用nodeLink作为参数名称
params.put("nodeLink",nodeLink);
addNode(father, treeid, treeName, itemType, showHref, curLevel, memo,
radioValue, checkboxValue, params);
}
return true;
}
private String getNodeLink(MenuItem menuItem,String sessionid)
{
String nodeLink = request.getContextPath() + "/" + Framework.getUrl(Framework.CONTENT_CONTAINER_URL,sessionid)
+ Framework.MENU_PATH + "=" +
StringUtil.encode(menuItem.getPath(), null) + "&"
+ Framework.MENU_TYPE + "=" +
// Framework.CONTENT_CONTAINER + "&ancestor=1";
Framework.CONTENT_CONTAINER;
return nodeLink;
}
}
|
tzou24/BPS
|
BPS/src/com/frameworkset/platform/menu/BaseColumnTree.java
|
Java
|
apache-2.0
| 7,661 |
#include <bits/stdc++.h>
using namespace std;
#include<string>
int mod(int n)
{
int s=0,c=1,a;
a=n;
while(a>0)
{
s+=a%10;
a/=10;
}
if(s==9)return 2;
else if(s<9)return 1;
if(s%9==0)
{
return 1+mod(s);
}
}
int main()
{
char str[1001];
int i,j,k,a,b,c,s,ln;
while(gets(str))
{
if(str[0]-48==0)return 0;
s=0;
c=0;
ln=strlen(str);
for(i=0;i<ln;i++)
s+=str[i]-48;
if(str[0]-48==9&&ln==1)c=1;
else if(s%9==0&&s==9&&ln!=1)c=2;
if(s%9==0&&s!=9)
{
c=mod(s);
}
if(c>0){
printf("%s",str);
cout << " is a multiple of 9 and has 9-degree "<< c << "." << endl;
}
else
{
printf("%s",str);
cout << " is not a multiple of 9."<<endl;
}
}
}
|
moniruzzaman-monir/Oj-solved
|
UVa all in C++/uva10922.cpp
|
C++
|
apache-2.0
| 917 |
//
// HTTPSStreamFactory.cpp
//
// Library: NetSSL_OpenSSL
// Package: HTTPSClient
// Module: HTTPSStreamFactory
//
// Copyright (c) 2006-2012, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "Poco/Net/HTTPSStreamFactory.h"
#include "Poco/Net/HTTPSClientSession.h"
#include "Poco/Net/HTTPIOStream.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include "Poco/Net/HTTPCredentials.h"
#include "Poco/Net/NetException.h"
#include "Poco/URI.h"
#include "Poco/URIStreamOpener.h"
#include "Poco/UnbufferedStreamBuf.h"
#include "Poco/NullStream.h"
#include "Poco/StreamCopier.h"
#include "Poco/Format.h"
#include "Poco/Version.h"
using Poco::URIStreamFactory;
using Poco::URI;
using Poco::URIStreamOpener;
using Poco::UnbufferedStreamBuf;
namespace Poco {
namespace Net {
HTTPSStreamFactory::HTTPSStreamFactory():
_proxyPort(HTTPSession::HTTP_PORT)
{
}
HTTPSStreamFactory::HTTPSStreamFactory(const std::string& proxyHost, Poco::UInt16 proxyPort):
_proxyHost(proxyHost),
_proxyPort(proxyPort)
{
}
HTTPSStreamFactory::HTTPSStreamFactory(const std::string& proxyHost, Poco::UInt16 proxyPort, const std::string& proxyUsername, const std::string& proxyPassword):
_proxyHost(proxyHost),
_proxyPort(proxyPort),
_proxyUsername(proxyUsername),
_proxyPassword(proxyPassword)
{
}
HTTPSStreamFactory::~HTTPSStreamFactory()
{
}
std::istream* HTTPSStreamFactory::open(const URI& uri)
{
poco_assert (uri.getScheme() == "https" || uri.getScheme() == "http");
URI resolvedURI(uri);
URI proxyUri;
HTTPClientSession* pSession = 0;
HTTPResponse res;
try
{
bool retry = false;
bool authorize = false;
int redirects = 0;
std::string username;
std::string password;
do
{
if (!pSession)
{
if (resolvedURI.getScheme() != "http")
pSession = new HTTPSClientSession(resolvedURI.getHost(), resolvedURI.getPort());
else
pSession = new HTTPClientSession(resolvedURI.getHost(), resolvedURI.getPort());
if (proxyUri.empty())
{
if (!_proxyHost.empty())
{
pSession->setProxy(_proxyHost, _proxyPort);
pSession->setProxyCredentials(_proxyUsername, _proxyPassword);
}
}
else
{
pSession->setProxy(proxyUri.getHost(), proxyUri.getPort());
if (!_proxyUsername.empty())
{
pSession->setProxyCredentials(_proxyUsername, _proxyPassword);
}
}
}
std::string path = resolvedURI.getPathAndQuery();
if (path.empty()) path = "/";
HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
if (authorize)
{
HTTPCredentials::extractCredentials(uri, username, password);
HTTPCredentials cred(username, password);
cred.authenticate(req, res);
}
req.set("User-Agent", Poco::format("poco/%d.%d.%d",
(POCO_VERSION >> 24) & 0xFF,
(POCO_VERSION >> 16) & 0xFF,
(POCO_VERSION >> 8) & 0xFF));
req.set("Accept", "*/*");
pSession->sendRequest(req);
std::istream& rs = pSession->receiveResponse(res);
bool moved = (res.getStatus() == HTTPResponse::HTTP_MOVED_PERMANENTLY ||
res.getStatus() == HTTPResponse::HTTP_FOUND ||
res.getStatus() == HTTPResponse::HTTP_SEE_OTHER ||
res.getStatus() == HTTPResponse::HTTP_TEMPORARY_REDIRECT);
if (moved)
{
resolvedURI.resolve(res.get("Location"));
if (!username.empty())
{
resolvedURI.setUserInfo(username + ":" + password);
authorize = false;
}
delete pSession;
pSession = 0;
++redirects;
retry = true;
}
else if (res.getStatus() == HTTPResponse::HTTP_OK)
{
return new HTTPResponseStream(rs, pSession);
}
else if (res.getStatus() == HTTPResponse::HTTP_USEPROXY && !retry)
{
// The requested resource MUST be accessed through the proxy
// given by the Location field. The Location field gives the
// URI of the proxy. The recipient is expected to repeat this
// single request via the proxy. 305 responses MUST only be generated by origin servers.
// only use for one single request!
proxyUri.resolve(res.get("Location"));
delete pSession;
pSession = 0;
retry = true; // only allow useproxy once
}
else if (res.getStatus() == HTTPResponse::HTTP_UNAUTHORIZED && !authorize)
{
authorize = true;
retry = true;
Poco::NullOutputStream null;
Poco::StreamCopier::copyStream(rs, null);
}
else throw HTTPException(res.getReason(), uri.toString());
}
while (retry && redirects < MAX_REDIRECTS);
throw HTTPException("Too many redirects", uri.toString());
}
catch (...)
{
delete pSession;
throw;
}
}
void HTTPSStreamFactory::registerFactory()
{
URIStreamOpener::defaultOpener().registerStreamFactory("https", new HTTPSStreamFactory);
}
void HTTPSStreamFactory::unregisterFactory()
{
URIStreamOpener::defaultOpener().unregisterStreamFactory("https");
}
} } // namespace Poco::Net
|
macchina-io/macchina.io
|
platform/NetSSL_OpenSSL/src/HTTPSStreamFactory.cpp
|
C++
|
apache-2.0
| 4,963 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2018.02.17 at 03:24:41 PM CET
//
package no.api.meteo.jaxb.temperatureverification.v1_0;
import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
/**
* Element denoting the wind speed by name, meters per second or the Beaufort scale.
*
*
* <p>Java class for windspeed complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="windspeed">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attribute name="mps" use="required">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}decimal">
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </attribute>
* <attribute name="name">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* </restriction>
* </simpleType>
* </attribute>
* <attribute name="beaufort">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <minInclusive value="0"/>
* <maxInclusive value="12"/>
* </restriction>
* </simpleType>
* </attribute>
* <attribute name="id" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "windspeed")
public class Windspeed {
@XmlAttribute(name = "mps", required = true)
protected BigDecimal mps;
@XmlAttribute(name = "name")
protected String name;
@XmlAttribute(name = "beaufort")
protected Integer beaufort;
@XmlAttribute(name = "id")
protected String id;
/**
* Gets the value of the mps property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getMps() {
return mps;
}
/**
* Sets the value of the mps property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setMps(BigDecimal value) {
this.mps = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the beaufort property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getBeaufort() {
return beaufort;
}
/**
* Sets the value of the beaufort property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setBeaufort(Integer value) {
this.beaufort = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
}
|
amedia/meteo
|
meteo-jaxb/src/main/java/no/api/meteo/jaxb/temperatureverification/v1_0/Windspeed.java
|
Java
|
apache-2.0
| 4,167 |
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/ds/model/DescribeLDAPSSettingsRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::DirectoryService::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
DescribeLDAPSSettingsRequest::DescribeLDAPSSettingsRequest() :
m_directoryIdHasBeenSet(false),
m_type(LDAPSType::NOT_SET),
m_typeHasBeenSet(false),
m_nextTokenHasBeenSet(false),
m_limit(0),
m_limitHasBeenSet(false)
{
}
Aws::String DescribeLDAPSSettingsRequest::SerializePayload() const
{
JsonValue payload;
if(m_directoryIdHasBeenSet)
{
payload.WithString("DirectoryId", m_directoryId);
}
if(m_typeHasBeenSet)
{
payload.WithString("Type", LDAPSTypeMapper::GetNameForLDAPSType(m_type));
}
if(m_nextTokenHasBeenSet)
{
payload.WithString("NextToken", m_nextToken);
}
if(m_limitHasBeenSet)
{
payload.WithInteger("Limit", m_limit);
}
return payload.View().WriteReadable();
}
Aws::Http::HeaderValueCollection DescribeLDAPSSettingsRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "DirectoryService_20150416.DescribeLDAPSSettings"));
return headers;
}
|
cedral/aws-sdk-cpp
|
aws-cpp-sdk-ds/source/model/DescribeLDAPSSettingsRequest.cpp
|
C++
|
apache-2.0
| 1,835 |
/*
* Copyright 2014 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef _GAZEBO_DARTMULTIRAYSHAPE_HH_
#define _GAZEBO_DARTMULTIRAYSHAPE_HH_
#include "gazebo/physics/MultiRayShape.hh"
#include "gazebo/physics/dart/DARTTypes.hh"
#include "gazebo/util/system.hh"
namespace gazebo
{
namespace physics
{
/// \ingroup gazebo_physics
/// \addtogroup gazebo_physics_bullet Bullet Physics
/// \{
/// \brief DART specific version of MultiRayShape
class GAZEBO_VISIBLE DARTMultiRayShape : public MultiRayShape
{
/// \brief Constructor.
/// \param[in] _parent Parent Collision.
public: explicit DARTMultiRayShape(CollisionPtr _parent);
/// \brief Destructor.
public: virtual ~DARTMultiRayShape();
// Documentation inherited.
public: virtual void UpdateRays();
/// \brief Add a ray to the collision.
/// \param[in] _start Start location of the ray.
/// \param[in] _end End location of the ray.
protected: void AddRay(const math::Vector3 &_start,
const math::Vector3 &_end);
/// \brief Pointer to the DART physics engine.
private: DARTPhysicsPtr physicsEngine;
};
}
}
#endif
|
arpg/Gazebo
|
gazebo/physics/dart/DARTMultiRayShape.hh
|
C++
|
apache-2.0
| 1,763 |
using System;
namespace MockResponse.Core.Utilities
{
public class DateTimeProvider : IDateTimeProvider
{
public DateTime Now => DateTime.Now;
public DateTime UtcNow => DateTime.UtcNow;
}
}
|
Orbittman/MockResponse
|
MockResponse.Core/Utilities/DateTimeProvider.cs
|
C#
|
apache-2.0
| 222 |
/* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ===========================================================================*/
#include <gtest/gtest.h>
#include <cstddef>
#include <vector>
#include "tfjs-backend-wasm/src/cc/backend.h"
#include "tfjs-backend-wasm/src/cc/kernels/ResizeBilinear.h"
TEST(BATCH_MATMUL, xnn_operator_lifetime) {
tfjs::wasm::init();
ASSERT_EQ(0, tfjs::backend::num_tensors());
const size_t x0_id = 1;
const size_t x1_id = 2;
const size_t x_size = 4;
float x_values[x_size] = {1, 2, 2, 2};
const size_t out_id = 3;
const size_t out_size = 8;
float out_values[out_size] = {0, 0, 0, 0, 0, 0, 0, 0};
tfjs::wasm::register_tensor(x0_id, x_size, x_values);
tfjs::wasm::register_tensor(x1_id, x_size, x_values);
tfjs::wasm::register_tensor(out_id, out_size, out_values);
ASSERT_EQ(3, tfjs::backend::num_tensors());
ASSERT_EQ(0, tfjs::backend::xnn_operator_count);
const size_t batch_size = 1;
// One new xnn_operator should be created for the first call to
// ResizeBilinear.
const size_t old_height0 = 2;
const size_t old_width0 = 1;
const size_t num_channels0 = 2;
const size_t new_height0 = 2;
const size_t new_width0 = 2;
bool align_corners0 = false;
bool half_pixel_centers0 = false;
tfjs::wasm::ResizeBilinear(x0_id, batch_size, old_height0, old_width0,
num_channels0, new_height0, new_width0,
align_corners0, half_pixel_centers0, out_id);
ASSERT_EQ(1, tfjs::backend::xnn_operator_count);
// No new xnn_operators should be created for the second call to
// ResizeBilinear with the same arguments.
tfjs::wasm::ResizeBilinear(x0_id, batch_size, old_height0, old_width0,
num_channels0, new_height0, new_width0,
align_corners0, half_pixel_centers0, out_id);
ASSERT_EQ(1, tfjs::backend::xnn_operator_count);
// No new xnn_operators should be created for the second call to
// ResizeBilinear with a new x id but same arguments.
tfjs::wasm::ResizeBilinear(x1_id, batch_size, old_height0, old_width0,
num_channels0, new_height0, new_width0,
align_corners0, half_pixel_centers0, out_id);
ASSERT_EQ(1, tfjs::backend::xnn_operator_count);
// One new xnn_operator should be created for another call to ResizeBilinear
// with a different num_channels argument.
const size_t old_height1 = 2;
const size_t old_width1 = 2;
const size_t num_channels1 = 1;
const size_t new_height1 = 2;
const size_t new_width1 = 4;
tfjs::wasm::ResizeBilinear(x0_id, batch_size, old_height1, old_width1,
num_channels1, new_height1, new_width1,
align_corners0, half_pixel_centers0, out_id);
ASSERT_EQ(2, tfjs::backend::xnn_operator_count);
// One new xnn_operator should be created for another call to ResizeBilinear
// with a different align_corners argument
bool align_corners1 = true;
tfjs::wasm::ResizeBilinear(x0_id, batch_size, old_height1, old_width1,
num_channels1, new_height1, new_width1,
align_corners1, half_pixel_centers0, out_id);
ASSERT_EQ(3, tfjs::backend::xnn_operator_count);
tfjs::wasm::dispose();
}
|
tensorflow/tfjs
|
tfjs-backend-wasm/src/cc/kernels/ResizeBilinear_test.cc
|
C++
|
apache-2.0
| 3,867 |
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2021 DBeaver Corp and others
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.dbeaver.model.impl.edit;
import org.jkiss.dbeaver.model.DBPDataSource;
import org.jkiss.dbeaver.model.sql.SQLUtils;
/**
* Comment action
*/
public class SQLDatabasePersistActionComment extends SQLDatabasePersistAction {
public SQLDatabasePersistActionComment(DBPDataSource dataSource, String comment) {
super("Comment",
SQLUtils.getDialectFromDataSource(dataSource).getSingleLineComments()[0] + " " + comment,
ActionType.COMMENT,
false);
}
}
|
Sargul/dbeaver
|
plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/impl/edit/SQLDatabasePersistActionComment.java
|
Java
|
apache-2.0
| 1,173 |
//
// Copyright 2014 Gustavo J Knuppe (https://github.com/knuppe)
//
// 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.
//
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - May you do good and not evil. -
// - May you find forgiveness for yourself and forgive others. -
// - May you share freely, never taking more than you give. -
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//
using System.Collections.Generic;
namespace SharpNL.Utility.FeatureGen {
/// <summary>
/// An interface for generating features for name entity identification and for
/// updating document level contexts.
/// </summary>
/// <remarks>
/// Most implementors do not need the adaptive functionality of this
/// interface, they should extend the <see cref="FeatureGeneratorAdapter"/> class instead.
///
/// Feature generation is not thread safe and a instance of a feature generator
/// must only be called from one thread. The resources used by a feature
/// generator are typically shared between man instances of features generators
/// which are called from many threads and have to be thread safe.
/// </remarks>
/// <seealso cref="FeatureGeneratorAdapter"/>
public interface IAdaptiveFeatureGenerator {
/// <summary>
/// Adds the appropriate features for the token at the specified index with the
/// specified array of previous outcomes to the specified list of features.
/// </summary>
/// <param name="features">The list of features to be added to.</param>
/// <param name="tokens">The tokens of the sentence or other text unit being processed.</param>
/// <param name="index">The index of the token which is currently being processed.</param>
/// <param name="previousOutcomes">The outcomes for the tokens prior to the specified index.</param>
void CreateFeatures(List<string> features, string[] tokens, int index, string[] previousOutcomes);
/// <summary>
/// Informs the feature generator that the specified tokens have been classified with the
/// corresponding set of specified outcomes.
/// </summary>
/// <param name="tokens">The tokens of the sentence or other text unit which has been processed.</param>
/// <param name="outcomes">The outcomes associated with the specified tokens.</param>
void UpdateAdaptiveData(string[] tokens, string[] outcomes);
/// <summary>
/// Informs the feature generator that the context of the adaptive data (typically a document)
/// is no longer valid.
/// </summary>
void ClearAdaptiveData();
}
}
|
knuppe/SharpNL
|
src/SharpNL/Utility/FeatureGen/IAdaptiveFeatureGenerator.cs
|
C#
|
apache-2.0
| 3,334 |
package jp.sourceforge.ea2ddl.dao.cbean.cq.bs;
import java.util.Map;
import org.seasar.dbflute.cbean.*;
import org.seasar.dbflute.cbean.cvalue.ConditionValue;
import org.seasar.dbflute.cbean.sqlclause.SqlClause;
import jp.sourceforge.ea2ddl.dao.cbean.cq.ciq.*;
import jp.sourceforge.ea2ddl.dao.cbean.*;
import jp.sourceforge.ea2ddl.dao.cbean.cq.*;
/**
* The base condition-query of t_connector.
* @author DBFlute(AutoGenerator)
*/
public class BsTConnectorCQ extends AbstractBsTConnectorCQ {
// ===================================================================================
// Attribute
// =========
protected TConnectorCIQ _inlineQuery;
// ===================================================================================
// Constructor
// ===========
public BsTConnectorCQ(ConditionQuery childQuery, SqlClause sqlClause, String aliasName, int nestLevel) {
super(childQuery, sqlClause, aliasName, nestLevel);
}
// ===================================================================================
// Inline
// ======
/**
* Prepare inline query. <br />
* {select ... from ... left outer join (select * from t_connector) where abc = [abc] ...}
* @return Inline query. (NotNull)
*/
public TConnectorCIQ inline() {
if (_inlineQuery == null) {
_inlineQuery = new TConnectorCIQ(getChildQuery(), getSqlClause(), getAliasName(), getNestLevel(), this);
}
_inlineQuery.xsetOnClauseInline(false); return _inlineQuery;
}
/**
* Prepare on-clause query. <br />
* {select ... from ... left outer join t_connector on ... and abc = [abc] ...}
* @return On-clause query. (NotNull)
*/
public TConnectorCIQ on() {
if (isBaseQuery(this)) { throw new UnsupportedOperationException("Unsupported on-clause for local table!"); }
TConnectorCIQ inlineQuery = inline(); inlineQuery.xsetOnClauseInline(true); return inlineQuery;
}
// ===================================================================================
// Query
// =====
protected ConditionValue _connectorId;
public ConditionValue getConnectorId() {
if (_connectorId == null) { _connectorId = new ConditionValue(); }
return _connectorId;
}
protected ConditionValue getCValueConnectorId() { return getConnectorId(); }
public BsTConnectorCQ addOrderBy_ConnectorId_Asc() { regOBA("Connector_ID"); return this; }
public BsTConnectorCQ addOrderBy_ConnectorId_Desc() { regOBD("Connector_ID"); return this; }
protected ConditionValue _name;
public ConditionValue getName() {
if (_name == null) { _name = new ConditionValue(); }
return _name;
}
protected ConditionValue getCValueName() { return getName(); }
public BsTConnectorCQ addOrderBy_Name_Asc() { regOBA("Name"); return this; }
public BsTConnectorCQ addOrderBy_Name_Desc() { regOBD("Name"); return this; }
protected ConditionValue _direction;
public ConditionValue getDirection() {
if (_direction == null) { _direction = new ConditionValue(); }
return _direction;
}
protected ConditionValue getCValueDirection() { return getDirection(); }
public BsTConnectorCQ addOrderBy_Direction_Asc() { regOBA("Direction"); return this; }
public BsTConnectorCQ addOrderBy_Direction_Desc() { regOBD("Direction"); return this; }
protected ConditionValue _notes;
public ConditionValue getNotes() {
if (_notes == null) { _notes = new ConditionValue(); }
return _notes;
}
protected ConditionValue getCValueNotes() { return getNotes(); }
public BsTConnectorCQ addOrderBy_Notes_Asc() { regOBA("Notes"); return this; }
public BsTConnectorCQ addOrderBy_Notes_Desc() { regOBD("Notes"); return this; }
protected ConditionValue _connectorType;
public ConditionValue getConnectorType() {
if (_connectorType == null) { _connectorType = new ConditionValue(); }
return _connectorType;
}
protected ConditionValue getCValueConnectorType() { return getConnectorType(); }
public BsTConnectorCQ addOrderBy_ConnectorType_Asc() { regOBA("Connector_Type"); return this; }
public BsTConnectorCQ addOrderBy_ConnectorType_Desc() { regOBD("Connector_Type"); return this; }
protected ConditionValue _subtype;
public ConditionValue getSubtype() {
if (_subtype == null) { _subtype = new ConditionValue(); }
return _subtype;
}
protected ConditionValue getCValueSubtype() { return getSubtype(); }
public BsTConnectorCQ addOrderBy_Subtype_Asc() { regOBA("SubType"); return this; }
public BsTConnectorCQ addOrderBy_Subtype_Desc() { regOBD("SubType"); return this; }
protected ConditionValue _sourcecard;
public ConditionValue getSourcecard() {
if (_sourcecard == null) { _sourcecard = new ConditionValue(); }
return _sourcecard;
}
protected ConditionValue getCValueSourcecard() { return getSourcecard(); }
public BsTConnectorCQ addOrderBy_Sourcecard_Asc() { regOBA("SourceCard"); return this; }
public BsTConnectorCQ addOrderBy_Sourcecard_Desc() { regOBD("SourceCard"); return this; }
protected ConditionValue _sourceaccess;
public ConditionValue getSourceaccess() {
if (_sourceaccess == null) { _sourceaccess = new ConditionValue(); }
return _sourceaccess;
}
protected ConditionValue getCValueSourceaccess() { return getSourceaccess(); }
public BsTConnectorCQ addOrderBy_Sourceaccess_Asc() { regOBA("SourceAccess"); return this; }
public BsTConnectorCQ addOrderBy_Sourceaccess_Desc() { regOBD("SourceAccess"); return this; }
protected ConditionValue _sourceelement;
public ConditionValue getSourceelement() {
if (_sourceelement == null) { _sourceelement = new ConditionValue(); }
return _sourceelement;
}
protected ConditionValue getCValueSourceelement() { return getSourceelement(); }
public BsTConnectorCQ addOrderBy_Sourceelement_Asc() { regOBA("SourceElement"); return this; }
public BsTConnectorCQ addOrderBy_Sourceelement_Desc() { regOBD("SourceElement"); return this; }
protected ConditionValue _destcard;
public ConditionValue getDestcard() {
if (_destcard == null) { _destcard = new ConditionValue(); }
return _destcard;
}
protected ConditionValue getCValueDestcard() { return getDestcard(); }
public BsTConnectorCQ addOrderBy_Destcard_Asc() { regOBA("DestCard"); return this; }
public BsTConnectorCQ addOrderBy_Destcard_Desc() { regOBD("DestCard"); return this; }
protected ConditionValue _destaccess;
public ConditionValue getDestaccess() {
if (_destaccess == null) { _destaccess = new ConditionValue(); }
return _destaccess;
}
protected ConditionValue getCValueDestaccess() { return getDestaccess(); }
public BsTConnectorCQ addOrderBy_Destaccess_Asc() { regOBA("DestAccess"); return this; }
public BsTConnectorCQ addOrderBy_Destaccess_Desc() { regOBD("DestAccess"); return this; }
protected ConditionValue _destelement;
public ConditionValue getDestelement() {
if (_destelement == null) { _destelement = new ConditionValue(); }
return _destelement;
}
protected ConditionValue getCValueDestelement() { return getDestelement(); }
public BsTConnectorCQ addOrderBy_Destelement_Asc() { regOBA("DestElement"); return this; }
public BsTConnectorCQ addOrderBy_Destelement_Desc() { regOBD("DestElement"); return this; }
protected ConditionValue _sourcerole;
public ConditionValue getSourcerole() {
if (_sourcerole == null) { _sourcerole = new ConditionValue(); }
return _sourcerole;
}
protected ConditionValue getCValueSourcerole() { return getSourcerole(); }
protected Map<String, TOperationCQ> _sourcerole_InScopeSubQuery_TOperationBySourceroleMap;
public Map<String, TOperationCQ> getSourcerole_InScopeSubQuery_TOperationBySourcerole() { return _sourcerole_InScopeSubQuery_TOperationBySourceroleMap; }
public String keepSourcerole_InScopeSubQuery_TOperationBySourcerole(TOperationCQ subQuery) {
if (_sourcerole_InScopeSubQuery_TOperationBySourceroleMap == null) { _sourcerole_InScopeSubQuery_TOperationBySourceroleMap = newLinkedHashMap(); }
String key = "subQueryMapKey" + (_sourcerole_InScopeSubQuery_TOperationBySourceroleMap.size() + 1);
_sourcerole_InScopeSubQuery_TOperationBySourceroleMap.put(key, subQuery); return "sourcerole_InScopeSubQuery_TOperationBySourcerole." + key;
}
public BsTConnectorCQ addOrderBy_Sourcerole_Asc() { regOBA("SourceRole"); return this; }
public BsTConnectorCQ addOrderBy_Sourcerole_Desc() { regOBD("SourceRole"); return this; }
protected ConditionValue _sourceroletype;
public ConditionValue getSourceroletype() {
if (_sourceroletype == null) { _sourceroletype = new ConditionValue(); }
return _sourceroletype;
}
protected ConditionValue getCValueSourceroletype() { return getSourceroletype(); }
public BsTConnectorCQ addOrderBy_Sourceroletype_Asc() { regOBA("SourceRoleType"); return this; }
public BsTConnectorCQ addOrderBy_Sourceroletype_Desc() { regOBD("SourceRoleType"); return this; }
protected ConditionValue _sourcerolenote;
public ConditionValue getSourcerolenote() {
if (_sourcerolenote == null) { _sourcerolenote = new ConditionValue(); }
return _sourcerolenote;
}
protected ConditionValue getCValueSourcerolenote() { return getSourcerolenote(); }
public BsTConnectorCQ addOrderBy_Sourcerolenote_Asc() { regOBA("SourceRoleNote"); return this; }
public BsTConnectorCQ addOrderBy_Sourcerolenote_Desc() { regOBD("SourceRoleNote"); return this; }
protected ConditionValue _sourcecontainment;
public ConditionValue getSourcecontainment() {
if (_sourcecontainment == null) { _sourcecontainment = new ConditionValue(); }
return _sourcecontainment;
}
protected ConditionValue getCValueSourcecontainment() { return getSourcecontainment(); }
public BsTConnectorCQ addOrderBy_Sourcecontainment_Asc() { regOBA("SourceContainment"); return this; }
public BsTConnectorCQ addOrderBy_Sourcecontainment_Desc() { regOBD("SourceContainment"); return this; }
protected ConditionValue _sourceisaggregate;
public ConditionValue getSourceisaggregate() {
if (_sourceisaggregate == null) { _sourceisaggregate = new ConditionValue(); }
return _sourceisaggregate;
}
protected ConditionValue getCValueSourceisaggregate() { return getSourceisaggregate(); }
public BsTConnectorCQ addOrderBy_Sourceisaggregate_Asc() { regOBA("SourceIsAggregate"); return this; }
public BsTConnectorCQ addOrderBy_Sourceisaggregate_Desc() { regOBD("SourceIsAggregate"); return this; }
protected ConditionValue _sourceisordered;
public ConditionValue getSourceisordered() {
if (_sourceisordered == null) { _sourceisordered = new ConditionValue(); }
return _sourceisordered;
}
protected ConditionValue getCValueSourceisordered() { return getSourceisordered(); }
public BsTConnectorCQ addOrderBy_Sourceisordered_Asc() { regOBA("SourceIsOrdered"); return this; }
public BsTConnectorCQ addOrderBy_Sourceisordered_Desc() { regOBD("SourceIsOrdered"); return this; }
protected ConditionValue _sourcequalifier;
public ConditionValue getSourcequalifier() {
if (_sourcequalifier == null) { _sourcequalifier = new ConditionValue(); }
return _sourcequalifier;
}
protected ConditionValue getCValueSourcequalifier() { return getSourcequalifier(); }
public BsTConnectorCQ addOrderBy_Sourcequalifier_Asc() { regOBA("SourceQualifier"); return this; }
public BsTConnectorCQ addOrderBy_Sourcequalifier_Desc() { regOBD("SourceQualifier"); return this; }
protected ConditionValue _destrole;
public ConditionValue getDestrole() {
if (_destrole == null) { _destrole = new ConditionValue(); }
return _destrole;
}
protected ConditionValue getCValueDestrole() { return getDestrole(); }
protected Map<String, TOperationCQ> _destrole_InScopeSubQuery_TOperationByDestroleMap;
public Map<String, TOperationCQ> getDestrole_InScopeSubQuery_TOperationByDestrole() { return _destrole_InScopeSubQuery_TOperationByDestroleMap; }
public String keepDestrole_InScopeSubQuery_TOperationByDestrole(TOperationCQ subQuery) {
if (_destrole_InScopeSubQuery_TOperationByDestroleMap == null) { _destrole_InScopeSubQuery_TOperationByDestroleMap = newLinkedHashMap(); }
String key = "subQueryMapKey" + (_destrole_InScopeSubQuery_TOperationByDestroleMap.size() + 1);
_destrole_InScopeSubQuery_TOperationByDestroleMap.put(key, subQuery); return "destrole_InScopeSubQuery_TOperationByDestrole." + key;
}
public BsTConnectorCQ addOrderBy_Destrole_Asc() { regOBA("DestRole"); return this; }
public BsTConnectorCQ addOrderBy_Destrole_Desc() { regOBD("DestRole"); return this; }
protected ConditionValue _destroletype;
public ConditionValue getDestroletype() {
if (_destroletype == null) { _destroletype = new ConditionValue(); }
return _destroletype;
}
protected ConditionValue getCValueDestroletype() { return getDestroletype(); }
public BsTConnectorCQ addOrderBy_Destroletype_Asc() { regOBA("DestRoleType"); return this; }
public BsTConnectorCQ addOrderBy_Destroletype_Desc() { regOBD("DestRoleType"); return this; }
protected ConditionValue _destrolenote;
public ConditionValue getDestrolenote() {
if (_destrolenote == null) { _destrolenote = new ConditionValue(); }
return _destrolenote;
}
protected ConditionValue getCValueDestrolenote() { return getDestrolenote(); }
public BsTConnectorCQ addOrderBy_Destrolenote_Asc() { regOBA("DestRoleNote"); return this; }
public BsTConnectorCQ addOrderBy_Destrolenote_Desc() { regOBD("DestRoleNote"); return this; }
protected ConditionValue _destcontainment;
public ConditionValue getDestcontainment() {
if (_destcontainment == null) { _destcontainment = new ConditionValue(); }
return _destcontainment;
}
protected ConditionValue getCValueDestcontainment() { return getDestcontainment(); }
public BsTConnectorCQ addOrderBy_Destcontainment_Asc() { regOBA("DestContainment"); return this; }
public BsTConnectorCQ addOrderBy_Destcontainment_Desc() { regOBD("DestContainment"); return this; }
protected ConditionValue _destisaggregate;
public ConditionValue getDestisaggregate() {
if (_destisaggregate == null) { _destisaggregate = new ConditionValue(); }
return _destisaggregate;
}
protected ConditionValue getCValueDestisaggregate() { return getDestisaggregate(); }
public BsTConnectorCQ addOrderBy_Destisaggregate_Asc() { regOBA("DestIsAggregate"); return this; }
public BsTConnectorCQ addOrderBy_Destisaggregate_Desc() { regOBD("DestIsAggregate"); return this; }
protected ConditionValue _destisordered;
public ConditionValue getDestisordered() {
if (_destisordered == null) { _destisordered = new ConditionValue(); }
return _destisordered;
}
protected ConditionValue getCValueDestisordered() { return getDestisordered(); }
public BsTConnectorCQ addOrderBy_Destisordered_Asc() { regOBA("DestIsOrdered"); return this; }
public BsTConnectorCQ addOrderBy_Destisordered_Desc() { regOBD("DestIsOrdered"); return this; }
protected ConditionValue _destqualifier;
public ConditionValue getDestqualifier() {
if (_destqualifier == null) { _destqualifier = new ConditionValue(); }
return _destqualifier;
}
protected ConditionValue getCValueDestqualifier() { return getDestqualifier(); }
public BsTConnectorCQ addOrderBy_Destqualifier_Asc() { regOBA("DestQualifier"); return this; }
public BsTConnectorCQ addOrderBy_Destqualifier_Desc() { regOBD("DestQualifier"); return this; }
protected ConditionValue _startObjectId;
public ConditionValue getStartObjectId() {
if (_startObjectId == null) { _startObjectId = new ConditionValue(); }
return _startObjectId;
}
protected ConditionValue getCValueStartObjectId() { return getStartObjectId(); }
protected Map<String, TObjectCQ> _startObjectId_InScopeSubQuery_TObjectByStartObjectIdMap;
public Map<String, TObjectCQ> getStartObjectId_InScopeSubQuery_TObjectByStartObjectId() { return _startObjectId_InScopeSubQuery_TObjectByStartObjectIdMap; }
public String keepStartObjectId_InScopeSubQuery_TObjectByStartObjectId(TObjectCQ subQuery) {
if (_startObjectId_InScopeSubQuery_TObjectByStartObjectIdMap == null) { _startObjectId_InScopeSubQuery_TObjectByStartObjectIdMap = newLinkedHashMap(); }
String key = "subQueryMapKey" + (_startObjectId_InScopeSubQuery_TObjectByStartObjectIdMap.size() + 1);
_startObjectId_InScopeSubQuery_TObjectByStartObjectIdMap.put(key, subQuery); return "startObjectId_InScopeSubQuery_TObjectByStartObjectId." + key;
}
public BsTConnectorCQ addOrderBy_StartObjectId_Asc() { regOBA("Start_Object_ID"); return this; }
public BsTConnectorCQ addOrderBy_StartObjectId_Desc() { regOBD("Start_Object_ID"); return this; }
protected ConditionValue _endObjectId;
public ConditionValue getEndObjectId() {
if (_endObjectId == null) { _endObjectId = new ConditionValue(); }
return _endObjectId;
}
protected ConditionValue getCValueEndObjectId() { return getEndObjectId(); }
protected Map<String, TObjectCQ> _endObjectId_InScopeSubQuery_TObjectByEndObjectIdMap;
public Map<String, TObjectCQ> getEndObjectId_InScopeSubQuery_TObjectByEndObjectId() { return _endObjectId_InScopeSubQuery_TObjectByEndObjectIdMap; }
public String keepEndObjectId_InScopeSubQuery_TObjectByEndObjectId(TObjectCQ subQuery) {
if (_endObjectId_InScopeSubQuery_TObjectByEndObjectIdMap == null) { _endObjectId_InScopeSubQuery_TObjectByEndObjectIdMap = newLinkedHashMap(); }
String key = "subQueryMapKey" + (_endObjectId_InScopeSubQuery_TObjectByEndObjectIdMap.size() + 1);
_endObjectId_InScopeSubQuery_TObjectByEndObjectIdMap.put(key, subQuery); return "endObjectId_InScopeSubQuery_TObjectByEndObjectId." + key;
}
public BsTConnectorCQ addOrderBy_EndObjectId_Asc() { regOBA("End_Object_ID"); return this; }
public BsTConnectorCQ addOrderBy_EndObjectId_Desc() { regOBD("End_Object_ID"); return this; }
protected ConditionValue _topStartLabel;
public ConditionValue getTopStartLabel() {
if (_topStartLabel == null) { _topStartLabel = new ConditionValue(); }
return _topStartLabel;
}
protected ConditionValue getCValueTopStartLabel() { return getTopStartLabel(); }
public BsTConnectorCQ addOrderBy_TopStartLabel_Asc() { regOBA("Top_Start_Label"); return this; }
public BsTConnectorCQ addOrderBy_TopStartLabel_Desc() { regOBD("Top_Start_Label"); return this; }
protected ConditionValue _topMidLabel;
public ConditionValue getTopMidLabel() {
if (_topMidLabel == null) { _topMidLabel = new ConditionValue(); }
return _topMidLabel;
}
protected ConditionValue getCValueTopMidLabel() { return getTopMidLabel(); }
public BsTConnectorCQ addOrderBy_TopMidLabel_Asc() { regOBA("Top_Mid_Label"); return this; }
public BsTConnectorCQ addOrderBy_TopMidLabel_Desc() { regOBD("Top_Mid_Label"); return this; }
protected ConditionValue _topEndLabel;
public ConditionValue getTopEndLabel() {
if (_topEndLabel == null) { _topEndLabel = new ConditionValue(); }
return _topEndLabel;
}
protected ConditionValue getCValueTopEndLabel() { return getTopEndLabel(); }
public BsTConnectorCQ addOrderBy_TopEndLabel_Asc() { regOBA("Top_End_Label"); return this; }
public BsTConnectorCQ addOrderBy_TopEndLabel_Desc() { regOBD("Top_End_Label"); return this; }
protected ConditionValue _btmStartLabel;
public ConditionValue getBtmStartLabel() {
if (_btmStartLabel == null) { _btmStartLabel = new ConditionValue(); }
return _btmStartLabel;
}
protected ConditionValue getCValueBtmStartLabel() { return getBtmStartLabel(); }
public BsTConnectorCQ addOrderBy_BtmStartLabel_Asc() { regOBA("Btm_Start_Label"); return this; }
public BsTConnectorCQ addOrderBy_BtmStartLabel_Desc() { regOBD("Btm_Start_Label"); return this; }
protected ConditionValue _btmMidLabel;
public ConditionValue getBtmMidLabel() {
if (_btmMidLabel == null) { _btmMidLabel = new ConditionValue(); }
return _btmMidLabel;
}
protected ConditionValue getCValueBtmMidLabel() { return getBtmMidLabel(); }
public BsTConnectorCQ addOrderBy_BtmMidLabel_Asc() { regOBA("Btm_Mid_Label"); return this; }
public BsTConnectorCQ addOrderBy_BtmMidLabel_Desc() { regOBD("Btm_Mid_Label"); return this; }
protected ConditionValue _btmEndLabel;
public ConditionValue getBtmEndLabel() {
if (_btmEndLabel == null) { _btmEndLabel = new ConditionValue(); }
return _btmEndLabel;
}
protected ConditionValue getCValueBtmEndLabel() { return getBtmEndLabel(); }
public BsTConnectorCQ addOrderBy_BtmEndLabel_Asc() { regOBA("Btm_End_Label"); return this; }
public BsTConnectorCQ addOrderBy_BtmEndLabel_Desc() { regOBD("Btm_End_Label"); return this; }
protected ConditionValue _startEdge;
public ConditionValue getStartEdge() {
if (_startEdge == null) { _startEdge = new ConditionValue(); }
return _startEdge;
}
protected ConditionValue getCValueStartEdge() { return getStartEdge(); }
public BsTConnectorCQ addOrderBy_StartEdge_Asc() { regOBA("Start_Edge"); return this; }
public BsTConnectorCQ addOrderBy_StartEdge_Desc() { regOBD("Start_Edge"); return this; }
protected ConditionValue _endEdge;
public ConditionValue getEndEdge() {
if (_endEdge == null) { _endEdge = new ConditionValue(); }
return _endEdge;
}
protected ConditionValue getCValueEndEdge() { return getEndEdge(); }
public BsTConnectorCQ addOrderBy_EndEdge_Asc() { regOBA("End_Edge"); return this; }
public BsTConnectorCQ addOrderBy_EndEdge_Desc() { regOBD("End_Edge"); return this; }
protected ConditionValue _ptstartx;
public ConditionValue getPtstartx() {
if (_ptstartx == null) { _ptstartx = new ConditionValue(); }
return _ptstartx;
}
protected ConditionValue getCValuePtstartx() { return getPtstartx(); }
public BsTConnectorCQ addOrderBy_Ptstartx_Asc() { regOBA("PtStartX"); return this; }
public BsTConnectorCQ addOrderBy_Ptstartx_Desc() { regOBD("PtStartX"); return this; }
protected ConditionValue _ptstarty;
public ConditionValue getPtstarty() {
if (_ptstarty == null) { _ptstarty = new ConditionValue(); }
return _ptstarty;
}
protected ConditionValue getCValuePtstarty() { return getPtstarty(); }
public BsTConnectorCQ addOrderBy_Ptstarty_Asc() { regOBA("PtStartY"); return this; }
public BsTConnectorCQ addOrderBy_Ptstarty_Desc() { regOBD("PtStartY"); return this; }
protected ConditionValue _ptendx;
public ConditionValue getPtendx() {
if (_ptendx == null) { _ptendx = new ConditionValue(); }
return _ptendx;
}
protected ConditionValue getCValuePtendx() { return getPtendx(); }
public BsTConnectorCQ addOrderBy_Ptendx_Asc() { regOBA("PtEndX"); return this; }
public BsTConnectorCQ addOrderBy_Ptendx_Desc() { regOBD("PtEndX"); return this; }
protected ConditionValue _ptendy;
public ConditionValue getPtendy() {
if (_ptendy == null) { _ptendy = new ConditionValue(); }
return _ptendy;
}
protected ConditionValue getCValuePtendy() { return getPtendy(); }
public BsTConnectorCQ addOrderBy_Ptendy_Asc() { regOBA("PtEndY"); return this; }
public BsTConnectorCQ addOrderBy_Ptendy_Desc() { regOBD("PtEndY"); return this; }
protected ConditionValue _seqno;
public ConditionValue getSeqno() {
if (_seqno == null) { _seqno = new ConditionValue(); }
return _seqno;
}
protected ConditionValue getCValueSeqno() { return getSeqno(); }
public BsTConnectorCQ addOrderBy_Seqno_Asc() { regOBA("SeqNo"); return this; }
public BsTConnectorCQ addOrderBy_Seqno_Desc() { regOBD("SeqNo"); return this; }
protected ConditionValue _headstyle;
public ConditionValue getHeadstyle() {
if (_headstyle == null) { _headstyle = new ConditionValue(); }
return _headstyle;
}
protected ConditionValue getCValueHeadstyle() { return getHeadstyle(); }
public BsTConnectorCQ addOrderBy_Headstyle_Asc() { regOBA("HeadStyle"); return this; }
public BsTConnectorCQ addOrderBy_Headstyle_Desc() { regOBD("HeadStyle"); return this; }
protected ConditionValue _linestyle;
public ConditionValue getLinestyle() {
if (_linestyle == null) { _linestyle = new ConditionValue(); }
return _linestyle;
}
protected ConditionValue getCValueLinestyle() { return getLinestyle(); }
public BsTConnectorCQ addOrderBy_Linestyle_Asc() { regOBA("LineStyle"); return this; }
public BsTConnectorCQ addOrderBy_Linestyle_Desc() { regOBD("LineStyle"); return this; }
protected ConditionValue _routestyle;
public ConditionValue getRoutestyle() {
if (_routestyle == null) { _routestyle = new ConditionValue(); }
return _routestyle;
}
protected ConditionValue getCValueRoutestyle() { return getRoutestyle(); }
public BsTConnectorCQ addOrderBy_Routestyle_Asc() { regOBA("RouteStyle"); return this; }
public BsTConnectorCQ addOrderBy_Routestyle_Desc() { regOBD("RouteStyle"); return this; }
protected ConditionValue _isbold;
public ConditionValue getIsbold() {
if (_isbold == null) { _isbold = new ConditionValue(); }
return _isbold;
}
protected ConditionValue getCValueIsbold() { return getIsbold(); }
public BsTConnectorCQ addOrderBy_Isbold_Asc() { regOBA("IsBold"); return this; }
public BsTConnectorCQ addOrderBy_Isbold_Desc() { regOBD("IsBold"); return this; }
protected ConditionValue _linecolor;
public ConditionValue getLinecolor() {
if (_linecolor == null) { _linecolor = new ConditionValue(); }
return _linecolor;
}
protected ConditionValue getCValueLinecolor() { return getLinecolor(); }
public BsTConnectorCQ addOrderBy_Linecolor_Asc() { regOBA("LineColor"); return this; }
public BsTConnectorCQ addOrderBy_Linecolor_Desc() { regOBD("LineColor"); return this; }
protected ConditionValue _stereotype;
public ConditionValue getStereotype() {
if (_stereotype == null) { _stereotype = new ConditionValue(); }
return _stereotype;
}
protected ConditionValue getCValueStereotype() { return getStereotype(); }
public BsTConnectorCQ addOrderBy_Stereotype_Asc() { regOBA("Stereotype"); return this; }
public BsTConnectorCQ addOrderBy_Stereotype_Desc() { regOBD("Stereotype"); return this; }
protected ConditionValue _virtualinheritance;
public ConditionValue getVirtualinheritance() {
if (_virtualinheritance == null) { _virtualinheritance = new ConditionValue(); }
return _virtualinheritance;
}
protected ConditionValue getCValueVirtualinheritance() { return getVirtualinheritance(); }
public BsTConnectorCQ addOrderBy_Virtualinheritance_Asc() { regOBA("VirtualInheritance"); return this; }
public BsTConnectorCQ addOrderBy_Virtualinheritance_Desc() { regOBD("VirtualInheritance"); return this; }
protected ConditionValue _linkaccess;
public ConditionValue getLinkaccess() {
if (_linkaccess == null) { _linkaccess = new ConditionValue(); }
return _linkaccess;
}
protected ConditionValue getCValueLinkaccess() { return getLinkaccess(); }
public BsTConnectorCQ addOrderBy_Linkaccess_Asc() { regOBA("LinkAccess"); return this; }
public BsTConnectorCQ addOrderBy_Linkaccess_Desc() { regOBD("LinkAccess"); return this; }
protected ConditionValue _pdata1;
public ConditionValue getPdata1() {
if (_pdata1 == null) { _pdata1 = new ConditionValue(); }
return _pdata1;
}
protected ConditionValue getCValuePdata1() { return getPdata1(); }
public BsTConnectorCQ addOrderBy_Pdata1_Asc() { regOBA("PDATA1"); return this; }
public BsTConnectorCQ addOrderBy_Pdata1_Desc() { regOBD("PDATA1"); return this; }
protected ConditionValue _pdata2;
public ConditionValue getPdata2() {
if (_pdata2 == null) { _pdata2 = new ConditionValue(); }
return _pdata2;
}
protected ConditionValue getCValuePdata2() { return getPdata2(); }
public BsTConnectorCQ addOrderBy_Pdata2_Asc() { regOBA("PDATA2"); return this; }
public BsTConnectorCQ addOrderBy_Pdata2_Desc() { regOBD("PDATA2"); return this; }
protected ConditionValue _pdata3;
public ConditionValue getPdata3() {
if (_pdata3 == null) { _pdata3 = new ConditionValue(); }
return _pdata3;
}
protected ConditionValue getCValuePdata3() { return getPdata3(); }
public BsTConnectorCQ addOrderBy_Pdata3_Asc() { regOBA("PDATA3"); return this; }
public BsTConnectorCQ addOrderBy_Pdata3_Desc() { regOBD("PDATA3"); return this; }
protected ConditionValue _pdata4;
public ConditionValue getPdata4() {
if (_pdata4 == null) { _pdata4 = new ConditionValue(); }
return _pdata4;
}
protected ConditionValue getCValuePdata4() { return getPdata4(); }
public BsTConnectorCQ addOrderBy_Pdata4_Asc() { regOBA("PDATA4"); return this; }
public BsTConnectorCQ addOrderBy_Pdata4_Desc() { regOBD("PDATA4"); return this; }
protected ConditionValue _pdata5;
public ConditionValue getPdata5() {
if (_pdata5 == null) { _pdata5 = new ConditionValue(); }
return _pdata5;
}
protected ConditionValue getCValuePdata5() { return getPdata5(); }
public BsTConnectorCQ addOrderBy_Pdata5_Asc() { regOBA("PDATA5"); return this; }
public BsTConnectorCQ addOrderBy_Pdata5_Desc() { regOBD("PDATA5"); return this; }
protected ConditionValue _diagramid;
public ConditionValue getDiagramid() {
if (_diagramid == null) { _diagramid = new ConditionValue(); }
return _diagramid;
}
protected ConditionValue getCValueDiagramid() { return getDiagramid(); }
public BsTConnectorCQ addOrderBy_Diagramid_Asc() { regOBA("DiagramID"); return this; }
public BsTConnectorCQ addOrderBy_Diagramid_Desc() { regOBD("DiagramID"); return this; }
protected ConditionValue _eaGuid;
public ConditionValue getEaGuid() {
if (_eaGuid == null) { _eaGuid = new ConditionValue(); }
return _eaGuid;
}
protected ConditionValue getCValueEaGuid() { return getEaGuid(); }
public BsTConnectorCQ addOrderBy_EaGuid_Asc() { regOBA("ea_guid"); return this; }
public BsTConnectorCQ addOrderBy_EaGuid_Desc() { regOBD("ea_guid"); return this; }
protected ConditionValue _sourceconstraint;
public ConditionValue getSourceconstraint() {
if (_sourceconstraint == null) { _sourceconstraint = new ConditionValue(); }
return _sourceconstraint;
}
protected ConditionValue getCValueSourceconstraint() { return getSourceconstraint(); }
public BsTConnectorCQ addOrderBy_Sourceconstraint_Asc() { regOBA("SourceConstraint"); return this; }
public BsTConnectorCQ addOrderBy_Sourceconstraint_Desc() { regOBD("SourceConstraint"); return this; }
protected ConditionValue _destconstraint;
public ConditionValue getDestconstraint() {
if (_destconstraint == null) { _destconstraint = new ConditionValue(); }
return _destconstraint;
}
protected ConditionValue getCValueDestconstraint() { return getDestconstraint(); }
public BsTConnectorCQ addOrderBy_Destconstraint_Asc() { regOBA("DestConstraint"); return this; }
public BsTConnectorCQ addOrderBy_Destconstraint_Desc() { regOBD("DestConstraint"); return this; }
protected ConditionValue _sourceisnavigable;
public ConditionValue getSourceisnavigable() {
if (_sourceisnavigable == null) { _sourceisnavigable = new ConditionValue(); }
return _sourceisnavigable;
}
protected ConditionValue getCValueSourceisnavigable() { return getSourceisnavigable(); }
public BsTConnectorCQ addOrderBy_Sourceisnavigable_Asc() { regOBA("SourceIsNavigable"); return this; }
public BsTConnectorCQ addOrderBy_Sourceisnavigable_Desc() { regOBD("SourceIsNavigable"); return this; }
protected ConditionValue _destisnavigable;
public ConditionValue getDestisnavigable() {
if (_destisnavigable == null) { _destisnavigable = new ConditionValue(); }
return _destisnavigable;
}
protected ConditionValue getCValueDestisnavigable() { return getDestisnavigable(); }
public BsTConnectorCQ addOrderBy_Destisnavigable_Asc() { regOBA("DestIsNavigable"); return this; }
public BsTConnectorCQ addOrderBy_Destisnavigable_Desc() { regOBD("DestIsNavigable"); return this; }
protected ConditionValue _isroot;
public ConditionValue getIsroot() {
if (_isroot == null) { _isroot = new ConditionValue(); }
return _isroot;
}
protected ConditionValue getCValueIsroot() { return getIsroot(); }
public BsTConnectorCQ addOrderBy_Isroot_Asc() { regOBA("IsRoot"); return this; }
public BsTConnectorCQ addOrderBy_Isroot_Desc() { regOBD("IsRoot"); return this; }
protected ConditionValue _isleaf;
public ConditionValue getIsleaf() {
if (_isleaf == null) { _isleaf = new ConditionValue(); }
return _isleaf;
}
protected ConditionValue getCValueIsleaf() { return getIsleaf(); }
public BsTConnectorCQ addOrderBy_Isleaf_Asc() { regOBA("IsLeaf"); return this; }
public BsTConnectorCQ addOrderBy_Isleaf_Desc() { regOBD("IsLeaf"); return this; }
protected ConditionValue _isspec;
public ConditionValue getIsspec() {
if (_isspec == null) { _isspec = new ConditionValue(); }
return _isspec;
}
protected ConditionValue getCValueIsspec() { return getIsspec(); }
public BsTConnectorCQ addOrderBy_Isspec_Asc() { regOBA("IsSpec"); return this; }
public BsTConnectorCQ addOrderBy_Isspec_Desc() { regOBD("IsSpec"); return this; }
protected ConditionValue _sourcechangeable;
public ConditionValue getSourcechangeable() {
if (_sourcechangeable == null) { _sourcechangeable = new ConditionValue(); }
return _sourcechangeable;
}
protected ConditionValue getCValueSourcechangeable() { return getSourcechangeable(); }
public BsTConnectorCQ addOrderBy_Sourcechangeable_Asc() { regOBA("SourceChangeable"); return this; }
public BsTConnectorCQ addOrderBy_Sourcechangeable_Desc() { regOBD("SourceChangeable"); return this; }
protected ConditionValue _destchangeable;
public ConditionValue getDestchangeable() {
if (_destchangeable == null) { _destchangeable = new ConditionValue(); }
return _destchangeable;
}
protected ConditionValue getCValueDestchangeable() { return getDestchangeable(); }
public BsTConnectorCQ addOrderBy_Destchangeable_Asc() { regOBA("DestChangeable"); return this; }
public BsTConnectorCQ addOrderBy_Destchangeable_Desc() { regOBD("DestChangeable"); return this; }
protected ConditionValue _sourcets;
public ConditionValue getSourcets() {
if (_sourcets == null) { _sourcets = new ConditionValue(); }
return _sourcets;
}
protected ConditionValue getCValueSourcets() { return getSourcets(); }
public BsTConnectorCQ addOrderBy_Sourcets_Asc() { regOBA("SourceTS"); return this; }
public BsTConnectorCQ addOrderBy_Sourcets_Desc() { regOBD("SourceTS"); return this; }
protected ConditionValue _destts;
public ConditionValue getDestts() {
if (_destts == null) { _destts = new ConditionValue(); }
return _destts;
}
protected ConditionValue getCValueDestts() { return getDestts(); }
public BsTConnectorCQ addOrderBy_Destts_Asc() { regOBA("DestTS"); return this; }
public BsTConnectorCQ addOrderBy_Destts_Desc() { regOBD("DestTS"); return this; }
protected ConditionValue _stateflags;
public ConditionValue getStateflags() {
if (_stateflags == null) { _stateflags = new ConditionValue(); }
return _stateflags;
}
protected ConditionValue getCValueStateflags() { return getStateflags(); }
public BsTConnectorCQ addOrderBy_Stateflags_Asc() { regOBA("StateFlags"); return this; }
public BsTConnectorCQ addOrderBy_Stateflags_Desc() { regOBD("StateFlags"); return this; }
protected ConditionValue _actionflags;
public ConditionValue getActionflags() {
if (_actionflags == null) { _actionflags = new ConditionValue(); }
return _actionflags;
}
protected ConditionValue getCValueActionflags() { return getActionflags(); }
public BsTConnectorCQ addOrderBy_Actionflags_Asc() { regOBA("ActionFlags"); return this; }
public BsTConnectorCQ addOrderBy_Actionflags_Desc() { regOBD("ActionFlags"); return this; }
protected ConditionValue _issignal;
public ConditionValue getIssignal() {
if (_issignal == null) { _issignal = new ConditionValue(); }
return _issignal;
}
protected ConditionValue getCValueIssignal() { return getIssignal(); }
public BsTConnectorCQ addOrderBy_Issignal_Asc() { regOBA("IsSignal"); return this; }
public BsTConnectorCQ addOrderBy_Issignal_Desc() { regOBD("IsSignal"); return this; }
protected ConditionValue _isstimulus;
public ConditionValue getIsstimulus() {
if (_isstimulus == null) { _isstimulus = new ConditionValue(); }
return _isstimulus;
}
protected ConditionValue getCValueIsstimulus() { return getIsstimulus(); }
public BsTConnectorCQ addOrderBy_Isstimulus_Asc() { regOBA("IsStimulus"); return this; }
public BsTConnectorCQ addOrderBy_Isstimulus_Desc() { regOBD("IsStimulus"); return this; }
protected ConditionValue _dispatchaction;
public ConditionValue getDispatchaction() {
if (_dispatchaction == null) { _dispatchaction = new ConditionValue(); }
return _dispatchaction;
}
protected ConditionValue getCValueDispatchaction() { return getDispatchaction(); }
public BsTConnectorCQ addOrderBy_Dispatchaction_Asc() { regOBA("DispatchAction"); return this; }
public BsTConnectorCQ addOrderBy_Dispatchaction_Desc() { regOBD("DispatchAction"); return this; }
protected ConditionValue _target2;
public ConditionValue getTarget2() {
if (_target2 == null) { _target2 = new ConditionValue(); }
return _target2;
}
protected ConditionValue getCValueTarget2() { return getTarget2(); }
public BsTConnectorCQ addOrderBy_Target2_Asc() { regOBA("Target2"); return this; }
public BsTConnectorCQ addOrderBy_Target2_Desc() { regOBD("Target2"); return this; }
protected ConditionValue _styleex;
public ConditionValue getStyleex() {
if (_styleex == null) { _styleex = new ConditionValue(); }
return _styleex;
}
protected ConditionValue getCValueStyleex() { return getStyleex(); }
public BsTConnectorCQ addOrderBy_Styleex_Asc() { regOBA("StyleEx"); return this; }
public BsTConnectorCQ addOrderBy_Styleex_Desc() { regOBD("StyleEx"); return this; }
protected ConditionValue _sourcestereotype;
public ConditionValue getSourcestereotype() {
if (_sourcestereotype == null) { _sourcestereotype = new ConditionValue(); }
return _sourcestereotype;
}
protected ConditionValue getCValueSourcestereotype() { return getSourcestereotype(); }
public BsTConnectorCQ addOrderBy_Sourcestereotype_Asc() { regOBA("SourceStereotype"); return this; }
public BsTConnectorCQ addOrderBy_Sourcestereotype_Desc() { regOBD("SourceStereotype"); return this; }
protected ConditionValue _deststereotype;
public ConditionValue getDeststereotype() {
if (_deststereotype == null) { _deststereotype = new ConditionValue(); }
return _deststereotype;
}
protected ConditionValue getCValueDeststereotype() { return getDeststereotype(); }
public BsTConnectorCQ addOrderBy_Deststereotype_Asc() { regOBA("DestStereotype"); return this; }
public BsTConnectorCQ addOrderBy_Deststereotype_Desc() { regOBD("DestStereotype"); return this; }
protected ConditionValue _sourcestyle;
public ConditionValue getSourcestyle() {
if (_sourcestyle == null) { _sourcestyle = new ConditionValue(); }
return _sourcestyle;
}
protected ConditionValue getCValueSourcestyle() { return getSourcestyle(); }
public BsTConnectorCQ addOrderBy_Sourcestyle_Asc() { regOBA("SourceStyle"); return this; }
public BsTConnectorCQ addOrderBy_Sourcestyle_Desc() { regOBD("SourceStyle"); return this; }
protected ConditionValue _deststyle;
public ConditionValue getDeststyle() {
if (_deststyle == null) { _deststyle = new ConditionValue(); }
return _deststyle;
}
protected ConditionValue getCValueDeststyle() { return getDeststyle(); }
public BsTConnectorCQ addOrderBy_Deststyle_Asc() { regOBA("DestStyle"); return this; }
public BsTConnectorCQ addOrderBy_Deststyle_Desc() { regOBD("DestStyle"); return this; }
protected ConditionValue _eventflags;
public ConditionValue getEventflags() {
if (_eventflags == null) { _eventflags = new ConditionValue(); }
return _eventflags;
}
protected ConditionValue getCValueEventflags() { return getEventflags(); }
public BsTConnectorCQ addOrderBy_Eventflags_Asc() { regOBA("EventFlags"); return this; }
public BsTConnectorCQ addOrderBy_Eventflags_Desc() { regOBD("EventFlags"); return this; }
// ===================================================================================
// Specified Derived OrderBy
// =========================
public BsTConnectorCQ addSpecifiedDerivedOrderBy_Asc(String aliasName) { registerSpecifiedDerivedOrderBy_Asc(aliasName); return this; }
public BsTConnectorCQ addSpecifiedDerivedOrderBy_Desc(String aliasName) { registerSpecifiedDerivedOrderBy_Desc(aliasName); return this; }
// ===================================================================================
// Union Query
// ===========
protected void reflectRelationOnUnionQuery(ConditionQuery baseQueryAsSuper, ConditionQuery unionQueryAsSuper) {
TConnectorCQ baseQuery = (TConnectorCQ)baseQueryAsSuper;
TConnectorCQ unionQuery = (TConnectorCQ)unionQueryAsSuper;
if (baseQuery.hasConditionQueryTOperationBySourcerole()) {
unionQuery.queryTOperationBySourcerole().reflectRelationOnUnionQuery(baseQuery.queryTOperationBySourcerole(), unionQuery.queryTOperationBySourcerole());
}
if (baseQuery.hasConditionQueryTOperationByDestrole()) {
unionQuery.queryTOperationByDestrole().reflectRelationOnUnionQuery(baseQuery.queryTOperationByDestrole(), unionQuery.queryTOperationByDestrole());
}
if (baseQuery.hasConditionQueryTObjectByStartObjectId()) {
unionQuery.queryTObjectByStartObjectId().reflectRelationOnUnionQuery(baseQuery.queryTObjectByStartObjectId(), unionQuery.queryTObjectByStartObjectId());
}
if (baseQuery.hasConditionQueryTObjectByEndObjectId()) {
unionQuery.queryTObjectByEndObjectId().reflectRelationOnUnionQuery(baseQuery.queryTObjectByEndObjectId(), unionQuery.queryTObjectByEndObjectId());
}
}
// ===================================================================================
// Foreign Query
// =============
public TOperationCQ queryTOperationBySourcerole() {
return getConditionQueryTOperationBySourcerole();
}
protected TOperationCQ _conditionQueryTOperationBySourcerole;
public TOperationCQ getConditionQueryTOperationBySourcerole() {
if (_conditionQueryTOperationBySourcerole == null) {
_conditionQueryTOperationBySourcerole = xcreateQueryTOperationBySourcerole();
xsetupOuterJoinTOperationBySourcerole();
}
return _conditionQueryTOperationBySourcerole;
}
protected TOperationCQ xcreateQueryTOperationBySourcerole() {
String nrp = resolveNextRelationPath("t_connector", "tOperationBySourcerole");
String jan = resolveJoinAliasName(nrp, getNextNestLevel());
TOperationCQ cq = new TOperationCQ(this, getSqlClause(), jan, getNextNestLevel());
cq.xsetForeignPropertyName("tOperationBySourcerole"); cq.xsetRelationPath(nrp); return cq;
}
protected void xsetupOuterJoinTOperationBySourcerole() {
TOperationCQ cq = getConditionQueryTOperationBySourcerole();
Map<String, String> joinOnMap = newLinkedHashMap();
joinOnMap.put(getRealColumnName("SourceRole"), cq.getRealColumnName("Name"));
registerOuterJoin(cq, joinOnMap);
}
public boolean hasConditionQueryTOperationBySourcerole() {
return _conditionQueryTOperationBySourcerole != null;
}
public TOperationCQ queryTOperationByDestrole() {
return getConditionQueryTOperationByDestrole();
}
protected TOperationCQ _conditionQueryTOperationByDestrole;
public TOperationCQ getConditionQueryTOperationByDestrole() {
if (_conditionQueryTOperationByDestrole == null) {
_conditionQueryTOperationByDestrole = xcreateQueryTOperationByDestrole();
xsetupOuterJoinTOperationByDestrole();
}
return _conditionQueryTOperationByDestrole;
}
protected TOperationCQ xcreateQueryTOperationByDestrole() {
String nrp = resolveNextRelationPath("t_connector", "tOperationByDestrole");
String jan = resolveJoinAliasName(nrp, getNextNestLevel());
TOperationCQ cq = new TOperationCQ(this, getSqlClause(), jan, getNextNestLevel());
cq.xsetForeignPropertyName("tOperationByDestrole"); cq.xsetRelationPath(nrp); return cq;
}
protected void xsetupOuterJoinTOperationByDestrole() {
TOperationCQ cq = getConditionQueryTOperationByDestrole();
Map<String, String> joinOnMap = newLinkedHashMap();
joinOnMap.put(getRealColumnName("DestRole"), cq.getRealColumnName("Name"));
registerOuterJoin(cq, joinOnMap);
}
public boolean hasConditionQueryTOperationByDestrole() {
return _conditionQueryTOperationByDestrole != null;
}
public TObjectCQ queryTObjectByStartObjectId() {
return getConditionQueryTObjectByStartObjectId();
}
protected TObjectCQ _conditionQueryTObjectByStartObjectId;
public TObjectCQ getConditionQueryTObjectByStartObjectId() {
if (_conditionQueryTObjectByStartObjectId == null) {
_conditionQueryTObjectByStartObjectId = xcreateQueryTObjectByStartObjectId();
xsetupOuterJoinTObjectByStartObjectId();
}
return _conditionQueryTObjectByStartObjectId;
}
protected TObjectCQ xcreateQueryTObjectByStartObjectId() {
String nrp = resolveNextRelationPath("t_connector", "tObjectByStartObjectId");
String jan = resolveJoinAliasName(nrp, getNextNestLevel());
TObjectCQ cq = new TObjectCQ(this, getSqlClause(), jan, getNextNestLevel());
cq.xsetForeignPropertyName("tObjectByStartObjectId"); cq.xsetRelationPath(nrp); return cq;
}
protected void xsetupOuterJoinTObjectByStartObjectId() {
TObjectCQ cq = getConditionQueryTObjectByStartObjectId();
Map<String, String> joinOnMap = newLinkedHashMap();
joinOnMap.put(getRealColumnName("Start_Object_ID"), cq.getRealColumnName("Object_ID"));
registerOuterJoin(cq, joinOnMap);
}
public boolean hasConditionQueryTObjectByStartObjectId() {
return _conditionQueryTObjectByStartObjectId != null;
}
public TObjectCQ queryTObjectByEndObjectId() {
return getConditionQueryTObjectByEndObjectId();
}
protected TObjectCQ _conditionQueryTObjectByEndObjectId;
public TObjectCQ getConditionQueryTObjectByEndObjectId() {
if (_conditionQueryTObjectByEndObjectId == null) {
_conditionQueryTObjectByEndObjectId = xcreateQueryTObjectByEndObjectId();
xsetupOuterJoinTObjectByEndObjectId();
}
return _conditionQueryTObjectByEndObjectId;
}
protected TObjectCQ xcreateQueryTObjectByEndObjectId() {
String nrp = resolveNextRelationPath("t_connector", "tObjectByEndObjectId");
String jan = resolveJoinAliasName(nrp, getNextNestLevel());
TObjectCQ cq = new TObjectCQ(this, getSqlClause(), jan, getNextNestLevel());
cq.xsetForeignPropertyName("tObjectByEndObjectId"); cq.xsetRelationPath(nrp); return cq;
}
protected void xsetupOuterJoinTObjectByEndObjectId() {
TObjectCQ cq = getConditionQueryTObjectByEndObjectId();
Map<String, String> joinOnMap = newLinkedHashMap();
joinOnMap.put(getRealColumnName("End_Object_ID"), cq.getRealColumnName("Object_ID"));
registerOuterJoin(cq, joinOnMap);
}
public boolean hasConditionQueryTObjectByEndObjectId() {
return _conditionQueryTObjectByEndObjectId != null;
}
// ===================================================================================
// Scalar SubQuery
// ===============
protected Map<String, TConnectorCQ> _scalarSubQueryMap;
public Map<String, TConnectorCQ> getScalarSubQuery() { return _scalarSubQueryMap; }
public String keepScalarSubQuery(TConnectorCQ subQuery) {
if (_scalarSubQueryMap == null) { _scalarSubQueryMap = newLinkedHashMap(); }
String key = "subQueryMapKey" + (_scalarSubQueryMap.size() + 1);
_scalarSubQueryMap.put(key, subQuery); return "scalarSubQuery." + key;
}
// ===================================================================================
// MySelf InScope SubQuery
// =======================
protected Map<String, TConnectorCQ> _myselfInScopeSubQueryMap;
public Map<String, TConnectorCQ> getMyselfInScopeSubQuery() { return _myselfInScopeSubQueryMap; }
public String keepMyselfInScopeSubQuery(TConnectorCQ subQuery) {
if (_myselfInScopeSubQueryMap == null) { _myselfInScopeSubQueryMap = newLinkedHashMap(); }
String key = "subQueryMapKey" + (_myselfInScopeSubQueryMap.size() + 1);
_myselfInScopeSubQueryMap.put(key, subQuery); return "myselfInScopeSubQuery." + key;
}
// ===================================================================================
// Very Internal
// =============
// Very Internal (for Suppressing Warn about 'Not Use Import')
String xCB() { return TConnectorCB.class.getName(); }
String xCQ() { return TConnectorCQ.class.getName(); }
String xMap() { return Map.class.getName(); }
}
|
taktos/ea2ddl
|
ea2ddl-dao/src/main/java/jp/sourceforge/ea2ddl/dao/cbean/cq/bs/BsTConnectorCQ.java
|
Java
|
apache-2.0
| 53,489 |
// Copyright 2017 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/torque/declaration-visitor.h"
namespace v8 {
namespace internal {
namespace torque {
void DeclarationVisitor::Visit(Expression* expr) {
CurrentSourcePosition::Scope scope(expr->pos);
switch (expr->kind) {
#define ENUM_ITEM(name) \
case AstNode::Kind::k##name: \
return Visit(name::cast(expr));
AST_EXPRESSION_NODE_KIND_LIST(ENUM_ITEM)
#undef ENUM_ITEM
default:
UNIMPLEMENTED();
}
}
void DeclarationVisitor::Visit(Statement* stmt) {
CurrentSourcePosition::Scope scope(stmt->pos);
switch (stmt->kind) {
#define ENUM_ITEM(name) \
case AstNode::Kind::k##name: \
return Visit(name::cast(stmt));
AST_STATEMENT_NODE_KIND_LIST(ENUM_ITEM)
#undef ENUM_ITEM
default:
UNIMPLEMENTED();
}
}
void DeclarationVisitor::Visit(Declaration* decl) {
CurrentSourcePosition::Scope scope(decl->pos);
switch (decl->kind) {
#define ENUM_ITEM(name) \
case AstNode::Kind::k##name: \
return Visit(name::cast(decl));
AST_DECLARATION_NODE_KIND_LIST(ENUM_ITEM)
#undef ENUM_ITEM
default:
UNIMPLEMENTED();
}
}
void DeclarationVisitor::Visit(CallableNode* decl, const Signature& signature,
Statement* body) {
switch (decl->kind) {
#define ENUM_ITEM(name) \
case AstNode::Kind::k##name: \
return Visit(name::cast(decl), signature, body);
AST_CALLABLE_NODE_KIND_LIST(ENUM_ITEM)
#undef ENUM_ITEM
default:
UNIMPLEMENTED();
}
}
Builtin* DeclarationVisitor::BuiltinDeclarationCommon(
BuiltinDeclaration* decl, bool external, const Signature& signature) {
const bool javascript = decl->javascript_linkage;
const bool varargs = decl->signature->parameters.has_varargs;
Builtin::Kind kind = !javascript ? Builtin::kStub
: varargs ? Builtin::kVarArgsJavaScript
: Builtin::kFixedArgsJavaScript;
if (signature.types().size() == 0 ||
!(signature.types()[0] ==
declarations()->LookupGlobalType(CONTEXT_TYPE_STRING))) {
std::stringstream stream;
stream << "first parameter to builtin " << decl->name
<< " is not a context but should be";
ReportError(stream.str());
}
if (varargs && !javascript) {
std::stringstream stream;
stream << "builtin " << decl->name
<< " with rest parameters must be a JavaScript builtin";
ReportError(stream.str());
}
if (javascript) {
if (signature.types().size() < 2 ||
!(signature.types()[1] ==
declarations()->LookupGlobalType(OBJECT_TYPE_STRING))) {
std::stringstream stream;
stream << "second parameter to javascript builtin " << decl->name
<< " is " << *signature.types()[1] << " but should be Object";
ReportError(stream.str());
}
}
if (const StructType* struct_type =
StructType::DynamicCast(signature.return_type)) {
std::stringstream stream;
stream << "builtins (in this case" << decl->name
<< ") cannot return structs (in this case " << struct_type->name()
<< ")";
ReportError(stream.str());
}
std::string generated_name = GetGeneratedCallableName(
decl->name, declarations()->GetCurrentSpecializationTypeNamesVector());
return declarations()->DeclareBuiltin(generated_name, kind, external,
signature);
}
void DeclarationVisitor::Visit(ExternalRuntimeDeclaration* decl,
const Signature& signature, Statement* body) {
if (global_context_.verbose()) {
std::cout << "found declaration of external runtime " << decl->name
<< " with signature ";
}
if (signature.parameter_types.types.size() == 0 ||
!(signature.parameter_types.types[0] ==
declarations()->LookupGlobalType(CONTEXT_TYPE_STRING))) {
std::stringstream stream;
stream << "first parameter to runtime " << decl->name
<< " is not a context but should be";
ReportError(stream.str());
}
if (signature.return_type->IsStructType()) {
std::stringstream stream;
stream << "runtime functions (in this case" << decl->name
<< ") cannot return structs (in this case "
<< static_cast<const StructType*>(signature.return_type)->name()
<< ")";
ReportError(stream.str());
}
declarations()->DeclareRuntimeFunction(decl->name, signature);
}
void DeclarationVisitor::Visit(ExternalMacroDeclaration* decl,
const Signature& signature, Statement* body) {
if (global_context_.verbose()) {
std::cout << "found declaration of external macro " << decl->name
<< " with signature ";
}
std::string generated_name = GetGeneratedCallableName(
decl->name, declarations()->GetCurrentSpecializationTypeNamesVector());
declarations()->DeclareMacro(generated_name, signature, decl->op);
}
void DeclarationVisitor::Visit(TorqueBuiltinDeclaration* decl,
const Signature& signature, Statement* body) {
Builtin* builtin = BuiltinDeclarationCommon(decl, false, signature);
CurrentCallableActivator activator(global_context_, builtin, decl);
DeclareSignature(signature);
if (signature.parameter_types.var_args) {
declarations()->DeclareExternConstant(
decl->signature->parameters.arguments_variable,
TypeOracle::GetArgumentsType(), "arguments");
}
torque_builtins_.push_back(builtin);
Visit(body);
}
void DeclarationVisitor::Visit(TorqueMacroDeclaration* decl,
const Signature& signature, Statement* body) {
std::string generated_name = GetGeneratedCallableName(
decl->name, declarations()->GetCurrentSpecializationTypeNamesVector());
Macro* macro =
declarations()->DeclareMacro(generated_name, signature, decl->op);
CurrentCallableActivator activator(global_context_, macro, decl);
DeclareSignature(signature);
if (body != nullptr) {
Visit(body);
}
}
void DeclarationVisitor::Visit(ConstDeclaration* decl) {
declarations()->DeclareModuleConstant(decl->name,
declarations()->GetType(decl->type));
Visit(decl->expression);
}
void DeclarationVisitor::Visit(StandardDeclaration* decl) {
Signature signature = MakeSignature(decl->callable->signature.get());
Visit(decl->callable, signature, decl->body);
}
void DeclarationVisitor::Visit(GenericDeclaration* decl) {
declarations()->DeclareGeneric(decl->callable->name, CurrentModule(), decl);
}
void DeclarationVisitor::Visit(SpecializationDeclaration* decl) {
if ((decl->body != nullptr) == decl->external) {
std::stringstream stream;
stream << "specialization of " << decl->name
<< " must either be marked 'extern' or have a body";
ReportError(stream.str());
}
GenericList* generic_list = declarations()->LookupGeneric(decl->name);
// Find the matching generic specialization based on the concrete parameter
// list.
CallableNode* matching_callable = nullptr;
SpecializationKey matching_key;
Signature signature_with_types = MakeSignature(decl->signature.get());
for (Generic* generic : generic_list->list()) {
SpecializationKey key = {generic, GetTypeVector(decl->generic_parameters)};
CallableNode* callable_candidate = generic->declaration()->callable;
// Abuse the Specialization nodes' scope to temporarily declare the
// specialization aliases for the generic types to compare signatures. This
// scope is never used for anything else, so it's OK to pollute it.
Declarations::CleanNodeScopeActivator specialization_activator(
declarations(), decl);
DeclareSpecializedTypes(key);
Signature generic_signature_with_types =
MakeSignature(generic->declaration()->callable->signature.get());
if (signature_with_types.HasSameTypesAs(generic_signature_with_types)) {
if (matching_callable != nullptr) {
std::stringstream stream;
stream << "specialization of " << callable_candidate->name
<< " is ambigous, it matches more than one generic declaration ("
<< *matching_key.first << " and " << *key.first << ")";
ReportError(stream.str());
}
matching_callable = callable_candidate;
matching_key = key;
}
}
if (matching_callable == nullptr) {
std::stringstream stream;
stream << "specialization of " << decl->name
<< " doesn't match any generic declaration";
ReportError(stream.str());
}
// Make sure the declarations of the parameter types for the specialization
// are the ones from the matching generic.
{
Declarations::CleanNodeScopeActivator specialization_activator(
declarations(), decl);
DeclareSpecializedTypes(matching_key);
}
SpecializeGeneric({matching_key, matching_callable, decl->signature.get(),
decl->body, decl->pos});
}
void DeclarationVisitor::Visit(ReturnStatement* stmt) {
if (stmt->value) {
Visit(*stmt->value);
}
}
Variable* DeclarationVisitor::DeclareVariable(const std::string& name,
const Type* type, bool is_const) {
Variable* result = declarations()->DeclareVariable(name, type, is_const);
return result;
}
Parameter* DeclarationVisitor::DeclareParameter(const std::string& name,
const Type* type) {
return declarations()->DeclareParameter(
name, GetParameterVariableFromName(name), type);
}
void DeclarationVisitor::Visit(VarDeclarationStatement* stmt) {
std::string variable_name = stmt->name;
if (!stmt->const_qualified) {
if (!stmt->type) {
ReportError(
"variable declaration is missing type. Only 'const' bindings can "
"infer the type.");
}
const Type* type = declarations()->GetType(*stmt->type);
if (type->IsConstexpr()) {
ReportError(
"cannot declare variable with constexpr type. Use 'const' instead.");
}
DeclareVariable(variable_name, type, stmt->const_qualified);
if (global_context_.verbose()) {
std::cout << "declared variable " << variable_name << " with type "
<< *type << "\n";
}
}
// const qualified variables are required to be initialized properly.
if (stmt->const_qualified && !stmt->initializer) {
std::stringstream stream;
stream << "local constant \"" << variable_name << "\" is not initialized.";
ReportError(stream.str());
}
if (stmt->initializer) {
Visit(*stmt->initializer);
if (global_context_.verbose()) {
std::cout << "variable has initialization expression at "
<< CurrentPositionAsString() << "\n";
}
}
}
void DeclarationVisitor::Visit(ExternConstDeclaration* decl) {
const Type* type = declarations()->GetType(decl->type);
if (!type->IsConstexpr()) {
std::stringstream stream;
stream << "extern constants must have constexpr type, but found: \""
<< *type << "\"\n";
ReportError(stream.str());
}
declarations()->DeclareExternConstant(decl->name, type, decl->literal);
}
void DeclarationVisitor::Visit(StructDeclaration* decl) {
std::vector<NameAndType> fields;
for (auto& field : decl->fields) {
const Type* field_type = declarations()->GetType(field.type);
fields.push_back({field.name, field_type});
}
declarations()->DeclareStruct(CurrentModule(), decl->name, fields);
}
void DeclarationVisitor::Visit(LogicalOrExpression* expr) {
{
Declarations::NodeScopeActivator scope(declarations(), expr->left);
declarations()->DeclareLabel(kFalseLabelName);
Visit(expr->left);
}
Visit(expr->right);
}
void DeclarationVisitor::Visit(LogicalAndExpression* expr) {
{
Declarations::NodeScopeActivator scope(declarations(), expr->left);
declarations()->DeclareLabel(kTrueLabelName);
Visit(expr->left);
}
Visit(expr->right);
}
void DeclarationVisitor::DeclareExpressionForBranch(
Expression* node, base::Optional<Statement*> true_statement,
base::Optional<Statement*> false_statement) {
Declarations::NodeScopeActivator scope(declarations(), node);
// Conditional expressions can either explicitly return a bit
// type, or they can be backed by macros that don't return but
// take a true and false label. By declaring the labels before
// visiting the conditional expression, those label-based
// macro conditionals will be able to find them through normal
// label lookups.
declarations()->DeclareLabel(kTrueLabelName, true_statement);
declarations()->DeclareLabel(kFalseLabelName, false_statement);
Visit(node);
}
void DeclarationVisitor::Visit(ConditionalExpression* expr) {
DeclareExpressionForBranch(expr->condition);
Visit(expr->if_true);
Visit(expr->if_false);
}
void DeclarationVisitor::Visit(IfStatement* stmt) {
DeclareExpressionForBranch(stmt->condition, stmt->if_true, stmt->if_false);
Visit(stmt->if_true);
if (stmt->if_false) Visit(*stmt->if_false);
}
void DeclarationVisitor::Visit(WhileStatement* stmt) {
Declarations::NodeScopeActivator scope(declarations(), stmt);
DeclareExpressionForBranch(stmt->condition);
Visit(stmt->body);
}
void DeclarationVisitor::Visit(ForOfLoopStatement* stmt) {
// Scope for for iteration variable
Declarations::NodeScopeActivator scope(declarations(), stmt);
Visit(stmt->var_declaration);
Visit(stmt->iterable);
if (stmt->begin) Visit(*stmt->begin);
if (stmt->end) Visit(*stmt->end);
Visit(stmt->body);
}
void DeclarationVisitor::Visit(ForLoopStatement* stmt) {
Declarations::NodeScopeActivator scope(declarations(), stmt);
if (stmt->var_declaration) Visit(*stmt->var_declaration);
// Same as DeclareExpressionForBranch, but without the extra scope.
// If no test expression is present we can not use it for the scope.
declarations()->DeclareLabel(kTrueLabelName);
declarations()->DeclareLabel(kFalseLabelName);
if (stmt->test) Visit(*stmt->test);
Visit(stmt->body);
if (stmt->action) Visit(*stmt->action);
}
void DeclarationVisitor::Visit(TryLabelExpression* stmt) {
// Activate a new scope to declare the handler's label parameters, they should
// not be visible outside the label block.
{
Declarations::NodeScopeActivator scope(declarations(), stmt);
// Declare label
{
LabelBlock* block = stmt->label_block;
CurrentSourcePosition::Scope scope(block->pos);
Label* shared_label =
declarations()->DeclareLabel(block->label, block->body);
{
Declarations::NodeScopeActivator scope(declarations(), block->body);
if (block->parameters.has_varargs) {
std::stringstream stream;
stream << "cannot use ... for label parameters";
ReportError(stream.str());
}
size_t i = 0;
for (const auto& p : block->parameters.names) {
const Type* type =
declarations()->GetType(block->parameters.types[i]);
if (type->IsConstexpr()) {
ReportError("no constexpr type allowed for label arguments");
}
shared_label->AddVariable(DeclareVariable(p, type, false));
++i;
}
if (global_context_.verbose()) {
std::cout << " declaring label " << block->label << "\n";
}
}
}
Visit(stmt->try_expression);
}
Visit(stmt->label_block->body);
}
void DeclarationVisitor::GenerateHeader(std::string& file_name) {
std::stringstream new_contents_stream;
new_contents_stream
<< "#ifndef V8_BUILTINS_BUILTIN_DEFINITIONS_FROM_DSL_H_\n"
"#define V8_BUILTINS_BUILTIN_DEFINITIONS_FROM_DSL_H_\n"
"\n"
"#define BUILTIN_LIST_FROM_DSL(CPP, API, TFJ, TFC, TFS, TFH, ASM) "
"\\\n";
for (auto builtin : torque_builtins_) {
int firstParameterIndex = 1;
bool declareParameters = true;
if (builtin->IsStub()) {
new_contents_stream << "TFS(" << builtin->name();
} else {
new_contents_stream << "TFJ(" << builtin->name();
if (builtin->IsVarArgsJavaScript()) {
new_contents_stream
<< ", SharedFunctionInfo::kDontAdaptArgumentsSentinel";
declareParameters = false;
} else {
assert(builtin->IsFixedArgsJavaScript());
// FixedArg javascript builtins need to offer the parameter
// count.
assert(builtin->parameter_names().size() >= 2);
new_contents_stream << ", " << (builtin->parameter_names().size() - 2);
// And the receiver is explicitly declared.
new_contents_stream << ", kReceiver";
firstParameterIndex = 2;
}
}
if (declareParameters) {
int index = 0;
for (const auto& parameter : builtin->parameter_names()) {
if (index >= firstParameterIndex) {
new_contents_stream << ", k" << CamelifyString(parameter);
}
index++;
}
}
new_contents_stream << ") \\\n";
}
new_contents_stream
<< "\n"
"#endif // V8_BUILTINS_BUILTIN_DEFINITIONS_FROM_DSL_H_\n";
std::string new_contents(new_contents_stream.str());
ReplaceFileContentsIfDifferent(file_name, new_contents);
}
void DeclarationVisitor::Visit(IdentifierExpression* expr) {
if (expr->generic_arguments.size() != 0) {
TypeVector specialization_types;
for (auto t : expr->generic_arguments) {
specialization_types.push_back(declarations()->GetType(t));
}
// Specialize all versions of the generic, since the exact parameter type
// list cannot be resolved until the call's parameter expressions are
// evaluated. This is an overly conservative but simple way to make sure
// that the correct specialization exists.
for (auto generic : declarations()->LookupGeneric(expr->name)->list()) {
CallableNode* callable = generic->declaration()->callable;
if (generic->declaration()->body) {
QueueGenericSpecialization({generic, specialization_types}, callable,
callable->signature.get(),
generic->declaration()->body);
}
}
}
}
void DeclarationVisitor::Visit(StatementExpression* expr) {
Visit(expr->statement);
}
void DeclarationVisitor::Visit(CallExpression* expr) {
Visit(&expr->callee);
for (Expression* arg : expr->arguments) Visit(arg);
}
void DeclarationVisitor::Visit(TypeDeclaration* decl) {
std::string generates = decl->generates ? *decl->generates : std::string("");
const AbstractType* type = declarations()->DeclareAbstractType(
decl->name, generates, {}, decl->extends);
if (decl->constexpr_generates) {
std::string constexpr_name = CONSTEXPR_TYPE_PREFIX + decl->name;
base::Optional<std::string> constexpr_extends;
if (decl->extends)
constexpr_extends = CONSTEXPR_TYPE_PREFIX + *decl->extends;
declarations()->DeclareAbstractType(
constexpr_name, *decl->constexpr_generates, type, constexpr_extends);
}
}
void DeclarationVisitor::DeclareSignature(const Signature& signature) {
auto type_iterator = signature.parameter_types.types.begin();
for (const auto& name : signature.parameter_names) {
const Type* t(*type_iterator++);
if (name.size() != 0) {
DeclareParameter(name, t);
}
}
for (auto& label : signature.labels) {
auto label_params = label.types;
Label* new_label = declarations()->DeclareLabel(label.name);
new_label->set_external_label_name("label_" + label.name);
size_t i = 0;
for (auto var_type : label_params) {
if (var_type->IsConstexpr()) {
ReportError("no constexpr type allowed for label arguments");
}
std::string var_name = label.name + std::to_string(i++);
new_label->AddVariable(
declarations()->CreateVariable(var_name, var_type, false));
}
}
}
void DeclarationVisitor::DeclareSpecializedTypes(const SpecializationKey& key) {
size_t i = 0;
Generic* generic = key.first;
const std::size_t generic_parameter_count =
generic->declaration()->generic_parameters.size();
if (generic_parameter_count != key.second.size()) {
std::stringstream stream;
stream << "Wrong generic argument count for specialization of \""
<< generic->name() << "\", expected: " << generic_parameter_count
<< ", actual: " << key.second.size();
ReportError(stream.str());
}
for (auto type : key.second) {
std::string generic_type_name =
generic->declaration()->generic_parameters[i++];
declarations()->DeclareType(generic_type_name, type);
}
}
void DeclarationVisitor::Specialize(const SpecializationKey& key,
CallableNode* callable,
const CallableNodeSignature* signature,
Statement* body) {
Generic* generic = key.first;
// TODO(tebbi): The error should point to the source position where the
// instantiation was requested.
CurrentSourcePosition::Scope pos_scope(generic->declaration()->pos);
size_t generic_parameter_count =
generic->declaration()->generic_parameters.size();
if (generic_parameter_count != key.second.size()) {
std::stringstream stream;
stream << "number of template parameters ("
<< std::to_string(key.second.size())
<< ") to intantiation of generic " << callable->name
<< " doesnt match the generic's declaration ("
<< std::to_string(generic_parameter_count) << ")";
ReportError(stream.str());
}
Signature type_signature;
{
// Manually activate the specialized generic's scope when declaring the
// generic parameter specializations.
Declarations::GenericScopeActivator namespace_scope(declarations(), key);
DeclareSpecializedTypes(key);
type_signature = MakeSignature(signature);
}
Visit(callable, type_signature, body);
}
} // namespace torque
} // namespace internal
} // namespace v8
|
fceller/arangodb
|
3rdParty/V8/v7.1.302.28/src/torque/declaration-visitor.cc
|
C++
|
apache-2.0
| 22,124 |
/*
* Copyright © 2010, 2011, 2012 Talis Systems Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.talis.hbase.rdf.layout.vpindexed;
import com.talis.hbase.rdf.store.TableDesc;
public class TableDescVPIndexedCommon extends TableDesc
{
protected static final String COL_FAMILY_NAME_STR = "nodes" ;
protected static final String NODE_SEPARATOR = "~~" ;
private final String _COL_FAMILY_NAME_STR ;
public TableDescVPIndexedCommon( String tName ) { this( tName, COL_FAMILY_NAME_STR ) ; }
public TableDescVPIndexedCommon( String tableName, String colFamily )
{
super( tableName, colFamily ) ;
_COL_FAMILY_NAME_STR = colFamily ;
}
public String getColFamilyName() { return _COL_FAMILY_NAME_STR ; }
}
|
castagna/hbase-rdf
|
src/main/java/com/talis/hbase/rdf/layout/vpindexed/TableDescVPIndexedCommon.java
|
Java
|
apache-2.0
| 1,247 |
/**
*/
package com.mguidi.soa.soa.impl;
import com.mguidi.soa.soa.Operation;
import com.mguidi.soa.soa.Service;
import com.mguidi.soa.soa.SoaPackage;
import java.util.Collection;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.InternalEList;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Service</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link com.mguidi.soa.soa.impl.ServiceImpl#getName <em>Name</em>}</li>
* <li>{@link com.mguidi.soa.soa.impl.ServiceImpl#getOperations <em>Operations</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class ServiceImpl extends MinimalEObjectImpl.Container implements Service
{
/**
* The default value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected static final String NAME_EDEFAULT = null;
/**
* The cached value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected String name = NAME_EDEFAULT;
/**
* The cached value of the '{@link #getOperations() <em>Operations</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getOperations()
* @generated
* @ordered
*/
protected EList<Operation> operations;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ServiceImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass()
{
return SoaPackage.Literals.SERVICE;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName()
{
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setName(String newName)
{
String oldName = name;
name = newName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, SoaPackage.SERVICE__NAME, oldName, name));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Operation> getOperations()
{
if (operations == null)
{
operations = new EObjectContainmentEList<Operation>(Operation.class, this, SoaPackage.SERVICE__OPERATIONS);
}
return operations;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
{
switch (featureID)
{
case SoaPackage.SERVICE__OPERATIONS:
return ((InternalEList<?>)getOperations()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType)
{
switch (featureID)
{
case SoaPackage.SERVICE__NAME:
return getName();
case SoaPackage.SERVICE__OPERATIONS:
return getOperations();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue)
{
switch (featureID)
{
case SoaPackage.SERVICE__NAME:
setName((String)newValue);
return;
case SoaPackage.SERVICE__OPERATIONS:
getOperations().clear();
getOperations().addAll((Collection<? extends Operation>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID)
{
switch (featureID)
{
case SoaPackage.SERVICE__NAME:
setName(NAME_EDEFAULT);
return;
case SoaPackage.SERVICE__OPERATIONS:
getOperations().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID)
{
switch (featureID)
{
case SoaPackage.SERVICE__NAME:
return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name);
case SoaPackage.SERVICE__OPERATIONS:
return operations != null && !operations.isEmpty();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString()
{
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (name: ");
result.append(name);
result.append(')');
return result.toString();
}
} //ServiceImpl
|
mguidi/SOA-Code-Factory
|
com.mguidi.soa/src-gen/com/mguidi/soa/soa/impl/ServiceImpl.java
|
Java
|
apache-2.0
| 5,474 |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.iotfleethub.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.iotfleethub.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* ListTagsForResourceResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListTagsForResourceResultJsonUnmarshaller implements Unmarshaller<ListTagsForResourceResult, JsonUnmarshallerContext> {
public ListTagsForResourceResult unmarshall(JsonUnmarshallerContext context) throws Exception {
ListTagsForResourceResult listTagsForResourceResult = new ListTagsForResourceResult();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return listTagsForResourceResult;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("tags", targetDepth)) {
context.nextToken();
listTagsForResourceResult.setTags(new MapUnmarshaller<String, String>(context.getUnmarshaller(String.class), context
.getUnmarshaller(String.class)).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return listTagsForResourceResult;
}
private static ListTagsForResourceResultJsonUnmarshaller instance;
public static ListTagsForResourceResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new ListTagsForResourceResultJsonUnmarshaller();
return instance;
}
}
|
aws/aws-sdk-java
|
aws-java-sdk-iotfleethub/src/main/java/com/amazonaws/services/iotfleethub/model/transform/ListTagsForResourceResultJsonUnmarshaller.java
|
Java
|
apache-2.0
| 2,982 |
package com.koch.ambeth.ioc;
import com.koch.ambeth.ioc.util.IImmutableTypeSet;
import com.koch.ambeth.util.IConversionHelper;
import com.koch.ambeth.util.typeinfo.IPropertyInfoProvider;
public class BeanMonitoringSupport extends AbstractBeanMonitoringSupport {
private IServiceContext beanContext;
private IPropertyInfoProvider propertyInfoProvider;
private IConversionHelper conversionHelper;
private IImmutableTypeSet immutableTypeSet;
public BeanMonitoringSupport(Object bean, IServiceContext beanContext) {
super(bean);
this.beanContext = beanContext;
}
@Override
protected IPropertyInfoProvider getPropertyInfoProvider() {
if (propertyInfoProvider == null) {
propertyInfoProvider = beanContext.getService(IPropertyInfoProvider.class);
}
return propertyInfoProvider;
}
@Override
protected IConversionHelper getConversionHelper() {
if (conversionHelper == null) {
conversionHelper = beanContext.getService(IConversionHelper.class);
}
return conversionHelper;
}
@Override
protected IImmutableTypeSet getImmutableTypeSet() {
if (immutableTypeSet == null) {
immutableTypeSet = beanContext.getService(IImmutableTypeSet.class);
}
return immutableTypeSet;
}
}
|
Dennis-Koch/ambeth
|
jambeth/jambeth-ioc/src/main/java/com/koch/ambeth/ioc/BeanMonitoringSupport.java
|
Java
|
apache-2.0
| 1,213 |
package fr.iut.csid.empower.elearning.core.service.impl;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import org.springframework.data.jpa.repository.JpaRepository;
import fr.iut.csid.empower.elearning.core.domain.course.Course;
import fr.iut.csid.empower.elearning.core.domain.course.CourseTeaching;
import fr.iut.csid.empower.elearning.core.domain.course.session.CourseSession;
import fr.iut.csid.empower.elearning.core.dto.impl.CourseSessionDTO;
import fr.iut.csid.empower.elearning.core.exception.CourseNotExistsException;
import fr.iut.csid.empower.elearning.core.service.CourseSessionService;
import fr.iut.csid.empower.elearning.core.service.NotificationService;
import fr.iut.csid.empower.elearning.core.service.dao.course.CourseDAO;
import fr.iut.csid.empower.elearning.core.service.dao.course.CourseTeachingDAO;
import fr.iut.csid.empower.elearning.core.service.dao.course.session.CourseSessionDAO;
/**
*
*/
@Named
public class CourseSessionServiceImpl extends AbstractCrudService<CourseSession, Long> implements CourseSessionService {
@Inject
private CourseSessionDAO courseSessionDAO;
@Inject
private CourseDAO courseDAO;
@Inject
private CourseTeachingDAO courseTeachingDAO;
@Inject
private NotificationService notificationService;
@Override
public CourseSession createFromDTO(CourseSessionDTO entityDTO) {
Course ownerCourse = courseDAO.findOne(Long.valueOf(entityDTO.getOwnerId()));
CourseSession courseSession = new CourseSession(entityDTO.getLabel(), ownerCourse, courseSessionDAO.countByOwnerCourse(ownerCourse) + 1, null, null,
entityDTO.getSummary());
List<CourseTeaching> courseTeachingList = courseTeachingDAO.findByCourse(ownerCourse);
if (ownerCourse != null) {
courseSessionDAO.save(courseSession);
for(CourseTeaching courseTeaching : courseTeachingList){
notificationService.createNotification("Création de session", courseTeaching.getTeacher(),
"La session " + courseSession.getLabel() + " a été créée pour le cours " + ownerCourse.getLabel() + ".");
}
return courseSession;
// entityDTO.getStartDate(), entityDTO.getEndDate()));
}
return null;
}
@Override
public CourseSession saveFromDTO(CourseSessionDTO entityDTO, Long id) {
CourseSession courseSession = courseSessionDAO.findOne(id);
if (courseSession != null) {
// TODO update autres champs ?
courseSession.setLabel(entityDTO.getLabel());
// courseSession.setStartDate(entityDTO.getStartDate());
// courseSession.setEndDate(entityDTO.getEndDate());
return courseSessionDAO.save(courseSession);
}
// TODO erreur globale
throw new CourseNotExistsException();
}
@Override
protected JpaRepository<CourseSession, Long> getDAO() {
return courseSessionDAO;
}
@Override
public List<CourseSession> findByOwner(Long ownerEntityId) {
Course course = courseDAO.findOne(ownerEntityId);
if (course != null) {
return courseSessionDAO.findByOwnerCourseOrderBySessionRankAsc(course);
}
throw new CourseNotExistsException();
}
@Override
public void delete(CourseSession courseSession) {
super.delete(courseSession);
Course ownerCourse = courseSession.getOwnerCourse();
List<CourseTeaching> courseTeachingList = courseTeachingDAO.findByCourse(ownerCourse);
for(CourseTeaching courseTeaching : courseTeachingList){
notificationService.createNotification("Suppression de session", courseTeaching.getTeacher(),
"La session " + courseSession.getLabel() + " a été supprimée pour le cours " + ownerCourse.getLabel() + ".");
}
}
}
|
piibl/elearning-parent
|
elearning-core/src/main/java/fr/iut/csid/empower/elearning/core/service/impl/CourseSessionServiceImpl.java
|
Java
|
apache-2.0
| 3,566 |
<?php
declare(strict_types=1);
/*
* +----------------------------------------------------------------------+
* | ThinkSNS Plus |
* +----------------------------------------------------------------------+
* | Copyright (c) 2016-Present ZhiYiChuangXiang Technology Co., Ltd. |
* +----------------------------------------------------------------------+
* | This source file is subject to enterprise private license, that is |
* | bundled with this package in the file LICENSE, and is available |
* | through the world-wide-web at the following url: |
* | https://github.com/slimkit/plus/blob/master/LICENSE |
* +----------------------------------------------------------------------+
* | Author: Slim Kit Group <master@zhiyicx.com> |
* | Homepage: www.thinksns.com |
* +----------------------------------------------------------------------+
*/
namespace Zhiyi\Plus\Models;
// use Illuminate\Cache\TaggableStore;
// use Illuminate\Support\Facades\Cache;
// use Illuminate\Support\Facades\Config;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
* Zhiyi\Plus\Models\Role.
*
* @property int $id
* @property string $name
* @property string|null $display_name
* @property string|null $description
* @property int|null $non_delete
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @property-read \Illuminate\Database\Eloquent\Collection|\Zhiyi\Plus\Models\Ability[] $abilities
* @property-read int|null $abilities_count
* @property-read \Illuminate\Database\Eloquent\Collection|\Zhiyi\Plus\Models\User[] $users
* @property-read int|null $users_count
* @method static \Illuminate\Database\Eloquent\Builder|Role newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|Role newQuery()
* @method static \Illuminate\Database\Eloquent\Builder|Role query()
* @method static \Illuminate\Database\Eloquent\Builder|Role whereCreatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|Role whereDescription($value)
* @method static \Illuminate\Database\Eloquent\Builder|Role whereDisplayName($value)
* @method static \Illuminate\Database\Eloquent\Builder|Role whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder|Role whereName($value)
* @method static \Illuminate\Database\Eloquent\Builder|Role whereNonDelete($value)
* @method static \Illuminate\Database\Eloquent\Builder|Role whereUpdatedAt($value)
* @mixin \Eloquent
*/
class Role extends Model
{
use HasFactory;
/**
* Get all abilities of the role.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
* @author Seven Du <shiweidu@outlook.com>
*/
public function abilities()
{
return $this->belongsToMany(Ability::class, 'ability_role', 'role_id', 'ability_id');
}
/**
* Get all users of the role.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
* @author Seven Du <shiweidu@outlook.com>
*/
public function users()
{
return $this->belongsToMany(User::class, 'role_user', 'role_id', 'user_id');
}
/**
* Get or check The role ability.
*
* @param string $ability
* @return false|Ability
* @author Seven Du <shiweidu@outlook.com>
*/
public function ability(string $ability)
{
return $this->abilities->keyBy('name')->get($ability, false);
}
}
|
slimkit/thinksns-plus
|
app/Models/Role.php
|
PHP
|
apache-2.0
| 3,639 |
/*
* Copyright 2017 SIP3.IO CORP.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.sip3.tapir.twig.mongo;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import io.sip3.tapir.core.partition.Partition;
import io.sip3.tapir.core.partition.PartitionFactory;
import io.sip3.tapir.twig.mongo.query.Query;
import io.sip3.tapir.twig.util.TimeIntervalIterator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Created by agafox.
*/
@Component("m")
public class Mongo {
private final Partition partition;
private final int batchSize;
private final MongoDatabase db;
@Autowired
public Mongo(@Value("${mongo.partition}") String partition,
@Value("${mongo.batchSize}") int batchSize,
MongoDatabase db) {
this.partition = PartitionFactory.ofPattern(partition);
this.batchSize = batchSize;
this.db = db;
}
public <T> Iterator<T> find(String prefix, Query query, Class<T> clazz) {
return new Iterator<T>() {
private final Iterator<Long> intervals = TimeIntervalIterator.of(query.millis(), partition);
private MongoCursor<T> cursor;
@Override
public boolean hasNext() {
if (cursor != null && cursor.hasNext()) {
return true;
}
while (intervals.hasNext()) {
long millis = intervals.next();
String collection = collection(prefix, partition.define(millis, false));
FindIterable<T> fi = db.getCollection(collection, clazz)
.find(query.filter())
.batchSize(batchSize);
if (query.sort() != null) {
fi.sort(query.sort());
}
cursor = fi.iterator();
if (cursor.hasNext()) {
return true;
}
}
return false;
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return cursor.next();
}
};
}
private String collection(String prefix, String suffix) {
return prefix + "_" + suffix;
}
}
|
sip3io/tapir
|
twig/src/main/java/io/sip3/tapir/twig/mongo/Mongo.java
|
Java
|
apache-2.0
| 3,180 |
/**
* Transcend Computing, Inc.
* Confidential and Proprietary
* Copyright (c) Transcend Computing, Inc. 2012
* All Rights Reserved.
*/
package com.transcend.monitor.transform;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import com.google.protobuf.Message;
import com.msi.tough.core.Appctx;
import com.msi.tough.monitor.common.MarshallingUtils;
import com.msi.tough.monitor.common.MonitorConstants;
import com.msi.tough.query.ProtobufUtil;
import com.transcend.monitor.message.MetricAlarmMessage.Dimension;
/**
* @author jgardner
*
*/
public abstract class BaseMonitorUnmarshaller<T extends Message> {
private final static Logger logger = Appctx
.getLogger(BaseMonitorUnmarshaller.class.getName());
/**
* General signature for umarshall.
*
* @param in
* @return built object
* @throws Exception
*/
public abstract T unmarshall(Map<String, String[]> in) throws Exception;
/**
* Convenience method to unmarshall common fields.
*
* @param instance
* @param in
* @throws Exception
*/
public T unmarshall(T instance, Map<String, String[]> in) {
String namespace = MarshallingUtils.unmarshallString(in,
MonitorConstants.NODE_NAMESPACE,
logger);
if ("AWS/EC2".equals(namespace)) {
// Since we are AWS compatible, accept AWS namespace, sub our own.
namespace = "MSI/EC2";
}
instance = ProtobufUtil.setRequiredField(instance, "namespace", namespace);
return instance;
}
/**
* @param mapIn
* @return
*/
Collection<Dimension> unmarshallDimensions(
Map<String, String[]> in)
{
List<Dimension> dims = new ArrayList<Dimension>();
int i = 0;
while (true)
{
i++;
String prefix = "Dimensions.member." + i + ".";
final String n[] = in.get(prefix + MonitorConstants.NODE_NAME);
if (n == null)
{
break;
}
final String v[] = in.get(prefix + MonitorConstants.NODE_VALUE);
Dimension.Builder d = Dimension.newBuilder();
d.setName(n[0]);
d.setValue((v != null ? v[0] : ""));
dims.add(d.build());
}
return dims;
}
}
|
TranscendComputing/TopStackMetricSearch
|
src/com/transcend/monitor/transform/BaseMonitorUnmarshaller.java
|
Java
|
apache-2.0
| 2,416 |
require 'spec_helper'
describe 'graphite', :type => :class do
let(:facts) { {:osfamily => 'Debian'} }
let(:params) {{
:user => 'graphite',
:group => 'graphite',
:manage_user => true,
}}
it { should contain_user('carbon_cache_user').with_ensure('present').
with_name('graphite').
with_gid('graphite')
}
it { should contain_group('carbon_cache_group').with_ensure('present').
with_name('graphite')
}
end
|
gds-operations/puppet-graphite
|
spec/classes/graphite/graphite__user_spec.rb
|
Ruby
|
apache-2.0
| 455 |
package ch.adnovum.jcan.katharsis.mock.repository;
import java.util.HashMap;
import java.util.Map;
import javax.enterprise.context.ApplicationScoped;
import ch.adnovum.jcan.katharsis.mock.models.Project;
import ch.adnovum.jcan.katharsis.security.ResourcePermissionInformationImpl;
import io.katharsis.queryspec.QuerySpec;
import io.katharsis.repository.ResourceRepositoryBase;
import io.katharsis.resource.list.DefaultResourceList;
import io.katharsis.resource.list.ResourceList;
@ApplicationScoped
public class ProjectRepository extends ResourceRepositoryBase<Project, Long> {
private static final Map<Long, Project> PROJECTS = new HashMap<>();
public ProjectRepository() {
super(Project.class);
}
@Override
public <S extends Project> S save(S entity) {
PROJECTS.put(entity.getId(), entity);
return entity;
}
@Override
public ResourceList<Project> findAll(QuerySpec querySpec) {
DefaultResourceList<Project> list = querySpec.apply(PROJECTS.values());
list.setMeta(new ResourcePermissionInformationImpl());
return list;
}
@Override
public void delete(Long id) {
PROJECTS.remove(id);
}
public static void clear() {
PROJECTS.clear();
}
}
|
apetrucci/katharsis-framework
|
katharsis-security/src/integrationTest/java/ch/adnovum/jcan/katharsis/mock/repository/ProjectRepository.java
|
Java
|
apache-2.0
| 1,176 |
/*******************************************************************************
*
* Pentaho Big Data
*
* Copyright (C) 2002-2017 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.bigdata.api.hdfs;
import org.pentaho.big.data.api.cluster.NamedCluster;
import org.pentaho.big.data.api.initializer.ClusterInitializationException;
import java.net.URI;
/**
* Created by bryan on 5/22/15.
*/
public interface HadoopFileSystemLocator {
@Deprecated
HadoopFileSystem getHadoopFilesystem( NamedCluster namedCluster ) throws ClusterInitializationException;
HadoopFileSystem getHadoopFilesystem( NamedCluster namedCluster, URI uri ) throws ClusterInitializationException;
}
|
stepanovdg/big-data-plugin
|
api/hdfs/src/main/java/org/pentaho/bigdata/api/hdfs/HadoopFileSystemLocator.java
|
Java
|
apache-2.0
| 1,411 |
/*
* Copyright 2013, Edmodo, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work except in compliance with the License.
* You may obtain a copy of the License in the LICENSE file, or 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.theartofdev.edmodo.cropper;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import com.edmodo.cropper.R;
import com.theartofdev.edmodo.cropper.cropwindow.CropOverlayView;
import com.theartofdev.edmodo.cropper.cropwindow.edge.Edge;
import com.theartofdev.edmodo.cropper.util.ImageViewUtil;
/**
* Custom view that provides cropping capabilities to an image.
*/
public class CropImageView extends FrameLayout {
//region: Fields and Consts
private static final Rect EMPTY_RECT = new Rect();
// Sets the default image guidelines to show when resizing
public static final int DEFAULT_GUIDELINES = 1;
public static final boolean DEFAULT_FIXED_ASPECT_RATIO = false;
public static final int DEFAULT_ASPECT_RATIO_X = 1;
public static final int DEFAULT_ASPECT_RATIO_Y = 1;
public static final int DEFAULT_SCALE_TYPE_INDEX = 0;
public static final int DEFAULT_CROP_SHAPE_INDEX = 0;
private static final int DEFAULT_IMAGE_RESOURCE = 0;
private static final ImageView.ScaleType[] VALID_SCALE_TYPES = new ImageView.ScaleType[]{ImageView.ScaleType.CENTER_INSIDE, ImageView.ScaleType.FIT_CENTER};
private static final CropShape[] VALID_CROP_SHAPES = new CropShape[]{CropShape.RECTANGLE, CropShape.OVAL};
private static final String DEGREES_ROTATED = "DEGREES_ROTATED";
private ImageView mImageView;
private CropOverlayView mCropOverlayView;
private Bitmap mBitmap;
private int mDegreesRotated = 0;
private int mLayoutWidth;
private int mLayoutHeight;
/**
* Instance variables for customizable attributes
*/
private int mGuidelines = DEFAULT_GUIDELINES;
private boolean mFixAspectRatio = DEFAULT_FIXED_ASPECT_RATIO;
private int mAspectRatioX = DEFAULT_ASPECT_RATIO_X;
private int mAspectRatioY = DEFAULT_ASPECT_RATIO_Y;
private int mImageResource = DEFAULT_IMAGE_RESOURCE;
private ImageView.ScaleType mScaleType = VALID_SCALE_TYPES[DEFAULT_SCALE_TYPE_INDEX];
/**
* The shape of the cropping area - rectangle/circular.
*/
private CropImageView.CropShape mCropShape;
/**
* The URI that the image was loaded from (if loaded from URI)
*/
private Uri mLoadedImageUri;
/**
* The sample size the image was loaded by if was loaded by URI
*/
private int mLoadedSampleSize = 1;
//endregion
public CropImageView(Context context) {
super(context);
init(context);
}
public CropImageView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CropImageView, 0, 0);
try {
mGuidelines = ta.getInteger(R.styleable.CropImageView_guidelines, DEFAULT_GUIDELINES);
mFixAspectRatio = ta.getBoolean(R.styleable.CropImageView_fixAspectRatio, DEFAULT_FIXED_ASPECT_RATIO);
mAspectRatioX = ta.getInteger(R.styleable.CropImageView_aspectRatioX, DEFAULT_ASPECT_RATIO_X);
mAspectRatioY = ta.getInteger(R.styleable.CropImageView_aspectRatioY, DEFAULT_ASPECT_RATIO_Y);
mImageResource = ta.getResourceId(R.styleable.CropImageView_imageResource, DEFAULT_IMAGE_RESOURCE);
mScaleType = VALID_SCALE_TYPES[ta.getInt(R.styleable.CropImageView_scaleType, DEFAULT_SCALE_TYPE_INDEX)];
mCropShape = VALID_CROP_SHAPES[ta.getInt(R.styleable.CropImageView_cropShape, DEFAULT_CROP_SHAPE_INDEX)];
} finally {
ta.recycle();
}
init(context);
}
/**
* Set the scale type of the image in the crop view
*/
public ImageView.ScaleType getScaleType() {
return mScaleType;
}
/**
* Set the scale type of the image in the crop view
*/
public void setScaleType(ImageView.ScaleType scaleType) {
mScaleType = scaleType;
if (mImageView != null)
mImageView.setScaleType(mScaleType);
}
/**
* The shape of the cropping area - rectangle/circular.
*/
public CropImageView.CropShape getCropShape() {
return mCropShape;
}
/**
* The shape of the cropping area - rectangle/circular.
*/
public void setCropShape(CropImageView.CropShape cropShape) {
if (cropShape != mCropShape) {
mCropShape = cropShape;
mCropOverlayView.setCropShape(cropShape);
}
}
/**
* Sets whether the aspect ratio is fixed or not; true fixes the aspect ratio, while
* false allows it to be changed.
*
* @param fixAspectRatio Boolean that signals whether the aspect ratio should be
* maintained.
*/
public void setFixedAspectRatio(boolean fixAspectRatio) {
mCropOverlayView.setFixedAspectRatio(fixAspectRatio);
}
/**
* Sets the guidelines for the CropOverlayView to be either on, off, or to show when
* resizing the application.
*
* @param guidelines Integer that signals whether the guidelines should be on, off, or
* only showing when resizing.
*/
public void setGuidelines(int guidelines) {
mCropOverlayView.setGuidelines(guidelines);
}
/**
* Sets the both the X and Y values of the aspectRatio.
*
* @param aspectRatioX int that specifies the new X value of the aspect ratio
* @param aspectRatioY int that specifies the new Y value of the aspect ratio
*/
public void setAspectRatio(int aspectRatioX, int aspectRatioY) {
mAspectRatioX = aspectRatioX;
mCropOverlayView.setAspectRatioX(mAspectRatioX);
mAspectRatioY = aspectRatioY;
mCropOverlayView.setAspectRatioY(mAspectRatioY);
}
/**
* Returns the integer of the imageResource
*/
public int getImageResource() {
return mImageResource;
}
/**
* Sets a Bitmap as the content of the CropImageView.
*
* @param bitmap the Bitmap to set
*/
public void setImageBitmap(Bitmap bitmap) {
// if we allocated the bitmap, release it as fast as possible
if (mBitmap != null && (mImageResource > 0 || mLoadedImageUri != null)) {
mBitmap.recycle();
}
// clean the loaded image flags for new image
mImageResource = 0;
mLoadedImageUri = null;
mLoadedSampleSize = 1;
mDegreesRotated = 0;
mBitmap = bitmap;
mImageView.setImageBitmap(mBitmap);
if (mCropOverlayView != null) {
mCropOverlayView.resetCropOverlayView();
}
}
/**
* Sets a Bitmap and initializes the image rotation according to the EXIT data.<br>
* <br>
* The EXIF can be retrieved by doing the following:
* <code>ExifInterface exif = new ExifInterface(path);</code>
*
* @param bitmap the original bitmap to set; if null, this
* @param exif the EXIF information about this bitmap; may be null
*/
public void setImageBitmap(Bitmap bitmap, ExifInterface exif) {
if (bitmap != null && exif != null) {
ImageViewUtil.RotateBitmapResult result = ImageViewUtil.rotateBitmapByExif(bitmap, exif);
bitmap = result.bitmap;
mDegreesRotated = result.degrees;
}
setImageBitmap(bitmap);
}
/**
* Sets a Drawable as the content of the CropImageView.
*
* @param resId the drawable resource ID to set
*/
public void setImageResource(int resId) {
if (resId != 0) {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resId);
setImageBitmap(bitmap);
mImageResource = resId;
}
}
/**
* Sets a bitmap loaded from the given Android URI as the content of the CropImageView.<br>
* Can be used with URI from gallery or camera source.<br>
* Will rotate the image by exif data.<br>
*
* @param uri the URI to load the image from
*/
public void setImageUri(Uri uri) {
if (uri != null) {
DisplayMetrics metrics = getResources().getDisplayMetrics();
double densityAdj = metrics.density > 1 ? 1 / metrics.density : 1;
int width = (int) (metrics.widthPixels * densityAdj);
int height = (int) (metrics.heightPixels * densityAdj);
ImageViewUtil.DecodeBitmapResult decodeResult =
ImageViewUtil.decodeSampledBitmap(getContext(), uri, width, height);
ImageViewUtil.RotateBitmapResult rotateResult =
ImageViewUtil.rotateBitmapByExif(getContext(), decodeResult.bitmap, uri);
setImageBitmap(rotateResult.bitmap);
mLoadedImageUri = uri;
mLoadedSampleSize = decodeResult.sampleSize;
mDegreesRotated = rotateResult.degrees;
}
}
/**
* Gets the crop window's position relative to the source Bitmap (not the image
* displayed in the CropImageView).
*
* @return a RectF instance containing cropped area boundaries of the source Bitmap
*/
public Rect getActualCropRect() {
if (mBitmap != null) {
final Rect displayedImageRect = ImageViewUtil.getBitmapRect(mBitmap, mImageView, mScaleType);
// Get the scale factor between the actual Bitmap dimensions and the displayed dimensions for width.
final float actualImageWidth = mBitmap.getWidth();
final float displayedImageWidth = displayedImageRect.width();
final float scaleFactorWidth = actualImageWidth / displayedImageWidth;
// Get the scale factor between the actual Bitmap dimensions and the displayed dimensions for height.
final float actualImageHeight = mBitmap.getHeight();
final float displayedImageHeight = displayedImageRect.height();
final float scaleFactorHeight = actualImageHeight / displayedImageHeight;
// Get crop window position relative to the displayed image.
final float displayedCropLeft = Edge.LEFT.getCoordinate() - displayedImageRect.left;
final float displayedCropTop = Edge.TOP.getCoordinate() - displayedImageRect.top;
final float displayedCropWidth = Edge.getWidth();
final float displayedCropHeight = Edge.getHeight();
// Scale the crop window position to the actual size of the Bitmap.
float actualCropLeft = displayedCropLeft * scaleFactorWidth;
float actualCropTop = displayedCropTop * scaleFactorHeight;
float actualCropRight = actualCropLeft + displayedCropWidth * scaleFactorWidth;
float actualCropBottom = actualCropTop + displayedCropHeight * scaleFactorHeight;
// Correct for floating point errors. Crop rect boundaries should not exceed the source Bitmap bounds.
actualCropLeft = Math.max(0f, actualCropLeft);
actualCropTop = Math.max(0f, actualCropTop);
actualCropRight = Math.min(mBitmap.getWidth(), actualCropRight);
actualCropBottom = Math.min(mBitmap.getHeight(), actualCropBottom);
return new Rect((int) actualCropLeft, (int) actualCropTop, (int) actualCropRight, (int) actualCropBottom);
} else {
return null;
}
}
/**
* Gets the crop window's position relative to the source Bitmap (not the image
* displayed in the CropImageView) and the original rotation.
*
* @return a RectF instance containing cropped area boundaries of the source Bitmap
*/
@SuppressWarnings("SuspiciousNameCombination")
public Rect getActualCropRectNoRotation() {
if (mBitmap != null) {
Rect rect = getActualCropRect();
int rotateSide = mDegreesRotated / 90;
if (rotateSide == 1) {
rect.set(rect.top, mBitmap.getWidth() - rect.right, rect.bottom, mBitmap.getWidth() - rect.left);
} else if (rotateSide == 2) {
rect.set(mBitmap.getWidth() - rect.right, mBitmap.getHeight() - rect.bottom, mBitmap.getWidth() - rect.left, mBitmap.getHeight() - rect.top);
} else if (rotateSide == 3) {
rect.set(mBitmap.getHeight() - rect.bottom, rect.left, mBitmap.getHeight() - rect.top, rect.right);
}
rect.set(rect.left * mLoadedSampleSize, rect.top * mLoadedSampleSize, rect.right * mLoadedSampleSize, rect.bottom * mLoadedSampleSize);
return rect;
} else {
return null;
}
}
/**
* Rotates image by the specified number of degrees clockwise. Cycles from 0 to 360
* degrees.
*
* @param degrees Integer specifying the number of degrees to rotate.
*/
public void rotateImage(int degrees) {
if (mBitmap != null) {
Matrix matrix = new Matrix();
matrix.postRotate(degrees);
Bitmap bitmap = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(), mBitmap.getHeight(), matrix, true);
setImageBitmap(bitmap);
mDegreesRotated += degrees;
mDegreesRotated = mDegreesRotated % 360;
}
}
/**
* Gets the cropped image based on the current crop window.
*
* @return a new Bitmap representing the cropped image
*/
public Bitmap getCroppedImage() {
return getCroppedImage(0, 0);
}
/**
* Gets the cropped image based on the current crop window.<br>
* If image loaded from URI will use sample size to fir the requested width and height.
*
* @return a new Bitmap representing the cropped image
*/
public Bitmap getCroppedImage(int reqWidth, int reqHeight) {
if (mBitmap != null) {
if (mLoadedImageUri != null && mLoadedSampleSize > 1) {
Rect rect = getActualCropRectNoRotation();
reqWidth = reqWidth > 0 ? reqWidth : rect.width();
reqHeight = reqHeight > 0 ? reqHeight : rect.height();
ImageViewUtil.DecodeBitmapResult result =
ImageViewUtil.decodeSampledBitmapRegion(getContext(), mLoadedImageUri, rect, reqWidth, reqHeight);
Bitmap bitmap = result.bitmap;
if (mDegreesRotated > 0) {
bitmap = ImageViewUtil.rotateBitmap(bitmap, mDegreesRotated);
}
return bitmap;
} else {
Rect rect = getActualCropRect();
return Bitmap.createBitmap(mBitmap, rect.left, rect.top, rect.width(), rect.height());
}
} else {
return null;
}
}
/**
* Gets the cropped circle image based on the current crop selection.
*
* @return a new Circular Bitmap representing the cropped image
*/
public Bitmap getCroppedOvalImage() {
if (mBitmap != null) {
Bitmap cropped = getCroppedImage();
int width = cropped.getWidth();
int height = cropped.getHeight();
Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
RectF rect = new RectF(0, 0, width, height);
canvas.drawOval(rect, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(cropped, 0, 0, paint);
return output;
} else {
return null;
}
}
//region: Private methods
@Override
public Parcelable onSaveInstanceState() {
final Bundle bundle = new Bundle();
bundle.putParcelable("instanceState", super.onSaveInstanceState());
bundle.putInt(DEGREES_ROTATED, mDegreesRotated);
return bundle;
}
@Override
public void onRestoreInstanceState(Parcelable state) {
if (state instanceof Bundle) {
final Bundle bundle = (Bundle) state;
if (mBitmap != null) {
// Fixes the rotation of the image when orientation changes.
mDegreesRotated = bundle.getInt(DEGREES_ROTATED);
int tempDegrees = mDegreesRotated;
rotateImage(mDegreesRotated);
mDegreesRotated = tempDegrees;
}
super.onRestoreInstanceState(bundle.getParcelable("instanceState"));
} else {
super.onRestoreInstanceState(state);
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
if (mBitmap != null) {
final Rect bitmapRect = ImageViewUtil.getBitmapRect(mBitmap, this, mScaleType);
mCropOverlayView.setBitmapRect(bitmapRect);
} else {
mCropOverlayView.setBitmapRect(EMPTY_RECT);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (mBitmap != null) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// Bypasses a baffling bug when used within a ScrollView, where
// heightSize is set to 0.
if (heightSize == 0) {
heightSize = mBitmap.getHeight();
}
int desiredWidth;
int desiredHeight;
double viewToBitmapWidthRatio = Double.POSITIVE_INFINITY;
double viewToBitmapHeightRatio = Double.POSITIVE_INFINITY;
// Checks if either width or height needs to be fixed
if (widthSize < mBitmap.getWidth()) {
viewToBitmapWidthRatio = (double) widthSize / (double) mBitmap.getWidth();
}
if (heightSize < mBitmap.getHeight()) {
viewToBitmapHeightRatio = (double) heightSize / (double) mBitmap.getHeight();
}
// If either needs to be fixed, choose smallest ratio and calculate
// from there
if (viewToBitmapWidthRatio != Double.POSITIVE_INFINITY || viewToBitmapHeightRatio != Double.POSITIVE_INFINITY) {
if (viewToBitmapWidthRatio <= viewToBitmapHeightRatio) {
desiredWidth = widthSize;
desiredHeight = (int) (mBitmap.getHeight() * viewToBitmapWidthRatio);
} else {
desiredHeight = heightSize;
desiredWidth = (int) (mBitmap.getWidth() * viewToBitmapHeightRatio);
}
}
// Otherwise, the picture is within frame layout bounds. Desired
// width is
// simply picture size
else {
desiredWidth = mBitmap.getWidth();
desiredHeight = mBitmap.getHeight();
}
int width = getOnMeasureSpec(widthMode, widthSize, desiredWidth);
int height = getOnMeasureSpec(heightMode, heightSize, desiredHeight);
mLayoutWidth = width;
mLayoutHeight = height;
final Rect bitmapRect = ImageViewUtil.getBitmapRect(mBitmap.getWidth(),
mBitmap.getHeight(),
mLayoutWidth,
mLayoutHeight,
mScaleType);
mCropOverlayView.setBitmapRect(bitmapRect);
// MUST CALL THIS
setMeasuredDimension(mLayoutWidth, mLayoutHeight);
} else {
mCropOverlayView.setBitmapRect(EMPTY_RECT);
setMeasuredDimension(widthSize, heightSize);
}
}
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
if (mLayoutWidth > 0 && mLayoutHeight > 0) {
// Gets original parameters, and creates the new parameters
final ViewGroup.LayoutParams origparams = this.getLayoutParams();
origparams.width = mLayoutWidth;
origparams.height = mLayoutHeight;
setLayoutParams(origparams);
}
}
private void init(Context context) {
final LayoutInflater inflater = LayoutInflater.from(context);
final View v = inflater.inflate(R.layout.crop_image_view, this, true);
mImageView = (ImageView) v.findViewById(R.id.ImageView_image);
mImageView.setScaleType(mScaleType);
setImageResource(mImageResource);
mCropOverlayView = (CropOverlayView) v.findViewById(R.id.CropOverlayView);
mCropOverlayView.setInitialAttributeValues(mGuidelines, mFixAspectRatio, mAspectRatioX, mAspectRatioY);
mCropOverlayView.setCropShape(mCropShape);
}
/**
* Determines the specs for the onMeasure function. Calculates the width or height
* depending on the mode.
*
* @param measureSpecMode The mode of the measured width or height.
* @param measureSpecSize The size of the measured width or height.
* @param desiredSize The desired size of the measured width or height.
* @return The final size of the width or height.
*/
private static int getOnMeasureSpec(int measureSpecMode, int measureSpecSize, int desiredSize) {
// Measure Width
int spec;
if (measureSpecMode == MeasureSpec.EXACTLY) {
// Must be this size
spec = measureSpecSize;
} else if (measureSpecMode == MeasureSpec.AT_MOST) {
// Can't be bigger than...; match_parent value
spec = Math.min(desiredSize, measureSpecSize);
} else {
// Be whatever you want; wrap_content
spec = desiredSize;
}
return spec;
}
//endregion
//region: Inner class: CropShape
/**
* The possible cropping area shape
*/
public static enum CropShape {
RECTANGLE,
OVAL
}
//endregion
}
|
akhilesh0707/Android-Image-Cropper
|
cropper/src/main/java/com/theartofdev/edmodo/cropper/CropImageView.java
|
Java
|
apache-2.0
| 23,437 |
/// <reference types="lodash" />
/**
* @module model
*/
/** */
import * as _ from 'lodash';
/**
* custom Array type supporting an index lookup.
*
* Beware, the implementation does not support modifications to the data contained.
*/
export interface ArrayLookup<T> extends Array<T> {
/**
* elements keyed by lookup property.
*/
index: _.Dictionary<T>;
/**
* whether an element of key exists.
*
* @param key to check.
* @return {boolean} existance indication.
*
* @see get
*/
has(key: string): boolean;
/**
* accesses an element by key.
*
* Use this method in case it is known that the key is valid.
* An assertion will fire if it is not.
*
* @param key lookup property value.
* @return {T} element of key.
*
* @see has
*/
get(key: string): T;
}
/**
* mirrors ModelContainer of Relution server.
*/
export declare class ModelContainer {
static factory: ModelFactory;
readonly factory: ModelFactory;
uuid: string;
version: number;
bundle: string;
application: string;
aclEntries: string[];
effectivePermissions: string;
createdUser: string;
createdDate: Date;
modifiedUser: string;
modifiedDate: Date;
name: string;
description: string;
models: ArrayLookup<MetaModel>;
constructor(other?: ModelContainer);
fromJSON(json: ModelContainer): this;
}
/**
* mirrors MetaModel of Relution server.
*/
export declare class MetaModel {
static factory: ModelFactory;
readonly factory: ModelFactory;
uuid: string;
version: number;
bundle: string;
aclEntries: string[];
effectivePermissions: string;
containerUuid: string;
name: string;
label: string;
description: string;
parents: string[];
abstrakt: boolean;
icon: any;
fieldDefinitions: ArrayLookup<FieldDefinition>;
propertyMap: any;
constructor(other?: MetaModel);
fromJSON(json: MetaModel): this;
}
/**
* mirrors FieldDefinition of Relution server.
*/
export declare class FieldDefinition {
static factory: ModelFactory;
readonly factory: ModelFactory;
name: string;
label: string;
description: string;
group: string;
tooltip: string;
dataType: string;
defaultValue: string;
enumDefinition: EnumDefinition;
keyField: boolean;
index: boolean;
mandatory: boolean;
minSize: number;
maxSize: number;
regexp: string;
propertyMap: any;
readonly dataTypeNormalized: string;
constructor(other?: FieldDefinition);
fromJSON(json: FieldDefinition): this;
}
/**
* mirrors EnumDefinition of Relution server.
*/
export declare class EnumDefinition {
static factory: ModelFactory;
readonly factory: ModelFactory;
items: ArrayLookup<Item>;
enumerable: string;
strict: boolean;
constructor(other?: EnumDefinition);
fromJSON(json: EnumDefinition): this;
}
/**
* represents a predefined choice of an EnumDefinition.
*/
export interface Item {
value: number | string;
label: string;
url?: string;
}
/**
* constructors of model types must adhere the following interface.
*/
export interface ModelFactoryCtor<T> {
/**
* new-able from JSON literal data.
*
* @param json literal data.
*/
new (other?: T): T;
/**
* static association to factory.
*/
factory: ModelFactory;
}
/**
* construction from JSON literal data.
*
* @example Use the following for creation of a subclasses hierarchy:
* export class SomeModelContainer extends ModelContainer {
* public static factory: SomeModelFactory;
* }
* export class SomeMetaModel extends MetaModel {
* public static factory: SomeModelFactory;
* }
* export class SomeFieldDefinition extends FieldDefinition {
* public static factory: SomeModelFactory;
* }
* export class SomeEnumDefinition extends EnumDefinition {
* public static factory: SomeModelFactory;
* }
* export class SomeModelFactory extends ModelFactory {
* public static instance = new SomeModelFactory(SomeModelContainer, SomeMetaModel,
* SomeFieldDefinition, SomeEnumDefinition);
* }
*/
export declare class ModelFactory {
ModelContainer: ModelFactoryCtor<ModelContainer>;
MetaModel: ModelFactoryCtor<MetaModel>;
FieldDefinition: ModelFactoryCtor<FieldDefinition>;
EnumDefinition: ModelFactoryCtor<EnumDefinition>;
static instance: ModelFactory;
constructor(ModelContainer: ModelFactoryCtor<ModelContainer>, MetaModel: ModelFactoryCtor<MetaModel>, FieldDefinition: ModelFactoryCtor<FieldDefinition>, EnumDefinition: ModelFactoryCtor<EnumDefinition>);
static factoryOf<T>(obj: T): ModelFactory;
fromJSON(json: string): ModelContainer;
fromJSON(json: any): ModelContainer;
}
|
relution-io/relution-sdk
|
lib/model/ModelContainer.d.ts
|
TypeScript
|
apache-2.0
| 4,822 |
/*
* Copyright 2015-2020 OpenCB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opencb.opencga.catalog.utils;
import java.nio.BufferUnderflowException;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class UuidUtils {
// OpenCGA uuid pattern: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
// -------- ----
// time low installation
// ---- ------------
// time mid random
// ----
// version (1 hex digit) + internal version (1 hex digit) + entity (2 hex digit)
public static final Pattern UUID_PATTERN = Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-00[0-9a-f]{2}-[0-9a-f]{4}-[0-9a-f]{12}");
public enum Entity {
AUDIT(0),
PROJECT(1),
STUDY(2),
FILE(3),
SAMPLE(4),
COHORT(5),
INDIVIDUAL(6),
FAMILY(7),
JOB(8),
CLINICAL(9),
PANEL(10),
INTERPRETATION(11);
private final int mask;
Entity(int mask) {
this.mask = mask;
}
public int getMask() {
return mask;
}
}
public static String generateOpenCgaUuid(Entity entity) {
return generateOpenCgaUuid(entity, new Date());
}
public static String generateOpenCgaUuid(Entity entity, Date date) {
long mostSignificantBits = getMostSignificantBits(date, entity);
long leastSignificantBits = getLeastSignificantBits();
String s = new UUID(mostSignificantBits, leastSignificantBits).toString();
isOpenCgaUuid(s);
return new UUID(mostSignificantBits, leastSignificantBits).toString();
}
public static boolean isOpenCgaUuid(String token) {
if (token.length() == 36) {
try {
Matcher matcher = UUID_PATTERN.matcher(token);
return matcher.find();
} catch (BufferUnderflowException e) {
return false;
}
}
return false;
}
private static long getMostSignificantBits(Date date, Entity entity) {
long time = date.getTime();
long timeLow = time & 0xffffffffL;
long timeMid = (time >>> 32) & 0xffffL;
// long timeHigh = (time >>> 48) & 0xffffL;
long uuidVersion = /*0xf &*/ 0;
long internalVersion = /*0xf &*/ 0;
long entityBin = 0xffL & (long)entity.getMask();
return (timeLow << 32) | (timeMid << 16) | (uuidVersion << 12) | (internalVersion << 8) | entityBin;
}
private static long getLeastSignificantBits() {
long installation = /*0xffL &*/ 0x1L;
// 12 hex digits random
Random rand = new Random();
long randomNumber = 0xffffffffffffL & rand.nextLong();
return (installation << 48) | randomNumber;
}
}
|
j-coll/opencga
|
opencga-catalog/src/main/java/org/opencb/opencga/catalog/utils/UuidUtils.java
|
Java
|
apache-2.0
| 3,545 |
<?php
/**
*
*/
class LocationModel
{
private $state;
public function setState($state) {
$this->state = $state;
}
public function getState() {
return $this->state;
}
}
|
prajyotpro/phpmvc
|
app/models/Location.php
|
PHP
|
apache-2.0
| 178 |
// Copyright 2000-2017 JetBrains s.r.o.
// Use of this source code is governed by the Apache 2.0 license that can be
// found in the LICENSE file.
package com.intellij.lang.java;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.completion.CompletionMemory;
import com.intellij.codeInsight.documentation.DocumentationManagerProtocol;
import com.intellij.codeInsight.documentation.PlatformDocumentationUtil;
import com.intellij.codeInsight.editorActions.CodeDocumentationUtil;
import com.intellij.codeInsight.javadoc.JavaDocExternalFilter;
import com.intellij.codeInsight.javadoc.JavaDocInfoGenerator;
import com.intellij.codeInsight.javadoc.JavaDocInfoGeneratorFactory;
import com.intellij.codeInsight.javadoc.JavaDocUtil;
import com.intellij.lang.CodeDocumentationAwareCommenter;
import com.intellij.lang.LangBundle;
import com.intellij.lang.LanguageCommenters;
import com.intellij.lang.documentation.CodeDocumentationProvider;
import com.intellij.lang.documentation.CompositeDocumentationProvider;
import com.intellij.lang.documentation.DocumentationProviderEx;
import com.intellij.lang.documentation.ExternalDocumentationProvider;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.JarFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileSystem;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiImplUtil;
import com.intellij.psi.impl.beanProperties.BeanPropertyElement;
import com.intellij.psi.impl.source.javadoc.PsiDocParamRef;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.javadoc.PsiDocTag;
import com.intellij.psi.util.PsiFormatUtil;
import com.intellij.psi.util.PsiFormatUtilBase;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.SmartList;
import com.intellij.util.Url;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.HashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.builtInWebServer.BuiltInWebBrowserUrlProviderKt;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author Maxim.Mossienko
*/
public class JavaDocumentationProvider extends DocumentationProviderEx implements CodeDocumentationProvider, ExternalDocumentationProvider {
private static final Logger LOG = Logger.getInstance(JavaDocumentationProvider.class);
private static final String LINE_SEPARATOR = "\n";
private static final String PARAM_TAG = "@param";
private static final String RETURN_TAG = "@return";
private static final String THROWS_TAG = "@throws";
public static final String HTML_EXTENSION = ".html";
public static final String PACKAGE_SUMMARY_FILE = "package-summary.html";
@Override
public String getQuickNavigateInfo(PsiElement element, PsiElement originalElement) {
if (element instanceof PsiClass) {
return generateClassInfo((PsiClass)element);
}
else if (element instanceof PsiMethod) {
return generateMethodInfo((PsiMethod)element, calcSubstitutor(originalElement));
}
else if (element instanceof PsiField) {
return generateFieldInfo((PsiField)element, calcSubstitutor(originalElement));
}
else if (element instanceof PsiVariable) {
return generateVariableInfo((PsiVariable)element);
}
else if (element instanceof PsiPackage) {
return generatePackageInfo((PsiPackage)element);
}
else if (element instanceof BeanPropertyElement) {
return generateMethodInfo(((BeanPropertyElement)element).getMethod(), PsiSubstitutor.EMPTY);
}
else if (element instanceof PsiJavaModule) {
return generateModuleInfo((PsiJavaModule)element);
}
return null;
}
private static PsiSubstitutor calcSubstitutor(PsiElement originalElement) {
PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
if (originalElement instanceof PsiReferenceExpression) {
LOG.assertTrue(originalElement.isValid());
substitutor = ((PsiReferenceExpression)originalElement).advancedResolve(true).getSubstitutor();
}
return substitutor;
}
@Override
public List<String> getUrlFor(final PsiElement element, final PsiElement originalElement) {
return getExternalJavaDocUrl(element);
}
private static void newLine(StringBuilder buffer) {
// Don't know why space has to be added after newline for good text alignment...
buffer.append("\n ");
}
private static void generateInitializer(StringBuilder buffer, PsiVariable variable) {
PsiExpression initializer = variable.getInitializer();
if (initializer != null) {
JavaDocInfoGenerator.appendExpressionValue(buffer, initializer, " = ");
PsiExpression constantInitializer = JavaDocInfoGenerator.calcInitializerExpression(variable);
if (constantInitializer != null) {
buffer.append("\n");
JavaDocInfoGenerator.appendExpressionValue(buffer, constantInitializer, CodeInsightBundle.message("javadoc.resolved.value"));
}
}
}
private static void generateModifiers(StringBuilder buffer, PsiModifierListOwner element) {
String modifiers = PsiFormatUtil.formatModifiers(element, PsiFormatUtilBase.JAVADOC_MODIFIERS_ONLY);
if (modifiers.length() > 0) {
buffer.append(modifiers);
buffer.append(" ");
}
}
private static String generatePackageInfo(PsiPackage aPackage) {
return aPackage.getQualifiedName();
}
private static void generateOrderEntryAndPackageInfo(StringBuilder buffer, @NotNull PsiElement element) {
PsiFile file = element.getContainingFile();
if (file != null) {
generateOrderEntryInfo(buffer, file.getVirtualFile(), element.getProject());
}
if (file instanceof PsiJavaFile) {
String packageName = ((PsiJavaFile)file).getPackageName();
if (packageName.length() > 0) {
buffer.append(packageName);
newLine(buffer);
}
}
}
private static void generateOrderEntryInfo(StringBuilder buffer, VirtualFile file, Project project) {
if (file != null) {
ProjectFileIndex index = ProjectRootManager.getInstance(project).getFileIndex();
if (index.isInLibrarySource(file) || index.isInLibraryClasses(file)) {
index.getOrderEntriesForFile(file).stream()
.filter(LibraryOrSdkOrderEntry.class::isInstance).findFirst()
.ifPresent(entry -> buffer.append('[').append(StringUtil.escapeXml(entry.getPresentableName())).append("] "));
}
else {
Module module = index.getModuleForFile(file);
if (module != null) {
buffer.append('[').append(module.getName()).append("] ");
}
}
}
}
@SuppressWarnings({"HardCodedStringLiteral"})
public static String generateClassInfo(PsiClass aClass) {
StringBuilder buffer = new StringBuilder();
if (aClass instanceof PsiAnonymousClass) return LangBundle.message("java.terms.anonymous.class");
generateOrderEntryAndPackageInfo(buffer, aClass);
generateModifiers(buffer, aClass);
final String classString = aClass.isAnnotationType() ? "java.terms.annotation.interface"
: aClass.isInterface()
? "java.terms.interface"
: aClass instanceof PsiTypeParameter
? "java.terms.type.parameter"
: aClass.isEnum() ? "java.terms.enum" : "java.terms.class";
buffer.append(LangBundle.message(classString)).append(" ");
buffer.append(JavaDocUtil.getShortestClassName(aClass, aClass));
generateTypeParameters(aClass, buffer);
if (!aClass.isEnum() && !aClass.isAnnotationType()) {
PsiReferenceList extendsList = aClass.getExtendsList();
writeExtends(aClass, buffer, extendsList == null ? PsiClassType.EMPTY_ARRAY : extendsList.getReferencedTypes());
}
writeImplements(aClass, buffer, aClass.getImplementsListTypes());
return buffer.toString();
}
public static void writeImplements(PsiClass aClass, StringBuilder buffer, PsiClassType[] refs) {
if (refs.length > 0) {
newLine(buffer);
buffer.append("implements ");
writeTypeRefs(aClass, buffer, refs);
}
}
public static void writeExtends(PsiClass aClass, StringBuilder buffer, PsiClassType[] refs) {
if (refs.length > 0 || !aClass.isInterface() && !CommonClassNames.JAVA_LANG_OBJECT.equals(aClass.getQualifiedName())) {
buffer.append(" extends ");
if (refs.length == 0) {
buffer.append("Object");
}
else {
writeTypeRefs(aClass, buffer, refs);
}
}
}
private static void writeTypeRefs(PsiClass aClass, StringBuilder buffer, PsiClassType[] refs) {
for (int i = 0; i < refs.length; i++) {
JavaDocInfoGenerator.generateType(buffer, refs[i], aClass, false, true);
if (i < refs.length - 1) {
buffer.append(", ");
}
}
}
public static void generateTypeParameters(PsiTypeParameterListOwner typeParameterOwner, StringBuilder buffer) {
if (typeParameterOwner.hasTypeParameters()) {
PsiTypeParameter[] params = typeParameterOwner.getTypeParameters();
buffer.append("<");
for (int i = 0; i < params.length; i++) {
PsiTypeParameter p = params[i];
buffer.append(p.getName());
PsiClassType[] refs = p.getExtendsList().getReferencedTypes();
if (refs.length > 0) {
buffer.append(" extends ");
for (int j = 0; j < refs.length; j++) {
JavaDocInfoGenerator.generateType(buffer, refs[j], typeParameterOwner, false, true);
if (j < refs.length - 1) {
buffer.append(" & ");
}
}
}
if (i < params.length - 1) {
buffer.append(", ");
}
}
buffer.append(">");
}
}
@SuppressWarnings({"HardCodedStringLiteral"})
public static String generateMethodInfo(PsiMethod method, PsiSubstitutor substitutor) {
StringBuilder buffer = new StringBuilder();
PsiClass parentClass = method.getContainingClass();
if (parentClass != null && !(parentClass instanceof PsiAnonymousClass)) {
if (method.isConstructor()) {
generateOrderEntryAndPackageInfo(buffer, parentClass);
}
buffer.append(JavaDocUtil.getShortestClassName(parentClass, method));
newLine(buffer);
}
generateModifiers(buffer, method);
generateTypeParameters(method, buffer);
if (method.getReturnType() != null) {
JavaDocInfoGenerator.generateType(buffer, substitutor.substitute(method.getReturnType()), method, false, true);
buffer.append(" ");
}
buffer.append(method.getName());
buffer.append("(");
PsiParameter[] params = method.getParameterList().getParameters();
for (int i = 0; i < params.length; i++) {
PsiParameter param = params[i];
JavaDocInfoGenerator.generateType(buffer, substitutor.substitute(param.getType()), method, false, true);
buffer.append(" ");
if (param.getName() != null) {
buffer.append(param.getName());
}
if (i < params.length - 1) {
buffer.append(", ");
}
}
buffer.append(")");
PsiClassType[] refs = method.getThrowsList().getReferencedTypes();
if (refs.length > 0) {
newLine(buffer);
buffer.append(" throws ");
for (int i = 0; i < refs.length; i++) {
PsiClass throwsClass = refs[i].resolve();
if (throwsClass != null) {
buffer.append(JavaDocUtil.getShortestClassName(throwsClass, method));
}
else {
buffer.append(refs[i].getPresentableText());
}
if (i < refs.length - 1) {
buffer.append(", ");
}
}
}
return buffer.toString();
}
private static String generateFieldInfo(PsiField field, PsiSubstitutor substitutor) {
StringBuilder buffer = new StringBuilder();
PsiClass parentClass = field.getContainingClass();
if (parentClass != null && !(parentClass instanceof PsiAnonymousClass)) {
buffer.append(JavaDocUtil.getShortestClassName(parentClass, field));
newLine(buffer);
}
generateModifiers(buffer, field);
JavaDocInfoGenerator.generateType(buffer, substitutor.substitute(field.getType()), field, false, true);
buffer.append(" ");
buffer.append(field.getName());
generateInitializer(buffer, field);
JavaDocInfoGenerator.enumConstantOrdinal(buffer, field, parentClass, "\n");
return buffer.toString();
}
private static String generateVariableInfo(PsiVariable variable) {
StringBuilder buffer = new StringBuilder();
generateModifiers(buffer, variable);
JavaDocInfoGenerator.generateType(buffer, variable.getType(), variable, false, true);
buffer.append(" ");
buffer.append(variable.getName());
generateInitializer(buffer, variable);
return buffer.toString();
}
private static String generateModuleInfo(PsiJavaModule module) {
StringBuilder sb = new StringBuilder();
VirtualFile file = PsiImplUtil.getModuleVirtualFile(module);
generateOrderEntryInfo(sb, file, module.getProject());
sb.append(LangBundle.message("java.terms.module")).append(' ').append(module.getName());
return sb.toString();
}
@Override
public PsiComment findExistingDocComment(final PsiComment comment) {
if (comment instanceof PsiDocComment) {
final PsiJavaDocumentedElement owner = ((PsiDocComment)comment).getOwner();
if (owner != null) {
return owner.getDocComment();
}
}
return null;
}
@Nullable
@Override
public Pair<PsiElement, PsiComment> parseContext(@NotNull PsiElement startPoint) {
PsiElement docCommentOwner = PsiTreeUtil.findFirstParent(startPoint, e -> {
if (e instanceof PsiDocCommentOwner && !(e instanceof PsiTypeParameter) && !(e instanceof PsiAnonymousClass)) {
return true;
}
return false;
});
if (docCommentOwner == null) return null;
PsiDocComment comment = ((PsiDocCommentOwner)docCommentOwner).getDocComment();
if (docCommentOwner instanceof PsiField) {
docCommentOwner = ((PsiField)docCommentOwner).getModifierList();
}
return Pair.create(docCommentOwner, comment);
}
@Override
public String generateDocumentationContentStub(PsiComment _comment) {
final PsiJavaDocumentedElement commentOwner = ((PsiDocComment)_comment).getOwner();
final Project project = _comment.getProject();
final StringBuilder builder = new StringBuilder();
final CodeDocumentationAwareCommenter commenter =
(CodeDocumentationAwareCommenter)LanguageCommenters.INSTANCE.forLanguage(_comment.getLanguage());
if (commentOwner instanceof PsiMethod) {
PsiMethod psiMethod = (PsiMethod)commentOwner;
generateParametersTakingDocFromSuperMethods(project, builder, commenter, psiMethod);
final PsiTypeParameterList typeParameterList = psiMethod.getTypeParameterList();
if (typeParameterList != null) {
createTypeParamsListComment(builder, project, commenter, typeParameterList);
}
if (psiMethod.getReturnType() != null && !PsiType.VOID.equals(psiMethod.getReturnType())) {
builder.append(CodeDocumentationUtil.createDocCommentLine(RETURN_TAG, _comment.getContainingFile(), commenter));
builder.append(LINE_SEPARATOR);
}
final PsiJavaCodeReferenceElement[] references = psiMethod.getThrowsList().getReferenceElements();
for (PsiJavaCodeReferenceElement reference : references) {
builder.append(CodeDocumentationUtil.createDocCommentLine(THROWS_TAG, _comment.getContainingFile(), commenter));
builder.append(reference.getText());
builder.append(LINE_SEPARATOR);
}
}
else if (commentOwner instanceof PsiClass) {
final PsiTypeParameterList typeParameterList = ((PsiClass)commentOwner).getTypeParameterList();
if (typeParameterList != null) {
createTypeParamsListComment(builder, project, commenter, typeParameterList);
}
}
return builder.length() > 0 ? builder.toString() : null;
}
public static void generateParametersTakingDocFromSuperMethods(Project project,
StringBuilder builder,
CodeDocumentationAwareCommenter commenter, PsiMethod psiMethod) {
final PsiParameter[] parameters = psiMethod.getParameterList().getParameters();
final Map<String, String> param2Description = new HashMap<>();
final PsiMethod[] superMethods = psiMethod.findSuperMethods();
for (PsiMethod superMethod : superMethods) {
final PsiDocComment comment = superMethod.getDocComment();
if (comment != null) {
final PsiDocTag[] params = comment.findTagsByName("param");
for (PsiDocTag param : params) {
final PsiElement[] dataElements = param.getDataElements();
if (dataElements != null) {
String paramName = null;
for (PsiElement dataElement : dataElements) {
if (dataElement instanceof PsiDocParamRef) {
//noinspection ConstantConditions
paramName = dataElement.getReference().getCanonicalText();
break;
}
}
if (paramName != null) {
param2Description.put(paramName, param.getText());
}
}
}
}
}
for (PsiParameter parameter : parameters) {
String description = param2Description.get(parameter.getName());
if (description != null) {
builder.append(CodeDocumentationUtil.createDocCommentLine("", psiMethod.getContainingFile(), commenter));
if (description.indexOf('\n') > -1) description = description.substring(0, description.lastIndexOf('\n'));
builder.append(description);
}
else {
builder.append(CodeDocumentationUtil.createDocCommentLine(PARAM_TAG, psiMethod.getContainingFile(), commenter));
builder.append(parameter.getName());
}
builder.append(LINE_SEPARATOR);
}
}
public static void createTypeParamsListComment(final StringBuilder buffer,
final Project project,
final CodeDocumentationAwareCommenter commenter,
final PsiTypeParameterList typeParameterList) {
final PsiTypeParameter[] typeParameters = typeParameterList.getTypeParameters();
for (PsiTypeParameter typeParameter : typeParameters) {
buffer.append(CodeDocumentationUtil.createDocCommentLine(PARAM_TAG, typeParameterList.getContainingFile(), commenter));
buffer.append("<").append(typeParameter.getName()).append(">");
buffer.append(LINE_SEPARATOR);
}
}
@Override
public String generateDoc(PsiElement element, PsiElement originalElement) {
// for new Class(<caret>) or methodCall(<caret>) proceed from method call or new expression
// same for new Cl<caret>ass() or method<caret>Call()
if (element instanceof PsiExpressionList ||
element instanceof PsiReferenceExpression && element.getParent() instanceof PsiMethodCallExpression) {
element = element.getParent();
originalElement = null;
}
if (element instanceof PsiMethodCallExpression) {
PsiMethod method = CompletionMemory.getChosenMethod((PsiMethodCallExpression)element);
if (method == null) return getMethodCandidateInfo((PsiMethodCallExpression)element);
else element = method;
}
// Try hard for documentation of incomplete new Class instantiation
PsiElement elt = originalElement != null && !(originalElement instanceof PsiPackage) ? PsiTreeUtil.prevLeaf(originalElement): element;
if (elt instanceof PsiErrorElement) elt = elt.getPrevSibling();
else if (elt != null && !(elt instanceof PsiNewExpression)) {
elt = elt.getParent();
}
if (elt instanceof PsiNewExpression) {
PsiClass targetClass = null;
if (element instanceof PsiJavaCodeReferenceElement) { // new Class<caret>
PsiElement resolve = ((PsiJavaCodeReferenceElement)element).resolve();
if (resolve instanceof PsiClass) targetClass = (PsiClass)resolve;
} else if (element instanceof PsiClass) { //Class in completion
targetClass = (PsiClass)element;
} else if (element instanceof PsiNewExpression) { // new Class(<caret>)
PsiJavaCodeReferenceElement reference = ((PsiNewExpression)element).getClassReference();
if (reference != null) {
PsiElement resolve = reference.resolve();
if (resolve instanceof PsiClass) targetClass = (PsiClass)resolve;
}
}
if (targetClass != null) {
PsiMethod[] constructors = targetClass.getConstructors();
if (constructors.length > 0) {
if (constructors.length == 1) return generateDoc(constructors[0], originalElement);
final StringBuilder sb = new StringBuilder();
for(PsiMethod constructor:constructors) {
final String str = PsiFormatUtil.formatMethod(constructor, PsiSubstitutor.EMPTY,
PsiFormatUtilBase.SHOW_NAME |
PsiFormatUtilBase.SHOW_TYPE |
PsiFormatUtilBase.SHOW_PARAMETERS,
PsiFormatUtilBase.SHOW_TYPE | PsiFormatUtilBase.SHOW_NAME);
createElementLink(sb, constructor, StringUtil.escapeXml(str));
}
return CodeInsightBundle.message("javadoc.constructor.candidates", targetClass.getName(), sb);
}
}
}
//external documentation finder
return generateExternalJavadoc(element);
}
@Override
public PsiElement getDocumentationElementForLookupItem(final PsiManager psiManager, final Object object, final PsiElement element) {
return null;
}
@Nullable
public static String generateExternalJavadoc(@NotNull final PsiElement element) {
List<String> docURLs = getExternalJavaDocUrl(element);
return generateExternalJavadoc(element, docURLs);
}
@Nullable
public static String generateExternalJavadoc(@NotNull final PsiElement element, @Nullable List<String> docURLs) {
final JavaDocInfoGenerator javaDocInfoGenerator = JavaDocInfoGeneratorFactory.create(element.getProject(), element);
return generateExternalJavadoc(javaDocInfoGenerator, docURLs);
}
@Nullable
public static String generateExternalJavadoc(@NotNull final PsiElement element, @NotNull JavaDocInfoGenerator generator) {
final List<String> docURLs = getExternalJavaDocUrl(element);
return generateExternalJavadoc(generator, docURLs);
}
@Nullable
private static String generateExternalJavadoc(@NotNull JavaDocInfoGenerator generator, @Nullable List<String> docURLs) {
return JavaDocExternalFilter.filterInternalDocInfo(generator.generateDocInfo(docURLs));
}
@Nullable
private static String fetchExternalJavadoc(final PsiElement element, String fromUrl, @NotNull JavaDocExternalFilter filter) {
try {
String externalDoc = filter.getExternalDocInfoForElement(fromUrl, element);
if (!StringUtil.isEmpty(externalDoc)) {
return externalDoc;
}
}
catch (ProcessCanceledException ignored) {}
catch (Exception e) {
LOG.warn(e);
}
return null;
}
private String getMethodCandidateInfo(PsiMethodCallExpression expr) {
final PsiResolveHelper rh = JavaPsiFacade.getInstance(expr.getProject()).getResolveHelper();
final CandidateInfo[] candidates = rh.getReferencedMethodCandidates(expr, true);
final String text = expr.getText();
if (candidates.length > 0) {
if (candidates.length == 1) {
PsiElement element = candidates[0].getElement();
if (element instanceof PsiMethod) return generateDoc(element, null);
}
final StringBuilder sb = new StringBuilder();
for (final CandidateInfo candidate : candidates) {
final PsiElement element = candidate.getElement();
if (!(element instanceof PsiMethod)) {
continue;
}
final String str = PsiFormatUtil.formatMethod((PsiMethod)element, candidate.getSubstitutor(),
PsiFormatUtilBase.SHOW_NAME |
PsiFormatUtilBase.SHOW_TYPE |
PsiFormatUtilBase.SHOW_PARAMETERS,
PsiFormatUtilBase.SHOW_TYPE);
createElementLink(sb, element, StringUtil.escapeXml(str));
}
return CodeInsightBundle.message("javadoc.candidates", text, sb);
}
return CodeInsightBundle.message("javadoc.candidates.not.found", text);
}
private static void createElementLink(StringBuilder sb, PsiElement element, String str) {
sb.append(" <a href=\"" + DocumentationManagerProtocol.PSI_ELEMENT_PROTOCOL);
sb.append(JavaDocUtil.getReferenceText(element.getProject(), element));
sb.append("\">");
sb.append(str);
sb.append("</a>");
sb.append("<br>");
}
@Nullable
public static List<String> getExternalJavaDocUrl(final PsiElement element) {
List<String> urls = null;
if (element instanceof PsiClass) {
urls = findUrlForClass((PsiClass)element);
}
else if (element instanceof PsiField) {
PsiField field = (PsiField)element;
PsiClass aClass = field.getContainingClass();
if (aClass != null) {
urls = findUrlForClass(aClass);
if (urls != null) {
for (int i = 0; i < urls.size(); i++) {
urls.set(i, urls.get(i) + "#" + field.getName());
}
}
}
}
else if (element instanceof PsiMethod) {
PsiMethod method = (PsiMethod)element;
PsiClass aClass = method.getContainingClass();
if (aClass != null) {
List<String> classUrls = findUrlForClass(aClass);
if (classUrls != null) {
urls = ContainerUtil.newSmartList();
final boolean useJava8Format = PsiUtil.isLanguageLevel8OrHigher(method);
final Set<String> signatures = getHtmlMethodSignatures(method, useJava8Format);
for (String signature : signatures) {
for (String classUrl : classUrls) {
urls.add(classUrl + "#" + signature);
}
}
}
}
}
else if (element instanceof PsiPackage) {
urls = findUrlForPackage((PsiPackage)element);
}
else if (element instanceof PsiDirectory) {
PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(((PsiDirectory)element));
if (aPackage != null) {
urls = findUrlForPackage(aPackage);
}
}
if (urls == null || urls.isEmpty()) {
return null;
}
else {
for (int i = 0; i < urls.size(); i++) {
urls.set(i, FileUtil.toSystemIndependentName(urls.get(i)));
}
return urls;
}
}
public static Set<String> getHtmlMethodSignatures(PsiMethod method, boolean java8FormatFirst) {
final Set<String> signatures = new LinkedHashSet<>();
signatures.add(formatMethodSignature(method, true, java8FormatFirst));
signatures.add(formatMethodSignature(method, false, java8FormatFirst));
signatures.add(formatMethodSignature(method, true, !java8FormatFirst));
signatures.add(formatMethodSignature(method, false, !java8FormatFirst));
return signatures;
}
private static String formatMethodSignature(PsiMethod method, boolean raw, boolean java8Format) {
int options = PsiFormatUtilBase.SHOW_NAME | PsiFormatUtilBase.SHOW_PARAMETERS;
int parameterOptions = PsiFormatUtilBase.SHOW_TYPE | PsiFormatUtilBase.SHOW_FQ_CLASS_NAMES;
if (raw) {
options |= PsiFormatUtilBase.SHOW_RAW_NON_TOP_TYPE;
parameterOptions |= PsiFormatUtilBase.SHOW_RAW_NON_TOP_TYPE;
}
String signature = PsiFormatUtil.formatMethod(method, PsiSubstitutor.EMPTY, options, parameterOptions, 999);
if (java8Format) {
signature = signature.replaceAll("\\(|\\)|, ", "-").replaceAll("\\[\\]", ":A");
}
return signature;
}
@Nullable
public static List<String> findUrlForClass(@NotNull PsiClass aClass) {
String qName = aClass.getQualifiedName();
if (qName == null) return null;
PsiFile file = aClass.getContainingFile();
if (!(file instanceof PsiJavaFile)) return null;
VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile == null) return null;
String packageName = ((PsiJavaFile)file).getPackageName();
String relPath;
if (packageName.isEmpty()) {
relPath = qName + HTML_EXTENSION;
}
else {
relPath = packageName.replace('.', '/') + '/' + qName.substring(packageName.length() + 1) + HTML_EXTENSION;
}
return findUrlForVirtualFile(file.getProject(), virtualFile, relPath);
}
@Nullable
public static List<String> findUrlForVirtualFile(@NotNull Project project, @NotNull VirtualFile virtualFile, @NotNull String relPath) {
final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
Module module = fileIndex.getModuleForFile(virtualFile);
if (module == null) {
final VirtualFileSystem fs = virtualFile.getFileSystem();
if (fs instanceof JarFileSystem) {
final VirtualFile jar = ((JarFileSystem)fs).getVirtualFileForJar(virtualFile);
if (jar != null) {
module = fileIndex.getModuleForFile(jar);
}
}
}
if (module != null) {
String[] javadocPaths = JavaModuleExternalPaths.getInstance(module).getJavadocUrls();
final List<String> httpRoots = PlatformDocumentationUtil.getHttpRoots(javadocPaths, relPath);
// if found nothing and the file is from library classes, fall back to order entries
if (httpRoots != null || !fileIndex.isInLibraryClasses(virtualFile)) {
return httpRoots;
}
}
for (OrderEntry orderEntry : fileIndex.getOrderEntriesForFile(virtualFile)) {
for (VirtualFile root : orderEntry.getFiles(JavadocOrderRootType.getInstance())) {
if (root.getFileSystem() == JarFileSystem.getInstance()) {
VirtualFile file = root.findFileByRelativePath(relPath);
List<Url> urls = file == null ? null : BuiltInWebBrowserUrlProviderKt.getBuiltInServerUrls(file, project, null);
if (!ContainerUtil.isEmpty(urls)) {
List<String> result = new SmartList<>();
for (Url url : urls) {
result.add(url.toExternalForm());
}
return result;
}
}
}
List<String> httpRoot = PlatformDocumentationUtil.getHttpRoots(JavadocOrderRootType.getUrls(orderEntry), relPath);
if (httpRoot != null) {
return httpRoot;
}
}
return null;
}
@Nullable
public static List<String> findUrlForPackage(PsiPackage aPackage) {
String qName = aPackage.getQualifiedName();
qName = qName.replace('.', '/') + '/' + PACKAGE_SUMMARY_FILE;
for (PsiDirectory directory : aPackage.getDirectories()) {
List<String> url = findUrlForVirtualFile(aPackage.getProject(), directory.getVirtualFile(), qName);
if (url != null) {
return url;
}
}
return null;
}
@Override
public PsiElement getDocumentationElementForLink(final PsiManager psiManager, final String link, final PsiElement context) {
return JavaDocUtil.findReferenceTarget(psiManager, link, context);
}
@Override
public String fetchExternalDocumentation(Project project, PsiElement element, List<String> docUrls) {
return fetchExternalJavadoc(element, project, docUrls);
}
@Override
public boolean hasDocumentationFor(PsiElement element, PsiElement originalElement) {
return CompositeDocumentationProvider.hasUrlsFor(this, element, originalElement);
}
@Override
public boolean canPromptToConfigureDocumentation(PsiElement element) {
return false;
}
@Override
public void promptToConfigureDocumentation(PsiElement element) {
}
@Nullable
@Override
public PsiElement getCustomDocumentationElement(@NotNull Editor editor, @NotNull PsiFile file, @Nullable PsiElement contextElement) {
PsiDocComment docComment = PsiTreeUtil.getParentOfType(contextElement, PsiDocComment.class, false);
if (docComment != null && JavaDocUtil.isInsidePackageInfo(docComment)) {
PsiDirectory directory = file.getContainingDirectory();
if (directory != null) {
return JavaDirectoryService.getInstance().getPackage(directory);
}
}
return null;
}
public static String fetchExternalJavadoc(PsiElement element, final Project project, final List<String> docURLs) {
return fetchExternalJavadoc(element, docURLs, new JavaDocExternalFilter(project));
}
public static String fetchExternalJavadoc(PsiElement element, List<String> docURLs, @NotNull JavaDocExternalFilter docFilter) {
if (docURLs != null) {
for (String docURL : docURLs) {
try {
final String javadoc = fetchExternalJavadoc(element, docURL, docFilter);
if (javadoc != null) return javadoc;
}
catch (IndexNotReadyException e) {
throw e;
}
catch (Exception e) {
LOG.info(e); //connection problems should be ignored
}
}
}
return null;
}
}
|
apixandru/intellij-community
|
java/java-impl/src/com/intellij/lang/java/JavaDocumentationProvider.java
|
Java
|
apache-2.0
| 34,288 |
<?php
/**
* Copyright (C) 2012 Vizualizer 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.
*
* @author Naohisa Minagawa <info@vizualizer.jp>
* @copyright Copyright (c) 2010, Vizualizer
* @license http://www.apache.org/licenses/LICENSE-2.0.html Apache License, Version 2.0
* @since PHP 5.3
* @version 1.0.0
*/
/**
* 決済のデータを削除する。
*
* @package VizualizerShop
* @author Naohisa Minagawa <info@vizualizer.jp>
*/
class VizualizerShop_Module_Payment_Delete extends Vizualizer_Plugin_Module_Delete
{
function execute($params)
{
$this->executeImpl("Shop", "Payment", "payment_id");
}
}
|
Vizualizer/VizualizerShop
|
classes/VizualizerShop/Module/Payment/Delete.php
|
PHP
|
apache-2.0
| 1,168 |
// @declaration: true
export module a {
export function foo(x: number) {
return x;
}
}
export module c {
export import b = a.foo;
export var bVal = b(10);
export var bVal2 = b;
}
|
mbrowne/typescript-dci
|
tests/cases/compiler/internalAliasFunctionInsideLocalModuleWithExport.ts
|
TypeScript
|
apache-2.0
| 220 |
// 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 "master/quota.hpp"
#include <string>
#include <mesos/mesos.hpp>
#include <mesos/quota/quota.hpp>
#include <mesos/resource_quantities.hpp>
#include <mesos/resources.hpp>
#include <mesos/roles.hpp>
#include <mesos/values.hpp>
#include <stout/error.hpp>
#include <stout/option.hpp>
#include <stout/set.hpp>
#include "common/resources_utils.hpp"
#include "common/validation.hpp"
using google::protobuf::Map;
using google::protobuf::RepeatedPtrField;
using mesos::quota::QuotaConfig;
using mesos::quota::QuotaInfo;
using mesos::quota::QuotaRequest;
using std::string;
namespace mesos {
namespace internal {
namespace master {
namespace quota {
UpdateQuota::UpdateQuota(const QuotaInfo& quotaInfo)
: info(quotaInfo) {}
Try<bool> UpdateQuota::perform(
Registry* registry,
hashset<SlaveID>* /*slaveIDs*/)
{
// If there is already quota stored for the role, update the entry.
foreach (Registry::Quota& quota, *registry->mutable_quotas()) {
if (quota.info().role() == info.role()) {
quota.mutable_info()->CopyFrom(info);
return true; // Mutation.
}
}
// If there is no quota yet for the role, create a new entry.
registry->add_quotas()->mutable_info()->CopyFrom(info);
return true; // Mutation.
}
RemoveQuota::RemoveQuota(const string& _role) : role(_role) {}
Try<bool> RemoveQuota::perform(
Registry* registry,
hashset<SlaveID>* /*slaveIDs*/)
{
// Remove quota for the role if a corresponding entry exists.
for (int i = 0; i < registry->quotas().size(); ++i) {
const Registry::Quota& quota = registry->quotas(i);
if (quota.info().role() == role) {
registry->mutable_quotas()->DeleteSubrange(i, 1);
// NOTE: Multiple entries per role are not allowed.
return true; // Mutation.
}
}
return false;
}
namespace {
QuotaInfo createQuotaInfo(
const string& role,
const RepeatedPtrField<Resource>& guarantee)
{
QuotaInfo quota;
quota.set_role(role);
quota.mutable_guarantee()->CopyFrom(guarantee);
return quota;
}
} // namespace {
QuotaInfo createQuotaInfo(const QuotaRequest& request)
{
return createQuotaInfo(request.role(), request.guarantee());
}
namespace validation {
Option<Error> quotaInfo(const QuotaInfo& quotaInfo)
{
if (!quotaInfo.has_role()) {
return Error("QuotaInfo must specify a role");
}
// Check the provided role is valid.
Option<Error> roleError = roles::validate(quotaInfo.role());
if (roleError.isSome()) {
return Error("QuotaInfo with invalid role: " + roleError->message);
}
// Disallow quota for '*' role.
// TODO(alexr): Consider allowing setting quota for '*' role, see MESOS-3938.
if (quotaInfo.role() == "*") {
return Error("QuotaInfo must not specify the default '*' role");
}
// Check that `QuotaInfo` contains at least one guarantee.
// TODO(alexr): Relaxing this may make sense once quota is the
// only way that we offer non-revocable resources. Setting quota
// with an empty guarantee would mean the role is not entitled to
// get non-revocable offers.
if (quotaInfo.guarantee().empty()) {
return Error("QuotaInfo with empty 'guarantee'");
}
hashset<string> names;
foreach (const Resource& resource, quotaInfo.guarantee()) {
// Check that `resource` does not contain fields that are
// irrelevant for quota.
if (resource.reservations_size() > 0) {
return Error("QuotaInfo must not contain any ReservationInfo");
}
if (resource.has_disk()) {
return Error("QuotaInfo must not contain DiskInfo");
}
if (resource.has_revocable()) {
return Error("QuotaInfo must not contain RevocableInfo");
}
if (resource.type() != Value::SCALAR) {
return Error("QuotaInfo must not include non-scalar resources");
}
// Check that resource names do not repeat.
if (names.contains(resource.name())) {
return Error("QuotaInfo contains duplicate resource name"
" '" + resource.name() + "'");
}
names.insert(resource.name());
}
return None();
}
} // namespace validation {
Option<Error> validate(const QuotaConfig& config)
{
if (!config.has_role()) {
return Error("'QuotaConfig.role' must be set");
}
// Check the provided role is valid.
Option<Error> error = roles::validate(config.role());
if (error.isSome()) {
return Error("Invalid 'QuotaConfig.role': " + error->message);
}
// Disallow quota for '*' role.
if (config.role() == "*") {
return Error(
"Invalid 'QuotaConfig.role': setting quota for the"
" default '*' role is not supported");
}
// Validate scalar values.
foreach (auto&& guarantee, config.guarantees()) {
Option<Error> error =
common::validation::validateInputScalarValue(guarantee.second.value());
if (error.isSome()) {
return Error(
"Invalid guarantee configuration {'" + guarantee.first + "': " +
stringify(guarantee.second) + "}: " + error->message);
}
}
foreach (auto&& limit, config.limits()) {
Option<Error> error =
common::validation::validateInputScalarValue(limit.second.value());
if (error.isSome()) {
return Error(
"Invalid limit configuration {'" + limit.first + "': " +
stringify(limit.second) + "}: " + error->message);
}
}
// Validate guarantees <= limits.
ResourceLimits limits{config.limits()};
ResourceQuantities guarantees{config.guarantees()};
if (!limits.contains(guarantees)) {
return Error(
"'QuotaConfig.guarantees' " + stringify(config.guarantees()) +
" is not contained within the 'QuotaConfig.limits' " +
stringify(config.limits()));
}
return None();
}
} // namespace quota {
} // namespace master {
} // namespace internal {
Quota2::Quota2(const QuotaConfig& config)
{
guarantees = ResourceQuantities(config.guarantees());
limits = ResourceLimits(config.limits());
}
Quota2::Quota2(const QuotaInfo& info)
{
guarantees = ResourceQuantities::fromScalarResources(info.guarantee());
// For legacy `QuotaInfo`, guarantee also acts as limit.
limits = [&info]() {
google::protobuf::Map<string, Value::Scalar> limits;
foreach (const Resource& r, info.guarantee()) {
limits[r.name()] = r.scalar();
}
return ResourceLimits(limits);
}();
}
Quota2::Quota2(const QuotaRequest& request)
{
guarantees = ResourceQuantities::fromScalarResources(request.guarantee());
// For legacy `QuotaInfo`, guarantee also acts as limit.
limits = [&request]() {
google::protobuf::Map<string, Value::Scalar> limits;
foreach (const Resource& r, request.guarantee()) {
limits[r.name()] = r.scalar();
}
return ResourceLimits(limits);
}();
}
bool Quota2::operator==(const Quota2& that) const
{
return guarantees == that.guarantees && limits == that.limits;
}
bool Quota2::operator!=(const Quota2& that) const
{
return guarantees != that.guarantees || limits != that.limits;
}
} // namespace mesos {
|
gsantovena/mesos
|
src/master/quota.cpp
|
C++
|
apache-2.0
| 7,795 |
/*
* Copyright (C) 2004 Felipe Gustavo de Almeida
* Copyright (C) 2010-2016 The MPDroid Project
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice,this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY 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.
*/
package com.anpmech.mpd.item;
/**
* This Interface represents a filesystem entry ({@link Directory}, {@link Entry}, {@link Music} or
* {@link PlaylistFile}) for a MPD protocol item.
*/
public interface FilesystemTreeEntry {
/**
* The full path as given by the MPD protocol.
*
* @return The full path for this entry.
*/
String getFullPath();
/**
* This method returns the last modified time for this entry in Unix time.
*
* <p>The Last-Modified response value is expected to be given in ISO8601.</p>
*
* @return The last modified time for this entry in Unix time.
*/
long getLastModified();
/**
* This returns the size a MPD entry file.
*
* <p><b>This is only available with some MPD command responses.</b></p>
*
* @return The size of a MPD entry file, {@link Integer#MIN_VALUE} if it doesn't exist in this
* response.
*/
long size();
}
|
hurzl/dmix
|
JMPDComm/src/main/java/com/anpmech/mpd/item/FilesystemTreeEntry.java
|
Java
|
apache-2.0
| 2,365 |
$(function() {
// $('.collapse').collapse('hide');
$('.list-group-item.active').parent().parent('.collapse').collapse('show');
$.ajaxSetup({cache: true});
var fuzzyhound = new FuzzySearch();
function setsource(url, keys) {
$.getJSON(url).then(function (response) {
fuzzyhound.setOptions({
source: response,
keys: keys
})
});
}
setsource(baseurl + '/search.json', ["title"]);
$('#search-box').typeahead({
minLength: 0,
highlight: true
}, {
name: 'pages',
display: 'title',
source: fuzzyhound
});
$('#search-box').bind('typeahead:select', function(ev, suggestion) {
window.location.href = suggestion.url;
});
// Markdown plain out to bootstrap style
$('#markdown-content-container table').addClass('table');
$('#markdown-content-container img').addClass('img-responsive');
});
|
hschroedl/FluentAST
|
docs/js/main.js
|
JavaScript
|
apache-2.0
| 966 |
package com.github.seanroy.plugins;
/**
* A Maven plugin allowing a jar built as a part of a Maven project to be
* deployed to AWS lambda.
* @author Sean N. Roy
*/
import java.io.File;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.lambda.AWSLambdaClient;
import com.amazonaws.services.lambda.model.CreateFunctionRequest;
import com.amazonaws.services.lambda.model.CreateFunctionResult;
import com.amazonaws.services.lambda.model.DeleteFunctionRequest;
import com.amazonaws.services.lambda.model.FunctionCode;
import com.amazonaws.services.lambda.model.Runtime;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.Bucket;
@Mojo(name = "deploy-lambda")
public class LambduhMojo extends AbstractMojo {
final Logger logger = LoggerFactory.getLogger(LambduhMojo.class);
@Parameter(property = "accessKey", defaultValue = "${accessKey}")
private String accessKey;
@Parameter(property = "secretKey", defaultValue = "${secretKey}")
private String secretKey;
@Parameter(required = true, defaultValue = "${functionCode}")
private String functionCode;
@Parameter(alias = "region", property = "region", defaultValue = "us-east-1")
private String regionName;
@Parameter(property = "s3Bucket", defaultValue = "lambda-function-code")
private String s3Bucket;
@Parameter(property = "description", defaultValue = "")
private String description;
@Parameter(required = true, defaultValue = "${lambdaRoleArn}")
private String lambdaRoleArn;
@Parameter(property = "functionName", defaultValue = "${functionName}")
private String functionName;
@Parameter(required = true, defaultValue = "${handler}")
private String handler;
@Parameter(property = "runtime", defaultValue = "Java8")
private Runtime runtime;
/**
* Lambda function execution timeout. Defaults to maximum allowed.
*/
@Parameter(property = "timeout", defaultValue = "60")
private int timeout;
@Parameter(property = "memorySize", defaultValue = "128")
private int memorySize;
private String fileName;
private Region region;
private AWSCredentials credentials;
private AmazonS3Client s3Client;
private AWSLambdaClient lambdaClient;
/**
* The entry point into the AWS lambda function.
*/
public void execute() throws MojoExecutionException {
if (accessKey != null && secretKey != null) {
credentials = new BasicAWSCredentials(accessKey, secretKey);
s3Client = new AmazonS3Client(credentials);
lambdaClient = new AWSLambdaClient(credentials);
} else {
s3Client = new AmazonS3Client();
lambdaClient = new AWSLambdaClient();
}
region = Region.getRegion(Regions.fromName(regionName));
lambdaClient.setRegion(region);
String pattern = Pattern.quote(File.separator);
String[] pieces = functionCode.split(pattern);
fileName = pieces[pieces.length - 1];
try {
uploadJarToS3();
deployLambdaFunction();
} catch (Exception e) {
logger.error(e.getMessage());
logger.trace(e.getMessage(), e);
throw new MojoExecutionException(e.getMessage());
}
}
/**
* Makes a create function call on behalf of the caller, deploying the
* function code to AWS lambda.
*
* @return A CreateFunctionResult indicating the success or failure of the
* request.
*/
private CreateFunctionResult createFunction() {
CreateFunctionRequest createFunctionRequest = new CreateFunctionRequest();
createFunctionRequest.setDescription(description);
createFunctionRequest.setRole(lambdaRoleArn);
createFunctionRequest.setFunctionName(functionName);
createFunctionRequest.setHandler(handler);
createFunctionRequest.setRuntime(runtime);
createFunctionRequest.setTimeout(timeout);
createFunctionRequest.setMemorySize(memorySize);
FunctionCode functionCode = new FunctionCode();
functionCode.setS3Bucket(s3Bucket);
functionCode.setS3Key(fileName);
createFunctionRequest.setCode(functionCode);
return lambdaClient.createFunction(createFunctionRequest);
}
/**
* Attempts to delete an existing function of the same name then deploys the
* function code to AWS Lambda. TODO: Attempt to do an update with
* versioning if the function already TODO: exists.
*/
private void deployLambdaFunction() {
// Attempt to delete it first
try {
DeleteFunctionRequest deleteRequest = new DeleteFunctionRequest();
// Why the hell didn't they make this a static method?
deleteRequest = deleteRequest.withFunctionName(functionName);
lambdaClient.deleteFunction(deleteRequest);
} catch (Exception ignored) {
// function didn't exist in the first place.
}
CreateFunctionResult result = createFunction();
logger.info("Function deployed: " + result.getFunctionArn());
}
/**
* The Lambda function will be deployed from AWS S3. This method uploads the
* function code to S3 in preparation of deployment.
*
* @throws Exception
*/
private void uploadJarToS3() throws Exception {
Bucket bucket = getBucket();
if (bucket != null) {
File file = new File(functionCode);
logger.info("Uploading " + functionCode + " to AWS S3 bucket "
+ s3Bucket);
s3Client.putObject(s3Bucket, fileName, file);
logger.info("Upload complete");
} else {
logger.error("Failed to create bucket " + s3Bucket
+ ". try running maven with -X to get full "
+ "debug output");
}
}
/**
* Attempts to return an existing bucket named <code>s3Bucket</code> if it
* exists. If it does not exist, it attempts to create it.
*
* @return An AWS S3 bucket with name <code>s3Bucket</code>
*/
private Bucket getBucket() {
Bucket bucket = getExistingBucket();
if (bucket != null) {
return bucket;
}
try {
bucket = s3Client.createBucket(s3Bucket,
com.amazonaws.services.s3.model.Region.US_Standard);
logger.info("Created bucket " + s3Bucket);
} catch (AmazonServiceException ase) {
logger.error(ase.getMessage());
} catch (AmazonClientException ace) {
logger.error(ace.getMessage());
}
return bucket;
}
private Bucket getExistingBucket() {
List<Bucket> buckets = s3Client.listBuckets();
for (Bucket bucket : buckets) {
if (bucket.getName().equals(s3Bucket)) {
return bucket;
}
}
return null;
}
}
|
buri17/lambduh-maven-plugin
|
src/main/java/com/github/seanroy/plugins/LambduhMojo.java
|
Java
|
apache-2.0
| 7,545 |
using System;
using ChartDirector;
namespace CSharpChartExplorer
{
public class rotatedarea : DemoModule
{
//Name of demo module
public string getName() { return "Rotated Area Chart"; }
//Number of charts produced in this demo module
public int getNoOfCharts() { return 1; }
//Main code for creating chart.
//Note: the argument chartIndex is unused because this demo only has 1 chart.
public void createChart(WinChartViewer viewer, int chartIndex)
{
// The data for the area chart
double[] data = {30, 28, 40, 55, 75, 68, 54, 60, 50, 62, 75, 65, 75, 89, 60, 55, 53, 35,
50, 66, 56, 48, 52, 65, 62};
// The labels for the area chart
double[] labels = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24};
// Create a XYChart object of size 320 x 320 pixels
XYChart c = new XYChart(320, 320);
// Swap the x and y axis to become a rotated chart
c.swapXY();
// Set the y axis on the top side (right + rotated = top)
c.setYAxisOnRight();
// Reverse the x axis so it is pointing downwards
c.xAxis().setReverse();
// Set the plotarea at (50, 50) and of size 200 x 200 pixels. Enable horizontal and
// vertical grids by setting their colors to grey (0xc0c0c0).
c.setPlotArea(50, 50, 250, 250).setGridColor(0xc0c0c0, 0xc0c0c0);
// Add a line chart layer using the given data
c.addAreaLayer(data, c.gradientColor(50, 0, 300, 0, 0xffffff, 0x0000ff));
// Set the labels on the x axis. Append "m" after the value to show the unit.
c.xAxis().setLabels2(labels, "{value} m");
// Display 1 out of 3 labels.
c.xAxis().setLabelStep(3);
// Add a title to the x axis
c.xAxis().setTitle("Depth");
// Add a title to the y axis
c.yAxis().setTitle("Carbon Dioxide Concentration (ppm)");
// Output the chart
viewer.Chart = c;
//include tool tip for the chart
viewer.ImageMap = c.getHTMLImageMap("clickable", "",
"title='Carbon dioxide concentration at {xLabel}: {value} ppm'");
}
}
}
|
jojogreen/Orbital-Mechanix-Suite
|
NetWinCharts/CSharpWinCharts/rotatedarea.cs
|
C#
|
apache-2.0
| 2,394 |
package com.quark.admin.service.impl;
import com.quark.admin.service.PostsService;
import com.quark.common.base.BaseServiceImpl;
import com.quark.common.dao.PostsDao;
import com.quark.common.entity.Posts;
import com.quark.common.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @Author LHR
* Create By 2017/9/3
*/
@Service
public class PostsServiceImpl extends BaseServiceImpl<PostsDao,Posts> implements PostsService {
@Override
public Page<Posts> findByPage(Posts posts, int pageNo, int length) {
PageRequest pageable = new PageRequest(pageNo, length);
Sort.Order order = new Sort.Order(Sort.Direction.ASC, "id");
Sort sort = new Sort(order);
Specification<Posts> specification = new Specification<Posts>() {
@Override
public Predicate toPredicate(Root<Posts> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
Path<Integer> $id = root.get("id");
Path<String> $title = root.get("title");
Path<User> $user = root.get("user");
Path<Boolean> $top = root.get("top");
Path<Boolean> $good = root.get("good");
ArrayList<Predicate> list = new ArrayList<>();
if (posts.getId()!=null) list.add(criteriaBuilder.equal($id,posts.getId()));
if (posts.getTitle()!=null) list.add(criteriaBuilder.like($title,"%" + posts.getTitle() + "%"));
if (posts.getUser()!=null) list.add(criteriaBuilder.equal($user,posts.getUser()));
if (posts.getTop()==true) list.add(criteriaBuilder.equal($top,true));
if (posts.getGood()==true) list.add(criteriaBuilder.equal($good,true));
Predicate predicate = criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
return predicate;
}
};
Page<Posts> page = repository.findAll(specification, pageable);
return page;
}
@Override
public void changeTop(Integer[] ids) {
List<Posts> all = findAll(Arrays.asList(ids));
for (Posts p :all) {
if (p.getTop()==false) p.setTop(true);
else p.setTop(false);
}
save(all);
}
@Override
public void changeGood(Integer[] ids) {
List<Posts> all = findAll(Arrays.asList(ids));
for (Posts p :all) {
if (p.getGood()==false) p.setGood(true);
else p.setGood(false);
}
save(all);
}
}
|
ChinaLHR/JavaQuarkBBS
|
quark-admin/src/main/java/com/quark/admin/service/impl/PostsServiceImpl.java
|
Java
|
apache-2.0
| 2,846 |
/**
* 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.
*/
export default () => {
describe('SqlLab query tabs', () => {
beforeEach(() => {
cy.login();
cy.server();
cy.visit('/superset/sqllab');
});
it('allows you to create a tab', () => {
cy.get('#a11y-query-editor-tabs > ul > li').then((tabList) => {
const initialTabCount = tabList.length;
// add tab
cy.get('#a11y-query-editor-tabs > ul > li')
.last()
.click();
cy.get('#a11y-query-editor-tabs > ul > li').should('have.length', initialTabCount + 1);
});
});
it('allows you to close a tab', () => {
cy.get('#a11y-query-editor-tabs > ul > li').then((tabListA) => {
const initialTabCount = tabListA.length;
// open the tab dropdown to remove
cy.get('#a11y-query-editor-tabs > ul > li:first button:nth-child(2)').click();
// first item is close
cy.get('#a11y-query-editor-tabs > ul > li:first ul li a')
.eq(0)
.click();
cy.get('#a11y-query-editor-tabs > ul > li').should('have.length', initialTabCount - 1);
});
});
});
};
|
zhouyao1994/incubator-superset
|
superset/assets/cypress/integration/sqllab/tabs.js
|
JavaScript
|
apache-2.0
| 1,920 |
<?php
function GetDBHandle($machine, $username, $password, $db_name) {
$con = mysqli_connect($machine, $username, $password, $db_name);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_errno();
$_SESSION['ErrMsg'] = 'Server Error'; // put up a server error page.
return;
}
return $con;
}
class BaseModel {
protected $con;
public function __construct($handle) {
$this->con = $handle;
}
}
class UserModel extends BaseModel {
public function GetUserByEmpIdAndPass($empId, $pass) {
$query = 'SELECT * FROM employee where empId = ' . $empId . ' and ' .
'password = MD5("' . $pass . '")';
return mysqli_query ($this->con, $query);
}
}
class LeavesModel extends BaseModel {
public function GetLeavesForEmpId($empid) {
$query = 'Select * from leaves where empId = ' . $empid;
return mysqli_query($this->con, $query);
}
public function GetLeavesCountByEmdId($empid) {
$query = 'Select * from lcount where empId = ' . $empid;
return mysqli_query($this->con, $query);
}
public function SubmitLeaves($empid, $start_date, $end_date, $type,
$reason) {
mysqli_query($this->con, 'start transaction');
$query = ('Insert into leaves (empId, startDate, endDate, type, reason) ' .
'values (' . $empid . ', "' . $start_date .'", "' . $end_date . '", ' .
'"' . $type . '", "' . $reason . '")');
$result = mysqli_query($this->con, $query);
$new_result = false;
if ($result) {
$new_q = 'update lcount set remaining = remaining - datediff("'
. $end_date . '", "' . $start_date . '") - 1 where ' .
'lcount.empId=' . $empid;
$new_result = mysqli_query($this->con, $new_q);
}
if ($result and $new_result) {
mysqli_query($this->con, 'commit');
} else {
mysqli_query($this->con, 'rollback');
}
return $result and $new_result;
}
public function GetPendingLeavesOfSubordinates($empid) {
// Change query to accomodate juniors.
$query = 'select ID, employee.empId, fName, lName, startDate, endDate, ' .
'status, reason, type from ' .
'employee join leaves where employee.empId !=' . $empid . ' and ' .
'employee.empId=leaves.empId and status="Pending"';
return mysqli_query($this->con, $query);
}
public function ApproveLeaves($decision_map) {
$ids = implode(',', array_keys($decision_map));
$query = 'select * from leaves where ID in (' . $ids . ')';
$old_data = mysqli_query($this->con, $query);
mysqli_query($this->con, 'start transaction');
$query = 'update leaves set status = case ID';
foreach ($decision_map as $key => $value) {
$query .= ' when ' . $key . ' then "' . $value .'"';
}
$query .= ' end where ID in (' . $ids . ')';
$result = mysqli_query($this->con, $query);
$new_result = false;
if ($result) {
$new_dm = array();
while ($row = mysqli_fetch_array($old_data)) {
if (!isset($new_dm[$row['ID']])) {
$new_dm += array($row['empId'] => 0);
}
if (isset($decision_map[(string)$row['ID']]) and $decision_map[
(string)$row['ID']] === 'Rejected') {
$new_dm[$row['empId']] += round(
(strtotime($row['endDate']) - strtotime(
$row['startDate'])) / 86400) + 1;
}
}
$new_q = 'update lcount set remaining = case empId';
foreach ($new_dm as $k => $v) {
$new_q .= ' when ' . $k . ' then remaining + ' . $v;
}
$new_q .= ' end where empId in (' . implode(',', array_keys(
$new_dm)) . ')';
$new_result = mysqli_query($this->con, $new_q);
}
if ($result and $new_result) {
mysqli_query($this->con, 'commit');
} else {
mysqli_query($this->con, 'rollback');
}
return $result and $new_result;
}
}
?>
|
parthabb/se
|
model/model.php
|
PHP
|
apache-2.0
| 4,147 |
(function() {
'use strict';
angular
.module('bamUiAngular')
.service('webDevTec', webDevTec);
/** @ngInject */
function webDevTec() {
var data = [
{
'title': 'AngularJS',
'url': 'https://angularjs.org/',
'description': 'HTML enhanced for web apps!',
'logo': 'angular.png'
},
{
'title': 'BrowserSync',
'url': 'http://browsersync.io/',
'description': 'Time-saving synchronised browser testing.',
'logo': 'browsersync.png'
},
{
'title': 'GulpJS',
'url': 'http://gulpjs.com/',
'description': 'The streaming build system.',
'logo': 'gulp.png'
},
{
'title': 'Jasmine',
'url': 'http://jasmine.github.io/',
'description': 'Behavior-Driven JavaScript.',
'logo': 'jasmine.png'
},
{
'title': 'Karma',
'url': 'http://karma-runner.github.io/',
'description': 'Spectacular Test Runner for JavaScript.',
'logo': 'karma.png'
},
{
'title': 'Protractor',
'url': 'https://github.com/angular/protractor',
'description': 'End to end test framework for AngularJS applications built on top of WebDriverJS.',
'logo': 'protractor.png'
},
{
'title': 'Bootstrap',
'url': 'http://getbootstrap.com/',
'description': 'Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile first projects on the web.',
'logo': 'bootstrap.png'
},
{
'title': 'Angular UI Bootstrap',
'url': 'http://angular-ui.github.io/bootstrap/',
'description': 'Bootstrap components written in pure AngularJS by the AngularUI Team.',
'logo': 'ui-bootstrap.png'
},
{
'title': 'Sass (Node)',
'url': 'https://github.com/sass/node-sass',
'description': 'Node.js binding to libsass, the C version of the popular stylesheet preprocessor, Sass.',
'logo': 'node-sass.png'
},
{
'key': 'jade',
'title': 'Jade',
'url': 'http://jade-lang.com/',
'description': 'Jade is a high performance template engine heavily influenced by Haml and implemented with JavaScript for node.',
'logo': 'jade.png'
}
];
this.getTec = getTec;
function getTec() {
return data;
}
}
})();
|
sandor-nemeth/bam
|
bam-ui-angular/src/app/components/webDevTec/webDevTec.service.js
|
JavaScript
|
apache-2.0
| 2,427 |
using System.Web.Http;
namespace IISApp.Controllers
{
public class SimpleController : ApiController
{
public string Get() {
return "In controller";
}
}
}
|
Bigsby/PoC
|
Web/Owin/IISApp/IISApp/Controllers/SimpleController.cs
|
C#
|
apache-2.0
| 198 |
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.internal.classpath;
import org.gradle.api.Transformer;
import org.gradle.cache.CacheBuilder;
import org.gradle.cache.CacheRepository;
import org.gradle.cache.FileLockManager;
import org.gradle.cache.PersistentCache;
import org.gradle.internal.Factories;
import org.gradle.internal.Factory;
import org.gradle.internal.UncheckedException;
import org.gradle.internal.file.JarCache;
import org.gradle.util.CollectionUtils;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import static org.gradle.cache.internal.filelock.LockOptionsBuilder.mode;
public class DefaultCachedClasspathTransformer implements CachedClasspathTransformer, Closeable {
private final PersistentCache cache;
private final Transformer<File, File> jarFileTransformer;
public DefaultCachedClasspathTransformer(CacheRepository cacheRepository, JarCache jarCache, List<CachedJarFileStore> fileStores) {
this.cache = cacheRepository
.cache("jars-3")
.withDisplayName("jars")
.withCrossVersionCache(CacheBuilder.LockTarget.DefaultTarget)
.withLockOptions(mode(FileLockManager.LockMode.None))
.open();
this.jarFileTransformer = new CachedJarFileTransformer(jarCache, cache, fileStores);
}
@Override
public ClassPath transform(ClassPath classPath) {
return DefaultClassPath.of(CollectionUtils.collect(classPath.getAsFiles(), jarFileTransformer));
}
@Override
public Collection<URL> transform(Collection<URL> urls) {
return CollectionUtils.collect(urls, new Transformer<URL, URL>() {
@Override
public URL transform(URL url) {
if (url.getProtocol().equals("file")) {
try {
return jarFileTransformer.transform(new File(url.toURI())).toURI().toURL();
} catch (URISyntaxException e) {
throw UncheckedException.throwAsUncheckedException(e);
} catch (MalformedURLException e) {
throw UncheckedException.throwAsUncheckedException(e);
}
} else {
return url;
}
}
});
}
@Override
public void close() throws IOException {
cache.close();
}
private static class CachedJarFileTransformer implements Transformer<File, File> {
private final JarCache jarCache;
private final PersistentCache cache;
private final List<String> prefixes;
CachedJarFileTransformer(JarCache jarCache, PersistentCache cache, List<CachedJarFileStore> fileStores) {
this.jarCache = jarCache;
this.cache = cache;
prefixes = new ArrayList<String>(fileStores.size() + 1);
prefixes.add(cache.getBaseDir().getAbsolutePath() + File.separator);
for (CachedJarFileStore fileStore : fileStores) {
for (File rootDir : fileStore.getFileStoreRoots()) {
prefixes.add(rootDir.getAbsolutePath() + File.separator);
}
}
}
@Override
public File transform(final File original) {
if (shouldUseFromCache(original)) {
return cache.useCache(new Factory<File>() {
public File create() {
return jarCache.getCachedJar(original, Factories.constant(cache.getBaseDir()));
}
});
} else {
return original;
}
}
private boolean shouldUseFromCache(File original) {
if (!original.isFile()) {
return false;
}
for (String prefix : prefixes) {
if (original.getAbsolutePath().startsWith(prefix)) {
return false;
}
}
return true;
}
}
}
|
gstevey/gradle
|
subprojects/core/src/main/java/org/gradle/internal/classpath/DefaultCachedClasspathTransformer.java
|
Java
|
apache-2.0
| 4,767 |
/**
* Copyright 2015 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {internalListenImplementation} from './event-helper-listen';
import {user} from './log';
/** @const {string} */
const LOAD_FAILURE_PREFIX = 'Failed to load:';
/**
* Returns a CustomEvent with a given type and detail; supports fallback for IE.
* @param {!Window} win
* @param {string} type
* @param {Object} detail
* @return {!Event}
*/
export function createCustomEvent(win, type, detail) {
if (win.CustomEvent) {
return new win.CustomEvent(type, {detail});
} else {
// Deprecated fallback for IE.
const e = win.document.createEvent('CustomEvent');
e.initCustomEvent(
type, /* canBubble */ false, /* cancelable */ false, detail);
return e;
}
}
/**
* Listens for the specified event on the element.
* @param {!EventTarget} element
* @param {string} eventType
* @param {function(!Event)} listener
* @param {boolean=} opt_capture
* @return {!UnlistenDef}
*/
export function listen(element, eventType, listener, opt_capture) {
return internalListenImplementation(
element, eventType, listener, opt_capture);
}
/**
* Listens for the specified event on the element and removes the listener
* as soon as event has been received.
* @param {!EventTarget} element
* @param {string} eventType
* @param {function(!Event)} listener
* @param {boolean=} opt_capture
* @return {!UnlistenDef}
*/
export function listenOnce(element, eventType, listener, opt_capture) {
let localListener = listener;
const unlisten = internalListenImplementation(element, eventType, event => {
try {
localListener(event);
} finally {
// Ensure listener is GC'd
localListener = null;
unlisten();
}
}, opt_capture);
return unlisten;
}
/**
* Returns a promise that will resolve as soon as the specified event has
* fired on the element.
* @param {!EventTarget} element
* @param {string} eventType
* @param {boolean=} opt_capture
* @param {function(!UnlistenDef)=} opt_cancel An optional function that, when
* provided, will be called with the unlistener. This gives the caller
* access to the unlistener, so it may be called manually when necessary.
* @return {!Promise<!Event>}
*/
export function listenOncePromise(element, eventType, opt_capture, opt_cancel) {
let unlisten;
const eventPromise = new Promise(resolve => {
unlisten = listenOnce(element, eventType, resolve, opt_capture);
});
eventPromise.then(unlisten, unlisten);
if (opt_cancel) {
opt_cancel(unlisten);
}
return eventPromise;
}
/**
* Whether the specified element/window has been loaded already.
* @param {!Element|!Window} eleOrWindow
* @return {boolean}
*/
export function isLoaded(eleOrWindow) {
return !!(eleOrWindow.complete || eleOrWindow.readyState == 'complete'
// If the passed in thing is a Window, infer loaded state from
//
|| (eleOrWindow.document
&& eleOrWindow.document.readyState == 'complete'));
}
/**
* Returns a promise that will resolve or fail based on the eleOrWindow's 'load'
* and 'error' events. Optionally this method takes a timeout, which will reject
* the promise if the resource has not loaded by then.
* @param {T} eleOrWindow Supports both Elements and as a special case Windows.
* @return {!Promise<T>}
* @template T
*/
export function loadPromise(eleOrWindow) {
let unlistenLoad;
let unlistenError;
if (isLoaded(eleOrWindow)) {
return Promise.resolve(eleOrWindow);
}
const loadingPromise = new Promise((resolve, reject) => {
// Listen once since IE 5/6/7 fire the onload event continuously for
// animated GIFs.
const tagName = eleOrWindow.tagName;
if (tagName === 'AUDIO' || tagName === 'VIDEO') {
unlistenLoad = listenOnce(eleOrWindow, 'loadstart', resolve);
} else {
unlistenLoad = listenOnce(eleOrWindow, 'load', resolve);
}
// For elements, unlisten on error (don't for Windows).
if (tagName) {
unlistenError = listenOnce(eleOrWindow, 'error', reject);
}
});
return loadingPromise.then(() => {
if (unlistenError) {
unlistenError();
}
return eleOrWindow;
}, () => {
if (unlistenLoad) {
unlistenLoad();
}
failedToLoad(eleOrWindow);
});
}
/**
* Emit error on load failure.
* @param {!Element|!Window} eleOrWindow Supports both Elements and as a special
* case Windows.
*/
function failedToLoad(eleOrWindow) {
// Report failed loads as user errors so that they automatically go
// into the "document error" bucket.
let target = eleOrWindow;
if (target && target.src) {
target = target.src;
}
throw user().createError(LOAD_FAILURE_PREFIX, target);
}
/**
* Returns true if this error message is was created for a load error.
* @param {string} message An error message
* @return {boolean}
*/
export function isLoadErrorMessage(message) {
return message.indexOf(LOAD_FAILURE_PREFIX) != -1;
}
|
lzanol/amphtml
|
src/event-helper.js
|
JavaScript
|
apache-2.0
| 5,533 |
import type { IScope } from 'angular';
import { mock, noop } from 'angular';
import { mount, shallow } from 'enzyme';
import React from 'react';
import type { Application, ApplicationDataSource, IMoniker, IServerGroup } from '@spinnaker/core';
import { ApplicationModelBuilder, REACT_MODULE } from '@spinnaker/core';
import type { IAccountRegionClusterSelectorProps } from './AccountRegionClusterSelector';
import { AccountRegionClusterSelector } from './AccountRegionClusterSelector';
describe('<AccountRegionClusterSelector />', () => {
let $scope: IScope;
let application: Application;
function createServerGroup(account: string, cluster: string, name: string, region: string): IServerGroup {
return {
account,
cloudProvider: 'cloud-provider',
cluster,
name,
region,
instances: [{ health: null, id: 'instance-id', launchTime: 0, name: 'instance-name', zone: 'GMT' }],
instanceCounts: { up: 1, down: 0, starting: 0, succeeded: 1, failed: 0, unknown: 0, outOfService: 0 },
moniker: { app: 'my-app', cluster, detail: 'my-detail', stack: 'my-stack', sequence: 1 },
} as IServerGroup;
}
beforeEach(mock.module(REACT_MODULE));
beforeEach(
mock.inject(($rootScope: IScope) => {
$scope = $rootScope.$new();
application = ApplicationModelBuilder.createApplicationForTests('app', {
key: 'serverGroups',
loaded: true,
data: [
createServerGroup('account-name-one', 'app-stack-detailOne', 'app', 'region-one'),
createServerGroup('account-name-two', 'app-stack-detailTwo', 'app', 'region-two'),
createServerGroup('account-name-one', 'app-stack-detailOne', 'app', 'region-three'),
createServerGroup('account-name-one', 'app-stack-detailThree', 'app', 'region-one'),
createServerGroup('account-name-one', 'app-stack-detailFour', 'app', 'region-three'),
createServerGroup('account-name-one', 'app-stack-detailFive', 'app', 'region-two'),
],
defaultData: [] as IServerGroup[],
} as ApplicationDataSource<IServerGroup[]>);
}),
);
it('initializes properly with provided component', () => {
const accountRegionClusterProps: IAccountRegionClusterSelectorProps = {
accounts: [
{
accountId: 'account-id-one',
name: 'account-name-one',
requiredGroupMembership: [],
type: 'account-type',
},
],
application,
cloudProvider: 'cloud-provider',
onComponentUpdate: noop,
component: {
credentials: 'account-name-one',
regions: ['region-one'],
},
};
const component = shallow<AccountRegionClusterSelector>(
<AccountRegionClusterSelector {...accountRegionClusterProps} />,
);
$scope.$digest();
expect(component.state().availableRegions.length).toBe(3, 'number of available regions does not match');
expect(component.state().availableRegions).toContain('region-one');
expect(component.state().availableRegions).toContain('region-two');
expect(component.state().availableRegions).toContain('region-three');
expect(component.state().clusters.length).toBe(2, 'number of clusters does not match');
expect(component.state().clusters).toContain('app-stack-detailOne');
expect(component.state().clusters).toContain('app-stack-detailThree');
expect(component.state().clusterField).toBe('cluster');
expect(component.state().componentName).toBe('');
});
it('retrieves the correct list of regions when account is changed', () => {
let credentials = '';
let region = 'SHOULD-CHANGE';
let regions = ['SHOULD-CHANGE'];
let cluster = 'SHOULD-CHANGE';
const accountRegionClusterProps: IAccountRegionClusterSelectorProps = {
accounts: [
{
accountId: 'account-id-two',
name: 'account-name-two',
requiredGroupMembership: [],
type: 'account-type',
},
{
accountId: 'account-id-one',
name: 'account-name-one',
requiredGroupMembership: [],
type: 'account-type',
},
],
application,
cloudProvider: 'cloud-provider',
onComponentUpdate: (value: any) => {
credentials = value.credentials;
region = value.region;
regions = value.regions;
cluster = value.cluster;
},
component: {
credentials: 'account-name-one',
regions: ['region-one'],
},
};
const component = mount<AccountRegionClusterSelector>(
<AccountRegionClusterSelector {...accountRegionClusterProps} />,
);
$scope.$digest();
expect(component.state().availableRegions.length).toBe(3, 'number of available regions does not match');
expect(component.state().availableRegions).toContain('region-one');
expect(component.state().availableRegions).toContain('region-two');
expect(component.state().availableRegions).toContain('region-three');
expect(component.state().clusters.length).toBe(2, 'number of clusters does not match');
expect(component.state().clusters).toContain('app-stack-detailOne');
expect(component.state().clusters).toContain('app-stack-detailThree');
const accountSelectComponent = component.find('Select[name="credentials"] .Select-control input');
accountSelectComponent.simulate('mouseDown');
accountSelectComponent.simulate('change', { target: { value: 'account-name-two' } });
accountSelectComponent.simulate('keyDown', { keyCode: 9, key: 'Tab' });
$scope.$digest();
expect(component.state().availableRegions.length).toBe(1, 'number of available regions does not match');
expect(component.state().availableRegions).toContain('region-two');
expect(component.state().clusters.length).toBe(0, 'number of clusters does not match');
expect(region).toEqual('', 'selected region is not cleared');
expect(regions.length).toBe(0, 'selected regions list is not cleared');
expect(credentials).toContain('account-name-two');
expect(cluster).toBeUndefined('selected cluster is not cleared');
});
it('retrieves the correct list of clusters when the selector is multi-region and the region is changed', () => {
let regions: string[] = [];
let cluster = 'SHOULD-CHANGE';
const accountRegionClusterProps: IAccountRegionClusterSelectorProps = {
accounts: [
{
accountId: 'account-id-two',
name: 'account-name-two',
requiredGroupMembership: [],
type: 'account-type',
},
{
accountId: 'account-id-one',
name: 'account-name-one',
requiredGroupMembership: [],
type: 'account-type',
},
],
application,
cloudProvider: 'cloud-provider',
clusterField: 'newCluster',
onComponentUpdate: (value: any) => {
regions = value.regions;
cluster = value.newCluster;
},
component: {
credentials: 'account-name-one',
regions: ['region-one'],
},
};
const component = mount<AccountRegionClusterSelector>(
<AccountRegionClusterSelector {...accountRegionClusterProps} />,
);
$scope.$digest();
expect(component.state().availableRegions.length).toBe(3, 'number of available regions does not match');
expect(component.state().availableRegions).toContain('region-one');
expect(component.state().availableRegions).toContain('region-two');
expect(component.state().availableRegions).toContain('region-three');
expect(component.state().clusters.length).toBe(2, 'number of clusters does not match');
expect(component.state().clusters).toContain('app-stack-detailOne');
expect(component.state().clusters).toContain('app-stack-detailThree');
const accountSelectComponent = component.find('Select[name="regions"] .Select-control input');
accountSelectComponent.simulate('mouseDown');
accountSelectComponent.simulate('change', { target: { value: 'region-three' } });
accountSelectComponent.simulate('keyDown', { keyCode: 9, key: 'Tab' });
$scope.$digest();
expect(component.state().clusters.length).toBe(3, 'number of clusters does not match');
expect(component.state().clusters).toContain('app-stack-detailOne');
expect(component.state().clusters).toContain('app-stack-detailThree');
expect(component.state().clusters).toContain('app-stack-detailFour');
expect(cluster).toBeUndefined('selected cluster is not cleared');
expect(regions.length).toBe(2);
expect(regions).toContain('region-one');
expect(regions).toContain('region-three');
});
it('retrieves the correct list of clusters on startup and the selector is single-region', () => {
const accountRegionClusterProps: IAccountRegionClusterSelectorProps = {
accounts: [
{
accountId: 'account-id-two',
name: 'account-name-two',
requiredGroupMembership: [],
type: 'account-type',
},
{
accountId: 'account-id-one',
name: 'account-name-one',
requiredGroupMembership: [],
type: 'account-type',
},
],
application,
cloudProvider: 'cloud-provider',
onComponentUpdate: (_value: any) => {},
component: {
cluster: 'app-stack-detailOne',
credentials: 'account-name-one',
region: 'region-one',
},
isSingleRegion: true,
};
const component = mount<AccountRegionClusterSelector>(
<AccountRegionClusterSelector {...accountRegionClusterProps} />,
);
$scope.$digest();
expect(component.state().availableRegions.length).toBe(3, 'number of available regions does not match');
expect(component.state().availableRegions).toContain('region-one');
expect(component.state().availableRegions).toContain('region-two');
expect(component.state().availableRegions).toContain('region-three');
expect(component.state().clusters.length).toBe(2, 'number of clusters does not match');
expect(component.state().clusters).toContain('app-stack-detailOne');
expect(component.state().clusters).toContain('app-stack-detailThree');
});
it('the cluster value is updated in the component when cluster is changed', () => {
let cluster = '';
let moniker: IMoniker = { app: '' };
const accountRegionClusterProps: IAccountRegionClusterSelectorProps = {
accounts: [
{
accountId: 'account-id-two',
name: 'account-name-two',
requiredGroupMembership: [],
type: 'account-type',
},
{
accountId: 'account-id-one',
name: 'account-name-one',
requiredGroupMembership: [],
type: 'account-type',
},
],
application,
cloudProvider: 'cloud-provider',
clusterField: 'newCluster',
onComponentUpdate: (value: any) => {
cluster = value.newCluster;
moniker = value.moniker;
},
component: {
cluster: 'app-stack-detailOne',
credentials: 'account-name-one',
regions: ['region-one'],
},
};
const expectedMoniker = {
app: 'my-app',
cluster: 'app-stack-detailThree',
detail: 'my-detail',
stack: 'my-stack',
sequence: null,
} as IMoniker;
const component = mount<AccountRegionClusterSelector>(
<AccountRegionClusterSelector {...accountRegionClusterProps} />,
);
$scope.$digest();
expect(component.state().availableRegions.length).toBe(3, 'number of available regions does not match');
expect(component.state().availableRegions).toContain('region-one');
expect(component.state().availableRegions).toContain('region-two');
expect(component.state().availableRegions).toContain('region-three');
expect(component.state().clusters.length).toBe(2, 'number of clusters does not match');
expect(component.state().clusters).toContain('app-stack-detailOne');
expect(component.state().clusters).toContain('app-stack-detailThree');
const clusterSelectComponent = component.find('Select[name="newCluster"] .Select-control input');
clusterSelectComponent.simulate('mouseDown');
clusterSelectComponent.simulate('change', { target: { value: 'app-stack-detailThree' } });
clusterSelectComponent.simulate('keyDown', { keyCode: 9, key: 'Tab' });
$scope.$digest();
expect(cluster).toBe('app-stack-detailThree');
expect(moniker).toEqual(expectedMoniker);
});
it('the cluster value is updated in the component when cluster is changed to freeform value', () => {
let cluster = '';
let moniker: IMoniker = { app: '' };
const accountRegionClusterProps: IAccountRegionClusterSelectorProps = {
accounts: [
{
accountId: 'account-id-two',
name: 'account-name-two',
requiredGroupMembership: [],
type: 'account-type',
},
{
accountId: 'account-id-one',
name: 'account-name-one',
requiredGroupMembership: [],
type: 'account-type',
},
],
application,
cloudProvider: 'cloud-provider',
clusterField: 'newCluster',
onComponentUpdate: (value: any) => {
cluster = value.newCluster;
moniker = value.moniker;
},
component: {
cluster: 'app-stack-detailOne',
credentials: 'account-name-one',
regions: ['region-one'],
},
};
const component = mount<AccountRegionClusterSelector>(
<AccountRegionClusterSelector {...accountRegionClusterProps} />,
);
$scope.$digest();
const clusterSelectComponent = component.find('Select[name="newCluster"] .Select-control input');
clusterSelectComponent.simulate('mouseDown');
clusterSelectComponent.simulate('change', { target: { value: 'app-stack-freeform' } });
clusterSelectComponent.simulate('keyDown', { keyCode: 9, key: 'Tab' });
$scope.$digest();
expect(cluster).toBe('app-stack-freeform');
expect(moniker).toBeUndefined();
expect(component.state().clusters).toContain('app-stack-freeform');
});
it('initialize with form names', () => {
const accountRegionClusterProps: IAccountRegionClusterSelectorProps = {
accounts: [
{
accountId: 'account-id-one',
name: 'account-name-one',
requiredGroupMembership: [],
type: 'account-type',
},
],
application,
cloudProvider: 'cloud-provider',
onComponentUpdate: noop,
componentName: 'form',
component: {
credentials: 'account-name-one',
regions: ['region-one'],
},
};
const component = shallow(<AccountRegionClusterSelector {...accountRegionClusterProps} />);
$scope.$digest();
expect(component.find('Select[name="form.credentials"]').length).toBe(1, 'select for account not found');
expect(component.find('Select[name="form.regions"]').length).toBe(1, 'select for regions not found');
expect(component.find('StageConfigField [name="form.cluster"]').length).toBe(1, 'select for cluster not found');
});
});
|
spinnaker/deck
|
packages/cloudfoundry/src/presentation/widgets/accountRegionClusterSelector/AccountRegionClusterSelector.spec.tsx
|
TypeScript
|
apache-2.0
| 15,140 |
<%--
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.
--%>
dojo.provide("dojotrader.widget.Context");
dojo.require("dojo.collections.*");
dojo.require("dojo.lang.timing.Timer");
dojotrader.widget.Context = function(userID){
this._user = userID;
this._quotesCache = new dojo.collections.Dictionary();
this._quotesToUpdate = 0;
this._updateTimer = null;
this.startUpdateTimer = function(interval) {
this._updateTimer = new dojo.lang.timing.Timer(interval);
this._updateTimer.onTick = dojo.lang.hitch(this,this._updateQuotesCache);
this._updateTimer.start();
};
this.stopUpdateTimer = function() {
this._updateTimer.stop();
this._updateTimer = null;
};
this._addQuoteToCache = function(quote) {
this._quotesCache.add(quote.symbol, quote);
//this.onQuoteAddComplete(quote);
};
this.getQuoteFromCache = function(symbol) {
//alert("getQuoteFromCache");
value = null;
if (this._quotesCache.contains(symbol)){
value = this._quotesCache.entry(symbol).value;
} else {
this._getQuoteFromServer(symbol);
}
return value;
};
this._getQuoteFromServer = function(symbol) {
//alert("_getQuoteFromServer");
dojo.io.bind({
method: "GET",
//url: "/proxy/SoapProxy/getQuote?p1=" + symbol.value + "&format=json",
url: "/daytraderProxy/doProxy/getQuote?p1=" + symbol,
mimetype: "text/json",
load: dojo.lang.hitch(this, this._handleQuote),
error: dojo.lang.hitch(this, this._handleError),
useCache: false,
preventCache: true
});
};
this._getQuoteFromServerForUpdate = function(symbol) {
//alert("_getQuoteFromServer");
dojo.io.bind({
method: "GET",
//url: "/proxy/SoapProxy/getQuote?p1=" + symbol.value + "&format=json",
url: "/daytraderProxy/doProxy/getQuote?p1=" + symbol,
mimetype: "text/json",
load: dojo.lang.hitch(this, this._handleQuoteUpdate),
error: dojo.lang.hitch(this, this._handleError),
useCache: false,
preventCache: true
});
};
this._handleQuote = function(type, data, evt) {
//alert("_handleQuote");
this._addQuoteToCache(data.getQuoteReturn);
this.onQuoteAddComplete(data.getQuoteReturn);
dojo.event.topic.publish("/quotes", {action: "add", quote: data.getQuoteReturn});
};
this._handleQuoteUpdate = function(type, data, evt) {
//alert("_handleQuote");
newQuote = data.getQuoteReturn;
// check for quote equality - only update if they are different
oldQuote = this._quotesCache.entry(newQuote.symbol).value;
if (oldQuote.price != newQuote.price || oldQuote.change != newQuote.change) {
this._addQuoteToCache(newQuote);
dojo.event.topic.publish("/quotes", {action: "update", quote: newQuote});
}
this._quotesToUpdate++;
if (this._quotesCache.count == this._quotesToUpdate) {
//alert("Refresh Complete: " + this._quotesCache.count + " - " + this._quotesToUpdate);
this.onQuotesUpdateComplete();
}
};
this._updateQuotesCache = function() {
this._quotesToUpdate = 0;
keys = this._quotesCache.getKeyList();
for (idx = 0; idx < keys.length; idx++) {
this._getQuoteFromServerForUpdate(keys[idx]);
}
};
this.onQuotesUpdateComplete = function() {};
this.onQuoteAddComplete = function() {}
};
|
awajid/daytrader
|
assemblies/javaee/dojo-ui-web/src/main/webapp/widget/Context.js
|
JavaScript
|
apache-2.0
| 4,087 |
package com.wateryan.matrix.api;
public class Version {
public static final String R_0 = "r0";
public static final String V_1 = "v1";
}
|
wateryan/matrix-java
|
src/main/java/com/wateryan/matrix/api/Version.java
|
Java
|
apache-2.0
| 142 |
/*
* Copyright 2016-present Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.drivers.cisco;
import com.google.common.collect.Lists;
import org.onosproject.net.AnnotationKeys;
import org.onosproject.net.DefaultAnnotations;
import org.onosproject.net.PortNumber;
import org.onosproject.net.device.DefaultPortDescription;
import org.onosproject.net.device.PortDescription;
import java.util.Arrays;
import java.util.List;
import static org.onosproject.net.Port.Type;
/**
*Parser for Netconf XML configurations and replys as plain text.
*/
final class TextBlockParserCisco {
private static final String PHRASE = "bytes of memory.";
private static final String VERSION = "Version ";
private static final String EOF_VERSION1 = "Software";
private static final String EOF_VERSION2 = "Software,";
private static final String EOF_VERSION3 = "RELEASE";
private static final String PROCESSOR_BOARD = "Processor board ID ";
private static final String BANDWIDTH = "BW ";
private static final String SPEED = " Kbit/sec";
private static final String ETHERNET = "Eth";
private static final String FASTETHERNET = "Fas";
private static final String GIGABITETHERNET = "Gig";
private static final String FDDI = "Fdd";
private static final String POS = "POS";
private static final String SERIAL = "Ser";
private static final String NEWLINE_SPLITTER = "\n";
private static final String PORT_DELIMITER = "/";
private static final String SPACE = " ";
private static final String IS_UP = "is up, line protocol is up";
private static final List INTERFACES = Arrays.asList(ETHERNET, FASTETHERNET, GIGABITETHERNET, SERIAL, FDDI, POS);
private static final List FIBERINTERFACES = Arrays.asList(FDDI, POS);
private TextBlockParserCisco() {
//not called
}
/**
* Adding information in an array for CiscoIosDeviceDescriptin call.
* @param version the return of show version command
* @return the array with the information
*/
static String[] parseCiscoIosDeviceDetails(String version) {
String[] details = new String[4];
details[0] = getManufacturer(version);
details[1] = getHwVersion(version);
details[2] = getSwVersion(version);
details[3] = serialNumber(version);
return details;
}
/**
* Retrieving manufacturer of device.
* @param version the return of show version command
* @return the manufacturer of the device
*/
private static String getManufacturer(String version) {
int i;
String[] textStr = version.split(NEWLINE_SPLITTER);
String[] lineStr = textStr[0].trim().split(SPACE);
return lineStr[0];
}
/**
* Retrieving hardware version of device.
* @param version the return of show version command
* @return the hardware version of the device
*/
private static String getHwVersion(String version) {
String[] textStr = version.split(NEWLINE_SPLITTER);
String processor = SPACE;
int i;
for (i = 0; i < textStr.length; i++) {
if (textStr[i].indexOf(PHRASE) > 0) {
String[] lineStr = textStr[i].trim().split(SPACE);
processor = lineStr[1];
break;
} else {
processor = SPACE;
}
}
return processor;
}
/**
* Retrieving software version of device.
* @param version the return of show version command
* @return the software version of the device
*/
private static String getSwVersion(String version) {
String[] textStr = version.split(NEWLINE_SPLITTER);
int i;
for (i = 0; i < textStr.length; i++) {
if (textStr[i].indexOf(VERSION) > 0) {
break;
}
}
String[] lineStr = textStr[i].trim().split(SPACE);
StringBuilder sw = new StringBuilder();
for (int j = 0; j < lineStr.length; j++) {
if (lineStr[j].equals(EOF_VERSION1) || lineStr[j].equals(EOF_VERSION2)
) {
sw.append(lineStr[j - 1]).append(SPACE);
} else if (lineStr[j].equals(EOF_VERSION3)) {
sw.append(lineStr[j - 1]);
sw.setLength(sw.length() - 1);
}
}
return sw.toString();
}
/**
* Retrieving serial number of device.
* @param version the return of show version command
* @return the serial number of the device
*/
private static String serialNumber(String version) {
String[] textStr = version.split(NEWLINE_SPLITTER);
int i;
for (i = 0; i < textStr.length; i++) {
if (textStr[i].indexOf(PROCESSOR_BOARD) > 0) {
break;
}
}
return textStr[i].substring(textStr[i].indexOf(PROCESSOR_BOARD) + PROCESSOR_BOARD.length(),
textStr[i].length());
}
/**
* Calls methods to create information about Ports.
* @param interfacesReply the interfaces as plain text
* @return the Port description list
*/
public static List<PortDescription> parseCiscoIosPorts(String interfacesReply) {
String parentInterface;
String[] parentArray;
String tempString;
List<PortDescription> portDesc = Lists.newArrayList();
int interfacesCounter = interfacesCounterMethod(interfacesReply);
for (int i = 0; i < interfacesCounter; i++) {
parentInterface = parentInterfaceMethod(interfacesReply);
portDesc.add(findPortInfo(parentInterface));
parentArray = parentInterface.split(SPACE);
tempString = parentArray[0] + SPACE;
interfacesReply = interfacesReply.replace(tempString, SPACE + tempString);
}
return portDesc;
}
/**
* Creates the port information object.
* @param interfaceTree the interfaces as plain text
* @return the Port description object
*/
private static DefaultPortDescription findPortInfo(String interfaceTree) {
String[] textStr = interfaceTree.split(NEWLINE_SPLITTER);
String[] firstLine = textStr[0].split(SPACE);
String firstWord = firstLine[0];
Type type = getPortType(textStr);
boolean isEnabled = getIsEnabled(textStr);
String port = getPort(textStr);
long portSpeed = getPortSpeed(textStr);
DefaultAnnotations.Builder annotations = DefaultAnnotations.builder()
.set(AnnotationKeys.PORT_NAME, firstWord);
return "-1".equals(port) ? null : new DefaultPortDescription(PortNumber.portNumber(port),
isEnabled, type, portSpeed, annotations.build());
}
/**
* Counts the number of existing interfaces.
* @param interfacesReply the interfaces as plain text
* @return interfaces counter
*/
private static int interfacesCounterMethod(String interfacesReply) {
int counter;
String first3Characters;
String[] textStr = interfacesReply.split(NEWLINE_SPLITTER);
int lastLine = textStr.length - 1;
counter = 0;
for (int i = 1; i < lastLine; i++) {
first3Characters = textStr[i].substring(0, 3);
if (INTERFACES.contains(first3Characters)) {
counter++;
}
}
return counter;
}
/**
* Parses the text and seperates to Parent Interfaces.
* @param interfacesReply the interfaces as plain text
* @return Parent interface
*/
private static String parentInterfaceMethod(String interfacesReply) {
String firstCharacter;
String first3Characters;
boolean isChild = false;
StringBuilder anInterface = new StringBuilder("");
String[] textStr = interfacesReply.split("\\n");
int lastLine = textStr.length - 1;
for (int i = 1; i < lastLine; i++) {
firstCharacter = textStr[i].substring(0, 1);
first3Characters = textStr[i].substring(0, 3);
if (!(firstCharacter.equals(SPACE)) && isChild) {
break;
} else if (firstCharacter.equals(SPACE) && isChild) {
anInterface.append(textStr[i]).append(NEWLINE_SPLITTER);
} else if (INTERFACES.contains(first3Characters)) {
isChild = true;
anInterface.append(textStr[i]).append(NEWLINE_SPLITTER);
}
}
return anInterface.toString();
}
/**
* Get the port type for an interface.
* @param textStr interface splitted as an array
* @return Port type
*/
private static Type getPortType(String[] textStr) {
String first3Characters;
first3Characters = textStr[0].substring(0, 3);
return FIBERINTERFACES.contains(first3Characters) ? Type.FIBER : Type.COPPER;
}
/**
* Get the state for an interface.
* @param textStr interface splitted as an array
* @return isEnabled state
*/
private static boolean getIsEnabled(String[] textStr) {
return textStr[0].contains(IS_UP);
}
/**
* Get the port number for an interface.
* @param textStr interface splitted as an array
* @return port number
*/
private static String getPort(String[] textStr) {
String port;
try {
if (textStr[0].indexOf(PORT_DELIMITER) > 0) {
port = textStr[0].substring(textStr[0].lastIndexOf(PORT_DELIMITER) + 1,
textStr[0].indexOf(SPACE));
} else {
port = "-1";
}
} catch (RuntimeException e) {
port = "-1";
}
return port;
}
/**
* Get the port speed for an interface.
* @param textStr interface splitted as an array
* @return port speed
*/
private static long getPortSpeed(String[] textStr) {
long portSpeed = 0;
String result;
int lastLine = textStr.length - 1;
for (int i = 0; i < lastLine; i++) {
if ((textStr[i].indexOf(BANDWIDTH) > 0) && (textStr[i].indexOf(SPEED) > 0)) {
result = textStr[i].substring(textStr[i].indexOf(BANDWIDTH) + 3, textStr[i].indexOf(SPEED));
portSpeed = Long.valueOf(result);
break;
}
}
return portSpeed;
}
}
|
LorenzReinhart/ONOSnew
|
drivers/cisco/netconf/src/main/java/org/onosproject/drivers/cisco/TextBlockParserCisco.java
|
Java
|
apache-2.0
| 11,067 |
<?php
declare(strict_types = 1);
/*
* This file is part of the Etcetera package.
*
* (c) bitExpert AG
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace bitExpert\Etcetera\Reader\File\Excel;
/**
* Generic implementation of an {@link \bitExpert\Etcetera\Reader\Reader} for
* legacy Microsoft Excel files.
*/
class LegacyExcelReader extends AbstractExcelReader
{
/**
* {@inheritDoc}
*/
public function read()
{
$inputFileName = $this->filename;
try {
$inputFileType = \PHPExcel_IOFactory::identify($inputFileName);
$objReader = \PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
} catch (\Exception $e) {
die(sprintf(
'Error loading file "%s": %s',
pathinfo($inputFileName, PATHINFO_BASENAME),
$e->getMessage()
));
}
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
if (0 !== $this->offset) {
//@todo implement
throw new \InvalidArgumentException('Offset is not yet supported');
}
$properties = [];
for ($rowIndex = 1; $rowIndex <= $highestRow; $rowIndex++) {
$values = $sheet->rangeToArray(
'A' . $rowIndex . ':' . $highestColumn . $rowIndex,
null,
null,
false
);
$values = $values[0];
if ($this->headerDetector->isHeader($rowIndex, $values)) {
$properties = $this->describeProperties($values);
continue;
}
if ($rowIndex < $this->offset) {
continue;
}
if (!count($properties)) {
continue;
}
$this->processValues($properties, $values);
}
}
/**
* @param string $filename
* @return \PHPExcel_Reader_IReader
*/
protected function getPhpExcelReader(string $filename)
{
$this->setPhpExcelConfigurations();
$reader = \PHPExcel_IOFactory::createReaderForFile($filename);
$instanceName = \get_class($reader);
switch ($instanceName) {
case 'PHPExcel_Reader_Excel2007':
case 'PHPExcel_Reader_Excel5':
case 'PHPExcel_Reader_OOCalc':
/* @var $reader \PHPExcel_Reader_Excel2007 */
$reader->setReadDataOnly(true);
break;
}
$phpExcel = $reader->load($filename);
return $phpExcel;
}
/**
* Set PHP Excel configurations
*/
protected function setPhpExcelConfigurations()
{
// set caching configuration
$cacheMethod = \PHPExcel_CachedObjectStorageFactory::cache_in_memory;
\PHPExcel_Settings::setCacheStorageMethod(
$cacheMethod
);
}
}
|
bitExpert/etcetera
|
src/bitExpert/Etcetera/Reader/File/Excel/LegacyExcelReader.php
|
PHP
|
apache-2.0
| 3,095 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package rdf_star;
import java.util.function.Predicate;
import org.apache.jena.atlas.lib.NotImplemented;
import org.apache.jena.atlas.lib.StrUtils;
import org.apache.jena.atlas.lib.tuple.Tuple;
import org.apache.jena.atlas.logging.LogCtl;
import org.apache.jena.graph.Graph;
import org.apache.jena.graph.GraphUtil;
import org.apache.jena.graph.Node;
import org.apache.jena.graph.Triple;
import org.apache.jena.graph.impl.GraphPlain;
import org.apache.jena.query.*;
import org.apache.jena.riot.RDFDataMgr;
import org.apache.jena.riot.RIOT;
import org.apache.jena.sparql.core.DatasetGraph;
import org.apache.jena.sparql.core.DatasetGraphFactory;
import org.apache.jena.sparql.core.Quad;
import org.apache.jena.sparql.engine.binding.Binding;
import org.apache.jena.sparql.engine.binding.BindingFactory;
import org.apache.jena.sparql.engine.main.solver.SolverRX3;
import org.apache.jena.sparql.engine.main.solver.SolverRX4;
import org.apache.jena.sparql.sse.SSE;
import org.apache.jena.sparql.util.QueryExecUtils;
import org.apache.jena.sys.JenaSystem;
import org.apache.jena.system.Txn;
import org.apache.jena.tdb.TDBFactory;
import org.apache.jena.tdb2.DatabaseMgr;
import org.apache.jena.tdb2.TDB2Factory;
import org.apache.jena.tdb2.solver.BindingNodeId;
import org.apache.jena.tdb2.store.NodeId;
import org.apache.jena.tdb2.sys.SystemTDB;
public class DevRDFStar {
static {
JenaSystem.init();
LogCtl.setLog4j2();
RIOT.getContext().set(RIOT.symTurtleDirectiveStyle, "sparql");
}
public static void main(String...a) {
// runFile();
// runInline();
// System.exit(0);
//runDataAccess();
runInline();
System.exit(0);
}
public static void runInline(String...a) {
Dataset dataset = TDB2Factory.createDataset();
Predicate<Tuple<NodeId>> filter = tuple -> false;
DatasetGraph dsgtdb2 = dataset.asDatasetGraph();
dsgtdb2.getContext().set(SystemTDB.symTupleFilter, filter);
String data = StrUtils.strjoinNL("(dataset"
," (_ <<:a :b :c>> :p 'abc')"
,")");
String qs = "SELECT * { <<?a ?b ?c>> ?p 'abc'}";
Query query = QueryFactory.create(qs);
Txn.executeWrite(dataset, ()->{
DatasetGraph dsg = SSE.parseDatasetGraph(data);
dataset.asDatasetGraph().addAll(dsg);
QueryExecution qExec = QueryExecutionFactory.create(query, dataset);
//qExec.getContext().set(TDB2.symUnionDefaultGraph, true);
QueryExecUtils.executeQuery(qExec);
});
}
public static void runFile() {
//Dataset dataset = TDB2Factory.createDataset();
Dataset dataset = DatasetFactory.create();
// String DIR = "/home/afs/W3C/rdf-star/tests/sparql/eval/";
// String DATA = DIR+"data-4.trig";
// String QUERY = DIR+"sparql-star-graphs-1.rq";
String DIR = "/home/afs/ASF/afs-jena/jena-arq/testing/ARQ/ExprBuiltIns";
String DATA = DIR+"/data-builtin-2.ttl";
String QUERY = DIR+"/q-lang-3.rq"; // Dataset general only?
Query query = QueryFactory.read(QUERY);
System.out.println(query);
Txn.executeWrite(dataset, ()->{
Graph plain = GraphPlain.plain();
RDFDataMgr.read(plain, DATA);
Dataset dataset2 = DatasetFactory.wrap(DatasetGraphFactory.wrap(plain));
//RDFDataMgr.read(dataset, DATA);
//Dataset dataset2 = dataset;
//GraphPlain
QueryExecution qExec = QueryExecutionFactory.create(query, dataset2);
QueryExecUtils.executeQuery(qExec);
});
arq.sparql.main("--data="+DATA, "--query="+QUERY);
System.exit(0);
}
public static void mainEngine(String...a) {
boolean USE_TDB2_QUERY = true;
boolean USE_TDB1_QUERY = true;
// Temp - force term into the node table.
String dataStr =
StrUtils.strjoinNL("(prefix ((: <http://example/>))",
" (graph",
" (:s :p :o )",
" (:s1 :p1 :o1 )",
" (:s2 :p2 :o2 )",
"))");
Graph terms = SSE.parseGraph(dataStr);
Graph graph1 = SSE.parseGraph("(prefix ((: <http://example/>)) (graph (<<:s :p :o >> :q :z) ))");
Graph graph2 = SSE.parseGraph("(prefix ((: <http://example/>)) (graph (<<:s0 :p0 :o0 >> :q :z) (<<:s :p :o >> :q :z) ( :s :p :o ) ( :s1 :p1 :o1 ) ))");
graph1.getPrefixMapping().setNsPrefix("", "http://example/");
graph2.getPrefixMapping().setNsPrefix("", "http://example/");
//String pattern = "{ <<:s ?p :o>> ?q :z . BIND('A' AS ?A) }";
// BIND(<<?s ?p ?o>> AS ?T)
//String pattern = "{ ?s ?p ?o {| :q ?z |} }";
String pattern = "{ <<:s :p ?o >> ?q ?z . }";
String qs = "PREFIX : <http://example/> SELECT * "+pattern;
Query query = QueryFactory.create(qs);
Graph graph = graph1;
// // In-memory
if ( false )
{
// TEST
System.out.println("== Basic test");
Triple tData = SSE.parseTriple("(<<:s :p :o >> :q :z)");
Triple tPattern = SSE.parseTriple("(<<:s ?p ?o >> ?q ?z)");
//Binding input = BindingFactory.binding(Var.alloc("p"), SSE.parseNode(":pz"));
Binding input = BindingFactory.binding();
Binding b1 = SolverRX3.matchTriple(input, tData, tPattern);
System.out.println(b1);
Quad qData = SSE.parseQuad("(:g <<:s :p :o >> :q :z)");
Node qGraph = SSE.parseNode(":g");
Triple qPattern = tPattern;
Binding b2 = SolverRX4.matchQuad(input, qData, qGraph, qPattern);
System.out.println(b2);
System.exit(0);
}
{
System.out.println("== In-memory");
QueryExecution qExec = QueryExecutionFactory.create(query, DatasetGraphFactory.wrap(graph));
QueryExecUtils.executeQuery(qExec);
}
if ( USE_TDB2_QUERY ) {
System.out.println("== TDB2/Query");
Predicate<BindingNodeId> filter = bnid -> true;
DatasetGraph dsgtdb2 = DatabaseMgr.createDatasetGraph();
dsgtdb2.getContext().set(SystemTDB.symTupleFilter, filter);
Txn.executeWrite(dsgtdb2, ()->GraphUtil.addInto(dsgtdb2.getDefaultGraph(), graph));
Txn.executeRead(dsgtdb2, ()->{
QueryExecution qExec = QueryExecutionFactory.create(query, dsgtdb2);
QueryExecUtils.executeQuery(qExec);
});
}
if ( USE_TDB1_QUERY ) {
System.out.println("== TDB1/Query");
try {
DatasetGraph dsgtdb1 = TDBFactory.createDatasetGraph();
Txn.executeWrite(dsgtdb1, ()-> GraphUtil.addInto(dsgtdb1.getDefaultGraph(), graph));
Txn.executeRead(dsgtdb1, ()->{
QueryExecution qExec = QueryExecutionFactory.create(query, dsgtdb1);
QueryExecUtils.executeQuery(qExec);
});
} catch (NotImplemented ex) {
System.out.println("Exception: "+ex.getClass().getName()+" : "+ex.getMessage());
}
}
}
// [RDFx]
// public static void main1(String...a) {
// // To/From NodeId space.
// //SolverRX.
//
// DatasetGraph dsg = DatasetGraphFactory.createTxnMem();
// RX.MODE_SA = false;
// RDFDataMgr.read(dsg, "/home/afs/tmp/D.ttl");
// String PREFIXES = "PREFIX : <http://example/>\n";
// String qs = PREFIXES+"SELECT * { <<:s ?p ?o >> :q :z . BIND('A' AS ?A) }";
// Query query = QueryFactory.create(qs);
// System.out.println("==== Query 1 ====");
// QueryExecution qExec1 = QueryExecutionFactory.create(query, dsg);
// QueryExecUtils.executeQuery(qExec1);
//
// System.out.println("==== Query 2 ====");
// RX.MODE_SA = true;
// QueryExecution qExec2 = QueryExecutionFactory.create(query, dsg);
// QueryExecUtils.executeQuery(qExec2);
//
//
// System.exit(0);
//
// ARQConstants.getGlobalPrefixMap().setNsPrefix("ex", "http://example/");
//
//// dwim(":x", "?v");
//// dwim("<< :s :p :o>>", "?v");
//// dwim("<< :s :p :o>>", "<< ?s ?p ?o>>");
//// dwim("<< <<:x :q :z>> :p :o>>", "<< ?s ?p ?o>>");
//// dwim("<< <<:x :q :z>> :p :o>>", "<< <<?x ?q ?z>> ?p ?o>>");
//
//// dwim("<< :s :p :o>>", "<< ?s :q ?o>>");
//// dwim("<< :s :p :o>>", "<< ?x ?p ?x>>");
//
//// dwim("<< <<:x :q :z>> :p :z>>", "<< <<?x ?q ?z>> ?p ?z>>");
//
// dwim("<< <<:x1 :q :z1>> :p <<:x2 :q :z2>> >>", "<< ?s :p <<?s2 ?q ?o2>> >>");
//
// }
//
// private static void dwim(String dataStr, String patternStr) {
// Node data = SSE.parseNode(dataStr);
// Node pattern = SSE.parseNode(patternStr);
// Binding r = RX_SA.match(BindingFactory.root(), data, pattern);
// //r.vars().forEachRemaining(v->
// System.out.println(NodeFmtLib.displayStr(data));
// System.out.println(NodeFmtLib.displayStr(pattern));
// System.out.println(" "+r);
// }
}
|
afs/jena-workspace
|
src/main/java/rdf_star/DevRDFStar.java
|
Java
|
apache-2.0
| 10,152 |
package io.cattle.platform.agent.instance.service.impl;
import static io.cattle.platform.core.model.tables.HostTable.*;
import static io.cattle.platform.core.model.tables.InstanceHostMapTable.*;
import static io.cattle.platform.core.model.tables.NicTable.*;
import io.cattle.platform.agent.instance.service.InstanceNicLookup;
import io.cattle.platform.core.model.HostIpAddressMap;
import io.cattle.platform.core.model.Nic;
import io.cattle.platform.core.model.tables.records.NicRecord;
import io.cattle.platform.db.jooq.dao.impl.AbstractJooqDao;
import java.util.List;
public class HostIpAddressMapNicLookup extends AbstractJooqDao implements InstanceNicLookup {
@Override
public List<? extends Nic> getNics(Object obj) {
if ( ! ( obj instanceof HostIpAddressMap ) ) {
return null;
}
return create()
.select(NIC.fields())
.from(HOST)
.join(INSTANCE_HOST_MAP)
.on(INSTANCE_HOST_MAP.HOST_ID.eq(HOST.ID))
.join(NIC)
.on(NIC.INSTANCE_ID.eq(INSTANCE_HOST_MAP.INSTANCE_ID))
.where(HOST.ID.eq(((HostIpAddressMap)obj).getHostId())
.and(NIC.REMOVED.isNull())
.and(INSTANCE_HOST_MAP.REMOVED.isNull()))
.fetchInto(NicRecord.class);
}
}
|
cloudnautique/cloud-cattle
|
code/iaas/agent-instance/src/main/java/io/cattle/platform/agent/instance/service/impl/HostIpAddressMapNicLookup.java
|
Java
|
apache-2.0
| 1,363 |
# -*- encoding: utf-8 -*-
from django.core.paginator import Paginator, EmptyPage, InvalidPage
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from functools import wraps
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.core.exceptions import PermissionDenied
from datetime import datetime
def paginate(template_name=None, list_name='default', objects_per_page=10):
def inner_p(fn):
def wrapped(request, *args, **kwargs):
fn_res = fn(request, *args, **kwargs)
objects = fn_res[list_name]
paginator = Paginator(objects, objects_per_page)
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
# If page request (9999) is out of range,
# deliver last page of results.
try:
loo = paginator.page(page)
except (EmptyPage, InvalidPage):
loo = paginator.page(paginator.num_pages)
fn_res.update({list_name: loo})
if 'template_name' in fn_res:
return render_to_response(fn_res['template_name'], fn_res,
context_instance=RequestContext(request))
else:
return render_to_response(template_name, fn_res,
context_instance=RequestContext(request))
return wraps(fn)(wrapped)
return inner_p
def only_doctor(func):
def _fn(request, *args, **kwargs):
if request.user.get_profile().is_doctor():
return func(request, *args, **kwargs)
else:
return HttpResponseRedirect(reverse('cal.index'))
return _fn
def only_doctor_consulting(func):
def _fn(request, *args, **kwargs):
if request.user.get_profile().is_doctor():
if 'patient_user_id' in kwargs and not request.user.doctor.filter(user__id=kwargs['patient_user_id']):
raise PermissionDenied
if 'id_patient' in kwargs and not request.user.doctor.filter(user__id=kwargs['id_patient']):
raise PermissionDenied
if 'id_task' in kwargs and not request.user.doctor.filter(user__patient_tasks__id=kwargs['id_task']):
raise PermissionDenied
if 'id_appointment' in kwargs and not request.user.doctor.filter(user__appointment_patient__id=kwargs['id_appointment']):
raise PermissionDenied
return func(request, *args, **kwargs)
else:
return HttpResponseRedirect(reverse('consulting_index'))
return _fn
def only_patient_consulting(func):
def _fn(request, *args, **kwargs):
if request.user.get_profile().is_patient():
return func(request, *args, **kwargs)
else:
return HttpResponseRedirect(reverse('consulting_index'))
return _fn
def only_doctor_administrative(func):
def _fn(request, *args, **kwargs):
if request.user.get_profile().is_administrative() or\
request.user.get_profile().is_doctor():
return func(request, *args, **kwargs)
else:
return HttpResponseRedirect(reverse('consulting_index'))
return _fn
def update_password_date(func):
def _fn(request, *args, **kwargs):
prof = request.user.get_profile()
prof.updated_password_at = datetime.today()
prof.save()
return func(request, *args, **kwargs)
return _fn
|
frhumanes/consulting
|
web/src/decorators.py
|
Python
|
apache-2.0
| 3,520 |
var a00068 =
[
[ "base", "a00068.html#a5ea674ad553da52d47ffe1df62d6eb9d", null ],
[ "MemberSignature", "a00068.html#a31088531e14b7f77e1df653d1003237d", null ],
[ "_ConstTessMemberResultCallback_5_3", "a00068.html#a47e920466d4dcc3529e4c296c8ad619f", null ],
[ "Run", "a00068.html#a5fa1d64d09741b114bda949599035b9c", null ]
];
|
stweil/tesseract-ocr.github.io
|
3.x/a00068.js
|
JavaScript
|
apache-2.0
| 340 |
package tech.hobbs.hlfdocmgmntsystem.dao.messages.Impl;
import java.util.List;
import javax.mail.Message;
import org.springframework.stereotype.Repository;
import tech.hobbs.hlfdocmgmntsystem.dao.messages.MessageDao;
import tech.hobbs.hlfdocmgmntsystem.model.student.Student;
@Repository
public class MessageDaoImpl implements MessageDao {
@Override
public List<Message> findAll() {
// TODO Auto-generated method stub
return null;
}
@Override
public void saveOrUpdate(Message model) {
// TODO Auto-generated method stub
}
@Override
public void delete(Message model) {
// TODO Auto-generated method stub
}
@Override
public List<Message> findByRecipientFileno(Student student) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Message> findBySenderFileno(Student student) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Message> findByReadStatus(Boolean status) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Message> findAllTrashed() {
// TODO Auto-generated method stub
return null;
}
}
|
wchiviti/hlfdocsweb
|
Higherlife Document Management System/src/main/java/tech/hobbs/hlfdocmgmntsystem/dao/messages/Impl/MessageDaoImpl.java
|
Java
|
apache-2.0
| 1,181 |
package de.uni_mannheim.informatik.dws.winter.usecase.events.model;
import java.util.ArrayList;
import java.util.List;
import de.uni_mannheim.informatik.dws.winter.model.DataSet;
import de.uni_mannheim.informatik.dws.winter.model.defaultmodel.Attribute;
import de.uni_mannheim.informatik.dws.winter.model.io.CSVDataSetFormatter;
/**
* {@link CSVDataSetFormatter} for {@link Event}s.
*
* @author Daniel Ringler
*
*/
public class EventCSVFormatter extends CSVDataSetFormatter<Event,Attribute> {
@Override
public String[] getHeader(List<Attribute> orderedHeader) {
List<String> names = new ArrayList<>();
for (Attribute att : orderedHeader) {
names.add(att.getIdentifier());
}
return names.toArray(new String[names.size()]);
}
@Override
public String[] format(Event record, DataSet<Event, Attribute> dataset, List<Attribute> orderedHeader) {//}, char s) {
return record.getAllAttributeValues(',');//s);
}
}
|
olehmberg/winter
|
winter-usecases/src/main/java/de/uni_mannheim/informatik/dws/winter/usecase/events/model/EventCSVFormatter.java
|
Java
|
apache-2.0
| 960 |
/*
* Copyright (C) 2013 The Android Open Source Project
*
* 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.voidstar.glass.voiceenabledtimer;
import com.google.android.glass.widget.CardScrollAdapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;
/**
* Adapter for the {@link CardSrollView} inside {@link SelectValueActivity}.
*/
public class SelectValueScrollAdapter extends CardScrollAdapter {
private final Context mContext;
private final int mCount;
public SelectValueScrollAdapter(Context context, int count) {
mContext = context;
mCount = count;
}
@Override
public int getCount() {
return mCount;
}
@Override
public Object getItem(int position) {
return Integer.valueOf(position);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.card_select_value, parent);
}
final TextView view = (TextView) convertView.findViewById(R.id.value);
view.setText(String.format("%02d", position));
return convertView;
}
@Override
public int getPosition(Object id) {
if (id instanceof Integer) {
int idInt = (Integer) id;
if (idInt >= 0 && idInt < mCount) {
return idInt;
}
}
return AdapterView.INVALID_POSITION;
}
}
|
0111001101111010/Voice-Enabled-Timer
|
src/com/voidstar/glass/voiceenabledtimer/SelectValueScrollAdapter.java
|
Java
|
apache-2.0
| 2,132 |
/*
* Copyright 2013, WebGate Consulting AG
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.openntf.xpt.agents.master;
import java.io.Serializable;
import java.util.List;
public class ExecutionUserProperties implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private boolean m_LoggedIn = false;
private String m_UserName = "";
private int m_AccessLevel;
private List<String> m_Roles;
public boolean isLoggedIn() {
return m_LoggedIn;
}
public void setLoggedIn(boolean loggedIn) {
m_LoggedIn = loggedIn;
}
public String getUserName() {
return m_UserName;
}
public void setUserName(String userName) {
m_UserName = userName;
}
public int getAccessLevel() {
return m_AccessLevel;
}
public void setAccessLevel(int accessLevel) {
m_AccessLevel = accessLevel;
}
public List<String> getRoles() {
return m_Roles;
}
public void setRoles(List<String> roles) {
m_Roles = roles;
}
}
|
OpenNTF/XPagesToolkit
|
org.openntf.xpt.agents/src/org/openntf/xpt/agents/master/ExecutionUserProperties.java
|
Java
|
apache-2.0
| 1,540 |
/// <reference path="GenericAnimator.ts"/>
class Vector2Animator<T extends RenderObject> extends GenericAnimator<T, Vector2> {
interpolate(amount: number, from: Vector2, to: Vector2, interpolation: Interpolation): Vector2 {
switch (interpolation) {
case Interpolation.Linear:
return new Vector2(Math.lerp(amount, from.x, to.x), Math.lerp(amount, from.y, to.y));
default:
throw "Not supported";
}
}
}
class NumberAnimator<T extends RenderObject> extends GenericAnimator<T, number> {
interpolate(amount: number, from: number, to: number, interpolation: Interpolation): number {
switch (interpolation) {
case Interpolation.Linear:
return Math.lerp(amount, from, to);
default:
throw "Not supported";
}
}
}
|
Dia6lo/Mechanism
|
Mechanism/RenderObjects/Animations/Animators.ts
|
TypeScript
|
apache-2.0
| 865 |
/*
* Copyright (C) 2012-2014 Jorrit "Chainfire" Jongma
*
* 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 eu.chainfire.libsuperuser;
import android.os.Handler;
import android.os.Looper;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import eu.chainfire.libsuperuser.StreamGobbler.OnLineListener;
/**
* Class providing functionality to execute commands in a (root) shell
*/
public class Shell {
/**
* <p>
* Runs commands using the supplied shell, and returns the output, or null
* in case of errors.
* </p>
* <p>
* This method is deprecated and only provided for backwards compatibility.
* Use {@link #run(String, String[], String[], boolean)} instead, and see
* that same method for usage notes.
* </p>
*
* @param shell The shell to use for executing the commands
* @param commands The commands to execute
* @param wantSTDERR Return STDERR in the output ?
* @return Output of the commands, or null in case of an error
*/
@Deprecated
public static List<String> run(String shell, String[] commands, boolean wantSTDERR) {
return run(shell, commands, null, wantSTDERR);
}
/**
* <p>
* Runs commands using the supplied shell, and returns the output, or null
* in case of errors.
* </p>
* <p>
* Note that due to compatibility with older Android versions, wantSTDERR is
* not implemented using redirectErrorStream, but rather appended to the
* output. STDOUT and STDERR are thus not guaranteed to be in the correct
* order in the output.
* </p>
* <p>
* Note as well that this code will intentionally crash when run in debug
* mode from the main thread of the application. You should always execute
* shell commands from a background thread.
* </p>
* <p>
* When in debug mode, the code will also excessively log the commands
* passed to and the output returned from the shell.
* </p>
* <p>
* Though this function uses background threads to gobble STDOUT and STDERR
* so a deadlock does not occur if the shell produces massive output, the
* output is still stored in a List<String>, and as such doing
* something like <em>'ls -lR /'</em> will probably have you run out of
* memory.
* </p>
*
* @param shell The shell to use for executing the commands
* @param commands The commands to execute
* @param environment List of all environment variables (in 'key=value'
* format) or null for defaults
* @param wantSTDERR Return STDERR in the output ?
* @return Output of the commands, or null in case of an error
*/
public static List<String> run(String shell, String[] commands, String[] environment,
boolean wantSTDERR) {
String shellUpper = shell.toUpperCase(Locale.ENGLISH);
if (Debug.getSanityChecksEnabledEffective() && Debug.onMainThread()) {
// check if we're running in the main thread, and if so, crash if
// we're in debug mode, to let the developer know attention is
// needed here.
Debug.log(ShellOnMainThreadException.EXCEPTION_COMMAND);
throw new ShellOnMainThreadException(ShellOnMainThreadException.EXCEPTION_COMMAND);
}
Debug.logCommand(String.format("[%s%%] START", shellUpper));
List<String> res = Collections.synchronizedList(new ArrayList<String>());
try {
// Combine passed environment with system environment
if (environment != null) {
Map<String, String> newEnvironment = new HashMap<String, String>();
newEnvironment.putAll(System.getenv());
int split;
for (String entry : environment) {
if ((split = entry.indexOf("=")) >= 0) {
newEnvironment.put(entry.substring(0, split), entry.substring(split + 1));
}
}
int i = 0;
environment = new String[newEnvironment.size()];
for (Map.Entry<String, String> entry : newEnvironment.entrySet()) {
environment[i] = entry.getKey() + "=" + entry.getValue();
i++;
}
}
// setup our process, retrieve STDIN stream, and STDOUT/STDERR
// gobblers
Process process = Runtime.getRuntime().exec(shell, environment);
DataOutputStream STDIN = new DataOutputStream(process.getOutputStream());
StreamGobbler STDOUT = new StreamGobbler(shellUpper + "-", process.getInputStream(),
res);
StreamGobbler STDERR = new StreamGobbler(shellUpper + "*", process.getErrorStream(),
wantSTDERR ? res : null);
// start gobbling and write our commands to the shell
STDOUT.start();
STDERR.start();
try {
for (String write : commands) {
Debug.logCommand(String.format("[%s+] %s", shellUpper, write));
STDIN.write((write + "\n").getBytes("UTF-8"));
STDIN.flush();
}
STDIN.write("exit\n".getBytes("UTF-8"));
STDIN.flush();
} catch (IOException e) {
if (e.getMessage().contains("EPIPE")) {
// method most horrid to catch broken pipe, in which case we
// do nothing. the command is not a shell, the shell closed
// STDIN, the script already contained the exit command, etc.
// these cases we want the output instead of returning null
} else {
// other issues we don't know how to handle, leads to
// returning null
throw e;
}
}
// wait for our process to finish, while we gobble away in the
// background
process.waitFor();
// make sure our threads are done gobbling, our streams are closed,
// and the process is destroyed - while the latter two shouldn't be
// needed in theory, and may even produce warnings, in "normal" Java
// they are required for guaranteed cleanup of resources, so lets be
// safe and do this on Android as well
try {
STDIN.close();
} catch (IOException e) {
}
STDOUT.join();
STDERR.join();
process.destroy();
// in case of su, 255 usually indicates access denied
if (SU.isSU(shell) && (process.exitValue() == 255)) {
res = null;
}
} catch (IOException e) {
// shell probably not found
res = null;
} catch (InterruptedException e) {
// this should really be re-thrown
res = null;
}
Debug.logCommand(String.format("[%s%%] END", shell.toUpperCase(Locale.ENGLISH)));
return res;
}
protected static String[] availableTestCommands = new String[] {
"echo -BOC-",
"id"
};
/**
* See if the shell is alive, and if so, check the UID
*
* @param ret Standard output from running availableTestCommands
* @param checkForRoot true if we are expecting this shell to be running as
* root
* @return true on success, false on error
*/
protected static boolean parseAvailableResult(List<String> ret, boolean checkForRoot) {
if (ret == null)
return false;
// this is only one of many ways this can be done
boolean echo_seen = false;
for (String line : ret) {
if (line.contains("uid=")) {
// id command is working, let's see if we are actually root
return !checkForRoot || line.contains("uid=0");
} else if (line.contains("-BOC-")) {
// if we end up here, at least the su command starts some kind
// of shell,
// let's hope it has root privileges - no way to know without
// additional
// native binaries
echo_seen = true;
}
}
return echo_seen;
}
/**
* This class provides utility functions to easily execute commands using SH
*/
public static class SH {
/**
* Runs command and return output
*
* @param command The command to run
* @return Output of the command, or null in case of an error
*/
public static List<String> run(String command) {
return Shell.run("sh", new String[] {
command
}, null, false);
}
/**
* Runs commands and return output
*
* @param commands The commands to run
* @return Output of the commands, or null in case of an error
*/
public static List<String> run(List<String> commands) {
return Shell.run("sh", commands.toArray(new String[commands.size()]), null, false);
}
/**
* Runs commands and return output
*
* @param commands The commands to run
* @return Output of the commands, or null in case of an error
*/
public static List<String> run(String[] commands) {
return Shell.run("sh", commands, null, false);
}
}
/**
* This class provides utility functions to easily execute commands using SU
* (root shell), as well as detecting whether or not root is available, and
* if so which version.
*/
public static class SU {
private static Boolean isSELinuxEnforcing = null;
private static String[] suVersion = new String[] {
null, null
};
/**
* Runs command as root (if available) and return output
*
* @param command The command to run
* @return Output of the command, or null if root isn't available or in
* case of an error
*/
public static List<String> run(String command) {
return Shell.run("su", new String[] {
command
}, null, false);
}
/**
* Runs commands as root (if available) and return output
*
* @param commands The commands to run
* @return Output of the commands, or null if root isn't available or in
* case of an error
*/
public static List<String> run(List<String> commands) {
return Shell.run("su", commands.toArray(new String[commands.size()]), null, false);
}
/**
* Runs commands as root (if available) and return output
*
* @param commands The commands to run
* @return Output of the commands, or null if root isn't available or in
* case of an error
*/
public static List<String> run(String[] commands) {
return Shell.run("su", commands, null, false);
}
/**
* Detects whether or not superuser access is available, by checking the
* output of the "id" command if available, checking if a shell runs at
* all otherwise
*
* @return True if superuser access available
*/
public static boolean available() {
// this is only one of many ways this can be done
List<String> ret = run(Shell.availableTestCommands);
return Shell.parseAvailableResult(ret, true);
}
/**
* <p>
* Detects the version of the su binary installed (if any), if supported
* by the binary. Most binaries support two different version numbers,
* the public version that is displayed to users, and an internal
* version number that is used for version number comparisons. Returns
* null if su not available or retrieving the version isn't supported.
* </p>
* <p>
* Note that su binary version and GUI (APK) version can be completely
* different.
* </p>
* <p>
* This function caches its result to improve performance on multiple
* calls
* </p>
*
* @param internal Request human-readable version or application
* internal version
* @return String containing the su version or null
*/
public static synchronized String version(boolean internal) {
int idx = internal ? 0 : 1;
if (suVersion[idx] == null) {
String version = null;
List<String> ret = Shell.run(
internal ? "su -V" : "su -v",
new String[] { "exit" },
null,
false
);
if (ret != null) {
for (String line : ret) {
if (!internal) {
if (line.contains(".")) {
version = line;
break;
}
} else {
try {
if (Integer.parseInt(line) > 0) {
version = line;
break;
}
} catch (NumberFormatException e) {
}
}
}
}
suVersion[idx] = version;
}
return suVersion[idx];
}
/**
* Attempts to deduce if the shell command refers to a su shell
*
* @param shell Shell command to run
* @return Shell command appears to be su
*/
public static boolean isSU(String shell) {
// Strip parameters
int pos = shell.indexOf(' ');
if (pos >= 0) {
shell = shell.substring(0, pos);
}
// Strip path
pos = shell.lastIndexOf('/');
if (pos >= 0) {
shell = shell.substring(pos + 1);
}
return shell.equals("su");
}
/**
* Constructs a shell command to start a su shell using the supplied uid
* and SELinux context. This is can be an expensive operation, consider
* caching the result.
*
* @param uid Uid to use (0 == root)
* @param context (SELinux) context name to use or null
* @return Shell command
*/
public static String shell(int uid, String context) {
// su[ --context <context>][ <uid>]
String shell = "su";
if ((context != null) && isSELinuxEnforcing()) {
String display = version(false);
String internal = version(true);
// We only know the format for SuperSU v1.90+ right now
if ((display != null) &&
(internal != null) &&
(display.endsWith("SUPERSU")) &&
(Integer.valueOf(internal) >= 190)) {
shell = String.format(Locale.ENGLISH, "%s --context %s", shell, context);
}
}
// Most su binaries support the "su <uid>" format, but in case
// they don't, lets skip it for the default 0 (root) case
if (uid > 0) {
shell = String.format(Locale.ENGLISH, "%s %d", shell, uid);
}
return shell;
}
/**
* Constructs a shell command to start a su shell connected to mount
* master daemon, to perform public mounts on Android 4.3+ (or 4.2+ in
* SELinux enforcing mode)
*
* @return Shell command
*/
public static String shellMountMaster() {
if (android.os.Build.VERSION.SDK_INT >= 17) {
return "su --mount-master";
}
return "su";
}
/**
* Detect if SELinux is set to enforcing, caches result
*
* @return true if SELinux set to enforcing, or false in the case of
* permissive or not present
*/
public static synchronized boolean isSELinuxEnforcing() {
if (isSELinuxEnforcing == null) {
Boolean enforcing = null;
// First known firmware with SELinux built-in was a 4.2 (17)
// leak
if (android.os.Build.VERSION.SDK_INT >= 17) {
// Detect enforcing through sysfs, not always present
if (enforcing == null) {
File f = new File("/sys/fs/selinux/enforce");
if (f.exists()) {
try {
InputStream is = new FileInputStream("/sys/fs/selinux/enforce");
try {
enforcing = (is.read() == '1');
} finally {
is.close();
}
} catch (Exception e) {
}
}
}
// 4.4+ builds are enforcing by default, take the gamble
if (enforcing == null) {
enforcing = (android.os.Build.VERSION.SDK_INT >= 19);
}
}
if (enforcing == null) {
enforcing = false;
}
isSELinuxEnforcing = enforcing;
}
return isSELinuxEnforcing;
}
/**
* <p>
* Clears results cached by isSELinuxEnforcing() and version(boolean
* internal) calls.
* </p>
* <p>
* Most apps should never need to call this, as neither enforcing status
* nor su version is likely to change on a running device - though it is
* not impossible.
* </p>
*/
public static synchronized void clearCachedResults() {
isSELinuxEnforcing = null;
suVersion[0] = null;
suVersion[1] = null;
}
}
private interface OnResult {
// for any onCommandResult callback
public static final int WATCHDOG_EXIT = -1;
public static final int SHELL_DIED = -2;
// for Interactive.open() callbacks only
public static final int SHELL_EXEC_FAILED = -3;
public static final int SHELL_WRONG_UID = -4;
public static final int SHELL_RUNNING = 0;
}
/**
* Command result callback, notifies the recipient of the completion of a
* command block, including the (last) exit code, and the full output
*/
public interface OnCommandResultListener extends OnResult {
/**
* <p>
* Command result callback
* </p>
* <p>
* Depending on how and on which thread the shell was created, this
* callback may be executed on one of the gobbler threads. In that case,
* it is important the callback returns as quickly as possible, as
* delays in this callback may pause the native process or even result
* in a deadlock
* </p>
* <p>
* See {@link Shell.Interactive} for threading details
* </p>
*
* @param commandCode Value previously supplied to addCommand
* @param exitCode Exit code of the last command in the block
* @param output All output generated by the command block
*/
public void onCommandResult(int commandCode, int exitCode, List<String> output);
}
/**
* Command per line callback for parsing the output line by line without
* buffering It also notifies the recipient of the completion of a command
* block, including the (last) exit code.
*/
public interface OnCommandLineListener extends OnResult, OnLineListener {
/**
* <p>
* Command result callback
* </p>
* <p>
* Depending on how and on which thread the shell was created, this
* callback may be executed on one of the gobbler threads. In that case,
* it is important the callback returns as quickly as possible, as
* delays in this callback may pause the native process or even result
* in a deadlock
* </p>
* <p>
* See {@link Shell.Interactive} for threading details
* </p>
*
* @param commandCode Value previously supplied to addCommand
* @param exitCode Exit code of the last command in the block
*/
public void onCommandResult(int commandCode, int exitCode);
}
/**
* Internal class to store command block properties
*/
private static class Command {
private static int commandCounter = 0;
private final String[] commands;
private final int code;
private final OnCommandResultListener onCommandResultListener;
private final OnCommandLineListener onCommandLineListener;
private final String marker;
public Command(String[] commands, int code,
OnCommandResultListener onCommandResultListener,
OnCommandLineListener onCommandLineListener) {
this.commands = commands;
this.code = code;
this.onCommandResultListener = onCommandResultListener;
this.onCommandLineListener = onCommandLineListener;
this.marker = UUID.randomUUID().toString() + String.format("-%08x", ++commandCounter);
}
}
/**
* Builder class for {@link Shell.Interactive}
*/
public static class Builder {
private Handler handler = null;
private boolean autoHandler = true;
private String shell = "sh";
private boolean wantSTDERR = false;
private List<Command> commands = new LinkedList<Command>();
private Map<String, String> environment = new HashMap<String, String>();
private OnLineListener onSTDOUTLineListener = null;
private OnLineListener onSTDERRLineListener = null;
private int watchdogTimeout = 0;
/**
* <p>
* Set a custom handler that will be used to post all callbacks to
* </p>
* <p>
* See {@link Shell.Interactive} for further details on threading and
* handlers
* </p>
*
* @param handler Handler to use
* @return This Builder object for method chaining
*/
public Builder setHandler(Handler handler) {
this.handler = handler;
return this;
}
/**
* <p>
* Automatically create a handler if possible ? Default to true
* </p>
* <p>
* See {@link Shell.Interactive} for further details on threading and
* handlers
* </p>
*
* @param autoHandler Auto-create handler ?
* @return This Builder object for method chaining
*/
public Builder setAutoHandler(boolean autoHandler) {
this.autoHandler = autoHandler;
return this;
}
/**
* Set shell binary to use. Usually "sh" or "su", do not use a full path
* unless you have a good reason to
*
* @param shell Shell to use
* @return This Builder object for method chaining
*/
public Builder setShell(String shell) {
this.shell = shell;
return this;
}
/**
* Convenience function to set "sh" as used shell
*
* @return This Builder object for method chaining
*/
public Builder useSH() {
return setShell("sh");
}
/**
* Convenience function to set "su" as used shell
*
* @return This Builder object for method chaining
*/
public Builder useSU() {
return setShell("su");
}
/**
* Set if error output should be appended to command block result output
*
* @param wantSTDERR Want error output ?
* @return This Builder object for method chaining
*/
public Builder setWantSTDERR(boolean wantSTDERR) {
this.wantSTDERR = wantSTDERR;
return this;
}
/**
* Add or update an environment variable
*
* @param key Key of the environment variable
* @param value Value of the environment variable
* @return This Builder object for method chaining
*/
public Builder addEnvironment(String key, String value) {
environment.put(key, value);
return this;
}
/**
* Add or update environment variables
*
* @param addEnvironment Map of environment variables
* @return This Builder object for method chaining
*/
public Builder addEnvironment(Map<String, String> addEnvironment) {
environment.putAll(addEnvironment);
return this;
}
/**
* Add a command to execute
*
* @param command Command to execute
* @return This Builder object for method chaining
*/
public Builder addCommand(String command) {
return addCommand(command, 0, null);
}
/**
* <p>
* Add a command to execute, with a callback to be called on completion
* </p>
* <p>
* The thread on which the callback executes is dependent on various
* factors, see {@link Shell.Interactive} for further details
* </p>
*
* @param command Command to execute
* @param code User-defined value passed back to the callback
* @param onCommandResultListener Callback to be called on completion
* @return This Builder object for method chaining
*/
public Builder addCommand(String command, int code,
OnCommandResultListener onCommandResultListener) {
return addCommand(new String[] {
command
}, code, onCommandResultListener);
}
/**
* Add commands to execute
*
* @param commands Commands to execute
* @return This Builder object for method chaining
*/
public Builder addCommand(List<String> commands) {
return addCommand(commands, 0, null);
}
/**
* <p>
* Add commands to execute, with a callback to be called on completion
* (of all commands)
* </p>
* <p>
* The thread on which the callback executes is dependent on various
* factors, see {@link Shell.Interactive} for further details
* </p>
*
* @param commands Commands to execute
* @param code User-defined value passed back to the callback
* @param onCommandResultListener Callback to be called on completion
* (of all commands)
* @return This Builder object for method chaining
*/
public Builder addCommand(List<String> commands, int code,
OnCommandResultListener onCommandResultListener) {
return addCommand(commands.toArray(new String[commands.size()]), code,
onCommandResultListener);
}
/**
* Add commands to execute
*
* @param commands Commands to execute
* @return This Builder object for method chaining
*/
public Builder addCommand(String[] commands) {
return addCommand(commands, 0, null);
}
/**
* <p>
* Add commands to execute, with a callback to be called on completion
* (of all commands)
* </p>
* <p>
* The thread on which the callback executes is dependent on various
* factors, see {@link Shell.Interactive} for further details
* </p>
*
* @param commands Commands to execute
* @param code User-defined value passed back to the callback
* @param onCommandResultListener Callback to be called on completion
* (of all commands)
* @return This Builder object for method chaining
*/
public Builder addCommand(String[] commands, int code,
OnCommandResultListener onCommandResultListener) {
this.commands.add(new Command(commands, code, onCommandResultListener, null));
return this;
}
/**
* <p>
* Set a callback called for every line output to STDOUT by the shell
* </p>
* <p>
* The thread on which the callback executes is dependent on various
* factors, see {@link Shell.Interactive} for further details
* </p>
*
* @param onLineListener Callback to be called for each line
* @return This Builder object for method chaining
*/
public Builder setOnSTDOUTLineListener(OnLineListener onLineListener) {
this.onSTDOUTLineListener = onLineListener;
return this;
}
/**
* <p>
* Set a callback called for every line output to STDERR by the shell
* </p>
* <p>
* The thread on which the callback executes is dependent on various
* factors, see {@link Shell.Interactive} for further details
* </p>
*
* @param onLineListener Callback to be called for each line
* @return This Builder object for method chaining
*/
public Builder setOnSTDERRLineListener(OnLineListener onLineListener) {
this.onSTDERRLineListener = onLineListener;
return this;
}
/**
* <p>
* Enable command timeout callback
* </p>
* <p>
* This will invoke the onCommandResult() callback with exitCode
* WATCHDOG_EXIT if a command takes longer than watchdogTimeout seconds
* to complete.
* </p>
* <p>
* If a watchdog timeout occurs, it generally means that the Interactive
* session is out of sync with the shell process. The caller should
* close the current session and open a new one.
* </p>
*
* @param watchdogTimeout Timeout, in seconds; 0 to disable
* @return This Builder object for method chaining
*/
public Builder setWatchdogTimeout(int watchdogTimeout) {
this.watchdogTimeout = watchdogTimeout;
return this;
}
/**
* <p>
* Enable/disable reduced logcat output
* </p>
* <p>
* Note that this is a global setting
* </p>
*
* @param useMinimal true for reduced output, false for full output
* @return This Builder object for method chaining
*/
public Builder setMinimalLogging(boolean useMinimal) {
Debug.setLogTypeEnabled(Debug.LOG_COMMAND | Debug.LOG_OUTPUT, !useMinimal);
return this;
}
/**
* Construct a {@link Shell.Interactive} instance, and start the shell
*/
public Interactive open() {
return new Interactive(this, null);
}
/**
* Construct a {@link Shell.Interactive} instance, try to start the
* shell, and call onCommandResultListener to report success or failure
*
* @param onCommandResultListener Callback to return shell open status
*/
public Interactive open(OnCommandResultListener onCommandResultListener) {
return new Interactive(this, onCommandResultListener);
}
}
/**
* <p>
* An interactive shell - initially created with {@link Shell.Builder} -
* that executes blocks of commands you supply in the background, optionally
* calling callbacks as each block completes.
* </p>
* <p>
* STDERR output can be supplied as well, but due to compatibility with
* older Android versions, wantSTDERR is not implemented using
* redirectErrorStream, but rather appended to the output. STDOUT and STDERR
* are thus not guaranteed to be in the correct order in the output.
* </p>
* <p>
* Note as well that the close() and waitForIdle() methods will
* intentionally crash when run in debug mode from the main thread of the
* application. Any blocking call should be run from a background thread.
* </p>
* <p>
* When in debug mode, the code will also excessively log the commands
* passed to and the output returned from the shell.
* </p>
* <p>
* Though this function uses background threads to gobble STDOUT and STDERR
* so a deadlock does not occur if the shell produces massive output, the
* output is still stored in a List<String>, and as such doing
* something like <em>'ls -lR /'</em> will probably have you run out of
* memory when using a {@link Shell.OnCommandResultListener}. A work-around
* is to not supply this callback, but using (only)
* {@link Shell.Builder#setOnSTDOUTLineListener(OnLineListener)}. This way,
* an internal buffer will not be created and wasting your memory.
* </p>
* <h3>Callbacks, threads and handlers</h3>
* <p>
* On which thread the callbacks execute is dependent on your
* initialization. You can supply a custom Handler using
* {@link Shell.Builder#setHandler(Handler)} if needed. If you do not supply
* a custom Handler - unless you set
* {@link Shell.Builder#setAutoHandler(boolean)} to false - a Handler will
* be auto-created if the thread used for instantiation of the object has a
* Looper.
* </p>
* <p>
* If no Handler was supplied and it was also not auto-created, all
* callbacks will be called from either the STDOUT or STDERR gobbler
* threads. These are important threads that should be blocked as little as
* possible, as blocking them may in rare cases pause the native process or
* even create a deadlock.
* </p>
* <p>
* The main thread must certainly have a Looper, thus if you call
* {@link Shell.Builder#open()} from the main thread, a handler will (by
* default) be auto-created, and all the callbacks will be called on the
* main thread. While this is often convenient and easy to code with, you
* should be aware that if your callbacks are 'expensive' to execute, this
* may negatively impact UI performance.
* </p>
* <p>
* Background threads usually do <em>not</em> have a Looper, so calling
* {@link Shell.Builder#open()} from such a background thread will (by
* default) result in all the callbacks being executed in one of the gobbler
* threads. You will have to make sure the code you execute in these
* callbacks is thread-safe.
* </p>
*/
public static class Interactive {
private final Handler handler;
private final boolean autoHandler;
private final String shell;
private final boolean wantSTDERR;
private final List<Command> commands;
private final Map<String, String> environment;
private final OnLineListener onSTDOUTLineListener;
private final OnLineListener onSTDERRLineListener;
private int watchdogTimeout;
private Process process = null;
private DataOutputStream STDIN = null;
private StreamGobbler STDOUT = null;
private StreamGobbler STDERR = null;
private ScheduledThreadPoolExecutor watchdog = null;
private volatile boolean running = false;
private volatile boolean idle = true; // read/write only synchronized
private volatile boolean closed = true;
private volatile int callbacks = 0;
private volatile int watchdogCount;
private Object idleSync = new Object();
private Object callbackSync = new Object();
private volatile int lastExitCode = 0;
private volatile String lastMarkerSTDOUT = null;
private volatile String lastMarkerSTDERR = null;
private volatile Command command = null;
private volatile List<String> buffer = null;
/**
* The only way to create an instance: Shell.Builder::open()
*
* @param builder Builder class to take values from
*/
private Interactive(final Builder builder,
final OnCommandResultListener onCommandResultListener) {
autoHandler = builder.autoHandler;
shell = builder.shell;
wantSTDERR = builder.wantSTDERR;
commands = builder.commands;
environment = builder.environment;
onSTDOUTLineListener = builder.onSTDOUTLineListener;
onSTDERRLineListener = builder.onSTDERRLineListener;
watchdogTimeout = builder.watchdogTimeout;
// If a looper is available, we offload the callbacks from the
// gobbling threads
// to whichever thread created us. Would normally do this in open(),
// but then we could not declare handler as final
if ((Looper.myLooper() != null) && (builder.handler == null) && autoHandler) {
handler = new Handler();
} else {
handler = builder.handler;
}
boolean ret = open();
if (onCommandResultListener == null) {
return;
} else if (ret == false) {
onCommandResultListener.onCommandResult(0,
OnCommandResultListener.SHELL_EXEC_FAILED, null);
return;
}
// Allow up to 60 seconds for SuperSU/Superuser dialog, then enable
// the user-specified
// timeout for all subsequent operations
watchdogTimeout = 60;
addCommand(Shell.availableTestCommands, 0, new OnCommandResultListener() {
public void onCommandResult(int commandCode, int exitCode, List<String> output) {
if (exitCode == OnCommandResultListener.SHELL_RUNNING &&
Shell.parseAvailableResult(output, Shell.SU.isSU(shell)) != true) {
// shell is up, but it's brain-damaged
exitCode = OnCommandResultListener.SHELL_WRONG_UID;
}
watchdogTimeout = builder.watchdogTimeout;
onCommandResultListener.onCommandResult(0, exitCode, output);
}
});
}
@Override
protected void finalize() throws Throwable {
if (!closed && Debug.getSanityChecksEnabledEffective()) {
// waste of resources
Debug.log(ShellNotClosedException.EXCEPTION_NOT_CLOSED);
throw new ShellNotClosedException();
}
super.finalize();
}
/**
* Add a command to execute
*
* @param command Command to execute
*/
public void addCommand(String command) {
addCommand(command, 0, (OnCommandResultListener) null);
}
/**
* <p>
* Add a command to execute, with a callback to be called on completion
* </p>
* <p>
* The thread on which the callback executes is dependent on various
* factors, see {@link Shell.Interactive} for further details
* </p>
*
* @param command Command to execute
* @param code User-defined value passed back to the callback
* @param onCommandResultListener Callback to be called on completion
*/
public void addCommand(String command, int code,
OnCommandResultListener onCommandResultListener) {
addCommand(new String[] {
command
}, code, onCommandResultListener);
}
/**
* <p>
* Add a command to execute, with a callback. This callback gobbles the
* output line by line without buffering it and also returns the result
* code on completion.
* </p>
* <p>
* The thread on which the callback executes is dependent on various
* factors, see {@link Shell.Interactive} for further details
* </p>
*
* @param command Command to execute
* @param code User-defined value passed back to the callback
* @param onCommandLineListener Callback
*/
public void addCommand(String command, int code, OnCommandLineListener onCommandLineListener) {
addCommand(new String[] {
command
}, code, onCommandLineListener);
}
/**
* Add commands to execute
*
* @param commands Commands to execute
*/
public void addCommand(List<String> commands) {
addCommand(commands, 0, (OnCommandResultListener) null);
}
/**
* <p>
* Add commands to execute, with a callback to be called on completion
* (of all commands)
* </p>
* <p>
* The thread on which the callback executes is dependent on various
* factors, see {@link Shell.Interactive} for further details
* </p>
*
* @param commands Commands to execute
* @param code User-defined value passed back to the callback
* @param onCommandResultListener Callback to be called on completion
* (of all commands)
*/
public void addCommand(List<String> commands, int code,
OnCommandResultListener onCommandResultListener) {
addCommand(commands.toArray(new String[commands.size()]), code, onCommandResultListener);
}
/**
* <p>
* Add commands to execute, with a callback. This callback gobbles the
* output line by line without buffering it and also returns the result
* code on completion.
* </p>
* <p>
* The thread on which the callback executes is dependent on various
* factors, see {@link Shell.Interactive} for further details
* </p>
*
* @param commands Commands to execute
* @param code User-defined value passed back to the callback
* @param onCommandLineListener Callback
*/
public void addCommand(List<String> commands, int code,
OnCommandLineListener onCommandLineListener) {
addCommand(commands.toArray(new String[commands.size()]), code, onCommandLineListener);
}
/**
* Add commands to execute
*
* @param commands Commands to execute
*/
public void addCommand(String[] commands) {
addCommand(commands, 0, (OnCommandResultListener) null);
}
/**
* <p>
* Add commands to execute, with a callback to be called on completion
* (of all commands)
* </p>
* <p>
* The thread on which the callback executes is dependent on various
* factors, see {@link Shell.Interactive} for further details
* </p>
*
* @param commands Commands to execute
* @param code User-defined value passed back to the callback
* @param onCommandResultListener Callback to be called on completion
* (of all commands)
*/
public synchronized void addCommand(String[] commands, int code,
OnCommandResultListener onCommandResultListener) {
this.commands.add(new Command(commands, code, onCommandResultListener, null));
runNextCommand();
}
/**
* <p>
* Add commands to execute, with a callback. This callback gobbles the
* output line by line without buffering it and also returns the result
* code on completion.
* </p>
* <p>
* The thread on which the callback executes is dependent on various
* factors, see {@link Shell.Interactive} for further details
* </p>
*
* @param commands Commands to execute
* @param code User-defined value passed back to the callback
* @param onCommandLineListener Callback
*/
public synchronized void addCommand(String[] commands, int code,
OnCommandLineListener onCommandLineListener) {
this.commands.add(new Command(commands, code, null, onCommandLineListener));
runNextCommand();
}
/**
* Run the next command if any and if ready, signals idle state if no
* commands left
*/
private void runNextCommand() {
runNextCommand(true);
}
/**
* Called from a ScheduledThreadPoolExecutor timer thread every second
* when there is an outstanding command
*/
private synchronized void handleWatchdog() {
final int exitCode;
if (watchdog == null)
return;
if (watchdogTimeout == 0)
return;
if (!isRunning()) {
exitCode = OnCommandResultListener.SHELL_DIED;
Debug.log(String.format("[%s%%] SHELL_DIED", shell.toUpperCase(Locale.ENGLISH)));
} else if (watchdogCount++ < watchdogTimeout) {
return;
} else {
exitCode = OnCommandResultListener.WATCHDOG_EXIT;
Debug.log(String.format("[%s%%] WATCHDOG_EXIT", shell.toUpperCase(Locale.ENGLISH)));
}
if (handler != null) {
postCallback(command, exitCode, buffer);
}
// prevent multiple callbacks for the same command
command = null;
buffer = null;
idle = true;
watchdog.shutdown();
watchdog = null;
kill();
}
/**
* Start the periodic timer when a command is submitted
*/
private void startWatchdog() {
if (watchdogTimeout == 0) {
return;
}
watchdogCount = 0;
watchdog = new ScheduledThreadPoolExecutor(1);
watchdog.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
handleWatchdog();
}
}, 1, 1, TimeUnit.SECONDS);
}
/**
* Disable the watchdog timer upon command completion
*/
private void stopWatchdog() {
if (watchdog != null) {
watchdog.shutdownNow();
watchdog = null;
}
}
/**
* Run the next command if any and if ready
*
* @param notifyIdle signals idle state if no commands left ?
*/
private void runNextCommand(boolean notifyIdle) {
// must always be called from a synchronized method
boolean running = isRunning();
if (!running)
idle = true;
if (running && idle && (commands.size() > 0)) {
Command command = commands.get(0);
commands.remove(0);
buffer = null;
lastExitCode = 0;
lastMarkerSTDOUT = null;
lastMarkerSTDERR = null;
if (command.commands.length > 0) {
try {
if (command.onCommandResultListener != null) {
// no reason to store the output if we don't have an
// OnCommandResultListener
// user should catch the output with an
// OnLineListener in this case
buffer = Collections.synchronizedList(new ArrayList<String>());
}
idle = false;
this.command = command;
startWatchdog();
for (String write : command.commands) {
Debug.logCommand(String.format("[%s+] %s",
shell.toUpperCase(Locale.ENGLISH), write));
STDIN.write((write + "\n").getBytes("UTF-8"));
}
STDIN.write(("echo " + command.marker + " $?\n").getBytes("UTF-8"));
STDIN.write(("echo " + command.marker + " >&2\n").getBytes("UTF-8"));
STDIN.flush();
} catch (IOException e) {
}
} else {
runNextCommand(false);
}
} else if (!running) {
// our shell died for unknown reasons - abort all submissions
while (commands.size() > 0) {
postCallback(commands.remove(0), OnCommandResultListener.SHELL_DIED, null);
}
}
if (idle && notifyIdle) {
synchronized (idleSync) {
idleSync.notifyAll();
}
}
}
/**
* Processes a STDOUT/STDERR line containing an end/exitCode marker
*/
private synchronized void processMarker() {
if (command.marker.equals(lastMarkerSTDOUT)
&& (command.marker.equals(lastMarkerSTDERR))) {
postCallback(command, lastExitCode, buffer);
stopWatchdog();
command = null;
buffer = null;
idle = true;
runNextCommand();
}
}
/**
* Process a normal STDOUT/STDERR line
*
* @param line Line to process
* @param listener Callback to call or null
*/
private synchronized void processLine(String line, OnLineListener listener) {
if (listener != null) {
if (handler != null) {
final String fLine = line;
final OnLineListener fListener = listener;
startCallback();
handler.post(new Runnable() {
@Override
public void run() {
try {
fListener.onLine(fLine);
} finally {
endCallback();
}
}
});
} else {
listener.onLine(line);
}
}
}
/**
* Add line to internal buffer
*
* @param line Line to add
*/
private synchronized void addBuffer(String line) {
if (buffer != null) {
buffer.add(line);
}
}
/**
* Increase callback counter
*/
private void startCallback() {
synchronized (callbackSync) {
callbacks++;
}
}
/**
* Schedule a callback to run on the appropriate thread
*/
private void postCallback(final Command fCommand, final int fExitCode,
final List<String> fOutput) {
if (fCommand.onCommandResultListener == null && fCommand.onCommandLineListener == null) {
return;
}
if (handler == null) {
if ((fCommand.onCommandResultListener != null) && (fOutput != null))
fCommand.onCommandResultListener.onCommandResult(fCommand.code, fExitCode,
fOutput);
if (fCommand.onCommandLineListener != null)
fCommand.onCommandLineListener.onCommandResult(fCommand.code, fExitCode);
return;
}
startCallback();
handler.post(new Runnable() {
@Override
public void run() {
try {
if ((fCommand.onCommandResultListener != null) && (fOutput != null))
fCommand.onCommandResultListener.onCommandResult(fCommand.code,
fExitCode, fOutput);
if (fCommand.onCommandLineListener != null)
fCommand.onCommandLineListener
.onCommandResult(fCommand.code, fExitCode);
} finally {
endCallback();
}
}
});
}
/**
* Decrease callback counter, signals callback complete state when
* dropped to 0
*/
private void endCallback() {
synchronized (callbackSync) {
callbacks--;
if (callbacks == 0) {
callbackSync.notifyAll();
}
}
}
/**
* Internal call that launches the shell, starts gobbling, and starts
* executing commands. See {@link Shell.Interactive}
*
* @return Opened successfully ?
*/
private synchronized boolean open() {
Debug.log(String.format("[%s%%] START", shell.toUpperCase(Locale.ENGLISH)));
try {
// setup our process, retrieve STDIN stream, and STDOUT/STDERR
// gobblers
if (environment.size() == 0) {
process = Runtime.getRuntime().exec(shell);
} else {
Map<String, String> newEnvironment = new HashMap<String, String>();
newEnvironment.putAll(System.getenv());
newEnvironment.putAll(environment);
int i = 0;
String[] env = new String[newEnvironment.size()];
for (Map.Entry<String, String> entry : newEnvironment.entrySet()) {
env[i] = entry.getKey() + "=" + entry.getValue();
i++;
}
process = Runtime.getRuntime().exec(shell, env);
}
STDIN = new DataOutputStream(process.getOutputStream());
STDOUT = new StreamGobbler(shell.toUpperCase(Locale.ENGLISH) + "-",
process.getInputStream(), new OnLineListener() {
@Override
public void onLine(String line) {
synchronized (Interactive.this) {
if (command == null) {
return;
}
if (line.startsWith(command.marker)) {
try {
lastExitCode = Integer.valueOf(
line.substring(command.marker.length() + 1), 10);
} catch (Exception e) {
}
lastMarkerSTDOUT = command.marker;
processMarker();
} else {
addBuffer(line);
processLine(line, onSTDOUTLineListener);
processLine(line, command.onCommandLineListener);
}
}
}
});
STDERR = new StreamGobbler(shell.toUpperCase(Locale.ENGLISH) + "*",
process.getErrorStream(), new OnLineListener() {
@Override
public void onLine(String line) {
synchronized (Interactive.this) {
if (command == null) {
return;
}
if (line.startsWith(command.marker)) {
lastMarkerSTDERR = command.marker;
processMarker();
} else {
if (wantSTDERR)
addBuffer(line);
processLine(line, onSTDERRLineListener);
}
}
}
});
// start gobbling and write our commands to the shell
STDOUT.start();
STDERR.start();
running = true;
closed = false;
runNextCommand();
return true;
} catch (IOException e) {
// shell probably not found
return false;
}
}
/**
* Close shell and clean up all resources. Call this when you are done
* with the shell. If the shell is not idle (all commands completed) you
* should not call this method from the main UI thread because it may
* block for a long time. This method will intentionally crash your app
* (if in debug mode) if you try to do this anyway.
*/
public void close() {
boolean _idle = isIdle(); // idle must be checked synchronized
synchronized (this) {
if (!running)
return;
running = false;
closed = true;
}
// This method should not be called from the main thread unless the
// shell is idle and can be cleaned up with (minimal) waiting. Only
// throw in debug mode.
if (!_idle && Debug.getSanityChecksEnabledEffective() && Debug.onMainThread()) {
Debug.log(ShellOnMainThreadException.EXCEPTION_NOT_IDLE);
throw new ShellOnMainThreadException(ShellOnMainThreadException.EXCEPTION_NOT_IDLE);
}
if (!_idle)
waitForIdle();
try {
try {
STDIN.write(("exit\n").getBytes("UTF-8"));
STDIN.flush();
} catch (IOException e) {
if (e.getMessage().contains("EPIPE")) {
// we're not running a shell, the shell closed STDIN,
// the script already contained the exit command, etc.
} else {
throw e;
}
}
// wait for our process to finish, while we gobble away in the
// background
process.waitFor();
// make sure our threads are done gobbling, our streams are
// closed, and the process is destroyed - while the latter two
// shouldn't be needed in theory, and may even produce warnings,
// in "normal" Java they are required for guaranteed cleanup of
// resources, so lets be safe and do this on Android as well
try {
STDIN.close();
} catch (IOException e) {
// STDIN going missing is no reason to abort
}
STDOUT.join();
STDERR.join();
stopWatchdog();
process.destroy();
} catch (IOException e) {
// various unforseen IO errors may still occur
} catch (InterruptedException e) {
// this should really be re-thrown
}
Debug.log(String.format("[%s%%] END", shell.toUpperCase(Locale.ENGLISH)));
}
/**
* Try to clean up as much as possible from a shell that's gotten itself
* wedged. Hopefully the StreamGobblers will croak on their own when the
* other side of the pipe is closed.
*/
public synchronized void kill() {
running = false;
closed = true;
try {
STDIN.close();
} catch (IOException e) {
}
try {
process.destroy();
} catch (Exception e) {
}
}
/**
* Is our shell still running ?
*
* @return Shell running ?
*/
public boolean isRunning() {
if (process == null) {
return false;
}
try {
// if this throws, we're still running
process.exitValue();
return false;
} catch (IllegalThreadStateException e) {
}
return true;
}
/**
* Have all commands completed executing ?
*
* @return Shell idle ?
*/
public synchronized boolean isIdle() {
if (!isRunning()) {
idle = true;
synchronized (idleSync) {
idleSync.notifyAll();
}
}
return idle;
}
/**
* <p>
* Wait for idle state. As this is a blocking call, you should not call
* it from the main UI thread. If you do so and debug mode is enabled,
* this method will intentionally crash your app.
* </p>
* <p>
* If not interrupted, this method will not return until all commands
* have finished executing. Note that this does not necessarily mean
* that all the callbacks have fired yet.
* </p>
* <p>
* If no Handler is used, all callbacks will have been executed when
* this method returns. If a Handler is used, and this method is called
* from a different thread than associated with the Handler's Looper,
* all callbacks will have been executed when this method returns as
* well. If however a Handler is used but this method is called from the
* same thread as associated with the Handler's Looper, there is no way
* to know.
* </p>
* <p>
* In practice this means that in most simple cases all callbacks will
* have completed when this method returns, but if you actually depend
* on this behavior, you should make certain this is indeed the case.
* </p>
* <p>
* See {@link Shell.Interactive} for further details on threading and
* handlers
* </p>
*
* @return True if wait complete, false if wait interrupted
*/
public boolean waitForIdle() {
if (Debug.getSanityChecksEnabledEffective() && Debug.onMainThread()) {
Debug.log(ShellOnMainThreadException.EXCEPTION_WAIT_IDLE);
throw new ShellOnMainThreadException(ShellOnMainThreadException.EXCEPTION_WAIT_IDLE);
}
if (isRunning()) {
synchronized (idleSync) {
while (!idle) {
try {
idleSync.wait();
} catch (InterruptedException e) {
return false;
}
}
}
if ((handler != null) &&
(handler.getLooper() != null) &&
(handler.getLooper() != Looper.myLooper())) {
// If the callbacks are posted to a different thread than
// this one, we can wait until all callbacks have called
// before returning. If we don't use a Handler at all, the
// callbacks are already called before we get here. If we do
// use a Handler but we use the same Looper, waiting here
// would actually block the callbacks from being called
synchronized (callbackSync) {
while (callbacks > 0) {
try {
callbackSync.wait();
} catch (InterruptedException e) {
return false;
}
}
}
}
}
return true;
}
/**
* Are we using a Handler to post callbacks ?
*
* @return Handler used ?
*/
public boolean hasHandler() {
return (handler != null);
}
}
}
|
aravindsagar/SmartLockScreen
|
libsuperuser/src/eu/chainfire/libsuperuser/Shell.java
|
Java
|
apache-2.0
| 66,888 |
#region License(Apache Version 2.0)
/******************************************
* Copyright ®2017-Now WangHuaiSheng.
* 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.
* Detail: https://github.com/WangHuaiSheng/WitsWay/LICENSE
* ***************************************/
#endregion
#region ChangeLog
/******************************************
* 2017-10-7 OutMan Create
*
* ***************************************/
#endregion
using System;
namespace WitsWay.Utilities.Thread
{
/// <summary>
/// 锁对象
/// </summary>
public class LockObject
{
private volatile bool _initing;
private readonly object _executeLock = new object();
/// <summary>
/// 锁定执行
/// </summary>
/// <param name="action">执行方法</param>
public void LockExecute(Action action)
{
if (!_initing)
{
lock (_executeLock)
{
if (_initing != true)
{
action();
}
_initing = true;
}
}
_initing = false;
}
}
}
|
wanghuaisheng/WitsWay
|
Solutions/AppUtilities/Utilities/Thread/LockObject.cs
|
C#
|
apache-2.0
| 1,682 |