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
|
---|---|---|---|---|---|
79c7a680bc09814b62b49a90365018facedce9ad | 1,724 | /*
* Copyright (c) 2010-2013 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.web.page.admin.server.dto;
import com.evolveum.midpoint.prism.query.builder.S_AtomicFilterEntry;
import com.evolveum.midpoint.util.exception.SystemException;
import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskExecutionStatusType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType;
/**
* Possible values that can be used to filter tasks by their execution status.
*
* @see com.evolveum.midpoint.task.api.TaskExecutionStatus
* @author Pavol Mederly
*/
public enum TaskDtoExecutionStatusFilter {
ALL,
RUNNING_OR_RUNNABLE,
WAITING,
SUSPENDED_OR_SUSPENDING,
CLOSED,
NOT_CLOSED;
public S_AtomicFilterEntry appendFilter(S_AtomicFilterEntry q) {
switch(this) {
case ALL: return q;
case RUNNING_OR_RUNNABLE: return q.item(TaskType.F_EXECUTION_STATUS).eq(TaskExecutionStatusType.RUNNABLE).and();
case WAITING: return q.item(TaskType.F_EXECUTION_STATUS).eq(TaskExecutionStatusType.WAITING).and();
case SUSPENDED_OR_SUSPENDING: return q.item(TaskType.F_EXECUTION_STATUS).eq(TaskExecutionStatusType.SUSPENDED).and();
case CLOSED: return q.item(TaskType.F_EXECUTION_STATUS).eq(TaskExecutionStatusType.CLOSED).and();
case NOT_CLOSED: return q.block().not().item(TaskType.F_EXECUTION_STATUS).eq(TaskExecutionStatusType.CLOSED).endBlock().and();
default: throw new SystemException("Unknown value for TaskDtoExecutionStatusFilter: " + this);
}
}
}
| 41.047619 | 138 | 0.74652 |
8fe0c6cdb52365ca1ada77affdda71a5f4293837 | 8,587 | package phantom.mvc.swagger.pluggin;
import static springfox.documentation.schema.Collections.collectionElementType;
import static springfox.documentation.schema.Collections.isContainerType;
import static springfox.documentation.swagger.common.SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER;
import com.fasterxml.classmate.ResolvedType;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiParam;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import phantom.common.UString;
import phantom.configuration.SwaggerProperties;
import phantom.reflect.UType;
import phantom.tool.validate.annotation.Mapping;
import phantom.tool.validate.annotation.Mapping.IMapping;
import phantom.tool.validate.annotation.Mapping.MappingHelper;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.schema.Example;
import springfox.documentation.service.AllowableListValues;
import springfox.documentation.service.ResolvedMethodParameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.schema.EnumTypeDeterminer;
import springfox.documentation.spi.service.ParameterBuilderPlugin;
import springfox.documentation.spi.service.contexts.ParameterContext;
import springfox.documentation.spring.web.DescriptionResolver;
import springfox.documentation.swagger.common.SwaggerPluginSupport;
/**
* 自动将@ApiModel中的数据转换为默认参数描述
* @author Frodez
*/
@Slf4j
@Component
@Profile({ "dev", "test" })
@Order(SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER + 300)
public class DefaultParamPlugin implements ParameterBuilderPlugin {
private static String param = ApiParam.class.getCanonicalName();
private static String model = ApiModel.class.getCanonicalName();
private final DescriptionResolver descriptions;
private boolean useCustomerizedPluggins = false;
@Autowired
public DefaultParamPlugin(DescriptionResolver descriptions, EnumTypeDeterminer enumTypeDeterminer,
SwaggerProperties properties) {
this.descriptions = descriptions;
this.useCustomerizedPluggins = properties.getUseCustomerizedPluggins();
}
@Override
public boolean supports(DocumentationType delimiter) {
return useCustomerizedPluggins;
}
@Override
public void apply(ParameterContext context) {
resolveParameterType(context);
if (context.resolvedMethodParameter().hasParameterAnnotation(ApiParam.class)) {
return;
}
resolveMapEnum(context);
resolveApiParam(context);
}
private void resolveParameterType(ParameterContext context) {
ResolvedMethodParameter parameter = context.resolvedMethodParameter();
ResolvedType type = context.alternateFor(parameter.getParameterType());
// Multi-part file trumps any other annotations
if (isFileType(type) || isListOfFiles(type)) {
context.parameterBuilder().parameterType("form");
return;
}
if (parameter.hasParameterAnnotation(PathVariable.class)) {
context.parameterBuilder().parameterType("path");
return;
}
if (parameter.hasParameterAnnotation(RequestBody.class)) {
context.parameterBuilder().parameterType("body");
return;
}
if (parameter.hasParameterAnnotation(RequestPart.class)) {
context.parameterBuilder().parameterType("formData");
return;
}
if (parameter.hasParameterAnnotation(RequestParam.class)) {
Set<? extends MediaType> consumes = context.getOperationContext().consumes();
HttpMethod method = context.getOperationContext().httpMethod();
if (consumes.contains(MediaType.APPLICATION_FORM_URLENCODED) && method == HttpMethod.POST) {
context.parameterBuilder().parameterType("form");
} else if (consumes.contains(MediaType.MULTIPART_FORM_DATA) && method == HttpMethod.POST) {
context.parameterBuilder().parameterType("formData");
} else {
context.parameterBuilder().parameterType("query");
}
return;
}
if (parameter.hasParameterAnnotation(RequestHeader.class)) {
context.parameterBuilder().parameterType("header");
return;
}
if (parameter.hasParameterAnnotation(ModelAttribute.class)) {
log.warn(UString.concat("@ModelAttribute annotated parameters should have already been expanded via ",
"the ExpandedParameterBuilderPlugin"));
}
if (parameter.hasParameterAnnotation(ApiParam.class)) {
context.parameterBuilder().parameterType("query");
return;
}
if (parameter.hasParameterAnnotation(Mapping.class)) {
context.parameterBuilder().parameterType("query");
return;
}
context.parameterBuilder().parameterType("body");
}
private boolean isListOfFiles(ResolvedType parameterType) {
return isContainerType(parameterType) && isFileType(collectionElementType(parameterType));
}
private boolean isFileType(ResolvedType parameterType) {
return MultipartFile.class.isAssignableFrom(parameterType.getErasedType());
}
private void resolveApiParam(ParameterContext context) {
ResolvedType resolvedType = context.resolvedMethodParameter().getParameterType();
Class<?> parameterClass = resolveParamType(resolvedType);
if (parameterClass == null) {
log.warn(UString.concat(resolvedType.getBriefDescription(), "的类型无法被DefaultParamPlugin解析"));
@SuppressWarnings("unused")
int a = 1;
return;
}
ApiModel apiModel = parameterClass.getAnnotation(ApiModel.class);
if (apiModel == null) {
if (!BeanUtils.isSimpleProperty(parameterClass)) {
warn(context, parameterClass);
}
return;
}
// 如果只有一个参数,名字就用param,否则用class的simpleName
boolean useClassName = context.getOperationContext().getParameters().size() > 1;
ParameterBuilder builder = context.parameterBuilder();
builder.name(useClassName ? parameterClass.getSimpleName() : "param");
builder.description(descriptions.resolve(apiModel.description()));
builder.allowMultiple(false);
builder.allowEmptyValue(false);
builder.hidden(false);
builder.collectionFormat("");
builder.order(SWAGGER_PLUGIN_ORDER);
}
private Class<?> resolveParamType(ResolvedType resolvedType) {
if (UType.isSimpleType(resolvedType)) {
return resolvedType.getErasedType();
} else {
List<ResolvedType> collectionResolvedTypes = UType.resolveGenericType(Collection.class, resolvedType);
if (collectionResolvedTypes == null) {
return null;
} else {
ResolvedType collectionResolvedType = collectionResolvedTypes.get(0);
if (UType.isComplexType(collectionResolvedType)) {
return null;
} else {
return collectionResolvedType.getErasedType();
}
}
}
}
private static void warn(ParameterContext context, Class<?> parameterClass) {
String pattern = context.getOperationContext().requestMappingPattern();
String parameterName = parameterClass.getCanonicalName();
log.warn(UString.concat(pattern, "的参数", parameterName, "既未配置@", param, "注解,也未配置@", model, "注解"));
}
@SneakyThrows
private void resolveMapEnum(ParameterContext context) {
Mapping enumParam = context.resolvedMethodParameter().findAnnotation(Mapping.class).orElse(null);
if (enumParam != null) {
Class<? extends Enum<?>> enumType = enumParam.value();
List<IMapping<?>> values = MappingHelper.getEnums(enumType);
Object defaultValue = MappingHelper.getDefaultValue(enumType);
AllowableListValues allowableListValues = new AllowableListValues(
values.stream().map((item) -> item.getVal().toString()).collect(
Collectors.toList()),
values.get(0).getVal().getClass().getSimpleName());
ParameterBuilder builder = context.parameterBuilder();
builder.description(Util.getDesc(values));
builder.scalarExample(new Example(defaultValue == null ? UString.EMPTY : defaultValue.toString()));
builder.allowableValues(allowableListValues);
builder.defaultValue(defaultValue == null ? UString.EMPTY : defaultValue.toString());
}
}
}
| 39.210046 | 105 | 0.787819 |
87b30962dcbf046956247ad46ac70d182565b082 | 1,171 | /*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.osgi.deployment.master;
import java.util.List;
/**
* Deploys features to a remote system.
*
* @author Keith M. Hughes
*/
public interface DeploymentServer {
/**
* Start up the deployment server.
*/
void startup();
/**
* Shut down the deployment server.
*/
void shutdown();
/**
* Deploy a set of features to a node.
*
* @param node
* the node to receive the features
* @param features
* the features to be deployed to the node
*/
void deployFeature(String node, List<String> features);
}
| 24.395833 | 80 | 0.681469 |
2cd476fecba15e8da940267f1647743e21d50e96 | 4,959 | package com.microsoft.azure.kusto.data;
import com.microsoft.azure.kusto.data.exceptions.DataClientException;
import com.microsoft.azure.kusto.data.exceptions.DataServiceException;
import com.microsoft.azure.kusto.data.exceptions.DataWebException;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
class Utils {
static Results post(String url, String aadAccessToken, String payload, Integer timeoutMs) throws DataServiceException, DataClientException {
HttpClient httpClient;
if (timeoutMs != null) {
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeoutMs).build();
httpClient = HttpClientBuilder.create().useSystemProperties().setDefaultRequestConfig(requestConfig).build();
} else {
httpClient = HttpClients.createSystem();
}
HttpPost httpPost = new HttpPost(url);
// Request parameters and other properties.
StringEntity requestEntity = new StringEntity(
payload,
ContentType.APPLICATION_JSON);
httpPost.setEntity(requestEntity);
httpPost.addHeader("Authorization", String.format("Bearer %s", aadAccessToken));
httpPost.addHeader("Content-Type", "application/json");
httpPost.addHeader("Accept-Encoding", "gzip,deflate");
httpPost.addHeader("Fed", "True");
String version = Utils.class.getPackage().getImplementationVersion();
String clientVersion = "Kusto.Java.Client";
if (StringUtils.isNotBlank(version)) {
clientVersion += ":" + version;
}
httpPost.addHeader("x-ms-client-version", clientVersion);
httpPost.addHeader("x-ms-client-request-id", String.format("KJC.execute;%s", java.util.UUID.randomUUID()));
try {
//Execute and get the response.
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
StatusLine statusLine = response.getStatusLine();
String responseContent = EntityUtils.toString(entity);
if (statusLine.getStatusCode() == 200) {
JSONObject jsonObject = new JSONObject(responseContent);
JSONArray tablesArray = jsonObject.getJSONArray("Tables");
JSONObject table0 = tablesArray.getJSONObject(0);
JSONArray resultsColumns = table0.getJSONArray("Columns");
HashMap<String, Integer> columnNameToIndex = new HashMap<>();
HashMap<String, String> columnNameToType = new HashMap<>();
for (int i = 0; i < resultsColumns.length(); i++) {
JSONObject column = resultsColumns.getJSONObject(i);
String columnName = column.getString("ColumnName");
columnNameToIndex.put(columnName, i);
columnNameToType.put(columnName, column.getString("DataType"));
}
JSONArray resultsRows = table0.getJSONArray("Rows");
ArrayList<ArrayList<String>> values = new ArrayList<>();
for (int i = 0; i < resultsRows.length(); i++) {
JSONArray row = resultsRows.getJSONArray(i);
ArrayList<String> rowVector = new ArrayList<>();
for (int j = 0; j < row.length(); ++j) {
Object obj = row.get(j);
if (obj == JSONObject.NULL) {
rowVector.add(null);
} else {
rowVector.add(obj.toString());
}
}
values.add(rowVector);
}
return new Results(columnNameToIndex, columnNameToType, values);
} else {
throw new DataServiceException(url, "Error in post request", new DataWebException(responseContent, response));
}
}
} catch (JSONException | IOException e) {
throw new DataClientException(url, "Error in post request", e);
}
return null;
}
}
| 43.121739 | 144 | 0.607582 |
0d0be43c6e1b34840be908b4dac75261113328b2 | 3,331 | package org.Jcing.controls;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import org.Jcing.main.Main;
/**
* InputManager manages Mouse / -motion and KeyEvents. It holds public static
* <b>Mouse</b>, <b>KeyBoard</b> and <b>BindingManager</b>.
*
* @author Jcing
*
*/
public class InputManager implements KeyListener, MouseListener, MouseMotionListener {
Main m;
public static Mouse mouse;
public static KeyBoard keyboard;
public static BindingManager bm = new BindingManager(50);
public InputManager() {
m = Main.getMain();
mouse = new Mouse();
keyboard = new KeyBoard();
}
public void keyPressed(KeyEvent e) {
// System.out.println("key " + e.getKeyCode());
keyboard.press(e.getKeyCode());
bm.press(e.getKeyCode());
}
public void keyReleased(KeyEvent e) {
keyboard.release(e.getKeyCode());
bm.release(e.getKeyCode());
}
public void mouseDragged(MouseEvent e) {
mouse.x = e.getX();
mouse.y = e.getY();
if (m.getCreator() != null && !m.options().creatorWindowed && m.getWin().creatorShown()) {
if (!m.getCreator().hovered(e.getX(), e.getY())) {
// System.out.println("ADD TILE!");
m.getGame().getActiveLevel().hover(e.getX(), e.getY());
m.getGame().getActiveLevel().click(true);
} else {
// TODO: maybe unsafe
m.getGame().getActiveLevel().hover(-1000, -1000);
}
} else {
// System.out.println("NO CREATOR SEEN");
m.getGame().getActiveLevel().hover(e.getX(), e.getY());
m.getGame().getActiveLevel().click(true);
}
}
public void mouseMoved(MouseEvent e) {
mouse.x = e.getX();
mouse.y = e.getY();
if (m.getCreator() != null && !m.options().creatorWindowed && m.getWin().creatorShown()) {
if (!m.getCreator().hovered(e.getX(), e.getY())) {
// System.out.println("ADD TILE!");
m.getGame().getActiveLevel().hover(e.getX(), e.getY());
} else {
// TODO: maybe unsafe
m.getGame().getActiveLevel().hover(-1000, -1000);
}
} else {
// System.out.println("NO CREATOR SEEN");
m.getGame().getActiveLevel().hover(e.getX(), e.getY());
}
}
public void mousePressed(MouseEvent e) {
mouse.pressed = true;
mouse.button = e.getButton();
if (m.getCreator() != null && !m.options().creatorWindowed) {
if (!m.getCreator().hovered(e.getX(), e.getY())) {
System.out.println("ADD TILE!");
m.getGame().getActiveLevel().click(false);
}
} else {
// System.out.println("NO CREATOR SEEN");
m.getGame().getActiveLevel().click(false);
}
}
public void mouseReleased(MouseEvent e) {
mouse.pressed = false;
if (m.getCreator() != null && !m.options().creatorWindowed) {
if (!m.getCreator().hovered(e.getX(), e.getY())) {
// System.out.println("ADD TILE!");
m.getGame().getActiveLevel().click(false);
}
} else {
// System.out.println("NO CREATOR SEEN");
m.getGame().getActiveLevel().click(false);
}
}
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
| 25.427481 | 92 | 0.651756 |
e80970e8e4c6381c49ab8905d5018be8ee37617c | 4,570 | package com.codepath.apps.restclienttemplate;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.codepath.apps.restclienttemplate.models.Tweet;
import org.parceler.Parcels;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
public class TweetAdapter extends RecyclerView.Adapter<TweetAdapter.ViewHolder> {
// 1- pass in tweets array (give adapter data)
private List<Tweet> mtweets;
Context context;
public TweetAdapter(List<Tweet> tweets) {
mtweets = tweets;
}
//2- inflate EACH row, cache references into ViewHolder
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
final View tweetView = inflater.inflate(R.layout.item_tweet,parent,false);
final ViewHolder viewHolder = new ViewHolder(tweetView);
//getItemViewType();
return viewHolder;
}
//3- bind value based on pos of element
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
//get data according to position
Tweet tweet = mtweets.get(position);
//populate views with this data
holder.tvUsername.setText(tweet.user.name);
holder.tvBody.setText(tweet.body);
final RoundedCornersTransformation roundedCornersTransformation = new RoundedCornersTransformation(15,15);
final RequestOptions requestOptions = RequestOptions.bitmapTransform(roundedCornersTransformation);
//load image with glide
Glide.with(holder.itemView.getContext())
.load(tweet.user.profileImageUrl).apply(requestOptions)
.into(holder.ivProfileImage);
// TODO - parse timestamp to abbreviate "minutes ago" to "m"
holder.tvCreatedAt.setText(getRelativeTimeAgo(tweet.createdAt));
}
@Override
public int getItemCount() {
return mtweets.size();
}
// getRelativeTimeAgo("Mon Apr 01 21:16:23 +0000 2014");
public String getRelativeTimeAgo(String rawJsonDate) {
String twitterFormat = "EEE MMM dd HH:mm:ss ZZZZZ yyyy";
SimpleDateFormat sf = new SimpleDateFormat(twitterFormat, Locale.ENGLISH);
sf.setLenient(true);
String relativeDate = "";
try {
long dateMillis = sf.parse(rawJsonDate).getTime();
relativeDate = DateUtils.getRelativeTimeSpanString(dateMillis,
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS).toString();
} catch (ParseException e) {
e.printStackTrace();
}
return relativeDate;
}
//4- make a ViewHolder class
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public ImageView ivProfileImage;
public TextView tvUsername;
public TextView tvBody;
public TextView tvCreatedAt;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
//findViewById lookups
ivProfileImage = (ImageView) itemView.findViewById(R.id.ivProfileImage);
tvUsername = (TextView) itemView.findViewById(R.id.tvUserName);
tvBody = (TextView) itemView.findViewById(R.id.tvBody);
tvCreatedAt = (TextView) itemView.findViewById(R.id.tvCreatedAgo);
}
@Override
public void onClick(View v) {
// create intent to pass tweet parcel to tweetDetailActivity
Intent i = new Intent(context, TweetDetailActivity.class);
i.putExtra("tweet", Parcels.wrap(mtweets.get(getAdapterPosition())));
context.startActivity(i);
}
}
public void clear() {
mtweets.clear();
notifyDataSetChanged();
}
// Add a list of items -- change to type used
public void addAll(List<Tweet> list) {
mtweets.addAll(list);
notifyDataSetChanged();
}
}
| 29.675325 | 114 | 0.683151 |
3746e3b62a7102156369a8702f522aa6d32acf7b | 503 | package com.laytonsmith.abstraction.enums;
import com.laytonsmith.annotations.MEnum;
/**
*
* @author jb_aero
*/
@MEnum("SpawnReason")
public enum MCSpawnReason {
BED,
BREEDING,
BUILD_IRONGOLEM,
BUILD_SNOWMAN,
BUILD_WITHER,
CHUNK_GEN,
/**
* Spawned by plugins
*/
CUSTOM,
/**
* Missing spawn reason
*/
DEFAULT,
/**
* The kind of egg you throw
*/
EGG,
JOCKEY,
LIGHTNING,
NATURAL,
REINFORCEMENTS,
SLIME_SPLIT,
SPAWNER,
SPAWNER_EGG,
VILLAGE_DEFENSE,
VILLAGE_INVASION
}
| 12.897436 | 42 | 0.697813 |
705ace3f772358013145463f60f0643b02426fe5 | 25,216 | /*
* Copyright 2000-2016 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 org.jetbrains.idea.maven.indices;
import com.intellij.jarRepository.services.bintray.BintrayModel;
import com.intellij.jarRepository.services.bintray.BintrayRepositoryService;
import com.intellij.openapi.util.ModificationTracker;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.util.CachedValue;
import com.intellij.psi.util.CachedValueProvider;
import com.intellij.util.CachedValueImpl;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.io.DataExternalizer;
import com.intellij.util.io.EnumeratorStringDescriptor;
import com.intellij.util.io.PersistentEnumeratorBase;
import com.intellij.util.io.PersistentHashMap;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import org.apache.lucene.search.Query;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import org.jetbrains.idea.maven.model.MavenArchetype;
import org.jetbrains.idea.maven.model.MavenArtifactInfo;
import org.jetbrains.idea.maven.project.MavenGeneralSettings;
import org.jetbrains.idea.maven.server.IndexedMavenId;
import org.jetbrains.idea.maven.server.MavenIndexerWrapper;
import org.jetbrains.idea.maven.server.MavenIndicesProcessor;
import org.jetbrains.idea.maven.server.MavenServerIndexerException;
import org.jetbrains.idea.maven.utils.MavenLog;
import org.jetbrains.idea.maven.utils.MavenProcessCanceledException;
import org.jetbrains.idea.maven.utils.MavenProgressIndicator;
import java.io.*;
import java.util.*;
import static com.intellij.openapi.util.text.StringUtil.join;
import static com.intellij.openapi.util.text.StringUtil.split;
import static com.intellij.util.containers.ContainerUtil.notNullize;
public class MavenIndex {
private static final String CURRENT_VERSION = "5";
protected static final String INDEX_INFO_FILE = "index.properties";
private static final String INDEX_VERSION_KEY = "version";
private static final String KIND_KEY = "kind";
private static final String ID_KEY = "id";
private static final String PATH_OR_URL_KEY = "pathOrUrl";
private static final String TIMESTAMP_KEY = "lastUpdate";
private static final String DATA_DIR_NAME_KEY = "dataDirName";
private static final String FAILURE_MESSAGE_KEY = "failureMessage";
private static final String DATA_DIR_PREFIX = "data";
private static final String ARTIFACT_IDS_MAP_FILE = "artifactIds-map.dat";
private static final String VERSIONS_MAP_FILE = "versions-map.dat";
private static final String ARCHETYPES_MAP_FILE = "archetypes-map.dat";
public enum Kind {
LOCAL, REMOTE
}
private final MavenIndexerWrapper myNexusIndexer;
private final NotNexusIndexer myNotNexusIndexer;
private final File myDir;
private final Set<String> myRegisteredRepositoryIds = ContainerUtil.newHashSet();
private final CachedValue<String> myId = new CachedValueImpl<>(new MyIndexRepositoryIdsProvider());
private final String myRepositoryPathOrUrl;
private final Kind myKind;
private Long myUpdateTimestamp;
private String myDataDirName;
private IndexData myData;
private String myFailureMessage;
private boolean isBroken;
private final IndexListener myListener;
public MavenIndex(MavenIndexerWrapper indexer,
File dir,
String repositoryId,
String repositoryPathOrUrl,
Kind kind,
IndexListener listener) throws MavenIndexException {
myNexusIndexer = indexer;
myDir = dir;
myRegisteredRepositoryIds.add(repositoryId);
myRepositoryPathOrUrl = normalizePathOrUrl(repositoryPathOrUrl);
myKind = kind;
myListener = listener;
myNotNexusIndexer = initNotNexusIndexer(kind, repositoryPathOrUrl);
open();
}
public MavenIndex(MavenIndexerWrapper indexer,
File dir,
IndexListener listener) throws MavenIndexException {
myNexusIndexer = indexer;
myDir = dir;
myListener = listener;
Properties props = new Properties();
try {
FileInputStream s = new FileInputStream(new File(dir, INDEX_INFO_FILE));
try {
props.load(s);
}
finally {
s.close();
}
}
catch (IOException e) {
throw new MavenIndexException("Cannot read " + INDEX_INFO_FILE + " file", e);
}
if (!CURRENT_VERSION.equals(props.getProperty(INDEX_VERSION_KEY))) {
throw new MavenIndexException("Incompatible index version, needs to be updated: " + dir);
}
myKind = Kind.valueOf(props.getProperty(KIND_KEY));
String myRepositoryIdsStr = props.getProperty(ID_KEY);
if (myRepositoryIdsStr != null) {
myRegisteredRepositoryIds.addAll(split(myRepositoryIdsStr, ","));
}
myRepositoryPathOrUrl = normalizePathOrUrl(props.getProperty(PATH_OR_URL_KEY));
try {
String timestamp = props.getProperty(TIMESTAMP_KEY);
if (timestamp != null) myUpdateTimestamp = Long.parseLong(timestamp);
}
catch (Exception ignored) {
}
myDataDirName = props.getProperty(DATA_DIR_NAME_KEY);
myFailureMessage = props.getProperty(FAILURE_MESSAGE_KEY);
myNotNexusIndexer = initNotNexusIndexer(myKind, myRepositoryPathOrUrl);
open();
}
private static NotNexusIndexer initNotNexusIndexer(Kind kind, String repositoryPathOrUrl) {
if (kind == Kind.REMOTE) {
BintrayModel.Repository info = BintrayRepositoryService.parseInfo(repositoryPathOrUrl);
if (info != null) {
return new BintrayIndexer(info.subject, info.repo);
}
}
return null;
}
public void registerId(String repositoryId) throws MavenIndexException {
if (myRegisteredRepositoryIds.add(repositoryId)) {
save();
close(true);
open();
}
}
@NotNull
public static String normalizePathOrUrl(@NotNull String pathOrUrl) {
pathOrUrl = pathOrUrl.trim();
pathOrUrl = FileUtil.toSystemIndependentName(pathOrUrl);
while (pathOrUrl.endsWith("/")) {
pathOrUrl = pathOrUrl.substring(0, pathOrUrl.length() - 1);
}
return pathOrUrl;
}
private void open() throws MavenIndexException {
try {
try {
doOpen();
}
catch (Exception e1) {
final boolean versionUpdated = e1.getCause() instanceof PersistentEnumeratorBase.VersionUpdatedException;
if (!versionUpdated) MavenLog.LOG.warn(e1);
try {
doOpen();
}
catch (Exception e2) {
throw new MavenIndexException("Cannot open index " + myDir.getPath(), e2);
}
markAsBroken();
}
}
finally {
save();
}
}
private void doOpen() throws Exception {
try {
File dataDir;
if (myDataDirName == null) {
dataDir = createNewDataDir();
myDataDirName = dataDir.getName();
}
else {
dataDir = new File(myDir, myDataDirName);
dataDir.mkdirs();
}
if (myData != null) {
myData.close(true);
}
myData = new IndexData(dataDir);
}
catch (Exception e) {
cleanupBrokenData();
throw e;
}
}
private void cleanupBrokenData() {
close(true);
//noinspection TestOnlyProblems
final File currentDataDir = getCurrentDataDir();
final File currentDataContextDir = getCurrentDataContextDir();
final File[] files = currentDataDir.listFiles();
if (files != null) {
for (File file : files) {
if (!FileUtil.filesEqual(file, currentDataContextDir)) {
FileUtil.delete(file);
}
}
}
else {
FileUtil.delete(currentDataDir);
}
}
public synchronized void close(boolean releaseIndexContext) {
try {
if (myData != null) myData.close(releaseIndexContext);
}
catch (MavenIndexException e) {
MavenLog.LOG.warn(e);
}
myData = null;
}
private synchronized void save() {
myDir.mkdirs();
Properties props = new Properties();
props.setProperty(KIND_KEY, myKind.toString());
props.setProperty(ID_KEY, myId.getValue());
props.setProperty(PATH_OR_URL_KEY, myRepositoryPathOrUrl);
props.setProperty(INDEX_VERSION_KEY, CURRENT_VERSION);
if (myUpdateTimestamp != null) props.setProperty(TIMESTAMP_KEY, String.valueOf(myUpdateTimestamp));
if (myDataDirName != null) props.setProperty(DATA_DIR_NAME_KEY, myDataDirName);
if (myFailureMessage != null) props.setProperty(FAILURE_MESSAGE_KEY, myFailureMessage);
try {
FileOutputStream s = new FileOutputStream(new File(myDir, INDEX_INFO_FILE));
try {
props.store(s, null);
}
finally {
s.close();
}
}
catch (IOException e) {
MavenLog.LOG.warn(e);
}
}
public String getRepositoryId() {
return myId.getValue();
}
public File getRepositoryFile() {
return myKind == Kind.LOCAL ? new File(myRepositoryPathOrUrl) : null;
}
public String getRepositoryUrl() {
return myKind == Kind.REMOTE ? myRepositoryPathOrUrl : null;
}
public String getRepositoryPathOrUrl() {
return myRepositoryPathOrUrl;
}
public Kind getKind() {
return myKind;
}
public boolean isFor(Kind kind, String pathOrUrl) {
if (myKind != kind) return false;
if (kind == Kind.LOCAL) return FileUtil.pathsEqual(myRepositoryPathOrUrl, normalizePathOrUrl(pathOrUrl));
return myRepositoryPathOrUrl.equalsIgnoreCase(normalizePathOrUrl(pathOrUrl));
}
public synchronized long getUpdateTimestamp() {
return myUpdateTimestamp == null ? -1 : myUpdateTimestamp;
}
public synchronized String getFailureMessage() {
return myFailureMessage;
}
public void updateOrRepair(boolean fullUpdate, MavenGeneralSettings settings, MavenProgressIndicator progress)
throws MavenProcessCanceledException {
try {
final File newDataDir = createNewDataDir();
final File newDataContextDir = getDataContextDir(newDataDir);
final File currentDataContextDir = getCurrentDataContextDir();
if (myNotNexusIndexer == null) {
boolean reuseExistingContext = fullUpdate ?
myKind != Kind.LOCAL && hasValidContext(currentDataContextDir) :
hasValidContext(currentDataContextDir);
fullUpdate = fullUpdate || !reuseExistingContext && myKind == Kind.LOCAL;
if (reuseExistingContext) {
try {
FileUtil.copyDir(currentDataContextDir, newDataContextDir);
}
catch (IOException e) {
throw new MavenIndexException(e);
}
}
if (fullUpdate) {
int context = createContext(newDataContextDir, "update");
try {
updateContext(context, settings, progress);
}
finally {
myNexusIndexer.releaseIndex(context);
}
}
}
updateData(progress, newDataDir, fullUpdate);
isBroken = false;
myFailureMessage = null;
}
catch (MavenProcessCanceledException e) {
throw e;
}
catch (Exception e) {
handleUpdateException(e);
}
save();
}
private boolean hasValidContext(@NotNull File contextDir) {
return contextDir.isDirectory() && myNexusIndexer.indexExists(contextDir);
}
private void handleUpdateException(Exception e) {
myFailureMessage = e.getMessage();
MavenLog.LOG.warn("Failed to update Maven indices for: [" + myId.getValue() + "] " + myRepositoryPathOrUrl, e);
}
private int createContext(File contextDir, String suffix) throws MavenServerIndexerException {
if (myNotNexusIndexer != null) return 0;
String indexId = myDir.getName() + "-" + suffix;
return myNexusIndexer.createIndex(indexId,
myId.getValue(),
getRepositoryFile(),
getRepositoryUrl(),
contextDir);
}
private void updateContext(int indexId, MavenGeneralSettings settings, MavenProgressIndicator progress)
throws MavenServerIndexerException, MavenProcessCanceledException {
myNexusIndexer.updateIndex(indexId, settings, progress);
}
private void updateData(MavenProgressIndicator progress, File newDataDir, boolean fullUpdate) throws MavenIndexException {
synchronized (this) {
IndexData oldData = myData;
if(oldData != null) {
oldData.close(true);
}
}
IndexData newData = new IndexData(newDataDir);
try {
doUpdateIndexData(newData, progress);
newData.flush();
}
catch (Throwable e) {
newData.close(true);
FileUtil.delete(newDataDir);
if (e instanceof MavenServerIndexerException) throw new MavenIndexException(e);
if (e instanceof IOException) throw new MavenIndexException(e);
throw new RuntimeException(e);
}
synchronized (this) {
myData = newData;
myDataDirName = newDataDir.getName();
if (fullUpdate) {
myUpdateTimestamp = System.currentTimeMillis();
}
for (File each : FileUtil.notNullize(myDir.listFiles())) {
if (each.getName().startsWith(DATA_DIR_PREFIX) && !each.getName().equals(myDataDirName)) {
FileUtil.delete(each);
}
}
}
}
private void doUpdateIndexData(IndexData data,
MavenProgressIndicator progress) throws IOException, MavenServerIndexerException {
final Map<String, Set<String>> groupToArtifactMap = new THashMap<>();
final Map<String, Set<String>> groupWithArtifactToVersionMap = new THashMap<>();
final Map<String, Set<String>> archetypeIdToDescriptionMap = new THashMap<>();
progress.pushState();
progress.setIndeterminate(true);
try {
final StringBuilder builder = new StringBuilder();
MavenIndicesProcessor mavenIndicesProcessor = artifacts -> {
for (IndexedMavenId id : artifacts) {
builder.setLength(0);
builder.append(id.groupId).append(":").append(id.artifactId);
String ga = builder.toString();
getOrCreate(groupToArtifactMap, id.groupId).add(id.artifactId);
getOrCreate(groupWithArtifactToVersionMap, ga).add(id.version);
if ("maven-archetype".equals(id.packaging)) {
builder.setLength(0);
builder.append(id.version).append(":").append(StringUtil.notNullize(id.description));
getOrCreate(archetypeIdToDescriptionMap, ga).add(builder.toString());
}
}
};
if (myNotNexusIndexer != null) {
myNotNexusIndexer.processArtifacts(progress, mavenIndicesProcessor);
}
else {
myNexusIndexer.processArtifacts(data.indexId, mavenIndicesProcessor);
}
persist(groupToArtifactMap, data.groupToArtifactMap);
persist(groupWithArtifactToVersionMap, data.groupWithArtifactToVersionMap);
persist(archetypeIdToDescriptionMap, data.archetypeIdToDescriptionMap);
}
finally {
progress.popState();
}
}
private static <T> Set<T> getOrCreate(Map<String, Set<T>> map, String key) {
return map.computeIfAbsent(key, k -> new THashSet<>());
}
private static <T> void persist(Map<String, T> map, PersistentHashMap<String, T> persistentMap) throws IOException {
for (Map.Entry<String, T> each : map.entrySet()) {
persistentMap.put(each.getKey(), each.getValue());
}
}
@TestOnly
public File getDir() {
return myDir;
}
@TestOnly
protected synchronized File getCurrentDataDir() {
return new File(myDir, myDataDirName);
}
private File getCurrentDataContextDir() {
//noinspection TestOnlyProblems
return new File(getCurrentDataDir(), "context");
}
private static File getDataContextDir(File dataDir) {
return new File(dataDir, "context");
}
@NotNull
private File createNewDataDir() {
return MavenIndices.createNewDir(myDir, DATA_DIR_PREFIX, 100);
}
public synchronized void addArtifact(final File artifactFile) {
doIndexTask(() -> {
IndexedMavenId id = myData.addArtifact(artifactFile);
myData.hasGroupCache.put(id.groupId, true);
String groupWithArtifact = id.groupId + ":" + id.artifactId;
myData.hasArtifactCache.put(groupWithArtifact, true);
myData.hasVersionCache.put(groupWithArtifact + ':' + id.version, true);
addToCache(myData.groupToArtifactMap, id.groupId, id.artifactId);
addToCache(myData.groupWithArtifactToVersionMap, groupWithArtifact, id.version);
if ("maven-archetype".equals(id.packaging)) {
addToCache(myData.archetypeIdToDescriptionMap, groupWithArtifact, id.version + ":" + StringUtil.notNullize(id.description));
}
myData.flush();
return null;
}, null);
}
private static void addToCache(PersistentHashMap<String, Set<String>> cache, String key, String value) throws IOException {
Set<String> values = cache.get(key);
if (values == null) values = new THashSet<>();
values.add(value);
cache.put(key, values);
}
public synchronized Collection<String> getGroupIds() {
return doIndexTask(() -> myData.groupToArtifactMap.getAllDataObjects(null), Collections.emptySet());
}
public synchronized Set<String> getArtifactIds(final String groupId) {
return doIndexTask(() -> notNullize(myData.groupToArtifactMap.get(groupId)), Collections.emptySet());
}
@TestOnly
public synchronized void printInfo() {
doIndexTask(() -> {
System.out.println("BaseFile: " + myData.groupToArtifactMap.getBaseFile());
System.out.println("All data objects: " + myData.groupToArtifactMap.getAllDataObjects(null));
return null;
}, null);
}
public synchronized Set<String> getVersions(final String groupId, final String artifactId) {
String ga = groupId + ":" + artifactId;
return doIndexTask(() -> notNullize(myData.groupWithArtifactToVersionMap.get(ga)), Collections.emptySet());
}
public synchronized boolean hasGroupId(String groupId) {
if (isBroken) return false;
return hasValue(myData.groupToArtifactMap, myData.hasGroupCache, groupId);
}
public synchronized boolean hasArtifactId(String groupId, String artifactId) {
if (isBroken) return false;
return hasValue(myData.groupWithArtifactToVersionMap, myData.hasArtifactCache, groupId + ":" + artifactId);
}
public synchronized boolean hasVersion(String groupId, String artifactId, final String version) {
if (isBroken) return false;
final String groupWithArtifactWithVersion = groupId + ":" + artifactId + ':' + version;
String groupWithArtifact = groupWithArtifactWithVersion.substring(0, groupWithArtifactWithVersion.length() - version.length() - 1);
return myData.hasVersionCache.computeIfAbsent(groupWithArtifactWithVersion, gav -> doIndexTask(
() -> notNullize(myData.groupWithArtifactToVersionMap.get(groupWithArtifact)).contains(version),
false));
}
private boolean hasValue(final PersistentHashMap<String, ?> map, Map<String, Boolean> cache, final String value) {
return cache.computeIfAbsent(value, v -> doIndexTask(() -> map.tryEnumerate(v) != 0, false));
}
public synchronized Set<MavenArtifactInfo> search(final Query query, final int maxResult) {
if (myNotNexusIndexer != null) return Collections.emptySet();
return doIndexTask(() -> myData.search(query, maxResult), Collections.emptySet());
}
public synchronized Set<MavenArchetype> getArchetypes() {
return doIndexTask(() -> {
Set<MavenArchetype> archetypes = new THashSet<>();
for (String ga : myData.archetypeIdToDescriptionMap.getAllKeysWithExistingMapping()) {
List<String> gaParts = split(ga, ":");
String groupId = gaParts.get(0);
String artifactId = gaParts.get(1);
for (String vd : myData.archetypeIdToDescriptionMap.get(ga)) {
int index = vd.indexOf(':');
if (index == -1) continue;
String version = vd.substring(0, index);
String description = vd.substring(index + 1);
archetypes.add(new MavenArchetype(groupId, artifactId, version, myRepositoryPathOrUrl, description));
}
}
return archetypes;
}, Collections.emptySet());
}
private <T> T doIndexTask(IndexTask<T> task, T defaultValue) {
assert Thread.holdsLock(this);
if (!isBroken) {
try {
return task.doTask();
}
catch (Exception e1) {
MavenLog.LOG.warn(e1);
cleanupBrokenData();
try {
open();
}
catch (MavenIndexException e2) {
MavenLog.LOG.warn(e2);
}
}
}
markAsBroken();
return defaultValue;
}
private void markAsBroken() {
if (!isBroken) {
myListener.indexIsBroken(this);
}
isBroken = true;
}
@FunctionalInterface
private interface IndexTask<T> {
T doTask() throws Exception;
}
private class IndexData {
final PersistentHashMap<String, Set<String>> groupToArtifactMap;
final PersistentHashMap<String, Set<String>> groupWithArtifactToVersionMap;
final PersistentHashMap<String, Set<String>> archetypeIdToDescriptionMap;
final Map<String, Boolean> hasGroupCache = new THashMap<>();
final Map<String, Boolean> hasArtifactCache = new THashMap<>();
final Map<String, Boolean> hasVersionCache = new THashMap<>();
private final int indexId;
public IndexData(File dir) throws MavenIndexException {
try {
groupToArtifactMap = createPersistentMap(new File(dir, ARTIFACT_IDS_MAP_FILE));
groupWithArtifactToVersionMap = createPersistentMap(new File(dir, VERSIONS_MAP_FILE));
archetypeIdToDescriptionMap = createPersistentMap(new File(dir, ARCHETYPES_MAP_FILE));
indexId = createContext(getDataContextDir(dir), dir.getName());
}
catch (IOException | MavenServerIndexerException e) {
close(true);
throw new MavenIndexException(e);
}
}
private PersistentHashMap<String, Set<String>> createPersistentMap(final File f) throws IOException {
return new PersistentHashMap<>(f, EnumeratorStringDescriptor.INSTANCE, new SetDescriptor());
}
public void close(boolean releaseIndexContext) throws MavenIndexException {
MavenIndexException[] exceptions = new MavenIndexException[1];
try {
if (indexId != 0 && releaseIndexContext) myNexusIndexer.releaseIndex(indexId);
}
catch (MavenServerIndexerException e) {
MavenLog.LOG.warn(e);
if (exceptions[0] == null) exceptions[0] = new MavenIndexException(e);
}
safeClose(groupToArtifactMap, exceptions);
safeClose(groupWithArtifactToVersionMap, exceptions);
safeClose(archetypeIdToDescriptionMap, exceptions);
if (exceptions[0] != null) throw exceptions[0];
}
private void safeClose(@Nullable Closeable enumerator, MavenIndexException[] exceptions) {
try {
if (enumerator != null) enumerator.close();
}
catch (IOException e) {
MavenLog.LOG.warn(e);
if (exceptions[0] == null) exceptions[0] = new MavenIndexException(e);
}
}
public void flush() throws IOException {
groupToArtifactMap.force();
groupWithArtifactToVersionMap.force();
archetypeIdToDescriptionMap.force();
}
public IndexedMavenId addArtifact(File artifactFile) throws MavenServerIndexerException {
return myNexusIndexer.addArtifact(indexId, artifactFile);
}
public Set<MavenArtifactInfo> search(Query query, int maxResult) throws MavenServerIndexerException {
return myNexusIndexer.search(indexId, query, maxResult);
}
}
private static class SetDescriptor implements DataExternalizer<Set<String>> {
public void save(@NotNull DataOutput s, Set<String> set) throws IOException {
s.writeInt(set.size());
for (String each : set) {
s.writeUTF(each);
}
}
public Set<String> read(@NotNull DataInput s) throws IOException {
int count = s.readInt();
Set<String> result = new THashSet<>(count);
while (count-- > 0) {
result.add(s.readUTF());
}
return result;
}
}
public interface IndexListener {
void indexIsBroken(MavenIndex index);
}
private class MyIndexRepositoryIdsProvider implements CachedValueProvider<String> {
@Nullable
@Override
public Result<String> compute() {
return Result.create(join(myRegisteredRepositoryIds, ","), (ModificationTracker)myRegisteredRepositoryIds::hashCode);
}
}
}
| 33.178947 | 135 | 0.688016 |
c8343245165bc9cfefdffe9ffd7e20ff00ecec64 | 629 | package com.github.hotreload.config;
import static com.github.hotreload.utils.ReloadUtil.joinKeywords;
import static org.apache.commons.collections4.CollectionUtils.isEmpty;
import java.util.List;
import com.github.hotreload.model.JvmProcess;
import lombok.Data;
/**
* @author liuzhengyang
*/
@Data
public class ApplicationConfig {
private String server;
private String selectedHostName;
private List<String> keywords;
private JvmProcess selectedProcess;
public String getKeywordText() {
if (isEmpty(keywords)) {
return "";
}
return joinKeywords(keywords);
}
}
| 21.689655 | 70 | 0.720191 |
3238d2b54099426084ff7b4e8becd050270b83d2 | 1,548 | /******************************************************************************
*
* Copyright (c) 1999-2011 Cryptzone Group AB. All Rights Reserved.
*
* This file contains Original Code and/or Modifications of Original Code as
* defined in and that are subject to the MindTerm Public Source License,
* Version 2.0, (the 'License'). You may not use this file except in compliance
* with the License.
*
* You should have received a copy of the MindTerm Public Source License
* along with this software; see the file LICENSE. If not, write to
* Cryptzone Group AB, Drakegatan 7, SE-41250 Goteborg, SWEDEN
*
*****************************************************************************/
package com.mindbright.ssh;
import java.io.IOException;
public interface SSHInteractor {
public void startNewSession(SSHClient client);
public void sessionStarted(SSHClient client);
public void connected(SSHClient client);
public void open(SSHClient client);
public void disconnected(SSHClient client, boolean graceful);
public void report(String msg);
public void alert(String msg);
public void propsStateChanged(SSHPropertyHandler props);
public boolean askConfirmation(String message, boolean defAnswer);
public boolean licenseDialog(String license);
public boolean quietPrompts();
public String promptLine(String prompt, String defaultVal) throws IOException;
public String promptPassword(String prompt) throws IOException;
public boolean isVerbose();
}
| 36.857143 | 83 | 0.665375 |
4ac1a3035842f7f50e8dd05a13e605df952b9113 | 652 | package main.boot;
public class Preference {
public String service;
public static class User{
public String name;
public String pass;
public int last;
}
public User[] users=new User[0];
public boolean store=false;
public boolean showMainWindowAtStartup=true;
public boolean requestHistoryNotificationsWhenLoginToAAccount=false;
public boolean broadcast=true;
public int broadcastFrameXOnScreen=80;
public int broadcastFrameYOnScreen=60;
public int broadcastFrameW=530;
public int mainWindowWidth=400;
public int mainWindowHeight=600;
public int recentLimit=100;
}
| 22.482759 | 72 | 0.720859 |
7bd9d703c15ace26ec70fc8d177fcc4588a8646e | 1,774 | package com.mehmetpekdemir.lion.service.impl;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import com.mehmetpekdemir.lion.dto.UserCreateDTO;
import com.mehmetpekdemir.lion.dto.UserViewDTO;
import com.mehmetpekdemir.lion.entity.User;
import com.mehmetpekdemir.lion.error.NotFoundException;
import com.mehmetpekdemir.lion.repository.UserRepository;
import com.mehmetpekdemir.lion.service.UserService;
import lombok.RequiredArgsConstructor;
/**
*
* @author MEHMET PEKDEMIR
* @since 1.0
*/
@Service
@RequiredArgsConstructor // Constructor Injection with lombok
public class UserServiceImpl implements UserService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
@Override
public List<UserViewDTO> sliceForUsers(Pageable pageable) {
return userRepository.findAll(pageable).stream().map(UserViewDTO::of).collect(Collectors.toList());
}
@Override
public UserViewDTO getUserById(Long id) {
final User user = userRepository.findById(id)
.orElseThrow(() -> new NotFoundException(String.format("User not found with id %d", id)));
return UserViewDTO.of(user);
}
@Override
public UserViewDTO createUser(UserCreateDTO userCreateDTO) {
encodeThePassword(userCreateDTO); // Password encoded
final User user = userRepository.save(
new User(userCreateDTO.getUsername(), userCreateDTO.getDisplayName(), userCreateDTO.getPassword()));
return UserViewDTO.of(user);
}
private void encodeThePassword(UserCreateDTO userCreateDTO) {
userCreateDTO.setPassword(this.passwordEncoder.encode(userCreateDTO.getPassword()));
}
}
| 30.586207 | 104 | 0.801015 |
bf7a8f020891cd9ce4e80fd06a2e67d377af34ba | 2,107 | // Copyright 2016 The Sawdust 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 backtracing;
import java.util.ArrayList;
import java.util.List;
/**
* <pre>
* Difficulty: Medium
* Given a set of candidate numbers (C) and a target number (T),
* find all unique combinations in C where the candidate numbers sums to T.
*
* The same repeated number may be chosen from C unlimited number of times.
*
* Note:
* All numbers (including target) will be positive integers.
* The solution set must not contain duplicate combinations.
* For example, given candidate set [2, 3, 6, 7] and target 7,
* A solution set is:
* [
* [7],
* [2, 2, 3]
* ]
* @see <a href="https://leetcode.com/problems/combination-sum/">link</a></a>
*/
public class Leetcode39CombinationSum {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
// int put check
List<List<Integer>> result = new ArrayList();
selectOne(candidates, target, result, new <Integer>ArrayList(), 0, 0);
return result;
}
private void selectOne(int[] candidates, int target, List<List<Integer>> result, List<Integer> cur, int sum, int from) {
if (sum == target) {
result.add(new ArrayList(cur));
return;
}
if (sum > target) {
return;
}
for (int i = from; i < candidates.length; i++) {
cur.add(candidates[i]);
selectOne(candidates, target, result, cur, sum + candidates[i], i);// from i
cur.remove(cur.size() - 1);
}
}
}
| 32.921875 | 124 | 0.651637 |
f6142113ed6d845a68520d1282e6633fc7244425 | 1,650 | package org.smoothbuild.exec.base;
import static com.google.common.collect.Streams.stream;
import static org.smoothbuild.cli.console.Level.ERROR;
import static org.smoothbuild.cli.console.Level.INFO;
import static org.smoothbuild.cli.console.Level.WARNING;
import java.util.Set;
import org.smoothbuild.cli.console.Level;
import org.smoothbuild.db.record.base.Array;
import org.smoothbuild.db.record.base.RString;
import org.smoothbuild.db.record.base.Record;
import org.smoothbuild.db.record.base.Tuple;
public class MessageStruct {
private static final Set<String> SEVERITIES = Set.of(ERROR.name(), WARNING.name(), INFO.name());
private static final int TEXT_INDEX = 0;
private static final int SEVERITY_INDEX = 1;
public static boolean containsErrors(Array messages) {
return stream(messages.asIterable(Tuple.class))
.anyMatch(m -> severity(m).equals(ERROR.name()));
}
public static boolean isValidSeverity(String severity) {
return SEVERITIES.contains(severity);
}
public static boolean isEmpty(Array messages) {
return !messages.asIterable(Tuple.class).iterator().hasNext();
}
public static Level level(Record message) {
return Level.valueOf(severity(message));
}
public static String severity(Record message) {
return messageSeverity((Tuple) message).jValue();
}
public static String text(Record message) {
return messageText((Tuple) message).jValue();
}
public static RString messageText(Tuple message) {
return (RString) message.get(TEXT_INDEX);
}
public static RString messageSeverity(Tuple message) {
return (RString) message.get(SEVERITY_INDEX);
}
}
| 30.555556 | 98 | 0.752121 |
78d7d1f24002fd820cda51a25dcedf9d2f016884 | 1,889 | package net.hogelab.android.androidui.mediacontrolandnotification;
/**
* Created by hirohisa on 2015/01/28.
*/
public class PlayerAction {
public static final String SYSTEM_METACHANGED = "com.android.music.metachanged";
public static final String SYSTEM_PLAYSTATECHANGED = "com.android.music.playstatechanged";
public static final String SYSTEM_PLAYBACKCOMPLETE = "com.android.music.playbackcomplete";
public static final String SYSTEM_QUEUECHANGED = "com.android.music.queuechanged";
public static final String METACHANGED = "net.hogelab.android.androidui.metachanged";
public static final String PLAYSTATECHANGED = "net.hogelab.android.androidui.playstatechanged";
public static final String PLAYBACKCOMPLETE = "net.hogelab.android.androidui.playbackcomplete";
public static final String QUEUECHANGED = "net.hogelab.android.androidui.queuechanged";
public static final String SET_PLAYLIST = "net.hogelab.android.androidui.set_playlist";
public static final String PLAY = "net.hogelab.android.androidui.play";
public static final String STOP = "net.hogelab.android.androidui.stop";
public static final String PAUSE = "net.hogelab.android.androidui.pause";
public static final String TOGGLE_PLAY_PAUSE = "net.hogelab.android.androidui.toggle_play_pause";
public static final String SKIP_TO_NEXT = "net.hogelab.android.androidui.skip_to_next";
public static final String SKIP_TO_PREVIOUS = "net.hogelab.android.androidui.skip_to_previous";
public static final String FAST_FORWARD = "net.hogelab.android.androidui.fast_forward";
public static final String REWIND = "net.hogelab.android.androidui.rewind";
public static final String SEEK_TO = "net.hogelab.android.androidui.seek_to";
public static final String EXTRA_KEY_PLAYLIST = "playlist";
public static final String EXTRA_KEY_POSITION = "position";
}
| 60.935484 | 101 | 0.785601 |
c91453704867da60c4f71affbc7516c5a83d0ab9 | 8,464 | package RenderEngine;
import Models.RawModel;
import org.lwjgl.util.vector.Vector2f;
import org.lwjgl.util.vector.Vector3f;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/*
An Object file parser to prevent hard coding of Models in the game. These object files have certain
characteristics which make parsing a bit tedious and not very portable. Firstly, the lines on the .obj files
are terminated with ASCII newline characters ('\n') and start with certain abbreviations that help identify
a certain aspect of the end model.
Note: Each of the following are preceded by an ASCII Space character and a series of floats
which are also separated by ASCII Space characters
v = Vertex information -> 3D Vector -> Eg. "v -100 -1.45 1.67"
vt = Texture information -> 2D Vector -> Eg. "vt 100 200"
vn = Normal information -> 3D Vector -> Eg. "vn 0.22 0.44 0.66"
f = Face information -> Hard to Explain -> Eg. "f 100/75/23 200/75/23 300/75/33"
The f (Face) is the most crucial piece of information in the file and requires a rather long process of parsing
in order to do correctly. The Face information is followed by a series of numbers which are terminated by ASCII
forward slash characters. Each letter in that sequence represents a vertex in the vertex information.
Each set of numbers in that sequence represents a triangle in the model. The information in the form of:
Vertex Index /Texture Index / Normal Index.
Below is a lot of tedious and rather inefficient way of parsing an OBJ File, but as it only needs to be loaded
once during the instantiation of the game, it has no impact on the performance.
*/
public class OBJLoader {
public static RawModel loadObjModel(String filename, Loader loader) {
FileReader fileReader = null;
// Try to open the file
try {
fileReader = new FileReader(new File("src/Resources/" + filename + ".obj"));
}
catch (FileNotFoundException e) {
System.err.println("An error occurred when loading Object File: " + filename);
e.printStackTrace();
}
// Create a buffered reader for efficient reads from memory
BufferedReader reader = new BufferedReader(fileReader);
String line;
// These lists will hold the vertices, textures coords, normals, and indices as they come from the OBJ File
List<Vector3f> vertices = new ArrayList<Vector3f>();
List<Vector2f> textures = new ArrayList<Vector2f>();
List<Vector3f> normals = new ArrayList<Vector3f>();
List<Integer> indices = new ArrayList<Integer>();
// These arrays will later be initialized to a fixed size and be used to create the final model
float[] verticesArray = null;
float[] texturesArray = null;
float[] normalsArray = null;
int[] indicesArray = null;
// Using try/catch to help debug
try {
// Iterate until broken out of the loop
while(true) {
// Read the line and split it at the space
line = reader.readLine();
String[] currentLine = line.split(" ");
// Vertex Position
if(line.startsWith("v ")) {
// Pull vertex information
Vector3f vertex = new Vector3f( Float.parseFloat(currentLine[1]), Float.parseFloat(currentLine[2]),
Float.parseFloat(currentLine[3]));
vertices.add(vertex);
}
// Texture coordinate
else if(line.startsWith("vt ")) {
// Pull texture coordinate information
Vector2f texture = new Vector2f(Float.parseFloat(currentLine[1]), Float.parseFloat(currentLine[2]));
textures.add(texture);
}
// Normal
else if(line.startsWith("vn ")) {
// Pull normal information
Vector3f normal = new Vector3f( Float.parseFloat(currentLine[1]), Float.parseFloat(currentLine[2]),
Float.parseFloat(currentLine[3]));
normals.add(normal);
}
// Face
// Once we reach the face (which are at the end of the file after the vertices, normals. and texture coords)
// we can initialize our arrays and break out of the loop
else if(line.startsWith("f ")) {
// When we reach here, we would've already gotten all of the vertices in the model
// so we use that information to initialize our arrays to a fixed size
texturesArray = new float[vertices.size() * 2]; // Texture arrays are 2D, so multiple by 2
normalsArray = new float[vertices.size() * 3]; // Normals are 3D, so multiply by 3
break;
}
}
// Now keep reading from the beginning of the face information
while(line != null) {
// If there is somehow a line that does not hold face information, skip to next iteration
if(!line.startsWith("f ")) {
line = reader.readLine();
continue;
}
// Split "f 100/75/20" to ["f", "100/75/20", "200/65/20", "300/75/20"];
String[] currentLine = line.split(" ");
String[] vertex1 = currentLine[1].split("/"); // Get first set of numbers
String[] vertex2 = currentLine[2].split("/"); // 2nd set
String[] vertex3 = currentLine[3].split("/"); // 3rd set
// Process all 3 vertices
processVertex(vertex1, indices, textures, normals, texturesArray, normalsArray);
processVertex(vertex2, indices, textures, normals, texturesArray, normalsArray);
processVertex(vertex3, indices, textures, normals, texturesArray, normalsArray);
line = reader.readLine(); // Read the next line
}
}
catch (Exception e) {
e.printStackTrace();
}
// Initialize our vertices and indices arrays
verticesArray = new float[vertices.size() * 3]; // Vertices are 3D so multiply by 3
indicesArray = new int[indices.size()];
// Iterate over all vertices in the vertices list that we made and add each component
// of that vertex to verticesArray
int vertexPointer = 0;
for(Vector3f vertex : vertices) {
verticesArray[vertexPointer++] = vertex.x;
verticesArray[vertexPointer++] = vertex.y;
verticesArray[vertexPointer++] = vertex.z;
}
// Add all indices into indicesArray
for(int i = 0; i < indices.size(); i++) {
indicesArray[i] = indices.get(i);
}
// Now use the data from the OBJ File to load the model into a VAO for rendering
return loader.loadToVAO(verticesArray, texturesArray, normalsArray, indicesArray);
}
private static void processVertex(String[] vertexData, List<Integer> indices, List<Vector2f> textures,
List<Vector3f> normals, float[] texturesArray, float[] normalsArray) {
// OBJ Files are indexed starting at 1, so we have to subtract 1
int currentVertexPointer = Integer.parseInt(vertexData[0]) - 1;
indices.add(currentVertexPointer); // Add the index for the vertex data to our indicesArray
// Parse texture information from the given vertexData
Vector2f currentIndex = textures.get(Integer.parseInt(vertexData[1]) - 1);
texturesArray[currentVertexPointer * 2] = currentIndex.x;
texturesArray[currentVertexPointer * 2 + 1] = 1 - currentIndex.y; // OBJ files start from bottom right, we start from top-left
// Parse normal information from the given vertexData
Vector3f currentNormal = normals.get(Integer.parseInt(vertexData[2]) - 1);
normalsArray[currentVertexPointer * 3] = currentNormal.x;
normalsArray[currentVertexPointer * 3 + 1] = currentNormal.y;
normalsArray[currentVertexPointer * 3 + 2] = currentNormal.z;
}
} | 48.090909 | 134 | 0.603379 |
c8efdd2480316f12661b15456bd99d2b42388d27 | 416 | package com.groupproject.repository;
import com.groupproject.entities.OrderDetails;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface OrderDetailsRepository extends JpaRepository<OrderDetails , Long> {
//find order details by orderId
List<OrderDetails> findByOrder_OrderId(Long orderId);
}
| 27.733333 | 84 | 0.824519 |
170a7249af68a974454573b66e8ebfdb33a3a81c | 636 | package de.vinado.wicket.participate.components.panels;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
/**
* @author Vincent Nadoll ([email protected])
*/
public class CheckboxPanel<T> extends Panel {
private IModel<T> model;
public CheckboxPanel(final String id, final IModel<T> model) {
super(id, model);
this.model = model;
add(new CheckBox("checkBox"));
}
public T getValue() {
return model.getObject();
}
public IModel<T> getModel() {
return model;
}
}
| 21.931034 | 66 | 0.666667 |
73c737185307e83fbc2855f2a8ddd533444fb71d | 4,942 | /*
* Copyright 2018-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.atayun.bazooka.rms.biz.component.bridge.cluster;
import net.atayun.bazooka.base.annotation.Bridge;
import net.atayun.bazooka.base.annotation.BridgeListAutowired;
import net.atayun.bazooka.base.annotation.StrategyNum;
import net.atayun.bazooka.rms.biz.component.strategy.cluster.ClusterComponentStatusCalcStrategy;
import net.atayun.bazooka.rms.biz.dal.entity.RmsClusterConfigEntity;
import net.atayun.bazooka.rms.biz.enums.ClusterConfigTypeEnum;
import lombok.extern.slf4j.Slf4j;
import net.atayun.bazooka.rms.biz.enums.ClusterStatusEnum;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
import static net.atayun.bazooka.base.utils.EnumUtil.getEnum;
import static net.atayun.bazooka.base.utils.StringUtil.eq;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;
import static org.springframework.core.annotation.AnnotationUtils.findAnnotation;
/**
* @author pqq
* @version v1.0
* @date 2019年7月17日 17:00:00
* @work dcos集群状态计算桥接
*/
@Slf4j
@Component
@StrategyNum(superClass = ClusterStatusCalcBridge.class, number = "0", describe = "计算Dcos集群状态")
@Bridge(associationClass = ClusterComponentStatusCalcStrategy.class, describe = "桥接ClusterComponentStatusCalcStrategy列表集合")
public class ClusterStatusCalcBridge4Dcos extends ClusterStatusCalcBridge {
/**
* 桥接注入
*
* @param clusterComponentStatusCalcStrategies
*/
@BridgeListAutowired(bridgeValues = {"0", "1", "2", "3", "4", "5"})
public void setClusterStatusCalcStrategies(List<ClusterComponentStatusCalcStrategy> clusterComponentStatusCalcStrategies) {
this.clusterComponentStatusCalcStrategies = clusterComponentStatusCalcStrategies;
}
@Override
protected String doCalcClusterStatus(List<RmsClusterConfigEntity> rmsClusterConfigEntities) {
Map<String, List<RmsClusterConfigEntity>> map = rmsClusterConfigEntities.stream().collect(groupingBy(RmsClusterConfigEntity::getType));
for (ClusterComponentStatusCalcStrategy clusterComponentStatusCalcStrategy : clusterComponentStatusCalcStrategies) {
StrategyNum strategyNum = findAnnotation(clusterComponentStatusCalcStrategy.getClass(), StrategyNum.class);
clusterComponentStatusCalcStrategy.calcComponentStatus(map.get(strategyNum.number()));
}
return doCalcDcosClusterStatus(rmsClusterConfigEntities, map);
}
/**
* 计算dcos集群状态
*
* @param rmsClusterConfigEntities
* @param map
* @return
*/
private String doCalcDcosClusterStatus(List<RmsClusterConfigEntity> rmsClusterConfigEntities, Map<String, List<RmsClusterConfigEntity>> map) {
List<RmsClusterConfigEntity> dcosRmsClusterConfigEntities = rmsClusterConfigEntities.stream().filter(r -> getEnum(ClusterConfigTypeEnum.class, r.getType()).canRefreshDcosStatus()).collect(toList());
boolean normalFlag = dcosRmsClusterConfigEntities.stream().allMatch(r -> eq(r.getStatus(), ClusterStatusEnum.NORMAL.getCode()));
if (normalFlag) {
return ClusterStatusEnum.NORMAL.getCode();
}
List<RmsClusterConfigEntity> dockerHubClusterConfigEntities = map.get(ClusterConfigTypeEnum.DOCKER_HUB.getCode());
boolean dockerHubAbnormalFlag = dockerHubClusterConfigEntities.stream().anyMatch(r -> eq(r.getStatus(), ClusterStatusEnum.ABNORMAL.getCode()));
if (dockerHubAbnormalFlag) {
return ClusterStatusEnum.ABNORMAL.getCode();
}
List<RmsClusterConfigEntity> marathonClusterConfigEntities = map.get(ClusterConfigTypeEnum.MARATHON.getCode());
boolean marathonAbnormalFlag = marathonClusterConfigEntities.stream().allMatch(r -> eq(r.getStatus(), ClusterStatusEnum.ABNORMAL.getCode()));
if (marathonAbnormalFlag) {
return ClusterStatusEnum.ABNORMAL.getCode();
}
List<RmsClusterConfigEntity> mlbClusterConfigEntities = map.get(ClusterConfigTypeEnum.MLB.getCode());
boolean mlbAbnormalFlag = mlbClusterConfigEntities.stream().allMatch(r -> eq(r.getStatus(), ClusterStatusEnum.ABNORMAL.getCode()));
if (mlbAbnormalFlag) {
return ClusterStatusEnum.ABNORMAL.getCode();
}
return ClusterStatusEnum.USABLE.getCode();
}
}
| 47.066667 | 206 | 0.75435 |
0cb5925c459385ada9cb1771244760663c0d181e | 381 | package arrays;
import java.util.Arrays;
public class ArraysBinarySearch2 {
public static void main(String[] args) {
int arr[] = {29, 3, 50, 9, 12, 73, 5, 89, 5, 34, 8, 97};
int key = 12;
Arrays.sort(arr);
System.out.println("Arrays after sort: "+Arrays.toString(arr));
System.out.println(key + " found at index: "+ Arrays.binarySearch(arr, 0, 10, key));
}
}
| 21.166667 | 86 | 0.643045 |
5160404f690cbd4af7db5360323c1fb8df95006f | 585 | package uk.gov.hmcts.reform.sscs.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "No appeal for given id")
public class AppealNotFoundException extends RuntimeException {
public AppealNotFoundException(String appealNumber) {
super(String.format("Appeal not found for appeal number: %s ", appealNumber));
}
public AppealNotFoundException(Long caseId) {
super(String.format("Appeal not found for case id: %s ", caseId));
}
}
| 32.5 | 86 | 0.752137 |
16e990c4efadc69d4e22fcd167a249e76169fb6e | 2,437 | import java.io.*;
import java.util.*;
public class Main {
static FastReader fastReader = new FastReader();
static StringBuilder sb = new StringBuilder();
static void input() {
N = fastReader.nextInt();
column = new int[N + 1];
}
static int N, ans;
static int[] column;
static boolean validityCheck(int row, int col) {
// 이전 로우들에 대해 validation check
for (int prevRow = 1; prevRow < row; prevRow++) {
int prevColumn = column[prevRow];
if (prevColumn == col) { // 세로 체크
return false;
}
if (Math.abs(prevRow - row) == Math.abs(prevColumn - col)) { // 대각선 체크
return false;
}
}
return true;
}
static void recFunc(int row) {
if (row == N + 1) {
ans++;
return;
}
for (int col = 1; col <= N; col++) {
column[row] = col;
if (validityCheck(row, col)) {
recFunc(row + 1);
}
column[row] = 0;
}
}
public static void main(String[] args) {
input();
recFunc(1);
System.out.println(ans);
}
// FastReader
static class FastReader {
private BufferedReader br;
private StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(new File(s)));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| 25.123711 | 82 | 0.472302 |
290693d320bc960ae9ae4dcc955b09f591299738 | 476 | ////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Of Fire Twins Wesp 2015. /
// Alise Wesp & Yuuki Wesp /
////////////////////////////////////////////////////////////////////////////////
package RC.Framework.Network;
public abstract class NetworkObject
{
public abstract byte[] ToByte();
public abstract void outByte(byte[] bitBox);
}
| 36.615385 | 80 | 0.342437 |
2f2fa661e431f01ba881b94824f5920e5bd04fd9 | 131 | package oocl.ita.keyboardman.parkinglotmanagerhelperbackend.exception;
public class NoFeezeException extends RuntimeException {
}
| 26.2 | 70 | 0.870229 |
a018777ebffe224ed7c96d09301e0fc05cc6b6da | 1,178 | package com.divide2.product.vo;
import com.divide2.product.dto.UnitDTO;
import com.divide2.product.model.Product;
import com.divide2.product.model.ProductSpec;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.List;
/**
* @author bvvy
* @date 2018/8/16
*/
@Data
@ApiModel("产品列表数据")
public class ProductVO {
@ApiModelProperty("id")
private String id;
/**
* 名称
*/
@ApiModelProperty("名称")
private String name;
@ApiModelProperty("图片")
private String [] image;
@ApiModelProperty("创建时间")
private LocalDateTime createTime;
/**
* 备注 描述
*/
@ApiModelProperty("备注描述")
private String remarks;
@ApiModelProperty("单位信息")
private List<UnitDTO> units;
@ApiModelProperty("产品规格")
private List<ProductSpec> specs;
public static ProductVO of(Product product) {
ProductVO vo = new ProductVO();
vo.setId(product.getId());
vo.setImage(product.getImage());
vo.setName(product.getName());
vo.setRemarks(product.getRemarks());
return vo;
}
}
| 20.310345 | 49 | 0.664686 |
0ce8b5e2c9cada3c155e8f39d41854679937ee65 | 1,333 | package com.destiny.squirrel.utils;
import com.destiny.squirrel.entity.User;
import lombok.extern.slf4j.Slf4j;
import ognl.Ognl;
import ognl.OgnlException;
import java.util.HashMap;
import java.util.Map;
/**
* @Description ognl 数据
* @Author liangwenchao
* @Date 2021-11-18 10:10 AM
*/
@Slf4j
public class OgnlTest {
public static void main(String[] args) throws OgnlException {
User user = new User();
user.setName("小明");
user.setId(2L);
user.setAddress("北京市");
user.setEmail("[email protected]");
Map<String, String> context = new HashMap<>();
context.put("introduction", "My name is ");
// 测试从Root对象中进行表达式计算并获取结果
Object name = Ognl.getValue(Ognl.parseExpression("name"), user);
System.out.println(name.toString());
// 测试从上下文环境中进行表达式计算并获取结果
Object contextValue = Ognl.getValue(Ognl.parseExpression("#introduction"), context, user);
System.out.println(contextValue);
// 测试同时从将Root对象和上下文环境作为表达式的一部分进行计算
Object hello = Ognl.getValue(Ognl.parseExpression("#introduction + name"), context, user);
System.out.println(hello);
// 对Root对象进行写值操作
// Ognl.setValue("group.name", user, "dev");
Ognl.setValue("age", user, "18");
System.out.println(user);
}
}
| 24.685185 | 98 | 0.645161 |
a4bf28a3794e7e61864e7a88a081a440b0e1320a | 7,282 | package org.ovirt.engine.ui.userportal.section.main.presenter.tab.basic;
import java.util.Arrays;
import org.ovirt.engine.core.compat.Event;
import org.ovirt.engine.core.compat.EventArgs;
import org.ovirt.engine.core.compat.IEventListener;
import org.ovirt.engine.ui.common.widget.HasEditorDriver;
import org.ovirt.engine.ui.uicommonweb.models.userportal.UserPortalBasicListModel;
import org.ovirt.engine.ui.uicommonweb.models.userportal.UserPortalItemModel;
import org.ovirt.engine.ui.userportal.section.main.presenter.popup.console.ConsoleModelChangedEvent;
import org.ovirt.engine.ui.userportal.section.main.presenter.popup.console.ConsoleModelChangedEvent.ConsoleModelChangedHandler;
import org.ovirt.engine.ui.userportal.uicommon.model.UserPortalModelInitEvent;
import org.ovirt.engine.ui.userportal.uicommon.model.UserPortalModelInitEvent.UserPortalModelInitHandler;
import org.ovirt.engine.ui.userportal.uicommon.model.basic.UserPortalBasicListProvider;
import org.ovirt.engine.ui.userportal.utils.ConsoleManager;
import org.ovirt.engine.ui.userportal.widget.basic.ConsoleProtocol;
import org.ovirt.engine.ui.userportal.widget.basic.ConsoleUtils;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.DoubleClickEvent;
import com.google.gwt.event.dom.client.DoubleClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.dom.client.HasDoubleClickHandlers;
import com.google.gwt.event.dom.client.HasMouseOutHandlers;
import com.google.gwt.event.dom.client.HasMouseOverHandlers;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.inject.Inject;
import com.gwtplatform.mvp.client.PresenterWidget;
import com.gwtplatform.mvp.client.View;
public class MainTabBasicListItemPresenterWidget extends PresenterWidget<MainTabBasicListItemPresenterWidget.ViewDef> implements MouseOutHandler, MouseOverHandler, ClickHandler, DoubleClickHandler {
private final ConsoleUtils consoleUtils;
private ConsoleProtocol selectedProtocol;
private UserPortalItemModel model;
private UserPortalBasicListModel listModel;
private final UserPortalBasicListProvider modelProvider;
private final ConsoleManager consoleManager;
public interface ViewDef extends View, HasEditorDriver<UserPortalItemModel>, HasMouseOutHandlers, HasMouseOverHandlers, HasClickHandlers, HasDoubleClickHandlers {
void showDoubleClickBanner();
void hideDoubleClickBanner();
void setVmUpStyle();
void setVmDownStyle();
void setMouseOverStyle();
void setSelected();
void setNotSelected(boolean vmIsUp);
void showErrorDialog(String message);
}
@Inject
public MainTabBasicListItemPresenterWidget(EventBus eventBus,
ViewDef view,
ConsoleUtils consoleUtils,
final UserPortalBasicListProvider modelProvider,
ConsoleManager consoleManager) {
super(eventBus, view);
this.consoleUtils = consoleUtils;
this.modelProvider = modelProvider;
this.consoleManager = consoleManager;
eventBus.addHandler(ConsoleModelChangedEvent.getType(), new ConsoleModelChangedHandler() {
@Override
public void onConsoleModelChanged(ConsoleModelChangedEvent event) {
// update only when my model has changed
if (sameEntity(model, event.getItemModel())) {
setupSelectedProtocol(model);
}
}
});
getEventBus().addHandler(UserPortalModelInitEvent.getType(), new UserPortalModelInitHandler() {
@Override
public void onUserPortalModelInit(UserPortalModelInitEvent event) {
listenOnSelectedItemChanged(modelProvider);
}
});
listenOnSelectedItemChanged(modelProvider);
}
private void listenOnSelectedItemChanged(UserPortalBasicListProvider modelProvider) {
modelProvider.getModel().getSelectedItemChangedEvent().addListener(new IEventListener() {
@Override
public void eventRaised(Event ev, Object sender, EventArgs args) {
if (!sameEntity((UserPortalItemModel) listModel.getSelectedItem(), model)) {
getView().setNotSelected(model.IsVmUp());
} else {
getView().setSelected();
}
}
});
}
public void setModel(final UserPortalItemModel model) {
this.model = model;
this.listModel = modelProvider.getModel();
setupSelectedProtocol(model);
setupDefaultVmStyles();
getView().edit(model);
if (sameEntity((UserPortalItemModel) listModel.getSelectedItem(), model)) {
setSelectedItem();
}
}
protected void setupSelectedProtocol(final UserPortalItemModel model) {
selectedProtocol = consoleUtils.determineDefaultProtocol(model);
}
protected boolean sameEntity(UserPortalItemModel prevModel, UserPortalItemModel newModel) {
if (prevModel == null || newModel == null) {
return false;
}
return modelProvider.getKey(prevModel).equals(modelProvider.getKey(newModel));
}
@Override
protected void onBind() {
super.onBind();
registerHandler(getView().addMouseOutHandler(this));
registerHandler(getView().addMouseOverHandler(this));
registerHandler(getView().addClickHandler(this));
registerHandler(getView().addDoubleClickHandler(this));
}
@Override
public void onMouseOut(MouseOutEvent event) {
getView().hideDoubleClickBanner();
setupDefaultVmStyles();
}
private void setupDefaultVmStyles() {
if (!isSelected()) {
if (model.IsVmUp()) {
getView().setVmUpStyle();
} else {
getView().setVmDownStyle();
}
}
}
@Override
public void onMouseOver(MouseOverEvent event) {
if (!isSelected()) {
getView().setMouseOverStyle();
}
if (canShowConsole()) {
getView().showDoubleClickBanner();
}
}
@Override
public void onDoubleClick(DoubleClickEvent event) {
String res = consoleManager.connectToConsole(selectedProtocol, model);
if (res != null) {
getView().showErrorDialog(res);
}
}
@Override
public void onClick(ClickEvent event) {
if (!isSelected()) {
setSelectedItem();
}
}
protected void setSelectedItem() {
listModel.setSelectedItem(model);
modelProvider.setSelectedItems(Arrays.asList(model));
getView().setSelected();
}
private boolean canShowConsole() {
return consoleUtils.canShowConsole(selectedProtocol, model);
}
boolean isSelected() {
return sameEntity((UserPortalItemModel) listModel.getSelectedItem(), model);
}
}
| 34.511848 | 198 | 0.700494 |
472610f11047860d522163218b82333855eefe92 | 1,880 | package com.gu.test.Common;
import com.gu.test.helpers.PageHelper;
import com.gu.test.pages.FrontPage;
import com.gu.test.pages.SectionFront;
import com.gu.test.shared.NavigationBar;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import static com.gu.test.WebDriverFactory.createWebDriver;
public class NavigationBarTest {
WebDriver driver;
private PageHelper pageHelper;
private NavigationBar navigationBar;
@Before
public void setUp() throws Exception {
driver = createWebDriver();
pageHelper = new PageHelper(driver);
navigationBar = new NavigationBar(driver);
pageHelper.goToFronts();
}
@Test
public void changingFromUKtoUSEdition() throws Exception {
navigationBar.goToEdition("US");
Assert.assertTrue("Failure: not seeing US fronts", driver.getCurrentUrl().contentEquals(pageHelper.getBaseUrl() + "/us"));
}
@Test
public void changingFromUKtoAUEdition() throws Exception {
navigationBar.goToEdition("AU");
Assert.assertTrue("Failure: not seeing AU fronts", driver.getCurrentUrl().contentEquals(pageHelper.getBaseUrl() + "/au"));
}
@Test
public void goToFootballFrontsViaNavBar() throws Exception {
navigationBar.goToFootballFront();
Assert.assertTrue("Failure: not seeing football fronts", driver.getCurrentUrl().contentEquals(pageHelper.getBaseUrl() + "/football"));
}
@Test
public void goToWorldNewsFrontsViaNavBar() throws Exception {
navigationBar.goToWorldNewsFront();
Assert.assertTrue("Failure: not seeing world news fronts", driver.getCurrentUrl().contentEquals(pageHelper.getBaseUrl() + "/world"));
}
@After
public void tearDown() throws Exception {
pageHelper.endTest();
}
}
| 30.819672 | 142 | 0.713298 |
346e2b66beb97dd05ea4a05caf003268b8b8a8ea | 1,098 | package org.eck;
import java.util.HashMap;
import java.util.Map;
import org.eck.exceptions.NoCollectorRegistredException;
import org.sql2o.Sql2o;
public class Yno {
private Sql2o sql2o;
@SuppressWarnings("rawtypes")
private Map<Class, Collector> collectors = new HashMap<Class, Collector>();
public Yno(String url, String user, String password) {
this.sql2o = new Sql2o(url, user, password);
}
@SuppressWarnings("rawtypes")
public void registerCollector(Class clazz, Collector collector) {
collectors.put(clazz, collector);
}
public Inserter insert(Object obj) {
Collector collector = collectors.get(obj.getClass());
if(collector == null) {
throw new NoCollectorRegistredException();
}
return new Inserter(collector, sql2o, obj);
}
public Updater update(Object obj) {
Collector collector = collectors.get(obj.getClass());
if(collector == null) {
throw new NoCollectorRegistredException();
}
return new Updater(collector, sql2o, obj);
}
}
| 27.45 | 79 | 0.661202 |
c41aecc93a99a07065046e65f5294f6005412683 | 1,967 | package de.uni_hildesheim.sse.vil.templatelang.ui.resources;
public class Images {
// VIL build language (also includes images for VIL template language)
public static final String NAME_ADVICE = "advice.jpg";
public static final String NAME_IMPORT = "import.jpg";
public static final String NAME_PARAMLIST = "parameter_list.jpg";
public static final String NAME_PARAM = "parameter.jpg";
public static final String NAME_PROP = "property.jpg";
public static final String NAME_RULE = "rule.jpg";
public static final String NAME_RULE_INSTANCE = "rule_instance.jpg";
public static final String NAME_OPERATION = "operation.jpg";
public static final String NAME_SCRIPTCONTENT = "script_contents.jpg";
public static final String NAME_VARIABLEDECLARATION = "variable_declaration.gif";
public static final String NAME_TYPEDEF = "typedef.jpg";
public static final String NAME_COMPOUND = "compound.jpg";
public static final String NAME_TYPE = "type.jpg";
public static final String NAME_VERSION = "version.jpg";
public static final String NAME_VILSCRIPT = "vilScript.jpg";
public static final String NAME_VILSCRIPTEXTENSION = "script_extension.jpg";
public static final String NAME_PATHPATTERN = "path_pattern.jpg";
public static final String NAME_INSTANTIATOR = "instantiator.jpg";
public static final String NAME_INSTANTIATE = "instantiate.jpg";
public static final String NAME_MAP = "map.jpg";
public static final String NAME_JOIN = "join.jpg";
// Additions for VIL template language (exlcusive)
public static final String NAME_DEF = "def.jpg";
public static final String NAME_INDENT = "indent.jpg";
public static final String NAME_JAVAEXT = "java_ext.jpg";
public static final String NAME_PARAMETERLIST = "parameter_list.jpg";
public static final String NAME_PARAMETER = "parameter.jpg";
public static final String NAME_VILTEMPLATE = "template.jpg";
}
| 54.638889 | 85 | 0.751398 |
d9b5b78112e8cd5065e5ea024a86c93c2ebaaba9 | 2,429 | /*
* Copyright 2018 Matt Liotta
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.tokhn.store;
import java.util.List;
import java.util.NavigableSet;
import java.util.stream.Collectors;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.mapdb.HTreeMap;
import org.mapdb.Serializer;
import io.tokhn.codec.HashSerializer;
import io.tokhn.codec.UTXOSerializer;
import io.tokhn.core.Address;
import io.tokhn.core.UTXO;
import io.tokhn.node.Network;
import io.tokhn.util.Hash;
public class MapDBUTXOStore implements UTXOStore, AutoCloseable {
private final Network network;
private final DB db;
private HTreeMap<Hash, UTXO> utxos;
private NavigableSet<byte[]> utxoIndex;
public MapDBUTXOStore(Network network) {
this.network = network;
db = DBMaker.fileDB("UStore-" + network.toString() + ".db").closeOnJvmShutdown().make();
utxos = db.hashMap("utxos").keySerializer(new HashSerializer()).valueSerializer(new UTXOSerializer()).createOrOpen();
utxoIndex = db.treeSet("utxoIndex").serializer(Serializer.BYTE_ARRAY).createOrOpen();
}
@Override
public void put(UTXO utxo) {
utxos.put(utxo.getUtxoId(), utxo);
utxoIndex.add(utxo.getUtxoId().getBytes());
db.commit();
}
@Override
public UTXO get(Hash utxoId) {
return utxos.get(utxoId);
}
@Override
public void remove(Hash utxoId) {
utxos.remove(utxoId);
utxoIndex.remove(utxoId.getBytes());
db.commit();
}
@Override
public Network getNetwork() {
return network;
}
@Override
public void close() throws Exception {
db.close();
}
@Override
public List<UTXO> getUtxos() {
return utxoIndex.stream().map(utxoId -> utxos.get(new Hash(utxoId))).collect(Collectors.toList());
}
@Override
public List<UTXO> getUtxosForAddress(Address address) {
return utxoIndex.stream().map(utxoId -> utxos.get(new Hash(utxoId))).filter(uxto -> uxto.getAddress().equals(address)).collect(Collectors.toList());
}
} | 28.244186 | 150 | 0.738576 |
58ce953306d0d92bc0b7126f1d211f870f5a60dd | 66 | package com.lu.test.beantest.service;
public class LuServie {
}
| 11 | 37 | 0.757576 |
1b66c2e22796c35b4d71f2d8cf85b93fc27803c7 | 8,401 | /*
The MIT License
Copyright 2016, 2017, 2018 Rudy Alex Kohn.
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 token;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import utility.Base64Coder;
public class TokenHandler {
private static TokenHandler instance;
// in minuttes.
private static final int TOKEN_LIFETIME = 10;
// 16 chars = 16 byte = 128 bit
private final static String KEY = "Summer petrichor";
private final static String SIGNATURE = "Tessaract, the four dimensional equivalent of a cube.";
private final static String SIGNATURE_KEY = "Tetradecahedrons";
public static TokenHandler getInstance() {
if (instance == null) {
instance = new TokenHandler();
}
return instance;
}
public String createToken(final String user_id) {
if (user_id.contains("\n")) {
throw new IllegalArgumentException("User Id cannot contain line breaks!");
}
final String signature = encrypt(SIGNATURE, SIGNATURE_KEY);
final String timestamp = prettyTime();
final String unixTime = String.valueOf(System.currentTimeMillis());
final String token = signature + '\n' + user_id + "\n" + timestamp + '\n' + unixTime;
return encrypt(token);
}
public String validateToken(final String token) {
try {
final String _data = decrypt(token);
final String[] data = _data.split("\n");
final String actual_signature = decrypt(data[0], SIGNATURE_KEY);
if (!SIGNATURE.equals(actual_signature)) {
System.err.println("Token signature doesn't match");
return null;
}
final String _unixTime = data[3];
final long unixTime = Long.parseLong(_unixTime);
if (unixTime + toMillis(TOKEN_LIFETIME, TimeUnit.MINUTES) > System.currentTimeMillis()) {
data[2] = prettyTime();
data[3] = String.valueOf(System.currentTimeMillis());
final StringBuilder sb = new StringBuilder();
for (final String s : data) {
sb.append(s).append('\n');
}
return sb.toString();
}
System.err.println("Token timed out");
return null;
} catch (final Exception e) {
return null;
}
}
public static String getUserID(final String token) {
try {
final String _data = decrypt(token);
final String[] data = _data.split("\n");
return data[1];
} catch (final Exception e) {
return null;
}
}
public static String getTimestamp(final String token) {
try {
final String _data = decrypt(token);
final String[] data = _data.split("\n");
return data[2];
} catch (final Exception e) {
return null;
}
}
public static String getUnixTime(final String token) {
try {
final String _data = decrypt(token);
final String[] data = _data.split("\n");
return data[3];
} catch (final Exception e) {
return null;
}
}
public static String encrypt(final String token) {
return encrypt(token, KEY);
}
public static String encrypt(final String token, final String key) {
try {
final Key aesKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
final IvParameterSpec ivParameterSpec = new IvParameterSpec(aesKey.getEncoded());
cipher.init(Cipher.ENCRYPT_MODE, aesKey, ivParameterSpec);
final byte[] encrypted = cipher.doFinal(token.getBytes("UTF-8"));
return Base64Coder.encodeLines(encrypted);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | UnsupportedEncodingException | InvalidAlgorithmParameterException e) {
e.printStackTrace();
}
return null;
}
public static String decrypt(final String encrypted) {
return decrypt(encrypted, KEY);
}
public static String decrypt(final String encrypted, final String key) {
try {
final Key aesKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
final IvParameterSpec ivParameterSpec = new IvParameterSpec(aesKey.getEncoded());
cipher.init(Cipher.DECRYPT_MODE, aesKey, ivParameterSpec);
final String token = new String(cipher.doFinal(Base64Coder.decode(encrypted)));
return token;
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | UnsupportedEncodingException | InvalidAlgorithmParameterException e) {
e.printStackTrace();
}
return null;
}
private String prettyTime() {
return prettyTime(System.currentTimeMillis());
}
private String prettyTime(final long millis) {
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(millis);
final int sec = cal.get(Calendar.SECOND);
final String _sec = String.format("%02d", sec);
final int min = cal.get(Calendar.MINUTE);
final String _min = String.format("%02d", min);
final int hour = cal.get(Calendar.HOUR_OF_DAY);
final String _hour = String.format("%02d", hour);
final int day = cal.get(Calendar.DAY_OF_MONTH);
final String _day = String.format("%02d", day);
final int month = cal.get(Calendar.MONTH) + 1;
final String _month = String.format("%02d", month);
final int year = cal.get(Calendar.YEAR);
final String _year = Integer.toString(year);
final String time = _hour + ":" + _min + ":" + _sec + " " + _day + "/" + _month + "-" + _year;
return time;
}
@SuppressWarnings("fallthrough")
private static int toMillis(int value, final TimeUnit unit) {
switch (unit) {
case DAYS:
value *= 24;
case HOURS:
value *= 60;
case MINUTES:
value *= 60;
case SECONDS:
value *= 1000;
case MILLISECONDS:
return value;
case MICROSECONDS:
throw new UnsupportedOperationException("Microseconds is not supported");
case NANOSECONDS:
throw new UnsupportedOperationException("Nanoseconds is not supported");
default:
throw new UnsupportedOperationException("The timeunit " + unit + " is not supported");
}
}
}
| 39.441315 | 211 | 0.637781 |
97400b47fee5cdcc55153c04b171a05a7de845ba | 309 | package bashir1.fueltrack;
/**
* Created by bashir1 on 1/28/16.
*/
/* https://github.com/b26/FillerCreepForAndroid/blob/master/app/src/main/java/es/softwareprocess/fillercreep/FView.java */
public interface LogView<Model> {
/* gets called by the model in notifyViews*/
void update(Model model);
}
| 25.75 | 122 | 0.728155 |
118eeaaf5dbc854710b30d5219dae9ce8af33de5 | 356 | package com.testwithspring.starter.testdata.javabean;
/**
* Declares the methods used to delete {@code Task} objects.
*/
public interface TaskRepository {
/**
* Deletes task whose id is given as a method parameter.
* @param id The id of the requested task.
* @return The deleted task.
*/
Task deleteById(Long id);
}
| 23.733333 | 60 | 0.657303 |
62826af7a20bb25b597c358df7bbe7407036e3f6 | 1,935 | package cn.yiya.shiji.entity;
import java.util.List;
/** 店铺单个订单佣金明细
* Created by Amy on 2016/10/20.
*/
public class OrderCashInfo {
/**
* cash_amount : 200 //佣金总计
* goods_list : [{"id":"1324jj23h11","num":2,"title":"nike","price":22,"goods_cash":100}]
*/
private int cash_amount;
/**
* id : 1324jj23h11 //商品id
* num : 2 //商品数量
* title : nike //商品名
* price : 22 //商品价格
* goods_cash : 100 //商品佣金
*/
private List<GoodsListEntity> goods_list;
public int getCash_amount() {
return cash_amount;
}
public void setCash_amount(int cash_amount) {
this.cash_amount = cash_amount;
}
public List<GoodsListEntity> getGoods_list() {
return goods_list;
}
public void setGoods_list(List<GoodsListEntity> goods_list) {
this.goods_list = goods_list;
}
public static class GoodsListEntity {
private String id;
private int num;
private String title;
private int price;
private int goods_cash;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getGoods_cash() {
return goods_cash;
}
public void setGoods_cash(int goods_cash) {
this.goods_cash = goods_cash;
}
}
}
| 21.263736 | 94 | 0.513178 |
b1b6ee8f675adf3910f521958a49d9a4f1b22c88 | 2,834 | package xyz.kkt.burpplefoodplaces.mvp.presenters;
import android.content.Context;
import android.database.Cursor;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import xyz.kkt.burpplefoodplaces.BurppleApp;
import xyz.kkt.burpplefoodplaces.data.model.BurppleModel;
import xyz.kkt.burpplefoodplaces.data.vos.FeaturedVO;
import xyz.kkt.burpplefoodplaces.data.vos.GuideVO;
import xyz.kkt.burpplefoodplaces.data.vos.PromotionVO;
import xyz.kkt.burpplefoodplaces.mvp.views.MainView;
/**
* Created by Lenovo on 1/6/2018.
*/
public class MainPresenter extends BasePresenter<MainView> {
@Inject
BurppleModel mBurppleModel;
public MainPresenter() {
}
@Override
public void onCreate(MainView view) {
super.onCreate(view);
BurppleApp burppleApp = (BurppleApp) mView.getContext();
burppleApp.getBurppleAppComponent().inject(this);
}
@Override
public void onStart() {
// EventBus.getDefault().register(this);
mBurppleModel.startLoadingFood(mView.getContext());
}
@Override
public void onStop() {
//EventBus.getDefault().unregister(this);
}
public void onProListEndReach(Context context) {
mBurppleModel.loadMorePromotion(mView.getContext());
}
public void onGuiListEndReach(Context context) {
mBurppleModel.loadMoreGuide(mView.getContext());
}
// public void onForceRefresh(Context context) {
// mNewsModel.forceRefreshNews(context);
// }
public void onProDataLoaded(Cursor data) {
if (data != null && data.moveToFirst()) {
List<PromotionVO> promotionList = new ArrayList<>();
do {
PromotionVO promotion = PromotionVO.parseFromCursor(mView.getContext(), data);
promotionList.add(promotion);
} while (data.moveToNext());
{
mView.displayPromotionList(promotionList);
}
}
}
public void onGuiDataLoaded(Cursor data) {
if (data != null && data.moveToFirst()) {
List<GuideVO> guideList = new ArrayList<>();
do {
GuideVO guide = GuideVO.parseFromCursor(data);
guideList.add(guide);
} while (data.moveToNext());
{
mView.displayGuideList(guideList);
}
}
}
public void onFeaDataLoaded(Cursor data) {
if (data != null && data.moveToFirst()) {
List<FeaturedVO> featuredList = new ArrayList<>();
do {
FeaturedVO featured = FeaturedVO.parseFromCursor(data);
featuredList.add(featured);
} while (data.moveToNext());
{
mView.displayFeaturedImgList(featuredList);
}
}
}
}
| 28.059406 | 94 | 0.6235 |
ff1be40d1c73d90f2668c90a5f823849ab3f7db9 | 1,713 | @Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
XMPPService xmpp = XMPPServiceFactory.getXMPPService();
Message msg = xmpp.parseMessage(req);
JID jid = msg.getFromJid();
String body = msg.getBody();
LOG.info(jid.getId() + " --> JEliza: " + body);
Key key = KeyFactory.createKey("chatData", ":" + jid.getId());
Entity lastLineEntity = null;
try {
lastLineEntity = DatastoreServiceFactory.getDatastoreService().get(key);
} catch (EntityNotFoundException e) {
lastLineEntity = new Entity(key);
lastLineEntity.setProperty(LINE, "");
}
final String lastLine = (String) lastLineEntity.getProperty(LINE);
final StringBuilder response = new StringBuilder();
final ElizaParse parser = new ElizaParse() {
@Override
public void PRINT(String s) {
if (lastLine.trim().length() > 0 && s.startsWith("HI! I'M ELIZA")) {
return;
}
response.append(s);
response.append('\n');
}
};
parser.lastline = lastLine;
parser.handleLine(body);
body = response.toString();
LOG.info(jid.getId() + " <-- JEliza: " + body);
msg = new MessageBuilder().withRecipientJids(jid).withBody(body).build();
xmpp.sendMessage(msg);
if (parser.exit) {
lastLineEntity.setProperty(LINE, "");
} else {
lastLineEntity.setProperty(LINE, parser.lastline);
}
DatastoreServiceFactory.getDatastoreService().put(lastLineEntity);
}
| 40.785714 | 93 | 0.575015 |
9d37be681dcbc9aacb8c3efe9ab07363aa294df7 | 12,252 | package top.nowandfuture.gamebrowser.gui;
import com.mojang.blaze3d.matrix.MatrixStack;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.util.ResourceLocation;
import net.montoyo.mcef.api.*;
import org.jline.utils.Log;
import top.nowandfuture.gamebrowser.InGameBrowser;
import top.nowandfuture.gamebrowser.utils.RenderHelper;
import top.nowandfuture.mygui.RootView;
import top.nowandfuture.mygui.ViewGroup;
import javax.annotation.Nullable;
import java.awt.event.MouseEvent;
import java.util.Optional;
public class BrowserView extends ViewGroup {
private String browserRenderId;
private IBrowser browser;
private String urlToLoad;
// TODO: 2021/8/8 create the html home page for this mod
private String home;
private IDisplayHandler displayHandler;
private IFocusListener focusListener;
private int outsideLight = RenderHelper.SKY_LIGHT;
public void setFocusListener(IFocusListener focusListener) {
this.focusListener = focusListener;
}
public String getBrowserRenderId() {
return browserRenderId;
}
public void setBrowserRenderId(String browserRenderId) {
this.browserRenderId = browserRenderId;
}
public int getOutsideLight() {
return outsideLight;
}
public void setOutsideLight(int outsideLight) {
this.outsideLight = outsideLight;
}
public interface IFocusListener {
void onFocusChanged(boolean f);
}
public BrowserView(RootView rootView) {
super(rootView);
}
@Override
public void onCreate(RootView rootView, @Nullable ViewGroup parent) {
home = InGameBrowser.getHomePage();
}
public void setUrl(String urlToLoad) {
Optional.ofNullable(browser)
.ifPresent(iBrowser -> {
if(iBrowser.isActivate())
iBrowser.loadURL(urlToLoad);
});
}
public void setUrlToLoad(String urlToLoad) {
this.urlToLoad = urlToLoad;
}
public BrowserView(ViewGroup parent) {
super(parent);
}
public IBrowser getBrowser() {
return browser;
}
@Override
protected void onLoad() {
super.onLoad();
API api = MCEFApi.getAPI();
if (api != null) {
api.registerDisplayHandler(new IDisplayHandler() {
@Override
public void onAddressChange(IBrowser browser, String url) {
//ugliness codes...
Optional.ofNullable(getDisplayHandler())
.ifPresent(iDisplayHandler -> {
if (getBrowser() == browser) {
iDisplayHandler.onAddressChange(browser, url);
}
});
}
@Override
public void onTitleChange(IBrowser browser, String title) {
Optional.ofNullable(getDisplayHandler())
.ifPresent(iDisplayHandler -> {
if (getBrowser() == browser) {
iDisplayHandler.onTitleChange(browser, title);
}
});
}
@Override
public void onTooltip(IBrowser browser, String text) {
Optional.ofNullable(getDisplayHandler())
.ifPresent(iDisplayHandler -> {
if (getBrowser() == browser) {
iDisplayHandler.onTooltip(browser, text);
}
});
}
@Override
public void onStatusMessage(IBrowser browser, String value) {
Optional.ofNullable(getDisplayHandler())
.ifPresent(iDisplayHandler -> {
if (getBrowser() == browser) {
iDisplayHandler.onStatusMessage(browser, value);
}
});
}
});
browser = api.createBrowser(urlToLoad == null ? home : urlToLoad);
Optional.ofNullable(browser)
.ifPresent(iBrowser -> iBrowser.visitSource(
str -> {
//do nothing
}));
} else {
browser = null;
}
urlToLoad = null;
}
@Override
protected void onLayout(int parentWidth, int parentHeight) {
Optional.ofNullable(browser)
.ifPresent((IBrowser iBrowser) -> {
if (iBrowser.isActivate() && getWidth() > 0 && getHeight() > 0) {
iBrowser.resize(getWidth(), getHeight());
}
});
}
@Override
public void destroy() {
super.destroy();
Log.info("close browser!");
Optional.ofNullable(browser)
.ifPresent(IBrowser::close);
}
@Override
protected void onDraw(MatrixStack stack, int mouseX, int mouseY, float partialTicks) {
int[] packetLight = RenderHelper.decodeCombineLight(outsideLight);
int light = RenderHelper.getCombineLight(packetLight[0], packetLight[1], RenderHelper.decodeCombineLight(RenderHelper.light)[1]);
Optional.ofNullable(browser)
.ifPresent(iBrowser -> {
ResourceLocation location = iBrowser.getTextureLocation();
Optional.ofNullable(location)
.ifPresent(resourceLocation -> RenderHelper.blit2(stack, 0, 0, 0, 0, 0f, getWidth(), getHeight(), getHeight(), getWidth(), light, location));
});
}
@Override
public void onUpdate() {
super.onUpdate();
Optional.ofNullable(urlToLoad)
.ifPresent(s -> {
setUrl(urlToLoad);
if(browser != null && browser.isActivate() && !browser.isPageLoading())
urlToLoad = null;
});
}
public void goBack() {
Optional.ofNullable(browser)
.ifPresent(IBrowser::goBack);
}
public void goForward() {
Optional.ofNullable(browser)
.ifPresent(IBrowser::goForward);
}
public boolean isActivate() {
return Optional.ofNullable(browser)
.map(IBrowser::isActivate)
.orElse(false);
}
public boolean isPageLoading() {
return Optional.ofNullable(browser)
.map(IBrowser::isPageLoading)
.orElse(false);
}
public String getUrlLoaded() {
return Optional.ofNullable(browser)
.map(IBrowser::getURL)
.orElse(home);
}
@Override
protected boolean onClicked(int mouseX, int mouseY, int mouseButton) {
return false;
}
@Override
protected boolean onLongClicked(int mouseX, int mouseY, int mouseButton) {
return false;
}
@Override
protected void onReleased(int mouseX, int mouseY, int state) {
//int x, int y, int mods, int btn, boolean pressed, int ccnt
Optional.ofNullable(browser).ifPresent(iBrowser -> iBrowser.injectMouseButton(mouseX, mouseY, getMask(), remapBtn(state), false, 1));
}
@Override
protected boolean onPressed(int mouseX, int mouseY, int state) {
Optional<IBrowser> browserOptional = Optional.ofNullable(browser);
return browserOptional
.map(iBrowser -> {
iBrowser.injectMouseButton(mouseX, mouseY, getMask(), remapBtn(state), true, 1);
return true;
})
.orElse(false);
//int x, int y, int mods, int btn, boolean pressed, int ccnt
}
@Override
protected boolean onMouseScrolled(int mouseX, int mouseY, float delta) {
Optional<IBrowser> browserOptional = Optional.ofNullable(browser);
return browserOptional
.map(iBrowser -> {
iBrowser.injectMouseWheel(mouseX, mouseY, getMask(), 1, ((int) delta * 100));
return true;
})
.orElseGet(() -> BrowserView.super.onMouseScrolled(mouseX, mouseY, delta));
}
int lastKeyCode;
@Override
protected boolean onKeyPressed(int keyCode, int scanCode, int modifiers) {
//int x, int y, int mods, int btn, boolean pressed, int ccnt
Optional<IBrowser> browserOptional = Optional.ofNullable(browser);
return browserOptional
.map(iBrowser -> {
iBrowser.injectKeyPressedByKeyCode(keyCode, (char) keyCode, getMask());
return true;
})
.orElseGet(() -> BrowserView.super.keyPressed(keyCode, scanCode, modifiers));
}
@Override
protected boolean onKeyReleased(int keyCode, int scanCode, int modifiers) {
//int x, int y, int mods, int btn, boolean pressed, int ccnt
Optional<IBrowser> browserOptional = Optional.ofNullable(browser);
return browserOptional
.map(iBrowser -> {
iBrowser.injectKeyReleasedByKeyCode(keyCode, (char) keyCode, getMask());
return true;
})
.orElseGet(() -> BrowserView.super.onKeyReleased(keyCode, scanCode, modifiers));
}
@Override
public boolean onKeyType(char typedChar, int mod) {
//int x, int y, int mods, int btn, boolean pressed, int ccnt
Optional<IBrowser> browserOptional = Optional.ofNullable(browser);
return browserOptional
.map(iBrowser -> {
iBrowser.injectKeyTyped(typedChar, lastKeyCode, mod);
return true;
})
.orElseGet(() -> BrowserView.super.onKeyType(typedChar, mod));
}
@Override
protected boolean onMouseMoved(int mouseX, int mouseY) {
//check the mouse btn was pressed or not
Optional<IBrowser> browserOptional = Optional.ofNullable(browser);
return browserOptional
.map(iBrowser -> {
iBrowser.injectMouseMove(mouseX, mouseY, getMask(), mouseY < 0);
return true;
})
.orElseGet(() -> BrowserView.super.onMouseMoved(mouseX, mouseY));
}
@Override
protected boolean onMouseDragged(int mouseX, int mouseY, int state, int dx, int dy) {
Optional<IBrowser> browserOptional = Optional.ofNullable(browser);
return browserOptional
.map(iBrowser -> {
iBrowser.injectMouseDrag(mouseX, mouseY, remapBtn(state), dx, dy);
return true;
})
.orElseGet(() -> BrowserView.super.onMouseDragged(mouseX, mouseY, state, dx, dy));
}
private static int getMask() {
return (Screen.hasShiftDown() ? MouseEvent.SHIFT_DOWN_MASK : 0) |
(Screen.hasAltDown() ? MouseEvent.ALT_DOWN_MASK : 0) |
(Screen.hasControlDown() ? MouseEvent.CTRL_DOWN_MASK : 0);
}
//remap from GLFW to AWT's button ids
private int remapBtn(int btn) {
if (btn == 0) {
btn = MouseEvent.BUTTON1;
} else if (btn == 1) {
btn = MouseEvent.BUTTON3;
} else {
btn = MouseEvent.BUTTON2;
}
return btn;
}
public IDisplayHandler getDisplayHandler() {
return displayHandler;
}
public void setDisplayHandler(final IDisplayHandler displayHandler) {
this.displayHandler = displayHandler;
}
@Override
public void focused() {
super.focused();
Optional.ofNullable(focusListener)
.ifPresent(iFocusListener -> iFocusListener.onFocusChanged(true));
}
@Override
public void loseFocus() {
super.loseFocus();
Optional.ofNullable(focusListener)
.ifPresent(iFocusListener -> iFocusListener.onFocusChanged(false));
}
}
| 33.384196 | 169 | 0.561296 |
e4a8eb59a88efae004defe0fa9a4045d585cbeb3 | 1,307 | package metrics;
import org.junit.Assert;
import org.junit.Test;
public class LinesOfCodeTest {
LinesOfCode loc = new LinesOfCode();
@Test
public void testStrcompLineCheckerDoubleSlash() {
String doubleSlashLine = "// line starting with double slash";
Assert.assertTrue(loc.strcompLineChecker(doubleSlashLine));
}
@Test
public void testStrcompLineCheckerSlashAsterisk() {
String slashAsteriskLine = "/* line starting with slash asterisk";
Assert.assertTrue(loc.strcompLineChecker(slashAsteriskLine));
}
@Test
public void testStrcompLineCheckerAsterisk() {
String asteriskLine = "* line starting with double asterisk";
Assert.assertTrue(loc.strcompLineChecker(asteriskLine));
}
@Test
public void testStrcompLineCheckerLeftBracket() {
String leftBracketLine = "{";
Assert.assertTrue(loc.strcompLineChecker(leftBracketLine));
}
@Test
public void testStrcompLineCheckerRightBracket() {
String rightBracketLine = "}";
Assert.assertTrue(loc.strcompLineChecker(rightBracketLine));
}
@Test
public void testStrcompLineCheckerEmpty() {
String emptyLine = "";
Assert.assertTrue(loc.strcompLineChecker(emptyLine));
}
@Test
public void testStrcompLineCheckerCode() {
String codeLine = "x = 10;";
Assert.assertFalse(loc.strcompLineChecker(codeLine));
}
}
| 25.627451 | 68 | 0.762816 |
8b63229ac7e5d6658d359c81ffeb9f17cc1be8f7 | 1,499 | /*
* Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.inbound.endpoint.protocol.grpc;
public class InboundGRPCConstants {
public static final String INBOUND_ENDPOINT_PARAMETER_GRPC_PORT = "inbound.grpc.port";
public static final String CONTENT_TYPE_JSON = "json";
public static final String CONTENT_TYPE_JSON_MIME_TYPE = "application/json";
public static final String CONTENT_TYPE_XML = "xml";
public static final String CONTENT_TYPE_XML_MIME_TYPE = "text/xml";
public static final String CONTENT_TYPE_TEXT = "text";
public static final String CONTENT_TYPE_TEXT_MIME_TYPE = "text/plain";
public static final String HEADER_MAP_SEQUENCE_PARAMETER_NAME = "sequence";
public static final String HEADER_MAP_CONTENT_TYPE_PARAMETER_NAME = "Content-Type";
public static final int DEFAULT_INBOUND_ENDPOINT_GRPC_PORT = 8888;
}
| 46.84375 | 90 | 0.763843 |
b26c64ea6b8f2fcbc85f0f6ca8b13d6e793233c4 | 16,371 | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package software.amazon.qldb.integrationtests;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import com.amazon.ion.IonBlob;
import com.amazon.ion.IonBool;
import com.amazon.ion.IonClob;
import com.amazon.ion.IonDecimal;
import com.amazon.ion.IonFloat;
import com.amazon.ion.IonInt;
import com.amazon.ion.IonList;
import com.amazon.ion.IonNull;
import com.amazon.ion.IonSexp;
import com.amazon.ion.IonString;
import com.amazon.ion.IonStruct;
import com.amazon.ion.IonSymbol;
import com.amazon.ion.IonTimestamp;
import com.amazon.ion.IonType;
import com.amazon.ion.IonValue;
import com.amazon.ion.Timestamp;
import com.amazon.ion.ValueFactory;
import com.amazon.ion.system.IonSystemBuilder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import software.amazon.qldb.PooledQldbDriver;
import software.amazon.qldb.Result;
import software.amazon.qldb.integrationtests.utils.Constants;
import software.amazon.qldb.integrationtests.utils.IntegrationTestBase;
public class IonTypesIntegTest {
private static IntegrationTestBase integrationTestBase;
private static PooledQldbDriver pooledQldbDriver;
private static ValueFactory valueFactory = IonSystemBuilder.standard().build();
@BeforeAll
private static void setup() throws InterruptedException {
integrationTestBase = new IntegrationTestBase(Constants.LEDGER_NAME, System.getProperty("region"));
integrationTestBase.runCreateLedger();
pooledQldbDriver = integrationTestBase.createQldbDriver(Constants.DEFAULT, Constants.DEFAULT, Constants.DEFAULT);
// Create table
String createTableQuery = String.format("CREATE TABLE %s", Constants.TABLE_NAME);
int createTableCount = pooledQldbDriver.execute(
txn -> {
Result result = txn.execute(createTableQuery);
int count = 0;
for (IonValue row : result) {
count++;
}
return count;
});
assertEquals(1, createTableCount);
Iterable<String> result = pooledQldbDriver.getSession().getTableNames();
for (String tableName : result) {
assertEquals(Constants.TABLE_NAME, tableName);
}
}
@AfterAll
private static void cleanup() throws InterruptedException {
integrationTestBase.deleteLedger();
pooledQldbDriver.close();
}
@AfterEach
public void testCleanup() {
// Delete everything from table after each test
String deleteQuery = String.format("DELETE FROM %s", Constants.TABLE_NAME);
pooledQldbDriver.execute(txn -> { txn.execute(deleteQuery); });
}
@ParameterizedTest
@MethodSource("createIonValues")
public void execute_InsertAndReadIonTypes_IonTypesAreInsertedAndRead(final IonValue ionValue) {
// Given
// Create Ion struct to be inserted
IonStruct ionStruct = valueFactory.newEmptyStruct();
ionStruct.add(Constants.COLUMN_NAME, ionValue);
String insertQuery = String.format("INSERT INTO %s ?", Constants.TABLE_NAME);
int insertCount = pooledQldbDriver.execute(
txn -> {
Result result = txn.execute(insertQuery, ionStruct);
int count = 0;
for (IonValue row : result) {
count++;
}
return count;
});
assertEquals(1, insertCount);
// When
IonValue searchResult;
if (ionValue.isNullValue()) {
String searchQuery = String.format("SELECT VALUE %s FROM %s WHERE %s IS NULL",
Constants.COLUMN_NAME, Constants.TABLE_NAME, Constants.COLUMN_NAME);
searchResult = pooledQldbDriver.execute(
txn -> {
Result result = txn.execute(searchQuery);
IonValue value = null;
for (IonValue row : result) {
value = row;
}
return value;
});
} else {
String searchQuery = String.format("SELECT VALUE %s FROM %s WHERE %s = ?",
Constants.COLUMN_NAME, Constants.TABLE_NAME, Constants.COLUMN_NAME);
searchResult = pooledQldbDriver.execute(
txn -> {
Result result = txn.execute(searchQuery, ionValue);
IonValue value = null;
for (IonValue row : result) {
value = row;
}
return value;
});
}
// Then
IonType searchType = searchResult.getType();
IonType ionValType = ionValue.getType();
if (searchType != ionValType) {
fail(String.format("The queried value type, %s, does not match %s.", searchType.toString(), ionValType.toString()));
}
}
@ParameterizedTest
@MethodSource("createIonValues")
public void execute_UpdateIonTypes_IonTypesAreUpdated(final IonValue ionValue) {
// Given
// Create Ion struct to be inserted
IonStruct ionStruct = valueFactory.newEmptyStruct();
ionStruct.add(Constants.COLUMN_NAME, ionValue);
String insertQuery = String.format("INSERT INTO %s ?", Constants.TABLE_NAME);
int insertCount = pooledQldbDriver.execute(
txn -> {
Result result = txn.execute(insertQuery, ionStruct);
int count = 0;
for (IonValue row : result) {
count++;
}
return count;
});
assertEquals(1, insertCount);
// When
String updateQuery = String.format("UPDATE %s SET %s = ?", Constants.TABLE_NAME, Constants.COLUMN_NAME);
int updateCount = pooledQldbDriver.execute(
txn -> {
Result result = txn.execute(updateQuery, ionValue);
int count = 0;
for (IonValue row : result) {
count++;
}
return count;
});
assertEquals(1, updateCount);
// Then
IonValue searchResult;
if (ionValue.isNullValue()) {
String searchQuery = String.format("SELECT VALUE %s FROM %s WHERE %s IS NULL",
Constants.COLUMN_NAME, Constants.TABLE_NAME, Constants.COLUMN_NAME);
searchResult = pooledQldbDriver.execute(
txn -> {
Result result = txn.execute(searchQuery);
IonValue value = null;
for (IonValue row : result) {
value = row;
}
return value;
});
} else {
String searchQuery = String.format("SELECT VALUE %s FROM %s WHERE %s = ?",
Constants.COLUMN_NAME, Constants.TABLE_NAME, Constants.COLUMN_NAME);
searchResult = pooledQldbDriver.execute(
txn -> {
Result result = txn.execute(searchQuery, ionValue);
IonValue value = null;
for (IonValue row : result) {
value = row;
}
return value;
});
}
IonType searchType = searchResult.getType();
IonType ionValType = ionValue.getType();
if (searchType != ionValType) {
fail(String.format("The queried value type, %s, does not match %s.", searchType.toString(), ionValType.toString()));
}
}
private static byte[] getAsciiBytes(final String str) {
return str.getBytes(StandardCharsets.US_ASCII);
}
private static List<IonValue> createIonValues() {
List<IonValue> ionValues = new ArrayList<>();
IonBlob ionBlob = valueFactory.newBlob(getAsciiBytes("value"));
ionValues.add(ionBlob);
IonBool ionBool = valueFactory.newBool(true);
ionValues.add(ionBool);
IonClob ionClob = valueFactory.newClob(getAsciiBytes("{{ 'Clob value.'}}"));
ionValues.add(ionClob);
IonDecimal ionDecimal = valueFactory.newDecimal(0.1);
ionValues.add(ionDecimal);
IonFloat ionFloat = valueFactory.newFloat(1.1);
ionValues.add(ionFloat);
IonInt ionInt = valueFactory.newInt(2);
ionValues.add(ionInt);
IonList ionList = valueFactory.newEmptyList();
ionList.add(valueFactory.newInt(3));
ionValues.add(ionList);
IonNull ionNull = valueFactory.newNull();
ionValues.add(ionNull);
IonSexp ionSexp = valueFactory.newEmptySexp();
ionSexp.add(valueFactory.newString("value"));
ionValues.add(ionSexp);
IonString ionString = valueFactory.newString("value");
ionValues.add(ionString);
IonStruct ionStruct = valueFactory.newEmptyStruct();
ionStruct.add("value", valueFactory.newBool(true));
ionValues.add(ionStruct);
IonSymbol ionSymbol = valueFactory.newSymbol("symbol");
ionValues.add(ionSymbol);
IonTimestamp ionTimestamp = valueFactory.newTimestamp(Timestamp.now());
ionValues.add(ionTimestamp);
IonBlob ionNullBlob = valueFactory.newNullBlob();
ionValues.add(ionNullBlob);
IonBool ionNullBool = valueFactory.newNullBool();
ionValues.add(ionNullBool);
IonClob ionNullClob = valueFactory.newNullClob();
ionValues.add(ionNullClob);
IonDecimal ionNullDecimal = valueFactory.newNullDecimal();
ionValues.add(ionNullDecimal);
IonFloat ionNullFloat = valueFactory.newNullFloat();
ionValues.add(ionNullFloat);
IonInt ionNullInt = valueFactory.newNullInt();
ionValues.add(ionNullInt);
IonList ionNullList = valueFactory.newNullList();
ionValues.add(ionNullList);
IonSexp ionNullSexp = valueFactory.newNullSexp();
ionValues.add(ionNullSexp);
IonString ionNullString = valueFactory.newNullString();
ionValues.add(ionNullString);
IonStruct ionNullStruct = valueFactory.newNullStruct();
ionValues.add(ionNullStruct);
IonSymbol ionNullSymbol = valueFactory.newNullSymbol();
ionValues.add(ionNullSymbol);
IonTimestamp ionNullTimestamp = valueFactory.newNullTimestamp();
ionValues.add(ionNullTimestamp);
IonBlob ionBlobWithAnnotation = valueFactory.newBlob(getAsciiBytes("value"));
ionBlobWithAnnotation.addTypeAnnotation("annotation");
ionValues.add(ionBlobWithAnnotation);
IonBool ionBoolWithAnnotation = valueFactory.newBool(true);
ionBoolWithAnnotation.addTypeAnnotation("annotation");
ionValues.add(ionBoolWithAnnotation);
IonClob ionClobWithAnnotation = valueFactory.newClob(getAsciiBytes("{{ 'Clob value.'}}"));
ionClobWithAnnotation.addTypeAnnotation("annotation");
ionValues.add(ionClobWithAnnotation);
IonDecimal ionDecimalWithAnnotation = valueFactory.newDecimal(0.1);
ionDecimalWithAnnotation.addTypeAnnotation("annotation");
ionValues.add(ionDecimalWithAnnotation);
IonFloat ionFloatWithAnnotation = valueFactory.newFloat(1.1);
ionFloatWithAnnotation.addTypeAnnotation("annotation");
ionValues.add(ionFloatWithAnnotation);
IonInt ionIntWithAnnotation = valueFactory.newInt(2);
ionIntWithAnnotation.addTypeAnnotation("annotation");
ionValues.add(ionIntWithAnnotation);
IonList ionListWithAnnotation = valueFactory.newEmptyList();
ionListWithAnnotation.add(valueFactory.newInt(3));
ionListWithAnnotation.addTypeAnnotation("annotation");
ionValues.add(ionListWithAnnotation);
IonNull ionNullWithAnnotation = valueFactory.newNull();
ionNullWithAnnotation.addTypeAnnotation("annotation");
ionValues.add(ionNullWithAnnotation);
IonSexp ionSexpWithAnnotation = valueFactory.newEmptySexp();
ionSexpWithAnnotation.add(valueFactory.newString("value"));
ionSexpWithAnnotation.addTypeAnnotation("annotation");
ionValues.add(ionSexpWithAnnotation);
IonString ionStringWithAnnotation = valueFactory.newString("value");
ionStringWithAnnotation.addTypeAnnotation("annotation");
ionValues.add(ionStringWithAnnotation);
IonStruct ionStructWithAnnotation = valueFactory.newEmptyStruct();
ionStructWithAnnotation.add("value", valueFactory.newBool(true));
ionStructWithAnnotation.addTypeAnnotation("annotation");
ionValues.add(ionStructWithAnnotation);
IonSymbol ionSymbolWithAnnotation = valueFactory.newSymbol("symbol");
ionSymbolWithAnnotation.addTypeAnnotation("annotation");
ionValues.add(ionSymbolWithAnnotation);
IonTimestamp ionTimestampWithAnnotation = valueFactory.newTimestamp(Timestamp.now());
ionTimestampWithAnnotation.addTypeAnnotation("annotation");
ionValues.add(ionTimestampWithAnnotation);
IonBlob ionNullBlobWithAnnotation = valueFactory.newNullBlob();
ionNullBlobWithAnnotation.addTypeAnnotation("annotation");
ionValues.add(ionNullBlobWithAnnotation);
IonBool ionNullBoolWithAnnotation = valueFactory.newNullBool();
ionNullBoolWithAnnotation.addTypeAnnotation("annotation");
ionValues.add(ionNullBoolWithAnnotation);
IonClob ionNullClobWithAnnotation = valueFactory.newNullClob();
ionNullClobWithAnnotation.addTypeAnnotation("annotation");
ionValues.add(ionNullClobWithAnnotation);
IonDecimal ionNullDecimalWithAnnotation = valueFactory.newNullDecimal();
ionNullDecimalWithAnnotation.addTypeAnnotation("annotation");
ionValues.add(ionNullDecimalWithAnnotation);
IonFloat ionNullFloatWithAnnotation = valueFactory.newNullFloat();
ionNullFloatWithAnnotation.addTypeAnnotation("annotation");
ionValues.add(ionNullFloatWithAnnotation);
IonInt ionNullIntWithAnnotation = valueFactory.newNullInt();
ionNullIntWithAnnotation.addTypeAnnotation("annotation");
ionValues.add(ionNullIntWithAnnotation);
IonList ionNullListWithAnnotation = valueFactory.newNullList();
ionNullListWithAnnotation.addTypeAnnotation("annotation");
ionValues.add(ionNullListWithAnnotation);
IonSexp ionNullSexpWithAnnotation = valueFactory.newNullSexp();
ionNullSexpWithAnnotation.addTypeAnnotation("annotation");
ionValues.add(ionNullSexpWithAnnotation);
IonString ionNullStringWithAnnotation = valueFactory.newNullString();
ionNullStringWithAnnotation.addTypeAnnotation("annotation");
ionValues.add(ionNullStringWithAnnotation);
IonStruct ionNullStructWithAnnotation = valueFactory.newNullStruct();
ionNullStructWithAnnotation.addTypeAnnotation("annotation");
ionValues.add(ionNullStructWithAnnotation);
IonSymbol ionNullSymbolWithAnnotation = valueFactory.newNullSymbol();
ionNullSymbolWithAnnotation.addTypeAnnotation("annotation");
ionValues.add(ionNullSymbolWithAnnotation);
IonTimestamp ionNullTimestampWithAnnotation = valueFactory.newNullTimestamp();
ionNullTimestampWithAnnotation.addTypeAnnotation("annotation");
ionValues.add(ionNullTimestampWithAnnotation);
return ionValues;
}
}
| 38.793839 | 128 | 0.663551 |
fbb48fbc2bb65a0d68844e59185a96fb9732454c | 8,131 | package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class login_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.List<String> _jspx_dependants;
private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector;
public java.util.List<String> getDependants() {
return _jspx_dependants;
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html;charset=UTF-8");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("<!DOCTYPE html>\n");
out.write("<html>\n");
out.write(" <head>\n");
out.write(" <title>We Care Site Admin</title>\n");
out.write(" <meta charset=\"UTF-8\">\n");
out.write("\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n");
out.write("\n");
out.write("\t<link rel=\"stylesheet\" type=\"text/css\" href=\"vendor/bootstrap/css/bootstrap.min.css\">\n");
out.write("<!--===============================================================================================-->\n");
out.write("\t<link rel=\"stylesheet\" type=\"text/css\" href=\"fonts/font-awesome-4.7.0/css/font-awesome.min.css\">\n");
out.write("<!--===============================================================================================-->\n");
out.write("\t<link rel=\"stylesheet\" type=\"text/css\" href=\"fonts/Linearicons-Free-v1.0.0/icon-font.min.css\">\n");
out.write("<!--===============================================================================================-->\n");
out.write("\t<link rel=\"stylesheet\" type=\"text/css\" href=\"vendor/animate/animate.css\">\n");
out.write("<!--===============================================================================================-->\t\n");
out.write("\t<link rel=\"stylesheet\" type=\"text/css\" href=\"vendor/css-hamburgers/hamburgers.min.css\">\n");
out.write("<!--===============================================================================================-->\n");
out.write("\t<link rel=\"stylesheet\" type=\"text/css\" href=\"vendor/animsition/css/animsition.min.css\">\n");
out.write("<!--===============================================================================================-->\n");
out.write("\t<link rel=\"stylesheet\" type=\"text/css\" href=\"vendor/select2/select2.min.css\">\n");
out.write("<!--===============================================================================================-->\t\n");
out.write("\t<link rel=\"stylesheet\" type=\"text/css\" href=\"vendor/daterangepicker/daterangepicker.css\">\n");
out.write("<!--===============================================================================================-->\n");
out.write("\t<link rel=\"stylesheet\" type=\"text/css\" href=\"util.css\">\n");
out.write("\t<link rel=\"stylesheet\" type=\"text/css\" href=\"main.css\">\n");
out.write(" </head>\n");
out.write(" <body>\n");
out.write(" <div class=\"limiter\">\n");
out.write("\t\t<div class=\"container-login100\" style=\"background-image: url('images/people.jpg');\">\n");
out.write("\t\t\t<div class=\"wrap-login100 p-t-30 p-b-50\">\n");
out.write("\t\t\t\t<span class=\"login100-form-title p-b-41\">\n");
out.write("\t\t\t\t\tAdmin Login\n");
out.write("\t\t\t\t</span>\n");
out.write(" \n");
out.write("\t\t\t\t<form class=\"login100-form validate-form p-b-33 p-t-5\" action=\"loginCheck.jsp\" method=\"post\">\n");
out.write("\n");
out.write("\t\t\t\t\t<div class=\"wrap-input100 validate-input\" data-validate = \"Enter username\">\n");
out.write("\t\t\t\t\t\t<input class=\"input100\" type=\"text\" name=\"username\" placeholder=\"User name\">\n");
out.write("\t\t\t\t\t\t<span class=\"focus-input100\" data-placeholder=\"\"></span>\n");
out.write("\t\t\t\t\t</div>\n");
out.write("\n");
out.write("\t\t\t\t\t<div class=\"wrap-input100 validate-input\" data-validate=\"Enter password\">\n");
out.write("\t\t\t\t\t\t<input class=\"input100\" type=\"password\" name=\"pass\" placeholder=\"Password\">\n");
out.write("\t\t\t\t\t\t<span class=\"focus-input100\" data-placeholder=\"\"></span>\n");
out.write("\t\t\t\t\t</div>\n");
out.write("\n");
out.write("\t\t\t\t\t<div class=\"container-login100-form-btn m-t-32\">\n");
out.write("\t\t\t\t\t\t<button class=\"login100-form-btn\">\n");
out.write("\t\t\t\t\t\t\tLogin\n");
out.write("\t\t\t\t\t\t</button>\n");
out.write("\t\t\t\t\t</div>\n");
out.write("\n");
out.write("\t\t\t\t</form>\n");
out.write("\t\t\t</div>\n");
out.write("\t\t</div>\n");
out.write("\t</div>\n");
out.write(" \n");
out.write(" <div id=\"dropDownSelect1\"></div>\n");
out.write("\t\n");
out.write("<!--===============================================================================================-->\n");
out.write("\t<script src=\"vendor/jquery/jquery-3.2.1.min.js\"></script>\n");
out.write("<!--===============================================================================================-->\n");
out.write("\t<script src=\"vendor/animsition/js/animsition.min.js\"></script>\n");
out.write("<!--===============================================================================================-->\n");
out.write("\t<script src=\"vendor/bootstrap/js/popper.js\"></script>\n");
out.write("\t<script src=\"vendor/bootstrap/js/bootstrap.min.js\"></script>\n");
out.write("<!--===============================================================================================-->\n");
out.write("\t<script src=\"vendor/select2/select2.min.js\"></script>\n");
out.write("<!--===============================================================================================-->\n");
out.write("\t<script src=\"vendor/daterangepicker/moment.min.js\"></script>\n");
out.write("\t<script src=\"vendor/daterangepicker/daterangepicker.js\"></script>\n");
out.write("<!--===============================================================================================-->\n");
out.write("\t<script src=\"vendor/countdowntime/countdowntime.js\"></script>\n");
out.write("<!--===============================================================================================-->\n");
out.write("\t<script src=\"js/main.js\"></script>\n");
out.write(" </body>\n");
out.write("</html>\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
| 59.350365 | 138 | 0.489731 |
02544a4ec08cebef79f8b90810e91837685aa81c | 6,491 | package java_course;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
public class A410877027_11_1 {
static int numsCount;
static String nums = "not Null";
static int size = 1;
static List<String> numsLine1;
static List<String> numsLine2;
static List<String> numsLine3;
static List<String> numsLine4;
static List<String> numsLine5;
public static void main(String[] argv) {
while (size != 0 && nums.charAt(0) != '0') {
//初始的表 未依size重建
numsLine1 = Arrays.asList(" - ", " ", " - ", " - ", " ", " - ", " - ", " - ", " - ", " - ");
numsLine2 = Arrays.asList("| |", " |", " |", " |", "| |", "| ", "| ", " |", "| |", "| |");
numsLine3 = Arrays.asList(" ", " ", " - ", " - ", " - ", " - ", " - ", " ", " - ", " - ");
numsLine4 = Arrays.asList("| |", " |", "| ", " |", " |", " |", "| |", " |", "| |", " |");
numsLine5 = Arrays.asList(" - ", " ", " - ", " - ", " ", " - ", " - ", " ", " - ", " - ");
// 輸入
BufferedReader inputReader = new BufferedReader(new InputStreamReader(System.in));
try {
String inputLine = inputReader.readLine();
String[] input = inputLine.split(" ");
size = Integer.parseInt(input[0]);
nums = input[1];
//0 0 中斷
if (size == 0 && nums.charAt(0) == '0')
System.exit(0);
//建表用
StringBuilder[] stringBuilders = new StringBuilder[5];
for (int initStringBuilder = 0; initStringBuilder < 5; initStringBuilder++)
stringBuilders[initStringBuilder] = new StringBuilder();
//建表
reFormat();
//找到要放入那些數字
for (numsCount = 0; numsCount < nums.length(); numsCount++) {
switch (nums.charAt(numsCount)) {
case '0':
getNum(0, stringBuilders);
break;
case '1':
getNum(1, stringBuilders);
break;
case '2':
getNum(2, stringBuilders);
break;
case '3':
getNum(3, stringBuilders);
break;
case '4':
getNum(4, stringBuilders);
break;
case '5':
getNum(5, stringBuilders);
break;
case '6':
getNum(6, stringBuilders);
break;
case '7':
getNum(7, stringBuilders);
break;
case '8':
getNum(8, stringBuilders);
break;
case '9':
getNum(9, stringBuilders);
break;
}
}
//輸出結果
System.out.println(stringBuilders[0].toString());
for (int printSize = 0; printSize < size; printSize++)
System.out.println(stringBuilders[1].toString());
System.out.println(stringBuilders[2].toString());
for (int printSize = 0; printSize < size; printSize++)
System.out.println(stringBuilders[3].toString());
System.out.println(stringBuilders[4].toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
static void reFormat() {
StringBuilder newVerticalSize = new StringBuilder();
StringBuilder newSpaceSize = new StringBuilder();
for (int newSize = 0; newSize < size; newSize++) {
newVerticalSize.append("-");
newSpaceSize.append(" ");
}
for (int reset = 0; reset < numsLine1.size(); reset++) {
numsLine1.set(reset, numsLine1.get(reset).replace("-", newVerticalSize.toString()));
numsLine1.set(reset, numsLine1.get(reset).replace(" ", " " + newSpaceSize.toString()) + " ");
numsLine3.set(reset, numsLine3.get(reset).replace("-", newVerticalSize.toString()));
numsLine3.set(reset, numsLine3.get(reset).replace(" ", " " + newSpaceSize.toString()) + " ");
numsLine5.set(reset, numsLine5.get(reset).replace("-", newVerticalSize.toString()));
numsLine5.set(reset, numsLine5.get(reset).replace(" ", " " + newSpaceSize.toString()) + " ");
}
for (int reset = 0; reset < numsLine2.size(); reset++) {
if (numsLine2.get(reset).equals(" |"))
numsLine2.set(reset, numsLine2.get(reset).replace(" |", newSpaceSize.toString()) + " | ");
if (numsLine2.get(reset).equals("| "))
numsLine2.set(reset, numsLine2.get(reset).replace("| ", "| " + newSpaceSize.toString() + " "));
if (numsLine2.get(reset).equals("| |"))
numsLine2.set(reset, numsLine2.get(reset).replace("| |", "|" + newSpaceSize.toString()) + "| ");
if (numsLine4.get(reset).equals(" |"))
numsLine4.set(reset, numsLine4.get(reset).replace(" |", newSpaceSize.toString()) + " | ");
if (numsLine4.get(reset).equals("| "))
numsLine4.set(reset, numsLine4.get(reset).replace("| ", "| " + newSpaceSize.toString()) + " ");
if (numsLine4.get(reset).equals("| |"))
numsLine4.set(reset, numsLine4.get(reset).replace("| |", "|" + newSpaceSize.toString()) + "| ");
}
}
static void getNum(int id, StringBuilder[] stringBuilders) {
stringBuilders[0].append(numsLine1.get(id));
stringBuilders[1].append(numsLine2.get(id));
stringBuilders[2].append(numsLine3.get(id));
stringBuilders[3].append(numsLine4.get(id));
stringBuilders[4].append(numsLine5.get(id));
}
}
| 43.563758 | 113 | 0.450778 |
628f2d33b100ab8e73739a891bf1d3884f0faea7 | 454 | package com.mimacom.shapeservice.services;
import com.mimacom.shapeservice.model.Shape;
import org.assertj.core.api.BDDAssertions;
import org.junit.Test;
public class ShapeServiceTest {
ShapeService shapeService = new ShapeService();
@Test
public void should_return_correct_triangle_calculation() {
Shape triangle = shapeService.getTriangle(100.0, 100.0);
BDDAssertions.then(triangle.getArea()).isEqualTo(5000.0);
}
} | 26.705882 | 65 | 0.751101 |
2de55ce074595ef4e74faafa094614a67374e25d | 83 | package com.codefellows.admintools.anotherpackage;
public class SomethingElse {
}
| 16.6 | 50 | 0.831325 |
ccdb2c172ce306e2fef84181e6ac408a3a0f9fd6 | 2,240 | /*
* 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 lab4_davidariel;
/**
*
* @author ariel
*/
public class pilotos {
private String nombre;
private int edad;
private String familiar;
private String encargado;
private String escuela;
private double sincronizacion;
private String asignado;
public pilotos() {
}
public pilotos(String nombre, int edad, String familiar, String encargado, String escuela, double sincronizacion, String asignado) {
this.nombre = nombre;
this.edad = edad;
this.familiar = familiar;
this.encargado = encargado;
this.escuela = escuela;
this.sincronizacion = sincronizacion;
this.asignado = asignado;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public int getEdad() {
return edad;
}
public void setEdad(int edad) {
this.edad = edad;
}
public String getFamiliar() {
return familiar;
}
public void setFamiliar(String familiar) {
this.familiar = familiar;
}
public String getEncargado() {
return encargado;
}
public void setEncargado(String encargado) {
this.encargado = encargado;
}
public String getEscuela() {
return escuela;
}
public void setEscuela(String escuela) {
this.escuela = escuela;
}
public double getSincronizacion() {
return sincronizacion;
}
public void setSincronizacion(double sincronizacion) {
this.sincronizacion = sincronizacion;
}
public String getAsignado() {
return asignado;
}
public void setAsignado(String asignado) {
this.asignado = asignado;
}
@Override
public String toString() {
return "pilotos{" + "nombre=" + nombre + ", edad=" + edad + ", familiar=" + familiar + ", encargado=" + encargado + ", escuela=" + escuela + ", sincronizacion=" + sincronizacion + ", asignado=" + asignado + '}';
}
}
| 22.626263 | 219 | 0.617857 |
2862c9e4a51af498b58ba2a278fcee61c0719586 | 690 | package lk.ijse.dep.fcms.bo.custom;
import lk.ijse.dep.fcms.bo.SuperBO;
import lk.ijse.dep.fcms.dto.MembershipDTO;
import lk.ijse.dep.fcms.dto.MembershipDetailDTO;
import lk.ijse.dep.fcms.dto.PaymentDTO;
import java.util.List;
public interface PaymentBO extends SuperBO {
boolean savePayment(PaymentDTO payment)throws Exception;
boolean updatePayment(PaymentDTO payment)throws Exception;
boolean deletePayment(String paymentID) throws Exception;
List<PaymentDTO>findAllPayments() throws Exception;
String getLastPaymentId()throws Exception;
PaymentDTO findPayment(String paymentID) throws Exception;
List<String> getAllPaymentIDs() throws Exception;
}
| 26.538462 | 62 | 0.789855 |
f38b8ca0a497763798a5b829823c66279ee5fa24 | 977 | package edu.salesianos.triana.realstatev2_2022.dto.inmobiliariaDto;
import edu.salesianos.triana.realstatev2_2022.model.Inmobiliaria;
import org.springframework.stereotype.Component;
@Component
public class InmobiliariaDtoConverter {
public Inmobiliaria createInmobiliariaDtoToInmobiliaria(CreateInmobiliariaDto createInmobiliariaDto){
return Inmobiliaria.builder()
.nombre(createInmobiliariaDto.getNombre())
.email(createInmobiliariaDto.getEmail())
.telefono(createInmobiliariaDto.getTelefono())
.build();
}
public GetInmobiliariaDto inmobiliariaToGetInmobiliariaDto(Inmobiliaria inmobiliaria){
return GetInmobiliariaDto
.builder()
.id(inmobiliaria.getId())
.nombre(inmobiliaria.getNombre())
.telefono(inmobiliaria.getTelefono())
.email(inmobiliaria.getEmail())
.build();
}
}
| 31.516129 | 105 | 0.67349 |
22ff0b9b6d4b470e12de6bdb4b6b941151f2cef5 | 1,959 | package com.wang.basic.levenshtein;
import lombok.extern.slf4j.Slf4j;
/**
* @description: 编辑距离算法——判断字符串相似度
* @author: wei·man cui
* @date: 2020/11/20 17:19
*/
@Slf4j
public class LevenshteinUtil {
public static Double levenshtein(String str1, String str2) {
//计算两个字符串的长度。
int len1 = str1.length();
int len2 = str2.length();
//建立上面说的数组,比字符长度大一个空间
int[][] dif = new int[len1 + 1][len2 + 1];
//赋初值,步骤B。
for (int a = 0; a <= len1; a++) {
dif[a][0] = a;
}
for (int a = 0; a <= len2; a++) {
dif[0][a] = a;
}
//计算两个字符是否一样,计算左上的值
int temp;
for (int i = 1; i <= len1; i++) {
for (int j = 1; j <= len2; j++) {
if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
temp = 0;
} else {
temp = 1;
}
//取三个值中最小的
dif[i][j] = min(dif[i - 1][j - 1] + temp, dif[i][j - 1] + 1,
dif[i - 1][j] + 1);
}
}
//计算相似度,取数组右下角的值,同样不同位置代表不同字符串的比较
double similarity = 1 - (double) dif[len1][len2] / Math.max(str1.length(), str2.length());
log.info("字符串 {} 与 {} 的比较,差异步骤为:{},相似度为:{}", str1, str2, dif[len1][len2], similarity);
return similarity;
}
/**
* 得到最小值
*
* @param is
* @return
*/
private static int min(int... is) {
int min = Integer.MAX_VALUE;
for (int i : is) {
if (min > i) {
min = i;
}
}
return min;
}
public static void main(String[] args) {
//要比较的两个字符串
String str1 = "兹的一声,卡怎么出不来呢";
String str2 = "吃的一声啊卡怎么出不来呢?";
final Double levenshtein = levenshtein(str1, str2);
System.out.println(levenshtein);
}
}
| 27.208333 | 99 | 0.436958 |
8bfe0afe932f3ab3018c40a0326f90a29cea800d | 2,021 | package com.luo.jobx.core.rpc;
import com.luo.jobx.core.exception.ExceptionX;
import com.luo.jobx.core.rpc.encoder.RpcRequest;
import com.luo.jobx.core.rpc.encoder.RpcResponse;
import com.luo.jobx.core.util.RpcUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.FactoryBean;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* RPC代理
*
* @author xiangnan
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class RpcClientProxy implements FactoryBean<Object> {
private String toUrl;
private Class<?> clazz;
public RpcClientProxy(Class<?> clazz, String toUrl) {
this.clazz = clazz;
this.toUrl = toUrl;
}
@Override
public Object getObject() throws Exception {
return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] { clazz },
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
RpcRequest request = new RpcRequest();
request.setToUrl(toUrl);
request.setClazz(method.getDeclaringClass().getName());
request.setMethod(method.getName());
request.setParamType(method.getParameterTypes());
request.setParam(args);
RpcResponse response = RpcUtil.send(request);
if (response.isSuccess()) {
return response.getResult();
} else {
throw ExceptionX.RPC_FAIL;
}
}
});
}
@Override
public Class<?> getObjectType() {
return null;
}
@Override
public boolean isSingleton() {
return false;
}
}
| 28.464789 | 108 | 0.591786 |
949bf712f28d803853850ef3c32aebc2d5957ae5 | 7,868 | package com.vliolios.eventposter;
public class RepositorySettings {
interface Keys {
String WEBHOOK = "webhook";
String PULL_REQUEST_COMMIT_COMMENT_ADDED_ON = "pullRequestCommitCommentAddedOn";
String PULL_REQUEST_COMMENT_REPLIED_ON = "pullRequestCommentRepliedOn";
String PULL_REQUEST_COMMENT_EDITED_ON = "pullRequestCommentEditedOn";
String PULL_REQUEST_COMMENT_DELETED_ON = "pullRequestCommentDeletedOn";
String PULL_REQUEST_COMMENT_ADDED_ON = "pullRequestCommentAddedOn";
String PULL_REQUEST_DECLINED_ON = "pullRequestDeclinedOn";
String PULL_REQUEST_OPENED_ON = "pullRequestOpenedOn";
String PULL_REQUEST_MERGED_ON = "pullRequestMergedOn";
String PULL_REQUEST_PARTICIPANT_STATUS_UPDATED_ON = "pullRequestParticipantStatusUpdatedOn";
String PULL_REQUEST_RESCOPED_ON = "pullRequestRescopedOn";
String PULL_REQUEST_REOPENED_ON = "pullRequestReopenedOn";
String PULL_REQUEST_UPDATED_ON = "pullRequestUpdatedOn";
String PULL_REQUEST_REVIEWERS_UPDATED_ON = "pullRequestReviewersUpdatedOn";
String TASK_CREATED_ON = "taskCreatedOn";
String TASK_UPDATED_ON = "taskUpdatedOn";
String TASK_DELETED_ON = "taskDeletedOn";
}
private String webhook;
private boolean pullRequestReviewersUpdatedOn;
private boolean pullRequestUpdatedOn;
private boolean pullRequestReopenedOn;
private boolean pullRequestRescopedOn;
private boolean pullRequestParticipantStatusUpdatedOn;
private boolean pullRequestMergedOn;
private boolean pullRequestOpenedOn;
private boolean pullRequestDeclinedOn;
private boolean pullRequestCommentAddedOn;
private boolean pullRequestCommentDeletedOn;
private boolean pullRequestCommentEditedOn;
private boolean pullRequestCommentRepliedOn;
private boolean pullRequestCommitCommentAddedOn;
private boolean taskCreatedOn;
private boolean taskDeletedOn;
private boolean taskUpdatedOn;
private RepositorySettings(Builder builder) {
this.webhook = builder.webhook;
this.pullRequestReviewersUpdatedOn = builder.pullRequestReviewersUpdatedOn;
this.pullRequestUpdatedOn = builder.pullRequestUpdatedOn;
this.pullRequestReopenedOn = builder.pullRequestReopenedOn;
this.pullRequestRescopedOn = builder.pullRequestRescopedOn;
this.pullRequestParticipantStatusUpdatedOn = builder.pullRequestParticipantStatusUpdatedOn;
this.pullRequestMergedOn = builder.pullRequestMergedOn;
this.pullRequestOpenedOn = builder.pullRequestOpenedOn;
this.pullRequestDeclinedOn = builder.pullRequestDeclinedOn;
this.pullRequestCommentAddedOn = builder.pullRequestCommentAddedOn;
this.pullRequestCommentDeletedOn = builder.pullRequestCommentDeletedOn;
this.pullRequestCommentEditedOn = builder.pullRequestCommentEditedOn;
this.pullRequestCommentRepliedOn = builder.pullRequestCommentRepliedOn;
this.pullRequestCommitCommentAddedOn = builder.pullRequestCommitCommentAddedOn;
this.taskCreatedOn = builder.taskCreatedOn;
this.taskDeletedOn = builder.taskDeletedOn;
this.taskUpdatedOn = builder.taskUpdatedOn;
}
public String getWebhook() {
return webhook;
}
public boolean isPullRequestReviewersUpdatedOn() {
return pullRequestReviewersUpdatedOn;
}
public boolean isPullRequestUpdatedOn() {
return pullRequestUpdatedOn;
}
public boolean isPullRequestReopenedOn() {
return pullRequestReopenedOn;
}
public boolean isPullRequestRescopedOn() {
return pullRequestRescopedOn;
}
public boolean isPullRequestParticipantStatusUpdatedOn() {
return pullRequestParticipantStatusUpdatedOn;
}
public boolean isPullRequestMergedOn() {
return pullRequestMergedOn;
}
public boolean isPullRequestOpenedOn() {
return pullRequestOpenedOn;
}
public boolean isPullRequestDeclinedOn() {
return pullRequestDeclinedOn;
}
public boolean isPullRequestCommentAddedOn() {
return pullRequestCommentAddedOn;
}
public boolean isPullRequestCommentDeletedOn() {
return pullRequestCommentDeletedOn;
}
public boolean isPullRequestCommentEditedOn() {
return pullRequestCommentEditedOn;
}
public boolean isPullRequestCommentRepliedOn() {
return pullRequestCommentRepliedOn;
}
public boolean isPullRequestCommitCommentAddedOn() {
return pullRequestCommitCommentAddedOn;
}
public boolean isTaskCreatedOn() {
return taskCreatedOn;
}
public boolean isTaskDeletedOn() {
return taskDeletedOn;
}
public boolean isTaskUpdatedOn() {
return taskUpdatedOn;
}
public static class Builder {
private String webhook = "";
private boolean pullRequestReviewersUpdatedOn = true;
private boolean pullRequestUpdatedOn = true;
private boolean pullRequestReopenedOn = true;
private boolean pullRequestRescopedOn = true;
private boolean pullRequestParticipantStatusUpdatedOn = true;
private boolean pullRequestMergedOn = true;
private boolean pullRequestOpenedOn = true;
private boolean pullRequestDeclinedOn = true;
private boolean pullRequestCommentAddedOn = true;
private boolean pullRequestCommentDeletedOn = true;
private boolean pullRequestCommentEditedOn = true;
private boolean pullRequestCommentRepliedOn = true;
private boolean pullRequestCommitCommentAddedOn = true;
private boolean taskCreatedOn = true;
private boolean taskDeletedOn = true;
private boolean taskUpdatedOn = true;
public Builder webhook(String webhook) {
this.webhook = webhook;
return this;
}
public Builder pullRequestReviewersUpdatedOn(boolean pullRequestReviewersUpdatedOn) {
this.pullRequestReviewersUpdatedOn = pullRequestReviewersUpdatedOn;
return this;
}
public Builder pullRequestUpdatedOn(boolean pullRequestUpdatedOn) {
this.pullRequestUpdatedOn = pullRequestUpdatedOn;
return this;
}
public Builder pullRequestReopenedOn(boolean pullRequestReopenedOn) {
this.pullRequestReopenedOn = pullRequestReopenedOn;
return this;
}
public Builder pullRequestRescopedOn(boolean pullRequestRescopedOn) {
this.pullRequestRescopedOn = pullRequestRescopedOn;
return this;
}
public Builder pullRequestParticipantStatusUpdatedOn(boolean pullRequestParticipantStatusUpdatedOn) {
this.pullRequestParticipantStatusUpdatedOn = pullRequestParticipantStatusUpdatedOn;
return this;
}
public Builder pullRequestMergedOn(boolean pullRequestMergedOn) {
this.pullRequestMergedOn = pullRequestMergedOn;
return this;
}
public Builder pullRequestOpenedOn(boolean pullRequestOpenedOn) {
this.pullRequestOpenedOn = pullRequestOpenedOn;
return this;
}
public Builder pullRequestDeclinedOn(boolean pullRequestDeclinedOn) {
this.pullRequestDeclinedOn = pullRequestDeclinedOn;
return this;
}
public Builder pullRequestCommentAddedOn(boolean pullRequestCommentAddedOn) {
this.pullRequestCommentAddedOn = pullRequestCommentAddedOn;
return this;
}
public Builder pullRequestCommentDeletedOn(boolean pullRequestCommentDeletedOn) {
this.pullRequestCommentDeletedOn = pullRequestCommentDeletedOn;
return this;
}
public Builder pullRequestCommentEditedOn(boolean pullRequestCommentEditedOn) {
this.pullRequestCommentEditedOn = pullRequestCommentEditedOn;
return this;
}
public Builder pullRequestCommentRepliedOn(boolean pullRequestCommentRepliedOn) {
this.pullRequestCommentRepliedOn = pullRequestCommentRepliedOn;
return this;
}
public Builder pullRequestCommitCommentAddedOn(boolean pullRequestCommitCommentAddedOn) {
this.pullRequestCommitCommentAddedOn = pullRequestCommitCommentAddedOn;
return this;
}
public Builder taskCreatedOn(boolean taskCreatedOn) {
this.taskCreatedOn = taskCreatedOn;
return this;
}
public Builder taskDeletedOn(boolean taskDeletedOn) {
this.taskDeletedOn = taskDeletedOn;
return this;
}
public Builder taskUpdatedOn(boolean taskUpdatedOn) {
this.taskUpdatedOn = taskUpdatedOn;
return this;
}
public RepositorySettings build() {
return new RepositorySettings(this);
}
}
}
| 32.783333 | 103 | 0.818124 |
f74523f0ef9b1d6899ae6a77aeab2436a4a00e84 | 978 | package edu.emory.bmi.tcia.client.exceptions;
/**
* The TCIA Client Exception
*/
public class TCIAClientException extends Exception {
private static final long serialVersionUID = -2548423882689490254L;
private String requestUrl;
public TCIAClientException(String requestUrl) {
super();
this.requestUrl = requestUrl;
}
public TCIAClientException(String message, Throwable cause , String requestUrl) {
super(message, cause);
this.requestUrl = requestUrl;
}
public TCIAClientException(String message, String requestUrl) {
super(message);
this.requestUrl = requestUrl;
}
public TCIAClientException(Throwable cause , String requestUrl) {
super(cause);
this.requestUrl = requestUrl;
}
public String toString()
{
return String.format("Request URL =[%s]\t%s", this.requestUrl , super.toString());
}
@Override
public String getMessage() {
return String.format("Request URL =[%s]\t%s", this.requestUrl , super.getMessage());
}
}
| 21.26087 | 86 | 0.729039 |
ed3d865b1b6a0fd76b6fdc9f3329235e6306abb1 | 1,651 | /*
* Copyright 2018 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.workbench.common.stunner.client.lienzo;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import com.ait.lienzo.client.core.config.LienzoCore;
import com.ait.lienzo.shared.core.types.ImageSelectionMode;
import org.jboss.errai.ioc.client.api.EntryPoint;
@ApplicationScoped
@EntryPoint
public class StunnerLienzoCore {
/**
* It's really important to set the <code>ImageSelectionMode</code> to the
* value <code>SELECT_BOUNDS</code> due to performance reasons (image rendering on different browsers).
* Stunner does not use image filters neither requires the image to be drawn in the
* selection context2D, so it uses the value <code>SELECT_BOUNDS</code> as default.
* Also it's being used due to huge differences on the resulting performance when
* rendering the images into the contexts.
*/
@PostConstruct
public void init() {
LienzoCore.get().setDefaultImageSelectionMode(ImageSelectionMode.SELECT_BOUNDS);
}
}
| 38.395349 | 107 | 0.750454 |
56630b60b7bff830941c3a995783ace1ad59133f | 446 | package me.egg82.ae.api.enchantments;
import java.util.UUID;
import me.egg82.ae.api.AdvancedEnchantment;
import me.egg82.ae.api.AdvancedEnchantmentTarget;
public class PoisonousEnchantment extends AdvancedEnchantment {
public PoisonousEnchantment() {
super(UUID.randomUUID(), "poisonous", "Poisonous", false, 1, 5);
targets.add(AdvancedEnchantmentTarget.WEAPON);
conflicts.add(AdvancedEnchantment.BLINDING);
}
}
| 31.857143 | 72 | 0.753363 |
0563bfde555db693ff738c9d5bdd42cd9e77d8cf | 15,994 | /**
HostNotificationProfile.java
Copyright (c) 2014 NTT DOCOMO,INC.
Released under the MIT license
http://opensource.org/licenses/mit-license.php
*/
package com.nttdocomo.android.dconnect.deviceplugin.host.profile;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.app.NotificationCompat;
import com.nttdocomo.android.dconnect.deviceplugin.host.R;
import com.nttdocomo.android.dconnect.event.Event;
import com.nttdocomo.android.dconnect.event.EventError;
import com.nttdocomo.android.dconnect.event.EventManager;
import com.nttdocomo.android.dconnect.message.MessageUtils;
import com.nttdocomo.android.dconnect.profile.NotificationProfile;
import com.nttdocomo.dconnect.message.DConnectMessage;
import com.nttdocomo.dconnect.message.intent.message.IntentDConnectMessage;
/**
* ホストデバイスプラグイン, Notification プロファイル.
* @author NTT DOCOMO, INC.
*/
public class HostNotificationProfile extends NotificationProfile {
/** Debug Tag. */
private static final String TAG = "HOST";
/** Randam Seed. */
private static final int RANDAM_SEED = 1000000;
/**
* Notificationテータスレシーバー.
*/
private NotificationStatusReceiver mNotificationStatusReceiver;
/**
* Notification Flag.
*/
private static final String ACTON_NOTIFICATION = "dconnect.notifiy";
/** Error. */
private static final int ERROR_VALUE_IS_NULL = 100;
/**
* POSTメッセージ受信時の処理.
*/
@Override
public boolean onPostNotify(final Intent request, final Intent response, final String deviceId,
final NotificationType type, final Direction dir, final String lang, final String body, final String tag,
final byte[] iconData) {
// super.onPostRequest(request, response);
if (deviceId == null) {
createEmptyDeviceId(response);
} else if (!checkDeviceId(deviceId)) {
createNotFoundDevice(response);
} else {
if (NotificationProfile.ATTRIBUTE_NOTIFY.equals(getAttribute(request))) {
if (body == null) {
MessageUtils.setError(response, ERROR_VALUE_IS_NULL, "body is null");
return true;
} else {
if (mNotificationStatusReceiver == null) {
mNotificationStatusReceiver = new NotificationStatusReceiver();
getContext().getApplicationContext().registerReceiver(mNotificationStatusReceiver,
new IntentFilter(ACTON_NOTIFICATION));
}
int iconType = 0;
String mTitle = "";
// Typeの処理
if (type == NotificationType.PHONE) {
iconType = R.drawable.notification_00;
mTitle = "PHONE";
} else if (type == NotificationType.MAIL) {
iconType = R.drawable.notification_01;
mTitle = "MAIL";
} else if (type == NotificationType.SMS) {
iconType = R.drawable.notification_02;
mTitle = "SMS";
} else if (type == NotificationType.EVENT) {
iconType = R.drawable.notification_03;
mTitle = "EVENT";
} else {
MessageUtils.setError(response, ERROR_VALUE_IS_NULL, "not support type");
return true;
}
String encodeBody = "";
try {
encodeBody = URLDecoder.decode(body, "UTF-8");
} catch (UnsupportedEncodingException e) {
}
Random random = new Random();
int notifyId = random.nextInt(RANDAM_SEED);
// Build intent for notification content
Intent notifyIntent = new Intent(ACTON_NOTIFICATION);
notifyIntent.putExtra("notificationId", notifyId);
notifyIntent.putExtra("deviceId", deviceId);
PendingIntent mPendingIntent = PendingIntent.getBroadcast(this.getContext(),
notifyId,
notifyIntent,
android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this.getContext())
.setSmallIcon(iconType)
.setContentTitle("" + mTitle)
.setContentText(encodeBody)
.setContentIntent(mPendingIntent);
// Get an instance of the NotificationManager service
NotificationManager mNotification = (NotificationManager) getContext()
.getSystemService(Context.NOTIFICATION_SERVICE);
// Build the notification and issues it with notification
// manager.
mNotification.notify(notifyId, notificationBuilder.build());
response.putExtra(NotificationProfile.PARAM_NOTIFICATION_ID, notifyId);
setResult(response, IntentDConnectMessage.RESULT_OK);
List<Event> events = EventManager.INSTANCE.getEventList(
deviceId,
HostNotificationProfile.PROFILE_NAME,
null,
HostNotificationProfile.ATTRIBUTE_ON_SHOW);
for (int i = 0; i < events.size(); i++) {
Event event = events.get(i);
Intent intent = EventManager.createEventMessage(event);
intent.putExtra(HostNotificationProfile.PARAM_NOTIFICATION_ID, notifyId);
getContext().sendBroadcast(intent);
}
return true;
}
} else {
MessageUtils.setError(response, ERROR_VALUE_IS_NULL, "not support profile");
return true;
}
}
return true;
}
/**
* デバイスへのノーティフィケーション消去リクエストハンドラー.<br/>
* ノーティフィケーションを消去し、その結果をレスポンスパラメータに格納する。
* レスポンスパラメータの送信準備が出来た場合は返り値にtrueを指定する事。
* 送信準備ができていない場合は、返り値にfalseを指定し、スレッドを立ち上げてそのスレッドで最終的にレスポンスパラメータの送信を行う事。
*
* @param request リクエストパラメータ
* @param response レスポンスパラメータ
* @param deviceId デバイスID
* @param notificationId 通知ID
* @return レスポンスパラメータを送信するか否か
*/
protected boolean onDeleteNotify(final Intent request, final Intent response, final String deviceId,
final String notificationId) {
if (deviceId == null) {
createEmptyDeviceId(response);
} else if (!checkDeviceId(deviceId)) {
createNotFoundDevice(response);
} else {
NotificationManager mNotificationManager =
(NotificationManager) this.getContext().getSystemService(
this.getContext().NOTIFICATION_SERVICE);
mNotificationManager.cancel(Integer.parseInt(notificationId));
setResult(response, IntentDConnectMessage.RESULT_OK);
List<Event> events = EventManager.INSTANCE.getEventList(
deviceId,
HostNotificationProfile.PROFILE_NAME,
null,
HostNotificationProfile.ATTRIBUTE_ON_CLOSE);
for (int i = 0; i < events.size(); i++) {
Event event = events.get(i);
Intent intent = EventManager.createEventMessage(event);
intent.putExtra(HostNotificationProfile.PARAM_NOTIFICATION_ID, notificationId);
getContext().sendBroadcast(intent);
}
}
return true;
}
@Override
protected boolean onPutOnClick(final Intent request, final Intent response,
final String deviceId, final String sessionKey) {
if (deviceId == null) {
createEmptyDeviceId(response);
} else if (!checkDeviceId(deviceId)) {
createNotFoundDevice(response);
} else if (sessionKey == null) {
createEmptySessionKey(response);
} else {
mNotificationStatusReceiver = new NotificationStatusReceiver();
IntentFilter intentFilter = new IntentFilter(ACTON_NOTIFICATION);
this.getContext().registerReceiver(mNotificationStatusReceiver, intentFilter);
// イベントの登録
EventError error = EventManager.INSTANCE.addEvent(request);
if (error == EventError.NONE) {
setResult(response, DConnectMessage.RESULT_OK);
return true;
} else {
setResult(response, DConnectMessage.RESULT_ERROR);
return true;
}
}
return true;
}
@Override
protected boolean onPutOnClose(final Intent request, final Intent response,
final String deviceId, final String sessionKey) {
if (deviceId == null) {
createEmptyDeviceId(response);
} else if (!checkDeviceId(deviceId)) {
createNotFoundDevice(response);
} else if (sessionKey == null) {
createEmptySessionKey(response);
} else {
// イベントの登録
EventError error = EventManager.INSTANCE.addEvent(request);
if (error == EventError.NONE) {
setResult(response, DConnectMessage.RESULT_OK);
return true;
} else {
setResult(response, DConnectMessage.RESULT_ERROR);
return true;
}
}
return true;
}
@Override
protected boolean onPutOnShow(final Intent request, final Intent response,
final String deviceId, final String sessionKey) {
if (deviceId == null) {
createEmptyDeviceId(response);
} else if (!checkDeviceId(deviceId)) {
createNotFoundDevice(response);
} else if (sessionKey == null) {
createEmptySessionKey(response);
} else {
// イベントの登録
EventError error = EventManager.INSTANCE.addEvent(request);
if (error == EventError.NONE) {
setResult(response, DConnectMessage.RESULT_OK);
} else {
setResult(response, DConnectMessage.RESULT_ERROR);
}
}
return true;
}
@Override
protected boolean onDeleteOnClick(final Intent request,
final Intent response, final String deviceId,
final String sessionKey) {
if (deviceId == null) {
createEmptyDeviceId(response);
} else if (!checkDeviceId(deviceId)) {
createNotFoundDevice(response);
} else if (sessionKey == null) {
createEmptySessionKey(response);
} else {
// イベントの解除
EventError error = EventManager.INSTANCE.removeEvent(request);
if (error == EventError.NONE) {
setResult(response, DConnectMessage.RESULT_OK);
} else {
setResult(response, DConnectMessage.RESULT_ERROR);
}
}
return true;
}
@Override
protected boolean onDeleteOnClose(final Intent request,
final Intent response, final String deviceId,
final String sessionKey) {
if (deviceId == null) {
createEmptyDeviceId(response);
} else if (!checkDeviceId(deviceId)) {
createNotFoundDevice(response);
} else if (sessionKey == null) {
createEmptySessionKey(response);
} else {
// イベントの解除
EventError error = EventManager.INSTANCE.removeEvent(request);
if (error == EventError.NONE) {
setResult(response, DConnectMessage.RESULT_OK);
} else {
setResult(response, DConnectMessage.RESULT_ERROR);
}
}
return true;
}
@Override
protected boolean onDeleteOnShow(final Intent request,
final Intent response, final String deviceId,
final String sessionKey) {
if (deviceId == null) {
createEmptyDeviceId(response);
} else if (!checkDeviceId(deviceId)) {
createNotFoundDevice(response);
} else if (sessionKey == null) {
createEmptySessionKey(response);
} else {
// イベントの解除
EventError error = EventManager.INSTANCE.removeEvent(request);
if (error == EventError.NONE) {
setResult(response, DConnectMessage.RESULT_OK);
} else {
setResult(response, DConnectMessage.RESULT_ERROR);
}
}
return true;
}
/**
* デバイスIDが空の場合のエラーを作成する.
*
* @param response レスポンスを格納するIntent
*/
private void createEmptyDeviceId(final Intent response) {
MessageUtils.setEmptyDeviceIdError(response);
}
/**
* セッションキーが空の場合のエラーを作成する.
*
* @param response レスポンスを格納するIntent
*/
private void createEmptySessionKey(final Intent response) {
MessageUtils.setError(response, ERROR_VALUE_IS_NULL, "SessionKey not found");
}
/**
* デバイスが発見できなかった場合のエラーを作成する.
*
* @param response レスポンスを格納するIntent
*/
private void createNotFoundDevice(final Intent response) {
MessageUtils.setNotFoundDeviceError(response);
}
/**
* デバイスIDをチェックする.
*
* @param deviceId デバイスID
* @return <code>deviceId</code>がテスト用デバイスIDに等しい場合はtrue、そうでない場合はfalse
*/
private boolean checkDeviceId(final String deviceId) {
String regex = HostNetworkServiceDiscoveryProfile.DEVICE_ID;
Pattern mPattern = Pattern.compile(regex);
Matcher match = mPattern.matcher(deviceId);
return match.find();
}
/**
* ノーティフィケーション.
*/
private class NotificationStatusReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
// クリティカルセクション(バッテリーステータスの状態更新etc)にmutexロックを掛ける。
synchronized (this) {
String actionName = intent.getAction();
int notificationId = intent.getIntExtra("notificationId", -1);
String mDeviceId = intent.getStringExtra("deviceId");
List<Event> events = EventManager.INSTANCE.getEventList(
mDeviceId,
HostNotificationProfile.PROFILE_NAME,
null,
HostNotificationProfile.ATTRIBUTE_ON_CLICK);
for (int i = 0; i < events.size(); i++) {
Event event = events.get(i);
Intent mIntent = EventManager.createEventMessage(event);
mIntent.putExtra(HostNotificationProfile.PARAM_NOTIFICATION_ID, "" + notificationId);
getContext().sendBroadcast(mIntent);
}
// 状態更新の為のmutexロックを外して、待っていた処理に通知する。
notifyAll();
}
}
}
}
| 37.023148 | 117 | 0.572277 |
7823bdc78a1998fc279f6a25a18b97590e4f2156 | 732 | import java.util.List;
import java.util.Map;
import java.util.HashMap;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import org.apache.ibatis.annotations.Select;
@Mapper
@Repository
public interface SqlInjectionMapper {
List<Test> bad1(String name);
List<Test> bad2(@Param("orderby") String name);
List<Test> bad3(Test test);
void bad4(@Param("test") Test test);
void bad5(Test test);
void bad6(Map<String, String> params);
void bad7(List<String> params);
void bad8(String[] params);
@Select({"select * from test", "where id = ${name}"})
public Test bad9(HashMap<String, Object> map);
List<Test> good1(Integer id);
}
| 21.529412 | 54 | 0.739071 |
9b7105f91c59a9a76ab6734772427fdb6c86cf18 | 958 | package io.perfeccionista.framework.exceptions;
import io.perfeccionista.framework.exceptions.base.PerfeccionistaRuntimeException;
import io.perfeccionista.framework.exceptions.base.Reason;
import org.jetbrains.annotations.NotNull;
public interface MethodInvocationFailed extends Reason {
static MethodInvocationFailedException exception(@NotNull String message) {
return new MethodInvocationFailedException(message);
}
static MethodInvocationFailedException exception(@NotNull String message, @NotNull Throwable cause) {
return new MethodInvocationFailedException(message, cause);
}
class MethodInvocationFailedException extends PerfeccionistaRuntimeException implements MethodNotFound {
MethodInvocationFailedException(String message) {
super(message);
}
MethodInvocationFailedException(String message, Throwable cause) {
super(message, cause);
}
}
}
| 31.933333 | 108 | 0.76618 |
6816df3b4373a57692e9ac6b164235c623e00822 | 2,368 | /*
* 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 concessionaria;
import java.util.ArrayList;
import java.util.List;
/**
* A classe estoque possui a relação de carros da concessionária.
* @author alinemello
*/
public class Estoque {
private List<Carro> carros;
public Estoque(){
carros = new ArrayList();
}
/**
* Adiciona um carro no estoque com as características informadas por parâmetro.
* @param chassi Número do chassi.
* @param preco Preço.
* @param modelo Modelo
* @param nroPortas Número de portas.
*/
public void addCarro(String chassi, double preco, String modelo, int nroPortas){
Carro carro = new Carro(chassi, preco, modelo, nroPortas);
carros.add(carro);
}
/**
* Captura o carro com o chassi informado.
* @param chassi Número de chassi.
* @return Carro que possui o chassi informado. Caso nenhum carro possua o
* chassi informado então retorna null.
*/
public Carro getCarro(String chassi){
for(Carro carro : carros){
if(carro.getChassi().equalsIgnoreCase(chassi))
return carro;
}
return null;
}
/**
* Procura um carro com as mesmas características do carroDesejado.
* @param carroDesejado Carro com as características desejadas.
* @return Retorna o carro com as características desejadas. Caso não exista
* nenhum carro que atenda todas as características então retorna null.
*/
public Carro procura(Carro carroDesejado){
String modeloDesejado = carroDesejado.getModelo();
int nroPortasDesejado = carroDesejado.getNroPortas();
double precoDesejado = carroDesejado.getPreco();
for(Carro carro : carros){
if((modeloDesejado != null) && (!modeloDesejado.equals("")) && (!modeloDesejado.equals(carro.getModelo())))
continue;
if((nroPortasDesejado != 0) && (nroPortasDesejado != carro.getNroPortas()))
continue;
if((precoDesejado != 0) && (precoDesejado < carro.getPreco()))
continue;
return carro;
}
return null;
}
}
| 32.888889 | 119 | 0.629223 |
0d659e81cdecbc461db06dfe221ab890acf1d3fc | 366 | package LinkedDB.UI;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.TreeItem;
/**
* This class defines the Abstract class for the new TreeView and its ContextMenu that shows on the Main Window
*
* @author Roger Valderrama
*/
public abstract class TreeAbstractNode extends TreeItem<String> {
public abstract ContextMenu getMenu();
}
| 22.875 | 111 | 0.773224 |
8b2aab29bfa21e8db0ecb91af0c8d9c7ac40f88f | 939 | package com.github.shaigem.linkgem.ui.listeners;
import com.github.shaigem.linkgem.model.item.BookmarkItem;
import com.github.shaigem.linkgem.model.item.FolderItem;
import com.github.shaigem.linkgem.ui.dialog.bookmark.BookmarkEditorDialog;
import com.github.shaigem.linkgem.ui.dialog.folder.FolderEditorDialog;
import com.github.shaigem.linkgem.ui.events.OpenItemEditorDialogRequest;
import org.sejda.eventstudio.Listener;
/**
* Listens for any requests to open the item editor dialog.
*
* @author Ronnie Tran
*/
public class ItemDialogListener implements Listener<OpenItemEditorDialogRequest> {
@Override
public void onEvent(OpenItemEditorDialogRequest event) {
if (event.getWorkingItem() instanceof BookmarkItem) {
new BookmarkEditorDialog().showDialog(event);
} else if (event.getWorkingItem() instanceof FolderItem) {
new FolderEditorDialog().showDialog(event);
}
}
}
| 36.115385 | 82 | 0.763578 |
8b0e17c236b8a5174d44a4387ec1d1dc5b1379e2 | 976 | package io.cloudreactor.javaquickstart;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
/** JUnit5 example test adopted from
*
* https://github.com/junit-team/junit5-samples/blob/r5.8.2/junit5-jupiter-starter-gradle/src/test/java/com/example/project/CalculatorTests.java
*
*/
public class MainTest {
@Test
@DisplayName("1 + 1 = 2")
void addsTwoNumbers() {
assertEquals(2, Main.add(1, 1), "1 + 1 should equal 2");
}
@ParameterizedTest(name = "{0} + {1} = {2}")
@CsvSource({
"0, 1, 1",
"1, 2, 3",
"49, 51, 100",
"1, 100, 101"
})
void add(int first, int second, int expectedResult) {
assertEquals(expectedResult, Main.add(first, second),
() -> first + " + " + second + " should equal " + expectedResult);
}
}
| 28.705882 | 145 | 0.663934 |
613434223b698fe1d5fb9b8b2d52da697e25af2f | 7,573 | /*
* 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 Library.Management.System;
import net.proteanit.sql.DbUtils;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
*
* @author harsh
*/
public class Statistics extends javax.swing.JFrame {
/**
* Creates new form Statistics
*/
public Statistics() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
Back_Label_btn = new javax.swing.JLabel();
IssueBookDetails_panel = new javax.swing.JPanel();
Table_JScroll = new javax.swing.JScrollPane();
IssueBookTable = new javax.swing.JTable();
ReturnBookDetails_panel = new javax.swing.JPanel();
Table_JScroll1 = new javax.swing.JScrollPane();
ReturnBookTable = new javax.swing.JTable();
BackgroundImage = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(new java.awt.Dimension(935, 800));
getContentPane().setLayout(null);
Back_Label_btn.setFont(new java.awt.Font("Segoe UI", 1, 16)); // NOI18N
Back_Label_btn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Library/Management/System/Icons/icons8_left_3_30px.png"))); // NOI18N
Back_Label_btn.setText("Back");
Back_Label_btn.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
setVisible(false);
Home home = new Home();
home.setVisible(true);
}
});
getContentPane().add(Back_Label_btn);
Back_Label_btn.setBounds(780, 20, 79, 30);
IssueBookDetails_panel.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 2), "Issue Book Details", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Segoe UI", 1, 24))); // NOI18N
IssueBookDetails_panel.setOpaque(false);
IssueBookDetails_panel.setLayout(null);
Table_JScroll.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
Table_JScroll.setViewportView(IssueBookTable);
IssueBookTable.setBackground(new Color(240, 248, 255));
IssueBookTable.setForeground(Color.DARK_GRAY);
IssueBookTable.setFont(new Font("Trebuchet MS", Font.BOLD, 14));
IssueBookDetails_panel.add(Table_JScroll);
Table_JScroll.setBounds(10, 30, 800, 300);
getContentPane().add(IssueBookDetails_panel);
IssueBookDetails_panel.setBounds(50, 40, 820, 340);
ReturnBookDetails_panel.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 2), "Return Book Details", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Segoe UI", 1, 24))); // NOI18N
ReturnBookDetails_panel.setOpaque(false);
ReturnBookDetails_panel.setLayout(null);
Table_JScroll1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
Table_JScroll1.setViewportView(ReturnBookTable);
ReturnBookTable.setBackground(new Color(240, 248, 255));
ReturnBookTable.setForeground(Color.DARK_GRAY);
ReturnBookTable.setFont(new Font("Trebuchet MS", Font.BOLD, 14));
ReturnBookDetails_panel.add(Table_JScroll1);
Table_JScroll1.setBounds(10, 30, 800, 300);
getContentPane().add(ReturnBookDetails_panel);
ReturnBookDetails_panel.setBounds(50, 390, 820, 340);
BackgroundImage.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Library/Management/System/Icons/Summer Dog.jpg"))); // NOI18N
getContentPane().add(BackgroundImage);
BackgroundImage.setBounds(0, 0, 920, 820);
pack();
issueBook();
returnBook();
setLocationRelativeTo(null);
}// </editor-fold>
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Statistics.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Statistics.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Statistics.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Statistics.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Statistics().setVisible(true);
}
});
}
public void issueBook() {
try {
conn con = new conn();
String sql = "select * from issueBook";
PreparedStatement st = con.c.prepareStatement(sql);
ResultSet rs = st.executeQuery();
IssueBookTable.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
// TODO: handle exception
}
}
public void returnBook() {
try {
conn con = new conn();
String sql = "select * from returnBook";
PreparedStatement st = con.c.prepareStatement(sql);
ResultSet rs = st.executeQuery();
ReturnBookTable.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
// TODO: handle exception
}
}
// Variables declaration - do not modify
private javax.swing.JLabel Back_Label_btn;
private javax.swing.JLabel BackgroundImage;
private javax.swing.JPanel IssueBookDetails_panel;
private javax.swing.JTable IssueBookTable;
private javax.swing.JPanel ReturnBookDetails_panel;
private javax.swing.JTable ReturnBookTable;
private javax.swing.JScrollPane Table_JScroll;
private javax.swing.JScrollPane Table_JScroll1;
// End of variables declaration
}
| 44.02907 | 312 | 0.664994 |
a95c817c70712543152c756fcd0632f37ac44771 | 870 | package org.seasar.doma.internal.jdbc.command;
import static org.seasar.doma.internal.util.AssertionUtil.assertNotNull;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Stream;
import org.seasar.doma.internal.jdbc.scalar.Scalar;
import org.seasar.doma.jdbc.query.SelectQuery;
public class ScalarStreamHandler<BASIC, CONTAINER, RESULT>
extends AbstractStreamHandler<CONTAINER, RESULT> {
protected final Supplier<Scalar<BASIC, CONTAINER>> supplier;
public ScalarStreamHandler(
Supplier<Scalar<BASIC, CONTAINER>> supplier, Function<Stream<CONTAINER>, RESULT> mapper) {
super(mapper);
assertNotNull(supplier);
this.supplier = supplier;
}
@Override
protected ScalarProvider<BASIC, CONTAINER> createObjectProvider(SelectQuery query) {
return new ScalarProvider<>(supplier, query);
}
}
| 31.071429 | 96 | 0.77931 |
4d42925ee6ec561df15a55bca7e94c081084792d | 13,840 | package mathtools;
import hashtools.Key;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
public class Order_old<V> {
/* * * * * * * *
* FIELDS *
* * * * * * * */
protected HashSet<V> elements;
protected HashSet<Key<V, V>> trans = null; // The transitive closure of order relations
protected HashMap<V, Interval> stdIntRanks = null;
/* * * * * * * * * * *
* CONSTRUCTORS *
* * * * * * * * * * */
public Order_old(){
elements = new HashSet<V>();
trans = new HashSet<Key<V, V>>();
}
public Order_old(HashSet<Key<V, V>> relations){
makeElements(relations);
makeTrans(relations);
}
public Order_old(HashSet<V> elements, HashSet<Key<V, V>> relations){
this(relations);
this.elements = elements;
}
/* * * * * * * * * * * * * *
* CONSTRUCTOR HELPERS *
* * * * * * * * * * * * * */
/**
* Calculates the elements in the poset as being those which
* are in the given relations.
*
* @param relations A set of pairs representing relations
* in the poset
*/
public void makeElements(HashSet<Key<V, V>> relations){
elements = new HashSet<V>();
for (Key<V, V> pair : relations){
elements.add(pair.getFirst());
elements.add(pair.getSecond());
}
}
/**
* Modeled after HasseToPoset
*
* @param relations A set of pairs representing a<b relations
* in the Order
*/
public void makeTrans(HashSet<Key<V, V>> relations){
HashSet<Key<V, V>> P = new HashSet<Key<V, V>>();
HashSet<Key<V, V>> P1 = (HashSet<Key<V, V>>) relations.clone();
while (!P.equals(P1)){
P.addAll(P1);
HashSet<Key<V, V>> toAdd = new HashSet<Key<V, V>>();
for (Key<V, V> pair : P1){
V smaller = pair.getFirst();
V larger = pair.getSecond();
for (Key<V, V> pair2 : P){
if (pair2.getFirst().equals(larger)){
toAdd.add(new Key<V, V>(smaller, pair2.getSecond()));
}
}
}
P1.addAll(toAdd);
}
for (V p : elements){
P.add(new Key<V, V>(p, p));
}
trans = P;
}
/* * * * * * * * * * * *
* GETTERS/SETTERS *
* * * * * * * * * * * */
/**
* @param e Adds an element to the Order
*/
public void addElement(V e){
elements.add(e);
}
/**
* @param relation Adds a relation to the Order
*/
public void addRelation(Key<V, V> relation){
trans.add(relation);
makeTrans(trans);
}
/**
* @return The set of poset elements
*/
public HashSet<V> getElements(){
return elements;
}
/**
* @return The full set of poset relations
*/
public HashSet<Key<V, V>> getTrans(){
return trans;
}
/* * * * * * *
* TESTS *
* * * * * * */
/**
* Checks to see if the number of relations is equal to
* the number of elements (n) choose 2, plus n. If so, then
* all relations must be present and so the poset is a chain.
*
* @return true if this poset is a chain, false otherwise
*/
public boolean isChain(){
int n = elements.size();
int m = trans.size();
if (m == n*(n-1)/2+n)
return true;
else
return false;
}
/**
* Checks to see if all relations are of the form <p, p>. If one is
* found that is <p, q> for p \neq q then it returns false at that time.
* Otherwise, after checking all relations, it returns true.
*
* @return true if this poset is an antichain, false otherwise
*/
public boolean isAntichain(){
for (Key<V, V> pair : trans){
if (!pair.getFirst().equals(pair.getSecond()))
return false;
}
return true;
}
/**
* @return true if the poset is graded, false otherwise. This is
* tested by looking at the standard interval rank. If all
* interval ranks are [i,i] then the Order is graded
*/
public boolean isGraded(){
HashMap<V, Interval> stdIntRank = stdIntRank();
boolean graded = true;
for (V e : elements){
Interval r = stdIntRank.get(e);
if (r.getLeft() != r.getRight()){
graded = false;
break;
}
}
return graded;
}
/* * * * * * * * * * * * *
* BASIC OPERATIONS *
* * * * * * * * * * * * */
/**
* @return The minimum elements of the Poset
*/
public HashSet<V> min(){
// First, find those elements which are second coordiates
// in covers. These elements can't be minimums because
// they are larger than something.
HashSet<V> notMin = new HashSet<V>();
for (Key<V, V> pair : trans){
if (!pair.getFirst().equals(pair.getSecond())){
notMin.add(pair.getSecond());
}
}
// Find those elements which are not in notMin
HashSet<V> Min = new HashSet<V>();
for (V p : elements){
if (!notMin.contains(p)){
Min.add(p);
}
}
return Min;
}
/**
* @return The maximum elements of the Poset
*/
public HashSet<V> max(){
// First, find those elements which are first coordiates
// in covers. These elements can't be maximums because
// they are smaller than something.
HashSet<V> notMax = new HashSet<V>();
for (Key<V, V> pair : trans){
if (!pair.getFirst().equals(pair.getSecond())){
notMax.add(pair.getFirst());
}
}
// Find those elements which are not in notMax
HashSet<V> Max = new HashSet<V>();
for (V p : elements){
if (!notMax.contains(p)){
Max.add(p);
}
}
return Max;
}
/**
* @return A set of the maximal chains in the poset. Each
* maximal chain is stored as an ArrayList where the elements
* increase from left to right (first to last).
*/
public HashSet<ArrayList<V>> maximalChains(){
HashSet<ArrayList<V>> MC = new HashSet<ArrayList<V>>();
if (elements.size() == 1){
ArrayList<V> C = new ArrayList<V>();
C.addAll(elements);
MC.add(C);
} else if (isAntichain()){
for (V e : elements){
ArrayList<V> C = new ArrayList<V>();
C.add(e);
MC.add(C);
}
} else {
HashSet<V> M = max();
for (V m : M){
Order_old<V> mDn = lessThan(m);
HashSet<ArrayList<V>> Cm = mDn.maximalChains();
for (ArrayList<V> C : Cm){
C.add(m);
MC.add(C);
}
}
}
return MC;
}
/**
* @return The height of this poset, i.e. the length
* of the largest chain.
*/
public int height(){
HashSet<ArrayList<V>> MC = maximalChains();
int H = Integer.MIN_VALUE;
for (ArrayList<V> C : MC){
if (C.size() > H){
H = C.size();
}
}
return H;
}
/**
* @param subElements A subset of elements
* @return The Poset with only those relations involving
* items from subElements
*/
public Order_old<V> restriction(HashSet<V> subElements){
HashSet<Key<V, V>> relations = new HashSet<Key<V, V>>();
for (Key<V, V> pair : trans){
if (subElements.contains(pair.getFirst()) && subElements.contains(pair.getSecond()))
relations.add(pair);
}
return new Order_old<V>(subElements, relations);
}
/**
* @param p An element of this poset
* @param q An element of this poset
* @return The set of all elements which are greater than or equal to p
* and smaller than or equal to q.
*/
public HashSet<V> intervalSet(V p, V q){
HashSet<V> upP = upSet(p);
HashSet<V> downQ = downSet(q);
HashSet<V> interval = new HashSet<V>();
for (V a : upP){
if (downQ.contains(a)){
interval.add(a);
}
}
return interval;
}
/**
* @param p An element of this poset
* @param q An element of this poset
* @return The poset formed by the set of all elements which are
* greater than or equal to p and smaller than or equal to q.
*/
public Order_old<V> interval(V p, V q){
HashSet<V> upP = upSet(p);
HashSet<V> downQ = downSet(q);
HashSet<V> interval = new HashSet<V>();
for (V a : upP){
if (downQ.contains(a)){
interval.add(a);
}
}
return restriction(interval);
}
/**
* @param p An element in this poset
* @return The poset formed by all elements smaller than or equal to p
*/
public Order_old<V> down(V p){
HashSet<V> subElements = new HashSet<V>();
// for each relation, if the larger (second) is p then add the
// smaller (first) to subElements
for (Key<V, V> pair : trans){
if (pair.getSecond().equals(p))
subElements.add(pair.getFirst());
}
return restriction(subElements);
}
/**
* @param p An element in this poset
* @return The set of elements smaller than or equal to p
*/
public HashSet<V> downSet(V p){
HashSet<V> subElements = new HashSet<V>();
// for each relation, if the larger (second) is p then add the
// smaller (first) to subElements
for (Key<V, V> pair : trans){
if (pair.getSecond().equals(p))
subElements.add(pair.getFirst());
}
return subElements;
}
/**
* @param p An element in this poset
* @return The poset formed by all elements smaller than or equal to p
*/
public Order_old<V> up(V p){
HashSet<V> subElements = new HashSet<V>();
// for each relation, if the smaller (first) is p then add the
// larger (second) to subElements
for (Key<V, V> pair : trans){
if (pair.getFirst().equals(p))
subElements.add(pair.getSecond());
}
return restriction(subElements);
}
/**
* @param p An element in this poset
* @return The set of elements larger than or equal to p
*/
public HashSet<V> upSet(V p){
HashSet<V> subElements = new HashSet<V>();
// for each relation, if the smaller (first) is p then add the
// larger (second) to subElements
for (Key<V, V> pair : trans){
if (pair.getFirst().equals(p))
subElements.add(pair.getSecond());
}
return subElements;
}
/**
* @param p An element in this poset
* @return The poset formed by all elements smaller than p
*/
public Order_old<V> lessThan(V p){
HashSet<V> subElements = new HashSet<V>();
// for each relation, if the larger (second) is p then add the
// smaller (first) to subElements
for (Key<V, V> pair : trans){
if (pair.getSecond().equals(p) && !pair.getFirst().equals(p))
subElements.add(pair.getFirst());
}
return restriction(subElements);
}
/**
* @param p An element in this poset
* @return The set of all elements smaller than p
*/
public HashSet<V> lessThanSet(V p){
HashSet<V> subElements = new HashSet<V>();
// for each relation, if the larger (second) is p then add the
// smaller (first) to subElements
for (Key<V, V> pair : trans){
if (pair.getSecond().equals(p) && !pair.getFirst().equals(p))
subElements.add(pair.getFirst());
}
return subElements;
}
/**
* @param p An element in this poset
* @return The poset formed by all elements larger than p
*/
public Order_old<V> greaterThan(V p){
HashSet<V> subElements = new HashSet<V>();
// for each relation, if the smaller (first) is p then add the
// larger (second) to subElements
for (Key<V, V> pair : trans){
if (pair.getFirst().equals(p) && !pair.getSecond().equals(p))
subElements.add(pair.getSecond());
}
return restriction(subElements);
}
/**
* @param p An element in this order
* @return The set of all elements larger than p
*/
public HashSet<V> greaterThanSet(V p){
HashSet<V> subElements = new HashSet<V>();
// for each relation, if the smaller (first) is p then add the
// larger (second) to subElements
for (Key<V, V> pair : trans){
if (pair.getFirst().equals(p) && !pair.getSecond().equals(p))
subElements.add(pair.getSecond());
}
return subElements;
}
/**
* @param t A given top bound
* @param b A given bottom bound
* @return A new poset with t and b added to the top and bottom
* respectively, only if they don't already exist in the poset
*/
public Order_old<V> bound(V t, V b){
HashSet<V> newElements = new HashSet<V>();
newElements.addAll(elements);
if (!elements.contains(t) && !elements.contains(b)){
newElements.add(t);
newElements.add(b);
} else if (!elements.contains(t) && elements.contains(b)){
newElements.add(t);
} else if (elements.contains(t) && !elements.contains(b)){
newElements.add(b);
}
HashSet<Key<V, V>> newRelations = new HashSet<Key<V, V>>();
newRelations.addAll(trans);
newRelations.add(new Key<V, V>(b, t));
newRelations.add(new Key<V, V>(b, b));
newRelations.add(new Key<V, V>(t, t));
for (V e : elements){
newRelations.add(new Key<V, V>(b, e));
newRelations.add(new Key<V, V>(e, t));
}
return new Order_old<V>(newElements, newRelations);
}
/* * * * * * * * * * * * * * * *
* STANDARD INTERVAL RANK *
* * * * * * * * * * * * * * * */
/**
* @return The standard interval rank for all elements of this poset
*/
public HashMap<V, Interval> stdIntRank(){
if (stdIntRanks != null){
return stdIntRanks;
} else {
HashMap<V, Interval> sirs = new HashMap<V, Interval>();
int n = elements.size(); System.out.print(n+": ");
int i=0;
for (V p : elements){
sirs.put(p, stdIntRank(p));
System.out.print(i+", ");
i++;
}System.out.println();
return sirs;
}
}
/**
* @param p An element of this poset
* @return The standard interval rank of this poset element. This is
* given by the integer inerval:
* [height(up(p)) - 1, height(this) - height(down(p))]
*/
public Interval stdIntRank(V p){
int H = height();
Order_old<V> pUp = up(p);
Order_old<V> pDn = down(p);
int r_lower_star = pUp.height()-1;
int r_upper_star = H-pDn.height();
return new Interval(r_lower_star, r_upper_star);
}
public Preorder<V> copyToPreorder(){
Preorder<V> pre = new Preorder<V>(new HashSet<V>(elements), new HashSet<Key<V, V>>(trans), false);
if (!pre.checkPreorderRules())
return null;
else
return pre;
}
public Poset_old2<V> copyToPoset(){
Poset_old2<V> po = new Poset_old2<V>(new HashSet<V>(elements), new HashSet<Key<V, V>>(trans), false);
if (!po.checkPosetRules())
return null;
else
return po;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString(){
String out = "";
out += "["+elements.toString()+", ";
out += trans.toString()+"]";
return out;
}
}
| 24.758497 | 103 | 0.614884 |
e36c5875bbc4df30189dcf2c205b1b6c1f3f594b | 1,438 | package com.example;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@SpringBootApplication
// @EnableSwagger2
public class ReactSpringbootApplication {
@Value("${origins.urls}")
private String originsUrls;
@Value("${origins.allowed.methods}")
private String allowedMethods;
@Value("${max.age.seconds}")
private long maxAgeSeconds;
@Value("${api.mapping.url}")
private String apiMappingUrl;
public static void main(String[] args) {
SpringApplication.run(ReactSpringbootApplication.class, args);
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
// registry.addMapping("/**")
registry.addMapping(apiMappingUrl)
.maxAge(maxAgeSeconds)
.allowedMethods(allowedMethods.split(","))
.allowedOrigins(originsUrls.split(","));
}
};
}
// @Bean
// public Docket api() {
// return new Docket(DocumentationType.SWAGGER_2)
// .select()
// .apis((Predicate<RequestHandler>)
// RequestHandlerSelectors.basePackage("com.example.demospringboot"))
// .build();
// }
}
| 27.132075 | 74 | 0.757302 |
c1f43c5d1c705206cc1b2edd4502be1bb352ecb7 | 3,431 | package seedu.address.model.person;
import static java.util.Objects.requireNonNull;
import static seedu.address.commons.util.CollectionUtil.requireAllNonNull;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
public class Duration {
public static final String MESSAGE_CONSTRAINTS_FORMAT =
"Duration has to be of the following format: HHmm-HHmm e.g. 1600-1800";
public static final String MESSAGE_CONSTRAINTS_ORDER =
"Start time has to be before end time";
public static final String VALIDATION_REGEX = "^(([0-1][0-9])|2[0-3])[0-5][0-9]-(([0-1][0-9])|2[0-3])[0-5][0-9]$";
private final LocalTime startTime;
private final LocalTime endTime;
/**
* Constructs a Duration object with a start and end time.
* @param startTime The start time.
* @param endTime The end time.
*/
public Duration(LocalTime startTime, LocalTime endTime) {
requireAllNonNull(startTime, endTime);
this.startTime = startTime;
this.endTime = endTime;
}
public LocalTime getStartTime() {
return startTime;
}
public LocalTime getEndTime() {
return endTime;
}
public static boolean isValidDuration(String test) {
return test.matches(VALIDATION_REGEX);
}
public static boolean isValidDuration(LocalTime startTime, LocalTime endTime) {
return startTime.isBefore(endTime);
}
/**
* Returns true if this duration is the same as the other duration.
* @param otherDuration The other duration to be checked.
* @return true if this duration is the same as the other duration.
*/
public boolean isSameDuration(Duration otherDuration) {
if (otherDuration == this) {
return true;
}
return otherDuration != null
&& otherDuration.getStartTime().equals(startTime)
&& otherDuration.getEndTime().equals(endTime);
}
/**
* Returns true if this duration has overlapping duration as the other duration.
* @param otherDuration The other duration to be checked.
* @return true if this duration has overlapping duration as the other duration.
*/
public boolean hasOverlapDuration(Duration otherDuration) {
requireNonNull(otherDuration);
LocalTime otherStartTime = otherDuration.getStartTime();
LocalTime otherEndTime = otherDuration.getEndTime();
boolean hasSameStartTime = startTime.equals(otherStartTime);
boolean hasSameEndTime = endTime.equals(otherEndTime);
boolean isStartTimeOverlap = startTime.isAfter(otherStartTime) && startTime.isBefore(otherEndTime);
boolean isEndTimeOverlap = endTime.isAfter(otherStartTime) && endTime.isBefore(otherEndTime);
boolean isCompletelyOverlap = startTime.isBefore(otherStartTime) && endTime.isAfter(otherEndTime);
return hasSameStartTime || hasSameEndTime || isStartTimeOverlap || isEndTimeOverlap || isCompletelyOverlap;
}
@Override
public int hashCode() {
// use this method for custom fields hashing instead of implementing your own
return Objects.hash(startTime, endTime);
}
@Override
public String toString() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HHmm");
return startTime.format(formatter) + "-" + endTime.format(formatter);
}
}
| 35.371134 | 118 | 0.688429 |
871607da1e0d7f63a0f47ac744ed76d946658a7e | 6,245 | import javax.swing.*;
import java.awt.*;
import java.awt.Color;
import java.awt.event.*;
import java.awt.image.BufferedImage;
/**
* Created by Rak Alexey on 4/3/17.
*/
public class Application extends JFrame{
private ImagePanel panel;
private double textAngle;
private int textDeep;
private String text ="Sample Text!";
private Color textColor=Color.YELLOW;
private double lightAngle;
private Application(){
super("Task1");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
BufferedImage textImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
panel=new ImagePanel(textImage);
add(panel);
JSlider rot=new JSlider(0,360);
rot.addChangeListener(e-> {
textAngle=Math.toRadians(rot.getValue());
applyInput();
});
JSlider deep=new JSlider(0,50);
deep.addChangeListener(e -> {
textDeep=deep.getValue();
applyInput();
});
JTextField tex=new JTextField(text);
tex.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e){
process();
}
void process(){
text=tex.getText();
applyInput();
}
});
JSlider lit=new JSlider(0,360);
lit.addChangeListener(e -> {
lightAngle=lit.getValue();
applyInput();
});
JButton col=new JButton("Color");
col.addActionListener(e -> {
Color temp = JColorChooser.showDialog(null,"Choose Color", textColor);
if (temp != null) {
textColor = temp;
}
applyInput();
});
tex.getKeyListeners()[0].keyReleased(null);
rot.getChangeListeners()[0].stateChanged(null);
lit.getChangeListeners()[0].stateChanged(null);
deep.getChangeListeners()[0].stateChanged(null);
applyInput();
JPanel toolsPanel= new JPanel(new GridLayout(2,2));
toolsPanel.add(new JLabel("Rotation"));
toolsPanel.add(new JLabel("Deep"));
toolsPanel.add(new JLabel("Text"));
toolsPanel.add(new JLabel("Color"));
toolsPanel.add(new JLabel("Light"));
toolsPanel.add(rot);
toolsPanel.add(deep);
toolsPanel.add(tex);
toolsPanel.add(col);
toolsPanel.add(lit);
add(toolsPanel,BorderLayout.SOUTH);
}
private void applyInput(){
panel.setImage(makeVolume());
}
static private BufferedImage writeText(Color color,String text,int size,double angle){
BufferedImage textImage=new BufferedImage(size*4+size * text.length(), size *2,BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D g=textImage.createGraphics();
g.setColor(color);
g.setFont(new Font("Arial",Font.BOLD, size));
g.drawString(text,2, size);
g.dispose();
applyFrame(textImage,color,angle);
return textImage;
}
private BufferedImage makeVolume(){
int SIZE = 50;
Image textImage=writeText(textColor,text, SIZE,lightAngle);
int size=textImage.getHeight(null);
BufferedImage img=new BufferedImage(textImage.getWidth(null),size*2,BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D g=img.createGraphics();
for(int i=0;i<textDeep;i++)
g.drawImage(textImage,size+(int)Math.round(i*Math.cos(textAngle)),size+(int)Math.round(i*Math.sin(textAngle)),null);
g.dispose();
return img;
}
static private void applyFrame(BufferedImage img,Color color,double angle){
int [][] pix=convertTo2DUsingGetRGB(img);
int mainCol=color.getRGB();
int darkCol=color.darker().darker().getRGB();
int brightCol=color.brighter().brighter().getRGB();
int topCol=mixColor(brightCol,darkCol,getPercentage(0,angle)*2);
int rightCol=mixColor(brightCol,darkCol,getPercentage(90,angle)*2);
int botCol=mixColor(brightCol,darkCol,getPercentage(180,angle)*2);
int leftCol=mixColor(brightCol,darkCol,getPercentage(270,angle)*2);
for(int i=1;i<pix[0].length-1;i++){
for(int j=1;j<pix.length-1;j++)
if(pix[j][i]==0){
if(pix[j][i-1]==mainCol) img.setRGB(i,j,leftCol);
if(pix[j][i+1]==mainCol) img.setRGB(i,j,rightCol);
if(pix[j-1][i]==mainCol) img.setRGB(i,j,topCol);
if(pix[j+1][i]==mainCol) img.setRGB(i,j,botCol);
}
}
}
private static double getPercentage(double a, double b){
if(a<b){
return (b-a)/360;
}
return (a-b)/360;
}
private static int mixColor(int aa, int bb, double percent){
Color x=new Color(aa);
Color y=new Color(bb);
int r=(int)Math.round(x.getRed()*percent+y.getRed()*(1-percent))/2;
int g=(int)Math.round(x.getGreen()*percent+y.getGreen()*(1-percent))/2;
int b=(int)Math.round(x.getBlue()*percent+y.getBlue()*(1-percent))/2;
return new Color(r,g,b).getRGB();
}
private static int[][] convertTo2DUsingGetRGB(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
int[][] result = new int[height][width];
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
result[row][col] = image.getRGB(col, row);
}
}
return result;
}
static private class ImagePanel extends JPanel{
private Image img;
ImagePanel(Image img){
setImage(img);
}
void setImage(Image img){
this.img=img;
setPreferredSize(new Dimension(img.getWidth(null),img.getHeight(null)));
this.repaint();
}
@Override
public void paint(Graphics g) {
super.paint(g);
g.drawImage(img,0,0,null);
}
}
public static void main(String[] args){
Application app = new Application();
app.setSize(800,600);
app.setLocationRelativeTo(null);
app.setVisible(true);
}
}
| 34.502762 | 128 | 0.582546 |
113b84145847f2598e25b1d48e0cc8b8d8b33d73 | 2,060 | package com.springessentialsbook.chapter5.service.impl;
import com.springessentialsbook.chapter5.service.BusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import java.util.Collection;
/**
* Created by hamid on 09/01/16.
*/
@Service
public class BusinessServiceImpl implements BusinessService {
@Autowired
UserDetailsService userDetailsService;
@PreAuthorize("hasRole('ADMIN') or hasRole('ACCOUNTANT')")
public void migrateUsers() {
//migrate user implementation
System.out.println("migrateUsers>>>>>>");
}
public Object loadUserData(String username) {
//load User Data implementation
System.out.println("loadUserData>>>>>>");
return new Object();
}
public boolean isEligibleToSeeUserData(String loggedinUserName, String username) {
UserDetails loggedinUserDetails=userDetailsService.loadUserByUsername(loggedinUserName);
return hasAdminRole() || loggedinUserDetails.getUsername().equalsIgnoreCase(username);
}
private boolean hasAdminRole( ) {
boolean hasAdminRole=false;
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
final Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
for (final GrantedAuthority grantedAuthority : authorities) {
if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
hasAdminRole=true;
break;
}
}
return hasAdminRole;
}
}
| 33.770492 | 96 | 0.739806 |
3c69dc20c98db1be9b7840937dd027f424b628b3 | 1,071 | /**
* @fileName: BinarySearch.java
* @author: Akhash Ramamurthy
* @CreatedOn: Jun 23, 2019
*
*/
package com.akh.algorithms.leetcode.easy.lc704;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
/**
* @fileName: BinarySearch.java
* @author: Akhash Ramamurthy
* @Created on: Jun 23, 2019
*
*/
public class BinarySearch {
public int search(int[] nums, int target) {
return binarySearch(nums, target, 0, nums.length-1);
}
private int binarySearch(int[] nums, int target, int left, int right) {
if (left > right) {
return -1;
}
int mid = (left+right)/2;
if (nums[mid] == target) {
return mid;
} else if(target < nums[mid]) {
return binarySearch(nums, target, left, mid-1);
} else {
return binarySearch(nums, target, mid+1, right);
}
}
@Test
public void Test_101() {
int[] nums = {-1,0,3,5,9,12};
int expected = 4;
assertEquals(expected, search(nums, 9));
}
@Test
public void Test_102() {
int[] nums = {-1,0,3,5,9,12};
int expected = -1;
assertEquals(expected, search(nums, 2));
}
}
| 19.472727 | 72 | 0.637722 |
6320afbba8a47049ad9b668573e2fca0a3639698 | 161 | package controller.util;
public interface IPSeekerMessage {
String bad_ip_file = "IP库文件错误";
String unknown_country = "未知国家";
String unknown_area = "未知地区";
}
| 20.125 | 34 | 0.757764 |
12594b21e4b1f39de77cac0e606fa87f169821d9 | 2,952 | package com.bytezone.dm3270.replyfield;
// -----------------------------------------------------------------------------------//
public class Highlight extends QueryReplyField
// -----------------------------------------------------------------------------------//
{
private static final String[] values =
{ "Normal", "Blink", "Reverse video", "", "Underscore", "", "", "", "Intensity" };
final static byte HIGHLIGHT_DEFAULT = 0x00;
final static byte HIGHLIGHT_NORMAL = (byte) 0xF0;
final static byte HIGHLIGHT_BLINK = (byte) 0xF1;
final static byte HIGHLIGHT_REVERSE = (byte) 0xF2;
final static byte HIGHLIGHT_UNDERSCORE = (byte) 0xF4;
final static byte HIGHLIGHT_INTENSIFY = (byte) 0xF8;
int pairs;
byte[] attributeValue;
byte[] action;
// ---------------------------------------------------------------------------------//
public Highlight ()
// ---------------------------------------------------------------------------------//
{
super (HIGHLIGHT_QUERY_REPLY);
int ptr = createReply (11); // 5 pairs x 2 plus 1
reply[ptr++] = 0x05; //Number of attribute-value/action pairs
// Byte 1: Data stream attribute
// Byte 2: Data stream action
reply[ptr++] = HIGHLIGHT_DEFAULT;
reply[ptr++] = HIGHLIGHT_NORMAL;
reply[ptr++] = HIGHLIGHT_BLINK;
reply[ptr++] = HIGHLIGHT_BLINK;
reply[ptr++] = HIGHLIGHT_REVERSE;
reply[ptr++] = HIGHLIGHT_REVERSE;
reply[ptr++] = HIGHLIGHT_UNDERSCORE;
reply[ptr++] = HIGHLIGHT_UNDERSCORE;
reply[ptr++] = HIGHLIGHT_INTENSIFY;
reply[ptr++] = HIGHLIGHT_INTENSIFY;
checkDataLength (ptr);
}
// ---------------------------------------------------------------------------------//
public Highlight (byte[] buffer)
// ---------------------------------------------------------------------------------//
{
super (buffer);
assert data[1] == HIGHLIGHT_QUERY_REPLY;
pairs = data[2] & 0xFF;
attributeValue = new byte[pairs];
action = new byte[pairs];
for (int i = 0; i < pairs; i++)
{
attributeValue[i] = data[i * 2 + 3];
action[i] = data[i * 2 + 4];
}
}
// ---------------------------------------------------------------------------------//
@Override
public String toString ()
// ---------------------------------------------------------------------------------//
{
StringBuilder text = new StringBuilder (super.toString ());
text.append (String.format ("%n pairs : %d", pairs));
for (int i = 0; i < pairs; i++)
{
int av = attributeValue[i];
String attrText = av == 0 ? "Default" : values[av & 0x0F];
String actionText = values[action[i] & 0x0F];
String out =
attrText.equals (actionText) ? attrText : attrText + " -> " + actionText;
text.append (String.format ("%n val/actn : %02X/%02X - %s", attributeValue[i],
action[i], out));
}
return text.toString ();
}
} | 32.086957 | 88 | 0.469512 |
c3cbf42fffd49c28f7d74d44d4fdcdcbc0032873 | 122 | @Presentation
package fr.ubordeaux.ddd.examples.presentation;
import fr.ubordeaux.ddd.annotations.packages.Presentation;
| 24.4 | 58 | 0.852459 |
f8d2cb6deef995289fbec1fe7b67024238ab6dec | 3,398 | /*
* Seldon -- open source prediction engine
* =======================================
* Copyright 2011-2015 Seldon Technologies Ltd and Rummble Ltd (http://www.seldon.io/)
*
**********************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************************
*/
package io.seldon.client.beans;
import org.springframework.stereotype.Component;
/**
* @author claudio
*/
@Component
public class UserTrustNodeBean extends ResourceBean {
private static final long serialVersionUID = 4624650364320075874L;
private String user;
private double trust;
private long pos;
private Long dimension;
public UserTrustNodeBean() {
}
public UserTrustNodeBean(String user, double trust,long pos, Long dimension) {
this.user = user;
this.trust = trust;
this.pos = pos;
this.dimension = dimension;
}
public Long getDimension() {
return dimension;
}
public void setDimension(Long dimension) {
this.dimension = dimension;
}
public double getTrust() {
return trust;
}
public void setTrust(double trust) {
this.trust = trust;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public long getPos() {
return pos;
}
public void setPos(long pos) {
this.pos = pos;
}
public int compareTo(UserTrustNodeBean o) {
if(this.trust == o.trust)
return this.user.compareTo(o.user);
else if(this.trust > o.trust)
return -1;
else
return 1;
}
@Override
public String toString() {
return "UserTrustNodeBean{" +
"user='" + user + '\'' +
", trust=" + trust +
", pos=" + pos +
", dimension=" + dimension +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof UserTrustNodeBean)) return false;
UserTrustNodeBean that = (UserTrustNodeBean) o;
if (pos != that.pos) return false;
if (Double.compare(that.trust, trust) != 0) return false;
if (dimension != null ? !dimension.equals(that.dimension) : that.dimension != null) return false;
if (user != null ? !user.equals(that.user) : that.user != null) return false;
return true;
}
@Override
public int hashCode() {
int result;
long temp;
result = user != null ? user.hashCode() : 0;
temp = trust != +0.0d ? Double.doubleToLongBits(trust) : 0L;
result = 31 * result + (int) (temp ^ (temp >>> 32));
result = 31 * result + (int) (pos ^ (pos >>> 32));
result = 31 * result + (dimension != null ? dimension.hashCode() : 0);
return result;
}
}
| 26.341085 | 105 | 0.581813 |
648755107ecb205431be7d194434ada82dc49b8a | 1,158 | package com.qiuzhongrun.classloader.initial.first.active.use.test3A;
import com.qiuzhongrun.classloader.initial.first.active.use.Test;
/**
* 3. static access
* A field get(getstatic)
*/
public class Tester implements Test {
/**
* only test one line at the same time for different cases
* @param args
*/
public static void main(String[] args) {
//System.out.println(Son.slogan); //case 1
//System.out.println(Son.finalSlogan); //case 2
System.out.println(Son.finalRuntimeSlogan); //case 3
}
/**
* case 1 output:
* 儿子上线!
* 儿子的口号永远是:打钱!
*
* case 2 output:
* 儿子的口号永远是:打钱!
*
* case 3 output:
* 儿子上线!
* 儿子的口号运行时是:打钱!fc463a30-94f4-4a3c-9eb4-fe42b6f65742
*
* ? why case 2 not initialize Son.class
* case Son.finalSlogan is modified with <em>final<em/>
* it means Son.finalSlogan's value will be set in the constant pool of which Class invoked it(here is Tester.class)
* so it doesn't need to do the Son.class's initialization
*
* ? why case 3 with <em>final<em/> still need to do initialization
*/
}
| 28.95 | 120 | 0.626079 |
3fbf9a6ee85b39d5288812fa467e1e2a1966e65f | 8,234 | package org.firstinspires.ftc.team11047.custommodules;
import com.acmerobotics.dashboard.config.Config;
import com.qualcomm.hardware.modernrobotics.ModernRoboticsI2cGyro;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorSimple;
@Config
public abstract class Chassis extends LinearOpMode {
public Wheel lf, lb, rf, rb;
public ModernRoboticsI2cGyro gyro;
public static double max_accelerate = 80,
terminate_power = 0,
code_per_inch_right = 55,
code_per_inch_forward = 42.6,
turn_weight = 10,
trace_kp = 0.2,
turn_k = 1.06825;
public static int buffer_size = 2;
private double last_refresh_time, loop_time = 0;
public double current_x, current_y, current_direction, target_x, target_y, target_direction;
private int last_direction;
public void initChassis() {
lf = new Wheel(hardwareMap.dcMotor.get("lf"), DcMotor.Direction.REVERSE);
lb = new Wheel(hardwareMap.dcMotor.get("lb"), DcMotor.Direction.REVERSE);
rf = new Wheel(hardwareMap.dcMotor.get("rf"), DcMotor.Direction.FORWARD);
rb = new Wheel(hardwareMap.dcMotor.get("rb"), DcMotor.Direction.FORWARD);
gyro = hardwareMap.get(ModernRoboticsI2cGyro.class, "gyro");
gyro.calibrate();
last_direction = gyro.getHeading();
last_refresh_time = getRuntime();
while (!gyro.isCalibrating()) idle();
}
public void drive(double right_speed, double forward_speed, double turn_speed, double speed) {
double forwardLeft_Power = right_speed + forward_speed - turn_speed;
double rearLeft_Power = -right_speed + forward_speed - turn_speed;
double forwardRight_Power = -right_speed + forward_speed + turn_speed;
double rearRight_Power = right_speed + forward_speed + turn_speed;
if (speed > 1)
speed = 1;
else if (speed < 0)
speed = 0;
double k;
if (forwardLeft_Power == 0 && forwardRight_Power == 0 && rearLeft_Power == 0 && rearRight_Power == 0)
k = 0;
else
k = speed / Math.max(Math.abs(forwardLeft_Power),
Math.max(Math.abs(rearLeft_Power),
Math.max(Math.abs(forwardRight_Power),
Math.abs(rearRight_Power))));
lf.setPower(forwardLeft_Power * k);
lb.setPower(rearLeft_Power * k);
rf.setPower(forwardRight_Power * k);
rb.setPower(rearRight_Power * k);
}
public void move(double x_Speed, double y_Speed, double turnSpeed, double speed) {
double rightSpeed = x_Speed * Math.cos(current_direction) + y_Speed * Math.sin(current_direction);
double forwardSpeed = -x_Speed * Math.sin(current_direction) + y_Speed * Math.cos(current_direction);
drive(rightSpeed, forwardSpeed, turnSpeed, speed);
}
public interface Period {
void execute();
}
public void move_to(double target_X, double target_Y, double target_Direction, double maxSpeed) {
move_to(target_X, target_Y, target_Direction, maxSpeed, 0, null);
}
public void move_to(double target_X, double target_Y, double target_Direction, double maxSpeed, double quit, Period period) {
double total_X = target_X - current_x;
double total_Y = target_Y - current_y;
double total_Direction = target_Direction - current_direction;
double distance = Math.sqrt(total_X * total_X + total_Y * total_Y + total_Direction * total_Direction * turn_weight * turn_weight);
double startTime = getRuntime();
double totalTime = Math.min(Math.sqrt(distance / max_accelerate / 2), distance / maxSpeed / 2) * Math.PI;
double incomplete_Rate = 0;
double error = distance;
if (period == null)
period = () -> {
};
while (opModeIsActive()
&& (getRuntime() - startTime) < totalTime + 1
&& (incomplete_Rate != 0 || error > quit)) {
period.execute();
incomplete_Rate = (getRuntime() - startTime) <= totalTime ? (Math.cos(Math.PI * (getRuntime() - startTime) / totalTime) + 1) / 2 : 0;
this.target_x = target_X - total_X * incomplete_Rate;
this.target_y = target_Y - total_Y * incomplete_Rate;
this.target_direction = target_Direction - total_Direction * incomplete_Rate;
double error_X = this.target_x - current_x;
double error_Y = this.target_y - current_y;
double error_direction = this.target_direction - current_direction;
error_direction *= turn_weight;
error = Math.sqrt(error_X * error_X + error_Y * error_Y + error_direction * error_direction);
move(error_X, error_Y / code_per_inch_forward * code_per_inch_right, error_direction,
MyMath.distanceToPower(error) * trace_kp);
}
lf.setPower(0);
lb.setPower(0);
rf.setPower(0);
rb.setPower(0);
}
public void resetPosition(double x, double y, double direction) {
current_x = x;
current_y = y;
current_direction = direction;
}
public void refreshPosition() {
loop_time = getRuntime() - last_refresh_time;
last_refresh_time = getRuntime();
lf.refresh();
lb.refresh();
rf.refresh();
rb.refresh();
int now_direction = gyro.getHeading();
double d_right = (lf.getSpeed() - lb.getSpeed() - rf.getSpeed() + rb.getSpeed()) / 4 * loop_time / code_per_inch_right;
double d_forward = (lf.getSpeed() + lb.getSpeed() + rf.getSpeed() + rb.getSpeed()) / 4 * loop_time / code_per_inch_forward;
double d_turn = now_direction - last_direction;
if (d_turn < -180)
d_turn += 360;
else if (d_turn > 180)
d_turn -= 360;
d_turn *= turn_k;
last_direction = now_direction;
current_x += d_right * Math.cos(current_direction) - d_forward * Math.sin(current_direction);
current_y += d_right * Math.sin(current_direction) + d_forward * Math.cos(current_direction);
current_direction += Math.toRadians(d_turn);
telemetry.addData("currentX", current_x);
telemetry.addData("currentY", current_y);
telemetry.addData("currentDirection", current_direction);
telemetry.addData("targetX", target_x);
telemetry.addData("targetY", target_y);
telemetry.addData("targetDirection", target_direction);
}
public class Wheel {
private final DcMotor wheel;
private double currentSpeed, previousSpeed;
private final int[] position = new int[buffer_size];
private int index = -1;
public Wheel(DcMotor wheel, DcMotorSimple.Direction direction) {
this.wheel = wheel;
wheel.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
wheel.setDirection(direction);
wheel.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
wheel.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
reset();
}
public void reset() {
last_refresh_time = getRuntime();
int temp = wheel.getCurrentPosition();
for (int i = 0; i < buffer_size; ++i)
position[i] = temp;
currentSpeed = previousSpeed = 0;
}
public void refresh() {
index = (index + 1) % buffer_size;
position[index] = wheel.getCurrentPosition();
previousSpeed = currentSpeed;
currentSpeed = (position[index] - position[(index + 1) % buffer_size]) / loop_time / (buffer_size - 1);
}
public void setPower(double power) {
wheel.setPower(Math.abs(power) <= terminate_power ? 0 : power);
}
public int getPosition() {
return position[index];
}
public double getSpeed() {
return currentSpeed;
}
public double getAcceleration() {
return (currentSpeed - previousSpeed) / loop_time;
}
}
}
| 43.109948 | 145 | 0.628735 |
f4f03e01d53b1fd5c577e5b9c22a7475c76ea9b3 | 8,833 | /*
* Copyright 2010 Hippo.
*
* 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.onehippo.forge.jcrshell;
import static org.junit.Assert.assertEquals;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import javax.xml.parsers.ParserConfigurationException;
import org.junit.Test;
import org.onehippo.forge.jcrshell.export.XmlFormatter;
import org.xml.sax.SAXException;
public class XmlFormatterTest {
private String readFileAsString(File file) throws IOException {
StringBuffer fileData = new StringBuffer();
BufferedReader reader = new BufferedReader(new FileReader(file));
char[] buf = new char[1024];
int numRead = 0;
while ((numRead = reader.read(buf)) != -1) {
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
}
reader.close();
return fileData.toString();
}
@Test
public void onlySystemViewNamespaceIsDeclared() throws IOException, ParserConfigurationException, SAXException {
assertFormat(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<sv:node xmlns:sv=\"jcr-sv-namespace\" sv:name=\"aap\">\n" +
" <sv:property sv:name=\"mies\">\n" +
" <sv:value>bla</sv:value>\n"+
" </sv:property>\n" +
"</sv:node>\n",
"<?xml version=\"1.0\"?>"+
"<sv:node xmlns:sv=\"jcr-sv-namespace\" xmlns:bla=\"die\" sv:name=\"aap\">"+
"<sv:property sv:name=\"mies\">"+
"<sv:value>bla</sv:value>"+
"</sv:property>"+
"</sv:node>");
}
private void assertFormat(String expected, String input) throws IOException, ParserConfigurationException, SAXException {
File inputFile = createTempFile("formatter-input", input);
File output = createTempFile("formatter-out");
assertFormat(expected, inputFile, output);
inputFile.delete();
output.delete();
}
private File createTempFile(String name) throws IOException {
File file = File.createTempFile(name, ".test");
file.delete();
return file;
}
private void assertFormat(String expected, File inputFile, File output) throws IOException, ParserConfigurationException, SAXException {
XmlFormatter.format(inputFile, output);
String content = readFileAsString(output);
assertEquals(expected, content);
}
private File createTempFile(String name, String content) throws IOException {
File file = File.createTempFile(name, ".test");
{
PrintStream ps = new PrintStream(new FileOutputStream(file));
ps.print(content);
ps.close();
}
return file;
}
@Test
public void testFormatterWithStructure() throws IOException, ParserConfigurationException, SAXException {
assertFormat(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<!-- header -->\n"+
"<sv:node xmlns:sv=\"jcr-sv-namespace\" sv:name=\"aap\">\n" +
" <!-- hoepla -->\n"+
" <sv:property sv:name=\"mies\">\n" +
" <sv:value>bla</sv:value>\n"+
" </sv:property>\n" +
"</sv:node>\n",
"<?xml version=\"1.0\"?>" +
"<sv:node xmlns:sv=\"jcr-sv-namespace\" xmlns:bla=\"die\" sv:name=\"aap\">" +
"<sv:property sv:name=\"mies\">" +
"<sv:value>bla</sv:value>" +
"</sv:property>"+
"</sv:node>",
"<?xml version=\"1.0\"?>\n" +
"<!-- header -->\n" +
"<sv:node xmlns:sv=\"jcr-sv-namespace\" xmlns:bla=\"die\" sv:name=\"aap\">" +
" <!-- hoepla -->\n" +
" <sv:property sv:name=\"mies\">" +
" <sv:value>noot</sv:value>" +
" </sv:property>" +
"</sv:node>");
}
private void assertFormat(String expected, String input, String old) throws IOException, ParserConfigurationException, SAXException {
File inputFile = createTempFile("formatter-input", input);
File output = createTempFile("formatter-out", old);
assertFormat(expected, inputFile, output);
inputFile.delete();
output.delete();
}
@Test
public void testWhitespaceInHeader() throws IOException, ParserConfigurationException, SAXException {
assertFormat(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<!-- header \n" +
"-->\n"+
"<sv:node xmlns:sv=\"jcr-sv-namespace\" sv:name=\"aap\">\n" +
" <!-- hoepla -->\n"+
" <sv:property sv:name=\"mies\">\n" +
" <sv:value>bla</sv:value>\n"+
" </sv:property>\n" +
"</sv:node>\n",
"<?xml version=\"1.0\"?>" +
"<sv:node xmlns:sv=\"jcr-sv-namespace\" xmlns:bla=\"die\" sv:name=\"aap\">" +
"<sv:property sv:name=\"mies\">" +
"<sv:value>bla</sv:value>" +
"</sv:property>"+
"</sv:node>",
"<?xml version=\"1.0\"?>\n" +
"<!-- header \n" +
"-->\n" +
"<sv:node xmlns:sv=\"jcr-sv-namespace\" xmlns:bla=\"die\" sv:name=\"aap\">" +
" <!-- hoepla -->\n" +
" <sv:property sv:name=\"mies\">" +
" <sv:value>noot</sv:value>" +
" </sv:property>" +
"</sv:node>");
}
@Test
public void testWhitespaceInComment() throws IOException, ParserConfigurationException, SAXException {
assertFormat(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<!-- header -->\n"+
"<sv:node xmlns:sv=\"jcr-sv-namespace\" sv:name=\"aap\">\n" +
" <!-- hoepla\n" +
"-->\n"+
" <sv:property sv:name=\"mies\">\n" +
" <sv:value>bla</sv:value>\n"+
" </sv:property>\n" +
"</sv:node>\n",
"<?xml version=\"1.0\"?>" +
"<sv:node xmlns:sv=\"jcr-sv-namespace\" xmlns:bla=\"die\" sv:name=\"aap\">" +
"<sv:property sv:name=\"mies\">" +
"<sv:value>bla</sv:value>" +
"</sv:property>"+
"</sv:node>",
"<?xml version=\"1.0\"?>\n" +
"<!-- header -->\n" +
"<sv:node xmlns:sv=\"jcr-sv-namespace\" xmlns:bla=\"die\" sv:name=\"aap\">" +
" <!-- hoepla\n" +
"-->\n" +
" <sv:property sv:name=\"mies\">" +
" <sv:value>noot</sv:value>" +
" </sv:property>" +
"</sv:node>");
}
@Test
public void testEntitiesEscaped() throws IOException, ParserConfigurationException, SAXException {
assertFormat(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<sv:node xmlns:sv=\"jcr-sv-namespace\" sv:name=\"aap\">\n" +
" <sv:property sv:name=\"mies\">\n" +
" <sv:value>a & b > c</sv:value>\n"+
" </sv:property>\n" +
"</sv:node>\n",
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<sv:node xmlns:sv=\"jcr-sv-namespace\" sv:name=\"aap\">" +
"<sv:property sv:name=\"mies\">" +
"<sv:value>a & b > c</sv:value>" +
"</sv:property>"+
"</sv:node>\n");
}
@Test
public void whiteSpaceInInputIsIgnored() throws IOException, ParserConfigurationException, SAXException {
assertFormat(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<sv:node xmlns:sv=\"jcr-sv-namespace\" sv:name=\"aap\">\n" +
" <sv:property sv:name=\"mies\">\n" +
" <sv:value>bla</sv:value>\n"+
" </sv:property>\n" +
"</sv:node>\n",
"<?xml version=\"1.0\"?>\n"+
"<sv:node xmlns:sv=\"jcr-sv-namespace\" sv:name=\"aap\">\n"+
" <sv:property sv:name=\"mies\">\n"+
" <sv:value>bla</sv:value>\n"+
" </sv:property>\n"+
"</sv:node>");
}
}
| 37.427966 | 140 | 0.518284 |
44f7b5eb6690c42a8122afd29a8a0188a9ee110b | 13,405 | package com.yilian.mall.ui;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.leshan.ylyj.view.activity.bankmodel.SetUpCashCardsActivity;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.orhanobut.logger.Logger;
import com.yilian.mall.BaseActivity;
import com.yilian.mall.R;
import com.yilian.mall.entity.CashSuccessModel;
import com.yilian.mall.retrofitutil.RetrofitUtils;
import com.yilian.mall.utils.NumberFormat;
import com.yilian.mylibrary.CheckServiceReturnEntityUtil;
import com.yilian.mylibrary.CodeException;
import com.yilian.mylibrary.Constants;
import com.yilian.mylibrary.GlideUtil;
import com.yilian.networkingmodule.entity.TakeCashEntity2;
import com.yilian.networkingmodule.retrofitutil.RetrofitUtils3;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import static com.leshan.ylyj.view.activity.bankmodel.SetUpCashCardsActivity.RESULT_SET_BANK_OK;
/**
* Created by Ray_L_Pain on 2017/7/7 0007.
*/
public class JTakeCashActivity extends BaseActivity {
public static final int CHECK_BANK_CARD_REQUEST_CODE = 22;
@ViewInject(R.id.v3Back)
ImageView v3Back;
@ViewInject(R.id.v3Left)
ImageView v3Left;
@ViewInject(R.id.v3Title)
TextView v3Title;
@ViewInject(R.id.tv_right)
TextView tv_right;
@ViewInject(R.id.v3Shop)
ImageView v3Shop;
@ViewInject(R.id.layout_card)
RelativeLayout layout_card;
@ViewInject(R.id.layout_no_card)
LinearLayout layout_no_card;
@ViewInject(R.id.layout_has_card)
LinearLayout layout_has_card;
@ViewInject(R.id.iv_has_card)
ImageView iv_has_card;
@ViewInject(R.id.tv1_has_card)
TextView tv1_has_card;
@ViewInject(R.id.tv2_has_card)
TextView tv2_has_card;
@ViewInject(R.id.tv_all_money)
TextView tv_all_money;
@ViewInject(R.id.tv_take_money)
TextView tv_take_money;
@ViewInject(R.id.btn_take)
Button btn_take;
@ViewInject(R.id.et)
EditText etInputMoney;
@ViewInject(R.id.tv_explain_first)
TextView tvExplainFirst;
@ViewInject(R.id.tv_explain_four)
TextView tvExplainFour;
@ViewInject(R.id.tv_explain_five)
TextView tvExplainFive;
@ViewInject(R.id.tv_explain_six)
TextView tvExplainSix;
private int all_money;
private String money;
private int status;
private String card_index;
private String bankId, card_holder, card_bank, branch_bank, pro_id, city_id, county_id, pro_name, city_name, county_name, card_number;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_take_cash);
ViewUtils.inject(this);
initView();
}
@Override
protected void onResume() {
super.onResume();
if (isLogin()) {
initData();
} else {
finish();
}
}
private void initView() {
btn_take.setClickable(false);
v3Back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
v3Left.setVisibility(View.INVISIBLE);
v3Title.setText("使用奖励");
v3Shop.setVisibility(View.GONE);
tv_right.setVisibility(View.VISIBLE);
tv_right.setText("使用奖励记录");
tv_right.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mContext, BalanceDetailActivity.class);
intent.putExtra("type", "2");
startActivity(intent);
}
});
layout_card.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startCheckBankCardActivity();
}
});
tv_take_money.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
etInputMoney.setText(money);
if (!TextUtils.isEmpty(money)) {
etInputMoney.setSelection(money.length());
}
}
});
btn_take.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
takeCash();
}
});
etInputMoney.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (etInputMoney.getText().toString().length() >= 3 && Integer.parseInt(etInputMoney.getText().toString()) % 100 == 0) {
Logger.i("输入金额满足提现");
btn_take.setBackgroundResource(R.drawable.bg_solid_red_90);
btn_take.setClickable(true);
} else {
Logger.i("输入金额 不满足提现");
btn_take.setBackgroundResource(R.drawable.bg_solid_red50_90);
btn_take.setClickable(false);
}
}
});
etInputMoney.requestFocus();
tvExplainFirst.setText(Html.fromHtml("<font color=\"#999999\">1.每次奖励金额 </font><font color=\"#fe5062\">≥100.00 " +
"</font><font color=\"#999999\">,领取金额必须是 </font><font color=\"#fe5062\">100 </font><font color=\"#999999\">的整数倍。 </font>"));
tvExplainFour.setText(Html.fromHtml("<font color=\"#999999\">1.工作日领奖励, </font><font color=\"#fe5062\">T+1 </font><font color=\"#999999\">到银行卡上。 </font>"));
tvExplainFive.setText(Html.fromHtml("<font color=\"#999999\">2.节假日领奖励,顺延节假日后第 </font><font color=\"#fe5062\">2 </font><font color=\"#999999\">个工作日到账。 </font>"));
tvExplainSix.setText(Html.fromHtml("<font color=\"#999999\">3.如有疑问,请拨打 </font><font color=\"#00bef7\">400-152-5159 </font><font color=\"#999999\">进行咨询。 </font>"));
tvExplainSix.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "400-152-5159"));
startActivity(intent);
}
});
}
/**
* 新版获取默认提现银行卡
*/
private void getTakeCashDefaultBankCard() {
startMyDialog(false);
Subscription subscription = RetrofitUtils3.getRetrofitService(mContext)
.getTakeCashDefaultCard("userBank/my_default_bank")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<TakeCashEntity2>() {
@Override
public void onCompleted() {
stopMyDialog();
}
@Override
public void onError(Throwable e) {
stopMyDialog();
if (e instanceof CodeException) {
if (0 == ((CodeException) e).code) {
// 暂无银行卡
showToast("请先绑定银行卡");
showNoCardDialog();
} else {
showToast(e.getMessage());
}
} else {
showToast(e.getMessage());
}
}
@Override
public void onNext(TakeCashEntity2 takeCashEntity2) {
showHasCard();
TakeCashEntity2.InfoBean cardInfo = takeCashEntity2.info;
GlideUtil.showImageNoSuffix(mContext, cardInfo.bankLogo, iv_has_card);
tv1_has_card.setText(cardInfo.cardTypeCn);
tv2_has_card.setText(cardInfo.cardBank + "尾号" + cardInfo.cardNumber);
all_money = NumberFormat.convertToInt(takeCashEntity2.availableCash, 0);
money = String.valueOf(all_money / 100);
tv_all_money.setText(all_money / 100 + "");
card_index = cardInfo.cardIndex;
}
});
addSubscription(subscription);
}
private void startCheckBankCardActivity() {
startActivityForResult(new Intent(mContext, SetUpCashCardsActivity.class), CHECK_BANK_CARD_REQUEST_CODE);
}
private void initData() {
getTakeCashDefaultBankCard();
}
private void showHasCard() {
layout_no_card.setVisibility(View.GONE);
layout_has_card.setVisibility(View.VISIBLE);
}
private void takeCash() {
String cash = etInputMoney.getText().toString().trim();
if (TextUtils.isEmpty(cash)) {
showToast(R.string.please_write_number);
return;
}
if (Integer.parseInt(cash) > all_money || Integer.parseInt(cash) == 0) {
showToast(R.string.cash_not_enough);
return;
}
if (Integer.parseInt(cash) % 100 != 0) {
showToast(R.string.cash_not_100);
return;
}
startMyDialog();
try {
RetrofitUtils.getInstance(mContext).setContext(mContext).takeCash(cash, card_index, new Callback<CashSuccessModel>() {
@Override
public void onResponse(Call<CashSuccessModel> call, Response<CashSuccessModel> response) {
if (CheckServiceReturnEntityUtil.checkServiceReturnEntity(mContext, response.body())) {
stopMyDialog();
switch (response.body().code) {
case 1:
sp.edit().putBoolean(Constants.REFRESH_USER_FRAGMENT, true).commit();
Intent intent = new Intent(mContext, JTakeCashSuccessActivity.class);
intent.putExtra("card_name", response.body().cardBank);
intent.putExtra("card_num", response.body().cardNumber);
intent.putExtra("card_time", response.body().time);
intent.putExtra("card_money", response.body().cashAmount);
startActivityForResult(intent, Constants.TAKE_CASH_SUCCESS);
break;
case -17:
startCheckBankCardActivity();
break;
default:
showToast(response.body().msg);
break;
}
}
}
@Override
public void onFailure(Call<CashSuccessModel> call, Throwable t) {
stopMyDialog();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Constants.TAKE_CASH_SUCCESS && resultCode == RESULT_OK) {
setResult(RESULT_OK);
finish();
} else if (requestCode == CHECK_BANK_CARD_REQUEST_CODE && resultCode == RESULT_SET_BANK_OK) {
getTakeCashDefaultBankCard();
}
}
private void showNoCardDialog() {
AlertDialog builder = new AlertDialog.Builder(this).create();
builder.setTitle("温馨提示");
builder.setMessage("您尚未绑定银行卡,是否现在绑定?");
builder.setButton(DialogInterface.BUTTON_NEGATIVE, "否", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
builder.setButton(DialogInterface.BUTTON_POSITIVE, "是", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startCheckBankCardActivity();
dialog.dismiss();
}
});
builder.show();
builder.getButton(DialogInterface.BUTTON_POSITIVE).setTextColor(mContext.getResources().getColor(R.color.color_red));
builder.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(mContext.getResources().getColor(R.color.color_333));
}
}
| 38.631124 | 171 | 0.589109 |
5d14e17d83ed27a30d2e9cd497fc3fade1ac3f98 | 1,377 | /*
* Copyright 2009-2014 Jose Luis Martin.
*
* 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.jdal.dao;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* Support class for {@link Dao} implementation.
*
* @author Jose Luis Martin
* @since 2.0
*
*/
public abstract class DaoSupport<T, PK extends Serializable> implements Dao<T, PK> {
/**
* {@inheritDoc}
*/
public void delete(Collection<T> collection) {
for (T t : collection) {
delete(t);
}
}
/**
* {@inheritDoc}
*/
public Collection<T> save(Collection<T> collection) {
List<T> saved = new ArrayList<T>();
for (T t : collection) {
saved.add(save(t));
}
return saved;
}
/**
* {@inheritDoc}
*/
public void deleteById(Collection<PK> ids) {
for (PK id : ids)
deleteById(id);
}
}
| 21.515625 | 85 | 0.67756 |
c3d8c2bccce602da772fb82cf58aba25df2b65e6 | 1,338 | package com.midi_automator.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.log4j.Logger;
/**
* Runs a command in the OS shell
*
* @author aguelle
*
*/
public class ShellRunner extends Thread {
static Logger log = Logger.getLogger(ShellRunner.class.getName());
private String[] cmd;
private String output;
/**
* Constructor
*
* @param cmd
* command to run
*/
public ShellRunner(String[] cmd) {
this.cmd = cmd;
}
/**
* Gets the output from the shell. BE AWARE: This blocks the calling thread
* until the shell command was finished.
*
* @return the output
*/
public String getOutput() {
while (isAlive()) {
// Do nothing
}
return this.output;
}
@Override
public void run() {
StringBuffer output = new StringBuffer();
try {
Process p = Runtime.getRuntime().exec(cmd);
p.getOutputStream().close();
BufferedReader reader = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
} catch (IOException e) {
log.error("Reading shell output failed", e);
}
this.output = output.toString();
}
}
| 19.391304 | 77 | 0.621824 |
73271fb69d0713366a0aab3f7ab8000901eee0ea | 19,190 | package ru.nanolive.draconicplus.common.fusioncrafting.client.render.tile;
import java.util.Random;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.ItemRenderer;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.client.renderer.entity.RenderItem;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.renderer.texture.TextureUtil;
import net.minecraft.crash.CrashReport;
import net.minecraft.crash.CrashReportCategory;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemCloth;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ReportedException;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.ForgeHooksClient;
public class RenderUtils {
protected static void bindTexture(ResourceLocation p_110776_1_)
{
Minecraft.getMinecraft().renderEngine.bindTexture(p_110776_1_);
}
public static Render getEntityClassRenderObject(Class p_78715_1_)
{
Render render = (Render)RenderManager.instance.entityRenderMap.get(p_78715_1_);
if (render == null && p_78715_1_ != Entity.class)
{
render = RenderUtils.getEntityClassRenderObject(p_78715_1_.getSuperclass());
RenderManager.instance.entityRenderMap.put(p_78715_1_, render);
}
return render;
}
public static Render getEntityRenderObject(Entity p_78713_1_)
{
return RenderUtils.getEntityClassRenderObject(p_78713_1_.getClass());
}
private static void renderEntityOnFire(Entity p_76977_1_, double p_76977_2_, double p_76977_4_, double p_76977_6_, float p_76977_8_)
{
GL11.glDisable(GL11.GL_LIGHTING);
IIcon iicon = Blocks.fire.getFireIcon(0);
IIcon iicon1 = Blocks.fire.getFireIcon(1);
GL11.glPushMatrix();
GL11.glTranslatef((float)p_76977_2_, (float)p_76977_4_, (float)p_76977_6_);
float f1 = p_76977_1_.width * 1.4F;
GL11.glScalef(f1, f1, f1);
Tessellator tessellator = Tessellator.instance;
float f2 = 0.5F;
float f3 = 0.0F;
float f4 = p_76977_1_.height / f1;
float f5 = (float)(p_76977_1_.posY - p_76977_1_.boundingBox.minY);
GL11.glRotatef(-RenderManager.instance.playerViewY, 0.0F, 1.0F, 0.0F);
GL11.glTranslatef(0.0F, 0.0F, -0.3F + (float)((int)f4) * 0.02F);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
float f6 = 0.0F;
int i = 0;
tessellator.startDrawingQuads();
while (f4 > 0.0F)
{
IIcon iicon2 = i % 2 == 0 ? iicon : iicon1;
RenderUtils.bindTexture(TextureMap.locationBlocksTexture);
float f7 = iicon2.getMinU();
float f8 = iicon2.getMinV();
float f9 = iicon2.getMaxU();
float f10 = iicon2.getMaxV();
if (i / 2 % 2 == 0)
{
float f11 = f9;
f9 = f7;
f7 = f11;
}
tessellator.addVertexWithUV((double)(f2 - f3), (double)(0.0F - f5), (double)f6, (double)f9, (double)f10);
tessellator.addVertexWithUV((double)(-f2 - f3), (double)(0.0F - f5), (double)f6, (double)f7, (double)f10);
tessellator.addVertexWithUV((double)(-f2 - f3), (double)(1.4F - f5), (double)f6, (double)f7, (double)f8);
tessellator.addVertexWithUV((double)(f2 - f3), (double)(1.4F - f5), (double)f6, (double)f9, (double)f8);
f4 -= 0.45F;
f5 -= 0.45F;
f2 *= 0.9F;
f6 += 0.03F;
++i;
}
tessellator.draw();
GL11.glPopMatrix();
GL11.glEnable(GL11.GL_LIGHTING);
}
public static void doRenderShadowAndFire(Entity p_76979_1_, double p_76979_2_, double p_76979_4_, double p_76979_6_, float p_76979_8_, float p_76979_9_)
{
if (RenderManager.instance.getEntityRenderObject(p_76979_1_).renderManager.options.fancyGraphics && RenderManager.instance.getEntityRenderObject(p_76979_1_).shadowSize > 0.0F && !p_76979_1_.isInvisible())
{
double d3 = RenderManager.instance.getEntityRenderObject(p_76979_1_).renderManager.getDistanceToCamera(p_76979_1_.posX, p_76979_1_.posY, p_76979_1_.posZ);
float f2 = (float)((1.0D - d3 / 256.0D) * (double)RenderManager.instance.getEntityRenderObject(p_76979_1_).shadowOpaque);
if (f2 > 0.0F)
{
RenderManager.instance.getEntityRenderObject(p_76979_1_).renderShadow(p_76979_1_, p_76979_2_, p_76979_4_, p_76979_6_, f2, p_76979_9_);
}
}
if (p_76979_1_.canRenderOnFire())
{
RenderUtils.renderEntityOnFire(p_76979_1_, p_76979_2_, p_76979_4_, p_76979_6_, p_76979_9_);
}
}
public static boolean renderItem(Entity p_147939_1_, double p_147939_2_, double p_147939_4_, double p_147939_6_, float p_147939_8_, float p_147939_9_, boolean p_147939_10_, byte facing)
{
Render render = null;
try
{
render = RenderUtils.getEntityRenderObject(p_147939_1_);
if (render != null && RenderManager.instance.renderEngine != null)
{
if (!render.isStaticEntity() || p_147939_10_)
{
try
{
RenderUtils.doRender((EntityItem) p_147939_1_, p_147939_2_, p_147939_4_, p_147939_6_, p_147939_8_, p_147939_9_, facing);
}
catch (Throwable throwable2)
{
throw new ReportedException(CrashReport.makeCrashReport(throwable2, "Rendering entity in world"));
}
try
{
doRenderShadowAndFire(p_147939_1_, p_147939_2_, p_147939_4_, p_147939_6_, p_147939_8_, p_147939_9_);
}
catch (Throwable throwable1)
{
throw new ReportedException(CrashReport.makeCrashReport(throwable1, "Post-rendering entity in world"));
}
}
}
else if (RenderManager.instance.renderEngine != null)
{
return false;
}
return true;
}
catch (Throwable throwable3)
{
CrashReport crashreport = CrashReport.makeCrashReport(throwable3, "Rendering entity in world");
CrashReportCategory crashreportcategory = crashreport.makeCategory("Entity being rendered");
p_147939_1_.addEntityCrashInfo(crashreportcategory);
CrashReportCategory crashreportcategory1 = crashreport.makeCategory("Renderer details");
crashreportcategory1.addCrashSection("Assigned renderer", render);
crashreportcategory1.addCrashSection("Location", CrashReportCategory.func_85074_a(p_147939_2_, p_147939_4_, p_147939_6_));
crashreportcategory1.addCrashSection("Rotation", Float.valueOf(p_147939_8_));
crashreportcategory1.addCrashSection("Delta", Float.valueOf(p_147939_9_));
throw new ReportedException(crashreport);
}
}
public static void doRender(EntityItem p_76986_1_, double p_76986_2_, double p_76986_4_, double p_76986_6_, float p_76986_8_, float p_76986_9_, byte facing)
{
ItemStack itemstack = p_76986_1_.getEntityItem();
if (itemstack.getItem() != null)
{
RenderUtils.bindEntityTexture(p_76986_1_);
TextureUtil.func_152777_a(false, false, 1.0F);
RenderUtils.random.setSeed(187L);
GL11.glPushMatrix();
float f2 = shouldBob() ? MathHelper.sin(((float)p_76986_1_.age + p_76986_9_) / 10.0F + p_76986_1_.hoverStart) * 0.1F + 0.1F : 0F;
float f3 = (((float)p_76986_1_.age + p_76986_9_) / 20.0F + p_76986_1_.hoverStart) * (180F / (float)Math.PI);
byte b0 = 1;
if (p_76986_1_.getEntityItem().stackSize > 1)
{
b0 = 2;
}
if (p_76986_1_.getEntityItem().stackSize > 5)
{
b0 = 3;
}
if (p_76986_1_.getEntityItem().stackSize > 20)
{
b0 = 4;
}
if (p_76986_1_.getEntityItem().stackSize > 40)
{
b0 = 5;
}
b0 = getMiniBlockCount(itemstack, b0);
GL11.glTranslatef((float)p_76986_2_, (float)p_76986_4_ + f2, (float)p_76986_6_);
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
float f6;
float f7;
int k;
if (ForgeHooksClient.renderEntityItem(p_76986_1_, itemstack, f2, f3, random, Minecraft.getMinecraft().renderEngine, RenderManager.instance.getEntityRenderObject(p_76986_1_).field_147909_c, b0))
{
;
}
else // Code Style break here to prevent the patch from editing RenderUtils line
if (itemstack.getItemSpriteNumber() == 0 && itemstack.getItem() instanceof ItemBlock && RenderBlocks.renderItemIn3d(Block.getBlockFromItem(itemstack.getItem()).getRenderType()))
{
Block block = Block.getBlockFromItem(itemstack.getItem());
GL11.glRotatef(f3, 0.0F, 1.0F, 0.0F);
if (RenderItem.renderInFrame)
{
GL11.glScalef(1.25F, 1.25F, 1.25F);
GL11.glTranslatef(0.0F, 0.05F, 0.0F);
GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F);
}
float f9 = 0.25F;
k = block.getRenderType();
if (k == 1 || k == 19 || k == 12 || k == 2)
{
f9 = 0.5F;
}
if (block.getRenderBlockPass() > 0)
{
GL11.glAlphaFunc(GL11.GL_GREATER, 0.1F);
GL11.glEnable(GL11.GL_BLEND);
OpenGlHelper.glBlendFunc(770, 771, 1, 0);
}
GL11.glScalef(f9, f9, f9);
for (int l = 0; l < b0; ++l)
{
GL11.glPushMatrix();
if (l > 0)
{
f6 = (RenderUtils.random.nextFloat() * 2.0F - 1.0F) * 0.2F / f9;
f7 = (RenderUtils.random.nextFloat() * 2.0F - 1.0F) * 0.2F / f9;
float f8 = (RenderUtils.random.nextFloat() * 2.0F - 1.0F) * 0.2F / f9;
GL11.glTranslatef(f6, f7, f8);
}
((RenderItem)RenderManager.instance.getEntityRenderObject(p_76986_1_)).renderBlocksRi.renderBlockAsItem(block, itemstack.getItemDamage(), 1.0F);
GL11.glPopMatrix();
}
if (block.getRenderBlockPass() > 0)
{
GL11.glDisable(GL11.GL_BLEND);
}
}
else
{
float f5;
if (itemstack.getItem().requiresMultipleRenderPasses())
{
if (RenderItem.renderInFrame)
{
GL11.glScalef(0.5128205F, 0.5128205F, 0.5128205F);
GL11.glTranslatef(0.0F, -0.05F, 0.0F);
}
else
{
GL11.glScalef(0.5F, 0.5F, 0.5F);
}
for (int j = 0; j < itemstack.getItem().getRenderPasses(itemstack.getItemDamage()); ++j)
{
RenderUtils.random.setSeed(187L);
IIcon iicon1 = itemstack.getItem().getIcon(itemstack, j);
if (((RenderItem)RenderManager.instance.getEntityRenderObject(p_76986_1_)).renderWithColor)
{
k = itemstack.getItem().getColorFromItemStack(itemstack, j);
f5 = (float)(k >> 16 & 255) / 255.0F;
f6 = (float)(k >> 8 & 255) / 255.0F;
f7 = (float)(k & 255) / 255.0F;
GL11.glColor4f(f5, f6, f7, 1.0F);
RenderUtils.renderDroppedItem(p_76986_1_, iicon1, b0, p_76986_9_, f5, f6, f7, j, facing);
}
else
{
RenderUtils.renderDroppedItem(p_76986_1_, iicon1, b0, p_76986_9_, 1.0F, 1.0F, 1.0F, j, facing);
}
}
}
else
{
if (itemstack != null && itemstack.getItem() instanceof ItemCloth)
{
GL11.glAlphaFunc(GL11.GL_GREATER, 0.1F);
GL11.glEnable(GL11.GL_BLEND);
OpenGlHelper.glBlendFunc(770, 771, 1, 0);
}
if (RenderItem.renderInFrame)
{
GL11.glScalef(0.5128205F, 0.5128205F, 0.5128205F);
GL11.glTranslatef(0.0F, -0.05F, 0.0F);
}
else
{
GL11.glScalef(0.5F, 0.5F, 0.5F);
}
IIcon iicon = itemstack.getIconIndex();
if (((RenderItem)RenderManager.instance.getEntityRenderObject(p_76986_1_)).renderWithColor)
{
int i = itemstack.getItem().getColorFromItemStack(itemstack, 0);
float f4 = (float)(i >> 16 & 255) / 255.0F;
f5 = (float)(i >> 8 & 255) / 255.0F;
f6 = (float)(i & 255) / 255.0F;
RenderUtils.renderDroppedItem(p_76986_1_, iicon, b0, p_76986_9_, f4, f5, f6, facing);
}
else
{
RenderUtils.renderDroppedItem(p_76986_1_, iicon, b0, p_76986_9_, 1.0F, 1.0F, 1.0F, facing);
}
if (itemstack != null && itemstack.getItem() instanceof ItemCloth)
{
GL11.glDisable(GL11.GL_BLEND);
}
}
}
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
GL11.glPopMatrix();
RenderUtils.bindEntityTexture(p_76986_1_);
TextureUtil.func_147945_b();
}
}
protected static void bindEntityTexture(Entity p_110777_1_)
{
RenderUtils.bindTexture(RenderUtils.getEntityTexture((EntityItem) p_110777_1_));
}
/**
* Returns the location of an entity's texture. Doesn't seem to be called unless you call Render.bindEntityTexture.
*/
protected static ResourceLocation getEntityTexture(EntityItem p_110775_1_)
{
return Minecraft.getMinecraft().renderEngine.getResourceLocation(p_110775_1_.getEntityItem().getItemSpriteNumber());
}
/**
* Renders a dropped item
*/
private static void renderDroppedItem(EntityItem p_77020_1_, IIcon p_77020_2_, int p_77020_3_, float p_77020_4_, float p_77020_5_, float p_77020_6_, float p_77020_7_, byte facing)
{
RenderUtils.renderDroppedItem(p_77020_1_, p_77020_2_, p_77020_3_, p_77020_4_, p_77020_5_, p_77020_6_, p_77020_7_, 0, facing);
}
private static Random random = new Random();
private static final ResourceLocation RES_ITEM_GLINT = new ResourceLocation("textures/misc/enchanted_item_glint.png");
private static void renderDroppedItem(EntityItem p_77020_1_, IIcon p_77020_2_, int p_77020_3_, float p_77020_4_, float p_77020_5_, float p_77020_6_, float p_77020_7_, int pass, byte facing)
{
Tessellator tessellator = Tessellator.instance;
if (p_77020_2_ == null)
{
TextureManager texturemanager = Minecraft.getMinecraft().getTextureManager();
ResourceLocation resourcelocation = texturemanager.getResourceLocation(p_77020_1_.getEntityItem().getItemSpriteNumber());
p_77020_2_ = ((TextureMap)texturemanager.getTexture(resourcelocation)).getAtlasSprite("missingno");
}
float f14 = ((IIcon)p_77020_2_).getMinU();
float f15 = ((IIcon)p_77020_2_).getMaxU();
float f4 = ((IIcon)p_77020_2_).getMinV();
float f5 = ((IIcon)p_77020_2_).getMaxV();
float f6 = 1.0F;
float f7 = 0.5F;
float f8 = 0.25F;
float f10;
GL11.glPushMatrix();
if (RenderItem.renderInFrame)
{
GL11.glRotatef(180.0F, 0.0F, 1.0F, 0.0F);
}
else
{
GL11.glRotatef((((float)p_77020_1_.age + p_77020_4_) / 20.0F + p_77020_1_.hoverStart) * (180F / (float)Math.PI), 0.0F, 1.0F, 0.0F);
}
float f9 = 0.0625F;
f10 = 0.021875F;
ItemStack itemstack = p_77020_1_.getEntityItem();
int j = itemstack.stackSize;
byte b0;
if (j < 2)
{
b0 = 1;
}
else if (j < 16)
{
b0 = 2;
}
else if (j < 32)
{
b0 = 3;
}
else
{
b0 = 4;
}
b0 = getMiniItemCount(itemstack, b0);
GL11.glTranslatef(-f7, -f8, -((f9 + f10) * (float)b0 / 2.0F));
for (int k = 0; k < b0; ++k)
{
GL11.glTranslatef(0f, 0f, f9 + f10);
if (itemstack.getItemSpriteNumber() == 0)
{
bindTexture(TextureMap.locationBlocksTexture);
}
else
{
bindTexture(TextureMap.locationItemsTexture);
}
GL11.glColor4f(p_77020_5_, p_77020_6_, p_77020_7_, 1.0F);
ItemRenderer.renderItemIn2D(tessellator, f15, f4, f14, f5, ((IIcon)p_77020_2_).getIconWidth(), ((IIcon)p_77020_2_).getIconHeight(), f9);
}
GL11.glPopMatrix();
}
public static boolean shouldBob()
{
return false;
}
public static byte getMiniBlockCount(ItemStack stack, byte original)
{
return original;
}
public static byte getMiniItemCount(ItemStack stack, byte original)
{
return original;
}
public static boolean shouldSpreadItems()
{
return true;
}
}
| 39.243354 | 212 | 0.556071 |
824eee3b4ae5c16701cf2db42d3cc58dc80cee15 | 566 | package com.example.demo.tomcat;
/**
* @author admin
* @date 2018-9-21 10:00
*/
public abstract class MyServlet {
public abstract void doGet(MyRequest myRequest,MyResponse myResponse);
public abstract void doPost(MyRequest myRequest,MyResponse myResponse);
public void service(MyRequest myRequest,MyResponse myResponse){
if(myRequest.getMethod().equalsIgnoreCase("Post")){
doPost(myRequest,myResponse);
}else if(myRequest.getMethod().equalsIgnoreCase("GET")){
doGet(myRequest,myResponse);
}
}
}
| 28.3 | 75 | 0.690813 |
92d7fd421591f84fbd9fec4282102278b9c2e6fd | 6,367 | package com.webank.weevent.jms;
import java.nio.charset.StandardCharsets;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.Session;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import com.webank.weevent.client.ErrorCode;
import com.webank.weevent.client.WeEvent;
import lombok.extern.slf4j.Slf4j;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
@Slf4j
public class JMSTest {
private final String topicName = "com.weevent.test";
private final String defaultBrokerUrl = "http://localhost:7000/weevent-broker";
private TopicConnectionFactory connectionFactory;
private TopicConnection connection;
private WeEventTopicSession session;
private WeEventTopic topic;
private final long wait3s = 3000L;
@Rule
public TestName testName = new TestName();
@Before
public void before() throws Exception {
log.info("=============================={}.{}==============================",
this.getClass().getSimpleName(),
this.testName.getMethodName());
this.connectionFactory = new WeEventConnectionFactory(this.defaultBrokerUrl);
this.connection = this.connectionFactory.createTopicConnection();
this.session = (WeEventTopicSession) this.connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
this.topic = (WeEventTopic) this.session.createTopic(this.topicName);
}
@After
public void after() throws Exception {
this.connection.close();
}
/**
* test connect
*/
@Test
public void testConnection() throws JMSException {
Assert.assertNotNull(this.connection.getClientID());
}
/**
* test groupId is not exist
*/
@Test
public void testGroupIdIsNotExist() {
try {
this.connectionFactory = new WeEventConnectionFactory(this.defaultBrokerUrl, "0");
this.connection = this.connectionFactory.createTopicConnection();
this.session = (WeEventTopicSession) this.connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
this.topic = (WeEventTopic) this.session.createTopic(this.topicName);
Assert.fail();
} catch (JMSException e) {
Assert.assertEquals(String.valueOf(ErrorCode.WEB3SDK_UNKNOWN_GROUP.getCode()), e.getErrorCode());
}
}
/**
* test create connection with userName and password
*/
@Test
public void testConnectionWithUserNamePassword() throws JMSException {
this.connectionFactory = new WeEventConnectionFactory(this.defaultBrokerUrl, WeEvent.DEFAULT_GROUP_ID);
// userName:"", password:""
this.connection = this.connectionFactory.createTopicConnection("", "");
this.session = (WeEventTopicSession) this.connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
this.topic = (WeEventTopic) this.session.createTopic(this.topicName);
Assert.assertTrue(true);
}
/**
* test create topic
*/
@Test
public void testCreateTopic() throws JMSException {
WeEventTopic topic = (WeEventTopic) this.session.createTopic("aa");
Assert.assertNotNull(topic.getTopicName());
}
/**
* topic is blank
*/
@Test
public void testCreateTopicIsBlank() {
try {
this.session.createTopic("");
Assert.fail();
} catch (JMSException e) {
Assert.assertEquals(String.valueOf(ErrorCode.TOPIC_IS_BLANK.getCode()), e.getErrorCode());
}
}
/**
* topic length > 64
*/
@Test
public void testCreateTopicOverMaxLen() {
try {
this.session.createTopic("topiclengthlonger64asdfghjklpoiuytrewqazxswcdevfrbg-" + System.currentTimeMillis());
Assert.fail();
} catch (JMSException e) {
Assert.assertEquals(String.valueOf(ErrorCode.TOPIC_EXCEED_MAX_LENGTH.getCode()), e.getErrorCode());
}
}
/**
* test subscriber
*/
@Test
public void testSubscriber() throws JMSException {
WeEventTopicSubscriber subscriber = (WeEventTopicSubscriber) this.session.createSubscriber(this.topic);
subscriber.setMessageListener(message -> {
BytesMessage msg = (BytesMessage) message;
try {
byte[] data = new byte[(int) msg.getBodyLength()];
msg.readBytes(data);
System.out.println("received: " + new String(data, StandardCharsets.UTF_8));
Assert.assertTrue(true);
} catch (JMSException e) {
e.printStackTrace();
}
});
Assert.assertNotNull(subscriber.getSubscriptionId());
}
/**
* test publish
*/
@Test
public void testPublish() throws JMSException {
WeEventTopicPublisher publisher = (WeEventTopicPublisher) this.session.createPublisher(this.topic);
BytesMessage msg = session.createBytesMessage();
msg.writeBytes(("hello WeEvent").getBytes(StandardCharsets.UTF_8));
publisher.publish(msg);
Assert.assertTrue(true);
}
/**
* test both subscribe and publish
*/
@Test
public void testBothSubscribePublish() throws JMSException, InterruptedException {
WeEventTopicSubscriber subscriber = (WeEventTopicSubscriber) this.session.createSubscriber(this.topic);
subscriber.setMessageListener(message -> {
BytesMessage msg = (BytesMessage) message;
try {
byte[] data = new byte[(int) msg.getBodyLength()];
msg.readBytes(data);
System.out.println("received: " + new String(data, StandardCharsets.UTF_8));
} catch (JMSException e) {
e.printStackTrace();
}
});
Assert.assertNotNull(subscriber.getSubscriptionId());
WeEventTopicPublisher publisher = (WeEventTopicPublisher) this.session.createPublisher(this.topic);
BytesMessage msg = session.createBytesMessage();
msg.writeBytes(("hello WeEvent").getBytes(StandardCharsets.UTF_8));
publisher.publish(msg);
Thread.sleep(this.wait3s);
Assert.assertTrue(true);
}
}
| 34.231183 | 122 | 0.6485 |
4958cdb36f7a2f2bd05226c903cba61da821f0d0 | 6,982 | /*
* Copyright 2018 Information and Computational Sciences,
* The James Hutton Institute.
*
* 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 jhi.germinate.client.page.accession;
import com.google.gwt.user.client.ui.*;
import org.gwtbootstrap3.client.shared.event.*;
import org.gwtbootstrap3.client.ui.*;
import java.util.*;
import jhi.germinate.client.i18n.*;
import jhi.germinate.client.page.*;
import jhi.germinate.client.page.search.*;
import jhi.germinate.client.service.*;
import jhi.germinate.client.util.*;
import jhi.germinate.client.util.callback.*;
import jhi.germinate.client.util.parameterstore.*;
import jhi.germinate.client.widget.element.*;
import jhi.germinate.client.widget.structure.resource.*;
import jhi.germinate.shared.*;
import jhi.germinate.shared.datastructure.*;
import jhi.germinate.shared.datastructure.Pagination;
import jhi.germinate.shared.datastructure.database.*;
import jhi.germinate.shared.enums.*;
import jhi.germinate.shared.exception.*;
import jhi.germinate.shared.search.*;
import jhi.germinate.shared.search.operators.*;
/**
* @author Sebastian Raubach
* @see Parameter#accessionId
* @see Parameter#accessionName
*/
public class PassportPage extends GerminateComposite implements HasLibraries, HasHelp, HasHyperlinkButton, ParallaxBannerPage
{
private Accession accession;
private boolean isOsterei;
public PassportPage(boolean isOsterei)
{
this.isOsterei = isOsterei;
}
@Override
protected void setUpContent()
{
PageHeader pageHeader = new PageHeader();
pageHeader.setText(Text.LANG.passportPassportData());
HTML html = new HTML();
panel.add(pageHeader);
panel.add(html);
if (isOsterei)
{
panel.add(new OsterPassportWidget());
}
else
{
/* See if there is information about the selected accession */
Long stateAccessionId = LongParameterStore.Inst.get().get(Parameter.accessionId);
String stateGeneralId = StringParameterStore.Inst.get().get(Parameter.generalId);
String accessionName = StringParameterStore.Inst.get().get(Parameter.accessionName);
/* Remove these parameters as they are only used to get here */
StringParameterStore.Inst.get().remove(Parameter.generalId);
StringParameterStore.Inst.get().remove(Parameter.accessionName);
/*
* We prefer the generalId, since it's only used for hard links to
* Germinate. In this case we don't want to use internally stored
* accession ids, but rather use the external one
*/
PartialSearchQuery filter = null;
if (stateGeneralId != null)
filter = new PartialSearchQuery(new SearchCondition(Accession.GENERAL_IDENTIFIER, new Equal(), stateGeneralId, Long.class));
/* We also prefer the "default display name" as this is the new way of representing an accession during export to Flapjack etc. */
else if (!StringUtils.isEmpty(accessionName))
filter = new PartialSearchQuery(new SearchCondition(Accession.NAME, new Equal(), accessionName, String.class));
else if (stateAccessionId != null)
filter = new PartialSearchQuery(new SearchCondition(Accession.ID, new Equal(), Long.toString(stateAccessionId), Long.class));
if (filter != null)
{
AccessionService.Inst.get().getForFilter(Cookie.getRequestProperties(), Pagination.getDefault(), filter, new DefaultAsyncCallback<PaginatedServerResult<List<Accession>>>()
{
@Override
public void onFailureImpl(Throwable caught)
{
if (caught instanceof DatabaseException)
{
html.setText(Text.LANG.errorNoParameterAccession());
}
else
{
super.onFailureImpl(caught);
}
}
@Override
public void onSuccessImpl(PaginatedServerResult<List<Accession>> result)
{
if (result.hasData())
{
accession = result.getServerResult().get(0);
createContent();
}
}
});
}
else
{
html.setText(Text.LANG.errorNoParameterAccession());
}
}
}
private void createContent()
{
// We've got a parent entity, go and get their data
if (accession.getEntityParentId() != null)
{
List<String> ids = new ArrayList<>();
ids.add(Long.toString(accession.getEntityParentId()));
AccessionService.Inst.get().getByIds(Cookie.getRequestProperties(), Pagination.getDefault(), ids, new DefaultAsyncCallback<ServerResult<List<Accession>>>()
{
@Override
protected void onSuccessImpl(ServerResult<List<Accession>> result)
{
if (result.hasData())
{
createTwinPanel(result.getServerResult().get(0));
}
}
});
}
else
{
// Get the information for this entity
panel.add(new PassportWidget(accession));
}
}
private void createTwinPanel(Accession parent)
{
PanelGroup group = new PanelGroup();
group.setId("accordion");
panel.add(group);
// Add the current accession
final SearchSection section = new SearchSection();
section.setPreventHideSibling(true);
section.setHeading(accession.getEntityType().getName() + ": " + accession.getGeneralIdentifier());
section.setMdi(Style.combine(Style.MDI_LG, accession.getEntityType().getMdi()));
section.addShownHandler(new ShownHandler()
{
private boolean isInit = false;
@Override
public void onShown(ShownEvent shownEvent)
{
if (!isInit)
{
isInit = true;
section.add(new PassportWidget(accession));
}
}
});
group.add(section);
// Add the parent
final SearchSection parentSection = new SearchSection();
parentSection.setPreventHideSibling(true);
parentSection.setHeading(parent.getEntityType().getName() + ": " + parent.getGeneralIdentifier());
parentSection.setMdi(Style.combine(Style.MDI_LG, parent.getEntityType().getMdi()));
parentSection.addShownHandler(new ShownHandler()
{
private boolean isInit = false;
@Override
public void onShown(ShownEvent shownEvent)
{
if (!isInit)
{
isInit = true;
parentSection.add(new PassportWidget(parent));
}
}
});
group.add(parentSection);
}
@Override
public Widget getHelpContent()
{
return new HTML(Text.LANG.passportHelp());
}
@Override
public HyperlinkPopupOptions getHyperlinkOptions()
{
return new HyperlinkPopupOptions()
.setPage(Page.PASSPORT)
.addParam(Parameter.accessionId);
}
@Override
public Library[] getLibraries()
{
return new Library[]{Library.LEAFLET_COMPLETE};
}
@Override
public String getParallaxStyle()
{
return ParallaxResource.INSTANCE.css().parallaxPassport();
}
}
| 29.710638 | 175 | 0.721283 |
97b1c53e0c7f697aea946ddefe9a7f37dd4e8e1f | 900 | package com.wso2.choreo.integrationtests.contractrunner.respository;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
public class FileRepositoryImpl implements FileRepository {
private static final Logger logger = LogManager.getLogger(FileRepositoryImpl.class);
@Override
public String getFileContent(String filePath) {
var mainFile = new File(filePath);
try (InputStream inputStream = new FileInputStream(mainFile)) {
return IOUtils.toString(inputStream, StandardCharsets.UTF_8.name());
} catch (IOException e) {
logger.error("File not found: ".concat(filePath), e);
return null;
}
}
}
| 33.333333 | 88 | 0.732222 |
c2d27f77dfd75218f9b7e2457a8eb7cd4ad04ae4 | 717 | package edu.neu.cs5200.repository;
import edu.neu.cs5200.models.Customer;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
public interface CustomerRepository extends CrudRepository<Customer, Integer> {
@Query("SELECT c FROM Customer c WHERE c.username=:username")
Iterable<Customer> findCustomerByUsername(@Param("username") String username);
@Query("SELECT c FROM Customer c WHERE c.username=:username AND c.password=:password")
Iterable<Customer> findCustomerByCredentials(
@Param("username") String username,
@Param("password") String password);
}
| 37.736842 | 90 | 0.767085 |
3bbc2fe926766d0ea2b85d728e3c3c289563c632 | 2,375 | package org.forten.demo.bo;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.forten.demo.dao.JDBCDao;
import org.forten.demo.dto.BookForList;
import org.forten.demo.dto.BookForSave;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import static org.forten.demo.dao.JDBCDao.EMPTY_PARAMS;
/**
* 书籍的业务逻辑Bean
*
* @author duyi
*/
// 声明这是一个Spring的Bean,并设置这个Bean的ID是bookBo
@Service("bookBo")
public class BookBo {
// 把id是jdbcDao的Bean注入到这个Bean中
@Resource
private JDBCDao jdbcDao;
/**
* 保存书籍数据
*
* @param book
* 要保存的数据对象
*/
// 声明这个方法是一个事务
@Transactional
public void doSave(BookForSave book) {
// 使用命名参数的SQL语句
String sql = "INSERT INTO bb_book (name,author,type,price,discount,publish_date) VALUES (:name,:author,:type,:price,:discount,:pubDate)";
// 声明参数Map对象
Map<String, Object> params = new HashMap<>();
// 设置参数
params.put("name", book.getName());
params.put("author", book.getAuthor());
params.put("type", book.getType());
params.put("price", book.getPrice());
params.put("discount", book.getDiscount());
params.put("pubDate", book.getPubDate());
// 执行更新
jdbcDao.update(sql, params);
}
/**
* 查询所有数据
*
* @return 所有书籍数据
*/
// 声明这个方法是一个只读事务
@Transactional(readOnly = true)
public List<BookForList> queryAll() {
// SQL语句
String sql = "SELECT id,name,author,type,price,discount,publish_date FROM bb_book";
// 执行查询,因为语句中没有参数,所以使用EMPTY_PARAMS做为第二个参数
List<BookForList> list = jdbcDao.findList(sql, EMPTY_PARAMS, new RowMapper<BookForList>() {
// 数据结果集合到对象映射关系的建立
@Override
public BookForList mapRow(ResultSet rs, int rowNum) throws SQLException {
int id = rs.getInt("id");
String name = rs.getString("name");
String author = rs.getString("author");
String type = rs.getString("type");
int price = rs.getInt("price");
double discount = rs.getDouble("discount");
Date pubDate = rs.getDate("publish_date");
return new BookForList(id, name, author, type, price, discount, pubDate);
}
});
return list;
}
}
| 26.685393 | 140 | 0.682526 |
12c89227e5d45271f4b330a498535a9fbbbabe6b | 4,743 | package automation.library.common;
import com.google.gson.Gson;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.*;
import java.util.*;
public class JsonHelper {
static Logger log = LogManager.getLogger(JsonHelper.class);
/**
* Reads JSON file and returns a specific json object from that file based on the root element value
*/
public static JSONObject getJSONData(String filepath, String...key) {
try {
FileReader reader = new FileReader(filepath);
JSONTokener token = new JSONTokener(reader);
JSONObject json = (JSONObject) (key.length>0?new JSONObject(token).get(key[0]):new JSONObject(token));
return json;
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}
/**
* Reads JSON file and returns a specific json object from that file based on the root element value
*/
public static JSONArray getJSONArray(String filepath, String... key) {
try {
FileReader reader = new FileReader(filepath);
JSONTokener token = new JSONTokener(reader);
JSONArray json = (JSONArray) (key.length > 0 ? new JSONObject(token).get(key[0]) : new JSONArray(token));
return json;
} catch (FileNotFoundException e) {
log.error("file not found", e);
e.printStackTrace();
return null;
}
}
/**
* reads data from json files and casts to supplied pojo format
*/
public static <T> T getDataPOJO(String filepath, Class<T> clazz) throws IOException {
Gson gson = new Gson();
File file = new File(filepath);
T dataObj = null;
try {
BufferedReader br = new BufferedReader(new FileReader(file));
dataObj = gson.fromJson(br, clazz);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return dataObj;
}
/**
* reads data from json files and casts to supplied pojo format
*/
public static <T> T getData(String path, String dataGroup, Class<T> clazz) throws IOException {
String filePath=path+dataGroup+".json";
Gson gson = new Gson();
File file = new File(filePath);
T dataObj = null;
try {
BufferedReader br = new BufferedReader(new FileReader(file));
dataObj = gson.fromJson(br, clazz);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return dataObj;
}
/**
* Convert json object to map
* @param json input JSON object
* @return map
*/
public static Map<String, String> getJSONToMap(JSONObject json) {
Map<String, String> map = new HashMap<String, String>();
String[] keys = JSONObject.getNames(json);
for (String key : keys) {
map.put(key, json.get(key).toString());
}
return map;
}
/**
* Performs a recursive merge between 2 json objects.
* When the json includes an array then will loop through this as
* part of the recursive merge.
*/
public static JSONObject jsonMerge(JSONObject source, JSONObject target) {
String[] keys = JSONObject.getNames(source);
if (keys !=null){
for (String key: keys) {
Object value = source.get(key);
if (!target.has(key)) {
target.put(key, value);
} else if (value instanceof JSONArray) {
JSONArray array = (JSONArray) value;
JSONArray targetarray = (JSONArray) target.get(key);
for (int i=0;i<array.length();i++){
Object arrayvalue = array.get(i);
Object targetarrayvalue = targetarray.get(i);
if (arrayvalue instanceof JSONObject) {
JSONObject valueJson = (JSONObject)arrayvalue;
JSONObject targetvalueJson = (JSONObject)targetarrayvalue;
jsonMerge(valueJson, targetvalueJson);
}else {
target.put(key, value);
}
}
} else if (value instanceof JSONObject) {
JSONObject valueJson = (JSONObject)value;
jsonMerge(valueJson, target.getJSONObject(key));
} else {
target.put(key, value);
}
}
}
return target;
}
}
| 34.620438 | 117 | 0.563567 |
536498c6a9704ea5392d79529e6637d624f329fe | 660 | package com.mmall.concurrency.immutable;
import com.mmall.concurrency.annotations.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;
import com.google.common.collect.Maps;
import java.util.Map;
@Slf4j
@NotThreadSafe //非线程安全
public class ImmutableExample1 {
private final static Integer a = 1;
private final static String b = "2";
private final static Map<Integer, Integer> map = Maps.newHashMap();
static {
map.put(1, 2);
map.put(3, 4);
map.put(5, 6);
}
public static void main(String[] args) {
map.put(1, 3);
log.info("{}", map.get(1));
}
private void test(final int a) {
}
}
| 20.625 | 71 | 0.640909 |
fd01012a2faa030ea7b87d6dbb237feb6060011a | 11,047 | /*
Technology Exponent Common Utilities For Java (TECUJ)
Copyright (C) 2003,2004 Abdul Habra
www.tek271.com
This file is part of TECUJ.
TECUJ 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; version 2.
TECUJ 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 TECUJ; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
You can contact the author at [email protected]
*/
package com.tek271.util.exception;
import java.sql.*;
import java.io.*;
import java.util.*;
import com.tek271.util.xml.*;
import com.tek271.util.string.StringUtility;
import com.tek271.util.log.*;
import com.tek271.util.collections.list.*;
/**
Generic static methods to manage exceptions, including:<ol>
<li>Build consistent debug or error messages.</li>
<li>Log a debug, warning, or error message to an ILogger object.</li>
<li>Convert an exception stack trace to a string.</li>
<li>Print an exception's stack trace to console, an <code>OutputStream</code>, or a
<code>Writer</code> object. This is useful to print the stack
trace to a web page during development.</li>
</ol>
* <p>Copyright (c) 2003 Technology Exponent</p>
* @author Abdul Habra
* @version 1.0
* <p><b>History</b><ol>
* <li>2005.10.28: Added asList() </li>
* </ol></p>
*/
public class ExceptionUtil {
public static void main(String[] args) {
SQLException ex1= new SQLException("Abdul's test-A");
SQLException ex2= new SQLException("Abdul's test-B");
ex1.setNextException(ex2);
printSqlException(ex1);
}
private ExceptionUtil() {}
/** Print aEx and all its sub-exceptions to System.err */
public static void printSqlException(final SQLException aEx) {
printSqlException(aEx, System.err);
}
/** Print aEx and all its sub-exceptions to aStream */
public static void printSqlException(final SQLException aEx, final OutputStream aStream) {
PrintWriter pw = new PrintWriter(aStream);
printSqlExImpl(aEx, pw);
}
/** Print aEx and all its sub-exceptions to aWriter */
public static void printSqlException(final SQLException aEx, final Writer aWriter) {
PrintWriter pw = new PrintWriter(aWriter);
printSqlExImpl(aEx, pw);
} // printSQLException
/** Print aEx and all its sub-exceptions to aWriter. Implementation. */
private static void printSqlExImpl(SQLException aEx, PrintWriter aWriter) {
while (aEx != null) {
printExImpl(aEx, aWriter);
aEx = aEx.getNextException();
}
aWriter.flush();
} // printSqlExImpl
/**
* Print aException stack trace to aWriter. Will not flush.
* @param aException Its stack trace will be printed. If null, no action.
* @param aWriter The device to write to. If null, no action.
*/
private static void printExImpl(final Throwable aException,
final PrintWriter aWriter) {
if (aWriter==null) return;
if (aException==null) return;
aWriter.println(aException.getMessage());
aException.printStackTrace(aWriter);
} // printExImpl
/** Print aEx to aStream */
public static void printException(final Exception aEx, final OutputStream aStream) {
PrintWriter pw = new PrintWriter(aStream);
printExImpl(aEx, pw);
pw.flush();
} // printException
/** Print aEx to aWriter */
public static void printException(final Exception aEx, final Writer aWriter) {
PrintWriter pw = new PrintWriter(aWriter);
printExImpl(aEx, pw);
pw.flush();
} // printException
/** Print aEx to System.err */
public static void printException(final Exception aEx) {
printException(aEx, System.err);
}
public static void printThrowableList(final List aThrowableList, final Writer aWriter) {
PrintWriter pw = new PrintWriter(aWriter);
int count=1;
for(Iterator i=aThrowableList.iterator(); i.hasNext();) {
pw.println("-------- Exception #" + count++);
printExImpl( (Throwable) i.next(), pw);
}
pw.flush();
} // printThrowableList
/** Get the stacktrace as a string */
public static String asString(final Throwable aTh) {
if (aTh==null) return null;
StringWriter sw= new StringWriter(128);
PrintWriter pw = new PrintWriter(sw);
aTh.printStackTrace(pw);
pw.flush();
String r= sw.toString();
pw.close();
return r;
} // asString
/** Convert a list of Throwable objects into a string */
public static String asString(final List aThrowableList) {
if (aThrowableList==null) return null;
StringWriter sw= new StringWriter(128 * aThrowableList.size());
printThrowableList(aThrowableList, sw);
sw.flush();
String r= sw.toString();
try {
sw.close();
} catch (IOException ex) {
r= ex.toString() + StringUtility.NEW_LINE + r;
}
return r;
} // asString()
/** Append given throwable to a ListOfString */
public static void appendToList(final Throwable aTh, final ListOfString aList) {
String s= asString(aTh);
aList.setText(s);
}
/** Append given throwable list to a ListOfString */
public static void appendToList(final List aThrowableList, final ListOfString aList) {
String s= asString(aThrowableList);
aList.setText(s);
}
/** Convert given Throwable to a ListOfString */
public static ListOfString asList(final Throwable aTh) {
ListOfString r= new ListOfString();
appendToList(aTh, r);
return r;
}
/** Convert given Throwable list to a ListOfString */
public static ListOfString asList(final List aThrowableList) {
ListOfString r= new ListOfString();
appendToList(aThrowableList, r);
return r;
}
private static final String pMETHOD_END = "(): ";
private static String buildMsg(final String aClass,
final String aMethod,
final String aMsg,
final String aXml) {
StringBuffer buf= new StringBuffer(256);
// buf.append(aPrefix).append(' ');
buf.append(aClass).append('.').append(aMethod).append(pMETHOD_END);
buf.append(aMsg);
if (aXml!=null) {
buf.append(StringUtility.NEW_LINE);
XmlUtil.tagCData(buf, aXml, 4);
}
return buf.toString();
} // buildErrMsg
/** Build an error message from the given parameters. Put aXml in a CData section. */
public static String buildErrMsg(final String aClass,
final String aMethod,
final String aMsg,
final String aXml) {
return buildMsg(aClass, aMethod, aMsg, aXml);
} // buildErrMsg
/** Build an error message from the given parameters */
public static String buildErrMsg(final String aClass, final String aMethod, final String aMsg) {
return buildMsg(aClass, aMethod, aMsg, null);
} // buildErrMsg
/** Build a debug message from the given parameters. Put aXml in a CData section. */
public static String buildDebugMsg(final String aClass,
final String aMethod,
final String aMsg,
final String aXml) {
return buildMsg(aClass, aMethod, aMsg, aXml);
} // buildErrMsg
/** Build a debug message from the given parameters */
public static String buildDebugMsg(final String aClass, final String aMethod, final String aMsg) {
return buildMsg(aClass, aMethod, aMsg, null);
} // buildErrMsg
/**
* Log an error msg.
* @param aLogger An object that implemets ILogger interface.
* @param aClassName The class where the error was generated.
* @param aMethod The method where the error was generated.
* @param aMsg The error msg to log.
*/
public static void error(final ILogger aLogger,
final String aClassName,
final String aMethod,
final String aMsg) {
aLogger.log(ILogger.ERROR, buildErrMsg(aClassName, aMethod, aMsg));
} //error
/**
* Log an error msg with a long XML part that will be inside a CData section.
* @param aLogger An object that implemets ILogger interface.
* @param aClassName The class where the error was generated.
* @param aMethod The method where the error was generated.
* @param aMsg The error msg to log.
* @param aXml
*/
public static void error(final ILogger aLogger,
final String aClassName,
final String aMethod,
final String aMsg,
final String aXml) {
aLogger.log(ILogger.ERROR, buildErrMsg(aClassName, aMethod, aMsg, aXml));
} //error
/**
* Log an error msg with the stacktrace of a Throwable
* @param aLogger An object that implemets ILogger interface.
* @param aClassName The class where the error was generated.
* @param aMethod The method where the error was generated.
* @param aMsg The error msg to log.
* @param aThrowable Will log its stack trace.
*/
public static void error(final ILogger aLogger,
final String aClassName,
final String aMethod,
final String aMsg,
final Throwable aThrowable) {
aLogger.log(ILogger.ERROR, buildErrMsg(aClassName, aMethod, aMsg), aThrowable);
} //error
/** Write a debug msg to the logger */
public static void debug(final ILogger aLogger,
final String aClassName,
final String aMethod,
final String aMsg) {
aLogger.log(ILogger.DEBUG, buildDebugMsg(aClassName, aMethod, aMsg));
} //debug
/** Write a debug msg to the logger */
public static void debug(final ILogger aLogger,
final String aClassName,
final String aMethod,
final String aMsg,
final String aXml) {
aLogger.log(ILogger.DEBUG, buildDebugMsg(aClassName, aMethod, aMsg, aXml));
} //error
/** Write a debug msg to the logger */
public static void warn(final ILogger aLogger,
final String aClassName,
final String aMethod,
final String aMsg) {
aLogger.log(ILogger.WARNING , buildDebugMsg(aClassName, aMethod, aMsg));
} //debug
/** Write an info msg to the logger */
public static void info(final ILogger aLogger,
final String aClassName,
final String aMethod,
final String aMsg) {
aLogger.log(ILogger.INFO, buildMsg(aClassName, aMethod, aMsg, null));
} // info
} // ExceptionUtil
| 35.866883 | 100 | 0.64995 |
65ed167140bc12a1180c55bb5f4edc13c76e2cdf | 2,437 | package io.github.kavahub.learnjava.lambda;
import static io.github.kavahub.learnjava.lambda.LambdaExceptionRethrow.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
/**
*
* {@link LambdaExceptionRethrow} 应用示例
*
* @author PinWei Wan
* @since 1.0.0
*/
public class LambdaExceptionRethrowTest {
@Test
public void testConsumer() throws MyTestException {
assertThrows(MyTestException.class,
() -> Stream.of((String) null).forEach(rethrowConsumer(s -> checkValue(s))));
}
private void checkValue(String value) throws MyTestException {
if (value == null) {
throw new MyTestException();
}
}
private class MyTestException extends Exception {
}
@Test
public void testConsumerRaisingExceptionInTheMiddle() {
MyLongAccumulator accumulator = new MyLongAccumulator();
try {
Stream.of(2L, 3L, 4L, null, 5L).forEach(rethrowConsumer(s -> accumulator.add(s)));
fail();
} catch (MyTestException e) {
assertEquals(9L, accumulator.acc);
}
}
private class MyLongAccumulator {
private long acc = 0;
public void add(Long value) throws MyTestException {
if (value == null) {
throw new MyTestException();
}
acc += value;
}
}
@Test
public void testFunction() throws MyTestException {
List<Integer> sizes = Stream.of("ciao", "hello").<Integer>map(rethrowFunction(s -> transform(s)))
.collect(Collectors.toList());
assertEquals(2, sizes.size());
assertEquals(4, sizes.get(0).intValue());
assertEquals(5, sizes.get(1).intValue());
}
private Integer transform(String value) throws MyTestException {
if (value == null) {
throw new MyTestException();
}
return value.length();
}
@Test
public void testFunctionRaisingException() throws MyTestException {
assertThrows(MyTestException.class, () -> Stream.of("ciao", null, "hello")
.<Integer>map(rethrowFunction(s -> transform(s))).collect(Collectors.toList()));
}
}
| 30.08642 | 105 | 0.635207 |
39365c79424157915e262eeef20ad419cd19e106 | 898 | package com.nitrous.iosched.client.component;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.user.client.Window;
/**
* Batch up and ignore intermediate window resize events to prevent layout thrashing.
*
* @author nitrousdigital
*/
public class DeferredWindowResizeHandler implements ResizeHandler {
private ResizeHandler handler;
private DelayedTask delay;
private ResizeEvent lastEvent;
public DeferredWindowResizeHandler(ResizeHandler handler) {
this.handler = handler;
this.delay = new DelayedTask() {
@Override
public void run() {
dispatchEventNow();
}
};
Window.addResizeHandler(this);
}
private void dispatchEventNow() {
handler.onResize(lastEvent);
}
@Override
public void onResize(ResizeEvent event) {
this.lastEvent = event;
delay.schedule(200);
}
}
| 23.631579 | 85 | 0.758352 |
d75401ecb18d626a0b5b69c4d11eab38adb23fd3 | 13,318 | package com.iogogogo.supervisord.core.parser;
import com.iogogogo.supervisord.exception.SupervisordException;
import com.iogogogo.supervisord.exception.XMLRPCException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* https://github.com/gturri/aXMLRPC
* <p>
* Created by tao.zeng on 2021/6/22.
*/
public class ResponseParser {
private enum TYPE {
/**
* 4 type.
*/
I4,
/**
* Int type.
*/
INT,
/**
* String type.
*/
STRING,
/**
* Boolean type.
*/
BOOLEAN,
/**
* Double type.
*/
DOUBLE,
/**
* Struct type.
*/
STRUCT,
/**
* Array type.
*/
ARRAY
}
private static final String FAULT_CODE = "faultCode";
private static final String FAULT_STRING = "faultString";
private static final String METHOD_RESPONSE = "methodResponse";
private static final String PARAMS = "params";
private static final String PARAM = "param";
/**
* The constant VALUE.
*/
public static final String VALUE = "value";
private static final String FAULT = "fault";
private static final String METHOD_CALL = "methodCall";
private static final String METHOD_NAME = "methodName";
private static final String STRUCT_MEMBER = "member";
/**
* Parse object.
*
* @param xmlIn the xml in
* @return the object
* @throws XMLRPCException the xmlrpc exception
* @throws SupervisordException the supervisord exception
*/
public Object parse(InputStream xmlIn) throws XMLRPCException, SupervisordException {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(xmlIn);
Element e = dom.getDocumentElement();
// Check for root tag
if (!e.getNodeName().equals(METHOD_RESPONSE)) {
throw new XMLRPCException("MethodResponse root tag is missing.");
}
//ROOT
e = getOnlyChildElement(e.getChildNodes());
if (e.getNodeName().equals(PARAMS)) {
//PARAMS
e = getOnlyChildElement(e.getChildNodes());
if (!e.getNodeName().equals(PARAM)) {
throw new XMLRPCException("The params tag must contain a param tag.");
}
//parse value
return getReturnValueFromElement(e);
} else if (e.getNodeName().equals(FAULT)) {
@SuppressWarnings("unchecked")
Map<String, Object> o = (Map<String, Object>) getReturnValueFromElement(e);
Integer faultCode = (Integer) o.get(FAULT_CODE);
throw new SupervisordException(faultCode, String.valueOf(o.get(FAULT_STRING)));
}
throw new XMLRPCException("The methodResponse tag must contain a fault or params tag.");
} catch (XMLRPCException | SupervisordException ex) {
throw ex;
} catch (Exception ex) {
throw new XMLRPCException("Error getting result from server.", ex);
}
}
/**
* Print document.
*
* @param doc the doc
* @param out the out
* @throws IOException the io exception
* @throws TransformerException the transformer exception
*/
public static void printDocument(Document doc, OutputStream out)
throws IOException, TransformerException {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.transform(new DOMSource(doc),
new StreamResult(new OutputStreamWriter(out, StandardCharsets.UTF_8)));
}
/**
* This method takes an element (must be a param or fault element) and returns the deserialized
* object of this param tag.
*
* @param element An param element.
* @return The deserialized object within the given param element.
* @throws XMLRPCException Will be thrown when the structure of the document doesn't match the
* XML-RPC specification.
*/
private Object getReturnValueFromElement(Element element) {
Element childElement = getOnlyChildElement(element.getChildNodes());
return extract(childElement);
}
private Object extract(Element element) {
Element childElement = getOnlyChildElement(element.getChildNodes());
String nodeName = childElement.getNodeName();
TYPE type = TYPE.valueOf(nodeName.toUpperCase());
switch (type) {
case INT:
return extractInt(childElement);
case BOOLEAN:
return true;
case STRING:
return extractString(childElement);
case STRUCT:
return extractStruct(childElement);
case ARRAY:
return extractArray(childElement);
default:
return 0;
}
}
private String extractString(Element content)
throws XMLRPCException {
String text = getOnlyTextContent(content.getChildNodes());
text = text.replaceAll("<", "<").replaceAll("&", "&");
return text;
}
private int extractInt(Element content) {
return Integer.parseInt(getOnlyTextContent(content.getChildNodes()));
}
private boolean extractBoolean(Element content) {
return getOnlyTextContent(content.getChildNodes()).equals("1")
? Boolean.TRUE : Boolean.FALSE;
}
private Object extractStruct(Element content) {
final String STRUCT_MEMBER = "member";
final String STRUCT_NAME = "name";
final String STRUCT_VALUE = "value";
Map<String, Object> map = new HashMap<>();
Node n, m;
String s;
Object o;
for (int i = 0; i < content.getChildNodes().getLength(); i++) {
n = content.getChildNodes().item(i);
// Strip only whitespace text elements and comments
if ((n.getNodeType() == Node.TEXT_NODE
&& n.getNodeValue().trim().length() <= 0)
|| n.getNodeType() == Node.COMMENT_NODE)
continue;
if (n.getNodeType() != Node.ELEMENT_NODE
|| !STRUCT_MEMBER.equals(n.getNodeName())) {
throw new XMLRPCException("Only struct members allowed within a struct.");
}
// Grep name and value from member
s = null;
o = null;
for (int j = 0; j < n.getChildNodes().getLength(); j++) {
m = n.getChildNodes().item(j);
// Strip only whitespace text elements and comments
if ((m.getNodeType() == Node.TEXT_NODE
&& m.getNodeValue().trim().length() <= 0)
|| m.getNodeType() == Node.COMMENT_NODE)
continue;
if (STRUCT_NAME.equals(m.getNodeName())) {
if (s != null) {
throw new XMLRPCException("Name of a struct member cannot be set twice.");
} else {
s = getOnlyTextContent(m.getChildNodes());
}
} else if (m.getNodeType() == Node.ELEMENT_NODE &&
STRUCT_VALUE.equals(m.getNodeName())) {
if (o != null) {
throw new XMLRPCException("Value of a struct member cannot be set twice.");
} else {
o = extract((Element) m);
}
} else {
throw new XMLRPCException("A struct member must only contain one name and one value.");
}
}
map.put(s, o);
}
return map;
}
private Object[] extractArray(Element content) {
final String ARRAY_DATA = "data";
final String ARRAY_VALUE = "value";
List<Object> list = new ArrayList<Object>();
Element data = getOnlyChildElement(content.getChildNodes());
if (!ARRAY_DATA.equals(data.getNodeName())) {
throw new XMLRPCException("The array must contain one data tag.");
}
// Deserialize every array element
Node value;
for (int i = 0; i < data.getChildNodes().getLength(); i++) {
value = data.getChildNodes().item(i);
// Strip only whitespace text elements and comments
if (value == null || (value.getNodeType() == Node.TEXT_NODE
&& value.getNodeValue().trim().length() <= 0)
|| value.getNodeType() == Node.COMMENT_NODE)
continue;
if (value.getNodeType() != Node.ELEMENT_NODE) {
throw new XMLRPCException("Wrong element inside of array.");
}
list.add(extract((Element) value));
}
return list.toArray();
}
/**
* Returns the only child element in a given NodeList. Will throw an error if there is more then
* one child element or any other child that is not an element or an empty text string
* (whitespace are normal).
*
* @param list A NodeList of children nodes.
* @return The only child element in the given node list.
* @throws XMLRPCException Will be thrown if there is more then one child element except empty
* text nodes.
*/
private static Element getOnlyChildElement(NodeList list)
throws XMLRPCException {
Element e = null;
Node n;
for (int i = 0; i < list.getLength(); i++) {
n = list.item(i);
// Strip only whitespace text elements and comments
if ((n.getNodeType() == Node.TEXT_NODE
&& n.getNodeValue().trim().length() <= 0)
|| n.getNodeType() == Node.COMMENT_NODE)
continue;
// Check if there is anything else than an element node.
if (n.getNodeType() != Node.ELEMENT_NODE) {
throw new XMLRPCException("Only element nodes allowed.");
}
// If there was already an element, throw exception.
if (e != null) {
throw new XMLRPCException("Element has more than one children.");
}
e = (Element) n;
}
return e;
}
/**
* Returns the text node from a given NodeList. If the list contains more then just text nodes,
* an exception will be thrown.
*
* @param list The given list of nodes.
* @return The text of the given node list.
* @throws XMLRPCException Will be thrown if there is more than just one text node within the
* list.
*/
private static String getOnlyTextContent(NodeList list)
throws XMLRPCException {
StringBuilder builder = new StringBuilder();
Node n;
for (int i = 0; i < list.getLength(); i++) {
n = list.item(i);
// Skip comments inside text tag.
if (n.getNodeType() == Node.COMMENT_NODE) {
continue;
}
if (n.getNodeType() != Node.TEXT_NODE) {
throw new XMLRPCException("Element must contain only text elements.");
}
builder.append(n.getNodeValue());
}
return builder.toString();
}
/**
* Checks if the given {@link NodeList} contains a child element.
*
* @param list The {@link NodeList} to check.
* @return Whether the {@link NodeList} contains children.
*/
public static boolean hasChildElement(NodeList list) {
Node n;
for (int i = 0; i < list.getLength(); i++) {
n = list.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) {
return true;
}
}
return false;
}
}
| 33.888041 | 107 | 0.574561 |
b0878bdaff86f974206544f851b2646d9d05e1ad | 1,151 | package info.smartkit.eip.thirdParty;
import java.lang.reflect.Array;
public class BaiduLoc {
private Object location;
public Object getLocation() {
return location;
}
public void setLocation(Object location) {
this.location = location;
}
private String formatted_address;
public String getFormatted_address() {
return formatted_address;
}
public void setFormatted_address(String formatted_address) {
this.formatted_address = formatted_address;
}
private String business;
public String getBusiness() {
return business;
}
public void setBusiness(String business) {
this.business = business;
}
private Object addressComponent;
public Object getAddressComponent() {
return addressComponent;
}
public void setAddressComponent(Object addressComponent) {
this.addressComponent = addressComponent;
}
private Object poiRegions;
public Object getPoiRegions() {
return poiRegions;
}
public void setPoiRegions(Object poiRegions) {
this.poiRegions = poiRegions;
}
private long cityCode;
public long getCityCode() {
return cityCode;
}
public void setCityCode(long cityCode) {
this.cityCode = cityCode;
}
}
| 23.02 | 61 | 0.76629 |
8753f007bd3201ebe19070748ea93b0ca4557450 | 1,496 | package com.sequenceiq.datalake.flow.dr.backup;
import com.sequenceiq.datalake.flow.dr.backup.event.DatalakeDatabaseBackupCouldNotStartEvent;
import com.sequenceiq.datalake.flow.dr.backup.event.DatalakeDatabaseBackupFailedEvent;
import com.sequenceiq.datalake.flow.dr.backup.event.DatalakeDatabaseBackupStartEvent;
import com.sequenceiq.datalake.flow.dr.backup.event.DatalakeDatabaseBackupSuccessEvent;
import com.sequenceiq.flow.core.FlowEvent;
import com.sequenceiq.flow.event.EventSelectorUtil;
public enum DatalakeDatabaseBackupEvent implements FlowEvent {
DATALAKE_DATABASE_BACKUP_EVENT(EventSelectorUtil.selector(DatalakeDatabaseBackupStartEvent.class)),
DATALAKE_DATABASE_BACKUP_COULD_NOT_START_EVENT(EventSelectorUtil.selector(DatalakeDatabaseBackupCouldNotStartEvent.class)),
DATALAKE_DATABASE_BACKUP_IN_PROGRESS_EVENT("DATALAKE_DATABASE_BACKUP_IN_PROGRESS_EVENT"),
DATALAKE_DATABASE_BACKUP_SUCCESS_EVENT(EventSelectorUtil.selector(DatalakeDatabaseBackupSuccessEvent.class)),
DATALAKE_DATABASE_BACKUP_FAILED_EVENT(EventSelectorUtil.selector(DatalakeDatabaseBackupFailedEvent.class)),
DATALAKE_DATABASE_BACKUP_FINALIZED_EVENT("DATALAKE_DATABASE_BACKUP_FINALIZED_EVENT"),
DATALAKE_DATABASE_BACKUP_FAILURE_HANDLED_EVENT("DATALAKE_DATABASE_BACKUP_FAILURE_HANDLED_EVENT");
private final String event;
DatalakeDatabaseBackupEvent(String event) {
this.event = event;
}
@Override
public String event() {
return event;
}
} | 49.866667 | 127 | 0.848262 |
e3032a8369013edc3946ebb2e2fcf71370613ee7 | 300 | package com.graphSearch.domain.Relation;
import com.graphSearch.domain.RelationShip;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.neo4j.ogm.annotation.RelationshipEntity;
@Data
@NoArgsConstructor
@RelationshipEntity(type = "NotSuit")
public class NotSuit extends RelationShip{
}
| 23.076923 | 51 | 0.833333 |
9da2bc8f6fa1376153a9f3def240a2cd81d8f5ec | 1,757 | /*
* Copyright 2014 NAVER Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.navercorp.pinpoint.web.applicationmap.histogram;
import com.navercorp.pinpoint.web.view.TimeViewModel;
import com.navercorp.pinpoint.web.vo.Application;
import com.navercorp.pinpoint.common.server.util.time.Range;
import java.util.*;
/**
* @author emeroad
*/
public class ApplicationTimeHistogram {
private final Application application;
private final Range range;
private final List<TimeHistogram> histogramList;
public ApplicationTimeHistogram(Application application, Range range) {
this(application, range, Collections.emptyList());
}
public ApplicationTimeHistogram(Application application, Range range, List<TimeHistogram> histogramList) {
this.application = Objects.requireNonNull(application, "application");
this.range = Objects.requireNonNull(range, "range");
this.histogramList = Objects.requireNonNull(histogramList, "histogramList");
}
public List<TimeViewModel> createViewModel(TimeHistogramFormat timeHistogramFormat) {
return new TimeViewModel.TimeViewModelBuilder(application, histogramList).setTimeHistogramFormat(timeHistogramFormat).build();
}
} | 38.195652 | 134 | 0.759249 |
c2f828ba1ddca8a9aba2f4938a025fd38528c162 | 1,902 | package com.zhigu.model;
/**
* 商品附属
*
* @author zhouqibing 2014年9月28日下午2:35:07
*/
public class GoodsAux {
private int id;
// 商品Id
private int goodsId;
// 数量
private int amount;
// 下载次数
private int downloadCount;
// 评价次数
private int evaluateCount;
// 销售数量
private int purchaseCount;
// 收藏次数
private int favouriteCount;
// 浏览次数
private int browseCount;
// 评分
private float score;
// 综合得分(下载 + 评价 + 销售 + 收藏 + 浏览 + 评分)
private float overallScore;
public GoodsAux() {
}
public GoodsAux(int goodsId) {
this.goodsId = goodsId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getGoodsId() {
return goodsId;
}
public void setGoodsId(int goodsId) {
this.goodsId = goodsId;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public int getDownloadCount() {
return downloadCount;
}
public void setDownloadCount(int downloadCount) {
this.downloadCount = downloadCount;
}
public int getEvaluateCount() {
return evaluateCount;
}
public void setEvaluateCount(int evaluateCount) {
this.evaluateCount = evaluateCount;
}
public int getPurchaseCount() {
return purchaseCount;
}
public void setPurchaseCount(int purchaseCount) {
this.purchaseCount = purchaseCount;
}
public int getFavouriteCount() {
return favouriteCount;
}
public void setFavouriteCount(int favouriteCount) {
this.favouriteCount = favouriteCount;
}
public float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
public int getBrowseCount() {
return browseCount;
}
public void setBrowseCount(int browseCount) {
this.browseCount = browseCount;
}
public float getOverallScore() {
return overallScore;
}
public void setOverallScore(float overallScore) {
this.overallScore = overallScore;
}
}
| 16.25641 | 52 | 0.704522 |
17fa145a0d795fc3181db59011e8d56cbc68b53b | 3,998 | /*
* The MIT License
*
* Copyright 2017 Neel Patel.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.neel.articleshubapi.restapi.beans;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Neel Patel on 26-07-2017.
* @author Neel Patel
* @version 1.0.0
*/
public class CommentDetail {
private long commentId;
private long articleId;
private String userName;
private String content;
private String date;
private String time;
private List<Link> links=new ArrayList<>();
/**
* @return comment id
*/
public long getCommentId() {
return commentId;
}
/**
* @param commentId comment id
*/
public void setCommentId(long commentId) {
this.commentId = commentId;
}
/**
* @return id of the associated article
*/
public long getArticleId() {
return articleId;
}
/**
* @param articleId id of associated article
*/
public void setArticleId(long articleId) {
this.articleId = articleId;
}
/**
* @return username of the user who makes comment
*/
public String getUserName() {
return userName;
}
/**
* @param userName username of the user who makes comment
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* @return content of the comment
*/
public String getContent() {
return content;
}
/**
* @param content content of the comment
*/
public void setContent(String content) {
this.content = content;
}
/**
* this method returns links related to this object.
* @return list of links
*/
public List<Link> getLinks() {
return links;
}
/**
* @return comment date
*/
public String getDate() {
return date;
}
/**
* @param date comment date
*/
public void setDate(String date) {
this.date = date;
}
/**
* @return comment time
*/
public String getTime() {
return time;
}
/**
* @param time comment time
*/
public void setTime(String time) {
this.time = time;
}
/**
* this method returns Link object having name specified from
the list returned by the {@code getLinks} method.
* @param name name of the link
* @return object of link having name specified. null otherwise.
*/
public Link getLink(String name){
try{
for(Link l:getLinks())
if(l.getName().equals(name))
return l;
}catch(Exception ex){
Log.e("CommentDetail", "getLink: "+ex.getMessage(),ex);
}
return null;
}
@Override
public String toString() {
return "CommentDetail:- comment_id: "+getCommentId()+", article_id: "+getArticleId();
}
}
| 24.832298 | 93 | 0.621061 |
efb6fefe3a5a85551099abe31792e0aa4032c32e | 7,007 | package ru.job4j.sqlite;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.Closeable;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* Class StoreSQL - work with SQLite.
*
* @author Gregory Smirnov ([email protected])
* @version 1.0
* @since 21/11/2018
*/
public class StoreSQL implements Closeable {
/**
* The logger for SQLite. It used for storing the working with database.
*/
private final Logger sqLiteLog = LogManager.getLogger(StoreSQL.class);
/**
* The connection to database.
*/
private final Connection connection;
/**
* The constructor which creates and initialises the connection to SQLite database.
*
* @param config - configuration of connection.
*/
public StoreSQL(Config config) {
try {
this.connection = DriverManager.getConnection(config.get("url"));
if (this.connection != null) {
DatabaseMetaData meta = this.connection.getMetaData();
this.sqLiteLog.info(String.format("The driver name is: %s", meta.getDriverName()));
this.sqLiteLog.info("Connection to SQLite has been established.");
}
} catch (Exception e) {
this.sqLiteLog.error(e.getMessage(), e);
throw new IllegalStateException(e);
}
}
/**
* The initializer which initialize database.
*
* @param quantity - the quantity of initialize numbers.
*/
public void init(int quantity) {
if (!this.isStructure()) {
this.createTable();
}
this.emptyTable();
this.fillTable(quantity);
}
/**
* Checks database 'magnit'.
*
* @return true if the structure exists.
*/
public boolean isStructure() {
boolean result = false;
ArrayList<String> tables = new ArrayList<String>();
try (PreparedStatement statement = this.connection.prepareStatement(
"select name from sqlite_master where type='table' order by name;")) {
try (ResultSet rslSet = statement.executeQuery()) {
while (rslSet.next()) {
tables.add(rslSet.getString("name"));
}
}
if (tables.contains("entry")) {
result = true;
this.sqLiteLog.info("Database contains table 'entry'.");
}
} catch (SQLException e) {
this.sqLiteLog.error(e.getMessage(), e);
}
return result;
}
/**
* Deletes all rows from the table.
*/
private void emptyTable() {
String sql = "delete from entry;";
try (Statement statement = this.connection.createStatement()) {
statement.execute(sql);
} catch (SQLException e) {
this.sqLiteLog.error(e.getMessage(), e);
}
}
/**
* Checks if entry-table is empty.
*
* @return true if empty.
*/
public boolean isTableEmpty() {
return this.findAll().size() == 0;
}
/**
* Deletes entry-table.
*/
public void deleteTable() {
String sql = "drop table entry;";
try (Statement statement = this.connection.createStatement()) {
statement.execute(sql);
} catch (SQLException e) {
this.sqLiteLog.error(e.getMessage(), e);
}
}
/**
* Creates new table if it not exists.
*/
private void createTable() {
String sql = "create table if not exists entry( "
+ "id integer primary key, "
+ "number integer"
+ ");";
try (Statement statement = this.connection.createStatement()) {
//statement.executeQuery(sql);
statement.execute(sql);
this.sqLiteLog.info("Table \'entry\' has been created.");
} catch (SQLException e) {
this.sqLiteLog.error(e.getMessage(), e);
}
}
/**
* Fills table with initial numbers.
*
* @param quantity - initial numbers, from 1 to "quantity".
*/
private void fillTable(int quantity) {
try {
this.connection.setAutoCommit(false);
for (int counter = 1; counter <= quantity; counter++) {
try (PreparedStatement statement = this.connection.prepareStatement(
"insert into entry(number) values(?);",
Statement.RETURN_GENERATED_KEYS
)) {
statement.setInt(1, counter);
statement.executeUpdate();
} catch (SQLException e) {
this.sqLiteLog.error(e.getMessage(), e);
}
}
this.connection.commit();
this.sqLiteLog.info(String.format("%d items has been added to table \'entry\'.", quantity));
} catch (SQLException e) {
this.sqLiteLog.error(e.getMessage(), e);
try {
this.connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
this.sqLiteLog.error(e1.getMessage(), e1);
}
}
}
/**
* Finds all numbers from database.
*
* @return the list of all numbers.
*/
public List<StoreXML.Field> findAll() {
List<StoreXML.Field> result = new LinkedList<StoreXML.Field>();
try (Statement statement = this.connection.createStatement()) {
try (ResultSet rslSet = statement.executeQuery("select * from entry;")) {
while (rslSet.next()) {
result.add(new StoreXML.Field(rslSet.getInt("number")));
}
this.sqLiteLog.info(String.format("\'Find all\' successful, found %d items.", result.size()));
}
} catch (SQLException e) {
this.sqLiteLog.error(e.getMessage(), e);
}
return result;
}
/**
* Clears the entry table.
*/
public void clearEntryTable() {
try (PreparedStatement statement = this.connection.prepareStatement(
"delete from entry;")) {
statement.executeUpdate();
this.sqLiteLog.info("Entry table was cleared.");
} catch (SQLException e) {
this.sqLiteLog.error(e.getMessage(), e);
}
}
/**
* Closes the connection.
*
* @throws IOException if SQLException occurs during close connection operation.
*/
@Override
public void close() throws IOException {
try {
if (this.connection != null) {
this.connection.close();
this.sqLiteLog.info("Connection has been closed.");
}
} catch (SQLException sqle) {
this.sqLiteLog.error(sqle.getMessage(), sqle);
throw new IOException(sqle);
}
}
} | 31.85 | 110 | 0.552162 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.