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
|
|---|---|---|---|---|---|
bd974659c739d65584e22c095d193e60377a1aff
| 328
|
package me.javaroad.mcloud.oauth.dto.request;
import java.util.Set;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.validator.constraints.NotEmpty;
/**
* @author heyx
*/
@Getter
@Setter
public class ModifyClientRequest {
private String clientSecret;
@NotEmpty
private Set<String> redirectUri;
}
| 18.222222
| 52
| 0.759146
|
5612debbbfe1079fde7470067f8b3e02d25c0f99
| 4,109
|
/* THIS IS SAMPLE CODE PROVIDED WITH THE UNDERSTANDING THAT
* IT IS TO BE USED FOLLOWING LICENSE COMPLIANCE. THE SAMPLE
* CAN ONLY BE USED WITH A TRIAL OR LICENSED VERSION OF
* HYBRID DATA PIPELINE. FOR MORE INFORMATION ON HYBRID
* DATA PIPELINE, PLEASE VISIT:
* https://www.progress.com/cloud-and-hybrid-data-integration
*
* Hybrid Data Pipeline External Authentication Example
*
* Developer: Julien Mansier
* Date: 7/25/2018
*
* Note from the developer: I am no programming expert, so
* please forgive any programming mistakes.
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.HttpsURLConnection;
import org.json.JSONArray;
import org.json.JSONObject;
import com.ddtek.cloudservice.plugins.auth.javaplugin.JavaAuthPluginException;
public class OktaAuth implements com.ddtek.cloudservice.plugins.auth.javaplugin.JavaAuthPluginInterface{
Logger oktaLogger;
String apiURL, apiToken;
public boolean authenticate(String arg0, String arg1, String arg2){
//Using the HDP Logger
oktaLogger.log(Level.CONFIG, "Authenticate Called.\n");
String response ="";
JSONArray jsonResp;
JSONObject jsonBody;
String status = "";
String id = "";
try {
// apiURL is passed by HDP and is set in the init method
URL userUrl = new URL(apiURL+"/api/v1/users?q="+arg0);
// Standard REST call
HttpsURLConnection conn = (HttpsURLConnection) userUrl.openConnection();
conn.setDoInput(true);
conn.setRequestMethod("GET");
conn.setDoOutput(false);
//conn.setInstanceFollowRedirects(false);
conn.addRequestProperty("Accept", "Application/JSON");
conn.addRequestProperty("Content-Type", "Application/JSON");
conn.addRequestProperty("Authorization", "SSWS "+ apiToken);
conn.connect();
int statusCode = conn.getResponseCode();
// We accept any response except 400 and up
if(statusCode >= 200 && statusCode < 400) {
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
while ((output = br.readLine()) != null) {
response+=output;
}
jsonResp = new JSONArray(response);
conn.disconnect();
if(jsonResp.length() > 0) {
status=jsonResp.getJSONObject(0).getString("status");
id=jsonResp.getJSONObject(0).getString("id");
}
else {
// If no response then user doesn't exist and/or has been deactivated
oktaLogger.log(Level.CONFIG, "No response. Return false.\n");
return false;
}
}
else {
// If Status Codee 400+, log which one it was.
oktaLogger.log(Level.CONFIG, "Status Code:"+statusCode+". Return false.\n");
return false;
}
} catch (MalformedURLException e) {
oktaLogger.log(Level.CONFIG, "URLException: "+e.toString()+"\n");
return false;
} catch (IOException e) {
oktaLogger.log(Level.CONFIG, "IOException: "+e.toString()+"\n");
return false;
}
if(status.equalsIgnoreCase("ACTIVE") || status.equalsIgnoreCase("PROVISIONED")) {
// We are ok to validate both Active users and Provisioned users
oktaLogger.log(Level.CONFIG, "User active. Return true.\n");
return true;
}
else {
// This is basically a catch all
oktaLogger.log(Level.CONFIG, "User not active. Return false.\n");
return false;
}
}
public void destroy() {
System.out.println("destroy() called");
}
public void init(HashMap<String, Object> arg0, Logger arg1) {
// Grab the URL and API token from the HDP attributes
apiURL = arg0.get("url").toString();
apiToken = arg0.get("token").toString();
oktaLogger = arg1;
oktaLogger.log(Level.CONFIG, "init() called.\n");
oktaLogger.log(Level.CONFIG, "url = "+apiURL+"\n");
}
}
| 26.856209
| 104
| 0.679727
|
f7ac1435ddf17ddb5b42b31b54ba9338b45862a7
| 4,356
|
package wraith.smithee.mixin;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.EntityGroup;
import net.minecraft.entity.LivingEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.util.Identifier;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.ModifyVariable;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
import wraith.smithee.properties.Modifier;
import wraith.smithee.properties.Trait;
import wraith.smithee.properties.TraitType;
import java.util.HashMap;
@Mixin(EnchantmentHelper.class)
public class EnchantmentHelperMixin {
@Inject(method = "hasAquaAffinity", at = @At("HEAD"), cancellable = true)
private static void hasAquaAffinity(LivingEntity entity, CallbackInfoReturnable<Boolean> cir) {
if (Trait.hasTrait(entity.getMainHandStack(), TraitType.AQUADYNAMIC)) {
cir.setReturnValue(true);
cir.cancel();
}
}
/*
@Inject(method = "getAttackDamage", at = @At("HEAD"), cancellable = true)
private static void getAttackDamage(ItemStack stack, EntityGroup group, CallbackInfoReturnable<Float> cir) {
HashMap<String, Object> result = Modifier.evaluateModifiers(stack);
if (result.containsKey("Quartz")) {
float dmg = 1.0F + Math.max(0, (float) result.get("Quartz") - 1) * 0.5F;
cir.setReturnValue(dmg);
cir.cancel();
}
}
@Inject(method = "getEfficiency", at = @At("HEAD"), cancellable = true)
private static void getEfficiency(LivingEntity entity, CallbackInfoReturnable<Integer> cir) {
HashMap<String, Object> result = Modifier.evaluateModifiers(entity.getMainHandStack());
if (result.containsKey("Redstone")) {
cir.setReturnValue((Integer) result.get("Redstone"));
cir.cancel();
}
}
*/
@Inject(method = "getLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/item/ItemStack;getEnchantments()Lnet/minecraft/nbt/ListTag;"), cancellable = true, locals = LocalCapture.CAPTURE_FAILSOFT)
private static void getLevel(Enchantment enchantment, ItemStack stack, CallbackInfoReturnable<Integer> cir, Identifier id) {
HashMap<String, Modifier> result = Modifier.evaluateModifiers(stack);
int level = 0;
for (Modifier modifiers : result.values()) {
for (String modifier : modifiers.modifiers) {
if (modifier.equals(id.toString())) {
level += modifiers.level;
}
}
}
if (level > 0) {
cir.setReturnValue(level);
cir.cancel();
}
}
@ModifyVariable(method = "forEachEnchantment(Lnet/minecraft/enchantment/EnchantmentHelper$Consumer;Lnet/minecraft/item/ItemStack;)V", at = @At(value = "INVOKE_ASSIGN", target = "Lnet/minecraft/item/ItemStack;getEnchantments()Lnet/minecraft/nbt/ListTag;"))
private static ListTag forEachEnchantment(ListTag listTag, EnchantmentHelper.Consumer consumer, ItemStack stack) {
HashMap<String, Modifier> result = Modifier.evaluateModifiers(stack);
if (result.isEmpty()) {
return listTag;
}
ListTag newListTag = listTag.copy();
for (Modifier modifiers : result.values()) {
if (!"enchant".equals(modifiers.type)) {
continue;
}
for (String modifier : modifiers.modifiers) {
CompoundTag tag = new CompoundTag();
tag.putString("id", modifier);
tag.putInt("lvl", modifiers.level);
newListTag.add(tag);
}
}
return newListTag;
}
@Inject(method = "getAttackDamage", at = @At("RETURN"), cancellable = true)
private static void addHolyDamage(ItemStack stack, EntityGroup group, CallbackInfoReturnable<Float> cir) {
if (Trait.hasTrait(stack, TraitType.HOLY) && group == EntityGroup.UNDEAD) {
cir.setReturnValue(cir.getReturnValue() + 2.5f);
}
}
}
| 44
| 259
| 0.671717
|
85b79dca1ceb52148f834ed66f9782edcc9090ed
| 2,019
|
package thenewglobals;
import play.Configuration;
import play.Environment;
import play.Logger;
import play.api.OptionalSourceMapper;
import play.api.UsefulException;
import play.api.routing.Router;
import play.http.DefaultHttpErrorHandler;
import play.libs.F;
import play.mvc.Http;
import play.mvc.Result;
import javax.inject.Inject;
import javax.inject.Provider;
public class CustomHttpErrorHandler extends DefaultHttpErrorHandler {
@Inject
public CustomHttpErrorHandler(final Configuration configuration, final Environment environment, final OptionalSourceMapper optionalSourceMapper, final Provider<Router> provider) {
super(configuration, environment, optionalSourceMapper, provider);
}
@Override
protected F.Promise<Result> onBadRequest(final Http.RequestHeader requestHeader, final String s) {
return super.onBadRequest(requestHeader, s);
}
@Override
public F.Promise<Result> onClientError(final Http.RequestHeader requestHeader, final int i, final String s) {
return super.onClientError(requestHeader, i, s);
}
@Override
protected F.Promise<Result> onDevServerError(final Http.RequestHeader requestHeader, final UsefulException e) {
return super.onDevServerError(requestHeader, e);
}
@Override
protected F.Promise<Result> onForbidden(final Http.RequestHeader requestHeader, final String s) {
return super.onForbidden(requestHeader, s);
}
@Override
protected F.Promise<Result> onNotFound(final Http.RequestHeader requestHeader, final String s) {
return super.onNotFound(requestHeader, s);
}
@Override
protected F.Promise<Result> onProdServerError(final Http.RequestHeader requestHeader, final UsefulException e) {
return super.onProdServerError(requestHeader, e);
}
@Override
public F.Promise<Result> onServerError(final Http.RequestHeader requestHeader, final Throwable throwable) {
return super.onServerError(requestHeader, throwable);
}
}
| 34.220339
| 183
| 0.759287
|
2e748e8f9b35cb6f004905aaf97c8082faee1b38
| 1,019
|
package com.github.fppt.jedismock.operations.lists;
import com.github.fppt.jedismock.datastructures.RMList;
import com.github.fppt.jedismock.operations.AbstractRedisOperation;
import com.github.fppt.jedismock.operations.RedisCommand;
import com.github.fppt.jedismock.server.Response;
import com.github.fppt.jedismock.storage.RedisBase;
import com.github.fppt.jedismock.datastructures.Slice;
import java.util.List;
@RedisCommand("lpop")
class LPop extends AbstractRedisOperation {
LPop(RedisBase base, List<Slice> params ) {
super(base, params);
}
Slice popper(List<Slice> list) {
return list.remove(0);
}
protected Slice response() {
Slice key = params().get(0);
final RMList listDBObj = getListFromBaseOrCreateEmpty(key);
List<Slice> list = listDBObj.getStoredData();
if(list == null || list.isEmpty()) return Response.NULL;
Slice v = popper(list);
base().putValue(key, listDBObj);
return Response.bulkString(v);
}
}
| 31.84375
| 67
| 0.711482
|
7bac82c851f98a2ec09e449232c34977091b0d78
| 2,088
|
/*
* Copyright 2013-2014 must-be.org
*
* 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 consulo.msil.representation;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.util.Consumer;
import consulo.annotation.UsedInPlugin;
import consulo.annotation.access.RequiredReadAction;
import javax.annotation.Nonnull;
/**
* @author VISTALL
* @since 03.06.14
*/
public class MsilRepresentationNavigateUtil
{
public static final Consumer<PsiFile> DEFAULT_NAVIGATOR = new Consumer<PsiFile>()
{
@Override
public void consume(PsiFile file)
{
file.navigate(true);
}
};
@RequiredReadAction
@UsedInPlugin
public static void navigateToRepresentation(@Nonnull final PsiElement msilElement, @Nonnull FileType fileType)
{
navigateToRepresentation(msilElement, fileType, DEFAULT_NAVIGATOR);
}
@RequiredReadAction
@UsedInPlugin
public static void navigateToRepresentation(@Nonnull final PsiElement msilElement, @Nonnull FileType fileType, @Nonnull Consumer<PsiFile> consumer)
{
MsilFileRepresentationManager manager = MsilFileRepresentationManager.getInstance(msilElement.getProject());
VirtualFile virtualFile = PsiUtilCore.getVirtualFile(msilElement);
if(virtualFile == null)
{
return;
}
PsiFile representationFile = manager.getRepresentationFile(fileType, virtualFile);
if(representationFile == null)
{
return;
}
consumer.consume(representationFile);
}
}
| 28.60274
| 148
| 0.777299
|
3bb03487afb9ef56e65d930071eb0a248a6dddbc
| 4,545
|
/* SPDX-License-Identifier: Apache 2.0 */
/* Copyright Contributors to the ODPi Egeria project. */
package org.odpi.openmetadata.accessservices.communityprofile.properties;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import org.odpi.openmetadata.accessservices.communityprofile.rest.MetadataSourceRequestBody;
import java.io.Serializable;
import java.util.Date;
import java.util.Objects;
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE;
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_ONLY;
/**
* MetadataSourceRequestBody carries the parameters for marking an asset or schema as external.
*/
@JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown=true)
public class AppointmentProperties implements Serializable
{
private static final long serialVersionUID = 1L;
private Date effectiveFrom = null;
private Date effectiveTo = null;
private boolean isPublic = false;
/**
* Default constructor
*/
public AppointmentProperties()
{
super();
}
/**
* Copy/clone constructor
*
* @param template object to copy
*/
public AppointmentProperties(AppointmentProperties template)
{
if (template != null)
{
effectiveFrom = template.getEffectiveFrom();
effectiveTo = template.getEffectiveTo();
isPublic = template.getIsPublic();
}
}
/**
* Return the date/time that this element is effective from (null means effective from the epoch).
*
* @return date object
*/
public Date getEffectiveFrom()
{
return effectiveFrom;
}
/**
* Set up the date/time that this element is effective from (null means effective from the epoch).
*
* @param effectiveFrom date object
*/
public void setEffectiveFrom(Date effectiveFrom)
{
this.effectiveFrom = effectiveFrom;
}
/**
* Return the date/time that element is effective to (null means that it is effective indefinitely into the future).
*
* @return date object
*/
public Date getEffectiveTo()
{
return effectiveTo;
}
/**
* Set the date/time that element is effective to (null means that it is effective indefinitely into the future).
*
* @param effectiveTo date object
*/
public void setEffectiveTo(Date effectiveTo)
{
this.effectiveTo = effectiveTo;
}
/**
* Return if the contents of this profile be shared with colleagues.
*
* @return flag
*/
public boolean getIsPublic()
{
return isPublic;
}
/**
* Set up if the contents of this profile be shared with colleagues.
*
* @param isPublic flag
*/
public void setIsPublic(boolean isPublic)
{
this.isPublic = isPublic;
}
/**
* JSON-style toString
*
* @return return string containing the property names and values
*/
@Override
public String toString()
{
return "AppointmentProperties{" +
"effectiveFrom=" + effectiveFrom +
", effectiveTo=" + effectiveTo +
", isPublic=" + isPublic +
'}';
}
/**
* Return comparison result based on the content of the properties.
*
* @param objectToCompare test object
* @return result of comparison
*/
@Override
public boolean equals(Object objectToCompare)
{
if (this == objectToCompare)
{
return true;
}
if (objectToCompare == null || getClass() != objectToCompare.getClass())
{
return false;
}
AppointmentProperties that = (AppointmentProperties) objectToCompare;
return isPublic == that.isPublic &&
Objects.equals(effectiveFrom, that.effectiveFrom) &&
Objects.equals(effectiveTo, that.effectiveTo);
}
/**
* Return hash code for this object
*
* @return int hash code
*/
@Override
public int hashCode()
{
return Objects.hash(super.hashCode(), effectiveFrom, effectiveTo, isPublic);
}
}
| 26.12069
| 120
| 0.631243
|
eaa5284ad559d6e6755af5f5e6e2837fe0c5ac10
| 13,535
|
// Copyright 2000-2021 Nokia
//
// Licensed under the Apache License 2.0
// SPDX-License-Identifier: Apache-2.0
//
package com.nextenso.mux.util;
import java.io.IOException;
import java.net.BindException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.log4j.Logger;
import alcatel.tess.hometop.gateways.utils.Log;
import com.alcatel.as.util.sctp.*;
import com.nextenso.mux.MuxConnection;
import com.nextenso.mux.MuxFactory;
import com.nextenso.mux.MuxFactory.ConnectionListener;
import com.nextenso.mux.MuxHandler.SctpAddressEvent;
import com.nextenso.mux.MuxHandler;
import com.nextenso.mux.MuxHeader;
import com.nextenso.mux.socket.SocketManager;
import com.nextenso.mux.socket.TcpMessageParser;
import com.nextenso.mux.util.MuxIdentification;
import com.nextenso.mux.util.MuxUtils;
import com.nextenso.mux.util.TimeoutManager;
public abstract class AbstractMuxConnection implements MuxConnection {
protected boolean _ipv6Support;
protected boolean _byteBufferMode;
protected SocketManager _socketManager;
protected TimeoutManager _timeoutManager;
protected MuxHandler _handler;
protected ConnectionListener _connectionListener;
protected Object[] _attributes;
protected Object _attachment;
protected int _id;
protected static AtomicInteger ID = new AtomicInteger(1);
protected boolean _threadSafe;
protected Log _logger;
protected Logger _logger4j;
protected volatile boolean _open;
protected boolean _muxOpened;
// used on the stack side
public AbstractMuxConnection (Logger logger){
setLogger (logger);
_id = ID.getAndIncrement();
}
// used on the agent side
public AbstractMuxConnection (MuxHandler mh, ConnectionListener listener, Logger logger){
this (logger);
_connectionListener = listener;
_socketManager = new SocketManagerImpl ();
setMuxHandler (mh);
}
// may be set after the constructor
public void setMuxHandler (MuxHandler mh){
_handler = mh;
if (mh != null){
@SuppressWarnings("rawtypes")
java.util.Hashtable muxConf = _handler.getMuxConfiguration();
_ipv6Support = ((Boolean) muxConf.get(MuxHandler.CONF_IPV6_SUPPORT)).booleanValue();
_byteBufferMode = ((Boolean) muxConf.get(MuxHandler.CONF_USE_NIO)).booleanValue();
_threadSafe = ((Boolean) muxConf.get(MuxHandler.CONF_THREAD_SAFE)).booleanValue();
}
}
public void shutdown (){ close ();}
public void opened (){
opened (true);
}
public void opened (boolean notifyMuxHandler){
// the goal is to be able to call this method twice to be able to delay _handler.muxOpened if needed
if (_open == false){
_open = true;
if (_connectionListener != null)
_connectionListener.muxConnected (this, null);
}
if (notifyMuxHandler){
if (_muxOpened) return; // make it idempotent
_muxOpened = true;
_handler.muxOpened (this);
}
}
public void failed (Throwable err){
if (_connectionListener != null)
_connectionListener.muxConnected (this, err);
}
public void closed() {
_open = false;
if (_connectionListener != null)
_connectionListener.muxClosed (this);
if (_muxOpened) _handler.muxClosed (this);
}
public boolean isOpened() { return _open;}
public int getId() { return _id;}
public int getInputChannel() { return 0;}
public Logger getLogger (){ return _logger4j;}
public void setLogger (Logger logger){ _logger = Log.getLogger (_logger4j = logger);}
public boolean setKeepAlive(int interval, int idleFactor){ throw new UnsupportedOperationException("method setKeepAlive() is not supported");}
public boolean useKeepAlive() {return false;}
/***********************/
protected String _stackAppName, _stackInstance, _stackHost, _stackAddress;
protected int _stackAppId = -1, _stackPort = -1;
protected InetSocketAddress _remoteAddress, _localAddress;
public AbstractMuxConnection setStackInfo (int stackAppId, String stackAppName, String stackInstance, String stackHost){
_stackAppId = stackAppId;
_stackAppName = stackAppName;
_stackInstance = stackInstance;
_stackHost = stackHost;
return this;
}
public AbstractMuxConnection setAddresses (InetSocketAddress remoteAddress, InetSocketAddress localAddress){
_remoteAddress = remoteAddress;
_localAddress = localAddress;
_stackAddress = _remoteAddress.getAddress().getHostAddress();
_stackPort = _remoteAddress.getPort ();
return this;
}
public int getStackAppId() { return _stackAppId;}
public String getStackAppName() { return _stackAppName;}
public String getStackInstance() { return _stackInstance;}
public String getStackHost() { return _stackHost;}
public String getStackAddress() { return _stackAddress;}
public int getStackPort() {return _stackPort;}
public InetSocketAddress getRemoteAddress() { return _remoteAddress;}
public InetSocketAddress getLocalAddress() {return _localAddress;}
public SocketManager getSocketManager() { return _socketManager;}
public void setTimeoutManager(TimeoutManager manager) { _timeoutManager = manager;}
public TimeoutManager getTimeoutManager() { return _timeoutManager;}
public MuxHandler getMuxHandler() { return _handler;}
public void setAttributes(Object[] attributes) {_attributes = attributes;}
public Object[] getAttributes() {return _attributes;}
public void attach(Object attachment) {_attachment = attachment;}
public <T> T attachment() { return (T) _attachment;}
@Override
public String toString() {
StringBuilder buff = new StringBuilder();
buff.append("MuxConnection [id=");
buff.append(_id);
buff.append(", stackId=");
buff.append(_stackAppId);
buff.append(", stackName=");
buff.append(_stackAppName);
buff.append(", stackInstance=");
buff.append(_stackInstance);
buff.append(", stackHost=");
buff.append(_stackHost);
buff.append(", stackAddr=");
buff.append(_stackAddress);
buff.append(", stackPort=");
buff.append(_stackPort);
buff.append(']');
return buff.toString();
}
/************************* mux *************************/
@Override
public boolean sendMuxData(MuxHeader header, byte[] data, int off, int len, boolean copy) {
if (data == null || len == 0) return sendMuxData (header, null);
return sendMuxData (header, copy, ByteBuffer.wrap (data, off, len));
}
@Override
public boolean sendMuxData(MuxHeader header, ByteBuffer buf) {
boolean copy = (buf != null && buf.remaining () > 0);
return sendMuxData (header, copy, buf);
}
@Override
public boolean sendMuxStart() { return _open;}
@Override
public boolean sendMuxStop() { return _open;}
@Override
public boolean sendMuxData(MuxHeader header, boolean copy, ByteBuffer ... buf) { return _open;}
@Override
public boolean sendMuxIdentification(MuxIdentification id) { return _open;}
/************************* tcp *************************/
@Override
public boolean sendTcpSocketListen(long listenId, int localIP, int localPort, boolean secure) {
String ip = (localIP == 0) ? "0.0.0.0" : MuxUtils.getIPAsString(localIP);
return sendTcpSocketListen(listenId, ip, localPort, secure);
}
@Override
public boolean sendTcpSocketConnect(long connectionId, String remoteHost, int remotePort, int localIP,
int localPort, boolean secure) {
return sendTcpSocketConnect(connectionId, remoteHost, remotePort, MuxUtils.getIPAsString(localIP),
localPort, secure, null);
}
@Override
public boolean sendTcpSocketData(int sockId, byte[] data, int off, int len, boolean copy) {
if (len == 0 || data == null)
return _open;
return sendTcpSocketData(sockId, copy, ByteBuffer.wrap(data, off, len));
}
@Override
public boolean sendTcpSocketListen(long listenId, String localIP, int localPort, boolean secure) {return _open;}
@Override
public boolean sendTcpSocketConnect(long connectionId, String remoteHost, int remotePort, String localIP,
int localPort, boolean secure) {
return sendTcpSocketConnect (connectionId, remoteHost, remotePort, localIP, localPort, secure, null);
}
@Override
public boolean sendTcpSocketConnect(long connectionId, String remoteHost, int remotePort, String localIP,
int localPort, boolean secure, java.util.Map<String, String> params){ return _open;}
@Override
public boolean sendTcpSocketReset(int sockId) {return _open;}
@Override
public boolean sendTcpSocketClose(int sockId) {return _open;}
@Override
public boolean sendTcpSocketAbort(int sockId) {return _open;}
@Override
public boolean sendTcpSocketData(int sockId, boolean copy, ByteBuffer ... bufs) {return _open;}
@Override
public boolean sendTcpSocketParams(int sockId, java.util.Map<String, String> params){return _open;}
/************************* sctp *************************/
@Override
public boolean sendSctpSocketListen(long listenId, String[] localAddrs, int localPort, int maxOutStreams,
int maxInStreams, boolean secure) {return _open;}
@Override
public boolean sendSctpSocketConnect(long connectionId, String remoteHost, int remotePort,
String[] localAddrs, int localPort, int maxOutSreams, int maxInStreams, boolean secure) {
return sendSctpSocketConnect (connectionId, remoteHost, remotePort, localAddrs, localPort, maxOutSreams, maxInStreams, secure, null, null);
}
@Override
public boolean sendSctpSocketConnect(long connectionId, String remoteHost, int remotePort,
String[] localAddrs, int localPort, int maxOutSreams, int maxInStreams, boolean secure,
java.util.Map<SctpSocketOption, SctpSocketParam> sctpSocketOptions, java.util.Map<String, String> params) {return _open;}
@Override
public boolean sendSctpSocketData(int sockId, String addr, boolean unordered, boolean complete,
int ploadPID, int streamNumber, long timeToLive, boolean copy,
ByteBuffer ... data) {return _open;}
@Override
public boolean sendSctpSocketReset(int sockId) {return _open;}
@Override
public boolean sendSctpSocketClose(int sockId) {return _open;}
@Override
public boolean sendSctpSocketOptions(int sockId, java.util.Map<SctpSocketOption, SctpSocketParam> sctpSocketOptions){ return _open;}
@Override
public boolean sendSctpSocketParams(int sockId, java.util.Map<String, String> params){ return _open;}
/************************* udp *************************/
@Override
public boolean sendUdpSocketBind(long bindId, String localIP, int localPort, boolean shared) {return _open;}
@Override
public boolean sendUdpSocketClose(int sockId) {return _open;}
@Override
public boolean sendUdpSocketData(int sockId, String remoteIP, int remotePort, String virtualIP,
int virtualPort, boolean copy, ByteBuffer ... bufs) {return _open;}
@Override
public boolean sendUdpSocketBind(long bindId, int localIP, int localPort, boolean shared) {
return sendUdpSocketBind (bindId, MuxUtils.getIPAsString (localIP), localPort, shared);
}
@Override
public boolean sendUdpSocketData(int sockId, int remoteIP, int remotePort, int virtualIP, int virtualPort,
byte[] data, int off, int len, boolean copy) {
return sendUdpSocketData(sockId, MuxUtils.getIPAsString(remoteIP), remotePort,
MuxUtils.getIPAsString(virtualIP), virtualPort, data, off, len, copy);
}
@Override
public boolean sendUdpSocketData(int sockId, String remoteIP, int remotePort, String virtualIP,
int virtualPort, byte[] data, int off, int len, boolean copy) {
if (len == 0 || data == null)
return _open;
return sendUdpSocketData(sockId, remoteIP, remotePort, virtualIP, virtualPort, copy,
ByteBuffer.wrap(data, off, len));
}
@Override
public boolean sendUdpSocketData(int sockId, int remoteIP, int remotePort, int virtualIP, int virtualPort,
boolean copy, ByteBuffer ... bufs) {
return sendUdpSocketData(sockId, MuxUtils.getIPAsString(remoteIP), remotePort,
MuxUtils.getIPAsString(virtualIP), virtualPort, copy, bufs);
}
/************************* dns *************************/
@Override
public boolean sendDnsGetByAddr(long reqId, String addr) { throw new UnsupportedOperationException("method sendDnsGetByAddr() is not supported");}
@Override
public boolean sendDnsGetByName(long reqId, String name) { throw new UnsupportedOperationException("method sendDnsGetByName() is not supported");}
/************************* release *************************/
@Override
public boolean sendRelease(final long sessionId) { return _open;}
@Override
public boolean sendReleaseAck(long sessionId, boolean confirm) { return _open;}
/******************* read controls ************************/
@Override
public void disableRead(int sockId) {}
@Override
public void enableRead(int sockId) {}
@Override
public void setInputExecutor(Executor inputExecutor) {}
}
| 40.523952
| 150
| 0.713188
|
639ac96289e771640b480f64fd1455fdb5e09704
| 1,093
|
// Copyright 2016 Yahoo Inc.
// Licensed under the terms of the Apache 2.0 license.
// Please see LICENSE file in the project root for terms.
package com.yahoo.labs.yamall.ml;
/**
* Hinge loss.
*
* @author Francesco Orabona
* @version 1.0
*/
@SuppressWarnings("serial")
public class HingeLoss implements Loss {
public double lossValue(double pred, double label) {
return Math.max(1 - pred * label, 0);
}
public double negativeGradient(double pred, double label, double importance) {
if (1 - pred * label > 0)
return label;
else
return 0;
}
public double negativeGradientInvariant(double pred, double label, double importance, double h_normx) {
if (1 - pred * label > 0)
return label;
else
return 0;
}
public String toString() {
return "Hinge loss";
}
public double lossConstantBinaryLabels(double sPlus, double sMinus) {
double c = Math.signum(sPlus - sMinus);
return (sPlus * (1 - c) + sMinus * (1 + c)) / (sPlus + sMinus);
}
}
| 26.02381
| 107
| 0.613907
|
39a56fad663f2c9b5b3c9b4bc974caa417bdb0af
| 4,687
|
// Code generated by Wire protocol buffer compiler, do not edit.
// Source file: proto/Offers.proto
package com.google.play.proto;
import com.squareup.wire.Message;
import com.squareup.wire.ProtoField;
import static com.squareup.wire.Message.Datatype.BOOL;
import static com.squareup.wire.Message.Datatype.INT64;
public final class OwnershipInfo extends Message {
public static final Long DEFAULT_INITIATIONTIMESTAMPMSEC = 0L;
public static final Long DEFAULT_VALIDUNTILTIMESTAMPMSEC = 0L;
public static final Boolean DEFAULT_AUTORENEWING = false;
public static final Long DEFAULT_REFUNDTIMEOUTTIMESTAMPMSEC = 0L;
public static final Long DEFAULT_POSTDELIVERYREFUNDWINDOWMSEC = 0L;
@ProtoField(tag = 1, type = INT64)
public final Long initiationTimestampMsec;
@ProtoField(tag = 2, type = INT64)
public final Long validUntilTimestampMsec;
@ProtoField(tag = 3, type = BOOL)
public final Boolean autoRenewing;
@ProtoField(tag = 4, type = INT64)
public final Long refundTimeoutTimestampMsec;
@ProtoField(tag = 5, type = INT64)
public final Long postDeliveryRefundWindowMsec;
public OwnershipInfo(Long initiationTimestampMsec, Long validUntilTimestampMsec, Boolean autoRenewing, Long refundTimeoutTimestampMsec, Long postDeliveryRefundWindowMsec) {
this.initiationTimestampMsec = initiationTimestampMsec;
this.validUntilTimestampMsec = validUntilTimestampMsec;
this.autoRenewing = autoRenewing;
this.refundTimeoutTimestampMsec = refundTimeoutTimestampMsec;
this.postDeliveryRefundWindowMsec = postDeliveryRefundWindowMsec;
}
private OwnershipInfo(Builder builder) {
this(builder.initiationTimestampMsec, builder.validUntilTimestampMsec, builder.autoRenewing, builder.refundTimeoutTimestampMsec, builder.postDeliveryRefundWindowMsec);
setBuilder(builder);
}
@Override
public boolean equals(Object other) {
if (other == this) return true;
if (!(other instanceof OwnershipInfo)) return false;
OwnershipInfo o = (OwnershipInfo) other;
return equals(initiationTimestampMsec, o.initiationTimestampMsec)
&& equals(validUntilTimestampMsec, o.validUntilTimestampMsec)
&& equals(autoRenewing, o.autoRenewing)
&& equals(refundTimeoutTimestampMsec, o.refundTimeoutTimestampMsec)
&& equals(postDeliveryRefundWindowMsec, o.postDeliveryRefundWindowMsec);
}
@Override
public int hashCode() {
int result = hashCode;
if (result == 0) {
result = initiationTimestampMsec != null ? initiationTimestampMsec.hashCode() : 0;
result = result * 37 + (validUntilTimestampMsec != null ? validUntilTimestampMsec.hashCode() : 0);
result = result * 37 + (autoRenewing != null ? autoRenewing.hashCode() : 0);
result = result * 37 + (refundTimeoutTimestampMsec != null ? refundTimeoutTimestampMsec.hashCode() : 0);
result = result * 37 + (postDeliveryRefundWindowMsec != null ? postDeliveryRefundWindowMsec.hashCode() : 0);
hashCode = result;
}
return result;
}
public static final class Builder extends Message.Builder<OwnershipInfo> {
public Long initiationTimestampMsec;
public Long validUntilTimestampMsec;
public Boolean autoRenewing;
public Long refundTimeoutTimestampMsec;
public Long postDeliveryRefundWindowMsec;
public Builder() {
}
public Builder(OwnershipInfo message) {
super(message);
if (message == null) return;
this.initiationTimestampMsec = message.initiationTimestampMsec;
this.validUntilTimestampMsec = message.validUntilTimestampMsec;
this.autoRenewing = message.autoRenewing;
this.refundTimeoutTimestampMsec = message.refundTimeoutTimestampMsec;
this.postDeliveryRefundWindowMsec = message.postDeliveryRefundWindowMsec;
}
public Builder initiationTimestampMsec(Long initiationTimestampMsec) {
this.initiationTimestampMsec = initiationTimestampMsec;
return this;
}
public Builder validUntilTimestampMsec(Long validUntilTimestampMsec) {
this.validUntilTimestampMsec = validUntilTimestampMsec;
return this;
}
public Builder autoRenewing(Boolean autoRenewing) {
this.autoRenewing = autoRenewing;
return this;
}
public Builder refundTimeoutTimestampMsec(Long refundTimeoutTimestampMsec) {
this.refundTimeoutTimestampMsec = refundTimeoutTimestampMsec;
return this;
}
public Builder postDeliveryRefundWindowMsec(Long postDeliveryRefundWindowMsec) {
this.postDeliveryRefundWindowMsec = postDeliveryRefundWindowMsec;
return this;
}
@Override
public OwnershipInfo build() {
return new OwnershipInfo(this);
}
}
}
| 37.496
| 174
| 0.756561
|
6133ecc5a8abcd7978d34d4e2b6eb4a353e172d2
| 2,238
|
package com.github.sergueik.junitparams;
/**
* Copyright 2017-2018 Serguei Kouzmine
*/
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
/* Boilerplate code of JUnit Parameterized test class relying on
* properties injection
* based on https://github.com/junit-team/junit4/wiki/parameterized-tests
* @author: Serguei Kouzmine (kouzmine_serguei@yahoo.com)
*/
@RunWith(Parameterized.class)
public class StandardParamPropertiesTest extends DataTest {
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] { { 1.0, "junit", 204 },
{ 2.0, "testng", 51 }, { 3.0, "spock", 28 } });
}
@Parameter
// NOTE: @Parameter-annotated class property has to be public -
// if made
// protected double rowNum;
// java.lang.IllegalAccessException will be thrown in runtime
// Class org.junit.runners.parameterized.BlockJUnt4ClassRunnerWithParameters
// can not access a member of class
// com.github.serguei.initparams.ParameterizedPropertiesTest
// with modifiers "protected"
public double rowNum;
// NOTE: the first property annotation in the clss definition
// is value (0) by default
@Parameter(1)
public String keyword;
@Parameter(2)
public int count;
// NOTE: possible typo in annotation DSL (annotate multiple properties with
// the same index )
// @Parameter(1)
// protected Object foo;
// @Parameter(1)
// protected Object bar;
// will be only detected at execution time as
// java.lang.Exception: @Parameter(1) is used more than once (2).
// java.lang.Exception: @Parameter(2) is never used.
@Test
// NOTE: java.lang.Exception: Method test should have no parameters
// public void test(double rowNum, String keyword,
// double count) {
// java.lang.IllegalArgumentException: wrong number of arguments
public void parameterizedTest() {
try {
dataTest(keyword, count);
} catch (IllegalStateException e) {
System.err
.println(String.format("keyword: %s , count : %d ", keyword, count));
}
}
}
| 31.083333
| 77
| 0.735925
|
ee44a766569cebb349ec68ef3a74dc6a2e2cee40
| 1,956
|
package org.ovirt.engine.core.common.action;
import org.ovirt.engine.core.compat.Guid;
public class RemoveMemoryVolumesParameters extends ActionParametersBase {
/** comma-separated string of UUIDs representing the memory volumes */
private String memoryVolumes;
private Guid vmId;
/** In the general case, we remove the memory volumes only if there is only
* one snapshot in DB that uses it because we remove the memory before
* removing the snapshots from the DB. But in some cases we first remove
* the snapshot from the DB and only then remove its memory and in that
* case we should remove the memory only if no other snapshot uses it */
private boolean removeOnlyIfNotUsedAtAll;
private boolean forceRemove;
public RemoveMemoryVolumesParameters(String memoryVolumes, Guid vmId) {
this(memoryVolumes, vmId, false);
}
public RemoveMemoryVolumesParameters(String memoryVolumes, Guid vmId, boolean forceRemove) {
this.memoryVolumes = memoryVolumes;
this.vmId = vmId;
this.forceRemove = forceRemove;
}
public RemoveMemoryVolumesParameters() {
this.memoryVolumes = "";
this.vmId = Guid.Empty;
}
public String getMemoryVolumes() {
return memoryVolumes;
}
public void setMemoryVolumes(String memoryVolumes) {
this.memoryVolumes = memoryVolumes;
}
public Guid getVmId() {
return vmId;
}
public void setVmId(Guid vmId) {
this.vmId = vmId;
}
public boolean isRemoveOnlyIfNotUsedAtAll() {
return removeOnlyIfNotUsedAtAll;
}
public void setRemoveOnlyIfNotUsedAtAll(boolean removeOnlyIfNotUsedAtAll) {
this.removeOnlyIfNotUsedAtAll = removeOnlyIfNotUsedAtAll;
}
public boolean isForceRemove() {
return forceRemove;
}
public void setForceRemove(boolean forceRemove) {
this.forceRemove = forceRemove;
}
}
| 30.092308
| 96
| 0.697853
|
71045dcb1f24499a22f1206e8ded883364dc9fb3
| 3,001
|
package org.folio.search.service;
import static org.elasticsearch.search.sort.SortBuilders.fieldSort;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.folio.search.cql.CqlSearchQueryConverter;
import org.folio.search.exception.SearchServiceException;
import org.folio.search.model.service.CqlResourceIdsRequest;
import org.folio.search.repository.SearchRepository;
import org.folio.search.utils.SearchUtils;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class ResourceIdService {
private final ObjectMapper objectMapper;
private final SearchRepository searchRepository;
private final CqlSearchQueryConverter queryConverter;
/**
* Returns instance ids for passed cql query.
*
* @param request resource ids request as {@link CqlResourceIdsRequest} object
* @param outputStream output stream where json will be written in.
*/
public void streamResourceIds(CqlResourceIdsRequest request, OutputStream outputStream) {
try (var json = objectMapper.createGenerator(outputStream)) {
json.writeStartObject();
json.writeFieldName("ids");
json.writeStartArray();
var totalRecordsCounter = new AtomicInteger();
streamResourceIds(request, ids -> {
totalRecordsCounter.addAndGet(ids.size());
writeRecordIdsToOutputStream(ids, json);
});
json.writeEndArray();
json.writeNumberField("totalRecords", totalRecordsCounter.get());
json.writeEndObject();
json.flush();
} catch (IOException e) {
throw new SearchServiceException(
String.format("Failed to write data into json [reason: %s]", e.getMessage()), e);
}
}
private void streamResourceIds(CqlResourceIdsRequest request, Consumer<List<String>> idsConsumer) {
var resource = request.getResource();
var searchSource = queryConverter.convert(request.getQuery(), resource)
.size(SearchUtils.MAX_ELASTICSEARCH_QUERY_SIZE)
.fetchSource(new String[] {request.getSourceFieldPath()}, null)
.sort(List.of(fieldSort("_doc")));
searchRepository.streamResourceIds(request, searchSource, idsConsumer);
}
private static void writeRecordIdsToOutputStream(List<String> recordIds, JsonGenerator json) {
if (CollectionUtils.isEmpty(recordIds)) {
return;
}
try {
for (var recordId : recordIds) {
json.writeStartObject();
json.writeStringField("id", recordId);
json.writeEndObject();
}
json.flush();
} catch (IOException e) {
throw new SearchServiceException(
String.format("Failed to write to id value into json stream [reason: %s]", e.getMessage()), e);
}
}
}
| 35.305882
| 103
| 0.739087
|
a8a3dd9267890c2d91584d7f6c856b3d7d583c99
| 587
|
package com.solvd.carinaproject.gui.pages;
import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;
import com.qaprosoft.carina.core.gui.AbstractPage;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.FindBy;
public class FacebookLoginErrorPage extends AbstractPage {
@FindBy(xpath = "//*[@id='email_container']/div[2]")
private ExtendedWebElement errorText;
public FacebookLoginErrorPage(WebDriver driver) {
super(driver);
}
public String getErrorMessage() {
return errorText.getText();
}
}
| 27.952381
| 83
| 0.752981
|
dfdd3c7050ddd84776e36e9772d396d14b080fc6
| 94
|
package cat.nyaa.nyaacore.cmdreceiver;
class NotPlayerException extends RuntimeException {
}
| 18.8
| 51
| 0.840426
|
52cd71abca5c83d4aebe61658b728441c658c34f
| 3,395
|
package com.moelyon.learning.algorithm;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.FutureTask;
public class ParallelQuickSort {
private static class QuickSort extends ForkJoinTask<Object>{
private final int[] arr;
private final int left;
private final int right;
public QuickSort(int[] arr, int left, int right) {
this.arr = arr;
this.left = left;
this.right = right;
}
@Override
public Object getRawResult() {
return null;
}
@Override
protected void setRawResult(Object value) {
}
private static final int CUT_OFF = 100;
@Override
protected boolean exec() {
if(left>= right){
return true;
}
if(right-left<=CUT_OFF){
InsertSort.insertSort(arr,left,right+1);
return true;
}
int pivot =partition(arr,left,right);
ForkJoinTask<Object> task1 = new QuickSort(arr,left,pivot-1);
ForkJoinTask<Object> task2 = new QuickSort(arr,pivot+1,right);
task1.fork();
task2.fork();
task1.join();
task2.join();
return true;
}
private static int partition(int[] arr, int left, int right){
int temp = arr[left];
int i = left;
while (left<right){
while(right>left && arr[right]>=temp){
right--;
}
while(left<right && arr[left]<=temp){
left++;
}
if(left<right){
swap(arr,left,right);
}
}
arr[i] = arr[left];
arr[left] = temp;
return left;
}
private static void swap(int[] arr,int i,int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j]=temp;
}
}
private static final long numOfArray = 500000;
public static void main(String[] args) {
ForkJoinPool pool = new ForkJoinPool();
int[] ints = new Random().ints().limit(numOfArray).toArray();
long current = System.currentTimeMillis();
ForkJoinTask<Object> task = new QuickSort(ints,0,ints.length-1);
pool.execute(task);
task.join();
System.out.println(" fork join cost time is " + (System.currentTimeMillis()-current) +" ms");
boolean isvalid = true;
for(int i=0; i<ints.length-1; ++i){
if(ints[i]>ints[i+1]){
isvalid = false;
break;
}
}
System.out.println(isvalid);
pool.shutdown();
ints = new Random().ints().limit(numOfArray).toArray();
current = System.currentTimeMillis();
// com.moelyon.learning.algorithm.QuickSort.quickSort(ints);
Arrays.sort(ints);
System.out.println(" one thread cost time is " + (System.currentTimeMillis()-current) +" ms");
for(int i=0; i<ints.length-1; ++i){
if(ints[i]>ints[i+1]){
isvalid = false;
break;
}
}
System.out.println(isvalid);
}
}
| 27.379032
| 102
| 0.513108
|
a2c1d649731e0ab2ce7eefbff7369538b1ff23dc
| 1,529
|
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.authorize;
import org.dspace.content.DSpaceObject;
/**
* Exception indicating the current user of the context does not have permission
* to perform a particular action.
*
* @author David Stuve
* @version $Revision$
*/
public class AuthorizeException extends Exception
{
private int myaction; // action attempted, or -1
private DSpaceObject myobject; // object action attempted on or null
/**
* Create an empty authorize exception
*/
public AuthorizeException()
{
super();
myaction = -1;
myobject = null;
}
/**
* create an exception with only a message
*
* @param message
*/
public AuthorizeException(String message)
{
super(message);
myaction = -1;
myobject = null;
}
/**
* Create an authorize exception with a message
*
* @param message
* the message
*/
public AuthorizeException(String message, DSpaceObject o, int a)
{
super(message);
myobject = o;
myaction = a;
}
public int getAction()
{
return myaction;
}
public DSpaceObject getObject()
{
return myobject;
}
}
| 20.945205
| 81
| 0.580772
|
af674cedf98a0e01f8cfbbcfb4733c3d7cf3f7dd
| 362
|
package org.springframework.tutorial.tutorial1;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppContext {
@Bean
public HelloWorld helloworld() {
HelloWorld helloworld = new HelloWorld();
helloworld.setMessage("Hello Lihongjie");
return helloworld;
}
}
| 21.294118
| 60
| 0.79558
|
7c46a7de5438c4f80d6931ecb6ce6f9253d8b1c0
| 2,479
|
/*
* (C) Copyright IBM Corp. 2020.
*
* 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.ibm.watson.assistant.v1.model;
import com.ibm.cloud.sdk.core.service.model.GenericModel;
/**
* An object describing the role played by a system entity that is specifies the beginning or end of
* a range recognized in the user input. This property is included only if the new system entities
* are enabled for the workspace.
*/
public class RuntimeEntityRole extends GenericModel {
/** The relationship of the entity to the range. */
public interface Type {
/** date_from. */
String DATE_FROM = "date_from";
/** date_to. */
String DATE_TO = "date_to";
/** number_from. */
String NUMBER_FROM = "number_from";
/** number_to. */
String NUMBER_TO = "number_to";
/** time_from. */
String TIME_FROM = "time_from";
/** time_to. */
String TIME_TO = "time_to";
}
protected String type;
/** Builder. */
public static class Builder {
private String type;
private Builder(RuntimeEntityRole runtimeEntityRole) {
this.type = runtimeEntityRole.type;
}
/** Instantiates a new builder. */
public Builder() {}
/**
* Builds a RuntimeEntityRole.
*
* @return the new RuntimeEntityRole instance
*/
public RuntimeEntityRole build() {
return new RuntimeEntityRole(this);
}
/**
* Set the type.
*
* @param type the type
* @return the RuntimeEntityRole builder
*/
public Builder type(String type) {
this.type = type;
return this;
}
}
protected RuntimeEntityRole(Builder builder) {
type = builder.type;
}
/**
* New builder.
*
* @return a RuntimeEntityRole builder
*/
public Builder newBuilder() {
return new Builder(this);
}
/**
* Gets the type.
*
* <p>The relationship of the entity to the range.
*
* @return the type
*/
public String type() {
return type;
}
}
| 25.295918
| 118
| 0.657523
|
facb2561ffd1d909be91b0ca59a48a1c08d8e762
| 825
|
package org.asciidoctor.arquillian.api;
/**
* A marker class passed to the {@link org.jboss.arquillian.test.api.ArquillianResource} annotation
* to mark the {@link org.asciidoctor.Asciidoctor} instance as shared between multiple test methods.
*
* <p>Example for a field that is shared among multiple test methods</p>
* <pre><code>
* @ArquillianResource(Shared.class)
* private Asciidoctor sharedAsciidoctor;
* </code></pre>
*
* <p>Example for a parameter that is shared among multiple test methods</p>
* <pre><code>
* public void test(@ArquillianResource(Shared.class) Asciidoctor asciidoctor) {...}
* </code></pre>
*
* <p>Without using the {@code Shared} marker Asciidoctor instances are not shared and behave
* as if the {@link Unshared} marker is used.</p>
*/
public class Shared {
}
| 35.869565
| 100
| 0.713939
|
47dca2c53ec661d1bd474814193486994e37de56
| 1,354
|
package cn.edu.seu.leetcode.dp;
/**
* @author personajian
* question:求解最长公共子序列LCS
*/
public class Lcs {
/**
* 动态规划求解LCS
* @param x是一个字符串序列
* @param y是另一个字符串序列
* @param b是对应计算c时所选择的子问题最优解
* @param c是保存了x和y的LCS长度
*/
public static void lcsLength(char[] x,char[] y,int[][] b,int[][] c) {
int m=x.length;
int n=y.length;
for(int i=1;i<m;i++) c[i][0]=0;
for(int j=0;j<n;j++) c[0][j]=0;
for (int i = 1; i <=m; i++) {
for (int j = 1; j <= n; j++) {
if(x[i-1]==y[j-1]){//字符串下标从0开始
c[i][j]=c[i-1][j-1]+1;
b[i][j]=-2;
}else if(c[i-1][j]>=c[i][j-1]){
c[i][j]=c[i-1][j];
b[i][j]=1;
}else{
c[i][j]=c[i][j-1];
b[i][j]=-1;
}
}
}
}
/**
* 打印最长公共子序列
* @param b
* @param x
* @param i
* @param j
*/
public static void printLcs(int[][] b,char[] x,int i,int j) {
if(i==0||j==0) return;
if(b[i][j]==-2){
printLcs(b, x, i-1, j-1);
System.out.print(x[i-1]);//字符串下标从0开始
}else if(b[i][j]==1) printLcs(b, x, i-1, j);
else printLcs(b, x, i, j-1);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
char[] x={'A','B','C','B','D','A','B'};
char[] y={'B','D','C','A','B','A'};
int i=x.length;
int j=y.length;
int[][] b=new int[i+1][j+1];
int[][] c=new int[i+1][j+1];
lcsLength(x, y, b, c);
printLcs(b, x, i, j);
}
}
| 20.208955
| 70
| 0.49483
|
00313b615257b01f8da7fc2638b59859b4285822
| 3,707
|
package ru.nsu.fit.mobdev.presentation.storagedemo;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import ru.nsu.fit.mobdev.data.storagedemo.IStorageDemoGateway;
import ru.nsu.fit.mobdev.data.storagedemo.StorageDemoFilesDataSource;
import ru.nsu.fit.mobdev.data.storagedemo.StorageDemoGateway;
import ru.nsu.fit.mobdev.data.storagedemo.StorageDemoSQLiteDataSource;
import ru.nsu.fit.mobdev.data.storagedemo.StorageDemoSharedPreferencesDataSource;
import ru.nsu.fit.mobdev.domain.storagedemo.StorageDemoDeleteUseCase;
import ru.nsu.fit.mobdev.domain.storagedemo.StorageDemoLoadUseCase;
import ru.nsu.fit.mobdev.domain.storagedemo.StorageDemoSaveUseCase;
import ru.nsu.fit.mobdev.model.Article;
import ru.nsu.fit.mobdev.R;
public final class StorageDemoActivity extends AppCompatActivity implements StorageDemoModuleContract.View {
public static Intent getIntent(final Context context) {
return new Intent(context, StorageDemoActivity.class);
}
private TextView amountTextView;
private TextView lastElementTextView;
private EditText titleEditText;
private StorageDemoModuleContract.Presenter presenter;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_storage_demo);
amountTextView = findViewById(R.id.amount_textView);
lastElementTextView = findViewById(R.id.last_element_textView);
titleEditText = findViewById(R.id.title_editText);
final Button saveButton = findViewById(R.id.save_button);
final Button loadButton = findViewById(R.id.load_button);
final Button deleteButton = findViewById(R.id.delete_button);
saveButton.setOnClickListener(view -> presenter.didTapSaveButton(titleEditText.getText().toString()));
loadButton.setOnClickListener(view -> presenter.didTapLoadButton());
deleteButton.setOnClickListener(view -> presenter.didTapDeleteButton());
// Временно (!) инициализируем здесь весь стек в Activity.
final IStorageDemoGateway storageDemoGateway = new StorageDemoGateway(
new StorageDemoFilesDataSource(getApplicationContext()),
new StorageDemoSharedPreferencesDataSource(getApplicationContext()),
new StorageDemoSQLiteDataSource()
);
final StorageDemoSaveUseCase saveUseCase = new StorageDemoSaveUseCase(storageDemoGateway);
final StorageDemoLoadUseCase loadUseCase = new StorageDemoLoadUseCase(storageDemoGateway);
final StorageDemoDeleteUseCase deleteUseCase = new StorageDemoDeleteUseCase(storageDemoGateway);
StorageDemoModuleContract.Presenter presenter = new StorageDemoPresenter(this, saveUseCase, loadUseCase, deleteUseCase);
}
@Override
public void linkPresenter(final StorageDemoModuleContract.Presenter presenter) {
this.presenter = presenter;
}
@Override
public void displayArticles(final List<Article> articles) {
amountTextView.setText("Общее количество записей: " + articles.size());
if (articles.size() > 0) {
lastElementTextView.setText("Последний элемент: " + articles.get(articles.size() - 1).getTitle());
} else {
lastElementTextView.setText("%нет_значения%");
}
}
@Override
public void displayMessage(final String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
| 43.104651
| 128
| 0.757756
|
5eeff294270395122ff5a1eb93d1f3395900e0c7
| 32,197
|
package android.support.v4.app;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.support.v4.content.Loader.OnLoadCanceledListener;
import android.support.v4.content.Loader.OnLoadCompleteListener;
import android.support.v4.util.DebugUtils;
import android.support.v4.util.SparseArrayCompat;
import android.util.Log;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.lang.reflect.Modifier;
/* compiled from: LoaderManager */
class LoaderManagerImpl extends LoaderManager {
static boolean DEBUG = false;
static final String TAG = "LoaderManager";
boolean mCreatingLoader;
FragmentHostCallback mHost;
final SparseArrayCompat<LoaderInfo> mInactiveLoaders = new SparseArrayCompat();
final SparseArrayCompat<LoaderInfo> mLoaders = new SparseArrayCompat();
boolean mRetaining;
boolean mRetainingStarted;
boolean mStarted;
final String mWho;
/* compiled from: LoaderManager */
final class LoaderInfo implements OnLoadCompleteListener<Object>, OnLoadCanceledListener<Object> {
final Bundle mArgs;
LoaderCallbacks<Object> mCallbacks;
Object mData;
boolean mDeliveredData;
boolean mDestroyed;
boolean mHaveData;
final int mId;
boolean mListenerRegistered;
Loader<Object> mLoader;
LoaderInfo mPendingLoader;
boolean mReportNextStart;
boolean mRetaining;
boolean mRetainingStarted;
boolean mStarted;
public LoaderInfo(int i, Bundle bundle, LoaderCallbacks<Object> loaderCallbacks) {
this.mId = i;
this.mArgs = bundle;
this.mCallbacks = loaderCallbacks;
}
void start() {
boolean z = true;
if (this.mRetaining && this.mRetainingStarted) {
this.mStarted = z;
} else if (!this.mStarted) {
this.mStarted = z;
if (LoaderManagerImpl.DEBUG) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(" Starting: ");
stringBuilder.append(this);
Log.v("LoaderManager", stringBuilder.toString());
}
if (this.mLoader == null && this.mCallbacks != null) {
this.mLoader = this.mCallbacks.onCreateLoader(this.mId, this.mArgs);
}
if (this.mLoader != null) {
if (!this.mLoader.getClass().isMemberClass() || Modifier.isStatic(this.mLoader.getClass().getModifiers())) {
if (!this.mListenerRegistered) {
this.mLoader.registerListener(this.mId, this);
this.mLoader.registerOnLoadCanceledListener(this);
this.mListenerRegistered = z;
}
this.mLoader.startLoading();
} else {
StringBuilder stringBuilder2 = new StringBuilder();
stringBuilder2.append("Object returned from onCreateLoader must not be a non-static inner member class: ");
stringBuilder2.append(this.mLoader);
throw new IllegalArgumentException(stringBuilder2.toString());
}
}
}
}
void retain() {
if (LoaderManagerImpl.DEBUG) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(" Retaining: ");
stringBuilder.append(this);
Log.v("LoaderManager", stringBuilder.toString());
}
this.mRetaining = true;
this.mRetainingStarted = this.mStarted;
this.mStarted = false;
this.mCallbacks = null;
}
void finishRetain() {
if (this.mRetaining) {
if (LoaderManagerImpl.DEBUG) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(" Finished Retaining: ");
stringBuilder.append(this);
Log.v("LoaderManager", stringBuilder.toString());
}
this.mRetaining = false;
if (!(this.mStarted == this.mRetainingStarted || this.mStarted)) {
stop();
}
}
if (this.mStarted && this.mHaveData && !this.mReportNextStart) {
callOnLoadFinished(this.mLoader, this.mData);
}
}
void reportStart() {
if (this.mStarted && this.mReportNextStart) {
this.mReportNextStart = false;
if (this.mHaveData && !this.mRetaining) {
callOnLoadFinished(this.mLoader, this.mData);
}
}
}
void stop() {
if (LoaderManagerImpl.DEBUG) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(" Stopping: ");
stringBuilder.append(this);
Log.v("LoaderManager", stringBuilder.toString());
}
boolean z = false;
this.mStarted = z;
if (!this.mRetaining && this.mLoader != null && this.mListenerRegistered) {
this.mListenerRegistered = z;
this.mLoader.unregisterListener(this);
this.mLoader.unregisterOnLoadCanceledListener(this);
this.mLoader.stopLoading();
}
}
boolean cancel() {
if (LoaderManagerImpl.DEBUG) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(" Canceling: ");
stringBuilder.append(this);
Log.v("LoaderManager", stringBuilder.toString());
}
if (!this.mStarted || this.mLoader == null || !this.mListenerRegistered) {
return false;
}
boolean cancelLoad = this.mLoader.cancelLoad();
if (!cancelLoad) {
onLoadCanceled(this.mLoader);
}
return cancelLoad;
}
void destroy() {
String str;
if (LoaderManagerImpl.DEBUG) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(" Destroying: ");
stringBuilder.append(this);
Log.v("LoaderManager", stringBuilder.toString());
}
this.mDestroyed = true;
boolean z = this.mDeliveredData;
boolean z2 = false;
this.mDeliveredData = z2;
String str2 = null;
if (this.mCallbacks != null && this.mLoader != null && this.mHaveData && z) {
if (LoaderManagerImpl.DEBUG) {
StringBuilder stringBuilder2 = new StringBuilder();
stringBuilder2.append(" Resetting: ");
stringBuilder2.append(this);
Log.v("LoaderManager", stringBuilder2.toString());
}
if (LoaderManagerImpl.this.mHost != null) {
str = LoaderManagerImpl.this.mHost.mFragmentManager.mNoTransactionsBecause;
LoaderManagerImpl.this.mHost.mFragmentManager.mNoTransactionsBecause = "onLoaderReset";
} else {
str = str2;
}
try {
this.mCallbacks.onLoaderReset(this.mLoader);
} finally {
if (LoaderManagerImpl.this.mHost != null) {
LoaderManagerImpl.this.mHost.mFragmentManager.mNoTransactionsBecause = str;
}
}
}
this.mCallbacks = str2;
this.mData = str2;
this.mHaveData = z2;
if (this.mLoader != null) {
if (this.mListenerRegistered) {
this.mListenerRegistered = z2;
this.mLoader.unregisterListener(this);
this.mLoader.unregisterOnLoadCanceledListener(this);
}
this.mLoader.reset();
}
if (this.mPendingLoader != null) {
this.mPendingLoader.destroy();
}
}
public void onLoadCanceled(Loader<Object> loader) {
if (LoaderManagerImpl.DEBUG) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("onLoadCanceled: ");
stringBuilder.append(this);
Log.v("LoaderManager", stringBuilder.toString());
}
if (this.mDestroyed) {
if (LoaderManagerImpl.DEBUG) {
Log.v("LoaderManager", " Ignoring load canceled -- destroyed");
}
} else if (LoaderManagerImpl.this.mLoaders.get(this.mId) != this) {
if (LoaderManagerImpl.DEBUG) {
Log.v("LoaderManager", " Ignoring load canceled -- not active");
}
} else {
LoaderInfo loaderInfo = this.mPendingLoader;
if (loaderInfo != null) {
if (LoaderManagerImpl.DEBUG) {
StringBuilder stringBuilder2 = new StringBuilder();
stringBuilder2.append(" Switching to pending loader: ");
stringBuilder2.append(loaderInfo);
Log.v("LoaderManager", stringBuilder2.toString());
}
LoaderInfo loaderInfo2 = null;
this.mPendingLoader = loaderInfo2;
LoaderManagerImpl.this.mLoaders.put(this.mId, loaderInfo2);
destroy();
LoaderManagerImpl.this.installLoader(loaderInfo);
}
}
}
public void onLoadComplete(Loader<Object> loader, Object obj) {
if (LoaderManagerImpl.DEBUG) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("onLoadComplete: ");
stringBuilder.append(this);
Log.v("LoaderManager", stringBuilder.toString());
}
if (this.mDestroyed) {
if (LoaderManagerImpl.DEBUG) {
Log.v("LoaderManager", " Ignoring load complete -- destroyed");
}
} else if (LoaderManagerImpl.this.mLoaders.get(this.mId) != this) {
if (LoaderManagerImpl.DEBUG) {
Log.v("LoaderManager", " Ignoring load complete -- not active");
}
} else {
LoaderInfo loaderInfo = this.mPendingLoader;
LoaderInfo loaderInfo2;
if (loaderInfo != null) {
if (LoaderManagerImpl.DEBUG) {
StringBuilder stringBuilder2 = new StringBuilder();
stringBuilder2.append(" Switching to pending loader: ");
stringBuilder2.append(loaderInfo);
Log.v("LoaderManager", stringBuilder2.toString());
}
loaderInfo2 = null;
this.mPendingLoader = loaderInfo2;
LoaderManagerImpl.this.mLoaders.put(this.mId, loaderInfo2);
destroy();
LoaderManagerImpl.this.installLoader(loaderInfo);
return;
}
if (!(this.mData == obj && this.mHaveData)) {
this.mData = obj;
this.mHaveData = true;
if (this.mStarted) {
callOnLoadFinished(loader, obj);
}
}
loaderInfo2 = (LoaderInfo) LoaderManagerImpl.this.mInactiveLoaders.get(this.mId);
if (!(loaderInfo2 == null || loaderInfo2 == this)) {
loaderInfo2.mDeliveredData = false;
loaderInfo2.destroy();
LoaderManagerImpl.this.mInactiveLoaders.remove(this.mId);
}
if (!(LoaderManagerImpl.this.mHost == null || LoaderManagerImpl.this.hasRunningLoaders())) {
LoaderManagerImpl.this.mHost.mFragmentManager.startPendingDeferredFragments();
}
}
}
void callOnLoadFinished(Loader<Object> loader, Object obj) {
if (this.mCallbacks != null) {
String str = null;
if (LoaderManagerImpl.this.mHost != null) {
str = LoaderManagerImpl.this.mHost.mFragmentManager.mNoTransactionsBecause;
LoaderManagerImpl.this.mHost.mFragmentManager.mNoTransactionsBecause = "onLoadFinished";
}
try {
if (LoaderManagerImpl.DEBUG) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(" onLoadFinished in ");
stringBuilder.append(loader);
stringBuilder.append(": ");
stringBuilder.append(loader.dataToString(obj));
Log.v("LoaderManager", stringBuilder.toString());
}
this.mCallbacks.onLoadFinished(loader, obj);
this.mDeliveredData = true;
} finally {
if (LoaderManagerImpl.this.mHost != null) {
LoaderManagerImpl.this.mHost.mFragmentManager.mNoTransactionsBecause = str;
}
}
}
}
public String toString() {
StringBuilder stringBuilder = new StringBuilder(64);
stringBuilder.append("LoaderInfo{");
stringBuilder.append(Integer.toHexString(System.identityHashCode(this)));
stringBuilder.append(" #");
stringBuilder.append(this.mId);
stringBuilder.append(" : ");
DebugUtils.buildShortClassTag(this.mLoader, stringBuilder);
stringBuilder.append("}}");
return stringBuilder.toString();
}
public void dump(String str, FileDescriptor fileDescriptor, PrintWriter printWriter, String[] strArr) {
StringBuilder stringBuilder;
printWriter.print(str);
printWriter.print("mId=");
printWriter.print(this.mId);
printWriter.print(" mArgs=");
printWriter.println(this.mArgs);
printWriter.print(str);
printWriter.print("mCallbacks=");
printWriter.println(this.mCallbacks);
printWriter.print(str);
printWriter.print("mLoader=");
printWriter.println(this.mLoader);
if (this.mLoader != null) {
Loader loader = this.mLoader;
stringBuilder = new StringBuilder();
stringBuilder.append(str);
stringBuilder.append(" ");
loader.dump(stringBuilder.toString(), fileDescriptor, printWriter, strArr);
}
if (this.mHaveData || this.mDeliveredData) {
printWriter.print(str);
printWriter.print("mHaveData=");
printWriter.print(this.mHaveData);
printWriter.print(" mDeliveredData=");
printWriter.println(this.mDeliveredData);
printWriter.print(str);
printWriter.print("mData=");
printWriter.println(this.mData);
}
printWriter.print(str);
printWriter.print("mStarted=");
printWriter.print(this.mStarted);
printWriter.print(" mReportNextStart=");
printWriter.print(this.mReportNextStart);
printWriter.print(" mDestroyed=");
printWriter.println(this.mDestroyed);
printWriter.print(str);
printWriter.print("mRetaining=");
printWriter.print(this.mRetaining);
printWriter.print(" mRetainingStarted=");
printWriter.print(this.mRetainingStarted);
printWriter.print(" mListenerRegistered=");
printWriter.println(this.mListenerRegistered);
if (this.mPendingLoader != null) {
printWriter.print(str);
printWriter.println("Pending Loader ");
printWriter.print(this.mPendingLoader);
printWriter.println(":");
LoaderInfo loaderInfo = this.mPendingLoader;
stringBuilder = new StringBuilder();
stringBuilder.append(str);
stringBuilder.append(" ");
loaderInfo.dump(stringBuilder.toString(), fileDescriptor, printWriter, strArr);
}
}
}
LoaderManagerImpl(String str, FragmentHostCallback fragmentHostCallback, boolean z) {
this.mWho = str;
this.mHost = fragmentHostCallback;
this.mStarted = z;
}
void updateHostController(FragmentHostCallback fragmentHostCallback) {
this.mHost = fragmentHostCallback;
}
private LoaderInfo createLoader(int i, Bundle bundle, LoaderCallbacks<Object> loaderCallbacks) {
LoaderInfo loaderInfo = new LoaderInfo(i, bundle, loaderCallbacks);
loaderInfo.mLoader = loaderCallbacks.onCreateLoader(i, bundle);
return loaderInfo;
}
private LoaderInfo createAndInstallLoader(int i, Bundle bundle, LoaderCallbacks<Object> loaderCallbacks) {
boolean z = false;
try {
this.mCreatingLoader = true;
LoaderInfo createLoader = createLoader(i, bundle, loaderCallbacks);
installLoader(createLoader);
return createLoader;
} finally {
this.mCreatingLoader = z;
}
}
void installLoader(LoaderInfo loaderInfo) {
this.mLoaders.put(loaderInfo.mId, loaderInfo);
if (this.mStarted) {
loaderInfo.start();
}
}
public <D> Loader<D> initLoader(int i, Bundle bundle, LoaderCallbacks<D> loaderCallbacks) {
if (this.mCreatingLoader) {
throw new IllegalStateException("Called while creating a loader");
}
LoaderInfo loaderInfo = (LoaderInfo) this.mLoaders.get(i);
if (DEBUG) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("initLoader in ");
stringBuilder.append(this);
stringBuilder.append(": args=");
stringBuilder.append(bundle);
Log.v("LoaderManager", stringBuilder.toString());
}
StringBuilder stringBuilder2;
if (loaderInfo == null) {
loaderInfo = createAndInstallLoader(i, bundle, loaderCallbacks);
if (DEBUG) {
stringBuilder2 = new StringBuilder();
stringBuilder2.append(" Created new loader ");
stringBuilder2.append(loaderInfo);
Log.v("LoaderManager", stringBuilder2.toString());
}
} else {
if (DEBUG) {
stringBuilder2 = new StringBuilder();
stringBuilder2.append(" Re-using existing loader ");
stringBuilder2.append(loaderInfo);
Log.v("LoaderManager", stringBuilder2.toString());
}
loaderInfo.mCallbacks = loaderCallbacks;
}
if (loaderInfo.mHaveData && this.mStarted) {
loaderInfo.callOnLoadFinished(loaderInfo.mLoader, loaderInfo.mData);
}
return loaderInfo.mLoader;
}
public <D> Loader<D> restartLoader(int i, Bundle bundle, LoaderCallbacks<D> loaderCallbacks) {
if (this.mCreatingLoader) {
throw new IllegalStateException("Called while creating a loader");
}
StringBuilder stringBuilder;
LoaderInfo loaderInfo = (LoaderInfo) this.mLoaders.get(i);
if (DEBUG) {
stringBuilder = new StringBuilder();
stringBuilder.append("restartLoader in ");
stringBuilder.append(this);
stringBuilder.append(": args=");
stringBuilder.append(bundle);
Log.v("LoaderManager", stringBuilder.toString());
}
if (loaderInfo != null) {
LoaderInfo loaderInfo2 = (LoaderInfo) this.mInactiveLoaders.get(i);
StringBuilder stringBuilder2;
if (loaderInfo2 == null) {
if (DEBUG) {
stringBuilder = new StringBuilder();
stringBuilder.append(" Making last loader inactive: ");
stringBuilder.append(loaderInfo);
Log.v("LoaderManager", stringBuilder.toString());
}
loaderInfo.mLoader.abandon();
this.mInactiveLoaders.put(i, loaderInfo);
} else if (loaderInfo.mHaveData) {
if (DEBUG) {
stringBuilder2 = new StringBuilder();
stringBuilder2.append(" Removing last inactive loader: ");
stringBuilder2.append(loaderInfo);
Log.v("LoaderManager", stringBuilder2.toString());
}
loaderInfo2.mDeliveredData = false;
loaderInfo2.destroy();
loaderInfo.mLoader.abandon();
this.mInactiveLoaders.put(i, loaderInfo);
} else {
LoaderInfo loaderInfo3 = null;
if (loaderInfo.cancel()) {
if (DEBUG) {
Log.v("LoaderManager", " Current loader is running; configuring pending loader");
}
if (loaderInfo.mPendingLoader != null) {
if (DEBUG) {
stringBuilder2 = new StringBuilder();
stringBuilder2.append(" Removing pending loader: ");
stringBuilder2.append(loaderInfo.mPendingLoader);
Log.v("LoaderManager", stringBuilder2.toString());
}
loaderInfo.mPendingLoader.destroy();
loaderInfo.mPendingLoader = loaderInfo3;
}
if (DEBUG) {
Log.v("LoaderManager", " Enqueuing as new pending loader");
}
loaderInfo.mPendingLoader = createLoader(i, bundle, loaderCallbacks);
return loaderInfo.mPendingLoader.mLoader;
}
if (DEBUG) {
Log.v("LoaderManager", " Current loader is stopped; replacing");
}
this.mLoaders.put(i, loaderInfo3);
loaderInfo.destroy();
}
}
return createAndInstallLoader(i, bundle, loaderCallbacks).mLoader;
}
public void destroyLoader(int i) {
if (this.mCreatingLoader) {
throw new IllegalStateException("Called while creating a loader");
}
if (DEBUG) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("destroyLoader in ");
stringBuilder.append(this);
stringBuilder.append(" of ");
stringBuilder.append(i);
Log.v("LoaderManager", stringBuilder.toString());
}
int indexOfKey = this.mLoaders.indexOfKey(i);
if (indexOfKey >= 0) {
LoaderInfo loaderInfo = (LoaderInfo) this.mLoaders.valueAt(indexOfKey);
this.mLoaders.removeAt(indexOfKey);
loaderInfo.destroy();
}
i = this.mInactiveLoaders.indexOfKey(i);
if (i >= 0) {
LoaderInfo loaderInfo2 = (LoaderInfo) this.mInactiveLoaders.valueAt(i);
this.mInactiveLoaders.removeAt(i);
loaderInfo2.destroy();
}
if (this.mHost != null && !hasRunningLoaders()) {
this.mHost.mFragmentManager.startPendingDeferredFragments();
}
}
public <D> Loader<D> getLoader(int i) {
if (this.mCreatingLoader) {
throw new IllegalStateException("Called while creating a loader");
}
LoaderInfo loaderInfo = (LoaderInfo) this.mLoaders.get(i);
if (loaderInfo == null) {
return null;
}
if (loaderInfo.mPendingLoader != null) {
return loaderInfo.mPendingLoader.mLoader;
}
return loaderInfo.mLoader;
}
void doStart() {
if (DEBUG) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Starting in ");
stringBuilder.append(this);
Log.v("LoaderManager", stringBuilder.toString());
}
if (this.mStarted) {
Throwable runtimeException = new RuntimeException("here");
runtimeException.fillInStackTrace();
StringBuilder stringBuilder2 = new StringBuilder();
stringBuilder2.append("Called doStart when already started: ");
stringBuilder2.append(this);
Log.w("LoaderManager", stringBuilder2.toString(), runtimeException);
return;
}
boolean z = true;
this.mStarted = z;
for (int size = this.mLoaders.size() - z; size >= 0; size--) {
((LoaderInfo) this.mLoaders.valueAt(size)).start();
}
}
void doStop() {
if (DEBUG) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Stopping in ");
stringBuilder.append(this);
Log.v("LoaderManager", stringBuilder.toString());
}
if (this.mStarted) {
for (int size = this.mLoaders.size() - 1; size >= 0; size--) {
((LoaderInfo) this.mLoaders.valueAt(size)).stop();
}
this.mStarted = false;
return;
}
Throwable runtimeException = new RuntimeException("here");
runtimeException.fillInStackTrace();
StringBuilder stringBuilder2 = new StringBuilder();
stringBuilder2.append("Called doStop when not started: ");
stringBuilder2.append(this);
Log.w("LoaderManager", stringBuilder2.toString(), runtimeException);
}
void doRetain() {
if (DEBUG) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Retaining in ");
stringBuilder.append(this);
Log.v("LoaderManager", stringBuilder.toString());
}
if (this.mStarted) {
boolean z = true;
this.mRetaining = z;
this.mStarted = false;
for (int size = this.mLoaders.size() - z; size >= 0; size--) {
((LoaderInfo) this.mLoaders.valueAt(size)).retain();
}
return;
}
Throwable runtimeException = new RuntimeException("here");
runtimeException.fillInStackTrace();
StringBuilder stringBuilder2 = new StringBuilder();
stringBuilder2.append("Called doRetain when not started: ");
stringBuilder2.append(this);
Log.w("LoaderManager", stringBuilder2.toString(), runtimeException);
}
void finishRetain() {
if (this.mRetaining) {
if (DEBUG) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Finished Retaining in ");
stringBuilder.append(this);
Log.v("LoaderManager", stringBuilder.toString());
}
this.mRetaining = false;
for (int size = this.mLoaders.size() - 1; size >= 0; size--) {
((LoaderInfo) this.mLoaders.valueAt(size)).finishRetain();
}
}
}
void doReportNextStart() {
boolean z = true;
for (int size = this.mLoaders.size() - z; size >= 0; size--) {
((LoaderInfo) this.mLoaders.valueAt(size)).mReportNextStart = z;
}
}
void doReportStart() {
for (int size = this.mLoaders.size() - 1; size >= 0; size--) {
((LoaderInfo) this.mLoaders.valueAt(size)).reportStart();
}
}
void doDestroy() {
StringBuilder stringBuilder;
int size;
if (!this.mRetaining) {
if (DEBUG) {
stringBuilder = new StringBuilder();
stringBuilder.append("Destroying Active in ");
stringBuilder.append(this);
Log.v("LoaderManager", stringBuilder.toString());
}
for (size = this.mLoaders.size() - 1; size >= 0; size--) {
((LoaderInfo) this.mLoaders.valueAt(size)).destroy();
}
this.mLoaders.clear();
}
if (DEBUG) {
stringBuilder = new StringBuilder();
stringBuilder.append("Destroying Inactive in ");
stringBuilder.append(this);
Log.v("LoaderManager", stringBuilder.toString());
}
for (size = this.mInactiveLoaders.size() - 1; size >= 0; size--) {
((LoaderInfo) this.mInactiveLoaders.valueAt(size)).destroy();
}
this.mInactiveLoaders.clear();
this.mHost = null;
}
public String toString() {
StringBuilder stringBuilder = new StringBuilder(128);
stringBuilder.append("LoaderManager{");
stringBuilder.append(Integer.toHexString(System.identityHashCode(this)));
stringBuilder.append(" in ");
DebugUtils.buildShortClassTag(this.mHost, stringBuilder);
stringBuilder.append("}}");
return stringBuilder.toString();
}
public void dump(String str, FileDescriptor fileDescriptor, PrintWriter printWriter, String[] strArr) {
StringBuilder stringBuilder;
String stringBuilder2;
int i = 0;
if (this.mLoaders.size() > 0) {
printWriter.print(str);
printWriter.println("Active Loaders:");
stringBuilder = new StringBuilder();
stringBuilder.append(str);
stringBuilder.append(" ");
stringBuilder2 = stringBuilder.toString();
for (int i2 = i; i2 < this.mLoaders.size(); i2++) {
LoaderInfo loaderInfo = (LoaderInfo) this.mLoaders.valueAt(i2);
printWriter.print(str);
printWriter.print(" #");
printWriter.print(this.mLoaders.keyAt(i2));
printWriter.print(": ");
printWriter.println(loaderInfo.toString());
loaderInfo.dump(stringBuilder2, fileDescriptor, printWriter, strArr);
}
}
if (this.mInactiveLoaders.size() > 0) {
printWriter.print(str);
printWriter.println("Inactive Loaders:");
stringBuilder = new StringBuilder();
stringBuilder.append(str);
stringBuilder.append(" ");
stringBuilder2 = stringBuilder.toString();
while (i < this.mInactiveLoaders.size()) {
LoaderInfo loaderInfo2 = (LoaderInfo) this.mInactiveLoaders.valueAt(i);
printWriter.print(str);
printWriter.print(" #");
printWriter.print(this.mInactiveLoaders.keyAt(i));
printWriter.print(": ");
printWriter.println(loaderInfo2.toString());
loaderInfo2.dump(stringBuilder2, fileDescriptor, printWriter, strArr);
i++;
}
}
}
public boolean hasRunningLoaders() {
int size = this.mLoaders.size();
int i = 0;
int i2 = i;
boolean z = i2;
while (i2 < size) {
LoaderInfo loaderInfo = (LoaderInfo) this.mLoaders.valueAt(i2);
int i3 = (!loaderInfo.mStarted || loaderInfo.mDeliveredData) ? i : 1;
z |= i3;
i2++;
}
return z;
}
}
| 42.253281
| 131
| 0.546293
|
6c287c7a2114d451a85998268f9b4d74937e3d73
| 21,704
|
package uk.co.plogic.gwt.lib.ui.layout;
import java.util.ArrayList;
import java.util.logging.Logger;
import uk.co.plogic.gwt.lib.map.GoogleMapAdapter;
import uk.co.plogic.gwt.lib.widget.mapControl.MapControl;
import uk.co.plogic.gwt.lib.widget.mapControl.MapControlPanel;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.ProvidesResize;
import com.google.gwt.user.client.ui.ResizeLayoutPanel;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.maps.gwt.client.GoogleMap;
import com.google.maps.gwt.client.LatLng;
import com.google.maps.gwt.client.GoogleMap.IdleHandler;
/**
*
* A layout controller to programatically adjust to mobile, fullscreen, iframe,
* named div and full page layouts.
*
* The 3 ways for this Layout are desktop, mobile landscape and mobile portrait.
* The info panel is on the left for desktop+landscape but at the bottom for
* portrait.
*
* There are four parts-
* - infoPanel - Adjustable side panel
* - header - HTML - hides when in iframe or fullscreen
* - footer - HTML
* - map - requires a Google map
*
* @author si
*
*/
public class ResponsivePlusLayout implements ProvidesResize {
Logger logger = Logger.getLogger("ResponsivePlusLayout");
DockLayoutPanel layoutPanel;
RootLayoutPanel rootPanel;
int windowWidth = -1;
int windowHeight = -1;
HTML header;
HTML footer;
ResizeLayoutPanel infoPanel; // outside container - can hold just one widget
FlowPanel infoContent; // inside container, holds controls and InfoPanelContent
HorizontalPanel iconControls;
CarouselBasedInfoPanel infoPanelContent;
int defaultInfoPanelSize;
int currentInfoPanelSize;
int previousInfoPanelSize;
ResponsiveLayoutImageResource images;
// panel content
FlowPanel folderTab; // controls when info panel is visible
FlowPanel mapPanel;
FlowPanel mapContainer; // this' element is given to GoogleMap.create(...)
MapControlPanel mapExtraControlsPanel;
GoogleMap map;
GoogleMapAdapter mapAdapter;
boolean mapReady = false;
boolean resizeLocked = false;
Image expandOpen; // arrows on folderTab when in mobile mode
Image expandClose;
Timer expandArrowsTimer;
final static int expandArrowsTimerDuration = 3000;
String responsiveMode = "unknown"; // 'mobile_landscape', 'mobile_portrait'
// and 'full_version'.
// A String instead of an enum as it makes
// for a better relationship with
// user defined variable (responsive_mode) used by
// ResponsiveJso.
ArrayList<ResponsiveElement> responsiveElements = new ArrayList<ResponsiveElement>();
// @see addResponsiveElement()
final int PANEL_RESIZE_PIXELS = 150; // size of jump when click the resize arrows
final int HEADER_HEIGHT_PIXELS = 50;
final int FOOTER_HEIGHT_PIXELS = 30;
final double INFO_PANEL_WINDOW_PORTION = 0.5;
final int MOBILE_THRESHOLD_PIXELS = 620;
class ResponsiveElement {
String target_element_id;
String responsive_mode;
String add_class;
String remove_class;
}
public ResponsivePlusLayout() {
rootPanel = RootLayoutPanel.get();
images = GWT.create(ResponsiveLayoutImageResource.class);
mapPanel = new FlowPanel();
mapPanel.getElement().setId("map_panel");
mapPanel.setStyleName("map_canvas");
mapContainer = new FlowPanel();
mapContainer.getElement().setId("map_container");
mapContainer.setStyleName("map_canvas");
mapPanel.add(mapContainer);
final ResponsivePlusLayout me = this;
Window.addResizeHandler(new ResizeHandler() {
Timer resizeTimer = new Timer() {
@Override
public void run() {
me.onResize();
}
};
@Override
public void onResize(ResizeEvent event) {
resizeTimer.cancel();
resizeTimer.schedule(200);
}
});
expandArrowsTimer = new Timer() {
@Override
public void run() {
showHideExpandArrows(false);
}
};
}
public FlowPanel getMapContainerPanel() {
return mapContainer;
}
public void setHtml(String headerHtml, String footerHtml, String infoPanelHtml) {
header = new HTML(SafeHtmlUtils.fromTrustedString(headerHtml));
header.setStyleName("header");
footer = new HTML(SafeHtmlUtils.fromTrustedString(footerHtml));
footer.setStyleName("footer");
infoPanel = new ResizeLayoutPanel();
infoContent = new FlowPanel();
infoPanel.add(infoContent);
infoContent.setStyleName("info_panel");
infoPanelContent = new CarouselBasedInfoPanel(SafeHtmlUtils.fromTrustedString(infoPanelHtml));
ResponsiveSizing rs = new ResponsiveSizing(getInfoPanel());
rs.setPixelAdjustments(-30, -40);
//rs.setScaleFactor(1.00, 0.5);
infoPanelContent.setSuperCarouselResponsiveSizing(rs);
infoContent.add(infoPanelContent);
}
public void setMap(GoogleMapAdapter gma) {
mapAdapter = gma;
map = gma.getGoogleMap();
map.addIdleListenerOnce(new IdleHandler() {
@Override
public void handle() {
mapReady = true;
}
});
}
public void addMapControl(MapControl c) {
if( mapExtraControlsPanel == null ) {
// init
mapExtraControlsPanel = new MapControlPanel();
mapPanel.add(mapExtraControlsPanel);
}
mapExtraControlsPanel.addControl(c);
}
public MapControlPanel getMapControlPanel() {
return mapExtraControlsPanel;
}
/**
* wrap (replace) of an element which is within the info panel's
* HTML with the given widget.
*
* @param elementId
* @param w
* @return if successful
*/
public boolean updateInfoPanelElement(String elementId, Widget w, Boolean replace) {
return infoPanelContent.updateElement(elementId, w, replace);
}
/**
* When the responsive mode (i.e. 'mobile'; 'full_version' etc.) changes, update
* these HTML elements' style class.
*
* If an element's 'responsive_mode' matches the current mode then it's 'add_class'
* style will be added and the 'remove_class' style will be removed. And importantly,
* vice versa.
*
* @param target_element_id
* @param responsive_mode
* @param add_class
* @param remove_class
*/
// this should be done by looking at all widgets onResize and seeing if they have RequiresResize
//
// public void addResponsiveElement(String target_element_id, String responsive_mode,
// String add_class, String remove_class) {
//
// ResponsiveElement re = new ResponsiveElement();
// re.target_element_id = target_element_id;
// re.responsive_mode = responsive_mode;
// re.add_class= add_class;
// re.remove_class = remove_class;
// responsiveElements.add(re);
// }
public void closePanel() {
if( responsiveMode.startsWith("mobile") ) {
if( currentInfoPanelSize > defaultInfoPanelSize ) {
// is currently closed
currentInfoPanelSize = defaultInfoPanelSize;
} else {
currentInfoPanelSize = 0;
}
} else {
previousInfoPanelSize = currentInfoPanelSize;
currentInfoPanelSize = 0;
}
resizeInfoPanel();
}
public void openPanel() {
if( responsiveMode.startsWith("mobile") ) {
/*
* mobile has 3 sizes, fully open, default and closed
*/
if( currentInfoPanelSize < defaultInfoPanelSize ) {
// is currently closed
currentInfoPanelSize = defaultInfoPanelSize;
} else if( responsiveMode.equals("mobile_portrait") ) {
currentInfoPanelSize = windowHeight - 35;
} else {
currentInfoPanelSize = windowWidth - 35;
}
} else {
currentInfoPanelSize = previousInfoPanelSize;
}
resizeInfoPanel();
}
/**
* mobile mode uses folder tabs with up down arrows
* that only appear after first press of folder-tab icon
* @param b
*/
public void showHideExpandArrows(boolean visible) {
expandOpen.setVisible(visible && (currentInfoPanelSize<=defaultInfoPanelSize));
expandClose.setVisible(visible && (currentInfoPanelSize>0));
expandArrowsTimer.cancel();
expandArrowsTimer.schedule(expandArrowsTimerDuration);
}
private void resizeInfoPanel() {
LatLng centre = null;
if( map != null )
centre = map.getCenter();
layoutPanel.setWidgetSize(infoPanel, currentInfoPanelSize);
layoutPanel.animate(250);
final LatLng cc = centre;
Timer resizeTimer = new Timer() {
@Override
public void run() {
if( cc != null && mapReady ) {
map.triggerResize();
map.setCenter(cc);
}
infoPanelContent.onResize();
updateFolderTabs();
}
};
// only after panel has finished changing size
resizeTimer.schedule(250);
}
public void setResizeLocked(boolean resizeLocked) {
this.resizeLocked = resizeLocked;
}
private void layoutAsDesktop() {
// 40%
defaultInfoPanelSize = (int) (windowWidth * INFO_PANEL_WINDOW_PORTION);
currentInfoPanelSize = defaultInfoPanelSize;
int header_height;
if( isIframed() && ! isFullscreen() )
header_height = 0;
else
header_height = HEADER_HEIGHT_PIXELS;
layoutPanel.addNorth(header, header_height);
layoutPanel.addSouth(footer, FOOTER_HEIGHT_PIXELS);
layoutPanel.addWest(infoPanel, currentInfoPanelSize);
layoutPanel.add(mapPanel);
}
private void layoutAsMobile() {
// 40%
if( responsiveMode.equals("mobile_portrait") ) {
defaultInfoPanelSize = (int) (windowHeight * INFO_PANEL_WINDOW_PORTION);
currentInfoPanelSize = defaultInfoPanelSize;
layoutPanel.addSouth(infoPanel, currentInfoPanelSize);
} else {
// landscape
defaultInfoPanelSize = (int) (windowWidth * INFO_PANEL_WINDOW_PORTION);
currentInfoPanelSize = defaultInfoPanelSize;
layoutPanel.addWest(infoPanel, currentInfoPanelSize);
}
layoutPanel.add(mapPanel);
}
private void setupWindowVariables() {
// // mobile devices shouldn't trigger a resize when the on-screen keyboard
// // appears. Detect device rotate by checking _both_ width and height
// // change.
// int newWidth = Window.getClientWidth();
// int newHeight = Window.getClientHeight();
//
// // check current responsive mode. This could be updated below.
// if( responsiveMode.startsWith("mobile") ) {
// if( newWidth != windowWidth && newHeight != windowHeight ) {
// windowWidth = newWidth;
// windowHeight = newHeight;
// }
// } else {
// windowWidth = newWidth;
// windowHeight = newHeight;
// }
windowWidth = Window.getClientWidth();
windowHeight = Window.getClientHeight();
responsiveMode = responsiveMode();
}
/**
* claim root panel and attach basic layout
*/
public void initialBuild() {
setupWindowVariables();
build();
// reset mode so onResize() can correctly build the initial
// page in a way consistent with a move between responsive
// modes.
responsiveMode = "unknown";
// any HTML parsing here.
// build UI
infoPanelContent.onResize();
}
/**
* Called when responsive mode changes and when initial
* layout is created.
*
* On change in responsive mode it re-creates the layout panel.
*/
private void build() {
if(layoutPanel != null)
layoutPanel.removeFromParent();
rootPanel.clear();
layoutPanel = new DockLayoutPanel(Unit.PX);
if( responsiveMode.equals("full_version") )
layoutAsDesktop();
else layoutAsMobile();
rootPanel.add(layoutPanel);
}
/**
* to be called after window resizes and when layout is ready to display.
*
* It also hides/reveals responsive parts of the layout.
*
*/
public void onResize() {
if( resizeLocked ) {
logger.fine("Resize is locked");
return;
}
String lastResponsiveMode = responsiveMode;
setupWindowVariables();
logger.fine("onResize called: window is "+windowWidth+"x"+windowHeight);
rootPanel.onResize();
if( ! lastResponsiveMode.equals(responsiveMode) ) {
// responsive mode has changed so re-create layout
String msg = "Switching responsive mode from " + lastResponsiveMode;
msg += " to " + responsiveMode;
logger.fine(msg);
build();
setupControls();
infoPanelContent.setResponsiveMode(responsiveMode);
updateResponsiveElements();
// CSS
infoContent.removeStyleName("responsive_"+lastResponsiveMode);
infoContent.addStyleName("responsive_"+responsiveMode);
// the layout needs to have been drawn by the browser before
// any of the responsive elements can find their sizes.
final ResponsivePlusLayout me = this;
Timer resizeTimer = new Timer() {
@Override
public void run() {
me.onResize();
if( responsiveMode.startsWith("mobile") ) {
// this should make mobile devices hide the url bar
logger.finer("scrolling to 0");
Window.scrollTo(0, 1);
}
}
};
resizeTimer.schedule(100);
}
updateFolderTabs();
infoPanelContent.onResize();
if( mapReady )
map.triggerResize();
}
private void updateResponsiveElements() {
for( ResponsiveElement re : responsiveElements ) {
Element el = Document.get().getElementById(re.target_element_id);
if( el == null )
continue;
if( responsiveMode.equals(re.responsive_mode) ) {
if( re.remove_class != null )
el.removeClassName(re.remove_class);
if( re.add_class != null )
el.addClassName(re.add_class);
} else {
if( re.remove_class != null )
el.addClassName(re.remove_class);
if( re.add_class != null )
el.removeClassName(re.add_class);
}
}
}
private void setupFolderTabs() {
if( folderTab != null ) {
folderTab.clear();
folderTab.removeFromParent();
}
folderTab = new FlowPanel();
Image tabImage;
if (responsiveMode.equals("full_version")) {
tabImage = new Image(images.tab());
tabImage.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
openPanel();
}
});
folderTab.setVisible(false);
folderTab.setStyleName("folder_tab");
folderTab.add(tabImage);
} else {
// mobile modes
AbsolutePanel abPanel = new AbsolutePanel();
if(responsiveMode.equals("mobile_portrait")) {
tabImage = new Image(images.tab_horizontal());
abPanel.setPixelSize(tabImage.getWidth(), tabImage.getHeight());
abPanel.add(tabImage, 0, 0);
expandOpen = new Image(images.expand_arrow_horizontal_out());
expandOpen.setVisible(false);
abPanel.add(expandOpen, 20, 5);
expandClose = new Image(images.expand_arrow_horizontal_in());
expandClose.setVisible(false);
abPanel.add(expandClose, 70, 5);
folderTab.setStyleName("folder_tab_horizontal");
} else { // if(responsiveMode.equals("mobile_landscape")) {
tabImage = new Image(images.tab_vertical());
abPanel.setPixelSize(tabImage.getWidth(), tabImage.getHeight());
abPanel.add(tabImage, 0, 0);
expandOpen = new Image(images.expand_arrow_vertical_out());
expandOpen.setVisible(false);
abPanel.add(expandOpen, 5, 20);
expandClose = new Image(images.expand_arrow_vertical_in());
expandClose.setVisible(false);
abPanel.add(expandClose, 5, 70);
folderTab.setStyleName("folder_tab_vertical");
}
expandOpen.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
openPanel();
}
});
expandClose.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
closePanel();
}
});
tabImage.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
showHideExpandArrows(true);
}
});
folderTab.setVisible(true);
folderTab.add(abPanel);
}
mapPanel.add(folderTab);
}
private void updateFolderTabs() {
if (responsiveMode.equals("full_version")) {
int panelWidth = infoPanel.getOffsetWidth();
if( panelWidth < 22 )
folderTab.setVisible(true);
else
folderTab.setVisible(false);
} else {
showHideExpandArrows(true);
}
}
private void setupInfoPanelControls() {
iconControls = new HorizontalPanel();
iconControls.setStyleName("info_panel_controls");
infoContent.insert(iconControls, 0);
// general layout setup
Image shrink = new Image(images.leftArrow());
shrink.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
if( (currentInfoPanelSize-PANEL_RESIZE_PIXELS) < PANEL_RESIZE_PIXELS+50 )
closePanel();
else {
currentInfoPanelSize -= PANEL_RESIZE_PIXELS;
resizeInfoPanel();
}
}
});
iconControls.add(shrink);
Image enlarge = new Image(images.rightArrow());
enlarge.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
currentInfoPanelSize += PANEL_RESIZE_PIXELS;
resizeInfoPanel();
}
});
iconControls.add(enlarge);
Image close = new Image(images.cross());
close.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
closePanel();
}
});
iconControls.add(close);
}
/**
* this is called by initialBuild() and when the responsive mode
* changes. It adds controls to change the size of the info panel.
*/
private void setupControls() {
if (responsiveMode.equals("full_version")) {
setupInfoPanelControls();
iconControls.setVisible(true);
} else if (responsiveMode.startsWith("mobile_") ) {
if( iconControls != null ) {
iconControls.setVisible(false);
}
}
setupFolderTabs();
}
public String responsiveMode() {
String r;
if( isMobile() ) {
if( windowHeight > windowWidth )
r = "mobile_portrait";
else
r = "mobile_landscape";
} else
r = "full_version";
return r;
}
public boolean isMobile() {
return windowWidth <= MOBILE_THRESHOLD_PIXELS
|| windowHeight <= MOBILE_THRESHOLD_PIXELS;
}
public boolean isIframed() {
String baseUrl = getParentUrl();
String ourUrl = Window.Location.getHref();
return ! baseUrl.equals(ourUrl);
}
public Widget getInfoPanel() {
return (Widget) infoContent;
}
// public CarouselBasedInfoPanel getInfoPanelContent() {
// return infoPanelContent;
// }
/**
* browser has full screen mode - not tested
* @return
*/
public native boolean hasFullscreen() /*-{
var fullscreenEnabled = $doc.fullscreenEnabled
|| $doc.mozFullScreenEnabled || $doc.webkitFullscreenEnabled;
return fullscreenEnabled;
}-*/;
public native boolean isFullscreen() /*-{
var fullscreenElement;
var fullscreenEnabled = $doc.fullscreenEnabled
|| $doc.mozFullScreenEnabled || $doc.webkitFullscreenEnabled;
if (!fullscreenEnabled)
return false;
if ($doc.fullscreenEnabled)
fullscreenElement = $doc.fullscreenElement;
else if ($doc.mozFullScreenEnabled)
fullscreenElement = $doc.mozFullScreenElement;
else if ($doc.webkitFullscreenEnabled)
fullscreenElement = $doc.webkitFullscreenElement;
return fullscreenElement != null;
}-*/;
/**
*
* @return url of parent frame. This will only work (i.e. security exception)
* when the site fully occupies the browser or is an iframe from the same
* domain as the parent.
*/
private static final native String getParentUrl() /*-{
try {
return $wnd.parent.location.href;
} catch (e) {
return "";
}
}-*/;
}
| 29.569482
| 96
| 0.647024
|
e8a9f50558d674e90d288b1d7a9ac88e3eb1dd4b
| 709
|
package com.bwheeler8715.wordsearch;
import java.util.Arrays;
import java.util.List;
/**
* An immutable POJO representing a word-search.
*/
public class WordSearch {
private char[][] field;
private List<String> wordList;
public WordSearch(char[][] field, List<String> wordList) {
this.field = field;
this.wordList = wordList;
}
public char[][] getField() {
return this.field;
}
public List<String> getWordList() {
return this.wordList;
}
@Override
public String toString() {
return "WordSearch{" +
"field=" + Arrays.toString(this.field) +
", wordList=" + this.wordList +
'}';
}
}
| 20.257143
| 62
| 0.588152
|
126d4b9a8adbccdb7776a8c5b42408c54db73673
| 417
|
package mpei.bkm.model.query;
import mpei.bkm.model.commonfeatures.Selector;
public class AggregateGoal extends Goal {
public static enum Aggregate {SUM, AVG, MAX, MIN}
private Aggregate aggregate;
public AggregateGoal(Selector selector, Aggregate aggregate) {
super(selector);
this.aggregate = aggregate;
}
public Aggregate getAggregate() {
return aggregate;
}
}
| 21.947368
| 66
| 0.697842
|
4062c38bbe98b7aa1d63ac3fdd70c8270eb06a65
| 592
|
package com.apa70.idvalidation.entity;
import java.util.Map;
public class Distance {
private Map<Integer,Integer> positiveNumber;
private Map<Integer,Integer> minusSign;
public Map<Integer, Integer> getPositiveNumber() {
return positiveNumber;
}
public void setPositiveNumber(Map<Integer, Integer> positiveNumber) {
this.positiveNumber = positiveNumber;
}
public Map<Integer, Integer> getMinusSign() {
return minusSign;
}
public void setMinusSign(Map<Integer, Integer> minusSign) {
this.minusSign = minusSign;
}
}
| 23.68
| 73
| 0.692568
|
e311734ced4bc1c9149f492a5fa3be2003ffc2c5
| 9,435
|
package com.pg85.otg;
import com.pg85.otg.common.LocalBiome;
import com.pg85.otg.common.LocalWorld;
import com.pg85.otg.configuration.PluginConfig;
import com.pg85.otg.configuration.biome.settings.BiomeResourcesManager;
import com.pg85.otg.configuration.customobjects.CustomObjectResourcesManager;
import com.pg85.otg.configuration.dimensions.DimensionsConfig;
import com.pg85.otg.customobjects.CustomObject;
import com.pg85.otg.customobjects.CustomObjectManager;
import com.pg85.otg.events.EventHandler;
import com.pg85.otg.events.EventPriority;
import com.pg85.otg.generator.ChunkBuffer;
import com.pg85.otg.generator.biome.BiomeModeManager;
import com.pg85.otg.generator.resource.Resource;
import com.pg85.otg.logging.LogMarker;
import com.pg85.otg.util.ChunkCoordinate;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class OTG
{
// Used to determine if a new world is being created or if a world save already exists
// TODO: Make this prettier.
public static boolean IsNewWorldBeingCreated = false;
/**
* The engine that powers Open Terrain Generator.
*/
private static OTGEngine Engine;
private OTG()
{
// Forbidden to instantiate.
}
// Engine
/**
* Returns the engine, containing the API methods.
* <p>
* @return The engine
*/
public static OTGEngine getEngine()
{
return Engine;
}
/**
* Sets the engine and calls its {@link OTGEngine#onStart()
* onStart()} method.
* <p>
* @param engine The engine.
*/
public static void setEngine(OTGEngine engine)
{
if (OTG.Engine != null)
{
throw new IllegalStateException("Engine is already set.");
}
OTG.Engine = engine;
engine.onStart();
}
/**
* Nulls out static references to free up memory. Should be called on
* shutdown. Engine can be restarted after this.
*/
public static void stopEngine()
{
Engine.onShutdown();
Engine = null;
}
// Managers
/**
* Returns the biome managers. Register your own biome manager here.
* <p>
* @return The biome managers.
*/
public static BiomeModeManager getBiomeModeManager()
{
return Engine.getBiomeModeManager();
}
public static BiomeResourcesManager getBiomeResourcesManager()
{
return Engine.getBiomeResourceManager();
}
public static CustomObjectResourcesManager getCustomObjectResourcesManager()
{
return Engine.getCustomObjectResourcesManager();
}
public static CustomObjectManager getCustomObjectManager()
{
return Engine.getCustomObjectManager();
}
// Plugin
public static PluginConfig getPluginConfig()
{
return Engine.getPluginConfig();
}
// Dimensions config
/**
* A config for each dimension of the currently active world
*/
public static DimensionsConfig getDimensionsConfig()
{
return Engine.getDimensionsConfig();
}
public static void setDimensionsConfig(DimensionsConfig dimensionsConfig)
{
Engine.setDimensionsConfig(dimensionsConfig);
}
// Biomes
// For bukkit plugin developers, do not remove. See: https://github.com/MCTCP/TerrainControl/wiki/Developer-page
/*
* Convienence method to quickly get the biome name at the given
* coordinates. Will return null if the world isn't loaded by OTG
* <p>
* @param worldName The world name.
* @param x The block x in the world.
* @param z The block z in the world.
* @return The biome name, or null if the world isn't managed by Terrain
* Control.
*/
public static String getBiomeName(String worldName, int x, int z)
{
LocalWorld world = getWorld(worldName);
if (world == null)
{
// World isn't loaded by OTG
return null;
}
return world.getSavedBiome(x, z).getName();
}
public static LocalBiome getBiomeByOTGId(int id)
{
ArrayList<LocalWorld> worlds = getAllWorlds();
if(worlds != null)
{
for(LocalWorld world : worlds)
{
LocalBiome biome = world.getBiomeByOTGIdOrNull(id);
if(biome != null)
{
return biome;
}
}
}
return null;
}
public static LocalBiome getBiome(String name, String worldName)
{
ArrayList<LocalWorld> worlds = getAllWorlds();
if(worlds != null)
{
for(LocalWorld world : worlds)
{
if(world.getName().toLowerCase().equals(worldName.toLowerCase()))
{
LocalBiome biome = world.getBiomeByNameOrNull(name);
if(biome != null)
{
return biome;
}
}
}
}
return null;
}
// Worlds
public static LocalWorld getWorld(String name)
{
return Engine.getWorld(name);
}
public static LocalWorld getUnloadedWorld(String name)
{
return Engine.getUnloadedWorld(name);
}
public static ArrayList<LocalWorld> getAllWorlds()
{
return Engine.getAllWorlds();
}
// Events
/**
* @see OTGEngine#registerEventHandler(EventHandler)
*/
public static void registerEventHandler(EventHandler handler)
{
Engine.registerEventHandler(handler);
}
/**
* @see OTGEngine#registerEventHandler(EventHandler,
* EventPriority)
*/
public static void registerEventHandler(EventHandler handler, EventPriority priority)
{
Engine.registerEventHandler(handler, priority);
}
public static boolean fireReplaceBiomeBlocksEvent(int x, int z, ChunkBuffer chunkBuffer, LocalWorld localWorld)
{
return Engine.fireReplaceBiomeBlocksEvent(x, z, chunkBuffer, localWorld);
}
/**
* @see OTGEngine#fireCanCustomObjectSpawnEvent(CustomObject,
* LocalWorld, int, int, int)
*/
public static boolean fireCanCustomObjectSpawnEvent(CustomObject object, LocalWorld world, int x, int y, int z)
{
return Engine.fireCanCustomObjectSpawnEvent(object, world, x, y, z);
}
/**
* @see OTGEngine#firePopulationEndEvent(LocalWorld, Random,
* boolean, ChunkCoordinate)
*/
public static void firePopulationEndEvent(LocalWorld world, Random random, boolean villageInChunk, ChunkCoordinate chunkCoord)
{
Engine.firePopulationEndEvent(world, random, villageInChunk, chunkCoord);
}
/**
* @see OTGEngine#firePopulationStartEvent(LocalWorld, Random,
* boolean, ChunkCoordinate)
*/
public static void firePopulationStartEvent(LocalWorld world, Random random, boolean villageInChunk, ChunkCoordinate chunkCoord)
{
Engine.firePopulationStartEvent(world, random, villageInChunk, chunkCoord);
}
/**
* @see OTGEngine#fireResourceProcessEvent(Resource,
* LocalWorld, Random, boolean, int, int)
*/
public static boolean fireResourceProcessEvent(Resource resource, LocalWorld world, Random random, boolean villageInChunk, int chunkX, int chunkZ)
{
return Engine.fireResourceProcessEvent(resource, world, random, villageInChunk, chunkX, chunkZ);
}
// Logging
/**
* Logs the messages with the given importance. Message will be
* prefixed with [OpenTerrainGenerator], so don't do that yourself.
* <p>
* @param messages The messages to log.
* @param level The severity of the message
*/
public static void log(LogMarker level, List<String> messages)
{
Engine.getLogger().log(level, messages);
}
/**
* Logs a format string message with the given importance. Message will
* be prefixed with [OpenTerrainGenerator], so don't do that yourself.
* <p>
* @param message The messages to log formatted similar to Logger.log()
* with the same args.
* @param level The severity of the message
* @param params The parameters belonging to {0...} in the message
* string
*/
public static void log(LogMarker level, String message, Object... params)
{
Engine.getLogger().log(level, message, params);
}
/**
* Prints the stackTrace of the provided Throwable object
* <p>
* @param level The log level to log this stack trace at
* @param e The Throwable object to obtain stack trace information from
*/
public static void printStackTrace(LogMarker level, Throwable e)
{
printStackTrace(level, e, Integer.MAX_VALUE);
}
/**
* Prints the stackTrace of the provided Throwable object to a certain
* depth
* <p>
* @param level The log level to log this stack trace at
* @param e The Throwable object to obtain stack trace information
* from
* @param maxDepth The max number of trace elements to print
*/
public static void printStackTrace(LogMarker level, Throwable e, int maxDepth)
{
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
e.printStackTrace(printWriter);
Engine.getLogger().log(level, stringWriter.toString());
}
}
| 29.210526
| 150
| 0.652252
|
8f8212d29cab00dc9e714c62ceca075b123d6bb8
| 2,346
|
/* Copyright (C) 2018 Chris Deter 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 de.mach.tools.neodesigner.inex.nexport.pdf;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javafx.application.HostServices;
import de.mach.tools.neodesigner.core.datamodel.Table;
public interface ModelPrinter {
/** erstellt das Indexverzeichnis.
*
* @throws IOException Fehler bei der Verarbeitung
* @throws InterruptedException Fehler bei der Verarbeitung */
void erstelleIndex() throws IOException, InterruptedException;
/** erstellt das PDF. */
void erstellePdf();
/** Kopiert die PDF vom Temp Order in das Zielverzeichnis, wenn nicht möglich gibt es die Temp Datei der PDF zurück
*
* @param output -> mpm.getPdfFile()
* @return die Zieldatei als File */
File kopierePdf(File output);
/** versucht ein PDF zu öffnen.
*
* @param hostServices notwendiger Parameter für das Öffnen der PDF */
void oeffnePdf(File output, HostServices hostServices);
/** Liest das Datenmodell ein und verarbeitet es im Template.
*
* @param lt das Datenmodell
* @param title Der Titel im PDF
* @param author Der Author des PDFs */
void verarbeiteTemplate(final List<Table> lt, final String title, final String author, Map<String, String> catTransl);
}
| 44.264151
| 120
| 0.757886
|
907f338e56b7b86ad693e02014b421f7b71dbc13
| 589
|
package com.eduwin.modals;
public class UserOpinionPollBean {
private long userId;
private String votedOption;
private String opinionFeedback;
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public String getVotedOption() {
return votedOption;
}
public void setVotedOption(String votedOption) {
this.votedOption = votedOption;
}
public String getOpinionFeedback() {
return opinionFeedback;
}
public void setOpinionFeedback(String opinionFeedback) {
this.opinionFeedback = opinionFeedback;
}
}
| 19.633333
| 57
| 0.748727
|
2b21a70f735e16be9d4154349cf0ab3faa4fc1f6
| 4,450
|
/**
* Licensed to the TomTom International B.V. under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. TomTom International B.V.
* 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.
**/
/**
* Copyright (C) 2009-12 TomTom International B.V.
*
* TomTom (Legal Department)
* Email: legal@tomtom.com
*
* TomTom (Technical contact)
* Email: openlr@tomtom.com
*
* Address: TomTom International B.V., Oosterdoksstraat 114, 1011DK Amsterdam,
* the Netherlands
*/
package openlr.otk.kml;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import de.micromata.opengis.kml.v_2_2_0.Document;
import de.micromata.opengis.kml.v_2_2_0.Folder;
import de.micromata.opengis.kml.v_2_2_0.Kml;
import de.micromata.opengis.kml.v_2_2_0.Style;
/**
* Bundles a KML output generation assembled from multiple content providers
*
* <p>
* OpenLR is a trade mark of TomTom International B.V.
* <p>
* email: software@openlr.org
*
* @author TomTom International B.V.
*/
public final class KmlOutput {
/**
* Instance of {@link de.micromata.opengis.kml.v_2_2_0.Document} used to
* generate the KML output file.
*/
private final Document kmlDocument;
/**
* The list of registered content providers
*/
private final List<ContentProvider<?>> contentProviders = new ArrayList<ContentProvider<?>>();
/**
* Instance of {@link de.micromata.opengis.kml.v_2_2_0.Kml} used to generate
* the KML output file.
*/
private final Kml kml;
/**
* The KML file to write the results to.
*/
private final File kmlFile;
/**
* Creates a new instance of this class.
*
* @param kFile
* the KML file to write the results to.
*/
public KmlOutput(final File kFile) {
kmlFile = kFile;
kml = new Kml();
kmlDocument = kml.createAndSetDocument();
kmlDocument.setOpen(true);
kmlDocument.withDescription("(C) 2009-11 TomTom International B.V.");
}
/**
* Adds the given style definitions to the context. Content providers can
* refer to these styles via their identifiers.
*
* @param styles
* The style definitions to add
*/
void addStyles(final Collection<Style> styles) {
for (Style style : styles) {
kmlDocument.addToStyleSelector(style);
}
}
/**
* Adds a folder to the KML output
*
* @param folder
* The folder to add
*/
void addFolder(final Folder folder) {
kmlDocument.getFeature().add(folder);
}
/**
* Registers a new content provider
*
* @param provider
* The content provider to add
*/
public void addContentProvider(final ContentProvider<?> provider) {
contentProviders.add(provider);
}
/**
* Writes the KML file to disk.
*
* @return true, if marshaling the KML file was successful
* @throws KmlGenerationException
* If an error occurred generation the KML from the data of one
* of the content providers
* @throws IOException
* If an error occurred writing the KML output to the specified
* file
*/
public boolean write() throws KmlGenerationException, IOException {
if (!kmlFile.exists()) {
kmlFile.createNewFile();
}
for (ContentProvider<?> contenProvider : contentProviders) {
contenProvider.addContent(this);
}
return kml.marshal(kmlFile);
}
}
| 29.470199
| 99
| 0.623371
|
936773cbabc476f30d6e36784975065906f70228
| 3,791
|
/*
* 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.syncope.console.wicket.markup.html.tree;
import javax.swing.tree.DefaultMutableTreeNode;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.authroles.authorization.strategies.role.metadata.MetaDataRoleAuthorizationStrategy;
import org.apache.wicket.event.Broadcast;
import org.apache.wicket.event.IEvent;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.html.tree.BaseTree;
import org.apache.wicket.markup.html.tree.LinkTree;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.syncope.client.to.RoleTO;
import org.syncope.console.commons.RoleTreeBuilder;
import org.syncope.console.commons.XMLRolesReader;
import org.syncope.console.pages.panels.RoleSummaryPanel.TreeNodeClickUpdate;
public class TreeRolePanel extends Panel {
private static final long serialVersionUID = 1762003213871836869L;
@SpringBean
private RoleTreeBuilder roleTreeBuilder;
@SpringBean
protected XMLRolesReader xmlRolesReader;
final WebMarkupContainer treeContainer;
private BaseTree tree;
public TreeRolePanel(final String id) {
super(id);
treeContainer = new WebMarkupContainer("treeContainer");
treeContainer.setOutputMarkupId(true);
add(treeContainer);
updateTree();
treeContainer.add(tree);
}
private void updateTree() {
tree = new LinkTree("treeTable", roleTreeBuilder.build()) {
private static final long serialVersionUID = -5514696922119256101L;
@Override
protected IModel getNodeTextModel(final IModel model) {
return new PropertyModel(model, "userObject.displayName");
}
@Override
protected void onNodeLinkClicked(final Object node,
final BaseTree baseTree, final AjaxRequestTarget target) {
DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) node;
RoleTO unitObject = (RoleTO) treeNode.getUserObject();
send(getPage(), Broadcast.BREADTH,
new TreeNodeClickUpdate(target, unitObject.getId()));
}
};
MetaDataRoleAuthorizationStrategy.authorize(
tree, ENABLE,
xmlRolesReader.getAllAllowedRoles("Roles", "read"));
tree.setOutputMarkupId(true);
tree.getTreeState().expandAll();
treeContainer.addOrReplace(tree);
}
@Override
public void onEvent(final IEvent<?> event) {
super.onEvent(event);
if (event.getPayload() instanceof TreeNodeClickUpdate) {
final TreeNodeClickUpdate update =
(TreeNodeClickUpdate) event.getPayload();
updateTree();
update.getTarget().add(treeContainer);
}
}
}
| 33.548673
| 108
| 0.705091
|
062ad67ab62bb96845e95fca35cf5876ffb85a31
| 1,050
|
package game.components;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.utils.AnimationController;
import game.GameWorld;
import game.entities.Entity;
public class AnimatedModelComponent extends ModelComponent {
public AnimatedModelComponent(String name, Entity owner) {
super(name, owner);
}
public AnimatedModelComponent(String name, Entity owner, Model model) {
super(name, owner, model);
}
public AnimatedModelComponent(String name, Entity owner, Model model, ColorAttribute environmentLight) {
super(name, owner, model, environmentLight);
}
@Override
public void SetModel(Model model)
{
super.SetModel(model);
_controller = new AnimationController(_modelInstance);
}
public AnimationController GetAnimationController()
{
return _controller;
}
protected AnimationController _controller;
@Override
public void update(GameWorld world) {
super.update(world);
_controller.update(world.GetDeltaTime());
}
}
| 23.863636
| 105
| 0.781905
|
3ae51bea45befcb7dbb1b6193b1ce4f3e84ca604
| 761
|
package org.revolutio.jasb;
/**
* https://wiki.openoffice.org/wiki/Documentation/FAQ/Calc/Miscellaneous/What's_the_maximum_number_of_rows_and_cells_for_a_spreadsheet_file%3F
*
* @author Caio Santesso
*
*/
public enum FileFormat {
/**
* Max column name = IV.
*/
XLS(65_536, 256),
/**
* Max column name = XFD.
*/
XLSX(1_048_576, 16_384),
/**
*
*/
ODS_1_1(32_000, 256),
/**
*
*/
ODS_3_0(65_536, 256),
/**
*
*/
ODS(1_048_576, 1_024);
private final int maxRows;
private final int maxColumns;
private FileFormat(int maxRowIndex, int maxColumnIndex) {
this.maxRows = maxRowIndex;
this.maxColumns = maxColumnIndex;
}
public int maxRowIndex() {
return maxRows;
}
public int maxColumnIndex() {
return maxColumns;
}
}
| 16.191489
| 142
| 0.676741
|
e4d3c31e28599f8f95c7b1cf5e70df6ae7da359e
| 4,238
|
/*
* Copyright (c) 2008-2013 Haulmont. All rights reserved.
* Use is subject to license terms, see http://www.cuba-platform.com/license for details.
*/
package com.haulmont.cuba.security;
import com.haulmont.cuba.core.*;
import com.haulmont.cuba.security.entity.Group;
import com.haulmont.cuba.security.entity.GroupHierarchy;
import java.util.UUID;
public class GroupTest extends CubaTestCase
{
private UUID rootId, group1Id, group2Id, group3Id;
private void createGroups() {
Transaction tx = Locator.createTransaction();
try {
EntityManager em = PersistenceProvider.getEntityManager();
Group root = new Group();
rootId = root.getId();
root.setName("root");
em.persist(root);
tx.commitRetaining();
em = PersistenceProvider.getEntityManager();
root = em.find(Group.class, rootId);
Group group1 = new Group();
group1Id = group1.getId();
group1.setName("group1");
group1.setParent(root);
em.persist(group1);
tx.commitRetaining();
em = PersistenceProvider.getEntityManager();
group1 = em.find(Group.class, group1Id);
Group group2 = new Group();
group2Id = group2.getId();
group2.setName("group2");
group2.setParent(group1);
em.persist(group2);
tx.commitRetaining();
em = PersistenceProvider.getEntityManager();
root = em.find(Group.class, rootId);
Group group3 = new Group();
group3Id = group3.getId();
group3.setName("group3");
group3.setParent(root);
em.persist(group3);
tx.commit();
} finally {
tx.end();
}
}
public void testNew() {
createGroups();
Transaction tx = Locator.createTransaction();
try {
EntityManager em = PersistenceProvider.getEntityManager();
Group group2 = em.find(Group.class, group2Id);
for (GroupHierarchy hierarchy : group2.getHierarchyList()) {
assertEquals(group2, hierarchy.getGroup());
if (hierarchy.getLevel() == 0)
assertEquals(rootId, hierarchy.getParent().getId());
else if (hierarchy.getLevel() == 1)
assertEquals(group1Id, hierarchy.getParent().getId());
}
tx.commit();
} finally {
tx.end();
}
}
public void testUpdate() {
createGroups();
Transaction tx = Locator.createTransaction();
try {
EntityManager em = PersistenceProvider.getEntityManager();
Group group1 = em.find(Group.class, group1Id);
Group group3 = em.find(Group.class, group3Id);
group1.setParent(group3);
tx.commitRetaining();
em = PersistenceProvider.getEntityManager();
group1 = em.find(Group.class, group1Id);
for (GroupHierarchy hierarchy : group1.getHierarchyList()) {
assertEquals(group1, hierarchy.getGroup());
if (hierarchy.getLevel() == 0)
assertEquals(rootId, hierarchy.getParent().getId());
else if (hierarchy.getLevel() == 1)
assertEquals(group3Id, hierarchy.getParent().getId());
}
Group group2 = em.find(Group.class, group2Id);
for (GroupHierarchy hierarchy : group2.getHierarchyList()) {
assertEquals(group2, hierarchy.getGroup());
if (hierarchy.getLevel() == 0)
assertEquals(rootId, hierarchy.getParent().getId());
else if (hierarchy.getLevel() == 1)
assertEquals(group3Id, hierarchy.getParent().getId());
else if (hierarchy.getLevel() == 2)
assertEquals(group1Id, hierarchy.getParent().getId());
}
tx.commit();
} finally {
tx.end();
}
}
}
| 36.222222
| 90
| 0.540585
|
c1cce8278e597c7832baea89305c8a14ff793c81
| 2,795
|
package net.ossrs.yasea.demo.Activity.View;
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.LinearLayout;
/**
* Created by kang on 2017/6/8.
*/
public class MyScrollView extends LinearLayout {
public static boolean isFlowHead = false;
private float mLastY;
private boolean isIntercept = true;
private int headHeight = 300;
public MyScrollView(Context context) {
super(context);init();
}
public MyScrollView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);init();
}
public MyScrollView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);init();
}
private void init(){
isFlowHead = false;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
return isIntercept;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float currentY = event.getY();
float deltaY = 0;
int dis = getScrollY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mLastY = currentY;
break;
case MotionEvent.ACTION_MOVE:
deltaY = mLastY - currentY;
isFlowHead = false;
if (deltaY >= 0) {//上滑
// Log.e("","deltaY >= 0");
if (dis < headHeight && dis >= 0) {//不能超出屏幕
scrollBy(0, (int) deltaY);
} else if (dis >= headHeight) {
isFlowHead = true;
isIntercept = false;
} else if (dis >= 0) {
scrollBy(0, (int) deltaY);
} else {
scrollBy(0, 0);
}
} else {//下滑
// Log.e("","deltaY < 0");
if (dis <= 0 && deltaY <= 0) {
scrollBy(0, 0);
} else if (dis >= 0) {
scrollBy(0, (int) deltaY);
}
}
break;
case MotionEvent.ACTION_UP:
if (dis <= 0) {
// isIntercept = false;
setScrollY(0);//假如滑动超出屏幕,回归0点
}
break;
}
// Log.e("deltaY", "deltaY " + deltaY + " dis " + dis);
mLastY = currentY;
return true;//防止事件向下传递导致move不触发
}
public void setHeadHeight(int headHeight) {
this.headHeight = headHeight;
}
public void setIntercept(boolean intercept) {
isIntercept = intercept;
}
}
| 28.814433
| 90
| 0.503399
|
7986d6bdf67b86a10fad1505f80797c48d191f12
| 6,878
|
package com.jtdev.webcomicreader.views;
import android.app.Activity;
import android.content.Context;
import android.graphics.*;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.view.GestureDetectorCompat;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.animation.*;
import android.widget.ImageView;
import java.util.EnumSet;
/**
* Copyright (c) 2016 James Ridey <james@snoopyaustralia.com>
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* File created on 1/24/16
*/
public class ZoomableImageView extends ImageView
{
private static final float FLING_VELOCITY = 2400;
private ZoomableImageCallback callback = null;
private Bitmap previousBitmap;
private ZoomImageGestureDetector zoomImageGestureDetector;
private GestureDetectorCompat gestureDetector;
private ScaleGestureDetector scaleGestureDetector;
private boolean doubleTapped;
private float oldScale;
private float oldX;
private float oldY;
private float density;
public ZoomableImageView(Context context)
{
super(context);
if (context instanceof ZoomableImageCallback) initZoomableImage(context, callback);
else initZoomableImage(context, null);
}
public ZoomableImageView(Context context, AttributeSet attrs)
{
super(context, attrs);
if (context instanceof ZoomableImageCallback) initZoomableImage(context, callback);
else initZoomableImage(context, null);
}
public ZoomableImageView(Context context, AttributeSet attrs, int defStyleAttr)
{
super(context, attrs, defStyleAttr);
if (context instanceof ZoomableImageCallback) initZoomableImage(context, callback);
else initZoomableImage(context, null);
}
public ZoomableImageView(Context context, ZoomableImageCallback callback)
{
super(context);
initZoomableImage(context, callback);
}
private void initZoomableImage(Context context, ZoomableImageCallback callback)
{
this.callback = callback;
zoomImageGestureDetector = new ZoomImageGestureDetector();
gestureDetector = new GestureDetectorCompat(context, zoomImageGestureDetector);
scaleGestureDetector = new ScaleGestureDetector(context, zoomImageGestureDetector);
doubleTapped = false;
DisplayMetrics displayMetrics = new DisplayMetrics();
((Activity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
density = displayMetrics.density;
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
gestureDetector.onTouchEvent(event);
scaleGestureDetector.onTouchEvent(event);
boolean scaled = false;
float scale = 1.0f;
float x = 0.0f;
float y = 0.0f;
float zoomX = 0.0f;
float zoomY = 0.0f;
final Matrix imageMatrix = new Matrix(getImageMatrix());
float[] f = new float[9];
imageMatrix.getValues(f);
//Scale is the same for Y
final float currentScale = f[Matrix.MSCALE_X];
EnumSet<ZoomImageGestureDetector.Events> events = zoomImageGestureDetector.getCurrentEvents();
if (events.contains(ZoomImageGestureDetector.Events.FLING))
{
if (currentScale <= oldScale)
{
float flingVelocity = zoomImageGestureDetector.getFlingVelocity() / density;
//Log.d("debug", flingVelocity+"");
if (callback != null)
{
if (flingVelocity < -FLING_VELOCITY) callback.nextImage();
else if (flingVelocity > FLING_VELOCITY) callback.previousImage();
}
}
}
else if (events.contains(ZoomImageGestureDetector.Events.DOUBLE_TAP))
{
//scale = 2.0f;
//scaled = true;
final float doubleTapX = zoomImageGestureDetector.getDoubleTapX();
final float doubleTapY = zoomImageGestureDetector.getDoubleTapY();
final AccelerateDecelerateInterpolator accelerateDecelerateInterpolator = new AccelerateDecelerateInterpolator();
final long startTime = System.currentTimeMillis();
final long duration = 400;
final float target = doubleTapped ? 0.5f : 2.0f;
doubleTapped = !doubleTapped;
Runnable scaleUp = new Runnable()
{
float k0 = 1.0f;
float k1;
@Override
public void run()
{
float t = (float) (System.currentTimeMillis() - startTime) / duration;
t = t > 1.0f ? 1.0f : t;
float ratio = accelerateDecelerateInterpolator.getInterpolation(t);
k1 = (1+ratio*(target-1));
float tempScale = k1 / k0;
k0 = k1;
imageMatrix.postScale(tempScale, tempScale, doubleTapX, doubleTapY);
setImageMatrix(imageMatrix);
if (t < 1.0f) {
post(this);
}
}
};
post(scaleUp);
}
else if (events.contains(ZoomImageGestureDetector.Events.PINCHING))
{
scale = zoomImageGestureDetector.getScale();
scaled = true;
zoomX = zoomImageGestureDetector.getFocusX();
zoomY = zoomImageGestureDetector.getFocusY();
if (currentScale * scale < oldScale)
{
scaled = false;
imageMatrix.setScale(oldScale, oldScale);
imageMatrix.postTranslate(oldX, oldY);
}
}
if (events.contains(ZoomImageGestureDetector.Events.SCROLL))
{
x = -zoomImageGestureDetector.getScrollDistanceX();
y = -zoomImageGestureDetector.getScrollDistanceY();
}
if (scaled) imageMatrix.postScale(scale, scale, zoomX, zoomY);
if (x != 0 || y != 0) imageMatrix.postTranslate(x, y);
zoomImageGestureDetector.clearCurrentEvents();
setImageMatrix(imageMatrix);
return true;
}
private void centerToFit()
{
Log.d("debug", "Centering to fit");
//Borrowed from Android Source code ImageView: configureBounds
Matrix mDrawMatrix = new Matrix();
float scale;
float dx;
float dy;
int dwidth = getDrawable().getIntrinsicWidth();
int dheight = getDrawable().getIntrinsicHeight();
int vwidth = getWidth() - getPaddingLeft() - getPaddingRight();
int vheight = getHeight() - getPaddingTop() - getPaddingBottom();
if (dwidth <= vwidth && dheight <= vheight) {
//Modified original: scale = 1.0f;
scale = (float) vwidth / (float) dwidth * 0.75f;
} else {
scale = Math.min((float) vwidth / (float) dwidth,
(float) vheight / (float) dheight);
}
dx = Math.round((vwidth - dwidth * scale) * 0.5f);
dy = Math.round((vheight - dheight * scale) * 0.5f);
mDrawMatrix.setScale(scale, scale);
mDrawMatrix.postTranslate(dx, dy);
setImageMatrix(mDrawMatrix);
//New code
oldScale = scale;
oldX = dx;
oldY = dy;
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom)
{
super.onLayout(changed, left, top, right, bottom);
centerToFit();
}
@Override
public void setImageDrawable(Drawable drawable)
{
if (getDrawable() instanceof BitmapDrawable) previousBitmap = ((BitmapDrawable) getDrawable()).getBitmap();
super.setImageDrawable(drawable);
}
public Bitmap getPreviousBitmap()
{
return previousBitmap;
}
}
| 27.846154
| 116
| 0.733062
|
59057f73e9ead59c3a24bf56f879cca0d2c69622
| 1,105
|
package tk.taroninak.cafe.models;
import javax.persistence.*;
import javax.persistence.Table;
@Entity
@Table(name="orders")
public class Order {
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
@Column(name="id", unique=true)
private Long id;
@Column(name = "table_id")
private Long tableId;
@Enumerated(EnumType.STRING)
@Column(name = "status")
private OrderStatus status;
public enum OrderStatus {
OPEN, CLOSED, CANCELED;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getTableId() {
return tableId;
}
public void setTableId(Long tableId) {
this.tableId = tableId;
}
public OrderStatus getStatus() {
return status;
}
public void setStatus(OrderStatus status) {
this.status = status;
}
@Override
public String toString() {
return "Order{" +
"id=" + id +
", tableId=" + tableId +
", status=" + status +
'}';
}
}
| 19.051724
| 50
| 0.563801
|
c1a88b36580d6cef4965babade58389b35d02d5c
| 4,946
|
/*
* Copyright 2013-2016 must-be.org
*
* 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 consulo.restclient.ui;
import java.awt.BorderLayout;
import java.util.List;
import javax.annotation.Nonnull;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.ScrollPaneConstants;
import javax.annotation.Nullable;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.editor.impl.EditorFactoryImpl;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.PlainTextFileType;
import com.intellij.openapi.project.Project;
import com.intellij.ui.EditorTextField;
import com.intellij.ui.OnePixelSplitter;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.SideBorder;
import com.intellij.ui.ToolbarDecorator;
import com.intellij.ui.table.TableView;
import com.intellij.util.ui.ColumnInfo;
import com.intellij.util.ui.ElementProducer;
import com.intellij.util.ui.ListTableModel;
import consulo.restclient.HttpHeader;
/**
* @author VISTALL
* @since 27-Sep-16
*/
public class RestRequestOrResponsePanel extends JPanel
{
private EditorTextField myEditorTextField;
private ListTableModel<HttpHeader> myModel;
private JLabel myStatusPanel;
public RestRequestOrResponsePanel(@Nonnull Project project, boolean request)
{
super(new BorderLayout());
OnePixelSplitter splitter = new OnePixelSplitter();
splitter.setProportion(0.2f);
splitter.setSplitterProportionKey("RestClientPanel#request=" + request);
add(splitter, BorderLayout.CENTER);
if(!request)
{
myStatusPanel = new JLabel();
add(myStatusPanel, BorderLayout.SOUTH);
}
myModel = new ListTableModel<>(new ColumnInfo<HttpHeader, String>("Header Name")
{
@Override
public boolean isCellEditable(HttpHeader stringCouple)
{
return true;
}
@Override
public void setValue(HttpHeader stringCouple, String value)
{
stringCouple.setName(value);
}
@Nullable
@Override
public String valueOf(HttpHeader stringCouple)
{
return stringCouple.getName();
}
}, new ColumnInfo<HttpHeader, String>("Value")
{
@Override
public boolean isCellEditable(HttpHeader stringCouple)
{
return true;
}
@Override
public void setValue(HttpHeader httpHeader, String value)
{
httpHeader.setValue(value);
}
@Nullable
@Override
public String valueOf(HttpHeader stringCouple)
{
return stringCouple.getValue();
}
}
);
TableView<HttpHeader> headersView = new TableView<>(myModel);
JComponent tableView;
if(request)
{
headersView.setBorder(null);
ToolbarDecorator toolbarDecorator = ToolbarDecorator.createDecorator(headersView, new ElementProducer<HttpHeader>()
{
@Override
public HttpHeader createElement()
{
return new HttpHeader("", "");
}
@Override
public boolean canCreateElement()
{
return true;
}
}).disableUpDownActions();
tableView = toolbarDecorator.createPanel();
tableView.setBorder(null);
}
else
{
tableView = ScrollPaneFactory.createScrollPane(headersView, SideBorder.BOTTOM | SideBorder.LEFT);
}
splitter.setFirstComponent(tableView);
myEditorTextField = new EditorTextField(EditorFactory.getInstance().createDocument(""), project, PlainTextFileType.INSTANCE, !request, false)
{
@Override
protected EditorEx createEditor()
{
EditorEx editor = super.createEditor();
editor.getScrollPane().setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
return editor;
}
};
myEditorTextField.setBorder(null);
myEditorTextField.setFontInheritedFromLAF(false);
splitter.setSecondComponent(myEditorTextField);
}
public void setStatusLabel(String label)
{
myStatusPanel.setText(label);
}
public void setHeaders(List<HttpHeader> headers)
{
myModel.setItems(headers);
}
@Nonnull
public List<HttpHeader> getHeaders()
{
return myModel.getItems();
}
public String getText()
{
return myEditorTextField.getText();
}
public void setText(FileType fileType, String body)
{
EditorFactoryImpl editorFactory = (EditorFactoryImpl) EditorFactory.getInstance();
Document document = editorFactory.createDocument(body, true, true);
myEditorTextField.setNewDocumentAndFileType(fileType, document);
}
}
| 25.895288
| 143
| 0.754347
|
a914b2c34f06ccda2a185ab162bce42676fd1aae
| 3,239
|
/**
* www.bplow.com
*/
package com.bplow.deep.sysmng.service.impl;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.bplow.deep.base.pagination.Page;
import com.bplow.deep.sysmng.domain.SysPermission;
import com.bplow.deep.sysmng.domain.SysPermissionResource;
import com.bplow.deep.sysmng.mapper.SysPermissionMapper;
import com.bplow.deep.sysmng.mapper.SysPermissionResourceMapper;
import com.bplow.deep.sysmng.service.PermissionService;
/**
* @desc 权限管理
* @author wangxiaolei
* @date 2017年3月26日 下午3:11:37
*/
@Service
@Transactional
public class PermissionServiceImpl implements PermissionService{
Logger logger =LoggerFactory.getLogger(this.getClass());
@Autowired
SysPermissionMapper sysPermissionMapper;
@Autowired
SysPermissionResourceMapper sysPermissionResourceMapper;
@Override
public Page<SysPermission> queryPermissionForPage(SysPermission permission) {
Page<SysPermission> page = sysPermissionMapper.queryForPage(permission);
return page;
}
@Override
public SysPermission queryPermission(SysPermission permission) {
SysPermission sysPermission = sysPermissionMapper.selectByPrimaryKey(permission.getPermissionId());
return sysPermission;
}
@Override
public SysPermission addPermission(SysPermission permission) {
sysPermissionMapper.insert(permission);
return null;
}
@Override
public void deletePermission(SysPermission permission) {
sysPermissionMapper.delete(permission.getPermissionId());
}
@Override
public void updatePermission(SysPermission permission) {
sysPermissionMapper.update(permission);
}
@Override
public List<SysPermissionResource> queryPermRes(String permissionId) {
List<SysPermissionResource> permRes = sysPermissionResourceMapper.queryPermRes(permissionId);
return permRes;
}
@Override
public void addPermRes(String permissionId, String resourceId,String delPermIds) {
String[] permArray = permissionId.split(",");
String[] permIds = delPermIds.split(",");
List<String> permIdsList = Arrays.asList(permIds);
SysPermissionResource delPermRes = new SysPermissionResource();
delPermRes.setDelIds(permIdsList);
delPermRes.setResourceId(resourceId);
if(permIdsList.size()>0)sysPermissionResourceMapper.delete(delPermRes);
for(String permId : permArray){
if(StringUtils.isBlank(permId)){
continue;
}
SysPermissionResource permRes = new SysPermissionResource();
permRes.setPermissionId(permId);
permRes.setResourceId(resourceId);
permRes.setGmtModify(new Date());
sysPermissionResourceMapper.insert(permRes);
}
}
@Override
public void delPermRes(String permissionId, String resourceId) {
SysPermissionResource delPermRes = new SysPermissionResource();
sysPermissionResourceMapper.delete(delPermRes);
}
}
| 26.54918
| 102
| 0.756098
|
506f9576b75ce39a993565f9129bb1c490aae857
| 2,866
|
/*
* Licensed to the jNode FTN Platform Develpoment Team (jNode Team)
* under one or more contributor license agreements.
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
* The jNode Team 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 jnode.protocol.binkp;
import java.io.IOException;
import jnode.dto.Link;
import jnode.logger.Logger;
import jnode.main.MainHandler;
import jnode.main.threads.PollQueue;
import jnode.main.threads.ThreadPool;
import jnode.protocol.binkp.connector.BinkpAbstractConnector;
import jnode.protocol.binkp.connector.BinkpAsyncConnector;
public class BinkpAsyncClientPool implements Runnable {
private static final Logger logger = Logger
.getLogger(BinkpAsyncClientPool.class);
private static final String BINKD_CLIENT = "binkp.client";
@Override
public void run() {
if (!MainHandler.getCurrentInstance().getBooleanProperty(BINKD_CLIENT,
true)) {
return;
}
while (true) {
Link l = null;
synchronized (PollQueue.getSelf()) {
if (PollQueue.getSelf().isEmpty()) {
try {
PollQueue.getSelf().wait();
} catch (InterruptedException e) {
}
}
l = PollQueue.getSelf().getNext();
}
try {
BinkpAbstractConnector conn = null;
String pa = l.getProtocolAddress();
for (String key : BinkpConnectorRegistry.getSelf().getKeys()) {
if (l.getProtocolAddress().startsWith(key)) {
conn = createConnector(pa, key);
break;
}
}
if (conn == null) {
conn = new BinkpAsyncConnector(l.getProtocolAddress());
}
ThreadPool.execute(conn);
} catch (RuntimeException e) {
logger.l2("Runtime exception: " + e.getLocalizedMessage(), e);
} catch (IOException e) {
logger.l2(e.getLocalizedMessage(), e);
}
}
}
protected BinkpAbstractConnector createConnector(String protocolAddress,
String key) throws IOException {
Class<? extends BinkpAbstractConnector> connectorClass = BinkpConnectorRegistry
.getSelf().getConnector(key);
try {
return connectorClass.getConstructor(String.class).newInstance(
protocolAddress.substring(key.length()));
} catch (Exception e) {
throw new IOException("Error instatiating class "
+ connectorClass.getName() + " ( " + protocolAddress
+ " ) ", e);
}
}
}
| 31.844444
| 81
| 0.71284
|
e9e1caee482cfd5677fe57c0eb8433105e748e9b
| 166
|
package com.maxproj.dagger2demo3;
import dagger.Component;
@Component(modules = {MarkCarModule.class})
public interface CarComponent {
void inject(Car car);
}
| 16.6
| 43
| 0.76506
|
0956fa11ee5703a6c1f5b3f17655a4bda6069abd
| 483
|
package buildcraft.api.enums;
import java.util.Locale;
import net.minecraft.util.IStringSerializable;
public enum EnumDecoratedBlock implements IStringSerializable {
DESTROY(0),
BLUEPRINT(10),
TEMPLATE(10),
PAPER(10),
LEATHER(10);
public final int lightValue;
private EnumDecoratedBlock(int lightValue) {
this.lightValue = lightValue;
}
@Override
public String getName() {
return name().toLowerCase(Locale.ROOT);
}
}
| 19.32
| 63
| 0.687371
|
77d1d310300a6702bf07f837034341304b9df23c
| 374
|
package com.dragoonsaga.mathex.parser;
/**
* Interface for an constant node
*
* @author Eric Brooks
*
*/
public interface NodeConstant extends Node {
/**
* The value of this constant
*
* @return the value
*/
float getValue();
/**
* Sets the value of this constant
*
* @param string
* the value
*/
void setValue(String string);
}
| 13.851852
| 44
| 0.617647
|
25bf89f99c0bb93877f1f2a558ba82f4283ad7a4
| 5,159
|
/*
* Copyright 2002-2020 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.appbroker.extensions.targets;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import org.assertj.core.util.Lists;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import reactor.test.StepVerifier;
import org.springframework.cloud.appbroker.deployer.BackingApplication;
import org.springframework.cloud.appbroker.deployer.TargetSpec;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
class TargetServiceTest {
private TargetService targetService;
@BeforeEach
void setUp() {
targetService = new TargetService(
Arrays.asList(new SpacePerServiceInstance(), new ServiceInstanceGuidSuffix()));
}
@Test
void shouldAddProperties() {
// given an app with a target
TargetSpec targetSpec = TargetSpec.builder().name("SpacePerServiceInstance").build();
BackingApplication backingApplication = BackingApplication.builder().name("app-name").build();
//when add gets called
List<BackingApplication> updatedBackingApplications =
targetService
.addToBackingApplications(singletonList(backingApplication), targetSpec, "service-id")
.block();
//then a host and space are added
BackingApplication updatedBackingApplication = updatedBackingApplications.get(0);
assertThat(updatedBackingApplication.getName()).isEqualTo("app-name");
assertThat(updatedBackingApplication.getProperties().get("host")).isEqualTo("app-name-service-id");
assertThat(updatedBackingApplication.getProperties().get("target")).isEqualTo("service-id");
}
@Test
void shouldAddPropertiesToAllBackingApps() {
// given an app with a target
TargetSpec targetSpec = TargetSpec.builder().name("SpacePerServiceInstance").build();
BackingApplication backingApplication1 = BackingApplication.builder().name("app-name1").build();
BackingApplication backingApplication2 = BackingApplication.builder().name("app-name2").build();
//when add gets called
List<BackingApplication> updatedBackingApplications =
targetService
.addToBackingApplications(Lists.newArrayList(backingApplication1, backingApplication2), targetSpec,
"service-id")
.block();
//then a host and space are added
BackingApplication updatedBackingApplication1 = updatedBackingApplications.get(0);
assertThat(updatedBackingApplication1.getName()).isEqualTo("app-name1");
assertThat(updatedBackingApplication1.getProperties().get("host")).isEqualTo("app-name1-service-id");
assertThat(updatedBackingApplication1.getProperties().get("target")).isEqualTo("service-id");
BackingApplication updatedBackingApplication2 = updatedBackingApplications.get(1);
assertThat(updatedBackingApplication2.getName()).isEqualTo("app-name2");
assertThat(updatedBackingApplication2.getProperties().get("host")).isEqualTo("app-name2-service-id");
assertThat(updatedBackingApplication2.getProperties().get("target")).isEqualTo("service-id");
}
@Test
void shouldAddShortNameAsServiceInstanceGuidSuffix() {
final String appName = "boo";
final String serviceInstanceId = UUID.randomUUID().toString();
final TargetSpec targetSpec = TargetSpec.builder().name("ServiceInstanceGuidSuffix").build();
final BackingApplication backingApplication = BackingApplication.builder().name(appName).build();
StepVerifier.create(targetService.addToBackingApplications(singletonList(backingApplication), targetSpec,
serviceInstanceId))
.consumeNextWith(backingApplications -> {
String name = backingApplications.get(0).getName();
assertThat(name.length()).isLessThan(50).isGreaterThan(serviceInstanceId.length());
assertThat(name).contains(serviceInstanceId).contains(appName);
})
.verifyComplete();
}
@Test
void shouldAddLongNameAsServiceInstanceGuidSuffix() {
final String appName = "this-is-a-much-longer-app-name-that-will-require-truncation";
final String serviceInstanceId = UUID.randomUUID().toString();
final TargetSpec targetSpec = TargetSpec.builder().name("ServiceInstanceGuidSuffix").build();
final BackingApplication backingApplication = BackingApplication.builder().name(appName).build();
StepVerifier.create(targetService.addToBackingApplications(singletonList(backingApplication), targetSpec,
serviceInstanceId))
.consumeNextWith(backingApplications -> {
String name = backingApplications.get(0).getName();
assertThat(name.length()).isEqualTo(50);
assertThat(name).contains(serviceInstanceId);
})
.verifyComplete();
}
}
| 41.604839
| 107
| 0.779221
|
959f298828108f081d232e56679bc4dad11f85c2
| 7,112
|
package com.opencore.dsfinvk.models.stammdaten;
import java.math.BigDecimal;
import java.util.StringJoiner;
import javax.validation.constraints.Digits;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Positive;
import javax.validation.constraints.Size;
import com.opencore.dsfinvk.models.BaseModel;
import com.opencore.dsfinvk.util.ValidStammUst;
import com.opencore.dsfinvk.util.ValidUstSchluessel;
import com.opencore.gdpdu.index.annotations.Column;
import com.opencore.gdpdu.index.models.DataType;
/**
* Stammdaten zur Umsatzsteuer (ID, USt-Satz, Beschreibung).
* <p/>
* Die Zuordnung der verwendeten Umsatzsteuerschlüssel wird innerhalb der DSFinV-K in den Stammdaten festgelegt (s. u.).
* <p/>
* In der folgenden Übersicht werden die Umsatzsteuerschlüssel mit Beschreibung und den aktuell gültigen Umsatzsteuersätzen dargestellt.
* Bei einer Änderung der gesetzlichen Umsatzsteuersätze können Anpassungen ab der ID 1000 individuell für den Unternehmer erfolgen.
* Diese Anpassungen (ab ID 1000) können nach einem Kassenabschluss jederzeit vorgenommen werden und sind in den entsprechenden Systembeschreibungen bzw. Verfahrensdokumentationen zu dokumentieren.
* <p/>
* Anpassungen der IDs von 8-999 bleiben der DFKA-Taxonomie und der DSFinV-K vorbehalten und sind in den Begleitdokumenten bei Änderungen zu dokumentieren und zu erläutern.
* <p/>
* Die Beschreibung kann individuell angepasst werden (z. B. Ergänzung kassenüblicher Beschreibungen, die auch auf den Belegen aufgedruckt sind).
*
* <table>
* <tr>
* <th>ID</th>
* <th>USt-Satz</th>
* <th>Beschreibung</th>
* </tr>
* <tr>
* <td>1</td>
* <td></td>
* <td>Zum Zeitpunkt der Erfassung des Geschäftsvorfalls geltender allgemeiner Steuersatz (§ 12 Abs. 1 UStG)</td>
* </tr>
* <tr>
* <td>2</td>
* <td></td>
* <td>Zum Zeitpunkt der Erfassung des Geschäftsvorfalls geltender ermäßigter Steuersatz (§ 12 Abs. 2 UStG)</td>
* </tr>
* <tr>
* <td>3</td>
* <td>10,70%</td>
* <td>Durchschnittsatz (§ 24 Abs. 1 Nr. 3 UStG) übrige Fälle</td>
* </tr>
* <tr>
* <td>4</td>
* <td>5,50%</td>
* <td>Durchschnittsatz (§ 24 Abs. 1 Nr. 1 UStG)</td>
* </tr>
* <tr>
* <td>5</td>
* <td>0,00%</td>
* <td>Nicht Steuerbar</td>
* </tr>
* <tr>
* <td>6</td>
* <td>0,00%</td>
* <td>Umsatzsteuerfrei</td>
* </tr>
* <tr>
* <td>7</td>
* <td>0,00%</td>
* <td>UmsatzsteuerNichtErmittelbar</td>
* </tr>
* <tr>
* <td>11</td>
* <td>19,00%</td>
* <td>Historischer allgemeiner Steuersatz (§ 12 Abs. 1 UStG)</td>
* </tr>
* <tr>
* <td>12</td>
* <td>7,00%</td>
* <td>Historischer ermäßigter Steuersatz (§ 12 Abs. 2 UStG)</td>
* </tr>
* <tr>
* <td>21</td>
* <td>16,00%</td>
* <td>Historischer allgemeiner Steuersatz (§ 12 Abs. 1 UStG)</td>
* </tr>
* <tr>
* <td>22</td>
* <td>5,00%</td>
* <td>Historischer ermäßigter Steuersatz (§ 12 Abs. 2 UStG)</td>
* </tr>
* <tr>
* <td>bis 999</td>
* <td></td>
* <td>reserviert für Änderungen DSFinV-K</td>
* </tr>
* <tr>
* <td>ab 1000</td>
* <td></td>
* <td>individuelle Sachverhalte (Altsteuersätze, § 13b UStG, o.ä.)</td>
* </tr>
* </table>
*
* <h3>Verwendung der ID 7</h3>
* In vielen Kassensystemen ist es technisch nicht möglich - bei späterem Zahlungseingang (Forderungsauflösung) - die Beträge getrennt nach USt-Sätzen darzustellen.
* <p/>
* Für Unternehmer, die ihren Gewinn gemäß § 4 Abs. 3 EStG ermitteln (Einnahme-Überschussrechner) und/oder Unternehmer, die eine Versteuerung nach vereinnahmten Entgelten gemäß § 20 UStG durchführen, wären diese Kassensysteme nicht zur Einnahmeerfassung nutzbar, da z. B. die Bezahlung von Lieferscheinen oder bestehenden Forderungen an der Kasse umsatzsteuerlich nicht korrekt dargestellt werden könnte.
* <p/>
* Damit auch diese Kassensysteme verwendet werden können, bietet die DSFinV-K die folgende Lösung, welche die Umsatzsteuer bereits zum Zeitpunkt der Warenbewegung und nicht erst zum Zeitpunkt der Zahlung auslöst:
* <p/>
* Die ID 7 dient der Kennzeichnung von Forderungsauflösungen, deren umsatzsteuerliche Zuordnung von der Kasse nicht dargestellt werden kann.
* Wird die ID 7 eingesetzt, ist dies im Kassenabschluss im Datenfeld KEINE_UST_ZUORDNUNG zu dokumentieren.
* <p/>
* In diesen Fällen ist seitens der Finanzverwaltung folgende Sichtweise zu vertreten:
* <blockquote>"Wird bei der Versteuerung nach vereinnahmten Entgelten die Umsatzsteuer aus technischen Gründen nicht zum Zeitpunkt der Vereinnahmung, sondern zu einem früheren Zeitpunkt berücksichtigt, z. B. zum Zeitpunkt der Entstehung einer Forde- rung bei Kreditkartenzahlung oder einer Stundung, ist dies nicht zu beanstanden."</blockquote>
*
* <h3>Besondere Sachverhalte i. R. d. Umsatzsteuer</h3>
* Ab der "ID" = 1000 können besondere umsatzsteuerliche Sachverhalte (z. B. Differenzbesteuerung § 25a UStG, Sachverhalte des § 13b UStG) kenntlich gemacht werden.
* <p/>
* Diese Sachverhalte müssen durch die Kassenhersteller bzw. Kassenhändler individuell angelegt werden.
*/
@ValidStammUst
public class StammUst extends BaseModel {
public static final String FILENAME = "vat.csv";
@Positive
@NotNull // TODO: This does not seem to work but it's still caught by the @Positive annotation
@ValidUstSchluessel
@Column(value = "UST_SCHLUESSEL", type = DataType.Numeric)
private long ustSchluessel;
@Digits(integer = Integer.MAX_VALUE, fraction = 2)
//@NotNull -> TODO This is now optional as of DSFinV-K
@Column(value = "UST_SATZ", type = DataType.Numeric)
private BigDecimal ustSatz;
@Size(max = 55)
@NotBlank
@Column(value = "UST_BESCHR", type = DataType.AlphaNumeric)
private String ustBeschr;
public long getUstSchluessel() {
return ustSchluessel;
}
public void setUstSchluessel(long ustSchluessel) {
this.ustSchluessel = ustSchluessel;
}
/**
* Hier wird der Prozentsatz des jeweiligen Umsatzsteuersatzes dokumentiert.
*/
public BigDecimal getUstSatz() {
return ustSatz;
}
public void setUstSatz(BigDecimal ustSatz) {
this.ustSatz = ustSatz;
}
/**
* Hier kann die Beschreibung der unterschiedlichen Steuersätze dokumentiert werden, z. B. "Allgemeiner Steuersatz", "ermäßigter Steuersatz".
* Zusätzlich können individuelle Anpassungen vorgenommen werden.
*/
public String getUstBeschr() {
return ustBeschr;
}
public void setUstBeschr(String ustBeschr) {
this.ustBeschr = ustBeschr;
}
@Override
public String toString() {
return new StringJoiner(", ", StammUst.class.getSimpleName() + "[", "]")
.add("ustSchluessel=" + ustSchluessel)
.add("ustSatz=" + ustSatz)
.add("ustBeschr='" + ustBeschr + "'")
.add("zKasseId='" + getzKasseId() + "'")
.add("zErstellung=" + getzErstellung())
.add("zNr=" + getzNr())
.toString();
}
}
| 38.236559
| 411
| 0.686867
|
f291eefffa67200b0c1043dd07aaf5caccf2b4bc
| 1,211
|
package prefuse.data.parser;
/**
* Exception indicating an error occurred during parsing of data values.
*
* @author <a href="http://jheer.org">jeffrey heer</a>
*/
public class DataParseException extends Exception {
/**
* Create a new DataParseException.
*/
public DataParseException() {
super();
}
/**
* Create a new DataParseException.
*
* @param message
* a descriptive error message
*/
public DataParseException(String message) {
super(message);
}
/**
* Create a new DataParseException.
*
* @param message
* a descriptive error message
* @param cause
* a Throwable (e.g., error or exception) that was the cause for this
* exception being thrown
*/
public DataParseException(String message, Throwable cause) {
super(message, cause);
}
/**
* Create a new DataParseException.
*
* @param cause
* a Throwable (e.g., error or exception) that was the cause for this
* exception being thrown
*/
public DataParseException(Throwable cause) {
super(cause);
}
} // end of class DataParseException
| 23.288462
| 81
| 0.601982
|
0a345f293bd635ae85d0ce346679dd5b11e6d00c
| 1,554
|
package net.boomerangplatform.service.runner.misc;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
import net.boomerangplatform.model.Task;
import net.boomerangplatform.mongo.model.TaskStatus;
import net.boomerangplatform.mongo.model.internal.InternalTaskResponse;
import net.boomerangplatform.service.refactor.TaskClient;
@Service
@Profile("local")
public class MockControllerClient implements ControllerClient {
@Autowired
private TaskClient flowTaskClient;
@Override
public void submitTemplateTask(Task task, String activityId, String workflowName) {
InternalTaskResponse response = new InternalTaskResponse();
response.setActivityId(task.getTaskActivityId());
response.setStatus(TaskStatus.completed);
flowTaskClient.endTask(response);
return;
}
@Override
public void submitCustomTask(Task task, String activityId, String workflowName) {
InternalTaskResponse response = new InternalTaskResponse();
response.setActivityId(task.getTaskActivityId());
response.setStatus(TaskStatus.completed);
flowTaskClient.endTask(response);
return;
}
@Override
public boolean terminateFlow(String workflowId, String workflowName, String activityId) {
return true;
}
@Override
public boolean createFlow(String workflowId, String workflowName, String activityId,
boolean enableStorage, Map<String, String> properties) {
return true;
}
}
| 32.375
| 91
| 0.790862
|
a07cdc6fb129ac7decc3a7a6e047a79b93757e44
| 1,171
|
/**
*
*/
package com.marcestarlet.booksearcher.rest.model.dao;
import java.util.List;
import com.marcestarlet.booksearcher.rest.model.entity.Book;
/**
* BookDAO defines how the operations for a Book will be
* @author MarceStarlet
*
* mongodb-basics
*/
public interface BookDAO extends DAO<Book> {
/**
* Creates a new book into the data store
* @param b Book to be created
*/
public void create( Book b );
/**
* Updates an existent book into the data store
* @param b Book to be updated
*/
public void update( Book b );
/**
* Deletes an existent book from the data store
* @param id ID of the book to be deleted
*/
public void delete( final String id );
/**
* Finds a book by the ID
* @param id ID of the book
* @return Book found
*/
public Book findById( final String id );
/**
* Finds all the books from the data store
* @return All the existent books
*/
public List<Book> findAll();
/**
* Finds all the corresponding books that matches the
* filters passed through
* @param filters Array of filters
* @return All the books that matched
*/
public List<Book> findByFilters( String filter );
}
| 20.189655
| 60
| 0.673783
|
2fba4ef039c4648fcf3e288c8a0699740ad3e608
| 2,493
|
// Copyright (C) 2017 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.permissions;
import static java.util.Objects.requireNonNull;
import com.google.gerrit.extensions.api.access.GerritPermission;
public enum ChangePermission implements ChangePermissionOrLabel {
READ,
/**
* The change can't be restored if its current patch set is locked.
*
* <p>Before checking this permission, the caller should first verify the current patch set of the
* change is not locked by calling {@code PatchSetUtil.isPatchSetLocked}.
*/
RESTORE,
DELETE,
/**
* The change can't be abandoned if its current patch set is locked.
*
* <p>Before checking this permission, the caller should first verify the current patch set of the
* change is not locked by calling {@code PatchSetUtil.isPatchSetLocked}.
*/
ABANDON,
EDIT_ASSIGNEE,
EDIT_DESCRIPTION,
EDIT_HASHTAGS,
EDIT_TOPIC_NAME,
REMOVE_REVIEWER,
/**
* A new patch set can't be added if the patch set is locked for the change.
*
* <p>Before checking this permission, the caller should first verify the current patch set of the
* change is not locked by calling {@code PatchSetUtil.isPatchSetLocked}.
*/
ADD_PATCH_SET,
/**
* The change can't be rebased if its current patch set is locked.
*
* <p>Before checking this permission, the caller should first verify the current patch set of the
* change is not locked by calling {@code PatchSetUtil.isPatchSetLocked}.
*/
REBASE,
SUBMIT,
SUBMIT_AS("submit on behalf of other users"),
TOGGLE_WORK_IN_PROGRESS_STATE;
private final String description;
ChangePermission() {
this.description = null;
}
ChangePermission(String description) {
this.description = requireNonNull(description);
}
@Override
public String describeForException() {
return description != null ? description : GerritPermission.describeEnumValue(this);
}
}
| 32.802632
| 100
| 0.736462
|
b95969a96f3e0c7bdd2d23780e0f3542f9a0a1a3
| 3,017
|
package ch.frostnova.force.based.layout.strategy.impl;
import ch.frostnova.force.based.layout.geom.Rectangle;
import ch.frostnova.force.based.layout.geom.Vector;
import ch.frostnova.force.based.layout.geom.domain.ShapeForces;
import ch.frostnova.force.based.layout.model.Scene;
import ch.frostnova.force.based.layout.model.Shape;
import ch.frostnova.force.based.layout.strategy.SceneLayoutStrategy;
import ch.frostnova.util.check.Check;
import ch.frostnova.util.check.CheckNumber;
import java.util.Optional;
/**
* Repulsion layout strategy: shapes repel each other if they are too near (or even overlapping).
*
* @author pwalser
* @since 11.09.2018.
*/
public class RepulsionLayoutStrategy implements SceneLayoutStrategy {
private final double minDistance;
/**
* Create a new repulsion layout strategy, using the given minimal distance between shapes.
*
* @param minDistance minimum distance between shapes, must not be negative
*/
public RepulsionLayoutStrategy(double minDistance) {
this.minDistance = Check.required(minDistance, "minDistance", CheckNumber.min(0));
}
@Override
public ShapeForces calculateForces(Scene scene) {
ShapeForces forces = new ShapeForces();
scene.shapes().forEach(a ->
scene.shapes().forEach(b -> {
if (System.identityHashCode(a) < System.identityHashCode(b)) {
calculateOverlapLength(a, b).ifPresent(length -> {
Vector centerA = a.getBounds().getCenter();
Vector centerB = b.getBounds().getCenter();
Vector middle = centerA.add(centerA.distance(centerB).scaled(0.5));
Vector forceA = middle.distance(centerA).normalized().scaled(length);
Vector forceB = middle.distance(centerB).normalized().scaled(length);
forces.add(a, forceA);
forces.add(b, forceB);
});
}
})
);
return forces;
}
private Optional<Double> calculateOverlapLength(Shape first, Shape second) {
Rectangle a = first.getBounds().addMargin(minDistance / 2);
Rectangle b = second.getBounds().addMargin(minDistance / 2);
double qx1 = Math.max(a.getLocation().getX(), b.getLocation().getX());
double qx2 = Math.min(a.getLocation().getX() + a.getSize().getWidth(), b.getLocation().getX() + b.getSize().getWidth());
double overlapX = qx2 - qx1;
double qy1 = Math.max(a.getLocation().getY(), b.getLocation().getY());
double qy2 = Math.min(a.getLocation().getY() + a.getSize().getHeight(), b.getLocation().getY() + b.getSize().getHeight());
double overlapY = qy2 - qy1;
if (overlapX > 0 && overlapY > 0) {
return Optional.of(new Vector(overlapX, overlapY).length());
}
return Optional.empty();
}
}
| 38.189873
| 130
| 0.623136
|
e2ac5d25a020cc33f95417ec30278e80c804636e
| 909
|
package com.fjut.pojo;
import java.util.Date;
import com.fjut.util.DateUtil;
import lombok.Getter;
import lombok.Setter;
/**
* 操作日志
* @author LGX
*
*/
@Getter@Setter
public class SystemLog {
/**
* ID
*/
private int id;
/**
* 操作日期
*/
private Date date;
/**
* 主机名 + IP地址
*/
private String userLocalHost;
/**
* 操作人员
*/
private String userId;
/**
* 具体操作
*/
private String handle;
public SystemLog() {}
public SystemLog(int id, Date date, String userLocalHost, String userId, String handle) {
this.id = id;
this.date = date;
this.userLocalHost = userLocalHost;
this.userId = userId;
this.handle = handle;
}
@Override
public String toString() {
return "★ 【日志】: " + id + "\n" +
"> 操作时间: " + DateUtil.dateFormate2(date) + "\n" +
"> 用户主机: " + userLocalHost + "\n" +
"> 操作用户ID: " + userId + "\n" +
"> 具体操作: " + handle + "\n";
}
}
| 14.901639
| 90
| 0.585259
|
416720b1b3f67b76b9fde6a0fd8af19b6d6eb1b0
| 6,167
|
package com.github.fgiannesini.libsass.gradle.plugin.installer;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import org.apache.commons.io.FileUtils;
import org.gradle.api.logging.Logger;
import com.github.fgiannesini.libsass.gradle.plugin.installer.jruby.JRubyCaller;
/**
* Library installer for scss framework using JRuby
*
*/
public class ScssFrameworkInstaller {
/**
* Specific version to download
*/
private String versionToDownload;
/**
* Path to install sources
*/
private Path installationPath;
/**
* Gradle logger
*/
protected final Logger logger;
public ScssFrameworkInstaller(final Logger logger) {
this.logger = logger;
}
/**
* Launch framework installation
*
* @param frameworkProperties
* @throws Exception
*/
public void installFramework(
final FrameworkPropertiesEnum frameworkProperties)
throws Exception {
final File folder = this.downloadSources(frameworkProperties);
this.installSources(frameworkProperties, folder);
}
private void installSources(
final FrameworkPropertiesEnum frameworkProperties,
final File folder) throws Exception {
try {
final File sourcesFolder = this
.getSourcesFolder(frameworkProperties, folder);
final Path installationPath = this.getInstallationPath(
frameworkProperties.getFolderInstallationName());
this.copySourcesToInstallationPath(sourcesFolder, installationPath);
} finally {
FileUtils.deleteDirectory(folder);
}
}
private File downloadSources(
final FrameworkPropertiesEnum frameworkProperties)
throws IOException {
final JRubyCaller jrubyCaller = new JRubyCaller(this.logger);
final File folder = jrubyCaller.unpack(frameworkProperties.getGemName(),
this.versionToDownload);
return folder;
}
protected void copySourcesToInstallationPath(final File sourcesFolder,
final Path installationPath) throws IOException {
final File[] listFiles = sourcesFolder.listFiles();
if (listFiles == null || listFiles.length == 0) {
this.logger.error(
"No files in folder " + sourcesFolder.getAbsolutePath());
return;
}
for (final File source : listFiles) {
if (source.isDirectory()) {
FileUtils.copyDirectory(source,
installationPath.resolve(source.getName()).toFile());
this.logger.info("Folder " + source.getName() + " copied");
} else {
FileUtils.copyFile(source,
installationPath.resolve(source.getName()).toFile());
this.logger.info("File " + source.getName() + " copied");
}
}
}
/**
* Retrieve from parameters install path and build missing directories if
* missing
*
* @param folderInstallationName
*
* @return
* @throws IOException
*/
protected Path getInstallationPath(final String folderInstallationName)
throws IOException {
if (this.installationPath == null) {
throw new IOException(
"Installation path is a mandatory parameter, please set it");
}
final Path installPath = this.installationPath
.resolve(folderInstallationName);
FileUtils.forceMkdir(installPath.toFile());
this.logger.info("Install folder : " + installPath);
return installPath;
}
/**
* Retrieve folder containing scss sources from unpacked gem
*
* @param frameworkProperties
* @param folder
*
* @return
* @throws Exception
*/
protected File getSourcesFolder(
final FrameworkPropertiesEnum frameworkProperties,
final File folder) throws Exception {
final File unpackedSourceFolder = this.getAndCheckUnpackedSourceFolder(
frameworkProperties.getGemName(), folder);
final File sourcesFolder = Paths
.get(unpackedSourceFolder.getAbsolutePath())
.resolve(frameworkProperties.getInternalGemSourcesPath())
.toFile();
this.logger.info(frameworkProperties + " sources folder : "
+ sourcesFolder.getAbsolutePath());
return sourcesFolder;
}
/**
* Check that unpack folder is correct, ie contains only one directory and
* return it
*
* @param gemName
* @param folder
*
* @throws Exception
*/
protected File getAndCheckUnpackedSourceFolder(final String gemName,
final File folder) throws Exception {
final File[] unpackedFiles = folder.listFiles();
if (unpackedFiles == null || unpackedFiles.length == 0) {
this.logger.error("No files in folder " + folder.getAbsolutePath());
throw new Exception("A problem occured while retrieving " + gemName
+ " sources files");
}
if (unpackedFiles.length != 1) {
this.logger.error("Folder " + folder.getAbsolutePath()
+ "should contains only one folder. Folder content :");
Arrays.stream(unpackedFiles).map(File::getName)
.forEach(this.logger::error);
throw new Exception("A problem occured while retrieving " + gemName
+ " sources files");
}
return unpackedFiles[0];
}
public void setVersionToDownload(final String versionToDownload) {
this.versionToDownload = versionToDownload;
}
public void setInstallationPath(final Path installationPath) {
this.installationPath = installationPath;
}
}
| 34.261111
| 82
| 0.603697
|
ef1db027036b5eb9b7e7470e16b7354877f15e65
| 3,653
|
package com.jlkj.project.ws.controller;
import java.util.List;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.jlkj.framework.aspectj.lang.annotation.Log;
import com.jlkj.framework.aspectj.lang.enums.BusinessType;
import com.jlkj.project.ws.domain.WsProjectSitePartition;
import com.jlkj.project.ws.service.IWsProjectSitePartitionService;
import com.jlkj.framework.web.controller.BaseController;
import com.jlkj.framework.web.domain.AjaxResult;
import com.jlkj.common.utils.poi.ExcelUtil;
import com.jlkj.framework.web.page.TableDataInfo;
/**
* 工地分区Controller
*
* @author pyy
* @date 2020-06-30
*/
@Api(tags = "工地分区接口")
@RestController
@RequestMapping("/ws/partition")
public class WsProjectSitePartitionController extends BaseController {
@Autowired
private IWsProjectSitePartitionService wsProjectSitePartitionService;
/**
* 查询工地分区列表
*/
@ApiOperation("查询项目下工地分区列表")
@PreAuthorize("@ss.hasPermi('ws:partition:list')")
@GetMapping("/list")
public AjaxResult list(Integer projectId) {
return AjaxResult.success(wsProjectSitePartitionService.selectWsProjectSitePartitionList(projectId));
}
/**
* 获取工地分区详细信息
*/
@ApiOperation("获取工地分区详细信息")
@PreAuthorize("@ss.hasPermi('ws:partition:query')")
@GetMapping(value = "/select/{id}")
public AjaxResult getInfo(@PathVariable("id") Integer id) {
return AjaxResult.success(wsProjectSitePartitionService.selectWsProjectSitePartitionById(id));
}
/**
* 新增工地分区
*/
@ApiOperation("新增工地分区")
@PreAuthorize("@ss.hasPermi('ws:partition:add')")
@Log(title = "工地分区", businessType = BusinessType.INSERT)
@PostMapping("/add")
public AjaxResult add(@RequestBody WsProjectSitePartition wsProjectSitePartition) {
int i = wsProjectSitePartitionService.insertWsProjectSitePartition(wsProjectSitePartition);
if (i == 0) {
return AjaxResult.error("分区名称重复");
}
return toAjax(i);
}
/**
* 修改工地分区
*/
@ApiOperation("修改工地分区")
@PreAuthorize("@ss.hasPermi('ws:partition:edit')")
@Log(title = "工地分区", businessType = BusinessType.UPDATE)
@PutMapping("/update")
public AjaxResult edit(@RequestBody WsProjectSitePartition wsProjectSitePartition) {
int i = wsProjectSitePartitionService.updateWsProjectSitePartition(wsProjectSitePartition);
if (i == 0) {
return AjaxResult.error("分区名称重复");
}
return toAjax(i);
}
/**
* 删除工地分区
*/
@ApiOperation("删除工地分区")
@PreAuthorize("@ss.hasPermi('ws:partition:remove')")
@Log(title = "工地分区", businessType = BusinessType.DELETE)
@DeleteMapping("/delete/{id}")
public AjaxResult remove(@PathVariable Integer id) {
String str = wsProjectSitePartitionService.deleteWsProjectSitePartitionById(id);
if (str.equals("1")){
return AjaxResult.success("删除成功");
}
return AjaxResult.error("该分区已被("+str+")启用,不能删除");
}
}
| 34.462264
| 109
| 0.722967
|
1909e9ff69ac2be9124ad780800f644dabc15d24
| 5,831
|
/*
* Copyright (c) 2013-2017 xiaomi.com, Inc. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.xiaomi.passport.util;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import com.xiaomi.passport.constant.GlobalConstants;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/**
* sdk common utils
*
* @author zhenchao.wang 2017-04-14 14:41:54
* @version 1.0.0
*/
public class CommonUtils {
private static final Logger log = LoggerFactory.getLogger(CommonUtils.class);
private static Random random = new SecureRandom();
private CommonUtils() {
}
/**
* generate mac signature
* format : nonce + \n + method(POST\GET) + \n + host + \n + uriPath + \n + qs + \n
*
* @param nonce random string
* @param method POST or GET
* @param uriPath request url path
* @param qs query param
* @param macAlgorithm signature algorithm, must be HmacSHA1
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
*/
public static String getMacAccessTokenSignature(
String nonce, String method, String host, String uriPath, String qs, String macKey, String macAlgorithm)
throws InvalidKeyException, NoSuchAlgorithmException {
log.debug("Get mac access token signature: nonce[{}], method[{}], host[{}], uriPath[{}], qs[{}], macKey[{}], macAlgorithm[{}].",
nonce, method, host, uriPath, qs, macKey, macAlgorithm);
List<String> elements = new ArrayList<String>();
elements.add(nonce);
elements.add(method.toUpperCase());
elements.add(host);
elements.add(uriPath);
StringBuilder builder = new StringBuilder();
if (StringUtils.isNotBlank(qs)) {
// qs may be blank
List<NameValuePair> params = new ArrayList<NameValuePair>();
URLEncodedUtils.parse(params, new Scanner(qs), GlobalConstants.DEFAULT_CHARSET);
Collections.sort(params, new Comparator<NameValuePair>() {
public int compare(NameValuePair p1, NameValuePair p2) {
return p1.getName().compareTo(p2.getName());
}
});
builder.append(URLEncodedUtils.format(params, GlobalConstants.DEFAULT_CHARSET));
}
elements.add(builder.toString());
String sign = StringUtils.join(elements.toArray(), "\n");
sign += "\n"; // don't forget this
log.debug("The generate max sign is [{}]", sign);
if (GlobalConstants.HMAC_SHA1.equalsIgnoreCase(macAlgorithm)) {
try {
return Base64.encode(
encryptHmacSha1(
sign.getBytes(GlobalConstants.DEFAULT_CHARSET), macKey.getBytes(GlobalConstants.DEFAULT_CHARSET)));
} catch (UnsupportedEncodingException e) {
// never happen
}
} else {
throw new NoSuchAlgorithmException("Unsupported mac algorithm : " + macAlgorithm);
}
return StringUtils.EMPTY;
}
/**
* build mac request header content
*
* @param accessTokenId
* @param nonce
* @param mac
* @return
*/
public static Header buildMacRequestHeader(String accessTokenId, String nonce, String mac) {
String content = "MAC access_token=\"%s\", nonce=\"%s\",mac=\"%s\"";
try {
content = String.format(content,
URLEncoder.encode(accessTokenId, GlobalConstants.DEFAULT_CHARSET),
URLEncoder.encode(nonce, GlobalConstants.DEFAULT_CHARSET),
URLEncoder.encode(mac, GlobalConstants.DEFAULT_CHARSET));
} catch (UnsupportedEncodingException e) {
// never happen
}
return new BasicHeader("Authorization", content);
}
/**
* generate nonce
*
* @return
*/
public static String generateNonce() {
return String.format("%d:%d", random.nextLong(), System.currentTimeMillis() / (1000 * 60));
}
/**
* encrypt by HmacSha1
*
* @param data
* @param key
* @return return null if encrypt failed
* @throws InvalidKeyException
*/
public static byte[] encryptHmacSha1(byte[] data, byte[] key) throws InvalidKeyException {
try {
Mac mac = Mac.getInstance(GlobalConstants.HMAC_SHA1);
mac.init(new SecretKeySpec(key, GlobalConstants.HMAC_SHA1));
mac.update(data);
return mac.doFinal();
} catch (NoSuchAlgorithmException e) {
// never happen
}
return null;
}
}
| 35.339394
| 136
| 0.645344
|
f68ecf48afdf8be320335450577a3629e06afb13
| 8,606
|
/*
* 02/21/2005
*
* CodeTemplate.java - A "template" (macro) for commonly-typed code.
* Copyright (C) 2005 Robert Futrell
* robert_futrell at users.sourceforge.net
* http://fifesoft.com/rsyntaxtextarea
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*/
package org.fife.ui.rsyntaxtextarea.templates;
import java.io.IOException;
import java.io.ObjectInputStream;
import javax.swing.text.BadLocationException;
import javax.swing.text.Caret;
import javax.swing.text.Element;
import org.fife.ui.rsyntaxtextarea.RSyntaxDocument;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.RSyntaxUtilities;
/**
* A code template that inserts static text before and after the caret.
* <p>
*
* For example, you can associate the identifier <code>forb</code> (short for "for-block") with the following code:
* <p>
*
* <pre>
* for (<caret>) {
*
* }
* </pre>
*
* Then, whenever you type <code>forb</code> followed by a trigger (e.g., a space) into a text area with this
* <code>CodeTemplate</code>, the code snippet is added in place of <code>forb</code>. Further, the caret is placed at
* the position denoted by <code><caret></code>.
*
* @author Robert Futrell
* @version 0.1
* @see CodeTemplate
*/
public class StaticCodeTemplate extends AbstractCodeTemplate {
private static final long serialVersionUID = 1;
/**
* The code inserted before the caret position.
*/
private String beforeCaret;
/**
* The code inserted after the caret position.
*/
private String afterCaret;
/**
* Cached value representing whether <code>beforeCaret</code> contains one or more newlines.
*/
private transient int firstBeforeNewline;
/**
* Cached value representing whether <code>afterCaret</code> contains one or more newlines.
*/
private transient int firstAfterNewline;
private static final String EMPTY_STRING = "";
/**
* Constructor. This constructor only exists to support persistance through serialization.
*/
public StaticCodeTemplate() {
}
/**
* Constructor.
*
* @param id
* The ID of this code template.
* @param beforeCaret
* The text to place before the caret.
* @param afterCaret
* The text to place after the caret.
*/
public StaticCodeTemplate(String id, String beforeCaret, String afterCaret) {
super(id);
setBeforeCaretText(beforeCaret);
setAfterCaretText(afterCaret);
}
/**
* Returns the text that will be placed after the caret.
*
* @return The text.
* @see #setAfterCaretText
*/
public String getAfterCaretText() {
return afterCaret;
}
/**
* Returns the text that will be placed before the caret.
*
* @return The text.
* @see #setBeforeCaretText
*/
public String getBeforeCaretText() {
return beforeCaret;
}
/**
* Returns the "after caret" text, with each new line indented by the specified amount.
*
* @param indent
* The amount to indent.
* @return The "after caret" text.
*/
private String getAfterTextIndented(String indent) {
return getTextIndented(getAfterCaretText(), firstAfterNewline, indent);
}
/**
* Returns the "before caret" text, with each new line indented by the specified amount.
*
* @param indent
* The amount to indent.
* @return The "before caret" text.
*/
private String getBeforeTextIndented(String indent) {
return getTextIndented(getBeforeCaretText(), firstBeforeNewline, indent);
}
/**
* Returns text with newlines indented by the specifed amount.
*
* @param text
* The original text.
* @param firstNewline
* The index of the first '\n' character.
* @param indent
* The amount to indent.
* @return The indented text.
*/
private String getTextIndented(String text, int firstNewline, String indent) {
if (firstNewline == -1) {
return text;
}
int pos = 0;
int old = firstNewline + 1;
StringBuffer sb = new StringBuffer(text.substring(0, old));
sb.append(indent);
while ((pos = text.indexOf('\n', old)) > -1) {
sb.append(text.substring(old, pos + 1));
sb.append(indent);
old = pos + 1;
}
if (old < text.length()) {
sb.append(text.substring(old));
}
return sb.toString();
}
/**
* Invokes this code template. The changes are made to the given text area.
*
* @param textArea
* The text area to operate on.
* @throws BadLocationException
* If something bad happens.
*/
public void invoke(RSyntaxTextArea textArea) throws BadLocationException {
Caret c = textArea.getCaret();
int dot = c.getDot();
int mark = c.getMark();
int p0 = Math.min(dot, mark);
int p1 = Math.max(dot, mark);
RSyntaxDocument doc = (RSyntaxDocument) textArea.getDocument();
Element map = doc.getDefaultRootElement();
int lineNum = map.getElementIndex(dot);
Element line = map.getElement(lineNum);
int start = line.getStartOffset();
int end = line.getEndOffset() - 1; // Why always "-1"?
String s = textArea.getText(start, end - start);
int len = s.length();
// endWS is the end of the leading whitespace
// of the current line.
int endWS = 0;
while (endWS < len && RSyntaxUtilities.isWhitespace(s.charAt(endWS))) {
endWS++;
}
s = s.substring(0, endWS);
p0 -= getID().length();
String beforeText = getBeforeTextIndented(s);
String afterText = getAfterTextIndented(s);
doc.replace(p0, p1 - p0, beforeText + afterText, null);
textArea.setCaretPosition(p0 + beforeText.length());
}
/**
* Called when reading a serialized version of this document. This is overridden to initialize the transient members
* of this class.
*
* @param in
* The input stream to read from.
* @throws ClassNotFoundException
* Never.
* @throws IOException
* If an IO error occurs.
*/
private void readObject(ObjectInputStream in) throws ClassNotFoundException,
IOException {
in.defaultReadObject();
// "Resetting" before and after text to the same values will replace
// nulls with empty srings, and set transient "first*Newline" values.
setBeforeCaretText(this.beforeCaret);
setAfterCaretText(this.afterCaret);
}
/**
* Sets the text to place after the caret.
*
* @param afterCaret
* The text.
* @see #getAfterCaretText()
*/
public void setAfterCaretText(String afterCaret) {
this.afterCaret = afterCaret == null ? EMPTY_STRING : afterCaret;
firstAfterNewline = this.afterCaret.indexOf('\n');
}
/**
* Sets the text to place before the caret.
*
* @param beforeCaret
* The text.
* @see #getBeforeCaretText()
*/
public void setBeforeCaretText(String beforeCaret) {
this.beforeCaret = beforeCaret == null ? EMPTY_STRING : beforeCaret;
firstBeforeNewline = this.beforeCaret.indexOf('\n');
}
/**
* Returns a string representation of this template for debugging purposes.
*
* @return A string representation of this template.
*/
public String toString() {
return "[StaticCodeTemplate: id=" + getID() +
", text=" + getBeforeCaretText() + "|" + getAfterCaretText() + "]";
}
}
| 31.874074
| 120
| 0.623751
|
a72b8631d76a22e36da3b22563d0263ae69eb902
| 4,068
|
package gov.nara.opa.api.utils;
import gov.nara.opa.architecture.exception.OpaRuntimeException;
import gov.nara.opa.architecture.logging.OpaLogger;
import java.security.InvalidParameterException;
import java.util.HashSet;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* Email client implementation
*/
@Component
public class EmailClient {
private static OpaLogger logger = OpaLogger.getLogger(EmailClient.class);
@Value("${mail.smtp.host}")
private String host;
@Value("${mail.smtp.port}")
private String port;
@Value("${mail.smtp.auth}")
private String useAuth;
@Value("${mail.smtp.starttls.enable}")
private String enableTLS;
@Value("${mail.smtp.username}")
private String username;
@Value("${mail.smtp.password}")
private String password;
@Value("${mail.smtp.fromaddress}")
private String fromAddress;
private HashSet<String> toAddresses;
private Properties properties;
public String getEnableTLS() {
return (enableTLS == null || enableTLS.isEmpty() ? "false" : enableTLS);
}
public void setEnableTLS(String enableTLS) {
this.enableTLS = enableTLS;
}
public String getUseAuth() {
return (useAuth == null || useAuth.isEmpty() ? "false" : useAuth);
}
public void setUseAuth(String useAuth) {
this.useAuth = useAuth;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFromAddress() {
return fromAddress;
}
public void setFromAddress(String fromAddress) {
this.fromAddress = fromAddress;
}
public HashSet<String> getToAddresses() {
if (toAddresses == null) {
toAddresses = new HashSet<String>();
}
return toAddresses;
}
public EmailClient() {
properties = System.getProperties();
}
/**
* Sends a message using the configuration in the account.properties file. The
* destination accounts must be set before calling this method.
*
* @param subject
* The email subject
* @param body
* The email body as html
*/
public void SendMessage(String subject, String body) {
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.auth", getUseAuth());
properties.setProperty("mail.smtp.starttls.enable", getEnableTLS());
properties.setProperty("mail.smtp.port", port);
Session session;
if (getUseAuth().equals("false")) {
session = Session.getInstance(properties);
} else {
session = Session.getInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(fromAddress));
if (toAddresses.size() <= 0) {
throw new InvalidParameterException(
"Must provide at least one destination address");
}
for (String toAddress : toAddresses) {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
toAddress));
}
message.setSubject(subject);
message.setContent(body, "text/html");
Transport.send(message);
} catch (AddressException e) {
logger.error(e.getMessage(), e);
throw new OpaRuntimeException(e);
} catch (MessagingException e) {
logger.error(e.getMessage(), e);
throw new OpaRuntimeException(e);
}
}
}
| 25.111111
| 80
| 0.692232
|
b509941e63a76f6e05fac78118f1d83dd3e1dd8f
| 4,735
|
package cube.ware.widget.voice;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import java.util.LinkedList;
import cube.ware.R;
/**
* 自定义录音波动效果
*
* @author Wangxx
* @date 2017/2/8
*/
public class HorVoiceView extends View {
private Paint paint;
private int color;
private float lineHeight = 8;
private float maxLineHeight;
private float lineWidth;
private float textSize;
private String text = "00:00";
private int textColor;
private Thread mThread;
private int milliSeconds;
private boolean isStart = false;
private Runnable mRunable;
LinkedList<Integer> list = new LinkedList<>();
public HorVoiceView(Context context) {
super(context);
}
public HorVoiceView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public HorVoiceView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
for (int i = 0; i < 10; i++) {
list.add(1);
}
paint = new Paint();
mRunable = new Runnable() {
@Override
public void run() {
while (isStart) {
milliSeconds += 200;
text = milliSeconds / 1000 < 10 ? "0" + milliSeconds / 1000 : milliSeconds / 1000 + "";
Log.e("horvoiceview", "text " + text);
addElement(1);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
postInvalidate();
}
}
};
TypedArray mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.HorVoiceView);
color = mTypedArray.getColor(R.styleable.HorVoiceView_voiceLineColor, Color.BLACK);
lineWidth = mTypedArray.getDimension(R.styleable.HorVoiceView_voiceLineWidth, 35);
lineHeight = mTypedArray.getDimension(R.styleable.HorVoiceView_voiceLineHeight, 8);
maxLineHeight = mTypedArray.getDimension(R.styleable.HorVoiceView_voiceLineHeight, 32);
textSize = mTypedArray.getDimension(R.styleable.HorVoiceView_voiceTextSize, 40);
textColor = mTypedArray.getColor(R.styleable.HorVoiceView_voiceTextColor, Color.BLACK);
mTypedArray.recycle();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int widthcentre = getWidth() / 2;
int heightcentre = getHeight() / 2;
paint.setStrokeWidth(0);
paint.setColor(textColor);
paint.setTextSize(textSize);
paint.setTypeface(Typeface.DEFAULT_BOLD);
float textWidth = paint.measureText(text);
canvas.drawText(text, widthcentre - textWidth / 2, heightcentre - (paint.ascent() + paint.descent()) / 2, paint);
paint.setColor(color);
paint.setStyle(Paint.Style.FILL);
paint.setStrokeWidth(lineWidth);
paint.setAntiAlias(true);
for (int i = 0; i < 10; i++) {
RectF rect = new RectF(widthcentre + 2 * i * lineHeight + textWidth / 2 + lineHeight, heightcentre - list.get(i) * lineHeight / 2, widthcentre + 2 * i * lineHeight + 2 * lineHeight + textWidth / 2, heightcentre + list.get(i) * lineHeight / 2);
RectF rect2 = new RectF(widthcentre - (2 * i * lineHeight + 2 * lineHeight + textWidth / 2), heightcentre - list.get(i) * lineHeight / 2, widthcentre - (2 * i * lineHeight + textWidth / 2 + lineHeight), heightcentre + list.get(i) * lineHeight / 2);
canvas.drawRect(rect, paint);
canvas.drawRect(rect2, paint);
}
}
public synchronized void addElement(Integer height) {
for (int i = 0; i <= height / 30; i++) {
list.remove(9 - i);
list.add(i, (height / 20 - i) < 1 ? 1 : height / 20 - i);
}
postInvalidate();
}
public synchronized void setText(String text) {
this.text = text;
postInvalidate();
}
public synchronized void startRecording() {
milliSeconds = 0;
isStart = true;
new Thread(mRunable).start();
}
public synchronized void stopRecord() {
isStart = false;
list.clear();
for (int i = 0; i < 10; i++) {
list.add(1);
}
//text = "00:00";
postInvalidate();
}
}
| 27.690058
| 260
| 0.599789
|
474a0ca35febd5b81a69c5704506161d72438d67
| 193
|
public class recursion1
{
static int f(int n)
{
if(n <= 0)
return 1;
else
return n * f(n-1);
}
public static void main(String[] args)
{
assert f(1)==1;
}
}
| 12.0625
| 40
| 0.512953
|
303256d11dcd175bb3f2984d0340134b6f88a738
| 566
|
package org.kyojo.schemaorg.m3n4.doma.core.clazz;
import org.seasar.doma.ExternalDomain;
import org.seasar.doma.jdbc.domain.DomainConverter;
import org.kyojo.schemaorg.m3n4.core.impl.RADIO_SEASON;
import org.kyojo.schemaorg.m3n4.core.Clazz.RadioSeason;
@ExternalDomain
public class RadioSeasonConverter implements DomainConverter<RadioSeason, String> {
@Override
public String fromDomainToValue(RadioSeason domain) {
return domain.getNativeValue();
}
@Override
public RadioSeason fromValueToDomain(String value) {
return new RADIO_SEASON(value);
}
}
| 24.608696
| 83
| 0.809187
|
c34d505a40124bc85b1884c6d7a157ca466123ae
| 306
|
package dev.alnat.moneykeeper.dao;
import dev.alnat.moneykeeper.model.Icon;
import org.springframework.data.repository.CrudRepository;
/**
* Created by @author AlNat on 02.08.2020.
* Licensed by Apache License, Version 2.0
*/
public interface IconRepository extends CrudRepository<Icon, Integer> {
}
| 23.538462
| 71
| 0.777778
|
1c6f4fdbdecd70f49df028ab9f1a535f3c23a648
| 208
|
package repository;
public class StoredVacuousExemption extends Exception {
public StoredVacuousExemption() {
super();
}
public StoredVacuousExemption(String tagline) {
super(tagline);
}
}
| 16
| 55
| 0.730769
|
3a4db738bb582bdef31d9027b424c97ddf97304f
| 350
|
package codes.fepi.libuser;
import java.util.List;
public class TestEntity {
private String name;
private List<String> features;
public TestEntity(String name, List<String> features) {
this.name = name;
this.features = features;
}
public String getName() {
return name;
}
public List<String> getFeatures() {
return features;
}
}
| 15.909091
| 56
| 0.714286
|
12db6cf3943403eeea93fe5e245815faff45b5c0
| 2,218
|
package org.tsystems.javaschool.repository;
import org.tsystems.javaschool.model.entity.ScheduleSectionEntity;
import org.tsystems.javaschool.model.entity.SectionEntity;
import org.tsystems.javaschool.model.entity.StationEntity;
import org.tsystems.javaschool.model.entity.TrainEntity;
import java.time.LocalDate;
import java.util.Collection;
import java.util.List;
/**
* The interface Schedule section repository.
*
* @author Trofim Kremen
*/
public interface ScheduleSectionRepository {
/**
* Find all list.
*
* @return the list
*/
List<ScheduleSectionEntity> findAll();
/**
* Find by train list.
*
* @param trainEntity the train entity
* @param rideDate the ride date
* @return the list
*/
List<ScheduleSectionEntity> findByTrainAndRideDate(TrainEntity trainEntity, LocalDate rideDate);
/**
* Find by train and section index.
*
* @param trainEntity the train entity
* @param sectionIndex the section index
* @return the list
*/
ScheduleSectionEntity findByTrainAndSectionIndex(TrainEntity trainEntity, int sectionIndex);
/**
* Find by section list.
*
* @param sectionEntity the section entity
* @return the list
*/
List<ScheduleSectionEntity> findBySection(SectionEntity sectionEntity);
/**
* Find by id schedule section entity.
*
* @param id the id
* @return the schedule section entity
*/
ScheduleSectionEntity findById(int id);
/**
* Find by departure station id and r ide date list.
*
* @param stationEntity the station entity
* @param rideDate the ride date
* @return the list
*/
List<ScheduleSectionEntity> findByStationAndRideDate(StationEntity stationEntity, LocalDate rideDate);
/**
* Add schedule section entity.
*
* @param scheduleSectionEntity the schedule section entity
*/
void add(ScheduleSectionEntity scheduleSectionEntity);
/**
* Add iterable.
*
* @param scheduleSectionEntityCollection the schedule section entity collection
*/
void add(Collection<ScheduleSectionEntity> scheduleSectionEntityCollection);
}
| 26.404762
| 106
| 0.687556
|
35cc3f9a4cdc5b4fc7aef3ab00e9a9e98240b762
| 5,158
|
package com.infernostats.wavehistory;
import lombok.extern.slf4j.Slf4j;
import net.runelite.api.NPC;
import net.runelite.api.coords.WorldPoint;
import org.apache.commons.lang3.time.DurationFormatUtils;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Spawn {
public final String name;
public final WorldPoint tile;
public Spawn(WorldPoint tile, NPC npc) {
this.name = npc.getName();
this.tile = tile;
}
@Override
public String toString()
{
return this.name + " (" + this.tile.getRegionX() + ", " + this.tile.getRegionY() + ")";
}
}
@Slf4j
public class Wave {
public int id;
public List<Spawn> NPCSpawns;
public int damageTaken = 0;
public int damageDealt = 0;
public int prayerDrain = 0;
public boolean failed = false;
public Instant startTime;
public Instant stopTime;
public Duration splitTime;
public Duration predictedTime;
public boolean forceReset;
private static final List<Integer> SPLIT_WAVES = new ArrayList<Integer>() {{
add(9);
add(18);
add(25);
add(35);
add(42);
add(50);
add(57);
add(60);
add(63);
add(66);
add(67);
add(68);
add(69);
}};
public Wave(int id, Duration splitTime)
{
this.id = id;
this.NPCSpawns = new ArrayList<>();
this.startTime = Instant.now();
this.splitTime = splitTime;
this.predictedTime = null;
}
public void AddSpawn(WorldPoint tile, NPC npc)
{
NPCSpawns.add(new Spawn(tile, npc));
}
public void ReinitWave()
{
this.startTime = this.startTime.plus(
Duration.between(this.stopTime, Instant.now())
);
this.stopTime = null;
this.forceReset = false;
}
public void Finished(boolean failed)
{
this.failed = failed;
stopTime = Instant.now();
}
public void Pause()
{
this.forceReset = true;
this.stopTime = Instant.now();
}
public boolean IsSplit()
{
return SPLIT_WAVES.contains(id);
}
public String SplitTimeString()
{
return formatTime(splitTime.toMillis());
}
public String PredictedTimeString()
{
return formatTime(predictedTime.toMillis());
}
public long WaveTime()
{
if (stopTime == null)
{
return Duration.between(startTime, Instant.now()).toMillis();
}
else
{
return Duration.between(startTime, stopTime).toMillis();
}
}
public String WaveTimeString()
{
return formatTime(WaveTime());
}
public long CurrentTime()
{
if (stopTime == null)
{
return Duration.between(startTime, Instant.now()).plus(splitTime).toMillis();
}
else
{
return Duration.between(startTime, stopTime).plus(splitTime).toMillis();
}
}
public String CurrentTimeString()
{
return formatTime(CurrentTime());
}
private String formatTime(long msTime)
{
long seconds = Duration.ofMillis(msTime).getSeconds();
return seconds / 60 + ":" + String.format("%02d", seconds % 60);
}
public Map<String, ArrayList<ArrayList<Integer>>> RebasedNPCs()
{
Map<String, ArrayList<ArrayList<Integer>>> mobs = new HashMap<>();
for (Spawn spawn : NPCSpawns)
{
// The SW-most corner region tile is 17,17
// The SW-most corner website tile is 0, 29
final int xOffset = 17;
// The NW-most corner region tile is 17,46
// The NW-most corner website tile is 0, 0
final int yOffset = 46;
final int x = spawn.tile.getRegionX()-xOffset;
final int y = yOffset-spawn.tile.getRegionY();
mobs.computeIfAbsent(spawn.name, k -> new ArrayList<ArrayList<Integer>>());
mobs.get(spawn.name).add(new ArrayList<Integer>(){{add(x); add(y);}});
}
return mobs;
}
public String SerializeWave()
{
Map<String, ArrayList<ArrayList<Integer>>> mobs = RebasedNPCs();
// Map in-game names to website parameter names
Map<String, String> npc_names = new HashMap<String, String>() {{
put("Jal-MejRah", "bat");
put("Jal-Ak", "blob");
put("Jal-ImKot", "melee");
put("Jal-Xil", "ranger");
put("Jal-Zek", "mager");
}};
StringBuilder sb = new StringBuilder();
sb.append("https://www.infernotrainer.com/?");
for (Map.Entry<String, ArrayList<ArrayList<Integer>>> entry : mobs.entrySet())
{
sb.append(npc_names.get(entry.getKey()));
sb.append("=");
sb.append(entry.getValue());
sb.append("&");
}
sb.deleteCharAt(sb.length()-1); // Remove trailing ampersand
return sb.toString().replaceAll("\\s", "");
}
}
| 25.408867
| 95
| 0.570958
|
fee7214410c9565e0391f2c86723673719e9cf2a
| 679
|
package ec.ware;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* @author zack <br>
* @create 2020-09-30 23:19 <br>
* @project project-ec <br>
*/
@EnableTransactionManagement
@RefreshScope
@EnableDiscoveryClient
@SpringBootApplication
public class WareApplication {
public static void main(String[] args) {
SpringApplication.run(WareApplication.class, args);
}
}
| 29.521739
| 78
| 0.81296
|
ccca80f8a5bc41714b383683bfae3772a1ad3821
| 11,199
|
/**
* Copyright: Copyright 2016-2020 JD.COM All Right Reserved
* FileName: test.com.jd.blockchain.ledger.data.LedgerTransactionImplTest
* Author: shaozhuguang
* Department: 区块链研发部
* Date: 2018/8/30 上午9:48
* Description:
*/
package test.com.jd.blockchain.ledger.core;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import java.util.UUID;
import org.junit.Before;
import org.junit.Test;
import com.jd.binaryproto.BinaryProtocol;
import com.jd.binaryproto.DataContractRegistry;
import com.jd.blockchain.crypto.AsymmetricKeypair;
import com.jd.blockchain.crypto.Crypto;
import com.jd.blockchain.crypto.CryptoAlgorithm;
import com.jd.blockchain.crypto.HashDigest;
import com.jd.blockchain.crypto.PubKey;
import com.jd.blockchain.crypto.SignatureDigest;
import com.jd.blockchain.crypto.service.classic.ClassicAlgorithm;
import com.jd.blockchain.crypto.service.classic.ClassicCryptoService;
import com.jd.blockchain.ledger.BlockchainKeyGenerator;
import com.jd.blockchain.ledger.BlockchainKeypair;
import com.jd.blockchain.ledger.DataAccountKVSetOperation;
import com.jd.blockchain.ledger.DigitalSignature;
import com.jd.blockchain.ledger.HashObject;
import com.jd.blockchain.ledger.LedgerDataSnapshot;
import com.jd.blockchain.ledger.LedgerTransaction;
import com.jd.blockchain.ledger.TransactionContent;
import com.jd.blockchain.ledger.TransactionRequest;
import com.jd.blockchain.ledger.TransactionResult;
import com.jd.blockchain.ledger.TransactionState;
import com.jd.blockchain.ledger.core.LedgerTransactionData;
import com.jd.blockchain.ledger.core.TransactionResultData;
import com.jd.blockchain.ledger.core.TransactionStagedSnapshot;
import com.jd.blockchain.transaction.BlockchainOperationFactory;
import com.jd.blockchain.transaction.DigitalSignatureBlob;
import com.jd.blockchain.transaction.TxBuilder;
import com.jd.blockchain.transaction.TxContentBlob;
import com.jd.blockchain.transaction.TxRequestMessage;
/**
*
* @author shaozhuguang
* @create 2018/8/30
* @since 1.0.0
*/
public class LedgerTransactionDataTest {
private TransactionResult data;
private TransactionRequest txRequest;
private LedgerTransactionData ledgerTransactionData;
private AsymmetricKeypair keypair = ClassicCryptoService.ED25519.generateKeypair();
@Before
public void initLedgerTransactionImpl() throws Exception {
DataContractRegistry.register(LedgerTransaction.class);
DataContractRegistry.register(LedgerDataSnapshot.class);
DataContractRegistry.register(HashObject.class);
DataContractRegistry.register(DataAccountKVSetOperation.class);
txRequest = initTxRequestMessage(ClassicAlgorithm.SHA256);
long blockHeight = 9986L;
TransactionStagedSnapshot snapshot = initTransactionStagedSnapshot();
data = new TransactionResultData(txRequest.getTransactionHash(), blockHeight, TransactionState.SUCCESS,
snapshot, null);
HashDigest hash = ClassicCryptoService.SHA256.hash("zhangsan".getBytes());
HashDigest adminAccountHash = ClassicCryptoService.SHA256.hash("lisi".getBytes());
HashDigest userAccountSetHash = ClassicCryptoService.SHA256.hash("wangwu".getBytes());
HashDigest dataAccountSetHash = ClassicCryptoService.SHA256.hash("zhaoliu".getBytes());
HashDigest contractAccountSetHash = ClassicCryptoService.SHA256.hash("sunqi".getBytes());
snapshot.setAdminAccountHash(adminAccountHash);
snapshot.setUserAccountSetHash(userAccountSetHash);
snapshot.setDataAccountSetHash(dataAccountSetHash);
snapshot.setContractAccountSetHash(contractAccountSetHash);
ledgerTransactionData = new LedgerTransactionData(txRequest, data);
}
@Test
public void testSerialize_LedgerTransaction() throws Exception {
byte[] serialBytes = BinaryProtocol.encode(ledgerTransactionData, LedgerTransaction.class);
LedgerTransaction resolvedData = BinaryProtocol.decode(serialBytes);
System.out.println("------Assert start ------");
Assert_TransactionResult(resolvedData.getResult());
Assert_TransactionRequest(resolvedData.getRequest());
}
@Test
public void testSerialize_TransactionResult() throws Exception {
byte[] serialBytes = BinaryProtocol.encode(data, TransactionResult.class);
TransactionResult resolvedData = BinaryProtocol.decode(serialBytes);
System.out.println("------Assert start ------");
Assert_TransactionResult(resolvedData);
// EndpointSignatures 验证
// DigitalSignature[] dataEndpointSignatures = data.getEndpointSignatures();
// DigitalSignature[] resolvedEndpointSignatures = resolvedData.getEndpointSignatures();
// for (int i = 0; i < dataEndpointSignatures.length; i++) {
// assertEquals(dataEndpointSignatures[i].getPubKey(), resolvedEndpointSignatures[i].getPubKey());
// assertEquals(dataEndpointSignatures[i].getDigest(), resolvedEndpointSignatures[i].getDigest());
// }
// NodeSignatures 验证
// DigitalSignature[] dataNodeSignatures = data.getNodeSignatures();
// DigitalSignature[] resolvedNodeSignatures = resolvedData.getNodeSignatures();
// for (int i = 0; i < dataNodeSignatures.length; i++) {
// assertEquals(dataNodeSignatures[i].getPubKey(), resolvedNodeSignatures[i].getPubKey());
// assertEquals(dataNodeSignatures[i].getDigest(), resolvedNodeSignatures[i].getDigest());
// }
//
// assertEqual(data.getTransactionContent(), resolvedData.getTransactionContent());
System.out.println("------Assert OK ------");
}
@Test
public void testSerialize_TransactionRequest() throws Exception {
byte[] serialBytes = BinaryProtocol.encode(txRequest, TransactionRequest.class);
TransactionRequest resolvedData = BinaryProtocol.decode(serialBytes);
System.out.println("------Assert start ------");
Assert_TransactionRequest(resolvedData);
System.out.println("------Assert OK ------");
}
private void Assert_TransactionResult(TransactionResult recvResult) {
assertEquals(recvResult.getExecutionState(), data.getExecutionState());
assertEquals(recvResult.getBlockHeight(), data.getBlockHeight());
assertEquals(recvResult.getDataSnapshot().getAdminAccountHash(),
data.getDataSnapshot().getAdminAccountHash());
assertEquals(recvResult.getDataSnapshot().getContractAccountSetHash(),
data.getDataSnapshot().getContractAccountSetHash());
assertEquals(recvResult.getDataSnapshot().getDataAccountSetHash(),
data.getDataSnapshot().getDataAccountSetHash());
assertEquals(recvResult.getDataSnapshot().getUserAccountSetHash(),
data.getDataSnapshot().getUserAccountSetHash());
assertEquals(recvResult.getExecutionState(), data.getExecutionState());
assertEquals(recvResult.getBlockHeight(), data.getBlockHeight());
}
private void Assert_TransactionRequest(TransactionRequest recvRequest) {
// EndpointSignatures 验证
DigitalSignature[] dataEndpointSignatures = txRequest.getEndpointSignatures();
DigitalSignature[] resolvedEndpointSignatures = recvRequest.getEndpointSignatures();
for (int i = 0; i < dataEndpointSignatures.length; i++) {
assertEquals(dataEndpointSignatures[i].getPubKey(), resolvedEndpointSignatures[i].getPubKey());
assertEquals(dataEndpointSignatures[i].getDigest(), resolvedEndpointSignatures[i].getDigest());
}
// NodeSignatures 验证
DigitalSignature[] dataNodeSignatures = txRequest.getNodeSignatures();
DigitalSignature[] resolvedNodeSignatures = recvRequest.getNodeSignatures();
for (int i = 0; i < dataNodeSignatures.length; i++) {
assertEquals(dataNodeSignatures[i].getPubKey(), resolvedNodeSignatures[i].getPubKey());
assertEquals(dataNodeSignatures[i].getDigest(), resolvedNodeSignatures[i].getDigest());
}
assertTransactionEqual(txRequest.getTransactionContent(), recvRequest.getTransactionContent());
}
private void assertTransactionEqual(TransactionContent dataTxContent, TransactionContent resolvedTxContent) {
assertEquals(dataTxContent.getLedgerHash(), resolvedTxContent.getLedgerHash());
byte[] txBytes1 = BinaryProtocol.encode(dataTxContent, TransactionContent.class);
byte[] txBytes2 = BinaryProtocol.encode(resolvedTxContent, TransactionContent.class);
assertArrayEquals(txBytes1, txBytes2);
// assertEquals(dataTxContent.getHash(), resolvedTxContent.getHash());
// assertEquals(dataTxContent.getSequenceNumber(),
// resolvedTxContent.getSequenceNumber());
// assertEquals(dataTxContent.getSubjectAccount(),
// resolvedTxContent.getSubjectAccount());
}
private TransactionStagedSnapshot initTransactionStagedSnapshot() {
TransactionStagedSnapshot transactionStagedSnapshot = new TransactionStagedSnapshot();
transactionStagedSnapshot.setAdminAccountHash(ClassicCryptoService.SHA256.hash("zhangsan".getBytes()));
transactionStagedSnapshot.setContractAccountSetHash(ClassicCryptoService.SHA256.hash("lisi".getBytes()));
transactionStagedSnapshot.setDataAccountSetHash(ClassicCryptoService.SHA256.hash("wangwu".getBytes()));
transactionStagedSnapshot.setUserAccountSetHash(ClassicCryptoService.SHA256.hash("zhaoliu".getBytes()));
return transactionStagedSnapshot;
}
private TxRequestMessage initTxRequestMessage(CryptoAlgorithm hashAlgorithm) throws Exception {
TransactionContent txContent = initTransactionContent();
HashDigest txHash = TxBuilder.computeTxContentHash(hashAlgorithm, txContent);
TxRequestMessage txRequestMessage = new TxRequestMessage(txHash, txContent);
AsymmetricKeypair keypair2 = ClassicCryptoService.ED25519.generateKeypair();
SignatureDigest digest1 =ClassicCryptoService.ED25519.sign(keypair.getPrivKey(),"zhangsan".getBytes());
SignatureDigest digest2 = ClassicCryptoService.ED25519.sign(keypair.getPrivKey(),"lisi".getBytes());
DigitalSignatureBlob endPoint1 = new DigitalSignatureBlob(
keypair.getPubKey(), digest1);
DigitalSignatureBlob endPoint2 = new DigitalSignatureBlob(
keypair2.getPubKey(), digest2);
txRequestMessage.addEndpointSignatures(endPoint1);
txRequestMessage.addEndpointSignatures(endPoint2);
AsymmetricKeypair keypair4 = ClassicCryptoService.ED25519.generateKeypair();
SignatureDigest digest3 = ClassicCryptoService.ED25519.sign(keypair.getPrivKey(),"wangwu".getBytes());
SignatureDigest digest4 = ClassicCryptoService.ED25519.sign(keypair4.getPrivKey(),"zhaoliu".getBytes());
DigitalSignatureBlob node1 = new DigitalSignatureBlob(
keypair.getPubKey(), digest3);
DigitalSignatureBlob node2 = new DigitalSignatureBlob(
keypair4.getPubKey(), digest4);
txRequestMessage.addNodeSignatures(node1);
txRequestMessage.addNodeSignatures(node2);
return txRequestMessage;
}
private TransactionContent initTransactionContent() throws Exception {
TxContentBlob contentBlob = null;
BlockchainKeypair id = BlockchainKeyGenerator.getInstance().generate(ClassicAlgorithm.ED25519);
HashDigest ledgerHash = Crypto.getHashFunction("SHA256").hash(UUID.randomUUID().toString().getBytes("UTF-8"));
BlockchainOperationFactory opFactory = new BlockchainOperationFactory();
contentBlob = new TxContentBlob(ledgerHash);
// contentBlob.setSubjectAccount(id.getAddress());
// contentBlob.setSequenceNumber(1);
DataAccountKVSetOperation kvsetOP = opFactory.dataAccount(id.getAddress()).setText("Name", "AAA", -1)
.getOperation();
contentBlob.addOperation(kvsetOP);
return contentBlob;
}
}
| 45.157258
| 112
| 0.803911
|
0d7cf30cb2ace759a992d56ad5c3de5ffa004ba4
| 193
|
package crudvector;
public class CrudVector {
public static void main(String[] args) {
CrudVectorFrame cframe = new CrudVectorFrame();
cframe.show();
}
}
| 17.545455
| 59
| 0.606218
|
a30ffcb467ac0a5b3fd3868244b324c580b8a381
| 3,534
|
package validation;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Validate model declaration
*/
public final class ModelDeclarationValidity implements Validation {
public ModelDeclarationValidity(final String code) {
this.code = code;
}
@Override
public boolean valid() {
final String[] lines = this.code.split("\n");
final int codeLength = lines.length;
for (int currentLine = 0; currentLine < codeLength; currentLine++) {
if (!this.lineHasModelKeyword(lines[currentLine])) {
continue;
}
if (!this.nothingAfterModelKeyword(lines[currentLine])) {
this.errLine = currentLine + 1;
this.errMsg = "No character allowed after the \"model\" keyword.";
return false;
}
if (this.onlyHasBlankBeforeModelKeyword(lines[currentLine])) {
this.errLine = currentLine + 1;
this.errMsg = "The model name is required.";
return false;
}
if (!this.oneSpaceBeforeModelKeyword(lines[currentLine])) {
this.errLine = currentLine + 1;
this.errMsg = "There should be only one space between name and \"model\" keyword.";
return false;
}
if (!this.firstLetterIsCaptialized(lines[currentLine])) {
this.errLine = currentLine + 1;
this.errMsg = "The first letter of model name should be capitalized.";
return false;
}
}
return true;
}
@Override
public int line() {
return this.errLine;
}
@Override
public String reason() {
return this.errMsg;
}
private boolean lineHasModelKeyword(final String line) {
final Pattern pattern = Pattern.compile(HAS_MODEL_PATTERN);
final Matcher matcher = pattern.matcher(line);
return matcher.find();
}
private boolean nothingAfterModelKeyword(final String line) {
final Pattern pattern = Pattern.compile(NOTHING_AFTER_MODEL_PATTERN);
final Matcher matcher = pattern.matcher(line);
return matcher.find();
}
private boolean onlyHasBlankBeforeModelKeyword(final String line) {
final Pattern pattern = Pattern.compile(ONLY_BLANK_BEFORE_MODEL_PATTERN);
final Matcher matcher = pattern.matcher(line);
return matcher.find();
}
private boolean oneSpaceBeforeModelKeyword(final String line) {
final Pattern pattern = Pattern.compile(ONE_SPACE_BEFORE_MODEL_PATTERN);
final Matcher matcher = pattern.matcher(line);
return matcher.find();
}
private boolean firstLetterIsCaptialized(final String line) {
final Pattern pattern = Pattern.compile(FIRST_LETTER_CAPTIALIZED_PATTERN);
final Matcher matcher = pattern.matcher(line);
return matcher.find();
}
private String errMsg;
private int errLine;
private final String code;
private static final String FIRST_LETTER_CAPTIALIZED_PATTERN = "^\\s*[A-Z][A-Za-z0-9]*\\smodel$";
private static final String ONE_SPACE_BEFORE_MODEL_PATTERN = "^\\s*[A-Za-z0-9]+\\smodel$";
private static final String ONLY_BLANK_BEFORE_MODEL_PATTERN = "^\\s*model$";
private static final String NOTHING_AFTER_MODEL_PATTERN = "^([\\S\\s]*\\s+|\\s?)model$";
private static final String HAS_MODEL_PATTERN = "^([\\S\\s]*\\s+|\\s?)model(\\s?|\\s+[\\s\\S]*)$";
}
| 36.061224
| 102
| 0.627617
|
d2cb4cc73e6256a8afe465e8c80a142297cc3067
| 242
|
package me.saket.dank.utils.okhttp;
/**
* For listening to response read progress with {@link OkHttpRequestWriteProgressListener}.
*/
public interface OkHttpRequestWriteProgressListener {
void update(long bytesRead, long totalBytes);
}
| 24.2
| 91
| 0.789256
|
82b4d08c4b13b6f6aa670aea4dde6233f61b919c
| 4,617
|
package cruise.umple.ui.eclipse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWizard;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;
public class UmpleWizard extends Wizard implements INewWizard {
private UmpleWizardPage page;
private ISelection selection;
/**
* Constructor for UMPLEWizard.
*/
public UmpleWizard() {
super();
setNeedsProgressMonitor(true);
}
/**
* Adding the page to the wizard.
*/
public void addPages() {
page = new UmpleWizardPage(selection);
addPage(page);
}
/**
* This method is called when 'Finish' button is pressed in the wizard. We
* will create an operation and run it using wizard as execution context.
*/
public boolean performFinish() {
final String containerName = page.getContainerName();
final String fileName = page.getFileName();
IRunnableWithProgress op = new IRunnableWithProgress() {
public void run(IProgressMonitor monitor)
throws InvocationTargetException {
try {
doFinish(containerName, fileName, monitor);
} catch (CoreException e) {
throw new InvocationTargetException(e);
} finally {
monitor.done();
}
}
};
try {
getContainer().run(true, false, op);
} catch (InterruptedException e) {
return false;
} catch (InvocationTargetException e) {
Throwable realException = e.getTargetException();
MessageDialog.openError(getShell(), "Error", realException
.getMessage());
return false;
}
return true;
}
/**
* The worker method. It will find the container, create the file if missing
* or just replace its contents, and open the editor on the newly created
* file.
*/
private void doFinish(String containerName, String fileName,
IProgressMonitor monitor) throws CoreException {
// create a sample file
monitor.beginTask("Creating " + fileName, 2);
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IResource resource = root.findMember(new Path(containerName));
if (!resource.exists() || !(resource instanceof IContainer)) {
throwCoreException("Container \"" + containerName
+ "\" does not exist.");
}
IContainer container = (IContainer) resource;
final IFile file = container.getFile(new Path(fileName));
try {
InputStream stream = openContentStream();
if (file.exists()) {
file.setContents(stream, true, true, monitor);
} else {
file.create(stream, true, monitor);
}
stream.close();
} catch (IOException e) {
}
monitor.worked(1);
monitor.setTaskName("Opening file for editing...");
getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
IWorkbenchPage page = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage();
try {
IDE.openEditor(page, file, true);
} catch (PartInitException e) {
}
}
});
monitor.worked(1);
}
/**
* We will initialize file contents with a sample text.
*/
private InputStream openContentStream() {
String contents =
"class Airline { \n" + "singleton;\n" + "name = \"DEFAULT_NAME\";\n"
+ "}";
return new ByteArrayInputStream(contents.getBytes());
}
private void throwCoreException(String message) throws CoreException {
IStatus status = new Status(IStatus.ERROR, "UMPLE", IStatus.OK,
message, null);
throw new CoreException(status);
}
/**
* We will accept the selection in the workbench to see if we can initialize
* from it.
*
* @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
*/
public void init(IWorkbench workbench, IStructuredSelection selection) {
this.selection = selection;
}
}
| 29.980519
| 77
| 0.730561
|
6cb9ae77926bf80363104dd665e6d4a15ff8d6e9
| 2,194
|
/*
* Copyright 2019-2021 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.lettuce.core;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import javax.inject.Inject;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.codec.StringCodec;
import io.lettuce.core.output.StatusOutput;
import io.lettuce.core.protocol.CommandArgs;
import io.lettuce.core.protocol.CommandType;
import io.lettuce.test.LettuceExtension;
import io.lettuce.test.condition.EnabledOnCommand;
import io.lettuce.test.settings.TestSettings;
/**
* Integration test for authentication.
*
* @author Mark Paluch
*/
@ExtendWith(LettuceExtension.class)
@EnabledOnCommand("ACL")
class AuthenticationIntegrationTests extends TestSupport {
@BeforeEach
@Inject
void setUp(StatefulRedisConnection<String, String> connection) {
connection.sync().dispatch(CommandType.ACL, new StatusOutput<>(StringCodec.UTF8),
new CommandArgs<>(StringCodec.UTF8).add("SETUSER").add("john").add("on").add(">foobared").add("-@all"));
}
@Test
@Inject
void authAsJohn(RedisClient client) {
RedisURI uri = RedisURI.builder().withHost(TestSettings.host()).withPort(TestSettings.port())
.withAuthentication("john", "foobared").build();
StatefulRedisConnection<String, String> connection = client.connect(uri);
assertThatThrownBy(() -> connection.sync().info()).hasMessageContaining("NOPERM");
connection.close();
}
}
| 33.242424
| 120
| 0.737922
|
e90c314b18f2d3da781e2d54fedf7da993fd25cc
| 71
|
/**
* JPA domain objects.
*/
package lv.rtu.homework.checker.domain;
| 14.2
| 39
| 0.690141
|
d3c6021df620e8687508f9911bff16d1cdc6c5dd
| 140
|
// "Replace with regular string literal" "true"
class TextBlockMigration {
void oneLineNoNewLine() {
String json = "foobar\n";
}
}
| 17.5
| 47
| 0.678571
|
1c427c18967c1038aadbfc5c60478e81b57351eb
| 1,280
|
package com.xncoding.jwt.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.xncoding.jwt.config.properties.DruidProperties;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.annotation.Resource;
/**
* MybatisPlus配置
*
* @author xiongneng
* @since 2017/5/20 21:58
*/
@Configuration
@EnableTransactionManagement(order = 2)
@MapperScan(basePackages = {
"com.xncoding.jwt.common.dao.repository",
"com.xncoding.jwt.dao.repository"})
public class MybatisPlusConfig {
@Resource
private DruidProperties druidProperties;
/**
* 单数据源连接池配置
*/
@Bean
public DruidDataSource singleDatasource() {
DruidDataSource dataSource = new DruidDataSource();
druidProperties.config(dataSource);
return dataSource;
}
/**
* mybatis-plus分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
| 26.666667
| 78
| 0.744531
|
ae26762fd4e6b27ede18c8ab98d6b069e90b3425
| 22,881
|
package com.challengeandresponse.nonox;
/*
* <p>NoNox watches log files for events such as "failed password". When such a pattern is seen several
* times within a specified time period (for example, 4 failed login attempts within 10 minutes)
* from the same source, NoNox can execute a command to mitigate the behavior, notify someone, or
* make a record of the event (or all these things). The patterns, time limits, files to monitor,
* and commands that can be triggered are all user-specified, so NoNox can be used to detect many
* kinds of events and to respond in a variety of ways. I use NoNox to monitor for password-scanning
* attacks, and to block attacking hosts at the firewall in real-time.</p>
*
* <P>
* This is the script i use to launch it after compiling and stuffing into a jar file:<br>
* start.sh:<br>
* #!/bin/bash<br>
* java -cp /usr/local/nonox/nonox-1.17.jar com.challengeandresponse.nonox.NoNox >> /var/log/nonox.log &
* </p>
*
* Created on Aug 2, 2005 Version 1.0
* Last revision Nov. 26, 2005 Version 1.17
* Documentation update Nov 11, 2007
*
* (c) 2005 Challenge/Response, LLC
* @author Jim Youll, Challenge/Response LLC, jim@cr-labs.com
*
* LICENSE
*
* This software is licensed under the CC-GNU GPL.
* License details: http://creativecommons.org/licenses/GPL/2.0/
*
* Copyright (C) 2005-2007 Challenge/Response, LLC
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Stack;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NoNox {
public static final String VERSION = "1.18 of 2005-11-26";
/** The default config file, if the -c parameters was not given at startup */
public static final String CONFIG_FILE_DEFAULT = "/usr/local/nonox/nonox.conf";
/** Scan pause-interval when there IS data... to avoid too tight a loop */
static final int LOOP_PAUSE_MSEC = 5;
/**
* Initial delay between runs of the reaper thread. This will be adjusted to the shortest TTL for active records.
* This delay can be really, really long because it just removes held state for conditions that could no longer
* fire an action, and there won't be millions of those... provided the patterns and rules aren't too madly
* general.
*/
static final long REAPER_INITIAL_DELAY_SEC = 60*30;
/**
* Every this-many seconds, close and re-open the underlying files that are bound to patterns.
* Set to 0 to disable periodic file re-opens.
* This value must be at least as large as FILE_REOPEN_TIME_MINIMUM_MSEC or it will be ignored.
* Here it's set to 1 hour.
*/
static final long FILE_REOPEN_TIME_MSEC = 60*60*1000;
/**
* If doing file reopens, the reopen interval must be at least as large as this setting, or reopens will
* not occur (to prevent massive thrashing). Here it's set to 10 minutes
*/
static final long FILE_REOPEN_TIME_MINIMUM_MSEC = 60*10*1000;
private static void sleep(int _msec) {
try {
Thread.sleep(_msec);
}
catch (InterruptedException ie) {
}
}
private static void writeLog(String _s) {
System.out.println((new Date())+" "+_s);
}
public static void main (String[] params) {
// the tally records are here
Hashtable<String, ActionCounter> counters = new Hashtable<String, ActionCounter>();
// the config file path and file name. This could be overridden by the command line paramter -c
String configFile = CONFIG_FILE_DEFAULT;
// testMode is enabled with the command line argument -t (meaning "set test mode")
// if testMode is true, the commands that would be triggered are displayed, but not actually executed. Good for debugging roles
boolean testMode = false;
// tailMode is disabled with the command line argument -f (meaning "full file")
// if tailMode is true, then the file is TAILed - NoNox seeks to EOF before processing any content. This is the default.
// if tailMode is false, then NoNox processes the entire log file at startup then tails the file.
// this is useful if you have a log that NoNox hasn't operated against,
// or if your actions (e.g. firewall rules) are transient and aren't saved when set, e.g. with iptables-save
boolean tailMode = true;
// debugMode is enabled with the command line argument -d
// if debugMode is true, additional details about what the program is doing will be printed to the output
boolean debugMode = false;
// to hold the patterns and actions found in the config file
Vector<PatternConfig> patterns = new Vector<PatternConfig>();
Vector<ActionConfig> actions = new Vector<ActionConfig>();
// GO
boolean running = true;
writeLog("NoNox version "+VERSION+" started. Read loop will pause:"+LOOP_PAUSE_MSEC+" msec between read cycles (hardcoded, sorry!)");
// first retrieve parameters, if any
// We recognize "-c /path/to/config_file" to use a config file other than the default
// and -t for test mode (no commands are executed when in test mode)
// and -f to process the FULL FILE rather than starting processing at EOF (equivalent to tailing the file)
// and -d for DEBUG MODE where lots of extra operating detail is written to stdout while the program is running
for (int i = 0; i < params.length; i++) {
String p = params[i].trim().toLowerCase();
if (p.equals("-t"))
testMode = true;
else if (p.equals("-f"))
tailMode = false;
else if (p.equals("-d"))
debugMode = true;
else if (p.equals("-c") && ( (i+1) < params.length))
configFile = params[++i];
}
writeLog("configuration parameters: "+" testMode="+testMode+"; tailMode="+tailMode+"; debugMode="+debugMode);
writeLog("Using config file:"+configFile);
// LOAD SETTINGS FROM CONFIG FILE
// build hashtables of the found patterns and actions
// the format for the file is...
// pattern (pattern_name) (file) (regex)
// action (pattern_name) (threshold_count) (timelimit_seconds) (command)
final String PATTERN_REGEX = "^(pattern)\\s*(\\S*)\\s*(\\S*)\\s*(.*)";
final String ACTION_REGEX = "^(action)\\s*(\\S*)\\s*(\\S*)\\s*(\\S*)\\s*(.*)";
final Pattern patternPattern = Pattern.compile(PATTERN_REGEX);
final Pattern actionPattern = Pattern.compile(ACTION_REGEX);
BufferedReader cfr = null;
String line = null;
try {
cfr = new BufferedReader(new FileReader(configFile));
// read the whole contents and process
while ( (line = cfr.readLine()) != null) {
line = line.trim();
// if it's a comment, skip
if (line.indexOf("#") == 0)
continue;
// not a comment, so process the line
// is it a PATTERN declaration?
if (debugMode)
writeLog("Processing non-comment: "+line);
PatternConfig pcTemp = null;
Matcher m = patternPattern.matcher(line);
if (m.matches()) {
try {
pcTemp = new PatternConfig(m.group(2),m.group(3),tailMode,m.group(4));
}
catch (FileNotFoundException fnfe) {
writeLog("File not found for pattern:"+m.group(2)+" file:"+m.group(3)+" This pattern will NOT be used");
continue;
}
catch (IOException ioe) {
writeLog("IO Exception seeking to EOF for pattern:"+m.group(2)+" file:"+m.group(3)+" This pattern will NOT be used");
continue;
}
// continue with the next one
patterns.add(pcTemp);
writeLog("loaded pattern:"+pcTemp);
continue;
}
// is it an ACTION declaration?
m = actionPattern.matcher(line);
int thresholdCount;
int timelimitSeconds;
if (m.matches()) {
try {
thresholdCount = Integer.parseInt(m.group(3));
timelimitSeconds = Integer.parseInt(m.group(4));
}
catch (NumberFormatException nfe) {
writeLog("Exception parsing integer values from config line:"+line+" This action will NOT be used");
continue;
}
ActionConfig acTemp = new ActionConfig(m.group(2),thresholdCount,timelimitSeconds,m.group(5));
actions.add(acTemp);
writeLog("loaded action:"+acTemp);
continue;
}
} // end of while
cfr.close();
if (debugMode)
writeLog("Config file read and closed");
}
catch (FileNotFoundException fnfe) {
writeLog("Config file not found:"+configFile);
running = false;
}
catch (IOException ioe) {
writeLog("IO Exception reading config file:"+configFile+" "+ioe.getMessage());
running = false;
}
if ( (FILE_REOPEN_TIME_MSEC != 0) &&
(FILE_REOPEN_TIME_MSEC > FILE_REOPEN_TIME_MINIMUM_MSEC) ) {
writeLog("Files will be closed and reopened every "+FILE_REOPEN_TIME_MSEC+" msec ("+FILE_REOPEN_TIME_MSEC/60/1000+" minutes)");
}
writeLog("Starting reaper thread");
Reaper reaper = new Reaper(REAPER_INITIAL_DELAY_SEC,counters);
reaper.start();
writeLog("Starting monitor loop");
try {
while (running) {
// sleep every time around just to avoid real crazy too-tight loops if it's busy
sleep(LOOP_PAUSE_MSEC);
// For all the patternconfigs, read a line from their respective files, using their readers
// and see if there is a match
// when a pattern matches, find all the ACTIONS that name that pattern
// increment the counter for those ACTIONs
// when an action goes over-threshold within timelimitSeconds, invoke it
for (Iterator<PatternConfig> iPattern = patterns.iterator(); iPattern.hasNext(); ) {
PatternConfig pc = iPattern.next();
// If we are doing file-reopens, see if the file should be reopened. Do so, if it's time to...
// we don't to file reopens if FILE_OPEN_TIME_MSEC is 0, or if it's less than FILE_OPEN_TIME_MINIMUM_MSEC
if ( (FILE_REOPEN_TIME_MSEC != 0) &&
(FILE_REOPEN_TIME_MSEC > FILE_REOPEN_TIME_MINIMUM_MSEC) &&
((System.currentTimeMillis() - FILE_REOPEN_TIME_MSEC) > pc.fileOpenTimestamp)
)
pc.reopen();
// fetch a line from the input file
line = pc.br.readLine();
if (line == null)
continue; // in other words, there was nothing to read
if (debugMode)
writeLog("checking line: "+line);
Matcher m = pc.compiledPattern.matcher(line);
// if a pattern matched, step thru the actions that name the pattern, increment their
// counters, and invoke them if the threshold was reached
if (m.matches()) {
String ipAddress = (m.groupCount() >= 2) ? m.group(2).trim() : "NONE";
// try all the actions against this rule
for (Iterator<ActionConfig> iActions = actions.iterator(); iActions.hasNext(); ) {
ActionConfig ac = iActions.next();
// if this Action names the current pattern, increment and optionally invoke it
if (! ac.patternName.equals(pc.patternName))
continue;
// every pattern + ip + action has a counter
String key = ac.patternName + ipAddress + ac.index;
// do we have a counter for this key? If not, make a new entry
ActionCounter aco = null;
if (! counters.containsKey(key)) {
aco = new ActionCounter(ac.thresholdCount,ac.timelimitSeconds);
counters.put(key,aco);
}
else
aco = (ActionCounter) counters.get(key);
// move on if this rule already fired
if (aco.fired)
continue;
// otherwise tally and see if we can fire now
aco.pushTimestamp(System.currentTimeMillis());
counters.put(key,aco);
writeLog("MATCH pattern:"+pc.patternName+" count:"+aco.timestamps.size()+" action:"+ac.index+" address:"+ipAddress+" source:"+line);
if (testMode) {
if (m.groupCount() >= 1)
System.out.println("date: "+m.group(1));
if (m.groupCount() >= 2)
System.out.println("ip: "+m.group(2));
}
if (aco.canFire()) {
StringBuffer sb = new StringBuffer(ac.command);
int repl = sb.indexOf("%s");
if (repl > -1)
sb.replace(repl,repl+2,ipAddress);
writeLog("ACTION running command:"+sb.toString());
// mark the action as FIRED: we will only try to run an action one time (to avoid real meltdowns if there is a problem with the associated command)
aco.fired = true;
// clear out the action's timestamps stack: no longer needed
aco.timestamps = null;
counters.put(key,aco);
Process pr = null;
if (testMode)
writeLog("TEST MODE -- COMMAND WILL NOT BE EXECUTED");
else {
try {
pr = Runtime.getRuntime().exec(sb.toString());
}
catch (Exception e) {
writeLog("Exception running command:"+sb.toString()+" message:"+e.getMessage());
}
if (pr != null)
writeLog("Command executed. Exit value:"+pr.waitFor());
} // if testMode
} // if (aco.canFire
} // for iterator iActions
} // if
} // for Iterator iPattern
} // while running
} // end of try
catch (Exception e) {
writeLog("Nonox terminating due to exception:"+e.getMessage());
}
writeLog("Nonox terminating");
} // end of main()
static class PatternConfig {
String patternName = null;
String fileName = null;
File f = null;
String regexp = null;
Pattern compiledPattern = null;
BufferedReader br = null;
long fileOpenTimestamp = 0; // timestamp when file reader was opened, so it could be periodically refreshed
PatternConfig(String _patternName, String _fileName, boolean _tailMode, String _regexp)
throws FileNotFoundException, IOException {
patternName = _patternName.trim().toLowerCase();
fileName = _fileName;
f = new File(fileName);
regexp = _regexp;
compiledPattern = Pattern.compile(_regexp);
reopen(_tailMode);
}
/**
* Establishes a connection to the releated file. If the file is already bound, it closes and re-opens
* the file. Useful to periodically renew file connections (e.g. in case the file is turned over
* by a logrotate and the linkage to the new file lost to this application).
*/
public void reopen(boolean _tailMode)
throws FileNotFoundException, IOException {
if (br != null) {
writeLog("Closing file for periodic reopen:"+fileName);
try { br.close(); }
catch (IOException ioe) { }
}
// open the file
writeLog("Opening file:"+fileName);
br = new BufferedReader(new FileReader(f));
fileOpenTimestamp = System.currentTimeMillis();
// seek to EOF to "tail" the file and not reprocess it (would cause misfires if program were restarted at few times)
if (_tailMode) {
writeLog("In tail mode. Skipping to EOF of:"+fileName+" size:"+f.length());
br.skip(f.length());
}
}
public void reopen()
throws FileNotFoundException, IOException {
reopen(true);
}
public String toString() {
return "Pattern:"+patternName+" bound to file:"+fileName+" with regexp:"+regexp;
}
}
static class ActionConfig {
String patternName;
int thresholdCount;
int timelimitSeconds;
String command;
int index;
static int nextIndex = 0; // a quick way to get the index of this actionConfig when making a key that uses it
ActionConfig(String _patternName, int _thresholdCount, int _timelimitSeconds, String _command) {
patternName = _patternName.trim().toLowerCase();
thresholdCount = _thresholdCount;
timelimitSeconds = _timelimitSeconds;
command = _command;
index = nextIndex++;
}
public String toString() {
return "Action bound to pattern:"+patternName+" threshold:"+thresholdCount+" time limit in seconds:"+timelimitSeconds+" Command:"+command;
}
} // end of class ActionConfig
static class ActionCounter {
Stack<Long> timestamps;
int howmany;
long maxAgeMsec;
boolean fired;
public ActionCounter(int _howMany, int _maxAgeSec) {
timestamps = new Stack<Long>();
howmany = _howMany;
maxAgeMsec = _maxAgeSec * 1000;
fired = false;
}
public void pushTimestamp(long _timestamp) {
timestamps.push(new Long(_timestamp));
// first trim the stack if it's full, by removing the oldest (bottom-most) item(s) if it's too big
if (timestamps.size() > howmany)
timestamps.removeElementAt(0);
// timestamps.setSize(howmany);
}
public boolean canFire() {
if (fired) return false;
if (timestamps.size() < howmany) return false;
Long tsL = (Long) timestamps.firstElement();
System.out.println("oldest timestamp: "+tsL.longValue()+" msec "+tsL.longValue()/1000+" seconds "+tsL.longValue()/60000+" minutes"+"\nAGE of oldest timestamp in seconds:"+((System.currentTimeMillis()-tsL.longValue())/1000));
System.out.println("Current system time: "+System.currentTimeMillis());
return (tsL.longValue() > (System.currentTimeMillis() - (maxAgeMsec)));
}
} // end of class ActionCounter
/**
* The reaper goes through the counter structure, and tosses out any counters that have no recent activity on record...
* that is, every logged timestamp that is expired and cannot contribute to firing an action rule.
*/
static class Reaper extends Thread {
long delayMsec;
Hashtable<String, ActionCounter> counters;
/**
* @param _initialDelaySec The delay in seconds between runs of the Reaper thread (the thread may adjust this dynamically as it's running)
* @param _counters The counters Hashtable to reap... this should be a Hashtable of ActionCounter objects
*/
public Reaper(long _initialDelaySec, Hashtable<String, ActionCounter> _counters) {
delayMsec = _initialDelaySec * 1000;
counters = _counters;
}
public void run() {
while (true) {
writeLog("Reaper thread running. Reaper will run every "+delayMsec+" msec ("+delayMsec/1000/60+" minutes)");
// do reaping
try {
sleep(delayMsec);
}
catch (InterruptedException ie) { }
}
}
}
} // end of class NoNox
| 46.506098
| 236
| 0.553909
|
d926cec609d629fe7473ebb9567e807c700c1130
| 694
|
package pl.sternik.kk.zadania;
import java.util.Scanner;
public class Zad04 {
public static void main(String[] args) {
System.out.println("linia 1");
System.out.println("lina 2");
int[] ssss = {2,3,4,6,7,0};
for (int i = 0; i < ssss.length; i++) {
System.out.println(ssss[i]);
}
int i =0;
while (i<ssss.length) {
System.out.println(ssss[i]);
i++;
}
i = 0;
do {
System.out.println(ssss[i]);
i++;
} while (i<ssss.length);
Scanner s = new Scanner(System.in);
int i = s.nextInt();
}
}
| 20.411765
| 47
| 0.449568
|
259361ab9f866b81d988106a48de7eb29801ad42
| 4,042
|
/*
* MIT License
*
* Copyright (c) 2019 - 2020 Marvin (DerFrZocker)
*
* 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 de.derfrzocker.custom.ore.generator.impl.blockselector;
import de.derfrzocker.custom.ore.generator.api.BlockSelector;
import de.derfrzocker.custom.ore.generator.api.Info;
import de.derfrzocker.custom.ore.generator.api.OreSetting;
import org.apache.commons.lang.Validate;
import org.jetbrains.annotations.NotNull;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Function;
public abstract class AbstractBlockSelector implements BlockSelector {
@NotNull
private final String name;
@NotNull
private final Set<OreSetting> neededOreSettings;
@NotNull
private final Info info;
@NotNull
private final Map<OreSetting, Info> oreSettingInfoMap;
/**
* The infoFunction gives the name of the BlockSelector as value.
* The oreSettingInfo gives the name of the BlockSelector and the OreSetting as values.
*
* @param name of the BlockSelector
* @param neededOreSettings a set which contains the needed OreSetting
* @param infoFunction function to get the info object of this BlockSelector
* @param oreSettingInfo biFunction to get the info object of a given OreSetting
* @throws IllegalArgumentException if one of the arguments are null
*/
public AbstractBlockSelector(@NotNull final String name, @NotNull final Set<OreSetting> neededOreSettings, @NotNull final Function<String, Info> infoFunction, @NotNull final BiFunction<String, OreSetting, Info> oreSettingInfo) {
Validate.notNull(name, "Name can not be null");
Validate.notNull(neededOreSettings, "OreSettings can not be null");
Validate.notNull(infoFunction, "InfoFunction can not be null");
this.name = name;
this.neededOreSettings = neededOreSettings;
this.info = infoFunction.apply(getName());
final Map<OreSetting, Info> oreSettingInfoMap = new HashMap<>(this.neededOreSettings.size());
this.neededOreSettings.forEach(oreSetting -> oreSettingInfoMap.put(oreSetting, Objects.requireNonNull(oreSettingInfo.apply(this.name, oreSetting))));
this.oreSettingInfoMap = Collections.unmodifiableMap(oreSettingInfoMap);
}
@NotNull
@Override
public Set<OreSetting> getNeededOreSettings() {
return this.neededOreSettings;
}
@NotNull
@Override
public String getName() {
return this.name;
}
@NotNull
@Override
public Info getInfo() {
return this.info;
}
@NotNull
@Override
public Info getOreSettingInfo(@NotNull final OreSetting oreSetting) {
Validate.notNull(oreSetting, "OreSetting can not be null");
Validate.isTrue(getNeededOreSettings().contains(oreSetting), "The OreGenerator '" + getName() + "' does not have the OreSetting '" + oreSetting + "'");
return this.oreSettingInfoMap.get(oreSetting);
}
}
| 40.019802
| 232
| 0.730084
|
2fcb9ebe25079c681affb4808f207f2f18a09cbb
| 1,844
|
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* 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.intellij.util.xml.impl;
import com.intellij.util.xml.Convert;
import com.intellij.util.xml.Converter;
import java.lang.annotation.Annotation;
/**
* @author peter
*/
public class ConvertAnnotationImpl implements Convert {
private final Converter myConverter;
private final boolean mySoft;
public ConvertAnnotationImpl(final Converter converter, final boolean soft) {
myConverter = converter;
mySoft = soft;
}
public Class<? extends Annotation> annotationType() {
return Convert.class;
}
public Converter getConverter() {
return myConverter;
}
public Class<? extends Converter> value() {
return myConverter.getClass();
}
public boolean soft() {
return mySoft;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ConvertAnnotationImpl)) return false;
ConvertAnnotationImpl that = (ConvertAnnotationImpl)o;
if (mySoft != that.mySoft) return false;
if (!myConverter.getClass().equals(that.myConverter.getClass())) return false;
return true;
}
@Override
public int hashCode() {
int result = myConverter.getClass().hashCode();
result = 31 * result + (mySoft ? 1 : 0);
return result;
}
}
| 25.971831
| 82
| 0.712039
|
5eb2403ca7f1f9f0b22a5267f98321c1b6116559
| 1,817
|
/*
* 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 foodnet.foodnetserver.rest.controllers;
import foodnet.foodnetserver.BLL.Comment;
import foodnet.foodnetserver.rest.services.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
*
* @author Kushtrim Hajrizi
*/
@RestController
@RequestMapping("/businesses/{businessId}/posts/{postId}")
public class CommentController {
@Autowired
private CommentService commentService;
@RequestMapping(value = "/comments", method = RequestMethod.POST)
@PreAuthorize("hasAuthority('USER')")
public void create(
@PathVariable int businessId, @PathVariable int postId, @RequestBody Comment comment) {
commentService.create(comment, postId);
}
@RequestMapping(value = "/comments/{commentId}", method = RequestMethod.DELETE)
@PreAuthorize("hasAuthority('USER')")
public void delete(@PathVariable int businessId, @PathVariable int postId, @PathVariable int commentId) {
commentService.delete(commentId);
}
@RequestMapping(value = "/comments/{commentId}", method = RequestMethod.GET)
public Comment get(@PathVariable int businessId, @PathVariable int postId, @PathVariable int commentId) {
return commentService.get(commentId);
}
}
| 38.659574
| 109
| 0.758393
|
8e0201ad6a6615eb8d5e4e3cf5b4ec5a4c0b0a6b
| 3,941
|
package com.thinkgem.jeesite.modules.act.service;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.act.dao.LsAddressMapper;
import com.thinkgem.jeesite.modules.act.dao.LsOfficeMapper;
import com.thinkgem.jeesite.modules.act.entity.LsAddress;
import com.thinkgem.jeesite.modules.act.entity.LsAddressExample;
import com.thinkgem.jeesite.modules.act.entity.LsOffice;
import com.thinkgem.jeesite.modules.act.entity.LsOfficeExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class NetworkService {
@Autowired
LsAddressMapper lsAddressMapper;
/**
* 查询所有网段
*
* @return
*/
public List<LsAddress> getAll() {
// TODO Auto-generated method stub
return lsAddressMapper.selectByExample(null);
}
public LsAddress getData(Integer id) {
return lsAddressMapper.selectByPrimaryKey(id);
}
/**
* 网段保存
*
* @param lsAddress
*/
public void saveData(LsAddress lsAddress) {
// TODO Auto-generated method stub
lsAddressMapper.insert(lsAddress);
}
public int saveDataGetId(LsAddress lsAddress) {
// TODO Auto-generated method stub
return lsAddressMapper.insertAndGetId(lsAddress);
}
/**
* 网段更新
*
* @param lsAddress
*/
public void updateData(LsAddress lsAddress) {
// TODO Auto-generated method stub
lsAddressMapper.updateByPrimaryKeySelective(lsAddress);
}
/**
* 网段删除
*
* @param id
*/
public void deleteData(Integer id) {
// TODO Auto-generated method stub
lsAddressMapper.deleteByPrimaryKey(id);
}
public void deleteBatch(List<Integer> ids) {
// TODO Auto-generated method stub
LsAddressExample example = new LsAddressExample();
LsAddressExample.Criteria criteria = example.createCriteria();
criteria.andNIdIn(ids);
lsAddressMapper.deleteByExample(example);
}
/**
* 检验校区名是否可用
*
* @param name
* @return true:代表当前姓名可用 fasle:不可用
*/
public boolean checkName(String name) {
// TODO Auto-generated method stub
LsAddressExample example = new LsAddressExample();
LsAddressExample.Criteria criteria = example.createCriteria();
criteria.andNMinAddressEqualTo(name);
long count = lsAddressMapper.countByExample(example);
return count == 0;
}
public boolean checkNameByStr(String name) {
LsAddressExample example = new LsAddressExample();
LsAddressExample.Criteria criteria = example.createCriteria();
if(StringUtils.isNotBlank(name)){
name = "%" + name + "%";
}
criteria.andNMinAddressLike(name);
long count = lsAddressMapper.countByExample(example);
return count == 0;
}
public boolean checkNetwork(String name) {
List<LsAddress> list =lsAddressMapper.selectByExample(null);
boolean flag = false;
for (int i = 0; i < list.size(); i++) {
if (StringUtils.substringBeforeLast(list.get(i).getnMaxAddress(),".").equals(name) && StringUtils.substringBeforeLast(list.get(i).getnMinAddress(),".").equals(name)) {
flag = true;
break;
} else {
flag = false;
}
}
return flag;
}
/**
* 根据部门名称获取部门id
*
* @param name
* @return
*/
public int getId(String name) {
LsAddressExample example = new LsAddressExample();
LsAddressExample.Criteria criteria = example.createCriteria();
if(StringUtils.isNotBlank(name)){
name = "%" + name + "%";
}
criteria.andNMinAddressLike(name);
return lsAddressMapper.selectByExample(example).get(0).getnId();
}
}
| 27.753521
| 179
| 0.639178
|
bb0c706c499c7fc2ddb49e86d2c7e424c394d11b
| 1,595
|
package memethespire.shoppatches;
import com.evacipated.cardcrawl.modthespire.lib.SpirePatch;
import com.evacipated.cardcrawl.modthespire.lib.SpirePostfixPatch;
import com.megacrit.cardcrawl.vfx.FastCardObtainEffect;
@SpirePatch(clz = FastCardObtainEffect.class, method = "update")
public class FastCardObtainEffectUpdatePatch {
// See ShopCardPurchase patch: a separate patch on FastCardObtainEffect
// is used to update the shop screen.
@SpirePostfixPatch
public static void update(FastCardObtainEffect instance) {
// The card is added to the deck after the animation is complete.
if (instance.isDone && ShopCardPurchasePatch.currentScreen != null) {
// Update the cards and relics.
ShopInitCardsPatch.modifyCardsAndRelics(ShopCardPurchasePatch.currentScreen);
// The FastCardObtainEffect is likely used in other places as
// well, thus it is better to make sure that the other uses do
// not interfere with a shop screen that has been left behind.
// It is safe* to assign the screen to null as it will be
// re-assigned when another card is purchased.
// *If the player clicks fast enough between card purchases, it
// is possible that one animation completes when another card
// is being purchased, causing the second card to not have access
// to the variable. However, since this case is relatively
// unlikely, I will be lazy here.
ShopCardPurchasePatch.currentScreen = null;
}
}
}
| 48.333333
| 89
| 0.697179
|
2ad7eb5263829a942f5e4601838e6e46345a2b04
| 2,357
|
package server.any;
import org.omg.CORBA.SystemException;
import shared._AnyTestOperations;
import shared.AnyTestPackage.*;
import shared.Tree;
import shared.TreeHelper;
/**
* The AnyTest implementation class.
*/
class AnyTestImplementation implements _AnyTestOperations {
Tree[] empty = {};
Tree _tree_3 = new Tree("3", empty);
Tree _tree_4 = new Tree("4", empty);
Tree[] _tree_2_children = {_tree_3, _tree_4};
Tree _tree_2 = new Tree("2",_tree_2_children);
Tree _tree_6 = new Tree("4", empty);
Tree _tree_7 = new Tree("4", empty);
Tree[] _tree_5_children = {_tree_6, _tree_7};
Tree _tree_5 = new Tree("5",_tree_5_children);
Tree[] _tree_1_children = {_tree_2, _tree_5};
Tree _tree = new Tree("1",_tree_1_children);
/*Tree _tree = Tree("1",
{Tree("2", {Tree("3",{}), Tree("4",{})}),
Tree("5",{Tree("6",{}), Tree("7",{})})
}); */
public AnyTestImplementation () throws SystemException{
super();
};
org.omg.CORBA.Any _any_attribute;
public org.omg.CORBA.Any any_attribute() {
return _any_attribute;
};
public void any_attribute(org.omg.CORBA.Any value) {
_any_attribute = value;
return;
};
org.omg.CORBA.Any _any_tree_attribute;
public org.omg.CORBA.Any any_tree_attribute() {
return _any_tree_attribute;
};
public void any_tree_attribute(org.omg.CORBA.Any value){
_any_tree_attribute = value;
return;
};
public void check_any_attribute() throws failure {
org.omg.CORBA.Any expected = new IE.Iona.OrbixWeb.CORBA.Any();
expected.insert_short((short) 0);
if (!(_any_attribute.equal(expected))) throw new failure();
//if ((_any_attribute.extract_short()) != 0) throw new failure();
return;
}
public void check_any_tree_attribute() throws failure {
org.omg.CORBA.Any expected = new IE.Iona.OrbixWeb.CORBA.Any();
TreeHelper.insert(expected, _tree);
if (!(_any_attribute.equal(expected))) throw new failure();
return;
}
public org.omg.CORBA.Any any_operation(org.omg.CORBA.Any one,org.omg.CORBA.AnyHolder two,org.omg.CORBA.AnyHolder three) {
two.value = two.value;
three.value = one;
return one;
} ;
}
| 29.835443
| 125
| 0.624523
|
b57ad21e187a147bd35248cbe028f6da84dad2f5
| 11,328
|
/*
* Copyright 2017 EntIT Software LLC, a Micro Focus company, L.P.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.microfocus.mqm.atrf.alm.services;
import com.microfocus.mqm.atrf.alm.core.AlmEntity;
import com.microfocus.mqm.atrf.alm.core.AlmEntityCollection;
import com.microfocus.mqm.atrf.alm.core.AlmEntityDescriptor;
import com.microfocus.mqm.atrf.alm.entities.*;
import com.microfocus.mqm.atrf.core.rest.HTTPUtils;
import com.microfocus.mqm.atrf.core.rest.Response;
import com.microfocus.mqm.atrf.core.rest.RestConnector;
import com.microfocus.mqm.atrf.core.rest.RestStatusException;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.*;
/**
* Created by berkovir on 21/11/2016.
*/
public class AlmEntityService {
public static final int PAGE_SIZE = 1000;
public static final int PAGE_SIZE_BY_ID = 200;
RestConnector restConnector;
Map<String, String> jsonHeaders = new HashMap<>();
private String domain;
private String project;
Map<String, AlmEntityDescriptor> typesMap = new HashMap<>();
public AlmEntityService(RestConnector restConnector) {
this.restConnector = restConnector;
jsonHeaders.put(HTTPUtils.HEADER_ACCEPT, HTTPUtils.HEADER_APPLICATION_JSON);
registerTypes();
}
private void registerTypes() {
typesMap.put(Release.TYPE, new ReleaseDescriptor());
typesMap.put(Run.TYPE, new RunDescriptor());
typesMap.put(TestSet.TYPE, new TestSetDescriptor());
typesMap.put(Test.TYPE, new TestDescriptor());
typesMap.put(Sprint.TYPE, new SprintDescriptor());
typesMap.put(TestConfiguration.TYPE, new TestConfigurationDescriptor());
typesMap.put(TestFolder.TYPE, new TestFolderDescriptor());
}
public int getTotalNumber(String collectionName, AlmQueryBuilder queryBuilder) {
String entityCollectionUrl = String.format(AlmRestConstants.ALM_REST_PROJECT_ENTITIES_FORMAT, getDomain(), getProject(), collectionName);
String queryString = AlmQueryBuilder.create().addSelectedFields(AlmEntity.FIELD_ID).addPageSize(1).addQueryConditions(queryBuilder.getQueryConditions()).build();
String entitiesCollectionStr = restConnector.httpGet(entityCollectionUrl, Arrays.asList(queryString), jsonHeaders).getResponseData();
AlmEntityCollection col = parseCollection(entitiesCollectionStr);
return col.getTotal();
}
public List<String> getAllowedProjectsList() {
String url = String.format(AlmRestConstants.ALM_REST_PROJECTS, getDomain());
try {
String json = restConnector.httpGet(url, null, jsonHeaders).getResponseData();
List<String> projects = parseProjects(json);
return projects;
} catch (RestStatusException e) {
handleExceptionFromALM(e);
}
return Collections.emptyList();
}
private void handleExceptionFromALM(RuntimeException e) {
String errorMsg;
try {
String msg = e.getMessage();
JSONObject jsonObj = new JSONObject(msg);
errorMsg = (String) jsonObj.get("Title");
} catch (Exception parseEx) {
throw e;
}
throw new AlmRestException(errorMsg);
}
public AlmEntityCollection getEntities(String collectionName, AlmQueryBuilder qb) {
String entityCollectionUrl = String.format(AlmRestConstants.ALM_REST_PROJECT_ENTITIES_FORMAT, getDomain(), getProject(), collectionName);
String queryString = qb.build();
String json = restConnector.httpGet(entityCollectionUrl, Arrays.asList(queryString), jsonHeaders).getResponseData();
AlmEntityCollection coll = parseCollection(json);
return coll;
}
public List<AlmEntity> getAllPagedEntities(String collectionName, AlmQueryBuilder qb) {
List<AlmEntity> entities = new ArrayList<>();
//get num of pages
int totalNumOfPages = Integer.MAX_VALUE;
int currentStartIndex = 1;
for (int i = 1; i <= totalNumOfPages; i++) {
AlmQueryBuilder myQb = qb.clone().addPageSize(PAGE_SIZE).addStartIndex(currentStartIndex);
AlmEntityCollection coll = getEntities(collectionName, myQb);
if (totalNumOfPages == Integer.MAX_VALUE) {
totalNumOfPages = getNumberOfPages(coll.getTotal(), PAGE_SIZE);
}
entities.addAll(coll.getEntities());
currentStartIndex = i * PAGE_SIZE + 1;
}
return entities;
}
public static int getNumberOfPages(int totalItems, int pageSize) {
int ret;
ret = totalItems / pageSize;
if (totalItems % pageSize > 0) {
ret++;
}
return ret;
}
public List<AlmEntity> getEntitiesByIds(String collectionName, Set<String> ids, Collection<String> fields) {
List<String> list = new ArrayList<>(ids);
List<AlmEntity> allEntities = new ArrayList<>();
for (int i = 0; i < list.size(); i = i + PAGE_SIZE_BY_ID) {
int maxIndex = Math.min(i + PAGE_SIZE_BY_ID, list.size());
List<String> subList = list.subList(i, maxIndex);
AlmQueryBuilder qb = AlmQueryBuilder.create().addQueryCondition("id", StringUtils.join(subList, " OR ")).addSelectedFields(fields);
AlmEntityCollection coll = getEntities(collectionName, qb);
allEntities.addAll(coll.getEntities());
}
return allEntities;
}
public void setDomain(String domain) {
this.domain = domain;
}
public void setProject(String project) {
this.project = project;
}
public String getDomain() {
return domain;
}
public String getProject() {
return project;
}
private AlmEntityCollection parseCollection(String entitiesCollectionStr) {
AlmEntityCollection coll = new AlmEntityCollection();
JSONObject jsonObj = new JSONObject(entitiesCollectionStr);
int total = jsonObj.getInt("TotalResults");
coll.setTotal(total);
JSONArray entitiesJArr = jsonObj.getJSONArray("entities");
for (int i = 0; i < entitiesJArr.length(); i++) {
JSONObject entObj = entitiesJArr.getJSONObject(i);
String type = entObj.getString("Type");
AlmEntity almEntity = createEntity(type);
JSONArray fieldsJArr = entObj.getJSONArray("Fields");
for (int j = 0; j < fieldsJArr.length(); j++) {
JSONObject fieldObj = fieldsJArr.getJSONObject(j);
String name = fieldObj.getString("Name");
JSONArray valuesArr = fieldObj.getJSONArray("values");
boolean filled = false;
if (valuesArr.length() > 0) {
JSONObject valueObj = valuesArr.getJSONObject(0);
if (valueObj.has("value")) {
Object value = valueObj.get("value");
almEntity.put(name, value);
filled = true;
}
}
if (!filled) {
//the field has no value - just set it with null value
almEntity.put(name, null);
}
}
//almEntity.put(AlmEntity.FIELD_URL, generateALMReferenceURL(almEntity));
coll.getEntities().add(almEntity);
}
return coll;
}
private List<String> parseProjects(String projectsjson) {
List<String> projectList = new ArrayList<>();
JSONObject jsonObj = new JSONObject(projectsjson);
JSONArray projectArr = null;
//single project
if (jsonObj.has("Project")) {
projectArr = (JSONArray) jsonObj.get("Project");
} else {
//several projects
JSONObject projectsObj = (JSONObject) jsonObj.get("Projects");
if (projectsObj.get("Project") instanceof JSONArray) {
projectArr = (JSONArray) projectsObj.get("Project");
} else {
//single project
projectArr = new JSONArray();
projectArr.put(projectsObj.get("Project"));
}
}
for (int i = 0; i < projectArr.length(); i++) {
JSONObject entObj = projectArr.getJSONObject(i);
String name = entObj.getString("Name");
projectList.add(name);
}
return projectList;
}
private AlmEntity createEntity(String type) {
AlmEntityDescriptor descriptor = typesMap.get(type);
if (descriptor == null) {
throw new RuntimeException("Unregistered type " + type);
}
AlmEntity entity = null;
try {
entity = descriptor.getEntityClass().getConstructor().newInstance();
} catch (Exception e) {
throw new RuntimeException("Failed to create entity of type " + type, e);
}
return entity;
}
public boolean login(String user, String password) {
boolean ret = false;
restConnector.clearAll();
if (password == null) {
password = "";
}
//Get LWSSO COOKIE
String xml = String.format(AlmRestConstants.ALM_AUTH_XML, user, password);
Map<String, String> headers = new HashMap<>();
headers.put(HTTPUtils.HEADER_CONTENT_TYPE, HTTPUtils.HEADER_APPLICATION_XML);
headers.put(HTTPUtils.HEADER_ACCEPT, HTTPUtils.HEADER_APPLICATION_XML);
Response authResponse = restConnector.httpPost(AlmRestConstants.ALM_REST_AUTHENTICATION, xml, headers);
if (authResponse.getStatusCode() == HttpStatus.SC_OK) {
//GET SESSION cookies
Response sessionResponse = restConnector.httpPost(AlmRestConstants.ALM_REST_SESSION, null, null);
if (sessionResponse.getStatusCode() == HttpStatus.SC_CREATED) {
ret = true;
}
}
return ret;
}
public String generateALMReferenceURL(AlmEntity entity) {
AlmEntityDescriptor descriptor = typesMap.get(entity.getType());
String protocol = restConnector.getBaseUrl().split("://", 2)[0];
String base = restConnector.getBaseUrl().split("://", 2)[1];
String tdProtocol;
switch (protocol.toLowerCase()) {
case "http":
default:
tdProtocol = "td";
break;
case "https":
tdProtocol = "tds";
break;
}
String url = String.format(descriptor.getAlmRefUrlFormat(), tdProtocol, project, domain, base, entity.getId());
return url;
}
}
| 36.307692
| 169
| 0.631974
|
0867abdf39e53f170fe7549d4c7768207cc23ecc
| 3,654
|
/*
* nusim-loader
*
* (c) 2020 Deutsche Telekom AG.
* Deutsche Telekom AG and all other contributors /
* copyright owners license 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 de.scoopgmbh.nusimapp.server.api.logging;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import org.apache.commons.lang.StringUtils;
import org.reactivestreams.Publisher;
import ratpack.stream.Streams;
import java.time.Duration;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
public class WebsocketLogAppender extends AppenderBase<ILoggingEvent> {
private static final int LOG_LINE_MAX_LENGTH = 500;
private final ObjectWriter ow = new ObjectMapper().writer();
private final int bufferSize;
private final Consumer<ILoggingEvent> discardHandler;
private final Publisher<String> stream;
private LinkedList<ILoggingEvent> buffer = new LinkedList<>();
public WebsocketLogAppender(final int bufferSize, final Duration pollInterval, final Consumer<ILoggingEvent> discardHandler, Function<ILoggingEvent, ?> mapper) {
this.bufferSize = bufferSize;
this.discardHandler = discardHandler;
final Function<ILoggingEvent, ?> theMapper = mapper != null ? mapper : new Function<ILoggingEvent, LogEvent>() {
@Override
public LogEvent apply(ILoggingEvent in) {
return new LogEvent(in.getLevel().levelStr, StringUtils.abbreviate(in.getFormattedMessage(), LOG_LINE_MAX_LENGTH), new Date(in.getTimeStamp()));
}
};
stream = Streams.periodically(Executors.newSingleThreadScheduledExecutor(), pollInterval, (i) -> {
final List<ILoggingEvent> list = buffer;
buffer = new LinkedList<>();
String s = ow.writeValueAsString(list.stream().map(theMapper).collect(Collectors.toList()));
return s;
});
}
public Publisher<String> getStream() {
return stream;
}
@Override
protected void append(ILoggingEvent eventObject) {
if (eventObject.getLevel().levelStr.equals("TRACE")) {
return;
}
buffer.addLast(eventObject);
while (buffer.size() > bufferSize) {
ILoggingEvent event = buffer.removeFirst();
discardHandler.accept(event);
}
}
private static final class LogEvent {
final String loglevel;
final String message;
final Date t;
private LogEvent(String loglevel, String message, Date t) {
this.loglevel = loglevel;
this.message = message;
this.t = t;
}
public String getLoglevel() {
return loglevel;
}
public String getMessage() {
return message;
}
public Date getT() {
return t;
}
}
}
| 33.218182
| 165
| 0.679803
|
429d4f05a06f726a0eaab75e2234719d17032b30
| 1,428
|
package com.gtdq.netty.netty03;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
/**
* @author : LiuMingyao
* @date : 2019/8/5 22:12
* @description : TODO
*/
public final class Server {
private static final String ip = "127.0.0.1";
private static final int port = 9527;
public static void main(String[] args) throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ServerInitializer());
//需要三次握手,所以同步等待客户端连接
ChannelFuture future = b.bind(ip, port).sync();
//监听服务端关闭,并阻塞
future.channel().closeFuture().sync();
System.out.println("server start");
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭两个EventLoopGroup对象
workGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
}
| 30.382979
| 63
| 0.630952
|
a5ede5c87990a888ca42589e377446d8b3eca75a
| 1,280
|
package com.zipcode.justcode.clamfortress.ClamFortress.models.game.models.resources;
import com.fasterxml.jackson.annotation.*;
import com.zipcode.justcode.clamfortress.ClamFortress.models.game.models.nodes.*;
import com.zipcode.justcode.clamfortress.ClamFortress.models.game.models.other.*;
import javax.persistence.*;
@Entity
public abstract class AbstractResource extends GameObject {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JsonIgnore
private Board board;
@ManyToOne
@JsonIgnore
private Village village;
public AbstractResource() { super("", ""); }
public AbstractResource(String name, String desc) {
super(name, desc);
}
@Override
public String toString() {
return this.getName();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Board getBoard() {
return board;
}
public void setBoard(Board board) {
this.board = board;
}
public Village getVillage() {
return village;
}
public void setVillage(Village village) {
this.village = village;
}
@Override
public abstract AbstractResource clone();
}
| 20.31746
| 84
| 0.659375
|
7e9bf4891831fbbc9ff7fc8af905129c98fcacf1
| 4,865
|
/*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package org.jbox2d.d.collision.shapes;
import org.jbox2d.d.collision.AABB;
import org.jbox2d.d.collision.RayCastInput;
import org.jbox2d.d.collision.RayCastOutput;
import org.jbox2d.d.common.Transform;
import org.jbox2d.d.common.Vector2;
/**
* A shape is used for collision detection. You can create a shape however you
* like. Shapes used for simulation in World are created automatically when a
* Fixture is created. Shapes may encapsulate a one or more child shapes.
*/
public abstract class Shape {
public final ShapeType m_type;
private double m_radius;
public Shape(ShapeType type) {
this.m_type = type;
}
/**
* Get the type of this shape. You can use this to down cast to the concrete
* shape.
*
* @return the shape type.
*/
public ShapeType getType() {
return m_type;
}
/**
* The radius of the underlying shape. This can refer to different things
* depending on the shape implementation
*
* @return
*/
public double getRadius() {
return m_radius;
}
/**
* Sets the radius of the underlying shape. This can refer to different
* things depending on the implementation
*
* @param radius
*/
public void setRadius(double radius) {
this.m_radius = radius;
}
/**
* Get the number of child primitives
*
* @return
*/
public abstract int getChildCount();
/**
* Test a point for containment in this shape. This only works for convex
* shapes.
*
* @param xf
* the shape world transform.
* @param p
* a point in world coordinates.
*/
public abstract boolean testPoint(final Transform xf, final Vector2 p);
/**
* Cast a ray against a child shape.
*
* @param argOutput
* the ray-cast results.
* @param argInput
* the ray-cast input parameters.
* @param argTransform
* the transform to be applied to the shape.
* @param argChildIndex
* the child shape index
* @return if hit
*/
public abstract boolean raycast(RayCastOutput output, RayCastInput input,
Transform transform, int childIndex);
/**
* Given a transform, compute the associated axis aligned bounding box for a
* child shape.
*
* @param argAabb
* returns the axis aligned box.
* @param argXf
* the world transform of the shape.
*/
public abstract void computeAABB(final AABB aabb, final Transform xf,
int childIndex);
/**
* Compute the mass properties of this shape using its dimensions and
* density. The inertia tensor is computed about the local origin.
*
* @param massData
* returns the mass data for this shape.
* @param density
* the density in kilograms per meter squared.
*/
public abstract void computeMass(final MassData massData,
final double density);
/**
* Compute the distance from the current shape to the specified point. This
* only works for convex shapes.
*
* @param xf
* the shape world transform.
* @param p
* a point in world coordinates.
* @param normalOut
* returns the direction in which the distance increases.
* @return distance returns the distance from the current shape.
*/
public abstract double computeDistanceToOut(Transform xf, Vector2 p,
int childIndex, Vector2 normalOut);
public abstract Shape clone();
}
| 32.006579
| 85
| 0.681398
|
7c27973221a245b8dc9c7d7cdb1a7c818ff3750c
| 3,957
|
/*
* Copyright 2017 MongoDB, 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 org.bson.codecs.pojo;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import static java.lang.reflect.Modifier.isPublic;
final class PropertyReflectionUtils {
private PropertyReflectionUtils() {}
private static final String IS_PREFIX = "is";
private static final String GET_PREFIX = "get";
private static final String SET_PREFIX = "set";
static boolean isGetter(final Method method) {
if (method.getParameterTypes().length > 0) {
return false;
} else if (method.getName().startsWith(GET_PREFIX) && method.getName().length() > GET_PREFIX.length()) {
return Character.isUpperCase(method.getName().charAt(GET_PREFIX.length()));
} else if (method.getName().startsWith(IS_PREFIX) && method.getName().length() > IS_PREFIX.length()) {
return Character.isUpperCase(method.getName().charAt(IS_PREFIX.length()));
}
return false;
}
static boolean isSetter(final Method method) {
if (method.getName().startsWith(SET_PREFIX) && method.getName().length() > SET_PREFIX.length()
&& method.getParameterTypes().length == 1) {
return Character.isUpperCase(method.getName().charAt(SET_PREFIX.length()));
}
return false;
}
static String toPropertyName(final Method method) {
String name = method.getName();
String propertyName = name.substring(name.startsWith(IS_PREFIX) ? 2 : 3, name.length());
char[] chars = propertyName.toCharArray();
chars[0] = Character.toLowerCase(chars[0]);
return new String(chars);
}
static PropertyMethods getPropertyMethods(final Class<?> clazz) {
List<Method> setters = new ArrayList<Method>();
List<Method> getters = new ArrayList<Method>();
for (Method method : clazz.getDeclaredMethods()) {
// Note that if you override a getter to provide a more specific return type, getting the declared methods
// on the subclass will return the overridden method as well as the method that was overridden from
// the super class. This original method is copied over into the subclass as a bridge method, so we're
// excluding them here to avoid multiple getters of the same property with different return types
if (isPublic(method.getModifiers()) && !method.isBridge()) {
if (isGetter(method)) {
getters.add(method);
} else if (isSetter(method)) {
// Setters are a bit more tricky - don't do anything fancy here
setters.add(method);
}
}
}
return new PropertyMethods(getters, setters);
}
static class PropertyMethods {
private final Collection<Method> getterMethods;
private final Collection<Method> setterMethods;
PropertyMethods(final Collection<Method> getterMethods, final Collection<Method> setterMethods) {
this.getterMethods = getterMethods;
this.setterMethods = setterMethods;
}
Collection<Method> getGetterMethods() {
return getterMethods;
}
Collection<Method> getSetterMethods() {
return setterMethods;
}
}
}
| 39.969697
| 118
| 0.654284
|
9b16af93bc598dd0e6470f0fc72aaa45aecef364
| 7,915
|
/**
* Copyright Notice
*
* This is a work of the U.S. Government and is not subject to copyright
* protection in the United States. Foreign copyrights may apply.
*
* 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 gov.va.isaac.gui.dialog;
import gov.va.isaac.AppContext;
import gov.va.isaac.gui.util.FxUtils;
import gov.va.isaac.model.ExportType;
import gov.va.isaac.util.ExportTypeStringConverter;
import gov.va.isaac.util.OTFUtility;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.stage.DirectoryChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.Window;
import javafx.stage.WindowEvent;
import org.ihtsdo.otf.tcc.api.concept.ConceptChronicleBI;
import org.ihtsdo.otf.tcc.api.contradiction.ContradictionException;
import org.ihtsdo.otf.tcc.api.metadata.binding.TermAux;
import org.ihtsdo.otf.tcc.api.spec.ValidationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterators;
// TODO: Auto-generated Javadoc
/**
* Controller class for {@link ExportFileSettingsDialog}.
*
* @author tnaing
* @author bcarlsenca
*/
public class ExportFileSettingsDialogController {
/** The Constant MODEL_TYPE_PROPERTY. */
public static final String MODEL_TYPE_PROPERTY =
"gov.va.isaac.gui.dialog.import-settings.model-type";
/** The Constant FILE_SELECTION_PROPERTY. */
public static final String FILE_SELECTION_PROPERTY =
"gov.va.isaac.gui.dialog.import-settings.file-selection";
/** The Constant LOG. */
private static final Logger LOG = LoggerFactory
.getLogger(ExportFileSettingsDialogController.class);
/** The model type combo. */
@FXML
private ComboBox<ExportType> modelTypeCombo;
/** The path combo. */
@FXML
private ComboBox<ConceptChronicleBI> pathCombo;
/** The folder selection label. */
@FXML
private Label folderSelectionLabel;
/** The zip. */
@FXML
private CheckBox zip;
/** The export settings dialog. */
private ExportFileSettingsDialog exportSettingsDialog;
/** The export stage. */
private Stage exportStage;
/**
* Sets the variables.
*
* @param exportSettingsDialog the export settings dialog
* @param parent the parent
*/
public void setVariables(ExportFileSettingsDialog exportSettingsDialog,
Window parent) {
this.exportSettingsDialog = exportSettingsDialog;
exportStage = buildExportStage(parent);
}
/**
* Initialize.
*/
@FXML
public void initialize() {
ExportTypeStringConverter converter = new ExportTypeStringConverter();
// Populate modelTypeCombo.
modelTypeCombo.setConverter(converter);
modelTypeCombo.setItems(ExportType.asObservableList());
// Populate pathCombo
ObservableList<ConceptChronicleBI> paths =
FXCollections.observableArrayList(new ArrayList<ConceptChronicleBI>());
try {
List<ConceptChronicleBI> pathConcepts = OTFUtility.getPathConcepts();
Iterators.removeIf(pathConcepts.iterator(),
new Predicate<ConceptChronicleBI>() {
@Override
public boolean apply(ConceptChronicleBI arg0) {
try {
return arg0.getVersion(OTFUtility.getViewCoordinate())
.getPreferredDescription().getText()
.startsWith(TermAux.SNOMED_CORE.getDescription() + " ");
} catch (IOException e) {
e.printStackTrace();
} catch (ContradictionException e) {
e.printStackTrace();
}
return false;
}
});
paths.addAll(pathConcepts);
} catch (ValidationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ContradictionException e) {
e.printStackTrace();
}
pathCombo.setItems(paths);
// Properties to speed development.
String modelTypeName = System.getProperty(MODEL_TYPE_PROPERTY);
if (modelTypeName != null) {
LOG.debug(MODEL_TYPE_PROPERTY + "=" + modelTypeName);
ExportType modelType = converter.fromString(modelTypeName);
modelTypeCombo.setValue(modelType);
}
}
/**
* Handler for folder selection button.
*/
public void handleFolderSelection() {
DirectoryChooser folderChooser = new DirectoryChooser();
// Show dialog.
File file = folderChooser.showDialog(exportSettingsDialog);
if (file != null) {
folderSelectionLabel.setText(file.getPath());
}
}
/**
* Handler for ok button.
*/
public void handleOk() {
ExportType exportType = modelTypeCombo.getValue();
String folderName = folderSelectionLabel.getText();
int pathNid = pathCombo.getValue().getConceptNid();
// Validate settings, show warning dialog if there is a problem.
String title = "Oops!";
if (exportType == null) {
AppContext.getCommonDialogs().showInformationDialog(title,
"Please select a export type.");
return;
}
if ((folderName == null) || (folderName.isEmpty())) {
AppContext.getCommonDialogs().showInformationDialog(title,
"Please select a folder to export.");
return;
}
exportSettingsDialog.close();
showExportView(exportType, pathNid, folderName, zip.isSelected());
}
/**
* Show export view.
*
* @param exportType the export type
* @param pathNid the path nid
* @param folder the folder
* @param zipChecked the zip checked
*/
public void showExportView(ExportType exportType, int pathNid, String folder,
boolean zipChecked) {
// Make sure in application thread.
FxUtils.checkFxUserThread();
try {
ExportView exportView = new ExportView();
exportStage.setScene(new Scene(exportView));
if (exportStage.isShowing()) {
exportStage.toFront();
} else {
exportStage.show();
}
((Stage) exportStage.getScene().getWindow())
.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent event) {
exportView.doCancel();
}
});
exportView.doExport(exportType, pathNid, folder, zipChecked);
} catch (Exception ex) {
String title = ex.getClass().getName();
String message = "Unexpected error displaying export view";
LOG.warn(message, ex);
AppContext.getCommonDialogs().showErrorDialog(title, message,
ex.getMessage());
}
}
/**
* Builds the export stage.
*
* @param owner the owner
* @return the stage
*/
private Stage buildExportStage(Window owner) {
// Use dialog for now, so Alo/Dan can use it.
Stage stage = new Stage();
stage.initModality(Modality.NONE);
stage.initOwner(owner);
stage.initStyle(StageStyle.DECORATED);
stage.setTitle("Export View");
return stage;
}
/**
* Handler for cancel button.
*/
public void handleCancel() {
exportSettingsDialog.close();
}
}
| 29.314815
| 79
| 0.68844
|
407f7ebd2124a40342689fd085dd0a572d88ba37
| 2,802
|
/*
* 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.sshd.common.file.nonefs;
import java.io.IOException;
import java.nio.file.FileStore;
import java.nio.file.FileSystem;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.WatchService;
import java.nio.file.attribute.UserPrincipalLookupService;
import java.nio.file.spi.FileSystemProvider;
import java.util.Collections;
import java.util.Set;
/**
* @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
*/
public class NoneFileSystem extends FileSystem {
public static final NoneFileSystem INSTANCE = new NoneFileSystem();
public NoneFileSystem() {
super();
}
@Override
public FileSystemProvider provider() {
return NoneFileSystemProvider.INSTANCE;
}
@Override
public void close() throws IOException {
// ignored
}
@Override
public boolean isOpen() {
return true;
}
@Override
public boolean isReadOnly() {
return true;
}
@Override
public String getSeparator() {
return "/";
}
@Override
public Iterable<Path> getRootDirectories() {
return Collections.emptyList();
}
@Override
public Iterable<FileStore> getFileStores() {
return Collections.emptyList();
}
@Override
public Set<String> supportedFileAttributeViews() {
return Collections.emptySet();
}
@Override
public Path getPath(String first, String... more) {
throw new UnsupportedOperationException("No paths available");
}
@Override
public PathMatcher getPathMatcher(String syntaxAndPattern) {
return p -> false;
}
@Override
public UserPrincipalLookupService getUserPrincipalLookupService() {
throw new UnsupportedOperationException("UserPrincipalLookupService N/A");
}
@Override
public WatchService newWatchService() throws IOException {
throw new UnsupportedOperationException("WatchService N/A");
}
}
| 27.203883
| 82
| 0.705211
|
5fdb95a9e19b172d0734f91d1fc517e4ef62c837
| 8,050
|
/*******************************************************************************
* # Copyright 2015 InfinitiesSoft Solutions 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.infinities.keystone4j.jpa.impl;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import com.google.common.collect.Lists;
import com.infinities.keystone4j.assignment.AssignmentDriver;
import com.infinities.keystone4j.common.Config;
import com.infinities.keystone4j.common.Config.Type;
import com.infinities.keystone4j.jpa.AbstractDao;
import com.infinities.keystone4j.model.assignment.Project;
import com.infinities.keystone4j.model.assignment.RoleAssignment;
import com.infinities.keystone4j.model.assignment.RoleAssignment.AssignmentType;
public class RoleAssignmentDao extends AbstractDao<RoleAssignment> {
public RoleAssignmentDao() {
super(RoleAssignment.class);
}
public List<String> listUserIdsForProject(String projectid) {
EntityManager em = getEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery(String.class);
Root<RoleAssignment> root = cq.from(getEntityType());
Path<RoleAssignment.AssignmentType> path = root.get("type");
List<Predicate> predicates = Lists.newArrayList();
Predicate typePredicate = cb.equal(path, RoleAssignment.AssignmentType.USER_PROJECT);
predicates.add(typePredicate);
Predicate targetPredicate = cb.equal(root.get("targetId"), projectid);
predicates.add(targetPredicate);
cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
cq.select(root.<String> get("actorId"));
cq.distinct(true);
TypedQuery<String> q = em.createQuery(cq);
List<String> actorIds = q.getResultList();
return actorIds;
}
public RoleAssignment getGrant(String roleid, String targetid, String actorid, boolean inheritedToProjects) {
EntityManager em = getEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<RoleAssignment> cq = cb.createQuery(RoleAssignment.class);
Root<RoleAssignment> root = cq.from(getEntityType());
List<Predicate> predicates = Lists.newArrayList();
Predicate actorPredicate = cb.equal(root.get("actorId"), actorid);
predicates.add(actorPredicate);
Predicate targetPredicate = cb.equal(root.get("targetId"), targetid);
predicates.add(targetPredicate);
Predicate rolePredicate = cb.equal(root.get("role").get("id"), roleid);
predicates.add(rolePredicate);
cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
cq.select(root);
TypedQuery<RoleAssignment> q = em.createQuery(cq);
return q.getSingleResult();
}
public List<RoleAssignment> listRoleAssignmentsForActors(List<String> actorList) {
EntityManager em = getEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<RoleAssignment> cq = cb.createQuery(RoleAssignment.class);
Root<RoleAssignment> root = cq.from(getEntityType());
List<Predicate> predicates = Lists.newArrayList();
Predicate actorPredicate = root.get("actorId").in(actorList);
predicates.add(actorPredicate);
cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
cq.select(root);
TypedQuery<RoleAssignment> q = em.createQuery(cq);
return q.getResultList();
}
public List<String> getGroupProjectRoles(List<String> groups, String projectid, String projectDomainId,
AssignmentDriver driver) throws Exception {
if (groups.isEmpty()) {
return new ArrayList<String>();
}
EntityManager em = getEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery(String.class);
Root<RoleAssignment> root = cq.from(getEntityType());
Predicate predicate1 = cb.and(cb.equal(root.get("type"), AssignmentType.GROUP_PROJECT),
cb.isFalse(root.<Boolean> get("inherited")), cb.equal(root.get("targetId"), projectid));
if (Config.getOpt(Type.os_inherit, "enabled").asBoolean()) {
Predicate predicate2 = cb.and(cb.equal(root.get("type"), AssignmentType.GROUP_DOMAIN),
cb.isTrue(root.<Boolean> get("inherited")), cb.equal(root.get("targetId"), projectDomainId));
predicate1 = cb.or(predicate1, predicate2);
List<String> projectParents = new ArrayList<String>();
for (Project project : driver.listProjectParents(projectid)) {
projectParents.add(project.getId());
}
if (!projectParents.isEmpty()) {
Predicate predicate3 = cb.and(cb.equal(root.get("type"), AssignmentType.GROUP_PROJECT),
cb.isTrue(root.<Boolean> get("inherited")), root.get("targetId").in(projectDomainId));
predicate1 = cb.or(predicate1, predicate3);
}
}
predicate1 = cb.and(predicate1, root.get("actorId").in(groups));
cq.where(predicate1);
cq.select(root.<String> get("role").<String> get("id")).distinct(true);
TypedQuery<String> q = em.createQuery(cq);
List<String> roleIds = q.getResultList();
return roleIds;
}
public void removeByRoleId(String roleid) {
EntityManager em = getEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<RoleAssignment> cq = cb.createQuery(RoleAssignment.class);
Root<RoleAssignment> root = cq.from(getEntityType());
List<Predicate> predicates = Lists.newArrayList();
Predicate rolePredicate = cb.equal(root.get("role").get("id"), roleid);
predicates.add(rolePredicate);
cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
cq.select(root);
TypedQuery<RoleAssignment> q = em.createQuery(cq);
List<RoleAssignment> roleAssignments = q.getResultList();
for (RoleAssignment ref : roleAssignments) {
remove(ref);
}
}
public void removeByActorId(String actorid) {
EntityManager em = getEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<RoleAssignment> cq = cb.createQuery(RoleAssignment.class);
Root<RoleAssignment> root = cq.from(getEntityType());
List<Predicate> predicates = Lists.newArrayList();
Predicate rolePredicate = cb.equal(root.get("actorId"), actorid);
predicates.add(rolePredicate);
cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
cq.select(root);
TypedQuery<RoleAssignment> q = em.createQuery(cq);
List<RoleAssignment> roleAssignments = q.getResultList();
for (RoleAssignment ref : roleAssignments) {
remove(ref);
}
}
public List<RoleAssignment> findAll(AssignmentType type, String actorId, String targetId) {
EntityManager em = getEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<RoleAssignment> cq = cb.createQuery(RoleAssignment.class);
Root<RoleAssignment> root = cq.from(getEntityType());
List<Predicate> predicates = Lists.newArrayList();
Predicate actorPredicate = cb.equal(root.get("actorId"), actorId);
predicates.add(actorPredicate);
Predicate targetPredicate = cb.equal(root.get("targetId"), targetId);
predicates.add(targetPredicate);
Predicate typePredicate = cb.equal(root.get("type"), type);
predicates.add(typePredicate);
cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
cq.select(root);
TypedQuery<RoleAssignment> q = em.createQuery(cq);
return q.getResultList();
}
}
| 43.513514
| 110
| 0.73913
|
83e15dbfd7ffb2a3dcdac204c6ffa505b2b94f92
| 2,140
|
package com.taobao.api;
import java.util.Date;
import java.util.List;
import com.taobao.api.domain.DiscardInfo;
import com.taobao.api.domain.NotifyTrade;
import com.taobao.api.request.CometDiscardinfoGetRequest;
import com.taobao.api.request.IncrementCustomerPermitRequest;
import com.taobao.api.request.IncrementTradesGetRequest;
import com.taobao.api.response.CometDiscardinfoGetResponse;
import com.taobao.api.response.IncrementTradesGetResponse;
/**
* 主动通知业务API
*
* @author Simon Leung
*
*/
public class StreamApi {
private ImprovedTaobaoClient taobaoClient;
public StreamApi(ImprovedTaobaoClient taobaoClient) {
this.taobaoClient = taobaoClient;
}
/**
* 为用户开通主动通知业务 <a href="http://api.taobao.com/apidoc/api.htm?path=cid:39-apiId:10882">taobao.increment.customer.permit </a>
*
* @param session
*/
public void permitCustomer(String session) {
IncrementCustomerPermitRequest request = new IncrementCustomerPermitRequest();
taobaoClient.execute(request, session);
}
/**
* 获取在某时段丢失了的主动通知消息(用户、时间段、类型)
*
* @param start 开始时间
* @param end 结束时间 (start与end之间的时间间隔不能超过1个小时)
* @return
*/
public List<DiscardInfo> getDiscardInfos(Date start, Date end) {
CometDiscardinfoGetRequest request = new CometDiscardinfoGetRequest();
request.setStart(start);
request.setEnd(end);
CometDiscardinfoGetResponse response = taobaoClient.execute(request);
return response.getDiscardInfoList();
}
public PagingResult<NotifyTrade> getIncrementTrades(String nick, Date startModified, Date endModified, Long pageNo) {
Long pageSize = 50L;
IncrementTradesGetRequest request = new IncrementTradesGetRequest();
request.setNick(nick);
request.setStartModified(startModified);
request.setEndModified(endModified);
request.setPageNo(pageNo);
request.setPageSize(pageSize);
IncrementTradesGetResponse response = taobaoClient.execute(request);
List<NotifyTrade> data = response.getNotifyTrades();
long total = response.getTotalResults();
return new PagingResult<NotifyTrade>(data, pageSize, pageNo, total);
}
}
| 31.014493
| 125
| 0.751869
|
24f6bc85c7137859bf7c32cc5828d17e291af0a2
| 3,744
|
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH under
* one or more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
* Licensed under the Zeebe Community License 1.1. You may not use this file
* except in compliance with the Zeebe Community License 1.1.
*/
package io.camunda.zeebe.engine.state.message;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatNoException;
import io.camunda.zeebe.engine.state.message.TransientSubscriptionCommandState.CommandEntry;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TransientSubscriptionCommandStateTest {
private TransientSubscriptionCommandState sut;
@BeforeEach
public void setUp() {
sut = new TransientSubscriptionCommandState();
}
@Test
public void shouldReturnNoEntriesByDefault() {
// when
final var actual = sut.getEntriesBefore(Long.MAX_VALUE);
// then
assertThat(actual).isEmpty();
}
@Test
public void shouldReturnEntriesBeforeDeadline() {
// when
final var expected = new CommandEntry(1, "message", 500);
sut.add(expected);
sut.add(new CommandEntry(2, "message", 2000));
// when
final var actual = sut.getEntriesBefore(1000);
// then
assertThat(actual).containsExactly(expected);
}
@Test
public void shouldReturnEntriesOrderedBySentTime() {
// when
final var first = new CommandEntry(1, "message", 500);
final var second = new CommandEntry(2, "message", 600);
final var third = new CommandEntry(3, "message", 700);
sut.add(second);
sut.add(first);
sut.add(third);
// when
final var actual = sut.getEntriesBefore(1000);
// then
assertThat(actual).containsExactly(first, second, third);
}
@Test
public void shouldOverwriteExistingEntries() {
// when
final var first = new CommandEntry(1, "message", 500);
final var second = new CommandEntry(1, "message", 600);
sut.add(first);
sut.add(second);
// when
final var actual = sut.getEntriesBefore(1000);
// then
assertThat(actual).containsExactly(second);
}
@Test
public void shouldAcceptEntriesWithTheSameSentTime() {
// when
sut.add(new CommandEntry(1, "message", 500));
sut.add(new CommandEntry(2, "message", 500));
// when
final var actual = sut.getEntriesBefore(1000);
// then
assertThat(actual).hasSize(2);
}
@Test
public void shouldReturnEntriesBasedOnUpdatedSentTime() {
// when
sut.add(new CommandEntry(1, "message", 3000));
sut.add(new CommandEntry(2, "message", 2000));
// when
final var expected = new CommandEntry(1, "message", 500);
sut.updateCommandSentTime(expected);
final var actual = sut.getEntriesBefore(1000);
// then
assertThat(actual).containsExactly(expected);
}
@Test
public void shouldNotReturnEntriesThatHaveBeenRemoved() {
// when
sut.add(new CommandEntry(1, "message", 500));
sut.add(new CommandEntry(2, "message", 2000));
// when
sut.remove(new CommandEntry(1, "message", 500));
final var actual = sut.getEntriesBefore(1000);
// then
assertThat(actual).isEmpty();
}
@Test
public void shouldBeTolerantWhenRemovingEntriesThatDoNotExist() {
// when + then
assertThatNoException().isThrownBy(() -> sut.remove(new CommandEntry(1, "message", 500)));
}
@Test
public void shouldBeTolerantWhenUpdatingEntriesThatDoNotExist() {
// when + then
assertThatNoException()
.isThrownBy(() -> sut.updateCommandSentTime(new CommandEntry(1, "message", 500)));
}
}
| 27.130435
| 94
| 0.69765
|
64cc8108596da463d5ed3d472d7eb28e2e4b540f
| 15,097
|
package com.hbm.render.tileentity;
import org.lwjgl.opengl.GL11;
import com.hbm.blocks.ModBlocks;
import com.hbm.lib.RefStrings;
import com.hbm.main.ResourceManager;
import com.hbm.render.model.ModelBroadcaster;
import com.hbm.render.model.ModelGeiger;
import com.hbm.render.model.ModelRadio;
import com.hbm.render.model.ModelSteelBeam;
import com.hbm.render.model.ModelSteelCorner;
import com.hbm.render.model.ModelSteelRoof;
import com.hbm.render.model.ModelSteelScaffold;
import com.hbm.render.model.ModelSteelWall;
import com.hbm.tileentity.deco.TileEntityBomber;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ResourceLocation;
public class RenderDecoBlock extends TileEntitySpecialRenderer {
private static final ResourceLocation texture1 = new ResourceLocation(RefStrings.MODID + ":" + "textures/models/SteelWall.png");
private static final ResourceLocation texture2 = new ResourceLocation(RefStrings.MODID + ":" + "textures/models/SteelCorner.png");
private static final ResourceLocation texture3 = new ResourceLocation(RefStrings.MODID + ":" + "textures/models/SteelRoof.png");
private static final ResourceLocation texture4 = new ResourceLocation(RefStrings.MODID + ":" + "textures/models/SteelBeam.png");
private static final ResourceLocation texture5 = new ResourceLocation(RefStrings.MODID + ":" + "textures/models/SteelScaffold.png");
private static final ResourceLocation texture6 = new ResourceLocation(RefStrings.MODID + ":" + "textures/models/ModelBroadcaster.png");
private static final ResourceLocation texture7 = new ResourceLocation(RefStrings.MODID + ":" + "textures/models/ModelRadio.png");
private static final ResourceLocation texture8 = new ResourceLocation(RefStrings.MODID + ":" + "textures/models/ModelRadioReceiver.png");
private static final ResourceLocation texture9 = new ResourceLocation(RefStrings.MODID + ":" + "textures/models/ModelGeiger.png");
private ModelSteelWall model1;
private ModelSteelCorner model2;
private ModelSteelRoof model3;
private ModelSteelBeam model4;
private ModelSteelScaffold model5;
private ModelBroadcaster model6;
private ModelRadio model7;
private ModelGeiger model8;
public RenderDecoBlock() {
this.model1 = new ModelSteelWall();
this.model2 = new ModelSteelCorner();
this.model3 = new ModelSteelRoof();
this.model4 = new ModelSteelBeam();
this.model5 = new ModelSteelScaffold();
this.model6 = new ModelBroadcaster();
this.model7 = new ModelRadio();
this.model8 = new ModelGeiger();
}
@Override
public void renderTileEntityAt(TileEntity tileentity, double x, double y, double z, float f) {
GL11.glPushMatrix();
GL11.glTranslatef((float) x + 0.5F, (float) y + 1.5F, (float) z + 0.5F);
GL11.glRotatef(180, 0F, 0F, 1F);
GL11.glEnable(GL11.GL_LIGHTING);
if(tileentity.getWorldObj().getBlock(tileentity.xCoord, tileentity.yCoord, tileentity.zCoord) == ModBlocks.steel_wall)
{
this.bindTexture(texture1);
switch(tileentity.getBlockMetadata())
{
case 4:
GL11.glRotatef(90, 0F, 1F, 0F); break;
case 2:
GL11.glRotatef(180, 0F, 1F, 0F); break;
case 5:
GL11.glRotatef(270, 0F, 1F, 0F); break;
case 3:
GL11.glRotatef(0, 0F, 1F, 0F); break;
}
}
if(tileentity.getWorldObj().getBlock(tileentity.xCoord, tileentity.yCoord, tileentity.zCoord) == ModBlocks.steel_corner)
{
this.bindTexture(texture2);
switch(tileentity.getBlockMetadata())
{
case 4:
GL11.glRotatef(90, 0F, 1F, 0F); break;
case 2:
GL11.glRotatef(180, 0F, 1F, 0F); break;
case 5:
GL11.glRotatef(270, 0F, 1F, 0F); break;
case 3:
GL11.glRotatef(0, 0F, 1F, 0F); break;
}
}
if(tileentity.getWorldObj().getBlock(tileentity.xCoord, tileentity.yCoord, tileentity.zCoord) == ModBlocks.steel_roof)
{
this.bindTexture(texture3);
}
if(tileentity.getWorldObj().getBlock(tileentity.xCoord, tileentity.yCoord, tileentity.zCoord) == ModBlocks.steel_beam)
{
this.bindTexture(texture4);
}
if(tileentity.getWorldObj().getBlock(tileentity.xCoord, tileentity.yCoord, tileentity.zCoord) == ModBlocks.steel_scaffold)
{
this.bindTexture(texture5);
switch(tileentity.getBlockMetadata())
{
case 4:
GL11.glRotatef(90, 0F, 1F, 0F); break;
case 2:
GL11.glRotatef(0, 0F, 1F, 0F); break;
case 5:
GL11.glRotatef(90, 0F, 1F, 0F); break;
case 3:
GL11.glRotatef(0, 0F, 1F, 0F); break;
}
}
if(tileentity.getWorldObj().getBlock(tileentity.xCoord, tileentity.yCoord, tileentity.zCoord) == ModBlocks.broadcaster_pc)
{
this.bindTexture(texture6);
switch(tileentity.getBlockMetadata())
{
case 4:
GL11.glRotatef(90, 0F, 1F, 0F); break;
case 2:
GL11.glRotatef(180, 0F, 1F, 0F); break;
case 5:
GL11.glRotatef(270, 0F, 1F, 0F); break;
case 3:
GL11.glRotatef(0, 0F, 1F, 0F); break;
}
}
if(tileentity.getWorldObj().getBlock(tileentity.xCoord, tileentity.yCoord, tileentity.zCoord) == ModBlocks.geiger)
{
this.bindTexture(texture9);
switch(tileentity.getBlockMetadata())
{
case 4:
GL11.glRotatef(90, 0F, 1F, 0F); break;
case 2:
GL11.glRotatef(180, 0F, 1F, 0F); break;
case 5:
GL11.glRotatef(270, 0F, 1F, 0F); break;
case 3:
GL11.glRotatef(0, 0F, 1F, 0F); break;
}
}
if(tileentity.getWorldObj().getBlock(tileentity.xCoord, tileentity.yCoord, tileentity.zCoord) == ModBlocks.radiorec)
{
this.bindTexture(texture8);
switch(tileentity.getBlockMetadata())
{
case 4:
GL11.glRotatef(90, 0F, 1F, 0F); break;
case 2:
GL11.glRotatef(180, 0F, 1F, 0F); break;
case 5:
GL11.glRotatef(270, 0F, 1F, 0F); break;
case 3:
GL11.glRotatef(0, 0F, 1F, 0F); break;
}
}
if(tileentity.getWorldObj().getBlock(tileentity.xCoord, tileentity.yCoord, tileentity.zCoord) == ModBlocks.radiobox)
{
this.bindTexture(texture7);
switch(tileentity.getBlockMetadata())
{
case 4:
case 8:
GL11.glRotatef(270, 0F, 1F, 0F); break;
case 2:
case 6:
GL11.glRotatef(0, 0F, 1F, 0F); break;
case 5:
case 9:
GL11.glRotatef(90, 0F, 1F, 0F); break;
case 3:
case 7:
GL11.glRotatef(180, 0F, 1F, 0F); break;
}
GL11.glTranslatef(0, 0, 1);
}
GL11.glPushMatrix();
if(tileentity.getWorldObj().getBlock(tileentity.xCoord, tileentity.yCoord, tileentity.zCoord) == ModBlocks.steel_wall)
this.model1.renderModel(0.0625F);
if(tileentity.getWorldObj().getBlock(tileentity.xCoord, tileentity.yCoord, tileentity.zCoord) == ModBlocks.steel_corner)
this.model2.renderModel(0.0625F);
if(tileentity.getWorldObj().getBlock(tileentity.xCoord, tileentity.yCoord, tileentity.zCoord) == ModBlocks.steel_roof)
this.model3.renderModel(0.0625F);
if(tileentity.getWorldObj().getBlock(tileentity.xCoord, tileentity.yCoord, tileentity.zCoord) == ModBlocks.steel_beam)
this.model4.renderModel(0.0625F);
if(tileentity.getWorldObj().getBlock(tileentity.xCoord, tileentity.yCoord, tileentity.zCoord) == ModBlocks.steel_scaffold)
this.model5.renderModel(0.0625F);
if(tileentity.getWorldObj().getBlock(tileentity.xCoord, tileentity.yCoord, tileentity.zCoord) == ModBlocks.broadcaster_pc)
this.model6.renderModel(0.0625F);
if(tileentity.getWorldObj().getBlock(tileentity.xCoord, tileentity.yCoord, tileentity.zCoord) == ModBlocks.geiger)
this.model8.renderModel(0.0625F);
if(tileentity.getWorldObj().getBlock(tileentity.xCoord, tileentity.yCoord, tileentity.zCoord) == ModBlocks.radiobox)
this.model7.renderModel(0.0625F, tileentity.getBlockMetadata() > 5 ? 160 : 20);
if(tileentity.getWorldObj().getBlock(tileentity.xCoord, tileentity.yCoord, tileentity.zCoord) == ModBlocks.radiorec)
this.model6.renderModel(0.0625F);
GL11.glPopMatrix();
if(tileentity.getWorldObj().getBlock(tileentity.xCoord, tileentity.yCoord, tileentity.zCoord) == ModBlocks.boxcar) {
GL11.glTranslatef(0, 0, -1.5F);
GL11.glRotated(90, 1, 0, 0);
GL11.glDisable(GL11.GL_CULL_FACE);
bindTexture(ResourceManager.boxcar_tex);
ResourceManager.boxcar.renderAll();
GL11.glEnable(GL11.GL_CULL_FACE);
}
if(tileentity.getWorldObj().getBlock(tileentity.xCoord, tileentity.yCoord, tileentity.zCoord) == ModBlocks.boat) {
GL11.glRotatef(180, 0F, 0F, 1F);
GL11.glTranslatef(0, 0, -1.5F);
GL11.glTranslatef(0, 0.5F, 0);
GL11.glEnable(GL11.GL_CULL_FACE);
bindTexture(ResourceManager.duchessgambit_tex);
ResourceManager.duchessgambit.renderAll();
}
if(tileentity instanceof TileEntityBomber)
{
TileEntityBomber bomber = (TileEntityBomber)tileentity;
float yaw = (float)(((double)bomber.yaw) / 180D * Math.PI);
float pitch = (float)(((double)bomber.pitch) / 180D * Math.PI);
GL11.glRotatef(yaw - 90.0F, 0.0F, 1.0F, 0.0F);
GL11.glRotatef(90, 0F, 0F, 1F);
GL11.glRotatef(pitch, 0.0F, 0.0F, 1.0F);
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_CULL_FACE);
GL11.glScalef(5F, 5F, 5F);
int i = bomber.type;
switch(i) {
case 0: bindTexture(ResourceManager.dornier_0_tex); break;
case 1: bindTexture(ResourceManager.dornier_1_tex); break;
case 2: bindTexture(ResourceManager.dornier_2_tex); break;
default: bindTexture(ResourceManager.dornier_1_tex); break;
}
ResourceManager.dornier.renderAll();
}
if(tileentity.getWorldObj().getBlock(tileentity.xCoord, tileentity.yCoord, tileentity.zCoord) == ModBlocks.sat_radar) {
GL11.glRotatef(180, 0F, 0F, 1F);
GL11.glTranslatef(0, -1.5F, 0);
GL11.glRotated(90, 0, 1, 0);
switch(tileentity.getBlockMetadata())
{
case 4:
GL11.glRotatef(270, 0F, 1F, 0F); break;
case 2:
GL11.glRotatef(180, 0F, 1F, 0F); break;
case 5:
GL11.glRotatef(90, 0F, 1F, 0F); break;
case 3:
GL11.glRotatef(0, 0F, 1F, 0F); break;
}
GL11.glEnable(GL11.GL_CULL_FACE);
bindTexture(ResourceManager.sat_base_tex);
ResourceManager.sat_base.renderAll();
bindTexture(ResourceManager.sat_radar_tex);
ResourceManager.sat_radar.renderAll();
}
if(tileentity.getWorldObj().getBlock(tileentity.xCoord, tileentity.yCoord, tileentity.zCoord) == ModBlocks.sat_resonator) {
GL11.glRotatef(180, 0F, 0F, 1F);
GL11.glTranslatef(0, -1.5F, 0);
GL11.glRotated(90, 0, 1, 0);
switch(tileentity.getBlockMetadata())
{
case 4:
GL11.glRotatef(270, 0F, 1F, 0F); break;
case 2:
GL11.glRotatef(180, 0F, 1F, 0F); break;
case 5:
GL11.glRotatef(90, 0F, 1F, 0F); break;
case 3:
GL11.glRotatef(0, 0F, 1F, 0F); break;
}
GL11.glEnable(GL11.GL_CULL_FACE);
bindTexture(ResourceManager.sat_base_tex);
ResourceManager.sat_base.renderAll();
bindTexture(ResourceManager.sat_resonator_tex);
ResourceManager.sat_resonator.renderAll();
}
if(tileentity.getWorldObj().getBlock(tileentity.xCoord, tileentity.yCoord, tileentity.zCoord) == ModBlocks.sat_scanner) {
GL11.glRotatef(180, 0F, 0F, 1F);
GL11.glTranslatef(0, -1.5F, 0);
GL11.glRotated(90, 0, 1, 0);
switch(tileentity.getBlockMetadata())
{
case 4:
GL11.glRotatef(270, 0F, 1F, 0F); break;
case 2:
GL11.glRotatef(180, 0F, 1F, 0F); break;
case 5:
GL11.glRotatef(90, 0F, 1F, 0F); break;
case 3:
GL11.glRotatef(0, 0F, 1F, 0F); break;
}
GL11.glEnable(GL11.GL_CULL_FACE);
bindTexture(ResourceManager.sat_base_tex);
ResourceManager.sat_base.renderAll();
bindTexture(ResourceManager.sat_scanner_tex);
ResourceManager.sat_scanner.renderAll();
}
if(tileentity.getWorldObj().getBlock(tileentity.xCoord, tileentity.yCoord, tileentity.zCoord) == ModBlocks.sat_mapper) {
GL11.glRotatef(180, 0F, 0F, 1F);
GL11.glTranslatef(0, -1.5F, 0);
GL11.glRotated(90, 0, 1, 0);
switch(tileentity.getBlockMetadata())
{
case 4:
GL11.glRotatef(270, 0F, 1F, 0F); break;
case 2:
GL11.glRotatef(180, 0F, 1F, 0F); break;
case 5:
GL11.glRotatef(90, 0F, 1F, 0F); break;
case 3:
GL11.glRotatef(0, 0F, 1F, 0F); break;
}
GL11.glEnable(GL11.GL_CULL_FACE);
bindTexture(ResourceManager.sat_base_tex);
ResourceManager.sat_base.renderAll();
bindTexture(ResourceManager.sat_mapper_tex);
ResourceManager.sat_mapper.renderAll();
}
if(tileentity.getWorldObj().getBlock(tileentity.xCoord, tileentity.yCoord, tileentity.zCoord) == ModBlocks.sat_laser) {
GL11.glRotatef(180, 0F, 0F, 1F);
GL11.glTranslatef(0, -1.5F, 0);
GL11.glRotated(90, 0, 1, 0);
switch(tileentity.getBlockMetadata())
{
case 4:
GL11.glRotatef(270, 0F, 1F, 0F); break;
case 2:
GL11.glRotatef(180, 0F, 1F, 0F); break;
case 5:
GL11.glRotatef(90, 0F, 1F, 0F); break;
case 3:
GL11.glRotatef(0, 0F, 1F, 0F); break;
}
GL11.glEnable(GL11.GL_CULL_FACE);
bindTexture(ResourceManager.sat_base_tex);
ResourceManager.sat_base.renderAll();
bindTexture(ResourceManager.sat_laser_tex);
ResourceManager.sat_laser.renderAll();
}
if(tileentity.getWorldObj().getBlock(tileentity.xCoord, tileentity.yCoord, tileentity.zCoord) == ModBlocks.sat_foeq) {
GL11.glRotatef(180, 0F, 0F, 1F);
GL11.glTranslatef(0, -1.5F, 0);
GL11.glRotated(90, 0, 1, 0);
switch(tileentity.getBlockMetadata())
{
case 4:
GL11.glRotatef(270, 0F, 1F, 0F); break;
case 2:
GL11.glRotatef(180, 0F, 1F, 0F); break;
case 5:
GL11.glRotatef(90, 0F, 1F, 0F); break;
case 3:
GL11.glRotatef(0, 0F, 1F, 0F); break;
}
GL11.glEnable(GL11.GL_CULL_FACE);
bindTexture(ResourceManager.sat_foeq_tex);
ResourceManager.sat_foeq.renderAll();
}
if(tileentity.getWorldObj().getBlock(tileentity.xCoord, tileentity.yCoord, tileentity.zCoord) == ModBlocks.sat_dock) {
GL11.glRotatef(180, 0F, 0F, 1F);
GL11.glTranslatef(0, -1.5F, 0);
bindTexture(ResourceManager.satdock_tex);
ResourceManager.satDock.renderAll();
}
GL11.glPopMatrix();
}
}
| 36.91198
| 139
| 0.652315
|
daad2066f92f58d1ae4f032f093ca4481924a47c
| 805
|
package com.example.application.backend.entities;
import javax.persistence.*;
/**
* This is a basic setting class.
*
* @author Jessica Reistel, Laura Neuendorf and Sabrine Gamdou
* @version 4.0
* @since 21-12-2020
* @lastUpdated 05.02.2021 by Laura Neuendorf
*/
@Entity(name ="settings")
public class SettingEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name ="setting_id")
private int settingsId;
private boolean darkmode;
public int getSettingsId() {
return settingsId;
}
public void setSettingsId(int settingsId) {
this.settingsId = settingsId;
}
public boolean getDarkmode() {
return darkmode;
}
public void setDarkmode(boolean darkmode) {
this.darkmode = darkmode;
}
}
| 19.634146
| 63
| 0.668323
|
80211b88f3c974442b96a66e5621cce47ea975b7
| 4,648
|
/*
* Copyright 2015 Netflix, 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.netflix.spinnaker.clouddriver.cache;
import com.netflix.spectator.api.Registry;
import com.netflix.spinnaker.cats.agent.AgentLock;
import com.netflix.spinnaker.cats.agent.AgentScheduler;
import com.netflix.spinnaker.cats.agent.DefaultAgentScheduler;
import com.netflix.spinnaker.cats.agent.ExecutionInstrumentation;
import com.netflix.spinnaker.cats.cache.Cache;
import com.netflix.spinnaker.cats.cache.NamedCacheFactory;
import com.netflix.spinnaker.cats.mem.InMemoryNamedCacheFactory;
import com.netflix.spinnaker.cats.module.CatsModule;
import com.netflix.spinnaker.cats.provider.Provider;
import com.netflix.spinnaker.cats.provider.ProviderRegistry;
import com.netflix.spinnaker.clouddriver.search.SearchProvider;
import com.netflix.spinnaker.fiat.shared.FiatPermissionEvaluator;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan({
"com.netflix.spinnaker.clouddriver.cache",
})
@EnableConfigurationProperties(CatsInMemorySearchProperties.class)
public class CacheConfig {
@Bean
@ConditionalOnMissingBean(NamedCacheFactory.class)
NamedCacheFactory namedCacheFactory() {
return new InMemoryNamedCacheFactory();
}
@Bean
@ConditionalOnMissingBean(AgentScheduler.class)
@ConditionalOnProperty(value = "caching.write-enabled", matchIfMissing = true)
AgentScheduler agentScheduler() {
return new DefaultAgentScheduler(60, TimeUnit.SECONDS);
}
@Bean
@ConditionalOnProperty(value = "caching.write-enabled", havingValue = "false")
@ConditionalOnMissingBean(AgentScheduler.class)
AgentScheduler noopAgentScheduler() {
return (agent, agentExecution, executionInstrumentation) -> {
// do nothing
};
}
@Bean
@ConditionalOnMissingBean(CatsModule.class)
CatsModule catsModule(
List<Provider> providers,
List<ExecutionInstrumentation> executionInstrumentation,
NamedCacheFactory cacheFactory,
AgentScheduler agentScheduler) {
return new CatsModule.Builder()
.cacheFactory(cacheFactory)
.scheduler(agentScheduler)
.instrumentation(executionInstrumentation)
.build(providers);
}
@Bean
Cache cacheView(CatsModule catsModule) {
return catsModule.getView();
}
@Bean
ProviderRegistry providerRegistry(CatsModule catsModule) {
return catsModule.getProviderRegistry();
}
@Bean
ExecutionInstrumentation loggingInstrumentation() {
return new LoggingInstrumentation();
}
@Bean
ExecutionInstrumentation metricInstrumentation(Registry registry) {
return new MetricInstrumentation(registry);
}
@Bean
OnDemandCacheUpdater catsOnDemandCacheUpdater(
List<Provider> providers,
CatsModule catsModule,
AgentScheduler<? extends AgentLock> agentScheduler) {
return new CatsOnDemandCacheUpdater(providers, catsModule, agentScheduler);
}
@Bean
@ConditionalOnProperty(value = "caching.search.enabled", matchIfMissing = true)
SearchProvider catsSearchProvider(
CatsInMemorySearchProperties catsInMemorySearchProperties,
Cache cacheView,
List<SearchableProvider> providers,
ProviderRegistry providerRegistry,
Optional<FiatPermissionEvaluator> permissionEvaluator,
Optional<List<KeyParser>> keyParsers) {
return new CatsSearchProvider(
catsInMemorySearchProperties,
cacheView,
providers,
providerRegistry,
permissionEvaluator,
keyParsers);
}
@Bean
@ConditionalOnMissingBean(SearchableProvider.class)
SearchableProvider noopSearchableProvider() {
return new NoopSearchableProvider();
}
}
| 34.176471
| 81
| 0.779475
|
f7b6fc59e7f598d2cd6e5af19973bdb68feb1e56
| 5,308
|
/*
* 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.logging.log4j.samples.dto;
import org.apache.logging.log4j.ThreadContext;
import org.apache.logging.log4j.core.util.UuidUtil;
/**
*
*/
public final class RequestContext {
private RequestContext() {
}
// Unique token to identify this request.
public static final String REQUEST_ID = "id";
// Token used to correlate multiple events within the request.
public static final String TRANSACTION_ID = "transId";
// The requested resource.
public static final String REQUEST_URI = "requestURI";
// Identify the user's session - should never contain the HTTP SessionId.
public static final String SESSION_ID = "sessionId";
// The id the user logged in with.
public static final String LOGIN_ID = "loginId";
// The id the system associates with the user.
public static final String USER_ID = "userId";
// user, admin, etc.
public static final String USER_TYPE = "userType";
// client id in a multi-tenant application
public static final String CLIENT_ID = "clientId";
// The user's ipAddress.
public static final String IP_ADDRESS = "ipAddress";
// The name of the product.
public static final String PRODUCT_NAME = "productName";
// The product version.
public static final String PRODUCT_VERSION = "productVersion";
// The users locale.
public static final String LOCALE = "locale";
// prod, preprod, beta, dev, etc.
public static final String REGION = "region";
// The user agent string from the browser.
public static final String USER_AGENT = "userAgent";
public static void initialize() {
ThreadContext.clearMap();
ThreadContext.put(REQUEST_ID, UuidUtil.getTimeBasedUuid().toString());
}
public static String getId() {
return ThreadContext.get(REQUEST_ID);
}
public static void setSessionId(final String id) {
ThreadContext.put(SESSION_ID, id);
}
public static String getSessionId() {
return ThreadContext.get(SESSION_ID);
}
public static void setTransId(final String id) {
ThreadContext.put(TRANSACTION_ID, id);
}
public static String getTransId() {
return ThreadContext.get(TRANSACTION_ID);
}
public static void setRequestURI(final String URI) {
ThreadContext.put(REQUEST_URI, URI);
}
public static String getRequestURI() {
return ThreadContext.get(REQUEST_URI);
}
public static void setLoginId(final String id) {
ThreadContext.put(LOGIN_ID, id);
}
public static String getLoginId() {
return ThreadContext.get(LOGIN_ID);
}
public static void setUserId(final String id) {
ThreadContext.put(USER_ID, id);
}
public static String getUserId() {
return ThreadContext.get(USER_ID);
}
public static void setUserType(final String type) {
ThreadContext.put(USER_TYPE, type);
}
public static String getUserType() {
return ThreadContext.get(USER_TYPE);
}
public static void setClientId(final String id) {
ThreadContext.put(CLIENT_ID, id);
}
public static String getClientId() {
return ThreadContext.get(CLIENT_ID);
}
public static void setIpAddress(final String addr) {
ThreadContext.put(IP_ADDRESS, addr);
}
public static String getIpAddress() {
return ThreadContext.get(IP_ADDRESS);
}
public static void setProductName(final String productName) {
ThreadContext.put(PRODUCT_NAME, productName);
}
public static String getProductName() {
return ThreadContext.get(PRODUCT_NAME);
}
public static void setProductVersion(final String productVersion) {
ThreadContext.put(PRODUCT_VERSION, productVersion);
}
public static String getProductVersion() {
return ThreadContext.get(PRODUCT_VERSION);
}
public static void setLocale(final String locale) {
ThreadContext.put(LOCALE, locale);
}
public static String getLocale() {
return ThreadContext.get(LOCALE);
}
public static void setRegion(final String region) {
ThreadContext.put(REGION, region);
}
public static String getRegion() {
return ThreadContext.get(REGION);
}
public static void setUserAgent(final String agent) {
ThreadContext.put(USER_AGENT, agent);
}
public static String getUserAgent() {
return ThreadContext.get(USER_AGENT);
}
}
| 30.682081
| 78
| 0.687641
|
a0e422f98c3c9c599d7b057533c309956816c9b2
| 319
|
package com.talkingdata.dmpplus.dao;
import java.util.List;
import com.talkingdata.dmpplus.dao.entity.UserAppMapping;
public interface UserAppMappingMapper {
UserAppMapping selectByPrimaryKey(String id);
List<UserAppMapping> selectByUserId(String userId);
List<UserAppMapping> selectByAppId(String appId);
}
| 22.785714
| 57
| 0.815047
|
d509ba545ac4a4f8678c6dc9572c8bf211a15fb6
| 1,127
|
package it.unica.foresee.tests;
import it.unica.foresee.datasets.DatasetElement;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import it.unica.foresee.datasets.interfaces.DoubleConvertible;
import org.junit.Test;
/**
* Test for the DatasetElement class.
*/
public class DatasetElementTest
{
@Test
public void testEquals()
{
DoubleConvertible<Double> dConverter = (d) -> d.doubleValue();
assertEquals(new DatasetElement<>(5.0, dConverter), new DatasetElement<>(5.0, dConverter));
assertEquals(new DatasetElement(5.0, dConverter), new DatasetElement(5.0, dConverter));
assertNotEquals(new DatasetElement(5.0, dConverter), new DatasetElement(7.0, dConverter));
DoubleConvertible<Integer> iConverter = (Integer d) -> d.doubleValue();
assertEquals(new DatasetElement<>(5, iConverter), new DatasetElement<>(5, iConverter));
assertEquals(new DatasetElement(5, iConverter), new DatasetElement(5, iConverter));
assertNotEquals(new DatasetElement(5, iConverter), new DatasetElement(7, iConverter));
}
}
| 37.566667
| 99
| 0.72937
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.