code
stringlengths 4
1.01M
| language
stringclasses 2
values |
|---|---|
set AUTH_TOKEN=123456& ^
set HTTP_PORT=8080& ^
set MQTT_URL=mqtt://localhost& ^
set MQTT_USER=user ^
set MQTT_PASS=pass ^
set DOMAIN=infra& ^
set TLD=ictu& ^
set SCRIPT_BASE_DIR=X:\mnt\data\scripts& ^
set DATA_DIR=X:\mnt\data& ^
set PIPEWORKS_CMD=eth0 -i eth0 @CONTAINER_NAME@ dhclient& ^
nodemon index.coffee
|
Java
|
# AUTOGENERATED FILE
FROM balenalib/qemux86-64-alpine:3.13-run
ENV GO_VERSION 1.16.3
# set up nsswitch.conf for Go's "netgo" implementation
# - https://github.com/golang/go/blob/go1.9.1/src/net/conf.go#L194-L275
# - docker run --rm debian:stretch grep '^hosts:' /etc/nsswitch.conf
RUN [ ! -e /etc/nsswitch.conf ] && echo 'hosts: files dns' > /etc/nsswitch.conf
# gcc for cgo
RUN apk add --no-cache git gcc ca-certificates
RUN fetchDeps='curl' \
&& set -x \
&& apk add --no-cache $fetchDeps \
&& mkdir -p /usr/local/go \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/golang/v$GO_VERSION/go$GO_VERSION.linux-alpine-amd64.tar.gz" \
&& echo "10d1c63534be387026f37a3ac3ed00c7258dfbc3ed40255956bc736cf8b3bf3b go$GO_VERSION.linux-alpine-amd64.tar.gz" | sha256sum -c - \
&& tar -xzf "go$GO_VERSION.linux-alpine-amd64.tar.gz" -C /usr/local/go --strip-components=1 \
&& rm -f go$GO_VERSION.linux-alpine-amd64.tar.gz
ENV GOROOT /usr/local/go
ENV GOPATH /go
ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH
RUN mkdir -p "$GOPATH/src" "$GOPATH/bin" && chmod -R 777 "$GOPATH"
WORKDIR $GOPATH
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@golang.sh" \
&& echo "Running test-stack@golang" \
&& chmod +x test-stack@golang.sh \
&& bash test-stack@golang.sh \
&& rm -rf test-stack@golang.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: Intel 64-bit (x86-64) \nOS: Alpine Linux 3.13 \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nGo v1.16.3 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo $'#!/bin/bash\nbalena-info\nbusybox ln -sf /bin/busybox /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& ln -f /bin/sh /bin/sh.real \
&& ln -f /bin/sh-shim /bin/sh
|
Java
|
'use strict';
viewModel.MonitoringAlarm = new Object();
var ma = viewModel.MonitoringAlarm;
ma.minDatetemp = new Date();
ma.maxDatetemp = new Date();
ma.minDateRet = new Date();
ma.maxDateRet = new Date();
vm.currentMenu('Alarm Data');
vm.currentTitle('Alarm Data');
vm.isShowDataAvailability(false);
vm.breadcrumb([
{ title: "Monitoring", href: '#' },
{ title: 'Alarm Data', href: viewModel.appName + 'page/monitoringalarm' }]);
var intervalTurbine = null;
ma.UpdateProjectList = function(project) {
setTimeout(function(){
$('#projectList').data('kendoDropDownList').value(project);
$("#projectList").data("kendoDropDownList").trigger("change");
},1000)
}
ma.UpdateTurbineList = function(turbineList) {
if(turbineList.length == 0){
$("#turbineList").multiselect('selectAll', false).multiselect("refresh");
}else{
$('#turbineList').multiselect("deselectAll", false).multiselect("refresh");
$('#turbineList').multiselect('select', turbineList);
}
}
ma.CreateGrid = function(gridType) {
app.loading(true);
$.when(fa.LoadData()).done(function () {
var COOKIES = {};
var cookieStr = document.cookie;
var param = {
period: fa.period,
dateStart: fa.dateStart,
dateEnd: fa.dateEnd,
turbine: [],
project: "",
tipe: gridType,
};
if(localStorage.getItem("projectname") !== null && localStorage.getItem("turbine") !== null) {
var locTurbine = localStorage.getItem("turbine");
param.turbine = locTurbine == "" ? [] : [locTurbine];
param.project = localStorage.getItem("projectname");
var tabActive = localStorage.getItem("tabActive");
$.when(ma.UpdateProjectList(param.project)).done(function () {
setTimeout(function(){
ma.UpdateTurbineList(param.turbine);
setTimeout(function() {
ma.LoadDataAvail(param.project, gridType);
if(tabActive !== null){
if(tabActive == "alarmRaw" ){
$("#alarmrawTab a:first-child").trigger('click');
}else{
ma.CreateGridAlarm(gridType, param);
}
}
},500);
app.resetLocalStorage();
}, 1500);
});
} else {
param.turbine = fa.turbine();
param.project = fa.project;
ma.CreateGridAlarm(gridType, param);
}
});
}
ma.buildParentFilter = function(filters, additionalFilter) {
$.each(filters, function(idx, val){
if(val.filter !== undefined) {
ma.buildParentFilter(val.filter.filters, additionalFilter)
}
additionalFilter.push(val);
});
}
ma.CreateGridAlarm = function(gridType, param) {
var gridName = "#alarmGrid"
var dt = new Date();
var time = dt.getHours() + "" + dt.getMinutes() + "" + dt.getSeconds();
var nameFile = "Monitoring Alarm Down_"+ moment(new Date()).format("Y-M-D")+"_"+time;
var defaultsort = [ { field: "TimeStart", dir: "desc" }, { field: "TimeEnd", dir: "asc" } ]
var url = viewModel.appName + "monitoringrealtime/getdataalarm";
if(gridType == "warning") {
gridName = "#warningGrid"
nameFile = "Monitoring Alarm Warning";
}
if(gridType == "alarmraw"){
gridName = "#alarmRawGrid"
nameFile = "Monitoring Alarm Raw";
defaultsort = [ { field: "TimeStamp", dir: "desc" } ]
}
var columns = [{
field: "turbine",
title: "Turbine",
attributes: {
style: "text-align:center;"
},
filterable: false,
width: 90
}, {
field: "timestart",
title: "Time Start",
width: 170,
filterable: false,
attributes: {
style: "text-align:center;"
},
template: "#= moment.utc(data.timestart).format('DD-MMM-YYYY') # #=moment.utc(data.timestart).format('HH:mm:ss')#"
}, {
field: "timeend",
title: "Time End",
width: 170,
filterable: false,
attributes: {
style: "text-align:center;"
},
template: "#= (moment.utc(data.timeend).format('DD-MM-YYYY') == '01-01-0001'?'Not yet finished' : (moment.utc(data.timeend).format('DD-MMM-YYYY') # #=moment.utc(data.timeend).format('HH:mm:ss')))#"
}, {
field: "duration",
title: "Duration (hh:mm:ss)",
width: 120,
attributes: {
style: "text-align:center;"
},
filterable: false,
//template: "#= time(data.duration) #"
template: '#= kendo.toString(secondsToTime(data.duration)) #',
}, {
field: "alarmcode",
title: "Alarm Code",
attributes: {
style: "text-align:center;"
},
filterable: {
operators: {
string: {
eq: "Is equal to"
}
},
ui: function(element) {
var form = element.closest("form");
form.find(".k-filter-help-text:first").text("Show items equal to:");
form.find("select").remove();
$("form").find("[data-bind='value:filters[0].value']").addClass('k-textbox');
}
},
width: 90,
},{
field: "alarmdesc",
title: "Description",
width: 330,
}];
if(gridType == "alarm"){
columns.push({
field: "reduceavailability",
title: "Reduce Avail.",
attributes: {
style: "text-align:center;"
},
filterable: false,
width: 90,
});
}
if(gridType == "alarmraw"){
columns = [{
field: "turbine",
title: "Turbine",
attributes: {
style: "text-align:center;"
},
filterable: false,
width: 70
}, {
field: "timestamp",
title: "Timestamp",
width: 120,
attributes: {
style: "text-align:center;"
},
filterable: false,
template: "#= moment.utc(data.timestamp).format('DD-MMM-YYYY') # #=moment.utc(data.timestamp).format('HH:mm:ss')#"
}, {
field: "tag",
title: "Tag",
width: 120,
filterable: false,
attributes: {
style: "text-align:center;"
},
}, {
field: "value",
title: "Value",
attributes: {
style: "text-align:center;"
},
filterable: false,
width: 70,
// template: "#= kendo.toString(data.Timestamp,'n2') #"
}, {
field: "description",
title: "Description",
width: 200
}, {
field: "addinfo",
title: "Note",
filterable: false,
width: 250
}];
}
$(gridName).html('');
$(gridName).kendoGrid({
dataSource: {
serverPaging: true,
serverSorting: true,
serverFiltering: true,
transport: {
read: {
url: url,
type: "POST",
data: param,
dataType: "json",
contentType: "application/json; charset=utf-8",
},
parameterMap: function(options) {
var additionalFilter = [];
if(options.filter !== undefined && options.filter != null) {
ma.buildParentFilter(options.filter.filters, additionalFilter)
}
if (additionalFilter.length > 0) {
options["filter"] = additionalFilter;
}
return JSON.stringify(options);
}
},
schema: {
data: function data(res) {
if (!app.isFine(res)) {
return;
}
var totalFreq = res.data.Total;
var totalHour = res.data.Duration;
ma.minDateRet = new Date(res.data.mindate);
ma.maxDateRet = new Date(res.data.maxdate);
ma.checkCompleteDate()
$('#alarm_duration').text((totalHour/3600).toFixed(2));
$('#alarm_frequency').text(totalFreq);
setTimeout(function(){
app.loading(false);
}, 300)
return res.data.Data;
},
total: function data(res) {
return res.data.Total;
}
},
pageSize: 10,
sort: defaultsort,
},
// toolbar: ["excel"],
excel: {
fileName: nameFile+".xlsx",
filterable: true,
allPages: true
},
// pdf: {
// fileName: nameFile+".pdf",
// },
sortable: true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
filterable: {
extra: false,
operators: {
string: {
contains: "Contains",
eq: "Is equal to"
},
}
},
columns: columns
});
};
function secondsToTime(d) {
d = Number(d);
var h = Math.floor(d / 3600);
var m = Math.floor(d % 3600 / 60);
var s = Math.floor(d % 3600 % 60);
var res = (h > 0 ? (h < 10 ? "0" + h : h) : "00") + ":" + (m > 0 ? (m < 10 ? "0" + m : m) : "00") + ":" + (s > 0 ? s : "00")
return res;
}
function time(s) {
return new Date(s * 1e3).toISOString().slice(-13, -5);
}
ma.InitDateValue = function () {
var maxDateData = new Date();
var lastStartDate = new Date(Date.UTC(moment(maxDateData).get('year'), maxDateData.getMonth(), maxDateData.getDate(), 0, 0, 0, 0));
var lastEndDate = new Date(Date.UTC(moment(maxDateData).get('year'), maxDateData.getMonth(), maxDateData.getDate(), 0, 0, 0, 0));
$('#dateStart').data('kendoDatePicker').value(lastStartDate);
$('#dateEnd').data('kendoDatePicker').value(lastEndDate);
}
ma.LoadDataAvail = function(projectname, gridType){
//fa.LoadData();
var payload = {
project: projectname,
tipe: gridType
};
toolkit.ajaxPost(viewModel.appName + "monitoringrealtime/getdataalarmavaildate", payload, function (res) {
if (!app.isFine(res)) {
return;
}
if (res.data.Data.length == 0) {
res.data.Data = [];
} else {
if (res.data.Data.length > 0) {
ma.minDatetemp = new Date(res.data.Data[0]);
ma.maxDatetemp = new Date(res.data.Data[1]);
app.currentDateData = new Date(res.data.Data[1]);
$('#availabledatestart').html(kendo.toString(moment.utc(ma.minDatetemp).format('DD-MMMM-YYYY')));
$('#availabledateend').html(kendo.toString(moment.utc(ma.maxDatetemp).format('DD-MMMM-YYYY')));
// $('#dateStart').data('kendoDatePicker').value( new Date(Date.UTC(moment( ma.maxDatetemp).get('year'), ma.maxDatetemp.getMonth(), ma.maxDatetemp.getDate() - 7, 0, 0, 0, 0)));
// $('#dateEnd').data('kendoDatePicker').value(kendo.toString(moment.utc(res.data.Data[1]).format('DD-MMM-YYYY')));
ma.checkCompleteDate();
}
}
});
}
ma.checkCompleteDate = function () {
var currentDateData = moment.utc(ma.maxDatetemp).format('YYYY-MM-DD');
var prevDateData = moment.utc(ma.minDatetemp).format('YYYY-MM-DD');
var dateStart = moment.utc(ma.minDateRet).format('YYYY-MM-DD');
var dateEnd = moment.utc(ma.maxDateRet).format('YYYY-MM-DD');
if ((dateEnd > currentDateData) || (dateStart > currentDateData)) {
fa.infoPeriodIcon(true);
} else if ((dateEnd < prevDateData) || (dateStart < prevDateData)) {
fa.infoPeriodIcon(true);
} else {
fa.infoPeriodIcon(false);
fa.infoPeriodRange("");
}
}
ma.ToByProject = function(){
setTimeout(function(){
app.loading(true);
app.resetLocalStorage();
var project = $('#projectList').data('kendoDropDownList').value();
localStorage.setItem('projectname', project);
if(localStorage.getItem("projectname")){
window.location = viewModel.appName + "page/monitoringbyproject";
}
},1500);
}
ma.exportToExcel = function(id){
$("#"+id).getKendoGrid().saveAsExcel();
}
$(document).ready(function(){
$('#btnRefresh').on('click', function () {
fa.checkTurbine();
if($('.nav').find('li.active').find('a.tab-custom').text() == "Alarm Down") {
ma.CreateGrid("alarm");
} else if($('.nav').find('li.active').find('a.tab-custom').text() == "Alarm Warning") {
ma.CreateGrid("warning");
}else{
ma.CreateGrid("alarmraw");
}
});
//setTimeout(function() {
$.when(ma.InitDateValue()).done(function () {
setTimeout(function() {
ma.CreateGrid("alarm");
ma.LoadDataAvail(fa.project, "alarm");
}, 100);
});
//}, 300);
$('#projectList').kendoDropDownList({
change: function () {
var project = $('#projectList').data("kendoDropDownList").value();
fa.populateTurbine(project);
ma.LoadDataAvail(project, "alarm");
}
});
});
|
Java
|
/*
* Copyright 2015 Matthew Timmermans
*
* 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.nobigsoftware.dfalex;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import static backport.java.util.function.BackportFuncs.computeIfAbsent;
/**
* Turns an NFA into a non-minimal RawDfa by powerset construction
*/
class DfaFromNfa<RESULT> {
//inputs
private final Nfa<RESULT> m_nfa;
private final int[] m_nfaStartStates;
private final int[] m_dfaStartStates;
private final DfaAmbiguityResolver<? super RESULT> m_ambiguityResolver;
//utility
private final DfaStateSignatureCodec m_dfaSigCodec = new DfaStateSignatureCodec();
//These fields are scratch space
private final IntListKey m_tempStateSignature = new IntListKey();
private final ArrayDeque<Integer> m_tempNfaClosureList = new ArrayDeque<>();
private final HashSet<RESULT> m_tempResultSet = new HashSet<RESULT>();
//accumulators
private final HashMap<RESULT, Integer> m_acceptSetMap = new HashMap<>();
private final ArrayList<RESULT> m_acceptSets = new ArrayList<>();
private final HashMap<IntListKey, Integer> m_dfaStateSignatureMap = new HashMap<>();
private final ArrayList<IntListKey> m_dfaStateSignatures = new ArrayList<>();
private final ArrayList<DfaStateInfo> m_dfaStates = new ArrayList<>();
public DfaFromNfa(Nfa<RESULT> nfa, int[] nfaStartStates,
DfaAmbiguityResolver<? super RESULT> ambiguityResolver) {
m_nfa = nfa;
m_nfaStartStates = nfaStartStates;
m_dfaStartStates = new int[nfaStartStates.length];
m_ambiguityResolver = ambiguityResolver;
m_acceptSets.add(null);
_build();
}
public RawDfa<RESULT> getDfa() {
return new RawDfa<>(m_dfaStates, m_acceptSets, m_dfaStartStates);
}
private void _build() {
final CompactIntSubset nfaStateSet = new CompactIntSubset(m_nfa.numStates());
final ArrayList<NfaTransition> dfaStateTransitions = new ArrayList<>();
final ArrayList<NfaTransition> transitionQ = new ArrayList<>(1000);
//Create the DFA start states
for (int i = 0; i < m_dfaStartStates.length; ++i) {
nfaStateSet.clear();
_addNfaStateAndEpsilonsToSubset(nfaStateSet, m_nfaStartStates[i]);
m_dfaStartStates[i] = _getDfaState(nfaStateSet);
}
//Create the transitions and other DFA states.
//m_dfaStateSignatures grows as we discover new states.
//m_dfaStates grows as we complete them
for (int stateNum = 0; stateNum < m_dfaStateSignatures.size(); ++stateNum) {
final IntListKey dfaStateSig = m_dfaStateSignatures.get(stateNum);
dfaStateTransitions.clear();
//For each DFA state, combine the NFA transitions for each
//distinct character range into a DFA transiton, appending new DFA states
//as we discover them.
transitionQ.clear();
//dump all the NFA transitions for the state into the Q
DfaStateSignatureCodec.expand(dfaStateSig,
state -> m_nfa.forStateTransitions(state, transitionQ::add));
//sort all the transitions by first character
Collections.sort(transitionQ, (arg0, arg1) -> {
if (arg0.m_firstChar != arg1.m_firstChar) {
return (arg0.m_firstChar < arg1.m_firstChar ? -1 : 1);
}
return 0;
});
final int tqlen = transitionQ.size();
//first character we haven't accounted for yet
char minc = 0;
//NFA transitions at index < tqstart are no longer relevant
//NFA transitions at index >= tqstart are in first char order OR have first char <= minc
//The sequence of NFA transitions contributing the the previous DFA transition starts here
int tqstart = 0;
//make a range of NFA transitions corresponding to the next DFA transition
while (tqstart < tqlen) {
NfaTransition trans = transitionQ.get(tqstart);
if (trans.m_lastChar < minc) {
++tqstart;
continue;
}
//INVAR - trans contributes to the next DFA transition
nfaStateSet.clear();
_addNfaStateAndEpsilonsToSubset(nfaStateSet, trans.m_stateNum);
char startc = trans.m_firstChar;
char endc = trans.m_lastChar;
if (startc < minc) {
startc = minc;
}
//make range of all transitions that include the start character, removing ones
//that drop out
for (int tqend = tqstart + 1; tqend < tqlen; ++tqend) {
trans = transitionQ.get(tqend);
if (trans.m_lastChar < startc) {
//remove this one
transitionQ.set(tqend, transitionQ.get(tqstart++));
continue;
}
if (trans.m_firstChar > startc) {
//this one is for the next transition
if (trans.m_firstChar <= endc) {
endc = (char) (trans.m_firstChar - 1);
}
break;
}
//this one counts
if (trans.m_lastChar < endc) {
endc = trans.m_lastChar;
}
_addNfaStateAndEpsilonsToSubset(nfaStateSet, trans.m_stateNum);
}
dfaStateTransitions.add(new NfaTransition(startc, endc, _getDfaState(nfaStateSet)));
minc = (char) (endc + 1);
if (minc < endc) {
//wrapped around
break;
}
}
//INVARIANT: m_dfaStatesOut.size() == stateNum
m_dfaStates.add(_createStateInfo(dfaStateSig, dfaStateTransitions));
}
}
//Add an NFA state to m_currentNFASubset, along with the transitive
//closure over its epsilon transitions
private void _addNfaStateAndEpsilonsToSubset(CompactIntSubset dest, int stateNum) {
m_tempNfaClosureList.clear();
if (dest.add(stateNum)) {
m_tempNfaClosureList.add(stateNum);
}
Integer newNfaState;
while ((newNfaState = m_tempNfaClosureList.poll()) != null) {
m_nfa.forStateEpsilons(newNfaState, (Integer src) -> {
if (dest.add(src)) {
m_tempNfaClosureList.add(src);
}
});
}
}
private void _addNfaStateToSignatureCodec(int stateNum) {
if (m_nfa.hasTransitionsOrAccepts(stateNum)) {
m_dfaSigCodec.acceptInt(stateNum);
}
}
//Make a DFA state for a set of simultaneous NFA states
private Integer _getDfaState(CompactIntSubset nfaStateSet) {
//dump state combination into compressed form
m_tempStateSignature.clear();
m_dfaSigCodec.start(m_tempStateSignature::add, nfaStateSet.getSize(),
nfaStateSet.getRange());
nfaStateSet.dumpInOrder(this::_addNfaStateToSignatureCodec);
m_dfaSigCodec.finish();
//make sure it's in the map
Integer dfaStateNum = m_dfaStateSignatureMap.get(m_tempStateSignature);
if (dfaStateNum == null) {
dfaStateNum = m_dfaStateSignatures.size();
IntListKey newSig = new IntListKey(m_tempStateSignature);
m_dfaStateSignatures.add(newSig);
m_dfaStateSignatureMap.put(newSig, dfaStateNum);
}
return dfaStateNum;
}
@SuppressWarnings("unchecked")
private DfaStateInfo _createStateInfo(IntListKey sig, List<NfaTransition> transitions) {
//calculate the set of accepts
m_tempResultSet.clear();
DfaStateSignatureCodec.expand(sig, nfastate -> {
RESULT accept = m_nfa.getAccept(nfastate);
if (accept != null) {
m_tempResultSet.add(accept);
}
});
//and get an accept set index for it
RESULT dfaAccept = null;
if (m_tempResultSet.size() > 1) {
dfaAccept = (RESULT) m_ambiguityResolver.apply(m_tempResultSet);
} else if (!m_tempResultSet.isEmpty()) {
dfaAccept = m_tempResultSet.iterator().next();
}
int acceptSetIndex = 0;
if (dfaAccept != null) {
acceptSetIndex = computeIfAbsent(m_acceptSetMap, dfaAccept, keyset -> {
m_acceptSets.add(keyset);
return m_acceptSets.size() - 1;
});
}
return new DfaStateInfo(transitions, acceptSetIndex);
}
}
|
Java
|
package com.emc.ecs.servicebroker.repository;
import com.emc.ecs.servicebroker.exception.EcsManagementClientException;
import com.emc.ecs.servicebroker.service.s3.S3Service;
import com.emc.ecs.servicebroker.model.Constants;
import com.emc.object.s3.bean.GetObjectResult;
import com.emc.object.s3.bean.ListObjectsResult;
import com.emc.object.s3.bean.S3Object;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.servicebroker.model.binding.SharedVolumeDevice;
import org.springframework.cloud.servicebroker.model.binding.VolumeDevice;
import org.springframework.cloud.servicebroker.model.binding.VolumeMount;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static java.lang.String.format;
@SuppressWarnings("unused")
public class ServiceInstanceBindingRepository {
static final Logger logger = LoggerFactory.getLogger(ServiceInstanceBindingRepository.class);
public static final String FILENAME_PREFIX = "service-instance-binding";
private final ObjectMapper objectMapper = new ObjectMapper();
{
// NOTE -- ideally we would not need this code, but for now, the VolumeMount class has
// custom serialization that is not matched with corresponding deserialization, so
// deserializing serialized volume mounts doesn't work OOTB.
SimpleModule module = new SimpleModule();
module.addDeserializer(VolumeMount.DeviceType.class, new DeviceTypeDeserializer());
module.addDeserializer(VolumeMount.Mode.class, new ModeDeserializer());
module.addDeserializer(VolumeDevice.class, new VolumeDeviceDeserializer());
objectMapper.registerModule(module);
}
@Autowired
private S3Service s3;
private static String getFilename(String id) {
return FILENAME_PREFIX + "/" + id + ".json";
}
private static boolean isCorrectFilename (String filename) {
return filename.matches(FILENAME_PREFIX + "/.*\\.json");
}
private ServiceInstanceBinding findByFilename(String filename) throws IOException {
if (!isCorrectFilename(filename)) {
String errorMessage = format("Invalid filename of service instance binding provided: %s", filename);
throw new IOException(errorMessage);
}
logger.debug("Loading service instance binding from repository file {}", filename);
GetObjectResult<InputStream> input = s3.getObject(filename);
return objectMapper.readValue(input.getObject(), ServiceInstanceBinding.class);
}
ServiceInstanceBinding removeSecretCredentials(ServiceInstanceBinding binding) {
Map<String, Object> credentials = binding.getCredentials();
credentials.remove(Constants.S3_URL);
credentials.remove(Constants.CREDENTIALS_SECRET_KEY);
binding.setCredentials(credentials);
return binding;
}
@PostConstruct
public void initialize() throws EcsManagementClientException {
logger.info("Service binding file prefix: {}", FILENAME_PREFIX);
}
public void save(ServiceInstanceBinding binding) throws IOException {
String filename = getFilename(binding.getBindingId());
String serialized = objectMapper.writeValueAsString(binding);
s3.putObject(filename, serialized);
}
public ServiceInstanceBinding find(String id) throws IOException {
String filename = getFilename(id);
return findByFilename(filename);
}
public ListServiceInstanceBindingsResponse listServiceInstanceBindings(String marker, int pageSize) throws IOException {
if (pageSize < 0) {
throw new IOException("Page size could not be negative number");
}
List<ServiceInstanceBinding> bindings = new ArrayList<>();
ListObjectsResult list = marker != null ?
s3.listObjects(FILENAME_PREFIX + "/", getFilename(marker), pageSize) :
s3.listObjects(FILENAME_PREFIX + "/", null, pageSize);
for (S3Object s3Object: list.getObjects()) {
String filename = s3Object.getKey();
if (isCorrectFilename(filename)) {
ServiceInstanceBinding binding = findByFilename(filename);
bindings.add(removeSecretCredentials(binding));
}
}
ListServiceInstanceBindingsResponse response = new ListServiceInstanceBindingsResponse(bindings);
response.setMarker(list.getMarker());
response.setPageSize(list.getMaxKeys());
response.setNextMarker(list.getNextMarker());
return response;
}
public void delete(String id) {
String filename = getFilename(id);
s3.deleteObject(filename);
}
public static class ModeDeserializer extends StdDeserializer<VolumeMount.Mode> {
ModeDeserializer() {
this(null);
}
ModeDeserializer(Class<?> vc) {
super(vc);
}
@Override
public VolumeMount.Mode deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
JsonNode node = jp.getCodec().readTree(jp);
String s = node.asText();
if (s.equals("rw")) {
return VolumeMount.Mode.READ_WRITE;
} else {
return VolumeMount.Mode.READ_ONLY;
}
}
}
public static class DeviceTypeDeserializer extends StdDeserializer<VolumeMount.DeviceType> {
DeviceTypeDeserializer() {
this(null);
}
DeviceTypeDeserializer(Class<?> vc) {
super(vc);
}
@Override
public VolumeMount.DeviceType deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
return VolumeMount.DeviceType.SHARED;
}
}
public static class VolumeDeviceDeserializer extends StdDeserializer<VolumeDevice> {
VolumeDeviceDeserializer() {
this(null);
}
VolumeDeviceDeserializer(Class<?> vc) {
super(vc);
}
@Override
public VolumeDevice deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
return jp.getCodec().readValue(jp, SharedVolumeDevice.class);
}
}
}
|
Java
|
<html dir="LTR">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
<title>RepositoryAttribute Constructor (String)</title>
<xml>
</xml>
<link rel="stylesheet" type="text/css" href="MSDN.css" />
</head>
<body id="bodyID" class="dtBODY">
<div id="nsbanner">
<div id="bannerrow1">
<table class="bannerparthead" cellspacing="0">
<tr id="hdr">
<td class="runninghead">Apache log4net SDK Documentation - Microsoft .NET Framework 4.0</td>
<td class="product">
</td>
</tr>
</table>
</div>
<div id="TitleRow">
<h1 class="dtH1">RepositoryAttribute Constructor (String)</h1>
</div>
</div>
<div id="nstext">
<p> Initialize a new instance of the <a href="log4net.Config.RepositoryAttribute.html">RepositoryAttribute</a> class with the name of the repository. </p>
<div class="syntax">
<span class="lang">[Visual Basic]</span>
<br />Overloads Public Sub New( _<br /> ByVal <i>name</i> As <a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrfSystemStringClassTopic.htm">String</a> _<br />)</div>
<div class="syntax">
<span class="lang">[C#]</span>
<br />public RepositoryAttribute(<br /> <a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrfSystemStringClassTopic.htm">string</a> <i>name</i><br />);</div>
<h4 class="dtH4">Parameters</h4>
<dl>
<dt>
<i>name</i>
</dt>
<dd>The name of the repository.</dd>
</dl>
<h4 class="dtH4">Remarks</h4>
<p> Initialize the attribute with the name for the assembly's repository. </p>
<h4 class="dtH4">See Also</h4><p><a href="log4net.Config.RepositoryAttribute.html">RepositoryAttribute Class</a> | <a href="log4net.Config.html">log4net.Config Namespace</a> | <a href="log4net.Config.RepositoryAttributeConstructor.html">RepositoryAttribute Constructor Overload List</a></p><hr /><div id="footer"><a href='http://logging.apache.org/log4net/'>Copyright 2004-2013 The Apache Software Foundation.</a><br></br>Apache log4net, Apache and log4net are trademarks of The Apache Software Foundation.</div></div>
</body>
</html>
|
Java
|
# -*- coding: UTF-8 -*-
from __future__ import unicode_literals, print_function, division
|
Java
|
/*
* Copyright (c) 2016 Snowplow Analytics Ltd. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package com.snowplowanalytics.kinesistee.config
import java.util
import awscala.dynamodbv2.{AttributeValue, DynamoDB}
import com.amazonaws.services.dynamodbv2.model.{QueryRequest, QueryResult}
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
class ConfigurationBuilderSpec extends Specification with Mockito {
val sampleGoodConfig = scala.io.Source.fromURL(getClass.getResource("/sample_self_describing_config.json")).mkString
val sampleConfig = Configuration(name = "My Kinesis Tee example",
targetStream = TargetStream("my-target-stream", None),
transformer = Some(Transformer(BuiltIn.SNOWPLOW_TO_NESTED_JSON)),
filter = None)
"A valid configuration" should {
"generate the correct case class" in {
ConfigurationBuilder.build(sampleGoodConfig) mustEqual sampleConfig
}
}
"An invalid JSON configuration" should {
"throw an exception" in {
ConfigurationBuilder.build("banana") must throwA[IllegalArgumentException]
}
}
"A configuration that doesn't match the given schema" should {
"throw an exception" in {
ConfigurationBuilder.build(
"""
|{
| "schema": "com.thing",
| "data": { "foo":"bar" }
|}
""".stripMargin) must throwA(new IllegalArgumentException("Invalid configuration"))
}
}
"Loading from DynamoDB" should {
val sampleConfigTableName = "config-table-sample-name"
"load a configuration using dynamodb and the specified table name" in {
implicit val dynamoDB = mock[DynamoDB]
val res = mock[QueryResult]
val items:util.List[java.util.Map[java.lang.String,com.amazonaws.services.dynamodbv2.model.AttributeValue]] = new util.ArrayList()
val one:util.Map[String,com.amazonaws.services.dynamodbv2.model.AttributeValue] = new util.HashMap()
one.put("id", new AttributeValue(Some("with-id")))
one.put("configuration", new AttributeValue(Some(sampleGoodConfig)))
items.add(one)
res.getItems returns items
dynamoDB.query(any[QueryRequest]) returns res
ConfigurationBuilder.build(sampleConfigTableName, "with-id") mustEqual sampleConfig
}
"give a good error if the table doesn't have a matching entry" in {
implicit val dynamoDB = mock[DynamoDB]
val res = mock[QueryResult]
val items:util.List[java.util.Map[java.lang.String,com.amazonaws.services.dynamodbv2.model.AttributeValue]] = new util.ArrayList()
res.getItems returns items
dynamoDB.query(any[QueryRequest]) returns res
ConfigurationBuilder.build(sampleConfigTableName, "with-id") must throwA(new IllegalStateException(s"No configuration in table '$sampleConfigTableName' for lambda 'with-id'!"))
}
"give a good error if the table doesn't have the right keys (id and configuration)" in {
implicit val dynamoDB = mock[DynamoDB]
val res = mock[QueryResult]
val items:util.List[java.util.Map[java.lang.String,com.amazonaws.services.dynamodbv2.model.AttributeValue]] = new util.ArrayList()
val one:util.Map[String,com.amazonaws.services.dynamodbv2.model.AttributeValue] = new util.HashMap()
one.put("id", new AttributeValue(Some("with-id")))
one.put("this-is-not-config", new AttributeValue(Some("abc")))
items.add(one)
res.getItems returns items
dynamoDB.query(any[QueryRequest]) returns res
ConfigurationBuilder.build(sampleConfigTableName, "with-id") must throwA(new IllegalStateException(s"Config table '${sampleConfigTableName}' for lambda 'with-id' is missing a 'configuration' field!"))
}
"do something reasonable if ddb errors" in {
implicit val dynamoDB = mock[DynamoDB]
val exception = new IllegalArgumentException("Query exploded")
dynamoDB.query(any[QueryRequest]) throws exception
// NB IllegalArgumentException is rethrown as IllegalStateException
ConfigurationBuilder.build(sampleConfigTableName, "with-id") must throwA[IllegalStateException](message = "Query exploded")
}
}
}
|
Java
|
/*
ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
2011,2012,2013,2014 Giovanni Di Sirio.
This file is part of ChibiOS/RT.
ChibiOS/RT is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
ChibiOS/RT is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file chheap.c
* @brief Heaps code.
*
* @addtogroup heaps
* @details Heap Allocator related APIs.
* <h2>Operation mode</h2>
* The heap allocator implements a first-fit strategy and its APIs
* are functionally equivalent to the usual @p malloc() and @p free()
* library functions. The main difference is that the OS heap APIs
* are guaranteed to be thread safe.<br>
* @pre In order to use the heap APIs the @p CH_CFG_USE_HEAP option must
* be enabled in @p chconf.h.
* @{
*/
#include "ch.h"
#if CH_CFG_USE_HEAP || defined(__DOXYGEN__)
/*===========================================================================*/
/* Module local definitions. */
/*===========================================================================*/
/*
* Defaults on the best synchronization mechanism available.
*/
#if CH_CFG_USE_MUTEXES || defined(__DOXYGEN__)
#define H_LOCK(h) chMtxLock(&(h)->h_mtx)
#define H_UNLOCK(h) chMtxUnlock(&(h)->h_mtx)
#else
#define H_LOCK(h) chSemWait(&(h)->h_sem)
#define H_UNLOCK(h) chSemSignal(&(h)->h_sem)
#endif
/*===========================================================================*/
/* Module exported variables. */
/*===========================================================================*/
/*===========================================================================*/
/* Module local types. */
/*===========================================================================*/
/*===========================================================================*/
/* Module local variables. */
/*===========================================================================*/
/**
* @brief Default heap descriptor.
*/
static memory_heap_t default_heap;
/*===========================================================================*/
/* Module local functions. */
/*===========================================================================*/
/*===========================================================================*/
/* Module exported functions. */
/*===========================================================================*/
/**
* @brief Initializes the default heap.
*
* @notapi
*/
void _heap_init(void) {
default_heap.h_provider = chCoreAlloc;
default_heap.h_free.h.u.next = (union heap_header *)NULL;
default_heap.h_free.h.size = 0;
#if CH_CFG_USE_MUTEXES || defined(__DOXYGEN__)
chMtxObjectInit(&default_heap.h_mtx);
#else
chSemObjectInit(&default_heap.h_sem, 1);
#endif
}
/**
* @brief Initializes a memory heap from a static memory area.
* @pre Both the heap buffer base and the heap size must be aligned to
* the @p stkalign_t type size.
*
* @param[out] heapp pointer to the memory heap descriptor to be initialized
* @param[in] buf heap buffer base
* @param[in] size heap size
*
* @init
*/
void chHeapObjectInit(memory_heap_t *heapp, void *buf, size_t size) {
union heap_header *hp;
chDbgCheck(MEM_IS_ALIGNED(buf) && MEM_IS_ALIGNED(size));
heapp->h_provider = (memgetfunc_t)NULL;
heapp->h_free.h.u.next = hp = buf;
heapp->h_free.h.size = 0;
hp->h.u.next = NULL;
hp->h.size = size - sizeof(union heap_header);
#if CH_CFG_USE_MUTEXES || defined(__DOXYGEN__)
chMtxObjectInit(&heapp->h_mtx);
#else
chSemObjectInit(&heapp->h_sem, 1);
#endif
}
/**
* @brief Allocates a block of memory from the heap by using the first-fit
* algorithm.
* @details The allocated block is guaranteed to be properly aligned for a
* pointer data type (@p stkalign_t).
*
* @param[in] heapp pointer to a heap descriptor or @p NULL in order to
* access the default heap.
* @param[in] size the size of the block to be allocated. Note that the
* allocated block may be a bit bigger than the requested
* size for alignment and fragmentation reasons.
* @return A pointer to the allocated block.
* @retval NULL if the block cannot be allocated.
*
* @api
*/
void *chHeapAlloc(memory_heap_t *heapp, size_t size) {
union heap_header *qp, *hp, *fp;
if (heapp == NULL)
heapp = &default_heap;
size = MEM_ALIGN_NEXT(size);
qp = &heapp->h_free;
H_LOCK(heapp);
while (qp->h.u.next != NULL) {
hp = qp->h.u.next;
if (hp->h.size >= size) {
if (hp->h.size < size + sizeof(union heap_header)) {
/* Gets the whole block even if it is slightly bigger than the
requested size because the fragment would be too small to be
useful.*/
qp->h.u.next = hp->h.u.next;
}
else {
/* Block bigger enough, must split it.*/
fp = (void *)((uint8_t *)(hp) + sizeof(union heap_header) + size);
fp->h.u.next = hp->h.u.next;
fp->h.size = hp->h.size - sizeof(union heap_header) - size;
qp->h.u.next = fp;
hp->h.size = size;
}
hp->h.u.heap = heapp;
H_UNLOCK(heapp);
return (void *)(hp + 1);
}
qp = hp;
}
H_UNLOCK(heapp);
/* More memory is required, tries to get it from the associated provider
else fails.*/
if (heapp->h_provider) {
hp = heapp->h_provider(size + sizeof(union heap_header));
if (hp != NULL) {
hp->h.u.heap = heapp;
hp->h.size = size;
hp++;
return (void *)hp;
}
}
return NULL;
}
#define LIMIT(p) (union heap_header *)((uint8_t *)(p) + \
sizeof(union heap_header) + \
(p)->h.size)
/**
* @brief Frees a previously allocated memory block.
*
* @param[in] p pointer to the memory block to be freed
*
* @api
*/
void chHeapFree(void *p) {
union heap_header *qp, *hp;
memory_heap_t *heapp;
chDbgCheck(p != NULL);
hp = (union heap_header *)p - 1;
heapp = hp->h.u.heap;
qp = &heapp->h_free;
H_LOCK(heapp);
while (true) {
chDbgAssert((hp < qp) || (hp >= LIMIT(qp)), "within free block");
if (((qp == &heapp->h_free) || (hp > qp)) &&
((qp->h.u.next == NULL) || (hp < qp->h.u.next))) {
/* Insertion after qp.*/
hp->h.u.next = qp->h.u.next;
qp->h.u.next = hp;
/* Verifies if the newly inserted block should be merged.*/
if (LIMIT(hp) == hp->h.u.next) {
/* Merge with the next block.*/
hp->h.size += hp->h.u.next->h.size + sizeof(union heap_header);
hp->h.u.next = hp->h.u.next->h.u.next;
}
if ((LIMIT(qp) == hp)) {
/* Merge with the previous block.*/
qp->h.size += hp->h.size + sizeof(union heap_header);
qp->h.u.next = hp->h.u.next;
}
break;
}
qp = qp->h.u.next;
}
H_UNLOCK(heapp);
return;
}
/**
* @brief Reports the heap status.
* @note This function is meant to be used in the test suite, it should
* not be really useful for the application code.
*
* @param[in] heapp pointer to a heap descriptor or @p NULL in order to
* access the default heap.
* @param[in] sizep pointer to a variable that will receive the total
* fragmented free space
* @return The number of fragments in the heap.
*
* @api
*/
size_t chHeapStatus(memory_heap_t *heapp, size_t *sizep) {
union heap_header *qp;
size_t n, sz;
if (heapp == NULL)
heapp = &default_heap;
H_LOCK(heapp);
sz = 0;
for (n = 0, qp = &heapp->h_free; qp->h.u.next; n++, qp = qp->h.u.next)
sz += qp->h.u.next->h.size;
if (sizep)
*sizep = sz;
H_UNLOCK(heapp);
return n;
}
#endif /* CH_CFG_USE_HEAP */
/** @} */
|
Java
|
# Unona fulva Wall. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
# AUTOGENERATED FILE
FROM balenalib/jetson-tx1-debian:bullseye-run
# remove several traces of debian python
RUN apt-get purge -y python.*
# http://bugs.python.org/issue19846
# > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK.
ENV LANG C.UTF-8
# install python dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates \
netbase \
&& rm -rf /var/lib/apt/lists/*
# key 63C7CC90: public key "Simon McVittie <smcv@pseudorandom.co.uk>" imported
# key 3372DCFA: public key "Donald Stufft (dstufft) <donald@stufft.io>" imported
RUN gpg --batch --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \
&& gpg --batch --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \
&& gpg --batch --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059
ENV PYTHON_VERSION 3.8.12
# if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'"
ENV PYTHON_PIP_VERSION 21.3.1
ENV SETUPTOOLS_VERSION 60.5.4
RUN set -x \
&& buildDeps=' \
curl \
' \
&& apt-get update && apt-get install -y $buildDeps --no-install-recommends && rm -rf /var/lib/apt/lists/* \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-aarch64-libffi3.3.tar.gz" \
&& echo "b04ecc256b15830a76bfcf1a5a4f8b510a10bc094e530df5267cd9e30e9aa955 Python-$PYTHON_VERSION.linux-aarch64-libffi3.3.tar.gz" | sha256sum -c - \
&& tar -xzf "Python-$PYTHON_VERSION.linux-aarch64-libffi3.3.tar.gz" --strip-components=1 \
&& rm -rf "Python-$PYTHON_VERSION.linux-aarch64-libffi3.3.tar.gz" \
&& ldconfig \
&& if [ ! -e /usr/local/bin/pip3 ]; then : \
&& curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \
&& echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \
&& python3 get-pip.py \
&& rm get-pip.py \
; fi \
&& pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \
&& find /usr/local \
\( -type d -a -name test -o -name tests \) \
-o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \
-exec rm -rf '{}' + \
&& cd / \
&& rm -rf /usr/src/python ~/.cache
# make some useful symlinks that are expected to exist
RUN cd /usr/local/bin \
&& ln -sf pip3 pip \
&& { [ -e easy_install ] || ln -s easy_install-* easy_install; } \
&& ln -sf idle3 idle \
&& ln -sf pydoc3 pydoc \
&& ln -sf python3 python \
&& ln -sf python3-config python-config
# set PYTHONPATH to point to dist-packages
ENV PYTHONPATH /usr/lib/python3/dist-packages:$PYTHONPATH
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@python.sh" \
&& echo "Running test-stack@python" \
&& chmod +x test-stack@python.sh \
&& bash test-stack@python.sh \
&& rm -rf test-stack@python.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Debian Bullseye \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.8.12, Pip v21.3.1, Setuptools v60.5.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh
|
Java
|
char *my_strcpy(char *dest, char *src)
{
char *adrr;
for (adrr = dest; *src; *dest++ = *src++);
*dest++ = '\0';
return (adrr);
}
|
Java
|
# AUTOGENERATED FILE
FROM balenalib/surface-go-debian:bullseye-build
ENV NODE_VERSION 17.6.0
ENV YARN_VERSION 1.22.4
RUN for key in \
6A010C5166006599AA17F08146C2130DFD2497F5 \
; do \
gpg --batch --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --batch --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --batch --keyserver keyserver.ubuntu.com --recv-keys "$key" ; \
done \
&& curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-x64.tar.gz" \
&& echo "de9596fda9cc88451d03146278806687e954c03413e8aa0ee98ad46442d6cb1c node-v$NODE_VERSION-linux-x64.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-x64.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-x64.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \
&& gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& mkdir -p /opt/yarn \
&& tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \
&& rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& npm config set unsafe-perm true -g --unsafe-perm \
&& rm -rf /tmp/*
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@node.sh" \
&& echo "Running test-stack@node" \
&& chmod +x test-stack@node.sh \
&& bash test-stack@node.sh \
&& rm -rf test-stack@node.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: Intel 64-bit (x86-64) \nOS: Debian Bullseye \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v17.6.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh
|
Java
|
{-# LANGUAGE TemplateHaskell #-}
-- Copyright (C) 2010-2012 John Millikin <john@john-millikin.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.
module DBusTests.Signature (test_Signature) where
import Test.Chell
import Test.Chell.QuickCheck
import Test.QuickCheck hiding ((.&.), property)
import DBus
import DBusTests.Util
test_Signature :: Suite
test_Signature = suite "Signature"
[ test_BuildSignature
, test_ParseSignature
, test_ParseInvalid
, test_FormatSignature
, test_IsAtom
, test_ShowType
]
test_BuildSignature :: Test
test_BuildSignature = property "signature" prop where
prop = forAll gen_SignatureTypes check
check types = case signature types of
Nothing -> False
Just sig -> signatureTypes sig == types
test_ParseSignature :: Test
test_ParseSignature = property "parseSignature" prop where
prop = forAll gen_SignatureString check
check (s, types) = case parseSignature s of
Nothing -> False
Just sig -> signatureTypes sig == types
test_ParseInvalid :: Test
test_ParseInvalid = assertions "parse-invalid" $ do
-- at most 255 characters
$expect (just (parseSignature (replicate 254 'y')))
$expect (just (parseSignature (replicate 255 'y')))
$expect (nothing (parseSignature (replicate 256 'y')))
-- length also enforced by 'signature'
$expect (just (signature (replicate 255 TypeWord8)))
$expect (nothing (signature (replicate 256 TypeWord8)))
-- struct code
$expect (nothing (parseSignature "r"))
-- empty struct
$expect (nothing (parseSignature "()"))
$expect (nothing (signature [TypeStructure []]))
-- dict code
$expect (nothing (parseSignature "e"))
-- non-atomic dict key
$expect (nothing (parseSignature "a{vy}"))
$expect (nothing (signature [TypeDictionary TypeVariant TypeVariant]))
test_FormatSignature :: Test
test_FormatSignature = property "formatSignature" prop where
prop = forAll gen_SignatureString check
check (s, _) = let
Just sig = parseSignature s
in formatSignature sig == s
test_IsAtom :: Test
test_IsAtom = assertions "IsAtom" $ do
let Just sig = signature []
assertAtom TypeSignature sig
test_ShowType :: Test
test_ShowType = assertions "show-type" $ do
$expect (equal "Bool" (show TypeBoolean))
$expect (equal "Bool" (show TypeBoolean))
$expect (equal "Word8" (show TypeWord8))
$expect (equal "Word16" (show TypeWord16))
$expect (equal "Word32" (show TypeWord32))
$expect (equal "Word64" (show TypeWord64))
$expect (equal "Int16" (show TypeInt16))
$expect (equal "Int32" (show TypeInt32))
$expect (equal "Int64" (show TypeInt64))
$expect (equal "Double" (show TypeDouble))
$expect (equal "UnixFd" (show TypeUnixFd))
$expect (equal "String" (show TypeString))
$expect (equal "Signature" (show TypeSignature))
$expect (equal "ObjectPath" (show TypeObjectPath))
$expect (equal "Variant" (show TypeVariant))
$expect (equal "[Word8]" (show (TypeArray TypeWord8)))
$expect (equal "Dict Word8 (Dict Word8 Word8)" (show (TypeDictionary TypeWord8 (TypeDictionary TypeWord8 TypeWord8))))
$expect (equal "(Word8, Word16)" (show (TypeStructure [TypeWord8, TypeWord16])))
gen_SignatureTypes :: Gen [Type]
gen_SignatureTypes = do
(_, ts) <- gen_SignatureString
return ts
gen_SignatureString :: Gen (String, [Type])
gen_SignatureString = gen where
anyType = oneof [atom, container]
atom = elements
[ ("b", TypeBoolean)
, ("y", TypeWord8)
, ("q", TypeWord16)
, ("u", TypeWord32)
, ("t", TypeWord64)
, ("n", TypeInt16)
, ("i", TypeInt32)
, ("x", TypeInt64)
, ("d", TypeDouble)
, ("h", TypeUnixFd)
, ("s", TypeString)
, ("o", TypeObjectPath)
, ("g", TypeSignature)
]
container = oneof
[ return ("v", TypeVariant)
, array
, dict
, struct
]
array = do
(tCode, tEnum) <- anyType
return ('a':tCode, TypeArray tEnum)
dict = do
(kCode, kEnum) <- atom
(vCode, vEnum) <- anyType
return (concat ["a{", kCode, vCode, "}"], TypeDictionary kEnum vEnum)
struct = do
ts <- listOf1 (halfSized anyType)
let (codes, enums) = unzip ts
return ("(" ++ concat codes ++ ")", TypeStructure enums)
gen = do
types <- listOf anyType
let (codes, enums) = unzip types
let chars = concat codes
if length chars > 255
then halfSized gen
else return (chars, enums)
instance Arbitrary Signature where
arbitrary = do
ts <- gen_SignatureTypes
let Just sig = signature ts
return sig
|
Java
|
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
//
// pch.h
// Header for standard system include files.
//
#pragma once
#include <msxml6.h>
#include <collection.h>
#include <ppltasks.h>
#include <wrl.h>
#include "Common\SuspensionManager.h"
#include "App.xaml.h"
#include <sstream>
|
Java
|
# Gitbook Simple Page TOC Plugin [](https://badge.fury.io/js/gitbook-plugin-simple-page-toc)
This plugin inserts a table of content (TOC) section into your GitBook page. It is powered by the [markdown-toc](https://github.com/jonschlinkert/markdown-toc) library.
## Usage
### Installation
Add the plugin to your `book.json`:
```
{
"plugins" : [ "simple-page-toc" ]
}
```
### Create TOC
Place a `<!-- toc -->` code comment somewhere into your text. Generating your GitBook inserts a table of contents immediately after this comment.
### Optional configuration
You can add the following configuration params to your `book.json`:
```
{
"plugins" : [
"simple-page-toc"
],
"pluginsConfig": {
"simple-page-toc": {
"maxDepth": 3,
"skipFirstH1": true
}
}
}
```
Name | Type | Default | Description
----------- | ------- | ------- | ------------
maxDepth | Number | 3 | Use headings whose depth is at most maxdepth.
skipFirstH1 | Boolean | true | Exclude the first h1-level heading in a file.
## Changelog
* 0.1.0 Releases:
* 0.1.0 First release
* 0.1.1 Fixed invalid config example in README (thanks at15)
* 0.1.2 Fixed bug: Titles with hyphen builds with wrong anchor link
|
Java
|
/*******************************************************************************
* Copyright (C) 2016 Kwaku Twumasi-Afriyie <kwaku.twumasi@quakearts.com>.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Kwaku Twumasi-Afriyie <kwaku.twumasi@quakearts.com> - initial API and implementation
******************************************************************************/
package com.quakearts.webapp.facelets.bootstrap.renderers;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.faces.component.UIColumn;
import javax.faces.component.UIComponent;
import javax.faces.component.UIData;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import com.quakearts.webapp.facelets.bootstrap.components.BootTable;
import com.quakearts.webapp.facelets.bootstrap.renderkit.Attribute;
import com.quakearts.webapp.facelets.bootstrap.renderkit.AttributeManager;
import com.quakearts.webapp.facelets.bootstrap.renderkit.html_basic.HtmlBasicRenderer;
import com.quakearts.webapp.facelets.util.UtilityMethods;
import static com.quakearts.webapp.facelets.bootstrap.renderkit.RenderKitUtils.*;
public class BootTableRenderer extends HtmlBasicRenderer {
private static final Attribute[] ATTRIBUTES =
AttributeManager.getAttributes(AttributeManager.Key.DATATABLE);
@Override
public void encodeBegin(FacesContext context, UIComponent component)
throws IOException {
if (!shouldEncode(component)) {
return;
}
BootTable data = (BootTable) component;
data.setRowIndex(-1);
ResponseWriter writer = context.getResponseWriter();
writer.startElement("table", component);
writer.writeAttribute("id", component.getClientId(context),
"id");
String styleClass = data.get("styleClass");
writer.writeAttribute("class","table "+(styleClass !=null?" "+styleClass:""), "styleClass");
renderHTML5DataAttributes(context, component);
renderPassThruAttributes(context, writer, component,
ATTRIBUTES);
writer.writeText("\n", component, null);
UIComponent caption = getFacet(component, "caption");
if (caption != null) {
String captionClass = data.get("captionClass");
String captionStyle = data.get("captionStyle");
writer.startElement("caption", component);
if (captionClass != null) {
writer.writeAttribute("class", captionClass, "captionClass");
}
if (captionStyle != null) {
writer.writeAttribute("style", captionStyle, "captionStyle");
}
encodeRecursive(context, caption);
writer.endElement("caption");
}
UIComponent colGroups = getFacet(component, "colgroups");
if (colGroups != null) {
encodeRecursive(context, colGroups);
}
BootMetaInfo info = getMetaInfo(context, component);
UIComponent header = getFacet(component, "header");
if (header != null || info.hasHeaderFacets) {
String headerClass = data.get("headerClass");
writer.startElement("thead", component);
writer.writeText("\n", component, null);
if (header != null) {
writer.startElement("tr", header);
writer.startElement("th", header);
if (headerClass != null) {
writer.writeAttribute("class", headerClass, "headerClass");
}
if (info.columns.size() > 1) {
writer.writeAttribute("colspan",
String.valueOf(info.columns.size()), null);
}
writer.writeAttribute("scope", "colgroup", null);
encodeRecursive(context, header);
writer.endElement("th");
writer.endElement("tr");
writer.write("\n");
}
if (info.hasHeaderFacets) {
writer.startElement("tr", component);
writer.writeText("\n", component, null);
for (UIColumn column : info.columns) {
String columnHeaderClass = info.getCurrentHeaderClass();
writer.startElement("th", column);
if (columnHeaderClass != null) {
writer.writeAttribute("class", columnHeaderClass,
"columnHeaderClass");
} else if (headerClass != null) {
writer.writeAttribute("class", headerClass, "headerClass");
}
writer.writeAttribute("scope", "col", null);
UIComponent facet = getFacet(column, "header");
if (facet != null) {
encodeRecursive(context, facet);
}
writer.endElement("th");
writer.writeText("\n", component, null);
}
writer.endElement("tr");
writer.write("\n");
}
writer.endElement("thead");
writer.writeText("\n", component, null);
}
}
@Override
public void encodeChildren(FacesContext context, UIComponent component)
throws IOException {
if (!shouldEncodeChildren(component)) {
return;
}
UIData data = (UIData) component;
ResponseWriter writer = context.getResponseWriter();
BootMetaInfo info = getMetaInfo(context, data);
if(info.columns.isEmpty()) {
writer.startElement("tbody", component);
renderEmptyTableRow(writer, component);
writer.endElement("tbody");
return;
}
int processed = 0;
int rowIndex = data.getFirst() - 1;
int rows = data.getRows();
List<Integer> bodyRows = getBodyRows(context.getExternalContext().getApplicationMap(), data);
boolean hasBodyRows = (bodyRows != null && !bodyRows.isEmpty());
boolean wroteTableBody = false;
if (!hasBodyRows) {
writer.startElement("tbody", component);
writer.writeText("\n", component, null);
}
boolean renderedRow = false;
while (true) {
if ((rows > 0) && (++processed > rows)) {
break;
}
data.setRowIndex(++rowIndex);
if (!data.isRowAvailable()) {
break;
}
if (hasBodyRows && bodyRows.contains(data.getRowIndex())) {
if (wroteTableBody) {
writer.endElement("tbody");
}
writer.startElement("tbody", data);
wroteTableBody = true;
}
writer.startElement("tr", component);
if (info.rowClasses.length > 0) {
writer.writeAttribute("class", info.getCurrentRowClass(),
"rowClasses");
}
writer.writeText("\n", component, null);
info.newRow();
for (UIColumn column : info.columns) {
boolean isRowHeader = Boolean.TRUE.equals(column.getAttributes()
.get("rowHeader"));
if (isRowHeader) {
writer.startElement("th", column);
writer.writeAttribute("scope", "row", null);
} else {
writer.startElement("td", column);
}
String columnClass = info.getCurrentColumnClass();
if (columnClass != null) {
writer.writeAttribute("class", columnClass, "columnClasses");
}
for (Iterator<UIComponent> gkids = getChildren(column); gkids
.hasNext();) {
encodeRecursive(context, gkids.next());
}
if (isRowHeader) {
writer.endElement("th");
} else {
writer.endElement("td");
}
writer.writeText("\n", component, null);
}
writer.endElement("tr");
writer.write("\n");
renderedRow = true;
}
if(!renderedRow) {
renderEmptyTableRow(writer, data);
}
writer.endElement("tbody");
writer.writeText("\n", component, null);
data.setRowIndex(-1);
}
@Override
public void encodeEnd(FacesContext context, UIComponent component)
throws IOException {
if (!shouldEncode(component)) {
return;
}
ResponseWriter writer = context.getResponseWriter();
BootMetaInfo info = getMetaInfo(context, component);
UIComponent footer = getFacet(component, "footer");
if (footer != null || info.hasFooterFacets) {
String footerClass = (String) component.getAttributes().get("footerClass");
writer.startElement("tfoot", component);
writer.writeText("\n", component, null);
if (info.hasFooterFacets) {
writer.startElement("tr", component);
writer.writeText("\n", component, null);
for (UIColumn column : info.columns) {
String columnFooterClass = (String) column.getAttributes().get(
"footerClass");
writer.startElement("td", column);
if (columnFooterClass != null) {
writer.writeAttribute("class", columnFooterClass,
"columnFooterClass");
} else if (footerClass != null) {
writer.writeAttribute("class", footerClass, "footerClass");
}
UIComponent facet = getFacet(column, "footer");
if (facet != null) {
encodeRecursive(context, facet);
}
writer.endElement("td");
writer.writeText("\n", component, null);
}
writer.endElement("tr");
writer.write("\n");
}
if (footer != null) {
writer.startElement("tr", footer);
writer.startElement("td", footer);
if (footerClass != null) {
writer.writeAttribute("class", footerClass, "footerClass");
}
if (info.columns.size() > 1) {
writer.writeAttribute("colspan",
String.valueOf(info.columns.size()), null);
}
encodeRecursive(context, footer);
writer.endElement("td");
writer.endElement("tr");
writer.write("\n");
}
writer.endElement("tfoot");
writer.writeText("\n", component, null);
}
clearMetaInfo(context, component);
((UIData) component).setRowIndex(-1);
writer.endElement("table");
writer.writeText("\n", component, null);
}
private List<Integer> getBodyRows(Map<String, Object> appMap, UIData data) {
List<Integer> result = null;
String bodyRows = (String) data.getAttributes().get("bodyrows");
if (bodyRows != null) {
String [] rows = UtilityMethods.split(appMap, bodyRows, ",");
if (rows != null) {
result = new ArrayList<Integer>(rows.length);
for (String curRow : rows) {
result.add(Integer.valueOf(curRow));
}
}
}
return result;
}
private void renderEmptyTableRow(final ResponseWriter writer,
final UIComponent component) throws IOException {
writer.startElement("tr", component);
writer.startElement("td", component);
writer.endElement("td");
writer.endElement("tr");
}
protected BootTableRenderer.BootMetaInfo getMetaInfo(FacesContext context,
UIComponent table) {
String key = createKey(table);
Map<Object, Object> attributes = context.getAttributes();
BootMetaInfo info = (BootMetaInfo) attributes
.get(key);
if (info == null) {
info = new BootMetaInfo(table);
attributes.put(key, info);
}
return info;
}
protected void clearMetaInfo(FacesContext context, UIComponent table) {
context.getAttributes().remove(createKey(table));
}
protected String createKey(UIComponent table) {
return BootMetaInfo.KEY + '_' + table.hashCode();
}
private static class BootMetaInfo {
private static final UIColumn PLACE_HOLDER_COLUMN = new UIColumn();
private static final String[] EMPTY_STRING_ARRAY = new String[0];
public static final String KEY = BootMetaInfo.class.getName();
public final String[] rowClasses;
public final String[] columnClasses;
public final String[] headerClasses;
public final List<UIColumn> columns;
public final boolean hasHeaderFacets;
public final boolean hasFooterFacets;
public final int columnCount;
public int columnStyleCounter;
public int headerStyleCounter;
public int rowStyleCounter;
public BootMetaInfo(UIComponent table) {
rowClasses = getRowClasses(table);
columnClasses = getColumnClasses(table);
headerClasses = getHeaderClasses(table);
columns = getColumns(table);
columnCount = columns.size();
hasHeaderFacets = hasFacet("header", columns);
hasFooterFacets = hasFacet("footer", columns);
}
public void newRow() {
columnStyleCounter = 0;
headerStyleCounter = 0;
}
public String getCurrentColumnClass() {
String style = null;
if (columnStyleCounter < columnClasses.length
&& columnStyleCounter <= columnCount) {
style = columnClasses[columnStyleCounter++];
}
return ((style != null && style.length() > 0) ? style : null);
}
public String getCurrentHeaderClass() {
String style = null;
if (headerStyleCounter < headerClasses.length
&& headerStyleCounter <= columnCount) {
style = headerClasses[headerStyleCounter++];
}
return ((style != null && style.length() > 0) ? style : null);
}
public String getCurrentRowClass() {
String style = rowClasses[rowStyleCounter++];
if (rowStyleCounter >= rowClasses.length) {
rowStyleCounter = 0;
}
return style;
}
private static String[] getColumnClasses(UIComponent table) {
String values = ((BootTable) table).get("columnClasses");
if (values == null) {
return EMPTY_STRING_ARRAY;
}
Map<String, Object> appMap = FacesContext.getCurrentInstance()
.getExternalContext().getApplicationMap();
return UtilityMethods.split(appMap, values.trim(), ",");
}
private static String[] getHeaderClasses(UIComponent table) {
String values = ((BootTable) table).get("headerClasses");
if (values == null) {
return EMPTY_STRING_ARRAY;
}
Map<String, Object> appMap = FacesContext.getCurrentInstance()
.getExternalContext().getApplicationMap();
return UtilityMethods.split(appMap, values.trim(), ",");
}
private static List<UIColumn> getColumns(UIComponent table) {
if (table instanceof UIData) {
int childCount = table.getChildCount();
if (childCount > 0) {
List<UIColumn> results = new ArrayList<UIColumn>(childCount);
for (UIComponent kid : table.getChildren()) {
if ((kid instanceof UIColumn) && kid.isRendered()) {
results.add((UIColumn) kid);
}
}
return results;
} else {
return Collections.emptyList();
}
} else {
int count;
Object value = table.getAttributes().get("columns");
if ((value != null) && (value instanceof Integer)) {
count = ((Integer) value);
} else {
count = 2;
}
if (count < 1) {
count = 1;
}
List<UIColumn> result = new ArrayList<UIColumn>(count);
for (int i = 0; i < count; i++) {
result.add(PLACE_HOLDER_COLUMN);
}
return result;
}
}
private static boolean hasFacet(String name, List<UIColumn> columns) {
if (!columns.isEmpty()) {
for (UIColumn column : columns) {
if (column.getFacetCount() > 0) {
if (column.getFacets().containsKey(name)) {
return true;
}
}
}
}
return false;
}
private static String[] getRowClasses(UIComponent table) {
String values = ((BootTable) table).get("rowClasses");
if (values == null) {
return (EMPTY_STRING_ARRAY);
}
Map<String, Object> appMap = FacesContext.getCurrentInstance()
.getExternalContext().getApplicationMap();
return UtilityMethods.split(appMap, values.trim(), ",");
}
}
}
|
Java
|
<?php
/**
* SystemProviderListResponseTest
*
* PHP version 5
*
* @category Class
* @package BumbalClient
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Bumbal Client Api
*
* Bumbal API documentation
*
* OpenAPI spec version: 2.0
* Contact: gerb@bumbal.eu
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Please update the test case below to test the model.
*/
namespace BumbalClient;
/**
* SystemProviderListResponseTest Class Doc Comment
*
* @category Class */
// * @description SystemProviderListResponse
/**
* @package BumbalClient
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class SystemProviderListResponseTest extends \PHPUnit_Framework_TestCase
{
/**
* Setup before running any test case
*/
public static function setUpBeforeClass()
{
}
/**
* Setup before running each test case
*/
public function setUp()
{
}
/**
* Clean up after running each test case
*/
public function tearDown()
{
}
/**
* Clean up after running all test cases
*/
public static function tearDownAfterClass()
{
}
/**
* Test "SystemProviderListResponse"
*/
public function testSystemProviderListResponse()
{
}
/**
* Test attribute "items"
*/
public function testPropertyItems()
{
}
/**
* Test attribute "count_filtered"
*/
public function testPropertyCountFiltered()
{
}
/**
* Test attribute "count_unfiltered"
*/
public function testPropertyCountUnfiltered()
{
}
/**
* Test attribute "count_limited"
*/
public function testPropertyCountLimited()
{
}
}
|
Java
|
using Foundation.Data.Hibernate;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using NHibernate;
using NHibernate.Context;
using NHibernate.Engine;
namespace Foundation.Tests.Data.Hibernate
{
[TestClass]
public class HibernateUnitOfWorkTests
{
[TestMethod]
public void Constructor_opens_session_from_factory()
{
var session = new Mock<ISession>();
var context = new Mock<CurrentSessionContext>();
var sessionFactory = new Mock<ISessionFactoryImplementor>();
sessionFactory.Setup(factory => factory.OpenSession()).Returns(session.Object);
sessionFactory.Setup(implementor => implementor.CurrentSessionContext).Returns(context.Object);
session.Setup(session2 => session2.SessionFactory).Returns(sessionFactory.Object);
new HibernateUnitOfWork(sessionFactory.Object);
sessionFactory.Verify(factory1 => factory1.OpenSession());
}
[TestMethod]
public void Constructor_sets_opened_session_flush_mode_to_commit()
{
var session = new Mock<ISession>();
var context = new Mock<CurrentSessionContext>();
var sessionFactory = new Mock<ISessionFactoryImplementor>();
sessionFactory.Setup(factory => factory.OpenSession()).Returns(session.Object);
sessionFactory.Setup(implementor => implementor.CurrentSessionContext).Returns(context.Object);
session.Setup(session2 => session2.SessionFactory).Returns(sessionFactory.Object);
var flushMode = FlushMode.Auto;
session.SetupSet(session2 => session2.FlushMode).Callback(mode => flushMode = mode);
new HibernateUnitOfWork(sessionFactory.Object);
session.VerifySet( session1 => session1.FlushMode, Times.Once());
Assert.AreEqual(FlushMode.Commit, flushMode);
}
[TestMethod]
public void Constructor_begins_transaction_from_session()
{
var session = new Mock<ISession>();
var context = new Mock<CurrentSessionContext>();
var sessionFactory = new Mock<ISessionFactoryImplementor>();
sessionFactory.Setup(factory => factory.OpenSession()).Returns(session.Object);
sessionFactory.Setup(implementor => implementor.CurrentSessionContext).Returns(context.Object);
session.Setup(session2 => session2.SessionFactory).Returns(sessionFactory.Object);
new HibernateUnitOfWork(sessionFactory.Object);
session.Verify(session1 => session1.BeginTransaction());
}
[TestMethod]
public void Dispose_also_disposes_of_session()
{
var session = new Mock<ISession>();
var context = new Mock<CurrentSessionContext>();
var sessionFactory = new Mock<ISessionFactoryImplementor>();
sessionFactory.Setup(factory => factory.OpenSession()).Returns(session.Object);
session.Setup(session2 => session2.SessionFactory).Returns(sessionFactory.Object);
sessionFactory.Setup(implementor => implementor.CurrentSessionContext).Returns(context.Object);
var work = new HibernateUnitOfWork(sessionFactory.Object);
work.Dispose();
session.Verify(session1 => session1.Dispose());
}
[TestMethod]
public void Dispose_also_disposes_of_transaction()
{
var session = new Mock<ISession>();
var transaction = new Mock<ITransaction>();
var context = new Mock<CurrentSessionContext>();
var sessionFactory = new Mock<ISessionFactoryImplementor>();
sessionFactory.Setup(factory => factory.OpenSession()).Returns(session.Object);
session.Setup(session2 => session2.SessionFactory).Returns(sessionFactory.Object);
session.Setup(session3 => session3.BeginTransaction()).Returns(transaction.Object);
sessionFactory.Setup(implementor => implementor.CurrentSessionContext).Returns(context.Object);
var work = new HibernateUnitOfWork(sessionFactory.Object);
work.Dispose();
transaction.Verify(transaction1 => transaction1.Dispose());
}
[TestMethod]
public void Commit_also_commits_transaction()
{
var session = new Mock<ISession>();
var transaction = new Mock<ITransaction>();
var context = new Mock<CurrentSessionContext>();
var sessionFactory = new Mock<ISessionFactory>().As<ISessionFactoryImplementor>();
session.Setup(session2 => session2.SessionFactory).Returns(sessionFactory.Object);
session.Setup(session3 => session3.BeginTransaction()).Returns(transaction.Object);
sessionFactory.Setup(factory => factory.OpenSession()).Returns(session.Object);
sessionFactory.Setup(implementor => implementor.CurrentSessionContext).Returns(context.Object);
var work = new HibernateUnitOfWork(sessionFactory.Object);
work.Commit();
transaction.Verify(transaction1 => transaction1.Commit());
}
}
}
|
Java
|
package info.pupcode.model.repo.test;
import org.junit.Before;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Created by fabientronche1 on 08.11.15.
*/
public class AbstractConcordionFixture {
protected SpringConfigTest springConfigTest;
protected ClassPathXmlApplicationContext applicationContext;
@Before
public void setUp() {
applicationContext = new ClassPathXmlApplicationContext("classpath*:applicationContext.xml");
if (springConfigTest == null) {
springConfigTest = (SpringConfigTest) applicationContext.getBean(SpringConfigTest.class.getName());
}
}
}
|
Java
|
/*
* Copyright 2002-2010 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.
*/
using System;
using System.Collections.Generic;
using Spring.Objects.Factory.Config;
namespace Spring.Objects.Factory.Support
{
/// <summary>
/// Programmatic means of constructing a <see cref="IObjectDefinition"/> using the builder pattern. Intended primarily
/// for use when implementing custom namespace parsers.
/// </summary>
/// <remarks>Set methods are used instead of properties, so that chaining of methods can be used to create
/// 'one-liner'definitions that set multiple properties at one.</remarks>
/// <author>Rod Johnson</author>
/// <author>Rob Harrop</author>
/// <author>Juergen Hoeller</author>
/// <author>Mark Pollack (.NET)</author>
public class ObjectDefinitionBuilder
{
private AbstractObjectDefinition objectDefinition;
private IObjectDefinitionFactory objectDefinitionFactory;
private int constructorArgIndex;
/// <summary>
/// Initializes a new instance of the <see cref="ObjectDefinitionBuilder"/> class, private
/// to force use of factory methods.
/// </summary>
private ObjectDefinitionBuilder()
{
}
/// <summary>
/// Creates a new <see cref="ObjectDefinitionBuilder"/> used to construct a <see cref="Spring.Objects.Factory.Support.GenericObjectDefinition"/>.
/// </summary>
public static ObjectDefinitionBuilder GenericObjectDefinition()
{
ObjectDefinitionBuilder builder = new ObjectDefinitionBuilder();
builder.objectDefinition = new GenericObjectDefinition();
return builder;
}
/// <summary>
/// Creates a new <see cref="ObjectDefinitionBuilder"/> used to construct a <see cref="Spring.Objects.Factory.Support.GenericObjectDefinition"/>.
/// </summary>
/// <param name="objectType">the <see cref="Type"/> of the object that the definition is being created for</param>
public static ObjectDefinitionBuilder GenericObjectDefinition(Type objectType)
{
ObjectDefinitionBuilder builder = new ObjectDefinitionBuilder();
builder.objectDefinition = new GenericObjectDefinition();
builder.objectDefinition.ObjectType = objectType;
return builder;
}
/// <summary>
/// Creates a new <see cref="ObjectDefinitionBuilder"/> used to construct a <see cref="Spring.Objects.Factory.Support.GenericObjectDefinition"/>.
/// </summary>
/// <param name="objectTypeName">the name of the <see cref="Type"/> of the object that the definition is being created for</param>
public static ObjectDefinitionBuilder GenericObjectDefinition(string objectTypeName)
{
ObjectDefinitionBuilder builder = new ObjectDefinitionBuilder();
builder.objectDefinition = new GenericObjectDefinition();
builder.objectDefinition.ObjectTypeName = objectTypeName;
return builder;
}
/// <summary>
/// Create a new <code>ObjectDefinitionBuilder</code> used to construct a root object definition.
/// </summary>
/// <param name="objectDefinitionFactory">The object definition factory.</param>
/// <param name="objectTypeName">The type name of the object.</param>
/// <returns>A new <code>ObjectDefinitionBuilder</code> instance.</returns>
public static ObjectDefinitionBuilder RootObjectDefinition(IObjectDefinitionFactory objectDefinitionFactory,
string objectTypeName)
{
return RootObjectDefinition(objectDefinitionFactory, objectTypeName, null);
}
/// <summary>
/// Create a new <code>ObjectDefinitionBuilder</code> used to construct a root object definition.
/// </summary>
/// <param name="objectDefinitionFactory">The object definition factory.</param>
/// <param name="objectTypeName">Name of the object type.</param>
/// <param name="factoryMethodName">Name of the factory method.</param>
/// <returns>A new <code>ObjectDefinitionBuilder</code> instance.</returns>
public static ObjectDefinitionBuilder RootObjectDefinition(IObjectDefinitionFactory objectDefinitionFactory,
string objectTypeName,
string factoryMethodName)
{
ObjectDefinitionBuilder builder = new ObjectDefinitionBuilder();
builder.objectDefinitionFactory = objectDefinitionFactory;
// Pass in null for parent name and also AppDomain to force object definition to be register by name and not type.
builder.objectDefinition =
objectDefinitionFactory.CreateObjectDefinition(objectTypeName, null, null);
builder.objectDefinition.FactoryMethodName = factoryMethodName;
return builder;
}
/// <summary>
/// Create a new <code>ObjectDefinitionBuilder</code> used to construct a root object definition.
/// </summary>
/// <param name="objectDefinitionFactory">The object definition factory.</param>
/// <param name="objectType">Type of the object.</param>
/// <returns>A new <code>ObjectDefinitionBuilder</code> instance.</returns>
public static ObjectDefinitionBuilder RootObjectDefinition(IObjectDefinitionFactory objectDefinitionFactory,
Type objectType)
{
return RootObjectDefinition(objectDefinitionFactory, objectType, null);
}
/// <summary>
/// Create a new <code>ObjectDefinitionBuilder</code> used to construct a root object definition.
/// </summary>
/// <param name="objectDefinitionFactory">The object definition factory.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="factoryMethodName">Name of the factory method.</param>
/// <returns>A new <code>ObjectDefinitionBuilder</code> instance.</returns>
public static ObjectDefinitionBuilder RootObjectDefinition(IObjectDefinitionFactory objectDefinitionFactory,
Type objectType, string factoryMethodName)
{
ObjectDefinitionBuilder builder = new ObjectDefinitionBuilder();
builder.objectDefinitionFactory = objectDefinitionFactory;
builder.objectDefinition =
objectDefinitionFactory.CreateObjectDefinition(objectType.FullName, null, AppDomain.CurrentDomain);
builder.objectDefinition.ObjectType = objectType;
builder.objectDefinition.FactoryMethodName = factoryMethodName;
return builder;
}
/// <summary>
/// Create a new <code>ObjectDefinitionBuilder</code> used to construct a child object definition..
/// </summary>
/// <param name="objectDefinitionFactory">The object definition factory.</param>
/// <param name="parentObjectName">Name of the parent object.</param>
/// <returns></returns>
public static ObjectDefinitionBuilder ChildObjectDefinition(IObjectDefinitionFactory objectDefinitionFactory,
string parentObjectName)
{
ObjectDefinitionBuilder builder = new ObjectDefinitionBuilder();
builder.objectDefinitionFactory = objectDefinitionFactory;
builder.objectDefinition =
objectDefinitionFactory.CreateObjectDefinition(null, parentObjectName, AppDomain.CurrentDomain);
return builder;
}
/// <summary>
/// Gets the current object definition in its raw (unvalidated) form.
/// </summary>
/// <value>The raw object definition.</value>
public AbstractObjectDefinition RawObjectDefinition
{
get { return objectDefinition; }
}
/// <summary>
/// Validate and gets the object definition.
/// </summary>
/// <value>The object definition.</value>
public AbstractObjectDefinition ObjectDefinition
{
get
{
objectDefinition.Validate();
return objectDefinition;
}
}
//TODO add expression support.
/// <summary>
/// Adds the property value under the given name.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="value">The value.</param>
/// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns>
public ObjectDefinitionBuilder AddPropertyValue(string name, object value)
{
objectDefinition.PropertyValues.Add(new PropertyValue(name, value));
return this;
}
/// <summary>
/// Adds a reference to the specified object name under the property specified.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="objectName">Name of the object.</param>
/// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns>
public ObjectDefinitionBuilder AddPropertyReference(string name, string objectName)
{
objectDefinition.PropertyValues.Add(new PropertyValue(name, new RuntimeObjectReference(objectName)));
return this;
}
/// <summary>
/// Adds an index constructor arg value. The current index is tracked internally and all addtions are
/// at the present point
/// </summary>
/// <param name="value">The constructor arg value.</param>
/// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns>
public ObjectDefinitionBuilder AddConstructorArg(object value)
{
objectDefinition.ConstructorArgumentValues.AddIndexedArgumentValue(constructorArgIndex++,value);
return this;
}
/// <summary>
/// Adds a reference to the named object as a constructor argument.
/// </summary>
/// <param name="objectName">Name of the object.</param>
/// <returns></returns>
public ObjectDefinitionBuilder AddConstructorArgReference(string objectName)
{
return AddConstructorArg(new RuntimeObjectReference(objectName));
}
/// <summary>
/// Sets the name of the factory method to use for this definition.
/// </summary>
/// <param name="factoryMethod">The factory method.</param>
/// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns>
public ObjectDefinitionBuilder SetFactoryMethod(string factoryMethod)
{
objectDefinition.FactoryMethodName = factoryMethod;
return this;
}
/// <summary>
/// Sets the name of the factory object to use for this definition.
/// </summary>
/// <param name="factoryObject">The factory object.</param>
/// <param name="factoryMethod">The factory method.</param>
/// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns>
public ObjectDefinitionBuilder SetFactoryObject(string factoryObject, string factoryMethod)
{
objectDefinition.FactoryObjectName = factoryObject;
objectDefinition.FactoryMethodName = factoryMethod;
return this;
}
/// <summary>
/// Sets whether or not this definition describes a singleton object.
/// </summary>
/// <param name="singleton">if set to <c>true</c> [singleton].</param>
/// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns>
public ObjectDefinitionBuilder SetSingleton(bool singleton)
{
objectDefinition.IsSingleton = singleton;
return this;
}
/// <summary>
/// Sets whether objects or not this definition is abstract.
/// </summary>
/// <param name="flag">if set to <c>true</c> [flag].</param>
/// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns>
public ObjectDefinitionBuilder SetAbstract(bool flag)
{
objectDefinition.IsAbstract = flag;
return this;
}
/// <summary>
/// Sets whether objects for this definition should be lazily initialized or not.
/// </summary>
/// <param name="lazy">if set to <c>true</c> [lazy].</param>
/// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns>
public ObjectDefinitionBuilder SetLazyInit(bool lazy)
{
objectDefinition.IsLazyInit = lazy;
return this;
}
/// <summary>
/// Sets the autowire mode for this definition.
/// </summary>
/// <param name="autowireMode">The autowire mode.</param>
/// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns>
public ObjectDefinitionBuilder SetAutowireMode(AutoWiringMode autowireMode)
{
objectDefinition.AutowireMode = autowireMode;
return this;
}
/// <summary>
/// Sets the autowire candidate value for this definition.
/// </summary>
/// <param name="autowireCandidate">The autowire candidate value</param>
/// <returns></returns>
public ObjectDefinitionBuilder SetAutowireCandidate(bool autowireCandidate)
{
objectDefinition.IsAutowireCandidate = autowireCandidate;
return this;
}
/// <summary>
/// Sets the primary value for this definition.
/// </summary>
/// <param name="primary">If object is primary</param>
/// <returns></returns>
public ObjectDefinitionBuilder SetPrimary(bool primary)
{
objectDefinition.IsPrimary = primary;
return this;
}
/// <summary>
/// Sets the dependency check mode for this definition.
/// </summary>
/// <param name="dependencyCheck">The dependency check.</param>
/// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns>
public ObjectDefinitionBuilder SetDependencyCheck(DependencyCheckingMode dependencyCheck)
{
objectDefinition.DependencyCheck = dependencyCheck;
return this;
}
/// <summary>
/// Sets the name of the destroy method for this definition.
/// </summary>
/// <param name="methodName">Name of the method.</param>
/// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns>
public ObjectDefinitionBuilder SetDestroyMethodName(string methodName)
{
objectDefinition.DestroyMethodName = methodName;
return this;
}
/// <summary>
/// Sets the name of the init method for this definition.
/// </summary>
/// <param name="methodName">Name of the method.</param>
/// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns>
public ObjectDefinitionBuilder SetInitMethodName(string methodName)
{
objectDefinition.InitMethodName = methodName;
return this;
}
/// <summary>
/// Sets the resource description for this definition.
/// </summary>
/// <param name="resourceDescription">The resource description.</param>
/// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns>
public ObjectDefinitionBuilder SetResourceDescription(string resourceDescription)
{
objectDefinition.ResourceDescription = resourceDescription;
return this;
}
/// <summary>
/// Adds the specified object name to the list of objects that this definition depends on.
/// </summary>
/// <param name="objectName">Name of the object.</param>
/// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns>
public ObjectDefinitionBuilder AddDependsOn(string objectName)
{
if (objectDefinition.DependsOn == null)
{
objectDefinition.DependsOn = new[] {objectName};
}
else
{
var list = new List<string>(objectDefinition.DependsOn.Count + 1);
list.AddRange(objectDefinition.DependsOn);
list.Add(objectName);
objectDefinition.DependsOn = list;
}
return this;
}
}
}
|
Java
|
package alicloud
import (
"fmt"
"testing"
"github.com/alibaba/terraform-provider/alicloud/connectivity"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)
func TestAccAlicloudSslVpnClientCert_basic(t *testing.T) {
var sslVpnClientCert vpc.DescribeSslVpnClientCertResponse
resource.Test(t, resource.TestCase{
PreCheck: func() {
testAccPreCheck(t)
},
// module name
IDRefreshName: "alicloud_ssl_vpn_client_cert.foo",
Providers: testAccProviders,
CheckDestroy: testAccCheckSslVpnClientCertDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccSslVpnClientCertConfig,
Check: resource.ComposeTestCheckFunc(
testAccCheckSslVpnClientCertExists("alicloud_ssl_vpn_client_cert.foo", &sslVpnClientCert),
resource.TestCheckResourceAttr(
"alicloud_ssl_vpn_client_cert.foo", "name", "tf-testAccSslVpnClientCertConfig"),
resource.TestCheckResourceAttrSet(
"alicloud_ssl_vpn_client_cert.foo", "ssl_vpn_server_id"),
),
},
},
})
}
func TestAccAlicloudSslVpnClientCert_update(t *testing.T) {
var sslVpnClientCert vpc.DescribeSslVpnClientCertResponse
resource.Test(t, resource.TestCase{
PreCheck: func() {
testAccPreCheck(t)
},
Providers: testAccProviders,
CheckDestroy: testAccCheckSslVpnClientCertDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccSslVpnClientCertConfig,
Check: resource.ComposeTestCheckFunc(
testAccCheckSslVpnClientCertExists("alicloud_ssl_vpn_client_cert.foo", &sslVpnClientCert),
resource.TestCheckResourceAttr(
"alicloud_ssl_vpn_client_cert.foo", "name", "tf-testAccSslVpnClientCertConfig"),
resource.TestCheckResourceAttrSet(
"alicloud_ssl_vpn_client_cert.foo", "ssl_vpn_server_id"),
),
},
resource.TestStep{
Config: testAccSslVpnClientCertConfigUpdate,
Check: resource.ComposeTestCheckFunc(
testAccCheckSslVpnClientCertExists("alicloud_ssl_vpn_client_cert.foo", &sslVpnClientCert),
resource.TestCheckResourceAttr(
"alicloud_ssl_vpn_client_cert.foo", "name", "tf-testAccSslVpnClientCertUpdate"),
resource.TestCheckResourceAttrSet(
"alicloud_ssl_vpn_client_cert.foo", "ssl_vpn_server_id"),
),
},
},
})
}
func testAccCheckSslVpnClientCertExists(n string, vpn *vpc.DescribeSslVpnClientCertResponse) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}
if rs.Primary.ID == "" {
return fmt.Errorf("No VPN ID is set")
}
client := testAccProvider.Meta().(*connectivity.AliyunClient)
vpnGatewayService := VpnGatewayService{client}
instance, err := vpnGatewayService.DescribeSslVpnClientCert(rs.Primary.ID)
if err != nil {
return err
}
*vpn = instance
return nil
}
}
func testAccCheckSslVpnClientCertDestroy(s *terraform.State) error {
client := testAccProvider.Meta().(*connectivity.AliyunClient)
vpnGatewayService := VpnGatewayService{client}
for _, rs := range s.RootModule().Resources {
if rs.Type != "alicloud_ssl_vpn_client_cert" {
continue
}
instance, err := vpnGatewayService.DescribeSslVpnClientCert(rs.Primary.ID)
if err != nil {
if NotFoundError(err) {
continue
}
return err
}
if instance.SslVpnClientCertId != "" {
return fmt.Errorf("Ssl VPN client cert %s still exist", instance.SslVpnClientCertId)
}
}
return nil
}
const testAccSslVpnClientCertConfig = `
variable "name" {
default = "tf-testAccSslVpnClientCertConfig"
}
resource "alicloud_vpc" "foo" {
cidr_block = "172.16.0.0/12"
name = "${var.name}"
}
data "alicloud_zones" "default" {
"available_resource_creation"= "VSwitch"
}
resource "alicloud_vswitch" "foo" {
vpc_id = "${alicloud_vpc.foo.id}"
cidr_block = "172.16.0.0/21"
availability_zone = "${data.alicloud_zones.default.zones.0.id}"
name = "${var.name}"
}
resource "alicloud_vpn_gateway" "foo" {
name = "${var.name}"
vpc_id = "${alicloud_vpc.foo.id}"
bandwidth = "10"
enable_ssl = true
instance_charge_type = "PostPaid"
description = "test_create_description"
}
resource "alicloud_ssl_vpn_server" "foo" {
name = "${var.name}"
vpn_gateway_id = "${alicloud_vpn_gateway.foo.id}"
client_ip_pool = "192.168.0.0/16"
local_subnet = "172.16.0.0/21"
protocol = "UDP"
cipher = "AES-128-CBC"
port = "1194"
compress = "false"
}
resource "alicloud_ssl_vpn_client_cert" "foo" {
ssl_vpn_server_id = "${alicloud_ssl_vpn_server.foo.id}"
name = "${var.name}"
}
`
const testAccSslVpnClientCertConfigUpdate = `
variable "name" {
default = "tf-testAccSslVpnClientCertUpdate"
}
resource "alicloud_vpc" "foo" {
cidr_block = "172.16.0.0/12"
name = "${var.name}"
}
data "alicloud_zones" "default" {
"available_resource_creation"= "VSwitch"
}
resource "alicloud_vswitch" "foo" {
vpc_id = "${alicloud_vpc.foo.id}"
cidr_block = "172.16.0.0/21"
availability_zone = "${data.alicloud_zones.default.zones.0.id}"
name = "${var.name}"
}
resource "alicloud_vpn_gateway" "foo" {
name = "${var.name}"
vpc_id = "${alicloud_vpc.foo.id}"
bandwidth = "10"
enable_ssl = true
instance_charge_type = "PostPaid"
description = "test_update_description"
}
resource "alicloud_ssl_vpn_server" "foo" {
name = "${var.name}"
vpn_gateway_id = "${alicloud_vpn_gateway.foo.id}"
client_ip_pool = "192.168.0.0/16"
local_subnet = "172.16.0.0/21"
protocol = "UDP"
cipher = "AES-128-CBC"
port = "1194"
compress = "false"
}
resource "alicloud_ssl_vpn_client_cert" "foo" {
ssl_vpn_server_id = "${alicloud_ssl_vpn_server.foo.id}"
name = "${var.name}"
}
`
|
Java
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_45) on Mon Apr 29 15:10:36 CEST 2013 -->
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<TITLE>
Uses of Class org.apache.solr.cloud.Overseer (Solr 4.3.0 API)
</TITLE>
<META NAME="date" CONTENT="2013-04-29">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.solr.cloud.Overseer (Solr 4.3.0 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/solr/cloud/Overseer.html" title="class in org.apache.solr.cloud"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/solr/cloud//class-useOverseer.html" target="_top"><B>FRAMES</B></A>
<A HREF="Overseer.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.solr.cloud.Overseer</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../org/apache/solr/cloud/Overseer.html" title="class in org.apache.solr.cloud">Overseer</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.solr.cloud"><B>org.apache.solr.cloud</B></A></TD>
<TD>
Classes for dealing with ZooKeeper when operating in <a href="http://wiki.apache.org/solr/SolrCloud">SolrCloud</a> mode. </TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.solr.cloud"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../org/apache/solr/cloud/Overseer.html" title="class in org.apache.solr.cloud">Overseer</A> in <A HREF="../../../../../org/apache/solr/cloud/package-summary.html">org.apache.solr.cloud</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Fields in <A HREF="../../../../../org/apache/solr/cloud/package-summary.html">org.apache.solr.cloud</A> declared as <A HREF="../../../../../org/apache/solr/cloud/Overseer.html" title="class in org.apache.solr.cloud">Overseer</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../../../org/apache/solr/cloud/Overseer.html" title="class in org.apache.solr.cloud">Overseer</A></CODE></FONT></TD>
<TD><CODE><B>ZkController.</B><B><A HREF="../../../../../org/apache/solr/cloud/ZkController.html#overseer">overseer</A></B></CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/solr/cloud/Overseer.html" title="class in org.apache.solr.cloud"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/solr/cloud//class-useOverseer.html" target="_top"><B>FRAMES</B></A>
<A HREF="Overseer.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<i>Copyright © 2000-2013 Apache Software Foundation. All Rights Reserved.</i>
<script src='../../../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</BODY>
</HTML>
|
Java
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="de">
<head>
<!-- Generated by javadoc (version 1.7.0_11) on Mon Apr 07 19:10:16 CEST 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class at.irian.ankor.big.json.BigListSerializer (Ankor - Project 0.2-SNAPSHOT API)</title>
<meta name="date" content="2014-04-07">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class at.irian.ankor.big.json.BigListSerializer (Ankor - Project 0.2-SNAPSHOT API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../at/irian/ankor/big/json/BigListSerializer.html" title="class in at.irian.ankor.big.json">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?at/irian/ankor/big/json/class-use/BigListSerializer.html" target="_top">Frames</a></li>
<li><a href="BigListSerializer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class at.irian.ankor.big.json.BigListSerializer" class="title">Uses of Class<br>at.irian.ankor.big.json.BigListSerializer</h2>
</div>
<div class="classUseContainer">No usage of at.irian.ankor.big.json.BigListSerializer</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../at/irian/ankor/big/json/BigListSerializer.html" title="class in at.irian.ankor.big.json">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?at/irian/ankor/big/json/class-use/BigListSerializer.html" target="_top">Frames</a></li>
<li><a href="BigListSerializer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2014. All rights reserved.</small></p>
</body>
</html>
|
Java
|
using System;
using Windows.ApplicationModel.Resources;
namespace Okra.Data.Helpers
{
internal static class ResourceHelper
{
// *** Constants ***
private const string RESOURCEMAP_ERROR = "Okra.Data/Errors";
private const string RESOURCE_NOT_FOUND_ERROR = "Exception_ArgumentException_ResourceStringNotFound";
// *** Static Fields ***
private static ResourceLoader errorResourceLoader;
// *** Methods ***
public static string GetErrorResource(string resourceName)
{
if (errorResourceLoader == null)
errorResourceLoader = ResourceLoader.GetForViewIndependentUse(RESOURCEMAP_ERROR);
string errorResource = errorResourceLoader.GetString(resourceName);
if (string.IsNullOrEmpty(errorResource) && resourceName != RESOURCE_NOT_FOUND_ERROR)
throw new ArgumentException(GetErrorResource(RESOURCE_NOT_FOUND_ERROR));
return errorResource;
}
}
}
|
Java
|
package pro.luxun.luxunanimation.presenter.adapter;
import android.support.annotation.UiThread;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
/**
* Created by wufeiyang on 16/5/7.
*/
public abstract class BaseRecyclerAdapter<T, V extends View> extends RecyclerView.Adapter<BaseRecyclerAdapter.BaseViewHolder<V>> {
protected List<T> mItems = new ArrayList<>();
@Override
public BaseViewHolder<V> onCreateViewHolder(ViewGroup parent, int viewType) {
return new BaseViewHolder<>(onCreateItemView(parent, viewType));
}
@Override
public int getItemCount() {
return mItems.size();
}
@UiThread
public void refresh(List<T> datas){
mItems.clear();
add(datas);
}
@UiThread
public void add(List<T> datas){
mItems.addAll(datas);
notifyDataSetChanged();
}
@Override
public void onBindViewHolder(BaseViewHolder holder, int position) {
V v = (V) holder.itemView;
onBindView(v, mItems.get(position));
}
protected abstract V onCreateItemView(ViewGroup parent, int viewType);
protected abstract void onBindView(V v, T t);
public static class BaseViewHolder<V extends View> extends RecyclerView.ViewHolder{
public BaseViewHolder(V itemView) {
super(itemView);
}
}
}
|
Java
|
---
title: gocloud.dev/internal/testing/terraform
type: pkg
---
|
Java
|
# Tragopogon dshimilensis K.Koch SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
package cn.xmut.experiment.service.impl;
import java.util.List;
import org.apache.commons.fileupload.FileItem;
import cn.xmut.experiment.dao.IExperimentDao;
import cn.xmut.experiment.dao.impl.jdbc.ExperimentDaoImpl;
import cn.xmut.experiment.domain.Experiment;
import cn.xmut.experiment.domain.ShowExperiment;
import cn.xmut.experiment.service.IExperimentService;
public class ExperimentServiceImpl implements IExperimentService {
IExperimentDao experimentDao = new ExperimentDaoImpl();
public boolean addExperiment(Experiment experiment, String docName,String dirPath, FileItem fileItem) {
return experimentDao.addExperiment(experiment, docName, dirPath, fileItem);
}
public boolean updateExperiment(Experiment experiment) {
return experimentDao.updateExperiment(experiment);
}
public String getDocPath(int experimentId) {
return experimentDao.getDocPath(experimentId);
}
public Experiment getExperiment(int experimentId) {
return experimentDao.getExperiment(experimentId);
}
public List<ShowExperiment> queryPass(Experiment experiment) {
return experimentDao.queryPass(experiment);
}
public List<ShowExperiment> queryNodistribute(Experiment experiment) {
return experimentDao.queryNodistribute(experiment);
}
public List<ShowExperiment> expertQueryNoExtimate(Experiment experiment, String expertId) {
return experimentDao.expertQueryNoExtimate(experiment, expertId);
}
public List<ShowExperiment> managerQueryNoExtimate(Experiment experiment) {
return experimentDao.managerQueryNoExtimate(experiment);
}
public List<ShowExperiment> managerQueryNoPass(Experiment experiment) {
return experimentDao.managerQueryNoPass(experiment);
}
public boolean delExperiment(Experiment experiment) {
return experimentDao.delExperiment(experiment);
}
public List<ShowExperiment> headmanQueryNoPass(Experiment experiment) {
return experimentDao.headmanQueryNoPass(experiment);
}
}
|
Java
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="de">
<head>
<!-- Generated by javadoc (1.8.0_121) on Sun Oct 15 23:06:23 CEST 2017 -->
<title>Class Hierarchy</title>
<meta name="date" content="2017-10-15">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Class Hierarchy";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="deprecated-list.html">Deprecated</a></li>
<li><a href="index-files/index-1.html">Index</a></li>
<li><a href="help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="index.html?overview-tree.html" target="_top">Frames</a></li>
<li><a href="overview-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 class="title">Hierarchy For All Packages</h1>
<span class="packageHierarchyLabel">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="org/shanerx/faketrollplus/core/package-tree.html">org.shanerx.faketrollplus.core</a>, </li>
<li><a href="org/shanerx/faketrollplus/core/data/package-tree.html">org.shanerx.faketrollplus.core.data</a>, </li>
<li><a href="org/shanerx/faketrollplus/utils/function/package-tree.html">org.shanerx.faketrollplus.utils.function</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li type="circle">java.lang.Object
<ul>
<li type="circle">org.shanerx.faketrollplus.core.<a href="org/shanerx/faketrollplus/core/GuiUser.html" title="class in org.shanerx.faketrollplus.core"><span class="typeNameLink">GuiUser</span></a></li>
<li type="circle">org.shanerx.faketrollplus.core.data.<a href="org/shanerx/faketrollplus/core/data/LocalUserCache.html" title="class in org.shanerx.faketrollplus.core.data"><span class="typeNameLink">LocalUserCache</span></a> (implements org.shanerx.faketrollplus.core.data.<a href="org/shanerx/faketrollplus/core/data/UserCache.html" title="interface in org.shanerx.faketrollplus.core.data">UserCache</a>)</li>
<li type="circle">org.shanerx.faketrollplus.core.data.<a href="org/shanerx/faketrollplus/core/data/RemoteUserCache.html" title="class in org.shanerx.faketrollplus.core.data"><span class="typeNameLink">RemoteUserCache</span></a> (implements org.shanerx.faketrollplus.core.data.<a href="org/shanerx/faketrollplus/core/data/UserCache.html" title="interface in org.shanerx.faketrollplus.core.data">UserCache</a>)</li>
<li type="circle">org.shanerx.faketrollplus.core.data.<a href="org/shanerx/faketrollplus/core/data/TrollPlayer.html" title="class in org.shanerx.faketrollplus.core.data"><span class="typeNameLink">TrollPlayer</span></a></li>
</ul>
</li>
</ul>
<h2 title="Interface Hierarchy">Interface Hierarchy</h2>
<ul>
<li type="circle">org.shanerx.faketrollplus.utils.function.<a href="org/shanerx/faketrollplus/utils/function/EmptyConsumer.html" title="interface in org.shanerx.faketrollplus.utils.function"><span class="typeNameLink">EmptyConsumer</span></a></li>
<li type="circle">org.shanerx.faketrollplus.utils.function.<a href="org/shanerx/faketrollplus/utils/function/Test.html" title="interface in org.shanerx.faketrollplus.utils.function"><span class="typeNameLink">Test</span></a></li>
<li type="circle">org.shanerx.faketrollplus.core.data.<a href="org/shanerx/faketrollplus/core/data/UserCache.html" title="interface in org.shanerx.faketrollplus.core.data"><span class="typeNameLink">UserCache</span></a></li>
</ul>
<h2 title="Enum Hierarchy">Enum Hierarchy</h2>
<ul>
<li type="circle">java.lang.Object
<ul>
<li type="circle">java.lang.Enum<E> (implements java.lang.Comparable<T>, java.io.Serializable)
<ul>
<li type="circle">org.shanerx.faketrollplus.core.<a href="org/shanerx/faketrollplus/core/TrollEffect.html" title="enum in org.shanerx.faketrollplus.core"><span class="typeNameLink">TrollEffect</span></a> (implements java.io.Serializable)</li>
<li type="circle">org.shanerx.faketrollplus.core.<a href="org/shanerx/faketrollplus/core/GuiType.html" title="enum in org.shanerx.faketrollplus.core"><span class="typeNameLink">GuiType</span></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="deprecated-list.html">Deprecated</a></li>
<li><a href="index-files/index-1.html">Index</a></li>
<li><a href="help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="index.html?overview-tree.html" target="_top">Frames</a></li>
<li><a href="overview-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
Java
|
/* Yet Another Forum.NET
* Copyright (C) 2003-2005 Bjørnar Henden
* Copyright (C) 2006-2013 Jaben Cargman
* Copyright (C) 2014-2020 Ingo Herbote
* https://www.yetanotherforum.net/
*
* 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
* 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.
*/
namespace YAF.Utils.Helpers
{
using System.Text.RegularExpressions;
/// <summary>
/// The URL helper.
/// </summary>
public static class UrlHelper
{
/// <summary>
/// Counts the URLs.
/// </summary>
/// <param name="message">The message.</param>
/// <returns>Returns how many URLs the message contains</returns>
public static int CountUrls(string message)
{
return
Regex.Matches(
message,
@"((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)")
.Count;
}
}
}
|
Java
|
/*
*
* (C) Copyright IBM Corp. and others 1998-2013 - All Rights Reserved
*
*/
#ifndef __SUBTABLEPROCESSOR2_H
#define __SUBTABLEPROCESSOR2_H
/**
* \file
* \internal
*/
#include "LETypes.h"
#include "MorphTables.h"
U_NAMESPACE_BEGIN
class LEGlyphStorage;
class SubtableProcessor2 : public UMemory {
public:
virtual void process(LEGlyphStorage &glyphStorage) = 0;
virtual ~SubtableProcessor2();
protected:
SubtableProcessor2(const MorphSubtableHeader2 *morphSubtableHeader);
SubtableProcessor2();
le_uint32 length;
SubtableCoverage2 coverage;
FeatureFlags subtableFeatures;
const MorphSubtableHeader2 *subtableHeader;
private:
SubtableProcessor2(const SubtableProcessor2 &other); // forbid copying of this class
SubtableProcessor2 &operator=(const SubtableProcessor2 &other); // forbid copying of this class
};
U_NAMESPACE_END
#endif
|
Java
|
{%extends "base.html"%}
{% block breadcrumb %}
{% endblock %}
{%block about_this_page %}
<h2>Attachments for Site {{site.number}}</h2>
{% if user.staff %}
<p>
<a href="{{ webapp2.uri_for('SiteView', id=site.key.integer_id()) }}">
Go back to Site #{{ site.number }}.
</a>
</p>
{% endif %}
{% if user.captain %}
<p>
<a href="{{ webapp2.uri_for('CaptainHome') }}">
Go back to your Captain home page.
</a>
</p>
{% endif %}
{% endblock %}
{% block body %}
{% include "site_attachments.html" %}
{% endblock %}
|
Java
|
/*!
* Start Bootstrap - Agency Bootstrap Theme (http://startbootstrap.com)
* Code licensed under the Apache License v2.0.
* For details, see http://www.apache.org/licenses/LICENSE-2.0.
*/
body {
overflow-x: hidden;
font-family: "Roboto Slab", "Helvetica Neue", Helvetica, Arial, sans-serif;
}
.text-muted {
color: #777;
}
.text-primary {
color: #fed136;
}
p {
font-size: 14px;
line-height: 1.75;
font-family: "Merriweather", serif;
}
p.large {
font-size: 16px;
}
a,
a:hover,
a:focus,
a:active,
a.active {
outline: 0;
}
a {
color: #fed136;
}
a:hover,
a:focus,
a:active,
a.active {
color: #fed136;
}
h1,
h2,
h3,
h4,
h5,
h6 {
text-transform: uppercase;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
font-weight: 700;
}
.img-centered {
margin: 0 auto;
}
.bg-light-gray {
background-color: #f7f7f7;
}
.bg-darkest-gray {
background-color: #222;
}
.btn-primary {
border-color: #fed136;
text-transform: uppercase;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
font-weight: 700;
color: #fff;
background-color: #fed136;
}
.btn-primary:hover,
.btn-primary:focus,
.btn-primary:active,
.btn-primary.active,
.open .dropdown-toggle.btn-primary {
border-color: #f6bf01;
color: #fff;
background-color: #fec503;
}
.btn-primary:active,
.btn-primary.active,
.open .dropdown-toggle.btn-primary {
background-image: none;
}
.btn-primary.disabled,
.btn-primary[disabled],
fieldset[disabled] .btn-primary,
.btn-primary.disabled:hover,
.btn-primary[disabled]:hover,
fieldset[disabled] .btn-primary:hover,
.btn-primary.disabled:focus,
.btn-primary[disabled]:focus,
fieldset[disabled] .btn-primary:focus,
.btn-primary.disabled:active,
.btn-primary[disabled]:active,
fieldset[disabled] .btn-primary:active,
.btn-primary.disabled.active,
.btn-primary[disabled].active,
fieldset[disabled] .btn-primary.active {
border-color: #fed136;
background-color: #fed136;
}
.btn-primary .badge {
color: #fed136;
background-color: #fff;
}
.btn-xl {
padding: 20px 40px;
border-color: #fed136;
border-radius: 3px;
text-transform: uppercase;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 18px;
font-weight: 700;
color: #fff;
background-color: #fed136;
}
.btn-xl:hover,
.btn-xl:focus,
.btn-xl:active,
.btn-xl.active,
.open .dropdown-toggle.btn-xl {
border-color: #f6bf01;
color: #fff;
background-color: #fec503;
}
.btn-xl:active,
.btn-xl.active,
.open .dropdown-toggle.btn-xl {
background-image: none;
}
.btn-xl.disabled,
.btn-xl[disabled],
fieldset[disabled] .btn-xl,
.btn-xl.disabled:hover,
.btn-xl[disabled]:hover,
fieldset[disabled] .btn-xl:hover,
.btn-xl.disabled:focus,
.btn-xl[disabled]:focus,
fieldset[disabled] .btn-xl:focus,
.btn-xl.disabled:active,
.btn-xl[disabled]:active,
fieldset[disabled] .btn-xl:active,
.btn-xl.disabled.active,
.btn-xl[disabled].active,
fieldset[disabled] .btn-xl.active {
border-color: #fed136;
background-color: #fed136;
}
.btn-xl .badge {
color: #fed136;
background-color: #fff;
}
.navbar-default {
border-color: transparent;
background-color: #222;
}
.navbar-default .navbar-brand {
font-family: "Jockey One", "Helvetica Neue", Helvetica, Arial, sans-serif;
color: #fed136;
}
.navbar-default .navbar-brand:hover,
.navbar-default .navbar-brand:focus,
.navbar-default .navbar-brand:active,
.navbar-default .navbar-brand.active {
color: #fed136;
}
.navbar-default .navbar-collapse {
border-color: rgba(255, 255, 255, 0.02);
}
.navbar-default .navbar-toggle {
border-color: #fed136;
background-color: #fed136;
}
.navbar-default .navbar-toggle .icon-bar {
background-color: #fff;
}
.navbar-default .navbar-toggle:hover,
.navbar-default .navbar-toggle:focus {
background-color: #fed136;
}
.navbar-default .nav li a {
text-transform: uppercase;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
font-weight: 400;
letter-spacing: 1px;
color: #fff;
}
.navbar-default .nav li a:hover,
.navbar-default .nav li a:focus {
outline: 0;
color: #fed136;
}
.navbar-default .navbar-nav > .active > a {
border-radius: 0;
color: #fff;
background-color: #fed136;
}
.navbar-default .navbar-nav > .active > a:hover,
.navbar-default .navbar-nav > .active > a:focus {
color: #fff;
background-color: #fec503;
}
@media (min-width: 768px) {
.navbar-default {
padding: 25px 0;
border: 0;
background-color: transparent;
-webkit-transition: padding .3s;
-moz-transition: padding .3s;
transition: padding .3s;
}
.navbar-default .navbar-brand {
font-size: 2em;
-webkit-transition: all .3s;
-moz-transition: all .3s;
transition: all .3s;
}
.navbar-default .navbar-nav > .active > a {
border-radius: 3px;
}
.navbar-default.navbar-shrink {
padding: 10px 0;
background-color: #222;
}
.navbar-default.navbar-shrink .navbar-brand {
font-size: 1.5em;
}
}
header {
text-align: center;
color: #fff;
background-attachment: scroll;
background-image: url('../img/globe2.jpg');
background-position: center center;
background-repeat: none;
-webkit-background-size: cover;
-moz-background-size: cover;
background-size: cover;
-o-background-size: cover;
}
header .intro-text {
padding-top: 100px;
padding-bottom: 50px;
}
header .intro-text .intro-lead-in {
margin-bottom: 25px;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 22px;
font-style: normal;
line-height: 22px;
}
header .intro-text .intro-heading {
text-transform: uppercase;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 50px;
font-weight: 700;
line-height: 50px;
margin-bottom: 0px;
}
@media (min-width: 768px) {
header .intro-text {
padding-top: 300px;
padding-bottom: 200px;
}
header .intro-text .intro-lead-in {
margin-bottom: 25px;
font-family: "Merriweather", serif;
font-size: 40px;
font-style: italic;
line-height: 40px;
}
header .intro-text .intro-heading {
margin-bottom: 50px;
text-transform: uppercase;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 75px;
font-weight: 700;
line-height: 75px;
}
}
section {
padding: 100px 0;
}
section h2.section-heading {
margin-top: 0;
margin-bottom: 15px;
font-size: 40px;
}
section h3.section-subheading {
margin-bottom: 75px;
text-transform: none;
font-size: 16px;
font-style: italic;
font-weight: 400;
font-family: "Merriweather", serif;
}
@media (min-width: 768px) {
section {
padding: 150px 0;
}
}
.service-heading {
margin: 15px 0;
text-transform: none;
}
#portfolio .portfolio-item {
right: 0;
margin: 0 0 15px;
}
#portfolio .portfolio-item .portfolio-link {
display: block;
position: relative;
margin: 0 auto;
max-width: 400px;
}
#portfolio .portfolio-item .portfolio-link .portfolio-hover {
position: absolute;
width: 100%;
height: 100%;
opacity: 0;
background: rgba(254, 209, 54, 0.9);
-webkit-transition: all ease .5s;
-moz-transition: all ease .5s;
transition: all ease .5s;
}
#portfolio .portfolio-item .portfolio-link .portfolio-hover:hover {
opacity: 1;
}
#portfolio .portfolio-item .portfolio-link .portfolio-hover .portfolio-hover-content {
position: absolute;
top: 50%;
width: 100%;
height: 20px;
margin-top: -12px;
text-align: center;
font-size: 20px;
color: #fff;
}
#portfolio .portfolio-item .portfolio-link .portfolio-hover .portfolio-hover-content i {
margin-top: -12px;
}
#portfolio .portfolio-item .portfolio-link .portfolio-hover .portfolio-hover-content h3,
#portfolio .portfolio-item .portfolio-link .portfolio-hover .portfolio-hover-content h4 {
margin: 0;
}
#portfolio .portfolio-item .portfolio-caption {
margin: 0 auto;
padding: 25px;
max-width: 400px;
text-align: center;
background-color: #fff;
}
#portfolio .portfolio-item .portfolio-caption h4 {
margin: 0;
text-transform: none;
}
#portfolio .portfolio-item .portfolio-caption p {
margin: 0;
font-family: "Droid Serif", "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 16px;
font-style: italic;
}
#portfolio * {
z-index: 2;
}
@media (min-width: 767px) {
#portfolio .portfolio-item {
margin: 0 0 30px;
}
}
.timeline {
position: relative;
padding: 0;
list-style: none;
}
.timeline:before {
content: "";
position: absolute;
top: 0;
bottom: 0;
left: 40px;
width: 2px;
margin-left: -1.5px;
background-color: #f1f1f1;
}
.timeline > li {
position: relative;
margin-bottom: 50px;
min-height: 50px;
}
.timeline > li:before,
.timeline > li:after {
content: " ";
display: table;
}
.timeline > li:after {
clear: both;
}
.timeline > li .timeline-panel {
float: right;
position: relative;
width: 100%;
padding: 0 20px 0 100px;
text-align: left;
}
.timeline > li .timeline-panel:before {
right: auto;
left: -15px;
border-right-width: 15px;
border-left-width: 0;
}
.timeline > li .timeline-panel:after {
right: auto;
left: -14px;
border-right-width: 14px;
border-left-width: 0;
}
.timeline > li .timeline-image {
z-index: 100;
position: absolute;
left: 0;
width: 80px;
height: 80px;
margin-left: 0;
border: 7px solid #f1f1f1;
border-radius: 100%;
text-align: center;
color: #fff;
background-color: #fed136;
}
.timeline > li .timeline-image h4 {
margin-top: 12px;
font-size: 10px;
line-height: 14px;
}
.timeline > li.timeline-inverted > .timeline-panel {
float: right;
padding: 0 20px 0 100px;
text-align: left;
}
.timeline > li.timeline-inverted > .timeline-panel:before {
right: auto;
left: -15px;
border-right-width: 15px;
border-left-width: 0;
}
.timeline > li.timeline-inverted > .timeline-panel:after {
right: auto;
left: -14px;
border-right-width: 14px;
border-left-width: 0;
}
.timeline > li:last-child {
margin-bottom: 0;
}
.timeline .timeline-heading h4 {
margin-top: 0;
color: inherit;
}
.timeline .timeline-heading h4.subheading {
text-transform: none;
}
.timeline .timeline-body > p,
.timeline .timeline-body > ul {
margin-bottom: 0;
}
@media (min-width: 768px) {
.timeline:before {
left: 50%;
}
.timeline > li {
margin-bottom: 100px;
min-height: 100px;
}
.timeline > li .timeline-panel {
float: left;
width: 41%;
padding: 0 20px 20px 30px;
text-align: right;
}
.timeline > li .timeline-image {
left: 50%;
width: 100px;
height: 100px;
margin-left: -50px;
}
.timeline > li .timeline-image h4 {
margin-top: 16px;
font-size: 13px;
line-height: 18px;
}
.timeline > li.timeline-inverted > .timeline-panel {
float: right;
padding: 0 30px 20px 20px;
text-align: left;
}
}
@media (min-width: 992px) {
.timeline > li {
min-height: 150px;
}
.timeline > li .timeline-panel {
padding: 0 20px 20px;
}
.timeline > li .timeline-image {
width: 150px;
height: 150px;
margin-left: -75px;
}
.timeline > li .timeline-image h4 {
margin-top: 30px;
font-size: 18px;
line-height: 26px;
}
.timeline > li.timeline-inverted > .timeline-panel {
padding: 0 20px 20px;
}
}
@media (min-width: 1200px) {
.timeline > li {
min-height: 170px;
}
.timeline > li .timeline-panel {
padding: 0 20px 20px 100px;
}
.timeline > li .timeline-image {
width: 170px;
height: 170px;
margin-left: -85px;
}
.timeline > li .timeline-image h4 {
margin-top: 40px;
}
.timeline > li.timeline-inverted > .timeline-panel {
padding: 0 100px 20px 20px;
}
}
.team-member {
text-align: center;
margin-bottom: -10px;
}
.team-member img {
margin: 0 auto;
border: 5px solid #fff;
}
.team-member h4 {
margin-top: 25px;
margin-bottom: 0;
text-transform: none;
}
.team-member p {
margin-top: 0;
background-color: #fed136;
padding: 15px;
}
aside.clients img {
margin: 50px auto;
}
section#contact {
background-color: #222;
background-image: url(../img/map-image.png);
background-position: center;
background-repeat: no-repeat;
padding-top: 50px;
padding-bottom: 50px;
}
section#contact .section-heading {
color: #fff;
}
section#contact .form-group {
margin-bottom: 25px;
}
section#contact .form-group input,
section#contact .form-group textarea {
padding: 20px;
}
section#contact .form-group input.form-control {
height: auto;
}
section#contact .form-group textarea.form-control {
height: 236px;
}
section#contact .form-control:focus {
border-color: #fed136;
box-shadow: none;
}
section#contact::-webkit-input-placeholder {
text-transform: uppercase;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
font-weight: 700;
color: #bbb;
}
section#contact:-moz-placeholder {
text-transform: uppercase;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
font-weight: 700;
color: #bbb;
}
section#contact::-moz-placeholder {
text-transform: uppercase;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
font-weight: 700;
color: #bbb;
}
section#contact:-ms-input-placeholder {
text-transform: uppercase;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
font-weight: 700;
color: #bbb;
}
section#contact .text-danger {
color: #e74c3c;
}
footer {
padding: 25px 0;
text-align: center;
}
footer span.copyright {
text-transform: none;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
line-height: 40px;
text-align: left;
}
footer ul.quicklinks {
margin-bottom: 0;
text-transform: uppercase;
text-transform: none;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
line-height: 40px;
}
ul.social-buttons {
margin-bottom: 0;
}
ul.social-buttons li a {
display: block;
width: 40px;
height: 40px;
border-radius: 100%;
font-size: 20px;
line-height: 40px;
outline: 0;
color: #fff;
background-color: #222;
-webkit-transition: all .3s;
-moz-transition: all .3s;
transition: all .3s;
}
ul.social-buttons li a:hover,
ul.social-buttons li a:focus,
ul.social-buttons li a:active {
background-color: #fed136;
}
.btn:focus,
.btn:active,
.btn.active,
.btn:active:focus {
outline: 0;
}
.portfolio-modal .modal-content {
padding: 100px 0;
min-height: 100%;
border: 0;
border-radius: 0;
text-align: center;
background-clip: border-box;
-webkit-box-shadow: none;
box-shadow: none;
}
.portfolio-modal .modal-content h2 {
margin-bottom: 15px;
font-size: 3em;
}
.portfolio-modal .modal-content p {
margin-bottom: 30px;
}
.portfolio-modal .modal-content p.item-intro {
margin: 20px 0 30px;
font-family: "Droid Serif", "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 16px;
font-style: italic;
}
.portfolio-modal .modal-content ul.list-inline {
margin-top: 0;
margin-bottom: 30px;
}
.portfolio-modal .modal-content img {
margin-bottom: 30px;
}
.portfolio-modal .close-modal {
position: absolute;
top: 25px;
right: 25px;
width: 75px;
height: 75px;
background-color: transparent;
cursor: pointer;
}
.portfolio-modal .close-modal:hover {
opacity: .3;
}
.portfolio-modal .close-modal .lr {
z-index: 1051;
width: 1px;
height: 75px;
margin-left: 35px;
background-color: #222;
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
}
.portfolio-modal .close-modal .lr .rl {
z-index: 1052;
width: 1px;
height: 75px;
background-color: #222;
-webkit-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
}
.portfolio-modal .modal-backdrop {
display: none;
opacity: 0;
}
::-moz-selection {
text-shadow: none;
background: #fed136;
}
::selection {
text-shadow: none;
background: #fed136;
}
img::selection {
background: 0 0;
}
img::-moz-selection {
background: 0 0;
}
body {
webkit-tap-highlight-color: #fed136;
}
.margins {
margin-left: 60px;
margin-right: 60px;
}
.photo {
margin-bottom: 0px;
margin-top: 0px;
padding-top: 70px;
padding-left: 0px;
margin-right: 0px;
left: 0px;
}
.professor {
padding-top: 100px;
padding-bottom: 0;
}
.biografia {
padding-bottom: 0px;
margin-bottom: 50px;
}
.depoimento {
margin-top: 30px;
}
.testemunho {
margin-top: 17px;
}
.testemunho h4 {
margin-bottom: 0;
}
section#pacotes {
background-color: #222;
}
section#pacotes .section-heading {
color: #fff;
}
section#contact h3 {
color: #fff;
}
section#contact p {
color: #fff;
}
.demo {
margin-left: 50px;
padding: 20px 40px;
border-color: #c6ccd2;
border-radius: 3px;
text-transform: uppercase;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 18px;
font-weight: 700;
color: #fff;
background-color: #c6ccd2;
}
.demo:hover {
color: #fff;
background-color: #767676;
}
.email {
line-height: 30px;
font-weight: 400;
height: 65px;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 22px;
}
section#demo {
padding-top: 55px;
padding-bottom: 55px;
background-color: #fed136;
}
.enviar {
margin-left: 0px;
padding: 20px 40px;
border-color: #c6ccd2;
border-radius: 3px;
text-transform: uppercase;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 18px;
font-weight: 700;
color: #fff;
background-color: #3996cc;
}
.enviar:hover {
color: #fff;
background-color: #3386b7;
}
section#demo p {
color: #222;
margin-top: 10px;
font-size: 14px;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
}
section#demo h3 {
text-transform: none;
margin-top: 0;
}
.logo {
color: #fed136;
text-transform: none;
font-size: 21px;
font-family: "Jockey One", "Helvetica Neue", Helvetica, Arial, sans-serif;
}
.glyphicon {
color: #fff;
}
section#contact .col-md-10,
.col-lg-10 {
margin-left: 0px;
padding-left: 3px;
}
.fa {
color: #222;
border: 10px;
background-color: #fff;
padding: 3px 6px 2px 5px;
border-radius: 9px;
margin-right: 0px;
margin-left: -3px;
}
.pacote {
background-color: #3996cc;
padding: 14px 8px 13px;
color: #fff;
text-align: center;
margin: 0;
}
section#pacotes p {
color: #222;
margin-top: 0;
font-size: 14px;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
padding: 8px;
font-weight: 200;
text-align: center;
border-top: 0;
border-bottom: 1px;
border-style: solid;
border-color: #ddd;
border-left: 0;
border-right: 0;
margin-bottom: 0;
}
section#pacotes h4 {
padding: 18px 8px;
color: #fff;
text-align: center;
background-color: #767676;
text-transform: none;
font-size: 35px;
margin: 0;
}
section#pacotes h5 {
padding: 15px 8px;
color: #222;
text-align: center;
background-color: #f6f6f6;
text-transform: none;
margin: 0;
font-size: 17px;
}
section#pacotes p.large {
color: #f7f7f7;
border: none;
text-align: left;
font-weight: 100;
font-size: 12px;
margin-top: 5px;
}
section#pacotes .col-md-10 {
padding-right: 0;
padding-left: 0;
}
.super {
border: 15px;
color: #e52323;
border-color: #fed136;
background-color: #df9898;
}
.pacote-coluna {
background-color: #fff;
padding-left: 0;
padding-right: 0;
border: 0.5px;
border-style: solid;
border-color: #ddd;
}
.pacote-max {
background-color: #fff;
padding-left: 0;
padding-right: 0;
border: 9px;
border-style: solid;
border-color: #fed136;
margin-top: -9px;
border-top-left-radius: 0;
border-top-right-radius: 0;
border-bottom-right-radius: 7px;
border-bottom-left-radius: 7px;
}
.valor {
background-color: #fed136;
padding-left: 0;
padding-right: 0;
border: 9px;
border-style: solid;
border-color: #fed136;
margin-top: -9px;
border-top-left-radius: 7px;
border-top-right-radius: 7px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
height: 29px;
}
.valor h5 {
background-color: #fed136;
font-size: 14px;
}
.valor h6 {
margin-top: 0;
text-align: center;
margin-bottom: 0;
}
header h1 {
text-transform: none;
font-style: normal;
font-weight: 100;
margin-top: -26px;
margin-bottom: 0px;
}
header .row {
margin-top: 0px;
}
section#portfolio p {
margin-bottom: 67px;
}
section#portfolio {
padding-bottom: 68px;
}
section#about strong {
text-align: right;
text-transform: none;
font-size: 18px;
font-style: italic;
font-family: "Merriweather", serif;
}
section#services img {
border: 5px;
border-color: #f7f7f7;
border-style: solid;
border-radius: 52px;
}
|
Java
|
/**
* @file
* Declares the any type.
*/
#pragma once
#include "../values/forward.hpp"
#include <ostream>
namespace puppet { namespace runtime { namespace types {
// Forward declaration of recursion_guard
struct recursion_guard;
/**
* Represents the Puppet Any type.
*/
struct any
{
/**
* Gets the name of the type.
* @return Returns the name of the type (i.e. Any).
*/
static char const* name();
/**
* Creates a generalized version of the type.
* @return Returns the generalized type.
*/
values::type generalize() const;
/**
* Determines if the given value is an instance of this type.
* @param value The value to determine if it is an instance of this type.
* @param guard The recursion guard to use for aliases.
* @return Returns true if the given value is an instance of this type or false if not.
*/
bool is_instance(values::value const& value, recursion_guard& guard) const;
/**
* Determines if the given type is assignable to this type.
* @param other The other type to check for assignability.
* @param guard The recursion guard to use for aliases.
* @return Returns true if the given type is assignable to this type or false if the given type is not assignable to this type.
*/
bool is_assignable(values::type const& other, recursion_guard& guard) const;
/**
* Writes a representation of the type to the given stream.
* @param stream The stream to write to.
* @param expand True to specify that type aliases should be expanded or false if not.
*/
void write(std::ostream& stream, bool expand = true) const;
};
/**
* Stream insertion operator for any type.
* @param os The output stream to write the type to.
* @param type The type to write.
* @return Returns the given output stream.
*/
std::ostream& operator<<(std::ostream& os, any const& type);
/**
* Equality operator for any.
* @param left The left type to compare.
* @param right The right type to compare.
* @return Always returns true (Any type is always equal to Any).
*/
bool operator==(any const& left, any const& right);
/**
* Inequality operator for any.
* @param left The left type to compare.
* @param right The right type to compare.
* @return Always returns false (Any type is always equal to Any).
*/
bool operator!=(any const& left, any const& right);
/**
* Hashes the any type.
* @param type The any type to hash.
* @return Returns the hash value for the type.
*/
size_t hash_value(any const& type);
}}} // namespace puppet::runtime::types
|
Java
|
package im.mange.jetpac.html
import im.mange.jetpac.{Styleable, Renderable, R}
import net.liftweb.http.SHtml.ajaxInvoke
import net.liftweb.http.js.JsCmd
//TODO: ultimately Tr or ClickableTr
//TODO: do the style in the same way as the inputs onClick etc ...
@deprecated("Use Tr instead", "28/08/2015")
case class ClickableRow(id: Option[String], onClick: () ⇒ JsCmd, cells: Renderable*) extends Renderable with Styleable {
def render = <tr id={id.getOrElse("")} class={classes.render} style={styles.render} onclick={ajaxInvoke(onClick).toJsCmd}>{R(cells).render}</tr>
}
|
Java
|
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>PHPXRef 0.7.1 : Unnamed Project : Function Reference: testsetfieldasstring()</title>
<link rel="stylesheet" href="../sample.css" type="text/css">
<link rel="stylesheet" href="../sample-print.css" type="text/css" media="print">
<style id="hilight" type="text/css"></style>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
</head>
<body bgcolor="#ffffff" text="#000000" link="#801800" vlink="#300540" alink="#ffffff">
<table class="pagetitle" width="100%">
<tr>
<td valign="top" class="pagetitle">
[ <a href="../index.html">Index</a> ]
</td>
<td align="right" class="pagetitle">
<h2 style="margin-bottom: 0px">PHP Cross Reference of Unnamed Project</h2>
</td>
</tr>
</table>
<!-- Generated by PHPXref 0.7.1 at Thu Oct 23 18:57:41 2014 -->
<!-- PHPXref (c) 2000-2010 Gareth Watts - gareth@omnipotent.net -->
<!-- http://phpxref.sourceforge.net/ -->
<script src="../phpxref.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
<!--
ext='.html';
relbase='../';
subdir='_functions';
filename='index.html';
cookiekey='phpxref';
handleNavFrame(relbase, subdir, filename);
logFunction('testsetfieldasstring');
// -->
</script>
<script language="JavaScript" type="text/javascript">
if (gwGetCookie('xrefnav')=='off')
document.write('<p class="navlinks">[ <a href="javascript:navOn()">Show Explorer<\/a> ]<\/p>');
else
document.write('<p class="navlinks">[ <a href="javascript:navOff()">Hide Explorer<\/a> ]<\/p>');
</script>
<noscript>
<p class="navlinks">
[ <a href="../nav.html" target="_top">Show Explorer</a> ]
[ <a href="index.html" target="_top">Hide Navbar</a> ]
</p>
</noscript>
[<a href="../index.html">Top level directory</a>]<br>
<script language="JavaScript" type="text/javascript">
<!--
document.writeln('<table align="right" class="searchbox-link"><tr><td><a class="searchbox-link" href="javascript:void(0)" onMouseOver="showSearchBox()">Search</a><br>');
document.writeln('<table border="0" cellspacing="0" cellpadding="0" class="searchbox" id="searchbox">');
document.writeln('<tr><td class="searchbox-title">');
document.writeln('<a class="searchbox-title" href="javascript:showSearchPopup()">Search History +</a>');
document.writeln('<\/td><\/tr>');
document.writeln('<tr><td class="searchbox-body" id="searchbox-body">');
document.writeln('<form name="search" style="margin:0px; padding:0px" onSubmit=\'return jump()\'>');
document.writeln('<a class="searchbox-body" href="../_classes/index.html">Class<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="classname"><br>');
document.writeln('<a id="funcsearchlink" class="searchbox-body" href="../_functions/index.html">Function<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="funcname"><br>');
document.writeln('<a class="searchbox-body" href="../_variables/index.html">Variable<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="varname"><br>');
document.writeln('<a class="searchbox-body" href="../_constants/index.html">Constant<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="constname"><br>');
document.writeln('<a class="searchbox-body" href="../_tables/index.html">Table<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="tablename"><br>');
document.writeln('<input type="submit" class="searchbox-button" value="Search">');
document.writeln('<\/form>');
document.writeln('<\/td><\/tr><\/table>');
document.writeln('<\/td><\/tr><\/table>');
// -->
</script>
<div id="search-popup" class="searchpopup"><p id="searchpopup-title" class="searchpopup-title">title</p><div id="searchpopup-body" class="searchpopup-body">Body</div><p class="searchpopup-close"><a href="javascript:gwCloseActive()">[close]</a></p></div>
<h3>Function and Method Cross Reference</h3>
<h2><a href="index.html#testsetfieldasstring">testsetfieldasstring()</a></h2>
<b>Defined at:</b><ul>
<li><a href="../tests/simpletest/test/acceptance_test.php.html#testsetfieldasstring">/tests/simpletest/test/acceptance_test.php</a> -> <a onClick="logFunction('testsetfieldasstring', '/tests/simpletest/test/acceptance_test.php.source.html#l185')" href="../tests/simpletest/test/acceptance_test.php.source.html#l185"> line 185</a></li>
</ul>
<b>No references found.</b><br><br>
</ul>
<!-- A link to the phpxref site in your customized footer file is appreciated ;-) -->
<br><hr>
<table width="100%">
<tr><td>Generated: Thu Oct 23 18:57:41 2014</td>
<td align="right"><i>Cross-referenced by <a href="http://phpxref.sourceforge.net/">PHPXref 0.7.1</a></i></td>
</tr>
</table>
</body></html>
|
Java
|
package server
import (
"bytes"
"context"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"strings"
"sync"
"sync/atomic"
"text/template"
"time"
"github.com/TV4/graceful"
"github.com/gogap/config"
"github.com/gogap/go-wkhtmltox/wkhtmltox"
"github.com/gorilla/mux"
"github.com/phyber/negroni-gzip/gzip"
"github.com/rs/cors"
"github.com/spf13/cast"
"github.com/urfave/negroni"
)
const (
defaultTemplateText = `{"code":{{.Code}},"message":"{{.Message}}"{{if .Result}},"result":{{.Result|jsonify}}{{end}}}`
)
var (
htmlToX *wkhtmltox.WKHtmlToX
renderTmpls = make(map[string]*template.Template)
defaultTmpl *template.Template
)
type ConvertData struct {
Data []byte `json:"data"`
}
type ConvertArgs struct {
To string `json:"to"`
Fetcher wkhtmltox.FetcherOptions `json:"fetcher"`
Converter json.RawMessage `json:"converter"`
Template string `json:"template"`
}
type TemplateArgs struct {
To string
ConvertResponse
Response *RespHelper
}
type ConvertResponse struct {
Code int `json:"code"`
Message string `json:"message"`
Result interface{} `json:"result"`
}
type serverWrapper struct {
tls bool
certFile string
keyFile string
reqNumber int64
addr string
n *negroni.Negroni
timeout time.Duration
}
func (p *serverWrapper) ServeHTTP(w http.ResponseWriter, r *http.Request) {
atomic.AddInt64(&p.reqNumber, 1)
defer atomic.AddInt64(&p.reqNumber, -1)
p.n.ServeHTTP(w, r)
}
func (p *serverWrapper) ListenAndServe() (err error) {
if p.tls {
err = http.ListenAndServeTLS(p.addr, p.certFile, p.keyFile, p)
} else {
err = http.ListenAndServe(p.addr, p)
}
return
}
func (p *serverWrapper) Shutdown(ctx context.Context) error {
num := atomic.LoadInt64(&p.reqNumber)
schema := "HTTP"
if p.tls {
schema = "HTTPS"
}
beginTime := time.Now()
for num > 0 {
time.Sleep(time.Second)
timeDiff := time.Now().Sub(beginTime)
if timeDiff > p.timeout {
break
}
}
log.Printf("[%s] Shutdown finished, Address: %s\n", schema, p.addr)
return nil
}
type WKHtmlToXServer struct {
conf config.Configuration
servers []*serverWrapper
}
func New(conf config.Configuration) (srv *WKHtmlToXServer, err error) {
serviceConf := conf.GetConfig("service")
wkHtmlToXConf := conf.GetConfig("wkhtmltox")
htmlToX, err = wkhtmltox.New(wkHtmlToXConf)
if err != nil {
return
}
// init templates
defaultTmpl, err = template.New("default").Funcs(funcMap).Parse(defaultTemplateText)
if err != nil {
return
}
err = loadTemplates(
serviceConf.GetConfig("templates"),
)
if err != nil {
return
}
// init http server
c := cors.New(
cors.Options{
AllowedOrigins: serviceConf.GetStringList("cors.allowed-origins"),
AllowedMethods: serviceConf.GetStringList("cors.allowed-methods"),
AllowedHeaders: serviceConf.GetStringList("cors.allowed-headers"),
ExposedHeaders: serviceConf.GetStringList("cors.exposed-headers"),
AllowCredentials: serviceConf.GetBoolean("cors.allow-credentials"),
MaxAge: int(serviceConf.GetInt64("cors.max-age")),
OptionsPassthrough: serviceConf.GetBoolean("cors.options-passthrough"),
Debug: serviceConf.GetBoolean("cors.debug"),
},
)
r := mux.NewRouter()
pathPrefix := serviceConf.GetString("path", "/")
r.PathPrefix(pathPrefix).Path("/convert").
Methods("POST").
HandlerFunc(handleHtmlToX)
r.PathPrefix(pathPrefix).Path("/ping").
Methods("GET", "HEAD").HandlerFunc(
func(rw http.ResponseWriter, req *http.Request) {
rw.Header().Set("Content-Type", "text/plain; charset=utf-8")
rw.Write([]byte("pong"))
},
)
n := negroni.Classic()
n.Use(c) // use cors
if serviceConf.GetBoolean("gzip-enabled", true) {
n.Use(gzip.Gzip(gzip.DefaultCompression))
}
n.UseHandler(r)
gracefulTimeout := serviceConf.GetTimeDuration("graceful.timeout", time.Second*3)
enableHTTP := serviceConf.GetBoolean("http.enabled", true)
enableHTTPS := serviceConf.GetBoolean("https.enabled", false)
var servers []*serverWrapper
if enableHTTP {
listenAddr := serviceConf.GetString("http.address", "127.0.0.1:8080")
httpServer := &serverWrapper{
n: n,
timeout: gracefulTimeout,
addr: listenAddr,
}
servers = append(servers, httpServer)
}
if enableHTTPS {
listenAddr := serviceConf.GetString("http.address", "127.0.0.1:443")
certFile := serviceConf.GetString("https.cert")
keyFile := serviceConf.GetString("https.key")
httpsServer := &serverWrapper{
n: n,
timeout: gracefulTimeout,
addr: listenAddr,
tls: true,
certFile: certFile,
keyFile: keyFile,
}
servers = append(servers, httpsServer)
}
srv = &WKHtmlToXServer{
conf: conf,
servers: servers,
}
return
}
func (p *WKHtmlToXServer) Run() (err error) {
wg := sync.WaitGroup{}
wg.Add(len(p.servers))
for i := 0; i < len(p.servers); i++ {
go func(srv *serverWrapper) {
defer wg.Done()
shcema := "HTTP"
if srv.tls {
shcema = "HTTPS"
}
log.Printf("[%s] Listening on %s\n", shcema, srv.addr)
graceful.ListenAndServe(srv)
}(p.servers[i])
}
wg.Wait()
return
}
func writeResp(rw http.ResponseWriter, convertArgs ConvertArgs, resp ConvertResponse) {
var tmpl *template.Template
if len(convertArgs.Template) == 0 {
tmpl = defaultTmpl
} else {
var exist bool
tmpl, exist = renderTmpls[convertArgs.Template]
if !exist {
tmpl = defaultTmpl
}
}
respHelper := newRespHelper(rw)
args := TemplateArgs{
To: convertArgs.To,
ConvertResponse: resp,
Response: respHelper,
}
buf := bytes.NewBuffer(nil)
err := tmpl.Execute(buf, args)
if err != nil {
log.Println(err)
}
if !respHelper.Holding() {
rw.Write(buf.Bytes())
}
}
func handleHtmlToX(rw http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(req.Body)
decoder.UseNumber()
args := ConvertArgs{}
err := decoder.Decode(&args)
if err != nil {
writeResp(rw, args, ConvertResponse{http.StatusBadRequest, err.Error(), nil})
return
}
if len(args.Converter) == 0 {
writeResp(rw, args, ConvertResponse{http.StatusBadRequest, "converter is nil", nil})
return
}
to := strings.ToUpper(args.To)
var opts wkhtmltox.ConvertOptions
if to == "IMAGE" {
opts = &wkhtmltox.ToImageOptions{}
} else if to == "PDF" {
opts = &wkhtmltox.ToPDFOptions{}
} else {
writeResp(rw, args, ConvertResponse{http.StatusBadRequest, "argument of to is illegal (image|pdf)", nil})
return
}
err = json.Unmarshal(args.Converter, opts)
if err != nil {
writeResp(rw, args, ConvertResponse{http.StatusBadRequest, err.Error(), nil})
return
}
var convData []byte
convData, err = htmlToX.Convert(args.Fetcher, opts)
if err != nil {
writeResp(rw, args, ConvertResponse{http.StatusBadRequest, err.Error(), nil})
return
}
writeResp(rw, args, ConvertResponse{0, "", ConvertData{Data: convData}})
return
}
func loadTemplates(tmplsConf config.Configuration) (err error) {
if tmplsConf == nil {
return
}
tmpls := tmplsConf.Keys()
for _, name := range tmpls {
file := tmplsConf.GetString(name + ".template")
tmpl := template.New(name).Funcs(funcMap)
var data []byte
data, err = ioutil.ReadFile(file)
if err != nil {
return
}
tmpl, err = tmpl.Parse(string(data))
if err != nil {
return
}
renderTmpls[name] = tmpl
}
return
}
type RespHelper struct {
rw http.ResponseWriter
hold bool
}
func newRespHelper(rw http.ResponseWriter) *RespHelper {
return &RespHelper{
rw: rw,
hold: false,
}
}
func (p *RespHelper) SetHeader(key, value interface{}) error {
k := cast.ToString(key)
v := cast.ToString(value)
p.rw.Header().Set(k, v)
return nil
}
func (p *RespHelper) Hold(v interface{}) error {
h := cast.ToBool(v)
p.hold = h
return nil
}
func (p *RespHelper) Holding() bool {
return p.hold
}
func (p *RespHelper) Write(data []byte) error {
p.rw.Write(data)
return nil
}
func (p *RespHelper) WriteHeader(code interface{}) error {
c, err := cast.ToIntE(code)
if err != nil {
return err
}
p.rw.WriteHeader(c)
return nil
}
|
Java
|
/*
* Copyright (c) 2002-2018 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.collection.primitive;
public interface PrimitiveLongIntVisitor<E extends Exception>
{
/**
* Visit the given entry.
*
* @param key The key of the entry.
* @param value The value of the entry.
* @return 'true' to signal that the iteration should be stopped, 'false' to signal that the iteration should
* continue if there are more entries to look at.
* @throws E any thrown exception of type 'E' will bubble up through the 'visit' method.
*/
boolean visited( long key, int value ) throws E;
}
|
Java
|
package org.anyline.entity;
import com.fasterxml.jackson.databind.JsonNode;
import org.anyline.util.*;
import org.anyline.util.regular.Regular;
import org.anyline.util.regular.RegularUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;
public class DataSet implements Collection<DataRow>, Serializable {
private static final long serialVersionUID = 6443551515441660101L;
protected static final Logger log = LoggerFactory.getLogger(DataSet.class);
private boolean result = true; // 执行结果
private Exception exception = null; // 异常
private String message = null; // 提示信息
private PageNavi navi = null; // 分页
private List<String> head = null; // 表头
private List<DataRow> rows = null; // 数据
private List<String> primaryKeys = null; // 主键
private String datalink = null; // 数据连接
private String dataSource = null; // 数据源(表|视图|XML定义SQL)
private String schema = null;
private String table = null;
private long createTime = 0; //创建时间
private long expires = -1; //过期时间(毫秒) 从创建时刻计时expires毫秒后过期
private boolean isFromCache = false; //是否来自缓存
private boolean isAsc = false;
private boolean isDesc = false;
private Map<String, Object> queryParams = new HashMap<String, Object>();//查询条件
/**
* 创建索引
*
* @param key key
* @return return
* crateIndex("ID");
* crateIndex("ID:ASC");
*/
public DataSet creatIndex(String key) {
return this;
}
public DataSet() {
rows = new ArrayList<DataRow>();
createTime = System.currentTimeMillis();
}
public DataSet(List<Map<String, Object>> list) {
rows = new ArrayList<DataRow>();
if (null == list)
return;
for (Map<String, Object> map : list) {
DataRow row = new DataRow(map);
rows.add(row);
}
}
public static DataSet build(Collection<?> list, String ... fields) {
return parse(list, fields);
}
/**
* list解析成DataSet
* @param list list
* @param fields 如果list是二维数据
* fields 下标对应的属性(字段/key)名称 如"ID","CODE","NAME"
* 如果不输入则以下标作为DataRow的key 如row.put("0","100").put("1","A01").put("2","张三");
* 如果属性数量超出list长度,取null值存入DataRow
*
* 如果list是一组数组
* fileds对应条目的属性值 如果不输入 则以条目的属性作DataRow的key 如"USER_ID:id","USER_NM:name"
*
* @return DataSet
*/
public static DataSet parse(Collection<?> list, String ... fields) {
DataSet set = new DataSet();
if (null != list) {
for (Object obj : list) {
DataRow row = null;
if(obj instanceof Collection){
row = DataRow.parseList((Collection)obj, fields);
}else {
row = DataRow.parse(obj, fields);
}
set.add(row);
}
}
return set;
}
public static DataSet parseJson(DataRow.KEY_CASE keyCase, String json) {
if (null != json) {
try {
return parseJson(keyCase, BeanUtil.JSON_MAPPER.readTree(json));
} catch (Exception e) {
}
}
return null;
}
public static DataSet parseJson(String json) {
return parseJson(DataRow.KEY_CASE.CONFIG, json);
}
public static DataSet parseJson(DataRow.KEY_CASE keyCase, JsonNode json) {
DataSet set = new DataSet();
if (null != json) {
if (json.isArray()) {
Iterator<JsonNode> items = json.iterator();
while (items.hasNext()) {
JsonNode item = items.next();
set.add(DataRow.parseJson(keyCase, item));
}
}
}
return set;
}
public static DataSet parseJson(JsonNode json) {
return parseJson(DataRow.KEY_CASE.CONFIG, json);
}
public DataSet Camel(){
for(DataRow row:rows){
row.Camel();
}
return this;
}
public DataSet camel(){
for(DataRow row:rows){
row.camel();
}
return this;
}
public DataSet setIsNew(boolean bol) {
for (DataRow row : rows) {
row.setIsNew(bol);
}
return this;
}
/**
* 移除每个条目中指定的key
*
* @param keys keys
* @return DataSet
*/
public DataSet remove(String... keys) {
for (DataRow row : rows) {
for (String key : keys) {
row.remove(key);
}
}
return this;
}
public DataSet trim(){
for(DataRow row:rows){
row.trim();
}
return this;
}
/**
* 添加主键
*
* @param applyItem 是否应用到集合中的DataRow 默认true
* @param pks pks
* @return return
*/
public DataSet addPrimaryKey(boolean applyItem, String... pks) {
if (null != pks) {
List<String> list = new ArrayList<>();
for (String pk : pks) {
list.add(pk);
}
addPrimaryKey(applyItem, list);
}
return this;
}
public DataSet addPrimaryKey(String... pks) {
return addPrimaryKey(true, pks);
}
public DataSet addPrimaryKey(boolean applyItem, Collection<String> pks) {
if (null == primaryKeys) {
primaryKeys = new ArrayList<>();
}
if (null == pks) {
return this;
}
for (String pk : pks) {
if (BasicUtil.isEmpty(pk)) {
continue;
}
pk = key(pk);
if (!primaryKeys.contains(pk)) {
primaryKeys.add(pk);
}
}
if (applyItem) {
for (DataRow row : rows) {
row.setPrimaryKey(false, primaryKeys);
}
}
return this;
}
public DataSet addPrimaryKey(Collection<String> pks) {
return addPrimaryKey(true, pks);
}
/**
* 设置主键
*
* @param applyItem applyItem
* @param pks pks
* @return return
*/
public DataSet setPrimaryKey(boolean applyItem, String... pks) {
if (null != pks) {
List<String> list = new ArrayList<>();
for (String pk : pks) {
list.add(pk);
}
setPrimaryKey(applyItem, list);
}
return this;
}
public DataSet setPrimaryKey(String... pks) {
return setPrimaryKey(true, pks);
}
public DataSet setPrimaryKey(boolean applyItem, Collection<String> pks) {
if (null == pks) {
return this;
}
this.primaryKeys = new ArrayList<>();
addPrimaryKey(applyItem, pks);
return this;
}
public DataSet setPrimaryKey(Collection<String> pks) {
return setPrimaryKey(true, pks);
}
public DataSet set(int index, DataRow item) {
rows.set(index, item);
return this;
}
/**
* 是否有主键
*
* @return return
*/
public boolean hasPrimaryKeys() {
if (null != primaryKeys && primaryKeys.size() > 0) {
return true;
} else {
return false;
}
}
/**
* 提取主键
*
* @return return
*/
public List<String> getPrimaryKeys() {
if (null == primaryKeys) {
primaryKeys = new ArrayList<>();
}
return primaryKeys;
}
/**
* 添加表头
*
* @param col col
* @return return
*/
public DataSet addHead(String col) {
if (null == head) {
head = new ArrayList<>();
}
if ("ROW_NUMBER".equals(col)) {
return this;
}
if (head.contains(col)) {
return this;
}
head.add(col);
return this;
}
/**
* 表头
*
* @return return
*/
public List<String> getHead() {
return head;
}
public int indexOf(Object obj) {
return rows.indexOf(obj);
}
/**
* 从begin开始截断到end,方法执行将改变原DataSet长度
*
* @param begin 开始位置
* @param end 结束位置
* @return DataSet
*/
public DataSet truncates(int begin, int end) {
if (!rows.isEmpty()) {
if (begin < 0) {
begin = 0;
}
if (end >= rows.size()) {
end = rows.size() - 1;
}
if (begin >= rows.size()) {
begin = rows.size() - 1;
}
if (end <= 0) {
end = 0;
}
rows = rows.subList(begin, end);
}
return this;
}
/**
* 从begin开始截断到最后一个
*
* @param begin 开始位置
* @return DataSet
*/
public DataSet truncates(int begin) {
if (begin < 0) {
begin = rows.size() + begin;
int end = rows.size() - 1;
return truncates(begin, end);
} else {
return truncates(begin, rows.size() - 1);
}
}
/**
* 从begin开始截断到最后一个并返回其中第一个DataRow
*
* @param begin 开始位置
* @return DataRow
*/
public DataRow truncate(int begin) {
return truncate(begin, rows.size() - 1);
}
/**
* 从begin开始截断到end位置并返回其中第一个DataRow
*
* @param begin 开始位置
* @param end 结束位置
* @return DataRow
*/
public DataRow truncate(int begin, int end) {
truncates(begin, end);
if (rows.size() > 0) {
return rows.get(0);
} else {
return null;
}
}
/**
* 从begin开始截取到最后一个
*
* @param begin 开始位置
* 如果输入负数则取后n个,如果造成数量不足,则取全部
* @return DataSet
*/
public DataSet cuts(int begin) {
if (begin < 0) {
begin = rows.size() + begin;
int end = rows.size() - 1;
return cuts(begin, end);
} else {
return cuts(begin, rows.size() - 1);
}
}
/**
* 从begin开始截取到end位置,方法执行时会创建新的DataSet并不改变原有set长度
*
* @param begin 开始位置
* @param end 结束位置
* @return DataSet
*/
public DataSet cuts(int begin, int end) {
DataSet result = new DataSet();
if (rows.isEmpty()) {
return result;
}
if (begin < 0) {
begin = 0;
}
if (end >= rows.size()) {
end = rows.size() - 1;
}
if (begin >= rows.size()) {
begin = rows.size() - 1;
}
if (end <= 0) {
end = 0;
}
for (int i = begin; i <= end; i++) {
result.add(rows.get(i));
}
return result;
}
/**
* 从begin开始截取到最后一个,并返回其中第一个DataRow
*
* @param begin 开始位置
* @return DataSet
*/
public DataRow cut(int begin) {
return cut(begin, rows.size() - 1);
}
/**
* 从begin开始截取到end位置,并返回其中第一个DataRow,方法执行时会创建新的DataSet并不改变原有set长度
*
* @param begin 开始位置
* @param end 结束位置
* @return DataSet
*/
public DataRow cut(int begin, int end) {
DataSet result = cuts(begin, end);
if (result.size() > 0) {
return result.getRow(0);
}
return null;
}
/**
* 记录数量
*
* @return return
*/
public int size() {
int result = 0;
if (null != rows)
result = rows.size();
return result;
}
public int getSize() {
return size();
}
/**
* 是否出现异常
*
* @return return
*/
public boolean isException() {
return null != exception;
}
public boolean isFromCache() {
return isFromCache;
}
public DataSet setIsFromCache(boolean bol) {
this.isFromCache = bol;
return this;
}
/**
* 返回数据是否为空
*
* @return return
*/
public boolean isEmpty() {
boolean result = true;
if (null == rows) {
result = true;
} else if (rows instanceof Collection) {
result = ((Collection<?>) rows).isEmpty();
}
return result;
}
/**
* 读取一行数据
*
* @param index index
* @return return
*/
public DataRow getRow(int index) {
DataRow row = null;
if (null != rows && index < rows.size()) {
row = rows.get(index);
}
if (null != row) {
row.setContainer(this);
}
return row;
}
public boolean exists(String ... params){
DataRow row = getRow(0, params);
return row != null;
}
public DataRow getRow(String... params) {
return getRow(0, params);
}
public DataRow getRow(DataRow params) {
return getRow(0, params);
}
public DataRow getRow(List<String> params) {
String[] kvs = BeanUtil.list2array(params);
return getRow(0, kvs);
}
public DataRow getRow(int begin, String... params) {
DataSet set = getRows(begin, 1, params);
if (set.size() > 0) {
return set.getRow(0);
}
return null;
}
public DataRow getRow(int begin, DataRow params) {
DataSet set = getRows(begin, 1, params);
if (set.size() > 0) {
return set.getRow(0);
}
return null;
}
/**
* 根据keys去重
*
* @param keys keys
* @return DataSet
*/
public DataSet distinct(String... keys) {
DataSet result = new DataSet();
if (null != rows) {
int size = rows.size();
for (int i = 0; i < size; i++) {
DataRow row = rows.get(i);
//查看result中是否已存在
String[] params = packParam(row, keys);
if (result.getRow(params) == null) {
DataRow tmp = new DataRow();
for (String key : keys) {
tmp.put(key, row.get(key));
}
result.addRow(tmp);
}
}
}
result.cloneProperty(this);
return result;
}
public DataSet distinct(List<String> keys) {
DataSet result = new DataSet();
if (null != rows) {
for (DataRow row:rows) {
//查看result中是否已存在
String[] params = packParam(row, keys);
if (result.getRow(params) == null) {
DataRow tmp = new DataRow();
for (String key : keys) {
tmp.put(key, row.get(key));
}
result.addRow(tmp);
}
}
}
result.cloneProperty(this);
return result;
}
public Object clone() {
DataSet set = new DataSet();
List<DataRow> rows = new ArrayList<DataRow>();
for (DataRow row : this.rows) {
rows.add((DataRow) row.clone());
}
set.setRows(rows);
set.cloneProperty(this);
return set;
}
private DataSet cloneProperty(DataSet from) {
return cloneProperty(from, this);
}
public static DataSet cloneProperty(DataSet from, DataSet to) {
if (null != from && null != to) {
to.exception = from.exception;
to.message = from.message;
to.navi = from.navi;
to.head = from.head;
to.primaryKeys = from.primaryKeys;
to.dataSource = from.dataSource;
to.datalink = from.datalink;
to.schema = from.schema;
to.table = from.table;
}
return to;
}
/**
* 指定key转换成number
* @param keys keys
* @return DataRow
*/
public DataSet convertNumber(String ... keys){
if(null != keys) {
for(DataRow row:rows){
row.convertNumber(keys);
}
}
return this;
}
public DataSet convertString(String ... keys){
if(null != keys) {
for(DataRow row:rows){
row.convertString(keys);
}
}
return this;
}
public DataSet skip(boolean skip){
for(DataRow row:rows){
row.skip = skip;
}
return this;
}
/**
* 筛选符合条件的集合
* 注意如果String类型 1与1.0比较不相等, 可以先调用convertNumber转换一下数据类型
* @param params key1,value1,key2:value2,key3,value3
* "NM:zh%","AGE:>20","NM","%zh%"
* @param begin begin
* @param qty 最多筛选多少个 0表示不限制
* @return return
*/
public DataSet getRows(int begin, int qty, String... params) {
DataSet set = new DataSet();
Map<String, String> kvs = new HashMap<String, String>();
int len = params.length;
int i = 0;
String srcFlagTag = "srcFlag"; //参数含有{}的 在kvs中根据key值+tag 放入一个新的键值对,如时间格式TIME:{10:10}
while (i < len) {
String p1 = params[i];
if (BasicUtil.isEmpty(p1)) {
i++;
continue;
} else if (p1.contains(":")) {
String ks[] = BeanUtil.parseKeyValue(p1);
kvs.put(ks[0], ks[1]);
i++;
continue;
} else {
if (i + 1 < len) {
String p2 = params[i + 1];
if (BasicUtil.isEmpty(p2) || !p2.contains(":")) {
kvs.put(p1, p2);
i += 2;
continue;
} else if (p2.startsWith("{") && p2.endsWith("}")) {
p2 = p2.substring(1, p2.length() - 1);
kvs.put(p1, p2);
kvs.put(p1 + srcFlagTag, "true");
i += 2;
continue;
} else {
String ks[] = BeanUtil.parseKeyValue(p2);
kvs.put(ks[0], ks[1]);
i += 2;
continue;
}
}
}
i++;
}
return getRows(begin, qty, kvs);
}
public DataSet getRows(int begin, int qty, DataRow kvs) {
Map<String,String> map = new HashMap<String,String>();
for(String k:kvs.keySet()){
map.put(k, kvs.getString(k));
}
return getRows(begin, qty, map);
}
public DataSet getRows(int begin, int qty, Map<String, String> kvs) {
DataSet set = new DataSet();
String srcFlagTag = "srcFlag"; //参数含有{}的 在kvs中根据key值+tag 放入一个新的键值对
BigDecimal d1;
BigDecimal d2;
for (DataRow row:rows) {
if(row.skip){
continue;
}
boolean chk = true;//对比结果
for (String k : kvs.keySet()) {
boolean srcFlag = false;
if (k.endsWith(srcFlagTag)) {
continue;
} else {
String srcFlagValue = kvs.get(k + srcFlagTag);
if (BasicUtil.isNotEmpty(srcFlagValue)) {
srcFlag = true;
}
}
String v = kvs.get(k);
Object value = row.get(k);
if(!row.containsKey(k) && null == value){
//注意这里有可能是个复合key
chk = false;
break;
}
if (null == v) {
if (null != value) {
chk = false;
break;
}else{
continue;
}
} else {
if (null == value) {
chk = false;
break;
}
//与SQL.COMPARE_TYPE保持一致
int compare = 10;
if (v.startsWith("=")) {
compare = 10;
v = v.substring(1);
} else if (v.startsWith(">")) {
compare = 20;
v = v.substring(1);
} else if (v.startsWith(">=")) {
compare = 21;
v = v.substring(2);
} else if (v.startsWith("<")) {
compare = 30;
v = v.substring(1);
} else if (v.startsWith("<=")) {
compare = 31;
v = v.substring(2);
} else if (v.startsWith("%") && v.endsWith("%")) {
compare = 50;
v = v.substring(1, v.length() - 1);
} else if (v.endsWith("%")) {
compare = 51;
v = v.substring(0, v.length() - 1);
} else if (v.startsWith("%")) {
compare = 52;
v = v.substring(1);
}
if(compare <= 31 && value instanceof Number) {
try {
d1 = new BigDecimal(value.toString());
d2 = new BigDecimal(v);
int cr = d1.compareTo(d2);
if (compare == 10) {
if (cr != 0) {
chk = false;
break;
}
} else if (compare == 20) {
if (cr <= 0) {
chk = false;
break;
}
} else if (compare == 21) {
if (cr < 0) {
chk = false;
break;
}
} else if (compare == 30) {
if (cr >= 0) {
chk = false;
break;
}
} else if (compare == 31) {
if (cr > 0) {
chk = false;
break;
}
}
}catch (NumberFormatException e){
chk = false;
break;
}
}
String str = value + "";
str = str.toLowerCase();
v = v.toLowerCase();
if (srcFlag) {
v = "{" + v + "}";
}
if (compare == 10) {
if (!v.equals(str)) {
chk = false;
break;
}
} else if (compare == 50) {
if (!str.contains(v)) {
chk = false;
break;
}
} else if (compare == 51) {
if (!str.startsWith(v)) {
chk = false;
break;
}
} else if (compare == 52) {
if (!str.endsWith(v)) {
chk = false;
break;
}
}
}
}//end for kvs
if (chk) {
set.add(row);
if (qty > 0 && set.size() >= qty) {
break;
}
}
}//end for rows
set.cloneProperty(this);
return set;
}
public DataSet getRows(int begin, String... params) {
return getRows(begin, -1, params);
}
public DataSet getRows(String... params) {
return getRows(0, params);
}
public DataSet getRows(DataSet set, String key) {
String kvs[] = new String[set.size()];
int i = 0;
for (DataRow row : set) {
String value = row.getString(key);
if (BasicUtil.isNotEmpty(value)) {
kvs[i++] = key + ":" + value;
}
}
return getRows(kvs);
}
public DataSet getRows(DataRow row, String... keys) {
List<String> list = new ArrayList<>();
int i = 0;
for (String key : keys) {
String value = row.getString(key);
if (BasicUtil.isNotEmpty(value)) {
list.add(key + ":" + value);
}
}
String[] kvs = BeanUtil.list2array(list);
return getRows(kvs);
}
/**
* 数字格式化
*
* @param format format
* @param cols cols
* @return return
*/
public DataSet formatNumber(String format, String... cols) {
if (null == cols || BasicUtil.isEmpty(format)) {
return this;
}
int size = size();
for (int i = 0; i < size; i++) {
DataRow row = getRow(i);
row.formatNumber(format, cols);
}
return this;
}
public DataSet numberFormat(String target, String key, String format){
for(DataRow row: rows){
numberFormat(target, key, format);
}
return this;
}
public DataSet numberFormat(String key, String format){
return numberFormat(key, key, format);
}
/**
* 日期格式化
*
* @param format format
* @param cols cols
* @return return
*/
public DataSet formatDate(String format, String... cols) {
if (null == cols || BasicUtil.isEmpty(format)) {
return this;
}
int size = size();
for (int i = 0; i < size; i++) {
DataRow row = getRow(i);
row.formatDate(format, cols);
}
return this;
}
public DataSet dateFormat(String target, String key, String format){
for(DataRow row: rows){
dateFormat(target, key, format);
}
return this;
}
public DataSet dateFormat(String key, String format){
return dateFormat(key, key, format);
}
/**
* 提取符合指定属性值的集合
*
* @param begin begin
* @param end end
* @param key key
* @param value value
* @return return
*/
public DataSet filter(int begin, int end, String key, String value) {
DataSet set = new DataSet();
String tmpValue;
int size = size();
if (begin < 0) {
begin = 0;
}
for (int i = begin; i < size && i <= end; i++) {
tmpValue = getString(i, key, "");
if ((null == value && null == tmpValue)
|| (null != value && value.equals(tmpValue))) {
set.add(getRow(i));
}
}
set.cloneProperty(this);
return set;
}
public DataSet getRows(int fr, int to) {
DataSet set = new DataSet();
int size = this.size();
if (fr < 0) {
fr = 0;
}
for (int i = fr; i < size && i <= to; i++) {
set.addRow(getRow(i));
}
return set;
}
/**
* 合计
* @param begin 开始
* @param end 结束
* @param key key
* @return BigDecimal
*/
public BigDecimal sum(int begin, int end, String key) {
BigDecimal result = BigDecimal.ZERO;
int size = rows.size();
if (begin <= 0) {
begin = 0;
}
for (int i = begin; i < size && i <= end; i++) {
BigDecimal tmp = getDecimal(i, key, 0);
if (null != tmp) {
result = result.add(getDecimal(i, key, 0));
}
}
return result;
}
public BigDecimal sum(String key) {
BigDecimal result = BigDecimal.ZERO;
result = sum(0, size() - 1, key);
return result;
}
/**
* 多列合计
* @param result 保存合计结果
* @param keys keys
* @return DataRow
*/
public DataRow sums(DataRow result, String... keys) {
if(null == result){
result = new DataRow();
}
if (size() > 0) {
if (null != keys) {
for (String key : keys) {
result.put(key, sum(key));
}
} else {
List<String> numberKeys = getRow(0).numberKeys();
for (String key : numberKeys) {
result.put(key, sum(key));
}
}
}
return result;
}
public DataRow sums(String... keys) {
return sums(new DataRow(), keys);
}
/**
* 多列平均值
*
* @param result 保存合计结果
* @param keys keys
* @return DataRow
*/
public DataRow avgs(DataRow result, String... keys) {
if(null == result){
result = new DataRow();
}
if (size() > 0) {
if (null != keys) {
for (String key : keys) {
result.put(key, avg(key));
}
} else {
List<String> numberKeys = getRow(0).numberKeys();
for (String key : numberKeys) {
result.put(key, avg(key));
}
}
}
return result;
}
public DataRow avgs(String... keys) {
return avgs(new DataRow(), keys);
}
/**
* 多列平均值
* @param result 保存合计结果
* @param scale scale
* @param round round
* @param keys keys
* @return DataRow
*/
public DataRow avgs(DataRow result, int scale, int round, String... keys) {
if(null == result){
result = new DataRow();
}
if (size() > 0) {
if (null != keys) {
for (String key : keys) {
result.put(key, avg(key, scale, round));
}
} else {
List<String> numberKeys = getRow(0).numberKeys();
for (String key : numberKeys) {
result.put(key, avg(key, scale, round));
}
}
}
return result;
}
public DataRow avgs(int scale, int round, String... keys) {
return avgs(new DataRow(), scale, round, keys);
}
/**
* 最大值
*
* @param top 多少行
* @param key key
* @return return
*/
public BigDecimal maxDecimal(int top, String key) {
BigDecimal result = null;
int size = rows.size();
if (size > top) {
size = top;
}
for (int i = 0; i < size; i++) {
BigDecimal tmp = getDecimal(i, key, 0);
if (null != tmp && (null == result || tmp.compareTo(result) > 0)) {
result = tmp;
}
}
return result;
}
public BigDecimal maxDecimal(String key) {
return maxDecimal(size(), key);
}
public int maxInt(int top, String key) {
BigDecimal result = maxDecimal(top, key);
if (null == result) {
return 0;
}
return result.intValue();
}
public int maxInt(String key) {
return maxInt(size(), key);
}
public double maxDouble(int top, String key) {
BigDecimal result = maxDecimal(top, key);
if (null == result) {
return 0;
}
return result.doubleValue();
}
public double maxDouble(String key) {
return maxDouble(size(), key);
}
// public BigDecimal max(int top, String key){
// BigDecimal result = maxDecimal(top, key);
// return result;
// }
// public BigDecimal max(String key){
// return maxDecimal(size(), key);
// }
/**
* 最小值
*
* @param top 多少行
* @param key key
* @return return
*/
public BigDecimal minDecimal(int top, String key) {
BigDecimal result = null;
int size = rows.size();
if (size > top) {
size = top;
}
for (int i = 0; i < size; i++) {
BigDecimal tmp = getDecimal(i, key, 0);
if (null != tmp && (null == result || tmp.compareTo(result) < 0)) {
result = tmp;
}
}
return result;
}
public BigDecimal minDecimal(String key) {
return minDecimal(size(), key);
}
public int minInt(int top, String key) {
BigDecimal result = minDecimal(top, key);
if (null == result) {
return 0;
}
return result.intValue();
}
public int minInt(String key) {
return minInt(size(), key);
}
public double minDouble(int top, String key) {
BigDecimal result = minDecimal(top, key);
if (null == result) {
return 0;
}
return result.doubleValue();
}
public double minDouble(String key) {
return minDouble(size(), key);
}
// public BigDecimal min(int top, String key){
// BigDecimal result = minDecimal(top, key);
// return result;
// }
// public BigDecimal min(String key){
// return minDecimal(size(), key);
// }
/**
* key对应的value最大的一行
*
* @param key key
* @return return
*/
public DataRow max(String key) {
int size = size();
if (size == 0) {
return null;
}
DataRow row = null;
if (isAsc) {
row = getRow(size - 1);
} else if (isDesc) {
row = getRow(0);
} else {
asc(key);
row = getRow(size - 1);
}
return row;
}
public DataRow min(String key) {
int size = size();
if (size == 0) {
return null;
}
DataRow row = null;
if (isAsc) {
row = getRow(0);
} else if (isDesc) {
row = getRow(size - 1);
} else {
asc(key);
row = getRow(0);
}
return row;
}
/**
* 平均值 空数据不参与加法但参与除法
*
* @param top 多少行
* @param key key
* @param scale scale
* @param round round
* @return return
*/
public BigDecimal avg(int top, String key, int scale, int round) {
BigDecimal result = BigDecimal.ZERO;
int size = rows.size();
if (size > top) {
size = top;
}
int count = 0;
for (int i = 0; i < size; i++) {
BigDecimal tmp = getDecimal(i, key, 0);
if (null != tmp) {
result = result.add(tmp);
}
count++;
}
if (count > 0) {
result = result.divide(new BigDecimal(count), scale, round);
}
return result;
}
public BigDecimal avg(String key, int scale, int round) {
BigDecimal result = avg(size(), key, scale ,round);
return result;
}
public BigDecimal avg(String key) {
BigDecimal result = avg(size(), key, 2, BigDecimal.ROUND_HALF_UP);
return result;
}
public DataSet addRow(DataRow row) {
if (null != row) {
rows.add(row);
}
return this;
}
public DataSet addRow(int idx, DataRow row) {
if (null != row) {
rows.add(idx, row);
}
return this;
}
/**
* 合并key例的值 以connector连接
*
* @param key key
* @param connector connector
* @return return v1,v2,v3
*/
public String concat(String key, String connector) {
return BasicUtil.concat(getStrings(key), connector);
}
public String concatNvl(String key, String connector) {
return BasicUtil.concat(getNvlStrings(key), connector);
}
/**
* 合并key例的值 以connector连接(不取null值)
*
* @param key key
* @param connector connector
* @return return v1,v2,v3
*/
public String concatWithoutNull(String key, String connector) {
return BasicUtil.concat(getStringsWithoutNull(key), connector);
}
/**
* 合并key例的值 以connector连接(不取空值)
*
* @param key key
* @param connector connector
* @return return v1,v2,v3
*/
public String concatWithoutEmpty(String key, String connector) {
return BasicUtil.concat(getStringsWithoutEmpty(key), connector);
}
public String concatNvl(String key) {
return BasicUtil.concat(getNvlStrings(key), ",");
}
public String concatWithoutNull(String key) {
return BasicUtil.concat(getStringsWithoutNull(key), ",");
}
public String concatWithoutEmpty(String key) {
return BasicUtil.concat(getStringsWithoutEmpty(key), ",");
}
public String concat(String key) {
return BasicUtil.concat(getStrings(key), ",");
}
/**
* 提取单列值
*
* @param key key
* @return return
*/
public List<Object> fetchValues(String key) {
List<Object> result = new ArrayList<Object>();
for (int i = 0; i < size(); i++) {
result.add(get(i, key));
}
return result;
}
/**
* 取单列不重复的值
*
* @param key key
* @return return
*/
public List<String> fetchDistinctValue(String key) {
List<String> result = new ArrayList<>();
for (int i = 0; i < size(); i++) {
String value = getString(i, key, "");
if (result.contains(value)) {
continue;
}
result.add(value);
}
return result;
}
public List<String> fetchDistinctValues(String key) {
return fetchDistinctValue(key);
}
/**
* 分页
*
* @param link link
* @return return
*/
public String displayNavi(String link) {
String result = "";
if (null != navi) {
result = navi.getHtml();
}
return result;
}
public String navi(String link) {
return displayNavi(link);
}
public String displayNavi() {
return displayNavi(null);
}
public String navi() {
return displayNavi(null);
}
public DataSet put(int idx, String key, Object value) {
DataRow row = getRow(idx);
if (null != row) {
row.put(key, value);
}
return this;
}
public DataSet removes(String... keys) {
for (DataRow row : rows) {
row.removes(keys);
}
return this;
}
/**
* String
*
* @param index index
* @param key key
* @return String
* @throws Exception Exception
*/
public String getString(int index, String key) throws Exception {
return getRow(index).getString(key);
}
public String getString(int index, String key, String def) {
try {
return getString(index, key);
} catch (Exception e) {
return def;
}
}
public String getString(String key) throws Exception {
return getString(0, key);
}
public String getString(String key, String def) {
return getString(0, key, def);
}
public Object get(int index, String key) {
DataRow row = getRow(index);
if (null != row) {
return row.get(key);
}
return null;
}
public List<Object> gets(String key) {
List<Object> list = new ArrayList<Object>();
for (DataRow row : rows) {
list.add(row.getString(key));
}
return list;
}
public List<DataSet> getSets(String key) {
List<DataSet> list = new ArrayList<DataSet>();
for (DataRow row : rows) {
DataSet set = row.getSet(key);
if (null != set) {
list.add(set);
}
}
return list;
}
public List<String> getStrings(String key) {
List<String> result = new ArrayList<>();
for (DataRow row : rows) {
result.add(row.getString(key));
}
return result;
}
public List<Integer> getInts(String key) throws Exception {
List<Integer> result = new ArrayList<Integer>();
for (DataRow row : rows) {
result.add(row.getInt(key));
}
return result;
}
public List<Object> getObjects(String key) {
List<Object> result = new ArrayList<Object>();
for (DataRow row : rows) {
result.add(row.get(key));
}
return result;
}
public List<String> getDistinctStrings(String key) {
return fetchDistinctValue(key);
}
public List<String> getNvlStrings(String key) {
List<String> result = new ArrayList<>();
List<Object> list = fetchValues(key);
for (Object val : list) {
if (null != val) {
result.add(val.toString());
} else {
result.add("");
}
}
return result;
}
public List<String> getStringsWithoutEmpty(String key) {
List<String> result = new ArrayList<>();
List<Object> list = fetchValues(key);
for (Object val : list) {
if (BasicUtil.isNotEmpty(val)) {
result.add(val.toString());
}
}
return result;
}
public List<String> getStringsWithoutNull(String key) {
List<String> result = new ArrayList<>();
List<Object> list = fetchValues(key);
for (Object val : list) {
if (null != val) {
result.add(val.toString());
}
}
return result;
}
public BigDecimal getDecimal(int idx, String key) throws Exception {
return getRow(idx).getDecimal(key);
}
public BigDecimal getDecimal(int idx, String key, double def) {
return getDecimal(idx, key, new BigDecimal(def));
}
public BigDecimal getDecimal(int idx, String key, BigDecimal def) {
try {
BigDecimal val = getDecimal(idx, key);
if (null == val) {
return def;
}
return val;
} catch (Exception e) {
return def;
}
}
/**
* 抽取指定列生成新的DataSet 新的DataSet只包括指定列的值与分页信息,不包含其他附加信息(如来源表)
* @param keys keys
* @return DataSet
*/
public DataSet extract(String ... keys){
DataSet result = new DataSet();
for(DataRow row:rows){
DataRow item = row.extract(keys);
result.add(item);
}
result.navi = this.navi;
return result;
}
public DataSet extract(List<String> keys){
DataSet result = new DataSet();
for(DataRow row:rows){
DataRow item = row.extract(keys);
result.add(item);
}
result.navi = this.navi;
return result;
}
/**
* html格式(未实现)
*
* @param index index
* @param key key
* @return return
* @throws Exception Exception
*/
public String getHtmlString(int index, String key) throws Exception {
return getString(index, key);
}
public String getHtmlString(int index, String key, String def) {
return getString(index, key, def);
}
public String getHtmlString(String key) throws Exception {
return getHtmlString(0, key);
}
/**
* escape String
*
* @param index index
* @param key key
* @return return
* @throws Exception Exception
*/
public String getEscapeString(int index, String key) throws Exception {
return EscapeUtil.escape(getString(index, key)).toString();
}
public String getEscapeString(int index, String key, String def) {
try {
return getEscapeString(index, key);
} catch (Exception e) {
return EscapeUtil.escape(def).toString();
}
}
public String getDoubleEscapeString(int index, String key) throws Exception {
return EscapeUtil.doubleEscape(getString(index, key));
}
public String getDoubleEscapeString(int index, String key, String def) {
try {
return getDoubleEscapeString(index, key);
} catch (Exception e) {
return EscapeUtil.doubleEscape(def);
}
}
public String getEscapeString(String key) throws Exception {
return getEscapeString(0, key);
}
public String getDoubleEscapeString(String key) throws Exception {
return getDoubleEscapeString(0, key);
}
/**
* int
*
* @param index index
* @param key key
* @return return
* @throws Exception Exception
*/
public int getInt(int index, String key) throws Exception {
return getRow(index).getInt(key);
}
public int getInt(int index, String key, int def) {
try {
return getInt(index, key);
} catch (Exception e) {
return def;
}
}
public int getInt(String key) throws Exception {
return getInt(0, key);
}
public int getInt(String key, int def) {
return getInt(0, key, def);
}
/**
* double
*
* @param index index
* @param key key
* @return return
* @throws Exception Exception
*/
public double getDouble(int index, String key) throws Exception {
return getRow(index).getDouble(key);
}
public double getDouble(int index, String key, double def) {
try {
return getDouble(index, key);
} catch (Exception e) {
return def;
}
}
public double getDouble(String key) throws Exception {
return getDouble(0, key);
}
public double getDouble(String key, double def) {
return getDouble(0, key, def);
}
/**
* 在key列基础上 +value,如果原来没有key列则默认0并put到target
* @param target 计算结果key
* @param key key
* @param value value
* @return this
*/
public DataSet add(String target, String key, int value){
for(DataRow row:rows){
row.add(target, key, value);
}
return this;
}
public DataSet add(String target, String key, double value){
for(DataRow row:rows){
row.add(target, key, value);
}
return this;
}
public DataSet add(String target, String key, short value){
for(DataRow row:rows){
row.add(target, key, value);
}
return this;
}
public DataSet add(String target, String key, float value){
for(DataRow row:rows){
row.add(target, key, value);
}
return this;
}
public DataSet add(String target, String key, BigDecimal value){
for(DataRow row:rows){
row.add(target, key, value);
}
return this;
}
public DataSet add(String key, int value){
return add(key, key, value);
}
public DataSet add(String key, double value){
return add(key, key, value);
}
public DataSet add(String key, short value){
return add(key, key, value);
}
public DataSet add(String key, float value){
return add(key, key, value);
}
public DataSet add(String key, BigDecimal value){
return add(key, key, value);
}
public DataSet subtract(String target, String key, int value){
for(DataRow row:rows){
row.subtract(target, key, value);
}
return this;
}
public DataSet subtract(String target, String key, double value){
for(DataRow row:rows){
row.subtract(target, key, value);
}
return this;
}
public DataSet subtract(String target, String key, short value){
for(DataRow row:rows){
row.subtract(target, key, value);
}
return this;
}
public DataSet subtract(String target, String key, float value){
for(DataRow row:rows){
row.subtract(target, key, value);
}
return this;
}
public DataSet subtract(String target, String key, BigDecimal value){
for(DataRow row:rows){
row.subtract(target, key, value);
}
return this;
}
public DataSet subtract(String key, int value){
return subtract(key, key, value);
}
public DataSet subtract(String key, double value){
return subtract(key, key, value);
}
public DataSet subtract(String key, short value){
return subtract(key, key, value);
}
public DataSet subtract(String key, float value){
return subtract(key, key, value);
}
public DataSet subtract(String key, BigDecimal value){
return subtract(key, key, value);
}
public DataSet multiply(String target, String key, int value){
for(DataRow row:rows){
row.multiply(target, key, value);
}
return this;
}
public DataSet multiply(String target, String key, double value){
for(DataRow row:rows){
row.multiply(target, key, value);
}
return this;
}
public DataSet multiply(String target, String key, short value){
for(DataRow row:rows){
row.multiply(target, key, value);
}
return this;
}
public DataSet multiply(String target, String key, float value){
for(DataRow row:rows){
row.multiply(target, key, value);
}
return this;
}
public DataSet multiply(String target, String key, BigDecimal value){
for(DataRow row:rows){
row.multiply(target, key, value);
}
return this;
}
public DataSet multiply(String key, int value){
return multiply(key,key,value);
}
public DataSet multiply(String key, double value){
return multiply(key,key,value);
}
public DataSet multiply(String key, short value){
return multiply(key,key,value);
}
public DataSet multiply(String key, float value){
return multiply(key,key,value);
}
public DataSet multiply(String key, BigDecimal value){
return multiply(key,key,value);
}
public DataSet divide(String target, String key, int value){
for(DataRow row:rows){
row.divide(target, key, value);
}
return this;
}
public DataSet divide(String target, String key, double value){
for(DataRow row:rows){
row.divide(target, key, value);
}
return this;
}
public DataSet divide(String target, String key, short value){
for(DataRow row:rows){
row.divide(target, key, value);
}
return this;
}
public DataSet divide(String target, String key, float value){
for(DataRow row:rows){
row.divide(target, key, value);
}
return this;
}
public DataSet divide(String target, String key, BigDecimal value, int mode){
for(DataRow row:rows){
row.divide(target, key, value, mode);
}
return this;
}
public DataSet divide(String key, int value){
return divide(key,key, value);
}
public DataSet divide(String key, double value){
return divide(key,key, value);
}
public DataSet divide(String key, short value){
return divide(key,key, value);
}
public DataSet divide(String key, float value){
return divide(key,key, value);
}
public DataSet divide(String key, BigDecimal value, int mode){
return divide(key,key, value, mode);
}
public DataSet round(String target, String key, int scale, int mode){
for (DataRow row:rows){
row.round(target, key, scale, mode);
}
return this;
}
public DataSet round(String key, int scale, int mode){
return round(key, key, scale, mode);
}
/**
* DataSet拆分成size部分
* @param page 拆成多少部分
* @return list
*/
public List<DataSet> split(int page){
List<DataSet> list = new ArrayList<>();
int size = this.size();
int vol = size / page;//每页多少行
for(int i=0; i<page; i++){
int fr = i*vol;
int to = (i+1)*vol-1;
if(i == page-1){
to = size-1;
}
DataSet set = this.cuts(fr, to);
list.add(set);
}
return list;
}
/**
* rows 列表中的数据格式化成json格式 不同与toJSON
* map.put("type", "list");
* map.put("result", result);
* map.put("message", message);
* map.put("rows", rows);
* map.put("success", result);
* map.put("navi", navi);
*/
public String toString() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("type", "list");
map.put("result", result);
map.put("message", message);
map.put("rows", rows);
map.put("success", result);
if(null != navi){
Map<String,Object> navi_ = new HashMap<String,Object>();
navi_.put("page", navi.getCurPage());
navi_.put("pages", navi.getTotalPage());
navi_.put("rows", navi.getTotalRow());
navi_.put("vol", navi.getPageRows());
map.put("navi", navi_);
}
return BeanUtil.map2json(map);
}
/**
* rows 列表中的数据格式化成json格式 不同与toString
*
* @return return
*/
public String toJson() {
return BeanUtil.object2json(this);
}
public String getJson() {
return toJSON();
}
public String toJSON() {
return toJson();
}
/**
* 根据指定列生成map
*
* @param key ID,{ID}_{NM}
* @return return
*/
public Map<String, DataRow> toMap(String key) {
Map<String, DataRow> maps = new HashMap<String, DataRow>();
for (DataRow row : rows) {
maps.put(row.getString(key), row);
}
return maps;
}
/**
* 子类
*
* @param idx idx
* @return return
*/
public Object getChildren(int idx) {
DataRow row = getRow(idx);
if (null != row) {
return row.getChildren();
}
return null;
}
public Object getChildren() {
return getChildren(0);
}
public DataSet setChildren(int idx, Object children) {
DataRow row = getRow(idx);
if (null != row) {
row.setChildren(children);
}
return this;
}
public DataSet setChildren(Object children) {
setChildren(0, children);
return this;
}
/**
* 父类
*
* @param idx idx
* @return return
*/
public Object getParent(int idx) {
DataRow row = getRow(idx);
if (null != row) {
return row.getParent();
}
return null;
}
public Object getParent() {
return getParent(0);
}
public DataSet setParent(int idx, Object parent) {
DataRow row = getRow(idx);
if (null != row) {
row.setParent(parent);
}
return this;
}
public DataSet setParent(Object parent) {
setParent(0, parent);
return this;
}
/**
* 转换成对象
*
* @param <T> T
* @param index index
* @param clazz clazz
* @return return
*/
public <T> T entity(int index, Class<T> clazz) {
DataRow row = getRow(index);
if (null != row) {
return row.entity(clazz);
}
return null;
}
/**
* 转换成对象集合
*
* @param <T> T
* @param clazz clazz
* @return return
*/
public <T> List<T> entity(Class<T> clazz) {
List<T> list = new ArrayList<T>();
if (null != rows) {
for (DataRow row : rows) {
list.add(row.entity(clazz));
}
}
return list;
}
public <T> T entity(Class<T> clazz, int idx) {
DataRow row = getRow(idx);
if (null != row) {
return row.entity(clazz);
}
return null;
}
public DataSet setDataSource(String dataSource) {
if (null == dataSource) {
return this;
}
this.dataSource = dataSource;
if (dataSource.contains(".") && !dataSource.contains(":")) {
schema = dataSource.substring(0, dataSource.indexOf("."));
table = dataSource.substring(dataSource.indexOf(".") + 1);
}
for (DataRow row : rows) {
if (BasicUtil.isEmpty(row.getDataSource())) {
row.setDataSource(dataSource);
}
}
return this;
}
/**
* 合并
* @param set DataSet
* @param keys 根据keys去重
* @return DataSet
*/
public DataSet union(DataSet set, String... keys) {
DataSet result = new DataSet();
if (null != rows) {
int size = rows.size();
for (int i = 0; i < size; i++) {
result.add(rows.get(i));
}
}
if (null == keys || keys.length == 0) {
keys = new String[1];
keys[0] = ConfigTable.getString("DEFAULT_PRIMARY_KEY");
}
int size = set.size();
for (int i = 0; i < size; i++) {
DataRow item = set.getRow(i);
if (!result.contains(item, keys)) {
result.add(item);
}
}
return result;
}
/**
* 合并合并不去重
*
* @param set set
* @return return
*/
public DataSet unionAll(DataSet set) {
DataSet result = new DataSet();
if (null != rows) {
int size = rows.size();
for (int i = 0; i < size; i++) {
result.add(rows.get(i));
}
}
int size = set.size();
for (int i = 0; i < size; i++) {
DataRow item = set.getRow(i);
result.add(item);
}
return result;
}
/**
* 是否包含这一行
*
* @param row row
* @param keys keys
* @return return
*/
public boolean contains(DataRow row, String... keys) {
if (null == rows || rows.size() == 0 || null == row) {
return false;
}
if (null == keys || keys.length == 0) {
keys = new String[1];
keys[0] = ConfigTable.getString("DEFAULT_PRIMARY_KEY", "ID");
}
String params[] = packParam(row, keys);
return exists(params);
}
public String[] packParam(DataRow row, String... keys) {
if (null == keys || null == row) {
return null;
}
String params[] = new String[keys.length * 2];
int idx = 0;
for (String key : keys) {
if (null == key) {
continue;
}
String ks[] = BeanUtil.parseKeyValue(key);
params[idx++] = ks[0];
params[idx++] = row.getString(ks[1]);
}
return params;
}
/**
* 根据数据与属性列表 封装kvs
* ["ID","1","CODE","A01"]
* @param row 数据 DataRow
* @param keys 属性 ID,CODE
* @return kvs
*/
public String[] packParam(DataRow row, List<String> keys) {
if (null == keys || null == row) {
return null;
}
String params[] = new String[keys.size() * 2];
int idx = 0;
for (String key : keys) {
if (null == key) {
continue;
}
String ks[] = BeanUtil.parseKeyValue(key);
params[idx++] = ks[0];
params[idx++] = row.getString(ks[1]);
}
return params;
}
/**
* 从items中按相应的key提取数据 存入
* dispatch("children",items, "DEPAT_CD")
* dispatchs("children",items, "CD:BASE_CD")
*
* @param field 默认"ITEMS"
* @param unique 是否只分配一次(同一个条目不能分配到多个组中)
* @param recursion 是否递归
* @param items items
* @param keys keys ID:DEPT_ID或ID
* @return return
*/
public DataSet dispatchs(String field, boolean unique, boolean recursion, DataSet items, String... keys) {
if(null == keys || keys.length == 0){
throw new RuntimeException("未指定对应关系");
}
if (null == items) {
return this;
}
if (BasicUtil.isEmpty(field)) {
field = "ITEMS";
}
for (DataRow row : rows) {
if (null == row.get(field)) {
String[] kvs = packParam(row, reverseKey(keys));
DataSet set = items.getRows(kvs);
if (recursion) {
set.dispatchs(field, unique, recursion, items, keys);
}
if(unique) {
set.skip(true);
}
row.put(field, set);
}
}
items.skip(false);
return this;
}
public DataSet dispatchs(boolean unique, boolean recursion, DataSet items, String... keys) {
return dispatchs("ITEMS", unique, recursion, items, keys);
}
public DataSet dispatchs(String field, DataSet items, String... keys) {
return dispatchs(field,false, false, items, keys);
}
public DataSet dispatchs(DataSet items, String... keys) {
return dispatchs("ITEMS", items, keys);
}
public DataSet dispatchs(boolean unique, boolean recursion, String... keys) {
return dispatchs("ITEMS", unique, recursion, this, keys);
}
public DataSet dispatchs(String field, boolean unique, boolean recursion, String... keys) {
return dispatchs(field, unique, recursion, this, keys);
}
public DataSet dispatch(String field, boolean unique, boolean recursion, DataSet items, String... keys) {
if(null == keys || keys.length == 0){
throw new RuntimeException("未指定对应关系");
}
if (null == items) {
return this;
}
if (BasicUtil.isEmpty(field)) {
field = "ITEM";
}
for (DataRow row : rows) {
if (null == row.get(field)) {
String[] params = packParam(row, reverseKey(keys));
DataRow result = items.getRow(params);
if(unique){
result.skip = true;
}
row.put(field, result);
}
}
items.skip(false);
return this;
}
public DataSet dispatch(String field, DataSet items, String... keys) {
return dispatch(field, false, false, items, keys);
}
public DataSet dispatch(DataSet items, String... keys) {
return dispatch("ITEM", items, keys);
}
public DataSet dispatch(boolean unique, boolean recursion, String... keys) {
return dispatch("ITEM", unique, recursion, this, keys);
}
public DataSet dispatch(String field, boolean unique, boolean recursion, String... keys) {
return dispatch(field, unique, recursion, this, keys);
}
/**
* 直接调用dispatchs
* @param field 默认"ITEMS"
* @param unique 是否只分配一次(同一个条目不能分配到多个组中)
* @param recursion 是否递归
* @param items items
* @param keys keys ID:DEPT_ID或ID
* @return return
*/
@Deprecated
public DataSet dispatchItems(String field, boolean unique, boolean recursion, DataSet items, String... keys) {
return dispatchs(field, unique, recursion, items, keys);
}
@Deprecated
public DataSet dispatchItems(boolean unique, boolean recursion, DataSet items, String... keys) {
return dispatchs( unique, recursion, items, keys);
}
@Deprecated
public DataSet dispatchItems(String field, DataSet items, String... keys) {
return dispatchs(field, items, keys);
}
@Deprecated
public DataSet dispatchItems(DataSet items, String... keys) {
return dispatchs(items, keys);
}
@Deprecated
public DataSet dispatchItems(boolean unique, boolean recursion, String... keys) {
return dispatchs( unique, recursion, keys);
}
@Deprecated
public DataSet dispatchItems(String field, boolean unique, boolean recursion, String... keys) {
return dispatchs(field, unique, recursion, keys);
}
@Deprecated
public DataSet dispatchItem(String field, boolean unique, boolean recursion, DataSet items, String... keys) {
return dispatch(field, unique, recursion, items, keys);
}
@Deprecated
public DataSet dispatchItem(String field, DataSet items, String... keys) {
return dispatch(field, items, keys);
}
@Deprecated
public DataSet dispatchItem(DataSet items, String... keys) {
return dispatch(items, keys);
}
@Deprecated
public DataSet dispatchItem(boolean unique, boolean recursion, String... keys) {
return dispatch(unique, recursion, keys);
}
@Deprecated
public DataSet dispatchItem(String field, boolean unique, boolean recursion, String... keys) {
return dispatch(field, unique, recursion, keys);
}
/**
* 根据keys列建立关联,并将关联出来的结果拼接到集合的条目上,如果有重复则覆盖条目
*
* @param items 被查询的集合
* @param keys 关联条件列
* @return return
*/
public DataSet join(DataSet items, String... keys) {
if (null == items || null == keys || keys.length == 0) {
return this;
}
for (DataRow row : rows) {
String[] params = packParam(row, reverseKey(keys));
DataRow result = items.getRow(params);
if (null != result) {
row.copy(result, result.keys());
}
}
return this;
}
public DataSet toLowerKey() {
for (DataRow row : rows) {
row.toLowerKey();
}
return this;
}
public DataSet toUpperKey() {
for (DataRow row : rows) {
row.toUpperKey();
}
return this;
}
/**
* 按keys分组
*
* @param keys keys
* @return return
*/
public DataSet group(String... keys) {
DataSet result = distinct(keys);
result.dispatchs(true,false, this, keys);
return result;
}
public DataSet or(DataSet set, String... keys) {
return this.union(set, keys);
}
public DataSet getRows(Map<String, String> kvs) {
return getRows(0, -1, kvs);
}
/**
* 多个集合的交集
*
* @param distinct 是否根据keys抽取不重复的集合
* @param sets 集合
* @param keys 判断依据
* @return DataSet
*/
public static DataSet intersection(boolean distinct, List<DataSet> sets, String... keys) {
DataSet result = null;
if (null != sets && sets.size() > 0) {
for (DataSet set : sets) {
if (null == result) {
result = set;
} else {
result = result.intersection(distinct, set, keys);
}
}
}
if (null == result) {
result = new DataSet();
}
return result;
}
public static DataSet intersection(List<DataSet> sets, String... keys) {
return intersection(false, sets, keys);
}
/**
* 交集
*
* @param distinct 是否根据keys抽取不重复的集合(根据keys去重)
* @param set set
* @param keys 根据keys列比较是否相等,如果列名不一致"ID:USER_ID",ID表示当前DataSet的列,USER_ID表示参数中DataSet的列
* @return return
*/
public DataSet intersection(boolean distinct, DataSet set, String... keys) {
DataSet result = new DataSet();
if (null == set) {
return result;
}
for (DataRow row : rows) {
String[] kv = reverseKey(keys);
if (set.contains(row, kv)) { //符合交集
if(!result.contains(row, kv)){//result中没有
result.add((DataRow) row.clone());
}else {
if(!distinct){//result中有但不要求distinct
result.add((DataRow) row.clone());
}
}
}
}
return result;
}
public DataSet intersection(DataSet set, String... keys) {
return intersection(false, set, keys);
}
public DataSet and(boolean distinct, DataSet set, String... keys) {
return intersection(distinct, set, keys);
}
public DataSet and(DataSet set, String... keys) {
return intersection(false, set, keys);
}
/**
* 补集
* 在this中,但不在set中
* this作为超集 set作为子集
*
* @param distinct 是否根据keys抽取不重复的集合
* @param set set
* @param keys keys
* @return return
*/
public DataSet complement(boolean distinct, DataSet set, String... keys) {
DataSet result = new DataSet();
for (DataRow row : rows) {
String[] kv = reverseKey(keys);
if (null == set || !set.contains(row, kv)) {
if (!distinct || !result.contains(row, kv)) {
result.add((DataRow) row.clone());
}
}
}
return result;
}
public DataSet complement(DataSet set, String... keys) {
return complement(false, set, keys);
}
/**
* 差集
* 从当前集合中删除set中存在的row,生成新的DataSet并不修改当前对象
* this中有 set中没有的
*
* @param distinct 是否根据keys抽取不重复的集合
* @param set set
* @param keys CD,"CD:WORK_CD"
* @return return
*/
public DataSet difference(boolean distinct, DataSet set, String... keys) {
DataSet result = new DataSet();
for (DataRow row : rows) {
String[] kv = reverseKey(keys);
if (null == set || !set.contains(row, kv)) {
if (!distinct || !result.contains(row, kv)) {
result.add((DataRow) row.clone());
}
}
}
return result;
}
public DataSet difference(DataSet set, String... keys) {
return difference(false, set, keys);
}
/**
* 颠倒kv-vk
*
* @param keys kv
* @return String[]
*/
private String[] reverseKey(String[] keys) {
if (null == keys) {
return new String[0];
}
int size = keys.length;
String result[] = new String[size];
for (int i = 0; i < size; i++) {
String key = keys[i];
if (BasicUtil.isNotEmpty(key) && key.contains(":")) {
String ks[] = BeanUtil.parseKeyValue(key);
key = ks[1] + ":" + ks[0];
}
result[i] = key;
}
return result;
}
/**
* 清除指定列全为空的行,如果不指定keys,则清除所有列都为空的行
*
* @param keys keys
* @return DataSet
*/
public DataSet removeEmptyRow(String... keys) {
int size = this.size();
for (int i = size - 1; i >= 0; i--) {
DataRow row = getRow(i);
if (null == keys || keys.length == 0) {
if (row.isEmpty()) {
this.remove(row);
}
} else {
boolean isEmpty = true;
for (String key : keys) {
if (row.isNotEmpty(key)) {
isEmpty = false;
break;
}
}
if (isEmpty) {
this.remove(row);
}
}
}
return this;
}
public DataSet changeKey(String key, String target, boolean remove) {
for(DataRow row:rows){
row.changeKey(key, target, remove);
}
return this;
}
public DataSet changeKey(String key, String target) {
return changeKey(key, target, true);
}
/**
* 删除rows中的columns列
*
* @param columns 检测的列,如果不输入则检测所有列
* @return DataSet
*/
public DataSet removeColumn(String... columns) {
if (null != columns) {
for (String column : columns) {
for (DataRow row : rows) {
row.remove(column);
}
}
}
return this;
}
/**
* 删除rows中值为空(null|'')的列
*
* @param columns 检测的列,如果不输入则检测所有列
* @return DataSet
*/
public DataSet removeEmptyColumn(String... columns) {
for (DataRow row : rows) {
row.removeEmpty(columns);
}
return this;
}
/**
* NULL > ""
*
* @return DataSet
*/
public DataSet nvl() {
for (DataRow row : rows) {
row.nvl();
}
return this;
}
/* ********************************************** 实现接口 *********************************************************** */
public boolean add(DataRow e) {
return rows.add((DataRow) e);
}
@SuppressWarnings({"rawtypes", "unchecked"})
public boolean addAll(Collection c) {
return rows.addAll(c);
}
public void clear() {
rows.clear();
}
public boolean contains(Object o) {
return rows.contains(o);
}
public boolean containsAll(Collection<?> c) {
return rows.containsAll(c);
}
public Iterator<DataRow> iterator() {
return rows.iterator();
}
public boolean remove(Object o) {
return rows.remove(o);
}
public boolean removeAll(Collection<?> c) {
return rows.removeAll(c);
}
public boolean retainAll(Collection<?> c) {
return rows.retainAll(c);
}
public Object[] toArray() {
return rows.toArray();
}
@SuppressWarnings("unchecked")
public Object[] toArray(Object[] a) {
return rows.toArray(a);
}
public String getSchema() {
return schema;
}
public DataSet setSchema(String schema) {
this.schema = schema;
return this;
}
public String getTable() {
return table;
}
public DataSet setTable(String table) {
if (null != table && table.contains(".")) {
String[] tbs = table.split("\\.");
this.table = tbs[1];
this.schema = tbs[0];
} else {
this.table = table;
}
return this;
}
/**
* 验证是否过期
* 根据当前时间与创建时间对比
* 过期返回 true
*
* @param millisecond 过期时间(毫秒) millisecond 过期时间(毫秒)
* @return boolean
*/
public boolean isExpire(int millisecond) {
if (System.currentTimeMillis() - createTime > millisecond) {
return true;
}
return false;
}
public boolean isExpire(long millisecond) {
if (System.currentTimeMillis() - createTime > millisecond) {
return true;
}
return false;
}
public boolean isExpire() {
if (getExpires() == -1) {
return false;
}
if (System.currentTimeMillis() - createTime > getExpires()) {
return true;
}
return false;
}
public long getCreateTime() {
return createTime;
}
public List<DataRow> getRows() {
return rows;
}
/************************** getter setter ***************************************/
/**
* 过期时间(毫秒)
*
* @return long
*/
public long getExpires() {
return expires;
}
public DataSet setExpires(long millisecond) {
this.expires = millisecond;
return this;
}
public DataSet setExpires(int millisecond) {
this.expires = millisecond;
return this;
}
public boolean isResult() {
return result;
}
public boolean isSuccess() {
return result;
}
public DataSet setResult(boolean result) {
this.result = result;
return this;
}
public Exception getException() {
return exception;
}
public DataSet setException(Exception exception) {
this.exception = exception;
return this;
}
public String getMessage() {
return message;
}
public DataSet setMessage(String message) {
this.message = message;
return this;
}
public PageNavi getNavi() {
return navi;
}
public DataSet setNavi(PageNavi navi) {
this.navi = navi;
return this;
}
public DataSet setRows(List<DataRow> rows) {
this.rows = rows;
return this;
}
public String getDataSource() {
String ds = table;
if (BasicUtil.isNotEmpty(ds) && BasicUtil.isNotEmpty(schema)) {
ds = schema + "." + ds;
}
if (BasicUtil.isEmpty(ds)) {
ds = dataSource;
}
return ds;
}
public DataSet order(final String... keys) {
return asc(keys);
}
public DataSet put(String key, Object value, boolean pk, boolean override) {
for (DataRow row : rows) {
row.put(key, value, pk, override);
}
return this;
}
public DataSet put(String key, Object value, boolean pk) {
for (DataRow row : rows) {
row.put(key, value, pk);
}
return this;
}
public DataSet put(String key, Object value) {
for (DataRow row : rows) {
row.put(key, value);
}
return this;
}
/**
* 行转列
* 表结构(编号, 姓名, 年度, 科目, 分数, 等级)
* @param pks 唯一标识key(如编号,姓名)
* @param classKeys 分类key(如年度,科目)
* @param valueKeys 取值key(如分数,等级),如果不指定key则将整行作为value
* @return
* 如果指定key
* 返回结构 [
* {编号:01,姓名:张三,2010-数学-分数:100},
* {编号:01,姓名:张三,2010-数学-等级:A},
* {编号:01,姓名:张三,2010-物理-分数:100}
* ]
* 如果只有一个valueKey则返回[
* {编号:01,姓名:张三,2010-数学:100},
* {编号:01,姓名:张三,2010-物理:90}
* ]
* 不指定valuekey则返回 [
* {编号:01,姓名:张三,2010-数学:{分数:100,等级:A}},
* {编号:01,姓名:张三,2010-物理:{分数:100,等级:A}}
* ]
*/
public DataSet pivot(List<String> pks, List<String> classKeys, List<String> valueKeys) {
DataSet result = distinct(pks);
DataSet classValues = distinct(classKeys); //[{年度:2010,科目:数学},{年度:2010,科目:物理},{年度:2011,科目:数学}]
for (DataRow row : result) {
for (DataRow classValue : classValues) {
DataRow params = new DataRow();
params.copy(row, pks).copy(classValue);
DataRow valueRow = getRow(params);
if(null != valueRow){
valueRow.skip = true;
}
String finalKey = concatValue(classValue,"-");//2010-数学
if(null != valueKeys && valueKeys.size() > 0){
if(valueKeys.size() == 1){
if (null != valueRow) {
row.put(finalKey, valueRow.get(valueKeys.get(0)));
} else {
row.put(finalKey, null);
}
}else {
for (String valueKey : valueKeys) {
//{2010-数学-分数:100;2010-数学-等级:A}
if (null != valueRow) {
row.put(finalKey + "-" + valueKey, valueRow.get(valueKey));
} else {
row.put(finalKey + "-" + valueKey, null);
}
}
}
}else{
if (null != valueRow){
row.put(finalKey, valueRow);
}else{
row.put(finalKey, null);
}
}
}
}
skip(false);
return result;
}
public DataSet pivot(String[] pks, String[] classKeys, String[] valueKeys) {
return pivot(Arrays.asList(pks),Arrays.asList(classKeys),Arrays.asList(valueKeys));
}
/**
* 行转列
* @param pk 唯一标识key(如姓名)多个key以,分隔如(编号,姓名)
* @param classKey 分类key(如科目)多个key以,分隔如(科目,年度)
* @param valueKey 取值key(如分数)多个key以,分隔如(分数,等级)
* @return
* 表结构(姓名,科目,分数)
* 返回结构 [{姓名:张三,数学:100,物理:90,英语:80},{姓名:李四,数学:100,物理:90,英语:80}]
*/
public DataSet pivot(String pk, String classKey, String valueKey) {
List<String> pks = new ArrayList<>(Arrays.asList(pk.trim().split(",")));
List<String> classKeys = new ArrayList<>(Arrays.asList(classKey.trim().split(",")));
List<String> valueKeys = new ArrayList<>(Arrays.asList(valueKey.trim().split(",")));
return pivot(pks, classKeys, valueKeys);
}
public DataSet pivot(String pk, String classKey) {
List<String> pks = new ArrayList<>(Arrays.asList(pk.trim().split(",")));
List<String> classKeys = new ArrayList<>(Arrays.asList(classKey.trim().split(",")));
List<String> valueKeys = new ArrayList<>();
return pivot(pks, classKeys, valueKeys);
}
public DataSet pivot(List<String> pks, List<String> classKeys, String ... valueKeys) {
List<String> list = new ArrayList<>();
if(null != valueKeys){
for(String item:valueKeys){
list.add(item);
}
}
return pivot(pks, classKeys, valueKeys);
}
private String concatValue(DataRow row, String split){
StringBuilder builder = new StringBuilder();
List<String> keys = row.keys();
for(String key:keys){
if(builder.length() > 0){
builder.append(split);
}
builder.append(row.getString(key));
}
return builder.toString();
}
private String[] kvs(DataRow row){
List<String> keys = row.keys();
int size = keys.size();
String[] kvs = new String[size*2];
for(int i=0; i<size; i++){
String k = keys.get(i);
String v = row.getStringNvl(k);
kvs[i*2] = k;
kvs[i*2+1] = v;
}
return kvs;
}
/**
* 排序
*
* @param keys keys
* @return DataSet
*/
public DataSet asc(final String... keys) {
Collections.sort(rows, new Comparator<DataRow>() {
public int compare(DataRow r1, DataRow r2) {
int result = 0;
for (String key : keys) {
Object v1 = r1.get(key);
Object v2 = r2.get(key);
if (null == v1) {
if (null == v2) {
continue;
}
return -1;
} else {
if (null == v2) {
return 1;
}
}
if (BasicUtil.isNumber(v1) && BasicUtil.isNumber(v2)) {
BigDecimal num1 = new BigDecimal(v1.toString());
BigDecimal num2 = new BigDecimal(v2.toString());
result = num1.compareTo(num2);
} else if (v1 instanceof Date && v2 instanceof Date) {
Date date1 = (Date)v1;
Date date2 = (Date)v2;
result = date1.compareTo(date2);
} else {
result = v1.toString().compareTo(v2.toString());
}
if (result != 0) {
return result;
}
}
return 0;
}
});
isAsc = true;
isDesc = false;
return this;
}
public DataSet desc(final String... keys) {
Collections.sort(rows, new Comparator<DataRow>() {
public int compare(DataRow r1, DataRow r2) {
int result = 0;
for (String key : keys) {
Object v1 = r1.get(key);
Object v2 = r2.get(key);
if (null == v1) {
if (null == v2) {
continue;
}
return 1;
} else {
if (null == v2) {
return -1;
}
}
if (BasicUtil.isNumber(v1) && BasicUtil.isNumber(v2)) {
BigDecimal val1 = new BigDecimal(v1.toString());
BigDecimal val2 = new BigDecimal(v2.toString());
result = val2.compareTo(val1);
} else if (v1 instanceof Date && v2 instanceof Date) {
Date date1 = (Date)v1;
Date date2 = (Date)v2;
result = date2.compareTo(date1);
} else {
result = v2.toString().compareTo(v1.toString());
}
if (result != 0) {
return result;
}
}
return 0;
}
});
isAsc = false;
isDesc = true;
return this;
}
public DataSet addAllUpdateColumns() {
for (DataRow row : rows) {
row.addAllUpdateColumns();
}
return this;
}
public DataSet clearUpdateColumns() {
for (DataRow row : rows) {
row.clearUpdateColumns();
}
return this;
}
public DataSet removeNull(String... keys) {
for (DataRow row : rows) {
row.removeNull(keys);
}
return this;
}
private static String key(String key) {
if (null != key && ConfigTable.IS_UPPER_KEY) {
key = key.toUpperCase();
}
return key;
}
/**
* 替换所有NULL值
*
* @param value value
* @return return
*/
public DataSet replaceNull(String value) {
for (DataRow row : rows) {
row.replaceNull(value);
}
return this;
}
/**
* 替换所有空值
*
* @param value value
* @return return
*/
public DataSet replaceEmpty(String value) {
for (DataRow row : rows) {
row.replaceEmpty(value);
}
return this;
}
/**
* 替换所有NULL值
*
* @param key key
* @param value value
* @return return
*/
public DataSet replaceNull(String key, String value) {
for (DataRow row : rows) {
row.replaceNull(key, value);
}
return this;
}
/**
* 替换所有空值
*
* @param key key
* @param value value
* @return return
*/
public DataSet replaceEmpty(String key, String value) {
for (DataRow row : rows) {
row.replaceEmpty(key, value);
}
return this;
}
public DataSet replace(String key, String oldChar, String newChar) {
if (null == key || null == oldChar || null == newChar) {
return this;
}
for (DataRow row : rows) {
row.replace(key, oldChar, newChar);
}
return this;
}
public DataSet replace(String oldChar, String newChar) {
for (DataRow row : rows) {
row.replace(oldChar, newChar);
}
return this;
}
/* ************************* 类sql操作 ************************************** */
/**
* 随机取一行
* @return DataRow
*/
public DataRow random() {
DataRow row = null;
int size = size();
if (size > 0) {
row = getRow(BasicUtil.getRandomNumber(0, size - 1));
}
return row;
}
/**
* 随机取qty行
* @param qty 行数
* @return DataSet
*/
public DataSet randoms(int qty) {
DataSet set = new DataSet();
int size = size();
if (qty < 0) {
qty = 0;
}
if (qty > size) {
qty = size;
}
for (int i = 0; i < qty; i++) {
while (true) {
int idx = BasicUtil.getRandomNumber(0, size - 1);
DataRow row = set.getRow(idx);
if (!set.contains(row)) {
set.add(row);
break;
}
}
}
set.cloneProperty(this);
return set;
}
/**
* 随机取min到max行
* @param min min
* @param max max
* @return DataSet
*/
public DataSet randoms(int min, int max) {
int qty = BasicUtil.getRandomNumber(min, max);
return randoms(qty);
}
public DataSet unique(String... keys) {
return distinct(keys);
}
/**
* 根据正则提取集合
* @param key key
* @param regex 正则
* @param mode 匹配方式
* @return DataSet
*/
public DataSet regex(String key, String regex, Regular.MATCH_MODE mode) {
DataSet set = new DataSet();
String tmpValue;
for (DataRow row : this) {
tmpValue = row.getString(key);
if (RegularUtil.match(tmpValue, regex, mode)) {
set.add(row);
}
}
set.cloneProperty(this);
return set;
}
public DataSet regex(String key, String regex) {
return regex(key, regex, Regular.MATCH_MODE.MATCH);
}
public boolean checkRequired(String... keys) {
for (DataRow row : rows) {
if (!row.checkRequired(keys)) {
return false;
}
}
return true;
}
public Map<String, Object> getQueryParams() {
return queryParams;
}
public DataSet setQueryParams(Map<String, Object> params) {
this.queryParams = params;
return this;
}
public Object getQueryParam(String key) {
return queryParams.get(key);
}
public DataSet addQueryParam(String key, Object param) {
queryParams.put(key, param);
return this;
}
public String getDatalink() {
return datalink;
}
public void setDatalink(String datalink) {
this.datalink = datalink;
}
public class Select implements Serializable {
private static final long serialVersionUID = 1L;
private boolean ignoreCase = true; //是否忽略大小写
/**
* 是否忽略NULL 如果设置成true 在执行equal notEqual like contains进 null与null比较返回false
* 左右出现NULL时直接返回false
* true会导致一行数据 equal notEqual都筛选不到
*/
private boolean ignoreNull = true;
public DataSet setIgnoreCase(boolean bol) {
this.ignoreCase = bol;
return DataSet.this;
}
public DataSet setIgnoreNull(boolean bol) {
this.ignoreNull = bol;
return DataSet.this;
}
/**
* 筛选key=value的子集
*
* @param key key
* @param value value
* @return DataSet
*/
public DataSet equals(String key, String value) {
return equals(DataSet.this, key, value);
}
private DataSet equals(DataSet src, String key, String value) {
DataSet set = new DataSet();
String tmpValue;
for (DataRow row : src) {
tmpValue = row.getString(key);
if (ignoreNull) {
if (null == tmpValue || null == value) {
continue;
}
} else {
if (null == tmpValue && null == value) {
set.add(row);
continue;
}
}
if (null != tmpValue) {
boolean chk = false;
if (ignoreCase) {
chk = tmpValue.equalsIgnoreCase(value);
} else {
chk = tmpValue.equals(value);
}
if (chk) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
/**
* 筛选key != value的子集
*
* @param key key
* @param value value
* @return DataSet
*/
public DataSet notEquals(String key, String value) {
return notEquals(DataSet.this, key, value);
}
private DataSet notEquals(DataSet src, String key, String value) {
DataSet set = new DataSet();
String tmpValue;
for (DataRow row : src) {
tmpValue = row.getString(key);
if (ignoreNull) {
if (null == tmpValue || null == value) {
continue;
}
} else {
if (null == tmpValue && null == value) {
set.add(row);
continue;
}
}
if (null != tmpValue) {
boolean chk = false;
if (ignoreCase) {
chk = !tmpValue.equalsIgnoreCase(value);
} else {
chk = !tmpValue.equals(value);
}
if (chk) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
/**
* 筛选key列的值是否包含value的子集
*
* @param key key
* @param value value
* @return DataSet
*/
public DataSet contains(String key, String value) {
return contains(DataSet.this, key, value);
}
private DataSet contains(DataSet src, String key, String value) {
DataSet set = new DataSet();
String tmpValue;
for (DataRow row : src) {
tmpValue = row.getString(key);
if (ignoreNull) {
if (null == tmpValue || null == value) {
continue;
}
} else {
if (null == tmpValue && null == value) {
set.add(row);
continue;
}
}
if (null != tmpValue) {
if (null == value) {
continue;
}
if (ignoreCase) {
tmpValue = tmpValue.toLowerCase();
value = value.toLowerCase();
}
if (tmpValue.contains(value)) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
/**
* 筛选key列的值like pattern的子集,pattern遵循sql通配符的规则,%表示任意个字符,_表示一个字符
*
* @param key 列
* @param pattern 表达式
* @return DataSet
*/
public DataSet like(String key, String pattern) {
return like(DataSet.this, key, pattern);
}
private DataSet like(DataSet src, String key, String pattern) {
DataSet set = new DataSet();
if (null != pattern) {
pattern = pattern.replace("!", "^").replace("_", "\\s|\\S").replace("%", "(\\s|\\S)*");
}
String tmpValue;
for (DataRow row : src) {
tmpValue = row.getString(key);
if (ignoreNull) {
if (null == tmpValue || null == pattern) {
continue;
}
} else {
if (null == tmpValue && null == pattern) {
set.add(row);
continue;
}
}
if (null != tmpValue) {
if (null == pattern) {
continue;
}
if (ignoreCase) {
tmpValue = tmpValue.toLowerCase();
pattern = pattern.toLowerCase();
}
if (RegularUtil.match(tmpValue, pattern, Regular.MATCH_MODE.MATCH)) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public DataSet notLike(String key, String pattern) {
return notLike(DataSet.this, key, pattern);
}
private DataSet notLike(DataSet src, String key, String pattern) {
DataSet set = new DataSet();
if (null == pattern) {
return set;
}
pattern = pattern.replace("!", "^").replace("_", "\\s|\\S").replace("%", "(\\s|\\S)*");
String tmpValue;
for (DataRow row : src) {
tmpValue = row.getString(key);
if (ignoreNull) {
if (null == tmpValue || null == pattern) {
continue;
}
} else {
if (null == tmpValue && null == pattern) {
set.add(row);
continue;
}
}
if (null != tmpValue) {
if (null == pattern) {
continue;
}
if (ignoreCase) {
tmpValue = tmpValue.toLowerCase();
pattern = pattern.toLowerCase();
}
if (!RegularUtil.match(tmpValue, pattern, Regular.MATCH_MODE.MATCH)) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public DataSet startWith(String key, String prefix) {
return startWith(DataSet.this, key, prefix);
}
private DataSet startWith(DataSet src, String key, String prefix) {
DataSet set = new DataSet();
String tmpValue;
for (DataRow row : src) {
tmpValue = row.getString(key);
if (ignoreNull) {
if (null == tmpValue || null == prefix) {
continue;
}
} else {
if (null == tmpValue && null == prefix) {
set.add(row);
continue;
}
}
if (null != tmpValue) {
if (null == prefix) {
continue;
}
if (ignoreCase) {
tmpValue = tmpValue.toLowerCase();
prefix = prefix.toLowerCase();
}
if (tmpValue.startsWith(prefix)) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public DataSet endWith(String key, String suffix) {
return endWith(DataSet.this, key, suffix);
}
private DataSet endWith(DataSet src, String key, String suffix) {
DataSet set = new DataSet();
String tmpValue;
for (DataRow row : src) {
tmpValue = row.getString(key);
if (ignoreNull) {
if (null == tmpValue || null == suffix) {
continue;
}
} else {
if (null == tmpValue && null == suffix) {
set.add(row);
continue;
}
}
if (null != tmpValue) {
if (null == suffix) {
continue;
}
if (ignoreCase) {
tmpValue = tmpValue.toLowerCase();
suffix = suffix.toLowerCase();
}
if (tmpValue.endsWith(suffix)) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public <T> DataSet in(String key, T... values) {
return in(DataSet.this, key, BeanUtil.array2list(values));
}
public <T> DataSet in(String key, Collection<T> values) {
return in(DataSet.this, key, values);
}
private <T> DataSet in(DataSet src, String key, Collection<T> values) {
DataSet set = new DataSet();
for (DataRow row : src) {
if (BasicUtil.containsString(ignoreNull, ignoreCase, values, row.getString(key))) {
set.add(row);
}
}
set.cloneProperty(src);
return set;
}
public <T> DataSet notIn(String key, T... values) {
return notIn(DataSet.this, key, BeanUtil.array2list(values));
}
public <T> DataSet notIn(String key, Collection<T> values) {
return notIn(DataSet.this, key, values);
}
private <T> DataSet notIn(DataSet src, String key, Collection<T> values) {
DataSet set = new DataSet();
if (null != values) {
String tmpValue = null;
for (DataRow row : src) {
tmpValue = row.getString(key);
if (ignoreNull && null == tmpValue) {
continue;
}
if (!BasicUtil.containsString(ignoreNull, ignoreCase, values, tmpValue)) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public DataSet isNull(String... keys) {
return isNull(DataSet.this, keys);
}
private DataSet isNull(DataSet src, String... keys) {
DataSet set = src;
if (null != keys) {
for (String key : keys) {
set = isNull(set, key);
}
}
return set;
}
private DataSet isNull(DataSet src, String key) {
DataSet set = new DataSet();
for(DataRow row:src){
if(null == row.get(key)){
set.add(row);
}
}
return set;
}
public DataSet isNotNull(String... keys) {
return isNotNull(DataSet.this, keys);
}
private DataSet isNotNull(DataSet src, String... keys) {
DataSet set = src;
if (null != keys) {
for (String key : keys) {
set = isNotNull(set, key);
}
}
return set;
}
private DataSet isNotNull(DataSet src, String key) {
DataSet set = new DataSet();
for(DataRow row:src){
if(null != row.get(key)){
set.add(row);
}
}
return set;
}
public DataSet notNull(String... keys) {
return isNotNull(keys);
}
public DataSet isEmpty(String... keys) {
return isEmpty(DataSet.this, keys);
}
private DataSet isEmpty(DataSet src, String... keys) {
DataSet set = src;
if (null != keys) {
for (String key : keys) {
set = isEmpty(set, key);
}
}
return set;
}
private DataSet isEmpty(DataSet src, String key) {
DataSet set = new DataSet();
for(DataRow row:src){
if(row.isEmpty(key)){
set.add(row);
}
}
return set;
}
public DataSet empty(String... keys) {
return isEmpty(keys);
}
public DataSet isNotEmpty(String... keys) {
return isNotEmpty(DataSet.this, keys);
}
private DataSet isNotEmpty(DataSet src, String... keys) {
DataSet set = src;
if (null != keys) {
for (String key : keys) {
set = isNotEmpty(set, key);
}
}
return set;
}
private DataSet isNotEmpty(DataSet src, String key) {
DataSet set = new DataSet();
for(DataRow row:src){
if(row.isNotEmpty(key)){
set.add(row);
}
}
return set;
}
public DataSet notEmpty(String... keys) {
return isNotEmpty(keys);
}
public <T> DataSet less(String key, T value) {
return less(DataSet.this, key, value);
}
private <T> DataSet less(DataSet src, String key, T value) {
DataSet set = new DataSet();
if (null == value) {
return set;
}
if (BasicUtil.isNumber(value)) {
BigDecimal number = new BigDecimal(value.toString());
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.getDecimal(key, 0).compareTo(number) < 0) {
set.add(row);
}
}
} else if (BasicUtil.isDate(value) || BasicUtil.isDateTime(value)) {
Date date = DateUtil.parse(value.toString());
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.isNotEmpty(key) &&
DateUtil.diff(DateUtil.DATE_PART_MILLISECOND, date, row.getDate(key, new Date())) < 0) {
set.add(row);
}
}
} else {
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.getString(key).compareTo(value.toString()) < 0) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public <T> DataSet lessEqual(String key, T value) {
return lessEqual(DataSet.this, key, value);
}
private <T> DataSet lessEqual(DataSet src, String key, T value) {
DataSet set = new DataSet();
if (null == value) {
return set;
}
if (BasicUtil.isNumber(value)) {
BigDecimal number = new BigDecimal(value.toString());
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.getDecimal(key, 0).compareTo(number) <= 0) {
set.add(row);
}
}
} else if (BasicUtil.isDate(value) || BasicUtil.isDateTime(value)) {
Date date = DateUtil.parse(value.toString());
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.isNotEmpty(key) &&
DateUtil.diff(DateUtil.DATE_PART_MILLISECOND, date, row.getDate(key, new Date())) <= 0) {
set.add(row);
}
}
} else {
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.getString(key).compareTo(value.toString()) >= 0) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public <T> DataSet greater(String key, T value) {
return greater(DataSet.this, key, value);
}
private <T> DataSet greater(DataSet src, String key, T value) {
DataSet set = new DataSet();
if (null == value) {
return set;
}
if (BasicUtil.isNumber(value)) {
BigDecimal number = new BigDecimal(value.toString());
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.getDecimal(key, 0).compareTo(number) > 0) {
set.add(row);
}
}
} else if (BasicUtil.isDate(value) || BasicUtil.isDateTime(value)) {
Date date = DateUtil.parse(value.toString());
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.isNotEmpty(key) &&
DateUtil.diff(DateUtil.DATE_PART_MILLISECOND, date, row.getDate(key, new Date())) > 0) {
set.add(row);
}
}
} else {
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.getString(key).compareTo(value.toString()) > 0) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public <T> DataSet greaterEqual(String key, T value) {
return greaterEqual(DataSet.this, key, value);
}
private <T> DataSet greaterEqual(DataSet src, String key, T value) {
DataSet set = new DataSet();
if (null == value) {
return set;
}
if (BasicUtil.isNumber(value)) {
BigDecimal number = new BigDecimal(value.toString());
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.getDecimal(key, 0).compareTo(number) >= 0) {
set.add(row);
}
}
} else if (BasicUtil.isDate(value) || BasicUtil.isDateTime(value)) {
Date date = DateUtil.parse(value.toString());
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.isNotEmpty(key) &&
DateUtil.diff(DateUtil.DATE_PART_MILLISECOND, date, row.getDate(key, new Date())) >= 0) {
set.add(row);
}
}
} else {
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.getString(key).compareTo(value.toString()) >= 0) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public <T> DataSet between(String key, T min, T max) {
return between(DataSet.this, key, min, max);
}
private <T> DataSet between(DataSet src, String key, T min, T max) {
DataSet set = greaterEqual(src, key, min);
set = lessEqual(set, key, max);
return set;
}
}
public Select select = new Select();
}
|
Java
|
/*
* Copyright (c) 2015-2017 EpiData, Inc.
*/
package controllers
import play.api.mvc._
import securesocial.core.SecureSocial
/** Controller to display the Notebook. */
object Notebook extends Controller with SecureSocial {
def show = SecuredAction { implicit request =>
Ok(views.html.Notebook.show())
}
}
|
Java
|
package ua.job4j.loop;
/**
* Class Класс для вычисления факториала заданного числа.
* @author vfrundin
* @since 05.11.2017
* @version 1.0
*/
public class Factorial {
/**
* Метод должен вычислять факториал поданного на вход числа.
* @param n Число для которого нужно определить факториал.
* @return result - найденный факториал числа n.
*/
public int calc(int n) {
int result = 1;
if (n != 0) {
for (int i = 1; i <= n; i++) {
result *= i;
}
}
return result;
}
}
|
Java
|
/*
Copyright 2013 KLab 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.
*/
#ifndef CKLBUIDebugItem_h
#define CKLBUIDebugItem_h
#include "CKLBUITask.h"
#include "CKLBNodeVirtualDocument.h"
/*!
* \class CKLBUIDebugItem
* \brief Debug Item Task Class
*
* CKLBUIDebugItem allows to display debug purpose items in the Game.
* A few properties (such as text, color, etc.) can be modified in runtime
* and used for debugging.
*/
class CKLBUIDebugItem : public CKLBUITask
{
friend class CKLBTaskFactory<CKLBUIDebugItem>;
private:
CKLBUIDebugItem();
virtual ~CKLBUIDebugItem();
bool init(CKLBUITask* pParent, CKLBNode* pNode, u32 order, float x, float y, u32 alpha, u32 color, const char* font, u32 size, const char* text, const char* callback,u32 id);
bool initCore(u32 order, float x, float y, u32 alpha, u32 color, const char* font, u32 size, const char* text, const char* callback,u32 id);
public:
static CKLBUIDebugItem* create(CKLBUITask* pParent, CKLBNode* pNode, u32 order, float x, float y, u32 alpha, u32 color, const char* font, u32 size, const char* text, const char* callback,u32 id);
u32 getClassID ();
bool initUI (CLuaState& lua);
void execute (u32 deltaT);
void dieUI ();
inline virtual void setOrder (u32 order) { m_order = order; m_update = true; }
inline virtual u32 getOrder () { return m_order; }
inline void setAlpha (u32 alpha) { m_alpha = alpha; m_update = true; }
inline u32 getAlpha () { return m_alpha; }
inline void setU24Color (u32 color) { m_color = color; m_update = true; }
inline u32 getU24Color () { return m_color; }
inline void setColor (u32 color) { m_alpha = color >> 24; m_color = color & 0xFFFFFF; m_update = true; }
inline u32 getColor () { return (m_alpha << 24) | m_color; }
inline void setFont (const char* font) { setStrC(m_font, font); m_update = true; }
inline const char* getFont () { return m_font; }
inline void setSize (u32 size) { m_size = size; m_update = true; }
inline u32 getSize () { return m_size; }
inline void setText (const char* text) { setStrC(m_text, text); m_update = true; }
inline const char* getText () { return m_text; }
private:
u32 m_order;
u8 m_format;
u8 m_alpha;
u32 m_color;
const char* m_font;
const char* m_text;
u32 m_size;
bool setup_node();
// 現在は VDocで仮実装しておく。
CKLBNodeVirtualDocument * m_pLabel;
bool m_update;
STextInfo m_txinfo;
const char * m_callback;
int m_ID;
int m_padId;
static PROP_V2 ms_propItems[];
};
#endif // CKLBUIDebugItem_h
|
Java
|
/* Copyright (C) 2013-2022 TU Dortmund
* This file is part of AutomataLib, http://www.automatalib.net/.
*
* 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 net.automatalib.graphs.base.compact;
import net.automatalib.commons.smartcollections.ResizingArrayStorage;
import org.checkerframework.checker.nullness.qual.Nullable;
public class CompactBidiGraph<@Nullable NP, @Nullable EP> extends AbstractCompactBidiGraph<NP, EP> {
private final ResizingArrayStorage<NP> nodeProperties;
public CompactBidiGraph() {
this.nodeProperties = new ResizingArrayStorage<>(Object.class);
}
public CompactBidiGraph(int initialCapacity) {
super(initialCapacity);
this.nodeProperties = new ResizingArrayStorage<>(Object.class, initialCapacity);
}
@Override
public void setNodeProperty(int node, @Nullable NP property) {
nodeProperties.ensureCapacity(node + 1);
nodeProperties.array[node] = property;
}
@Override
public NP getNodeProperty(int node) {
return node < nodeProperties.array.length ? nodeProperties.array[node] : null;
}
}
|
Java
|
package com.github.binarywang.wxpay.service.impl;
import com.github.binarywang.wxpay.bean.request.*;
import com.github.binarywang.wxpay.bean.result.*;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.testbase.ApiTestModule;
import com.google.common.base.Joiner;
import com.google.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
/**
* @author chenliang
* @date 2021-08-02 6:45 下午
*/
@Test
@Guice(modules = ApiTestModule.class)
public class WxEntrustPapServiceTest {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Inject
private WxPayService payService;
/**
* 公众号纯签约
*/
@Test
public void testMpSign() {
String contractCode = "222200002222";
String displayAccount = Joiner.on("").join("陈*", "(", "10000014", ")");
WxMpEntrustRequest wxMpEntrust = WxMpEntrustRequest.newBuilder()
.planId("142323") //模板ID:跟微信申请
.contractCode(contractCode)
.contractDisplayAccount(displayAccount)
.notifyUrl("http://domain.com/api/wxpay/sign/callback.do")
.requestSerial(6L)
//.returnWeb(1)
.version("1.0")
.timestamp(String.valueOf(System.currentTimeMillis() / 1000))
.outerId(displayAccount)
.build();
String url = null;
try {
url = this.payService.getWxEntrustPapService().mpSign(wxMpEntrust);
} catch (WxPayException e) {
e.printStackTrace();
}
logger.info(url);
}
/**
* 小程序纯签约
*/
@Test
public void testMaSign() {
String contractCode = "222220000022222";
String displayAccount = Joiner.on("").join("陈*", "(", "10000001", ")");
WxMaEntrustRequest wxMaEntrustRequest = WxMaEntrustRequest.newBuilder()
.contractCode(contractCode)
.contractDisplayAccount(contractCode)
.notifyUrl("http://domain.com/api/wxpay/sign/callback.do")
.outerId(displayAccount)
.planId("141535")
.requestSerial(2L)
.timestamp(String.valueOf(System.currentTimeMillis() / 1000))
.build();
try {
String url = this.payService.getWxEntrustPapService().maSign(wxMaEntrustRequest);
logger.info(url);
} catch (WxPayException e) {
e.printStackTrace();
}
}
/**
* h5纯签约
*/
@Test
public void testH5Sign() {
String contractCode = "222111122222";
String displayAccount = Joiner.on("").join("陈*", "(", "100000000", ")");
WxH5EntrustRequest wxH5EntrustRequest = WxH5EntrustRequest.newBuilder()
.requestSerial(2L)
.clientIp("127.0.0.1")
.contractCode(contractCode)
.contractDisplayAccount(displayAccount)
.notifyUrl("http://domain.com/api/wxpay/sign/callback.do")
.planId("141535")
.returnAppid("1")
.timestamp(String.valueOf(System.currentTimeMillis() / 1000))
.version("1.0")
.outerId(displayAccount)
.build();
try {
WxH5EntrustResult wxH5EntrustResult = this.payService.getWxEntrustPapService().h5Sign(wxH5EntrustRequest);
logger.info(wxH5EntrustResult.toString());
} catch (WxPayException e) {
e.printStackTrace();
}
}
@Test
public void testPaySign() {
String contractCode = "2222211110000222";
String displayAccount = Joiner.on("").join("陈*", "(", "10000005", ")");
String outTradeNo = "11100111101";
WxPayEntrustRequest wxPayEntrustRequest = WxPayEntrustRequest.newBuilder()
.attach("local")
.body("产品名字")
.contractAppId(this.payService.getConfig().getAppId())
.contractCode(contractCode)
.contractDisplayAccount(displayAccount)
.contractMchId(this.payService.getConfig().getMchId())
//签约回调
.contractNotifyUrl("http://domain.com/api/wxpay/sign/callback.do")
.detail("产品是好")
.deviceInfo("oneplus 7 pro")
//.goodsTag()
//.limitPay()
//支付回调
.notifyUrl("http://domain.com/api/wxpay/pay/callback.do")
.openId("oIvLdt8Q-_aKy4Vo6f4YI6gsIhMc") //openId
.outTradeNo(outTradeNo)
.planId("141535")
//.productId()
.requestSerial(3L)
.spbillCreateIp("127.0.0.1")
//.timeExpire()
//.timeStart()
.totalFee(1)
.tradeType("MWEB")
.contractOuterId(displayAccount)
.build();
try {
WxPayEntrustResult wxPayEntrustResult = this.payService.getWxEntrustPapService().paySign(wxPayEntrustRequest);
logger.info(wxPayEntrustResult.toString());
} catch (WxPayException e) {
e.printStackTrace();
}
}
@Test
public void testWithhold() {
String outTradeNo = "101010101";
WxWithholdRequest withholdRequest = WxWithholdRequest.newBuilder()
.attach("local")
.body("产品名字")
.contractId("202011065409471222") // 微信返回的签约协议号
.detail("产品描述")
.feeType("CNY")
//.goodsTag()
.notifyUrl("http://domain.com/api/wxpay/withhold/callback.do")
.outTradeNo(outTradeNo)
.spbillCreateIp("127.0.0.1")
.totalFee(1)
.tradeType("PAP")
.build();
try {
WxWithholdResult wxWithholdResult = this.payService.getWxEntrustPapService().withhold(withholdRequest);
logger.info(wxWithholdResult.toString());
} catch (WxPayException e) {
e.printStackTrace();
}
}
@Test
public void testPreWithhold() {
WxPreWithholdRequest.EstimateAmount estimateAmount = new WxPreWithholdRequest.EstimateAmount();
estimateAmount.setAmount(1);
estimateAmount.setCurrency("CNY");
WxPreWithholdRequest wxPreWithholdRequest = WxPreWithholdRequest.newBuilder()
.appId("wx73dssxxxxxx")
.contractId("202010275173070001")
.estimateAmount(estimateAmount)
.mchId("1600010102")
.build();
try {
String httpResponseModel = this.payService.getWxEntrustPapService().preWithhold(wxPreWithholdRequest);
logger.info(httpResponseModel);
} catch (WxPayException e) {
e.printStackTrace();
}
}
@Test
public void testQuerySign() {
String outTradeNo = "1212121212";
WxSignQueryRequest wxSignQueryRequest = WxSignQueryRequest.newBuilder()
//.contractId("202010275173073211")
.contractCode(outTradeNo)
.planId(1432112)
.version("1.0")
.build();
try {
WxSignQueryResult wxSignQueryResult = this.payService.getWxEntrustPapService().querySign(wxSignQueryRequest);
logger.info(wxSignQueryResult.toString());
} catch (WxPayException e) {
logger.info("异常码:" + e.getErrCode());
logger.info("异常:" + e);
}
}
@Test
public void testTerminationContract() {
WxTerminatedContractRequest wxTerminatedContractRequest = WxTerminatedContractRequest.newBuilder()
.contractId("202010275173070231")
.contractTerminationRemark("测试解约")
.version("1.0")
.build();
try {
WxTerminationContractResult wxTerminationContractResult = this.payService.getWxEntrustPapService().terminationContract(wxTerminatedContractRequest);
logger.info(wxTerminationContractResult.toString());
} catch (WxPayException e) {
logger.error(e.getMessage());
}
}
}
|
Java
|
package org.clinical3PO.common.security;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import org.clinical3PO.common.security.model.User;
import org.clinical3PO.common.security.service.UserService;
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Autowired
private UserService userService;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String password = (String) authentication.getCredentials();
User user = userService.loadUserByUsername(username);
if (user == null) {
throw new BadCredentialsException("Username not found.");
}
if (!password.equals(user.getPassword())) {
throw new BadCredentialsException("Wrong password.");
}
Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
return new UsernamePasswordAuthenticationToken(user, password, authorities);
}
@Override
public boolean supports(Class<?> arg0) {
return true;
}
}
|
Java
|
---
layout: interior
title: The Heart of Wichita
speaker: Alex Pemberton
permalink: alex-pemberton
image: img/20160607/alex_pemberton.jpg
event: 20160607
video: ctGrTBgGcN0
favorite: The prominent and hidden architectural gems, such as The Orpheum, the Kress building, Carthalite, Proudfoot & Bird buildings, and Frank Lloyd Wright’s Allen-Lambe House and Corbin Education building.
about: A native Kansan, Alex has been living in Wichita since 2010 and now refers to it as the hometown he chose. Despite this, he still pronounces the Arkansas River like the state and Greenwich Road like the neighborhood in New York. When not helping entrepreneurs and property owners find solutions to their commercial real estate needs as an advisor at NAI Martens, you can find him volunteer coaching a youth baseball team for League 42, taking in Wichita’s burgeoning live music and visual arts scenes, attending entrepreneurship- and civic-oriented events, or cruising his Vespa down Douglas Avenue. A graduate of Wichita State University with majors in entrepreneurship, management, and economics with a real estate emphasis, he builds a spreadsheet to inform virtually every life decision.
twitter:
facebook: alex.pemberton.14
instagram:
linkedin: alexpembertonict
website:
email: apemberton@naimartens.com
telephone:
---
|
Java
|
<?php
/**
* This file is part of the SevenShores/NetSuite library
* AND originally from the NetSuite PHP Toolkit.
*
* New content:
* @package ryanwinchester/netsuite-php
* @copyright Copyright (c) Ryan Winchester
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
* @link https://github.com/ryanwinchester/netsuite-php
*
* Original content:
* @copyright Copyright (c) NetSuite Inc.
* @license https://raw.githubusercontent.com/ryanwinchester/netsuite-php/master/original/NetSuite%20Application%20Developer%20License%20Agreement.txt
* @link http://www.netsuite.com/portal/developers/resources/suitetalk-sample-applications.shtml
*
* generated: 2020-04-10 09:56:55 PM UTC
*/
namespace NetSuite\Classes;
class NSSoapFault {
/**
* @var \NetSuite\Classes\FaultCodeType
*/
public $code;
/**
* @var string
*/
public $message;
static $paramtypesmap = array(
"code" => "FaultCodeType",
"message" => "string",
);
}
|
Java
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { NgModule } from '@angular/core';
import { SharedModule } from '../../shared/shared.module';
import { ConfigureRowsComponent } from './configure-rows.component';
import { ShowHideAlertEntriesComponent } from './show-hide/show-hide-alert-entries.component';
import { SwitchModule } from 'app/shared/switch/switch.module';
import { QueryBuilder } from '../alerts-list/query-builder';
import { ShowHideService } from './show-hide/show-hide.service';
@NgModule({
imports: [ SharedModule, SwitchModule ],
declarations: [ ConfigureRowsComponent, ShowHideAlertEntriesComponent ],
exports: [ ConfigureRowsComponent ],
providers: [ QueryBuilder, ShowHideService ],
})
export class ConfigureRowsModule {
constructor(private showHideService: ShowHideService) {}
}
|
Java
|
package com.example.mywechat.utils;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
/**
* ActivityCollector ÀàÓÃÓÚ¹ÜÀíËùÓеĻ
* @author dzhiqin
*
*/
public class ActivityCollector {
public static List<Activity> activities=new ArrayList<Activity>();
public static void addActivity(Activity activity){
activities.add(activity);
}
public static void removeActivity(Activity activity){
activities.remove(activity);
}
/**
* ¹Ø±ÕËùÓл
*/
public static void finishAll(){
for(Activity activity:activities){
if(!activity.isFinishing()){
activity.finish();
}
}
}
public ActivityCollector() {
// TODO ×Ô¶¯Éú³ÉµÄ¹¹Ô캯Êý´æ¸ù
}
}
|
Java
|
# Teloschistes flavicans var. pallidus Sambo VARIETY
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Teloschistes flavicans var. pallidus Sambo
### Remarks
null
|
Java
|
# 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.
def strip_region_tags(sample_text):
"""Remove blank lines and region tags from sample text"""
magic_lines = [
line for line in sample_text.split("\n") if len(line) > 0 and "# [" not in line
]
return "\n".join(magic_lines)
|
Java
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Cleidimar Viana
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.seamusdawkins.tablayout.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.seamusdawkins.tablayout.R;
public class FirstFragment extends Fragment {
TextView tv;
RelativeLayout rl;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_one, container, false);
tv = (TextView) rootView.findViewById(R.id.action);
tv.setText(R.string.str_first);
return rootView;
}
}
|
Java
|
<font class='sw'>Connexion ($var['msize'] bytes).</font>
|
Java
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.gora.cassandra.store;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import me.prettyprint.cassandra.model.ConfigurableConsistencyLevel;
import me.prettyprint.cassandra.serializers.ByteBufferSerializer;
import me.prettyprint.cassandra.serializers.IntegerSerializer;
import me.prettyprint.cassandra.serializers.StringSerializer;
import me.prettyprint.cassandra.service.CassandraHostConfigurator;
import me.prettyprint.hector.api.Cluster;
import me.prettyprint.hector.api.Keyspace;
import me.prettyprint.hector.api.beans.OrderedRows;
import me.prettyprint.hector.api.beans.OrderedSuperRows;
import me.prettyprint.hector.api.beans.Row;
import me.prettyprint.hector.api.beans.SuperRow;
import me.prettyprint.hector.api.ddl.ColumnFamilyDefinition;
import me.prettyprint.hector.api.ddl.ComparatorType;
import me.prettyprint.hector.api.ddl.KeyspaceDefinition;
import me.prettyprint.hector.api.factory.HFactory;
import me.prettyprint.hector.api.mutation.Mutator;
import me.prettyprint.hector.api.query.QueryResult;
import me.prettyprint.hector.api.query.RangeSlicesQuery;
import me.prettyprint.hector.api.query.RangeSuperSlicesQuery;
import me.prettyprint.hector.api.HConsistencyLevel;
import me.prettyprint.hector.api.Serializer;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Type;
import org.apache.avro.generic.GenericArray;
import org.apache.avro.util.Utf8;
import org.apache.gora.cassandra.query.CassandraQuery;
import org.apache.gora.cassandra.serializers.GenericArraySerializer;
import org.apache.gora.cassandra.serializers.GoraSerializerTypeInferer;
import org.apache.gora.cassandra.serializers.TypeUtils;
import org.apache.gora.mapreduce.GoraRecordReader;
import org.apache.gora.persistency.Persistent;
import org.apache.gora.persistency.impl.PersistentBase;
import org.apache.gora.persistency.State;
import org.apache.gora.persistency.StatefulHashMap;
import org.apache.gora.query.Query;
import org.apache.gora.util.ByteUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CassandraClient<K, T extends PersistentBase> {
public static final Logger LOG = LoggerFactory.getLogger(CassandraClient.class);
private Cluster cluster;
private Keyspace keyspace;
private Mutator<K> mutator;
private Class<K> keyClass;
private Class<T> persistentClass;
private CassandraMapping cassandraMapping = null;
private Serializer<K> keySerializer;
public void initialize(Class<K> keyClass, Class<T> persistentClass) throws Exception {
this.keyClass = keyClass;
// get cassandra mapping with persistent class
this.persistentClass = persistentClass;
this.cassandraMapping = CassandraMappingManager.getManager().get(persistentClass);
// LOG.info("persistentClass=" + persistentClass.getName() + " -> cassandraMapping=" + cassandraMapping);
this.cluster = HFactory.getOrCreateCluster(this.cassandraMapping.getClusterName(), new CassandraHostConfigurator(this.cassandraMapping.getHostName()));
// add keyspace to cluster
checkKeyspace();
// Just create a Keyspace object on the client side, corresponding to an already existing keyspace with already created column families.
this.keyspace = HFactory.createKeyspace(this.cassandraMapping.getKeyspaceName(), this.cluster);
this.keySerializer = GoraSerializerTypeInferer.getSerializer(keyClass);
this.mutator = HFactory.createMutator(this.keyspace, this.keySerializer);
}
/**
* Check if keyspace already exists.
*/
public boolean keyspaceExists() {
KeyspaceDefinition keyspaceDefinition = this.cluster.describeKeyspace(this.cassandraMapping.getKeyspaceName());
return (keyspaceDefinition != null);
}
/**
* Check if keyspace already exists. If not, create it.
* In this method, we also utilise Hector's {@ConfigurableConsistencyLevel}
* logic. It is set by passing a ConfigurableConsistencyLevel object right
* when the Keyspace is created. Currently consistency level is .ONE which
* permits consistency to wait until one replica has responded.
*/
public void checkKeyspace() {
// "describe keyspace <keyspaceName>;" query
KeyspaceDefinition keyspaceDefinition = this.cluster.describeKeyspace(this.cassandraMapping.getKeyspaceName());
if (keyspaceDefinition == null) {
List<ColumnFamilyDefinition> columnFamilyDefinitions = this.cassandraMapping.getColumnFamilyDefinitions();
// GORA-197
for (ColumnFamilyDefinition cfDef : columnFamilyDefinitions) {
cfDef.setComparatorType(ComparatorType.BYTESTYPE);
}
keyspaceDefinition = HFactory.createKeyspaceDefinition(this.cassandraMapping.getKeyspaceName(), "org.apache.cassandra.locator.SimpleStrategy", 1, columnFamilyDefinitions);
this.cluster.addKeyspace(keyspaceDefinition, true);
// LOG.info("Keyspace '" + this.cassandraMapping.getKeyspaceName() + "' in cluster '" + this.cassandraMapping.getClusterName() + "' was created on host '" + this.cassandraMapping.getHostName() + "'");
// Create a customized Consistency Level
ConfigurableConsistencyLevel configurableConsistencyLevel = new ConfigurableConsistencyLevel();
Map<String, HConsistencyLevel> clmap = new HashMap<String, HConsistencyLevel>();
// Define CL.ONE for ColumnFamily "ColumnFamily"
clmap.put("ColumnFamily", HConsistencyLevel.ONE);
// In this we use CL.ONE for read and writes. But you can use different CLs if needed.
configurableConsistencyLevel.setReadCfConsistencyLevels(clmap);
configurableConsistencyLevel.setWriteCfConsistencyLevels(clmap);
// Then let the keyspace know
HFactory.createKeyspace("Keyspace", this.cluster, configurableConsistencyLevel);
keyspaceDefinition = null;
}
else {
List<ColumnFamilyDefinition> cfDefs = keyspaceDefinition.getCfDefs();
if (cfDefs == null || cfDefs.size() == 0) {
LOG.warn(keyspaceDefinition.getName() + " does not have any column family.");
}
else {
for (ColumnFamilyDefinition cfDef : cfDefs) {
ComparatorType comparatorType = cfDef.getComparatorType();
if (! comparatorType.equals(ComparatorType.BYTESTYPE)) {
// GORA-197
LOG.warn("The comparator type of " + cfDef.getName() + " column family is " + comparatorType.getTypeName()
+ ", not BytesType. It may cause a fatal error on column validation later.");
}
else {
// LOG.info("The comparator type of " + cfDef.getName() + " column family is " + comparatorType.getTypeName() + ".");
}
}
}
}
}
/**
* Drop keyspace.
*/
public void dropKeyspace() {
// "drop keyspace <keyspaceName>;" query
this.cluster.dropKeyspace(this.cassandraMapping.getKeyspaceName());
}
/**
* Insert a field in a column.
* @param key the row key
* @param fieldName the field name
* @param value the field value.
*/
public void addColumn(K key, String fieldName, Object value) {
if (value == null) {
return;
}
ByteBuffer byteBuffer = toByteBuffer(value);
String columnFamily = this.cassandraMapping.getFamily(fieldName);
String columnName = this.cassandraMapping.getColumn(fieldName);
if (columnName == null) {
LOG.warn("Column name is null for field=" + fieldName + " with value=" + value.toString());
return;
}
synchronized(mutator) {
HectorUtils.insertColumn(mutator, key, columnFamily, columnName, byteBuffer);
}
}
/**
* Insert a member in a super column. This is used for map and record Avro types.
* @param key the row key
* @param fieldName the field name
* @param columnName the column name (the member name, or the index of array)
* @param value the member value
*/
@SuppressWarnings("unchecked")
public void addSubColumn(K key, String fieldName, ByteBuffer columnName, Object value) {
if (value == null) {
return;
}
ByteBuffer byteBuffer = toByteBuffer(value);
String columnFamily = this.cassandraMapping.getFamily(fieldName);
String superColumnName = this.cassandraMapping.getColumn(fieldName);
synchronized(mutator) {
HectorUtils.insertSubColumn(mutator, key, columnFamily, superColumnName, columnName, byteBuffer);
}
}
public void addSubColumn(K key, String fieldName, String columnName, Object value) {
addSubColumn(key, fieldName, StringSerializer.get().toByteBuffer(columnName), value);
}
public void addSubColumn(K key, String fieldName, Integer columnName, Object value) {
addSubColumn(key, fieldName, IntegerSerializer.get().toByteBuffer(columnName), value);
}
/**
* Delete a member in a super column. This is used for map and record Avro types.
* @param key the row key
* @param fieldName the field name
* @param columnName the column name (the member name, or the index of array)
*/
@SuppressWarnings("unchecked")
public void deleteSubColumn(K key, String fieldName, ByteBuffer columnName) {
String columnFamily = this.cassandraMapping.getFamily(fieldName);
String superColumnName = this.cassandraMapping.getColumn(fieldName);
synchronized(mutator) {
HectorUtils.deleteSubColumn(mutator, key, columnFamily, superColumnName, columnName);
}
}
public void deleteSubColumn(K key, String fieldName, String columnName) {
deleteSubColumn(key, fieldName, StringSerializer.get().toByteBuffer(columnName));
}
@SuppressWarnings("unchecked")
public void addGenericArray(K key, String fieldName, GenericArray array) {
if (isSuper( cassandraMapping.getFamily(fieldName) )) {
int i= 0;
for (Object itemValue: array) {
// TODO: hack, do not store empty arrays
if (itemValue instanceof GenericArray<?>) {
if (((GenericArray)itemValue).size() == 0) {
continue;
}
} else if (itemValue instanceof StatefulHashMap<?,?>) {
if (((StatefulHashMap)itemValue).size() == 0) {
continue;
}
}
addSubColumn(key, fieldName, i++, itemValue);
}
}
else {
addColumn(key, fieldName, array);
}
}
@SuppressWarnings("unchecked")
public void addStatefulHashMap(K key, String fieldName, StatefulHashMap<Utf8,Object> map) {
if (isSuper( cassandraMapping.getFamily(fieldName) )) {
int i= 0;
for (Utf8 mapKey: map.keySet()) {
if (map.getState(mapKey) == State.DELETED) {
deleteSubColumn(key, fieldName, mapKey.toString());
continue;
}
// TODO: hack, do not store empty arrays
Object mapValue = map.get(mapKey);
if (mapValue instanceof GenericArray<?>) {
if (((GenericArray)mapValue).size() == 0) {
continue;
}
} else if (mapValue instanceof StatefulHashMap<?,?>) {
if (((StatefulHashMap)mapValue).size() == 0) {
continue;
}
}
addSubColumn(key, fieldName, mapKey.toString(), mapValue);
}
}
else {
addColumn(key, fieldName, map);
}
}
/**
* Serialize value to ByteBuffer.
* @param value the member value
* @return ByteBuffer object
*/
@SuppressWarnings("unchecked")
public ByteBuffer toByteBuffer(Object value) {
ByteBuffer byteBuffer = null;
Serializer serializer = GoraSerializerTypeInferer.getSerializer(value);
if (serializer == null) {
LOG.info("Serializer not found for: " + value.toString());
}
else {
byteBuffer = serializer.toByteBuffer(value);
}
if (byteBuffer == null) {
LOG.info("value class=" + value.getClass().getName() + " value=" + value + " -> null");
}
return byteBuffer;
}
/**
* Select a family column in the keyspace.
* @param cassandraQuery a wrapper of the query
* @param family the family name to be queried
* @return a list of family rows
*/
public List<Row<K, ByteBuffer, ByteBuffer>> execute(CassandraQuery<K, T> cassandraQuery, String family) {
String[] columnNames = cassandraQuery.getColumns(family);
ByteBuffer[] columnNameByteBuffers = new ByteBuffer[columnNames.length];
for (int i = 0; i < columnNames.length; i++) {
columnNameByteBuffers[i] = StringSerializer.get().toByteBuffer(columnNames[i]);
}
Query<K, T> query = cassandraQuery.getQuery();
int limit = (int) query.getLimit();
if (limit < 1) {
limit = Integer.MAX_VALUE;
}
K startKey = query.getStartKey();
K endKey = query.getEndKey();
RangeSlicesQuery<K, ByteBuffer, ByteBuffer> rangeSlicesQuery = HFactory.createRangeSlicesQuery(this.keyspace, this.keySerializer, ByteBufferSerializer.get(), ByteBufferSerializer.get());
rangeSlicesQuery.setColumnFamily(family);
rangeSlicesQuery.setKeys(startKey, endKey);
rangeSlicesQuery.setRange(ByteBuffer.wrap(new byte[0]), ByteBuffer.wrap(new byte[0]), false, GoraRecordReader.BUFFER_LIMIT_READ_VALUE);
rangeSlicesQuery.setRowCount(limit);
rangeSlicesQuery.setColumnNames(columnNameByteBuffers);
QueryResult<OrderedRows<K, ByteBuffer, ByteBuffer>> queryResult = rangeSlicesQuery.execute();
OrderedRows<K, ByteBuffer, ByteBuffer> orderedRows = queryResult.get();
return orderedRows.getList();
}
/**
* Select the families that contain at least one column mapped to a query field.
* @param query indicates the columns to select
* @return a map which keys are the family names and values the corresponding column names required to get all the query fields.
*/
public Map<String, List<String>> getFamilyMap(Query<K, T> query) {
Map<String, List<String>> map = new HashMap<String, List<String>>();
for (String field: query.getFields()) {
String family = this.cassandraMapping.getFamily(field);
String column = this.cassandraMapping.getColumn(field);
// check if the family value was already initialized
List<String> list = map.get(family);
if (list == null) {
list = new ArrayList<String>();
map.put(family, list);
}
if (column != null) {
list.add(column);
}
}
return map;
}
/**
* Select the field names according to the column names, which format if fully qualified: "family:column"
* @param query
* @return a map which keys are the fully qualified column names and values the query fields
*/
public Map<String, String> getReverseMap(Query<K, T> query) {
Map<String, String> map = new HashMap<String, String>();
for (String field: query.getFields()) {
String family = this.cassandraMapping.getFamily(field);
String column = this.cassandraMapping.getColumn(field);
map.put(family + ":" + column, field);
}
return map;
}
public boolean isSuper(String family) {
return this.cassandraMapping.isSuper(family);
}
public List<SuperRow<K, String, ByteBuffer, ByteBuffer>> executeSuper(CassandraQuery<K, T> cassandraQuery, String family) {
String[] columnNames = cassandraQuery.getColumns(family);
Query<K, T> query = cassandraQuery.getQuery();
int limit = (int) query.getLimit();
if (limit < 1) {
limit = Integer.MAX_VALUE;
}
K startKey = query.getStartKey();
K endKey = query.getEndKey();
RangeSuperSlicesQuery<K, String, ByteBuffer, ByteBuffer> rangeSuperSlicesQuery = HFactory.createRangeSuperSlicesQuery(this.keyspace, this.keySerializer, StringSerializer.get(), ByteBufferSerializer.get(), ByteBufferSerializer.get());
rangeSuperSlicesQuery.setColumnFamily(family);
rangeSuperSlicesQuery.setKeys(startKey, endKey);
rangeSuperSlicesQuery.setRange("", "", false, GoraRecordReader.BUFFER_LIMIT_READ_VALUE);
rangeSuperSlicesQuery.setRowCount(limit);
rangeSuperSlicesQuery.setColumnNames(columnNames);
QueryResult<OrderedSuperRows<K, String, ByteBuffer, ByteBuffer>> queryResult = rangeSuperSlicesQuery.execute();
OrderedSuperRows<K, String, ByteBuffer, ByteBuffer> orderedRows = queryResult.get();
return orderedRows.getList();
}
/**
* Obtain Schema/Keyspace name
* @return Keyspace
*/
public String getKeyspaceName() {
return this.cassandraMapping.getKeyspaceName();
}
}
|
Java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.io.sstable;
import java.io.IOException;
import java.util.Iterator;
import com.google.common.util.concurrent.RateLimiter;
import com.google.common.collect.AbstractIterator;
import org.apache.cassandra.db.DataRange;
import org.apache.cassandra.db.DecoratedKey;
import org.apache.cassandra.db.RowIndexEntry;
import org.apache.cassandra.db.RowPosition;
import org.apache.cassandra.db.columniterator.IColumnIteratorFactory;
import org.apache.cassandra.db.columniterator.LazyColumnIterator;
import org.apache.cassandra.db.columniterator.OnDiskAtomIterator;
import org.apache.cassandra.db.compaction.ICompactionScanner;
import org.apache.cassandra.db.filter.QueryFilter;
import org.apache.cassandra.dht.AbstractBounds;
import org.apache.cassandra.dht.Range;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.io.util.FileUtils;
import org.apache.cassandra.io.util.RandomAccessReader;
import org.apache.cassandra.utils.ByteBufferUtil;
public class SSTableScanner implements ICompactionScanner
{
protected final RandomAccessReader dfile;
protected final RandomAccessReader ifile;
public final SSTableReader sstable;
private final DataRange dataRange;
private final long stopAt;
protected Iterator<OnDiskAtomIterator> iterator;
/**
* @param sstable SSTable to scan; must not be null
* @param filter range of data to fetch; must not be null
* @param limiter background i/o RateLimiter; may be null
*/
SSTableScanner(SSTableReader sstable, DataRange dataRange, RateLimiter limiter)
{
assert sstable != null;
this.dfile = limiter == null ? sstable.openDataReader() : sstable.openDataReader(limiter);
this.ifile = sstable.openIndexReader();
this.sstable = sstable;
this.dataRange = dataRange;
this.stopAt = computeStopAt();
seekToStart();
}
private void seekToStart()
{
if (dataRange.startKey().isMinimum(sstable.partitioner))
return;
long indexPosition = sstable.getIndexScanPosition(dataRange.startKey());
// -1 means the key is before everything in the sstable. So just start from the beginning.
if (indexPosition == -1)
return;
ifile.seek(indexPosition);
try
{
while (!ifile.isEOF())
{
indexPosition = ifile.getFilePointer();
DecoratedKey indexDecoratedKey = sstable.partitioner.decorateKey(ByteBufferUtil.readWithShortLength(ifile));
int comparison = indexDecoratedKey.compareTo(dataRange.startKey());
if (comparison >= 0)
{
// Found, just read the dataPosition and seek into index and data files
long dataPosition = ifile.readLong();
ifile.seek(indexPosition);
dfile.seek(dataPosition);
break;
}
else
{
RowIndexEntry.serializer.skip(ifile);
}
}
}
catch (IOException e)
{
sstable.markSuspect();
throw new CorruptSSTableException(e, sstable.getFilename());
}
}
private long computeStopAt()
{
AbstractBounds<RowPosition> keyRange = dataRange.keyRange();
if (dataRange.stopKey().isMinimum(sstable.partitioner) || (keyRange instanceof Range && ((Range)keyRange).isWrapAround()))
return dfile.length();
RowIndexEntry position = sstable.getPosition(keyRange.toRowBounds().right, SSTableReader.Operator.GT);
return position == null ? dfile.length() : position.position;
}
public void close() throws IOException
{
FileUtils.close(dfile, ifile);
}
public long getLengthInBytes()
{
return dfile.length();
}
public long getCurrentPosition()
{
return dfile.getFilePointer();
}
public String getBackingFiles()
{
return sstable.toString();
}
public boolean hasNext()
{
if (iterator == null)
iterator = createIterator();
return iterator.hasNext();
}
public OnDiskAtomIterator next()
{
if (iterator == null)
iterator = createIterator();
return iterator.next();
}
public void remove()
{
throw new UnsupportedOperationException();
}
private Iterator<OnDiskAtomIterator> createIterator()
{
return new KeyScanningIterator();
}
protected class KeyScanningIterator extends AbstractIterator<OnDiskAtomIterator>
{
private DecoratedKey nextKey;
private RowIndexEntry nextEntry;
private DecoratedKey currentKey;
private RowIndexEntry currentEntry;
protected OnDiskAtomIterator computeNext()
{
try
{
if (ifile.isEOF() && nextKey == null)
return endOfData();
if (currentKey == null)
{
currentKey = sstable.partitioner.decorateKey(ByteBufferUtil.readWithShortLength(ifile));
currentEntry = RowIndexEntry.serializer.deserialize(ifile, sstable.descriptor.version);
}
else
{
currentKey = nextKey;
currentEntry = nextEntry;
}
assert currentEntry.position <= stopAt;
if (currentEntry.position == stopAt)
return endOfData();
if (ifile.isEOF())
{
nextKey = null;
nextEntry = null;
}
else
{
nextKey = sstable.partitioner.decorateKey(ByteBufferUtil.readWithShortLength(ifile));
nextEntry = RowIndexEntry.serializer.deserialize(ifile, sstable.descriptor.version);
}
assert !dfile.isEOF();
if (dataRange.selectsFullRowFor(currentKey.key))
{
dfile.seek(currentEntry.position);
ByteBufferUtil.readWithShortLength(dfile); // key
if (sstable.descriptor.version.hasRowSizeAndColumnCount)
dfile.readLong();
long dataSize = (nextEntry == null ? dfile.length() : nextEntry.position) - dfile.getFilePointer();
return new SSTableIdentityIterator(sstable, dfile, currentKey, dataSize);
}
return new LazyColumnIterator(currentKey, new IColumnIteratorFactory()
{
public OnDiskAtomIterator create()
{
return dataRange.columnFilter(currentKey.key).getSSTableColumnIterator(sstable, dfile, currentKey, currentEntry);
}
});
}
catch (IOException e)
{
sstable.markSuspect();
throw new CorruptSSTableException(e, sstable.getFilename());
}
}
}
@Override
public String toString()
{
return getClass().getSimpleName() + "(" +
"dfile=" + dfile +
" ifile=" + ifile +
" sstable=" + sstable +
")";
}
}
|
Java
|
/*
* Copyright 2012-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.
*/
package com.amazonaws.services.glacier.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.glacier.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* PartListElement JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class PartListElementJsonUnmarshaller implements Unmarshaller<PartListElement, JsonUnmarshallerContext> {
public PartListElement unmarshall(JsonUnmarshallerContext context) throws Exception {
PartListElement partListElement = new PartListElement();
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 null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("RangeInBytes", targetDepth)) {
context.nextToken();
partListElement.setRangeInBytes(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("SHA256TreeHash", targetDepth)) {
context.nextToken();
partListElement.setSHA256TreeHash(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 partListElement;
}
private static PartListElementJsonUnmarshaller instance;
public static PartListElementJsonUnmarshaller getInstance() {
if (instance == null)
instance = new PartListElementJsonUnmarshaller();
return instance;
}
}
|
Java
|
package seborama.demo2.kafka.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Order {
private String id;
private boolean fulfilled;
private boolean dispatched;
private boolean completed;
public void setId(String id) {
this.id = id;
}
public void setFulfilled(Boolean fulfilled) {
this.fulfilled = fulfilled;
}
public void setDispatched(Boolean dispatched) {
this.dispatched = dispatched;
}
public void setCompleted(Boolean completed) {
this.completed = completed;
}
public String getId() {
return id;
}
public Boolean getFulfilled() {
return fulfilled;
}
public Boolean getDispatched() {
return dispatched;
}
public Boolean getCompleted() {
return completed;
}
@Override
public String toString() {
return "Order{" +
"id='" + id + '\'' +
", fulfilled=" + fulfilled +
", dispatched=" + dispatched +
", completed=" + completed +
'}';
}
}
|
Java
|
# Salix goepperti Andersson SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
# Cortinarius olidissimus Ripart SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Cortinarius olidissimus Ripart
### Remarks
null
|
Java
|
# Polystictoides leucomelas Lázaro Ibiza, 1916 SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Revta R. Acad. Cienc. exact. fis. nat. Madr. 14: 833 (1916)
#### Original name
Polystictoides leucomelas Lázaro Ibiza, 1916
### Remarks
null
|
Java
|
public class ChickenBurger extends Burger {
@Override
public float price() {
return 50.5f;
}
@Override
public String name() {
return "Chicken Burger";
}
}
|
Java
|
/*
* Copyright (c) 2017 Otávio Santana and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php.
*
* You may elect to redistribute this code under either of these licenses.
*
* Contributors:
*
* Otavio Santana
*/
package org.jnosql.artemis.column.query;
import org.jnosql.artemis.CDIExtension;
import org.jnosql.artemis.model.Person;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import javax.inject.Inject;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
@ExtendWith(CDIExtension.class)
public class DefaultColumnQueryMapperBuilderTest {
@Inject
private ColumnQueryMapperBuilder mapperBuilder;
@Test
public void shouldReturnErrorWhenEntityClassIsNull() {
assertThrows(NullPointerException.class, () -> mapperBuilder.selectFrom(null));
}
@Test
public void shouldReturnSelectFrom() {
ColumnMapperFrom columnFrom = mapperBuilder.selectFrom(Person.class);
assertNotNull(columnFrom);
}
@Test
public void shouldReturnErrorWhenDeleteEntityClassIsNull() {
assertThrows(NullPointerException.class, () -> mapperBuilder.deleteFrom(null));
}
@Test
public void shouldReturnDeleteFrom() {
ColumnMapperDeleteFrom columnDeleteFrom = mapperBuilder.deleteFrom(Person.class);
assertNotNull(columnDeleteFrom);
}
}
|
Java
|
/* tslint:disable:max-classes-per-file */
import { forEach } from 'ramda';
import Interactor from '../CourseInteractor';
import InteractorLoader from '../CourseInteractorLoader';
import { ICourseStorage } from '../ICourseStorage';
import { IProgressStorage } from '../IProgressStorage';
import { ISerializedCourse } from '../ISerializedCourse';
import { ISerializedProgress, Progress } from '../ISerializedProgress';
const courses: { [propName: string]: ISerializedCourse } = {
'09438926-b170-4005-a6e8-5dd8fba83cde': {
id: '09438926-b170-4005-a6e8-5dd8fba83cde',
title: 'Foo bar',
children: [
{
id: '01f23c2a-b681-43db-9d27-5d8d59f62aed',
children: [
{
id: '23e20d5b-ad8e-41be-9891-5ca7b12675c4',
type: 'foo'
}
]
},
{
id: 'e194f80b-7312-43a2-995e-060f64631782',
children: [
{
id: '84fdc1a1-e3bf-4a87-8360-0c3b7beec179',
foo: 'bar',
type: 'foo'
}
]
}
]
}
};
const progresses: ISerializedProgress = {};
class MockCourseStorage implements ICourseStorage {
public getCourse(id: string) {
return new Promise<ISerializedCourse>((resolve, reject) => {
if (courses[id]) {
resolve(courses[id]);
}
reject(new Error(`There exists no course with id ${id}`));
});
}
}
class MockProgressStorage implements IProgressStorage {
public getProgress(id: string) {
return Promise.resolve(progresses);
}
public setProgress(id: string, progress: ISerializedProgress): Promise<void> {
return Promise.resolve();
}
public resetProgress() {
return Promise.resolve();
}
}
let interactorLoader: InteractorLoader;
let interactor: Interactor;
beforeEach(() => {
const storage = new MockCourseStorage();
const progress = new MockProgressStorage();
interactorLoader = new InteractorLoader(storage, progress);
});
it('loadCourse loads the course from storage if it exists', () =>
interactorLoader.loadCourse('09438926-b170-4005-a6e8-5dd8fba83cde'));
it('loadCourse fails if the course does not exist', () => {
return interactorLoader
.loadCourse('c990eacb-12af-4085-8b50-25d95d114984')
.catch(err => {
expect(err).toBeInstanceOf(Error);
});
});
describe('getStructure', () => {
beforeEach(() =>
interactorLoader
.loadCourse('09438926-b170-4005-a6e8-5dd8fba83cde')
.then(i => {
interactor = i;
})
);
it('returns the whole tree by default', () => {
expect(interactor.getStructure()).toMatchSnapshot();
});
it('returns only the first levels if a level is passed', () => {
expect(interactor.getStructure(1)).toMatchSnapshot();
});
});
describe('reset children progress', () => {
beforeEach(() =>
interactorLoader
.loadCourse('09438926-b170-4005-a6e8-5dd8fba83cde')
.then(i => {
interactor = i;
})
);
it('resets progress correctly', () => {
const root = '09438926-b170-4005-a6e8-5dd8fba83cde';
const children = [
'01f23c2a-b681-43db-9d27-5d8d59f62aed',
'23e20d5b-ad8e-41be-9891-5ca7b12675c4',
'e194f80b-7312-43a2-995e-060f64631782',
'84fdc1a1-e3bf-4a87-8360-0c3b7beec179'
];
forEach(
id => {
interactor.markAsCorrect(id);
},
[root, ...children]
);
interactor.resetChildrenProgress(root);
expect(interactor.getProgress(root).progress).toBe(Progress.Correct);
forEach(id => {
expect(interactor.getProgress(id).progress).toBe(Progress.Unseen);
}, children);
});
});
|
Java
|
import React from 'react';
import { action } from '@storybook/addon-actions';
import { Action } from '../Actions';
import ActionBar from './ActionBar.component';
const primary = {
label: 'Primary',
icon: 'talend-cog',
bsStyle: 'primary',
'data-feature': 'actionbar.primary',
onClick: action('You clicked me'),
};
const actions = {
left: [
primary,
{
label: 'Secondary1',
icon: 'talend-cog',
'data-feature': 'actionbar.secondary',
onClick: action('You clicked me'),
},
{
displayMode: ActionBar.DISPLAY_MODES.SPLIT_DROPDOWN,
label: 'Secondary3',
icon: 'talend-cog',
'data-feature': 'actionbar.splitdropdown',
onClick: action('on split button click'),
items: [
{
label: 'From Local',
'data-feature': 'actionbar.splitdropdown.items',
onClick: action('From Local click'),
},
{
label: 'From Remote',
'data-feature': 'actionbar.splitdropdown.items',
onClick: action('From Remote click'),
},
],
emptyDropdownLabel: 'No option',
},
{
id: 'dropdown',
displayMode: ActionBar.DISPLAY_MODES.DROPDOWN,
label: 'Dropdown',
icon: 'talend-cog',
items: [
{
label: 'From Local',
onClick: action('From Local click'),
},
{
label: 'From Remote',
onClick: action('From Remote click'),
},
],
},
],
right: [
{
label: 'Secondary4',
icon: 'talend-upload',
displayMode: 'file',
onChange: action('You changed me'),
},
{
label: 'Secondary5',
icon: 'talend-cog',
onClick: action('You clicked me'),
},
],
};
const multi3 = {
label: 'multi3',
icon: 'talend-cog',
onClick: action('You clicked me'),
};
const multiSelectActions = {
left: [
{
label: 'multi1',
icon: 'talend-cog',
onClick: action('You clicked me'),
},
{
label: 'multi2',
icon: 'talend-cog',
onClick: action('You clicked me'),
},
],
center: [
{
label: 'multi5',
icon: 'talend-cog',
onClick: action('You clicked me'),
},
],
right: [
multi3,
{
label: 'multi4',
icon: 'talend-cog',
onClick: action('You clicked me'),
},
],
};
const btnGroupActions = {
left: [
{
displayMode: ActionBar.DISPLAY_MODES.BTN_GROUP,
actions: [
{
label: 'hidden mean tooltips',
icon: 'talend-cog',
hideLabel: true,
onClick: action('cog'),
},
{
label: 'you are a super star',
icon: 'talend-badge',
hideLabel: true,
onClick: action('badge'),
},
{
label: 'but don t click this',
icon: 'talend-cross',
hideLabel: true,
onClick: action('boom'),
},
{
label: 'edit me',
icon: 'talend-pencil',
hideLabel: true,
onClick: action('oh yes'),
},
],
},
{
displayMode: ActionBar.DISPLAY_MODES.BTN_GROUP,
actions: [
{
label: 'you can also add',
icon: 'talend-plus-circle',
hideLabel: true,
onClick: action('add !'),
},
{
label: 'search',
icon: 'talend-search',
hideLabel: true,
onClick: action('search'),
},
{
label: 'star',
icon: 'talend-star',
hideLabel: true,
onClick: action('star'),
},
],
},
],
center: [
{
displayMode: ActionBar.DISPLAY_MODES.BTN_GROUP,
actions: [
{
label: 'go to dataprep',
icon: 'talend-dataprep',
hideLabel: true,
onClick: action('dataprep'),
},
{
label: 'go to elastic',
icon: 'talend-elastic',
hideLabel: true,
onClick: action('elastic'),
},
{
label: 'go to cloud engine',
icon: 'talend-cloud-engine',
hideLabel: true,
onClick: action('cloud-engine'),
},
],
},
],
right: [
{
displayMode: ActionBar.DISPLAY_MODES.BTN_GROUP,
actions: [
{
label: 'table',
icon: 'talend-table',
hideLabel: true,
onClick: action('table'),
},
{
label: 'trash',
icon: 'talend-trash',
hideLabel: true,
onClick: action('trash'),
},
],
},
],
};
const basicProps = {
actions,
multiSelectActions,
};
const multiDelete = {
label: 'Delete',
icon: 'talend-trash',
onClick: action('multiple delete'),
className: 'btn-icon-text',
};
const multiDuplicate = {
label: 'Duplicate',
icon: 'talend-files-o',
onClick: action('multiple duplicate'),
className: 'btn-icon-text',
};
const multiUpdate = {
label: 'Update',
icon: 'talend-file-move',
onClick: action('multiple update'),
className: 'btn-icon-text',
};
const multiFavorite = {
label: 'Favorite',
icon: 'talend-star',
onClick: action('multiple favorite'),
className: 'btn-icon-text',
};
const multiCertify = {
label: 'Certify',
icon: 'talend-badge',
onClick: action('multiple certify'),
className: 'btn-icon-text',
};
const massActions = {
left: [multiDelete, multiDuplicate, multiUpdate],
};
const appMassActions = {
left: [multiFavorite, multiCertify],
};
export default {
title: 'Form/Controls/ActionBar',
};
export const Default = () => (
<nav>
<p>No Selected, Layout: Left Space Right</p>
<div id="default">
<ActionBar {...basicProps} selected={0} />
</div>
<p>1 Selected, Layout: Left Center Right</p>
<div id="selected">
<ActionBar {...basicProps} selected={1} />
</div>
<p>1 Selected, Layout: Right</p>
<div id="right">
<ActionBar
selected={1}
actions={{ left: [primary] }}
multiSelectActions={{ right: [multi3] }}
/>
</div>
<p>Toolbar with btn-group and only icons/ Layout: left, center, right</p>
<div id="btn-group">
<ActionBar actions={btnGroupActions} />
</div>
<p>3 items selected, with mass/bulk Actions</p>
<div id="mass-actions">
<ActionBar
selected={3}
multiSelectActions={massActions}
appMultiSelectActions={appMassActions}
/>
</div>
</nav>
);
export const Custom = () => (
<nav>
<div id="default">
<ActionBar>
<ActionBar.Content tag="a" left href="#/foo/bar">
Hello anchor
</ActionBar.Content>
<ActionBar.Content tag="button" className="btn btn-default" left>
Hello button
</ActionBar.Content>
<ActionBar.Content left>
<Action label="hello Action" icon="talend-trash" onClick={action('onClick')} />
</ActionBar.Content>
<ActionBar.Content tag="form" role="search" center>
<div className="form-group">
<input type="text" className="form-control" placeholder="Search" />
</div>
<button type="submit" className="btn btn-default">
Submit
</button>
</ActionBar.Content>
<ActionBar.Content tag="p" right>
Hello paragraph
</ActionBar.Content>
</ActionBar>
</div>
</nav>
);
|
Java
|
import hashlib
from core.analytics import InlineAnalytics
from core.observables import Hash
HASH_TYPES_DICT = {
"md5": hashlib.md5,
"sha1": hashlib.sha1,
"sha256": hashlib.sha256,
"sha512": hashlib.sha512,
}
class HashFile(InlineAnalytics):
default_values = {
"name": "HashFile",
"description": "Extracts MD5, SHA1, SHA256, SHA512 hashes from file",
}
ACTS_ON = ["File", "Certificate"]
@staticmethod
def each(f):
if f.body:
f.hashes = []
for hash_type, h in HashFile.extract_hashes(f.body.contents):
hash_object = Hash.get_or_create(value=h.hexdigest())
hash_object.add_source("analytics")
hash_object.save()
f.active_link_to(
hash_object,
"{} hash".format(hash_type.upper()),
"HashFile",
clean_old=False,
)
f.hashes.append({"hash": hash_type, "value": h.hexdigest()})
f.save()
@staticmethod
def extract_hashes(body_contents):
hashers = {k: HASH_TYPES_DICT[k]() for k in HASH_TYPES_DICT}
while True:
chunk = body_contents.read(512 * 16)
if not chunk:
break
for h in hashers.values():
h.update(chunk)
return hashers.items()
|
Java
|
/**
* Copyright 2011-2021 Asakusa Framework Team.
*
* 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.asakusafw.dmdl.directio.text;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import org.apache.hadoop.io.compress.CompressionCodec;
import com.asakusafw.dmdl.directio.util.CharsetUtil;
import com.asakusafw.dmdl.directio.util.ClassName;
import com.asakusafw.dmdl.directio.util.Value;
import com.asakusafw.dmdl.java.emitter.EmitContext;
import com.asakusafw.dmdl.java.util.JavaName;
import com.asakusafw.dmdl.model.BasicTypeKind;
import com.asakusafw.dmdl.semantics.ModelDeclaration;
import com.asakusafw.dmdl.semantics.PropertyDeclaration;
import com.asakusafw.dmdl.semantics.type.BasicType;
import com.asakusafw.dmdl.util.AttributeUtil;
import com.asakusafw.runtime.io.text.TextFormat;
import com.asakusafw.runtime.io.text.TextInput;
import com.asakusafw.runtime.io.text.directio.AbstractTextStreamFormat;
import com.asakusafw.runtime.io.text.driver.FieldDefinition;
import com.asakusafw.runtime.io.text.driver.RecordDefinition;
import com.asakusafw.runtime.io.text.value.BooleanOptionFieldAdapter;
import com.asakusafw.runtime.io.text.value.ByteOptionFieldAdapter;
import com.asakusafw.runtime.io.text.value.DateOptionFieldAdapter;
import com.asakusafw.runtime.io.text.value.DateTimeOptionFieldAdapter;
import com.asakusafw.runtime.io.text.value.DecimalOptionFieldAdapter;
import com.asakusafw.runtime.io.text.value.DoubleOptionFieldAdapter;
import com.asakusafw.runtime.io.text.value.FloatOptionFieldAdapter;
import com.asakusafw.runtime.io.text.value.IntOptionFieldAdapter;
import com.asakusafw.runtime.io.text.value.LongOptionFieldAdapter;
import com.asakusafw.runtime.io.text.value.ShortOptionFieldAdapter;
import com.asakusafw.runtime.io.text.value.StringOptionFieldAdapter;
import com.asakusafw.runtime.io.text.value.ValueOptionFieldAdapter;
import com.asakusafw.runtime.io.util.InputSplitter;
import com.asakusafw.runtime.io.util.InputSplitters;
import com.asakusafw.runtime.value.StringOption;
import com.asakusafw.utils.java.model.syntax.ClassDeclaration;
import com.asakusafw.utils.java.model.syntax.Expression;
import com.asakusafw.utils.java.model.syntax.InfixOperator;
import com.asakusafw.utils.java.model.syntax.MethodDeclaration;
import com.asakusafw.utils.java.model.syntax.ModelFactory;
import com.asakusafw.utils.java.model.syntax.SimpleName;
import com.asakusafw.utils.java.model.syntax.Statement;
import com.asakusafw.utils.java.model.syntax.Type;
import com.asakusafw.utils.java.model.syntax.TypeBodyDeclaration;
import com.asakusafw.utils.java.model.util.AttributeBuilder;
import com.asakusafw.utils.java.model.util.ExpressionBuilder;
import com.asakusafw.utils.java.model.util.JavadocBuilder;
import com.asakusafw.utils.java.model.util.Models;
import com.asakusafw.utils.java.model.util.TypeBuilder;
/**
* Generates {@link AbstractTextStreamFormat}.
* @since 0.9.1
*/
public abstract class AbstractTextStreamFormatGenerator {
private static final Map<BasicTypeKind, Class<? extends ValueOptionFieldAdapter<?>>> ADAPTER_TYPES;
static {
Map<BasicTypeKind, Class<? extends ValueOptionFieldAdapter<?>>> map = new EnumMap<>(BasicTypeKind.class);
map.put(BasicTypeKind.BYTE, ByteOptionFieldAdapter.class);
map.put(BasicTypeKind.SHORT, ShortOptionFieldAdapter.class);
map.put(BasicTypeKind.INT, IntOptionFieldAdapter.class);
map.put(BasicTypeKind.LONG, LongOptionFieldAdapter.class);
map.put(BasicTypeKind.FLOAT, FloatOptionFieldAdapter.class);
map.put(BasicTypeKind.DOUBLE, DoubleOptionFieldAdapter.class);
map.put(BasicTypeKind.DECIMAL, DecimalOptionFieldAdapter.class);
map.put(BasicTypeKind.TEXT, StringOptionFieldAdapter.class);
map.put(BasicTypeKind.BOOLEAN, BooleanOptionFieldAdapter.class);
map.put(BasicTypeKind.DATE, DateOptionFieldAdapter.class);
map.put(BasicTypeKind.DATETIME, DateTimeOptionFieldAdapter.class);
ADAPTER_TYPES = map;
}
/**
* The current context.
*/
protected final EmitContext context;
/**
* The target model.
*/
protected final ModelDeclaration model;
private final ModelFactory f;
private final TextFormatSettings formatSettings;
private final TextFieldSettings fieldDefaultSettings;
/**
* Creates a new instance.
* @param context the current context
* @param model the target model
* @param formatSettings the text format settings
* @param fieldDefaultSettings the field default settings
*/
public AbstractTextStreamFormatGenerator(
EmitContext context, ModelDeclaration model,
TextFormatSettings formatSettings, TextFieldSettings fieldDefaultSettings) {
this.context = context;
this.model = model;
this.formatSettings = formatSettings;
this.fieldDefaultSettings = fieldDefaultSettings;
this.f = context.getModelFactory();
}
/**
* Emits an implementation of {@link AbstractTextStreamFormat} class as a Java compilation unit.
* @param description the format description
* @throws IOException if I/O error was occurred while emitting the compilation unit
*/
protected void emit(String description) throws IOException {
ClassDeclaration decl = f.newClassDeclaration(
new JavadocBuilder(f)
.inline(Messages.getString("AbstractTextStreamFormatGenerator.javadocClassOverview"), //$NON-NLS-1$
d -> d.text(description),
d -> d.linkType(context.resolve(model.getSymbol())))
.toJavadoc(),
new AttributeBuilder(f)
.Public()
.toAttributes(),
context.getTypeName(),
f.newParameterizedType(
context.resolve(AbstractTextStreamFormat.class),
context.resolve(model.getSymbol())),
Collections.emptyList(),
createMembers());
context.emit(decl);
}
private List<? extends TypeBodyDeclaration> createMembers() {
List<TypeBodyDeclaration> results = new ArrayList<>();
results.add(createGetSupportedType());
results.add(createCreateTextFormat());
results.addAll(createCreateRecordDefinition());
createGetInputSplitter().ifPresent(results::add);
createGetCompressionCodecClass().ifPresent(results::add);
createAfterInput().ifPresent(results::add);
createBeforeOutput().ifPresent(results::add);
return results;
}
private MethodDeclaration createGetSupportedType() {
return f.newMethodDeclaration(
null,
new AttributeBuilder(f)
.annotation(context.resolve(Override.class))
.Public()
.toAttributes(),
f.newParameterizedType(
context.resolve(Class.class),
context.resolve(model.getSymbol())),
f.newSimpleName("getSupportedType"), //$NON-NLS-1$
Collections.emptyList(),
Arrays.asList(new TypeBuilder(f, context.resolve(model.getSymbol()))
.dotClass()
.toReturnStatement()));
}
private MethodDeclaration createCreateTextFormat() {
return f.newMethodDeclaration(
null,
new AttributeBuilder(f)
.annotation(context.resolve(Override.class))
.Public()
.toAttributes(),
context.resolve(TextFormat.class),
f.newSimpleName("createTextFormat"), //$NON-NLS-1$
Collections.emptyList(),
createGetTextFormatInternal());
}
/**
* Returns a body of {@link AbstractTextStreamFormat#getTextFormat()}.
* @return the body statements
*/
protected abstract List<Statement> createGetTextFormatInternal();
private List<MethodDeclaration> createCreateRecordDefinition() {
SimpleName builder = f.newSimpleName("builder"); //$NON-NLS-1$
List<Statement> statements = new ArrayList<>();
statements.add(new TypeBuilder(f, context.resolve(RecordDefinition.class))
.method("builder", f.newClassLiteral(context.resolve(model.getSymbol()))) //$NON-NLS-1$
.toLocalVariableDeclaration(
f.newParameterizedType(
context.resolve(RecordDefinition.Builder.class),
context.resolve(model.getSymbol())),
builder));
List<MethodDeclaration> fields = buildRecordDefinition(statements, builder);
statements.add(new ExpressionBuilder(f, builder)
.method("build") //$NON-NLS-1$
.toReturnStatement());
List<MethodDeclaration> results = new ArrayList<>();
results.add(f.newMethodDeclaration(
null,
new AttributeBuilder(f)
.annotation(context.resolve(Override.class))
.Protected()
.toAttributes(),
f.newParameterizedType(
context.resolve(RecordDefinition.class),
context.resolve(model.getSymbol())),
f.newSimpleName("createRecordDefinition"), //$NON-NLS-1$
Collections.emptyList(),
statements));
results.addAll(fields);
return results;
}
private List<MethodDeclaration> buildRecordDefinition(List<Statement> statements, SimpleName builder) {
formatSettings.getHeaderType().ifPresent(v -> statements.add(new ExpressionBuilder(f, builder)
.method("withHeaderType", resolve(v)) //$NON-NLS-1$
.toStatement()));
formatSettings.getLessInputAction().ifPresent(v -> statements.add(new ExpressionBuilder(f, builder)
.method("withOnLessInput", resolve(v)) //$NON-NLS-1$
.toStatement()));
formatSettings.getMoreInputAction().ifPresent(v -> statements.add(new ExpressionBuilder(f, builder)
.method("withOnMoreInput", resolve(v)) //$NON-NLS-1$
.toStatement()));
fieldDefaultSettings.getTrimInputWhitespaces().ifPresent(v -> statements.add(new ExpressionBuilder(f, builder)
.method("withTrimInput", resolve(v)) //$NON-NLS-1$
.toStatement()));
fieldDefaultSettings.getSkipEmptyInput().ifPresent(v -> statements.add(new ExpressionBuilder(f, builder)
.method("withSkipEmptyInput", resolve(v)) //$NON-NLS-1$
.toStatement()));
fieldDefaultSettings.getMalformedInputAction().ifPresent(v -> statements.add(new ExpressionBuilder(f, builder)
.method("withOnMalformedInput", resolve(v)) //$NON-NLS-1$
.toStatement()));
fieldDefaultSettings.getUnmappableOutputAction().ifPresent(v -> statements.add(
new ExpressionBuilder(f, builder)
.method("withOnUnmappableOutput", resolve(v)) //$NON-NLS-1$
.toStatement()));
List<MethodDeclaration> fields = new ArrayList<>();
for (PropertyDeclaration property : model.getDeclaredProperties()) {
if (TextFieldTrait.getKind(property) != TextFieldTrait.Kind.VALUE) {
continue;
}
MethodDeclaration method = createGetFieldDefinition(property);
fields.add(method);
statements.add(new ExpressionBuilder(f, builder)
.method("withField", //$NON-NLS-1$
new TypeBuilder(f, context.resolve(model.getSymbol()))
.methodReference(context.getOptionGetterName(property))
.toExpression(),
new ExpressionBuilder(f, f.newThis())
.method(method.getName())
.toExpression())
.toStatement());
}
return fields;
}
private MethodDeclaration createGetFieldDefinition(PropertyDeclaration property) {
SimpleName builder = f.newSimpleName("builder"); //$NON-NLS-1$
List<Statement> statements = new ArrayList<>();
statements.add(new TypeBuilder(f, context.resolve(FieldDefinition.class))
.method("builder", //$NON-NLS-1$
resolve(TextFieldTrait.getName(property)),
buildFieldAdapter(property))
.toLocalVariableDeclaration(
f.newParameterizedType(
context.resolve(FieldDefinition.Builder.class),
context.getFieldType(property)),
builder));
TextFieldSettings settings = TextFieldTrait.getSettings(property);
settings.getTrimInputWhitespaces().ifPresent(v -> statements.add(new ExpressionBuilder(f, builder)
.method("withTrimInput", resolve(v)) //$NON-NLS-1$
.toStatement()));
settings.getSkipEmptyInput().ifPresent(v -> statements.add(new ExpressionBuilder(f, builder)
.method("withSkipEmptyInput", resolve(v)) //$NON-NLS-1$
.toStatement()));
settings.getMalformedInputAction().ifPresent(v -> statements.add(new ExpressionBuilder(f, builder)
.method("withOnMalformedInput", resolve(v)) //$NON-NLS-1$
.toStatement()));
settings.getUnmappableOutputAction().ifPresent(v -> statements.add(new ExpressionBuilder(f, builder)
.method("withOnUnmappableOutput", resolve(v)) //$NON-NLS-1$
.toStatement()));
settings.getQuoteStyle().ifPresent(v -> statements.add(new ExpressionBuilder(f, builder)
.method("withOutputOption", resolve(v)) //$NON-NLS-1$
.toStatement()));
statements.add(new ExpressionBuilder(f, builder)
.method("build") //$NON-NLS-1$
.toReturnStatement());
JavaName name = JavaName.of(property.getName());
name.addFirst("get"); //$NON-NLS-1$
name.addLast("field"); //$NON-NLS-1$
name.addLast("definition"); //$NON-NLS-1$
return f.newMethodDeclaration(
new JavadocBuilder(f)
.inline(Messages.getString("AbstractTextStreamFormatGenerator.javafocGetFieldDefinitionOverview"), //$NON-NLS-1$
d -> d.linkMethod(
context.resolve(model.getSymbol()),
context.getOptionGetterName(property)))
.returns()
.text(Messages.getString("AbstractTextStreamFormatGenerator.javadocGetFieldDefinitionReturn")) //$NON-NLS-1$
.toJavadoc(),
new AttributeBuilder(f)
.Protected()
.toAttributes(),
f.newParameterizedType(
context.resolve(FieldDefinition.class),
context.getFieldType(property)),
f.newSimpleName(name.toMemberName()),
Collections.emptyList(),
statements);
}
private Expression buildFieldAdapter(PropertyDeclaration property) {
TextFieldSettings settings = TextFieldTrait.getSettings(property);
Value<ClassName> adapterClass = setting(settings, TextFieldSettings::getAdapterClass);
if (adapterClass.isPresent()) {
return new TypeBuilder(f, resolve(adapterClass.getEntity()))
.constructorReference()
.toExpression();
}
BasicTypeKind kind = ((BasicType) property.getType()).getKind();
Class<? extends ValueOptionFieldAdapter<?>> basicAdapterClass = ADAPTER_TYPES.get(kind);
assert basicAdapterClass != null;
ExpressionBuilder builder = new TypeBuilder(f, context.resolve(basicAdapterClass)).method("builder"); //$NON-NLS-1$
setting(settings, TextFieldSettings::getNullFormat).ifPresent(v -> builder
.method("withNullFormat", resolve(v))); //$NON-NLS-1$
switch (kind) {
case BOOLEAN:
setting(settings, TextFieldSettings::getTrueFormat).ifPresent(v -> builder
.method("withTrueFormat", resolve(v))); //$NON-NLS-1$
setting(settings, TextFieldSettings::getFalseFormat).ifPresent(v -> builder
.method("withFalseFormat", resolve(v))); //$NON-NLS-1$
break;
case DATE:
setting(settings, TextFieldSettings::getDateFormat).ifPresent(v -> builder
.method("withDateFormat", resolve(v.toString()))); //$NON-NLS-1$
break;
case DATETIME:
setting(settings, TextFieldSettings::getDateTimeFormat).ifPresent(v -> builder
.method("withDateTimeFormat", resolve(v.toString()))); //$NON-NLS-1$
setting(settings, TextFieldSettings::getTimeZone).ifPresent(v -> builder
.method("withTimeZone", resolve(v.getId()))); //$NON-NLS-1$
break;
case DECIMAL:
setting(settings, TextFieldSettings::getNumberFormat).ifPresent(v -> builder
.method("withNumberFormat", resolve(v.toString()))); //$NON-NLS-1$
setting(settings, TextFieldSettings::getDecimalOutputStyle).ifPresent(v -> builder
.method("withOutputStyle", resolve(v))); //$NON-NLS-1$
break;
case BYTE:
case INT:
case SHORT:
case LONG:
case FLOAT:
case DOUBLE:
setting(settings, TextFieldSettings::getNumberFormat).ifPresent(v -> builder
.method("withNumberFormat", resolve(v.toString()))); //$NON-NLS-1$
break;
case TEXT:
// no special members
break;
default:
throw new AssertionError(kind);
}
return builder.method("lazy").toExpression(); //$NON-NLS-1$
}
private <T> Value<T> setting(TextFieldSettings settings, Function<TextFieldSettings, Value<T>> getter) {
return getter.apply(settings).orDefault(getter.apply(fieldDefaultSettings));
}
private Optional<MethodDeclaration> createGetInputSplitter() {
if (isSplittable()) {
return Optional.of(f.newMethodDeclaration(
null,
new AttributeBuilder(f)
.annotation(context.resolve(Override.class))
.Protected()
.toAttributes(),
context.resolve(InputSplitter.class),
f.newSimpleName("getInputSplitter"), //$NON-NLS-1$
Collections.emptyList(),
Arrays.asList(new TypeBuilder(f, context.resolve(InputSplitters.class))
.method("byLineFeed") //$NON-NLS-1$
.toReturnStatement())));
} else {
return Optional.empty();
}
}
private boolean isSplittable() {
if (formatSettings.getCharset().isPresent()) {
if (!CharsetUtil.isAsciiCompatible(formatSettings.getCharset().getEntity())) {
return false;
}
}
if (formatSettings.getCompressionType().isPresent()) {
return false;
}
if (model.getDeclaredProperties().stream()
.map(TextFieldTrait::getKind)
.anyMatch(Predicate.isEqual(TextFieldTrait.Kind.LINE_NUMBER)
.or(Predicate.isEqual(TextFieldTrait.Kind.RECORD_NUMBER)))) {
return false;
}
return isSplittableInternal();
}
/**
* Returns whether or not the input is splittable.
* @return {@code true} if it is splittable, otherwise {@code false}
*/
protected abstract boolean isSplittableInternal();
private Optional<MethodDeclaration> createGetCompressionCodecClass() {
if (formatSettings.getCompressionType().isPresent()) {
ClassName codec = formatSettings.getCompressionType().getEntity();
return Optional.of(f.newMethodDeclaration(
null,
new AttributeBuilder(f)
.annotation(context.resolve(Override.class))
.Protected()
.toAttributes(),
new TypeBuilder(f, context.resolve(Class.class))
.parameterize(f.newWildcardExtends(context.resolve(CompressionCodec.class)))
.toType(),
f.newSimpleName("getCompressionCodecClass"), //$NON-NLS-1$
Collections.emptyList(),
Arrays.asList(new TypeBuilder(f, resolve(codec))
.dotClass()
.toReturnStatement())));
} else {
return Optional.empty();
}
}
private Optional<MethodDeclaration> createAfterInput() {
SimpleName object = f.newSimpleName("object"); //$NON-NLS-1$
SimpleName path = f.newSimpleName("path"); //$NON-NLS-1$
SimpleName input = f.newSimpleName("input"); //$NON-NLS-1$
List<Statement> statements = new ArrayList<>();
for (PropertyDeclaration property : model.getDeclaredProperties()) {
switch (TextFieldTrait.getKind(property)) {
case VALUE:
break; // does nothing
case IGNORE:
statements.add(new ExpressionBuilder(f, object)
.method(context.getOptionSetterName(property), Models.toNullLiteral(f))
.toStatement());
break;
case FILE_NAME:
statements.add(new ExpressionBuilder(f, object)
.method(context.getOptionSetterName(property), path)
.toStatement());
break;
case LINE_NUMBER:
statements.add(new ExpressionBuilder(f, object)
.method(context.getValueSetterName(property),
adjustLong(property, new ExpressionBuilder(f, input)
.method("getLineNumber") //$NON-NLS-1$
.apply(InfixOperator.PLUS, Models.toLiteral(f, 1L))))
.toStatement());
break;
case RECORD_NUMBER:
statements.add(new ExpressionBuilder(f, object)
.method(context.getValueSetterName(property),
adjustLong(property, new ExpressionBuilder(f, input)
.method("getRecordIndex") //$NON-NLS-1$
.apply(InfixOperator.PLUS, Models.toLiteral(f, 1L))))
.toStatement());
break;
default:
throw new AssertionError(TextFieldTrait.getKind(property));
}
}
if (statements.isEmpty()) {
return Optional.empty();
} else {
return Optional.of(f.newMethodDeclaration(
null,
new AttributeBuilder(f)
.annotation(context.resolve(Override.class))
.Protected()
.toAttributes(),
context.resolve(void.class),
f.newSimpleName("afterInput"), //$NON-NLS-1$
Arrays.asList(
f.newFormalParameterDeclaration(context.resolve(model.getSymbol()), object),
f.newFormalParameterDeclaration(context.resolve(StringOption.class), path),
f.newFormalParameterDeclaration(
f.newParameterizedType(
context.resolve(TextInput.class),
context.resolve(model.getSymbol())),
input)),
statements));
}
}
private Expression adjustLong(PropertyDeclaration property, ExpressionBuilder builder) {
if (AttributeUtil.hasFieldType(property, BasicTypeKind.LONG)) {
return builder.toExpression();
} else if (AttributeUtil.hasFieldType(property, BasicTypeKind.INT)) {
return builder.castTo(context.resolve(int.class)).toExpression();
} else {
throw new AssertionError(property);
}
}
private Optional<MethodDeclaration> createBeforeOutput() {
return Optional.empty();
}
/**
* Resolves a value.
* @param value the value
* @return the resolved expression
*/
protected Expression resolve(boolean value) {
return Models.toLiteral(f, value);
}
/**
* Resolves a value.
* @param value the value
* @return the resolved expression
*/
protected Expression resolve(char value) {
return Models.toLiteral(f, value);
}
/**
* Resolves a value.
* @param value the value
* @return the resolved expression
*/
protected Expression resolve(String value) {
return Models.toLiteral(f, value);
}
/**
* Resolves a value.
* @param value the value
* @return the resolved expression
*/
protected Expression resolve(Enum<?> value) {
return new TypeBuilder(f, context.resolve(value.getDeclaringClass()))
.field(value.name())
.toExpression();
}
/**
* Resolves a value.
* @param type the value
* @return the resolved expression
*/
protected Type resolve(ClassName type) {
return context.resolve(Models.toName(f, type.toString()));
}
}
|
Java
|
/*
* Copyright 2007 Sascha Weinreuter
*
* 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.intellij.plugins.relaxNG.references;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import com.intellij.codeInsight.daemon.EmptyResolveMessageProvider;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.LocalQuickFixProvider;
import com.intellij.codeInspection.XmlQuickFixFactory;
import com.intellij.lang.xml.XMLLanguage;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.intellij.psi.PsiReferenceProvider;
import com.intellij.psi.XmlElementFactory;
import com.intellij.psi.impl.source.resolve.reference.impl.providers.BasicAttributeValueReference;
import com.intellij.psi.impl.source.xml.SchemaPrefix;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlAttributeValue;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ProcessingContext;
/*
* Created by IntelliJ IDEA.
* User: sweinreuter
* Date: 24.07.2007
*/
public class PrefixReferenceProvider extends PsiReferenceProvider
{
private static final Logger LOG = Logger.getInstance("#org.intellij.plugins.relaxNG.references.PrefixReferenceProvider");
@Override
@NotNull
public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context)
{
final XmlAttributeValue value = (XmlAttributeValue) element;
final String s = value.getValue();
final int i = s.indexOf(':');
if(i <= 0 || s.startsWith("xml:"))
{
return PsiReference.EMPTY_ARRAY;
}
return new PsiReference[]{
new PrefixReference(value, i)
};
}
private static class PrefixReference extends BasicAttributeValueReference implements EmptyResolveMessageProvider, LocalQuickFixProvider
{
public PrefixReference(XmlAttributeValue value, int length)
{
super(value, TextRange.from(1, length));
}
@Override
@Nullable
public PsiElement resolve()
{
final String prefix = getCanonicalText();
XmlTag tag = PsiTreeUtil.getParentOfType(getElement(), XmlTag.class);
while(tag != null)
{
if(tag.getLocalNamespaceDeclarations().containsKey(prefix))
{
final XmlAttribute attribute = tag.getAttribute("xmlns:" + prefix, "");
final TextRange textRange = TextRange.from("xmlns:".length(), prefix.length());
return new SchemaPrefix(attribute, textRange, prefix);
}
tag = tag.getParentTag();
}
return null;
}
@Override
public boolean isReferenceTo(PsiElement element)
{
if(element instanceof SchemaPrefix && element.getContainingFile() == myElement.getContainingFile())
{
final PsiElement e = resolve();
if(e instanceof SchemaPrefix)
{
final String s = ((SchemaPrefix) e).getName();
return s != null && s.equals(((SchemaPrefix) element).getName());
}
}
return super.isReferenceTo(element);
}
@Nullable
@Override
public LocalQuickFix[] getQuickFixes()
{
final PsiElement element = getElement();
final XmlElementFactory factory = XmlElementFactory.getInstance(element.getProject());
final String value = ((XmlAttributeValue) element).getValue();
final String[] name = value.split(":");
final XmlTag tag = factory.createTagFromText("<" + (name.length > 1 ? name[1] : value) + " />", XMLLanguage.INSTANCE);
return new LocalQuickFix[]{XmlQuickFixFactory.getInstance().createNSDeclarationIntentionFix(tag, getCanonicalText(), null)};
}
@Override
@NotNull
public Object[] getVariants()
{
return ArrayUtil.EMPTY_OBJECT_ARRAY;
}
@Override
public boolean isSoft()
{
return false;
}
@Override
@NotNull
public String getUnresolvedMessagePattern()
{
return "Undefined namespace prefix ''{0}''";
}
}
}
|
Java
|
/**
* Copyright 2017 Hortonworks.
*
* 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.hortonworks.streamline.streams.service;
import com.codahale.metrics.annotation.Timed;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hortonworks.streamline.common.exception.service.exception.request.BadRequestException;
import com.hortonworks.streamline.common.exception.service.exception.request.EntityNotFoundException;
import com.hortonworks.streamline.common.exception.service.exception.server.UnhandledServerException;
import com.hortonworks.streamline.common.util.WSUtils;
import com.hortonworks.streamline.streams.actions.topology.service.TopologyActionsService;
import com.hortonworks.streamline.streams.catalog.Topology;
import com.hortonworks.streamline.streams.catalog.TopologySink;
import com.hortonworks.streamline.streams.catalog.TopologySource;
import com.hortonworks.streamline.streams.catalog.TopologyTestRunCase;
import com.hortonworks.streamline.streams.catalog.TopologyTestRunCaseSink;
import com.hortonworks.streamline.streams.catalog.TopologyTestRunCaseSource;
import com.hortonworks.streamline.streams.catalog.TopologyTestRunHistory;
import com.hortonworks.streamline.streams.catalog.service.StreamCatalogService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.BooleanUtils;
import org.datanucleus.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
import static javax.ws.rs.core.Response.Status.CREATED;
import static javax.ws.rs.core.Response.Status.OK;
@Path("/v1/catalog")
@Produces(MediaType.APPLICATION_JSON)
public class TopologyTestRunResource {
private static final Logger LOG = LoggerFactory.getLogger(TopologyTestRunResource.class);
private static final Integer DEFAULT_LIST_ENTITIES_COUNT = 5;
public static final Charset ENCODING_UTF_8 = Charset.forName("UTF-8");
private final StreamCatalogService catalogService;
private final TopologyActionsService actionsService;
private final ObjectMapper objectMapper;
public TopologyTestRunResource(StreamCatalogService catalogService, TopologyActionsService actionsService) {
this.catalogService = catalogService;
this.actionsService = actionsService;
this.objectMapper = new ObjectMapper();
}
@POST
@Path("/topologies/{topologyId}/actions/testrun")
@Timed
public Response testRunTopology (@Context UriInfo urlInfo,
@PathParam("topologyId") Long topologyId,
String testRunInputJson) throws Exception {
Topology result = catalogService.getTopology(topologyId);
if (result != null) {
TopologyTestRunHistory history = actionsService.testRunTopology(result, testRunInputJson);
return WSUtils.respondEntity(history, OK);
}
throw EntityNotFoundException.byId(topologyId.toString());
}
@GET
@Path("/topologies/{topologyId}/testhistories")
@Timed
public Response getHistoriesOfTestRunTopology (@Context UriInfo urlInfo,
@PathParam("topologyId") Long topologyId,
@QueryParam("limit") Integer limit) throws Exception {
Collection<TopologyTestRunHistory> histories = catalogService.listTopologyTestRunHistory(topologyId);
if (histories == null) {
throw EntityNotFoundException.byFilter("topology id " + topologyId);
}
List<TopologyTestRunHistory> filteredHistories = filterHistories(limit, histories);
return WSUtils.respondEntities(filteredHistories, OK);
}
@GET
@Path("/topologies/{topologyId}/versions/{versionId}/testhistories")
@Timed
public Response getHistoriesOfTestRunTopology (@Context UriInfo urlInfo,
@PathParam("topologyId") Long topologyId,
@PathParam("versionId") Long versionId,
@QueryParam("limit") Integer limit) throws Exception {
Collection<TopologyTestRunHistory> histories = catalogService.listTopologyTestRunHistory(topologyId, versionId);
if (histories == null) {
throw EntityNotFoundException.byFilter("topology id " + topologyId);
}
List<TopologyTestRunHistory> filteredHistories = filterHistories(limit, histories);
return WSUtils.respondEntities(filteredHistories, OK);
}
@GET
@Path("/topologies/{topologyId}/testhistories/{historyId}")
@Timed
public Response getHistoryOfTestRunTopology (@Context UriInfo urlInfo,
@PathParam("topologyId") Long topologyId,
@PathParam("historyId") Long historyId,
@QueryParam("simplify") Boolean simplify) throws Exception {
TopologyTestRunHistory history = catalogService.getTopologyTestRunHistory(historyId);
if (history == null) {
throw EntityNotFoundException.byId(String.valueOf(historyId));
}
if (!history.getTopologyId().equals(topologyId)) {
throw BadRequestException.message("Test history " + historyId + " is not belong to topology " + topologyId);
}
if (BooleanUtils.isTrue(simplify)) {
return WSUtils.respondEntity(new SimplifiedTopologyTestRunHistory(history), OK);
} else {
return WSUtils.respondEntity(history, OK);
}
}
@GET
@Path("/topologies/{topologyId}/testhistories/{historyId}/events")
public Response getEventsOfTestRunTopologyHistory(@Context UriInfo urlInfo,
@PathParam("topologyId") Long topologyId,
@PathParam("historyId") Long historyId) throws Exception {
return getEventsOfTestRunTopologyHistory(topologyId, historyId, null);
}
@GET
@Path("/topologies/{topologyId}/testhistories/{historyId}/events/{componentName}")
public Response getEventsOfTestRunTopologyHistory(@Context UriInfo urlInfo,
@PathParam("topologyId") Long topologyId,
@PathParam("historyId") Long historyId,
@PathParam("componentName") String componentName) throws Exception {
return getEventsOfTestRunTopologyHistory(topologyId, historyId, componentName);
}
@GET
@Path("/topologies/{topologyId}/testhistories/{historyId}/events/download")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadEventsOfTestRunTopologyHistory(@Context UriInfo urlInfo,
@PathParam("topologyId") Long topologyId,
@PathParam("historyId") Long historyId) throws Exception {
File eventLogFile = getEventLogFile(topologyId, historyId);
String content = FileUtils.readFileToString(eventLogFile, ENCODING_UTF_8);
InputStream is = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8));
String fileName = String.format("events-topology-%d-history-%d.log", topologyId, historyId);
return Response.status(OK)
.entity(is)
.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"")
.build();
}
private Response getEventsOfTestRunTopologyHistory(Long topologyId, Long historyId, String componentName) throws IOException {
File eventLogFile = getEventLogFile(topologyId, historyId);
List<String> lines = FileUtils.readLines(eventLogFile, ENCODING_UTF_8);
Stream<Map<String, Object>> eventsStream = lines.stream().map(line -> {
try {
return objectMapper.readValue(line, new TypeReference<Map<String, Object>>() {});
} catch (IOException e) {
throw new RuntimeException(e);
}
});
if (!StringUtils.isEmpty(componentName)) {
eventsStream = eventsStream.filter(event -> {
String eventComponentName = (String) event.get("componentName");
return eventComponentName != null && eventComponentName.equals(componentName);
});
}
return WSUtils.respondEntities(eventsStream.collect(toList()), OK);
}
private File getEventLogFile(Long topologyId, Long historyId) {
TopologyTestRunHistory history = catalogService.getTopologyTestRunHistory(historyId);
if (history == null) {
throw EntityNotFoundException.byId(String.valueOf(historyId));
}
if (!history.getTopologyId().equals(topologyId)) {
throw BadRequestException.message("Test history " + historyId + " is not belong to topology " + topologyId);
}
String eventLogFilePath = history.getEventLogFilePath();
File eventLogFile = new File(eventLogFilePath);
if (!eventLogFile.exists() || eventLogFile.isDirectory() || !eventLogFile.canRead()) {
throw BadRequestException.message("Event log file of history " + historyId + " does not exist or is not readable.");
}
return eventLogFile;
}
private List<TopologyTestRunHistory> filterHistories(Integer limit, Collection<TopologyTestRunHistory> histories) {
if (limit == null) {
limit = DEFAULT_LIST_ENTITIES_COUNT;
}
return histories.stream()
// reverse order
.sorted((h1, h2) -> (int) (h2.getId() - h1.getId()))
.limit(limit)
.collect(toList());
}
@POST
@Path("/topologies/{topologyId}/testcases")
public Response addTestRunCase(@PathParam("topologyId") Long topologyId,
TopologyTestRunCase testRunCase) {
testRunCase.setTopologyId(topologyId);
Long currentVersionId = catalogService.getCurrentVersionId(topologyId);
testRunCase.setVersionId(currentVersionId);
TopologyTestRunCase addedCase = catalogService.addTopologyTestRunCase(testRunCase);
return WSUtils.respondEntity(addedCase, CREATED);
}
@POST
@Path("/topologies/{topologyId}/versions/{versionId}/testcases")
public Response addTestRunCase(@PathParam("topologyId") Long topologyId,
@PathParam("versionId") Long versionId,
TopologyTestRunCase testRunCase) {
testRunCase.setTopologyId(topologyId);
testRunCase.setVersionId(versionId);
TopologyTestRunCase addedCase = catalogService.addTopologyTestRunCase(testRunCase);
return WSUtils.respondEntity(addedCase, CREATED);
}
@PUT
@Path("/topologies/{topologyId}/testcases/{testCaseId}")
public Response addOrUpdateTestRunCase(@PathParam("topologyId") Long topologyId,
@PathParam("testCaseId") Long testCaseId,
TopologyTestRunCase testRunCase) {
testRunCase.setTopologyId(topologyId);
testRunCase.setId(testCaseId);
TopologyTestRunCase updatedCase = catalogService.addOrUpdateTopologyTestRunCase(topologyId, testRunCase);
return WSUtils.respondEntity(updatedCase, OK);
}
@GET
@Path("/topologies/{topologyId}/testcases/{testCaseId}")
public Response getTestRunCase(@PathParam("topologyId") Long topologyId,
@PathParam("testCaseId") Long testCaseId) {
TopologyTestRunCase testcase = catalogService.getTopologyTestRunCase(topologyId, testCaseId);
if (testcase == null) {
throw EntityNotFoundException.byId(Long.toString(testCaseId));
}
return WSUtils.respondEntity(testcase, OK);
}
@GET
@Path("/topologies/{topologyId}/testcases")
@Timed
public Response listTestRunCases(@Context UriInfo urlInfo,
@PathParam("topologyId") Long topologyId,
@QueryParam("limit") Integer limit) throws Exception {
Long currentVersionId = catalogService.getCurrentVersionId(topologyId);
Collection<TopologyTestRunCase> cases = catalogService.listTopologyTestRunCase(topologyId, currentVersionId);
if (cases == null) {
throw EntityNotFoundException.byFilter("topology id " + topologyId);
}
List<TopologyTestRunCase> filteredCases = filterTestRunCases(limit, cases);
return WSUtils.respondEntities(filteredCases, OK);
}
@GET
@Path("/topologies/{topologyId}/versions/{versionId}/testcases")
@Timed
public Response listTestRunCases(@Context UriInfo urlInfo,
@PathParam("topologyId") Long topologyId,
@PathParam("versionId") Long versionId,
@QueryParam("limit") Integer limit) throws Exception {
Collection<TopologyTestRunCase> cases = catalogService.listTopologyTestRunCase(topologyId, versionId);
if (cases == null) {
throw EntityNotFoundException.byFilter("topology id " + topologyId);
}
List<TopologyTestRunCase> filteredCases = filterTestRunCases(limit, cases);
return WSUtils.respondEntities(filteredCases, OK);
}
@DELETE
@Path("/topologies/{topologyId}/testcases/{testCaseId}")
public Response removeTestRunCase(@PathParam("topologyId") Long topologyId,
@PathParam("testCaseId") Long testCaseId) {
TopologyTestRunCase testRunCase = catalogService.removeTestRunCase(topologyId, testCaseId);
if (testRunCase != null) {
return WSUtils.respondEntity(testRunCase, OK);
}
throw EntityNotFoundException.byId(testCaseId.toString());
}
private List<TopologyTestRunCase> filterTestRunCases(Integer limit, Collection<TopologyTestRunCase> cases) {
if (limit == null) {
limit = DEFAULT_LIST_ENTITIES_COUNT;
}
return cases.stream()
// reverse order
.sorted((h1, h2) -> (int) (h2.getId() - h1.getId()))
.limit(limit)
.collect(toList());
}
@POST
@Path("/topologies/{topologyId}/testcases/{testCaseId}/sources")
public Response addTestRunCaseSource(@PathParam("topologyId") Long topologyId,
@PathParam("testCaseId") Long testCaseId,
TopologyTestRunCaseSource testRunCaseSource) {
TopologySource topologySource = getAssociatedTopologySource(topologyId, testCaseId, testRunCaseSource.getSourceId());
testRunCaseSource.setVersionId(topologySource.getVersionId());
TopologyTestRunCaseSource addedCaseSource = catalogService.addTopologyTestRunCaseSource(testRunCaseSource);
return WSUtils.respondEntity(addedCaseSource, CREATED);
}
@PUT
@Path("/topologies/{topologyId}/testcases/{testCaseId}/sources/{id}")
public Response addOrUpdateTestRunCaseSource(@PathParam("topologyId") Long topologyId,
@PathParam("testCaseId") Long testCaseId,
@PathParam("id") Long id,
TopologyTestRunCaseSource testRunCaseSource) {
testRunCaseSource.setId(id);
testRunCaseSource.setTestCaseId(testCaseId);
TopologySource topologySource = getAssociatedTopologySource(topologyId, testCaseId, testRunCaseSource.getSourceId());
testRunCaseSource.setVersionId(topologySource.getVersionId());
TopologyTestRunCaseSource updatedCase = catalogService.addOrUpdateTopologyTestRunCaseSource(testRunCaseSource.getId(), testRunCaseSource);
return WSUtils.respondEntity(updatedCase, OK);
}
private TopologySource getAssociatedTopologySource(Long topologyId, Long testCaseId, Long topologySourceId) {
TopologyTestRunCase testCase = catalogService.getTopologyTestRunCase(topologyId, testCaseId);
if (testCase == null) {
throw EntityNotFoundException.byId("Topology test case with topology id " + topologyId +
" and test case id " + testCaseId);
}
TopologySource topologySource = catalogService.getTopologySource(topologyId, topologySourceId,
testCase.getVersionId());
if (topologySource == null) {
throw EntityNotFoundException.byId("Topology source with topology id " + topologyId +
" and version id " + testCase.getVersionId());
} else if (!testCase.getVersionId().equals(topologySource.getVersionId())) {
throw new IllegalStateException("Test case and topology source point to the different version id: "
+ "version id of test case: " + testCase.getVersionId() + " / "
+ "version id of topology source: " + topologySource.getVersionId());
}
return topologySource;
}
@GET
@Path("/topologies/{topologyId}/testcases/{testcaseId}/sources/{id}")
public Response getTestRunCaseSource(@PathParam("topologyId") Long topologyId,
@PathParam("testcaseId") Long testcaseId,
@PathParam("id") Long id) {
TopologyTestRunCaseSource testCaseSource = catalogService.getTopologyTestRunCaseSource(testcaseId, id);
if (testCaseSource == null) {
throw EntityNotFoundException.byId(Long.toString(id));
}
return WSUtils.respondEntity(testCaseSource, OK);
}
@GET
@Path("/topologies/{topologyId}/testcases/{testCaseId}/sources/topologysource/{sourceId}")
public Response getTestRunCaseSourceByTopologySource(@PathParam("topologyId") Long topologyId,
@PathParam("testCaseId") Long testCaseId,
@PathParam("sourceId") Long sourceId) {
TopologyTestRunCaseSource testCaseSource = catalogService.getTopologyTestRunCaseSourceBySourceId(testCaseId, sourceId);
if (testCaseSource == null) {
throw EntityNotFoundException.byId("test case id: " + testCaseId + " , topology source id: " + sourceId);
}
return WSUtils.respondEntity(testCaseSource, OK);
}
@GET
@Path("/topologies/{topologyId}/testcases/{testCaseId}/sources")
public Response listTestRunCaseSource(@PathParam("topologyId") Long topologyId,
@PathParam("testCaseId") Long testCaseId) {
Collection<TopologyTestRunCaseSource> sources = catalogService.listTopologyTestRunCaseSource(topologyId, testCaseId);
if (sources == null) {
throw EntityNotFoundException.byFilter("topologyId: " + topologyId + " / testCaseId: " + testCaseId);
}
return WSUtils.respondEntities(sources, OK);
}
@POST
@Path("/topologies/{topologyId}/testcases/{testCaseId}/sinks")
public Response addTestRunCaseSink(@PathParam("topologyId") Long topologyId,
@PathParam("testCaseId") Long testCaseId,
TopologyTestRunCaseSink testRunCaseSink) {
TopologySink topologySink = getAssociatedTopologySink(topologyId, testCaseId, testRunCaseSink.getSinkId());
testRunCaseSink.setVersionId(topologySink.getVersionId());
TopologyTestRunCaseSink addedCaseSink = catalogService.addTopologyTestRunCaseSink(testRunCaseSink);
return WSUtils.respondEntity(addedCaseSink, CREATED);
}
@PUT
@Path("/topologies/{topologyId}/testcases/{testCaseId}/sinks/{id}")
public Response addOrUpdateTestRunCaseSink(@PathParam("topologyId") Long topologyId,
@PathParam("testCaseId") Long testCaseId,
@PathParam("id") Long id,
TopologyTestRunCaseSink testRunCaseSink) {
testRunCaseSink.setId(id);
testRunCaseSink.setTestCaseId(testCaseId);
TopologySink topologySink = getAssociatedTopologySink(topologyId, testCaseId, testRunCaseSink.getSinkId());
testRunCaseSink.setVersionId(topologySink.getVersionId());
TopologyTestRunCaseSink updatedCase = catalogService.addOrUpdateTopologyTestRunCaseSink(testRunCaseSink.getId(), testRunCaseSink);
return WSUtils.respondEntity(updatedCase, OK);
}
private TopologySink getAssociatedTopologySink(Long topologyId, Long testCaseId, Long topologySinkId) {
TopologyTestRunCase testCase = catalogService.getTopologyTestRunCase(topologyId, testCaseId);
if (testCase == null) {
throw EntityNotFoundException.byId("Topology test case with topology id " + topologyId +
" and test case id " + testCaseId);
}
TopologySink topologySink = catalogService.getTopologySink(topologyId, topologySinkId,
testCase.getVersionId());
if (topologySink == null) {
throw EntityNotFoundException.byId("Topology sink with topology id " + topologyId +
" and version id " + testCase.getVersionId());
} else if (!testCase.getVersionId().equals(topologySink.getVersionId())) {
throw new IllegalStateException("Test case and topology sink point to the different version id: "
+ "version id of test case: " + testCase.getVersionId() + " / "
+ "version id of topology sink: " + topologySink.getVersionId());
}
return topologySink;
}
@GET
@Path("/topologies/{topologyId}/testcases/{testcaseId}/sinks/{id}")
public Response getTestRunCaseSink(@PathParam("topologyId") Long topologyId,
@PathParam("testcaseId") Long testcaseId,
@PathParam("id") Long id) {
TopologyTestRunCaseSink testCaseSink = catalogService.getTopologyTestRunCaseSink(testcaseId, id);
if (testCaseSink == null) {
throw EntityNotFoundException.byId(Long.toString(id));
}
return WSUtils.respondEntity(testCaseSink, OK);
}
@GET
@Path("/topologies/{topologyId}/testcases/{testCaseId}/sinks/topologysink/{sinkId}")
public Response getTestRunCaseSinkByTopologySink(@PathParam("topologyId") Long topologyId,
@PathParam("testCaseId") Long testCaseId,
@PathParam("sinkId") Long sinkId) {
TopologyTestRunCaseSink testCaseSink = catalogService.getTopologyTestRunCaseSinkBySinkId(testCaseId, sinkId);
if (testCaseSink == null) {
throw EntityNotFoundException.byId("test case id: " + testCaseId + " , topology source id: " + sinkId);
}
return WSUtils.respondEntity(testCaseSink, OK);
}
@GET
@Path("/topologies/{topologyId}/testcases/{testCaseId}/sinks")
public Response listTestRunCaseSink(@PathParam("topologyId") Long topologyId,
@PathParam("testCaseId") Long testCaseId) {
Collection<TopologyTestRunCaseSink> sources = catalogService.listTopologyTestRunCaseSink(topologyId, testCaseId);
if (sources == null) {
throw EntityNotFoundException.byFilter("topologyId: " + topologyId + " / testCaseId: " + testCaseId);
}
return WSUtils.respondEntities(sources, OK);
}
private static class SimplifiedTopologyTestRunHistory {
private Long id;
private Long topologyId;
private Long versionId;
private Boolean finished = false;
private Boolean success = false;
private Boolean matched = false;
private Long startTime;
private Long finishTime;
private Long timestamp;
SimplifiedTopologyTestRunHistory(TopologyTestRunHistory history) {
id = history.getId();
topologyId = history.getTopologyId();
versionId = history.getVersionId();
finished = history.getFinished();
success = history.getSuccess();
matched = history.getMatched();
startTime = history.getStartTime();
finishTime = history.getFinishTime();
timestamp = history.getTimestamp();
}
public Long getId() {
return id;
}
public Long getTopologyId() {
return topologyId;
}
public Long getVersionId() {
return versionId;
}
public Boolean getFinished() {
return finished;
}
public Boolean getSuccess() {
return success;
}
public Boolean getMatched() {
return matched;
}
public Long getStartTime() {
return startTime;
}
public Long getFinishTime() {
return finishTime;
}
public Long getTimestamp() {
return timestamp;
}
}
}
|
Java
|
package org.jruby.ext.ffi.jna;
import java.util.ArrayList;
import org.jruby.runtime.ThreadContext;
/**
* An invocation session.
* This provides post-invoke cleanup.
*/
final class Invocation {
private final ThreadContext context;
private ArrayList<Runnable> postInvokeList;
Invocation(ThreadContext context) {
this.context = context;
}
void finish() {
if (postInvokeList != null) {
for (Runnable r : postInvokeList) {
r.run();
}
}
}
void addPostInvoke(Runnable postInvoke) {
if (postInvokeList == null) {
postInvokeList = new ArrayList<Runnable>();
}
postInvokeList.add(postInvoke);
}
ThreadContext getThreadContext() {
return context;
}
}
|
Java
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_75) on Tue May 19 17:12:39 PDT 2015 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>org.apache.hadoop.registry.client.impl.zk (Apache Hadoop Main 2.6.0-cdh5.4.2 API)</title>
<meta name="date" content="2015-05-19">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
</head>
<body>
<h1 class="bar"><a href="../../../../../../../org/apache/hadoop/registry/client/impl/zk/package-summary.html" target="classFrame">org.apache.hadoop.registry.client.impl.zk</a></h1>
<div class="indexContainer">
<h2 title="Interfaces">Interfaces</h2>
<ul title="Interfaces">
<li><a href="RegistryBindingSource.html" title="interface in org.apache.hadoop.registry.client.impl.zk" target="classFrame"><i>RegistryBindingSource</i></a></li>
</ul>
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="BindingInformation.html" title="class in org.apache.hadoop.registry.client.impl.zk" target="classFrame">BindingInformation</a></li>
<li><a href="RegistryOperationsService.html" title="class in org.apache.hadoop.registry.client.impl.zk" target="classFrame">RegistryOperationsService</a></li>
</ul>
</div>
</body>
</html>
|
Java
|
# Zigara tenuis (Salisb.) Raf. SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
package lists
class OrderedTest(val value: String) extends Ordered[OrderedTest] {
override def compare(that: OrderedTest): Int = {
value.compareToIgnoreCase(that.value)
}
override def toString = value
}
object Test extends App {
val test1 = List(0, 1, 2, 3, 4, 5, 6, 7)
val test1concat = List(8, 9, 10)
val test2 = List("Foo", "Bar")
val test2concat = List("Baz")
val test3 = List(new OrderedTest("a"), new OrderedTest("C"), new OrderedTest("B"))
println(length(test1))
println(concat(test1, test1concat))
println(length(test2))
println(concat(test2, test2concat))
println(last(test1))
println(init(test1))
println(tail(test2concat))
println(head(test1))
println(reverse(concat(test1, test1concat)))
println(reverse(reverse(test1)) == test1)
println(take(test1, 3))
println(drop(test1, 3))
println(apply(test1, 3))
println(splitAt(test1, length(test1) / 2))
println(flatten(List(test1, test1concat)))
println(flatten(List(test2, test2concat)))
val normalOrderMerge = mergeSort[Int](_ < _)_
val normalOrderInsert = insertSort[Int](_ < _)_
val reverseOrderMerge = mergeSort[Int](_ > _)_
val reverseOrderInsert = insertSort[Int](_ > _)_
val stringSortMerge = mergeSort[String](_ < _)_
val stringSortInsert = insertSort[String](_ < _)_
println(stringSortMerge(concat(test2concat, test2)))
println(stringSortInsert(concat(test2concat, test2)))
println(normalOrderMerge(concat(reverse(test1), test1concat)))
println(normalOrderInsert(concat(reverse(test1), test1concat)))
println(reverseOrderMerge(test1))
println(reverseOrderInsert(test1))
println(normalOrderMerge(reverseOrderMerge(test1)))
println(normalOrderInsert(reverseOrderInsert(test1)))
println(orderedMergeSort(test3))
}
|
Java
|
package org.onetwo.ext.security.utils;
import java.util.Collection;
import org.onetwo.common.web.userdetails.UserDetail;
import org.onetwo.common.web.userdetails.UserRoot;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
@SuppressWarnings("serial")
public class LoginUserDetails extends User implements UserDetail, /*SsoTokenable,*/ UserRoot {
final private long userId;
// private String token;
private String nickname;
private String avatar;
public LoginUserDetails(long userId, String username, String password,
Collection<? extends GrantedAuthority> authorities) {
super(username, password, authorities);
this.userId = userId;
}
public long getUserId() {
return userId;
}
@Override
public String getUserName() {
return getUsername();
}
@Override
public boolean isSystemRootUser() {
return userId==ROOT_USER_ID;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
/*public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}*/
}
|
Java
|
/*
<samplecode>
<abstract>
A DSPKernel subclass implementing the realtime signal processing portion of the FilterDemo audio unit.
</abstract>
</samplecode>
*/
#ifndef FilterDSPKernel_hpp
#define FilterDSPKernel_hpp
#import "DSPKernel.hpp"
#import "ParameterRamper.hpp"
#import <vector>
static inline float convertBadValuesToZero(float x) {
/*
Eliminate denormals, not-a-numbers, and infinities.
Denormals will fail the first test (absx > 1e-15), infinities will fail
the second test (absx < 1e15), and NaNs will fail both tests. Zero will
also fail both tests, but since it will get set to zero that is OK.
*/
float absx = fabs(x);
if (absx > 1e-15 && absx < 1e15) {
return x;
}
return 0.0;
}
enum {
FilterParamCutoff = 0,
FilterParamResonance = 1
};
static inline double squared(double x) {
return x * x;
}
/*
FilterDSPKernel
Performs our filter signal processing.
As a non-ObjC class, this is safe to use from render thread.
*/
class FilterDSPKernel : public DSPKernel {
public:
// MARK: Types
struct FilterState {
float x1 = 0.0;
float x2 = 0.0;
float y1 = 0.0;
float y2 = 0.0;
void clear() {
x1 = 0.0;
x2 = 0.0;
y1 = 0.0;
y2 = 0.0;
}
void convertBadStateValuesToZero() {
/*
These filters work by feedback. If an infinity or NaN should come
into the filter input, the feedback variables can become infinity
or NaN which will cause the filter to stop operating. This function
clears out any bad numbers in the feedback variables.
*/
x1 = convertBadValuesToZero(x1);
x2 = convertBadValuesToZero(x2);
y1 = convertBadValuesToZero(y1);
y2 = convertBadValuesToZero(y2);
}
};
struct BiquadCoefficients {
float a1 = 0.0;
float a2 = 0.0;
float b0 = 0.0;
float b1 = 0.0;
float b2 = 0.0;
void calculateLopassParams(double frequency, double resonance) {
/*
The transcendental function calls here could be replaced with
interpolated table lookups or other approximations.
*/
// Convert from decibels to linear.
double r = pow(10.0, 0.05 * -resonance);
double k = 0.5 * r * sin(M_PI * frequency);
double c1 = (1.0 - k) / (1.0 + k);
double c2 = (1.0 + c1) * cos(M_PI * frequency);
double c3 = (1.0 + c1 - c2) * 0.25;
b0 = float(c3);
b1 = float(2.0 * c3);
b2 = float(c3);
a1 = float(-c2);
a2 = float(c1);
}
// Arguments in Hertz.
double magnitudeForFrequency( double inFreq) {
// Cast to Double.
double _b0 = double(b0);
double _b1 = double(b1);
double _b2 = double(b2);
double _a1 = double(a1);
double _a2 = double(a2);
// Frequency on unit circle in z-plane.
double zReal = cos(M_PI * inFreq);
double zImaginary = sin(M_PI * inFreq);
// Zeros response.
double numeratorReal = (_b0 * (squared(zReal) - squared(zImaginary))) + (_b1 * zReal) + _b2;
double numeratorImaginary = (2.0 * _b0 * zReal * zImaginary) + (_b1 * zImaginary);
double numeratorMagnitude = sqrt(squared(numeratorReal) + squared(numeratorImaginary));
// Poles response.
double denominatorReal = squared(zReal) - squared(zImaginary) + (_a1 * zReal) + _a2;
double denominatorImaginary = (2.0 * zReal * zImaginary) + (_a1 * zImaginary);
double denominatorMagnitude = sqrt(squared(denominatorReal) + squared(denominatorImaginary));
// Total response.
double response = numeratorMagnitude / denominatorMagnitude;
return response;
}
};
// MARK: Member Functions
FilterDSPKernel() {}
void init(int channelCount, double inSampleRate) {
channelStates.resize(channelCount);
sampleRate = float(inSampleRate);
nyquist = 0.5 * sampleRate;
inverseNyquist = 1.0 / nyquist;
dezipperRampDuration = (AUAudioFrameCount)floor(0.02 * sampleRate);
cutoffRamper.init();
resonanceRamper.init();
}
void reset() {
cutoffRamper.reset();
resonanceRamper.reset();
for (FilterState& state : channelStates) {
state.clear();
}
}
void setParameter(AUParameterAddress address, AUValue value) {
switch (address) {
case FilterParamCutoff:
//cutoffRamper.setUIValue(clamp(value * inverseNyquist, 0.0f, 0.99f));
cutoffRamper.setUIValue(clamp(value * inverseNyquist, 0.0005444f, 0.9070295f));
break;
case FilterParamResonance:
resonanceRamper.setUIValue(clamp(value, -20.0f, 20.0f));
break;
}
}
AUValue getParameter(AUParameterAddress address) {
switch (address) {
case FilterParamCutoff:
// Return the goal. It is not thread safe to return the ramping value.
//return (cutoffRamper.getUIValue() * nyquist);
return roundf((cutoffRamper.getUIValue() * nyquist) * 100) / 100;
case FilterParamResonance:
return resonanceRamper.getUIValue();
default: return 12.0f * inverseNyquist;
}
}
void startRamp(AUParameterAddress address, AUValue value, AUAudioFrameCount duration) override {
switch (address) {
case FilterParamCutoff:
cutoffRamper.startRamp(clamp(value * inverseNyquist, 12.0f * inverseNyquist, 0.99f), duration);
break;
case FilterParamResonance:
resonanceRamper.startRamp(clamp(value, -20.0f, 20.0f), duration);
break;
}
}
void setBuffers(AudioBufferList* inBufferList, AudioBufferList* outBufferList) {
inBufferListPtr = inBufferList;
outBufferListPtr = outBufferList;
}
void process(AUAudioFrameCount frameCount, AUAudioFrameCount bufferOffset) override {
int channelCount = int(channelStates.size());
cutoffRamper.dezipperCheck(dezipperRampDuration);
resonanceRamper.dezipperCheck(dezipperRampDuration);
// For each sample.
for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) {
/*
The filter coefficients are updated every sample! This is very
expensive. You probably want to do things differently.
*/
double cutoff = double(cutoffRamper.getAndStep());
double resonance = double(resonanceRamper.getAndStep());
coeffs.calculateLopassParams(cutoff, resonance);
int frameOffset = int(frameIndex + bufferOffset);
for (int channel = 0; channel < channelCount; ++channel) {
FilterState& state = channelStates[channel];
float* in = (float*)inBufferListPtr->mBuffers[channel].mData + frameOffset;
float* out = (float*)outBufferListPtr->mBuffers[channel].mData + frameOffset;
float x0 = *in;
float y0 = (coeffs.b0 * x0) + (coeffs.b1 * state.x1) + (coeffs.b2 * state.x2) - (coeffs.a1 * state.y1) - (coeffs.a2 * state.y2);
*out = y0;
state.x2 = state.x1;
state.x1 = x0;
state.y2 = state.y1;
state.y1 = y0;
}
}
// Squelch any blowups once per cycle.
for (int channel = 0; channel < channelCount; ++channel) {
channelStates[channel].convertBadStateValuesToZero();
}
}
// MARK: Member Variables
private:
std::vector<FilterState> channelStates;
BiquadCoefficients coeffs;
float sampleRate = 44100.0;
float nyquist = 0.5 * sampleRate;
float inverseNyquist = 1.0 / nyquist;
AUAudioFrameCount dezipperRampDuration;
AudioBufferList* inBufferListPtr = nullptr;
AudioBufferList* outBufferListPtr = nullptr;
public:
// Parameters.
ParameterRamper cutoffRamper = 400.0 / 44100.0;
ParameterRamper resonanceRamper = 20.0;
};
#endif /* FilterDSPKernel_hpp */
|
Java
|
// import { Domain } from '../Domain';
// import { GetDomain } from './GetDomain';
//
// /**
// * Find domain from object or type
// */
// export function FindDomain(target: Function | object): Domain | undefined {
// let prototype;
// if (typeof target === 'function') {
// prototype = target.prototype;
// } else {
// prototype = target;
// }
//
// while (prototype) {
// const domain = GetDomain(prototype);
// if (domain) {
// // console.log('FOUND');
// return domain;
// }
// // console.log('NOT FOUND!!!');
// prototype = Reflect.getPrototypeOf(prototype);
// }
// return;
// }
|
Java
|
/*
* Copyright (C) 2015 P100 OG, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.shiftconnects.android.auth.example.util;
import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import retrofit.converter.ConversionException;
import retrofit.converter.Converter;
import retrofit.mime.MimeUtil;
import retrofit.mime.TypedInput;
import retrofit.mime.TypedOutput;
/**
* A {@link Converter} which uses GSON for serialization and deserialization of entities.
*
* @author Jake Wharton (jw@squareup.com)
*/
public class GsonConverter implements Converter {
private final Gson gson;
private String charset;
/**
* Create an instance using the supplied {@link Gson} object for conversion. Encoding to JSON and
* decoding from JSON (when no charset is specified by a header) will use UTF-8.
*/
public GsonConverter(Gson gson) {
this(gson, "UTF-8");
}
/**
* Create an instance using the supplied {@link Gson} object for conversion. Encoding to JSON and
* decoding from JSON (when no charset is specified by a header) will use the specified charset.
*/
public GsonConverter(Gson gson, String charset) {
this.gson = gson;
this.charset = charset;
}
@Override public Object fromBody(TypedInput body, Type type) throws ConversionException {
String charset = this.charset;
if (body.mimeType() != null) {
charset = MimeUtil.parseCharset(body.mimeType(), charset);
}
InputStreamReader isr = null;
try {
isr = new InputStreamReader(body.in(), charset);
return gson.fromJson(isr, type);
} catch (IOException e) {
throw new ConversionException(e);
} catch (JsonParseException e) {
throw new ConversionException(e);
} finally {
if (isr != null) {
try {
isr.close();
} catch (IOException ignored) {
}
}
}
}
@Override public TypedOutput toBody(Object object) {
try {
return new JsonTypedOutput(gson.toJson(object).getBytes(charset), charset);
} catch (UnsupportedEncodingException e) {
throw new AssertionError(e);
}
}
private static class JsonTypedOutput implements TypedOutput {
private final byte[] jsonBytes;
private final String mimeType;
JsonTypedOutput(byte[] jsonBytes, String encode) {
this.jsonBytes = jsonBytes;
this.mimeType = "application/json; charset=" + encode;
}
@Override public String fileName() {
return null;
}
@Override public String mimeType() {
return mimeType;
}
@Override public long length() {
return jsonBytes.length;
}
@Override public void writeTo(OutputStream out) throws IOException {
out.write(jsonBytes);
}
}
}
|
Java
|
package acceptance;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import utils.CommandStatus;
import utils.TemporaryDigdagServer;
import java.nio.file.Path;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static utils.TestUtils.copyResource;
import static utils.TestUtils.main;
//
// This file doesn't contain normal case.
// It defined in another test.
//
public class ValidateProjectIT
{
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Rule
public TemporaryDigdagServer server = TemporaryDigdagServer.builder()
.build();
private Path config;
private Path projectDir;
@Before
public void setUp()
throws Exception
{
projectDir = folder.getRoot().toPath().resolve("foobar");
config = folder.newFile().toPath();
}
@Test
public void uploadInvalidTaskProject()
throws Exception
{
// Create new project
CommandStatus initStatus = main("init",
"-c", config.toString(),
projectDir.toString());
assertThat(initStatus.code(), is(0));
copyResource("acceptance/error_task/invalid_at_group.dig", projectDir.resolve("invalid_at_group.dig"));
// Push the project
CommandStatus pushStatus = main(
"push",
"--project", projectDir.toString(),
"foobar",
"-c", config.toString(),
"-e", server.endpoint());
assertThat(pushStatus.code(), is(1));
assertThat(pushStatus.errUtf8(), containsString("A task can't have more than one operator"));
}
@Test
public void uploadInvalidScheduleProject()
throws Exception
{
// Create new project
CommandStatus initStatus = main("init",
"-c", config.toString(),
projectDir.toString());
assertThat(initStatus.code(), is(0));
copyResource("acceptance/schedule/invalid_schedule.dig", projectDir.resolve("invalid_schedule.dig"));
// Push the project
CommandStatus pushStatus = main(
"push",
"--project", projectDir.toString(),
"foobar",
"-c", config.toString(),
"-e", server.endpoint());
assertThat(pushStatus.code(), is(1));
assertThat(pushStatus.errUtf8(), containsString("scheduler requires mm:ss format"));
}
}
|
Java
|
/*
* Copyright Strimzi authors.
* License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).
*/
package io.strimzi.api.kafka.model.connect.build;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import io.strimzi.api.kafka.model.UnknownPropertyPreserving;
import io.strimzi.crdgenerator.annotations.Description;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* Abstract baseclass for different representations of connect build outputs, discriminated by {@link #getType() type}.
*/
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.EXISTING_PROPERTY,
property = "type"
)
@JsonSubTypes(
{
@JsonSubTypes.Type(value = DockerOutput.class, name = Output.TYPE_DOCKER),
@JsonSubTypes.Type(value = ImageStreamOutput.class, name = Output.TYPE_IMAGESTREAM)
}
)
@JsonInclude(JsonInclude.Include.NON_NULL)
@EqualsAndHashCode
public abstract class Output implements UnknownPropertyPreserving, Serializable {
private static final long serialVersionUID = 1L;
public static final String TYPE_DOCKER = "docker";
public static final String TYPE_IMAGESTREAM = "imagestream";
private String image;
private Map<String, Object> additionalProperties = new HashMap<>(0);
@Description("Output type. " +
"Must be either `docker` for pushing the newly build image to Docker compatible registry or `imagestream` for pushing the image to OpenShift ImageStream. " +
"Required.")
public abstract String getType();
@Description("The name of the image which will be built. " +
"Required")
@JsonProperty(required = true)
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
@Override
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@Override
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
|
Java
|
/**
*
*/
package com.transcend.rds.worker;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.springframework.transaction.annotation.Transactional;
import com.msi.tough.cf.json.DatabagParameter;
import com.msi.tough.core.Appctx;
import com.msi.tough.core.HibernateUtil;
import com.msi.tough.core.JsonUtil;
import com.msi.tough.model.AccountBean;
import com.msi.tough.model.rds.RdsDbinstance;
import com.msi.tough.model.rds.RdsDbparameterGroup;
import com.msi.tough.model.rds.RdsParameter;
import com.msi.tough.query.ErrorResponse;
import com.msi.tough.query.QueryFaults;
import com.msi.tough.query.ServiceRequestContext;
import com.msi.tough.rds.ValidationManager;
import com.msi.tough.rds.json.RDSConfigDatabagItem;
import com.msi.tough.rds.json.RDSDatabag;
import com.msi.tough.rds.json.RDSParameterGroupDatabagItem;
import com.msi.tough.utils.AccountUtil;
import com.msi.tough.utils.ChefUtil;
import com.msi.tough.utils.ConfigurationUtil;
import com.msi.tough.utils.Constants;
import com.msi.tough.utils.RDSQueryFaults;
import com.msi.tough.utils.rds.InstanceEntity;
import com.msi.tough.utils.rds.ParameterGroupEntity;
import com.msi.tough.utils.rds.RDSUtilities;
import com.msi.tough.workflow.core.AbstractWorker;
import com.transcend.rds.message.ModifyDBParameterGroupActionMessage.ModifyDBParameterGroupActionRequestMessage;
import com.transcend.rds.message.ModifyDBParameterGroupActionMessage.ModifyDBParameterGroupActionResultMessage;
import com.transcend.rds.message.RDSMessage.Parameter;
/**
* @author tdhite
*/
public class ModifyDBParameterGroupActionWorker extends
AbstractWorker<ModifyDBParameterGroupActionRequestMessage, ModifyDBParameterGroupActionResultMessage> {
private final static Logger logger = Appctx
.getLogger(ModifyDBParameterGroupActionWorker.class.getName());
/**
* We need a local copy of this doWork to provide the transactional
* annotation. Transaction management is handled by the annotation, which
* can only be on a concrete class.
* @param req
* @return
* @throws Exception
*/
@Transactional
public ModifyDBParameterGroupActionResultMessage doWork(
ModifyDBParameterGroupActionRequestMessage req) throws Exception {
logger.debug("Performing work for ModifyDBParameterGroupAction.");
return super.doWork(req, getSession());
}
/**
* modifyDBParameterGroup ************************************************
* This Operation modifies the parameters associated with the named
* DBParameterGroup. It essentially adds/updates parameters associated with
* a DBParameterGroup If parameter exists then update if parameter doesn't
* exist then insert Request: DBParameterGroupName(R) List of Parameter
* records(R) Parameters: List of up to 20 parameter records Response:
* DBParameterGroup Exceptions: DBParameterGroupNotFound
* InvalidDBParameterGroupState Processing 1. Confirm that ParamaterGroup
* exists and is in the appropriate state 2. Update the Parameter records by
* inserting or updating new parameter 3. Return response
*/
@Override
protected ModifyDBParameterGroupActionResultMessage doWork0(ModifyDBParameterGroupActionRequestMessage req,
ServiceRequestContext context) throws Exception {
logger.debug("ModifyDBParameterGroup action is called.");
final Session sess = HibernateUtil.newSession();
final AccountBean ac = context.getAccountBean();
final ModifyDBParameterGroupActionResultMessage.Builder resp = ModifyDBParameterGroupActionResultMessage.newBuilder();
try {
sess.beginTransaction();
final long userId = ac.getId();
final String grpName = ValidationManager.validateIdentifier(
req.getDbParameterGroupName(), 255, true);
final List<Parameter> pList = req.getParametersList();
final int pListLen = pList.size();
logger.info("ModifyDBParameterGroup: " + " UserID = " + userId
+ " ParameterGroupName = " + grpName
+ " Total Number of Listed Parameters = " + pListLen);
if (grpName.equals("default.mysql5.5")) {
throw RDSQueryFaults
.InvalidClientTokenId("You do not have privilege to modify default DBParameterGroup.");
}
// check that DBParameterGroup exists
final RdsDbparameterGroup pGrpRec = ParameterGroupEntity
.getParameterGroup(sess, grpName, ac.getId());
if (pGrpRec == null) {
throw RDSQueryFaults.DBParameterGroupNotFound();
}
final Collection<RdsDbinstance> dbInstances = InstanceEntity
.selectDBInstancesByParameterGroup(sess, grpName, -1, ac);
// make sure that all DBInstances using this DBParameterGroup are in
// available state
for (final RdsDbinstance dbinstance : dbInstances) {
if (!dbinstance.getDbinstanceStatus().equals(
RDSUtilities.STATUS_AVAILABLE)) {
throw RDSQueryFaults
.InvalidDBParameterGroupState("Currently there are DBInstance(s) that use this DBParameterGroup and it"
+ " is not in available state.");
}
}
// reset the parameters in the DB
List<RdsParameter> forRebootPending = new LinkedList<RdsParameter>();
final String paramGrpFamily = pGrpRec.getDbparameterGroupFamily();
final AccountBean sac = AccountUtil.readAccount(sess, 1L);
for (final Parameter p : pList) {
final RdsParameter target = ParameterGroupEntity.getParameter(
sess, grpName, p.getParameterName(), userId);
if (target == null) {
throw RDSQueryFaults.InvalidParameterValue(p
.getParameterName() + " parameter does not exist.");
}
logger.debug("Current target parameter: " + target.toString());
if (!target.getIsModifiable()) {
throw RDSQueryFaults.InvalidParameterValue(p
.getParameterName()
+ " is not modifiable parameter.");
}
// TODO validate p.getParameterValue along with
// p.getParameterName to ensure the value is allowed
else if (p.getApplyMethod().equals(
RDSUtilities.PARM_APPMETHOD_IMMEDIATE)) {
if (target.getApplyType().equals(
RDSUtilities.PARM_APPTYPE_STATIC)) {
throw QueryFaults
.InvalidParameterCombination(target
.getParameterName()
+ " is not dynamic. You can only"
+ " use \"pending-reboot\" as valid ApplyMethod for this parameter.");
}
target.setParameterValue(p.getParameterValue());
target.setSource(Constants.USER);
sess.save(target);
} else if (p.getApplyMethod().equals(
RDSUtilities.PARM_APPMETHOD_PENDING)) {
final RdsParameter temp = new RdsParameter();
temp.setParameterName(p.getParameterName());
temp.setApplyMethod(p.getApplyMethod());
temp.setParameterValue(p.getParameterValue());
forRebootPending.add(temp);
}
}
// Delete and regenerate the Databag
logger.debug("There are " + dbInstances.size()
+ " databags to modify.");
for (final RdsDbinstance instance : dbInstances) {
logger.debug("Currently updating the databag for DBInstance "
+ instance.getDbinstanceId());
final String databagName = "rds-" + ac.getId() + "-"
+ instance.getDbinstanceId();
logger.debug("Deleting the databag " + databagName);
ChefUtil.deleteDatabagItem(databagName, "config");
final String postWaitUrl = (String) ConfigurationUtil
.getConfiguration(Arrays.asList(new String[] {
"TRANSCEND_URL", instance.getAvailabilityZone() }));
final String servletUrl = (String) ConfigurationUtil
.getConfiguration(Arrays.asList(new String[] {
"SERVLET_URL", instance.getAvailabilityZone() }));
final RDSConfigDatabagItem configDataBagItem = new RDSConfigDatabagItem(
"config", instance.getAllocatedStorage().toString(),
instance.getMasterUsername(),
instance.getMasterUserPassword(),
instance.getAutoMinorVersionUpgrade(),
instance.getEngine(), instance.getEngineVersion(),
instance.getDbName(), instance
.getBackupRetentionPeriod().toString(),
instance.getPreferredBackupWindow(),
instance.getPreferredMaintenanceWindow(), instance
.getPort().toString(), postWaitUrl, servletUrl,
instance.getDbinstanceId(), "rds." + ac.getId() + "."
+ instance.getDbinstanceId(), ac.getId(), instance.getDbinstanceClass(), "false");
final RDSParameterGroupDatabagItem parameterGroupDatabagItem = new RDSParameterGroupDatabagItem(
"parameters", pGrpRec);
parameterGroupDatabagItem.getParameters().remove("read_only");
parameterGroupDatabagItem.getParameters().put(
"read_only",
DatabagParameter.factory("boolean",
"" + instance.getRead_only(), true, "dynamic"));
parameterGroupDatabagItem.getParameters().remove("port");
parameterGroupDatabagItem.getParameters().put(
"port",
DatabagParameter.factory("integer",
"" + instance.getPort(), false, "static"));
final RDSDatabag bag = new RDSDatabag(configDataBagItem,
parameterGroupDatabagItem);
logger.debug("Databag: "
+ JsonUtil.toJsonPrettyPrintString(bag));
logger.debug("Regenerating the databag " + databagName);
ChefUtil.createDatabagItem(databagName, "config", bag.toJson());
}
if (forRebootPending != null && forRebootPending.size() > 0) {
// forRebootPending is now a list of static parameters and
// dynamic parameters with pending-reboot ApplyMethod
forRebootPending = ParameterGroupEntity
.modifyParamGroupWithPartialList(sess, pGrpRec,
forRebootPending, userId);
// code below may need to be rewritten for better performance;
// Hibernate may be useful to improve the snippet below
for (final RdsDbinstance instance : dbInstances) {
final List<RdsParameter> alreadyPending = instance
.getPendingRebootParameters();
if (alreadyPending == null || alreadyPending.size() == 0) {
instance.setPendingRebootParameters(forRebootPending);
// instance.setDbinstanceStatus(RDSUtilities.STATUS_MODIFYING);
sess.save(instance);
} else {
for (final RdsParameter newParam : forRebootPending) {
boolean found = false;
int i = 0;
while (!found && i < alreadyPending.size()) {
if (alreadyPending.get(i).getParameterName()
.equals(newParam.getParameterName())) {
alreadyPending.get(i).setParameterValue(
newParam.getParameterValue());
found = true;
}
++i;
}
if (!found) {
alreadyPending.add(newParam);
}
}
}
}
}
// build response document - returns DBParameterGroupName
resp.setDbParameterGroupName(grpName);
logger.debug("Committing all the changes...");
sess.getTransaction().commit();
} catch (final ErrorResponse rde) {
sess.getTransaction().rollback();
throw rde;
} catch (final Exception e) {
e.printStackTrace();
sess.getTransaction().rollback();
final String msg = "CreateInstance: Class: " + e.getClass()
+ "Msg:" + e.getMessage();
logger.error(msg);
throw RDSQueryFaults.InternalFailure();
} finally {
sess.close();
}
return resp.buildPartial();
}
}
|
Java
|
/*
* Copyright (C) 2014 Johannes Donath <johannesd@evil-co.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.evilco.emulator.extension.chip8;
import org.evilco.emulator.ui_old.extension.AbstractEmulatorExtension;
import org.evilco.emulator.ui_old.extension.InterfaceExtensionManager;
/**
* @author Johannes Donath <johannesd@evil-co.com>
* @copyright Copyright (C) 2014 Evil-Co <http://www.evil-co.com>
*/
public class Chip8Extension extends AbstractEmulatorExtension {
/**
* {@inheritDoc}
*/
@Override
public String getIdentifier () {
return "org.evilco.emulator.extension.chip8";
}
/**
* {@inheritDoc}
*/
@Override
public void onEnable (InterfaceExtensionManager extensionManager) {
super.onEnable (extensionManager);
extensionManager.registerExtension (this, "c8", Chip8Emulator.class);
}
}
|
Java
|
class PagosController < ApplicationController
before_action :set_pago, only: [:show, :edit, :update, :destroy]
# GET /pagos
# GET /pagos.json
def index
@pagos = Pago.all
end
# GET /pagos/1
# GET /pagos/1.json
def show
end
# GET /pagos/new
def new
@pago = Pago.new
end
# GET /pagos/1/edit
def edit
end
# POST /pagos
# POST /pagos.json
def create
@pago = Pago.new(pago_params)
respond_to do |format|
if @pago.save
format.html { redirect_to @pago, notice: 'Pago añadido' }
format.json { render :show, status: :created, location: @pago }
else
format.html { render :new }
format.json { render json: @pago.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /pagos/1
# PATCH/PUT /pagos/1.json
def update
respond_to do |format|
if @pago.update(pago_params)
format.html { redirect_to @pago, notice: 'Pago actualizado' }
format.json { render :show, status: :ok, location: @pago }
else
format.html { render :edit }
format.json { render json: @pago.errors, status: :unprocessable_entity }
end
end
end
# DELETE /pagos/1
# DELETE /pagos/1.json
def destroy
@pago.destroy
respond_to do |format|
format.html { redirect_to pagos_url, notice: 'Pago eliminado' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_pago
@pago = Pago.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def pago_params
params.require(:pago).permit(:cliente_id,:dominio_fecha_expiracion, :pagado, :fecha_pago, :ano,:dominio_nombre ,:dominio_anual ,:hosting_mes ,:hosting_anual, :total, :comentarios)
end
end
|
Java
|
/** Automatically generated file. DO NOT MODIFY */
package com.example.android_servicetest;
public final class BuildConfig {
public final static boolean DEBUG = true;
}
|
Java
|
To set your browser's language preferences,
follow the instructions in
[Setting language preferences in a browser](https://www.w3.org/International/questions/qa-lang-priorities).
|
Java
|
/*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include "inter_vn_stats.h"
#include <oper/interface.h>
#include <oper/mirror_table.h>
using namespace std;
InterVnStatsCollector::VnStatsSet *InterVnStatsCollector::Find(string vn) {
VnStatsMap::iterator it = inter_vn_stats_.find(vn);
if (it != inter_vn_stats_.end()) {
return it->second;
}
return NULL;
}
void InterVnStatsCollector::PrintAll() {
VnStatsMap::iterator it = inter_vn_stats_.begin();
while(it != inter_vn_stats_.end()) {
PrintVn(it->first);
it++;
}
}
void InterVnStatsCollector::PrintVn(string vn) {
VnStatsSet *stats_set;
VnStats *stats;
LOG(DEBUG, "...........Stats for Vn " << vn);
VnStatsMap::iterator it = inter_vn_stats_.find(vn);
if (it != inter_vn_stats_.end()) {
stats_set = it->second;
/* Remove all the elements of map entry value which is a set */
VnStatsSet::iterator stats_it = stats_set->begin();
while(stats_it != stats_set->end()) {
stats = *stats_it;
stats_it++;
LOG(DEBUG, " Other-VN " << stats->dst_vn);
LOG(DEBUG, " in_pkts " << stats->in_pkts << " in_bytes " << stats->in_bytes);
LOG(DEBUG, " out_pkts " << stats->out_pkts << " out_bytes " << stats->out_bytes);
}
}
}
void InterVnStatsCollector::Remove(string vn) {
VnStatsSet *stats_set;
VnStats *stats;
VnStatsMap::iterator it = inter_vn_stats_.find(vn);
if (it != inter_vn_stats_.end()) {
stats_set = it->second;
/* Remove the entry from the inter_vn_stats_ map */
inter_vn_stats_.erase(it);
/* Remove all the elements of map entry value which is a set */
VnStatsSet::iterator stats_it = stats_set->begin();
VnStatsSet::iterator del_it;
while(stats_it != stats_set->end()) {
stats = *stats_it;
delete stats;
del_it = stats_it;
stats_it++;
stats_set->erase(del_it);
}
delete stats_set;
}
}
void InterVnStatsCollector::UpdateVnStats(FlowEntry *fe, uint64_t bytes,
uint64_t pkts) {
string src_vn = fe->data.source_vn, dst_vn = fe->data.dest_vn;
if (!fe->data.source_vn.length())
src_vn = *FlowHandler::UnknownVn();
if (!fe->data.dest_vn.length())
dst_vn = *FlowHandler::UnknownVn();
if (fe->local_flow) {
VnStatsUpdateInternal(src_vn, dst_vn, bytes, pkts, true);
VnStatsUpdateInternal(dst_vn, src_vn, bytes, pkts, false);
} else {
if (fe->data.ingress) {
VnStatsUpdateInternal(src_vn, dst_vn, bytes, pkts, true);
} else {
VnStatsUpdateInternal(dst_vn, src_vn, bytes, pkts, false);
}
}
//PrintAll();
}
void InterVnStatsCollector::VnStatsUpdateInternal(string src_vn, string dst_vn,
uint64_t bytes, uint64_t pkts,
bool outgoing) {
VnStatsSet *stats_set;
VnStats *stats;
VnStatsMap::iterator it = inter_vn_stats_.find(src_vn);
if (it == inter_vn_stats_.end()) {
stats = new VnStats(dst_vn, bytes, pkts, outgoing);
stats_set = new VnStatsSet;
stats_set->insert(stats);
inter_vn_stats_.insert(make_pair(src_vn, stats_set));
} else {
stats_set = it->second;
VnStats key(dst_vn, 0, 0, false);
VnStatsSet::iterator stats_it = stats_set->find(&key);
if (stats_it == stats_set->end()) {
stats = new VnStats(dst_vn, bytes, pkts, outgoing);
stats_set->insert(stats);
} else {
stats = *stats_it;
if (outgoing) {
stats->out_bytes += bytes;
stats->out_pkts += pkts;
} else {
stats->in_bytes += bytes;
stats->in_pkts += pkts;
}
}
}
}
|
Java
|
package com.fordprog.matrix.interpreter.type;
public enum Type {
RATIONAL,
MATRIX,
FUNCTION,
VOID
}
|
Java
|
/*
* Copyright 2016 peter.
*
* 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 onl.area51.filesystem.io;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Map;
import org.kohsuke.MetaInfServices;
/**
* A flat FileSystem which locally matches it's structure
*/
@MetaInfServices(FileSystemIO.class)
public class Flat
extends LocalFileSystemIO
{
public Flat( Path basePath,
Map<String, ?> env )
{
super( basePath, env );
}
@Override
protected String getPath( char[] path )
throws IOException
{
return String.valueOf( path );
}
}
|
Java
|
/*
* @author Flavio Keller
*
* Copyright 2014 University of Zurich
*
* 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.signalcollect.sna.constants;
/**
* Enumeration for the different classes that can occur
* when running a SNA method algorithm
*/
public enum SNAClassNames {
DEGREE("Degree"), PAGERANK("PageRank"), CLOSENESS("Closeness"), BETWEENNESS("Betweenness"), PATH("Path"), LOCALCLUSTERCOEFFICIENT(
"LocalClusterCoefficient"), TRIADCENSUS("Triad Census"), LABELPROPAGATION(
"Label Propagation") ;
private final String className;
SNAClassNames(String name) {
this.className = name;
}
}
|
Java
|
/***************************************************************************
* Copyright 2015 Kieker Project (http://kieker-monitoring.net)
*
* 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 kieker.test.common.junit.record.flow.trace.concurrency.monitor;
import java.nio.ByteBuffer;
import org.junit.Assert;
import org.junit.Test;
import kieker.common.record.flow.trace.concurrency.monitor.MonitorNotifyEvent;
import kieker.common.util.registry.IRegistry;
import kieker.common.util.registry.Registry;
import kieker.test.common.junit.AbstractKiekerTest;
/**
* @author Jan Waller
*
* @since 1.8
*/
public class TestMonitorNotifyEvent extends AbstractKiekerTest {
private static final long TSTAMP = 987998L;
private static final long TRACE_ID = 23444L;
private static final int ORDER_INDEX = 234;
private static final int LOCK_ID = 13;
/**
* Default constructor.
*/
public TestMonitorNotifyEvent() {
// empty default constructor
}
/**
* Tests the constructor and toArray(..) methods of {@link MonitorNotifyEvent}.
*
* Assert that a record instance event1 equals an instance event2 created by serializing event1 to an array event1Array
* and using event1Array to construct event2. This ignores a set loggingTimestamp!
*/
@Test
public void testSerializeDeserializeEquals() {
final MonitorNotifyEvent event1 = new MonitorNotifyEvent(TSTAMP, TRACE_ID, ORDER_INDEX, LOCK_ID);
Assert.assertEquals("Unexpected timestamp", TSTAMP, event1.getTimestamp());
Assert.assertEquals("Unexpected trace ID", TRACE_ID, event1.getTraceId());
Assert.assertEquals("Unexpected order index", ORDER_INDEX, event1.getOrderIndex());
Assert.assertEquals("Unexpected lock id", LOCK_ID, event1.getLockId());
final Object[] event1Array = event1.toArray();
final MonitorNotifyEvent event2 = new MonitorNotifyEvent(event1Array);
Assert.assertEquals(event1, event2);
Assert.assertEquals(0, event1.compareTo(event2));
}
/**
* Tests the constructor and writeBytes(..) methods of {@link MonitorNotifyEvent}.
*/
@Test
public void testSerializeDeserializeBinaryEquals() {
final MonitorNotifyEvent event1 = new MonitorNotifyEvent(TSTAMP, TRACE_ID, ORDER_INDEX, LOCK_ID);
Assert.assertEquals("Unexpected timestamp", TSTAMP, event1.getTimestamp());
Assert.assertEquals("Unexpected trace ID", TRACE_ID, event1.getTraceId());
Assert.assertEquals("Unexpected order index", ORDER_INDEX, event1.getOrderIndex());
Assert.assertEquals("Unexpected lock id", LOCK_ID, event1.getLockId());
final IRegistry<String> stringRegistry = new Registry<String>();
final ByteBuffer buffer = ByteBuffer.allocate(event1.getSize());
event1.writeBytes(buffer, stringRegistry);
buffer.flip();
final MonitorNotifyEvent event2 = new MonitorNotifyEvent(buffer, stringRegistry);
Assert.assertEquals(event1, event2);
Assert.assertEquals(0, event1.compareTo(event2));
}
}
|
Java
|
import zerorpc
import gevent.queue
import logging
import sys
logging.basicConfig()
# root logger
logger = logging.getLogger()
# set the mimimum level for root logger so it will be possible for a client
# to subscribe and receive logs for any log level
logger.setLevel(0)
class QueueingLogHandler(logging.Handler):
""" A simple logging handler which puts all emitted logs into a
gevent queue.
"""
def __init__(self, queue, level, formatter):
super(QueueingLogHandler, self).__init__()
self._queue = queue
self.setLevel(level)
self.setFormatter(formatter)
def emit(self, record):
msg = self.format(record)
self._queue.put_nowait(msg)
def close(self):
super(QueueingLogHandler, self).close()
self._queue.put_nowait(None)
@property
def emitted(self):
return self._queue
class TestService(object):
_HANDLER_CLASS = QueueingLogHandler
_DEFAULT_FORMAT = '%(name)s - %(levelname)s - %(asctime)s - %(message)s'
logger = logging.getLogger("service")
def __init__(self):
self._logging_handlers = set()
def test(self, logger_name, logger_level, message):
logger = logging.getLogger(logger_name)
getattr(logger, logger_level.lower())(message)
def available_loggers(self):
""" List of initalized loggers """
return logging.getLogger().manager.loggerDict.keys()
def close_log_streams(self):
""" Closes all log_stream streams. """
while self._logging_handlers:
self._logging_handlers.pop().close()
@zerorpc.stream
def log_stream(self, logger_name, level_name, format_str):
""" Attaches a log handler to the specified logger and sends emitted logs
back as stream.
"""
if logger_name != "" and logger_name not in self.available_loggers():
raise ValueError("logger {0} is not available".format(logger_name))
level_name_upper = level_name.upper() if level_name else "NOTSET"
try:
level = getattr(logging, level_name_upper)
except AttributeError, e:
raise AttributeError("log level {0} is not available".format(level_name_upper))
q = gevent.queue.Queue()
fmt = format_str if format_str.strip() else self._DEFAULT_FORMAT
logger = logging.getLogger(logger_name)
formatter = logging.Formatter(fmt)
handler = self._HANDLER_CLASS(q, level, formatter)
logger.addHandler(handler)
self._logging_handlers.add(handler)
self.logger.debug("new subscriber for {0}/{1}".format(logger_name or "root", level_name_upper))
try:
for msg in handler.emitted:
if msg is None:
return
yield msg
finally:
self._logging_handlers.discard(handler)
handler.close()
self.logger.debug("subscription finished for {0}/{1}".format(logger_name or "root", level_name_upper))
if __name__ == "__main__":
service = TestService()
server = zerorpc.Server(service)
server.bind(sys.argv[1])
logger.warning("starting service")
try:
server.run()
except BaseException, e:
logger.error(str(e))
finally:
logger.warning("shutting down")
|
Java
|
package com.twitter.finagle.postgres.values
/*
* Enumeration of value types that can be included in query results.
*/
object Types {
val BOOL = 16
val BYTE_A = 17
val CHAR = 18
val NAME = 19
val INT_8 = 20
val INT_2 = 21
val INT_4 = 23
val REG_PROC = 24
val TEXT = 25
val OID = 26
val TID = 27
val XID = 28
val CID = 29
val JSON = 114
val XML = 142
val POINT = 600
val L_SEG = 601
val PATH = 602
val BOX = 603
val POLYGON = 604
val LINE = 628
val CIDR = 650
val FLOAT_4 = 700
val FLOAT_8 = 701
val ABS_TIME = 702
val REL_TIME = 703
val T_INTERVAL = 704
val UNKNOWN = 705
val CIRCLE = 718
val MONEY = 790
val MAC_ADDR = 829
val INET = 869
val BP_CHAR = 1042
val VAR_CHAR = 1043
val DATE = 1082
val TIME = 1083
val TIMESTAMP = 1114
val TIMESTAMP_TZ = 1184
val INTERVAL = 1186
val TIME_TZ = 1266
val BIT = 1560
val VAR_BIT = 1562
val NUMERIC = 1700
val REF_CURSOR = 1790
val RECORD = 2249
val VOID = 2278
val UUID = 2950
}
|
Java
|
# Leptopodia murina var. alpestris (Boud.) R. Heim & L. Remy VARIETY
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Leptopodia alpestris Boud.
### Remarks
null
|
Java
|
/**
* Copyright © 2013 enioka. All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.enioka.jqm.api.test;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.junit.Assert;
import org.junit.Test;
import com.enioka.jqm.api.JqmClientFactory;
import com.enioka.jqm.api.Query;
import com.enioka.jqm.api.Query.Sort;
import com.enioka.jqm.api.State;
import com.enioka.jqm.jdbc.Db;
import com.enioka.jqm.jdbc.DbConn;
import com.enioka.jqm.model.Instruction;
import com.enioka.jqm.model.JobDef;
import com.enioka.jqm.model.JobDef.PathType;
import com.enioka.jqm.model.JobInstance;
import com.enioka.jqm.model.Queue;
/**
* Simple tests for checking query syntax (no data)
*/
public class BasicTest
{
private static Logger jqmlogger = Logger.getLogger(BasicTest.class);
@Test
public void testChain()
{
// No exception allowed!
JqmClientFactory.getClient().getQueues();
jqmlogger.info("q1");
JqmClientFactory.getClient().getQueues();
jqmlogger.info("q2");
}
@Test
public void testQuery()
{
Query q = new Query("toto", null);
q.setInstanceApplication("marsu");
q.setInstanceKeyword2("pouet");
q.setInstanceModule("module");
q.setParentId(12);
q.setJobInstanceId(132);
q.setQueryLiveInstances(true);
q.setJobDefKeyword2("pouet2");
JqmClientFactory.getClient().getJobs(q);
}
@Test
public void testQueryDate()
{
Query q = new Query("toto", null);
q.setInstanceApplication("marsu");
q.setInstanceKeyword2("pouet");
q.setInstanceModule("module");
q.setParentId(12);
q.setJobInstanceId(132);
q.setQueryLiveInstances(true);
q.setEnqueuedBefore(Calendar.getInstance());
q.setEndedAfter(Calendar.getInstance());
q.setBeganRunningAfter(Calendar.getInstance());
q.setBeganRunningBefore(Calendar.getInstance());
q.setEnqueuedAfter(Calendar.getInstance());
q.setEnqueuedBefore(Calendar.getInstance());
q.setJobDefKeyword2("pouet2");
JqmClientFactory.getClient().getJobs(q);
}
@Test
public void testQueryStatusOne()
{
Query q = new Query("toto", null);
q.setQueryLiveInstances(true);
q.setInstanceApplication("marsu");
q.addStatusFilter(State.CRASHED);
JqmClientFactory.getClient().getJobs(q);
}
@Test
public void testQueryStatusTwo()
{
Query q = new Query("toto", null);
q.setQueryLiveInstances(true);
q.setInstanceApplication("marsu");
q.addStatusFilter(State.CRASHED);
q.addStatusFilter(State.HOLDED);
JqmClientFactory.getClient().getJobs(q);
}
@Test
public void testFluentQuery()
{
Query q = new Query("toto", null);
q.setQueryLiveInstances(true);
q.setInstanceApplication("marsu");
q.addStatusFilter(State.CRASHED);
q.addStatusFilter(State.HOLDED);
JqmClientFactory.getClient().getJobs(Query.create().addStatusFilter(State.RUNNING).setApplicationName("MARSU"));
}
@Test
public void testQueryPercent()
{
JqmClientFactory.getClient().getJobs(Query.create().setApplicationName("%TEST"));
}
@Test
public void testQueryNull()
{
JqmClientFactory.getClient().getJobs(new Query("", null));
}
@Test
public void testQueueNameId()
{
Query.create().setQueueName("test").run();
Query.create().setQueueId(12).run();
}
@Test
public void testPaginationWithFilter()
{
Query.create().setQueueName("test").setPageSize(10).run();
Query.create().setQueueId(12).setPageSize(10).run();
}
@Test
public void testUsername()
{
Query.create().setUser("test").setPageSize(10).run();
}
@Test
public void testSortHistory()
{
Query.create().setUser("test").setPageSize(10).addSortAsc(Sort.APPLICATIONNAME).addSortDesc(Sort.DATEATTRIBUTION)
.addSortAsc(Sort.DATEEND).addSortDesc(Sort.DATEENQUEUE).addSortAsc(Sort.ID).addSortDesc(Sort.QUEUENAME)
.addSortAsc(Sort.STATUS).addSortDesc(Sort.USERNAME).addSortAsc(Sort.PARENTID).run();
}
@Test
public void testSortJi()
{
Query.create().setQueryHistoryInstances(false).setQueryLiveInstances(true).setUser("test").addSortAsc(Sort.APPLICATIONNAME)
.addSortDesc(Sort.DATEATTRIBUTION).addSortDesc(Sort.DATEENQUEUE).addSortAsc(Sort.ID).addSortDesc(Sort.QUEUENAME)
.addSortAsc(Sort.STATUS).addSortDesc(Sort.USERNAME).addSortAsc(Sort.PARENTID).run();
}
@Test
public void testOnlyQueue()
{
Query.create().setQueryLiveInstances(true).setQueryHistoryInstances(false).setUser("test").run();
}
@Test
public void testBug159()
{
Query.create().setJobInstanceId(1234).setQueryLiveInstances(true).setQueryHistoryInstances(false).setPageSize(15).setFirstRow(0)
.run();
}
@Test
public void testBug292()
{
Query.create().addSortDesc(Query.Sort.ID).setQueueName("QBATCH").setQueryHistoryInstances(true).setQueryLiveInstances(true).run();
}
@Test
public void testBug305()
{
Properties p = new Properties();
p.putAll(Db.loadProperties());
Db db = new Db(p);
DbConn cnx = null;
try
{
cnx = db.getConn();
int qId = Queue.create(cnx, "q1", "q1 description", true);
int jobDefdId = JobDef.create(cnx, "test description", "class", null, "jar", qId, 1, "appName", null, null, null, null, null,
false, null, PathType.FS);
JobInstance.enqueue(cnx, com.enioka.jqm.model.State.RUNNING, qId, jobDefdId, null, null, null, null, null, null, null, null,
null, false, false, null, 1, Instruction.RUN, new HashMap<String, String>());
JobInstance.enqueue(cnx, com.enioka.jqm.model.State.RUNNING, qId, jobDefdId, null, null, null, null, null, null, null, null,
null, false, false, null, 1, Instruction.RUN, new HashMap<String, String>());
cnx.commit();
Properties p2 = new Properties();
p2.put("com.enioka.jqm.jdbc.contextobject", db);
List<com.enioka.jqm.api.JobInstance> res = JqmClientFactory.getClient("test", p2, false)
.getJobs(Query.create().setQueryHistoryInstances(false).setQueryLiveInstances(true).addSortDesc(Query.Sort.ID)
.setPageSize(1).setApplicationName("appName"));
Assert.assertEquals(1, res.size());
}
finally
{
if (cnx != null)
{
cnx.closeQuietly(cnx);
}
}
}
}
|
Java
|
<?php
declare(strict_types=1);
namespace DaPigGuy\PiggyCustomEnchants\enchants\armor\chestplate;
use DaPigGuy\PiggyCustomEnchants\enchants\CustomEnchant;
use DaPigGuy\PiggyCustomEnchants\enchants\ToggleableEnchantment;
use DaPigGuy\PiggyCustomEnchants\enchants\traits\TickingTrait;
use pocketmine\entity\effect\EffectInstance;
use pocketmine\entity\effect\VanillaEffects;
use pocketmine\inventory\Inventory;
use pocketmine\item\Item;
use pocketmine\player\Player;
class ProwlEnchant extends ToggleableEnchantment
{
use TickingTrait;
public string $name = "Prowl";
public int $maxLevel = 1;
public int $usageType = CustomEnchant::TYPE_CHESTPLATE;
public int $itemType = CustomEnchant::ITEM_TYPE_CHESTPLATE;
/** @var bool[] */
public array $prowled;
public function toggle(Player $player, Item $item, Inventory $inventory, int $slot, int $level, bool $toggle): void
{
if (!$toggle && isset($this->prowled[$player->getName()])) {
foreach ($player->getServer()->getOnlinePlayers() as $p) {
$p->showPlayer($player);
}
$player->getEffects()->remove(VanillaEffects::SLOWNESS());
if (!$player->getEffects()->has(VanillaEffects::INVISIBILITY())) {
$player->setInvisible(false);
}
unset($this->prowled[$player->getName()]);
}
}
public function tick(Player $player, Item $item, Inventory $inventory, int $slot, int $level): void
{
if ($player->isSneaking()) {
foreach ($player->getServer()->getOnlinePlayers() as $p) {
$p->hidePlayer($player);
}
$effect = new EffectInstance(VanillaEffects::SLOWNESS(), 2147483647, 0, false);
$player->setInvisible();
$player->getEffects()->add($effect);
$this->prowled[$player->getName()] = true;
} else {
if (isset($this->prowled[$player->getName()])) {
foreach ($player->getServer()->getOnlinePlayers() as $p) {
$p->showPlayer($player);
}
$player->getEffects()->remove(VanillaEffects::SLOWNESS());
if (!$player->getEffects()->has(VanillaEffects::INVISIBILITY())) {
$player->setInvisible(false);
}
unset($this->prowled[$player->getName()]);
}
}
}
}
|
Java
|
# -*- coding: utf-8 -*-
# Copyright 2022 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.
#
import proto # type: ignore
from google.protobuf import duration_pb2 # type: ignore
from google.protobuf import timestamp_pb2 # type: ignore
__protobuf__ = proto.module(
package="google.cloud.gaming.v1",
manifest={
"OperationMetadata",
"OperationStatus",
"LabelSelector",
"RealmSelector",
"Schedule",
"SpecSource",
"TargetDetails",
"TargetState",
"DeployedFleetDetails",
},
)
class OperationMetadata(proto.Message):
r"""Represents the metadata of the long-running operation.
Attributes:
create_time (google.protobuf.timestamp_pb2.Timestamp):
Output only. The time the operation was
created.
end_time (google.protobuf.timestamp_pb2.Timestamp):
Output only. The time the operation finished
running.
target (str):
Output only. Server-defined resource path for
the target of the operation.
verb (str):
Output only. Name of the verb executed by the
operation.
status_message (str):
Output only. Human-readable status of the
operation, if any.
requested_cancellation (bool):
Output only. Identifies whether the user has requested
cancellation of the operation. Operations that have
successfully been cancelled have [Operation.error][] value
with a [google.rpc.Status.code][google.rpc.Status.code] of
1, corresponding to ``Code.CANCELLED``.
api_version (str):
Output only. API version used to start the
operation.
unreachable (Sequence[str]):
Output only. List of Locations that could not
be reached.
operation_status (Sequence[google.cloud.gaming_v1.types.OperationMetadata.OperationStatusEntry]):
Output only. Operation status for Game
Services API operations. Operation status is in
the form of key-value pairs where keys are
resource IDs and the values show the status of
the operation. In case of failures, the value
includes an error code and error message.
"""
create_time = proto.Field(proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp,)
end_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,)
target = proto.Field(proto.STRING, number=3,)
verb = proto.Field(proto.STRING, number=4,)
status_message = proto.Field(proto.STRING, number=5,)
requested_cancellation = proto.Field(proto.BOOL, number=6,)
api_version = proto.Field(proto.STRING, number=7,)
unreachable = proto.RepeatedField(proto.STRING, number=8,)
operation_status = proto.MapField(
proto.STRING, proto.MESSAGE, number=9, message="OperationStatus",
)
class OperationStatus(proto.Message):
r"""
Attributes:
done (bool):
Output only. Whether the operation is done or
still in progress.
error_code (google.cloud.gaming_v1.types.OperationStatus.ErrorCode):
The error code in case of failures.
error_message (str):
The human-readable error message.
"""
class ErrorCode(proto.Enum):
r""""""
ERROR_CODE_UNSPECIFIED = 0
INTERNAL_ERROR = 1
PERMISSION_DENIED = 2
CLUSTER_CONNECTION = 3
done = proto.Field(proto.BOOL, number=1,)
error_code = proto.Field(proto.ENUM, number=2, enum=ErrorCode,)
error_message = proto.Field(proto.STRING, number=3,)
class LabelSelector(proto.Message):
r"""The label selector, used to group labels on the resources.
Attributes:
labels (Sequence[google.cloud.gaming_v1.types.LabelSelector.LabelsEntry]):
Resource labels for this selector.
"""
labels = proto.MapField(proto.STRING, proto.STRING, number=1,)
class RealmSelector(proto.Message):
r"""The realm selector, used to match realm resources.
Attributes:
realms (Sequence[str]):
List of realms to match.
"""
realms = proto.RepeatedField(proto.STRING, number=1,)
class Schedule(proto.Message):
r"""The schedule of a recurring or one time event. The event's time span
is specified by start_time and end_time. If the scheduled event's
timespan is larger than the cron_spec + cron_job_duration, the event
will be recurring. If only cron_spec + cron_job_duration are
specified, the event is effective starting at the local time
specified by cron_spec, and is recurring.
::
start_time|-------[cron job]-------[cron job]-------[cron job]---|end_time
cron job: cron spec start time + duration
Attributes:
start_time (google.protobuf.timestamp_pb2.Timestamp):
The start time of the event.
end_time (google.protobuf.timestamp_pb2.Timestamp):
The end time of the event.
cron_job_duration (google.protobuf.duration_pb2.Duration):
The duration for the cron job event. The
duration of the event is effective after the
cron job's start time.
cron_spec (str):
The cron definition of the scheduled event.
See https://en.wikipedia.org/wiki/Cron. Cron
spec specifies the local time as defined by the
realm.
"""
start_time = proto.Field(proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp,)
end_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,)
cron_job_duration = proto.Field(
proto.MESSAGE, number=3, message=duration_pb2.Duration,
)
cron_spec = proto.Field(proto.STRING, number=4,)
class SpecSource(proto.Message):
r"""Encapsulates Agones fleet spec and Agones autoscaler spec
sources.
Attributes:
game_server_config_name (str):
The game server config resource. Uses the form:
``projects/{project}/locations/{location}/gameServerDeployments/{deployment_id}/configs/{config_id}``.
name (str):
The name of the Agones leet config or Agones
scaling config used to derive the Agones fleet
or Agones autoscaler spec.
"""
game_server_config_name = proto.Field(proto.STRING, number=1,)
name = proto.Field(proto.STRING, number=2,)
class TargetDetails(proto.Message):
r"""Details about the Agones resources.
Attributes:
game_server_cluster_name (str):
The game server cluster name. Uses the form:
``projects/{project}/locations/{location}/realms/{realm}/gameServerClusters/{cluster}``.
game_server_deployment_name (str):
The game server deployment name. Uses the form:
``projects/{project}/locations/{location}/gameServerDeployments/{deployment_id}``.
fleet_details (Sequence[google.cloud.gaming_v1.types.TargetDetails.TargetFleetDetails]):
Agones fleet details for game server clusters
and game server deployments.
"""
class TargetFleetDetails(proto.Message):
r"""Details of the target Agones fleet.
Attributes:
fleet (google.cloud.gaming_v1.types.TargetDetails.TargetFleetDetails.TargetFleet):
Reference to target Agones fleet.
autoscaler (google.cloud.gaming_v1.types.TargetDetails.TargetFleetDetails.TargetFleetAutoscaler):
Reference to target Agones fleet autoscaling
policy.
"""
class TargetFleet(proto.Message):
r"""Target Agones fleet specification.
Attributes:
name (str):
The name of the Agones fleet.
spec_source (google.cloud.gaming_v1.types.SpecSource):
Encapsulates the source of the Agones fleet
spec. The Agones fleet spec source.
"""
name = proto.Field(proto.STRING, number=1,)
spec_source = proto.Field(proto.MESSAGE, number=2, message="SpecSource",)
class TargetFleetAutoscaler(proto.Message):
r"""Target Agones autoscaler policy reference.
Attributes:
name (str):
The name of the Agones autoscaler.
spec_source (google.cloud.gaming_v1.types.SpecSource):
Encapsulates the source of the Agones fleet
spec. Details about the Agones autoscaler spec.
"""
name = proto.Field(proto.STRING, number=1,)
spec_source = proto.Field(proto.MESSAGE, number=2, message="SpecSource",)
fleet = proto.Field(
proto.MESSAGE,
number=1,
message="TargetDetails.TargetFleetDetails.TargetFleet",
)
autoscaler = proto.Field(
proto.MESSAGE,
number=2,
message="TargetDetails.TargetFleetDetails.TargetFleetAutoscaler",
)
game_server_cluster_name = proto.Field(proto.STRING, number=1,)
game_server_deployment_name = proto.Field(proto.STRING, number=2,)
fleet_details = proto.RepeatedField(
proto.MESSAGE, number=3, message=TargetFleetDetails,
)
class TargetState(proto.Message):
r"""Encapsulates the Target state.
Attributes:
details (Sequence[google.cloud.gaming_v1.types.TargetDetails]):
Details about Agones fleets.
"""
details = proto.RepeatedField(proto.MESSAGE, number=1, message="TargetDetails",)
class DeployedFleetDetails(proto.Message):
r"""Details of the deployed Agones fleet.
Attributes:
deployed_fleet (google.cloud.gaming_v1.types.DeployedFleetDetails.DeployedFleet):
Information about the Agones fleet.
deployed_autoscaler (google.cloud.gaming_v1.types.DeployedFleetDetails.DeployedFleetAutoscaler):
Information about the Agones autoscaler for
that fleet.
"""
class DeployedFleet(proto.Message):
r"""Agones fleet specification and details.
Attributes:
fleet (str):
The name of the Agones fleet.
fleet_spec (str):
The fleet spec retrieved from the Agones
fleet.
spec_source (google.cloud.gaming_v1.types.SpecSource):
The source spec that is used to create the
Agones fleet. The GameServerConfig resource may
no longer exist in the system.
status (google.cloud.gaming_v1.types.DeployedFleetDetails.DeployedFleet.DeployedFleetStatus):
The current status of the Agones fleet.
Includes count of game servers in various
states.
"""
class DeployedFleetStatus(proto.Message):
r"""DeployedFleetStatus has details about the Agones fleets such
as how many are running, how many allocated, and so on.
Attributes:
ready_replicas (int):
The number of GameServer replicas in the
READY state in this fleet.
allocated_replicas (int):
The number of GameServer replicas in the
ALLOCATED state in this fleet.
reserved_replicas (int):
The number of GameServer replicas in the
RESERVED state in this fleet. Reserved instances
won't be deleted on scale down, but won't cause
an autoscaler to scale up.
replicas (int):
The total number of current GameServer
replicas in this fleet.
"""
ready_replicas = proto.Field(proto.INT64, number=1,)
allocated_replicas = proto.Field(proto.INT64, number=2,)
reserved_replicas = proto.Field(proto.INT64, number=3,)
replicas = proto.Field(proto.INT64, number=4,)
fleet = proto.Field(proto.STRING, number=1,)
fleet_spec = proto.Field(proto.STRING, number=2,)
spec_source = proto.Field(proto.MESSAGE, number=3, message="SpecSource",)
status = proto.Field(
proto.MESSAGE,
number=5,
message="DeployedFleetDetails.DeployedFleet.DeployedFleetStatus",
)
class DeployedFleetAutoscaler(proto.Message):
r"""Details about the Agones autoscaler.
Attributes:
autoscaler (str):
The name of the Agones autoscaler.
spec_source (google.cloud.gaming_v1.types.SpecSource):
The source spec that is used to create the
autoscaler. The GameServerConfig resource may no
longer exist in the system.
fleet_autoscaler_spec (str):
The autoscaler spec retrieved from Agones.
"""
autoscaler = proto.Field(proto.STRING, number=1,)
spec_source = proto.Field(proto.MESSAGE, number=4, message="SpecSource",)
fleet_autoscaler_spec = proto.Field(proto.STRING, number=3,)
deployed_fleet = proto.Field(proto.MESSAGE, number=1, message=DeployedFleet,)
deployed_autoscaler = proto.Field(
proto.MESSAGE, number=2, message=DeployedFleetAutoscaler,
)
__all__ = tuple(sorted(__protobuf__.manifest))
|
Java
|
# AUTOGENERATED FILE
FROM balenalib/edge-ubuntu:xenial-build
# remove several traces of debian python
RUN apt-get purge -y python.*
# http://bugs.python.org/issue19846
# > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK.
ENV LANG C.UTF-8
# key 63C7CC90: public key "Simon McVittie <smcv@pseudorandom.co.uk>" imported
# key 3372DCFA: public key "Donald Stufft (dstufft) <donald@stufft.io>" imported
RUN gpg --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \
&& gpg --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \
&& gpg --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059
ENV PYTHON_VERSION 3.6.15
# if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'"
ENV PYTHON_PIP_VERSION 21.3.1
ENV SETUPTOOLS_VERSION 60.5.4
RUN set -x \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-amd64-libffi3.2.tar.gz" \
&& echo "363447510565fe95ceb59ab3b11473c5ddc27b8b646ba02f7892c37174be1696 Python-$PYTHON_VERSION.linux-amd64-libffi3.2.tar.gz" | sha256sum -c - \
&& tar -xzf "Python-$PYTHON_VERSION.linux-amd64-libffi3.2.tar.gz" --strip-components=1 \
&& rm -rf "Python-$PYTHON_VERSION.linux-amd64-libffi3.2.tar.gz" \
&& ldconfig \
&& if [ ! -e /usr/local/bin/pip3 ]; then : \
&& curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \
&& echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \
&& python3 get-pip.py \
&& rm get-pip.py \
; fi \
&& pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \
&& find /usr/local \
\( -type d -a -name test -o -name tests \) \
-o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \
-exec rm -rf '{}' + \
&& cd / \
&& rm -rf /usr/src/python ~/.cache
# install "virtualenv", since the vast majority of users of this image will want it
RUN pip3 install --no-cache-dir virtualenv
ENV PYTHON_DBUS_VERSION 1.2.18
# install dbus-python dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
libdbus-1-dev \
libdbus-glib-1-dev \
&& rm -rf /var/lib/apt/lists/* \
&& apt-get -y autoremove
# install dbus-python
RUN set -x \
&& mkdir -p /usr/src/dbus-python \
&& curl -SL "http://dbus.freedesktop.org/releases/dbus-python/dbus-python-$PYTHON_DBUS_VERSION.tar.gz" -o dbus-python.tar.gz \
&& curl -SL "http://dbus.freedesktop.org/releases/dbus-python/dbus-python-$PYTHON_DBUS_VERSION.tar.gz.asc" -o dbus-python.tar.gz.asc \
&& gpg --verify dbus-python.tar.gz.asc \
&& tar -xzC /usr/src/dbus-python --strip-components=1 -f dbus-python.tar.gz \
&& rm dbus-python.tar.gz* \
&& cd /usr/src/dbus-python \
&& PYTHON_VERSION=$(expr match "$PYTHON_VERSION" '\([0-9]*\.[0-9]*\)') ./configure \
&& make -j$(nproc) \
&& make install -j$(nproc) \
&& cd / \
&& rm -rf /usr/src/dbus-python
# make some useful symlinks that are expected to exist
RUN cd /usr/local/bin \
&& ln -sf pip3 pip \
&& { [ -e easy_install ] || ln -s easy_install-* easy_install; } \
&& ln -sf idle3 idle \
&& ln -sf pydoc3 pydoc \
&& ln -sf python3 python \
&& ln -sf python3-config python-config
# set PYTHONPATH to point to dist-packages
ENV PYTHONPATH /usr/lib/python3/dist-packages:$PYTHONPATH
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@python.sh" \
&& echo "Running test-stack@python" \
&& chmod +x test-stack@python.sh \
&& bash test-stack@python.sh \
&& rm -rf test-stack@python.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: Intel 64-bit (x86-64) \nOS: Ubuntu xenial \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.6.15, Pip v21.3.1, Setuptools v60.5.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh
|
Java
|
/**
* Copyright (c) 2013-2020 Nikita Koksharov
*
* 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.redisson.iterator;
import java.util.AbstractMap;
import java.util.Map;
import java.util.Map.Entry;
/**
*
* @author Nikita Koksharov
*
* @param <V> value type
*/
public abstract class RedissonBaseMapIterator<V> extends BaseIterator<V, Entry<Object, Object>> {
@SuppressWarnings("unchecked")
protected V getValue(Map.Entry<Object, Object> entry) {
return (V) new AbstractMap.SimpleEntry(entry.getKey(), entry.getValue()) {
@Override
public Object setValue(Object value) {
return put(entry, value);
}
};
}
protected abstract Object put(Entry<Object, Object> entry, Object value);
}
|
Java
|
package org.artifactory.ui.rest.resource.home;
import org.artifactory.api.security.AuthorizationService;
import org.artifactory.ui.rest.resource.BaseResource;
import org.artifactory.ui.rest.service.general.GeneralServiceFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* @author Chen keinan
*/
@Path("home")
@RolesAllowed({AuthorizationService.ROLE_ADMIN, AuthorizationService.ROLE_USER})
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class HomeResource extends BaseResource {
@Autowired
GeneralServiceFactory generalFactory;
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getHomeData()
throws Exception {
return runService(generalFactory.getHomePage());
}
}
|
Java
|
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace Castleroid.NPCs
{
public class ai8 : ModNPC
{
public override void SetDefaults()
{
npc.name = "ai8";
npc.displayName = "ai8";
npc.width = 28;
npc.height = 20;
npc.damage = 2;
npc.defense = 0;
npc.lifeMax = 2;
npc.soundHit = 1;
npc.soundKilled = 16;
npc.value = 60f;
npc.knockBackResist = 0.0f;
npc.aiStyle = 8;
Main.npcFrameCount[npc.type] = Main.npcFrameCount[NPCID.CyanBeetle];
aiType = NPCID.CyanBeetle;
animationType = NPCID.CyanBeetle;
npc.noGravity = false;
npc.noTileCollide = true;
}
public override void HitEffect(int hitDirection, double damage)
{
for (int i = 0; i < 10; i++)
{
int dustType = Main.rand.Next(139, 143);
int dustIndex = Dust.NewDust(npc.position, npc.width, npc.height, dustType);
Dust dust = Main.dust[dustIndex];
dust.velocity.X = dust.velocity.X + Main.rand.Next(-50, 51) * 0.01f;
dust.velocity.Y = dust.velocity.Y + Main.rand.Next(-50, 51) * 0.01f;
dust.scale *= 1f + Main.rand.Next(-30, 31) * 0.01f;
}
}
}
}
|
Java
|
/*
* Licensed to Cloudkick, Inc ('Cloudkick') under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* Cloudkick 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 com.cloudkick;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class LoginActivity extends Activity {
private static final int SETTINGS_ACTIVITY_ID = 0;
RelativeLayout loginView = null;
private String user = null;
private String pass = null;
private ProgressDialog progress = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
setTitle("Cloudkick for Android");
findViewById(R.id.button_login).setOnClickListener(new LoginClickListener());
findViewById(R.id.button_signup).setOnClickListener(new SignupClickListener());
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == SETTINGS_ACTIVITY_ID) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
if (prefs.getString("editKey", "").equals("") && prefs.getString("editSecret", "").equals("")) {
finish();
}
else {
Intent result = new Intent();
result.putExtra("login", true);
setResult(Activity.RESULT_OK, result);
finish();
}
}
}
private class LoginClickListener implements View.OnClickListener {
public void onClick(View v) {
new AccountLister().execute();
}
}
private class SignupClickListener implements View.OnClickListener {
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.cloudkick.com/pricing/")));
}
}
private class AccountLister extends AsyncTask<Void, Void, ArrayList<String>>{
private Integer statusCode = null;
@Override
protected void onPreExecute() {
user = ((EditText) findViewById(R.id.input_email)).getText().toString();
pass = ((EditText) findViewById(R.id.input_password)).getText().toString();
progress = ProgressDialog.show(LoginActivity.this, "", "Logging In...", true);
}
@Override
protected ArrayList<String> doInBackground(Void...voids) {
ArrayList<String> accounts = new ArrayList<String>();
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://www.cloudkick.com/oauth/list_accounts/");
ArrayList<NameValuePair> values = new ArrayList<NameValuePair>(2);
values.add(new BasicNameValuePair("user", user));
values.add(new BasicNameValuePair("password", pass));
post.setEntity(new UrlEncodedFormEntity(values));
HttpResponse response = client.execute(post);
statusCode = response.getStatusLine().getStatusCode();
InputStream is = response.getEntity().getContent();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = rd.readLine()) != null) {
accounts.add(line);
Log.i("LoginActivity", line);
}
}
catch (Exception e) {
e.printStackTrace();
statusCode = 0;
}
return accounts;
}
@Override
protected void onPostExecute(ArrayList<String> accounts) {
switch (statusCode) {
case 200:
if (accounts.size() == 1) {
new KeyRetriever().execute(accounts.get(0));
}
else {
String[] tmpAccountArray = new String[accounts.size()];
final String[] accountArray = accounts.toArray(tmpAccountArray);
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setTitle("Select an Account");
builder.setItems(accountArray, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
new KeyRetriever().execute(accountArray[item]);
}
});
AlertDialog selectAccount = builder.create();
selectAccount.show();
}
break;
case 400:
progress.dismiss();
if (accounts.get(0).equals("You have enabled multi factor authentication for this account. To access the API key list, please visit the website.")) {
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setTitle("MFA is Enabled");
String mfaMessage = ("You appear to have multi-factor authentication enabled on your account. "
+ "You will need to manually create an API key with read permissions in the "
+ "web interface, then enter it directly in the settings panel.");
builder.setMessage(mfaMessage);
builder.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent settingsActivity = new Intent(getBaseContext(), Preferences.class);
startActivityForResult(settingsActivity, SETTINGS_ACTIVITY_ID);
}
});
AlertDialog mfaDialog = builder.create();
mfaDialog.show();
}
else {
Toast.makeText(LoginActivity.this, "Invalid Username or Password", Toast.LENGTH_LONG).show();
}
break;
default:
progress.dismiss();
Toast.makeText(LoginActivity.this, "An Error Occurred Retrieving Your Accounts", Toast.LENGTH_LONG).show();
};
}
}
private class KeyRetriever extends AsyncTask<String, Void, String[]>{
private Integer statusCode = null;
@Override
protected String[] doInBackground(String...accts) {
Log.i("LoginActivity", "Selected Account: " + accts[0]);
String[] creds = new String[2];
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://www.cloudkick.com/oauth/create_consumer/");
ArrayList<NameValuePair> values = new ArrayList<NameValuePair>(2);
values.add(new BasicNameValuePair("user", user));
values.add(new BasicNameValuePair("password", pass));
values.add(new BasicNameValuePair("account", accts[0]));
values.add(new BasicNameValuePair("system", "Cloudkick for Android"));
values.add(new BasicNameValuePair("perm_read", "True"));
values.add(new BasicNameValuePair("perm_write", "False"));
values.add(new BasicNameValuePair("perm_execute", "False"));
post.setEntity(new UrlEncodedFormEntity(values));
HttpResponse response = client.execute(post);
statusCode = response.getStatusLine().getStatusCode();
Log.i("LoginActivity", "Return Code: " + statusCode);
InputStream is = response.getEntity().getContent();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
for (int i = 0; i < 2; i++) {
line = rd.readLine();
if (line == null) {
return creds;
}
creds[i] = line;
}
}
catch (Exception e) {
statusCode = 0;
}
return creds;
}
@Override
protected void onPostExecute(String[] creds) {
progress.dismiss();
if (statusCode != 200) {
// Show short error messages - this is a dirty hack
if (creds[0] != null && creds[0].startsWith("User with role")) {
Toast.makeText(LoginActivity.this, creds[0], Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(LoginActivity.this, "An Error Occurred on Login", Toast.LENGTH_LONG).show();
return;
}
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("editKey", creds[0]);
editor.putString("editSecret", creds[1]);
editor.commit();
Intent result = new Intent();
result.putExtra("login", true);
setResult(Activity.RESULT_OK, result);
LoginActivity.this.finish();
}
}
}
|
Java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.