text stringlengths 10 2.72M |
|---|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.kroky.jminesweeper.events;
import org.kroky.jminesweeper.Tile;
/**
*
* @author Peter Krokavec
*/
public class TileActionEvent {
private final Tile source;
public TileActionEvent(Tile source) {
this.source = source;
}
/**
* @return the source
*/
public Tile getSource() {
return source;
}
}
|
package proghf.controller;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Separator;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import proghf.ViewManager;
import proghf.view.SearchView;
import proghf.view.TaskView;
/**
* A keresési nézet kontrollere
*/
public class SearchController {
/**
* A találatok listáját tartalmazó doboz
*/
@FXML
private VBox resultList;
/**
* A keresési nézet kötése
* <p>
* Végigiterál a találatokon, és létrehozza a képernyőn megjelenő elemeket
*
* @param searchView a keresési nézet
*/
public void bindView(SearchView searchView) {
searchView.getResult().forEach(task -> {
var hbox = new HBox();
var title = new Label(task.getName());
title.setFont(Font.font(14));
var pane = new Pane();
var tableName = new Label(task.getParent().getName());
tableName.setFont(Font.font(14));
var openButton = new Button("Megnyitás");
openButton.setOnAction(actionEvent -> {
var taskView = new TaskView(task);
ViewManager.getInstance().setCurrentView(taskView.getView());
});
hbox.getChildren().addAll(title, pane, tableName, openButton);
hbox.setSpacing(8.0);
hbox.setPadding(new Insets(8, 8, 8, 8));
HBox.setHgrow(pane, Priority.ALWAYS);
resultList.getChildren().add(hbox);
var separator = new Separator();
resultList.getChildren().add(separator);
});
}
/**
* A vissza navigáló gomb eseménykezelője
*
* @param actionEvent esemény paraméter
*/
public void onBackPressed(ActionEvent actionEvent) {
ViewManager.getInstance().navigateBack();
}
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: sample.proto
package org.springframework.protobuf;
/**
* Protobuf type {@code Msg}
*/
@SuppressWarnings("serial")
public final class Msg extends
com.google.protobuf.GeneratedMessage
implements MsgOrBuilder {
// Use Msg.newBuilder() to construct.
private Msg(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
super(builder);
this.unknownFields = builder.getUnknownFields();
}
private Msg(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
private static final Msg defaultInstance;
public static Msg getDefaultInstance() {
return defaultInstance;
}
public Msg getDefaultInstanceForType() {
return defaultInstance;
}
private final com.google.protobuf.UnknownFieldSet unknownFields;
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private Msg(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
initFields();
@SuppressWarnings("unused")
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
done = true;
}
break;
}
case 10: {
bitField0_ |= 0x00000001;
foo_ = input.readBytes();
break;
}
case 18: {
org.springframework.protobuf.SecondMsg.Builder subBuilder = null;
if (((bitField0_ & 0x00000002) == 0x00000002)) {
subBuilder = blah_.toBuilder();
}
blah_ = input.readMessage(org.springframework.protobuf.SecondMsg.PARSER, extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(blah_);
blah_ = subBuilder.buildPartial();
}
bitField0_ |= 0x00000002;
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return org.springframework.protobuf.OuterSample.internal_static_Msg_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return org.springframework.protobuf.OuterSample.internal_static_Msg_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.springframework.protobuf.Msg.class, org.springframework.protobuf.Msg.Builder.class);
}
public static com.google.protobuf.Parser<Msg> PARSER =
new com.google.protobuf.AbstractParser<Msg>() {
public Msg parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new Msg(input, extensionRegistry);
}
};
@java.lang.Override
public com.google.protobuf.Parser<Msg> getParserForType() {
return PARSER;
}
private int bitField0_;
// optional string foo = 1;
public static final int FOO_FIELD_NUMBER = 1;
private java.lang.Object foo_;
/**
* <code>optional string foo = 1;</code>
*/
public boolean hasFoo() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional string foo = 1;</code>
*/
public java.lang.String getFoo() {
java.lang.Object ref = foo_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
foo_ = s;
}
return s;
}
}
/**
* <code>optional string foo = 1;</code>
*/
public com.google.protobuf.ByteString
getFooBytes() {
java.lang.Object ref = foo_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
foo_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
// optional .SecondMsg blah = 2;
public static final int BLAH_FIELD_NUMBER = 2;
private org.springframework.protobuf.SecondMsg blah_;
/**
* <code>optional .SecondMsg blah = 2;</code>
*/
public boolean hasBlah() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>optional .SecondMsg blah = 2;</code>
*/
public org.springframework.protobuf.SecondMsg getBlah() {
return blah_;
}
/**
* <code>optional .SecondMsg blah = 2;</code>
*/
public org.springframework.protobuf.SecondMsgOrBuilder getBlahOrBuilder() {
return blah_;
}
private void initFields() {
foo_ = "";
blah_ = org.springframework.protobuf.SecondMsg.getDefaultInstance();
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized != -1) return isInitialized == 1;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeBytes(1, getFooBytes());
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeMessage(2, blah_);
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(1, getFooBytes());
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, blah_);
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static org.springframework.protobuf.Msg parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.springframework.protobuf.Msg parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.springframework.protobuf.Msg parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.springframework.protobuf.Msg parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.springframework.protobuf.Msg parseFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static org.springframework.protobuf.Msg parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static org.springframework.protobuf.Msg parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
public static org.springframework.protobuf.Msg parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
public static org.springframework.protobuf.Msg parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static org.springframework.protobuf.Msg parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(org.springframework.protobuf.Msg prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code Msg}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder>
implements org.springframework.protobuf.MsgOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return org.springframework.protobuf.OuterSample.internal_static_Msg_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return org.springframework.protobuf.OuterSample.internal_static_Msg_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.springframework.protobuf.Msg.class, org.springframework.protobuf.Msg.Builder.class);
}
// Construct using org.springframework.protobuf.Msg.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
getBlahFieldBuilder();
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
foo_ = "";
bitField0_ = (bitField0_ & ~0x00000001);
if (blahBuilder_ == null) {
blah_ = org.springframework.protobuf.SecondMsg.getDefaultInstance();
} else {
blahBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000002);
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return org.springframework.protobuf.OuterSample.internal_static_Msg_descriptor;
}
public org.springframework.protobuf.Msg getDefaultInstanceForType() {
return org.springframework.protobuf.Msg.getDefaultInstance();
}
public org.springframework.protobuf.Msg build() {
org.springframework.protobuf.Msg result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public org.springframework.protobuf.Msg buildPartial() {
org.springframework.protobuf.Msg result = new org.springframework.protobuf.Msg(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.foo_ = foo_;
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
if (blahBuilder_ == null) {
result.blah_ = blah_;
} else {
result.blah_ = blahBuilder_.build();
}
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof org.springframework.protobuf.Msg) {
return mergeFrom((org.springframework.protobuf.Msg)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(org.springframework.protobuf.Msg other) {
if (other == org.springframework.protobuf.Msg.getDefaultInstance()) return this;
if (other.hasFoo()) {
bitField0_ |= 0x00000001;
foo_ = other.foo_;
onChanged();
}
if (other.hasBlah()) {
mergeBlah(other.getBlah());
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
org.springframework.protobuf.Msg parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (org.springframework.protobuf.Msg) e.getUnfinishedMessage();
throw e;
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
// optional string foo = 1;
private java.lang.Object foo_ = "";
/**
* <code>optional string foo = 1;</code>
*/
public boolean hasFoo() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional string foo = 1;</code>
*/
public java.lang.String getFoo() {
java.lang.Object ref = foo_;
if (!(ref instanceof java.lang.String)) {
java.lang.String s = ((com.google.protobuf.ByteString) ref)
.toStringUtf8();
foo_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>optional string foo = 1;</code>
*/
public com.google.protobuf.ByteString
getFooBytes() {
java.lang.Object ref = foo_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
foo_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>optional string foo = 1;</code>
*/
public Builder setFoo(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
foo_ = value;
onChanged();
return this;
}
/**
* <code>optional string foo = 1;</code>
*/
public Builder clearFoo() {
bitField0_ = (bitField0_ & ~0x00000001);
foo_ = getDefaultInstance().getFoo();
onChanged();
return this;
}
/**
* <code>optional string foo = 1;</code>
*/
public Builder setFooBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
foo_ = value;
onChanged();
return this;
}
// optional .SecondMsg blah = 2;
private org.springframework.protobuf.SecondMsg blah_ = org.springframework.protobuf.SecondMsg.getDefaultInstance();
private com.google.protobuf.SingleFieldBuilder<
org.springframework.protobuf.SecondMsg, org.springframework.protobuf.SecondMsg.Builder,
org.springframework.protobuf.SecondMsgOrBuilder> blahBuilder_;
/**
* <code>optional .SecondMsg blah = 2;</code>
*/
public boolean hasBlah() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>optional .SecondMsg blah = 2;</code>
*/
public org.springframework.protobuf.SecondMsg getBlah() {
if (blahBuilder_ == null) {
return blah_;
} else {
return blahBuilder_.getMessage();
}
}
/**
* <code>optional .SecondMsg blah = 2;</code>
*/
public Builder setBlah(org.springframework.protobuf.SecondMsg value) {
if (blahBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
blah_ = value;
onChanged();
} else {
blahBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
return this;
}
/**
* <code>optional .SecondMsg blah = 2;</code>
*/
public Builder setBlah(
org.springframework.protobuf.SecondMsg.Builder builderForValue) {
if (blahBuilder_ == null) {
blah_ = builderForValue.build();
onChanged();
} else {
blahBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
return this;
}
/**
* <code>optional .SecondMsg blah = 2;</code>
*/
public Builder mergeBlah(org.springframework.protobuf.SecondMsg value) {
if (blahBuilder_ == null) {
if (((bitField0_ & 0x00000002) == 0x00000002) &&
blah_ != org.springframework.protobuf.SecondMsg.getDefaultInstance()) {
blah_ =
org.springframework.protobuf.SecondMsg.newBuilder(blah_).mergeFrom(value).buildPartial();
} else {
blah_ = value;
}
onChanged();
} else {
blahBuilder_.mergeFrom(value);
}
bitField0_ |= 0x00000002;
return this;
}
/**
* <code>optional .SecondMsg blah = 2;</code>
*/
public Builder clearBlah() {
if (blahBuilder_ == null) {
blah_ = org.springframework.protobuf.SecondMsg.getDefaultInstance();
onChanged();
} else {
blahBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000002);
return this;
}
/**
* <code>optional .SecondMsg blah = 2;</code>
*/
public org.springframework.protobuf.SecondMsg.Builder getBlahBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getBlahFieldBuilder().getBuilder();
}
/**
* <code>optional .SecondMsg blah = 2;</code>
*/
public org.springframework.protobuf.SecondMsgOrBuilder getBlahOrBuilder() {
if (blahBuilder_ != null) {
return blahBuilder_.getMessageOrBuilder();
} else {
return blah_;
}
}
/**
* <code>optional .SecondMsg blah = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilder<
org.springframework.protobuf.SecondMsg, org.springframework.protobuf.SecondMsg.Builder,
org.springframework.protobuf.SecondMsgOrBuilder>
getBlahFieldBuilder() {
if (blahBuilder_ == null) {
blahBuilder_ = new com.google.protobuf.SingleFieldBuilder<>(
blah_,
getParentForChildren(),
isClean());
blah_ = null;
}
return blahBuilder_;
}
// @@protoc_insertion_point(builder_scope:Msg)
}
static {
defaultInstance = new Msg(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:Msg)
}
|
package com.example.demo;
public class RootObject {
// private final long id;
private final String root;
PartyObject party = new PartyObject();
ClassificationNode cNode = new ClassificationNode();
public ClassificationNode getcNode() {
return cNode;
}
public RootObject() {
// this.id = 2;
this.root = "";
}
public PartyObject getParty() {
return party;
}
public String getRoot() {
return root;
}
/*public long getId() {
return id;
}
public String getContent() {
return content;
}
*/
} |
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Unit tests for {@link ProblemDetail}.
*
* @author Juergen Hoeller
* @author Yanming Zhou
*/
class ProblemDetailTests {
@Test
void equalsAndHashCode() {
ProblemDetail pd1 = ProblemDetail.forStatus(500);
ProblemDetail pd2 = ProblemDetail.forStatus(HttpStatus.INTERNAL_SERVER_ERROR);
ProblemDetail pd3 = ProblemDetail.forStatus(HttpStatus.NOT_FOUND);
ProblemDetail pd4 = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, "some detail");
assertThat(pd1).isEqualTo(pd2);
assertThat(pd2).isEqualTo(pd1);
assertThat(pd1.hashCode()).isEqualTo(pd2.hashCode());
assertThat(pd3).isNotEqualTo(pd4);
assertThat(pd4).isNotEqualTo(pd3);
assertThat(pd3.hashCode()).isNotEqualTo(pd4.hashCode());
assertThat(pd1).isNotEqualTo(pd3);
assertThat(pd1).isNotEqualTo(pd4);
assertThat(pd2).isNotEqualTo(pd3);
assertThat(pd2).isNotEqualTo(pd4);
assertThat(pd1.hashCode()).isNotEqualTo(pd3.hashCode());
assertThat(pd1.hashCode()).isNotEqualTo(pd4.hashCode());
}
@Test // gh-30294
void equalsAndHashCodeWithDeserialization() throws Exception {
ProblemDetail originalDetail = ProblemDetail.forStatus(500);
ObjectMapper mapper = new ObjectMapper();
byte[] bytes = mapper.writeValueAsBytes(originalDetail);
ProblemDetail deserializedDetail = mapper.readValue(bytes, ProblemDetail.class);
assertThat(originalDetail).isEqualTo(deserializedDetail);
assertThat(deserializedDetail).isEqualTo(originalDetail);
assertThat(originalDetail.hashCode()).isEqualTo(deserializedDetail.hashCode());
}
}
|
package com.sinodynamic.hkgta.controller.salesreport;
import com.sinodynamic.hkgta.controller.ControllerBase;
import com.sinodynamic.hkgta.service.crm.sales.UserMasterService;
import com.sinodynamic.hkgta.util.TokenUtils;
import com.sinodynamic.hkgta.util.constant.GTAError;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ReportController extends ControllerBase {
@Autowired
private UserMasterService userMasterService;
protected void handleExpirySession(HttpServletRequest request, HttpServletResponse response) {
String url = request.getHeader("Referer");
String base64Token = request.getHeader("token");
GTAError errorCode = null;
boolean valid = false;
if (null==base64Token || StringUtils.isEmpty(base64Token))
{
base64Token = request.getParameter("token");
}
//If session is expire or token is invalid, redirect to login page.
if (StringUtils.isEmpty(base64Token))
{
try {
response.sendRedirect(url);
} catch (IOException e1) {
e1.printStackTrace();
}
}else {
byte[] t = Base64.decodeBase64(base64Token);
String authToken = new String(t);
valid = TokenUtils.validateUUIDToken(authToken);
errorCode = userMasterService.updateSessionToken(authToken);
if (!valid || !GTAError.Success.SUCCESS.equals(errorCode))
{
try {
response.sendRedirect(url);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
protected void chooseFileType(HttpServletRequest request, HttpServletResponse response,String fileName,String fileType) {
if("pdf".equalsIgnoreCase(fileType)){
response.setHeader("Content-Disposition", "attachment; filename=" +fileName+".pdf");
response.setContentType("application/pdf");
}else{
response.setHeader("Content-Disposition", "attachment; filename=" +fileName+".csv");
response.setContentType("text/csv");
}
}
}
|
/**
* --------------------------------------------------------------------------------------------------------------------
* <copyright company="Aspose Pty Ltd" file="VerifyQRCodeOptions.java">
* Copyright (c) 2003-2023 Aspose Pty Ltd
* </copyright>
* <summary>
* 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.
* </summary>
* --------------------------------------------------------------------------------------------------------------------
*/
package com.groupdocs.cloud.signature.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.groupdocs.cloud.signature.model.PagesSetup;
import com.groupdocs.cloud.signature.model.VerifyTextOptions;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
/**
* Option keeps settings to verify QR-code signature of document
*/
@ApiModel(description = "Option keeps settings to verify QR-code signature of document")
public class VerifyQRCodeOptions extends VerifyTextOptions {
@SerializedName("qrCodeType")
private String qrCodeType = null;
public VerifyQRCodeOptions qrCodeType(String qrCodeType) {
this.qrCodeType = qrCodeType;
return this;
}
/**
* Get or set QR-code type verification
* @return qrCodeType
**/
@ApiModelProperty(value = "Get or set QR-code type verification")
public String getQrCodeType() {
return qrCodeType;
}
public void setQrCodeType(String qrCodeType) {
this.qrCodeType = qrCodeType;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
VerifyQRCodeOptions verifyQRCodeOptions = (VerifyQRCodeOptions) o;
return Objects.equals(this.qrCodeType, verifyQRCodeOptions.qrCodeType) &&
super.equals(o);
}
@Override
public int hashCode() {
return Objects.hash(qrCodeType, super.hashCode());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class VerifyQRCodeOptions {\n");
sb.append(" ").append(toIndentedString(super.toString())).append("\n");
sb.append(" qrCodeType: ").append(toIndentedString(qrCodeType)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
package framework;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;
/**
* Created by nika.khaladkar on 18/08/2016.
*/
public class ProductsLightsPage extends BasePage{
@FindBy(how = How.XPATH, using = ".//*[@data-omniture-ref='HALshowCTA']")
private WebElement lightsBuyNowElement;
public ProductsLightsPage(WebDriver driver){
super(driver);
PageFactory.initElements(driver, this);
}
public void goToShopLightsPage()
{
lightsBuyNowElement.click();
Utilities.waitForSomeTime();
}
}
|
package com.org.bookservice.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
@Entity(name = "RoleEntity")
@Table(name = "roles", uniqueConstraints = {
@UniqueConstraint(columnNames = "roleid")})
public class RoleEntity {
public RoleEntity() {
super();
// TODO Auto-generated constructor stub
}
private static final long serialVersionUID = -6790693372846798580L;
@Id
@Column(name = "roleid", unique = true, nullable = false)
private String roleId;
public RoleEntity(String roleId) {
this.roleId = roleId;
}
public String getRoleId() {
return roleId;
}
public void setRoleId(String roleId) {
this.roleId = roleId;
}
}
|
package com.netcracker.entities;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Objects;
@Entity
@Table(name="Type_Group")
public class TypeGroup {
@Id
@NotNull
@Column(name = "Type_Group_ID")
private Long id;
@NotNull
@Column(name="Name_Type")
private String nameType;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNameType() {
return nameType;
}
public void setNameType(String name_type) {
this.nameType = name_type;
}
public TypeGroup() { }
public TypeGroup(@NotNull Long id, @NotNull String name_type) {
this.id = id;
this.nameType = name_type;
}
@Override
public String toString() {
return "TypeGroup{" +
"id=" + id +
", name_type='" + nameType + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TypeGroup typeGroup = (TypeGroup) o;
return Objects.equals(getId(), typeGroup.getId()) &&
Objects.equals(getNameType(), typeGroup.getNameType());
}
@Override
public int hashCode() {
return Objects.hash(getId(), getNameType());
}
}
|
package io.flood.rpc;
/**
* Created by Administrator on 2015/11/2.
*/
public class FloodConstants {
public final static String VERSION="0.0.1";
public final static int RPC_BLOCKING_REQUEST=0x1;
public final static int RPC_RESPONSE=0x2;
public final static int RPC_STATE_SUCCESS=0;
public final static int RPC_STATE_SERVICE_NOT_FOUND=1;
public final static int RPC_STATE_METHOD_NOT_FOUND=2;
public final static int RPC_STATE_FAILD=4;
}
|
/*
* 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 oj;
import java.awt.Desktop;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.WriteException;
/**
*
* @author Junaeid
*/
public class loginframe extends javax.swing.JFrame {
/**
* Creates new form loginframe
*/
public loginframe() {
initComponents();
}
public loginframe(String us) {
initComponents();
user=us;
showproblem();
addtosubtable();
mysub(us);
jLabel5.setText("Hi, "+us);
//setUndecorated(true);
// setAlwaysOnTop(true);
//setResizable(false);
// setVisible(true);
//Toolkit tk = Toolkit.getDefaultToolkit();
// double x = (double) tk.getScreenSize().getWidth();
// double y = (double) tk.getScreenSize().getHeight();
// this.setSize((int)x,(int)y);
}
/**
* 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">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel3 = new javax.swing.JPanel();
add = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
table1 = new javax.swing.JTable();
jLabel7 = new javax.swing.JLabel();
idcombo = new javax.swing.JComboBox<>();
openpdf = new javax.swing.JButton();
jPanel4 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
subarea = new javax.swing.JTextArea();
problang = new javax.swing.JComboBox<>();
jLabel4 = new javax.swing.JLabel();
submit = new javax.swing.JButton();
jLabel6 = new javax.swing.JLabel();
subprobid = new javax.swing.JComboBox<>();
jPanel5 = new javax.swing.JPanel();
jScrollPane5 = new javax.swing.JScrollPane();
submissionTable = new javax.swing.JTable();
jPanel8 = new javax.swing.JPanel();
jScrollPane6 = new javax.swing.JScrollPane();
mysub = new javax.swing.JTable();
jPanel7 = new javax.swing.JPanel();
problinklabel = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
probid = new javax.swing.JTextField();
probname = new javax.swing.JTextField();
category = new javax.swing.JComboBox<>();
problink = new javax.swing.JTextField();
jScrollPane3 = new javax.swing.JScrollPane();
indata = new javax.swing.JTextArea();
jScrollPane4 = new javax.swing.JScrollPane();
outdata = new javax.swing.JTextArea();
addproblem = new javax.swing.JButton();
categorylabel = new javax.swing.JLabel();
probidlabel = new javax.swing.JLabel();
probnamelabel = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("RUET OJ");
jPanel1.setBackground(new java.awt.Color(0, 102, 102));
jPanel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel2.setForeground(new java.awt.Color(255, 255, 255));
jLabel2.setText("RUET OJ");
jLabel5.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel5.setForeground(new java.awt.Color(204, 255, 255));
jLabel5.setText("");
jLabel3.setIcon(new javax.swing.ImageIcon("G:\\Project1\\OJ\\Untitled2.png")); // NOI18N
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setText("Log Out");
jLabel1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel1MouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(19, 19, 19)
.addComponent(jLabel3)
.addGap(18, 18, 18)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING))
.addGap(36, 36, 36))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1))
.addComponent(jLabel3))
.addContainerGap())
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(19, 19, 19)
.addComponent(jLabel2)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel2.setBackground(new java.awt.Color(102, 102, 102));
jButton1.setText("Problemsets");
jButton1.setAlignmentY(0.0F);
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Submit Code");
jButton2.setAlignmentY(0.0F);
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("Submissions");
jButton3.setAlignmentY(0.0F);
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jButton4.setText("My Submissions");
jButton4.setAlignmentY(0.0F);
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addContainerGap(29, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(27, 27, 27))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(70, 70, 70)
.addComponent(jButton1)
.addGap(56, 56, 56)
.addComponent(jButton2)
.addGap(55, 55, 55)
.addComponent(jButton3)
.addGap(57, 57, 57)
.addComponent(jButton4)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jTabbedPane1.setBackground(new java.awt.Color(255, 255, 255));
jTabbedPane1.setBorder(javax.swing.BorderFactory.createCompoundBorder());
jTabbedPane1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
add.setBackground(new java.awt.Color(0, 204, 204));
add.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
add.setText("Add Problem");
add.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addActionPerformed(evt);
}
});
table1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Problem ID", "Name", "Category"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(table1);
if (table1.getColumnModel().getColumnCount() > 0) {
table1.getColumnModel().getColumn(0).setResizable(false);
table1.getColumnModel().getColumn(2).setResizable(false);
}
jLabel7.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel7.setText("Open Problem");
idcombo.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
openpdf.setBackground(new java.awt.Color(204, 255, 204));
openpdf.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
openpdf.setText("Open");
openpdf.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
openpdfActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 564, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(idcombo, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(add, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(jLabel7)
.addGap(0, 83, Short.MAX_VALUE)))
.addContainerGap())
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(47, 47, 47)
.addComponent(openpdf)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 442, Short.MAX_VALUE)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(28, 28, 28)
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(idcombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(openpdf)
.addGap(104, 104, 104)
.addComponent(add, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jTabbedPane1.addTab("Problemsets", jPanel3);
subarea.setColumns(20);
subarea.setRows(5);
subarea.setText("/* In case of Java language, \n the main class must be named as \"M\"+Problem ID */\n\n");
jScrollPane2.setViewportView(subarea);
problang.setBackground(new java.awt.Color(153, 153, 255));
problang.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
problang.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "C", "C++", "Java", " " }));
jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel4.setText("Language");
submit.setBackground(new java.awt.Color(0, 255, 204));
submit.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
submit.setText("Submit");
submit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
submitActionPerformed(evt);
}
});
jLabel6.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel6.setText("Problem ID");
subprobid.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 626, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(submit, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel6)
.addComponent(subprobid, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(10, 10, 10)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(problang, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))))
.addGap(24, 24, 24))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane2))
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(subprobid, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(problang, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(40, 40, 40)
.addComponent(submit)
.addGap(0, 238, Short.MAX_VALUE))
);
jTabbedPane1.addTab("Submit Code", jPanel4);
submissionTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"#", "Problem ID", "User", "Problem name", "Language", "Verdict"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane5.setViewportView(submissionTable);
if (submissionTable.getColumnModel().getColumnCount() > 0) {
submissionTable.getColumnModel().getColumn(0).setResizable(false);
submissionTable.getColumnModel().getColumn(0).setHeaderValue("#");
submissionTable.getColumnModel().getColumn(1).setResizable(false);
submissionTable.getColumnModel().getColumn(1).setHeaderValue("Problem ID");
submissionTable.getColumnModel().getColumn(2).setResizable(false);
submissionTable.getColumnModel().getColumn(2).setHeaderValue("User");
submissionTable.getColumnModel().getColumn(3).setResizable(false);
submissionTable.getColumnModel().getColumn(3).setHeaderValue("Problem name");
submissionTable.getColumnModel().getColumn(4).setResizable(false);
submissionTable.getColumnModel().getColumn(4).setHeaderValue("Language");
submissionTable.getColumnModel().getColumn(5).setResizable(false);
submissionTable.getColumnModel().getColumn(5).setHeaderValue("Verdict");
}
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 773, Short.MAX_VALUE)
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 442, Short.MAX_VALUE)
);
jTabbedPane1.addTab("Submissions", jPanel5);
mysub.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"#", "Problem ID", "Problem Name", "Language", "Verdict"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane6.setViewportView(mysub);
if (mysub.getColumnModel().getColumnCount() > 0) {
mysub.getColumnModel().getColumn(0).setResizable(false);
mysub.getColumnModel().getColumn(1).setResizable(false);
mysub.getColumnModel().getColumn(2).setResizable(false);
mysub.getColumnModel().getColumn(3).setResizable(false);
mysub.getColumnModel().getColumn(4).setResizable(false);
}
javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
jPanel8.setLayout(jPanel8Layout);
jPanel8Layout.setHorizontalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane6, javax.swing.GroupLayout.DEFAULT_SIZE, 773, Short.MAX_VALUE)
);
jPanel8Layout.setVerticalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane6, javax.swing.GroupLayout.DEFAULT_SIZE, 442, Short.MAX_VALUE)
);
jTabbedPane1.addTab("My Submissions", jPanel8);
problinklabel.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
problinklabel.setText("Link");
jLabel10.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel10.setText("Sample Input");
jLabel11.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel11.setText("Sample Output");
category.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
category.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Easy", "Medium", "Hard" }));
indata.setColumns(20);
indata.setRows(5);
jScrollPane3.setViewportView(indata);
outdata.setColumns(20);
outdata.setRows(5);
jScrollPane4.setViewportView(outdata);
addproblem.setBackground(new java.awt.Color(0, 204, 204));
addproblem.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
addproblem.setText("Add");
addproblem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addproblemActionPerformed(evt);
}
});
categorylabel.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
categorylabel.setText("Category");
probidlabel.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
probidlabel.setText("Problem id");
probnamelabel.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
probnamelabel.setText("Problem Name");
javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
jPanel7.setLayout(jPanel7Layout);
jPanel7Layout.setHorizontalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addGap(37, 37, 37)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addGap(1, 1, 1)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel10)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 248, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel11)
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(93, 93, 93))
.addGroup(jPanel7Layout.createSequentialGroup()
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel7Layout.createSequentialGroup()
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(categorylabel)
.addComponent(problinklabel))
.addGap(47, 47, 47)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(problink)
.addGroup(jPanel7Layout.createSequentialGroup()
.addComponent(category, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel7Layout.createSequentialGroup()
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(probnamelabel)
.addComponent(probidlabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(probid, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(probname, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(474, Short.MAX_VALUE))))
.addGroup(jPanel7Layout.createSequentialGroup()
.addGap(316, 316, 316)
.addComponent(addproblem)
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel7Layout.setVerticalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addGap(35, 35, 35)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(probidlabel)
.addComponent(probid, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(probname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(probnamelabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(categorylabel)
.addComponent(category, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(12, 12, 12)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(problink, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(problinklabel))
.addGap(30, 30, 30)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel10)
.addComponent(jLabel11))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE)
.addComponent(jScrollPane3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
.addComponent(addproblem)
.addGap(64, 64, 64))
);
jTabbedPane1.addTab("Add Problem", jPanel7);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTabbedPane1))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTabbedPane1)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
/*try {
BufferedReader out;
out = new BufferedReader(new FileReader("Data\\Probleminfo\\Problems.txt"));
modelproblem=(DefaultTableModel) table1.getModel();
Object[] tablelines = out.lines().toArray();
for(int i=0;i<tablelines.length;i++)
{
String line = tablelines[i].toString().trim();
String[] datarow = line.split(" ");
Object row[]=datarow;
modelproblem.addRow(row);
idcombo.addItem(datarow[0]);
subprobid.addItem(datarow[0]);
}
} catch (IOException ex) {
Logger.getLogger(loginframe.class.getName()).log(Level.SEVERE, null, ex);
}*/
jTabbedPane1.setSelectedIndex(0);
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
jTabbedPane1.setSelectedIndex(1);
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
jTabbedPane1.setSelectedIndex(2);
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
jTabbedPane1.setSelectedIndex(3);
}//GEN-LAST:event_jButton4ActionPerformed
private void addActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addActionPerformed
jTabbedPane1.setSelectedIndex(4);;
}//GEN-LAST:event_addActionPerformed
private void addproblemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addproblemActionPerformed
if(!probid.getText().isEmpty()) {
FileWriter writer1;
FileWriter writer2;
FileWriter writer3;
FileWriter writer4;
// TODO Auto-generated method stub
try {
Files.createDirectories(Paths.get("Data\\Problem\\" +probid.getText()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
writer1 = new FileWriter("Data\\Problem\\" +probid.getText()+"\\"+probid.getText()+"_in.txt");
indata.write(writer1);
writer1.close();
writer2 = new FileWriter("Data\\Problem\\" +probid.getText()+"\\"+probid.getText()+"_out.txt");
outdata.write(writer2);
writer2.close();
writer3 = new FileWriter("Data\\problem\\" +probid.getText()+"\\"+probid.getText()+"_link.txt");
problink.write(writer3);
writer3.close();
writer4 = new FileWriter("Data\\problem\\" +probid.getText()+"\\"+probid.getText()+"_name.txt");
probname.write(writer4);
writer4.close();
String s1 = problink.getText().toString();
String s2 = "Data\\problem\\" +probid.getText()+"\\"+probid.getText()+".pdf";
if(new File(s1).exists()) {
fileCopy(new File(s1), new File(s2));
//new pdfRead().openPdf(new File(s2));
String []value = new String[3];
value[0]=probid.getText().toString();
value[1]=probname.getText().toString();
value[2]=category.getSelectedItem().toString();
Object rowObject[]=value;
modelproblem=(DefaultTableModel) table1.getModel();
modelproblem.addRow(rowObject);
idcombo.addItem(value[0]);
subprobid.addItem(value[0]);
JOptionPane.showMessageDialog(this,"Problem added Succesfully");
clearFields();
new textrecord().writein(value);
//JOptionPane.showMessageDialog(this,"Excel write");
}else {
JOptionPane.showMessageDialog(this,"Error pdf");
}
// try {
// fileCopy(new File(s1), new File(s2));
// } catch (Exception e) {
// // TODO: handle exception
// jp("error pdf");
// }
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}//GEN-LAST:event_addproblemActionPerformed
private void submitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitActionPerformed
if (problang.getSelectedItem().toString().toLowerCase().equals("c")) {
//String codefileString = "data/submitted code/"+"Problem4A"+"."+"java";
String codefileString = subprobid.getSelectedItem() + "." + "c";
FileWriter codeWriter;
try {
codeWriter = new FileWriter(codefileString);
subarea.write(codeWriter);
subarea.setText("/* In case of Java language, \n" +" the main class must be named as \"M\"+Problem ID */\n\n");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
CChecking cChecking = new CChecking((String)subprobid.getSelectedItem()+".c","Data\\Problem\\" +subprobid.getSelectedItem()+"\\"+subprobid.getSelectedItem());
String resultJava = cChecking.compilec();
JOptionPane.showMessageDialog(null,resultJava);
//System.out.println(resultJava);
//System.out.println(sublang.getSelectedItem().toString());
modelsubmission=(DefaultTableModel) submissionTable.getModel();
mysubmission=(DefaultTableModel) mysub.getModel();
Object[] tablelines = null;
Object[] subtablelines = null;
int i=0,j=0;
Scanner st=null;
File a,b;
a = new File("Data\\Submissions\\submissions.txt");
b = new File("Data\\Submissions\\"+user+"sub.txt");
if(!a.exists()){
try {
a.createNewFile();
} catch (IOException ex) {
Logger.getLogger(loginframe.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(!b.exists()){
try {
b.createNewFile();
} catch (IOException ex) {
Logger.getLogger(loginframe.class.getName()).log(Level.SEVERE, null, ex);
}
}
try {
st = new Scanner(new File("Data\\Problem\\"+(String)subprobid.getSelectedItem()+"\\"+(String)subprobid.getSelectedItem()+"_name.txt"));
} catch (FileNotFoundException ex) {
Logger.getLogger(loginframe.class.getName()).log(Level.SEVERE, null, ex);
}
try {
BufferedReader out,subout;
out = new BufferedReader(new FileReader("Data\\Submissions\\submissions.txt"));
subout = new BufferedReader(new FileReader("Data\\Submissions\\"+user+"sub.txt"));
tablelines=out.lines().toArray();
i=tablelines.length;
++i;
subtablelines=subout.lines().toArray();
j=subtablelines.length;
++j;
} catch (FileNotFoundException ex) {
Logger.getLogger(loginframe.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null,"Error");
}
String[] value = new String[6];
String[] val=new String[5];
value[0]=String.valueOf(i);
value[1] = (String) subprobid.getSelectedItem();
value[2] = user;
value[3]=(String)st.next();
value[4] = "C";
value[5]= resultJava;
Object [] v1 = value;
//modelsubmission.
((DefaultTableModel) modelsubmission).addRow(v1);
val[0]=String.valueOf(j);
val[1]=value[1];
val[2]=value[3];
val[3]=value[4];
val[4]=value[5];
Object[] v2 = val;
((DefaultTableModel) mysubmission).addRow(v2);
try {
new textrecord().submission(value);
new textrecord().mysub(val,user);
} catch (FileNotFoundException ex) {
Logger.getLogger(loginframe.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(loginframe.class.getName()).log(Level.SEVERE, null, ex);
}
}
else if (problang.getSelectedItem().toString().toLowerCase().equals("c++")) {
//String codefileString = "data/submitted code/"+"Problem4A"+"."+"java";
String codefileString = subprobid.getSelectedItem() + "." + "cpp";
FileWriter codeWriter;
try {
codeWriter = new FileWriter(codefileString);
subarea.write(codeWriter);
subarea.setText("/* In case of Java language, \n" +" the main class must be named as \"M\"+Problem ID */\n\n");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
CppChecking cChecking = new CppChecking((String)subprobid.getSelectedItem()+".cpp","Data\\Problem\\" +subprobid.getSelectedItem()+"\\"+subprobid.getSelectedItem());
String resultJava = cChecking.compilec();
JOptionPane.showMessageDialog(null,resultJava);
//System.out.println(resultJava);
//System.out.println(sublang.getSelectedItem().toString());
modelsubmission=(DefaultTableModel) submissionTable.getModel();
mysubmission=(DefaultTableModel) mysub.getModel();
Object[] tablelines = null;
Object[] subtablelines = null;
int i=0,j=0;
Scanner st=null;
File a,b;
a = new File("Data\\Submissions\\submissions.txt");
b = new File("Data\\Submissions\\"+user+"sub.txt");
if(!a.exists()){
try {
a.createNewFile();
} catch (IOException ex) {
Logger.getLogger(loginframe.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(!b.exists()){
try {
b.createNewFile();
} catch (IOException ex) {
Logger.getLogger(loginframe.class.getName()).log(Level.SEVERE, null, ex);
}
}
try {
st = new Scanner(new File("Data\\Problem\\"+(String)subprobid.getSelectedItem()+"\\"+(String)subprobid.getSelectedItem()+"_name.txt"));
} catch (FileNotFoundException ex) {
Logger.getLogger(loginframe.class.getName()).log(Level.SEVERE, null, ex);
}
try {
BufferedReader out,subout;
out = new BufferedReader(new FileReader("Data\\Submissions\\submissions.txt"));
subout = new BufferedReader(new FileReader("Data\\Submissions\\"+user+"sub.txt") );
tablelines=out.lines().toArray();
i=tablelines.length;
++i;
subtablelines=subout.lines().toArray();
j=subtablelines.length;
++j;
} catch (FileNotFoundException ex) {
Logger.getLogger(loginframe.class.getName()).log(Level.SEVERE, null, ex);
}
String[] value = new String[6];
String[] val=new String[5];
value[0]=String.valueOf(i);
value[1] = (String) subprobid.getSelectedItem();
value[2] = user;
value[3]=(String)st.next();
value[4] = "C++";
value[5]= resultJava;
Object [] v1 = value;
//modelsubmission.
((DefaultTableModel) modelsubmission).addRow(v1);
val[0]=String.valueOf(j);
val[1]=value[1];
val[2]=value[3];
val[3]=value[4];
val[4]=value[5];
Object[] v2 = val;
((DefaultTableModel) mysubmission).addRow(v2);
try {
new textrecord().submission(value);
new textrecord().mysub(val,user);
} catch (FileNotFoundException ex) {
Logger.getLogger(loginframe.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(loginframe.class.getName()).log(Level.SEVERE, null, ex);
}
}
else if (problang.getSelectedItem().toString().toLowerCase().equals("java")) {
//String codefileString = "data/submitted code/"+"Problem4A"+"."+"java";
String codefileString = "M"+subprobid.getSelectedItem() + "." + "java";
FileWriter codeWriter;
try {
codeWriter = new FileWriter(codefileString);
subarea.write(codeWriter);
subarea.setText("/* In case of Java language, \n" +" the main class must be named as \"M\"+Problem ID */\n\n");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JavaChecking cChecking = new JavaChecking((String)"M"+subprobid.getSelectedItem()+".java","Data\\Problem\\" +subprobid.getSelectedItem()+"\\"+subprobid.getSelectedItem());
String resultJava = cChecking.compilejava();
JOptionPane.showMessageDialog(null,resultJava);
//System.out.println(resultJava);
//System.out.println(sublang.getSelectedItem().toString());
modelsubmission=(DefaultTableModel) submissionTable.getModel();
mysubmission=(DefaultTableModel) mysub.getModel();
Object[] tablelines = null;
Object[] subtablelines = null;
int i=0,j=0;
Scanner st=null;
File a,b;
a = new File("Data\\Submissions\\submissions.txt");
b = new File("Data\\Submissions\\"+user+"sub.txt");
if(!a.exists()){
try {
a.createNewFile();
} catch (IOException ex) {
Logger.getLogger(loginframe.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(!b.exists()){
try {
b.createNewFile();
} catch (IOException ex) {
Logger.getLogger(loginframe.class.getName()).log(Level.SEVERE, null, ex);
}
}
try {
st = new Scanner(new File("Data\\Problem\\"+(String)subprobid.getSelectedItem()+"\\"+(String)subprobid.getSelectedItem()+"_name.txt"));
} catch (FileNotFoundException ex) {
Logger.getLogger(loginframe.class.getName()).log(Level.SEVERE, null, ex);
}
try {
BufferedReader out,subout;
out = new BufferedReader(new FileReader("Data\\Submissions\\submissions.txt"));
subout = new BufferedReader(new FileReader("Data\\Submissions\\"+user+"sub.txt"));
tablelines=out.lines().toArray();
i=tablelines.length;
++i;
subtablelines=subout.lines().toArray();
j=subtablelines.length;
++j;
} catch (FileNotFoundException ex) {
Logger.getLogger(loginframe.class.getName()).log(Level.SEVERE, null, ex);
}
String[] value = new String[6];
String[] val=new String[5];
value[0]=String.valueOf(i);
value[1] = (String) subprobid.getSelectedItem();
value[2] = user;
value[3]=(String)st.next();
value[4] = "Java";
value[5]= resultJava;
Object [] v1 = value;
//modelsubmission.
((DefaultTableModel) modelsubmission).addRow(v1);
val[0]=String.valueOf(j);
val[1]=value[1];
val[2]=value[3];
val[3]=value[4];
val[4]=value[5];
Object[] v2 = val;
((DefaultTableModel) mysubmission).addRow(v2);
try {
new textrecord().submission(value);
new textrecord().mysub(val,user);
} catch (FileNotFoundException ex) {
Logger.getLogger(loginframe.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(loginframe.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_submitActionPerformed
private void openpdfActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openpdfActionPerformed
Object id = idcombo.getSelectedItem();
String idno = (String) id;
try {
openPdf(idno);
} catch (IOException ex) {
Logger.getLogger(loginframe.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_openpdfActionPerformed
private void jLabel1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel1MouseClicked
dispose();
new NewJFrame().setVisible(true);
}//GEN-LAST:event_jLabel1MouseClicked
public void showproblem(){
try {
BufferedReader out;
out = new BufferedReader(new FileReader("Data\\Probleminfo\\Problems.txt"));
modelproblem=(DefaultTableModel) table1.getModel();
Object[] tablelines = out.lines().toArray();
for(int i=0;i<tablelines.length;i++)
{
String line = tablelines[i].toString().trim();
String[] datarow = line.split("\t");
Object row[]=datarow;
modelproblem.addRow(row);
idcombo.addItem(datarow[0]);
subprobid.addItem(datarow[0]);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(loginframe.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void addtosubtable(){
try {
BufferedReader out;
out = new BufferedReader(new FileReader("Data\\Submissions\\submissions.txt"));
modelsubmission=(DefaultTableModel) submissionTable.getModel();
Object[] tablelines = out.lines().toArray();
for(int i=0;i<tablelines.length;i++)
{
String line = tablelines[i].toString().trim();
String[] datarow = line.split(" \t ");
Object row[]=datarow;
modelsubmission.addRow(row);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(loginframe.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void mysub(String us){
try {
BufferedReader out;
out = new BufferedReader(new FileReader("Data\\Submissions\\"+us+"sub.txt"));
mysubmission=(DefaultTableModel) mysub.getModel();
Object[] tablelines = out.lines().toArray();
for(int i=0;i<tablelines.length;i++)
{
String line = tablelines[i].toString().trim();
String[] datarow = line.split(" \t ");
Object row[]=datarow;
mysubmission.addRow(row);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(loginframe.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void clearFields(){
probid.setText(null);
probname.setText(null);
problink.setText(null);
indata.setText(null);
outdata.setText(null);
}
public void openPdf(String s) throws IOException {
try {
File pdf = new File("Data\\Problem\\"+s+"\\"+s+".pdf");
//File pdf = new File("data\\problem\\"+s+".pdf");
//File pdf = new File("E:\\practice\\java swing practice\\swing practice\\data\\problem\\codef.pdf");
//File pdf = new File("C:\\Users\\MD. Fahim Faisal\\Documents\\dadospdf.com_problem-4a-codeforces-.pdf");
if(pdf.exists()) {
if(Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(pdf);
}else {
JOptionPane.showMessageDialog(null,"error to open pdf");
}
}else {
JOptionPane.showMessageDialog(null,"error to open pdf");
}
} catch (Exception e) {
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(null,"error to open pdf");
e.printStackTrace();
}
}
public void fileCopy(File src,File dst) throws IOException {
Files.copy(src.toPath(), dst.toPath());
}
/**
*
*/
/**
* @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(loginframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(loginframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(loginframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(loginframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new loginframe().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton add;
private javax.swing.JButton addproblem;
private javax.swing.JComboBox<String> category;
private javax.swing.JLabel categorylabel;
private javax.swing.JComboBox<String> idcombo;
private javax.swing.JTextArea indata;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel7;
private javax.swing.JPanel jPanel8;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JScrollPane jScrollPane5;
private javax.swing.JScrollPane jScrollPane6;
private javax.swing.JTabbedPane jTabbedPane1;
private javax.swing.JTable mysub;
private javax.swing.JButton openpdf;
private javax.swing.JTextArea outdata;
private javax.swing.JTextField probid;
private javax.swing.JLabel probidlabel;
private javax.swing.JComboBox<String> problang;
private javax.swing.JTextField problink;
private javax.swing.JLabel problinklabel;
private javax.swing.JTextField probname;
private javax.swing.JLabel probnamelabel;
private javax.swing.JTextArea subarea;
private javax.swing.JTable submissionTable;
private javax.swing.JButton submit;
private javax.swing.JComboBox<String> subprobid;
private javax.swing.JTable table1;
// End of variables declaration//GEN-END:variables
DefaultTableModel modelsubmission, modelproblem, mysubmission;
String user;
} |
package com.oa.bbs.dao;
import java.util.List;
import com.oa.bbs.form.Forum;
import com.oa.page.form.Page;
public interface ForumDao {
public void addForum(Forum forum);
public void updateForum(Forum forum);
public void deleteForum(int forumId);
public List<Forum> findAllForumByUserId(Integer userId);
public Forum findForumById(Integer forumId);
public List<Forum> findForumByPage(Page page);
public List<Forum> findForums();
}
|
package perdonin.renaissance;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import perdonin.renaissance.screen.ScreenManager;
public class MyGame extends ApplicationAdapter {
public ScreenManager sm;
public AssetManager assets;
@Override
public void create () {
sm = new ScreenManager(this);
sm.setScreen(ScreenManager.ScreenType.SPLASH);
Gdx.input.setCatchBackKey(false);
}
@Override
public void render () {
sm.update(Gdx.graphics.getDeltaTime());
}
@Override
public void resize(int width, int height) {
super.resize(width, height);
sm.viewport.update(width, height);
}
@Override
public void dispose () {
}
}
|
package nl.topicus.wqplot.options;
import java.io.Serializable;
import nl.topicus.wqplot.components.plugins.IRenderer;
import org.codehaus.jackson.annotate.JsonAutoDetect;
import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
@JsonSerialize(include = Inclusion.NON_NULL)
public class PlotCursor implements Serializable
{
private static final long serialVersionUID = 1L;
private String style;
private Boolean zoom;
private Boolean show;
private Boolean showTooltip;
private Boolean followMouse;
private PlotTooltipLocation tooltipLocation;
private Integer tooltipOffset;
private Boolean showTooltipGridPosition;
private Boolean showTooltipUnitPosition;
private String tooltipFormatString;
private Boolean useAxesFormatters;
// private String[] tooltipAxesGroups;
@JsonSerialize(using = PluginReferenceSerializer.class, include = Inclusion.NON_NULL)
private String renderer;
public PlotCursor()
{
renderer = "$.jqplot.Cursor";
}
public String getStyle()
{
return style;
}
public PlotCursor setStyle(String style)
{
this.style = style;
return this;
}
public Boolean getZoom()
{
return zoom;
}
public PlotCursor setZoom(Boolean zoom)
{
this.zoom = zoom;
return this;
}
public Boolean getShow()
{
return show;
}
public PlotCursor setShow(Boolean show)
{
this.show = show;
return this;
}
public Boolean getShowTooltip()
{
return showTooltip;
}
public PlotCursor setShowTooltip(Boolean showTooltip)
{
this.showTooltip = showTooltip;
return this;
}
public Boolean getFollowMouse()
{
return followMouse;
}
public PlotCursor setFollowMouse(Boolean followMouse)
{
this.followMouse = followMouse;
return this;
}
public PlotTooltipLocation getTooltipLocation()
{
return tooltipLocation;
}
public PlotCursor setTooltipLocation(PlotTooltipLocation tooltipLocation)
{
this.tooltipLocation = tooltipLocation;
return this;
}
public Integer getTooltipOffset()
{
return tooltipOffset;
}
public PlotCursor setTooltipOffset(Integer tooltipOffset)
{
this.tooltipOffset = tooltipOffset;
return this;
}
public Boolean getShowTooltipGridPosition()
{
return showTooltipGridPosition;
}
public PlotCursor setShowTooltipGridPosition(Boolean showTooltipGridPosition)
{
this.showTooltipGridPosition = showTooltipGridPosition;
return this;
}
public Boolean getShowTooltipUnitPosition()
{
return showTooltipUnitPosition;
}
public PlotCursor setShowTooltipUnitPosition(Boolean showTooltipUnitPosition)
{
this.showTooltipUnitPosition = showTooltipUnitPosition;
return this;
}
public String getTooltipFormatString()
{
return tooltipFormatString;
}
public PlotCursor setTooltipFormatString(String tooltipFormatString)
{
this.tooltipFormatString = tooltipFormatString;
return this;
}
public Boolean getUseAxesFormatters()
{
return useAxesFormatters;
}
public PlotCursor setUseAxesFormatters(Boolean useAxesFormatters)
{
this.useAxesFormatters = useAxesFormatters;
return this;
}
public String getRenderer()
{
return renderer;
}
public PlotCursor setRenderer(String renderer)
{
this.renderer = renderer;
return this;
}
public PlotCursor setRenderer(IRenderer renderer)
{
this.renderer = renderer.getName();
return this;
}
}
|
package de.codecentric.cvgenerator;
import org.springframework.data.jpa.repository.JpaRepository;
public interface QualificationRepository extends JpaRepository<Qualification, Integer>{
}
|
package org.giddap.dreamfactory.leetcode.onlinejudge.implementations;
import org.giddap.dreamfactory.leetcode.commons.TreeLinkNode;
import org.giddap.dreamfactory.leetcode.onlinejudge.PopulatingNextRightPointersInEachNodeII;
public class PopulatingNextRightPointersInEachNodeIIRecursiveImpl implements PopulatingNextRightPointersInEachNodeII {
@Override
public void connect(TreeLinkNode root) {
if (root == null) {
return;
}
TreeLinkNode curr = root;
TreeLinkNode prev = null;
while (curr != null) {
if (curr.left != null) {
if (prev != null) {
prev.next = curr.left;
}
prev = curr.left;
}
if (curr.right != null) {
if (prev != null) {
prev.next = curr.right;
}
prev = curr.right;
}
curr = curr.next;
}
connect(root.left);
connect(root.right);
}
}
|
package ca.pluszero.headphoneviewer;
import java.util.List;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.nostra13.universalimageloader.core.ImageLoader;
public class ImageTextListAdapter extends BaseAdapter {
private final Activity context;
private final List<Product> products;
private final ImageLoader imageLoader;
public ImageTextListAdapter(Activity context, List<Product> products, ImageLoader imageLoader) {
this.context = context;
this.products = products;
this.imageLoader = imageLoader;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.row_card, null, true);
Product product = products.get(position);
TextView txtTitle = (TextView) rowView.findViewById(R.id.tvProductName);
txtTitle.setText(product.getName());
TextView txtPrice = (TextView) rowView.findViewById(R.id.tvPrice);
txtPrice.setText("$" + product.getPrice());
ImageView imageView = (ImageView) rowView.findViewById(R.id.ivProduct);
imageLoader.displayImage(product.getImageUrl(), imageView);
return rowView;
}
@Override
public int getCount() {
return products.size();
}
@Override
public Object getItem(int position) {
return products.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
}
|
/*
* Welcome to use the TableGo Tools.
*
* http://vipbooks.iteye.com
* http://blog.csdn.net/vipbooks
* http://www.cnblogs.com/vipbooks
*
* Author:bianj
* Email:edinsker@163.com
* Version:5.8.0
*/
package com.lenovohit.hwe.org.model;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.lenovohit.hwe.base.model.AuditableModel;
/**
* HWE_DEPT
*
* @author zyus
* @version 1.0.0 2017-12-14
*/
@Entity
@Table(name = "HWE_DEPT")
public class Dept extends AuditableModel implements java.io.Serializable {
/** 版本号 */
private static final long serialVersionUID = -7822834764786404969L;
/** name */
private String name;
/** 便于程序编码实现的代码 */
private String code;
/** description */
private String description;
/** status */
private String status;
/** org */
private Org org;
/** parent */
private Dept parent;
private Set<Dept> children;
private Set<Post> posts;
private Set<User> users;
/**
* 获取name
*
* @return name
*/
@Column(name = "NAME", nullable = true, length = 32)
public String getName() {
return this.name;
}
/**
* 设置name
*
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* 获取便于程序编码实现的代码
*
* @return 便于程序编码实现的代码
*/
@Column(name = "CODE", nullable = false, length = 50)
public String getCode() {
return this.code;
}
/**
* 设置便于程序编码实现的代码
*
* @param code
* 便于程序编码实现的代码
*/
public void setCode(String code) {
this.code = code;
}
/**
* 获取description
*
* @return description
*/
@Column(name = "DESCRIPTION", nullable = true, length = 255)
public String getDescription() {
return this.description;
}
/**
* 设置description
*
* @param description
*/
public void setDescription(String description) {
this.description = description;
}
/**
* 获取status
*
* @return status
*/
@Column(name = "STATUS", nullable = true, length = 1)
public String getStatus() {
return this.status;
}
/**
* 设置status
*
* @param status
*/
public void setStatus(String status) {
this.status = status;
}
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "ORG_ID")
@NotFound(action=NotFoundAction.IGNORE)
public Org getOrg() {
return org;
}
public void setOrg(Org org) {
this.org = org;
}
@ManyToOne(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY, optional = true)
@JoinColumn(name = "PARENT_ID", nullable = true)
@NotFound(action=NotFoundAction.IGNORE)
public Dept getParent() {
return parent;
}
public void setParent(Dept parent) {
this.parent = parent;
}
@Transient
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
@Transient
public Set<Post> getPosts() {
return posts;
}
public void setPosts(Set<Post> posts) {
this.posts = posts;
}
@Transient
@JsonIgnoreProperties({"parent","children","org","posts","users"})
public Set<Dept> getChildren() {
if(null == children)
children= new HashSet<Dept>();
return children;
}
public void setChildren(Set<Dept> children) {
this.children = children;
}
} |
/*
* Scott
*/
package lab2;
/**
*
* @ Scott
*/
public interface Course {
public abstract String CourseName();
public abstract String CourseNumber();
public abstract double CourseCredits();
public abstract String Prerequisites();
} |
package com.wrathOfLoD.Models.Map.AreaEffect;
import com.wrathOfLoD.Models.Entity.Entity;
import com.wrathOfLoD.VisitorInterfaces.AreaEffectVisitor;
/**
* Created by luluding on 4/16/16.
*/
public class HealDamageAreaEffect extends AreaEffect {
private int healAmount;
public HealDamageAreaEffect(String name, int healAmount){
super(name);
this.healAmount = healAmount;
}
@Override
public void interact(Entity entity) {
entity.heal(healAmount);
}
public void accept(AreaEffectVisitor aev){
aev.visitHealDamageAreaEffect(this);
}
}
|
package Getters_Setters;
public class __Setter_serverRESPONSE {
}
|
package com.hesen.crawler.task;
import com.hesen.crawler.BaseTest;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
public class testItemTask extends BaseTest {
@Autowired
private ItemTaskJD itemTaskJD;
@Autowired
private ItemTaskTM itemTaskTM;
@Test
public void testTaskJD() throws Exception {
itemTaskJD.itemTask();
}
@Test
public void testTaskTM() throws Exception {
itemTaskTM.itemTask();
}
}
|
package com.record.model;
import java.sql.Timestamp;
import java.util.List;
public interface RecordDAO_interface {
public void insert(RecordVO recordVO);
public void update(RecordVO recordVO);
public void delete(Timestamp start_time ,String mem_no);
public List<RecordVO> findByPrimaryKey(String mem_no);
public RecordVO findByTwoPrimaryKeys (String mem_no , Timestamp start_time);
public List<RecordVO> getAll();
public List<RecordVO> findByPKAndRouteNo (String mem_no , String route_no);
}
|
package en00a;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Q05 {
public static void main(String[] args) {
String output;
Date date = new Date();
DateFormat dft2;
dft2 = new SimpleDateFormat("yyyy年M月d日(E)H時mm分ss秒");
output = dft2.format(date);
System.out.println(output);
}
}
|
package ca.uot.scs2682.marvelcatalog.ui.creators;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import ca.uot.scs2682.marvelcatalog.R;
import ca.uot.scs2682.marvelcatalog.data.Creator;
/**
* Created by ricardohidekiyamamoto on 2017-04-02.
*/
public class CreatorsListCellViewHolder extends RecyclerView.ViewHolder {
private final TextView creatorName;
private final TextView creatorRole;
public CreatorsListCellViewHolder(View itemView){
super(itemView);
this.creatorName = (TextView) itemView.findViewById(R.id.creatorName);
this.creatorRole = (TextView) itemView.findViewById(R.id.creatorRole);
}
public void update(Creator creator){
creatorName.setText(creator.name);
creatorRole.setText(creator.role);
}
}
|
package com.sh.offer.stack;
import java.util.LinkedList;
import java.util.Stack;
/**
* @Auther: bjshaohang
* @Date: 2019/1/31
*/
public class GetMin {
private Stack<Integer> stack1 = new Stack<>();
private Stack<Integer> stack2 = new Stack<>();
private int min;
public static void main(String[] args) {
GetMin stack = new GetMin();
stack.push(3);
System.out.println(stack.min());
stack.push(4);
System.out.println(stack.min());
stack.push(2);
System.out.println(stack.min());
stack.push(3);
System.out.println(stack.min());
stack.pop();
System.out.println(stack.min());
stack.pop();
System.out.println(stack.min());
stack.pop();
System.out.println(stack.min());
stack.push(0);
System.out.println(stack.min());
}
public void push(int node) {
stack1.push(node);
if(node > min){
if(stack2.empty()){
stack2.push(node);
min = node;
}else {
stack2.push(min);
}
}else {
stack2.push(node);
min = node;
}
}
public void pop() {
stack1.pop();
stack2.pop();
}
public int top() {
return stack1.peek();
}
public int min() {
return stack2.peek();
}
}
|
package com.yxkj.facexradix.utils;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import com.yxdz.commonlib.util.SPUtils;
import com.yxkj.facexradix.MyApplication;
import com.yxkj.facexradix.Constants;
/**
* @PackageName: com.yxdz.facex.utils
* @Desription:
* @Author: Dreamcoding
* @CreatDate: 2019/3/12 16:06
*/
public class AppErrorUtil {
public static void toCameraError(){
int error= SPUtils.getInstance().getInt(Constants.CAMERA_ERROR_REMOVE,0);
if (error==5){
//被移除了5次
SPUtils.getInstance().put(Constants.CAMERA_ERROR_REMOVE,0);
// MyApplication.getFireflyApi().reboot();
}else{
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent resetAppIntent = MyApplication.getAppContext().getPackageManager()
.getLaunchIntentForPackage(MyApplication.getAppContext().getPackageName());
PendingIntent restartIntent = PendingIntent.getActivity(MyApplication.getAppContext(), 0, resetAppIntent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager mgr = (AlarmManager)MyApplication.getAppContext().getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 5000, restartIntent);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
}
},5000);
}
}
}
|
package com.thegriffen.projectsoaringgriffen;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.thegriffen.projectsoaringgriffen.utils.CustomAdapter;
import com.thegriffen.projectsoaringgriffen.utils.DatabaseHandler;
import com.thegriffen.projectsoaringgriffen.utils.Entry;
import com.thegriffen.projectsoaringgriffen.utils.TimeCalculator;
public class ListViewActivity extends ActionBarActivity {
ListView list;
List<String> dateArray;
List<Integer> imageArray;
List<Integer> idArray;
List<String> timeArray;
DatabaseHandler db;
CustomAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
final Context context = this;
dateArray = new ArrayList<String>();
imageArray = new ArrayList<Integer>();
timeArray = new ArrayList<String>();
idArray = new ArrayList<Integer>();
db = new DatabaseHandler(this);
adapter = new CustomAdapter(ListViewActivity.this, dateArray, imageArray, timeArray);
getListData();
list = (ListView)findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(context, ViewEntryActivity.class);
intent.putExtra("entryId", idArray.get(position));
startActivity(intent);
}
});
setTitle("My Log");
}
private void getListData() {
List<Entry> entries = db.getAllEntries();
dateArray.clear();
imageArray.clear();
timeArray.clear();
idArray.clear();
for (Entry entry : entries) {
idArray.add(entry.getID());
dateArray.add(entry.getDate());
imageArray.add(entry.getImage());
timeArray.add(new TimeCalculator(entry.getStartTime(), entry.getEndTime()).calculate());
}
adapter.notifyDataSetChanged();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.actionbar_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.new_item:
newEntry();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onPause() {
super.onPause();
db.close();
}
private void newEntry() {
Intent intent = new Intent(this, NewEntryActivity.class);
startActivity(intent);
}
} |
package com.github.dongchan.scheduler;
import com.github.dongchan.scheduler.stats.StatsRegistry;
import com.github.dongchan.scheduler.task.Task;
import com.github.dongchan.scheduler.task.helper.OneTimeTask;
import com.github.dongchan.scheduler.testhelper.SettableClock;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
/**
* @author DongChan
* @date 2020/10/22
* @time 11:19 PM
*/
public class SchedulerTest {
private TestTasks.CountingHandler<Void> handler;
private SettableClock clock;
@BeforeEach
public void setUp(){
handler = new TestTasks.CountingHandler<>();
}
private Scheduler schedulerFor(ExecutorService executor, Task<?>... tasks){
final StatsRegistry statsRegistry = StatsRegistry.NOOP;
// JdbcTaskRepository taskRepository = new JdbcTaskRepository()
// return new Scheduler(clock, )
return null;
}
@Test
public void scheduler_should_execute_task_when_exactly_due(){
OneTimeTask<Void> oneTimeTask = TestTasks.oneTime("OneTime", Void.class, handler);
assertThat(handler.timesExecuted.get(), is(0));
assertThat(handler.timesExecuted.get(), is(1));
}
@Test
public void scheduleShouldExecuteRecurringTaskAndReschedule(){
// RecurringTask<Void> recurringTask = TestTasks.recurring("Recurring", FixedDelay.of(Duration.ofHours(1)));
}
}
|
package com.bleuart.demo;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import com.bleuart.lib.bleApi;
import com.bleuart.lib.iCallback;
import com.bleuart.lib.util.Util;
import com.bleuart.winksoft.idcardcer.bean.IdCardBean;
import com.bleuart.winksoft.idcardcer.callback.IReadIdCardCallBack;
import com.bleuart.winksoft.idcardcer.main.IDCardAuthTask;
import com.bleuart.winksoft.idcardcer.util.ByteUtils;
import com.bleuart.winksoft.idcardcer.util.decode;
import com.bleuart.winksoft.reader.IRec4Socket;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
public class BTActivity extends Activity {
private Object mObject = new Object();
protected static final String TAG = BTActivity.class.getSimpleName();
private BluetoothManager mBluetoothManager = null;
private static BluetoothAdapter mBluetoothAdapter = null;
public static BluetoothGatt mBluetoothGatt = null;
public static final String EXTRAS_DEVICE_NAME = "deviceName";
public static final String EXTRAS_DEVICE_ADDRESS = "deviceAddress";
private boolean dataRecvFlag = false;
private String deviceName;
private String deviceAddress;
public static byte[] card_infor = null;
/**
* connection state
*/
private boolean mConnected = false;
/**
* scan all Service ?
*/
private boolean isInitialize = false;
private static final int MAX_DATA_SIZE = 40 * 6;
// / public
private TextView textDeviceName;
private TextView textDeviceAddress;
private TextView textDeviceState;
private TextView textDataReceived;
// / start
protected static String uuidService = "0000cc01-0000-1000-8000-00805f9b34fb";
protected static String uuidCharWrite = "0000cd01-0000-1000-8000-00805f9b34fb";
private long SumDataReceived = 0; // / summary of data received.
private long RecvDataTime = 0;
private static BTActivity mActivity = null;
private ScrollView sclv_Debug;
private Button btn_Clear_Message;
private Button btn_Send;
private EditText edit_Data;
private ClickHandler click = null;
public static String currentAction = "";
private String dev_sn = "";
private String mReaderData;
private static String mCmdStr;
private int mTs;
private int mTs1;
private boolean isStep3 = false;
private int step3Count = 6;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mActivity = this;
SetScreen(mActivity, 1);
// Does not enter sleep
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
| WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
click = new ClickHandler();
findView();
}
private void findView() {
sclv_Debug = (ScrollView) findViewById(R.id.sclv_debug);
btn_Clear_Message = (Button) findViewById(R.id.btn_clear_message);
btn_Clear_Message.setOnClickListener(click);
btn_Send = (Button) findViewById(R.id.btn_send);
btn_Send.setOnClickListener(click);
edit_Data = (EditText) findViewById(R.id.et_data);
edit_Data.setText("1B000225211D");
// Get Version "1B000225211D"
textDeviceName = (TextView) findViewById(R.id.label_device_name);
textDeviceAddress = (TextView) findViewById(R.id.label_device_address);
textDeviceState = (TextView) findViewById(R.id.label_state);
textDataReceived = (TextView) findViewById(R.id.label_data_received);
deviceName = getIntent().getExtras().getString(EXTRAS_DEVICE_NAME);
deviceAddress = getIntent().getExtras().getString(EXTRAS_DEVICE_ADDRESS);
textDeviceName.setText(deviceName);
textDeviceAddress.setText(deviceAddress);
if (!initialize()) {
Log.e(TAG, "Unable to initialize Bluetooth");
finish();
}
bleApi.setCallback(new iCallback() {
public void onReceiveData(BluetoothGatt mBluetoothGatt, String UUIDForNotifyChar, String Data) {
if (!dataRecvFlag) {
handlerDataRate.postDelayed(runnableDataRate, 1000);
dataRecvFlag = true;
}
SumDataReceived = SumDataReceived + Data.length();
setNotify(Data);
Log.d(TAG, "onReceiveData: " + Data);
mReaderData = Data;
Log.d(TAG, "onReceiveData: count" + mTs);
Log.d(TAG, "onReceiveData: 循环次数" + mTs1);
synchronized (mObject) {
mObject.notify();
}
}
});
}
private void setNotify(final String errStr) {
runOnUiThread(new Runnable() {
@Override
public void run() {
textDataReceived.setText(errStr);
sclv_Debug.post(new Runnable() {
@Override
public void run() {
sclv_Debug.fullScroll(View.FOCUS_DOWN);
}
});
}
});
}
public void SetScreen(Activity sComboActivity, int dir) {
if (dir == 0)
sComboActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
else
sComboActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
final Handler handlerDataRate = new Handler();
final Runnable runnableDataRate = new Runnable() {
public void run() {
RecvDataTime++;
// PutMessage(" " + SumDataReceived / RecvDataTime + " Bps");
dataRecvFlag = false;
}
};
private class ClickHandler implements OnClickListener {
@Override
public void onClick(View v) {
if (v == btn_Clear_Message) {
textDataReceived.setText("");
} else if (v == btn_Send) {
new IDCardAuthTask(
new IRec4Socket() {
@Override
public byte[] rec_login_send_step1() {
mCmdStr = "0001000100";
sendData();
Log.d(TAG, "rec_login_send_step1: " + mReaderData);
return ByteUtils.hexToByte(mReaderData);
}
@Override
public byte[] rec_step1_send_step2(byte[] IDINFO) {
mCmdStr = "00020011010F" + ByteUtils.byteToHex(IDINFO);
sendData();
Log.d(TAG, "rec_step1_send_step2: " + mReaderData);
return ByteUtils.hexToByte(mReaderData);
}
@Override
public byte[] rec_step2_send_step3(byte[] IDINFO) {
isStep3 = true;
Log.d(TAG, "rec_step2_send_step3: " + ByteUtils.byteToHex(IDINFO));
mCmdStr = "00030011010F" + ByteUtils.byteToHex(IDINFO);
// .substring(0, ByteUtils.byteToHex(IDINFO).length() - 2);
sendData();
Log.d(TAG, "rec_step2_send_step3: " + mReaderData);
return ByteUtils.hexToByte(mReaderData);
}
@Override
public byte[] send_step4() {
isStep3 = false;
mCmdStr = "0004000100";
sendData();
Log.d(TAG, "send_step4: " + mReaderData);
return ByteUtils.hexToByte(mReaderData);
}
@Override
public byte[] rec_step4_send_step5(byte[] IDINFO) {
isStep3 = false;
mCmdStr = "00050011010F" + ByteUtils.byteToHex(IDINFO);
sendData();
Log.d(TAG, "rec_step4_send_step5: " + mReaderData);
return ByteUtils.hexToByte(mReaderData);
}
@Override
public void rec_step5(byte[] IDINFO) {
isStep3 = false;
Log.d(TAG, "rec_step5: " + ByteUtils.byteToHex(IDINFO));
if (IDINFO == null) {
card_infor = null;
return;
}
if (IDINFO.length > 1000) {
byte[] temp = new byte[IDINFO.length - 10];
System.arraycopy(IDINFO, 10, temp, 0, IDINFO.length - 10);
card_infor = temp;
} else {
card_infor = null;
}
decode d = new decode(card_infor);
Log.d(TAG, "rec_step5: name " + d.name());
}
}, new IReadIdCardCallBack() {
@Override
public void onStartRead() {
}
@Override
public void onSuccess(IdCardBean idCardBean) {
}
@Override
public void onFail(int errCode, String errMsg) {
Log.d(TAG, "onFail: " + errMsg);
}
@Override
public void onConnectSuccess() {
Log.d(TAG, "onConnectSuccess: 连接成功 ");
}
@Override
public void onConnectClose() {
Log.d(TAG, "onConnectSuccess: 连接关闭 ");
}
}, "192.168.0.164", 8988
).execute();
}
}
}
/**
* 进行SHA加密
*
* @param info 要加密的信息
* @return String 加密后的字符串
*/
public String encryptToSHA(String info) {
byte[] digesta = null;
try {
// 得到一个SHA-1的消息摘要
MessageDigest alga = MessageDigest.getInstance("SHA-1");
// 添加要进行计算摘要的信息
alga.update(info.getBytes());
// 得到该摘要
digesta = alga.digest();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// 将摘要转为字符串
String rs = Util.byte2hex(digesta);
return rs;
}
private boolean initialize() {
// For API level 18 and above, get a reference to BluetoothAdapter
// through BluetoothManager.
if (mBluetoothManager == null) {
mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
if (mBluetoothManager == null) {
Log.e(TAG, "Unable to initialize BluetoothManager.");
return false;
}
}
mBluetoothAdapter = mBluetoothManager.getAdapter();
if (mBluetoothAdapter == null) {
Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
return false;
}
return true;
}
public static void PrintBytes(byte[] bytes) {
if (bytes == null)
return;
final StringBuilder stringBuilder = new StringBuilder(bytes.length);
for (byte byteChar : bytes)
stringBuilder.append(String.format("%02X ", byteChar));
Log.i(TAG, " :" + stringBuilder.toString());
}
void sendData() {
// Thread sendDataThread = new Thread(runnableSend);
// sendDataThread.start();
SendNextData();
}
byte[] getPackageData() {
String strInput;
// strInput = edit_Data.getText().toString();
strInput = mCmdStr;
Log.d(TAG, "getPackageData: mCmdStr " + mCmdStr);
if (strInput.length() == 0)
return null;
if (strInput.length() % 2 == 1) {
strInput = "0" + strInput;
}
return Util.hexStringToByteArray(strInput);
}
private boolean SendNextData() {
byte[] data = getPackageData();
if (data == null) {
Log.e(TAG, "data is empty");
return false;
}
int length = data.length;
Log.e(TAG, "data.length" + data.length);
int count = 0;
int offset = 0;
mTs1 = 0;
while (offset < length) {
mTs1 += 1;
if ((length - offset) < bleApi.ServerBufferSize) {
count = length - offset;
Log.e(TAG, "count" + count);
Log.e(TAG, "length" + length);
Log.e(TAG, "offset" + offset);
} else {
count = bleApi.ServerBufferSize;
}
byte tempArray[] = new byte[count];
System.arraycopy(data, offset, tempArray, 0, count);
PrintBytes(tempArray);
bleApi.SendData(mBluetoothGatt, tempArray);
offset = offset + count;
Log.e(TAG, "offset" + offset);
Log.e(TAG, "count" + count);
mTs = count;
try {
Thread.sleep(80);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
synchronized (mObject) {
try {
mObject.wait(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return true;
}
final Runnable runnableSend = new Runnable() {
byte[] getPackageData() {
String strInput;
strInput = edit_Data.getText().toString();
if (strInput.length() == 0)
return null;
if (strInput.length() % 2 == 1) {
strInput = "0" + strInput;
}
return Util.hexStringToByteArray(strInput);
}
private boolean SendNextData() {
byte[] data = getPackageData();
if (data == null) {
Log.e(TAG, "data is empty");
return false;
}
int length = data.length;
Log.e(TAG, "data.length" + data.length);
int count = 0;
int offset = 0;
while (offset < length) {
if ((length - offset) < bleApi.ServerBufferSize) {
count = length - offset;
Log.e(TAG, "count" + count);
Log.e(TAG, "length" + length);
Log.e(TAG, "offset" + offset);
} else {
count = bleApi.ServerBufferSize;
}
byte tempArray[] = new byte[count];
System.arraycopy(data, offset, tempArray, 0, count);
PrintBytes(tempArray);
bleApi.SendData(mBluetoothGatt, tempArray);
offset = offset + count;
Log.e(TAG, "offset" + offset);
Log.e(TAG, "count" + count);
try {
Thread.sleep(80);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return true;
}
public void run() {
SendNextData();
}
};
private void clearHandler(Handler handler, Runnable runner) {
if (handler != null) {
handler.removeCallbacks(runner);
handler = null;
}
}
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
Log.i(TAG, "onConnectionStateChange : " + status + " newState : " + newState);
if (newState == BluetoothProfile.STATE_CONNECTED) {
mBluetoothGatt.discoverServices();
mConnected = true;
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
mConnected = false;
clearHandler(handlerDataRate, runnableDataRate);
dataRecvFlag = false;
close();
}
invalidateOptionsMenu();
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (bleApi.Enable(mBluetoothGatt, uuidService, uuidCharWrite)) {
isInitialize = true;
} else {
isInitialize = false;
}
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
bleApi.updateValueForNotification(gatt, characteristic);
}
@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
// super.onDescriptorWrite(gatt, descriptor, status);
Log.w(TAG, "onDescriptorWrite");
bleApi.setNextNotify(gatt, true);
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
// super.onCharacteristicWrite(gatt, characteristic, status);
if (status == BluetoothGatt.GATT_SUCCESS) {
} else {
Log.e(TAG, "Send failed!!!!");
}
}
};
public boolean connect(final String address) {
if (mBluetoothAdapter == null || address == null) {
Log.w("Qn Dbg", "BluetoothAdapter not initialized or unspecified address.");
return false;
}
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
if (device == null) {
Log.w(TAG, "Device not found. Unable to connect.");
return false;
}
// setting the autoConnect parameter to false.
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
Log.d(TAG, "Trying to create a new connection. Gatt: " + mBluetoothGatt);
return true;
}
public void disconnect() {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w("Qn Dbg", "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.disconnect();
}
public void close() {
if (mBluetoothGatt != null) {
mBluetoothGatt.close();
mBluetoothGatt = null;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.connect, menu);
if (mConnected) {
textDeviceState.setText("BLE connected");
menu.findItem(R.id.menu_connect).setVisible(false);
menu.findItem(R.id.menu_disconnect).setVisible(true);
} else {
menu.findItem(R.id.menu_connect).setVisible(true);
menu.findItem(R.id.menu_disconnect).setVisible(false);
textDeviceState.setText("BLE Not connected");
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_connect:
connect(deviceAddress);
return true;
case R.id.menu_disconnect:
disconnect();
return true;
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onResume() {
super.onResume();
if (!mConnected) {
invalidateOptionsMenu();
connect(deviceAddress);
}
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
clearHandler(handlerDataRate, runnableDataRate);
close();
}
}
|
package spigot.greg.bwaddon;
import org.bukkit.plugin.java.JavaPlugin;
import org.screamingsandals.bedwars.Main;
import spigot.greg.bwaddon.gameSelectNpc.GameSelector;
public final class BwAddon extends JavaPlugin {
private static BwAddon plugin;
private static Tournament tournament;
@Override
public void onEnable() {
plugin = this;
tournament = new Tournament();
tournament.load();
getServer().getPluginManager().registerEvents(new BedwarsListener(), this);
new AdminCommands();
getCommand("jointournamentround").setExecutor(new GameSelector());
I18n.load(this, Main.getConfigurator().config.getString("locale"));
}
@Override
public void onDisable() {
Main.getCommands().remove("tournament");
}
public static BwAddon getInstance() {
return plugin;
}
public static Tournament getTournament() {
return tournament;
}
}
|
package Interface;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import static java.awt.image.ImageObserver.ERROR;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public final class Ventana extends JFrame
{
private OutputStream Output = null;
SerialPort serialPort;
private final String PORT_NAME = "COM3";
private static final int TIME_OUT = 2000;
private static final int DATA_RATE = 9600;
private final JButton btnEnviarTexto,btnCerrar;
private static JTextField txtMensaje;
private final JLabel labelTitle;
public Ventana()
{
btnEnviarTexto = new JButton("Enviar");
txtMensaje = new JTextField();
btnCerrar = new JButton("Cerrar");
labelTitle = new JLabel("Inserte su mensaje aqui");
initializeArduinoConnection();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(350,250);
this.setUndecorated(true);
this.setVisible(true);
this.setLocationRelativeTo(null);
this.setLayout(null);
this.add(btnEnviarTexto);
this.add(txtMensaje);
this.add(btnCerrar);
this.add(labelTitle);
labelTitle.setBounds(30,20,250,20);
txtMensaje.setBounds(50,50,250,30);
btnEnviarTexto.setBounds(110, 110, 100, 30);
btnCerrar.setBounds(110, 150, 100, 30);
Escuchas();
}
public void initializeArduinoConnection()
{
CommPortIdentifier portId = null;
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
while (portEnum.hasMoreElements())
{
CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
if (PORT_NAME.equals(currPortId.getName()))
{
portId = currPortId;
break;
}
}
if (portId == null)
{
showError(PORT_NAME);
System.exit(ERROR);
return;
}
try
{
serialPort = (SerialPort) portId.open(this.getClass().getName(), TIME_OUT);
serialPort.setSerialPortParams(DATA_RATE,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
Output = serialPort.getOutputStream();
} catch (Exception e) {
System.exit(ERROR);
}
}
private void showError(String errorMessage){
JOptionPane.showMessageDialog(null,errorMessage,"Error",JOptionPane.ERROR_MESSAGE);
}
private void Escuchas(){
btnEnviarTexto.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent ev)
{
String data = txtMensaje.getText();
txtMensaje.setText(null);
try
{
Output.write(data.getBytes());
}
catch (IOException ex)
{
System.exit(ERROR);
}
}
});
txtMensaje.addKeyListener(new KeyAdapter()
{
public void keyTyped(KeyEvent e)
{
if (txtMensaje.getText().length()== 25)
e.consume();
}
public void keyReleased(KeyEvent e)
{
if(e.getKeyCode()==e.VK_ENTER)
{
String data = txtMensaje.getText();
txtMensaje.setText(null);
try
{
Output.write(data.getBytes());
}
catch (IOException ex)
{
System.exit(ERROR);
}
}
}
});
btnCerrar.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent ev){
System.exit(0);
}
});
}
} |
/**
* Package for junior.pack3.p4.ch3.task1. Car store. CrudRepository.
*
* @author Gureyev Ilya (mailto:ill-jah@yandex.ru)
* @version 2019-05-27
* @since 2019-05-27
*/
package ru.job4j.services; |
package tw.org.iii.AbnerJava;
public class Second {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1 = new String();
byte []a1 = {97,98,99,100};
String b1 = new String(a1);
String b2 = new String(a1,1,2);
Bike myBike = new Bike();
System.out.println(s1);
System.out.println(b1);
System.out.println(b2);
//----在Bike的類別中沒有寫toString的方法的話直接印出來會顯示他在記憶體的位置
System.out.println(myBike);
}
}
|
package util;
import java.util.Hashtable;
public class DataUtil {
public static Object[][] getData(Xls_Reader xls, String testCaseName) {
// D:\Selenium\Workspace\POMWithPF
String sheetName = Constants.DATA_XLS_SHEET;
int testStartRow = 1;
System.out.println(xls.getCellData(sheetName, 0, testStartRow));
while (!xls.getCellData(sheetName, 0, testStartRow).equals(testCaseName)) {
testStartRow++;
}
System.out.println("test row starts: " + testStartRow);
int colStartRowNum = testStartRow + 1;
int dataStartRowNum = testStartRow + 2;
// calculate number colnumber
int cols = 0;
while (!xls.getCellData(sheetName, cols, colStartRowNum).equals("")) {
cols++;
}
System.out.println("total number of col: " + cols);
int rows = 0;
while (!xls.getCellData(sheetName, 0, dataStartRowNum + rows).equals("")) {
rows++;
}
System.out.println("total number of rows: " + rows);
Object[][] data = new Object[rows][1];
int dataRow = 0;
Hashtable<String, String> table;
for (int rowNum = dataStartRowNum; rowNum < dataStartRowNum + rows; rowNum++) {
table = new Hashtable<String, String>();
for (int colNum = 0; colNum < cols; colNum++) {
String key = xls.getCellData(sheetName, colNum, colStartRowNum);
String value = xls.getCellData(sheetName, colNum, rowNum);
table.put(key, value);
// data[dataRow][colNum] = xls.getCellData("Data", colNum, rowNum);
// 0,0 0,1 1,0 ...
}
data[dataRow][0] = table;
dataRow++;
}
return data;
}
public static boolean isTestExecutable(Xls_Reader xls, String testCaseName) {
int rows = xls.getRowCount(Constants.TESTCASE_XLS_SHEET);
for (int rNum = 2; rNum <= rows; rNum++) {
String testName = xls.getCellData(Constants.TESTCASE_XLS_SHEET, Constants.TESTCASENAME_XLS, rNum);
if (testName.equals(testCaseName)) {
String runMode = xls.getCellData(Constants.TESTCASE_XLS_SHEET, Constants.RUNMODE_XLS, rNum);
if (runMode.equals("Y")) {
return true;
} else
return false;
}
}
return false;
}
}
|
package org.shv.contactapp.server;
import org.shv.contactapp.app.api.ContactView;
import org.shv.contactapp.app.api.IContactAppService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
/**
* Rest controller providing basic rest endpoints for contact manipulation
*
* @author sharapov
*
*/
@RestController
public class ContactRestServer {
private final IContactAppService contactAppService;
public ContactRestServer(IContactAppService contactAppService) {
this.contactAppService = contactAppService;
}
@GetMapping(path = "/contacts/{contactId}", consumes = "application/json", produces = "application/json")
public ResponseEntity<ContactView> findContact(@PathVariable Long contactId) {
ContactView foundContact = contactAppService.findContact(contactId);
return new ResponseEntity<>(foundContact, new HttpHeaders(), HttpStatus.OK);
}
@PostMapping(path = "/contacts", consumes = "application/json", produces = "application/json")
public ResponseEntity<ContactView> createContact(@RequestBody ContactView contactView) {
ContactView createdContact = contactAppService.createContact(contactView);
return new ResponseEntity<>(createdContact, new HttpHeaders(), HttpStatus.CREATED);
}
@PutMapping(path = "/contacts/{contactId}", consumes = "application/json", produces = "application/json")
public ResponseEntity<ContactView> editContact(@RequestBody ContactView contactView, @PathVariable Long contactId) {
ContactView updatedContact = contactAppService.editContact(contactView, contactId);
return new ResponseEntity<>(updatedContact, new HttpHeaders(), HttpStatus.OK);
}
@DeleteMapping(path = "/contacts/{contactId}", consumes = "application/json", produces = "application/json")
public ResponseEntity<Void> deleteContact(@PathVariable Long contactId) {
contactAppService.deleteContact(contactId);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
|
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.identity.governance.internal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.wso2.carbon.identity.core.ConnectorConfig;
import org.wso2.carbon.identity.event.services.IdentityEventService;
import org.wso2.carbon.identity.governance.IdentityGovernanceService;
import org.wso2.carbon.identity.governance.IdentityGovernanceServiceImpl;
import org.wso2.carbon.identity.governance.common.IdentityConnectorConfig;
import org.wso2.carbon.identity.governance.internal.service.impl.notification.DefaultNotificationChannelManager;
import org.wso2.carbon.identity.governance.internal.service.impl.otp.DefaultOTPGenerator;
import org.wso2.carbon.identity.governance.service.IdentityDataStoreService;
import org.wso2.carbon.identity.governance.service.IdentityDataStoreServiceImpl;
import org.wso2.carbon.identity.governance.service.notification.NotificationChannelManager;
import org.wso2.carbon.identity.governance.listener.IdentityMgtEventListener;
import org.wso2.carbon.identity.governance.listener.IdentityStoreEventListener;
import org.wso2.carbon.identity.governance.service.otp.OTPGenerator;
import org.wso2.carbon.idp.mgt.IdpManager;
import org.wso2.carbon.user.core.listener.UserOperationEventListener;
import org.wso2.carbon.user.core.service.RealmService;
@Component(
name = "org.wso2.carbon.identity.governance.internal.IdentityMgtServiceComponent",
immediate = true)
public class IdentityMgtServiceComponent {
private static final Log log = LogFactory.getLog(IdentityMgtServiceComponent.class);
@Activate
protected void activate(ComponentContext context) {
try {
IdentityMgtEventListener listener = new IdentityMgtEventListener();
context.getBundleContext().registerService(UserOperationEventListener.class, listener, null);
// IdentityDataStoreService should be registered before the IdentityStoreEventListener.
IdentityDataStoreService identityDataStoreService = new IdentityDataStoreServiceImpl();
context.getBundleContext()
.registerService(IdentityDataStoreService.class.getName(), identityDataStoreService, null);
IdentityMgtServiceDataHolder.getInstance().setIdentityDataStoreService(identityDataStoreService);
context.getBundleContext().registerService(UserOperationEventListener.class, new
IdentityStoreEventListener(), null);
IdentityGovernanceServiceImpl identityGovernanceService = new IdentityGovernanceServiceImpl();
context.getBundleContext().registerService(IdentityGovernanceService.class, identityGovernanceService,
null);
IdentityMgtServiceDataHolder.getInstance().setIdentityGovernanceService(identityGovernanceService);
DefaultNotificationChannelManager defaultNotificationChannelManager =
new DefaultNotificationChannelManager();
context.getBundleContext()
.registerService(NotificationChannelManager.class.getName(), defaultNotificationChannelManager, null);
DefaultOTPGenerator defaultOtpGenerator = new DefaultOTPGenerator();
context.getBundleContext()
.registerService(OTPGenerator.class.getName(), defaultOtpGenerator, null);
if (log.isDebugEnabled()) {
log.debug("Identity Management Listener is enabled");
}
} catch (Exception e) {
log.error("Error while activating identity governance component.", e);
}
}
@Deactivate
protected void deactivate(ComponentContext context) {
if (log.isDebugEnabled()) {
log.debug("Identity Management bundle is de-activated");
}
}
protected void unsetIdentityEventService(IdentityEventService identityEventService) {
IdentityMgtServiceDataHolder.getInstance().setIdentityEventService(null);
}
@Reference(
name = "EventMgtService",
service = org.wso2.carbon.identity.event.services.IdentityEventService.class,
cardinality = ReferenceCardinality.MANDATORY,
policy = ReferencePolicy.DYNAMIC,
unbind = "unsetIdentityEventService")
protected void setIdentityEventService(IdentityEventService identityEventService) {
IdentityMgtServiceDataHolder.getInstance().setIdentityEventService(identityEventService);
}
@Reference(
name = "idp.mgt.event.listener.service",
service = org.wso2.carbon.identity.governance.common.IdentityConnectorConfig.class,
cardinality = ReferenceCardinality.MULTIPLE,
policy = ReferencePolicy.DYNAMIC,
unbind = "unsetIdentityGovernanceConnector")
protected void setIdentityGovernanceConnector(IdentityConnectorConfig identityConnectorConfig) {
IdentityMgtServiceDataHolder.getInstance().addIdentityGovernanceConnector(identityConnectorConfig);
try {
BundleContext bundleContext = FrameworkUtil.getBundle(IdentityMgtServiceComponent.class).getBundleContext();
bundleContext.registerService(ConnectorConfig.class.getName(), identityConnectorConfig, null);
} catch (Throwable e) {
log.error(
"Error while re-registering the service " + identityConnectorConfig.getClass().getName() + " as " +
ConnectorConfig.class.getName());
}
}
protected void unsetIdentityGovernanceConnector(IdentityConnectorConfig identityConnectorConfig) {
IdentityMgtServiceDataHolder.getInstance().unsetIdentityGovernanceConnector(identityConnectorConfig);
}
protected void unsetIdpManager(IdpManager idpManager) {
IdentityMgtServiceDataHolder.getInstance().setIdpManager(null);
}
@Reference(
name = "IdentityProviderManager",
service = org.wso2.carbon.idp.mgt.IdpManager.class,
cardinality = ReferenceCardinality.MANDATORY,
policy = ReferencePolicy.DYNAMIC,
unbind = "unsetIdpManager")
protected void setIdpManager(IdpManager idpManager) {
IdentityMgtServiceDataHolder.getInstance().setIdpManager(idpManager);
}
@Reference(
name = "RealmService",
service = org.wso2.carbon.user.core.service.RealmService.class,
cardinality = ReferenceCardinality.MANDATORY,
policy = ReferencePolicy.DYNAMIC,
unbind = "unsetRealmService")
protected void setRealmService(RealmService realmService) {
if (log.isDebugEnabled()) {
log.debug("Setting the Realm Service");
}
IdentityMgtServiceDataHolder.getInstance().setRealmService(realmService);
}
protected void unsetRealmService(RealmService realmService) {
log.debug("UnSetting the Realm Service");
IdentityMgtServiceDataHolder.getInstance().setRealmService(null);
}
}
|
package com.giderosmobile.android.plugins.ads;
import java.lang.ref.WeakReference;
import android.app.Activity;
import android.view.KeyEvent;
public interface AdsInterface {
public void onCreate(WeakReference<Activity> activity);
public void onDestroy();
public void onStart();
public void onStop();
public void onPause();
public void onResume();
public boolean onKeyUp(int keyCode, KeyEvent event);
public void setKey(final Object parameters);
public void enableTesting();
public void loadAd(final Object parameters);
public void showAd(final Object parameters);
public void hideAd(String type);
public int getWidth();
public int getHeight();
}
|
package com.company.vehicleinventory.enums;
/**
* Represents db action status codes. toString() and convert() are in essence stubs to
* handle custom conversions when needed.
*/
public enum VehicleInventoryDatabaseStatusCode {
ADDED,
DELETED,
UPDATED,
FAILED;
public String toString(){
String retn = "";
if (this == ADDED) {
retn = "ADDED";
}
if (this == DELETED) {
retn = "DELETED";
}
if (this == UPDATED) {
retn = "UPDATED";
}
if (this == FAILED) {
retn = "FAILED";
}
return retn;
}
public static VehicleInventoryDatabaseStatusCode convert(String code) {
VehicleInventoryDatabaseStatusCode retn = null;
if(code.equalsIgnoreCase("added")) {
retn = ADDED;
}
if(code.equalsIgnoreCase("deleted")) {
retn = DELETED;
}
if(code.equalsIgnoreCase("updated")) {
retn = UPDATED;
}
if(code.equalsIgnoreCase("failed")) {
retn = FAILED;
}
return retn;
}
}
|
package org.dada.swt;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import org.eclipse.swt.widgets.TableItem;
public class TableState<K, V> {
//private Map<K, V> extant = new HashMap<K, V>();
//private Map<K, V> extinct = new HashMap<K, V>();
public Timer timer = new Timer();
public Map<K, TableItem> primaryKeyToTableItem = new HashMap<K, TableItem>();
}
|
package DesignPattern.Adapter;
public class Adapter implements Tap {
private final Tube6 t6 = new Tube6();
private final Tube8 t8 = new Tube8();
@Override
public int WaterOutput( int tp) {
// TODO Auto-generated method stub
if(tp==4){
return t6.OutputWater6cm()-2;
}else if(tp==6){
return t8.OutputWater8cm()-4;
}
return 0;
}
} |
package com.itheima.day_03.sleep;
public class SleepDemo {
public static void main(String[] args) {
usePerson(new PassengerA());
System.out.println("-------------");
usePerson(getPerson());
}
private static void usePerson(Person person) {
//在调用时相当于多态形式的 Person person = new PassengerA();
person.sleep();
}
private static Person getPerson() {
return new PassengerB();
}
}
|
package ru.job4j.list;
/* public List<Integer> toList (int[][] array) {} - в метод приходит двумерный массив целых чисел,
необходимо пройтись по всем элементам массива и добавить их в List<Integer>.*/
import java.util.ArrayList;
import java.util.List;
public class ConverterMatrix2List {
public List<Integer> toList(int array[][]) {
List<Integer> list = new ArrayList<>();
for (int[] rows : array) {
for (int cells : rows) {
list.add(cells);
}
}
return list;
}
}
|
package top.docstorm.documentstormcommon.service;
import top.docstorm.documentstormcommon.domain.FileInfo;
/**
* @Description:
* @author: passer
* @version:2019/9/17
*/
public interface FileInfoService {
/**
* 往数据库插入上传文件信息
* @param fileInfo
* @return
*/
int insertUploadFileInfo(FileInfo fileInfo);
/**
* 更新文件状态
* @param fileId
* @param fileStatus
* @return
*/
int updateFileStatus(int fileId, byte fileStatus);
/**
* 根据信息插入数据
* @param fileName
* @param fileKey
* @param opt
* @return
*/
FileInfo insertFromUploadInfo(String fileName, String fileKey, String opt, Integer userId);
String generateFileExt(String opt);
String generateUploadFileName(String fileName, String newFileName);
String generateSaveFileName(String fileKey, String opt);
String generateAfterTransFileName(FileInfo fileInfo);
String generateBeforeTransFileName(FileInfo fileInfo);
}
|
package com.cb.cbfunny.tv.fragment;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.support.v4.app.Fragment;
import com.cb.cbfunny.utils.DialogUtils;
public class BaseFragment extends Fragment {
private static final long serialVersionUID = 1L;
private Dialog progressDialog;
@SuppressLint("NewApi")
protected void showDialog(Object resID) {
if (progressDialog == null) {
progressDialog = DialogUtils.showCBProgressDialog(getActivity(),resID,20,null);
}else{
if (!getActivity().isDestroyed()) {
progressDialog.show();
}
}
}
@SuppressLint("NewApi")
protected void dismissDialog() {
if (progressDialog != null && !getActivity().isDestroyed()) {
progressDialog.dismiss();
}
}
}
|
public class IntegerToRoman {
public String intToRoman(int num) {
String[] onesToRoman = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
String[] tensToRoman = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
String[] hundredsToRoman = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
String[] thousandsToRoman = {"", "M", "MM", "MMM"};
return new StringBuilder(thousandsToRoman[num / 1000])
.append(hundredsToRoman[(num % 1000) / 100])
.append(tensToRoman[(num % 100) / 10])
.append(onesToRoman[num % 10])
.toString();
}
public static void main(String[] args) {
IntegerToRoman integerToRoman = new IntegerToRoman();
System.out.println(integerToRoman.intToRoman(1994));
}
}
|
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory.config;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.FactoryBeanNotInitializedException;
import org.springframework.lang.Nullable;
/**
* {@link FactoryBean} which returns a value which is the result of a static or instance
* method invocation. For most use cases it is better to just use the container's
* built-in factory method support for the same purpose, since that is smarter at
* converting arguments. This factory bean is still useful though when you need to
* call a method which doesn't return any value (for example, a static class method
* to force some sort of initialization to happen). This use case is not supported
* by factory methods, since a return value is needed to obtain the bean instance.
*
* <p>Note that as it is expected to be used mostly for accessing factory methods,
* this factory by default operates in a <b>singleton</b> fashion. The first request
* to {@link #getObject} by the owning bean factory will cause a method invocation,
* whose return value will be cached for subsequent requests. An internal
* {@link #setSingleton singleton} property may be set to "false", to cause this
* factory to invoke the target method each time it is asked for an object.
*
* <p><b>NOTE: If your target method does not produce a result to expose, consider
* {@link MethodInvokingBean} instead, which avoids the type determination and
* lifecycle limitations that this {@link MethodInvokingFactoryBean} comes with.</b>
*
* <p>This invoker supports any kind of target method. A static method may be specified
* by setting the {@link #setTargetMethod targetMethod} property to a String representing
* the static method name, with {@link #setTargetClass targetClass} specifying the Class
* that the static method is defined on. Alternatively, a target instance method may be
* specified, by setting the {@link #setTargetObject targetObject} property as the target
* object, and the {@link #setTargetMethod targetMethod} property as the name of the
* method to call on that target object. Arguments for the method invocation may be
* specified by setting the {@link #setArguments arguments} property.
*
* <p>This class depends on {@link #afterPropertiesSet()} being called once
* all properties have been set, as per the InitializingBean contract.
*
* <p>An example (in an XML based bean factory definition) of a bean definition
* which uses this class to call a static factory method:
*
* <pre class="code">
* <bean id="myObject" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
* <property name="staticMethod" value="com.whatever.MyClassFactory.getInstance"/>
* </bean></pre>
*
* <p>An example of calling a static method then an instance method to get at a
* Java system property. Somewhat verbose, but it works.
*
* <pre class="code">
* <bean id="sysProps" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
* <property name="targetClass" value="java.lang.System"/>
* <property name="targetMethod" value="getProperties"/>
* </bean>
*
* <bean id="javaVersion" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
* <property name="targetObject" ref="sysProps"/>
* <property name="targetMethod" value="getProperty"/>
* <property name="arguments" value="java.version"/>
* </bean></pre>
*
* @author Colin Sampaleanu
* @author Juergen Hoeller
* @since 21.11.2003
* @see MethodInvokingBean
* @see org.springframework.util.MethodInvoker
*/
public class MethodInvokingFactoryBean extends MethodInvokingBean implements FactoryBean<Object> {
private boolean singleton = true;
private boolean initialized = false;
/** Method call result in the singleton case. */
@Nullable
private Object singletonObject;
/**
* Set if a singleton should be created, or a new object on each
* {@link #getObject()} request otherwise. Default is "true".
*/
public void setSingleton(boolean singleton) {
this.singleton = singleton;
}
@Override
public void afterPropertiesSet() throws Exception {
prepare();
if (this.singleton) {
this.initialized = true;
this.singletonObject = invokeWithTargetException();
}
}
/**
* Returns the same value each time if the singleton property is set
* to "true", otherwise returns the value returned from invoking the
* specified method on the fly.
*/
@Override
@Nullable
public Object getObject() throws Exception {
if (this.singleton) {
if (!this.initialized) {
throw new FactoryBeanNotInitializedException();
}
// Singleton: return shared object.
return this.singletonObject;
}
else {
// Prototype: new object on each call.
return invokeWithTargetException();
}
}
/**
* Return the type of object that this FactoryBean creates,
* or {@code null} if not known in advance.
*/
@Override
public Class<?> getObjectType() {
if (!isPrepared()) {
// Not fully initialized yet -> return null to indicate "not known yet".
return null;
}
return getPreparedMethod().getReturnType();
}
@Override
public boolean isSingleton() {
return this.singleton;
}
}
|
package com.bshare.core;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
/**
* 全部可支持平台,若要增加或刪除平台请修改该枚举
*/
public enum PlatformType implements Parcelable {
EMAIL("email"), SINAMINIBLOG("sinaminiblog", true), SOHUMINIBLOG("sohuminiblog", true), QQMB("qqmb", true), KAIXIN("kaixin001", true), RENREN("renren", true), FAV115("115"),
COM139("139"), MAIL139("139mail"), COM51("51"), TAONAN("51taonan"), DIAN9("9dian"), FAV9("9fav"), ASK("ask"), BAIDUCANG("baiducang"), BAIDUHI("baiduhi"), BAOHE("baohe"),
BGOOGLE("bgoogle"), BYAHOO("byahoo"), CAIMI("caimi"), CFOL("cfol"), CHINANEWS("chinanews"), CHOUTI("chouti"), CLZG("clzg"), CYOLBBS("cyolbbs"), CYZONE("cyzone"),
DELICIOUS("delicious"), DIG24("dig24"), DIGG("digg"), DIGLOG("diglog"), DIGU("digu"), DIGOO("diigo"), DOUBAN("douban"), DREAM("dream"),
EVERNOTE("evernote"), FACEBOOK("facebook"), FANFOU("fanfou"), FEIXIN("feixin"), FRIENDFEED("friendfeed"), FUNP("funp"), FWISP("fwisp"), GANNIU("ganniu"), GMW("gmw"),
HAOEI("haoei"), HEMIDEMI("hemidemi"), HEXUNMB("hexunmb"), IFENGMB("ifengmb"), ifensi("ifensi"), INSTPAPER("instapaper"), ITIEBA("itieba"), LESHOU("leshou"),
LINKEDIN("linkedin"), LIVEFAV("livefav"), LIVESPACE("livespace"), LOO365("loo365"), MALA("mala"), MARKZHI("markzhi"), MASAR("masar"), MISTERWONG("mister-wong"),
MOPTK("moptk"), MPLIFE("mplife"), MSN("msn"), MYSHARE("myshare"), MYSPACE("myspace"), NETEASEMB("neteasemb"), NETVIBES("netvibes"), PEOPLEMB("peoplemb"),
PHONEFAVS("phonefavs"), PINGFM("pingfm"), PLURK("plurk"), POCO("poco"), POLLADIUM("polladium"), PRINTF("printf"), QING6("qing6"), QQSHUQIAN("qqshuqian"),
QQXIAQYOU("qqxiaoyou"), QZONE("qzone"), READITLATER("readitlater"), REDDIT("reddit"), RENJIAN("renjian"), SHOUJI("shouji"), RENMAIKU("renmaiku"), SINAVIVI("sinavivi"),
SOUHUBAI("sohubai"), STUMBLEUPON("stumbleupon"), SZONE("szone"), TAOJIANGHU("taojianghu"), TIANYA("tianya"), TONGXUE("tongxue"), TUITA("tuita"), TUMBLR("tumblr"),
TWITTER("twitter"), USHI("ushi"), WAAKEE("waakee"), WEALINK("wealink"), WOSHAO("woshao"), XIANGUO("xianguo"), XIAOMEISNS("xiaomeisns"), XYWEIBO("xyweibo"),
YIJEE("yijee"), YOUDAO("youdao"), ZHUANMING("zhuanming"), ZJOL("zjol"), ZUOSA("zuosa"), BSYNC("bsync"), SMS("sms"), MORE("more"), QING("sinaqing"),
MAIL189("189mail"), SHARE189("189share"), CHANGSHAMB("changshamb"), CHEZHUMB("chezhumb"), DUANKOU("duankou"), DUITANG("duitang"), EASTDAYMB("eastdaymb"),
GMWEIBO("gmweibo"), GPLUS("gplus"), GTRANSLATE("gtranslate"), HEFEIMB("hefeimb"), HUABAN("huaban"), IFENGKB("ifengkb"), JIANWEIBO("jianweibo"),
JIPIN("jipin"), JOINWISH("joinwish"), JSCHINA("jschina"), JXCN("jxcn"), LAODAO("laodao"), LEZHIMARK("lezhimark"), MAIKUNOTE("maikunote"), MEILISHUO("meilishuo"),
MFEIXIN("mfeixin"), MILIAO("miliao"), MINGDAO("mingdao"), MOGUJIE("mogujie"), MQZONE("mqzone"), MWEIBO("mweibo"), PINTEREST("pinterest"), QILEKE("qileke"),
QINGBIJI("qingbiji"), QQIM("qqim"), REDMB("redmb"), SOHUKAN("sohukan"), SOUTHMB("southmb"), SZMB("szmb"), TIANJI("tianji"), WANSHA("wansha"),
WO("wo"), XINHUAMB("xinhuamb"), XINMINMB("xinminmb"), YAOLANMB("yaolanmb"), YIDONGWEIBO("yidongweibo"), YOUDAONOTE("youdaonote"), WECHAT("wechat"), WECHAT_PENGYOU("wechatpengyou"), UNKNOWN("unknown");
private final String platformId;
private final String platformName;
private final boolean isOauth;
//平台显示名前缀
private static final String NAME_PREFIX = "bshare_pn_";
private PlatformType(String platformId) {
this(platformId, NAME_PREFIX + platformId, false);
}
private PlatformType(String platformId, boolean isOauth) {
this(platformId, NAME_PREFIX + platformId, isOauth);
}
private PlatformType(String platformId, String platformName) {
this(platformId, platformName, false);
}
private PlatformType(String platformId, String platformName, boolean isOauth) {
this.platformId = platformId;
this.platformName = platformName;
this.isOauth = isOauth;
}
public String getPlatformId() {
return platformId;
}
public String getPlatfromName() {
return platformName;
}
public boolean isOauth() {
return isOauth;
}
public static PlatformType getPlatfromById(String platformId) {
if (TextUtils.isEmpty(platformId)) {
return null;
}
PlatformType[] ps = PlatformType.values();
for (PlatformType p : ps) {
if (p.getPlatformId().equals(platformId)) {
return p;
}
}
return null;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(final Parcel dest, final int flags) {
dest.writeInt(this.ordinal());
}
public static final Creator<PlatformType> CREATOR = new Creator<PlatformType>() {
@Override
public PlatformType createFromParcel(final Parcel source) {
return PlatformType.values()[source.readInt()];
}
@Override
public PlatformType[] newArray(final int size) {
return new PlatformType[size];
}
};
}
|
package pt.joja;
import java.util.Arrays;
import java.util.Random;
public class MaxHeap {
public static void main(String[] args) {
int nums = 100;
Random rand = new Random(47);
int[] eles = new int[nums];
for (int i = 0; i < nums; i++) {
eles[i] = rand.nextInt(1000);
}
System.out.println(Arrays.toString(eles));
MaxHeap maxHeap = new MaxHeap(eles.length);
for (int ele : eles) {
maxHeap.add(ele);
}
for (int i = eles.length - 1; i >= 0; i--) {
eles[i] = maxHeap.remove();
}
System.out.println("[Heap.sort] compared: " + compCtr);
System.out.println("[Heap.sort] swaped : " + swapCtr);
System.out.println(Arrays.toString(eles));
}
private static int compCtr = 0;
private static int swapCtr = 0;
private int[] eles;
private int size = 0;
public MaxHeap(int maxSize) {
eles = new int[maxSize + 1];
}
public void add(int ele) {
if (size < eles.length) {
eles[++size] = ele;
swim(size);
return;
}
throw new RuntimeException("Heap is full.");
}
public int remove() {
if (size > 0) {
int result = eles[1];
eles[1] = eles[size--];
sink(1);
return result;
}
throw new RuntimeException("Heap is empty.");
}
public void sink(int index) {
while (2 * index <= size) {
int child = 2 * index;
if (child < size) {
compCtr++;
if (eles[child] < eles[child + 1]) {
child++;
}
}
compCtr++;
if (eles[index] > eles[child]) {
break;
}
swapCtr++;
int temp = eles[index];
eles[index] = eles[child];
eles[child] = temp;
index = child;
}
}
public void swim(int index) {
while (index > 0) {
int father = index / 2;
compCtr++;
if (eles[index] < eles[father]) {
break;
}
swapCtr++;
int temp = eles[index];
eles[index] = eles[father];
eles[father] = temp;
index = father;
}
}
// 1
// 2 3
// 4 5 6 7
}
|
package com.thinkdevs.cryptomarket;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
public class PrefUtils {
private static final String START_TIME="Countdown_timer";
private static final String MAX_TIME="Countdown_max";
private SharedPreferences mPreferences;
public PrefUtils(Context context){
mPreferences= PreferenceManager.getDefaultSharedPreferences(context);
}
public int getStartedTime(){
return mPreferences.getInt(START_TIME,0);
}
public void setStartedTime(int startedTime){
SharedPreferences.Editor editor=mPreferences.edit();
editor.putInt(START_TIME,startedTime);
editor.apply();
}
public int getMaxTime(){
return mPreferences.getInt(MAX_TIME,0);
}
public void setMaxTime(int startedTime){
SharedPreferences.Editor editor=mPreferences.edit();
editor.putInt(MAX_TIME,startedTime);
editor.apply();
}
}
|
package com.wangzhu.spring.scan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
* Created by wang.zhu on 2020-06-13 15:34.
**/
public abstract class AbstractRegistrar implements EnvironmentAware, ResourceLoaderAware, ImportBeanDefinitionRegistrar {
protected final Logger logger = LoggerFactory.getLogger(getClass());
protected Environment environment;
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}
protected ResourceLoader resourceLoader;
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
final Set<String> packagesToScan = getPackagesToScan(importingClassMetadata);
scan(registry, packagesToScan);
}
private Set<String> getPackagesToScan(final AnnotationMetadata annotationMetadata) {
final AnnotationAttributes attributes = AnnotationAttributes
.fromMap(annotationMetadata.getAnnotationAttributes(getAnnotation().getName()));
final String[] basePackages = attributes.getStringArray("basePackages");
final Class<?>[] basePackageClasses = attributes.getClassArray("basePackageClasses");
final Set<String> packagesToScan = new LinkedHashSet<>(Arrays.asList(basePackages));
for (final Class<?> basePackageClass : basePackageClasses) {
packagesToScan.add(ClassUtils.getPackageName(basePackageClass));
}
if (packagesToScan.isEmpty()) {
packagesToScan.add(ClassUtils.getPackageName(annotationMetadata.getClassName()));
}
packagesToScan.removeIf((candidate) -> !StringUtils.hasText(candidate));
return packagesToScan;
}
protected abstract Class<? extends Annotation> getAnnotation();
private void scan(BeanDefinitionRegistry registry, Set<String> packages) {
final ClassPathScanningCandidateComponentProvider scanner = getScanner();
for (final String basePackage : packages) {
final Set<BeanDefinition> beanDefinitions = scanner.findCandidateComponents(basePackage);
logger.info("detail basePackage|{}|beanDefinitions|{}", basePackage, beanDefinitions);
for (final BeanDefinition beanDefinition : beanDefinitions) {
if (beanDefinition instanceof AnnotatedBeanDefinition) {
final AnnotatedBeanDefinition annotatedBeanDefinition = (AnnotatedBeanDefinition) beanDefinition;
registerBeanDefinition(annotatedBeanDefinition, registry);
}
}
}
}
protected final ClassPathScanningCandidateComponentProvider getScanner() {
final ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false) {
@Override
protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
return AbstractRegistrar.this.isCandidateComponent(beanDefinition);
}
};
scanner.setEnvironment(this.environment);
scanner.setResourceLoader(this.resourceLoader);
final List<TypeFilter> includeFilters = getIncludeFilters();
includeFilters.forEach(scanner::addIncludeFilter);
return scanner;
}
protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
AnnotationMetadata metadata = beanDefinition.getMetadata();
return metadata.isIndependent() && metadata.isInterface();
}
protected abstract List<TypeFilter> getIncludeFilters();
private void registerBeanDefinition(final AnnotatedBeanDefinition annotatedBeanDefinition, BeanDefinitionRegistry registry) {
final BeanDefinitionHolder definitionHolder = builderBeanDefinitionHolder(annotatedBeanDefinition);
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, registry);
}
protected abstract BeanDefinitionHolder builderBeanDefinitionHolder(AnnotatedBeanDefinition annotatedBeanDefinition);
}
|
package creational.factorymethod.product;
// A 产品
public class AProduct implements Product {
@Override
public void name() {
System.out.println("AProduce");
}
}
|
public class TestDemo {
/* ApplicationContext ac;
SqlSessionFactory sessionFactory;
DeptmentMapper deptmentMapper;
@Before
public void init(){
ac = new ClassPathXmlApplicationContext("spring/applicationContext-dao.xml");
sessionFactory = (SqlSessionFactory)ac.getBean("sqlSessionFactory");
}
@Test
public void testAddDeptment() throws Exception {
SqlSession sqlSession = sessionFactory.openSession();
DeptmentMapper mapper = sqlSession.getMapper(DeptmentMapper.class);
Deptment deptment = new Deptment();
deptment.setDeptName("ssss");
deptment.setCreateDate(new Date());
deptment.setUpdateDate(new Date());
deptment.setDiscription("sssss");
mapper.addDeptment(deptment );
}*/
}
|
package modelo;
public class Economico implements Motor{
@Override
public void arracar() {
System.out.println("Arrancar motor.");
}
@Override
public void acelerar() {
System.out.println("Acelerando motor.");
}
@Override
public void apagar() {
System.out.println("Apagando motor,");
}
}
|
package vo;
import java.util.Date;
public class PayVO {
private int payId; // 결제 아이디
private String payWay; // 결제 수단
private Date payDate; // 결제 일자
private String payInfo; // 결제 정보
//외래키
private String userId; // 회원 아이디
private int mScheduleId; // 영화 시간 아이디
public int getPayId() {
return payId;
}
public void setPayId(int payId) {
this.payId = payId;
}
public String getPayWay() {
return payWay;
}
public void setPayWay(String payWay) {
this.payWay = payWay;
}
public Date getPayDate() {
return payDate;
}
public void setPayDate(Date payDate) {
this.payDate = payDate;
}
public String getPayInfo() {
return payInfo;
}
public void setPayInfo(String payInfo) {
this.payInfo = payInfo;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public int getmScheduleId() {
return mScheduleId;
}
public void setmScheduleId(int mScheduleId) {
this.mScheduleId = mScheduleId;
}
}
|
package com.sl.app.access.find.account.dao;
import com.sl.app.access.find.account.vo.AppAccessFindAccountVO;
import net.sf.json.JSONObject;
public interface AppAccessFindAccountDAO {
JSONObject updateFindMember(AppAccessFindAccountVO vo);
}
|
/*
* Ubb.java
*
* Created on 2006Äê5ÔÂ17ÈÕ, ÏÂÎç2:21
*
* To change this template, choose Tools | Options and locate the template under
* the Source Creation and Management node. Right-click the template and choose
* Open. You can then make changes to the template in the Source Editor.
*/
package tot.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author Administrator
*/
public class Ubb {
private String source;
private String ubbTags[];
private String htmlTags[];
/** Creates a new instance of Ubb */
public Ubb() {
byte byte0 = 52;
source = new String();
ubbTags = new String[byte0];
htmlTags = new String[byte0];
ubbTags[0] = "[b]";
htmlTags[0] = "<b>";
ubbTags[1] = "[/b]";
htmlTags[1] = "</b>";
ubbTags[2] = "[i]";
htmlTags[2] = "<em>";
ubbTags[3] = "[/i]";
htmlTags[3] = "</em>";
ubbTags[4] = "[quote]";
htmlTags[4] = "<div style=\"border-style:dashed;background-color:#CCCCCC;border-width:thin;bord" +
"er-color:#999999\"><br><em>"
;
ubbTags[5] = "[/quote]";
htmlTags[5] = "</em><br><br></div>";
ubbTags[6] = "[/size]";
htmlTags[6] = "</font>";
ubbTags[7] = "[size=6]";
htmlTags[7] = "<font style=\"font-size:6px\">";
ubbTags[8] = "[size=8]";
htmlTags[8] = "<font style=\"font-size:8px\">";
ubbTags[9] = "[size=10]";
htmlTags[9] = "<font style=\"font-size:10px\">";
ubbTags[10] = "[size=12]";
htmlTags[10] = "<font style=\"font-size:12px\">";
ubbTags[11] = "[size=14]";
htmlTags[11] = "<font style=\"font-size:14px\">";
ubbTags[12] = "[size=18]";
htmlTags[12] = "<font style=\"font-size:18px\">";
ubbTags[13] = "[size=24]";
htmlTags[13] = "<font style=\"font-size:24px\">";
ubbTags[14] = "[size=36]";
htmlTags[14] = "<font style=\"font-size:36px\">";
ubbTags[15] = "[/font]";
htmlTags[15] = "</font>";
ubbTags[16] = "[font=\u5B8B\u4F53]";
htmlTags[16] = "<font face=\"\u5B8B\u4F53\">";
ubbTags[17] = "[font=\u9ED1\u4F53]";
htmlTags[17] = "<font face=\"\u9ED1\u4F53\">";
ubbTags[18] = "[font=\u96B6\u4E66]";
htmlTags[18] = "<font face=\"\u96B6\u4E66\">";
ubbTags[19] = "[font=\u4EFF\u5B8B_GB2312]";
htmlTags[19] = "<font face=\"\u4EFF\u5B8B_GB2312\">";
ubbTags[20] = "[font=\u5E7C\u5706]";
htmlTags[20] = "<font face=\"\u5E7C\u5706\">";
ubbTags[21] = "[font=Arial]";
htmlTags[21] = "<font face=\"Arial\">";
ubbTags[22] = "[font=Times New Roman]";
htmlTags[22] = "<font face=\"Times New Roman\">";
ubbTags[23] = "[red]";
htmlTags[23] = "<font color=\"red\">";
ubbTags[24] = "[/red]";
htmlTags[24] = "</font>";
ubbTags[25] = "[blue]";
htmlTags[25] = "<font color=\"blue\">";
ubbTags[26] = "[/blue]";
htmlTags[26] = "</font>";
ubbTags[27] = "[yellow]";
htmlTags[27] = "<font color=\"yellow\">";
ubbTags[28] = "[/yellow]";
htmlTags[28] = "</font>";
ubbTags[29] = "[green]";
htmlTags[29] = "<font color=\"green\">";
ubbTags[30] = "[/green]";
htmlTags[30] = "</font>";
ubbTags[31] = "[h1]";
htmlTags[31] = "<h1>";
ubbTags[32] = "[/h1]";
htmlTags[32] = "</h1>";
ubbTags[33] = "[h2]";
htmlTags[33] = "<h2>";
ubbTags[34] = "[/h2]";
htmlTags[34] = "</h2>";
ubbTags[35] = "[h3]";
htmlTags[35] = "<h3>";
ubbTags[36] = "[/h3]";
htmlTags[36] = "</h3>";
ubbTags[37] = "[h4]";
htmlTags[37] = "<h4>";
ubbTags[38] = "[/h4]";
htmlTags[38] = "</h4>";
ubbTags[39] = "[h5]";
htmlTags[39] = "<h5>";
ubbTags[40] = "[/h5]";
htmlTags[40] = "</h5>";
ubbTags[41] = "[h6]";
htmlTags[41] = "<h6>";
ubbTags[42] = "[/h6]";
htmlTags[42] = "</h6>";
ubbTags[43] = "[hr]";
htmlTags[43] = "<hr>";
ubbTags[44] = "[img]";
htmlTags[44] = "<br><img src=\"";
ubbTags[45] = "[/img]";
htmlTags[45] = "\"><br>";
ubbTags[46] = "[center]";
htmlTags[46] = "<div align=\"center\">";
ubbTags[47] = "[/center]";
htmlTags[47] = "</div>";
ubbTags[48] = "[left]";
htmlTags[48] = "<div align=\"left\">";
ubbTags[49] = "[/left]";
htmlTags[49] = "</div>";
ubbTags[50] = "[right]";
htmlTags[50] = "<div align=\"right\">";
ubbTags[51] = "[/right]";
htmlTags[51] = "</div>";
}
private String replace(String s, String s1, String s2)
{
StringBuffer stringbuffer = new StringBuffer();
for(int i = 0; i < s1.length(); i++)
{
char c = s1.charAt(i);
switch(c)
{
case 91: // '['
stringbuffer.append("\\[");
break;
case 93: // ']'
stringbuffer.append("\\]");
break;
default:
stringbuffer.append(c);
break;
}
}
Pattern pattern = Pattern.compile(stringbuffer.toString());
Matcher matcher = pattern.matcher(s);
StringBuffer stringbuffer1 = new StringBuffer();
for(boolean flag = matcher.find(); flag; flag = matcher.find())
{
matcher.appendReplacement(stringbuffer1, s2);
}
return matcher.appendTail(stringbuffer1).toString();
}
private String replaceNormalUBBCode(String s)
{
String s1 = new String(s);
for(int i = 0; i < ubbTags.length; i++)
{
s1 = replace(s1, ubbTags[i], htmlTags[i]);
}
return s1;
}
private String replaceURL(String s)
{
StringBuffer stringbuffer = new StringBuffer(s);
String s1 = new String();
int i = s.indexOf("[url]");
int j = s.indexOf("[/url]");
if(i != -1 && j != -1 && i < j)
{
String s2 = s.substring(i + 5, j);
String s3 = "<a href=\"" + s2 + "\">" + s2 + "</a>";
stringbuffer.replace(i, j + 6, s3);
}
return stringbuffer.toString();
}
private String replaceEmail(String s)
{
StringBuffer stringbuffer = new StringBuffer(s);
String s1 = new String();
int i = s.indexOf("[email]");
int j = s.indexOf("[/email]");
if(i != -1 && j != -1 && i < j)
{
String s2 = s.substring(i + 7, j);
String s3 = "<a href=\"mailto:" + s2 + "\">" + s2 + "</a>";
stringbuffer.replace(i, j + 8, s3);
}
return stringbuffer.toString();
}
public void setSource(String s)
{
source = s;
}
public String getResult()
{
return source;
}
public void run()
{
for(source = replaceNormalUBBCode(source); source.indexOf("[url]") != -1 && source.indexOf("[/url]") != -1; source = replaceURL(source)) { }
for(; source.indexOf("[email]") != -1 && source.indexOf("[/email]") != -1; source = replaceEmail(source)) { }
}
}
|
package com.codingKnowledge.controller;
import java.util.Scanner;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.codingKnowledge.entity.Client;
public class TestClient {
private static Scanner sc = null;
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext cap = new ClassPathXmlApplicationContext("spring.xml");
while (true) {
sc = new Scanner(System.in);
System.out.println("Enter 1 to 'Save' or 2 to 'Close'....");
int key = sc.nextInt();
switch (key) {
case 1:
Client c = (Client) cap.getBean("client");
System.out.println("Enter the Client Id:");
int id = sc.nextInt();
System.out.println("Enter the Client Name:");
String name = sc.next();
System.out.println("Enter the Client Gender:");
String gender = sc.next();
System.out.println("Enter the Client Address:");
String address = sc.next();
c.save(id, name, gender, address);
break;
default:
cap.close();
break;
}
}
}
}
|
package course.chapter9.objects2;
public class Account {
// fields
double balance;
String accountId;
static int nextId = 0;
static final int ROUTING_NUMBER = 123456789;
// methods
void deposit(double amount) {
balance +=amount;
}
void withdraw(double amount) {
balance -= amount;
}
}
|
package linkedlists;
import static org.junit.Assert.*;
import org.junit.Test;
public class IntersectionTest {
@Test
public void testIntersection() {
Node node1 = new Node(1);
node1.append(2);
node1.append(3);
Node node4 = new Node(4);
Node node5 = new Node(5);
Node node6 = new Node(6);
node4.next = node1;
node5.next = node6;
node6.next = node1;
assertEquals(node1,Intersection.getIntersection(node4, node5));
}
}
|
package patterns.behavioral.strategy;
public class ConcreteStrategyA implements Strategy
{
@Override
public void behavior()
{
System.out.println("use strategy A!");
}
}
|
package org.bots.clients;
public enum BotPlatformType {
TELEGRAM,
FACEBOOK;
}
|
package xdroid.adapter;
/**
* @author Oleksii Kropachov (o.kropachov@shamanland.com)
*/
public interface ViewTypeResolver<D> {
int getViewType(int position, D data);
}
|
package com.example.shivani.shivani;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
public class Image_Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_);
String url = getIntent().getStringExtra("url");
ImageView imageView = (ImageView) findViewById(R.id.image);
Picasso.with(this)
.load(url)
.into(imageView);
}
}
|
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
public class BubbleSortTest {
@Test
public void testBubbleSort(){
BubbleSort bubbleSort = new BubbleSort();
assertThat(bubbleSort.bubbleSort(new int[] {4, 7, 2, 3, 8}), is(equalTo(new int[] {2, 3, 4, 7, 8})));
}
} |
/* BindingRendererUtil.java
{{IS_NOTE
Purpose:
Description:
History:
Apr 25, 2011 4:44:06 PM , Created by simonpai
}}IS_NOTE
Copyright (C) 2011 Potix Corporation. All Rights Reserved.
{{IS_RIGHT
}}IS_RIGHT
*/
package org.zkoss.zkplus.databind;
import java.util.Iterator;
import java.util.Map;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.IdSpace;
import org.zkoss.zul.Combobox;
import org.zkoss.zul.Comboitem;
import org.zkoss.zul.Grid;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.Row;
/**
* @author simonpai
* @since 5.0.7
*/
public class BindingRendererUtil {
/**
* Link cloned components with bindings of templates
*/
/*package*/ static void linkTemplates(Component clone, Component template, Map templatemap, DataBinder binder) {
if (binder.existsBindings(template)) {
templatemap.put(template, clone);
clone.setAttribute(DataBinder.TEMPLATEMAP, templatemap);
clone.setAttribute(DataBinder.TEMPLATE, template);
}
final Iterator itt = template.getChildren().iterator();
final Iterator itc = clone.getChildren().iterator();
while (itt.hasNext()) {
final Component t = (Component) itt.next();
final Component c = (Component) itc.next();
// skip Listitem, Row, Comboitem
// Listbox in Listbox, Listbox in Grid, Grid in Listbox, Grid in Grid, etc.
// no need to process down since BindingRowRenderer of the under collection
// item will do its own linkTemplates()
if (isSkippable(t)) //bug#1968615.
continue;
linkTemplates(c, t, templatemap, binder); //recursive
}
}
/**
* Check if comp can be waived from linking templates
* @param comp
*/
private static boolean isSkippable(Component comp) {
// Bug: B50-3183438: skip only when it has model
if(comp instanceof Comboitem) {
Combobox b = (Combobox)((Comboitem) comp).getParent();
if(b != null && b.getModel() != null)
return true;
} else if(comp instanceof Row) {
Grid g = ((Row) comp).getGrid();
if(g != null && g.getModel() != null)
return true;
} else if(comp instanceof Listitem) {
Listbox b = (Listbox)((Listitem) comp).getListbox();
if(b != null && b.getModel() != null)
return true;
}
return false;
}
/**
* Setup id of cloned components (cannot called until the component is attached to Listbox)
*/
/*package*/ static void setupCloneIds(Component clone) {
//bug #1813271: Data binding generates duplicate ids in grids/listboxes
//Bug #1962153: Data binding generates duplicate id in some case (add "_")
clone.setId(null); //init id to null to avoid duplicate id issue
//Feature #3061671: Databinding foreach keep cloned cmp's id when in spaceowner
if (!(clone instanceof IdSpace)) { //parent is an IdSpace, so keep the id as is, no need to traverse down
for(final Iterator it = clone.getChildren().iterator(); it.hasNext(); ) {
final Component kid = (Component) it.next();
// skip Listitem, Row, Comboitem
// Listbox in Listbox, Listbox in Grid, Grid in Listbox, Grid in Grid, etc.
// no need to process down since BindingRowRenderer of the under collection
// item will do its own setupCloneIds()
if (isSkippable(kid)) //bug#1968615.
continue;
setupCloneIds(kid); //recursive
}
}
}
}
|
package a3.behaviour;
import a3.algorithm.ShortestPath;
import a3.memory.CollectiveMemory;
import a3.memory.model.Position;
import a3.memory.model.Tile;
import a3.utility.Calc;
import static a3.utility.Calc.distanceFromAtoB;
import static a3.utility.Calc.getMovementDirection;
import static a3.utility.Debug.print;
import static a3.utility.Debug.println;
import aiantwars.EAction;
import aiantwars.IAntInfo;
import aiantwars.ILocationInfo;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* @author Tobias Jacobsen
*/
public class Explore {
private final IAntInfo thisAnt;
private final ILocationInfo thisLocation;
private final CollectiveMemory cm;
public Explore(IAntInfo thisAnt, ILocationInfo thisLocation, CollectiveMemory cm) {
this.thisAnt = thisAnt;
this.thisLocation = thisLocation;
this.cm = cm;
}
/**
* Go's through all tiles in collective memory. Calculates distance to this
* location and calculates explorationPropensity on each tile.
* ExplorationPropensity (double value) is a factor of frequency, distance
* to queen spawn, distance to scout and the tile's potentially unexplored
* neighbors. The tile with the lowest value is the most attractive tile for
* the scout to go to.
*
* @return
*/
public EAction getAction() {
SortedSet<Tile> possibleLocations = new TreeSet(Tile.ExplorationPropensityComparator);
double unexploredFactor = 0.1;
// look through all tiles in collectiveMemory
for (Map.Entry<Position, Tile> entry : cm.getTiles().entrySet()) {
Tile tile = entry.getValue();
// if tile is not rock or filled and not thisLocation
if (!tile.isFilled() && !tile.isRock() && (tile.getX() != thisLocation.getX() || tile.getY() != thisLocation.getY())) {
// save distance toScout for later use in PropensityFactorComparator
tile.setDistanceToScout(distanceFromAtoB(tile, thisLocation));
// frequency * distance to queenspawn * distance to scout
double explorationPropensity = (tile.getFrequency() + 1) * (distanceFromAtoB(thisLocation, cm.getQueenSpawn()) + 1) * (tile.getDistanceToScout() + 1);
// if tile has unexplored neighbour, multiply by 0.1
if (cm.getTile(tile.getX() + "," + (tile.getY() + 1)) == null) { // north
explorationPropensity = explorationPropensity * unexploredFactor;
} else if (cm.getTile(tile.getX() + "," + (tile.getY() - 1)) == null) { // south
explorationPropensity = explorationPropensity * unexploredFactor;
} else if (cm.getTile((tile.getX() - 1) + "," + tile.getY()) == null) { // west
explorationPropensity = explorationPropensity * unexploredFactor;
} else if (cm.getTile((tile.getX() + 1) + "," + tile.getY()) == null) { // east
explorationPropensity = explorationPropensity * unexploredFactor;
}
// save explorationPropensity-factor to tile
tile.setExplorationPropensity(explorationPropensity);
possibleLocations.add(tile);
}
}
// find tile with lowest explorationPropensity-factor
if (possibleLocations.size() > 0) {
for (Tile t : possibleLocations) {
println("Scout: possible locations: " + t);
}
ShortestPath sp = new ShortestPath(thisAnt, thisLocation, possibleLocations.first(), cm);
List<ILocationInfo> shortestPath = sp.getShortestPath();
if (shortestPath != null) {
println("shortestPath ->");
for (ILocationInfo l : shortestPath) {
print("(" + l.getX() + "," + l.getY() + "),");
}
int movementDirection = getMovementDirection(thisLocation, shortestPath.get(0));
println("chosenLocation: " + possibleLocations.first());
println("chosenDirection: " + movementDirection);
return Calc.getMovementAction(thisAnt.getDirection(), movementDirection, false);
}
}
return EAction.Pass;
}
}
|
package com.example.scso.school_social;
/**
* Created by Administrator on 2017/7/8.
*/
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by Administrator on 2017/7/5.
*/
public class MyAdapter3 extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String,Object>> list;
private static LayoutInflater inflater=null;
public MyAdapter3(Activity a, ArrayList<HashMap<String,Object>> list){
this.activity=a;
this.list=list;
inflater=(LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
convertView=inflater.inflate(R.layout.servercheck_item,null);
}
TextView server_id = (TextView) convertView.findViewById(R.id.server_id);
TextView servername = (TextView) convertView.findViewById(R.id.servername);
TextView state = (TextView) convertView.findViewById(R.id.state);
TextView intro = (TextView) convertView.findViewById(R.id.intro);
HashMap<String,Object> info=new HashMap<>();
info=list.get(position);
// Log.d("tag", "getView: "+position);
// Log.d("tag", "getView: ------>"+convertView.getId());
server_id.setText((String)info.get("server_id"));
servername.setText((String)info.get("servername"));
state.setText((String)info.get("state"));
intro.setText((String)info.get("intro"));
return convertView;
}
}
|
package co.edu.campusucc.sd.modelo;
// Generated 23/05/2020 02:30:18 PM by Hibernate Tools 5.4.7.Final
import java.util.HashSet;
import java.util.Set;
/**
* TipoCuenta generated by hbm2java
*/
public class TipoCuenta implements java.io.Serializable {
private String idTipoCuenta;
private String nombre;
private Set cuentas = new HashSet(0);
public TipoCuenta() {
}
public TipoCuenta(String idTipoCuenta, String nombre) {
this.idTipoCuenta = idTipoCuenta;
this.nombre = nombre;
}
public TipoCuenta(String idTipoCuenta, String nombre, Set cuentas) {
this.idTipoCuenta = idTipoCuenta;
this.nombre = nombre;
this.cuentas = cuentas;
}
public String getIdTipoCuenta() {
return this.idTipoCuenta;
}
public void setIdTipoCuenta(String idTipoCuenta) {
this.idTipoCuenta = idTipoCuenta;
}
public String getNombre() {
return this.nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public Set getCuentas() {
return this.cuentas;
}
public void setCuentas(Set cuentas) {
this.cuentas = cuentas;
}
}
|
package com.pwc.sort.test;
import com.pwc.sort.BitMap;
import com.pwc.test.TestBase;
import com.pwc.util.BinaryObject;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
public class BitMapTest extends TestBase {
@Test
public void testSort() throws Exception {
final int from = 0;
final int to = 1024 * 1024 * 10 - 1;
final String fileName = "bitmap_sort_test";
BinaryObject.generateRandomNumber(from, to, fileName);
gc.add(fileName);
BitMap map = new BitMap(fileName);
String file = map.sort();
gc.add(file);
int[] a = BinaryObject.loadAsIntArray(file);
for (int i = from; i <= to; i++) {
assertEquals(i, a[i]);
}
}
}
|
package com.example.NFEspring.entity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import javax.persistence.*;
import javax.persistence.Entity;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
@Entity
@Table(name = "link_ticket")
public class LinkTicket implements Serializable {
@Id
@Column(name = "lk_tk_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@OneToOne
@JoinColumn(name = "lk_tk_link")
@NotNull
private Link link;
@ManyToOne
@JoinColumn(name = "lk_tk_referent_ticket")
@NotNull
@JsonIgnoreProperties({ "reporter", "assignees", "referents", "references", "data" })
private Ticket referent;
@ManyToOne
@JoinColumn(name = "lk_tk_reference_ticket")
@NotNull
@JsonIgnoreProperties({ "reporter", "assignees", "referents", "references", "data" })
private Ticket reference;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Link getLink() {
return link;
}
public void setLink(Link link) {
this.link = link;
}
public Ticket getReferent() {
return referent;
}
public void setReferent(Ticket referent) {
this.referent = referent;
}
public Ticket getReference() {
return reference;
}
public void setReference(Ticket reference) {
this.reference = reference;
}
}
|
/* Copyright 2015 Esri
*
* 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.esri.arcgis.android.samples.routing;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.esri.android.map.GraphicsLayer;
import com.esri.android.map.LocationDisplayManager;
import com.esri.android.map.LocationDisplayManager.AutoPanMode;
import com.esri.android.map.MapView;
import com.esri.android.map.ags.ArcGISTiledMapServiceLayer;
import com.esri.android.map.event.OnLongPressListener;
import com.esri.android.map.event.OnSingleTapListener;
import com.esri.core.geometry.GeometryEngine;
import com.esri.core.geometry.Point;
import com.esri.core.geometry.Polyline;
import com.esri.core.geometry.SpatialReference;
import com.esri.core.map.Graphic;
import com.esri.core.symbol.PictureMarkerSymbol;
import com.esri.core.symbol.SimpleLineSymbol;
import com.esri.core.symbol.SimpleMarkerSymbol;
import com.esri.core.tasks.na.NAFeaturesAsFeature;
import com.esri.core.tasks.na.Route;
import com.esri.core.tasks.na.RouteDirection;
import com.esri.core.tasks.na.RouteParameters;
import com.esri.core.tasks.na.RouteResult;
import com.esri.core.tasks.na.RouteTask;
import com.esri.core.tasks.na.StopGraphic;
public class RoutingSample extends Activity implements
RoutingListFragment.onDrawerListSelectedListener,
RoutingDialogFragment.onGetRoute {
public static MapView map = null;
ArcGISTiledMapServiceLayer tileLayer;
GraphicsLayer routeLayer, hiddenSegmentsLayer;
public LocationManager manager;
// Symbol used to make route segments "invisible"
SimpleLineSymbol segmentHider = new SimpleLineSymbol(Color.WHITE, 5);
// Symbol used to highlight route segments
SimpleLineSymbol segmentShower = new SimpleLineSymbol(Color.RED, 5);
// Label showing the current direction, time, and length
TextView directionsLabel;
// List of the directions for the current route (used for the ListActivity)
public static ArrayList<String> curDirections = null;
// Current route, route summary, and gps location
Route curRoute = null;
String routeSummary = null;
public static Point mLocation = null;
// Global results variable for calculating route on separate thread
RouteTask mRouteTask = null;
RouteResult mResults = null;
// Variable to hold server exception to show to user
Exception mException = null;
ImageView img_cancel;
ImageView img_currLocation;
ImageView img_getDirections;
public static DrawerLayout mDrawerLayout;
LocationDisplayManager ldm;
// Handler for processing the results
final Handler mHandler = new Handler();
final Runnable mUpdateResults = new Runnable() {
public void run() {
updateUI();
}
};
// Progress dialog to show when route is being calculated
ProgressDialog dialog;
// Spatial references used for projecting points
final SpatialReference wm = SpatialReference.create(102100);
final SpatialReference egs = SpatialReference.create(4326);
// Index of the currently selected route segment (-1 = no selection)
int selectedSegmentID = -1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
buildAlertMessageNoGps();
}
// Retrieve the map and initial extent from XML layout
map = (MapView) findViewById(R.id.map);
// Add tiled layer to MapView
tileLayer = new ArcGISTiledMapServiceLayer(
"http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer");
map.addLayer(tileLayer);
// Add the route graphic layer (shows the full route)
routeLayer = new GraphicsLayer();
map.addLayer(routeLayer);
// Initialize the RouteTask
try {
mRouteTask = RouteTask
.createOnlineRouteTask(
"http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Network/USA/NAServer/Route",
null);
} catch (Exception e1) {
e1.printStackTrace();
}
// Add the hidden segments layer (for highlighting route segments)
hiddenSegmentsLayer = new GraphicsLayer();
map.addLayer(hiddenSegmentsLayer);
// Make the segmentHider symbol "invisible"
segmentHider.setAlpha(1);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
img_cancel = (ImageView) findViewById(R.id.iv_cancel);
img_currLocation = (ImageView) findViewById(R.id.iv_myLocation);
img_getDirections = (ImageView) findViewById(R.id.iv_getDirections);
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
// Get the location display manager and start reading location. Don't
// auto-pan
// to center our position
ldm = map.getLocationDisplayManager();
ldm.setLocationListener(new MyLocationListener());
ldm.start();
ldm.setAutoPanMode(AutoPanMode.OFF);
// Set the directionsLabel with initial instructions.
directionsLabel = (TextView) findViewById(R.id.directionsLabel);
directionsLabel.setText(getString(R.string.route_label));
/**
* On single clicking the directions label, start a ListActivity to show
* the list of all directions for this route. Selecting one of those
* items will return to the map and highlight that segment.
*
*/
directionsLabel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (curDirections == null)
return;
mDrawerLayout.openDrawer(Gravity.END);
String segment = directionsLabel.getText().toString();
ListView lv = RoutingListFragment.mDrawerList;
for (int i = 0; i < lv.getCount() - 1; i++) {
String lv_segment = lv.getItemAtPosition(i).toString();
if (segment.equals(lv_segment)) {
lv.setSelection(i);
}
}
}
});
img_cancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
clearAll();
}
});
img_currLocation.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Point p = (Point) GeometryEngine.project(mLocation, egs, wm);
map.zoomToResolution(p, 20.0);
}
});
img_getDirections.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
RoutingDialogFragment frag_dialog = new RoutingDialogFragment();
ft.add(frag_dialog, "Dialog");
ft.commit();
}
});
/**
* On single tapping the map, query for a route segment and highlight
* the segment and show direction summary in the label if a segment is
* found.
*/
map.setOnSingleTapListener(new OnSingleTapListener() {
private static final long serialVersionUID = 1L;
public void onSingleTap(float x, float y) {
// Get all the graphics within 20 pixels the click
int[] indexes = hiddenSegmentsLayer.getGraphicIDs(x, y, 20);
// Hide the currently selected segment
hiddenSegmentsLayer.updateGraphic(selectedSegmentID,
segmentHider);
if (indexes.length < 1) {
// If no segments were found but there is currently a route,
// zoom to the extent of the full route
if (curRoute != null) {
map.setExtent(curRoute.getEnvelope(), 250);
directionsLabel.setText(routeSummary);
}
return;
}
// Otherwise update our currently selected segment
selectedSegmentID = indexes[0];
Graphic selected = hiddenSegmentsLayer
.getGraphic(selectedSegmentID);
// Highlight it on the map
hiddenSegmentsLayer.updateGraphic(selectedSegmentID,
segmentShower);
String direction = ((String) selected.getAttributeValue("text"));
double time = (Double) selected.getAttributeValue("time");
double length = (Double) selected.getAttributeValue("length");
// Update the label with this direction's information
String label = String.format("%s%n%.1f minutes (%.1f miles)",
direction, time, length);
directionsLabel.setText(label);
// Zoom to the extent of that segment
map.setExtent(selected.getGeometry(), 50);
}
});
/**
* On long pressing the map view, route from our current location to the
* pressed location.
*
*/
map.setOnLongPressListener(new OnLongPressListener() {
private static final long serialVersionUID = 1L;
public boolean onLongPress(final float x, final float y) {
final Point loc = map.toMapPoint(x, y);
Point p = (Point) GeometryEngine.project(loc, wm, egs);
clearAll();
QueryDirections(mLocation, p);
return true;
}
});
}
private void QueryDirections(final Point mLocation, final Point p) {
// Show that the route is calculating
dialog = ProgressDialog.show(RoutingSample.this, "Routing Sample",
"Calculating route...", true);
// Spawn the request off in a new thread to keep UI responsive
Thread t = new Thread() {
@Override
public void run() {
try {
// Start building up routing parameters
RouteParameters rp = mRouteTask
.retrieveDefaultRouteTaskParameters();
NAFeaturesAsFeature rfaf = new NAFeaturesAsFeature();
// Convert point to EGS (decimal degrees)
// Create the stop points (start at our location, go
// to pressed location)
StopGraphic point1 = new StopGraphic(mLocation);
StopGraphic point2 = new StopGraphic(p);
rfaf.setFeatures(new Graphic[] { point1, point2 });
rfaf.setCompressedRequest(true);
rp.setStops(rfaf);
// Set the routing service output SR to our map
// service's SR
rp.setOutSpatialReference(wm);
// Solve the route and use the results to update UI
// when received
mResults = mRouteTask.solve(rp);
mHandler.post(mUpdateResults);
} catch (Exception e) {
mException = e;
mHandler.post(mUpdateResults);
}
}
};
// Start the operation
t.start();
}
/**
* If GPS is disabled, app won't be able to route. Hence display a dialoge window to enable the GPS
*/
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Please enable your GPS before proceeding")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
});
final AlertDialog alert = builder.create();
alert.show();
}
/**
* Updates the UI after a successful rest response has been received.
*/
void updateUI() {
dialog.dismiss();
if (mResults == null) {
Toast.makeText(RoutingSample.this, mException.toString(),
Toast.LENGTH_LONG).show();
curDirections = null;
return;
}
// Creating a fragment if it has not been created
FragmentManager fm = getFragmentManager();
if (fm.findFragmentByTag("Nav Drawer") == null) {
FragmentTransaction ft = fm.beginTransaction();
RoutingListFragment frag = new RoutingListFragment();
ft.add(frag, "Nav Drawer");
ft.commit();
} else {
FragmentTransaction ft = fm.beginTransaction();
ft.remove(fm.findFragmentByTag("Nav Drawer"));
RoutingListFragment frag = new RoutingListFragment();
ft.add(frag, "Nav Drawer");
ft.commit();
}
// Unlock the NAvigation Drawer
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
// Making visible the cancel icon
img_cancel.setVisibility(View.VISIBLE);
curRoute = mResults.getRoutes().get(0);
// Symbols for the route and the destination (blue line, checker flag)
SimpleLineSymbol routeSymbol = new SimpleLineSymbol(Color.BLUE, 3);
PictureMarkerSymbol destinationSymbol = new PictureMarkerSymbol(
map.getContext(), getResources().getDrawable(
R.drawable.ic_action_place));
// Add all the route segments with their relevant information to the
// hiddenSegmentsLayer, and add the direction information to the list
// of directions
for (RouteDirection rd : curRoute.getRoutingDirections()) {
HashMap<String, Object> attribs = new HashMap<>();
attribs.put("text", rd.getText());
attribs.put("time", Double.valueOf(rd.getMinutes()));
attribs.put("length", Double.valueOf(rd.getLength()));
curDirections.add(String.format("%s%n%.1f minutes (%.1f miles)",
rd.getText(), rd.getMinutes(), rd.getLength()));
Graphic routeGraphic = new Graphic(rd.getGeometry(), segmentHider,
attribs);
hiddenSegmentsLayer.addGraphic(routeGraphic);
}
// Reset the selected segment
selectedSegmentID = -1;
// Add the full route graphics, start and destination graphic to the
// routeLayer
Graphic routeGraphic = new Graphic(curRoute.getRouteGraphic()
.getGeometry(), routeSymbol);
Graphic endGraphic = new Graphic(
((Polyline) routeGraphic.getGeometry()).getPoint(((Polyline) routeGraphic
.getGeometry()).getPointCount() - 1), destinationSymbol);
routeLayer.addGraphics(new Graphic[] { routeGraphic, endGraphic });
// Get the full route summary and set it as our current label
routeSummary = String.format("%s%n%.1f minutes (%.1f miles)",
curRoute.getRouteName(), curRoute.getTotalMinutes(),
curRoute.getTotalMiles());
directionsLabel.setText(routeSummary);
// Zoom to the extent of the entire route with a padding
map.setExtent(curRoute.getEnvelope(), 250);
// Replacing the first and last direction segments
curDirections.remove(0);
curDirections.add(0, "My Location");
curDirections.remove(curDirections.size() - 1);
curDirections.add("Destination");
}
private class MyLocationListener implements LocationListener {
public MyLocationListener() {
super();
}
/**
* If location changes, update our current location. If being found for
* the first time, zoom to our current position with a resolution of 20
*/
public void onLocationChanged(Location loc) {
if (loc == null)
return;
boolean zoomToMe = (mLocation == null);
mLocation = new Point(loc.getLongitude(), loc.getLatitude());
if (zoomToMe) {
Point p = (Point) GeometryEngine.project(mLocation, egs, wm);
map.zoomToResolution(p, 20.0);
}
}
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "GPS Disabled",
Toast.LENGTH_SHORT).show();
buildAlertMessageNoGps();
}
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "GPS Enabled",
Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
@Override
protected void onPause() {
super.onPause();
map.pause();
}
@Override
protected void onResume() {
super.onResume();
map.unpause();
}
/*
* When the user selects the segment from the listview, it gets highlighted
* on the map
*/
@Override
public void onSegmentSelected(String segment) {
if (segment == null)
return;
// Look for the graphic that corresponds to this direction
for (int index : hiddenSegmentsLayer.getGraphicIDs()) {
Graphic g = hiddenSegmentsLayer.getGraphic(index);
if (segment.contains((String) g.getAttributeValue("text"))) {
// When found, hide the currently selected, show the new
// selection
hiddenSegmentsLayer.updateGraphic(selectedSegmentID,
segmentHider);
hiddenSegmentsLayer.updateGraphic(index, segmentShower);
selectedSegmentID = index;
// Update label with information for that direction
directionsLabel.setText(segment);
// Zoom to the extent of that segment
map.setExtent(hiddenSegmentsLayer.getGraphic(selectedSegmentID)
.getGeometry(), 50);
break;
}
}
}
@Override
public void onDialogRouteClicked(Point p1, Point p2) {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.remove(fm.findFragmentByTag("Dialog")).commit();
Point p_start = (Point) GeometryEngine.project(p1, wm, egs);
Point p_dest = (Point) GeometryEngine.project(p2, wm, egs);
clearAll();
// Adding the symbol for start point
SimpleMarkerSymbol startSymbol = new SimpleMarkerSymbol(Color.DKGRAY,
15, SimpleMarkerSymbol.STYLE.CIRCLE);
Graphic gStart = new Graphic(p1, startSymbol);
routeLayer.addGraphic(gStart);
QueryDirections(p_start, p_dest);
}
/*
* Clear the graphics and empty the directions list
*/
public void clearAll() {
//Removing the graphics from the layer
routeLayer.removeAll();
hiddenSegmentsLayer.removeAll();
curDirections = new ArrayList<>();
mResults = null;
curRoute = null;
//Setting to default text
directionsLabel.setText(getString(R.string.route_label));
//Locking the Drawer
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
//Removing the cancel icon
img_cancel.setVisibility(View.GONE);
//Removing the RoutingListFragment if present
FragmentManager fm = getFragmentManager();
if (fm.findFragmentByTag("Nav Drawer") != null) {
FragmentTransaction ft = fm.beginTransaction();
ft.remove(fm.findFragmentByTag("Nav Drawer"));
ft.commit();
}
}
} |
package com.atm.factory;
import com.atm.dao.IAtmDAO;
import com.atm.dao.proxy.AtmDAOProxy;
public class AtmDAOFactory {
public static IAtmDAO getIAtmDAOInstance(){
return new AtmDAOProxy();
}
}
|
package towerofhanoi;
import java.util.EmptyStackException;
import stack.StackInterface;
/**
* Implentation of Linked Stack to be used in Tower of Hanoi.
* @author Daniel Xu <xudy>
* @version 2015.10.19
*
* @param <T> can take any type
*/
public class LinkedStack<T> implements StackInterface<T> {
private Node<T> topNode;
private int size;
/**
* Initializes the first node and the size to their
* default values.
*/
public LinkedStack()
{
topNode = null;
size = 0;
}
/**
* Size of the linked stack.
* @return int of the size.
*/
public int size()
{
return size;
}
/**
* Nullifies the first node in the stack so that
* all other nodes are nullified.
*/
@Override
public void clear() {
if (!this.isEmpty())
{
topNode.data = null;
topNode.next = null;
size = 0;
}
}
/**
* Checks whether the stack is empty.
* @return true or false whether the stack is empty.
*/
@Override
public boolean isEmpty() {
return size == 0;
}
/**
* Shows the most recent entry.
* @return the most recent entry
*/
@Override
public T peek() {
if (this.isEmpty())
{
throw new EmptyStackException();
}
else
{
return topNode.data;
}
}
/**
* Removes and returns the most recent entry.
* @return the most recent entry.
*/
@Override
public T pop() {
if (this.isEmpty())
{
throw new EmptyStackException();
}
else
{
T temp = topNode.data;
topNode = topNode.next;
size--;
return temp;
}
}
/**
* Adds a new node entry to the stack.
* @param anEntry entry to be added to the stack.
*/
@Override
public void push(T anEntry) {
Node<T> newNode = new Node<T>(anEntry, topNode);
topNode = newNode;
size++;
}
/**
* Returns the stack as a string
* @return String representation of the stack.
*/
@Override
public String toString()
{
LinkedStack<T> stack = this;
if (stack.size() == 0)
{
return "[]";
}
StringBuilder builder = new StringBuilder();
builder.append("[");
while (!stack.isEmpty())
{
builder.append(String.valueOf(stack.pop()));
if (stack.size() != 0)
{
builder.append(", ");
}
else
{
builder.append("]");
}
}
return builder.toString();
}
/**
* Private node class only used by LinkedStack.
* @author Daniel Xu <xudy>
* @version 2015.10.19
*
* @param <T> takes any type
*/
@SuppressWarnings("hiding")
private class Node<T>
{
private Node<T> next;
private T data;
/**
* Takes data and a next node.
* @param data Data in the node
* @param next Reference to the next node
*/
@SuppressWarnings("unused")
public Node(T data, Node<T> next)
{
this.data = data;
this.next = next;
}
/**
* Takes one parameter of data.
* @param data Data in the node.
*/
@SuppressWarnings("unused")
public Node(T data)
{
this.data = data;
}
/**
* Shows the next node.
* @return the next node.
*/
@SuppressWarnings("unused")
public Node<T> getNextNode()
{
return this.next;
}
/**
* Shows data in the current node.
* @return Data in the current node.
*/
@SuppressWarnings("unused")
public T getData()
{
return data;
}
/**
* Sets what the next node will be.
* @param newNext What the next node will be set as.
*/
@SuppressWarnings("unused")
public void setNextNode(Node<T> newNext)
{
next = newNext;
}
}
}
|
package com.dream.the.code.droidswatch;
/**
* This class is taken from https://github.com/bennapp/forwardBackwardChaining
*
* @author Ben Nappier ben2113
*
*/
public class Or extends Operator{
public Or(Variable first, Variable second){
this.first = first;
this.second = second;
this.token = "v";
}
public void op(){
if(this.first.set){
if(this.first.getValue()){
this.second.set(true);
this.second.setValue(true);
}
}
if(this.second.set){
if(this.second.getValue()){
this.second.set(true); //redundant
}
}else{
//this.second.set(false);
}
}
} |
package com.gagetalk.gagetalkcustomer.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by hyochan on 3/29/15.
*/
public class DBHelper extends SQLiteOpenHelper{
//Use Disturb Mode
public static final String DATABASE = "gagetalk.db";
// public static final String MY_MARKET_TABLE = "my_market_table";
public static final String CHAT_ROOM_TABLE = "chat_room_table";
public static final String CHAT_TABLE = "chat_table";
public static final int dbVersion = 2;
public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
/*
db.execSQL("CREATE TABLE " + MY_MARKET_TABLE + "(" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"market_name TEXT, " +
"tel TEXT, " +
"phone TEXT, " +
"img TEXT, " +
"email TEXT, " +
"address TEXT, " +
"category TEXT, " +
"homepage TEXT, " +
"description TEXT)"
);
*/
db.execSQL("CREATE TABLE " + CHAT_ROOM_TABLE + "(" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"mar_id TEXT, " +
"mar_name TEXT, " +
"cus_id TEXT, " +
"cus_name TEXT, " +
"message TEXT, " +
"type integer, " +
"path TEXT, " +
"send_date TEXT, " +
"read integer, " +
"sender TEXT " +
")"
);
db.execSQL("CREATE TABLE " + CHAT_TABLE + "(" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"mar_id TEXT, " +
"mar_name TEXT, " +
"cus_id TEXT, " +
"cus_name TEXT, " +
"message TEXT, " +
"type integer, " +
"path TEXT, " +
"send_date TEXT, " +
"read integer, " +
"sender TEXT " +
")"
);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// db.execSQL("DROP TABLE IF EXIST " + MY_MARKET_TABLE + ";");
db.execSQL("DROP TABLE IF EXISTS " + CHAT_ROOM_TABLE + ";");
db.execSQL("DROP TABLE IF EXISTS " + CHAT_TABLE + ";");
onCreate(db);
}
}
|
package ivge;
import java.lang.invoke.SwitchPoint;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Supplier;
public class Main {
public static void main(String[] args){
Deque<Element> queue = new ArrayDeque<>();
ArrayList<Computer> arrayList = new ArrayList<Computer>(){{
for (int i = 0; i < 100; i++)
add(new Computer());
}};
arrayList.forEach(System.out::println);
while (!(((Supplier<Boolean>) () -> {
for (Computer computer : arrayList)
if (computer.isComplete())
return Boolean.TRUE;
return Boolean.FALSE;
}).get())) {
for (int i = 0; i < 1000; i++)
queue.addFirst(((Supplier<Element>) () -> {
int a = (int) (Math.random() * 4);
Element ans = new Hard(-1);
switch (a) {
case 0:
ans = new Hard((int) (Math.random() * 100));
break;
case 1:
ans = new Ram((int) (Math.random() * 100));
break;
case 2:
ans = new MotherBoard((int) (Math.random() * 100));
break;
case 3:
ans = new Box((int) (Math.random() * 100));
break;
}
return ans;
}).get());
for (int i = 0; i < 1000; i++) {
Element element = queue.pollLast();
//бесполезная проверка
assert element != null;
String a = element.getClass().getName();
switch (a) {
case "ivge.Hard":
arrayList.get(element.getId()).setHard((Hard) element);
break;
case "ivge.Ram":
arrayList.get(element.getId()).setRam((Ram) element);
break;
case "ivge.MotherBoard":
arrayList.get(element.getId()).setMotherBoard((MotherBoard) element);
break;
case "ivge.Box":
arrayList.get(element.getId()).setBox((Box) element);
break;
}
;
}
System.out.println(arrayList);
}
}
} |
package ankang.springcloud.homework.common.service;
import ankang.springcloud.homework.common.dao.IdentifyingCodeDao;
import ankang.springcloud.homework.common.pojo.IdentifyingCode;
import org.springframework.stereotype.Service;
import java.util.Optional;
import java.util.Random;
/**
* @author: ankang
* @email: dreedisgood@qq.com
* @create: 2021-01-11
*/
@Service
public class IdentifyingCodeServiceImpl implements IdentifyingCodeService {
private static final int CODE_LENGTH = 6;
private static final Random RANDOM = new Random();
private final IdentifyingCodeDao identifyingCodeDao;
public IdentifyingCodeServiceImpl(IdentifyingCodeDao identifyingCodeDao) {
this.identifyingCodeDao = identifyingCodeDao;
}
@Override
public IdentifyingCode create() {
final StringBuilder sb = new StringBuilder(CODE_LENGTH);
for (int i = 0 ; i < sb.capacity() ; i++) {
sb.append(RANDOM.nextInt(10));
}
final IdentifyingCode code = new IdentifyingCode();
code.setCode(sb.toString());
identifyingCodeDao.save(code);
return code;
}
@Override
public boolean check(IdentifyingCode code) {
final Optional<IdentifyingCode> actual = identifyingCodeDao.findById(code.getId());
return actual.isPresent() && actual.get().getCode().equals(code.getCode());
}
}
|
package com.codigo.smartstore.webapi;
// package com.codigo.smartstore.webapi;
//
// import org.junit.Before;
// import org.junit.jupiter.api.Test;
// import org.junit.runner.RunWith;
// import org.mockito.ArgumentCaptor;
// import org.mockito.Mockito;
// import org.springframework.beans.factory.annotation.Autowired;
// import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
// import org.springframework.boot.test.context.TestConfiguration;
// import org.springframework.boot.test.mock.mockito.MockBean;
// import org.springframework.context.annotation.Bean;
// import org.springframework.data.domain.PageRequest;
// import org.springframework.data.domain.Pageable;
// import org.springframework.data.domain.Sort;
// import org.springframework.test.context.ContextConfiguration;
// import org.springframework.test.context.junit4.SpringRunner;
// import org.springframework.test.context.web.WebAppConfiguration;
// import org.springframework.test.web.servlet.MockMvc;
// import org.springframework.test.web.servlet.setup.MockMvcBuilders;
// import org.springframework.web.context.WebApplicationContext;
//
//
// import com.codigo.smartstore.webapi.controllers.PagedController;
// import com.codigo.smartstore.webapi.repository.EmployeeRepository;
// import com.codigo.smartstore.webapi.services.CustomerService;
// import com.codigo.smartstore.webapi.services.ICustomerService;
//
//// import static io.reflectoring.paging.PageableAssert.*;
//// import static io.reflectoring.paging.SortAssert.*;
//
// import static com.codigo.smartstore.webapi.PageableAssert.*;
//
// import static org.mockito.Mockito.*;
// import static
// org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
// import static
// org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
//
// @RunWith(SpringRunner.class)
// @WebMvcTest(
// controllers = PagedController.class
// // If we exclude SpringDataWebAutoConfiguration, the Pageable parameter will
// not be resolved.
// // If we only exclude it on the Application class itself, the test will still
// work!!!
// // excludeAutoConfiguration = SpringDataWebAutoConfiguration.class
// )
// @WebAppConfiguration
//// @ContextConfiguration(classes = {
//// SpringMockMvcConfiguration.class
//// })
// class PagedControllerTest {
//
// @TestConfiguration
// protected static class Config {
//
// @Bean
// public ICustomerService languageService() {
// return Mockito.mock(CustomerService.class);
// }
// }
//
// @Autowired
// private PagedController languageApiController;
//
// @MockBean
// private EmployeeRepository characterRepository;
//
// @Autowired
// private MockMvc mockMvc;
//
// @Autowired
// private WebApplicationContext webApplicationContext;
//
// @Before
// public void setUp() {
//// mockMvc = MockMvcBuilders
//// .standaloneSetup(languageApiController)
//// .build();
//
// mockMvc = MockMvcBuilders
// .webAppContextSetup(webApplicationContext)
// .build();
// }
//
// @Test
// void evaluatesPageableParameter() throws Exception {
//
// mockMvc.perform(get("/characters/page")
// .param("page", "5")
// .param("size", "10")
// .param("sort", "id,desc") // <-- no space after comma!!!
// .param("sort", "name,asc")) // <-- no space after comma!!!
// .andExpect(status().isOk());
//
// ArgumentCaptor<Pageable> pageableCaptor =
// ArgumentCaptor.forClass(Pageable.class);
// verify(characterRepository).findAllPage(pageableCaptor.capture());
// PageRequest pageable = (PageRequest) pageableCaptor.getValue();
//
// assertThat(pageable).hasPageNumber(5);
// assertThat(pageable).hasPageSize(10);
// assertThat(pageable).hasSort("name", Sort.Direction.ASC);
// assertThat(pageable).hasSort("id", Sort.Direction.DESC);
// }
//
// @Test
// void evaluatesQualifier() throws Exception {
//
// mockMvc.perform(get("/characters/qualifier")
// .param("my_page", "5")
// .param("my_size", "10")
// .param("my_sort", "id,desc") // <-- no space after comma!!!
// .param("my_sort", "name,asc")) // <-- no space after comma!!!
// .andExpect(status().isOk());
//
// ArgumentCaptor<Pageable> pageableCaptor =
// ArgumentCaptor.forClass(Pageable.class);
// verify(characterRepository).findAllPage(pageableCaptor.capture());
// PageRequest pageable = (PageRequest) pageableCaptor.getValue();
//
// assertThat(pageable).hasPageNumber(5);
// assertThat(pageable).hasPageSize(10);
// assertThat(pageable).hasSort("name", Sort.Direction.ASC);
// assertThat(pageable).hasSort("id", Sort.Direction.DESC);
// }
//
// @Test
// void setsUpperPageLimit() throws Exception {
//
// mockMvc.perform(get("/characters/page")
// .param("size", "10000"))
// .andExpect(status().isOk());
//
// ArgumentCaptor<Pageable> pageableCaptor =
// ArgumentCaptor.forClass(Pageable.class);
// verify(characterRepository).findAllPage(pageableCaptor.capture());
// PageRequest pageable = (PageRequest) pageableCaptor.getValue();
//
// assertThat(pageable).hasPageSize(2_000);
// }
//
// @Test
// void evaluatesPageableDefault() throws Exception {
//
// mockMvc.perform(get("/characters/page"))
// .andExpect(status().isOk());
//
// ArgumentCaptor<Pageable> pageableCaptor =
// ArgumentCaptor.forClass(Pageable.class);
// verify(characterRepository).findAllPage(pageableCaptor.capture());
// PageRequest pageable = (PageRequest) pageableCaptor.getValue();
//
// assertThat(pageable).hasPageNumber(0);
// assertThat(pageable).hasPageSize(20);
// assertThat(pageable).hasSort("name", Sort.Direction.DESC);
// assertThat(pageable).hasSort("id", Sort.Direction.ASC);
// }
//
// @Test
// void returnsSlice() throws Exception {
//
// mockMvc.perform(get("/characters/slice")
// .param("page", "5")
// .param("size", "10")
// .param("sort", "id,desc") // <-- no space after comma!!!
// .param("sort", "name,asc")) // <-- no space after comma!!!
// .andExpect(status().isOk());
//
// ArgumentCaptor<Pageable> pageableCaptor =
// ArgumentCaptor.forClass(Pageable.class);
// verify(characterRepository).findAllSlice(pageableCaptor.capture());
// PageRequest pageable = (PageRequest) pageableCaptor.getValue();
//
// assertThat(pageable).hasPageNumber(5);
// assertThat(pageable).hasPageSize(10);
// assertThat(pageable).hasSort("name", Sort.Direction.ASC);
// assertThat(pageable).hasSort("id", Sort.Direction.DESC);
// }
//
// @Test
// void evaluatesSortParameter() throws Exception {
//
// mockMvc.perform(get("/characters/sorted")
// .param("sort", "id,desc") // <-- no space after comma!!!
// .param("sort", "name,asc")) // <-- no space after comma!!!
// .andExpect(status().isOk());
//
// ArgumentCaptor<Sort> sortCaptor = ArgumentCaptor.forClass(Sort.class);
// verify(characterRepository).findAllSorted(sortCaptor.capture());
// Sort sort = sortCaptor.getValue();
//
//// PageableAssert.assertThat(sort).hasSort("name", Sort.Direction.ASC);
//// assertThat(sort).hasSort("id", Sort.Direction.DESC);
// }
// } |
package com.sinodynamic.hkgta.dao.crm;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.sinodynamic.hkgta.dao.GenericDao;
import com.sinodynamic.hkgta.entity.crm.UserDevice;
import com.sinodynamic.hkgta.util.constant.Constant;
@Repository
public class UserDeviceDaoImpl extends GenericDao<UserDevice> implements UserDeviceDao {
@Override
public int deleteUserDevice(String userId,String arnApplication)
{
String hql = "update UserDevice set status = ? where userId = ? and arnApplication =? ";
List<Serializable> params = new ArrayList<Serializable>();
params.add(Constant.Status.CAN.name());
params.add(userId);
params.add(arnApplication);
return super.hqlUpdate(hql, params);
}
@Override
public UserDevice getUserDeviceByApplication(String userId, String arnApplication) {
StringBuilder hql = new StringBuilder();
hql.append("from UserDevice where userId = ? ");
List<Serializable> params = new ArrayList<Serializable>();
params.add(userId);
if (arnApplication != null) {
hql.append(" and arnApplication = ? ");
params.add(arnApplication);
}
return (UserDevice) super.getUniqueByHql(hql.toString(), params);
}
}
|
package br.usjt.chatbot;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
/**
* Created by tnf98 on 18/04/2018.
*/
public class Database {
public Usuario inserir(Usuario usuario){
DatabaseReference raiz = FirebaseDatabase.getInstance().getReference();
raiz.child("usuarios").push().setValue(usuario);
return usuario;
}
}
|
package com.github.simy4.poc;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
import com.amazonaws.services.dynamodbv2.util.TableUtils;
import com.github.simy4.poc.model.ModifiableEntity;
import io.awspring.cloud.core.region.RegionProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
/** Starting point of this application. */
@SpringBootApplication
public class ImmutablesDynamoDbMapperPocApplication {
public static void main(String[] args) {
SpringApplication.run(ImmutablesDynamoDbMapperPocApplication.class, args);
}
// AWS v1
@Bean
public AmazonDynamoDB dynamoDB(
AWSCredentialsProvider awsCredentialsProvider,
@Value("${aws.local.endpoint:#{null}}") String localEndpoint,
RegionProvider regionProvider) {
var builder = AmazonDynamoDBClientBuilder.standard().withCredentials(awsCredentialsProvider);
builder =
null == localEndpoint
? builder.withRegion(regionProvider.getRegion().getName())
: builder.withEndpointConfiguration(
new AwsClientBuilder.EndpointConfiguration(
localEndpoint, regionProvider.getRegion().getName()));
return builder.build();
}
@Bean
public ApplicationRunner dynamoDBInitializer(
AmazonDynamoDB dynamoDB, DynamoDBMapper dynamoDBMapper) {
return args -> {
var request = dynamoDBMapper.generateCreateTableRequest(ModifiableEntity.class);
TableUtils.createTableIfNotExists(
dynamoDB, request.withProvisionedThroughput(new ProvisionedThroughput(2L, 2L)));
TableUtils.waitUntilActive(dynamoDB, request.getTableName());
};
}
@Bean
public DynamoDBMapper dynamoDBMapper(AmazonDynamoDB dynamoDB, Environment env) {
var builder = DynamoDBMapperConfig.builder();
builder.setTableNameResolver(
(clazz, config) -> {
var dynamoDBTable = clazz.getAnnotation(DynamoDBTable.class);
return env.resolvePlaceholders(dynamoDBTable.tableName());
});
return new DynamoDBMapper(dynamoDB, builder.build());
}
}
|
class Date{
private int year;
private String month;
private int day;
public Date() {
month = "1¿ù";
day = 1;
year = 2009;
}
public Date(int year, String month, int day) {
setDate(year,month,day);
}
public Date(int year) {
setDate(year, "1¿ù", 1);
}
public void setDate(int year, String month, int day) {
this.month = month;
this.day = day;
this.year = year;
}
}
public class two {
public static void main(String args[]) {
Date date1 = new Date(2009,"3¿ù",2);
Date date2 = new Date(2010);
Date date3 = new Date();
}
}
|
/*
* Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.jet.beam.transforms;
import org.apache.beam.sdk.PipelineResult;
import org.apache.beam.sdk.testing.PAssert;
import org.apache.beam.sdk.transforms.FlatMapElements;
import org.apache.beam.sdk.transforms.Impulse;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.TypeDescriptors;
import org.junit.Ignore;
import org.junit.Test;
import java.util.Arrays;
import static junit.framework.TestCase.assertEquals;
/* "Inspired" by org.apache.beam.sdk.transforms.ImpulseTest */
public class ImpulseTest extends AbstractTransformTest {
@Test
@Ignore //this test fail when there is parallelism, because the data is emitted multiple times...
public void testImpulse() {
PCollection<Integer> result =
pipeline.apply(Impulse.create())
.apply(
FlatMapElements.into(TypeDescriptors.integers())
.via(impulse -> Arrays.asList(1, 2, 3)));
PAssert.that(result).containsInAnyOrder(1, 2, 3);
PipelineResult.State state = pipeline.run().waitUntilFinish();
assertEquals(PipelineResult.State.DONE, state);
}
}
|
package fr.centralesupelec.sio.endpoints;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import fr.centralesupelec.sio.data.MoviesRepository;
import fr.centralesupelec.sio.endpoints.utils.ResponseHelper;
import fr.centralesupelec.sio.model.Director;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
/**
* A servlet to access the list of {@link Director}s.
*/
@WebServlet(urlPatterns = "/directors")
public class DirectorsServlet extends HttpServlet{
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Get directors from the repository.
//Pagination parameters
String limitParameter = req.getParameter("limit");
String offsetParameter = req.getParameter("offset");
int limit;
int offset;
// Manage limit parameter (default value of 15).
if (limitParameter == null || limitParameter.isEmpty()) {
limit= 15;
}
else {
limit = Integer.parseInt(limitParameter);
}
// Manage offset parameter (default value of 0).
if (offsetParameter == null || offsetParameter.isEmpty()) {
offset = 0;
}
else {
offset = Integer.parseInt(offsetParameter);
}
// Get a list of all the directors in the movies
List<String> directors = MoviesRepository.getInstance().getDirectors();
// Cast to a TreeSet to obtain an ordered list of unique elements and apply pagination parameters
Set<String> uniqueDirectors = new TreeSet<>(directors);
uniqueDirectors = uniqueDirectors.stream().limit(limit).skip(offset)
.collect(Collectors.toCollection(TreeSet::new));
// Write to the response.
ResponseHelper.writeJsonResponse(resp, uniqueDirectors);
}
}
|
package al.ahgitdevelopment.municion;
import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginPasswordActivity extends AppCompatActivity {
ActionBar actionBar;
SharedPreferences prefs;
EditText password;
Button button;
/**
* Inicializa la actividad
*
* @param savedInstanceState Instancia del estado de la activity
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final SharedPreferences prefs = getSharedPreferences("Preferences", Context.MODE_PRIVATE);
password = (EditText) findViewById(R.id.password);
button = (Button) findViewById(R.id.continuar);
// Registro de contraseña
if (!prefs.contains("password")) {
password.setHint(getResources().getString(R.string.lbl_password));
button.setText(R.string.guardar);
} else {
password.setHint(getResources().getString(R.string.lbl_insert_password));
button.setText(R.string.login);
}
//Añadimos la contraseña a las preferencias
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CheckPassword(prefs);
}
});
password.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
switch (actionId) {
case EditorInfo.IME_ACTION_DONE:
CheckPassword(prefs);
break;
default:
Toast.makeText(LoginPasswordActivity.this, "IME erroneo", Toast.LENGTH_SHORT).show();
}
return true;
}
});
}
/**
* Validación de la contraseña para poder entrar a la aplicación
*
* @param prefs Preferencias
*/
private void CheckPassword(SharedPreferences prefs) {
// Registro de usuario
if (!prefs.contains("password")) {
if (savePassword()) { // Guardamos la contraseña
Toast.makeText(LoginPasswordActivity.this, "Contraseña guardada", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(LoginPasswordActivity.this, FragmentMainActivity.class);
startActivity(intent);
finish();
} else { // Fallo al guardar la contraseñas
password.setText("");
password.setError(getResources().getString(R.string.password_save_fail));
}
}
// Login de usuario
else {
if (!checkPassword()) { // Password erronea
password.setText("");
password.setError(getResources().getString(R.string.password_fail));
} else { // Password correcta
Toast.makeText(LoginPasswordActivity.this, "Login Correcto", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(LoginPasswordActivity.this, FragmentMainActivity.class);
startActivity(intent);
finish();
}
}
}
/**
* Guarda la contraseña en el sharedPreference
*
* @return Contraseña valida o no
*/
private boolean savePassword() {
boolean flag = false;
if (prefs == null)
prefs = getSharedPreferences("Preferences", Context.MODE_PRIVATE);
if (password.getText().toString().length() > 4) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("password", password.getText().toString());
editor.commit();
flag = true;
} else
flag = false;
return flag;
}
/**
* Valida la contraseña introducida por el usuario frente a la guardad en el sharedPreferences
*
* @return Contraseña valida o invalida
*/
private boolean checkPassword() {
if (prefs == null)
prefs = getSharedPreferences("Preferences", Context.MODE_PRIVATE);
String pass = prefs.getString("password", "");
return pass.equals(password.getText().toString());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_login, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent = new Intent(LoginPasswordActivity.this, SettingsActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
}
|
package otf.obj.msg.remote;
import otf.model.ServerDataModel;
/**
* @author ⋈
*
*/
public class GetBloodSugarValuesRequest implements ExecutableRequest
{
/**
* @see otf.obj.msg.remote.ExecutableRequest#execute()
*/
@Override
public ExecutableResponse execute()
{
var list = ServerDataModel.get().getBloodSugarValues();
var response = new GetBloodSugarValuesResponse();
response.setBloodSugarValues(list);
return response;
}
} |
package com.cs.casino.game;
import com.cs.avatar.Avatar;
import com.cs.avatar.AvatarBaseType;
import com.cs.avatar.HairColor;
import com.cs.avatar.Level;
import com.cs.avatar.SkinColor;
import com.cs.casino.player.TestConfig;
import com.cs.game.Channel;
import com.cs.game.Game;
import com.cs.game.GameDto;
import com.cs.game.GameInfo;
import com.cs.game.GameService;
import com.cs.game.GameTransactionService;
import com.cs.game.LeaderboardEntry;
import com.cs.payment.Money;
import com.cs.persistence.Language;
import com.cs.player.Player;
import com.cs.player.PlayerService;
import com.cs.player.Wallet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.result.ContentResultMatchers;
import org.springframework.web.context.WebApplicationContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static com.cs.persistence.Language.ENGLISH;
import static com.cs.persistence.Status.ACTIVE;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.when;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
/**
* @author Omid Alaepour
*/
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = {TestConfig.class, GameController.class})
public class GameControllerIntegrationTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext context;
@Autowired
private FilterChainProxy springSecurityFilter;
@Autowired
private ObjectMapper mapper;
@Autowired
private GameService gameService;
@Autowired
private PlayerService playerService;
@Mock
private GameTransactionService gameTransactionService;
@Before
public void setup() {
mockMvc = webAppContextSetup(context).build();
}
private GameInfo createGameInfo() {
final GameInfo gameInfo = new GameInfo();
gameInfo.setId(1L);
gameInfo.setGame(new Game("BlackJack"));
gameInfo.setLanguage(ENGLISH);
return gameInfo;
}
private GameInfoDto createGameInfoDto() {
return new GameInfoDto(createGameInfo(), "Session-123", "BlingCity");
}
private Player createPlayerWithAvatarAndWallet() {
final Player player = new Player();
player.setId(0L);
player.setWallet(new Wallet());
player.setFirstName("First");
player.setLastName("Last");
player.setEmailAddress("email@email.com");
player.setPassword("$2a$10$9UhOj9mS294sxq0NyIwMb.N5fYvJNRCyGDbI3RD0xF8W1AXs3aRyG");
player.setNickname("Nick");
player.setBirthday(new Date(20120101));
player.setStatus(ACTIVE);
final AvatarBaseType avatarBaseType = new AvatarBaseType();
avatarBaseType.setId(1);
final Avatar avatar = new Avatar(1L);
avatar.setHairColor(HairColor.DARK);
avatar.setSkinColor(SkinColor.CAUCASIAN);
avatar.setPictureUrl("");
avatar.setAvatarBaseType(avatarBaseType);
avatar.setLevel(new Level(1L));
final Level level = new Level();
level.setLevel(1L);
level.setCashbackPercentage(new BigDecimal("2"));
level.setTurnover(new Money(3L));
player.setAvatar(avatar);
player.setLevel(level);
return player;
}
private List<GameInfo> createActiveGames() {
final Game game1 = new Game();
game1.setGameId("BJ");
game1.setStatus(ACTIVE);
final List<GameInfo> games = new ArrayList<>();
final GameInfo gameInfo = new GameInfo();
gameInfo.setGame(game1);
games.add(gameInfo);
return games;
}
//CAS-553. Penthouse
private List<LeaderboardEntry> getLeadersForTheWeek() {
Object[] player = Arrays.asList(3655, 9, 29, "s1h3.png", "Alessandro", "wish-master", "The Wish Master", new BigDecimal(18200), 0).toArray();
List<LeaderboardEntry> leaderboardEntryList = new ArrayList<>();
LeaderboardEntry leaderboardEntry = new LeaderboardEntry(player);
leaderboardEntryList.add(leaderboardEntry);
return leaderboardEntryList;
}
//CAS-553. Penthouse
private LeaderboardDto buildLeaderboardDto(List<LeaderboardEntry> playerList){
LeaderboardDto leaderboardDto = new LeaderboardDto(playerList);
return leaderboardDto;
}
private Set<GameDto> convert(final List<GameInfo> games) {
final Set<GameDto> gameDtos = new HashSet<>();
if (games != null) {
for (final GameInfo game : games) {
gameDtos.add(new GameDto(game));
}
}
return gameDtos;
}
@Test
@Ignore
public void playGame_ShouldReturnGameInfoDtoWithPlayerIdAndSessionId()
throws Exception {
final Player player = createPlayerWithAvatarAndWallet();
final GameInfoDto gameInfoDto = createGameInfoDto();
final GameInfo gameInfo = createGameInfo();
mockMvc = webAppContextSetup(context).addFilter(springSecurityFilter, "/*").build();
when(playerService.getPlayer(anyLong())).thenReturn(player);
when(gameService.getGameInfo(any(Game.class), any(Language.class))).thenReturn(gameInfo);
when(gameService.loginPlayer(any(Player.class), any(Channel.class))).thenReturn("Session-123");
final String sentContent = mapper.writeValueAsString(gameInfoDto);
final String expectedContent = mapper.writeValueAsString(gameInfoDto);
mockMvc.perform(
post("/api/games/").content(sentContent).contentType(APPLICATION_JSON).accept(APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().string(expectedContent));
}
@Test
@Ignore
public void activeGames_ShouldReturnActiveGames()
throws Exception {
final Player player = createPlayerWithAvatarAndWallet();
final List<GameInfo> activeGames = createActiveGames();
when(gameService.getActiveGames(player.getLanguage())).thenReturn(activeGames);
final String expectedContent = mapper.writeValueAsString(convert(activeGames));
mockMvc = webAppContextSetup(context).addFilter(springSecurityFilter, "/*").build();
final ContentResultMatchers content = content();
mockMvc.perform(
get("/api/games/").contentType(APPLICATION_JSON).accept(APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content.string(expectedContent));
}
@Test
@Ignore
public void shouldReturnPenthousePlayerList()
throws Exception {
List<LeaderboardEntry> playerList = getLeadersForTheWeek();
when(gameTransactionService.getLeaderPlayersOfTheWeek((Date)any())).thenReturn(playerList);
final String expectedContent = mapper.writeValueAsString(buildLeaderboardDto(playerList));
mockMvc = webAppContextSetup(context).addFilter(springSecurityFilter, "/*").build();
final ContentResultMatchers content = content();
mockMvc.perform(
get("/api/games/weekly").contentType(APPLICATION_JSON).accept(APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content.string(expectedContent));
}
}
|
package com.sevael.lgtool.dao;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.client.MongoDatabase;
import com.mongodb.gridfs.GridFSDBFile;
public interface CommonDBDao {
public int getNextSequence(MongoDatabase db, String collName);
public Document getEntityWithFilter(String databaseName, String collName, Bson filter, Bson projection);
public List<Document> getAllEntity(String databaseName, String collName, Bson filter, Bson sort, Bson projection,
int limit);
public List<Document> searchContact(String searchstr, String collName);
public String randomColor();
GridFSDBFile getImage(String filename, String dbName);
String saveImage(InputStream file, String filename, String dbName) throws IOException;
public List<Document> getAllEntityWithPagination(String databaseName, String collName, Bson filter, Bson sort,
Bson projection, int skip, int limit);
}
|
package com.shubhamnegi.flashchatnewfirebase;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import java.util.ArrayList;
public class ChatListAdapter extends BaseAdapter {
// Base Adapter --> https://developer.android.com/reference/android/widget/BaseAdapter
// Member Variables
private Activity mActivity;
private DatabaseReference mDatabaseReference;
private String mDisplayName;
private ArrayList<DataSnapshot> mSnapshotList;
/* DataSnapshot is a type used by Firebase for passing the data from database back to our app.
Every time we read from a cloud database, we receive the data in a form of DataSnapshot.
DataSnapshot --> https://firebase.google.com/docs/reference/android/com/google/firebase/database/DataSnapshot
*/
/*
ChildEventListener is a listener that will get notified if there have been any changes to the database.
For eg. when someone sends a message and new data gets added to our database, that qualifies as a change
and our listener will report back.
ChildEventListener --> https://firebase.google.com/docs/reference/android/com/google/firebase/database/ChildEventListener
*/
private ChildEventListener mListener = new ChildEventListener() {
// Fired when new chat message is added to the database
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
mSnapshotList.add(dataSnapshot);
notifyDataSetChanged();
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
// Constructor of ChatListAdapter
public ChatListAdapter(Activity activity, DatabaseReference ref, String name) {
mActivity = activity;
mDisplayName = name;
// common error: typo in the db location. Needs to match what's in MainChatActivity.
mDatabaseReference = ref.child("messages");
mDatabaseReference.addChildEventListener(mListener);
mSnapshotList = new ArrayList<>();
}
// Inner class --> Class inside a class
private static class ViewHolder{
TextView authorName;
TextView body;
LinearLayout.LayoutParams params;
}
/**
* Overriding Methods of Base Adapter
*/
@Override
public int getCount() {
return mSnapshotList.size();
}
@Override
// Returning item of type InstantMessage
public InstantMessage getItem(int position) {
DataSnapshot snapshot = mSnapshotList.get(position);
// The DataSnapshot actually comes in the form of JSON and contains our chat message data.
return snapshot.getValue(InstantMessage.class); // converts the JSON from the snapshot into an InstantMessage object
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
/*
Creating an individual row from scratch for each list item is computationally expensive, and it would be a crappy user experience if our phone starts lagging as we are scrolling through the list.
One way to avoid a lag is to load up the entire list into memory. However, if we have a list of thousand items, we cannot possibly load all these rows at once.
So the solution is, as soon as a row scroll out of the sight, we need to keep hold of the view that make up that row. And when a new row scrolls on the screen,
we will supply that row with the view that we've used before, but we will populate the view wit new data.
Reconfiguring an existing row has a big performance advantage because we don't constantly create and destroy the same type of object.
*/
/*
Checking if there's an existing row that can be reused :
The convertView here represents a list item. If it exists (convertView != null) , we can reconfigure it.
And if it does not exists (convertView == null), then we have to create a new row from the layout file.
*/
if (convertView == null) {
/*
Creating new row from scratch
*/
// To create a view from a layout XML file, we need a component called the layoutInflater
LayoutInflater inflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// With the inflate method, we will supply our chat_msg_row.xml file and stick that into the convertView.
convertView = inflater.inflate(R.layout.chat_msg_row, parent, false);
// This is the inner helper class that will hold onto all the things that make up an individual chat_msg_row.
final ViewHolder holder = new ViewHolder();
// Linking the fields of the ViewHolder to the views in the chat_msg_row
holder.authorName = convertView.findViewById(R.id.author);
holder.body = convertView.findViewById(R.id.message);
holder.params = (LinearLayout.LayoutParams) holder.authorName.getLayoutParams();
/* Finally we need to give the adapter a way of storing our ViewHolder for a short period of time so that we can reuse it later.
Reusing the ViewHolder will allow us to avoid calling findViewById() method.
Using the setTag() method to temporarily store our ViewHolder in the convertView
*/
convertView.setTag(holder);
}
/**
* No need to create a new row from the scratch
*/
// Getting the InstantMessage at the current position in the list
final InstantMessage message = getItem(position);
// Using the getTag() method in order to retrieve the ViewHolder that was temporarily saved in the convertView
final ViewHolder holder = (ViewHolder) convertView.getTag();
// For checking which user have sent the chat and style the chat messages accordingly
boolean isMe = message.getAuthor().equals(mDisplayName);
setChatRowAppearance(isMe, holder);
/* The viewHolder that we just fetched from the convertView is still going to have the old data in it from the previous time that it was used.
So we're going to change that by replacing the old data.
*/
String author = message.getAuthor();
holder.authorName.setText(author);
String msg = message.getMessage();
holder.body.setText(msg);
// If convertView != null, return convertView
return convertView;
}
// Method for styling the chat messages
private void setChatRowAppearance(boolean isItMe, ViewHolder holder) {
if (isItMe) {
// If message belongs to the sending user, change the layout of entire row to align to the right and change the color of the Author name to green
holder.params.gravity = Gravity.END;
holder.authorName.setTextColor(Color.GREEN);
// If you want to use colours from colors.xml
// int colourAsARGB = ContextCompat.getColor(mActivity.getApplicationContext(), R.color.yellow);
// holder.authorName.setTextColor(colourAsARGB);
// Wrapping chat message in speech bubble
holder.body.setBackgroundResource(R.drawable.bubble2); // bubble2.9.png --> Image file of type 9 patch
} else {
// If message belongs to the other user, change the layout of entire row to align to the left and change the color of the Author name to blue
holder.params.gravity = Gravity.START;
holder.authorName.setTextColor(Color.BLUE);
// Wrapping chat message in speech bubble
holder.body.setBackgroundResource(R.drawable.bubble1); // bubble1.9.png --> Image file of type 9 patch
}
holder.authorName.setLayoutParams(holder.params);
holder.body.setLayoutParams(holder.params);
/*
9 patch image file defines a set of pixels which can be stretched in any direction.
It helps in creating a speech bubble effect and cover the entire chat message regardless if the message is short or long
9 Patch Graphics --> https://developer.android.com/guide/topics/graphics/drawables#nine-patch
Creating 9 Patch Graphics --> https://developer.android.com/studio/write/draw9patch
*/
}
/*
Calling method to stop checking for new events on the firebase's database so that we can free up resources when we don't need them anymore
*/
void cleanup() {
// Removes the firebase event listener when the app leaves the foreground
mDatabaseReference.removeEventListener(mListener);
}
}
|
package com.example.vplayer.ui.activity;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import com.example.vplayer.R;
public class SettingsActivity extends AppCompatActivity {
ImageView back_setting;
RelativeLayout lout_privacy_policy, lout_rate_us, lout_share_us, lout_about_us;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
getWindow().setStatusBarColor(getResources().getColor(R.color.black, this.getTheme()));
getWindow().setNavigationBarColor(ContextCompat.getColor(this, R.color.black));
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setNavigationBarColor(ContextCompat.getColor(this, R.color.black));
getWindow().setStatusBarColor(getResources().getColor(R.color.black));
}
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
//getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.darkGray)));
setContentView(R.layout.activity_settings);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
back_setting = findViewById(R.id.back_setting);
lout_privacy_policy = findViewById(R.id.lout_privacy_policy);
lout_rate_us = findViewById(R.id.lout_rate_us);
lout_share_us = findViewById(R.id.lout_share_us);
lout_about_us = findViewById(R.id.lout_about_us);
back_setting.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
lout_privacy_policy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(SettingsActivity.this, PrivacyPolicyActivity.class));
}
});
lout_share_us.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "https://play.google.com/store/apps/details?id=" + getPackageName();
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, getResources().getString(R.string.app_name));
sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
});
/*lout_share_us.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
String shareUrl = "https://play.google.com/store/apps/details?id=" + getPackageName() + "";
share.putExtra(Intent.EXTRA_SUBJECT, getResources().getString(R.string.app_name));
share.putExtra(Intent.EXTRA_TEXT, "Click on below link to download " + getResources().getString(R.string.app_name) + "\n" + shareUrl);
startActivity(Intent.createChooser(share, "Share Using!"));
}
});*/
lout_about_us.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/*startActivity(new Intent(SettingsActivity.this, AboutUsActivity.class));*/
Uri uri = Uri.fromParts(
"mailto",getResources().getString(R.string.feedback_email), null);
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, uri);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Query:");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Hello");
startActivity(Intent.createChooser(emailIntent, "Chooser Title"));
}
});
}
} |
package by.htp.les02.main;
public class TwelthTask {
public static void main(String[] args) {
for (int n = 33; n <= 125; n++) {
System.out.println((char) n + " " + n);
}
}
}
|
package com.shahinnazarov.gradle.models.k8s;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonPropertyOrder(
{
"apiVersion",
"kind",
"metadata",
"spec"
}
)
public final class StatefulSet implements DefaultK8sResource<StatefulSet> {
private StatefulSet() {
}
@JsonProperty("kind")
private String kind = "StatefulSet";
@JsonProperty("apiVersion")
private String apiVersion = "apps/v1";
@JsonProperty("metadata")
private Metadata<StatefulSet> metadata;
@JsonProperty("spec")
private StatefulSetSpec<StatefulSet> specification;
public Metadata<StatefulSet> metadata() {
return new Metadata<>(this, this::metadata);
}
public StatefulSet metadata(Metadata<StatefulSet> metadata) {
this.metadata = metadata;
return this;
}
public StatefulSetSpec<StatefulSet> spec() {
if(specification != null) {
return specification;
}
return new StatefulSetSpec<>(this, this::spec);
}
public StatefulSet spec(StatefulSetSpec<StatefulSet> specification) {
this.specification = specification;
return this;
}
@Override
public String getApiVersion() {
return apiVersion;
}
@Override
public String getKind() {
return kind;
}
@Override
public Metadata getMetadata() {
return metadata;
}
public StatefulSet build() {
return this;
}
public static StatefulSet instance() {
return new StatefulSet();
}
}
|
package com.larry.shugo.activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.baidu.mapapi.SDKInitializer;
import com.larry.shugo.utils.ConfigUtil;
import cn.bmob.v3.Bmob;
import cn.sharesdk.framework.ShareSDK;
/**
* 基类Activity
* 提炼应用公有逻辑
*/
public class BaseActivity extends AppCompatActivity {
public Context context;
public ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getApplicationContext();
SDKInitializer.initialize(context); //初始化地图SDK
Bmob.initialize(context, ConfigUtil.BMOB_APP_ID); //初始化BmobSDK
ShareSDK.initSDK(context); //初始化分享SDK
}
/**
* 开启进度弹窗
*/
public void showProgressDialog(Context c, String content) {
if (progressDialog == null) {
progressDialog = new ProgressDialog(c);
progressDialog.setMessage(content);
}
progressDialog.show();
}
/**
* 关闭进度弹窗
*/
public void closeProgressDialog() {
if (progressDialog != null) {
progressDialog.cancel();
progressDialog = null;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
ShareSDK.stopSDK(context); //关闭
}
}
|
package com.bramgussekloo.projectb.Activities.EditProduct;
import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.sip.SipSession;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Toast;
import com.bramgussekloo.projectb.Activities.Login.MainActivity;
import com.bramgussekloo.projectb.Activities.NewProductActivity;
import com.bramgussekloo.projectb.R;
import com.bumptech.glide.Glide;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.ListenerRegistration;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
import id.zelory.compressor.Compressor;
public class EditProduct extends AppCompatActivity {
private FirebaseFirestore firebaseFirestore;
private EditText quantity;
private EditText description;
private EditText title;
private ImageView image;
private String ProductID;
private Spinner Category;
private Button EditProductButton;
private Button DeleteProductBtton;
private ProgressBar progressbar;
private Uri productImageUri = null;
private StorageReference storageReference;
private Bitmap compressedImageFile;
private String image_urlValue;
private String downloadUri;
private String thumbDownloadUri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_product);
ProductID = getIntent().getExtras().getString("productID");
ItemsFromDatabase();
Buttons();
customizeActionBar();
}
private void ItemsFromDatabase() {
setSpinner();
title = findViewById(R.id.edit_product_title);
description = findViewById(R.id.edit_product_desc);
quantity = findViewById(R.id.edit_product_quantity);
image = findViewById(R.id.edit_product_image);
firebaseFirestore = FirebaseFirestore.getInstance();
firebaseFirestore.collection("Products").document(ProductID).addSnapshotListener(new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.w("snapshotListener", "listen failed", e);
return;
}
if (documentSnapshot != null && documentSnapshot.exists()) {
Log.d("snapshotListener", "onEvent: " + documentSnapshot.getData());
Map<String, Object> object_data = documentSnapshot.getData();
String quantityValue = object_data.get("quantity").toString();
String categoryValue = object_data.get("category").toString();
String descriptionValue = object_data.get("desc").toString();
image_urlValue = object_data.get("image_url").toString();
String titleValue = object_data.get("title").toString();
title.setText(titleValue);
ArrayAdapter myAdap = (ArrayAdapter) Category.getAdapter();
int spinnerPosition = myAdap.getPosition(categoryValue);
Category.setSelection(spinnerPosition);
description.setText(descriptionValue);
quantity.setText(quantityValue);
Glide.with(getBaseContext()).load(image_urlValue).into(image);
} else {
Log.d("snapshotListener", "onEvent: Null");
}
}
});
}
private void Buttons() {
quantity = findViewById(R.id.edit_product_quantity);
title = findViewById(R.id.edit_product_title);
description = findViewById(R.id.edit_product_desc);
Category = findViewById(R.id.spinnerCategoryProduct);
EditProductButton = findViewById(R.id.EditProductButton);
DeleteProductBtton = findViewById(R.id.DeleteProductButton);
image = findViewById(R.id.edit_product_image);
storageReference = FirebaseStorage.getInstance().getReference();
progressbar = findViewById(R.id.edit_product_progress);
image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cropImage();
}
});
DeleteProductBtton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(EditProduct.this);
builder.setTitle("Are you sure ?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
deleteProduct();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog ad =builder.create();
ad.show();
}
});
EditProductButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
firebaseFirestore.collection("Products").document(ProductID).addSnapshotListener(new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
if (!TextUtils.isEmpty(title.getText().toString()) && !TextUtils.isEmpty(description.getText().toString()) && !TextUtils.isEmpty(quantity.getText().toString())) { // checks if fields aren't aempty
final Integer quantityValue = Integer.parseInt(quantity.getText().toString());
if (documentSnapshot != null && productImageUri == null){
Map<String, Object> snapshot = documentSnapshot.getData();
thumbDownloadUri = snapshot.get("thumb_url").toString();
downloadUri = snapshot.get("image_url").toString();
Map<String, Object> productMap = new HashMap<>();
productMap.put("image_url", downloadUri);
productMap.put("thumb_url", thumbDownloadUri);
productMap.put("title", title.getText().toString());
productMap.put("desc", description.getText().toString());
productMap.put("quantity", quantityValue);
productMap.put("category", Category.getSelectedItem());
firebaseFirestore.collection("Products").document(title.getText().toString()).set(productMap).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Product is Edited", Toast.LENGTH_LONG).show();
sendToMain();
} else {
String errorMessage = task.getException().getMessage();
Toast.makeText(getApplicationContext(), "Error : " + errorMessage, Toast.LENGTH_LONG).show();
}
progressbar.setVisibility(View.INVISIBLE);
}
});
}
else if (productImageUri != null) {
progressbar.setVisibility(View.VISIBLE);
StorageReference filePath = storageReference.child("product_images").child(title.getText().toString() + ".jpg");
filePath.putFile(productImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
Task<Uri> urlTask = task.getResult().getStorage().getDownloadUrl();
while (!urlTask.isSuccessful()) ;
downloadUri = urlTask.getResult().toString();
if (task.isSuccessful()) {
File newImageFile = new File(productImageUri.getPath());
try {
compressedImageFile = new Compressor(EditProduct.this)
.setMaxHeight(100)
.setMaxWidth(100)
.setQuality(2)
.compressToBitmap(newImageFile);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
compressedImageFile.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = storageReference.child("product_images/thumbs").child(title.getText().toString() + ".jpg").putBytes(data);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> urlTaskThumb = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTaskThumb.isSuccessful()) ;
thumbDownloadUri = urlTaskThumb.getResult().toString();
Map<String, Object> productMap = new HashMap<>();
productMap.put("image_url", downloadUri);
productMap.put("thumb_url", thumbDownloadUri);
productMap.put("title", title.getText().toString());
productMap.put("desc", description.getText().toString());
productMap.put("quantity", quantityValue);
productMap.put("category", Category.getSelectedItem());
firebaseFirestore.collection("Products").document(title.getText().toString()).set(productMap).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Product is Edited", Toast.LENGTH_LONG).show();
emptyInputEditText();
sendToMain();
} else {
String errorMessage = task.getException().getMessage();
Toast.makeText(getApplicationContext(), "Error : " + errorMessage, Toast.LENGTH_LONG).show();
}
progressbar.setVisibility(View.INVISIBLE);
}
});
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
String errorMessage = e.getMessage();
Toast.makeText(EditProduct.this, "Error : " + errorMessage, Toast.LENGTH_SHORT).show();
}
});
} else {
progressbar.setVisibility(View.INVISIBLE);
String errorMessage = task.getException().getMessage();
Toast.makeText(getApplicationContext(), "Error : " + errorMessage, Toast.LENGTH_LONG).show();
}
}
});
} else {
Log.d("Snapshot: ", "Something went wrong");
}
} else {
progressbar.setVisibility(View.INVISIBLE);
Log.d("Onclick", "Fields are empty");
}
}
});
}
});
}
private void deleteProduct() {
firebaseFirestore.collection("Products").document(ProductID).delete()
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(getApplicationContext(),"Product Deleted",Toast.LENGTH_LONG).show();
finish();
sendToMain();
}
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { // checks result of given picture
image = findViewById(R.id.edit_product_image);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
productImageUri = result.getUri(); // appends the uri to given variable
image.setImageURI(productImageUri); // appends the uri to newproductimage
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError(); // error if mistakes in image
Log.d("Imageloader", "Error: " + error);
}
}
}
private void setSpinner(){
Category = findViewById(R.id.spinnerCategoryProduct);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.category, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Category.setAdapter(adapter);
}
private void cropImage(){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ // checks if phone has right build
if(ContextCompat.checkSelfPermission(EditProduct.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){ // checks if used phone has right permissions
Toast.makeText(getApplicationContext(), "Permission denied", Toast.LENGTH_LONG).show();
ActivityCompat.requestPermissions(EditProduct.this, new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, 1); // requests read permission
} else {
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON) // sets guidelines for cropping images
.setMinCropResultSize(512, 512) // sets minimal image size
.setAspectRatio(255, 150) // sets aspect ratio
.start(EditProduct.this); // starts the crop image acivity
}
}
}
private void emptyInputEditText() { // empty input fields
quantity.setText(null);
description.setText(null);
title.setText(null);
}
private void customizeActionBar(){
getSupportActionBar().setTitle("Edit a product"); // sets title for toolbar
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
private void sendToMain(){
Intent backIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(backIntent);
finish();
}
}
|
package log;
import contacts.Contact;
import contacts.ContactDisplayPanel;
import panel.ComProps;
import panel.UploadPanelDisabled;
import upload.Upload;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import static java.time.temporal.ChronoUnit.DAYS;
/*
LogPanel is the panel structure for a single day of logs. It composes the title/day of the logs, followed by a table
of the logs. This approach allows for multiple instances of these panels to be used to form a potentially endless
scrolling Panel inside of HistoryPanel for the visual display of logs. The table utilises a custom Table LogTableModel
to be able to present the information desired. Any time a Log is chosen from the table. A pop-up window is shown with a
non-editable view of that Log's associated data(Contact or Upload). This is currently limited to only showing the
newest data of that Contact or Upload, not the changes at the point of the log. This can be changed by adding more
tables to the database, but adds complexity and time consuming. This is already beyond the scope of the spec so it was
decided this was sufficient.
*/
public class LogPanel extends JPanel{
JLabel day;
JTable logTable;
int mainFont = 32;
public LogPanel(LocalDate date, List log){
setLayout(new BorderLayout());
if(DAYS.between(date, LocalDate.now()) == 0){
day = new JLabel("Today");
} else if(DAYS.between(date, LocalDate.now()) == 1){
day = new JLabel("Yesterday");
}else {
day = new JLabel(date.format(DateTimeFormatter.ofPattern("EEEE, dd LLLL")));
}
add(day, BorderLayout.NORTH);
logTable = new JTable(new LogTableModel(log));
logTable.getSelectionModel().addListSelectionListener(this::valueChanged);
add(logTable, BorderLayout.CENTER);
addComponentListener(new ComponentAdapter(){
public void componentResized(ComponentEvent e){
int windowWidth = getWidth();
int headerFont = mainFont;
int listFont = (int)(mainFont*(0.75));
int rowHeight = 30;
if (windowWidth < 550) {
rowHeight = (int)(windowWidth/(550/30));
headerFont = (int)windowWidth /(550/headerFont);
listFont = (int)(windowWidth/(550/listFont));
}
ComProps.headingProperties(day, headerFont);
logTable.setFont(new Font("Arial", Font.PLAIN, listFont));
setJTableColumnsWidth(logTable, getWidth()-50, 20, 20, 80);
logTable.setRowHeight(rowHeight);
repaint();
revalidate();
}
});
}
//Courtesy of https://www.codejava.net/java-se/swing/setting-column-width-and-row-height-for-jtable
public static void setJTableColumnsWidth(JTable table, int tablePreferredWidth,
double... percentages) {
double total = 0;
for (int i = 0; i < table.getColumnModel().getColumnCount(); i++) {
total += percentages[i];
}
for (int i = 0; i < table.getColumnModel().getColumnCount(); i++) {
TableColumn column = table.getColumnModel().getColumn(i);
column.setPreferredWidth((int)
(tablePreferredWidth * (percentages[i] / total)));
}
}
public void valueChanged(ListSelectionEvent e){
LogTableModel tableModel = (LogTableModel) logTable.getModel();
Log l;
if(logTable.getSelectedRow() != -1) {
switch ((String) tableModel.getValueAt(logTable.getSelectedRow(), 0)) {
case "Upload":
UploadPanelDisabled upload = null;
upload = new UploadPanelDisabled();
l = (Log) tableModel.getValueAt(logTable.getSelectedRow(), 3);
Upload u = (Upload) l.getData();
upload.setToExistingUpload(u.getUploadID());
upload.setPreferredSize(new Dimension(1280, 720));
JOptionPane.showConfirmDialog(null, upload, "Viewing Upload", JOptionPane.PLAIN_MESSAGE);
break;
case "Contact":
//Display the shown contact in a non editable panel
l = (Log) tableModel.getValueAt(logTable.getSelectedRow(), 3);
Contact c = (Contact) l.getData();
ContactDisplayPanel dp = new ContactDisplayPanel(c);
dp.setMainFont(64);// Because view is smaller then intended use the font size is doubled so it is readable
dp.setPreferredSize(new Dimension(350, 350));
JOptionPane.showConfirmDialog(null, dp, "Viewing Contact", JOptionPane.PLAIN_MESSAGE);
break;
}
}
}
}
|
/*
* Copyright (c) 2009, Julian Gosnell
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.dada.demo;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import javax.swing.table.AbstractTableModel;
import org.dada.core.Getter;
import org.dada.core.Metadata;
import org.dada.core.Update;
import org.dada.core.View;
import org.dada.slf4j.Logger;
import org.dada.slf4j.LoggerFactory;
public class TableModelView<K, V> extends AbstractTableModel implements View<V> {
private class IndexedMap<K, V> {
private class Entry implements Map.Entry<K, V> {
private final K key;
private V value;
private Entry(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public V setValue(V newValue) {
V oldValue = this.value;
this.value = newValue;
return oldValue;
}
}
private List<Entry> list = new ArrayList<Entry>();
private Comparator<Entry> comparator = new Comparator<Entry>() {@Override public int compare(Entry o1, Entry o2) {return ((Comparable<K>)o1.getKey()).compareTo(o2.getKey());}};
public int put(K key, V value) {
Entry entry = new Entry(key, value);
int i = Collections.binarySearch(list, entry, comparator);
if (i > -1) {
list.set(i, entry);
return i;
} else {
int index = (i + 1) * -1;
list.add(index, entry);
return index;
}
}
public int remove(K key) {
Entry entry = new Entry(key, null);
int i = Collections.binarySearch(list, entry, comparator);
if (i > -1) {
list.remove(i);
return i;
} else {
return -1;
}
}
public V get(int i) {
return list.get(i).getValue();
}
public int size() {
return list.size();
}
}
private final Logger logger = LoggerFactory.getLogger(getClass());
private final CountDownLatch latch = new CountDownLatch(1);
private Metadata<K, V> metadata;
//private final ConcurrentSkipListMap<K, V> map = new ConcurrentSkipListMap<K, V>();
private final IndexedMap<K, V> map = new IndexedMap<K, V>();
private final String name;
public TableModelView(String name) {
this.name = name;
}
public void setMetadata(Metadata<K, V> metadata) {
this.metadata = metadata;
latch.countDown();
}
public Metadata<K, V> getMetadata() {
try {
latch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return metadata;
}
// TableModel
// Listener
@Override
public synchronized void update(Collection<Update<V>> insertions, Collection<Update<V>> alterations, Collection<Update<V>> deletions) {
logger.trace("{}: input: insertions={}, alterations={}, deletions={}", name, insertions.size(), alterations.size(), deletions.size());
// TODO - what about extinct values ?
Getter<K, V> keyGetter = getMetadata().getPrimaryGetter();
for (Update<V> insertion : insertions) {
V newValue = insertion.getNewValue();
K key = keyGetter.get(newValue);
int index = map.put(key, newValue);
fireTableRowsInserted(index, index);
}
for (Update<V> update : alterations) {
V newValue = update.getNewValue();
K newKey = keyGetter.get(newValue);
V oldValue = update.getOldValue();
K oldKey = keyGetter.get(oldValue);
int oldIndex;
int newIndex;
if (newKey.equals(oldKey)) {
oldIndex = newIndex = map.put(newKey, newValue);
} else {
newIndex = map.put(newKey, newValue);
oldIndex = map.remove(oldKey);
}
if (oldIndex == newIndex)
fireTableRowsUpdated(newIndex, newIndex);
else {
if (oldIndex > -1) fireTableRowsDeleted(oldIndex, oldIndex);
fireTableRowsInserted(newIndex, newIndex);
}
}
for (Update<V> deletion : deletions) {
V value = deletion.getOldValue();
K key = keyGetter.get(value);
int index= map.remove(key);
if (index > -1) fireTableRowsDeleted(index, index);
}
// TODO: can we collapse i/a/d into dirty blocks and make single UI updates ?
}
@Override
public String getColumnName(int columnIndex) {
return getMetadata().getAttributes().get(columnIndex).getKey().toString();
}
@Override
public int getColumnCount() {
return getMetadata().getAttributes().size();
}
@Override
public synchronized int getRowCount() {
return map.size();
}
@Override
public synchronized Object getValueAt(int rowIndex, int columnIndex) {
return getMetadata().getAttributeValue(map.get(rowIndex), columnIndex);
}
}
|
package ca.mcgill.ecse223.kingdomino.view;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Group;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.text.JTextComponent;
import ca.mcgill.ecse223.kingdomino.controller.QueryMethodController;
import ca.mcgill.ecse223.kingdomino.controller.TOPlayer;
import ca.mcgill.ecse223.kingdomino.controller.TOUser;
/**
*
* @author Mohamad
*
*/
public class EndOfGamePage extends JFrame {
private static final long serialVersionUID = 3984796675573114484L;
//define UI elements
private JPanel panel;
private JLabel winner;
private JTable scores;
private JButton restart;
//define data elements
private ArrayList<Integer> ranks = new ArrayList<Integer>();
private ArrayList<String> users = new ArrayList<String>();
private ArrayList<Integer> propertyScores = new ArrayList<Integer>();
private ArrayList<Integer> bonusScores = new ArrayList<Integer>();
private ArrayList<Integer> totalScores = new ArrayList<Integer>();
private DefaultTableModel tableModel; //new
private JScrollPane scrollPane; //new
private Object data[][] = { {"Rank", "User", "Property Score", "Bonus Score", "Total Score"},
{1, "P1", 0, 0, 0},
{2, "P2", 0, 0, 0},
{3, "P3", 0, 0, 0},
{4, "P4", 0, 0, 0} };
String[] columnNames = {"Rank", "User", "Property Score", "Bonus Score", "Total Score"};
private String winningUser = "";
private int numPlayers;
//@TODO add save game button?
public EndOfGamePage() {
initComponents();
refreshData();
}
public void run() {
new EndOfGamePage().setVisible(true);
}
//initializing components
private void initComponents() {
//window setup
panel = new JPanel();
this.add(panel);
this.setSize(750, 250);
//text to declare winner
winner = new JLabel("The winner is ???");
panel.add(winner);
//score table
scores = new JTable(data, columnNames);
scrollPane = new JScrollPane(scores);
panel.add(scrollPane);
//panel.add(scores.getTableHeader(), BorderLayout.NORTH);
//panel.add(scores, BorderLayout.CENTER);
//button to restart application
restart = new JButton("Restart KingDomino");
restart.addActionListener(new java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent evt) {
restartActionPerformed(evt);
}
});
panel.add(restart);
//setting the layout
GroupLayout layout = new GroupLayout(panel);
panel.setLayout(layout);
layout.setAutoCreateContainerGaps(true);
layout.setAutoCreateGaps(true);
layout.setHorizontalGroup(
layout.createParallelGroup()
.addComponent(winner)
.addComponent(scores)
.addComponent(restart)
);
layout.setVerticalGroup(
layout.createSequentialGroup()
.addComponent(winner)
.addComponent(scores)
.addComponent(restart)
);
}
//restarting game (going back to Kingdomino Menu)
private void restartActionPerformed(ActionEvent evt) {
panel.removeAll();;
//new KingdominoMenu().setVisible(true); call the main menu
}
//refreshing data
private void refreshData() {
//getting winner
winningUser = QueryMethodController.getWinner();
winner.setText("The winner is "+winningUser+"!");
//refreshing data for score table
List<TOPlayer> players = QueryMethodController.getPlayers();
numPlayers = players.size();
for(TOPlayer p : players) {
int rank = p.getCurrentRanking();
//using [rank-1] as row number orders table from rank 1-4
data[rank - 1][0] = rank; //col 0: rank
data[rank - 1][1] = "Name"; //col 1: user
data[rank - 1][2] = p.getPropertyScore(); //col 2: property score
data[rank - 1][3] = p.getBonusScore(); //col 3: bonus score
data[rank - 1][4] = p.getBonusScore() +p.getPropertyScore(); //col 4: total score
}
}
}
|
/*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2011 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.ow2.proactive.scheduler.common.task;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.objectweb.proactive.core.util.converter.ByteToObjectConverter;
import org.objectweb.proactive.core.util.converter.ObjectToByteConverter;
import org.ow2.proactive.scheduler.task.launcher.TaskLauncher.OneShotDecrypter;
import org.ow2.proactive.utils.NodeSet;
/**
* JavaExecutableInitializer is the class used to store context of java executable initialization
*
* @author The ProActive Team
* @since ProActive Scheduling 1.0
*/
public class JavaExecutableInitializer implements ExecutableInitializer {
/** */
private static final long serialVersionUID = 31L;
/** Demanded nodes */
protected NodeSet nodes;
/** Arguments of the java task */
protected Map<String, byte[]> serializedArguments;
/**
* Get the nodes list
*
* @return the nodes list
*/
public NodeSet getNodes() {
return nodes;
}
/**
* Set the nodes list value to the given nodes value
*
* @param nodes the nodes to set
*/
public void setNodes(NodeSet nodes) {
this.nodes = nodes;
}
/**
* Get the arguments of the executable. Instances are created from the serialized version.
*
* @return the arguments of the executable
* @throws IOException if the deserialization of the value cannot be performed.
* @throws ClassNotFoundException if the value's class cannot be loaded.
*/
public Map<String, Serializable> getArguments(ClassLoader cl) throws IOException, ClassNotFoundException {
final Map<String, Serializable> deserialized = new HashMap<String, Serializable>(
this.serializedArguments.size());
for (Entry<String, byte[]> e : this.serializedArguments.entrySet()) {
deserialized.put(e.getKey(), (Serializable) ByteToObjectConverter.ObjectStream.convert(e
.getValue(), cl));
}
return deserialized;
}
/**
* Return a map containing all the task arguments serialized as byte[].
*
* @return the serialized arguments map.
*/
public Map<String, byte[]> getSerializedArguments() {
return serializedArguments;
}
/**
* Set an argument
*
* @param key key of the argument to set
* @param arg de-serialized version of the argument
*/
public void setArgument(String key, Serializable arg) {
if (key != null && key.length() > 255) {
throw new IllegalArgumentException("Key is too long, it must have 255 chars length max : " + key);
} else {
byte[] serialized = null;
try {
serialized = ObjectToByteConverter.ObjectStream.convert(arg);
this.serializedArguments.put(key, serialized);
} catch (IOException e) {
throw new IllegalArgumentException("Cannot add argument " + key, e);
}
this.serializedArguments.put(key, serialized);
}
}
/**
* Set the arguments value to the given arguments value
*
* @param serializedArguments the arguments to set
*/
public void setSerializedArguments(Map<String, byte[]> serializedArguments) {
this.serializedArguments = serializedArguments;
}
/**
* {@inheritDoc}
*/
public OneShotDecrypter getDecrypter() {
throw new RuntimeException("Should not be called in this context");
}
/**
* {@inheritDoc}
*/
public void setDecrypter(OneShotDecrypter decrypter) {
throw new RuntimeException("Should not be called in this context");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.