hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
cdfb3c85cb081eefaade6abe740de7980d8ac612 | 457 | package org.apache.batik.css.engine;
import org.apache.batik.util.ParsedURL;
import org.w3c.dom.Element;
public interface CSSStylableElement extends Element {
StyleMap getComputedStyleMap(String var1);
void setComputedStyleMap(String var1, StyleMap var2);
String getXMLId();
String getCSSClass();
ParsedURL getCSSBase();
boolean isPseudoInstanceOf(String var1);
StyleDeclarationProvider getOverrideStyleDeclarationProvider();
}
| 21.761905 | 66 | 0.78337 |
dd89eb570e63aed0eb7f06d76a87048215bfb54a | 2,906 | package org.ei.opensrp.path.fragment;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import org.ei.opensrp.path.R;
/**
* Created by coder on 6/28/17.
*/
public class SendMonthlyDraftDialogFragment extends DialogFragment {
String month;
public static SendMonthlyDraftDialogFragment newInstance(String month) {
SendMonthlyDraftDialogFragment f = new SendMonthlyDraftDialogFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putString("month", month);
f.setArguments(args);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// View v = inflater.inflate(R.layout.dialog_fragment_send_monthly, container, false);
// View tv = v.findViewById(R.id.text);
// ((TextView)tv).setText("Dialog #" + mNum + ": using style "
// + getNameForNum(mNum));
//
// // Watch for button clicks.
// Button button = (Button)v.findViewById(R.id.show);
// button.setOnClickListener(new View.OnClickListener() {
// public void onClick(View v) {
// // When button is clicked, call up to owning activity.
// ((FragmentDialog)getActivity()).showDialog();
// }
// });
// return v;
// }
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
// request a window without the title
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
AlertDialog.Builder b= new AlertDialog.Builder(getActivity())
.setPositiveButton("Send",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// do something...
}
}
)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}
);
LayoutInflater i = getActivity().getLayoutInflater();
View v = i.inflate(R.layout.dialog_fragment_send_monthly,null);
b.setView(v);
return dialog;
}
}
| 33.790698 | 93 | 0.592223 |
32817aa3c9cad777d079b39dd7519dc1d276429f | 8,744 | /*******************************************************************************
* Copyright 2015 ShopGun
*
* 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.shopgun.android.sdk.network.impl;
import com.shopgun.android.sdk.api.Parameters;
import com.shopgun.android.sdk.network.Cache;
import com.shopgun.android.sdk.network.NetworkResponse;
import com.shopgun.android.sdk.network.Request;
import com.shopgun.android.sdk.network.Response;
import com.shopgun.android.sdk.network.Response.Listener;
import com.shopgun.android.sdk.network.ShopGunError;
import com.shopgun.android.sdk.utils.SgnUtils;
import com.shopgun.android.utils.TextUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
public class JsonArrayRequest extends JsonRequest<JSONArray> {
/**
* The default limit for API calls.<br>
* By using this limit, queries are more likely to hit a cache on the server, hence making queries faster */
public static final int DEFAULT_LIMIT = 24;
private static final String ERROR_OFFSET_NEGATIVE = "Offset may not be negative";
private static final String ERROR_LIMIT_NEGATIVE = "Limit may not be negative";
private static final long CACHE_TTL = TimeUnit.MINUTES.toMillis(3);
public JsonArrayRequest(String url, Listener<JSONArray> listener) {
super(Method.GET, url, null, listener);
init();
}
public JsonArrayRequest(Method method, String url, Listener<JSONArray> listener) {
super(method, url, null, listener);
init();
}
public JsonArrayRequest(Method method, String url, JSONArray requestBody, Listener<JSONArray> listener) {
super(method, url, requestBody == null ? null : requestBody.toString(), listener);
init();
}
public JsonArrayRequest(Method method, String url, JSONObject requestBody, Listener<JSONArray> listener) {
super(method, url, requestBody == null ? null : requestBody.toString(), listener);
init();
}
private void init() {
setOffset(0);
setLimit(DEFAULT_LIMIT);
}
@Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
String jsonString = "";
try {
try {
jsonString = new String(response.data, getParamsEncoding());
} catch (UnsupportedEncodingException e) {
jsonString = new String(response.data);
}
Response<JSONArray> r = null;
if (SgnUtils.isSuccess(response.statusCode)) {
// Parse into array if it's successful
JSONArray jArray = new JSONArray(jsonString);
r = Response.fromSuccess(jArray, getCache());
JsonCacheHelper.cacheJSONArray(this, r.result);
} else {
// Parse into object if it failed.
JSONObject jObject = new JSONObject(jsonString);
ShopGunError e = ShopGunError.fromJSON(jObject);
r = Response.fromError(e);
}
return r;
} catch (Exception e) {
return Response.fromError(new ParseError(e, JSONArray.class));
}
}
@Override
public Response<JSONArray> parseCache(Cache c) {
return JsonCacheHelper.getJSONArray(this, c);
}
@Override
public long getCacheTTL() {
return CACHE_TTL;
}
/**
* Set the order the API should order the data by
* @param order parameter to order data by
* @return this object
*/
public Request<?> setOrderBy(String order) {
getParameters().put(Parameters.ORDER_BY, order);
return this;
}
/**
* Set a list of "order_by" parameters that the API should order the data by.
* @param order parameters to order data by
* @return this object
*/
public Request<?> setOrderBy(String[] order) {
if (order != null && order.length != 0) {
String tmp = TextUtils.join(",", order);
getParameters().put(Parameters.ORDER_BY, tmp);
}
return this;
}
/**
* Set a list of "order_by" parameters that the API should order the data by.
* @param order parameters to order data by
* @return this object
*/
public Request<?> setOrderBy(List<String> order) {
if (!order.isEmpty()) {
String tmp = TextUtils.join(",", order);
getParameters().put(Parameters.ORDER_BY, tmp);
}
return this;
}
/**
* Get the order the API should order data by
* @return the order as a String, or null if no order have been given.
*/
public String getOrderBy() {
return getParameters().get(Parameters.ORDER_BY);
}
/**
* The API relies on pagination for retrieving data. Therefore you need to
* define the offset to the first item in the requested list, when querying for data.
* If no offset is set it will default to 0.
* @param offset to first item in list
* @return this object
*/
public Request<?> setOffset(int offset) {
if (offset < 0) {
throw new IllegalStateException(ERROR_OFFSET_NEGATIVE);
}
getParameters().put(Parameters.OFFSET, String.valueOf(offset));
return this;
}
/**
* Get the offset parameter used for the query.
* @return offset
*/
public int getOffset() {
return Integer.valueOf(getParameters().get(Parameters.OFFSET));
}
/**
* The API relies on pagination for retrieving data. Therefore you need to
* define a limit for the data you want to retrieve. If no limit is set
* this will default to {@link #DEFAULT_LIMIT DEFAULT_LIMIT} if no limit is set.
* @param limit A limit for the number of items returned
* @return this object
*/
public Request<?> setLimit(int limit) {
if (limit < 0) {
throw new IllegalStateException(ERROR_LIMIT_NEGATIVE);
}
getParameters().put(Parameters.LIMIT, String.valueOf(limit));
return this;
}
/**
* Get the upper limit on how many items the API should return.
* @return max number of items API should return
*/
public int getLimit() {
return Integer.valueOf(getParameters().get(Parameters.LIMIT));
}
/**
* Set a parameter for what specific id's to get from a given endpoint.<br><br>
*
*
* @param type The id type, e.g. Parameters.CATALOG_IDS
* @param ids The id's to get
* @return this object
*/
public Request<?> setIds(String type, Set<String> ids) {
if (!ids.isEmpty()) {
String idList = TextUtils.join(",", ids);
getParameters().put(type, idList);
}
return this;
}
/**
* Type of publication the client supports
* @param type parameter
* @return this object
*/
public Request<?> setPublicationType(String type) {
getParameters().put(Parameters.PUBLICATION_TYPE, type);
return this;
}
/**
* Type of publication the client supports
* @param type parameter
* @return this object
*/
public Request<?> setPublicationType(String[] type) {
if (type != null && type.length != 0) {
String tmp = TextUtils.join(",", type);
getParameters().put(Parameters.PUBLICATION_TYPE, tmp);
}
return this;
}
/**
* Type of publication the client supports
* @param type parameter
* @return this object
*/
public Request<?> setPublicationType(List<String> type) {
if (!type.isEmpty()) {
String tmp = TextUtils.join(",", type);
getParameters().put(Parameters.PUBLICATION_TYPE, tmp);
}
return this;
}
/**
* Get the requested publication types
* @return the requested types or null
*/
public String getPublicationTypes() {
return getParameters().get(Parameters.PUBLICATION_TYPE);
}
}
| 32.996226 | 112 | 0.620425 |
1bbaa8d660fab6d1a6c10862f22f83caeb703357 | 191 | package net.minecraft.src;
public class ItemCoal extends Item {
public ItemCoal(int var1) {
super(var1);
this.setHasSubtypes(true);
this.setMaxDamage(0);
}
}
| 19.1 | 36 | 0.633508 |
7fe532241a3ef97b74de749742b1c63cc7cd6ef0 | 6,322 | package voss.discovery.agent.alaxala.profile;
import net.snmp.RepeatedOidException;
import net.snmp.SnmpResponseException;
import voss.discovery.agent.mib.Mib2;
import voss.discovery.iolib.AbortedException;
import voss.discovery.iolib.snmp.SnmpAccess;
import voss.discovery.iolib.snmp.SnmpUtil;
import java.io.IOException;
public class Alaxala7800SHitachiTypeProfile extends
Alaxala7800SVendorProfile {
private String vendorId = ".116";
private String gs4kBaseOid = Mib2.Snmpv2_SMI_enterprises + vendorId;
private String gs4kIfStatsBase = gs4kBaseOid + ".6.25.1.1.1.4.1.1";
private final String gs4kVBBaseVlanIfIndex = gs4kBaseOid
+ ".6.25.1.1.6.1.1.1.1.6";
private final String gs4kVBBaseVlanType = gs4kBaseOid
+ ".6.25.1.1.6.1.1.1.1.6";
private String gs4kBaseVlanId = gs4kBaseOid
+ ".6.25.1.1.6.1.1.1.1.7";
private String gs4kVBBasePortIfIndex = gs4kBaseOid
+ ".6.25.1.1.6.1.1.2.1.3";
private String vlanAndPortBindingState = gs4kBaseOid
+ ".6.25.1.1.6.1.1.2.1.8";
private String deviceBaseOid = gs4kBaseOid + ".6.25.1.3";
private String gs4kModelType = deviceBaseOid + ".1.1";
private String gs4kSoftwareName = deviceBaseOid + ".1.2.1";
private String gs4kSoftwareVersion = deviceBaseOid + ".1.2.3";
private String nifBoardNumber = deviceBaseOid + ".2.1.2.1.10";
private String gs4kNifBoardName = deviceBaseOid + ".2.4.1.1.4";
private String nifPhysicalLineNumber = deviceBaseOid + ".2.4.1.1.7";
private String axIfIndex = deviceBaseOid + ".2.6.1.1.2";
private String axPhysLineConnectorType = deviceBaseOid + ".2.5.1.1.2";
private final String gs4kFlowQosBase = ".6.25.1.1.8.5";
private final String gs4kFlowQosInBase = gs4kFlowQosBase + ".1";
private final String gs4kFlowQosInPremiumBase = gs4kFlowQosBase + ".2";
private final String gs4kFlowQosOutBase = gs4kFlowQosBase + ".3";
private final String gs4kFlowQosOutPremiumBase = gs4kFlowQosBase + ".4";
private final String gs4kFlowQosStatsBase = ".6.25.1.1.8.6";
private final String gs4kFlowQosStatsInBase = gs4kFlowQosStatsBase + ".1";
private final String gs4kFlowQosStatsInPremiumBase = gs4kFlowQosStatsBase + ".2";
private final String gs4kFlowQosStatsOutBase = gs4kFlowQosStatsBase + ".3";
private final String gs4kFlowQosStatsOutPremiumBase = gs4kFlowQosStatsBase + ".4";
@Override
public String getOsType() {
return OS_TYPE_CISCO_LIKE;
}
@Override
public String getModelName(SnmpAccess _snmp) throws IOException, AbortedException {
try {
int modelTypeId = SnmpUtil.getIntSnmpEntries(_snmp, gs4kModelType).get(0).intValue();
switch (modelTypeId) {
case 1:
return "Other";
case 100:
return "GS4000-80E1";
case 101:
return "GS4000-80E2";
case 102:
return "GS4000-160E1";
case 103:
return "GS4000-160E2";
case 104:
return "GS4000-320E-DC";
case 105:
return "GS4000-320E-AC";
}
return "UNKNOWN";
} catch (RepeatedOidException e) {
throw new IOException(e);
} catch (SnmpResponseException e) {
throw new IOException(e);
}
}
@Override
public String getDeviceBaseOid() {
return this.deviceBaseOid;
}
@Override
public String getOsNameOid() {
return this.gs4kSoftwareName;
}
@Override
public String getOsVersionOid() {
return this.gs4kSoftwareVersion;
}
@Override
public String getNumberOfSlotOid() {
return this.nifBoardNumber;
}
@Override
public String getBoardNameOid() {
return this.gs4kNifBoardName;
}
@Override
public String getNumberOfPortOid() {
return this.nifPhysicalLineNumber;
}
@Override
public String getVendorIdOid() {
return this.vendorId;
}
@Override
public String getAlaxalaBaseOid() {
return this.gs4kBaseOid;
}
@Override
public String getAlaxalaVBBaseVlanTypeOid() {
return this.gs4kVBBaseVlanType;
}
@Override
public String getAlaxalaBaseVlanIdOid() {
return this.gs4kBaseVlanId;
}
@Override
public String getAxsVBBasePortIfIndexOid() {
return this.gs4kVBBasePortIfIndex;
}
@Override
public String getVlanAndPortBindingStateOid() {
return this.vlanAndPortBindingState;
}
@Override
public String getAxIfIndexOid() {
return this.axIfIndex;
}
@Override
public String getPhysLineConnectorTypeOid() {
return this.axPhysLineConnectorType;
}
@Override
public String getAxsIfStatsHighSpeedOid() {
return this.gs4kIfStatsBase + ".11";
}
@Override
public String getQosFlowStatsInListName() {
return null;
}
@Override
public String getAxsVBBaseVlanIfIndexOid() {
return gs4kVBBaseVlanIfIndex;
}
@Override
public String getFlowQosBaseOid() {
return this.gs4kFlowQosBase;
}
@Override
public String getFlowQosInBaseOid() {
return this.gs4kFlowQosInBase;
}
@Override
public String getFlowQosInPremiumBaseOid() {
return this.gs4kFlowQosInPremiumBase;
}
@Override
public String getFlowQosOutBaseOid() {
return this.gs4kFlowQosOutBase;
}
@Override
public String getFlowQosOutPremiumBaseOid() {
return this.gs4kFlowQosOutPremiumBase;
}
@Override
public String getFlowQosStatsBaseOid() {
return this.gs4kFlowQosStatsBase;
}
@Override
public String getFlowQosStatsInBaseOid() {
return this.gs4kFlowQosStatsInBase;
}
@Override
public String getFlowQosStatsInPremiumBaseOid() {
return this.gs4kFlowQosStatsInPremiumBase;
}
@Override
public String getFlowQosStatsOutBaseOid() {
return this.gs4kFlowQosStatsOutBase;
}
@Override
public String getFlowQosStatsOutPremiumBaseOid() {
return this.gs4kFlowQosStatsOutPremiumBase;
}
} | 28.477477 | 97 | 0.650269 |
fbb204482989d313c7fa9d570a420c6b1e8f3017 | 259 | package com.vuforia;
public class CameraDevice {
static final CameraDevice cameraDevice = new CameraDevice();
public static CameraDevice getInstance() {
return cameraDevice;
}
public void setFlashTorchMode(boolean enabled) {
}
}
| 21.583333 | 64 | 0.710425 |
0aaaa23371878d0a433b377f184ec23456ec78a3 | 1,461 | package main;
import java.io.File;
import kepLib.KepInstance;
import kepLib.KepParseData;
import kepLib.KepTextReaderWriter;
import unosData.UnosData;
import unosData.UnosDonorEdge;
import unosData.UnosExchangeUnit;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import exchangeGraph.minWaitingTime.MinWaitingTimeProblemData;
public class ConvertUnosData {
public static void main(String[] args) {
UnosData data = UnosData.readUnosData("data" + File.separator
+ "unosDataItaiCorrected.csv", false, true);
KepInstance<UnosExchangeUnit, UnosDonorEdge> instance = new KepInstance<UnosExchangeUnit, UnosDonorEdge>(
data.exportKepProblemData(), Functions.constant(1), Integer.MAX_VALUE,
3, 0);
Function<UnosExchangeUnit, String> nodeNames = KepParseData
.anonymousNodeNames(instance);
Function<UnosDonorEdge, String> edgeNames = KepParseData
.anonymousEdgeNames(instance);
KepTextReaderWriter.INSTANCE.write(instance, nodeNames, edgeNames,
"kepLibInstances" + File.separator + "big" + File.separator
+ "unos.csv");
MinWaitingTimeProblemData<UnosExchangeUnit> minWaitingTimeProblemData = data
.exportMinWaitingTimeProblemData();
KepTextReaderWriter.INSTANCE.writeNodeArrivalTimes("kepLibInstances"
+ File.separator + "big" + File.separator + "unosArrivalTimes.csv",
minWaitingTimeProblemData, nodeNames);
}
}
| 35.634146 | 109 | 0.755647 |
e3aea64bc450aa7a187094a17d2a8823b27cb5f2 | 1,172 | package com.devsuperior.userdept.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "tb_user") //Criando o nome da Table do Banco de Dados.
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) //Definindo o ID do Banco de Dados
private Long id;
private String name;
private String email;
@ManyToOne
@JoinColumn(name = "department_id") //Definindo o nome da Chave Estrangeira do Banco
private Department department;
public User() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
}
| 18.3125 | 87 | 0.732935 |
d5c6c75df80ae167fcd6390a8af49656c682d824 | 8,724 | package com.github.forax.tomahawk.vec;
import static java.nio.file.Files.list;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.Closeable;
import java.io.IOException;
import java.nio.file.Files;
import java.util.function.LongFunction;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import jdk.incubator.foreign.MemorySegment;
@SuppressWarnings("static-method")
public class VecU32Test {
@SuppressWarnings("unused")
public static Stream<LongFunction<U32Vec>> provideIntVecs() {
return Stream.of(
length -> U32Vec.wrap(new int[(int) length]),
length -> U32Vec.from(null, MemorySegment.allocateNative(length * 4))
);
}
@SuppressWarnings("unused")
public static Stream<LongFunction<U32Vec>> provideFloatVecs() {
return Stream.of(
length -> U32Vec.wrap(new float[(int) length]),
length -> U32Vec.from(null, MemorySegment.allocateNative(length * 4))
);
}
@SuppressWarnings("unused")
public static Stream<LongFunction<U32Vec>> provideAllVecs() {
return Stream.of(
length -> U32Vec.wrap(new float[(int) length]),
length -> U32Vec.wrap(new float[(int) length]),
length -> U32Vec.from(null, MemorySegment.allocateNative(length * 4))
);
}
@ParameterizedTest
@MethodSource("provideAllVecs")
public void length(LongFunction<? extends U32Vec> factory) {
assertAll(
() -> {
try (var vec = factory.apply(13)) {
assertEquals(13, vec.length());
}
},
() -> {
try (var vec = factory.apply(42)) {
assertEquals(42, vec.length());
}
}
);
}
@ParameterizedTest
@MethodSource("provideAllVecs")
public void notNullableByDefault(LongFunction<? extends U32Vec> factory) {
try(var vec = factory.apply(5)) {
assertAll(
() -> assertFalse(vec.isNull(3)),
() -> assertThrows(IllegalStateException.class, () -> vec.setNull(3))
);
}
}
@ParameterizedTest
@MethodSource("provideIntVecs")
public void getSetInts(LongFunction<? extends U32Vec> factory) {
try(var vec = factory.apply(5)) {
assertEquals(0, vec.getInt(0));
assertEquals(0, vec.getInt(3));
vec.setInt(0, 42);
vec.setInt(3, 56);
assertEquals(42, vec.getInt(0));
assertEquals(56, vec.getInt(3));
}
}
@ParameterizedTest
@MethodSource("provideIntVecs")
public void getBoxInts(LongFunction<? extends U32Vec> factory) {
try(var base = factory.apply(5);
var vec = base.withValidity(U1Vec.wrap(new long[1]))) {
vec.setInt(1, 1324);
vec.setNull(2);
vec.setInt(3, 2768);
var box = new IntBox();
vec.getInt(0, box);
assertFalse(box.validity);
vec.getInt(1, box);
assertTrue(box.validity);
assertEquals(1324, box.value);
vec.getInt(2, box);
assertFalse(box.validity);
vec.getInt(3, box);
assertTrue(box.validity);
assertEquals(2768, box.value);
}
}
@ParameterizedTest
@MethodSource("provideIntVecs")
public void wrapOutOfBoundsInts(LongFunction<? extends U32Vec> factory) {
try(var vec = factory.apply(5)) {
assertAll(
() -> assertThrows(IndexOutOfBoundsException.class, () -> vec.getInt(7)),
() -> assertThrows(IndexOutOfBoundsException.class, () -> vec.getInt(-1)),
() -> assertThrows(IndexOutOfBoundsException.class, () -> vec.setInt(7, 42)),
() -> assertThrows(IndexOutOfBoundsException.class, () -> vec.setInt(-1, 42))
);
}
}
@ParameterizedTest
@MethodSource("provideIntVecs")
public void validityInts(LongFunction<? extends U32Vec> factory) {
try(var simpleDataset = factory.apply(5);
var vec = simpleDataset.withValidity(U1Vec.wrap(new long[1]))) {
vec.setInt(0, 42);
vec.setInt(3, 56);
vec.setNull(0);
vec.setNull(3);
assertAll(
() -> assertTrue(vec.isNull(0)),
() -> assertThrows(NullPointerException.class, () -> vec.getInt(0)),
() -> assertFalse(vec.getInt(0, new IntBox()).validity),
() -> assertTrue(vec.isNull(3)),
() -> assertThrows(NullPointerException.class, () -> vec.getInt(3)),
() -> assertFalse(vec.getInt(3, new IntBox()).validity)
);
}
}
@ParameterizedTest
@MethodSource("provideFloatVecs")
public void getSetFloats(LongFunction<? extends U32Vec> factory) {
try(var vec = factory.apply(5)) {
assertEquals(0f, vec.getFloat(0));
assertEquals(0f, vec.getFloat(3));
vec.setFloat(0, 42f);
vec.setFloat(3, 56f);
assertEquals(42f, vec.getFloat(0));
assertEquals(56f, vec.getFloat(3));
}
}
@ParameterizedTest
@MethodSource("provideFloatVecs")
public void getBoxFloats(LongFunction<? extends U32Vec> factory) {
try(var base = factory.apply(5);
var vec = base.withValidity(U1Vec.wrap(new long[1]))) {
vec.setFloat(1, 1324f);
vec.setNull(2);
vec.setFloat(3, 2768f);
var box = new FloatBox();
vec.getFloat(0, box);
assertFalse(box.validity);
vec.getFloat(1, box);
assertTrue(box.validity);
assertEquals(1324f, box.value);
vec.getFloat(2, box);
assertFalse(box.validity);
vec.getFloat(3, box);
assertTrue(box.validity);
assertEquals(2768f, box.value);
}
}
@ParameterizedTest
@MethodSource("provideFloatVecs")
public void wrapOutOfBoundsFloats(LongFunction<? extends U32Vec> factory) {
try(var vec = factory.apply(5)) {
assertAll(
() -> assertThrows(IndexOutOfBoundsException.class, () -> vec.getFloat(7)),
() -> assertThrows(IndexOutOfBoundsException.class, () -> vec.getFloat(-1)),
() -> assertThrows(IndexOutOfBoundsException.class, () -> vec.setFloat(7, 42f)),
() -> assertThrows(IndexOutOfBoundsException.class, () -> vec.setFloat(-1, 42f))
);
}
}
@ParameterizedTest
@MethodSource("provideFloatVecs")
public void validityFloats(LongFunction<? extends U32Vec> factory) {
try(var simpleDataset = factory.apply(5);
var vec = simpleDataset.withValidity(U1Vec.wrap(new long[1]))) {
vec.setFloat(0, 42f);
vec.setFloat(3, 56f);
vec.setNull(0);
vec.setNull(3);
assertAll(
() -> assertTrue(vec.isNull(0)),
() -> assertThrows(NullPointerException.class, () -> vec.getFloat(0)),
() -> assertFalse(vec.getFloat(0, new FloatBox()).validity),
() -> assertTrue(vec.isNull(3)),
() -> assertThrows(NullPointerException.class, () -> vec.getFloat(3)),
() -> assertFalse(vec.getFloat(3, new FloatBox()).validity)
);
}
}
@Test
public void mapNew() throws IOException {
var path = Files.createTempFile("map-new", "");
Closeable andClean = () -> Files.delete(path);
try(andClean) {
try(var vec = U32Vec.mapNew(null, path, 128)) {
assertEquals(128, vec.length());
}
}
}
@Test
public void simple() throws IOException {
var path = Files.createTempFile("map-new", "");
Closeable andClean = () -> Files.delete(path);
Vec vec;
try(andClean) {
var builder = U32Vec.builder(null, path);
builder.appendInt(3)
.appendFloat(42.5f);
vec = builder.toVec();
}
try(vec) {
assertEquals(vec.length(), 2);
}
}
@Test
public void demo() throws IOException {
var dir = Files.createTempDirectory("vec-u32");
Closeable andClean = () -> {
try(var stream = list(dir)) {
for(var path: stream.toList()) {
Files.delete(path);
}
}
Files.delete(dir);
};
try(andClean) {
var dataPath = dir.resolve("element");
var validityPath = dir.resolve("validity");
U32Vec vec;
try (var validityBuilder = U1Vec.builder(null, validityPath);
var builder = U32Vec.builder(validityBuilder, dataPath)) {
LongStream.range(0, 100_000).forEach(i -> builder.appendInt((int) i));
vec = builder.toVec();
}
try (vec) {
assertEquals(100_000, vec.length());
assertEquals(6, vec.getInt(6));
assertEquals(66_794, vec.getInt(66_794));
vec.setNull(13);
assertTrue(vec.isNull(13));
}
}
}
} | 31.723636 | 90 | 0.626662 |
9c320bd037edfed40ae2a0b151b5728280a0c5df | 8,152 | class k4b {
public int DScVoZ7;
public static void pDjGM (String[] T_r9IPwhl4FHC) throws XSb5ACJpB {
e5WnqHS7R[] u8bGlF3Tqslb;
;
boolean[] Cv = new ug4l6[ false[ !-true.fDWgGi()]].m = -!Nerv57()[ -PZeh().AveQr2NR];
void[][] M2dVBNz = !this.wVuox21meyNw() = !true.oFYEs42;
return;
;
{
while ( -null.rZOJ2HXBPqj30d()) ;
;
{
int[][] X9U7BKatWQcRHu;
}
int[] QhqNpF6oPKN;
!null[ -true.jpKDVW];
boolean[] KKE1;
DFWOv8[] WB;
;
boolean[] yhgyxYA;
int[][] E;
int[][] HZMLy;
}
while ( ( new ivmnO7Su2mFaa[ this.ct6RJ][ this.mIFD18mvDhJ()]).gwQt4ND_0Rd1d) return;
boolean IXW8NQUQnlGQ;
;
;
DJXsAP2[] poMp = !null.WFqg4xt();
return NXk_u()[ -true.Aj34iroOsKHiL()];
this.HR0ekhptX3A;
boolean OmJru = -!983552.Q8w7();
;
int[] HsyTV6BzfA5EDA;
int Q;
int URtMAKTZOk = !!--TjK8Gs8db()[ 645961323[ ---new wxUTm().Jg2IfJbQCGFv()]];
}
public void CdIH3 () {
!QbvWQ0Yn0cGPD()[ this.xDW_l2()];
if ( this[ -!-!false.nrzlpNw9O_()]) ;else return;
gBf22V9GgQ I6sFBdqlntpO;
void CDY1T7jE = !false.yro3rlq();
}
public boolean MSUu7fbb2zs;
public boolean[] wyggBbnCw_U;
}
class ipRyoYxdvRE {
public static void Zgo52h2UHX (String[] D93bkFKIXc5X0) throws KegUPdDjTrxf_B {
int K0taJBdqq;
return;
;
while ( 1592827[ -null.NHe3kSSULP]) {
t3MaBg[][] o1L;
}
int eRf0Q4 = !( !nJiKHp8N0eWVXa().b7E9OnZOV).AmMUQpBa();
!!--!!-false.D0vuQDt24S7();
LKMno qIuCDmx3wLd;
boolean[][][][][] uev3I7t = !true[ !!---true.n39L()];
void[][][][] e7Fjnu;
{
bLvX[][] CSH6Y0Qw;
false.KFuW0V1X_XwPH;
huoag80aT_w2[] gOBg;
boolean[][][][][][] pxy;
while ( new yzheqD07L2pVe().edmZ2DuY8Grss()) ;
return;
if ( --!-false[ -!!RTBYCeK()[ -true.AbnHE()]]) while ( ---null.E9()) !jZJMnyRsXGq.ipQwdQ3ChCsr;
!null.i0RzUjaeqcQitt();
void B;
;
-55787.ZnvPHpLZXpSLv;
void[] qNf7i89;
c85vCGZdYMimx they;
{
;
}
}
int yNiY = !-new G()[ null[ -!-057872.L4RmcJ5lCm]];
boolean[][][][] _5M6Dvr;
boolean jEZ3y9;
uuoULbV_t XZrgz = itAVAu().JseXRYqei4ENuS;
void[] NEzMGnuTy2XHV = new bVU[ -!null.gxu()][ !ncsX8D_jSbfMh6()[ new jXb[ new D().mlj4eWQX6Q7U()].qSk]];
while ( true[ ( b()[ -new int[ null.HN][ L2TtL93().zwkQz8]]).O6aZ]) while ( null.eAdJQimQuLipcj) {
{
if ( false.K6iccy2) return;
}
}
;
{
new int[ !-new int[ new bofJWlJfUD0lQ9[ !-this.svcs594()][ --null[ kfs1r().cg9fHGFP]]][ 67.vIzRIQ3uMlO()]].a;
void hI0Josf;
new UhGpJKINKNiwqJ()[ S().vd()];
void eAMNa8sYq;
return;
-true.flf7uzSo();
{
JuhC9XId15 i;
}
boolean[] PCmT;
int[][] HXSuGjPs9MT;
}
while ( !this.b6yx4dTz7s7()) return;
int Kh = 665264.ypAHyk;
}
public boolean gSH442LUah;
public static void vYQEslRhe (String[] gfZFO5RjtNGyv) {
int[][][] sYT = null.DDFjc();
ETXZvc6EW().PxnBxDcoIG();
int ELRTVS4ghTDa;
SdGDiCr_8JG6 fT9LRa5M;
return -!!this[ sNUTQ.o8DuJ];
boolean[] rlhogyiK2E;
nz7tcjTR7_F[] AFIf0q9s0Gu7r;
boolean[] bQ = !oWnxDtu.DNLzDXbm1;
void yRYv9xs6uSszGN;
void _GVwIbQSM68;
MFp1bJV8a8c SnxI;
boolean[] ycFbyP8dql = this.o8JjGkxTMrS2();
;
boolean[][] _aF = -Mz426Aq7C4.A5kyA8wx3yN = !-!new int[ !false.KLcU].qC4sKZY8aaGnn;
;
boolean nakikcmE9RNI;
}
public void[][][] dVzvE;
public int[] JR (boolean pDBKY, int[][] dD55ovWfru4C_, void n, int[][][] fBLV0ZqxiYCWze, int jT, boolean eZmmT) throws CzGsXYtE6ejO {
int synE8d8Uw9 = jn_Gcdv8o[ new w0().pYmQXaq774] = -PA[ ---true.n()];
{
!--this.zn9buQN;
GedSnlo[ !!gUrC5mI37zl.Z_8V8DNKQeQ()];
return;
{
{
boolean[][][][][][][][] je;
}
}
{
gB0I6gmr CV66;
}
;
void TZc;
void[] qKo;
-2.JY();
void[][] FYE27bj;
boolean K;
return;
boolean[][] Ak3w6;
}
int MThWidGHAP926;
void[] RbKVu3Gmx0;
while ( ---!s7EMG5Y.p4GhPzK) if ( ( new x6Lw().NORv7Krv3WG7t)[ !false.h4D]) while ( !-false[ null.D31j7F()]) if ( !null.oUiA()) 57[ !-null.NiDRn4()];
}
public int c_Qg3D (OClc0Q3X85OtUg[][] xDVnTAxsu, void[] CehZiuXjw1p, boolean GXE_9DA) {
int DK_Sievv3 = -!!new boolean[ new nv[ XxKpRF5C_x1i().DL9KTAn()].ybD].Vh() = rpXlaON2j0().obHDo;
void oY7_kNvgv = new mQU9().mKncpXPC57Za() = 462725[ new yx3H9FvO4AX6V6()[ 0880[ KFf[ -!-( true[ -vJuJF72B.AWJHsIsqASc()])[ true.Es()]]]]];
!this.p;
j1Hy1Bwnj[] M8b = A5lmpHt[ --dyTGzfLSwRQ.XicLKSODh_V6Wd] = !new J_U_bpA()[ !lde8LqjGPrMdk().WgdY9Qq()];
;
GshnFi[] h93PnXdMwfpwl = -true.GaTqCPb19GP = -null[ -!null._d()];
int[] LGsir;
int dgv0Mc5;
{
boolean[] Pfx19Qyn41XKr;
void[][] qNvyL;
void[][][] tRd2Ah;
return;
void[][] HVp;
ZpNVMzVGWBApCX cVVAy;
void[][] tan4;
!--!!true[ !!this[ false.gt6DYkMx6o()]];
!6.j_oUOp2aFrt();
if ( V.fMR()) if ( JqPIIs5hjzJNth.h()) while ( new ax8QutLCxWy[ new boolean[ !Hl15wi_u3__SfO.wMWWbd_PmEE][ !--1.PHULKvX]][ this[ null.p1g5e()]]) {
rzz3gS LnDwtLTLPsr;
}
int[][][] C07GYRS;
void[] V3u5pv7;
;
if ( ih87zHsZIXBoi[ new int[ -new int[ !false.zy5r2R()].OncnYDA5W_ja()][ !null[ !-LDinQucaJ().tOI4pKeBRvfks]]]) ;
boolean[][][][][][][][][][] hHmmnw1uv;
boolean[][][][] hJIfTK;
XjbWs1KpPrLOxc fu1c;
if ( ( ---false.Q_DQ).QOKEn()) ;
new AsiQJjngEoN6[ !HYyOIf2Fj8If().NoEzkIiRlYEj()].WPuDyfQpf();
int[][][] WgQtrv;
}
false.q7cq8_8o();
return;
boolean SALbRq8WzMN;
;
return;
;
void WgRZuQTSPF5 = this[ ( -----!-!997.gFE2Z0whlIAC()).CL34JbN0PaoAh()] = 55[ !this.uGg()];
void[][] sqtWdqSQM8sa6 = Q8B60f().Bszr_gE();
}
public int[] cW2Xu5CNzI (int eW4FrC, void[][] E, boolean t1aznyMQJv8rOr, int rVfi7SNy57J) throws bsKhItQzKzVS {
if ( new vjWaIT().RrJ()) {
new grzwOeOe().W7FIlwgc();
}else {
while ( !( -new int[ 30._iUug()]._l6SfS()).i()) if ( -92623.uniFLWwdPzZY) return;
}
IBLbG2ax().k33ct_LM();
boolean VSv_3nZgSbcF = new PWtA4U5Nv()[ !!!true[ false[ new FCoMOkby().TfsB()]]] = -new AalnPEFIe()[ null.ev_kjqNQEk];
{
int PPvU;
boolean[][][] _Z;
while ( -24272.MLeW3()) if ( new int[ -new uFVOsNucwsR_o[ ---false.Ajpt()][ new fWZAN[ ow_()[ oFJarpov3y7Y()[ -vvhk.R()]]].uIo03aFbRK()]][ this.U8eT7zjX6Dhqw()]) return;
{
bLvFN[] S83d;
}
( this.GUef9B3KFUUI())[ this[ ( new sPzSFvSu()[ --!hGim4VA30()[ null.P]])[ false[ -false.gO]]]];
int[] wSTEud2Rx8t;
{
boolean[][][][][] pjOr;
}
int[] L3tV5Q;
while ( null.nzIoF7rKs()) while ( 766439[ -this.WH4keX()]) ;
dDn63SUkyMUs37[] mGxOuDcEkAj;
int kc5niABXb;
}
if ( ( !-true.P2).cHx0wuxglC) if ( !null.raVoxLN()) return;
}
public boolean avBUwa3C2Pi_;
}
| 36.392857 | 181 | 0.488592 |
dd64885902955afc7482080bff2990abfe7bc8c2 | 3,567 | /*
* Copyright 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.
*/
package org.springframework.migrationanalyzer.contributions.deploymentdescriptors.jboss;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.InputStream;
import java.util.Set;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.migrationanalyzer.analyze.fs.FileSystemEntry;
import org.springframework.migrationanalyzer.analyze.fs.FileSystemEntry.Callback;
import org.springframework.migrationanalyzer.analyze.support.EntryAnalyzer;
import org.springframework.migrationanalyzer.contributions.deploymentdescriptors.DeploymentDescriptor;
import org.springframework.migrationanalyzer.util.IoUtils;
public class JBossServiceXmlDetectingEntryAnalyzerTests {
private final EntryAnalyzer<DeploymentDescriptor> entryAnalyzer = new JBossServiceXmlDetectingEntryAnalyzer();
@Test
public void jBossServiceXmlIsDetected() throws Exception {
Set<DeploymentDescriptor> analyze = this.entryAnalyzer.analyze(createFileSystemEntry("jboss-service.xml"));
assertNotNull(analyze);
assertEquals(1, analyze.size());
}
@Test
public void otherServiceXmlWithCorrectContentAreDetected() throws Exception {
Set<DeploymentDescriptor> analyze = this.entryAnalyzer.analyze(createFileSystemEntry("another-service.xml"));
assertNotNull(analyze);
assertEquals(1, analyze.size());
}
@Test
public void filesWithMatchingNameButIncorrectContentAreNotDetected() throws Exception {
Set<DeploymentDescriptor> analyze = this.entryAnalyzer.analyze(createFileSystemEntry("something-else-service.xml"));
assertNotNull(analyze);
assertEquals(0, analyze.size());
}
@Test
public void nonServiceXmlProducesEmptySet() throws Exception {
Set<DeploymentDescriptor> analyze = this.entryAnalyzer.analyze(createFileSystemEntry("/something-else.xml"));
assertNotNull(analyze);
assertEquals(0, analyze.size());
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private FileSystemEntry createFileSystemEntry(final String name) {
FileSystemEntry fileSystemEntry = mock(FileSystemEntry.class);
when(fileSystemEntry.getName()).thenReturn(name);
when(fileSystemEntry.doWithInputStream(any(Callback.class))).thenAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
InputStream in = getClass().getResourceAsStream(name);
try {
return ((Callback) invocation.getArguments()[0]).perform(in);
} finally {
IoUtils.closeQuietly(in);
}
}
});
return fileSystemEntry;
}
}
| 39.633333 | 124 | 0.736193 |
39a882e31875971a08ab462c496d4ac0bcc0ad04 | 1,728 | package com.obank.kafka.connect.cassandra;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.kafka.common.config.ConfigDef;
import org.apache.kafka.connect.connector.Task;
import org.apache.kafka.connect.sink.SinkConnector;
public class OBankCassandraSinkConnector extends SinkConnector {
private Map<String, String> configProperties;
@Override
public String version() {
return VersionUtil.getVersion();
}
@Override
public void start(Map<String, String> map) {
new OBankCassandraSinkConnectorConfig(map);
configProperties = map;
// TODO: Add things you need to do to setup your connector.
/**
* This will be executed once per connector. This can be used to handle
* connector level setup.
*/
}
@Override
public Class<? extends Task> taskClass() {
// TODO: Return your task implementation.
return OBankCassandraSinkTask.class;
}
@Override
public List<Map<String, String>> taskConfigs(int maxTasks) {
List<Map<String, String>> taskConfigs = new ArrayList<>();
Map<String, String> taskProps = new HashMap<>();
taskProps.putAll(configProperties);
for (int i = 0; i < maxTasks; i++) {
taskConfigs.add(taskProps);
}
return taskConfigs;
// TODO: Define the individual task configurations that will be executed.
/**
* This is used to schedule the number of tasks that will be running. This
* should not exceed maxTasks.
*/
}
@Override
public void stop() {
// TODO: Do things that are necessary to stop your connector.
}
@Override
public ConfigDef config() {
return OBankCassandraSinkConnectorConfig.conf();
}
}
| 24.685714 | 78 | 0.70081 |
bff5f16ba1886ec86bc9825d9a6197017ae289bb | 16,925 | package com.github.abagabagon.verifico.automation.web.selenium;
import java.util.List;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.UnexpectedTagNameException;
public class SeleniumGetCommands extends SeleniumCommands {
protected WebDriver driver;
protected Logger log;
private SeleniumWait seleniumWait;
private String retrievedValue;
public SeleniumGetCommands(WebDriver driver, SeleniumWait seleniumWait) {
super(driver, seleniumWait);
this.log = LogManager.getLogger(this.getClass());
this.driver = driver;
this.seleniumWait = seleniumWait;
}
boolean execute(GetAction getAction, WebElement element, String attribute) {
boolean actionPerformed = false;
this.retrievedValue = null;
Select select = null;
try {
switch(getAction) {
case GET_ATTRIBUTE:
retrievedValue = element.getAttribute(attribute);
break;
case GET_DROPDOWN:
select = new Select(element);
this.retrievedValue = select.getFirstSelectedOption().getText().toLowerCase();
break;
case GET_TEXT:
this.retrievedValue = element.getText().trim();
break;
default:
this.log.fatal("Unsupported User Action.");
}
actionPerformed = true;
} catch (NullPointerException e) {
this.log.warn("Unable to perform \"" + String.valueOf(getAction) + "\" for Web Element \"" + element.toString() + "\". Element created is NULL.");
this.log.debug(ExceptionUtils.getStackTrace(e));
} catch (StaleElementReferenceException e) {
this.log.warn("Unable to perform \"" + String.valueOf(getAction) + "\" for Web Element \"" + element.toString() + "\". The Web Element is no longer present in the Web Page.");
this.log.debug(ExceptionUtils.getStackTrace(e));
} catch (UnexpectedTagNameException e) {
this.log.warn("Unable to perform \"" + String.valueOf(getAction) + "\" for Web Element \"" + element.toString() + "\". Element does not have a SELECT Tag.");
this.log.debug(ExceptionUtils.getStackTrace(e));
} catch (Exception e) {
this.log.warn("Unable to perform \"" + String.valueOf(getAction) + "\" for Web Element \"" + element.toString() + "\".");
this.log.debug(ExceptionUtils.getStackTrace(e));
}
return actionPerformed;
}
String doBasicCommand(GetAction getAction, By locator, String attribute) {
boolean actionPerformed = false;
WebElement element = null;
for(int i = 1; i <= 4; i++) {
element = this.seleniumWait.waitForObjectToBePresent(locator);
actionPerformed = this.execute(getAction, element, attribute);
if (!actionPerformed) {
if(i < 4) {
this.log.debug("Retrying User Action \"" + String.valueOf(getAction) + "\" for Web Element \"" + locator.toString() + "\" " + i + "/3.");
wait(1);
} else {
this.log.error("Failed to perform User Action \"" + String.valueOf(getAction) + "\" for Web Element \"" + locator.toString() + "\".");
}
} else {
break;
}
}
return retrievedValue;
}
String doBasicCommand(GetAction getAction, By parent, By child, String attribute) {
boolean actionPerformed = false;
WebElement parentElement = null;
WebElement childElement = null;
for(int i = 1; i <= 4; i++) {
parentElement = this.seleniumWait.waitForObjectToBeVisible(parent);
childElement = this.seleniumWait.waitForNestedObjectToBePresent(parentElement, child);
actionPerformed = this.execute(getAction, childElement, attribute);
if (!actionPerformed) {
if(i < 4) {
this.log.debug("Retrying User Action \"" + String.valueOf(getAction) + "\" for Child Web Element \"" + child.toString() + "\" under Parent Web Element \"" + parent.toString() + "\" " + i + "/3.");
wait(1);
} else {
this.log.error("Failed to perform User Action \"" + String.valueOf(getAction) + "\" for Child Web Element \"" + child.toString() + "\" under Parent Web Element \"" + parent.toString() + "\".");
}
} else {
break;
}
}
return retrievedValue;
}
String doBasicCommand(GetAction getAction, By parentList, int index, By child, String attribute) {
boolean actionPerformed = false;
WebElement parentElement = null;
WebElement childElement = null;
for(int i = 1; i <= 4; i++) {
parentElement = this.seleniumWait.waitForObjectsToBeVisible(parentList).get(index);
childElement = this.seleniumWait.waitForNestedObjectToBePresent(parentElement, child);
actionPerformed = this.execute(getAction, childElement, attribute);
if (!actionPerformed) {
if(i < 4) {
this.log.debug("Retrying User Action \"" + String.valueOf(getAction) + "\" for Child Web Element \"" + child.toString() + "\" under Parent Web Element \"" + parentList.toString() + "\" " + i + "/3.");
wait(1);
} else {
this.log.error("Failed to perform User Action \"" + String.valueOf(getAction) + "\" for Child Web Element \"" + child.toString() + "\" under Parent Web Element \"" + parentList.toString() + "\".");
}
} else {
break;
}
}
return retrievedValue;
}
String doTableCommand(GetAction getAction, By parent, By rowObjectList, int index, By child, String attribute) {
boolean actionPerformed = false;
WebElement parentElement = null;
WebElement childElement = null;
for(int i = 1; i <= 4; i++) {
parentElement = this.seleniumWait.waitForNestedObjectsToBePresent(parent, rowObjectList).get(index);
childElement = this.seleniumWait.waitForNestedObjectToBePresent(parentElement, child);
actionPerformed = this.execute(getAction, childElement, attribute);
if (!actionPerformed) {
if(i < 4) {
this.log.debug("Retrying User Action \"" + String.valueOf(getAction) + "\" for Child Web Element \"" + child.toString() + "\" under Parent Web Element \"" + parent.toString() + "\" " + i + "/3.");
wait(1);
} else {
this.log.error("Failed to perform User Action \"" + String.valueOf(getAction) + "\" for Child Web Element \"" + child.toString() + "\" under Parent Web Element \"" + parent.toString() + "\".");
}
} else {
break;
}
}
return this.retrievedValue;
}
String doTableCommand(GetAction getAction, By parentList, int parentIndex, By rowObjectList, int rowIndex, By child, String attribute) {
boolean actionPerformed = false;
List<WebElement> parentElementList = null;
List<WebElement> rowChildElement = null;
WebElement childElement = null;
for(int i = 1; i <= 4; i++) {
parentElementList = this.seleniumWait.waitForObjectsToBePresent(parentList);
rowChildElement = this.seleniumWait.waitForNestedObjectsToBeVisible(parentElementList.get(parentIndex), rowObjectList);
childElement = this.seleniumWait.waitForNestedObjectToBePresent(rowChildElement.get(rowIndex), child);
this.seleniumWait.waitForObjectToBeVisible(childElement);
actionPerformed = this.execute(getAction, childElement, attribute);
if (!actionPerformed) {
if(i < 4) {
this.log.debug("Retrying User Action \"" + String.valueOf(getAction) + "\" for Child Web Element \"" + child.toString() + "\" under Parent Web Element \"" + parentList.toString() + "\" " + i + "/3.");
wait(1);
} else {
this.log.error("Failed to perform User Action \"" + String.valueOf(getAction) + "\" for Child Web Element \"" + child.toString() + "\" under Parent Web Element \"" + parentList.toString() + "\".");
}
} else {
break;
}
}
return this.retrievedValue;
}
String doTableCommandBasedOnText(GetAction getAction, By rowObjectList, By rowObjectToCheckText, String textToCheck, By rowObjectToDoActionTo, String attribute) {
List<WebElement> rows = this.seleniumWait.waitForListElement(rowObjectList);
int size = rows.size();
boolean flgTextFound = false;
String value = null;
for(int i = 1; i <= 4; i++) {
for(int j = 0; j < size; j++) {
WebElement elementToCheckText = this.seleniumWait.waitForNestedObjectToBeVisible(rowObjectList, rowObjectToCheckText, j);
String text = elementToCheckText.getText().trim();
if (text.contains(textToCheck)) {
value = this.doBasicCommand(getAction, rowObjectList, j, rowObjectToDoActionTo, attribute);
flgTextFound = true;
break;
}
}
if (!flgTextFound) {
if(i < 4) {
this.log.debug("I didn't see the text \"" + textToCheck + "\" from the Web Element: \"" + rowObjectToCheckText.toString() + "\" within one of the Rows of Web Element: \"" + rowObjectList.toString() + "\". Retrying " + i + "/3.");
wait(1);
} else {
this.log.error("I didn't see the text \"" + textToCheck + "\" from the Web Element: \"" + rowObjectToCheckText.toString() + "\" within one of the Rows of Web Element: \"" + rowObjectList.toString() + "\".");
}
} else {
break;
}
}
return value;
}
String doTableCommandBasedOnText(GetAction getAction, By parent, By rowObjectList, By rowObjectToCheckText, String textToCheck, By rowObjectToDoActionTo, String attribute) {
this.seleniumWait.waitForListElement(rowObjectList);
List<WebElement> rows = this.seleniumWait.waitForNestedObjectsToBeVisible(parent, rowObjectList);
int size = rows.size();
boolean flgTextFound = false;
String value = null;
for(int i = 1; i <= 4; i++) {
for(int j = 0; j < size; j++) {
WebElement elementToCheckText = this.seleniumWait.waitForNestedObjectToBeVisible(parent, rowObjectList, rowObjectToCheckText, j);
String text = elementToCheckText.getText().trim();
if (text.contains(textToCheck)) {
value = this.doTableCommand(getAction, parent, rowObjectList, j, rowObjectToDoActionTo, attribute);
flgTextFound = true;
break;
}
}
if (!flgTextFound) {
if(i < 4) {
this.log.debug("I didn't see the text \"" + textToCheck + "\" from the Web Element: \"" + rowObjectToCheckText.toString() + "\" within one of the Rows of Web Element: \"" + rowObjectList.toString() + "\". Retrying " + i + "/3.");
wait(1);
} else {
this.log.error("I didn't see the text \"" + textToCheck + "\" from the Web Element: \"" + rowObjectToCheckText.toString() + "\" within one of the Rows of Web Element: \"" + rowObjectList.toString() + "\".");
}
} else {
break;
}
}
return value;
}
String doTableCommandBasedOnText(GetAction getAction, By parentList, int parentIndex, By rowObjectList, By rowObjectToCheckText, String textToCheck, By rowObjectToDoActionTo, String attribute) {
this.seleniumWait.waitForListElement(rowObjectList);
List<WebElement> parentElementList = this.seleniumWait.waitForListElement(parentList);
List<WebElement> rows = this.seleniumWait.waitForNestedObjectsToBeVisible(parentElementList.get(parentIndex), rowObjectList);
int size = rows.size();
boolean flgTextFound = false;
String value = null;
for(int i = 1; i <= 4; i++) {
for(int j = 0; j < size; j++) {
WebElement elementToCheckText = this.seleniumWait.waitForNestedObjectToBeVisible(parentElementList.get(parentIndex), rowObjectList, rowObjectToCheckText, j);
String text = elementToCheckText.getText().trim();
if (text.contains(textToCheck)) {
value = this.doTableCommand(getAction, parentList, parentIndex, rowObjectList, j, rowObjectToDoActionTo, attribute);
flgTextFound = true;
break;
}
}
if (!flgTextFound) {
if(i < 4) {
this.log.debug("I didn't see the text \"" + textToCheck + "\" from the Web Element: \"" + rowObjectToCheckText.toString() + "\" within one of the Rows of Web Element: \"" + rowObjectList.toString() + "\". Retrying " + i + "/3.");
wait(1);
} else {
this.log.error("I didn't see the text \"" + textToCheck + "\" from the Web Element: \"" + rowObjectToCheckText.toString() + "\" within one of the Rows of Web Element: \"" + rowObjectList.toString() + "\".");
}
} else {
break;
}
}
return value;
}
String doTableCommandBasedOnAttributeValue(GetAction getAction, By rowObjectList, By rowObjectToCheckAttributeValue, String attributeToCheck, String valueToCheck, By rowObjectToDoActionTo, String attribute) {
List<WebElement> rows = this.seleniumWait.waitForListElement(rowObjectList);
int size = rows.size();
boolean flgTextFound = false;
String value = null;
for(int i = 1; i <= 4; i++) {
for(int j = 0; j < size; j++) {
WebElement elementToCheckText = this.seleniumWait.waitForNestedObjectToBeVisible(rowObjectList, rowObjectToCheckAttributeValue, j);
String text = elementToCheckText.getAttribute(attributeToCheck).trim();
if (text.contains(valueToCheck)) {
value = this.doBasicCommand(getAction, rowObjectList, j, rowObjectToDoActionTo, attribute);
flgTextFound = true;
break;
}
}
if (!flgTextFound) {
if(i < 4) {
this.log.debug("I didn't see the \"" + attribute + "\" attribute value \"" + valueToCheck + "\" from the Web Element: \"" + rowObjectToCheckAttributeValue.toString() + "\" within one of the Rows of Web Element: \"" + rowObjectList.toString() + "\". Retrying " + i + "/3.");
wait(1);
} else {
this.log.error("I didn't see the \"" + attribute + "\" attribute value \"" + valueToCheck + "\" from the Web Element: \"" + rowObjectToCheckAttributeValue.toString() + "\" within one of the Rows of Web Element: \"" + rowObjectList.toString() + "\".");
}
} else {
break;
}
}
return value;
}
String doTableCommandBasedOnAttributeValue(GetAction getAction, By parent, By rowObjectList, By rowObjectToCheckAttributeValue, String attributeToCheck, String valueToCheck, By rowObjectToDoActionTo, String attribute) {
this.seleniumWait.waitForListElement(rowObjectList);
List<WebElement> rows = this.seleniumWait.waitForNestedObjectsToBeVisible(parent, rowObjectList);
int size = rows.size();
boolean flgTextFound = false;
String value = null;
for(int i = 1; i <= 4; i++) {
for(int j = 0; j < size; j++) {
WebElement elementToCheckText = this.seleniumWait.waitForNestedObjectToBeVisible(parent, rowObjectList, rowObjectToCheckAttributeValue, j);
String text = elementToCheckText.getAttribute(attribute).trim();
if (text.contains(valueToCheck)) {
value = this.doTableCommand(getAction, parent, rowObjectList, j, rowObjectToDoActionTo, attribute);
flgTextFound = true;
break;
}
}
if (!flgTextFound) {
if(i < 4) {
this.log.debug("I didn't see the \"" + attribute + "\" attribute value \"" + valueToCheck + "\" from the Web Element: \"" + rowObjectToCheckAttributeValue.toString() + "\" within one of the Rows of Web Element: \"" + rowObjectList.toString() + "\". Retrying " + i + "/3.");
wait(1);
} else {
this.log.error("I didn't see the \"" + attribute + "\" attribute value \"" + valueToCheck + "\" from the Web Element: \"" + rowObjectToCheckAttributeValue.toString() + "\" within one of the Rows of Web Element: \"" + rowObjectList.toString() + "\".");
}
} else {
break;
}
}
return value;
}
String doTableCommandBasedOnAttributeValue(GetAction getAction, By parentList, int parentIndex, By rowObjectList, By rowObjectToCheckAttributeValue, String attributeToCheck, String valueToCheck, By rowObjectToDoActionTo, String attribute) {
this.seleniumWait.waitForListElement(rowObjectList);
List<WebElement> parentElementList = this.seleniumWait.waitForObjectsToBeVisible(parentList);
List<WebElement> rows = this.seleniumWait.waitForNestedObjectsToBeVisible(parentElementList.get(parentIndex), rowObjectList);
int size = rows.size();
boolean flgTextFound = false;
String value = null;
for(int i = 1; i <= 4; i++) {
for(int j = 0; j < size; j++) {
WebElement elementToCheckText = this.seleniumWait.waitForNestedObjectToBeVisible(parentElementList.get(parentIndex), rowObjectList, rowObjectToCheckAttributeValue, j);
String text = elementToCheckText.getAttribute(attribute).trim();
if (text.contains(valueToCheck)) {
value = this.doTableCommand(getAction, parentList, parentIndex, rowObjectList, j, rowObjectToDoActionTo, attribute);
flgTextFound = true;
break;
}
}
if (!flgTextFound) {
if(i < 4) {
this.log.debug("I didn't see the \"" + attribute + "\" attribute value \"" + valueToCheck + "\" from the Web Element: \"" + rowObjectToCheckAttributeValue.toString() + "\" within one of the Rows of Web Element: \"" + rowObjectList.toString() + "\". Retrying " + i + "/3.");
wait(1);
} else {
this.log.error("I didn't see the \"" + attribute + "\" attribute value \"" + valueToCheck + "\" from the Web Element: \"" + rowObjectToCheckAttributeValue.toString() + "\" within one of the Rows of Web Element: \"" + rowObjectList.toString() + "\".");
}
} else {
break;
}
}
return value;
}
} | 47.542135 | 279 | 0.688154 |
c770bc8578ac1d85d95fb262f7cc7c40e306c5f1 | 3,020 | /**
* Copyright 2010-2016 the original author or authors.
*
* 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.uorm.orm.mapping;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Types;
import java.util.Map;
import org.uorm.orm.annotation.ClassMapping;
import org.uorm.orm.annotation.FieldMapping;
/**
*
* @author <a href="mailto:[email protected]">郭训常</a>
* @version 1.0.0
* ===================================<br/>
* 修订日期 修订人 描述<br/>
* 2012-1-18 郭训常 创建<br/>
*/
public interface IObjectReader {
/**
* read ResultSet to Class cls instance
* @param <T>
* @param cls
* @param result
* @param rsmd
* @return
* @throws Exception
*/
public <T> T read(Class<T> cls, ResultSet result, ResultSetMetaData rsmd) throws Exception;
/**
* read object value to map, key is table colName
* @param pojo
* @return
* @throws Exception
*/
public Map<String, Object> readValue2Map(Object pojo) throws Exception;
/**
* write pk value to object
* @param pojo
* @param pkcolumnName
* @return
* @throws Exception
*/
public boolean writePkVal2Pojo(Object pojo, Object pkval, String pkcolumnName) throws Exception;
/**
* read ResultSet to Map
* @param rs
* @param rsmd
* @return
* @throws Exception
*/
public Map<String, Object> readToMap(ResultSet rs, ResultSetMetaData rsmd) throws Exception;
/**
* read ResultSet to Object[]
* @param rs
* @param rsmd
* @return
* @throws Exception
*/
public Object[] readToArray(ResultSet rs, ResultSetMetaData rsmd) throws Exception;
/**
* get class mapping info
* @param <T>
* @param cls
* @return
*/
public <T> ClassMapping getClassMapping(Class<T> cls);
/**
* get cls mapping table's primary keys, order by @param keyOrder
* @param cls
* @param keyOrder
* @return
*/
public FieldMapping[] getClassPrimaryKeys(Class<?> cls, String keyOrder);
/**
* get object FieldMapping info
* @param cls
* @return
*/
public Map<String, FieldMapping> getObjectFieldMap(Class<?> cls);
/**
* get target sql class by SQL types
* @param sqlType: SQL type: @see {@link Types}
* @return
*/
public Class<?> getTargetSqlClass(int sqlType);
}
| 26.26087 | 97 | 0.677483 |
595874a78a015843003a16673525bbb0c3d18c5c | 181 | package com.github.taymindis.nio.channeling.http;
public enum HttpResponseType {
PENDING,
TRANSFER_CHUNKED,
CONTENT_LENGTH,
PARTIAL_CONTENT // Not supporting yet
}
| 20.111111 | 49 | 0.751381 |
0c2a3c92659f0a405b16971d6627f06e346805d0 | 31,188 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.modules.vcs.profiles.vss.list;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import org.netbeans.modules.vcscore.Variables;
import org.netbeans.modules.vcscore.VcsDirContainer;
import org.netbeans.modules.vcscore.VcsFileSystem;
import org.netbeans.modules.vcscore.cmdline.VcsListRecursiveCommand;
import org.netbeans.modules.vcscore.commands.CommandDataOutputListener;
import org.netbeans.modules.vcscore.commands.CommandOutputListener;
import org.netbeans.modules.vcscore.commands.VcsCommand;
import org.netbeans.modules.vcscore.commands.VcsCommandExecutor;
import org.netbeans.modules.vcscore.util.VcsUtilities;
import org.netbeans.modules.vcs.profiles.vss.commands.GetAdjustedRelevantMasks;
import org.netbeans.modules.vcs.profiles.vss.commands.GetInitializationVariable;
/**
* The recursive refresh command.
* Runs "ss diff -R" and "ss status -R" commands.
*
* @author Martin Entlicher
*/
public class VssListRecursive extends VcsListRecursiveCommand implements CommandDataOutputListener {
private static final String DIFFING_ENG = "Diffing:"; // NOI18N
private static final String DIFFING_LOC = org.openide.util.NbBundle.getBundle(VssListRecursive.class).getString("VSS_ProjectDiffing"); // NOI18N
private static final String AGAINST_ENG = "Against:"; // NOI18N
private static final String AGAINST_LOC = org.openide.util.NbBundle.getBundle(VssListRecursive.class).getString("VSS_ProjectAgainst"); // NOI18N
private static final int LINE_LENGTH = 79;
private String dir = null; // The local dir being refreshed.
private String relDir = null;
private CommandOutputListener stdoutNRListener = null;
private CommandOutputListener stderrNRListener = null;
private CommandDataOutputListener stdoutListener = null;
private CommandDataOutputListener stderrListener = null;
private String dataRegex = null;
private String errorRegex = null;
private VcsFileSystem fileSystem;
private VcsDirContainer rootFilesByNameCont;
private List undistiguishable = new ArrayList();
private Pattern maskRegExpPositive;
private Pattern maskRegExpNegative;
private String PROJECT_BEGIN, PROJECT_PATH, LOCAL_FILES, SOURCE_SAFE_FILES, DIFFERENT_FILES;
private String DIFFING, AGAINST;
/** Creates a new instance of VssListRecursive */
public VssListRecursive() {
}
public void setFileSystem(VcsFileSystem fileSystem) {
this.fileSystem = fileSystem;
}
private void initDir(Hashtable vars) {
String rootDir = (String) vars.get("ROOTDIR");
if (rootDir == null) {
rootDir = ".";
vars.put("ROOTDIR",".");
}
this.dir = (String) vars.get("DIR");
if (this.dir == null) {
this.dir = "";
vars.put("DIR","");
}
String module = (String) vars.get("MODULE"); // NOI18N
//D.deb("rootDir = "+rootDir+", module = "+module+", dir = "+dir); // NOI18N
String ps = (String) vars.get("PS");
if (ps == null) ps = File.separator;
else ps = Variables.expand(vars, ps, false);
relDir = new String(dir);
if (dir.equals("")) { // NOI18N
dir=rootDir;
if (module != null && module.length() > 0) {
dir += ps + module;
relDir = new String(module);
}
} else {
if (module == null || module.length() == 0)
dir=rootDir+ps+dir;
else {
dir=rootDir+ps+module+ps+dir;
relDir = new String(module+ps+relDir);
}
}
dir = rootDir;
if (dir.charAt(dir.length() - 1) == File.separatorChar) {
dir = dir.substring(0, dir.length() - 1);
}
relDir = "";//relDir.replace(ps.charAt(0), '/');
}
private boolean runCommand(Hashtable vars, String cmdName, final boolean[] errMatch,
CommandDataOutputListener outputListener) throws InterruptedException {
String workingDirPath = "${ROOTDIR}${PS}${MODULE}${PS}${DIR}"; // NOI18N
workingDirPath = Variables.expand(vars, workingDirPath, false);
File workingDir = new File(workingDirPath);
File tmpEmptyDir = null;
if (!workingDir.exists()) {
File tmpDir = new File(System.getProperty("java.io.tmpdir"));
String tmpDirName = "refresh"; // NOI18N
for (int i = 0; ; i++) {
tmpEmptyDir = new File(tmpDir, tmpDirName + i);
if (!tmpEmptyDir.exists()) {
tmpEmptyDir.mkdir();
break;
}
}
vars.put("EMPTY_REFRESH_FOLDER", tmpEmptyDir.getAbsolutePath());
}
try {
VcsCommand cmd = fileSystem.getCommand(cmdName);
VcsCommandExecutor ec = fileSystem.getVcsFactory().getCommandExecutor(cmd, vars);
ec.addDataOutputListener(outputListener);
if (errMatch != null && errMatch.length > 0) {
ec.addDataErrorOutputListener(new CommandDataOutputListener() {
public void outputData(String[] data) {
if (data != null) errMatch[0] = true;
}
});
}
ec.addErrorOutputListener(new CommandOutputListener() {
public void outputLine(String line) {
stderrNRListener.outputLine(line);
}
});
fileSystem.getCommandsPool().preprocessCommand(ec, vars, fileSystem);
fileSystem.getCommandsPool().startExecutor(ec);
try {
fileSystem.getCommandsPool().waitToFinish(ec);
} catch (InterruptedException iexc) {
fileSystem.getCommandsPool().kill(ec);
throw iexc;
}
return (ec.getExitStatus() == VcsCommandExecutor.SUCCEEDED);
} finally {
if (tmpEmptyDir != null) {
tmpEmptyDir.delete();
}
}
}
/**
* List files of CVS Repository recursively.
* @param vars Variables used by the command
* @param args Command-line arguments
* @param filesByNameCont listing of files with statuses. For each directory there is a <code>Hashtable</code>
* with files.
* @param stdoutNRListener listener of the standard output of the command
* @param stderrNRListener listener of the error output of the command
* @param stdoutListener listener of the standard output of the command which
* satisfies regex <CODE>dataRegex</CODE>
* @param dataRegex the regular expression for parsing the standard output
* @param stderrListener listener of the error output of the command which
* satisfies regex <CODE>errorRegex</CODE>
* @param errorRegex the regular expression for parsing the error output
*/
public boolean listRecursively(Hashtable vars, String[] args, VcsDirContainer filesByNameCont,
CommandOutputListener stdoutNRListener,
CommandOutputListener stderrNRListener,
CommandDataOutputListener stdoutListener, String dataRegex,
CommandDataOutputListener stderrListener, String errorRegex) {
this.stdoutNRListener = stdoutNRListener;
this.stderrNRListener = stderrNRListener;
this.stdoutListener = stdoutListener;
this.stderrListener = stderrListener;
this.dataRegex = dataRegex;
this.errorRegex = errorRegex;
this.rootFilesByNameCont = filesByNameCont;
boolean localized = false;
if (args.length > 1 && VssListCommand.ARG_LOC.equals(args[0])) {
localized = true;
String[] newArgs = new String[args.length - 1];
System.arraycopy(args, 1, newArgs, 0, newArgs.length);
args = newArgs;
}
if (args.length < 3) {
stderrNRListener.outputLine("Expecting three commands as arguments: directory reader, directory status reader and file status reader."); //NOI18N
return false;
}
PROJECT_BEGIN = (localized) ? VssListCommand.PROJECT_BEGIN_LOC : VssListCommand.PROJECT_BEGIN_ENG;
LOCAL_FILES = (localized) ? VssListCommand.LOCAL_FILES_LOC : VssListCommand.LOCAL_FILES_ENG;
SOURCE_SAFE_FILES = (localized) ? VssListCommand.SOURCE_SAFE_FILES_LOC : VssListCommand.SOURCE_SAFE_FILES_ENG;
DIFFERENT_FILES = (localized) ? VssListCommand.DIFFERENT_FILES_LOC : VssListCommand.DIFFERENT_FILES_ENG;
DIFFING = (localized) ? DIFFING_LOC : DIFFING_ENG;
AGAINST = (localized) ? AGAINST_LOC : AGAINST_ENG;
PROJECT_PATH = (String) vars.get("PROJECT");
initDir(vars);
String ssDir = (String) vars.get("ENVIRONMENT_VAR_SSDIR"); // NOI18N
String userName = (String) vars.get("USER_NAME"); // NOI18N
if (userName == null || userName.length() == 0) {
userName = System.getProperty("user.name");
}
String relevantMasks;
try {
relevantMasks = GetInitializationVariable.getVariable(ssDir, userName, GetAdjustedRelevantMasks.RELEVANT_MASKS);
} catch (IOException ioex) {
relevantMasks = null;
}
Pattern[] regExpPositivePtr = new Pattern[] { null };
Pattern[] regExpNegativePtr = new Pattern[] { null };
VssListCommand.createMaskRegularExpressions(relevantMasks, regExpPositivePtr, regExpNegativePtr);
this.maskRegExpPositive = regExpPositivePtr[0];
this.maskRegExpNegative = regExpNegativePtr[0];
readLocalFiles(rootFilesByNameCont.getPath(), rootFilesByNameCont);
boolean[] errMatch = new boolean[1];
try {
runCommand(vars, args[0], errMatch, this);
} catch (InterruptedException iexc) {
return false;
}
if (!errMatch[0]) {
flushLastFile();
try {
projectPathContinued = null;
runCommand(vars, args[1], errMatch, new CommandDataOutputListener() {
public void outputData(String[] elements) {
statusOutputData(elements);
}
});
} catch (InterruptedException iexc) {
return false;
}
if (!errMatch[0] && undistiguishable.size() > 0) {
try {
processUndistinguishableFiles(vars, args[2]);
} catch (InterruptedException iexc) {
return false;
}
}
}
printOutputData(rootFilesByNameCont);
return !errMatch[0];
}
private void printOutputData(VcsDirContainer filesByNameCont) {
stdoutListener.outputData(new String[] { "Path:", filesByNameCont.getPath() });
Hashtable filesByName = (Hashtable) filesByNameCont.getElement();
if (filesByName != null) {
for (Iterator it = filesByName.values().iterator(); it.hasNext(); ) {
String[] statuses = (String[]) it.next();
stdoutListener.outputData(statuses);
}
}
VcsDirContainer[] subCont = filesByNameCont.getSubdirContainers();
for (int i = 0; i < subCont.length; i++) {
printOutputData(subCont[i]);
}
}
private void processUndistinguishableFiles(Hashtable vars, String cmdName) throws InterruptedException {
VcsCommand cmd = fileSystem.getCommand(cmdName);
if (cmd != null) {
String psStr = (String) vars.get("PS");
char ps;
if (psStr == null) ps = File.separatorChar;
else {
psStr = Variables.expand(vars, psStr, false);
ps = psStr.charAt(0);
}
for (Iterator it = undistiguishable.iterator(); it.hasNext(); ) {
String filePath = (String) it.next();
int slashIndex = filePath.lastIndexOf('/');
String path = filePath.substring(0, slashIndex);
String pattern = filePath.substring(slashIndex + 1);
VcsDirContainer filesByNameCont = (path.length() > 0) ? rootFilesByNameCont.getContainerWithPath(path) : rootFilesByNameCont;
if (filesByNameCont == null) continue;
Hashtable filesByName = (Hashtable) filesByNameCont.getElement();
Hashtable varsCmd = new Hashtable(vars);
varsCmd.put("DIR", path.replace('/', ps));
varsCmd.put("MODULE", relDir);
String[] files = getUndistinguishableFiles(pattern, filesByName.keySet());
for (int i = 0; i < files.length; i++) {
String file = files[i];
varsCmd.put("FILE", file);
final String[] statuses = (String[]) filesByName.get(file);
//cmd.setProperty(UserCommand.PROPERTY_DATA_REGEX, "^"+file.substring(0, Math.min(STATUS_POSITION, file.length()))+" (.*$)");
statuses[2] = null;
VcsCommandExecutor vce = fileSystem.getVcsFactory().getCommandExecutor(cmd, varsCmd);
vce.addDataOutputListener(new CommandDataOutputListener() {
public void outputData(String[] elements) {
if (elements != null) {
//D.deb(" **** status match = "+VcsUtilities.arrayToString(elements));
if (elements[0].indexOf(PROJECT_BEGIN) == 0) return ; // skip the $/... folder
if (statuses[2] != null) return ; // The status was already set and we get some garbage
VssListCommand.addStatuses(elements, statuses);
}
}
});
fileSystem.getCommandsPool().preprocessCommand(vce, varsCmd, fileSystem);
fileSystem.getCommandsPool().startExecutor(vce);
try {
fileSystem.getCommandsPool().waitToFinish(vce);
} catch (InterruptedException iexc) {
fileSystem.getCommandsPool().kill(vce);
throw iexc;
}
}
}
}
}
private String[] getUndistinguishableFiles(String pattern, Collection allFiles) {
List files = new ArrayList();
for (Iterator it = allFiles.iterator(); it.hasNext(); ) {
String file = (String) it.next();
if (file.startsWith(pattern)) {
files.add(file);
}
}
return (String[]) files.toArray(new String[0]);
}
private VcsDirContainer getFilesContainer(String path) {
VcsDirContainer filesContainer;
if (path.length() == 0) {
filesContainer = rootFilesByNameCont;
} else {
filesContainer = rootFilesByNameCont.getContainerWithPath(path);
if (filesContainer == null) {
filesContainer = rootFilesByNameCont.addSubdirRecursive(path);
}
}
if (filesContainer.getElement() == null) {
filesContainer.setElement(new Hashtable());
}
return filesContainer;
}
private void readLocalFiles(String path, VcsDirContainer filesCont) {
File fileDir = (path.length() > 0) ? new File(dir, path) : new File(dir);
Hashtable filesByName = (Hashtable) filesCont.getElement();
if (filesByName == null) {
filesByName = new Hashtable();
filesCont.setElement(filesByName);
}
String[] subFiles = fileDir.list();
if (subFiles == null) return ;
//File ignoredFile = new File(dir, VssListCommand.IGNORED_FILE);
for (int i = 0; i < subFiles.length; i++) {
String fileName = subFiles[i];
File file = new File(fileDir, fileName);
if (file.isFile()) {
if (!VssListCommand.IGNORED_FILE.equalsIgnoreCase(fileName) &&
(maskRegExpPositive == null || maskRegExpPositive.matcher(fileName).matches()) &&
(maskRegExpNegative == null || !maskRegExpNegative.matcher(fileName).matches())) {
String[] statuses = (String[]) filesByName.get(fileName);
if (statuses == null) {
statuses = new String[3];
}
statuses[0] = fileName;
statuses[1] = VssListCommand.STATUS_CURRENT;
filesByName.put(fileName, statuses);
}
}
}
String cpath = filesCont.getPath();
if (cpath.length() > 0) {
int slashIndex = cpath.lastIndexOf('/');
if (slashIndex < 0) slashIndex = 0;
String dirParent = cpath.substring(0, slashIndex);
if (slashIndex > 0) slashIndex++;
String dirName = cpath.substring(slashIndex) + '/';
VcsDirContainer parentCont = rootFilesByNameCont.getContainerWithPath(dirParent);
if (parentCont != null && parentCont.getPath().equals(filesCont.getPath())) parentCont = null;
if (parentCont != null) {
filesByName = (Hashtable) parentCont.getElement();
if (filesByName != null) {
String[] statuses = new String[3];
statuses[0] = dirName;
if (fileDir.exists()) {
statuses[1] = VssListCommand.STATUS_CURRENT;
} else {
statuses[1] = VssListCommand.STATUS_MISSING;
}
filesByName.put(dirName, statuses);
}
}
}
}
private boolean gettingFolders = true;
private boolean gettingLocalFiles = false;
private boolean gettingSourceSafeFiles = false;
private boolean gettingDifferentFiles = false;
private String lastFileName = "";
private String diffingFolder;
private VcsDirContainer lastFilesCont = null;
private void removeLocalFiles() {
//System.out.println("REMOVE LOCAL FILES: lastFileName = '"+lastFileName+"', lastFilesCont = "+lastFilesCont);
if (lastFileName == null || lastFilesCont == null) return ;
Hashtable filesByName = (Hashtable) lastFilesCont.getElement();
Collection currentFiles = filesByName.keySet();
while (lastFileName.length() > 0) {
String fileName = VssListCommand.getFileFromRow(currentFiles, lastFileName);
currentFiles.remove(fileName.trim());
//System.out.println(" removed: '"+fileName.trim()+"'");
lastFileName = lastFileName.substring(fileName.length());
}
}
private void flushLastFile() {
//System.out.println("FLUSING LAST FILE: lastFileName = '"+lastFileName+"', lastFilesCont = "+lastFilesCont);
if (lastFileName == null || lastFileName.length() == 0 || lastFilesCont == null) return ;
if (gettingSourceSafeFiles) {
Hashtable filesByName = (Hashtable) lastFilesCont.getElement();
String fileName = lastFileName.trim();
String[] statuses = (String[]) filesByName.get(fileName);
if (statuses == null) {
statuses = new String[3];
statuses[0] = fileName;
}
filesByName.put(fileName, statuses);
statuses[1] = VssListCommand.STATUS_MISSING;
//System.out.println("FLUSHING FILE: "+java.util.Arrays.asList(statuses));
lastFileName = "";
} else if (gettingDifferentFiles) {
Hashtable filesByName = (Hashtable) lastFilesCont.getElement();
String fileName = lastFileName.trim();
String[] statuses = (String[]) filesByName.get(fileName);
if (statuses == null) {
statuses = new String[3];
statuses[0] = fileName;
}
filesByName.put(fileName, statuses);
statuses[1] = VssListCommand.STATUS_LOCALLY_MODIFIED;
//System.out.println("FLUSHING FILE: "+java.util.Arrays.asList(statuses));
lastFileName = "";
} else if (gettingLocalFiles) {
removeLocalFiles();
}
}
private boolean diffingPathFollows = false;
private String projectPathContinued = null;
/** Parse the output of "ss dir -R -F- && ss diff -R" commands
* ss dir -R -F- gives the subfolders in the given folder
* ss diff -R gives the differences between the local folders and the repository.
*/
public void outputData(String[] elements) {
String line = elements[0];
//System.out.println("outputData("+line+")");
if (line == null) return;
String file = line.trim();
if (!diffingPathFollows && (projectPathContinued != null || file.startsWith(PROJECT_PATH))) { // Listing of a folder from "dir" will follow
String folder;
if (projectPathContinued != null) {
folder = projectPathContinued + file;
} else {
folder = file.substring(PROJECT_PATH.length());
}
if (folder.endsWith(":")) {
folder = folder.substring(0, folder.length() - 1);
projectPathContinued = null;
} else {
projectPathContinued = folder;
if (line.length() < LINE_LENGTH) {
// If the line is broken sooner, it's most probably at a space!
projectPathContinued += " ";
}
return ;
}
folder = folder.replace(File.separatorChar, '/');
if (folder.startsWith(relDir)) {
folder = folder.substring(relDir.length());
if (folder.startsWith("/")) folder = folder.substring(1);
}
gettingFolders = true;
lastFilesCont = getFilesContainer(folder);
} else if (gettingFolders && file.startsWith("$")) { // A folder
String folder = file.substring(1);
folder = folder.replace(File.separatorChar, '/');
folder = (lastFilesCont != null && lastFilesCont.getPath().length() > 0) ? (lastFilesCont.getPath() + '/' + folder) : folder;
VcsDirContainer subDir;
if (lastFilesCont != null) {
subDir = lastFilesCont.addSubdir(folder);
} else {
subDir = rootFilesByNameCont.addSubdir(folder);
}
readLocalFiles(folder, subDir);
} else if (file.startsWith(AGAINST) && diffingPathFollows) {
diffingFolder = diffingFolder.trim();
diffingFolder = diffingFolder.substring(PROJECT_PATH.length()); // remove "/$"
diffingFolder = diffingFolder.replace(File.separatorChar, '/');
if (diffingFolder.startsWith(relDir)) {
diffingFolder = diffingFolder.substring(relDir.length());
if (diffingFolder.startsWith("/")) diffingFolder = diffingFolder.substring(1);
}
lastFilesCont = getFilesContainer(diffingFolder);
//System.out.println("AGAINST, end diffing folder '"+diffingFolder+"'");
diffingPathFollows = false;
gettingLocalFiles = false;
gettingSourceSafeFiles = false;
gettingDifferentFiles = false;
} else if (file.startsWith(DIFFING) || diffingPathFollows) {
//System.out.print("DIFFING: '");
flushLastFile();
gettingFolders = false;
// The folder might be divided !!! Like: Diffing: $/Java Project '\n'1/src/...
if (diffingPathFollows) {
diffingFolder += file;
} else {
diffingFolder = file.substring(DIFFING.length()) + " ";
// If the name contains a space, the line is broken at that space
// If not, it's trimmed
}
//System.out.println(""+diffingFolder+"");
diffingPathFollows = true;
} else if (LOCAL_FILES.equals(file)) {
//System.out.println("getting local files...");
gettingLocalFiles = true;
} else if (SOURCE_SAFE_FILES.equals(file)) {
//System.out.println("getting source safe files...");
flushLastFile();
gettingLocalFiles = false;
gettingDifferentFiles = false;
gettingSourceSafeFiles = true;
} else if (DIFFERENT_FILES.equals(file)) {
//System.out.println("getting different files...");
flushLastFile();
gettingLocalFiles = false;
gettingSourceSafeFiles = false;
gettingDifferentFiles = true;
} else if (line.trim().length() == 0) {
if (lastFileName.length() > 0) {
flushLastFile();
gettingLocalFiles = false;
gettingSourceSafeFiles = false;
gettingDifferentFiles = false;
}
} else if (gettingLocalFiles) {
lastFileName += line;
} else if (gettingSourceSafeFiles || gettingDifferentFiles) {
if (line.startsWith(" ")) {
flushLastFile();
}
lastFileName += line;
}
}
private boolean skipNextLine = false;
private void statusOutputData(String[] elements) {
if (elements[0] == null) return;
String file = elements[0].trim();
if (projectPathContinued != null || file.startsWith(PROJECT_PATH)) { // Listing of a folder from "dir" will follow
String folder;
if (projectPathContinued != null) {
folder = projectPathContinued + file;
} else {
folder = file.substring(PROJECT_PATH.length());
}
if (folder.endsWith(":")) {
folder = folder.substring(0, folder.length() - 1);
projectPathContinued = null;
} else {
projectPathContinued = folder;
if (file.length() < LINE_LENGTH) {
// If the line is broken sooner, it's most probably at a space!
projectPathContinued += " ";
}
return ;
}
folder = folder.replace(File.separatorChar, '/');
if (folder.startsWith(relDir)) {
folder = folder.substring(relDir.length());
if (folder.startsWith("/")) folder = folder.substring(1);
}
gettingFolders = true;
lastFilesCont = getFilesContainer(folder);
skipNextLine = false;
} else if (!skipNextLine) {
int index = Math.min(VssListCommand.STATUS_POSITION + 1, elements[0].length());
int index2 = elements[0].indexOf(" ", index);
if (index2 < 0) index2 = elements[0].length();
if (index < index2) {
skipNextLine = true;
Hashtable filesByName = (Hashtable) lastFilesCont.getElement();
String pattern = elements[0].substring(0, VssListCommand.STATUS_POSITION).trim();
file = getDistinguishable(pattern, filesByName.keySet());
if (file != null) {
String[] statuses = (String[]) filesByName.get(file);
statuses[2] = VssListCommand.addLocker(statuses[2], VssListCommand.parseLocker(elements[0].substring(index, index2).trim()));
} else {
String patternPath = lastFilesCont.getPath()+"/"+pattern;
if (!undistiguishable.contains(patternPath)) {
undistiguishable.add(patternPath);
}
}
}
} else {
skipNextLine = false;
}
}
private static String getDistinguishable(String pattern, Set files) {
String file = null;
for (Iterator it = files.iterator(); it.hasNext(); ) {
String fileName = (String) it.next();
if (pattern.equals(fileName.substring(0, Math.min(VssListCommand.STATUS_POSITION, fileName.length())).trim())) {
if (file != null) {
return null;
} else {
file = fileName;
}
}
}
return file;
}
}
| 46.618834 | 157 | 0.585417 |
dba6569a09257ba3934f71efef1c9abaef0d8c72 | 2,426 | /* 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.camunda.bpm.engine.rest.util.migration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MigrationPlanDtoBuilder {
public static final String PROP_SOURCE_PROCESS_DEFINITION_ID = "sourceProcessDefinitionId";
public static final String PROP_TARGET_PROCESS_DEFINITION_ID = "targetProcessDefinitionId";
public static final String PROP_INSTRUCTIONS = "instructions";
protected final Map<String, Object> migrationPlan;
public MigrationPlanDtoBuilder(String sourceProcessDefinitionId, String targetProcessDefinitionId) {
migrationPlan = new HashMap<String, Object>();
migrationPlan.put(PROP_SOURCE_PROCESS_DEFINITION_ID, sourceProcessDefinitionId);
migrationPlan.put(PROP_TARGET_PROCESS_DEFINITION_ID, targetProcessDefinitionId);
}
public MigrationPlanDtoBuilder instructions(List<Map<String, Object>> instructions) {
migrationPlan.put(PROP_INSTRUCTIONS, instructions);
return this;
}
public MigrationPlanDtoBuilder instruction(String sourceActivityId, String targetActivityId) {
return instruction(sourceActivityId, targetActivityId, null);
}
public MigrationPlanDtoBuilder instruction(String sourceActivityId, String targetActivityId, Boolean updateEventTrigger) {
List<Map<String, Object>> instructions = (List<Map<String, Object>>) migrationPlan.get(PROP_INSTRUCTIONS);
if (instructions == null) {
instructions = new ArrayList<Map<String, Object>>();
migrationPlan.put(PROP_INSTRUCTIONS, instructions);
}
Map<String, Object> migrationInstruction = new MigrationInstructionDtoBuilder()
.migrate(sourceActivityId, targetActivityId, updateEventTrigger)
.build();
instructions.add(migrationInstruction);
return this;
}
public Map<String, Object> build() {
return migrationPlan;
}
}
| 37.90625 | 124 | 0.774938 |
c5536f115d120ca3cc6ca3eb107544323b3cb8c0 | 490 | package com.jiuzhang.flashsale.exception;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@EqualsAndHashCode(callSuper = false)
public class RedisStockException extends RedisException {
private static final long serialVersionUID = 1L;
private Long activityId;
public RedisStockException(Long activityId, String message) {
this.activityId = activityId;
this.setMessage(message + "\n" + this.toString());
}
}
| 22.272727 | 65 | 0.746939 |
11a8bb4bba82617a0dd5f997b67ba7f2ec38f9ba | 3,106 | /**
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
* This file is part of the Smart Developer Hub Project:
* http://www.smartdeveloperhub.org/
*
* Center for Open Middleware
* http://www.centeropenmiddleware.com/
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
* Copyright (C) 2015-2016 Center for Open Middleware.
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
* 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.
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
* Artifact : org.smartdeveloperhub.curator:sdh-curator-connector:0.2.0
* Bundle : sdh-curator-connector-0.2.0.jar
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
*/
package org.smartdeveloperhub.curator.connector;
import java.io.IOException;
import org.smartdeveloperhub.curator.connector.BrokerController.Cleaner;
import com.rabbitmq.client.Channel;
final class CleanerFactory {
private static final class UnbindQueueCleaner implements Cleaner {
private final String exchangeName;
private final String queueName;
private final String routingKey;
private UnbindQueueCleaner(final String exchangeName, final String queueName, final String routingKey) {
this.exchangeName = exchangeName;
this.queueName = queueName;
this.routingKey = routingKey;
}
@Override
public void clean(final Channel channel) throws IOException {
channel.queueUnbind(this.queueName,this.exchangeName,this.routingKey);
}
@Override
public String toString() {
return "Unbind queue '"+this.queueName+"' from exchange '"+this.exchangeName+"' and routing key '"+this.routingKey+"'";
}
}
private static final class DeleteQueueCleaner implements Cleaner {
private final String queueName;
private DeleteQueueCleaner(final String queueName) {
this.queueName = queueName;
}
@Override
public void clean(final Channel channel) throws IOException {
channel.queueDelete(this.queueName);
}
@Override
public String toString() {
return "Delete queue '"+this.queueName+"'";
}
}
private CleanerFactory() {
}
static Cleaner queueDelete(final String queueName) {
return new DeleteQueueCleaner(queueName);
}
static Cleaner queueUnbind(final String exchangeName, final String queueName, final String routingKey) {
return new UnbindQueueCleaner(exchangeName, queueName, routingKey);
}
}
| 34.131868 | 123 | 0.624276 |
5290324bb90eb69abe85727f5aaba1ad76757928 | 6,359 | /*
* Copyright 2020 Arthur Sadykov.
*
* 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.github.isarthur.netbeans.editor.generator.java;
import java.io.File;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import javax.swing.JEditorPane;
import javax.swing.text.StyledDocument;
import junit.framework.Test;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertNotNull;
import org.netbeans.api.java.source.JavaSource;
import org.netbeans.junit.NbTestCase;
import org.netbeans.junit.NbModuleSuite;
import org.openide.cookies.EditorCookie;
import org.openide.filesystems.FileLock;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.loaders.DataObject;
/**
*
* @author: Arthur Sadykov
*/
public class SetterInvocationGeneratorTest extends NbTestCase {
private final String content =
"import javax.swing.text.StyledDocument;\n"
+ "public class X {\n"
+ "\n"
+ " private int x;\n"
+ " private int y;\n"
+ "\n"
+ " public void foo() {\n"
+ " StyledDocument document = null;\n"
+ " }\n"
+ "}";
private StyledDocument document;
private JEditorPane editorPane;
private SetterInvocationGenerator generator;
public SetterInvocationGeneratorTest(String testName) {
super(testName);
}
@Override
protected void setUp() throws Exception {
super.setUp();
clearWorkDir();
File root = getWorkDir();
FileObject fo = FileUtil.toFileObject(root);
FileObject java = FileUtil.createData(fo, "X.java");
FileLock lock = java.lock();
try ( OutputStream out = java.getOutputStream(lock)) {
out.write(content.getBytes());
} finally {
lock.releaseLock();
}
JavaSource javaSource = JavaSource.forFileObject(java);
assertNotNull("javaSource was null", javaSource);
DataObject dataObject = DataObject.find(java);
EditorCookie editorCookie = dataObject.getLookup().lookup(EditorCookie.class);
document = editorCookie.openDocument();
editorPane = new JEditorPane();
editorPane.setDocument(document);
editorPane.getDocument().putProperty(JavaSource.class, new WeakReference<>(javaSource));
generator = SetterInvocationGenerator.create(editorPane);
}
public static Test suite() {
return NbModuleSuite.createConfiguration(SetterInvocationGeneratorTest.class)
.clusters("extide")
.clusters("ide")
.clusters("java")
.gui(false)
.suite();
}
public void testWhenInvokingOnSelectedVariableOrFieldShouldGenerateSetters() throws Exception {
String text = document.getText(0, document.getLength());
String string = "document";
int indexOfString = text.indexOf(string);
editorPane.setSelectionStart(indexOfString);
editorPane.setSelectionEnd(indexOfString + string.length());
assertEquals("", string, editorPane.getSelectedText());
generator.invoke();
String actualText = generator.getText();
String expectedText =
"import javax.swing.text.StyledDocument;\n"
+ "public class X {\n"
+ "\n"
+ " private int x;\n"
+ " private int y;\n"
+ "\n"
+ " public void foo() {\n"
+ " StyledDocument document = null;\n"
+ " document.setCharacterAttributes(x, x, null, false);\n"
+ " document.setParagraphAttributes(x, x, null, false);\n"
+ " document.setLogicalStyle(x, null);\n"
+ " }\n"
+ "}";
assertEquals("Expected source text and actual source text are not equal", expectedText, actualText);
}
public void testWhenInvokingOnAnythingThatIsNotVariableOrFieldThenDoNotGenerateAnyCode() throws Exception {
String text = document.getText(0, document.getLength());
String string = "private";
int indexOfString = text.indexOf(string);
editorPane.setSelectionStart(indexOfString);
editorPane.setSelectionEnd(indexOfString + string.length());
assertEquals("", string, editorPane.getSelectedText());
generator.invoke();
String actualText = generator.getText();
assertEquals("Expected source text and actual source text are not equal", content, actualText);
string = "int";
indexOfString = text.indexOf(string);
editorPane.setSelectionStart(indexOfString);
editorPane.setSelectionEnd(indexOfString + string.length());
assertEquals("", string, editorPane.getSelectedText());
generator.invoke();
actualText = generator.getText();
assertEquals("Expected source text and actual source text are not equal", content, actualText);
string = "void";
indexOfString = text.indexOf(string);
editorPane.setSelectionStart(indexOfString);
editorPane.setSelectionEnd(indexOfString + string.length());
assertEquals("", string, editorPane.getSelectedText());
generator.invoke();
actualText = generator.getText();
assertEquals("Expected source text and actual source text are not equal", content, actualText);
}
public void testWhenTextIsNotSelectedThenDoNotGenerateAnyCode() throws Exception {
editorPane.setCaretPosition(0);
generator.invoke();
String actualText = generator.getText();
assertEquals("Text of document should not change", content, actualText);
}
}
| 41.292208 | 111 | 0.650102 |
b75ab95e8137af5f888ed353c290d33fd4a85833 | 1,436 | package us.ihmc.humanoidBehaviors.taskExecutor;
import us.ihmc.humanoidBehaviors.behaviors.primitives.HandDesiredConfigurationBehavior;
import us.ihmc.humanoidBehaviors.behaviors.simpleBehaviors.BehaviorAction;
import us.ihmc.humanoidRobotics.communication.packets.dataobjects.HandConfiguration;
import us.ihmc.humanoidRobotics.communication.packets.manipulation.HandDesiredConfigurationMessage;
import us.ihmc.robotics.robotSide.RobotSide;
public class HandDesiredConfigurationTask<E extends Enum<E>> extends BehaviorAction<E>
{
private final HandDesiredConfigurationMessage ihmcMessage;
private final HandDesiredConfigurationBehavior behavior;
public HandDesiredConfigurationTask(RobotSide robotSide, HandConfiguration handDesiredConfiguration, HandDesiredConfigurationBehavior handDesiredConfigurationBehavior)
{
this(null, robotSide, handDesiredConfiguration, handDesiredConfigurationBehavior);
}
public HandDesiredConfigurationTask(E stateEnum,RobotSide robotSide, HandConfiguration handDesiredConfiguration, HandDesiredConfigurationBehavior handDesiredConfigurationBehavior)
{
super(stateEnum,handDesiredConfigurationBehavior);
this.ihmcMessage = new HandDesiredConfigurationMessage(robotSide, handDesiredConfiguration);
this.behavior = handDesiredConfigurationBehavior;
}
@Override
protected void setBehaviorInput()
{
behavior.setInput(ihmcMessage);
}
}
| 43.515152 | 182 | 0.840529 |
6348813a177aadd7a399713e36d304aa89b5bc9c | 83 | package org.batfish.representation.azure;
public class ConvertedConfiguration {
}
| 16.6 | 41 | 0.831325 |
7ef05c879b07aac50b94a88986442afde8c45923 | 5,839 | package Practice2;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class PetDao {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection root = null;
try {
root = DriverManager.getConnection("jdbc:mysql://localhost:3306/bxytest?characterEncoding=UTF-8&useSSL=false", "root", "123456");
} catch (SQLException e) {
e.printStackTrace();
}
return root;
}
public static void addPet(Pet p) throws SQLException {
Connection connection = getConnection();
PreparedStatement preparedStatement = null;
String sql = "insert into petinfo(name, type, color, price) values (?, ?, ?, ?)";
boolean needUpdate = false;
ResultSet resultSet = null;
try {
preparedStatement = connection.prepareStatement("select count(*) from petinfo where type=?");
preparedStatement.setString(1, "dog");
resultSet = preparedStatement.executeQuery();
int oldNum = 0;
while (resultSet.next()) {
oldNum = resultSet.getInt(1);
}
preparedStatement.close();
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, p.getName());
preparedStatement.setString(2, p.getType());
preparedStatement.setString(3, p.getColor());
preparedStatement.setDouble(4, p.getPrice());
preparedStatement.executeUpdate();
preparedStatement.close();
preparedStatement = connection.prepareStatement("select count(*) from petinfo where type=?");
preparedStatement.setString(1, "dog");
resultSet = preparedStatement.executeQuery();
int newNum = 0;
while (resultSet.next()) {
newNum = resultSet.getInt(1);
}
preparedStatement.close();
if (newNum > oldNum && newNum == 6) {
preparedStatement = connection.prepareStatement("update petinfo set price=price*0.6 where " +
"type=\"dog\"");
preparedStatement.executeUpdate();
}
} finally {
if (resultSet != null) {
resultSet.close();
}
if (preparedStatement != null) {
preparedStatement.close();
}
if (connection != null) {
connection.close();
}
}
}
public static void delPet(int id) throws SQLException {
Connection connection = getConnection();
PreparedStatement preparedStatement = null;
String sql = "delete from petinfo where id=?";
boolean needUpdate = false;
ResultSet resultSet = null;
try {
preparedStatement = connection.prepareStatement("select count(*) from petinfo where type=?");
preparedStatement.setString(1, "dog");
resultSet = preparedStatement.executeQuery();
int oldNum = 0;
while (resultSet.next()) {
oldNum = resultSet.getInt(1);
}
preparedStatement.close();
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, id);
preparedStatement.executeUpdate();
preparedStatement.close();
preparedStatement = connection.prepareStatement("select count(*) from petinfo where type=?");
preparedStatement.setString(1, "dog");
resultSet = preparedStatement.executeQuery();
int newNum = 0;
while (resultSet.next()) {
newNum = resultSet.getInt(1);
}
preparedStatement.close();
if (newNum < oldNum && newNum == 5) {
preparedStatement = connection.prepareStatement("update petinfo set price=price/0.6 where " +
"type=\"dog\"");
preparedStatement.executeUpdate();
}
} finally {
if (resultSet != null) {
resultSet.close();
}
if (preparedStatement != null) {
preparedStatement.close();
}
if (connection != null) {
connection.close();
}
}
}
public static List<Pet> listPet(int type, String field) throws SQLException {
Connection connection = getConnection();
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
ArrayList<Pet> pets = new ArrayList<>();
String sql = null;
if (type == 1) {
sql = "select * from petinfo where color=?";
} else if (type == 2) {
sql = "select * from petinfo where type=?";
} else {
sql = "select * from petinfo order by id";
}
try {
preparedStatement = connection.prepareStatement(sql);
if (type == 1 || type == 2) {
preparedStatement.setString(1, field);
}
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Pet pet = new Pet(resultSet.getInt(1), resultSet.getString(2), resultSet.getString(3), resultSet.getString(4),
resultSet.getDouble(5));
pets.add(pet);
}
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (connection != null) {
connection.close();
}
}
return pets;
}
}
| 36.267081 | 141 | 0.53999 |
02f1f789f79541d8b85316f50d53cde19482a571 | 7,363 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.ftd.educational.mvc.cmds;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.catolica.prog4.persistencia.daos.GeneroDAO;
import org.catolica.prog4.persistencia.daos.LivroDAO;
import org.catolica.prog4.persistencia.daos.exceptions.NonexistentEntityException;
import org.catolica.prog4.persistencia.entities.Genero;
import org.catolica.prog4.persistencia.entities.Livro;
import org.ftd.educational.mvc.abstacts.AbstractWebCmd;
import org.ftd.educational.mvc.interfaces.IWebCmd;
import org.ftd.educational.mvc.utils.util;
/**
*
* @author Cyber
*/
public class LivroCmd extends AbstractWebCmd implements IWebCmd {
private static final String ERRO = "erro";
private static final String MENSAGEM = "msg";
private static final String list = "/WEB-INF/views/livroViews/listarLivros.jsp";
private static final String INSERT_OR_EDIT = "/WEB-INF/views/livroViews/adicionar_editarLivro.jsp";
private static final String detalhes = "/WEB-INF/views/livroViews/detalhesLivro.jsp";
private static final String deletar = "/WEB-INF/views/livroViews/deletarLivro.jsp";
private String forward = "";
private static final EntityManagerFactory factory = Persistence.createEntityManagerFactory("PersistenciaPU");
private final LivroDAO livroDao;
private final GeneroDAO generoDao;
private Long id;
private Livro livro;
private List<Genero> generos;
public LivroCmd() {
generoDao = new GeneroDAO(factory);
livroDao = new LivroDAO(factory);
generos = new ArrayList<>();
}
@Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
super.setDefaultAppModel(request);
id = null;
livro = null;
String action = "";
if (request.getParameter("action") != null) {
action = request.getParameter("action");
}
switch (action) {
case "adicionar":
request.setAttribute("tAdEd", "Adicionar");
generos = generoDao.findAll();
request.setAttribute("comboGeneros", generos);
forward = INSERT_OR_EDIT;
break;
case "detalhes":
repassarParamentroParaTela(request, detalhes);
break;
case "editar":
request.setAttribute("tAdEd", "Editar");
repassarParamentroParaTela(request, INSERT_OR_EDIT);
break;
case "editado":
livro = new Livro();
String livroId = request.getParameter("id");
livro.setTitulo(request.getParameter("titulo"));
Genero genero = new Genero();
genero = generoDao.findGenero(Long.parseLong(request.getParameter("comboGeneros")));
livro.setGenero(genero);
if (request.getParameter("autor") != null) {
livro.setAutor(request.getParameter("autor"));
}
if (request.getParameter("ano") != null) {
livro.setAnoEdicao(Integer.parseInt(request.getParameter("ano")));
}
if (request.getParameter("valor") != null) {
livro.setValor(request.getParameter("valor"));
}
if (livroId == null || livroId.isEmpty()) {
livroDao.create(livro);
request.setAttribute(MENSAGEM, "Livro criado com sucesso");
} else {
livro.setId(Long.parseLong(livroId));
try {
livroDao.edit(livro);
request.setAttribute(MENSAGEM, "Livro editado com sucesso");
} catch (Exception ex) {
Logger.getLogger(LivroCmd.class.getName()).log(Level.SEVERE, null, ex);
request.setAttribute(ERRO, "Erro ao editar livro");
}
}
recarregarListagem(request);
break;
case "deletar?":
repassarParamentroParaTela(request, deletar);
break;
case "excluido":
id = Long.parseLong(request.getParameter("id"));
try {
livroDao.destroy(id);
request.setAttribute(MENSAGEM, "Livro excluido com sucesso");
} catch (NonexistentEntityException ex) {
Logger.getLogger(LivroCmd.class.getName()).log(Level.SEVERE, null, ex);
request.setAttribute(ERRO, "Erro ao excluir");
}
recarregarListagem(request);
break;
case "procurar":
String conteudo = request.getParameter("cProcurar");
if (conteudo == null || conteudo.isEmpty()) {
recarregarListagem(request);
} else {
List<Livro> livrosFiltrados = new ArrayList<>();
allLivros().stream().filter((p) -> ((util.tryParseLong(conteudo) && Long.parseLong(conteudo) == p.getId())
|| (p.getTitulo().toLowerCase().contains(conteudo))
|| (p.getValor().contains(conteudo))
|| (p.getGenero().getNome().toLowerCase().contains(conteudo)))).forEachOrdered((p) -> {
livrosFiltrados.add(p);
});
if (livrosFiltrados.isEmpty()) {
request.setAttribute(ERRO, "Nenhum resultado encontrado");
}
request.setAttribute("livros", livrosFiltrados);
if (livrosFiltrados.isEmpty()) {
request.setAttribute(ERRO, "Nenhum resultado encontrado");
}
}
forward = list;
break;
default:
recarregarListagem(request);
break;
}
return forward;
}
public void recarregarListagem(HttpServletRequest request) {
forward = list;
request.setAttribute("livros", this.allLivros());
}
private List<Livro> allLivros() {
List<Livro> lst = livroDao.findLivroEntities();
return lst;
}
private void repassarParamentroParaTela(HttpServletRequest request, String tela) {
id = Long.parseLong(request.getParameter("id"));
livro = livroDao.findLivro(id);
generos = generoDao.findAll();
request.setAttribute("comboGeneros", generos);
request.setAttribute("idSelecionado", livro.getGenero().getId());
request.setAttribute("livro", livro);
forward = tela;
}
;
}
| 38.348958 | 126 | 0.585902 |
40b871332358eb1f6cd72c322ee41b355d43dbaf | 2,058 | package com.chylee.fxiaoke.controller.quartz;
import com.chylee.fxiaoke.common.event.ResponseEvent;
import com.chylee.fxiaoke.common.event.RestResponse;
import com.chylee.fxiaoke.common.event.support.Page;
import com.chylee.fxiaoke.core.model.QrtzTrigger;
import com.chylee.fxiaoke.core.service.QrtzTriggerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/quartz/trigger")
public class QrtzTriggerController {
private static Logger logger = LoggerFactory.getLogger(QrtzTriggerController.class);
private final QrtzTriggerService qrtzTriggerService;
public QrtzTriggerController(QrtzTriggerService qrtzTriggerService) {
this.qrtzTriggerService = qrtzTriggerService;
}
@PostMapping("delete")
public ResponseEvent delete(@RequestParam int id) {
try {
qrtzTriggerService.deleteTrigger(id);
return new ResponseEvent();
}
catch(Exception e) {
return RestResponse.failure(e);
}
}
@PostMapping("status")
public ResponseEvent status(@RequestParam int id, @RequestParam byte status) {
try {
return RestResponse.success(qrtzTriggerService.toggleStatus(id, status));
}
catch(Exception e) {
return RestResponse.failure(e);
}
}
@GetMapping
public ResponseEvent list(Integer page) {
int pageToUse = page == null ? 1 : page;
return RestResponse.success(qrtzTriggerService.listTriggerByPage(new Page(pageToUse, 10)));
}
@PostMapping
public ResponseEvent save(QrtzTrigger qrtzTrigger) {
ResponseEvent respEvent;
try {
respEvent = RestResponse.success(qrtzTriggerService.saveTrigger(qrtzTrigger));
}
catch(Exception e) {
logger.error("保存任务信息失败", e);
respEvent = RestResponse.failure(e);
}
return respEvent;
}
}
| 32.15625 | 99 | 0.693878 |
7cf6ed43cbecd61aa08c6f6b53e7878ce022b122 | 11,600 | // Pecan 1.0 nodes. Free and open source. See licence.txt.
package pecan;
import java.util.*;
import static pecan.Op.*;
/* A Node represents any parsing expression, together with source text and
annotation information.
A node has an op, up to two subnodes, a source string, some flags, some counts,
and a temporary note also used to store a print format. If the left subnode is
null, the right subnode represents a cross-reference link instead of a child.
For more information about annotations, see the classes which handle them. */
class Node {
private Op op;
private Node left, right;
private Source source;
private int flags;
private int[] counts = new int[Count.values().length];
private String note = "";
// Flag and count constants.
public static enum Flag { TI, SN, FN, SP, FP, WF, AA, EE, AB; }
public static enum Count { NET, NEED, PC, LEN, SEQ; }
// Construct a node with any number of subnodes and a source,
Node(Op o, Node x, Node y, Source s) { op=o; left=x; right=y; source=s; }
Node(Op o, Node x, Source s) { this(o, x, null, s); }
Node(Op o, Source s) { this(o, null, null, s); }
// Construct a node from strings (during transforms).
Node(Op op, String b, Node x, String m, Node y, String a) {
this(op, x, y, null);
String sx = (x == null) ? "" : x.text();
String sy = (y == null) ? "" : y.text();
source = new Source(b + sx + m + sy + a);
}
Node(Op op, String b, Node x, String a) { this(op, b, x, "", null, a); }
Node(Op op, String a) { this(op, a, null, "", null, ""); }
// Make a deep copy of a node (during transforms).
Node deepCopy() {
Node copy = new Node(op, left, right, source);
if (left != null) copy.left = left.deepCopy();
if (right != null) copy.right = right.deepCopy();
copy.flags = flags;
return copy;
}
// Get the fields. Formats share the note field.
Op op() { return op; }
Node left() { return left; }
Node right() { return left == null ? null : right; }
Node ref() { return left != null ? null : right; }
Source source() { return source; }
String text() { return source.text(); }
int flags() { return flags; }
String note() { return note; }
String format() { return note; }
// Set the fields.
void op(Op o) { op = o; }
void left(Node x) {
assert((right == null) || ((x == null) == (left == null)));
left = x;
}
void right(Node y) { assert(left != null); right = y; }
void ref(Node r) { assert(left == null); right = r; }
void source(Source s) { source = s; }
void flags(int fs) { flags = fs; }
void note(String s) { note = s; }
void format(String s) { note = s; }
// Get or set a flag or a count.
boolean has(Flag f) { return (flags & (1 << f.ordinal())) != 0; }
void set(Flag f) { flags |= (1 << f.ordinal()); }
void unset(Flag f) { flags &= ~(1 << f.ordinal()); }
int get(Count c) { return counts[c.ordinal()]; }
void set(Count c, int n) { counts[c.ordinal()] = n; }
// Get the raw text of a node, i.e. the text without quotes, escapes etc.
// Adapt identifiers and literals, as for compiling, to detect name clashes.
String rawText() {
String s = source.rawText();
char ch = s.charAt(0);
if (ch == '#' || ch == '%') s = s.substring(1);
else if (ch == '@') {
s = s.substring(1);
while (s.length() > 0 && '0' <= s.charAt(0) && s.charAt(0) <= '9') {
s = s.substring(1);
}
if (s.length() == 0) return s;
}
ch = s.charAt(0);
if ("\"'<{`".indexOf(ch) >= 0) s = s.substring(1, s.length() - 1);
else if (s.indexOf('-') >= 0) s = translateId(s);
if (ch == '`') s = translateLiteral(s);
return s;
}
// For a character, extract the value, i.e. Unicode code point.
int charCode() {
assert(op == Char);
return source.rawCharAt(1);
}
// For a range, return the low end (i = 0) or high end (i > 0).
int end(int i) {
assert(op == Range);
if (i == 0) return low();
return high();
}
// For a range, extract the low end.
int low() {
assert(op == Range);
return source.rawCharAt(1);
}
// For a range, extract the high end.
int high() {
assert(op == Range);
int len = source.rawLength(1);
int n = 1 + len + 2;
return source.rawCharAt(n);
}
// For an action or drop, extract the arity.
int arity() {
assert(op == Act || op == Drop);
String s = text();
int n = 1;
while (s.length() > n && '0' <= s.charAt(n) && s.charAt(n) <= '9') n++;
if (n == 1) return 0;
return Integer.parseInt(s.substring(1, n));
}
// Clear the notes.
private void clear() {
note("");
if (left != null) left.clear();
if (left != null && right != null) right.clear();
}
// Return a node tree as multi-line text. Then clear the notes, ready
// for the next pass.
public String toString() {
String s = toString("") + "\n";
clear();
return s;
}
// Return a node tree as text, with the given indent for each line. Avoid
// following cross references. Include the range of text covered by the
// node, and any note attached by one of the passes. Indent a list of Rule
// nodes, or subnodes of a chain of And or Or nodes, by the same amount.
private String toString(String indent) {
if (op == Error) return note();
String s = indent + op;
String text = text();
if (text.length() > 0 || note().length() > 0) s += " ";
if (! text.contains("\n")) s += text;
else {
int n = text.indexOf('\n');
s += text.substring(0, n) + "...";
}
if (note().length() > 0) s += " " + note();
indent += " ";
if (left != null && (op == List || op == And || op == Or)) {
s += "\n" + left.toString(indent);
Node x = right;
while (x.op == op) {
s += "\n" + x.left.toString(indent);
x = x.right;
}
s += "\n" + x.toString(indent);
return s;
}
if (left != null) s += "\n" + left.toString(indent);
if (left != null && right != null) s += "\n" + right.toString(indent);
return s;
}
// Print the source text of a node on one line, e.g. when tracing.
String trace() {
int end = source.length();
int lineNumber = source.lineNumber();
int newline = source.indexOf("\n");
if (newline < 0) {
return "P" + lineNumber + ": " + source.text();
}
String s = "P" + lineNumber + "... : ";
int pos = 10;
if (newline < pos) pos = newline;
s += source.substring(0, pos);
s += "...";
pos = end - 10;
newline = source.lastIndexOf("\n") + 1;
if (newline >= 0 && newline > pos) pos = newline;
s += source.substring(pos, end);
return s;
}
// Translate an identifier name, replacing hyphens by camel case.
String translateId(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch != '-') { sb.append(ch); continue; }
if (i >= s.length() - 1) { sb.append("Mi"); break; }
ch = s.charAt(++i);
if ('a'<=ch && ch<='z') sb.append(Character.toUpperCase(ch));
else sb.append("Mi");
}
return sb.toString();
}
private static String[] charMap;
// Translate a literal name into a target language identifier.
String translateLiteral(String s) {
if (charMap == null) fillCharMap();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); ) {
int ch = s.codePointAt(i);
if (ch < 128) sb.append(charMap[ch]);
else sb.append("U" + ch);
i += Character.charCount(ch);
}
return sb.toString();
}
// For each visible ascii character, define how it is translated when it
// appears in a literal name.
private static void fillCharMap() {
charMap = new String[128];
for (char ch = 'a'; ch <= 'z'; ch++) charMap[ch] = "" + ch;
for (char ch = 'A'; ch <= 'Z'; ch++) charMap[ch] = "" + ch;
for (char ch = '0'; ch <= '9'; ch++) charMap[ch] = "" + ch;
for (char ch = ' '; ch < '~'; ch++) switch (ch) {
case ' ': charMap[ch] = "Sp"; break;
case '!': charMap[ch] = "Em"; break;
case '"': charMap[ch] = "Dq"; break;
case '#': charMap[ch] = "Hs"; break;
case '$': charMap[ch] = "Dl"; break;
case '%': charMap[ch] = "Pc"; break;
case '&': charMap[ch] = "Am"; break;
case '\'': charMap[ch] = "Sq"; break;
case '(': charMap[ch] = "Ob"; break;
case ')': charMap[ch] = "Cb"; break;
case '*': charMap[ch] = "St"; break;
case '+': charMap[ch] = "Pl"; break;
case ',': charMap[ch] = "Cm"; break;
case '-': charMap[ch] = "Mi"; break;
case '.': charMap[ch] = "Dt"; break;
case '/': charMap[ch] = "Sl"; break;
case ':': charMap[ch] = "Cl"; break;
case ';': charMap[ch] = "Sc"; break;
case '<': charMap[ch] = "Lt"; break;
case '=': charMap[ch] = "Eq"; break;
case '>': charMap[ch] = "Gt"; break;
case '?': charMap[ch] = "Qm"; break;
case '@': charMap[ch] = "At"; break;
case '[': charMap[ch] = "Os"; break;
case '\\': charMap[ch] = "Bs"; break;
case ']': charMap[ch] = "Cs"; break;
case '^': charMap[ch] = "Ht"; break;
case '_': charMap[ch] = "Us"; break;
case '`': charMap[ch] = "Bq"; break;
case '{': charMap[ch] = "Oc"; break;
case '|': charMap[ch] = "Vb"; break;
case '}': charMap[ch] = "Cc"; break;
case '~': charMap[ch] = "Ti"; break;
}
}
public static void main(String[] args) {
Op.main(null);
Source.main(null);
Node n = new Node(Char, new Source("'a'"));
assert(n.rawText().equals("a"));
assert(n.charCode() == 97);
n = new Node(Char, new Source("'\\127'"));
assert(n.rawText().equals("\177"));
n = new Node(Act, new Source("@add"));
assert(n.rawText().equals("add"));
assert(n.arity() == 0);
n = new Node(Act, new Source("@2mul"));
assert(n.rawText().equals("mul"));
assert(n.arity() == 2);
n = new Node(Range, new Source("'a..z'"));
assert(n.rawText().equals("a..z"));
assert(n.low() == 97);
assert(n.high() == 97+25);
n = new Node(Id, new Source("one-two"));
assert(n.rawText().equals("oneTwo"));
n = new Node(Id, new Source("`<=`"));
assert(n.rawText().equals("LtEq"));
System.out.println("Node class OK");
}
}
| 38.283828 | 81 | 0.48931 |
f1c3ac1cf74346a523d53d8e96904da1bcd2d51d | 495 | package edu.northeastern.cs5200.models;
public class Priviledge {
private int id;
private String priviledge;
public Priviledge() {
super();
}
public Priviledge(int id, String priviledge) {
super();
this.id = id;
this.priviledge = priviledge;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPriviledge() {
return priviledge;
}
public void setPriviledge(String priviledge) {
this.priviledge = priviledge;
}
} | 15 | 47 | 0.684848 |
ce784f5f4c18712c7dbcc4b691110c0021eafd54 | 191 | package io.eventuate.tram.springcloudsleuthintegration;
public interface MessageHeaderAccessor {
void put(String key, String value);
String get(String key);
void remove(String key);
}
| 23.875 | 55 | 0.78534 |
433d3f79607a13757e3e97e23dff78dc94d8a17e | 3,297 | /*
* Copyright (c) 2019 Nextworks s.r.l
* 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 it.nextworks.nfvmano.catalogue.template.messages;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnore;
import it.nextworks.nfvmano.catalogue.template.elements.NstConfigurationRule;
import it.nextworks.nfvmano.libs.ifa.descriptors.nsd.Nsd;
import it.nextworks.nfvmano.libs.ifa.catalogues.interfaces.messages.OnBoardVnfPackageRequest;
import it.nextworks.nfvmano.libs.ifa.common.InterfaceMessage;
import it.nextworks.nfvmano.libs.ifa.common.exceptions.MalformattedElementException;
import it.nextworks.nfvmano.libs.ifa.descriptors.nsd.Pnfd;
import it.nextworks.nfvmano.libs.ifa.templates.NST;
public class OnBoardNsTemplateRequest implements InterfaceMessage {
private NST nst;
private List<Nsd> nsds = new ArrayList<>();
private List<OnBoardVnfPackageRequest> vnfPackages = new ArrayList<>();
private List<Pnfd> pnfds = new ArrayList<>();
private List<NstConfigurationRule> configurationRules = new ArrayList<>();
public OnBoardNsTemplateRequest() { }
/**
* Constructor
* @param nst
* @param nsds
*/
public OnBoardNsTemplateRequest(NST nst, List<Nsd> nsds, List<OnBoardVnfPackageRequest> vnfPackages, List<Pnfd> pnfds, List<NstConfigurationRule> configurationRules) {
if(this.nsds!=null)
this.nsds = nsds;
this.nst = nst;
if(vnfPackages!=null)
this.vnfPackages= vnfPackages;
if(pnfds!=null)
this.pnfds = pnfds;
if (configurationRules != null) this.configurationRules = configurationRules;
}
@Override
public void isValid() throws MalformattedElementException {
if (nsds!=null && nsds.isEmpty()){
for (Nsd nsd : nsds) nsd.isValid();
}
if(vnfPackages!=null && !vnfPackages.isEmpty()){
for (OnBoardVnfPackageRequest vnf : vnfPackages) vnf.isValid();
}
if (nst == null) throw new MalformattedElementException("On board NS Template request without NS Template");
else nst.isValid();
if(pnfds != null && !pnfds.isEmpty()){
for (Pnfd pnfd : pnfds) pnfd.isValid();
}
if(!configurationRules.isEmpty()) for (NstConfigurationRule r : configurationRules) r.isValid();
}
public NST getNst() {
return nst;
}
public void setNst(NST nst) {
this.nst = nst;
}
public List<Nsd> getNsds() {
return nsds;
}
public List<Pnfd> getPnfds() { return pnfds; }
/**
* @return the vnfPackages
*/
public List<OnBoardVnfPackageRequest> getVnfPackages() {
return vnfPackages;
}
public List<NstConfigurationRule> getConfigurationRules() {
return configurationRules;
}
@JsonIgnore
public void setNstIdInConfigurationRules(String nstId) {
for (NstConfigurationRule cr : configurationRules)
cr.setNstId(nstId);
}
}
| 30.813084 | 168 | 0.73764 |
b27651916c671faaf43eb19cb45db0e3881b2c58 | 585 | package com.abin.lee.serialize.fst;
import org.nustaq.serialization.FSTConfiguration;
/**
* Created by abin on 2018/4/15 17:14.
* serialize-svr
* com.abin.lee.serialize.fst
* https://blog.csdn.net/z69183787/article/details/53005961
*/
public class FstSerialize {
public static FSTConfiguration fstConfiguration = FSTConfiguration.createStructConfiguration();
public static byte[] serialize(Object obj) {
return fstConfiguration.asByteArray(obj);
}
public static Object deserialize(byte[] sec) {
return fstConfiguration.asObject(sec);
}
}
| 24.375 | 99 | 0.729915 |
2b4a723ef41a4e47b76a3a898fbbd2223fd070f4 | 2,164 | package seedu.address.logic.commands.debtcommands;
import static java.util.Objects.requireNonNull;
import java.util.List;
import seedu.address.commons.core.Messages;
import seedu.address.commons.core.index.Index;
import seedu.address.logic.CommandHistory;
import seedu.address.logic.commands.Command;
import seedu.address.logic.commands.CommandResult;
import seedu.address.logic.commands.exceptions.CommandException;
import seedu.address.model.Model;
import seedu.address.model.debt.Debt;
/**
* Selects a debt identified using it's displayed index from the Finance Tracker.
*/
public class SelectDebtCommand extends Command {
public static final String COMMAND_WORD = "selectdebt";
public static final String COMMAND_WORD_SHORTCUT = "sd";
public static final String MESSAGE_USAGE = COMMAND_WORD
+ ": Selects the debt identified by the index number used in the displayed debt list.\n"
+ "Parameters: INDEX (must be a positive integer)\n"
+ "Example: " + COMMAND_WORD + " 1";
public static final String MESSAGE_SELECT_DEBT_SUCCESS = "Selected Debt: %1$s";
private final Index targetIndex;
public SelectDebtCommand(Index targetIndex) {
this.targetIndex = targetIndex;
}
@Override
public CommandResult execute(Model model, CommandHistory history) throws CommandException {
requireNonNull(model);
model.setSelectedDebt(null);
List<Debt> filteredDebtList = model.getFilteredDebtList();
if (targetIndex.getZeroBased() >= filteredDebtList.size()) {
throw new CommandException(Messages.MESSAGE_INVALID_DEBT_DISPLAYED_INDEX);
}
model.setSelectedDebt(filteredDebtList.get(targetIndex.getZeroBased()));
return new CommandResult(String.format(MESSAGE_SELECT_DEBT_SUCCESS, targetIndex.getOneBased()));
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof SelectDebtCommand // instanceof handles nulls
&& targetIndex.equals(((SelectDebtCommand) other).targetIndex)); // state check
}
}
| 35.47541 | 104 | 0.725046 |
6ed312a316293831af2998e0bbd88a948b1bba30 | 1,016 | package atomic;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Tester {
List<Integer> numbers = new ArrayList<Integer>();
private List<Thread> threads;
public void test() {
threads = new ArrayList<Thread>();
for (int i = 0; i < 4000; i++) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
numbers.add(NextNumberWrong.getNext());
}
});
threads.add(thread);
thread.start();
}
}
public void check() {
boolean wait = false;
do {
for (Thread thread : threads) {
if (thread.isAlive()) {
wait = true;
}
}
} while (wait);
Collections.sort(numbers);
// for (int i = 0; i < numbers.size() - 1; i++) {
// if (numbers.get(i).equals(numbers.get(i + 1))) {
// throw new RuntimeException("We have a collision");
// }
// }
System.out.println("No double number");
}
public static void main(String[] args) {
Tester test = new Tester();
test.test();
test.check();
}
}
| 20.32 | 55 | 0.610236 |
6cbd5d17f6a381822c7093fed13610646c36d33e | 589 | package Lab_7;
/**
* Created by Ahmed Al masade on 01/03/2022.
*/
public class LinkedQueue<E> implements Queue<E> {
SinglyLinkedList<E>list=new SinglyLinkedList<E>();
@Override
public boolean isEmpty() {
return list.isEmpty() ;
}
@Override
public int size() {
return list.size();
}
@Override
public void enqueue(E el) {
list.addLast(el);
}
@Override
public E dequeue() {
return list.removeFirst();
}
@Override
public E first() {
return list.first();
}
}
| 17.848485 | 55 | 0.548387 |
5868ba3ae9a005d12c5cd7b228ecc38d0c2d630d | 2,882 | package org.usfirst.frc.team1736.robot;
import org.usfirst.frc.team1736.lib.Calibration.Calibration;
import org.usfirst.frc.team1736.lib.Util.CrashTracker;
import edu.wpi.first.wpilibj.Spark;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.AnalogInput;
import edu.wpi.first.wpilibj.DigitalInput;
/**
* Class to control the elbow motor, which raises and lowers the intake arms
* @author Chris Gerth
*
*/
public class ElbowControl {
private static ElbowControl singularInstance = null;
boolean curRaiseCmd = false;
boolean curLowerCmd = false;
boolean prevLowerCmd = false;
boolean upperLimitReached = false;
boolean lowerLimitReached = false;
DigitalInput upperLimitSwitch;
private double startTime = 0.0;
private double currentTime = 0.0;
private double elapsedTime = 0.0;
//Cutoffs
//Present value passed to motor. Positive means raise, negative means lower.
double curMotorCmd = 0;
Spark elbowMotor = null;
Calibration raiseSpeedCal = null;
Calibration lowerSpeedCal = null;
public static synchronized ElbowControl getInstance() {
if ( singularInstance == null)
singularInstance = new ElbowControl();
return singularInstance;
}
private ElbowControl() {
CrashTracker.logClassInitStart(this.getClass());
elbowMotor = new Spark(RobotConstants.PWM_ELBOW);
upperLimitSwitch = new DigitalInput(RobotConstants.DI_ELBOW_UPPER_LIMIT_SW);
raiseSpeedCal = new Calibration("Elbow Raise Speed", 0.35, 0.0, 1.0);
lowerSpeedCal = new Calibration("Elbow Lower Speed", 0.25, 0.0, 1.0);
CrashTracker.logClassInitEnd(this.getClass());
}
public void sampleSensors() {
//Read Potentiometer
if(upperLimitSwitch.get() == true) {
upperLimitReached = true;
} else {
upperLimitReached = false;
}
}
public void update() {
//Default to off
curMotorCmd = 0;
//calculate motor command
if(upperLimitReached == false && curRaiseCmd == true) {
curMotorCmd = raiseSpeedCal.get();
} else {
if(curLowerCmd == true && prevLowerCmd == false) {
startTime = Timer.getFPGATimestamp();
}
if(curLowerCmd == true) {
elapsedTime = Timer.getFPGATimestamp() - startTime;
if(elapsedTime < 0.25) {
curMotorCmd = -1*raiseSpeedCal.get();
} else {
curMotorCmd = 0;
}
} else {
curMotorCmd = 0;
}
}
//Set the motor command to the motor
elbowMotor.set(curMotorCmd);
}
//Public Getters and Setters
public void setRaiseDesired(boolean cmd) {
curRaiseCmd = cmd;
}
public void setLowerDesired(boolean cmd) {
prevLowerCmd = curLowerCmd;
curLowerCmd = cmd;
}
public boolean isUpperLimitReached() {
return upperLimitReached;
}
public double getMotorCmd() {
return curMotorCmd;
}
}
| 23.430894 | 79 | 0.679042 |
614fb96792701afca77d33679f4f78425e5bdd99 | 1,310 | package com.example.demo.application.webhook;
import com.example.demo.domain.fundamentals.url.Url;
import com.example.demo.domain.model.webhook.MultiWebHook;
import com.example.demo.domain.model.webhook.WebHookItem;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
class WebHookServiceTest {
@Autowired
WebHookService webHookService;
@Test
public void 複数のWebHookを並列で非同期にできる() {
WebHookItem webHookItem1 = new WebHookItem(
new Url("http", "localhost:8080", "/test", "param=1"),
"hogehoge", "0123456abcdefg", "fugafuga");
WebHookItem webHookItem2 = new WebHookItem(
new Url("http", "localhost:8080", "/test", "param=2"),
"hogehoge", "0123456abcdefg", "fugafuga");
WebHookItem webHookItem3 = new WebHookItem(
new Url("http", "localhost:8080", "/test", "param=3"),
"hogehoge", "0123456abcdefg", "fugafuga");
MultiWebHook multiWebHook = new MultiWebHook(List.of(webHookItem1, webHookItem2, webHookItem3));
webHookService.webHooks(multiWebHook);
}
}
| 36.388889 | 104 | 0.691603 |
bf07abbbaec289d897364694bec90d5178550fe5 | 3,845 | package io.aftersound.weave.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
@Configuration
public class WeaveServiceProperties {
@Value("${security-asset-directory}")
private String securityAssetDirectory;
@Value("${cache-factory-types-json}")
private String cacheFactoryTypesJson;
@Value("${data-client-factory-types-json}")
private String dataClientFactoryTypesJson;
@Value("${param-deriver-types-json}")
private String paramDeriverTypesJson;
@Value("${data-format-types-json}")
private String dataFormatTypesJson;
@Value("${service-executor-types-json}")
private String serviceExecutorTypesJson;
@Value("${job-runner-types-json}")
private String jobRunnerTypesJson;
@Value("${admin-service-metadata-directory}")
private String adminServiceMetadataDirectory;
@Value("${admin-service-executor-types-json}")
private String adminServiceExecutorTypesJson;
@Value("${service-metadata-directory}")
private String serviceMetadataDirectory;
@Value("${job-spec-directory}")
private String jobSpecDirectory;
public String getSecurityAssetDirectory() {
return securityAssetDirectory;
}
public void setSecurityAssetDirectory(String securityAssetDirectory) {
this.securityAssetDirectory = securityAssetDirectory;
}
public String getAdminServiceMetadataDirectory() {
return adminServiceMetadataDirectory;
}
public void setAdminServiceMetadataDirectory(String adminServiceMetadataDirectory) {
this.adminServiceMetadataDirectory = adminServiceMetadataDirectory;
}
public String getAdminServiceExecutorTypesJson() {
return adminServiceExecutorTypesJson;
}
public void setAdminServiceExecutorTypesJson(String adminServiceExecutorTypesJson) {
this.adminServiceExecutorTypesJson = adminServiceExecutorTypesJson;
}
public String getServiceMetadataDirectory() {
return serviceMetadataDirectory;
}
public void setServiceMetadataDirectory(String serviceMetadataDirectory) {
this.serviceMetadataDirectory = serviceMetadataDirectory;
}
public String getCacheFactoryTypesJson() {
return cacheFactoryTypesJson;
}
public void setCacheFactoryTypesJson(String cacheFactoryTypesJson) {
this.cacheFactoryTypesJson = cacheFactoryTypesJson;
}
public String getDataClientFactoryTypesJson() {
return dataClientFactoryTypesJson;
}
public void setDataClientFactoryTypesJson(String dataClientFactoryTypesJson) {
this.dataClientFactoryTypesJson = dataClientFactoryTypesJson;
}
public String getParamDeriverTypesJson() {
return paramDeriverTypesJson;
}
public void setParamDeriverTypesJson(String paramDeriverTypesJson) {
this.paramDeriverTypesJson = paramDeriverTypesJson;
}
public String getDataFormatTypesJson() {
return dataFormatTypesJson;
}
public void setDataFormatTypesJson(String dataFormatTypesJson) {
this.dataFormatTypesJson = dataFormatTypesJson;
}
public String getServiceExecutorTypesJson() {
return serviceExecutorTypesJson;
}
public void setServiceExecutorTypesJson(String serviceExecutorTypesJson) {
this.serviceExecutorTypesJson = serviceExecutorTypesJson;
}
public String getJobRunnerTypesJson() {
return jobRunnerTypesJson;
}
public void setJobRunnerTypesJson(String jobRunnerTypesJson) {
this.jobRunnerTypesJson = jobRunnerTypesJson;
}
public String getJobSpecDirectory() {
return jobSpecDirectory;
}
public void setJobSpecDirectory(String jobSpecDirectory) {
this.jobSpecDirectory = jobSpecDirectory;
}
}
| 29.351145 | 88 | 0.742783 |
d79e591861675eec51210b6690409a09307ac4fa | 5,646 | /*
* ACDD Project
* file PackageAdmin.java is part of ACCD
* The MIT License (MIT) Copyright (c) 2015 Bunny Blue,achellies.
*
*
* 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 org.osgi.service.packageadmin;
import org.osgi.framework.Bundle;
public interface PackageAdmin {
/**
* Gets the exported package for the specified package name.
* <p>
* <p>
* If there are multiple exported packages with specified name, the exported
* package with the highest version will be returned.
*
* @param name The name of the exported package to be returned.
* @return The exported package, or <code>null</code> if no exported
* package with the specified name exists.
*/
ExportedPackage getExportedPackage(String name);
ExportedPackage[] getExportedPackages(Bundle bundle);
/**
* Forces the update (replacement) or removal of packages exported by the
* specified bundles.
* <p>
* <p>
* If no bundles are specified, this method will update or remove any
* packages exported by any bundles that were previously updated or
* uninstalled since the last call to this method. The technique by which
* this is accomplished may vary among different Framework implementations.
* One permissible implementation is to stop and restart the Framework.
* <p>
* <p>
* This method returns to the caller immediately and then performs the
* following steps on a separate thread:
* <p>
* <ol>
* <li>Compute a graph of bundles starting with the specified bundles. If no
* bundles are specified, compute a graph of bundles starting with bundle
* updated or uninstalled since the last call to this method. Add to the
* graph any bundle that is wired to a package that is currently exported by
* a bundle in the graph. The graph is fully constructed when there is no
* bundle outside the graph that is wired to a bundle in the graph. The
* graph may contain <code>UNINSTALLED</code> bundles that are currently
* still exporting packages.
* <p>
* <li>Each bundle in the graph that is in the <code>ACTIVE</code> state
* will be stopped as described in the <code>Bundle.stop</code> method.
* <p>
* <li>Each bundle in the graph that is in the <code>RESOLVED</code> state
* is unresolved and thus moved to the <code>INSTALLED</code> state. The
* effect of this step is that bundles in the graph are no longer
* <code>RESOLVED</code>.
* <p>
* <li>Each bundle in the graph that is in the <code>UNINSTALLED</code>
* state is removed from the graph and is now completely removed from the
* Framework.
* <p>
* <li>Each bundle in the graph that was in the <code>ACTIVE</code> state
* prior to Step 2 is started as described in the <code>Bundle.start</code>
* method, causing all bundles required for the restart to be resolved. It
* is possible that, as a result of the previous steps, packages that were
* previously exported no longer are. Therefore, some bundles may be
* unresolvable until another bundle offering a compatible package for
* export has been installed in the Framework.
* <li>A framework event of type
* <code>FrameworkEvent.PACKAGES_REFRESHED</code> is fired.
* </ol>
* <p>
* <p>
* For any exceptions that are thrown during any of these steps, a
* <code>FrameworkEvent</code> of type <code>ERROR</code> is fired
* containing the exception. The source bundle for these events should be
* the specific bundle to which the exception is related. If no specific
* bundle can be associated with the exception then the System Bundle must
* be used as the source bundle for the event.
*
* @param bundles The bundles whose exported packages are to be updated or
* removed, or <code>null</code> for all bundles updated or
* uninstalled since the last call to this method.
* @throws SecurityException If the caller does not have
* <code>AdminPermission[System Bundle,RESOLVE]</code> and the Java
* runtime environment supports permissions.
* @throws IllegalArgumentException If the specified <code>Bundle</code>s
* were not created by the same framework instance that registered
* this <code>PackageAdmin</code> service.
*/
void refreshPackages(Bundle[] bundles);
}
| 48.25641 | 104 | 0.685087 |
26c348dcbf106c192afb7b7d6e80bf201af4876f | 1,532 | package fr.paris10.poa.td4.filesystem;
/**
* Created by vabouque on 24/10/2016.
*/
public class WinFactory implements AbstractFileFactory {
WinFactory() {
}
@Override
public File createFile(String fileName, String userName) {
return new WinOrdinaryFile(fileName, userName);
}
@Override
public File createDirectory(String directoryName, String userName) {
return new WinDirectory(directoryName, userName);
}
@Override
public boolean open(File file, File.OpenMode mode) {
return file.open(mode);
}
@Override
public boolean close(File file) {
return file.close();
}
@Override
public void rename(File file, String fileName) {
file.rename(fileName);
}
@Override
public String read(File file) {
return file.read();
}
@Override
public boolean write(File file, String content) {
return file.write(content);
}
@Override
public String getName(File file) {
return file.getName();
}
@Override
public int getId(File file) {
return file.getId();
}
@Override
public int size(File file) {
return file.size();
}
@Override
public UserRegistry.User getUser(File file) {
return file.getUser();
}
@Override
public File.OpenMode getMode(File file) {
return file.getMode();
}
@Override
public boolean write(File directory, File file) {
return directory.write(file);
}
}
| 20.157895 | 72 | 0.619452 |
e3b919d26800f5866f0ea38a36592c8df12df686 | 643 | package com.toconnor.pool.model;
import java.io.Serializable;
import com.googlecode.objectify.annotation.Embed;
import com.toconnor.pool.Team;
/**
* RankedTeam
*/
@Embed
public class RankedTeam implements Serializable
{
private static final long serialVersionUID = 1L;
private int rank;
private String team;
private RankedTeam()
{
//needed for persistence
}
public RankedTeam(int rank, Team team)
{
this.rank = rank;
this.team = team.getCode();
}
public int getRank()
{
return rank;
}
public Team getTeam()
{
return Team.get(team);
}
@Override
public String toString()
{
return rank + "=" + team;
}
}
| 13.978261 | 49 | 0.698289 |
3dbb0ab8da366d5dc2062eac03456691ff7001de | 393 | package pull.domain;
public class ProductCategory {
private String name;
public ProductCategory() {
super();
}
public ProductCategory(String name) {
super();
this.name = name;
}
@Override
public String toString() {
return "ProductCategory [name=" + name + "]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| 13.551724 | 47 | 0.659033 |
07bcaaa14248a812110498d4d55fae197e7b916f | 1,112 | package fr.syncrase.ecosyst.service;
import fr.syncrase.ecosyst.domain.Racine;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
/**
* Service Interface for managing {@link Racine}.
*/
public interface RacineService {
/**
* Save a racine.
*
* @param racine the entity to save.
* @return the persisted entity.
*/
Racine save(Racine racine);
/**
* Partially updates a racine.
*
* @param racine the entity to update partially.
* @return the persisted entity.
*/
Optional<Racine> partialUpdate(Racine racine);
/**
* Get all the racines.
*
* @param pageable the pagination information.
* @return the list of entities.
*/
Page<Racine> findAll(Pageable pageable);
/**
* Get the "id" racine.
*
* @param id the id of the entity.
* @return the entity.
*/
Optional<Racine> findOne(Long id);
/**
* Delete the "id" racine.
*
* @param id the id of the entity.
*/
void delete(Long id);
}
| 21.803922 | 52 | 0.614209 |
ef2351c72cd7bb99228fc5438f39b2929736c441 | 1,427 | package scoopy.client.command;
import net.minecraft.command.ICommandSender;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.server.command.CommandTreeBase;
import net.minecraftforge.server.command.CommandTreeHelp;
import scoopy.Scoopy;
import scoopy.common.command.CommandDataParameters;
import scoopy.common.command.CommandEventHandlers;
import static scoopy.Scoopy.DEP_GREGTECH_ID;
import static scoopy.Scoopy.DEP_NUTRITION_ID;
public class CommandClientScoopy extends CommandTreeBase implements IScoopyClientCommand {
public CommandClientScoopy() {
addSubcommand(new CommandPingPong());
if (Loader.isModLoaded(DEP_GREGTECH_ID)) {
Scoopy.log.info("Client Gregtech Commands Loaded");
addSubcommand(new CommandTreeGregtech());
}
if (Loader.isModLoaded(DEP_NUTRITION_ID)) {
Scoopy.log.info("Client Nutrition Commands Loaded");
addSubcommand(new CommandTreeNutrition());
}
addSubcommand(new CommandDataParameters());
addSubcommand(new CommandEventHandlers());
addSubcommand(new CommandTreeHelp(this));
}
@Override
public String getName() {
return "cscoopy";
}
@Override
public String getUsage(ICommandSender sender) {
return "Client Scoopy Commands";
}
@Override
public int getRequiredPermissionLevel() {
return 0;
}
}
| 31.021739 | 90 | 0.718991 |
a9b8aa0e40d649d67ec4ba5ad64d3b2a86d9bd33 | 1,258 | import javax.swing.JOptionPane;
public class BlackJack {
public static void main(String[] args) {
weiterSpielen();
}
public static int karteZiehen() {
int rueckgabePunkt = 0;
int karteZahl = (int) (Math.random()*13)+1;
for (int i = 1; i <= 13; i++) {
switch(karteZahl) {
case 1: rueckgabePunkt=11;break;
case 10: rueckgabePunkt=10;break;
case 10|11|12: rueckgabePunkt=10;break;
default:rueckgabePunkt = i;break;
}
if (karteZahl == i) {
return rueckgabePunkt;
}
}
return 999;
}
public static void weiterSpielen() {
JOptionPane.showMessageDialog(null, "Willkommen im BlackJack Simulator");
JOptionPane.showMessageDialog(null, "Zieh nun deine Erste Karte");
boolean weiter = false;
int punktestand = 0;
String entscheidung = "";
while(weiter == false){
int kartenwert = karteZiehen();
punktestand = punktestand + kartenwert;
System.out.println("Du hast eine Karte mit dem Wert von " + kartenwert + " gezogen " +
"und hast nun " + punktestand + " Punkte");
entscheidung = JOptionPane.showInputDialog("Willst du weiter spielen? ");
if (entscheidung.equalsIgnoreCase("nein")) {
weiter = true;
}
}
System.out.println("Du Hast " + punktestand + " Punkte erreicht" );
}
}
| 27.955556 | 89 | 0.673291 |
f867b42d6d2834d9c26b0fde2d39a75293f34b6d | 481 | package cn.mulanbay.face.api.web.bean.response.chart;
/**
* 日历饼图明细
*
* @author fenghong
* @create 2017-07-10 21:44
*/
public class ChartCalendarPieDetailData {
private String name;
private long value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getValue() {
return value;
}
public void setValue(long value) {
this.value = value;
}
}
| 15.516129 | 53 | 0.602911 |
3efebe433cda049514d23815db5b236d34a993ef | 494 | package org.synyx.urlaubsverwaltung.restapi.person;
import java.util.List;
/**
* @author Aljona Murygina - [email protected]
*/
public class PersonListResponse {
private List<PersonResponse> persons;
public PersonListResponse(List<PersonResponse> persons) {
this.persons = persons;
}
public List<PersonResponse> getPersons() {
return persons;
}
public void setPersons(List<PersonResponse> persons) {
this.persons = persons;
}
}
| 17.034483 | 61 | 0.680162 |
a745e520b3f402c91427d1ea5bc1a21c62310db5 | 314 | package ucacue.edu.ec.dto;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class CuentaDTO {
private long id;
private ClienteDTO clienteDTO;
private TipoCuentaDTO tipoCuentaDTO;
private int estado;
private String fechaCreacion;
private String descripcion;
}
| 13.083333 | 40 | 0.726115 |
9fafb6caf3cd73b34ee60dfd91c07226ff888035 | 1,525 | /*
* 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.uima.util;
import org.apache.uima.resource.ManagementObject;
/**
* Management interface to a {@link CasPool}.
*/
public interface CasPoolManagement extends ManagementObject {
/**
* Get the total size of the CAS Pool.
*
* @return the pool size
*/
int getPoolSize();
/**
* Get the number of CAS instances currently available in the pool.
*
* @return the number of available CAS instances
*/
int getAvailableInstances();
// /**
// * Get the average time, in milliseconds, that getCas() requests on
// * the pool have to wait for a CAS to become available
// * @return average wait time in milliseconds
// */
// public int getAverageWaitTime();
}
| 31.122449 | 71 | 0.714098 |
1ca1dd78382538e2142a4af1492858e6eb311bc3 | 225 | package com.godfunc.modules.merchant.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.godfunc.entity.MerchantBalance;
public interface MerchantBalanceMapper extends BaseMapper<MerchantBalance> {
}
| 28.125 | 76 | 0.848889 |
d6d4d91f8075f6597491cd2c32ebe7c7b0f9da13 | 1,317 | package net.encode.wurmesp.feature.hook;
import java.lang.reflect.Field;
import java.util.logging.Level;
import org.gotti.wurmunlimited.modloader.ReflectionUtil;
import com.wurmonline.client.renderer.GroundItemData;
import net.encode.wurmesp.Unit;
import net.encode.wurmesp.WurmEspMod;
public class GroundItemCellRenderableRemove
extends Hook {
public GroundItemCellRenderableRemove() {
this.prepareHook("com.wurmonline.client.renderer.cell.GroundItemCellRenderable", "removed", "(Z)V", () -> (proxy, method, args) -> {
method.invoke(proxy, args);
Class<?> cls = proxy.getClass();
GroundItemData item = (GroundItemData)ReflectionUtil.getPrivateField((Object)proxy, (Field)ReflectionUtil.getField(cls, (String)"item"));
for (Unit unit : WurmEspMod.pickableUnits) {
if (unit.getId() != item.getId()) continue;
WurmEspMod.toRemove.add(unit);
}
for (Unit unit : WurmEspMod.toRemove) {
if (unit.getId() != item.getId()) continue;
WurmEspMod.pickableUnits.remove(unit);
}
WurmEspMod.toRemove.clear();
return null;
});
WurmEspMod.logger.log(Level.INFO, "[WurmEspMod] GroundItemCellRenderable.removed hooked");
}
}
| 37.628571 | 149 | 0.654518 |
1aa621535f59f7cff165585e0e7ec73b311408be | 889 | package com.ning.http.pool;
public abstract class Connection<T> {
private String baseUrl;
private T channel;
private long lastTimeUsed;
private AsyncConnectionPoolImpl<T> pool;
public Connection(T channel2) {
this.channel = channel2;
this.lastTimeUsed = System.currentTimeMillis();
}
/**
* Implement how to close the channel so you can do getChannel().close() in the subclass.
*/
protected abstract void close();
public void releaseConnection() {
pool.releaseConnection(this);
}
public String getBaseUrl() {
return baseUrl;
}
void setBaseUrl(String uri) {
this.baseUrl = uri;
}
void setPool(AsyncConnectionPoolImpl<T> pool) {
this.pool = pool;
}
void setLastTimeUsed(long currentTimeMillis) {
this.lastTimeUsed = currentTimeMillis;
}
long getLastTimeUsed() {
return lastTimeUsed;
}
public T getChannel() {
return channel;
}
}
| 17.78 | 90 | 0.715411 |
1c76dd3d7b7b97d3953c361c298b54f90329ea05 | 3,131 | package net.lintim.algorithm.tools;
import net.lintim.exception.ConfigNoFileNameGivenException;
import net.lintim.io.ConfigReader;
import net.lintim.io.InfrastructureReader;
import net.lintim.io.InfrastructureWriter;
import net.lintim.io.ODReader;
import net.lintim.model.Graph;
import net.lintim.model.InfrastructureNode;
import net.lintim.model.OD;
import net.lintim.model.WalkingEdge;
import net.lintim.model.impl.MapOD;
import net.lintim.model.impl.SimpleMapGraph;
import net.lintim.util.Config;
import net.lintim.util.Logger;
import net.lintim.util.tools.WalkingPreprocessorParameters;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class WalkingPreprocessor {
private final static Logger logger = new Logger(WalkingPreprocessor.class.getCanonicalName());
public static Graph<InfrastructureNode, WalkingEdge> preprocess(Graph<InfrastructureNode, WalkingEdge> originalGraph,
OD nodeOd, WalkingPreprocessorParameters parameters) {
Graph<InfrastructureNode, WalkingEdge> preprocessedGraph = new SimpleMapGraph<>();
for (InfrastructureNode node: originalGraph.getNodes()) {
preprocessedGraph.addNode(node);
// Is there any demand for this node, i.e., do we want to start or end walking here?
boolean foundDemand = false;
for (InfrastructureNode destination: originalGraph.getNodes()) {
if (node.equals(destination)) {
continue;
}
if (nodeOd.getValue(node.getId(), destination.getId()) > 0) {
foundDemand = true;
break;
}
}
if (!foundDemand) {
// There was no demand starting at node, we therefore don't need any walking edges starting there
continue;
}
// Now determine where we may go from here
List<WalkingEdge> possibleEdges = originalGraph.getOutgoingEdges(node).stream()
.filter(e -> e.getOtherSide(node).isStopPossible())
.sorted(Comparator.comparingDouble(WalkingEdge::getLength))
.collect(Collectors.toList());
// Now add the valid edges into the new graph
int numberOfEdgesAdded = 0;
double minimalDistance = possibleEdges.get(0).getLength();
for (WalkingEdge edge: possibleEdges) {
if (parameters.getMaxWalkingAmount() > 0 && parameters.getMaxWalkingAmount() <= numberOfEdgesAdded ||
parameters.getMaxWalkingRatio() > 0 && parameters.getMaxWalkingRatio() < edge.getLength() / minimalDistance ||
parameters.getMaxWalkingTime() > 0 && parameters.getMaxWalkingTime() < edge.getLength()) {
break;
}
preprocessedGraph.addEdge(edge);
numberOfEdgesAdded += 1;
}
}
preprocessedGraph.orderEdges(Comparator.comparingInt(WalkingEdge::getId));
return preprocessedGraph;
}
}
| 44.098592 | 126 | 0.65123 |
f72a4df500bd7d348be1af0480385a506a62b264 | 615 | package org.zbus.net;
import org.zbus.net.core.Dispatcher;
import org.zbus.net.http.Message;
import org.zbus.net.http.MessageClient;
public class MyClient {
public static void main(String[] args) throws Exception {
final Dispatcher dispatcher = new Dispatcher();
final MessageClient client = new MessageClient("127.0.0.1:80", dispatcher);
Message msg = new Message();
msg.setRequestString("/hello?key=value");
msg.setBody("hello world");
for(int i=0;i<1;i++){
Message res = client.invokeSync(msg);
System.out.println(res);
}
client.close();
dispatcher.close();
}
}
| 22.777778 | 77 | 0.689431 |
67ae2a76d46c99adcaf16c5f9556eb1d55e22282 | 2,207 | package org.rays3d.builder.java.transform;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import org.rays3d.builder.java.AbstractBuilder;
import org.rays3d.transform.RotationTransform;
import org.rays3d.transform.ScaleTransform;
import org.rays3d.transform.Transform;
import org.rays3d.transform.Transformable;
import org.rays3d.transform.TranslationTransform;
public interface TransformableBuilder<T extends Transformable, TB extends TransformableBuilder<T, TB, P>, P extends AbstractBuilder<?, ?>>
extends AbstractBuilder<T, P> {
/**
* Return this builder's current list of configured
* {@link TransformBuilder}s.
*
* @return
*/
public Deque<TransformBuilder<?, TB>> getWorldToLocalBuilders();
/**
* Configure a new {@link RotationTransform} on this transformable object.
*
* @return
*/
public default RotationTransformBuilder<TB> rotate() {
@SuppressWarnings("unchecked")
final RotationTransformBuilder<TB> builder = new RotationTransformBuilder<>((TB) this);
getWorldToLocalBuilders().addLast(builder);
return builder;
}
/**
* Configure a new {@link ScaleTransform} on this transformable object.
*
* @return
*/
public default ScaleTransformBuilder<TB> scale() {
@SuppressWarnings("unchecked")
final ScaleTransformBuilder<TB> builder = new ScaleTransformBuilder<>((TB) this);
getWorldToLocalBuilders().addLast(builder);
return builder;
}
/**
* Configure a new {@link TranslationTransform} on this transformable
* object.
*
* @return
*/
public default TranslationTransformBuilder<TB> translate() {
@SuppressWarnings("unchecked")
final TranslationTransformBuilder<TB> builder = new TranslationTransformBuilder<>((TB) this);
getWorldToLocalBuilders().addLast(builder);
return builder;
}
/**
* Build the list of configured {@link TransformableBuilder}s and return it.
*
* @return
*/
public default List<Transform> buildWorldToLocalTransforms() {
return getWorldToLocalBuilders().stream().map(b -> b.build()).collect(Collectors.toCollection(LinkedList::new));
}
}
| 28.662338 | 139 | 0.721794 |
2c8f3b6e7d470a69b926052d24899664d9c1bfd0 | 6,021 | package dev.codesoapbox.dummy4j.dummies.finance;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ExtendWith(MockitoExtension.class)
class IbanFormulaTest {
private IbanFormula formula;
@BeforeEach
void setUp() {
formula = new IbanFormula();
}
/**
* Tests for example IBAN values
* @see <a href="https://www.swift.com/standards/data-standards/iban-international-bank-account-number">
* IBAN Registry</a>
*/
@ParameterizedTest
@CsvSource({
"1, A, 59",
"123, FA, 07",
"12345, A, 28",
"WEST12345698765432, GB, 82",
"WEST 1234 5698 765 432, GB, 82",
"WEST-1234-5698 765 432, GB, 82",
"00012030200359100100, AD, 12", // Andorra
"0331234567890123456, AE, 07", // United Arab Emirates
"212110090000000235698741, AL, 47", // Albania
"1904300234573201, AT, 61", // Austria
"NABZ00000000137010001944, AZ, 21", // Azerbaijan
"1290079401028494, BA, 39", // Bosnia and Herzegovina
"539007547034, BE, 68", // Belgium
"BNBG96611020345678, BG, 80", // Bulgaria
"BMAG00001299123456, BH, 67", // Bahrain
"00000000141455123924100C2, BR, 18", // Brazil
"NBRB3600900000002Z00AB00, BY, 13", // Republic of Belarus
"00762011623852957, CH, 93", // Switzerland
"015202001026284066, CR, 05", // Costa Rica
"002001280000001200527600, CY, 17", // Cyprus
"08000000192000145399, CZ, 65", // Czechoslovakia
"370400440532013000, DE, 89", // Germany
"00400440116243, DK, 50", // Denmark
"BAGR00000001212453611324, DO, 28", // Dominican Republic
"2200221020145685, EE, 38", // Estonia
"0019000500000000263180002, EG, 38", // Egypt
"23100001180000012345, ES, 80", // Spain
"12345600000785, FI, 21", // Finland
"64600001631634, FO, 62", // Faroe Islands
"20041010050500013M02606, FR, 14", // France
"NWBK60161331926819, GB, 29", // UK
"NB0000000101904917, GE, 29", // Georgia
"NWBK000000007099453, GI, 75", // Gibraltar
"64710001000206, GL, 89", // Greenland
"01101250000000012300695, GR, 16", // Greece
"TRAJ01020000001210029690, GT, 82", // Guatemala
"10010051863000160, HR, 12", // Croatia
"117730161111101800000000, HU, 42", // Hungary
"AIBK93115212345678, IE, 29", // Ireland
"0108000000099999999, IL, 62", // Israel
"NBIQ850123456789012, IQ, 98", // Iraq
"0159260076545510730339, IS, 14", // Iceland
"X0542811101000000123456, IT, 60", // Italy
"CBJO0010000000000131000302, JO, 94",// Jordan
"CBKU0000000000001234560101, KW, 81",// Kuwait
"125KZT5004100100, KZ, 86", // Kazakhstan
"099900000001001901229114, LB, 62", // Lebanon
"HEMM000100010012001200023015, LC, 55",//Saint Lucia
"088100002324013AA, LI, 21", // Liechtenstein
"1000011101001000, LT, 12", // Lithuania
"0019400644750000, LU, 28", // Luxembourg
"BANK0000435195001, LV, 80", // Latvia
"002048000020100120361, LY, 83", // Libya
"11222000010123456789030, MC, 58", // Monaco
"AG000225100013104168, MD, 24", // Moldova
"505000012345678951, ME, 25", // Montenegro
"250120000058984, MK, 07", // Macedonia
"00020001010000123456753, MR, 13", // Mauritania
"MALT011000012345MTLCAST001S, MT, 84",// Malta
"BOMM0101101030300200000MUR, MU, 17",// Mauritius
"ABNA0417164300, NL, 91", // Netherlands
"86011117947, NO, 93", // Norway
"SCBL0000001123456702, PK, 36", // Pakistan
"109010140000071219812874, PL, 61", // Poland
"PALS000000000400123456702, PS, 92", // Palestine
"000201231234567890154, PT, 50", // Portugal
"DOHB00001234567890ABCDEFG, QA, 58", // Qatar
"AAAA1B31007593840000, RO, 49", // Romania
"260005601001611379, RS, 35", // Serbia
"80000000608010167519, SA, 03", // Saudi Arabia
"SSCB11010000000000001497USD, SC, 18",// Seychelles
"50000000058398257466, SE, 45", // Sweden
"191000000123438, SI, 56", // Slovenia
"12000000198742637541, SK, 31", // Slovakia
"U0322509800000000270100, SM, 86", // San Marino
"000100010051845310146, ST, 23", // Sao Tome and Principe
"CENR00000000000000700025, SV, 62", // El Salvador
"0080012345678910157, TL, 38", // Timor-Leste
"10006035183598478831, TN, 59", // Tunisia
"0006100519786457841326, TR, 33", // Turkey
"3223130000026007233566001, UA, 21", // Ukraine
"001123000012345678, VA, 59", // Vatican City State
"VPVG0000012345678901, VG, 96", // Virgin Islands
"1212012345678906, XK, 05" // Kosovo
})
void shouldReturnCheckDigits(String accountNumber, String countryCode, String expected) {
String digits = formula.generateCheckDigits(accountNumber, countryCode);
assertEquals(expected, digits);
}
} | 51.025424 | 108 | 0.55705 |
c997b85a9b87282f16d05a30d8235fb805b5bdcf | 930 | package me.retrodaredevil.solarthing.message.event;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonTypeName;
import me.retrodaredevil.solarthing.message.MessageSender;
import me.retrodaredevil.solarthing.packets.Packet;
import me.retrodaredevil.solarthing.packets.collection.InstancePacketGroup;
import me.retrodaredevil.solarthing.type.event.feedback.ExecutionFeedbackPacket;
@JsonTypeName("feedback")
public class ExecutionFeedbackEvent implements MessageEvent {
@JsonCreator
public ExecutionFeedbackEvent() {
}
@Override
public void runForEvent(MessageSender sender, InstancePacketGroup packetGroup) {
for (Packet packet : packetGroup.getPackets()) {
if (packet instanceof ExecutionFeedbackPacket) {
ExecutionFeedbackPacket executionFeedbackPacket = (ExecutionFeedbackPacket) packet;
sender.sendMessage(executionFeedbackPacket.getMessage());
}
}
}
}
| 35.769231 | 87 | 0.826882 |
d923898ad67ae632eafde1913ad1a040cf4de3a2 | 1,477 | package com.github.salvatorenovelli.seo.websiteversioning.crawler.crawler4j;
import com.github.salvatorenovelli.seo.websiteversioning.domain.PatternGenerator;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.url.WebURL;
import java.util.regex.Pattern;
class DefaultWebCrawler extends WebCrawler {
private final Pattern patter;
private final String id;
DefaultWebCrawler(String baseDomain, String id) {
patter = PatternGenerator.generatePatternFor(baseDomain);
this.id = id;
}
@Override
public boolean shouldVisit(Page referringPage, WebURL url) {
return patter.matcher(url.getURL()).matches();
}
@Override
public void visit(Page page) {
String url = page.getWebURL().getURL();
System.out.println("URL: " + url);
//
// if (page.getParseData() instanceof HtmlParseData) {
// HtmlParseData htmlParseData = (HtmlParseData) page.getParseData();
// String text = htmlParseData.getText();
// String html = htmlParseData.getHtml();
// Set<WebURL> links = htmlParseData.getOutgoingUrls();
//
// System.out.println("Text length: " + text.length());
// System.out.println("Html length: " + html.length());
// System.out.println("Number of outgoing links: " + links.size());
// }
}
public String getId() {
return id;
}
}
| 31.425532 | 81 | 0.659445 |
2951987e0319326e899c3046d737aea241809ca1 | 3,082 | package sxg.main;
import java.nio.ByteBuffer;
public class BitMap {
public static final long LimitMaxValue = 0xffffffffl;
long max;
long offset;
ByteBuffer buffer;
public BitMap(long max, long offset) throws IllegalArgumentException {
long value = normalized(max, offset);
if (value == -1) {
String errInfo = String.format("非法的值[%d], 值必须在[%d, %d]之间", max, offset+1, offset+LimitMaxValue);
throw new IllegalArgumentException(errInfo);
}
grow(max);
}
//offset + 1 ~ offset + LimitMaxValue
private long normalized(long value, long offset) {
value = value - offset;
if (value > 0 && value <= LimitMaxValue) {
return value;
} else {
return -1;
}
}
private void grow(long max) {
if (max <= this.max) {
return;
}
this.max = max;
int index = (int)(max >>> 3);
byte mod = (byte)(max & 0x07);
if (mod == 0) {
index -= 1;
}
ByteBuffer newBuffer = ByteBuffer.allocate(index + 1);
if (buffer != null) {
buffer.position(0);
newBuffer.put(buffer);
}
buffer = newBuffer;
}
private byte mask(byte mod) {
if (mod == 0) {
return -128;
} else {
return (byte)(0x01 << (mod - 1));
}
}
public long offset() {
return offset;
}
public boolean existed(long value) {
value = normalized(value, offset);
if (value < 1 || value > max) {
return false;
}
int index = (int)(value >>> 3);
byte mod = (byte)(value & 0x07);
if (mod == 0) {
index -= 1;
}
short mask = mask(mod);
buffer.position(index);
return (buffer.get() & mask) != 0;
}
public void put(long value) throws IllegalArgumentException {
System.out.println("Put in " + value);
value = normalized(value, offset);
if (value == -1) {
String errInfo = String.format("非法的值[%d], 值必须在[%d, %d]之间", max, offset+1, offset+LimitMaxValue);
throw new IllegalArgumentException(errInfo);
}
if (value > max) {
grow(value);
}
int index = (int)(value >>> 3);
byte mod = (byte)(value & 0x07);
if (mod == 0) {
index -= 1;
}
byte mask = mask(mod);
buffer.position(index);
byte origin = buffer.get();
buffer.position(index);
buffer.put((byte)(origin | mask));
}
public void remove(long value) {
value = normalized(value, offset);
if (value == -1) {
return;
}
int index = (int)(value >>> 3);
byte mod = (byte)(value & 0x07);
if (mod == 0) {
index -= 1;
}
byte mask = mask(mod);
buffer.position(index);
byte origin = buffer.get();
buffer.position(index);
buffer.put((byte)(origin & ~mask));
}
public static void main(String[] args) {
BitMap bigMap = new BitMap(10, 0); //range from (offset + 1) to (offset + 2^32)
bigMap.put(6);
bigMap.put(24);
bigMap.put(200000000);
System.out.println(bigMap.existed(6));
System.out.println(bigMap.existed(23));
System.out.println(bigMap.existed(24));
bigMap.remove(24);
System.out.println(bigMap.existed(24));
System.out.println(bigMap.existed(200000000));
}
}
| 23.526718 | 100 | 0.592472 |
b91ac9f90a2c00a5ff508aca1160befc96fedd43 | 5,229 | package edu.rice.rubis.servlets;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/** This servlets displays the full description of a given item
* and allows the user to bid on this item.
* It must be called this way :
* <pre>
* http://..../ViewItem?itemId=xx where xx is the id of the item
* /<pre>
* @author <a href="mailto:[email protected]">Emmanuel Cecchet</a> and <a href="mailto:[email protected]">Julie Marguerite</a>
* @version 1.0
*/
public class ViewItem extends RubisHttpServlet
{
public int getPoolSize()
{
return Config.ViewItemPoolSize;
}
/**
* Close both statement and connection to the database.
*/
private void closeConnection(PreparedStatement stmt, Connection conn)
{
try
{
if (stmt != null)
stmt.close(); // close statement
if (conn != null)
releaseConnection(conn);
}
catch (Exception ignore)
{
}
}
/**
* Display an error message.
* @param errorMsg the error message value
*/
private void printError(String errorMsg, ServletPrinter sp)
{
sp.printHTMLheader("RUBiS ERROR: View item");
sp.printHTML(
"<h2>We cannot process your request due to the following error :</h2><br>");
sp.printHTML(errorMsg);
sp.printHTMLfooter();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
ServletPrinter sp = null;
PreparedStatement stmt = null;
Connection conn = null;
sp = new ServletPrinter(response, "ViewItem");
ResultSet rs = null;
String value = request.getParameter("itemId");
if ((value == null) || (value.equals("")))
{
printError("No item identifier received - Cannot process the request<br>", sp);
return;
}
Integer itemId = new Integer(value);
// get the item
try
{
conn = getConnection();
stmt = conn.prepareStatement("SELECT * FROM items WHERE id=?");
stmt.setInt(1, itemId.intValue());
rs = stmt.executeQuery();
}
catch (Exception e)
{
sp.printHTML("Failed to execute Query for item: " + e);
closeConnection(stmt, conn);
return;
}
/**
try
{
if (!rs.first())
{
stmt.close();
stmt = conn.prepareStatement("SELECT * FROM old_items WHERE id=?");
stmt.setInt(1, itemId.intValue());
rs = stmt.executeQuery();
}
}
catch (Exception e)
{
sp.printHTML("Failed to execute Query for item in table old_items: " + e);
closeConnection(stmt, conn);
return;
}
*/
try
{
if (!rs.first())
{
sp.printHTML("<h2>This item does not exist!</h2>");
closeConnection(stmt, conn);
return;
}
String itemName, endDate, startDate, description, sellerName;
float maxBid, initialPrice, buyNow, reservePrice;
int quantity, sellerId, nbOfBids = 0;
itemName = rs.getString("name");
description = rs.getString("description");
endDate = rs.getString("end_date");
startDate = rs.getString("start_date");
initialPrice = rs.getFloat("initial_price");
reservePrice = rs.getFloat("reserve_price");
buyNow = rs.getFloat("buy_now");
quantity = rs.getInt("quantity");
sellerId = rs.getInt("seller");
maxBid = rs.getFloat("max_bid");
nbOfBids = rs.getInt("nb_of_bids");
if (maxBid < initialPrice)
maxBid = initialPrice;
PreparedStatement sellerStmt = null;
try
{
sellerStmt =
conn.prepareStatement("SELECT nickname FROM users WHERE id=?");
sellerStmt.setInt(1, sellerId);
ResultSet sellerResult = sellerStmt.executeQuery();
// Get the seller's name
if (sellerResult.first())
sellerName = sellerResult.getString("nickname");
else
{
sp.printHTML("Unknown seller");
sellerStmt.close();
closeConnection(stmt, conn);
return;
}
sellerStmt.close();
}
catch (SQLException e)
{
sp.printHTML("Failed to executeQuery for seller: " + e);
sellerStmt.close();
closeConnection(stmt, conn);
return;
}
sp.printItemDescription(
itemId.intValue(),
itemName,
description,
initialPrice,
reservePrice,
buyNow,
quantity,
maxBid,
nbOfBids,
sellerName,
sellerId,
startDate,
endDate,
-1,
conn);
}
catch (Exception e)
{
printError("Exception getting item list: " + e + "<br>", sp);
}
closeConnection(stmt, conn);
sp.printHTMLfooter();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
doGet(request, response);
}
/**
* Clean up the connection pool.
*/
public void destroy()
{
super.destroy();
}
}
| 25.632353 | 137 | 0.61331 |
42215b030498ac18b8258c61ffccde33e7db25e1 | 598 | package com.aumum.app.mobile.core.service;
import com.aumum.app.mobile.core.Constants;
import com.aumum.app.mobile.core.api.ListWrapper;
import com.aumum.app.mobile.core.model.EventCategory;
import retrofit.http.GET;
import retrofit.http.Query;
/**
* Created by Administrator on 21/03/2015.
*/
public interface EventCategoryService {
@GET(Constants.Http.URL_EVENT_CATEGORIES_FRAG)
ListWrapper<EventCategory> getList(@Query("order") String order,
@Query("where") String where,
@Query("limit") int limit);
}
| 29.9 | 68 | 0.668896 |
3d0e14f2a6b6f79b129d0582648dc2336fac0d7b | 1,187 | package nxt.http;
import nxt.Account;
import nxt.Escrow;
import nxt.NxtException;
import nxt.util.Convert;
import org.json.simple.JSONObject;
import org.json.simple.JSONStreamAware;
import javax.servlet.http.HttpServletRequest;
public final class GetEscrowTransaction extends APIServlet.APIRequestHandler {
static final GetEscrowTransaction instance = new GetEscrowTransaction();
private GetEscrowTransaction() {
super(new APITag[] {APITag.ACCOUNTS}, "escrow");
}
@Override
JSONStreamAware processRequest(HttpServletRequest req) throws NxtException {
Long escrowId;
try {
escrowId = Convert.parseUnsignedLong(Convert.emptyToNull(req.getParameter("escrow")));
}
catch(Exception e) {
JSONObject response = new JSONObject();
response.put("errorCode", 3);
response.put("errorDescription", "Invalid or not specified escrow");
return response;
}
Escrow escrow = Escrow.getEscrowTransaction(escrowId);
if(escrow == null) {
JSONObject response = new JSONObject();
response.put("errorCode", 5);
response.put("errorDescription", "Escrow transaction not found");
return response;
}
return JSONData.escrowTransaction(escrow);
}
}
| 26.377778 | 89 | 0.751474 |
dc3d044a528825f1c45cdc44f8043bf694d46e31 | 877 | package com.taihui.springboot.db.entity;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
@Table(name = "t_role")
@Entity
public class Role implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected Integer id;
protected String name;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
protected Date createDate;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
}
| 19.931818 | 60 | 0.657925 |
79ddc4f5ea3b527e3683d6fdb2a50fafbab09312 | 1,696 | /*
* Copyright (c) 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.util;
import com.google.api.client.testing.util.MockBackOff;
import com.google.api.client.testing.util.MockSleeper;
import junit.framework.TestCase;
/**
* Tests {@link BackOffUtils}.
*
* @author Yaniv Inbar
*/
public class BackOffUtilsTest extends TestCase {
public void testNext() throws Exception {
subtestNext(7);
subtestNext(0);
subtestNext(BackOff.STOP);
}
public void subtestNext(long millis) throws Exception {
MockSleeper sleeper = new MockSleeper();
MockBackOff backOff = new MockBackOff().setBackOffMillis(millis);
if (millis == BackOff.STOP) {
backOff.setMaxTries(0);
}
int retries = 0;
while (retries <= backOff.getMaxTries() + 1) {
boolean next = BackOffUtils.next(sleeper, backOff);
assertEquals(retries < backOff.getMaxTries(), next);
if (next) {
retries++;
}
assertEquals(retries, sleeper.getCount());
assertEquals(retries, backOff.getNumberOfTries());
if (!next) {
break;
}
assertEquals(millis, sleeper.getLastMillis());
}
}
}
| 30.285714 | 100 | 0.694575 |
ed4d3150f3964b1fdb68037f95c193a5a0434b10 | 491 | package com.neo.springexamples.ioc.context.pojo.annotation;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class TestDemo {
@Setter
@Getter
private String demo;
public TestDemo() {
log.info("-----------new TestDemo()--------------");
this.demo = "demo";
}
public TestDemo(double random) {
log.info("-----------new TestDemo(random)--------------");
this.demo = "demo" + random;
}
}
| 20.458333 | 66 | 0.570265 |
98c78c0d1374d8aacf4402d23faa41ef416128a7 | 6,358 | /*
* SoapUI, Copyright (C) 2004-2016 SmartBear Software
*
* Licensed under the EUPL, Version 1.1 or - as soon as they will be approved by the European Commission - subsequent
* versions of the EUPL (the "Licence");
* You may not use this work except in compliance with the Licence.
* You may obtain a copy of the Licence at:
*
* http://ec.europa.eu/idabc/eupl
*
* Unless required by applicable law or agreed to in writing, software distributed under the Licence is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the Licence for the specific language governing permissions and limitations
* under the Licence.
*/
package com.eviware.soapui.impl.rest.support;
import com.eviware.soapui.impl.rest.RestURIParser;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
/**
* Basic RestURIParser using java's .net.URI and .net.URL class
*
* @author Shadid Chowdhury
* @since 4.5.6
*/
public class RestURIParserImpl implements RestURIParser {
private static final String SCHEME_SEPARATOR = "://";
private static final String DEFAULT_SCHEME = "http";
private String resourcePath = "";
private String query = "";
private String scheme = "";
private String authority = "";
public RestURIParserImpl(String uriString) throws MalformedURLException {
preValidation(uriString);
parseURI(uriString);
postValidation();
}
private void preValidation(String uriString) throws MalformedURLException {
if (uriString == null || uriString.isEmpty()) {
throw new MalformedURLException("Empty URI");
}
}
private void parseURI(String uriString) throws MalformedURLException {
try {
if (isAPossibleEndPointWithoutScheme(uriString)) {
uriString = DEFAULT_SCHEME + SCHEME_SEPARATOR + uriString;
}
parseWithURI(uriString);
} catch (URISyntaxException e) {
parseWithURL(uriString);
}
}
private void postValidation() throws MalformedURLException {
if (!validateScheme()) {
throw new MalformedURLException("URI contains unsupported protocol. Supported protocols are HTTP/HTTPS");
} else if (!validateAuthority()) {
throw new MalformedURLException("Invalid endpoint");
}
}
private boolean validateScheme() throws MalformedURLException {
String scheme = getScheme();
return scheme.isEmpty() || scheme.matches("(HTTP|http).*");
}
private boolean validateAuthority() throws MalformedURLException {
String endpoint = getEndpoint();
return endpoint.isEmpty() || !endpoint.matches(".*[\\\\]+.*");
}
@Override
public String getEndpoint() {
String endpoint;
if (authority.isEmpty()) {
endpoint = "";
} else if (scheme.isEmpty()) {
endpoint = DEFAULT_SCHEME + SCHEME_SEPARATOR + authority;
} else {
endpoint = scheme + SCHEME_SEPARATOR + authority;
}
return endpoint;
}
@Override
public String getResourceName() {
String path = getResourcePath();
if (path.isEmpty()) {
return path;
}
String[] splitResourcePath = path.split("/");
if (splitResourcePath.length == 0) {
return "";
}
String resourceName = splitResourcePath[splitResourcePath.length - 1];
if (resourceName.startsWith(";")) {
return "";
}
resourceName = resourceName.replaceAll("\\{", "").replaceAll("\\}", "");
if (resourceName.contains(";")) {
resourceName = resourceName.substring(0, resourceName.indexOf(";"));
}
return resourceName.substring(0, 1).toUpperCase() + resourceName.substring(1);
}
@Override
public String getScheme() {
return scheme;
}
@Override
public String getResourcePath() {
String path = resourcePath;
path = addPrefixSlash(path);
return path;
}
@Override
public String getQuery() {
return query;
}
private String addPrefixSlash(String path) {
if (!path.startsWith("/") && !path.isEmpty()) {
path = "/" + path;
}
return path;
}
private void parseWithURI(String uriString) throws URISyntaxException {
URI uri = new URI(uriString);
resourcePath = (uri.getPath() == null ? "" : uri.getPath());
query = (uri.getQuery() == null ? "" : uri.getQuery());
scheme = (uri.getScheme() == null ? "" : uri.getScheme());
authority = (uri.getAuthority() == null ? "" : uri.getAuthority());
}
private boolean isURIWithoutScheme(String uriString) {
return !uriString.matches("[a-zA-Z]+\\:[\\/\\/]+.*");
}
private boolean isAPossibleEndPointWithoutScheme(String uriString) {
int indexOfDot = uriString.indexOf(".");
return indexOfDot > 0 && isURIWithoutScheme(uriString);
}
private void parseWithURL(String uriString) throws MalformedURLException {
URL url;
try {
url = new URL(uriString);
resourcePath = (url.getPath() == null ? "" : url.getPath());
query = (url.getQuery() == null ? "" : url.getQuery());
scheme = (url.getProtocol() == null ? "" : url.getProtocol());
authority = (url.getAuthority() == null ? "" : url.getAuthority());
} catch (MalformedURLException e) {
parseManually(uriString);
}
}
private void parseManually(String uriString) {
resourcePath = uriString;
query = "";
scheme = "";
authority = "";
int startIndexOfQuery = uriString.indexOf('?');
if (startIndexOfQuery >= 0) {
query = uriString.substring(startIndexOfQuery + 1);
resourcePath = uriString.substring(0, startIndexOfQuery);
}
int startIndexOfResource = resourcePath.indexOf('/');
if (startIndexOfResource >= 0) {
resourcePath = resourcePath.substring(startIndexOfResource + 1);
authority = resourcePath.substring(0, startIndexOfResource);
}
}
}
| 30.714976 | 118 | 0.6134 |
e06956efdb2d5aef0d506ba6dd75a9b290f7f710 | 1,238 | package com.example.android.quakereport;
/**
* Created by Capri on 25.04.2018.
*/
public class Earthquake {
private double mMagnitude;
private String mCity;
private long mTimeInMilliseconds;
private String mUrl;
// Create a new Earthquake object.
public Earthquake(double magnitude, String city, long timeInMilliseconds, String url) {
mMagnitude = magnitude;
mCity = city;
mTimeInMilliseconds = timeInMilliseconds;
mUrl = url;
}
// Get the magnitude of the earthquake.
public double getMagnitude() {
return mMagnitude;
}
// Get the city of the earthquake.
public String getCity() {
return mCity;
}
// Get the date and time of the earthquake.
public long getTimeInMilliseconds() {
return mTimeInMilliseconds;
}
// Get the url of the earthquake.
public String getUrl() {
return mUrl;
}
@Override
public String toString() {
return "Earthquake{" +
"mMagnitude=" + mMagnitude +
", mCity='" + mCity + '\'' +
", mTimeInMilliseconds=" + mTimeInMilliseconds +
", mUrl='" + mUrl + '\'' +
'}';
}
}
| 23.807692 | 91 | 0.584006 |
11ba3896ef2b166a020f71c00652793e3377a679 | 612 | package l04_Introducing_Objects_P2;
/**
* Card Ranks as they appear on the card.
*/
public class Ranks {
public static final int TWO = 0;
public static final int THREE = 1;
public static final int FOUR = 2;
public static final int FIVE = 3;
public static final int SIX = 4;
public static final int SEVEN = 5;
public static final int EIGHT = 6;
public static final int NINE = 7;
public static final int TEN = 8;
public static final int JACK = 9;
public static final int QUEEN = 10;
public static final int KING = 11;
public static final int ACE = 12;
}
| 27.818182 | 41 | 0.665033 |
5633e743929d3c95f76af9080df0aebbd27d50a6 | 750 | package com.webside.shiro.filter;
import javax.inject.Inject;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.PathMatchingFilter;
import com.webside.user.mapper.UserMapper;
/**
*
* @author wjggwm
*
*/
public class SysUserFilter extends PathMatchingFilter {
@Inject
private UserMapper userMapper;
@Override
protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
String userName = (String)SecurityUtils.getSubject().getPrincipal();
request.setAttribute("user", userMapper.findByName(userName));
return true;
}
} | 26.785714 | 123 | 0.737333 |
49553cddfd936e3ad232f794f3ac0b29eaba302e | 787 | import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
public class ResizableCanvas extends Canvas {
public ResizableCanvas() {
// Redraw canvas when size changes.
widthProperty().addListener(evt -> draw());
heightProperty().addListener(evt -> draw());
}
@Override
public void resize(double width, double height)
{
super.setWidth(width);
super.setHeight(height);
}
private void draw() {
}
@Override
public boolean isResizable() {
return true;
}
@Override
public double prefWidth(double height) {
return getWidth();
}
@Override
public double prefHeight(double width) {
return getHeight();
}
} | 21.27027 | 52 | 0.631512 |
11cab85d61167b6ddced81b21c9344cd299b888f | 6,851 | /*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.csp.sentinel.config;
import com.alibaba.csp.sentinel.log.RecordLog;
import com.alibaba.csp.sentinel.util.AppNameUtil;
import com.alibaba.csp.sentinel.util.AssertUtil;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
/**
* The universal local configuration center of Sentinel. The config is retrieved from command line arguments
* and customized properties file by default.
*
* @author leyou
* @author Eric Zhao
*/
public class SentinelConfig {
/**
* The default application type.
*
* @since 1.6.0
*/
public static final int APP_TYPE_COMMON = 0;
private static final Map<String, String> props = new ConcurrentHashMap<>();
private static int appType = APP_TYPE_COMMON;
public static final String APP_TYPE = "csp.sentinel.app.type";
public static final String CHARSET = "csp.sentinel.charset";
public static final String SINGLE_METRIC_FILE_SIZE = "csp.sentinel.metric.file.single.size";
public static final String TOTAL_METRIC_FILE_COUNT = "csp.sentinel.metric.file.total.count";
public static final String COLD_FACTOR = "csp.sentinel.flow.cold.factor";
public static final String STATISTIC_MAX_RT = "csp.sentinel.statistic.max.rt";
static final String DEFAULT_CHARSET = "UTF-8";
static final long DEFAULT_SINGLE_METRIC_FILE_SIZE = 1024 * 1024 * 50;
static final int DEFAULT_TOTAL_METRIC_FILE_COUNT = 6;
static final int DEFAULT_COLD_FACTOR = 3;
static final int DEFAULT_STATISTIC_MAX_RT = 4900;
static {
try {
initialize();
loadProps();
resolveAppType();
RecordLog.info("[SentinelConfig] Application type resolved: " + appType);
} catch (Throwable ex) {
RecordLog.warn("[SentinelConfig] Failed to initialize", ex);
ex.printStackTrace();
}
}
private static void resolveAppType() {
try {
String type = getConfig(APP_TYPE);
if (type == null) {
appType = APP_TYPE_COMMON;
return;
}
appType = Integer.parseInt(type);
if (appType < 0) {
appType = APP_TYPE_COMMON;
}
} catch (Exception ex) {
appType = APP_TYPE_COMMON;
}
}
private static void initialize() {
// Init default properties.
setConfig(CHARSET, DEFAULT_CHARSET);
setConfig(SINGLE_METRIC_FILE_SIZE, String.valueOf(DEFAULT_SINGLE_METRIC_FILE_SIZE));
setConfig(TOTAL_METRIC_FILE_COUNT, String.valueOf(DEFAULT_TOTAL_METRIC_FILE_COUNT));
setConfig(COLD_FACTOR, String.valueOf(DEFAULT_COLD_FACTOR));
setConfig(STATISTIC_MAX_RT, String.valueOf(DEFAULT_STATISTIC_MAX_RT));
}
private static void loadProps() {
Properties properties = SentinelConfigLoader.getProperties();
for (Object key : properties.keySet()) {
setConfig((String) key, (String) properties.get(key));
}
}
/**
* Get config value of the specific key.
*
* @param key config key
* @return the config value.
*/
public static String getConfig(String key) {
AssertUtil.notNull(key, "key cannot be null");
return props.get(key);
}
public static void setConfig(String key, String value) {
AssertUtil.notNull(key, "key cannot be null");
AssertUtil.notNull(value, "value cannot be null");
props.put(key, value);
}
public static String removeConfig(String key) {
AssertUtil.notNull(key, "key cannot be null");
return props.remove(key);
}
public static void setConfigIfAbsent(String key, String value) {
AssertUtil.notNull(key, "key cannot be null");
AssertUtil.notNull(value, "value cannot be null");
String v = props.get(key);
if (v == null) {
props.put(key, value);
}
}
public static String getAppName() {
return AppNameUtil.getAppName();
}
/**
* Get application type.
*
* @return application type, common (0) by default
* @since 1.6.0
*/
public static int getAppType() {
return appType;
}
public static String charset() {
return props.get(CHARSET);
}
public static long singleMetricFileSize() {
try {
return Long.parseLong(props.get(SINGLE_METRIC_FILE_SIZE));
} catch (Throwable throwable) {
RecordLog.warn("[SentinelConfig] Parse singleMetricFileSize fail, use default value: "
+ DEFAULT_SINGLE_METRIC_FILE_SIZE, throwable);
return DEFAULT_SINGLE_METRIC_FILE_SIZE;
}
}
public static int totalMetricFileCount() {
try {
return Integer.parseInt(props.get(TOTAL_METRIC_FILE_COUNT));
} catch (Throwable throwable) {
RecordLog.warn("[SentinelConfig] Parse totalMetricFileCount fail, use default value: "
+ DEFAULT_TOTAL_METRIC_FILE_COUNT, throwable);
return DEFAULT_TOTAL_METRIC_FILE_COUNT;
}
}
public static int coldFactor() {
try {
int coldFactor = Integer.parseInt(props.get(COLD_FACTOR));
// check the cold factor larger than 1
if (coldFactor <= 1) {
coldFactor = DEFAULT_COLD_FACTOR;
RecordLog.warn("cold factor=" + coldFactor + ", should be larger than 1, use default value: "
+ DEFAULT_COLD_FACTOR);
}
return coldFactor;
} catch (Throwable throwable) {
RecordLog.warn("[SentinelConfig] Parse coldFactor fail, use default value: "
+ DEFAULT_COLD_FACTOR, throwable);
return DEFAULT_COLD_FACTOR;
}
}
public static int statisticMaxRt() {
try {
return Integer.parseInt(props.get(STATISTIC_MAX_RT));
} catch (Throwable throwable) {
RecordLog.warn("[SentinelConfig] Parse statisticMaxRt fail, use default value: "
+ DEFAULT_STATISTIC_MAX_RT, throwable);
return DEFAULT_STATISTIC_MAX_RT;
}
}
}
| 34.60101 | 109 | 0.638739 |
caee4f081e24988a4a12e4ac40a039dc7ec4bf8a | 343 | package com.protonail.leveldb.jna;
public class KeyValuePair {
private byte[] key;
private byte[] value;
public KeyValuePair(byte[] key, byte[] value) {
this.key = key;
this.value = value;
}
public byte[] getKey() {
return key;
}
public byte[] getValue() {
return value;
}
}
| 17.15 | 51 | 0.565598 |
cfa4d07c6e1945cfe4d6c53b697a6d40071733fa | 17,359 | package mil.dds.anet.database;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response.Status;
import org.joda.time.DateTime;
import org.skife.jdbi.v2.GeneratedKeys;
import org.skife.jdbi.v2.Handle;
import org.skife.jdbi.v2.Query;
import org.skife.jdbi.v2.TransactionCallback;
import org.skife.jdbi.v2.TransactionStatus;
import com.google.common.base.Joiner;
import mil.dds.anet.AnetObjectEngine;
import mil.dds.anet.beans.Organization;
import mil.dds.anet.beans.Organization.OrganizationType;
import mil.dds.anet.beans.Person;
import mil.dds.anet.beans.Poam;
import mil.dds.anet.beans.Report;
import mil.dds.anet.beans.Report.ReportState;
import mil.dds.anet.beans.ReportPerson;
import mil.dds.anet.beans.RollupGraph;
import mil.dds.anet.beans.lists.AbstractAnetBeanList.ReportList;
import mil.dds.anet.beans.search.OrganizationSearchQuery;
import mil.dds.anet.beans.search.ReportSearchQuery;
import mil.dds.anet.database.AdminDao.AdminSettingKeys;
import mil.dds.anet.database.mappers.PoamMapper;
import mil.dds.anet.database.mappers.ReportMapper;
import mil.dds.anet.database.mappers.ReportPersonMapper;
import mil.dds.anet.search.sqlite.SqliteReportSearcher;
import mil.dds.anet.utils.DaoUtils;
import mil.dds.anet.utils.Utils;
public class ReportDao implements IAnetDao<Report> {
private static String[] fields = { "id", "state", "createdAt", "updatedAt", "engagementDate",
"locationId", "approvalStepId", "intent", "exsum", "atmosphere", "cancelledReason",
"advisorOrganizationId", "principalOrganizationId", "releasedAt",
"atmosphereDetails", "text", "keyOutcomes",
"nextSteps", "authorId"};
private static String tableName = "reports";
public static String REPORT_FIELDS = DaoUtils.buildFieldAliases(tableName, fields);
Handle dbHandle;
public ReportDao(Handle db) {
this.dbHandle = db;
}
@Override
public ReportList getAll(int pageNum, int pageSize) {
String sql;
if (DaoUtils.isMsSql(dbHandle)) {
sql = "/* getAllReports */ SELECT " + REPORT_FIELDS + ", " + PersonDao.PERSON_FIELDS
+ ", COUNT(*) OVER() AS totalCount FROM reports, people "
+ "WHERE reports.authorId = people.id "
+ "ORDER BY reports.createdAt DESC OFFSET :offset ROWS FETCH NEXT :limit ROWS ONLY";
} else {
sql = "/* getAllReports */ SELECT " + REPORT_FIELDS + ", " + PersonDao.PERSON_FIELDS
+ "FROM reports, people "
+ "WHERE reports.authorId = people.id "
+ "ORDER BY reports.createdAt DESC LIMIT :limit OFFSET :offset";
}
Query<Report> query = dbHandle.createQuery(sql)
.bind("limit", pageSize)
.bind("offset", pageSize * pageNum)
.map(new ReportMapper());
return ReportList.fromQuery(query, pageNum, pageSize);
}
@Override
public Report insert(Report r) {
return dbHandle.inTransaction(new TransactionCallback<Report>() {
@Override
public Report inTransaction(Handle conn, TransactionStatus status) throws Exception {
r.setCreatedAt(DateTime.now());
r.setUpdatedAt(r.getCreatedAt());
//MSSQL requires explicit CAST when a datetime2 might be NULL.
StringBuilder sql = new StringBuilder("/* insertReport */ INSERT INTO reports "
+ "(state, createdAt, updatedAt, locationId, intent, exsum, "
+ "text, keyOutcomes, nextSteps, authorId, "
+ "engagementDate, releasedAt, atmosphere, cancelledReason, "
+ "atmosphereDetails, advisorOrganizationId, "
+ "principalOrganizationId) VALUES "
+ "(:state, :createdAt, :updatedAt, :locationId, :intent, "
+ ":exsum, :reportText, :keyOutcomes, "
+ ":nextSteps, :authorId, ");
if (DaoUtils.isMsSql(dbHandle)) {
sql.append("CAST(:engagementDate AS datetime2), CAST(:releasedAt AS datetime2), ");
} else {
sql.append(":engagementDate, :releasedAt, ");
}
sql.append(":atmosphere, :cancelledReason, :atmosphereDetails, :advisorOrgId, :principalOrgId)");
GeneratedKeys<Map<String, Object>> keys = dbHandle.createStatement(sql.toString())
.bindFromProperties(r)
.bind("state", DaoUtils.getEnumId(r.getState()))
.bind("atmosphere", DaoUtils.getEnumId(r.getAtmosphere()))
.bind("cancelledReason", DaoUtils.getEnumId(r.getCancelledReason()))
.bind("locationId", DaoUtils.getId(r.getLocation()))
.bind("authorId", DaoUtils.getId(r.getAuthor()))
.bind("advisorOrgId", DaoUtils.getId(r.getAdvisorOrg()))
.bind("principalOrgId", DaoUtils.getId(r.getPrincipalOrg()))
.executeAndReturnGeneratedKeys();
r.setId(DaoUtils.getGeneratedId(keys));
if (r.getAttendees() != null) {
//Setify based on attendeeId to prevent violations of unique key constraint.
Map<Integer,ReportPerson> attendeeMap = new HashMap<Integer,ReportPerson>();
r.getAttendees().stream().forEach(rp -> attendeeMap.put(rp.getId(), rp));
for (ReportPerson p : attendeeMap.values()) {
//TODO: batch this
dbHandle.createStatement("/* insertReport.attendee */ INSERT INTO reportPeople "
+ "(personId, reportId, isPrimary) VALUES (:personId, :reportId, :isPrimary)")
.bind("personId", p.getId())
.bind("reportId", r.getId())
.bind("isPrimary", p.isPrimary())
.execute();
}
}
if (r.getPoams() != null) {
for (Poam p : r.getPoams()) {
//TODO: batch this.
dbHandle.createStatement("/* insertReport.poam */ INSERT INTO reportPoams "
+ "(reportId, poamId) VALUES (:reportId, :poamId)")
.bind("reportId", r.getId())
.bind("poamId", p.getId())
.execute();
}
}
return r;
}
});
}
@Override
public Report getById(int id) {
Query<Report> query = dbHandle.createQuery("/* getReportById */ SELECT " + REPORT_FIELDS + ", " + PersonDao.PERSON_FIELDS
+ "FROM reports, people "
+ "WHERE reports.id = :id "
+ "AND reports.authorId = people.id")
.bind("id", id)
.map(new ReportMapper());
List<Report> results = query.list();
if (results.size() == 0) { return null; }
Report r = results.get(0);
return r;
}
@Override
public int update(Report r) {
r.setUpdatedAt(DateTime.now());
StringBuilder sql = new StringBuilder("/* updateReport */ UPDATE reports SET "
+ "state = :state, updatedAt = :updatedAt, locationId = :locationId, "
+ "intent = :intent, exsum = :exsum, text = :reportText, "
+ "keyOutcomes = :keyOutcomes, nextSteps = :nextSteps, "
+ "approvalStepId = :approvalStepId, ");
if (DaoUtils.isMsSql(dbHandle)) {
sql.append("engagementDate = CAST(:engagementDate AS datetime2), releasedAt = CAST(:releasedAt AS datetime2), ");
} else {
sql.append("engagementDate = :engagementDate, releasedAt = :releasedAt, ");
}
sql.append("atmosphere = :atmosphere, atmosphereDetails = :atmosphereDetails, "
+ "cancelledReason = :cancelledReason, "
+ "principalOrganizationId = :principalOrgId, advisorOrganizationId = :advisorOrgId "
+ "WHERE id = :id");
return dbHandle.createStatement(sql.toString())
.bindFromProperties(r)
.bind("state", DaoUtils.getEnumId(r.getState()))
.bind("locationId", DaoUtils.getId(r.getLocation()))
.bind("authorId", DaoUtils.getId(r.getAuthor()))
.bind("approvalStepId", DaoUtils.getId(r.getApprovalStep()))
.bind("atmosphere", DaoUtils.getEnumId(r.getAtmosphere()))
.bind("cancelledReason", DaoUtils.getEnumId(r.getCancelledReason()))
.bind("advisorOrgId", DaoUtils.getId(r.getAdvisorOrg()))
.bind("principalOrgId", DaoUtils.getId(r.getPrincipalOrg()))
.execute();
}
public int addAttendeeToReport(ReportPerson rp, Report r) {
return dbHandle.createStatement("/* addReportAttendee */ INSERT INTO reportPeople "
+ "(personId, reportId, isPrimary) VALUES (:personId, :reportId, :isPrimary)")
.bind("personId", rp.getId())
.bind("reportId", r.getId())
.bind("isPrimary", rp.isPrimary())
.execute();
}
public int removeAttendeeFromReport(Person p, Report r) {
return dbHandle.createStatement("/* deleteReportAttendee */ DELETE FROM reportPeople "
+ "WHERE reportId = :reportId AND personId = :personId")
.bind("reportId", r.getId())
.bind("personId", p.getId())
.execute();
}
public int updateAttendeeOnReport(ReportPerson rp, Report r) {
return dbHandle.createStatement("/* updateAttendeeOnReport*/ UPDATE reportPeople "
+ "SET isPrimary = :isPrimary WHERE reportId = :reportId AND personId = :personId")
.bind("reportId", r.getId())
.bind("personId", rp.getId())
.bind("isPrimary", rp.isPrimary())
.execute();
}
public int addPoamToReport(Poam p, Report r) {
return dbHandle.createStatement("/* addPoamToReport */ INSERT INTO reportPoams (poamId, reportId) "
+ "VALUES (:poamId, :reportId)")
.bind("reportId", r.getId())
.bind("poamId", p.getId())
.execute();
}
public int removePoamFromReport(Poam p, Report r) {
return dbHandle.createStatement("/* removePoamFromReport*/ DELETE FROM reportPoams "
+ "WHERE reportId = :reportId AND poamId = :poamId")
.bind("reportId", r.getId())
.bind("poamId", p.getId())
.execute();
}
public List<ReportPerson> getAttendeesForReport(int reportId) {
return dbHandle.createQuery("/* getAttendeesForReport */ SELECT " + PersonDao.PERSON_FIELDS
+ ", reportPeople.isPrimary FROM reportPeople "
+ "LEFT JOIN people ON reportPeople.personId = people.id "
+ "WHERE reportPeople.reportId = :reportId")
.bind("reportId", reportId)
.map(new ReportPersonMapper())
.list();
}
public List<Poam> getPoamsForReport(Report report) {
return dbHandle.createQuery("/* getPoamsForReport */ SELECT * FROM poams, reportPoams "
+ "WHERE reportPoams.reportId = :reportId "
+ "AND reportPoams.poamId = poams.id")
.bind("reportId", report.getId())
.map(new PoamMapper())
.list();
}
//Does an unauthenticated search. This will never return any DRAFT or REJECTED reports
public ReportList search(ReportSearchQuery query) {
return search(query, null);
}
public ReportList search(ReportSearchQuery query, Person user) {
return AnetObjectEngine.getInstance().getSearcher().getReportSearcher()
.runSearch(query, dbHandle, user);
}
/*
* Deletes a given report from the database.
* Ensures consistency by removing all references to a report before deleting a report.
*/
public void deleteReport(final Report report) {
dbHandle.inTransaction(new TransactionCallback<Void>() {
public Void inTransaction(Handle conn, TransactionStatus status) throws Exception {
//Delete poams
dbHandle.execute("/* deleteReport.poams */ DELETE FROM reportPoams where reportId = ?", report.getId());
//Delete attendees
dbHandle.execute("/* deleteReport.attendees */ DELETE FROM reportPeople where reportId = ?", report.getId());
//Delete comments
dbHandle.execute("/* deleteReport.comments */ DELETE FROM comments where reportId = ?", report.getId());
//Delete approvalActions
dbHandle.execute("/* deleteReport.actions */ DELETE FROM approvalActions where reportId = ?", report.getId());
//Delete report
dbHandle.execute("/* deleteReport.report */ DELETE FROM reports where id = ?", report.getId());
return null;
}
});
}
private DateTime getRollupEngagmentStart(DateTime start) {
String maxReportAgeStr = AnetObjectEngine.getInstance().getAdminSetting(AdminSettingKeys.DAILY_ROLLUP_MAX_REPORT_AGE_DAYS);
if (maxReportAgeStr == null) {
throw new WebApplicationException("Missing Admin Setting for " + AdminSettingKeys.DAILY_ROLLUP_MAX_REPORT_AGE_DAYS);
}
Integer maxReportAge = Integer.parseInt(maxReportAgeStr);
return start.minusDays(maxReportAge);
}
/* Generates the Rollup Graph for a particular Organization Type, starting at the root of the org hierarchy */
public List<RollupGraph> getDailyRollupGraph(DateTime start, DateTime end, OrganizationType orgType) {
List<Map<String, Object>> results = rollupQuery(start, end, orgType, null, false);
Map<Integer,Organization> orgMap = AnetObjectEngine.getInstance().buildTopLevelOrgHash(orgType);
return generateRollupGraphFromResults(results, orgMap);
}
/* Generates a Rollup graph for a particular organiztaion. Starting with a given parent Organization */
public List<RollupGraph> getDailyRollupGraph(DateTime start, DateTime end, Integer parentOrgId, OrganizationType orgType) {
List<Organization> orgList = null;
Map<Integer,Organization> orgMap;
if (parentOrgId.equals(-1) == false) { // -1 is code for no parent org.
//doing this as two separate queries because I do need all the information about the organizations
OrganizationSearchQuery query = new OrganizationSearchQuery();
query.setParentOrgId(parentOrgId);
query.setParentOrgRecursively(true);
query.setPageSize(Integer.MAX_VALUE);
orgList = AnetObjectEngine.getInstance().getOrganizationDao().search(query).getList();
Optional<Organization> parentOrg = orgList.stream().filter(o -> o.getId().equals(parentOrgId)).findFirst();
if (parentOrg.isPresent() == false) {
throw new WebApplicationException("No such organization with id " + parentOrgId, Status.NOT_FOUND);
}
orgMap = Utils.buildParentOrgMapping(orgList, parentOrgId);
} else {
orgMap = new HashMap<Integer, Organization>(); //guaranteed to match no orgs!
}
List<Map<String,Object>> results = rollupQuery(start, end, orgType, orgList, parentOrgId.equals(-1));
return generateRollupGraphFromResults(results, orgMap);
}
/** Helper method that builds and executes the daily rollup query
* Handles both MsSql and Sqlite
* Searching for just all reports and for reports in certain organizations.
* @param orgType: the type of organization Id to be lookinf ro
* @param orgs: the list of orgs for whose reports to find, null means all
* @param missingOrgReports: true if we want to look for reports specifically with NULL org Ids.
*/
private List<Map<String,Object>> rollupQuery(DateTime start,
DateTime end,
OrganizationType orgType,
List<Organization> orgs,
boolean missingOrgReports) {
String orgColumn = orgType == OrganizationType.ADVISOR_ORG ? "advisorOrganizationId" : "principalOrganizationId";
Map<String,Object> sqlArgs = new HashMap<String,Object>();
StringBuilder sql = new StringBuilder();
sql.append("/* RollupQuery */ SELECT " + orgColumn + " as orgId, state, count(*) AS count ");
sql.append("FROM reports WHERE ");
if (DaoUtils.isMsSql(dbHandle)) {
sql.append("releasedAt >= :startDate and releasedAt <= :endDate "
+ "AND engagementDate > :engagementDateStart ");
sqlArgs.put("startDate", start);
sqlArgs.put("endDate", end);
sqlArgs.put("engagementDateStart", getRollupEngagmentStart(start));
} else {
sql.append("releasedAt >= DateTime(:startDate) AND releasedAt <= DateTime(:endDate) "
+ "AND engagementDate > DateTime(:engagementDateStart) ");
sqlArgs.put("startDate", SqliteReportSearcher.sqlitePattern.print(start));
sqlArgs.put("endDate", SqliteReportSearcher.sqlitePattern.print(end));
sqlArgs.put("engagementDateStart", SqliteReportSearcher.sqlitePattern.print(getRollupEngagmentStart(start)));
}
if (orgs != null) {
List<String> sqlBind = new LinkedList<String>();
int orgNum = 0;
for (Organization o : orgs) {
sqlArgs.put("orgId" + orgNum, o.getId());
sqlBind.add(":orgId" + orgNum);
orgNum++;
}
String orgInSql = Joiner.on(',').join(sqlBind);
sql.append("AND " + orgColumn + " IN (" + orgInSql + ") ");
} else if (missingOrgReports) {
sql.append(" AND " + orgColumn + " IS NULL ");
}
sql.append("GROUP BY " + orgColumn + ", state");
return dbHandle.createQuery(sql.toString())
.bindFromMap(sqlArgs)
.list();
}
/* Given the results from the database on the number of reports grouped by organization
* And the map of each organization to the organization that their reports roll up to
* this method returns the final rollup graph information.
*/
private List<RollupGraph> generateRollupGraphFromResults(List<Map<String,Object>> dbResults, Map<Integer, Organization> orgMap) {
Map<Integer,Map<ReportState,Integer>> rollup = new HashMap<Integer,Map<ReportState,Integer>>();
for (Map<String,Object> result : dbResults) {
Integer orgId = (Integer) result.get("orgId");
Integer count = (Integer) result.get("count");
ReportState state = ReportState.values()[(Integer) result.get("state")];
Integer parentOrgId = (orgId == null) ? null : DaoUtils.getId(orgMap.get(orgId));
Map<ReportState,Integer> orgBar = rollup.get(parentOrgId);
if (orgBar == null) {
orgBar = new HashMap<ReportState,Integer>();
rollup.put(parentOrgId, orgBar);
}
orgBar.put(state, Utils.orIfNull(orgBar.get(state), 0) + count);
}
List<RollupGraph> result = new LinkedList<RollupGraph>();
for (Map.Entry<Integer, Map<ReportState,Integer>> entry : rollup.entrySet()) {
Map<ReportState,Integer> values = entry.getValue();
RollupGraph bar = new RollupGraph();
bar.setOrg(orgMap.get(entry.getKey()));
bar.setReleased(Utils.orIfNull(values.get(ReportState.RELEASED), 0));
bar.setCancelled(Utils.orIfNull(values.get(ReportState.CANCELLED), 0));
result.add(bar);
}
return result;
}
}
| 41.232779 | 131 | 0.707184 |
fba49280a7ec265231d97fb30460e00a4ec4489f | 312 | package com.gzc.cloud.dao;
import com.gzc.cloud.domain.Order;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface OrderDao {
void create(Order order);
void update(@Param("userId") Long userId, @Param("status") Integer status);
}
| 22.285714 | 79 | 0.762821 |
a274d0607bc903dc4ddb6226e3c08986a3fb61bd | 2,337 | package com.nshmura.recyclertablayout.demo.years;
import com.nshmura.recyclertablayout.RecyclerTabLayout;
import com.nshmura.recyclertablayout.demo.Demo;
import com.nshmura.recyclertablayout.demo.R;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class DemoYearsActivity extends AppCompatActivity {
protected static final String KEY_DEMO = "demo";
public static void startActivity(Context context, Demo demo) {
Intent intent = new Intent(context, DemoYearsActivity.class);
intent.putExtra(KEY_DEMO, demo.name());
context.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo_basic);
Demo demo = Demo.valueOf(getIntent().getStringExtra(KEY_DEMO));
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(demo.titleResId);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
int startYear = 1900;
int endYear = 3000;
int initialYear = Calendar.getInstance().get(Calendar.YEAR);
List<String> items = new ArrayList<>();
for (int i = startYear; i <= endYear; i++) {
items.add(String.valueOf(i));
}
DemoYearsPagerAdapter adapter = new DemoYearsPagerAdapter();
adapter.addAll(items);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(initialYear - startYear);
RecyclerTabLayout recyclerTabLayout = (RecyclerTabLayout)
findViewById(R.id.recycler_tab_layout);
recyclerTabLayout.setUpWithViewPager(viewPager);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
} | 32.915493 | 72 | 0.69662 |
96cf8e3c2724d9ed29b0846de692611a2030defc | 247 | package ru.schernigin.list;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
/**
* class ArrayListTest.
* @author schernigin
* @since 8.02.2017
* @version 1.0
*/
public class ArrayListTest {
} | 16.466667 | 38 | 0.716599 |
6082bedb1f03a07cb7704f5d047dccdd87e1c21b | 761 | package com.yirendai.oss.lib.webmvc.starter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
/**
* Created by Meifans on 17/1/9.
*/
@ConditionalOnClass(name = "com.fasterxml.jackson.databind.ObjectMapper")
@Configuration
public class Jackson2Configuration {
@Autowired(required = false)
private Environment environment;
@Autowired(required = false)
public void setObjectMapper(final com.fasterxml.jackson.databind.ObjectMapper objectMapper) {
com.yirendai.oss.lib.common.Jackson2Utils.setupObjectMapper(this.environment, objectMapper);
}
}
| 33.086957 | 96 | 0.812089 |
aabeaa879bbe0868dcc72f24680d6a2d21777708 | 2,931 | package com.gxl.core.tracing;
import java.io.Serializable;
import com.alibaba.dubbo.common.URL;
/***
*
* <p>description:</p>
* @author songkejun
* @since 2017年7月24日下午4:25:04
*/
public class TraceBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Long traceId = -1L;
private Integer parentSpanId = -1;
private Integer spanId = 0;
private String host;
private Integer port;
private String serviceName;
private String methodName;
/* 事件类型,0为调用方,1为提供方 */
private Integer eventType;
/* 服务调用结果状态,0成功,1异常 */
private Integer resultState;
/* 根调用标记 */
private boolean isRootSpan = false;
private String isSampling;
private URL provider;
private URL consumer;
private long duration;
private Object[] args;
@SuppressWarnings("rawtypes")
private Class[] paraTypes;
public URL getProvider() {
return provider;
}
public void setProvider(URL provider) {
this.provider = provider;
}
public URL getConsumer() {
return consumer;
}
public void setConsumer(URL consumer) {
this.consumer = consumer;
}
public long getDuration() {
return duration;
}
public void setDuration(long duration) {
this.duration = duration;
}
public Object[] getArgs() {
return args;
}
public void setArgs(Object[] args) {
this.args = args;
}
public Class[] getParaTypes() {
return paraTypes;
}
public void setParaTypes(Class[] paraTypes) {
this.paraTypes = paraTypes;
}
public String getIsSampling() {
return isSampling;
}
public void setIsSampling(String isSampling) {
this.isSampling = isSampling;
}
public boolean isRootSpan() {
return isRootSpan;
}
public void setRootSpan(boolean isRootSpan) {
this.isRootSpan = isRootSpan;
}
public Integer getParentSpanId() {
return parentSpanId;
}
public void setParentSpanId(Integer parentSpanId) {
this.parentSpanId = parentSpanId;
}
public Long getTraceId() {
return traceId;
}
public void setTraceId(Long traceId) {
this.traceId = traceId;
}
public Integer getSpanId() {
return spanId;
}
public void setSpanId(Integer spanId) {
this.spanId = spanId;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
public Integer getEventType() {
return eventType;
}
public void setEventType(Integer eventType) {
this.eventType = eventType;
}
public Integer getResultState() {
return resultState;
}
public void setResultState(Integer resultState) {
this.resultState = resultState;
}
} | 17.241176 | 52 | 0.711361 |
c350ace94ec9dd12ed05db7a03e7f7b2b8150c4d | 4,500 | package algorithm.leetcode;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import utils.JsonHelper;
import java.util.*;
/**
* 滑动窗口中位数
*
* 中位数是有序序列最中间的那个数。如果序列的长度是偶数,则没有最中间的数;
* 此时中位数是最中间的两个数的平均数。
*
* 例如:
*
* [2,3,4],中位数是3
* [2,3],中位数是 (2 + 3) / 2 = 2.5
* 给你一个数组 nums,有一个长度为 k 的窗口从最左端滑动到最右端。
* 窗口中有 k 个数,每次窗口向右移动 1 位。
* 你的任务是找出每次窗口移动后得到的新窗口中元素的中位数,并输出由它们组成的数组。
*
*
*
* 示例:
*
* 给出nums = [1,3,-1,-3,5,3,6,7],以及k = 3。
*
* 窗口位置 中位数
* --------------- -----
* [1 3 -1] -3 5 3 6 7 1
* 1 [3 -1 -3] 5 3 6 7 -1
* 1 3 [-1 -3 5] 3 6 7 -1
* 1 3 -1 [-3 5 3] 6 7 3
* 1 3 -1 -3 [5 3 6] 7 5
* 1 3 -1 -3 5 [3 6 7] 6
* 因此,返回该滑动窗口的中位数数组[1,-1,-1,3,5,6]。
*
*
*
* 提示:
*
* 你可以假设k始终有效,即:k 始终小于输入的非空数组的元素个数。
* 与真实值误差在 10 ^ -5 以内的答案将被视作正确答案。
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/sliding-window-median
*/
@Slf4j
public class MedianSlidingWindow {
// 动窗口/双重优先队列滑
public double[] medianSlidingWindow(int[] nums, int k) {
int len = nums.length;
double[] res = new double[len - k + 1];
DualHeap dh = new DualHeap(k);
for (int i = 0; i < k; i++) {
dh.insert(nums[i]);
}
int index = 0;
res[index++] = dh.getMedian();
int left = 0;
int right = k;
while (right < len) {
dh.insert(nums[right]);
dh.delete(nums[left]);
left++;
right++;
res[index++] = dh.getMedian();
}
return res;
}
private class DualHeap {
private int k;
// 大数队列
private PriorityQueue<Integer> large;
// 小数队列
private PriorityQueue<Integer> small;
// 延迟删除哈希表
Map<Integer, Integer> delays;
int largeSize;
int smallSize;
public DualHeap(int k) {
small = new PriorityQueue<>(Comparator.reverseOrder());
large = new PriorityQueue<>(Comparator.naturalOrder());
delays = new HashMap<>();
largeSize = 0;
smallSize = 0;
this.k = k;
}
public double getMedian() {
if (k % 2 == 0) {
return ((double) small.peek() + large.peek()) / 2;
}
return small.peek();
}
public void insert(int num) {
if (small.isEmpty() || num <= small.peek()) {
small.offer(num);
smallSize ++;
} else {
large.offer(num);
largeSize ++;
}
makeBalance();
}
public void delete(int num) {
delays.put(num, delays.getOrDefault(num, 0) + 1);
if (num <= small.peek()) {
smallSize --;
if (num == small.peek()) {
prune(small);
}
} else {
largeSize --;
if (num == large.peek()) {
prune(large);
}
}
makeBalance();
}
// 弹出堆顶元素,更新哈希表
private void prune(PriorityQueue<Integer> queue) {
while (!queue.isEmpty()) {
int num = queue.peek();
if (delays.containsKey(num)) {
int count = delays.get(num);
delays.put(num, count - 1);
if(count == 1) {
delays.remove(num);
}
queue.poll();
} else {
break;
}
}
}
// 调整large和small个数
private void makeBalance() {
if (smallSize > largeSize + 1) {
large.offer(small.poll());
largeSize ++;
smallSize --;
prune(small);
} else if (smallSize < largeSize) {
small.offer(large.poll());
smallSize ++;
largeSize --;
prune(large);
}
}
}
@Test
public void test() {
int[] nums = {-2147483648,-2147483648,2147483647,-2147483648,
-2147483648,-2147483648,2147483647,2147483647,2147483647,
2147483647,-2147483648,2147483647,-2147483648};
int k = 3;
double[] doubles = medianSlidingWindow(nums, k);
log.info(JsonHelper.toJson(doubles));
}
}
| 25.862069 | 73 | 0.445333 |
9b946dd1b779114a17f7a16d04f23529578ce50c | 7,374 | package com.artur.JocDeRol.joc;
import java.util.ArrayList;
import java.util.Objects;
/**
* Clase abstracta per a crear diferents tipus de personatjes.
*
* @author artur
* @version 2.0
*/
public abstract class Player {
static int VIDA = 100;
protected String name;
protected int attackPoints;
protected int defensePoints;
protected int life;
protected ArrayList<Team> teams;
protected ArrayList<Item> items;
/**
* Constructor generic
*
* @param name nom del personatge.
* @param attackPoints quantitat de punts de atac.
* @param defensePoints quantitat de punts de defensa.
* @param life quantitat de punts de vida.
*/
public Player(String name, int attackPoints, int defensePoints) {
this.name = name;
this.attackPoints = attackPoints;
this.defensePoints = defensePoints;
this.life = VIDA;
this.teams = new ArrayList<>();
this.items = new ArrayList<>();
}
/**
* Afegim un equip al llistat de equips del jugador i el jugador al llistat de
* jugadors del equip.
*
* @param t el equip que afegim
*/
public void addTeam(Team t) {
if (this.teams.contains(t))
return;
this.teams.add(t);
t.add(this);
}
/**
* Eliminem el equip del llistat, i al jugador del llistat del equip.
*
* @param t
*/
public void removeTeam(Team t) {
if (!this.teams.contains(t))
return;
this.teams.remove(t);
t.remove(this);
}
/**
* Calcula la suma de bonificació de punts de atacks dels objectes de un player
*
* @param items el llistat de items
* @return un integer que representa la suma de punts d'atac
*/
public int bonificacioObjectes(ArrayList<Item> items) {
int attackPointsItems = 0;
for (Item i : items)
attackPointsItems += i.attackBonus;
return attackPointsItems;
}
/**
* Calcula la suma de bonificació de punts de defensa dels objectes de un player
*
* @param items el llistat de items
* @return un integer que representa la suma de punts de defensa
*/
public int bonificacioDefensivaObjectes(ArrayList<Item> items) {
int defensePointsItems = 0;
for (Item i : items)
defensePointsItems += i.defenseBonus;
return defensePointsItems;
}
/**
* Si estas mort no pots atacar.
*/
public class estarMortExcepcio extends Exception {
public estarMortExcepcio(String msg) {
super(msg);
}
}
/**
* Funció per atacar entre diferents tipus de Players. Si no mor, el personatge
* atacat retorna el atac.
*
* @param p es el personatge que volem atacar.
*/
public void atack(Player p) throws estarMortExcepcio {
// atac
p.hit(attackPoints + bonificacioObjectes(items));
try {
if (p.life > 0)
this.hit(p.attackPoints + bonificacioObjectes(p.items));
} catch (Exception e) {
throw new estarMortExcepcio("El jugador esta mort.");
}
}
/**
* Mètode per a dir que un jugador es golpejat per un altre amb tants punts
* d'atac
*
* @param attack els punts d'atac amb els quals es produeix el atac.
*/
protected void hit(int attack) {
// sumem bonificacio objectes
int defense = defensePoints + bonificacioDefensivaObjectes(items);
// Atac o punts de vida mai podran ser menors de zero
int dany = attack - defense;
dany = dany > 0 ? dany : 0;
int lifeLoss = life - dany;
lifeLoss = lifeLoss > 0 ? lifeLoss : 0;
// log
System.out.println(name + " és colpejat amb " + attack + " punts i es defén amb " + defense + ". Vides: " + life
+ " - " + dany + " = " + lifeLoss);
life = lifeLoss;
}
/**
* Sobreescrivim el metode equals per a poder comprar jugadors. El criteri es
* tots els parametres.
*
* @param o el jugador amb el qual fem la comparació.
* @return true o false, depenen del resultat de la comparació.
*/
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Player player = (Player) o;
return name.equals(player.name);
}
@Override
public int hashCode() {
return Objects.hash(name, attackPoints, defensePoints, life);
}
/**
* Afegix un element al llistat de items del jugador
*
* @param i el element que afegim al llistat de items
*/
public void add(Item i) {
if (!i.tePropietari) {
this.items.add(i);
i.tePropietari = true;
} else {
System.out.println("Error: el objecte " + i.name + " ja te propietari.");
}
}
/**
* Lleva un element del llistat de items del jugador
*
* @param i el element que llevem al jugador
*/
public void remove(Item i) {
this.items.remove(i);
}
/**
* getter. Necessari per a les modificacions del metodo toString de classe
* alien.
*
* @return el llistat de items
*/
public ArrayList<Item> getItems() {
return this.items;
}
/**
* Retorna totes les dades del jugador en forma de cadena de text.
*/
@Override
public String toString() {
String representacio = name + " PA: " + attackPoints + " / " + "PD: " + defensePoints + " / " + "PV: " + life;
if (teams.size() > 1) {
representacio += " (pertany a " + teams.size() + " equips)";
}
if (teams.size() == 1) {
representacio += " (pertany a 1 equip)";
}
if (items.size() > 1) {
representacio += " i té els ítems:\n";
}
if (items.size() == 1) {
representacio += " i té el ítem:\n";
}
for (int j = 0; j < items.size(); j++) {
Item i = items.get(j);
if (!(j == items.size() - 1)) {
representacio += "- " + i.name + " BA: " + i.attackBonus + " / BD: " + i.defenseBonus + "\n";
} else {
representacio += "- " + i.name + " BA: " + i.attackBonus + " / BD: " + i.defenseBonus;
}
}
return representacio;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAttackPoints() {
return attackPoints;
}
public void setAttackPoints(int attackPoints) {
this.attackPoints = attackPoints;
}
public int getDefensePoints() {
return defensePoints;
}
public void setDefensePoints(int defensePoints) {
this.defensePoints = defensePoints;
}
public int getLife() {
return life;
}
public void setLife(int life) {
this.life = life;
}
}
| 28.361538 | 121 | 0.541633 |
7066bf772f6df19d707bc83cf9db95d77c5fdfcf | 13,842 | /*
* Copyright (C) 2010-2019, Danilo Pianini and contributors listed in the main project's alchemist/build.gradle file.
*
* This file is part of Alchemist, and is distributed under the terms of the
* GNU General Public License, with a linking exception,
* as described in the file LICENSE in the Alchemist distribution's top directory.
*/
package it.unibo.alchemist.model.implementations.conditions;
import it.unibo.alchemist.expressions.implementations.ListTreeNode;
import it.unibo.alchemist.expressions.implementations.NumTreeNode;
import it.unibo.alchemist.expressions.implementations.Type;
import it.unibo.alchemist.expressions.implementations.UIDNode;
import it.unibo.alchemist.expressions.interfaces.IExpression;
import it.unibo.alchemist.expressions.interfaces.ITreeNode;
import it.unibo.alchemist.model.implementations.molecules.LsaMolecule;
import it.unibo.alchemist.model.interfaces.ILsaCondition;
import it.unibo.alchemist.model.interfaces.ILsaMolecule;
import it.unibo.alchemist.model.interfaces.ILsaNode;
import it.unibo.alchemist.model.interfaces.Node;
import it.unibo.alchemist.model.interfaces.Reaction;
import org.danilopianini.lang.HashString;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
*/
public abstract class LsaAbstractCondition extends AbstractCondition<List<ILsaMolecule>> implements ILsaCondition {
private static final long serialVersionUID = -5633486241371700913L;
/**
* @param node
* the node hosting this action
* @param m
* the set of molecules on which this actions act
*/
public LsaAbstractCondition(final ILsaNode node, final Set<ILsaMolecule> m) {
super(node);
for (final ILsaMolecule mol : m) {
declareDependencyOn(mol);
}
}
@Override
public abstract String toString();
@Override
public final ILsaNode getNode() {
return (ILsaNode) super.getNode();
}
@Override
public abstract LsaAbstractCondition cloneCondition(Node<List<ILsaMolecule>> node, Reaction<List<ILsaMolecule>> reaction);
/**
* @param partialInstance
* the template, possibly partly instanced
* @param duplicateVariables
* true if partialInstance contains the same variable multiple
* times
* @param lsaSpace
* the LSA space of the node on which this function is working on
* @param alreadyRemoved
* the list of the molecules already removed from this node.
* @return the list of molecules in this LSA space that match the
* partialInstance, excluding all those which have been already
* removed.
*/
protected static List<ILsaMolecule> calculateMatches(
final List<IExpression> partialInstance,
final boolean duplicateVariables,
final List<ILsaMolecule> lsaSpace,
final List<ILsaMolecule> alreadyRemoved
) {
final List<ILsaMolecule> l = new ArrayList<>(lsaSpace.size() - alreadyRemoved.size());
for (final ILsaMolecule matched : lsaSpace) {
if (matched.matches(partialInstance, duplicateVariables)
&& countElements(lsaSpace, matched) > countElements(alreadyRemoved, matched)) {
l.add(matched);
}
}
return l;
}
private static <T> int countElements(final Collection<T> l, final T o) {
int count = 0;
for (final T t : l) {
if (t.equals(o)) {
count++;
}
}
return count;
}
/**
* @param template
* the template molecule
* @param node
* the node on which this function is working
* @param matchesList
* the list of matches to populate (theoretically, it should
* always be empty when calling this method)
* @param retrieved
* the list of the molecules removed from each node
* (theoretically, it should always be empty when calling this
* method)
*/
protected static void createMatches(
final ILsaMolecule template,
final ILsaNode node,
final List<Map<HashString, ITreeNode<?>>> matchesList,
final List<Map<ILsaNode, List<ILsaMolecule>>> retrieved
) {
final List<ILsaMolecule> lsaSpace = node.getLsaSpace();
for (final ILsaMolecule matched : lsaSpace) {
if (template.matches(matched)) {
/*
* If a match is found, the matched LSA must be added to the
* list of removed items corresponding to the match, the matches
* map must be created, the map should be added to the possible
* matches list, and the index must not be increased.
*/
final Map<HashString, ITreeNode<?>> matches = new HashMap<>(matched.argsNumber() * 2 + 1, 1f);
matches.put(LsaMolecule.SYN_MOL_ID, new UIDNode(matched.toHashString()));
updateMap(matches, matched, template);
matchesList.add(matches);
final List<ILsaMolecule> modifiedSpace = new ArrayList<>(lsaSpace.size());
modifiedSpace.add(matched);
final Map<ILsaNode, List<ILsaMolecule>> retrievedInThisNode = new HashMap<>(lsaSpace.size(), 1f);
retrievedInThisNode.put(node, modifiedSpace);
retrieved.add(retrievedInThisNode);
}
}
}
/**
* Updates the matches map by adding the mapping between the variables of
* template and the contents of instance.
*
* @param map
* : the map to update
* @param instance
* : LsaMolecule instance (contain variable values)
* @param template
* : LsaMolecule template (contain variable names)
*/
protected static void updateMap(
final Map<HashString, ITreeNode<?>> map,
final Iterable<IExpression> instance,
final ILsaMolecule template
) {
/*
* Iterate over inst
*/
int i = 0;
for (final IExpression instarg : instance) {
final IExpression molarg = template.getArg(i);
if (molarg.getRootNodeType() == Type.VAR) {
/*
* If it's a variable
*/
map.put((HashString) molarg.getRootNodeData(), instarg.getRootNode());
} else {
/*
* If it's a comparator
*/
if (molarg.getRootNodeType() == Type.COMPARATOR) {
if (molarg.getAST().getRoot().getLeftChild().getType() == Type.VAR) {
map.put(molarg.getLeftChildren().toHashString(), instarg.getRootNode());
}
} else if (molarg.getRootNodeType() == Type.LISTCOMPARATOR) {
if (molarg.getAST().getRoot().getLeftChild().getType() == Type.VAR
&& instarg.getRootNodeData() instanceof Set<?>) {
map.put(molarg.getLeftChildren().toHashString(), instarg.getRootNode());
}
} else if (molarg.getRootNodeType() == Type.LIST) {
/*
* Assignment of variables within lists.
*/
final Set<ITreeNode<?>> molList = ((ListTreeNode) molarg.getAST().getRoot()).getData();
final Iterator<ITreeNode<?>> instList = ((ListTreeNode) instarg.getAST().getRoot()).getData().iterator();
for (final ITreeNode<?> var : molList) {
if (var.getType() == Type.VAR) {
map.put(var.toHashString(), instList.next());
}
}
}
}
i++;
}
}
/**
* @param node
* The node on which the condition has been verified
* @param otherMatches
* The list of new matches that have been calculated
* @param oldMatches
* The previous matches
* @param template
* The molecule template which has been verified
* @param matchesList
* The list of all the valid matches. If more than one valid
* match has been found, new entries will be added
* @param alreadyRemoved
* the map of the lists of molecules already removed from each
* node for the current match
* @param retrieved
* the list of all the maps that lists the molecules removed from
* each node
*/
protected static void incorporateNewMatches(
final ILsaNode node, final List<ILsaMolecule> otherMatches,
final Map<HashString, ITreeNode<?>> oldMatches,
final ILsaMolecule template,
final List<Map<HashString, ITreeNode<?>>> matchesList,
final Map<ILsaNode, List<ILsaMolecule>> alreadyRemoved,
final List<Map<ILsaNode, List<ILsaMolecule>>> retrieved
) {
for (int j = 1; j < otherMatches.size(); j++) {
final ILsaMolecule instance = otherMatches.get(j);
/*
* Make copies of the match under analysis, then populate them with
* the new matches
*/
final Map<HashString, ITreeNode<?>> newMap = new HashMap<>(oldMatches);
updateMap(newMap, instance, template);
matchesList.add(newMap);
final Map<ILsaNode, List<ILsaMolecule>> contentMap = new HashMap<>(alreadyRemoved);
final List<ILsaMolecule> oldRetrieved = contentMap.get(node);
/*
* If this node already has some modified molecule, copy them.
* Otherwise, create a new list.
*/
final List<ILsaMolecule> newRetrieved = oldRetrieved == null ? new ArrayList<>() : new ArrayList<>(oldRetrieved);
newRetrieved.add(instance);
contentMap.put(node, newRetrieved);
retrieved.add(contentMap);
}
/*
* Now, update the matches for the first entry
*/
final ILsaMolecule instance = otherMatches.get(0);
updateMap(oldMatches, instance, template);
List<ILsaMolecule> alreadyRetrievedInThisNode = alreadyRemoved.get(node);
if (alreadyRetrievedInThisNode == null) {
alreadyRetrievedInThisNode = new ArrayList<>();
alreadyRetrievedInThisNode.add(instance);
alreadyRemoved.put(node, alreadyRetrievedInThisNode);
} else {
alreadyRetrievedInThisNode.add(instance);
}
}
/**
* This has to be used to incorporate new matches when the they are
* node-specific and available for multiple nodes.
*
* @param otherMatchesMap
* Other matches map
* @param oldMatches
* The previous matches
* @param template
* The molecule template which has been verified
* @param matchesList
* The list of all the valid matches. If more than one valid
* match has been found, new entries will be added
* @param alreadyRemoved
* the map of the lists of molecules already removed from each
* node for the current match
* @param retrieved
* the list of all the maps that lists the molecules removed from
* each node
*/
protected static void incorporateNewMatches(
final Map<ILsaNode, List<ILsaMolecule>> otherMatchesMap,
final Map<HashString, ITreeNode<?>> oldMatches,
final ILsaMolecule template,
final List<Map<HashString, ITreeNode<?>>> matchesList,
final Map<ILsaNode, List<ILsaMolecule>> alreadyRemoved,
final List<Map<ILsaNode, List<ILsaMolecule>>> retrieved
) {
for (final Entry<ILsaNode, List<ILsaMolecule>> e : otherMatchesMap.entrySet()) {
final ILsaNode node = e.getKey();
final List<ILsaMolecule> otherMatches = e.getValue();
for (final ILsaMolecule instance : otherMatches) {
/*
* Make copies of the match under analysis, then populate them
* with the new matches
*/
final Map<HashString, ITreeNode<?>> newMap = new HashMap<>(oldMatches);
updateMap(newMap, instance, template);
newMap.put(LsaMolecule.SYN_SELECTED, new NumTreeNode(node.getId()));
matchesList.add(newMap);
final Map<ILsaNode, List<ILsaMolecule>> contentMap = new HashMap<>(alreadyRemoved);
final List<ILsaMolecule> oldRetrieved = contentMap.get(node);
/*
* If this node already has some modified molecule, copy them.
* Otherwise, create a new list.
*/
final List<ILsaMolecule> newRetrieved = oldRetrieved == null
? new ArrayList<>(node.getLsaSpace().size())
: new ArrayList<>(oldRetrieved);
newRetrieved.add(instance);
contentMap.put(node, newRetrieved);
retrieved.add(contentMap);
}
}
/*
* Remove the original entry.
*/
final int i = matchesList.indexOf(oldMatches);
matchesList.remove(i);
retrieved.remove(i);
}
}
| 42.072948 | 126 | 0.589727 |
4988aec2603d68b06e30753ed4f6169386545998 | 1,244 | package com.korochun.neutrino.test;
import com.korochun.neutrino.*;
public class NeutrinoTest implements Game {
public static void main(String[] args) {
new Neutrino(new NeutrinoTest()).start();
}
@Override
public String getTitle() {
return "Neutrino Test";
}
@Override
public void init(Neutrino neutrino) {
Texture texture = new Texture("assets/tex.png").register("fire");
neutrino.setScene(new Scene("test")
.setBackground(0.02f, 0.28f, 0.78f)
.addLayer(new ImageLayer("image", new AnimatedTexture(5,
texture.subImage(0, 0, 16, 16),
texture.subImage(0, 16, 16, 16),
texture.subImage(0, 32, 16, 16),
texture.subImage(0, 48, 16, 16),
texture.subImage(0, 64, 16, 16),
texture.subImage(0, 80, 16, 16),
texture.subImage(0, 96, 16, 16),
texture.subImage(0, 112, 16, 16)
))));
}
@Override
public void key(Neutrino neutrino, int action, int key, int mods) {
}
@Override
public void update(Neutrino neutrino) {
}
}
| 29.619048 | 73 | 0.528939 |
2a4e070af9bab52639d5b42ebca5a79784ab9ab2 | 5,673 | /*
* Copyright (c) 2014 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.stdext.identity;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;
import pl.edu.icm.unity.MessageSource;
import pl.edu.icm.unity.exceptions.IllegalIdentityValueException;
import pl.edu.icm.unity.exceptions.IllegalTypeException;
import pl.edu.icm.unity.exceptions.InternalException;
import pl.edu.icm.unity.server.api.internal.LoginSession;
import pl.edu.icm.unity.server.authn.InvocationContext;
import pl.edu.icm.unity.stdext.identity.SessionIdentityModel.PerSessionEntry;
import pl.edu.icm.unity.stdext.utils.Escaper;
import pl.edu.icm.unity.types.basic.Attribute;
import pl.edu.icm.unity.types.basic.AttributeType;
import pl.edu.icm.unity.types.basic.IdentityParam;
import pl.edu.icm.unity.types.basic.IdentityRepresentation;
/**
* Identity type which creates a different identifier for each target, which is valid only for a time span of a single
* login session.
* @author K. Benedyczak
*/
@Component
public class TransientIdentity extends AbstractIdentityTypeProvider
{
public static final String ID = "transient";
private static final List<Attribute<?>> empty = Collections.unmodifiableList(new ArrayList<Attribute<?>>(0));
private ObjectMapper mapper;
@Autowired
public TransientIdentity(ObjectMapper mapper)
{
this.mapper = mapper;
}
/**
* {@inheritDoc}
*/
@Override
public String getId()
{
return ID;
}
/**
* {@inheritDoc}
*/
@Override
public String getDefaultDescription()
{
return "Transient targeted id";
}
@Override
public boolean isRemovable()
{
return false;
}
/**
* {@inheritDoc}
*/
@Override
public Set<AttributeType> getAttributesSupportedForExtraction()
{
return Collections.emptySet();
}
/**
* {@inheritDoc}
*/
@Override
public void validate(String value) throws IllegalIdentityValueException
{
}
/**
* {@inheritDoc}
*/
@Override
public String getComparableValue(String from, String realm, String target)
{
if (realm == null || target == null)
return null;
LoginSession ls;
try
{
InvocationContext ctx = InvocationContext.getCurrent();
ls = ctx.getLoginSession();
if (ls == null)
return null;
} catch (InternalException e)
{
return null;
}
return getComparableValueInternal(from, realm, target, ls);
}
private String getComparableValueInternal(String from, String realm, String target, LoginSession ls)
{
return Escaper.encode(realm, target, ls.getId(), from);
}
/**
* {@inheritDoc}
*/
@Override
public List<Attribute<?>> extractAttributes(String from, Map<String, String> toExtract)
{
return empty;
}
/**
* {@inheritDoc}
*/
@Override
public String toPrettyStringNoPrefix(IdentityParam from)
{
return from.getValue();
}
@Override
public boolean isDynamic()
{
return true;
}
@Override
public String toExternalForm(String realm, String target, String inDbValue)
throws IllegalIdentityValueException
{
if (realm == null || target == null || inDbValue == null)
throw new IllegalIdentityValueException("No enough arguments");
LoginSession ls;
try
{
InvocationContext ctx = InvocationContext.getCurrent();
ls = ctx.getLoginSession();
if (ls == null)
throw new IllegalIdentityValueException("No login session");
} catch (Exception e)
{
throw new IllegalIdentityValueException("Error getting invocation context", e);
}
return toExternalFormNoContext(inDbValue);
}
@Override
public IdentityRepresentation createNewIdentity(String realm, String target, String value)
throws IllegalTypeException
{
if (realm == null || target == null)
throw new IllegalTypeException("Identity can be created only when target is defined");
if (value == null)
value = UUID.randomUUID().toString();
try
{
InvocationContext ctx = InvocationContext.getCurrent();
LoginSession ls = ctx.getLoginSession();
if (ls == null)
return null;
SessionIdentityModel model = new SessionIdentityModel(mapper, ls, value);
String contents = model.serialize();
String comparableValue = getComparableValueInternal(value, realm, target, ls);
return new IdentityRepresentation(comparableValue, contents);
} catch (Exception e)
{
throw new IllegalTypeException("Identity can be created only when login session is defined", e);
}
}
@Override
public boolean isExpired(IdentityRepresentation representation)
{
SessionIdentityModel model = new SessionIdentityModel(mapper, representation.getContents());
PerSessionEntry info = model.getEntry();
return info.isExpired();
}
@Override
public boolean isTargeted()
{
return true;
}
@Override
public String toExternalFormNoContext(String inDbValue)
{
SessionIdentityModel model = new SessionIdentityModel(mapper, inDbValue);
return model.getEntry().getValue();
}
@Override
public String toHumanFriendlyString(MessageSource msg, IdentityParam from)
{
return msg.getMessage("TransientIdentity.random");
}
@Override
public String getHumanFriendlyDescription(MessageSource msg)
{
return msg.getMessage("TransientIdentity.description");
}
@Override
public boolean isVerifiable()
{
return false;
}
@Override
public String getHumanFriendlyName(MessageSource msg)
{
return msg.getMessage("TransientIdentity.name");
}
}
| 23.345679 | 118 | 0.740173 |
123928b382f523df6cf421f28ef54143d8a67763 | 460 | package elevator;
import designs.elevator.Direction;
import designs.elevator.ElevatorManagementSystem;
public class ElTest {
public static void main(String[] args) {
ElevatorManagementSystem ems = new ElevatorManagementSystem(3, 5);
ems.addPickup(1, Direction.UP);
ems.addPickup(2, Direction.UP);
ems.addPickup(3, Direction.UP);
ems.addPickup(4, Direction.UP);
ems.addPickup(2, Direction.DOWN);
}
}
| 24.210526 | 74 | 0.684783 |
29529981e98aeeceeddcc22e9cda504d09c7fcf2 | 14,961 | package com.github.Eddyosos.integracao20171.esus.cds.procedimento;
import br.gov.saude.esus.cds.transport.generated.thrift.procedimento.FichaProcedimentoChildThrift;
import com.github.eddyosos.e_sus_ab_factory.cds.esus.cds.procedimento.IFichaProcedimentoChild;
import java.util.Iterator;
import java.util.List;
public class FichaProcedimentoChild implements IFichaProcedimentoChild {
private FichaProcedimentoChildThrift instancia;
public FichaProcedimentoChild(){
instancia = new FichaProcedimentoChildThrift();
}
/**
* Retorna uma instancia nao thrift
* @param fichaProcedimentoChildThrift
*/
public FichaProcedimentoChild(FichaProcedimentoChildThrift fichaProcedimentoChildThrift) {
this.instancia = fichaProcedimentoChildThrift;
}
/**
* @return Objeto thrift para acesso aos metodos do thrift
* @param fichaProcedimentoChildThrift
*/
@Override
public FichaProcedimentoChildThrift getInstance(){
return this.instancia;
}
/**
* Retorna o numero de prontuario
* @return String
*/
@Override
public String getNumProntuario() {
return instancia.getNumProntuario();
}
/**
* Atribui o numero de prontuario
* @param String
*/
@Override
public void setNumProntuario(String numProntuario) {
instancia.setNumProntuario(numProntuario);
}
/**
* Verfica se o numero de prontuario foi atribuido
* @return true se tiver setado, false caso nao esteja
*/
@Override
public boolean isSetNumProntuario() {
return instancia.isSetNumProntuario();
}
/**
* Marca que o numero de prontuario foi setado
* @param value
*/
@Override
public void setNumProntuarioIsSet(boolean value) {
instancia.setNumProntuarioIsSet(value);
}
/**
* Retorna o numero do cartao sus
* @return String
*/
@Override
public String getNumCartaoSus() {
return instancia.getNumCartaoSus();
}
/**
* Atribui o numero de prontuario
* @param String
*/
@Override
public void setNumCartaoSus(String numCartaoSus) {
instancia.setNumCartaoSus(numCartaoSus);
}
/**
* Verfica se o numero do cartao foi atribuido
* @return true se tiver setado, false caso nao esteja
*/
@Override
public boolean isSetNumCartaoSus() {
return instancia.isSetNumCartaoSus();
}
/**
* Marca que o atributo foi setado
* @param value
*/
@Override
public void setNumCartaoSusIsSet(boolean value) {
instancia.setNumCartaoSusIsSet(value);
}
/**
* Retorna o valor do atributo
* @return long
*/
@Override
public long getDtNascimento() {
return instancia.getDtNascimento();
}
/**
* Atribui o valor do atributo
* @param data de nascimento
*/
@Override
public void setDtNascimento(long dtNascimento) {
instancia.setDtNascimento(dtNascimento);
}
/**
* Verfica se o atributo foi atribuido
* @return true se tiver setado, false caso nao esteja
*/
@Override
public boolean isSetDtNascimento() {
return instancia.isSetDtNascimento();
}
/**
* Marca que o atributo foi setado
* @param se esta setado ou nao
*/
@Override
public void setDtNascimentoIsSet(boolean value) {
instancia.setDtNascimentoIsSet(value);
}
/**
* Retorna o valor do atributo
* @return o valor do atributo
*/
@Override
public long getSexo() {
return instancia.getSexo();
}
/**
* Atribui o valor do atributo
* @param o valor do atributo
*/
@Override
public void setSexo(long sexo) {
instancia.setSexo(sexo);
}
/**
* Verfica se o atributo foi atribuido
* @return true se tiver setado, false caso nao esteja
*/
@Override
public boolean isSetSexo() {
return instancia.isSetSexo();
}
/**
* Marca que o atributo foi setado
* @param se esta setado ou nao
*/
@Override
public void setSexoIsSet(boolean value) {
instancia.setSexoIsSet(value);
}
/**
* Retorna o valor do atributo
* @return o valor do atributo
*/
@Override
public long getLocalAtendimento() {
return instancia.getLocalAtendimento();
}
/**
* Atribui o valor do atributo
* @param o valor do atributo
*/
@Override
public void setLocalAtendimento(long localAtendimento) {
instancia.setLocalAtendimento(localAtendimento);
}
/**
* Verfica se o atributo foi atribuido
* @return true se tiver setado, false caso nao esteja
*/
@Override
public boolean isSetLocalAtendimento() {
return instancia.isSetLocalAtendimento();
}
/**
* Marca que o atributo foi setado
* @param se esta setado ou nao
*/
@Override
public void setLocalAtendimentoIsSet(boolean value) {
instancia.setLocalAtendimentoIsSet(value);
}
/**
* Retorna o valor do atributo
* @return o valor do atributo
*/
@Override
public long getTurno() {
return instancia.getTurno();
}
/**
* Atribui o valor do atributo
* @param o valor do atributo
*/
@Override
public void setTurno(long turno) {
instancia.setTurno(turno);
}
/**
* Verfica se o atributo foi atribuido
* @return true se tiver setado, false caso nao esteja
*/
@Override
public boolean isSetTurno() {
return instancia.isSetTurno();
}
/**
* Marca que o atributo foi setado
* @param se esta setado ou nao
*/
@Override
public void setTurnoIsSet(boolean value) {
instancia.setTurnoIsSet(value);
}
/**
* Verfica se o atributo foi atribuido
* @return true se tiver setado, false caso nao esteja
*/
@Override
public boolean isStatusEscutaInicialOrientacao() {
return instancia.isStatusEscutaInicialOrientacao();
}
/**
* Marca que o atributo foi setado
* @param se esta setado ou nao
*/
@Override
public void setStatusEscutaInicialOrientacao(boolean statusEscutaInicialOrientacao) {
instancia.setStatusEscutaInicialOrientacao(statusEscutaInicialOrientacao);
}
/**
* Verfica se o atributo foi atribuido
* @return true se tiver setado, false caso nao esteja
*/
@Override
public boolean isSetStatusEscutaInicialOrientacao() {
return instancia.isSetStatusEscutaInicialOrientacao();
}
/**
* Atribui o valor do atributo
* @param o valor do atributo
*/
@Override
public void setStatusEscutaInicialOrientacaoIsSet(boolean value) {
instancia.setStatusEscutaInicialOrientacaoIsSet(value);
}
/**
* Atribui o valor do atributo
* @param o valor do atributo
*/
@Override
public int getProcedimentosSize() {
return instancia.getProcedimentosSize();
}
/**
* Verfica se o atributo foi atribuido
* @return true se tiver setado, false caso nao esteja
*/
@Override
public Iterator<String> getProcedimentosIterator() {
return instancia.getProcedimentosIterator();
}
/**
* Retorna o valor do atributo
* @return o valor do atributo
*/
@Override
public void addToProcedimentos(String elem) {
instancia.addToProcedimentos(elem);
}
/**
* Retorna o valor do atributo
* @return o valor do atributo
*/
@Override
public List<String> getProcedimentos() {
return instancia.getProcedimentos();
}
/**
* Atribui o valor do atributo
* @param o valor do atributo
*/
@Override
public void setProcedimentos(List<String> procedimentos) {
instancia.setProcedimentos(procedimentos);
}
/**
* Verfica se o atributo foi atribuido
* @return true se tiver setado, false caso nao esteja
*/
@Override
public boolean isSetProcedimentos() {
return instancia.isSetProcedimentos();
}
/**
* Marca que o atributo foi setado
* @param se esta setado ou nao
*/
@Override
public void setProcedimentosIsSet(boolean value) {
instancia.setProcedimentosIsSet(value);
}
/**
* Atribui o valor do atributo
* @param o valor do atributo
*/
@Override
public int getOutrosSiaProcedimentosSize() {
return instancia.getOutrosSiaProcedimentosSize();
}
/**
* Verfica se o atributo foi atribuido
* @return true se tiver setado, false caso nao esteja
*/
@Override
public Iterator<String> getOutrosSiaProcedimentosIterator() {
return instancia.getOutrosSiaProcedimentosIterator();
}
/**
* Marca que o atributo foi setado
* @param se esta setado ou nao
*/
@Override
public void addToOutrosSiaProcedimentos(String elem) {
instancia.addToOutrosSiaProcedimentos(elem);
}
/**
* Retorna o valor do atributo
* @return o valor do atributo
*/
@Override
public List<String> getOutrosSiaProcedimentos() {
return instancia.getOutrosSiaProcedimentos();
}
/**
* Atribui o valor do atributo
* @param o valor do atributo
*/
@Override
public void setOutrosSiaProcedimentos(List<String> outrosSiaProcedimentos) {
instancia.setOutrosSiaProcedimentos(outrosSiaProcedimentos);
}
/**
* Verfica se o atributo foi atribuido
* @return true se tiver setado, false caso nao esteja
*/
@Override
public boolean isSetOutrosSiaProcedimentos() {
return instancia.isSetOutrosSiaProcedimentos();
}
/**
* Marca que o atributo foi setado
* @param se esta setado ou nao
*/
@Override
public void setOutrosSiaProcedimentosIsSet(boolean value) {
instancia.setOutrosSiaProcedimentosIsSet(value);
}
/**
* Valida todos os campos.
* @return True caso valido, false caso esteja inconsistente
*/
@Override
public boolean validate(){
return this.validateGroup() &&
this.validateLocalAtendimento() &&
this.validateNumCartaoSus() &&
this.validateSexo() &&
this.validateStatusEscutaInicialOrientacao() &&
this.validateTurno() &&
this.validateUuidFicha();
}
/**
* Número do prontuário do cidadão na UBS.
* Opcional
* @return True caso valido, false caso esteja inconsistente
*/
@Override
public boolean validateUuidFicha(){
if(this.getNumProntuario() == null){
return true;
}
if(this.getNumProntuario().length() < 0 || this.getNumProntuario().length() > 30){
return false;
}
return true;
}
/**
* Numero do cartão SUS do cidadão.
* Opcional
* @return True caso valido, false caso esteja inconsistente
*/
@Override
public boolean validateNumCartaoSus(){
if(this.instancia.getNumCartaoSus() == null){
return true;
}
if(!this.instancia.isSetNumCartaoSus()){
return true;
}
if(this.instancia.getNumCartaoSus().length() != 15){
return false;
}
return true;
}
/**
* Código do sexo do cidadão.
* Obrigatorio
* @return True caso valido, false caso esteja inconsistente
*/
@Override
public boolean validateSexo(){
if(!this.instancia.isSetSexo()){
return false;
}
if(this.instancia.getSexo() > 1 || this.instancia.getSexo() < 0){
return false;
}
return true;
}
/**
* Código do local onde o atendimento foi realizado.
* Obrigatorio
* @return True caso valido, false caso esteja inconsistente
*/
@Override
public boolean validateLocalAtendimento(){
if(!this.instancia.isSetLocalAtendimento()){
return false;
}
if(this.instancia.getLocalAtendimento()> 10 || this.instancia.getLocalAtendimento() < 1){
return false;
}
return true;
}
/**
* Código do turno onde aconteceu o atendimento.
* Opcional
* @return True caso valido, false caso esteja inconsistente
*/
@Override
public boolean validateTurno(){
if(!this.instancia.isSetTurno()){
return false;
}
if(this.instancia.getTurno()> 10 || this.instancia.getTurno() < 1){
return false;
}
return true;
}
/**
* Indica a realização da escuta inicial.
* Opcional
* @return True caso valido, false caso esteja inconsistente
*/
@Override
public boolean validateStatusEscutaInicialOrientacao(){
if(!this.instancia.isSetStatusEscutaInicialOrientacao()){
return true;
}
return true;
}
/**
* Lista dos códigos dos procedimentos que são registrados na ficha de procedimentos.
* Condicional
* @return True caso valido, false caso esteja inconsistente
*/
@Override
public boolean validateProcedimentos(){
if(!this.instancia.isSetProcedimentos()){
return false;
}
if(this.instancia.getProcedimentos().size() < 0 || this.instancia.getProcedimentos().size() > 23){
return false;
}
return true;
}
/**
* Lista dos códigos dos procedimentos que são registrados na ficha de procedimentos.
* Condicional
* @return True caso valido, false caso esteja inconsistente
*/
@Override
public boolean validateOutrosSiaProcedimentos(){
if(!this.instancia.isSetProcedimentos()){
return false;
}
if(this.instancia.getOutrosSiaProcedimentos().size() < 0 || this.instancia.getOutrosSiaProcedimentos().size() > 6){
return false;
}
for(String proc : this.instancia.getOutrosSiaProcedimentos()){
if(proc.matches("\\A\\w{8}\\z")){
return false;
}
}
return true;
}
/**
* Valida os campos com preenchimento condicional.
* @return True caso ao menos um dos campos esteja válido, false caso todos estejam inválidos
*/
@Override
public boolean validateGroup(){
return this.validateProcedimentos() ||
this.validateOutrosSiaProcedimentos();
}
}
| 25.487223 | 123 | 0.607112 |
8a26f86967934ab75b47eade722a5050b221832c | 2,180 | /**
*
*/
package le.cache.bis.services.impl;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import le.cache.bis.services.Cache;
import le.cache.bis.services.IndexTask;
import le.cache.bis.services.Indexer;
import le.cache.bis.services.exception.SnapshotException;
import le.cache.util.Property;
import le.cache.util.Utility;
/**
* @author ledwinson
*
*/
@Service
@Scope(value = BeanDefinition.SCOPE_PROTOTYPE)
class IndexTaskImpl<P,V> implements IndexTask<P, V> {
private Method method;
private boolean isCaseSensitive = true;
private PrimaryKeyType<P> type;
private Cache<P, V> cache;
private Indexer<P> indexer;
@Override
public Indexer<P> call() throws Exception {
if(Utility.isAnyNull(new Object[]{method, type, cache, indexer})) {
throw new SnapshotException("Call the init method and set the values to process.");
}
final Annotation[][] anotations = method.getParameterAnnotations();
if(anotations.length == 0) {
return null;
}
final List<Property> parameters = new ArrayList<>(anotations.length);
for(int property = 0; property < anotations.length; property++) {
final Annotation annotation = anotations[property][0];
if(Property.class.isAssignableFrom(annotation.getClass())) {
parameters.add(((Property)annotation));
}
}
indexer.setCaseSensitiveSearch(isCaseSensitive)
.setPrimaryKeyType(type)
.setQuery(method.getName())
.indexBy(parameters, cache);
return indexer;
}
@Override
public void init(Cache<P, V> cache, Indexer<P> indexer ,Method method, boolean isCaseSensitive, PrimaryKeyType<P> type) {
this.method = method;
this.isCaseSensitive = isCaseSensitive;
this.type = type;
this.cache = cache;
this.indexer = indexer;
}
}
| 30.277778 | 125 | 0.673853 |
f4051f3dd121796abde63971ae09247e788b33b3 | 1,668 | package com.abforce.toop.popups;
import org.andengine.entity.modifier.MoveYModifier;
import org.andengine.entity.scene.IOnSceneTouchListener;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.sprite.Sprite;
import org.andengine.input.touch.TouchEvent;
import com.abforce.toop.entities.SSprite;
import com.abforce.toop.managers.RM;
public class GetReady implements IOnSceneTouchListener {
Scene mChild;
Scene mParent;
public GetReady(OnDisposeListener listener){
mListener = listener;
}
public void attachToScene(Scene scene){
float x = RM.CW / 2 - RM.SX * RM.txGetReady.getWidth() / 2;
float y = RM.CH / 2 - RM.SY * RM.txGetReady.getHeight() / 2;
SSprite sprite = new SSprite(x, y, RM.txGetReady);
mChild = new Scene();
mChild.setBackgroundEnabled(false);
mChild.attachChild(sprite);
scene.setChildScene(mChild, false, true, true);
mChild.setOnSceneTouchListener(this);
mParent = scene;
}
@Override
public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
if(pSceneTouchEvent.isActionDown()){
Sprite ent = (Sprite) mChild.getChildByIndex(0);
float from = ent.getY();
float to = -ent.getHeight();
MoveYModifier modifier = new MoveYModifier(0.2f, from, to){
protected void onModifierFinished(org.andengine.entity.IEntity pItem) {
mParent.clearChildScene();
mListener.onDisposed();
};
};
ent.registerEntityModifier(modifier);
return true;
}
return false;
}
OnDisposeListener mListener;
public interface OnDisposeListener{
public void onDisposed();
}
}
| 26.0625 | 79 | 0.703837 |
7b96e64dce624a5a1c9f017667f4888bd6bab018 | 3,816 | package com.uhasoft.smurf.ratelimit.sentinel.configuration;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.SentinelWebInterceptor;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.config.SentinelWebMvcConfig;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.uhasoft.registry.core.RegistryServer;
import com.uhasoft.smurf.config.core.ConfigService;
import com.uhasoft.smurf.ratelimit.core.OriginParser;
import com.uhasoft.smurf.ratelimit.core.model.Rule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static com.uhasoft.smurf.ratelimit.core.constant.RateLimitConstant.DEFAULT_ORIGIN;
/**
* @author Weihua
* @since 1.0.0
*/
@Configuration
public class SentinelAutoConfiguration implements WebMvcConfigurer {
private static final Logger logger = LoggerFactory.getLogger(SentinelAutoConfiguration.class);
@Autowired
private OriginParser<HttpServletRequest> originParser;
@Autowired
private ConfigService configService;
@Autowired
private RegistryServer registryServer;
@PostConstruct
public void init(){
configService.observe("smurf.ratelimit." + registryServer.getServiceName(), "smurf.ratelimit.rules", value -> {
logger.info("RateLimit rules: {}", value);
if(value != null){
Type type = new TypeToken<List<Rule>>(){}.getType();
List<Rule> rules = new Gson().fromJson(value, type);
List<FlowRule> flowRules = new ArrayList<>();
for(Rule rule : rules){
if(rule.getDefaultThreshold() > 0){
FlowRule flowRule = new FlowRule();
flowRule.setCount(rule.getDefaultThreshold());
flowRule.setResource(rule.getResource());
flowRule.setLimitApp(DEFAULT_ORIGIN);
flowRules.add(flowRule);
}
if(!CollectionUtils.isEmpty(rule.getOriginThreshold())){
for(String origin : rule.getOriginThreshold().keySet()){
FlowRule flowRule = new FlowRule();
flowRule.setCount(rule.getOriginThreshold().get(origin));
flowRule.setResource(rule.getResource());
flowRule.setLimitApp(origin);
flowRules.add(flowRule);
}
}
}
FlowRuleManager.loadRules(flowRules);
logger.info("Loaded {} ratelimit rules for {} APIs.", flowRules.size(), rules.size());
}
});
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
SentinelWebMvcConfig config = new SentinelWebMvcConfig();
// Enable the HTTP method prefix.
config.setHttpMethodSpecify(true);
config.setOriginParser(request -> originParser.parse(request));
// Add to the interceptor list.
registry.addInterceptor(new SentinelWebInterceptor(config)).addPathPatterns("/**");
}
}
| 41.934066 | 119 | 0.669811 |
97c1c83960f73b196e9cf8f0e54dd882cecf0e98 | 302 | package com.DesignPatterns.CreationalPatterns.abstractFactory.material;
import com.DesignPatterns.CreationalPatterns.abstractFactory.TextBox;
public class MaterialTextBox implements TextBox {
@Override
public void render() {
System.out.println("Rendering material text box");
}
}
| 27.454545 | 71 | 0.778146 |
0acfd3c36e5add39546186e94c4852bb21ef0e7a | 873 | package com.example.demo.diagnosis.dto;
import com.example.demo.diagnosis.domain.Air;
import com.example.demo.diagnosis.domain.Corna;
import com.example.demo.diagnosis.domain.Diagnosis;
import com.example.demo.diagnosis.domain.Macak;
import com.example.demo.member.domain.Member;
import lombok.Builder;
import lombok.Getter;
@Getter
public class DiagnosisDto {
private Long id;
private Member member;
private String name; // 진단 질병명
private Corna corna;
private Macak macak;
private Air air;
private String dog;
@Builder
public DiagnosisDto(Diagnosis entity){
this.id = entity.getId();
this.member = entity.getMember();
this.name = entity.getName();
this.corna = entity.getCorna();
this.macak = entity.getMacak();
this.air = entity.getAir();
this.dog = entity.getDog();
}
}
| 26.454545 | 51 | 0.690722 |
b09fcce308f453e126ecef0383ad4c29038863cf | 1,154 | package com.google.android.gms.internal.ads;
import android.os.Bundle;
import android.view.ViewGroup;
import com.google.android.gms.internal.ads.zzbtp;
/* compiled from: com.google.android.gms:play-services-ads@@19.4.0 */
public final class zzcwd extends zzcwe<zzboq> {
private final zzccw zzeve;
private final zzbys zzfbr;
private final zzcyn zzfig;
private final ViewGroup zzfpw;
private final zzbwk zzfrk;
private final zzbix zzgpt;
private final zzbtp.zza zzgpu;
public zzcwd(zzbix zzbix, zzbtp.zza zza, zzcyn zzcyn, zzbys zzbys, zzccw zzccw, zzbwk zzbwk, ViewGroup viewGroup) {
this.zzgpt = zzbix;
this.zzgpu = zza;
this.zzfig = zzcyn;
this.zzfbr = zzbys;
this.zzeve = zzccw;
this.zzfrk = zzbwk;
this.zzfpw = viewGroup;
}
/* access modifiers changed from: protected */
public final zzdzc<zzboq> zza(zzdok zzdok, Bundle bundle) {
return this.zzgpt.zzadp().zzd(this.zzgpu.zza(zzdok).zzf(bundle).zzajv()).zzd(this.zzfbr).zza(this.zzfig).zzb(this.zzeve).zza(new zzbqh(this.zzfrk)).zzc(new zzbol(this.zzfpw)).zzafw().zzaev().zzajh();
}
}
| 36.0625 | 207 | 0.684575 |
1eaaeaccee72cc96ea923562ca94f5a9c4715e20 | 2,442 | package io.github.rowak.nanoleafdesktop.ui.dialog;
import io.github.rowak.nanoleafdesktop.IListenToMessages;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class ConfirmationActionListener implements ActionListener {
private final IListenToMessages parent;
private final String repo;
private IDeliverMessages message = null;
public ConfirmationActionListener(IListenToMessages parent, String repo) {
this.parent = parent;
this.repo = repo;
}
@Override
public void actionPerformed(ActionEvent e) {
if (desktopIsSupported()) {
actOnEvent(e);
try {
callRepo();
} catch (IOException e1) {
//TODO this has to be decoupled; again visitor or observer pattern shoudl do the trick
//TODO simply have an error message, which will be passed to a global listener (text dialog)
message = new ErrorMessage("Failed to automatically redirect. Go to " +
repo + " to download the update.");
} catch (URISyntaxException e1) {
message = new ErrorMessage("An internal error occurred. The update cannot be completed.");
}
} else {
message = new ErrorMessage("Failed to automatically redirect. Go to " +
repo + " to download the update.");
}
if (hasError()) {
parent.createDialog(message);
}
}
//TODO seam for testing; will be removed after refactoring
protected void actOnEvent(ActionEvent e) {
JButton btn = (JButton) e.getSource();
OptionDialog dialog = (OptionDialog) btn.getFocusCycleRootAncestor();
dialog.dispose();
}
//TODO seam for testing; will be removed after refactoring
protected void callRepo() throws IOException, URISyntaxException {
Desktop.getDesktop().browse(new URI(repo));
}
//TODO seam for testing; will be removed after refactoring
protected boolean desktopIsSupported() {
return Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE);
}
private boolean hasError() {
return message != null;
}
}
| 34.885714 | 108 | 0.634726 |
6ed7a361fb131eae76d07ba894844c6b57e77de8 | 3,285 | package br.com.villsec.model.configuration;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import br.com.villsec.model.security.JWTAuthenticationFilter;
import br.com.villsec.model.security.JWTAuthorizationFilter;
import br.com.villsec.model.security.JWTUtil;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private JWTUtil jwtUtil;
private static final String[] PUBLIC_MATCHERS = { "/login" };
private static final String[] PUBLIC_MATCHERS_GET = {
"/albuns/**",
"/eventos/**",
"/galerias/**",
"/imagens/**",
"/musicas/**",
"/proprietarios/2",
"/videos/**"
};
private static final String[] PUBLIC_MATCHERS_POST = {
"/seguidores",
"/auth/**"
};
@Override
protected void configure(HttpSecurity https) throws Exception {
https.cors().and().csrf().disable();
https.authorizeRequests().antMatchers(HttpMethod.POST, PUBLIC_MATCHERS_POST).permitAll()
.antMatchers(HttpMethod.GET, PUBLIC_MATCHERS_GET).permitAll().antMatchers(PUBLIC_MATCHERS).permitAll()
.anyRequest().authenticated();
https.addFilter(new JWTAuthenticationFilter(authenticationManager(), this.jwtUtil));
https.addFilter(new JWTAuthorizationFilter(authenticationManager(), this.jwtUtil, this.userDetailsService));
https.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(this.userDetailsService).passwordEncoder(bCryptPasswordEncoder());
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration().applyPermitDefaultValues();
configuration.setAllowedMethods(Arrays.asList("POST", "GET", "PUT", "DELETE", "OPTIONS"));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}
| 39.107143 | 110 | 0.812177 |
e4ce0c2696d0cf4d9cddf06276acacd9babb99f9 | 3,408 | package kr.msleague.bcsp.bukkit;
import io.netty.channel.Channel;
import kr.msleague.bcsp.bukkit.event.connection.BCSPDisconnectedEvent;
import kr.msleague.bcsp.bukkit.event.packet.ASyncPacketReceivedEvent;
import kr.msleague.bcsp.bukkit.event.packet.PacketReceivedEvent;
import kr.msleague.bcsp.internal.BungeeComsoServerBootStrap;
import kr.msleague.bcsp.internal.logger.BCSPLogManager;
import kr.msleague.bcsp.internal.netty.packet.sys.HandShakePacket;
import kr.msleague.bcsp.internal.netty.pipeline.BossHandler;
import kr.msleague.bcsp.internal.netty.pipeline.ConnectionState;
import kr.msleague.bcsp.internal.netty.pipeline.TimeOutHandler;
import kr.msleague.bootstrap.MSLibraryBukkitBootstrap;
import lombok.Setter;
import org.bukkit.Bukkit;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class ChannelConnecterThread implements Runnable {
@Setter
private static boolean enabled;
private static boolean bootup = true;
@Setter
private static int waitTime = 3;
@Override
public void run() {
if (!enabled)
return;
CompletableFuture<Channel> future = BungeeComsoServerBootStrap.initClient(bootup);
bootup = false;
future.whenCompleteAsync((channel, throwable) -> {
if (throwable != null) {
BCSPLogManager.getLogger().err("BCSP Failed to bootup successfully. Check following stack trace. Trying connect after {0} seconds", waitTime);
throwable.printStackTrace();
try {
TimeUnit.SECONDS.sleep(waitTime);
run();
} catch (InterruptedException e) {
e.printStackTrace();
}
return;
}
setWaitTime(3);
BossHandler handlerBoss = channel.pipeline().get(BossHandler.class);
handlerBoss.setDisconnectHandler((x) -> {
if (!BCSPBootstrapBukkit.isActive())
return;
x.setEnabled(false);
Bukkit.getScheduler().runTask(MSLibraryBukkitBootstrap.getPlugin(), () -> Bukkit.getPluginManager().callEvent(new BCSPDisconnectedEvent(x, x.getHandler().getConnectionState())));
BCSPLogManager.getLogger().err("BCSP Checked unexpected disconnection. Trying connect after {0} seconds.", waitTime);
try {
TimeUnit.SECONDS.sleep(waitTime);
run();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
handlerBoss.setPacketPreProcessHandler((handler, wrapper) -> {
Bukkit.getPluginManager().callEvent(new ASyncPacketReceivedEvent(handler, wrapper));
Bukkit.getScheduler().runTask(MSLibraryBukkitBootstrap.getPlugin(), () -> Bukkit.getPluginManager().callEvent(new PacketReceivedEvent(handler, wrapper)));
});
BCSPLogManager.getLogger().info("BSCP Server Initialization Success!");
handlerBoss.setConnectionState(ConnectionState.HANDSHAKING);
channel.writeAndFlush(new HandShakePacket(BCSPBootstrapBukkit.getAuthCodeA(), BCSPBootstrapBukkit.getAuthCodeB(), Bukkit.getPort()));
channel.pipeline().addFirst("timeout-handler", new TimeOutHandler(5L, TimeUnit.SECONDS));
});
}
}
| 48 | 194 | 0.664026 |
3459f14d14263e294c45ca4810ad88bf8e6ed9a1 | 1,478 | package hashing;
import java.util.TreeMap;
import java.util.Vector;
import java.util.Map.Entry;
public class VerticalOrderBtree {
static class Node{
int key;
Node left;
Node right;
Node (int data){
key=data;
left=null;
right=null;
}
}
static void getVerticalOrder(Node root,int hd,TreeMap<Integer,Vector<Integer>>m) {
if (root==null) // base case
return;
Vector<Integer>get = m.get(hd); // get vector list as hd
if(get==null) {
get = new Vector<>();
get.add(root.key);
}
else
get.add(root.key);
m.put(hd,get); // passing key,value pair to TreeMap m
getVerticalOrder(root.left,hd-1,m); //stores nodes in left subtree
getVerticalOrder(root.right,hd+1,m); //stores nodes in right subtree
}
static void printVerticalOrder(Node root) {
TreeMap<Integer,Vector<Integer>>m = new TreeMap<>();
int hd=0;
getVerticalOrder(root,hd,m);
for(Entry<Integer,Vector<Integer>> entry : m.entrySet())
System.out.println(entry.getValue());
}
public static void main(String[] args) {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
root.right.right.left = new Node(8);
root.right.right.right = new Node(9);
System.out.println("VERTICAL ORDER:");
printVerticalOrder(root);
}
}
| 24.633333 | 84 | 0.639378 |
1271618d9717fa7095d8edef4b998d75b9b4688e | 2,010 | // Copyright (c) 2003 Per M.A. Bothner.
// This is free software; for terms and warranty disclaimer see ./COPYING.
package gnu.kawa.xml;
import gnu.lists.*;
import gnu.mapping.*;
import java.io.*;
/** Abstract class that scans part of a node tree.
* Takes a node argument, and writes matching "relative" nodes
* out to a PositionConsumer as a sequence of position pairs.
* This is uses to implement "path expressions" as in XPath/XSLT/XQuery.
* For example, the ChildAxis sub-class writes out all child nodes
* of the argument that match the 'type' NodePredicate.
*/
public abstract class TreeScanner extends MethodProc
implements Externalizable
{
TreeScanner ()
{
setProperty(Procedure.validateApplyKey,
"gnu.kawa.xml.CompileXmlFunctions:validateApplyTreeScanner");
}
public NodePredicate type;
public NodePredicate getNodePredicate () { return type; }
public abstract void scan (AbstractSequence seq, int ipos,
PositionConsumer out);
public int numArgs() { return 0x1001; }
public void apply (CallContext ctx) throws Throwable
{
PositionConsumer out = (PositionConsumer) ctx.consumer;
Object node = ctx.getNextArg();
ctx.lastArg();
KNode spos;
try
{
spos = (KNode) node;
}
catch (ClassCastException ex)
{
throw new WrongType(getDesc(), WrongType.ARG_CAST, node, "node()");
}
scan(spos.sequence, spos.getPos(), out);
}
public void writeExternal(ObjectOutput out) throws IOException
{
out.writeObject(type);
}
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException
{
type = (NodePredicate) in.readObject();
}
public String getDesc ()
{
String thisName = getClass().getName();
int dot = thisName.lastIndexOf('.');
if (dot > 0)
thisName = thisName.substring(dot+1);
return thisName+"::"+type;
}
public String toString ()
{
return "#<" + getClass().getName() + ' ' + type + '>';
}
}
| 26.103896 | 77 | 0.674627 |
186414d07cc22552fb00015cc40421d95c4c1b6e | 1,061 | /*
* Copyright (c) 2022 Amadeus
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0
*
* SPDX-License-Identifier: Apache-2.0
*
* Contributors:
* Amadeus - initial API and implementation
*
*/
package org.eclipse.dataspaceconnector.transfer.dataplane.sync;
import org.eclipse.dataspaceconnector.spi.EdcSetting;
import java.util.concurrent.TimeUnit;
public interface DataPlaneTransferSyncConfig {
@EdcSetting
String DATA_PROXY_ENDPOINT = "edc.transfer.proxy.endpoint";
@EdcSetting
String DATA_PROXY_TOKEN_VALIDITY_SECONDS = "edc.transfer.proxy.token.validity.seconds";
long DEFAULT_DATA_PROXY_TOKEN_VALIDITY_SECONDS = TimeUnit.MINUTES.toSeconds(10);
@EdcSetting
String TOKEN_SIGNER_PRIVATE_KEY_ALIAS = "edc.transfer.proxy.token.signer.privatekey.alias";
@EdcSetting
String TOKEN_VERIFIER_PUBLIC_KEY_ALIAS = "edc.transfer.proxy.token.verifier.publickey.alias";
}
| 30.314286 | 97 | 0.765316 |
f10b9dadee5766b6e3f5e398d9d227b9938fb250 | 3,685 | /**
* Copyright 2017 Remi Guillemette - n4dev.ca
*
* 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 ca.n4dev.aegaeon.server.view;
/**
* UserInfoView.java
*
* TODO(rguillemette) Add description
*
* @author by rguillemette
* @since Dec 13, 2017
*/
public class UserInfoView {
private int index;
private Long refId;
private Long refTypeId;
private String category;
private String code;
private String name;
private String value;
public UserInfoView(){}
public UserInfoView(Long pId, String pCode, String pName, String pCategory, String pValue){
this.refId = pId;
this.code = pCode;
this.name = pName;
this.category = pCategory;
this.value = pValue;
}
/**
* @return the category
*/
public String getCategory() {
return category;
}
/**
* @param pCategory the category to set
*/
public void setCategory(String pCategory) {
category = pCategory;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param pName the name to set
*/
public void setName(String pName) {
name = pName;
}
/**
* @return the value
*/
public String getValue() {
return value;
}
/**
* @param pValue the value to set
*/
public void setValue(String pValue) {
value = pValue;
}
/**
* @return the code
*/
public String getCode() {
return code;
}
/**
* @param pCode the code to set
*/
public void setCode(String pCode) {
code = pCode;
}
/**
* @return the refId
*/
public Long getRefId() {
return refId;
}
/**
* @param pRefId the refId to set
*/
public void setRefId(Long pRefId) {
refId = pRefId;
}
/**
* @return the index
*/
public int getIndex() {
return index;
}
/**
* @param pIndex the index to set
*/
public void setIndex(int pIndex) {
index = pIndex;
}
/**
* @return the otherType
*/
public boolean isOtherType() {
return code != null && code.contains("OTHER");
}
/**
* @return the refTypeId
*/
public Long getRefTypeId() {
return refTypeId;
}
/**
* @param pRefTypeId the refTypeId to set
*/
public void setRefTypeId(Long pRefTypeId) {
refTypeId = pRefTypeId;
}
public String toString() {
return new StringBuilder()
.append(getClass().getSimpleName())
.append("[refId:").append(this.refId)
.append(",code:").append(this.code)
.append(",value:").append(this.value)
.append("]")
.toString();
}
}
| 21.300578 | 95 | 0.569607 |
e54f7172b48de6ea7cc4af855f714d6b40a122f1 | 7,027 | package com.zdran.springboot.guava;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.collect.*;
import com.google.common.primitives.Ints;
import com.zdran.springboot.dao.AccountInfo;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.*;
/**
* Create by ranzhendong on 2019-09-09
*
* @author [email protected]
*/
public class MyCollections {
public static void testImmutable() {
ImmutableSet<String> immutableSet = ImmutableSet.<String>builder().add("c")
.add("b").build();
for (String s : immutableSet) {
System.out.print(s + ",");
}
System.out.println();
}
private static void testSort() {
ImmutableSortedSet<String> immutableSortedSet = ImmutableSortedSet.of("c", "a", "b");
for (String s : immutableSortedSet) {
System.out.print(s + ",");
}
System.out.println();
}
private static void testMultiset() {
Multiset<String> multiset = HashMultiset.create();
multiset.add("a");
multiset.add("a");
multiset.add("b");
multiset.add("c");
multiset.setCount("b", 3);
System.out.println(multiset.contains("a"));
System.out.println(multiset.count("a"));
System.out.println(multiset.remove("b"));
System.out.println(multiset.count("b"));
System.out.println(multiset.count("a"));
System.out.println(multiset.size());
}
private static void testSortMultiset() {
SortedMultiset<Integer> multiset = TreeMultiset.create();
multiset.addAll(Lists.newArrayList(3, 2, 5, 6, 9, 2, 5, 6, 8));
for (int num : multiset) {
System.out.print(num + ",");
}
}
private static void testMultimap() {
Multimap<String, Integer> multimap = ArrayListMultimap.create();
multimap.put("a", 1);
multimap.put("a", 2);
multimap.put("a", 3);
multimap.put("a", 4);
System.out.println(multimap.containsKey("a"));
System.out.println(multimap.containsEntry("a", 1));
System.out.println(multimap.containsEntry("a", 0));
System.out.println(multimap.remove("a", 3));
System.out.println(Arrays.deepToString(multimap.get("a").toArray()));
}
private static void testBiMap() {
BiMap<String, Integer> biMap = HashBiMap.create();
biMap.put("a", 1);
biMap.put("b", 2);
System.out.println(biMap.inverse().get(2));
biMap.forcePut("c", 2);
System.out.println(biMap.inverse().get(2));
}
private static void testUtil1() {
List<AccountInfo> accountInfoList = Lists.newArrayList();
List<AccountInfo> accountInfoList2 = Lists.newArrayListWithCapacity(3);
List<AccountInfo> accountInfoList3 = Lists.newArrayListWithExpectedSize(3);
List<AccountInfo> accountInfoList4 = Lists.newArrayList(new AccountInfo());
Iterable<Integer> concatenated = Iterables.concat(Ints.asList(1, 2, 3),
Ints.asList(3, 4, 5));
System.out.println(Iterables.frequency(concatenated, 3));
System.out.println(Iterables.getFirst(concatenated, 0));
}
private static void testSets() {
Set<Integer> set = Sets.union(Sets.newHashSet(1, 2, 3), Sets.newHashSet(3, 4, 5));
System.out.println(Arrays.deepToString(set.toArray()));
Set<Integer> set2 = Sets.intersection(Sets.newHashSet(1, 2, 3), Sets.newHashSet(3, 4, 5));
System.out.println(Arrays.deepToString(set2.toArray()));
Set<Integer> set3 = Sets.difference(Sets.newHashSet(1, 2, 3), Sets.newHashSet(1, 2));
System.out.println(Arrays.deepToString(set3.toArray()));
}
private static void testMaps() {
Map<String, Integer> hashMap = Maps.newHashMap();
hashMap.put("a", 1);
hashMap.put("bb", 2);
hashMap.put("ccc", 3);
Map<String, Integer> hashMap1 = Maps.filterKeys(hashMap, new Predicate<String>() {
@Override
public boolean apply(@Nullable String input) {
return input.length() > 2;
}
});
System.out.println(Arrays.deepToString(hashMap1.entrySet().toArray()));
Map<String, Integer> hashMap2 = Maps.filterEntries(hashMap, new Predicate<Map.Entry<String, Integer>>() {
@Override
public boolean apply(Map.@Nullable Entry<String, Integer> input) {
return input.getValue() > 2;
}
});
System.out.println(Arrays.deepToString(hashMap2.entrySet().toArray()));
Map<Integer, String> hashMap3 = Maps.uniqueIndex(Lists.newArrayList("sss", "ss", "ssss"),
new Function<String, Integer>() {
@Nullable
@Override
public Integer apply(@Nullable String input) {
return input.length();
}
});
System.out.println(Arrays.deepToString(hashMap3.entrySet().toArray()));
Map<String, Integer> left = ImmutableMap.of("a", 1, "b", 2, "c", 3);
Map<String, Integer> right = ImmutableMap.of("a", 1, "b", 2, "c", 3);
MapDifference<String, Integer> diff = Maps.difference(left, right);
diff.entriesInCommon(); // {"b" => 2}
diff.entriesInCommon(); // {"b" => 2}
diff.entriesOnlyOnLeft(); // {"a" => 1}
diff.entriesOnlyOnRight(); // {"d" => 5}MapDifference
}
private static void testForwarding() {
ForwardingList<String> forwardingList = new ForwardingList<String>() {
final List<String> delegate = new ArrayList<>(); // backing list
@Override
protected List<String> delegate() {
return delegate;
}
@Override
public void add(int index, String element) {
System.out.println("add:" + element);
super.add(index, element);
}
@Override
public String get(int index) {
System.out.println("get:" + index);
return super.get(index);
}
};
forwardingList.add(0, "aaa");
System.out.println(forwardingList.get(0));
}
public static void main(String[] args) {
// testImmutable();
// testSort();
// testMultiset();
// testSortMultiset();
// testMultimap();
// testBiMap();
// testSets();
// testMaps();
// testForwarding();
test();
}
private static void test() {
Map<String, Object> result = new HashMap<>();
List<Integer> integers = new ArrayList<>();
integers.add(8);
integers.add(23);
integers.add(85);
result.put("attrIds", integers);
System.out.println(Joiner.on(",").join((Collection) (result.get("attrIds"))));
}
}
| 33.783654 | 113 | 0.581756 |
9fcddb782e74b3fc6d7b22ef45d4743125f88a04 | 6,266 | /*
* Copyright 2004-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springmodules.validation.valang.functions;
import org.springframework.util.Assert;
import org.springmodules.validation.valang.ValangException;
/**
* <p>Base class for functions. Function classes should extend this class.
* <p/>
* <p>The lifecyle of a function that extends this class is:
* <p/>
* <ul>
* <li>Function instance is created through {@link AbstractFunction#AbstractFunction(Function[], int, int)}
* <li>Spring callback interfaces are called (in this order):
* <ul>
* <li>{@link org.springframework.beans.factory.BeanFactoryAware#setBeanFactory(org.springframework.beans.factory.BeanFactory)}
* <li>{@link org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)}
* <li>{@link org.springframework.context.ResourceLoaderAware#setResourceLoader(org.springframework.core.io.ResourceLoader)}
* <li>{@link org.springframework.context.MessageSourceAware#setMessageSource(org.springframework.context.MessageSource)}
* <li>{@link org.springframework.context.ApplicationEventPublisherAware#setApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher)}
* <li>{@link org.springframework.web.context.ServletContextAware#setServletContext(javax.servlet.ServletContext)}
* </ul>
* <li>Function properties are autowired by name if {@link AbstractFunction#isAutowireByName()} returns true
* <li>Function properties are autowired by type if {@link AbstractFunction#isAutowireByType()} returns true
* <li>{@link AbstractFunction#init()} is called
* <li>Function is ready for use by validator
* </ul>
* <p/>
* <p>Function implementations can implement any of the Spring callback interfaces listed above to get access to the specific objects.
*
* @author Steven Devijver
* @since Apr 23, 2005
*/
public abstract class AbstractFunction implements Function {
private Function[] arguments = null;
private FunctionTemplate template = null;
/**
* Constructor
*/
protected AbstractFunction() {}
/**
* <p>Constructor</p>
*
* <p><strong>Note</strong>: Sub classes must implement this constructor
* unless they implement <code>ConfigurableConstructor</code>.</p>
*/
public AbstractFunction(Function[] arguments, int line, int column) {
super();
setArguments(arguments);
setTemplate(line, column);
}
/**
* Gets arguments
*/
public Function[] getArguments() {
return arguments;
}
/**
* Sets arguments.
*/
protected void setArguments(Function[] arguments) {
Assert.notNull(arguments, "Function parameters should not be null!");
this.arguments = arguments;
}
/**
* Gets template.
*/
protected FunctionTemplate getTemplate() {
return this.template;
}
/**
* Sets template.
*/
protected void setTemplate(FunctionTemplate template) {
this.template = template;
}
/**
* Sets template with line and row number by
* creating a new <code>FunctionTemplate</code>.
*/
protected void setTemplate(int line, int column) {
setTemplate(new FunctionTemplate(line, column));
}
/**
* Call this method in the constructor of custom functions to define the minimum number of arguments.
*/
protected void definedMinNumberOfArguments(int minNumberOfArguments) {
if (getArguments().length < minNumberOfArguments) {
throw new ValangException("Function requires at least " + minNumberOfArguments + " argument(s)", getTemplate().getLine(), getTemplate().getColumn());
}
}
/**
* Call this method in the constructor of custom functions to define the maximum number of arguments.
*/
protected void definedMaxNumberOfArguments(int maxNumberOfArguments) {
if (getArguments().length > maxNumberOfArguments) {
throw new ValangException("Function cannot have more than " + maxNumberOfArguments + " arguments(s)", getTemplate().getLine(), getTemplate().getColumn());
}
}
/**
* Call this method in the constructor of custom functions to define the exact number of arguments.
*/
protected void definedExactNumberOfArguments(int exactNumberOfArguments) {
if (getArguments().length != exactNumberOfArguments) {
throw new ValangException("Function must have exactly " + exactNumberOfArguments + " arguments", getTemplate().getLine(), getTemplate().getColumn());
}
}
/**
* Gets result. Implementation of <code>Function</code>.
*/
public final Object getResult(Object target) {
return getTemplate().execute(target, new FunctionCallback() {
public Object execute(Object target) throws Exception {
return doGetResult(target);
}
});
}
/**
* Processes result for subclasses.
*/
protected abstract Object doGetResult(Object target) throws Exception;
/**
* If true properties of function will be autowired by type by the Spring bean factory.
*/
public boolean isAutowireByType() {
return false;
}
/**
* If true properties of function will be autowired by name by the Spring bean factory.
*/
public boolean isAutowireByName() {
return false;
}
/**
* This method is called when all properties have been set through autowiring. This method
* can be implemented to initialize resources or verify if mandatory properties have been set.
*/
public void init() throws Exception {
}
}
| 36.011494 | 166 | 0.691829 |
586a99f825798fda8754d5a16715af1fe99dab8f | 9,671 | /*
* Generated by the Jasper component of Apache Tomcat
* Version: Apache Tomcat/7.0.47
* Generated at: 2020-08-16 09:42:28 UTC
* Note: The last modified time of this file was set to
* the last modified time of the source file after
* generation to assist with modification tracking.
*/
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final javax.servlet.jsp.JspFactory _jspxFactory =
javax.servlet.jsp.JspFactory.getDefaultFactory();
private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;
private javax.el.ExpressionFactory _el_expressionfactory;
private org.apache.tomcat.InstanceManager _jsp_instancemanager;
public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
_jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
}
public void _jspDestroy() {
}
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
throws java.io.IOException, javax.servlet.ServletException {
final javax.servlet.jsp.PageContext pageContext;
javax.servlet.http.HttpSession session = null;
final javax.servlet.ServletContext application;
final javax.servlet.ServletConfig config;
javax.servlet.jsp.JspWriter out = null;
final java.lang.Object page = this;
javax.servlet.jsp.JspWriter _jspx_out = null;
javax.servlet.jsp.PageContext _jspx_page_context = null;
try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("<html>\r\n");
out.write("<body bgcolor=\"#D3D3D3\">\r\n");
out.write("<table style=\"border-collapse: collapse;\" border=\"0\" width=\"100%\" cellspacing=\"0\" cellpadding=\"0\">\r\n");
out.write(" <tr style=\"background-color: #D3D3D3;\">\r\n");
out.write(" <td> </td>\r\n");
out.write(" </tr>\r\n");
out.write(" <tr>\r\n");
out.write(" <td align=\"center\" valign=\"top\" bgcolor=\"#D3D3D3\">\r\n");
out.write(" <table table style=\"border-collapse: collapse; font-family:Arial; font-size: 14px;\r\n");
out.write(" border: solid 2px black; border-radius: 2px;\"\r\n");
out.write(" width=\"550\" cellspacing=\"0\" cellpadding=\"0\" bgcolor=\"#D3D3D3\">\r\n");
out.write(" <tr>\r\n");
out.write(" <td align=\"center\" valign=\"top\" bgcolor=\"#ffffff\">\r\n");
out.write(" <table style=\"border-collapse: collapse; \"\r\n");
out.write(" border=\"0\" width=\"500\"\r\n");
out.write(" cellspacing=\"0\" cellpadding=\"0\" align=\"center\">\r\n");
out.write(" <tr style=\"background-color: #ffffff;\">\r\n");
out.write(" <td> </td>\r\n");
out.write(" </tr>\r\n");
out.write(" <tr>\r\n");
out.write(" <td align=\"center\">\r\n");
out.write(" <h2>Welcome to GSI bank</h2>\r\n");
out.write(" <h3>Proceed to our login page or use register form to create new account.</h3>\r\n");
out.write(" </td>\r\n");
out.write(" </tr>\r\n");
out.write(" <tr style=\"background-color: #ffffff; \">\r\n");
out.write(" <td> </td>\r\n");
out.write(" </tr>\r\n");
out.write(" <tr>\r\n");
out.write(" <td>\r\n");
out.write(" <table style=\"border-collapse: collapse; \"\r\n");
out.write(" border=\"0\" width=\"230\"\r\n");
out.write(" cellspacing=\"0\" cellpadding=\"0\" align=\"left\">\r\n");
out.write(" <tr>\r\n");
out.write(" <td align=\"center\" width=\"230px\">\r\n");
out.write(" <form action=\"login.jsp\" method=\"post\">\r\n");
out.write(" <input type=\"submit\" value=\"Login\" style=\"margin: 10px 20px 5px 20px\"/>\r\n");
out.write(" </form>\r\n");
out.write(" </td>\r\n");
out.write(" </tr>\r\n");
out.write(" </table>\r\n");
out.write(" <table style=\"border-collapse: collapse; \"\r\n");
out.write(" border=\"0\" width=\"230\"\r\n");
out.write(" cellspacing=\"0\" cellpadding=\"0\" align=\"right\">\r\n");
out.write(" <tr>\r\n");
out.write(" <td align=\"center\" width=\"230px\">\r\n");
out.write(" <form action=\"registerUser.jsp\" method=\"post\">\r\n");
out.write(" <input type=\"submit\" value=\"Register\" style=\"margin: 10px 20px 0px 20px\"/>\r\n");
out.write(" </form>\r\n");
out.write(" </td>\r\n");
out.write(" </tr>\r\n");
out.write(" </table>\r\n");
out.write(" </td>\r\n");
out.write(" </tr>\r\n");
out.write(" <tr><td align=\"center\">\r\n");
out.write(" <form action=\"createDatabaseAction\" method=\"post\">\r\n");
out.write(" <input type=\"submit\" value=\"Create Database\" style=\"margin: 10px 0px 0px 0px\"/>\r\n");
out.write(" </form>\r\n");
out.write(" </td></tr>\r\n");
out.write(" <tr>\r\n");
out.write(" <td align=\"center\">\r\n");
out.write(" <h5>\r\n");
out.write(" ");
String reg = request.getParameter("reg");
if (reg != null)
{
out.println("You are successfully registered to GSI bank.");
out.println("Please, use your login to enter our bank.");
}
String data = request.getParameter("data");
if (data != null)
{
out.println("Database ready for work!");
}
out.write("\r\n");
out.write(" </h5>\r\n");
out.write(" </td>\r\n");
out.write(" </tr>\r\n");
out.write(" <tr style=\"background-color: #ffffff; \">\r\n");
out.write(" <td> </td>\r\n");
out.write(" </tr>\r\n");
out.write("\r\n");
out.write(" </table>\r\n");
out.write(" </td>\r\n");
out.write(" </tr>\r\n");
out.write(" </table>\r\n");
out.write(" </td>\r\n");
out.write(" </tr>\r\n");
out.write("</table>\r\n");
out.write("</body>\r\n");
out.write("</html>");
} catch (java.lang.Throwable t) {
if (!(t instanceof javax.servlet.jsp.SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try { out.clearBuffer(); } catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
| 57.565476 | 156 | 0.440182 |
52776e6f532947479b87b02b02d098e92393b574 | 497 | //
// このファイルは、JavaTM Architecture for XML Binding(JAXB) Reference Implementation、v2.2.8-b130911.1802によって生成されました
// <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>を参照してください
// ソース・スキーマの再コンパイル時にこのファイルの変更は失われます。
// 生成日: 2015.08.14 時間 10:22:22 PM JST
//
@javax.xml.bind.annotation.XmlSchema(namespace = "http://webservices.amazon.com/AWSECommerceService/2011-08-01", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package com.eitax.recall.amazon.xsd;
| 49.7 | 180 | 0.768612 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.