blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
410
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
51
| license_type
stringclasses 2
values | repo_name
stringlengths 5
132
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
80
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 131
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
9.45M
| extension
stringclasses 32
values | content
stringlengths 3
9.45M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
313
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6fb94e555c84b2317c453ce0eda3fb122e726225 | 3e0d2b36b6393c0c1d59cec6fdaa008144500359 | /application/src/main/java/eu/ec/dgempl/eessi/rina/tool/migration/application/Application.java | 84faceac815f0ef587d91c65c62dcb8f59e2f64b | [] | no_license | navikt/eessi-DataMigrationTool | fedffb4b76390468d16e7d585f0b34d51133000e | 0e6fd76e4c2ee0d08b29e90aad9c1241d58d2759 | refs/heads/master | 2023-07-07T17:10:57.029043 | 2021-08-05T15:45:39 | 2021-08-05T15:45:39 | 392,406,417 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,599 | java | package eu.ec.dgempl.eessi.rina.tool.migration.application;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.boot.SpringApplication;
import org.springframework.util.CollectionUtils;
import eu.ec.dgempl.eessi.rina.tool.migration.application.full.FullApp;
import eu.ec.dgempl.eessi.rina.tool.migration.application.utils.DatabaseExecutionUtils;
import eu.ec.dgempl.eessi.rina.tool.migration.application.validation.ValidationApp;
public class Application {
public final static String ARG_VALIDATE_ALL = "-validate-all";
public final static String ARG_VALIDATE_CASE = "-validate-case";
public final static String ARG_VALIDATE_CASES_BULK = "-validate-cases-bulk";
public final static String ARG_VALIDATE_AND_IMPORT = "-validate-import";
public final static String ARG_IMPORT_ALL = "-import-all";
public final static String ARG_IMPORT_CASE = "-import-case";
public final static String ARG_IMPORT_CASES_BULK = "-import-cases-bulk";
public final static String ARG_THREADS = "-threads=";
private final static String ARG_HELP_LONG = "-help";
private final static String ARG_HELP_SHORT = "-h";
public static void main(String[] args) throws FileNotFoundException {
// Accepted args:
//
// -validate-all (default)
// -validate-case case
// -validate-cases-bulk filename
// -validate-import [importer_name] [threads_number]
// -import-all [importer_name] [threads_number]
// -import-case case
// -import-cases-bulk filename [threads_number]
// -help, -h
List<String> arguments = Arrays.stream(args).collect(Collectors.toList());
boolean proceed = true;
switch (args.length) {
case 0: {
showNoArgsInfo();
break;
}
case 1: {
if ((arguments.contains(ARG_HELP_LONG) || arguments.contains(ARG_HELP_SHORT))
|| (!arguments.contains(ARG_VALIDATE_ALL)
&& !arguments.contains(ARG_VALIDATE_AND_IMPORT)
&& !arguments.contains(ARG_IMPORT_ALL))) {
showHelp();
proceed = false;
}
break;
}
case 2: {
String importOption = arguments.get(0);
if ((!importOption.equals(ARG_VALIDATE_ALL) &&
!importOption.equals(ARG_VALIDATE_CASE) &&
!importOption.equals(ARG_VALIDATE_CASES_BULK) &&
!importOption.equals(ARG_IMPORT_CASE) &&
!importOption.equals(ARG_VALIDATE_AND_IMPORT) &&
!importOption.equals(ARG_IMPORT_ALL) &&
!importOption.equals(ARG_IMPORT_CASES_BULK))
|| !areValidParams(arguments)) {
showHelp();
proceed = false;
}
break;
}
case 3: {
String importOption = arguments.get(0);
if ((!importOption.equals(ARG_VALIDATE_AND_IMPORT)
&& !importOption.equals(ARG_IMPORT_ALL)
&& !importOption.equals(ARG_IMPORT_CASES_BULK)
&& !importOption.equals(ARG_VALIDATE_CASES_BULK))
|| !areValidParams(arguments)) {
showHelp();
proceed = false;
}
break;
}
default:
showHelp();
proceed = false;
break;
}
if (proceed) {
redirectSystemErr();
if (arguments.contains(ARG_VALIDATE_ALL)
|| arguments.contains(ARG_VALIDATE_CASE)
|| arguments.contains(ARG_VALIDATE_CASES_BULK)
|| CollectionUtils.isEmpty(arguments)) {
SpringApplication.run(ValidationApp.class, args);
} else {
DatabaseExecutionUtils.createTempTables();
SpringApplication.run(FullApp.class, args);
}
}
}
private static boolean areValidParams(List<String> args) {
switch (args.size()) {
case 2: {
String option = args.get(0);
String argument = args.get(1);
if ((ARG_VALIDATE_CASES_BULK.equals(option)
|| ARG_IMPORT_CASES_BULK.equals(option)
|| ARG_VALIDATE_CASE.equals(option)
|| ARG_IMPORT_CASE.equals(option))
&& argument.contains(ARG_THREADS)) {
return false;
}
else if (argument.contains(ARG_THREADS)) {
try {
Integer.valueOf(argument.substring(ARG_THREADS.length()));
} catch (NumberFormatException ex) {
System.out.println("\nIncorrect value. Expected a numeric value for " + ARG_THREADS + " parameter");
return false;
}
}
break;
}
case 3: {
String argument1 = args.get(1);
String argument2 = args.get(2);
String threadsArg;
if (argument1.contains(ARG_THREADS)) {
threadsArg = argument1.substring(ARG_THREADS.length());
} else if (argument2.contains(ARG_THREADS)) {
threadsArg = argument2.substring(ARG_THREADS.length());
} else {
return false;
}
try {
Integer.valueOf(threadsArg);
} catch (NumberFormatException ex) {
System.out.println("\nIncorrect value. Expected a numeric value for " + ARG_THREADS + " parameter");
return false;
}
break;
}
default: {
return false;
}
}
return true;
}
private static void showHelp() {
String help = String.join(System.lineSeparator(), "", "---Data Migration Help---", "", "Usage: java -jar <jar_name> [options]", "",
"Options:", "", " " + ARG_VALIDATE_ALL + " Default execution. Validates the data from the source",
" indicated in the config/applications.properties", "",
" " + ARG_VALIDATE_CASE + " value Validates the specified caseId indicated",
" in the 'value' parameter", "",
" " + ARG_VALIDATE_CASES_BULK + " filename Validates the caseIds specified in the file, one caseId per line", "",
" " + ARG_VALIDATE_AND_IMPORT + " First validates the data and then imports it", "",
" " + ARG_IMPORT_ALL + " Imports the data without previous validation", "",
" " + ARG_IMPORT_CASE + " value Imports the specified caseId indicated",
" in the 'value' parameter", "",
" " + ARG_IMPORT_CASES_BULK + " filename Imports the caseIds specified in the file, one caseId per line", "",
" " + ARG_HELP_LONG + ", " + ARG_HELP_SHORT + " Shows this help", "",
" " + "Please review the User Manual for more information and examples", "");
System.out.println(help);
}
private static void showNoArgsInfo() {
String help = System.lineSeparator() + "Starting application with DEFAULT execution: only validation." + System.lineSeparator()
+ "Please execute 'java -jar <jar_name> " + ARG_HELP_LONG + "' to see different execution options" + System.lineSeparator();
System.out.println(help);
}
private static void redirectSystemErr() throws FileNotFoundException {
File logs = new File("./logs");
if (!logs.exists()) {
logs.mkdir();
}
File file = new File("./logs/err.txt");
FileOutputStream fos = new FileOutputStream(file);
PrintStream ps = new PrintStream(fos);
System.setErr(ps);
}
}
| [
"[email protected]"
] | |
ab5790ed44b54b94c8031fe52990c4a7b4a29e70 | 077ad1330f77172a59c7e7621c72bb653d9ff40a | /generator/src/main/java/com/graphicsfuzz/generator/semanticspreserving/AddDeadBarrierMutationFinder.java | 0f72b3c703cf0dfdff84e223828aeb71ef28a680 | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | permissive | google/graphicsfuzz | 48e82803e0354c4a92dc913fe36b8f6bae2eaa11 | aa32d4cb556647ddaaf2048815bd6bca07d1bdab | refs/heads/master | 2023-08-22T18:28:49.278862 | 2022-03-10T09:08:51 | 2022-03-10T09:08:51 | 150,133,859 | 573 | 155 | Apache-2.0 | 2023-09-06T18:14:58 | 2018-09-24T16:31:05 | Java | UTF-8 | Java | false | false | 1,279 | java | /*
* Copyright 2019 The GraphicsFuzz Project 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 com.graphicsfuzz.generator.semanticspreserving;
import com.graphicsfuzz.common.ast.TranslationUnit;
import com.graphicsfuzz.common.util.IRandom;
import com.graphicsfuzz.generator.util.GenerationParams;
public class AddDeadBarrierMutationFinder
extends InjectionPointMutationFinder<AddDeadBarrierMutation> {
public AddDeadBarrierMutationFinder(TranslationUnit tu,
IRandom random,
GenerationParams generationParams) {
super(tu, random, item -> true, item -> new AddDeadBarrierMutation(item, random,
tu.getShadingLanguageVersion(), generationParams));
}
}
| [
"[email protected]"
] | |
81f2f3f09058dc538ced06d56145d5bbe979b468 | e4e318fc24b747eb9022a910d852cbd800978d8b | /ApiVoiture/src/main/java/com/example/ApiVoiture/web/controller/VoitureController.java | 381c0502b0f48618349b43d7cfd4879fec1cbba7 | [] | no_license | Cedric-Alonso/CarRental | 218eef1600283c7093efe782e522f31d364989ff | 58933ae585bc3a40a85c524a2efb6fa51ef4b26c | refs/heads/master | 2022-07-16T08:58:18.495725 | 2019-10-31T10:45:25 | 2019-10-31T10:45:25 | 218,004,067 | 0 | 0 | null | 2022-06-21T02:08:39 | 2019-10-28T08:53:52 | Java | UTF-8 | Java | false | false | 2,053 | java | package com.example.ApiVoiture.web.controller;
import com.example.ApiVoiture.dao.VoitureDao;
import com.example.ApiVoiture.model.Voiture;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.List;
@Api(tags = "CRUD")
@EnableSwagger2
@RestController
public class VoitureController {
@Autowired
VoitureDao dao;
@ApiOperation(value = "liste des voitures")
@GetMapping(value = "/voitures")
public List<Voiture> list_des_vehicules(){
return dao.findAll();
}
@ApiOperation(value = "recuperer une voiture")
@GetMapping(value = "/voitures/{id}")
public Voiture choixVoiture(@PathVariable int id){
return dao.findById(id);
}
@ApiOperation(value = "modifier une voiture")
@PutMapping(value = "/voiture/update")
public String updateVoiture(@RequestBody Voiture voiture){
if (choixVoiture(voiture.getId()) != null) {
dao.save(voiture);
return "modify ok";
}else {
return "L'élément n'a pas était trouver.";
}
}
@ApiOperation(value = "ajouter une voiture")
@PostMapping(value = "/voiture/add")
public String ajouterVoiture(@RequestBody Voiture voiture){
if (choixVoiture(voiture.getId()) == null) {
dao.save(voiture);
return "ajout ok";
}else {
return "L'élément n'a pas était trouver.";
}
}
@ApiOperation(value = "supprimer une voiture")
@DeleteMapping(value = "/voiture/delete/{id}")
public String deletVoiture(@PathVariable int id){
Voiture voitureDelete = choixVoiture(id);
dao.delete(voitureDelete);
return "delete ok";
}
// @DeleteMapping(value = "/voiture/delete/{id}")
// public void deletevoiture(@PathVariable int id){
// dao.deleteById(id);
// }
}
| [
"[email protected]"
] | |
581867d1f548dd73a8d2608e97f79e03b7055c3a | 0dbc549713a64c9b098574dcb77eb822e2569ab8 | /ccxx-icu/ccxx-icu-api/src/main/java/com/pig4cloud/pigx/ccxxicu/api/entity/bed/HospitalBed.java | 7c1a2a06a64c9b9aece3f8be79bbc45590fff26e | [] | no_license | soon14/icujava | ad7b234bc5bf37d38d65b04a5cbbb627bfeb47ef | f3098bc5c5c1af31188c2549d4a2f0982a402aad | refs/heads/master | 2022-12-25T17:02:25.665626 | 2020-01-05T11:25:26 | 2020-01-05T11:25:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,125 | java | /*
* Copyright (c) 2018-2025, lengleng 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.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng ([email protected])
*/
package com.pig4cloud.pigx.ccxxicu.api.entity.bed;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.time.LocalDateTime;
/**
* 床位表
*
* @author yyj
* @date 2019-08-07 21:24:05
*/
@Data
@TableName("nur_hospital_bed")
@EqualsAndHashCode(callSuper = true)
@ApiModel(value = "床位表")
public class HospitalBed extends Model<HospitalBed> {
private static final long serialVersionUID = 1L;
/**
* 床位表 主键id
*/
@TableId
@ApiModelProperty(value="床位表 主键id")
private Integer id;
/**
* 生成的id
*/
@ApiModelProperty(value="生成的id")
private String bedId;
/**
* 床位名
*/
@ApiModelProperty(value="床位名")
private String bedName;
/**
* 床位编号
*/
@ApiModelProperty(value="床位编号")
private String bedCode;
/**
* 床位RFID
*/
@ApiModelProperty(value="床位RFID")
private String rfid;
/**
* 床位使用状态 0未使用 1使用中 2维修中
*/
@ApiModelProperty(value="床位使用状态 0未使用 1使用中 2维修中")
private Integer useFlag;
/**
* 科室id
*/
@ApiModelProperty(value="科室id")
private String deptId;
/**
* 删除标识 0正常 1删除
*/
@ApiModelProperty(value="删除标识 0正常 1删除")
private Integer delFlag;
/**
* 删除时间
*/
@ApiModelProperty(value="删除时间")
private LocalDateTime delTime;
/**
* 删除人
*/
@ApiModelProperty(value="删除人")
private String delUserId;
/**
* 修改时间
*/
@ApiModelProperty(value="修改时间")
private LocalDateTime updateTime;
/**
* 修改人
*/
@ApiModelProperty(value="修改人")
private String updateUserId;
/**
* 创建人
*/
@ApiModelProperty(value="创建人")
private String createUserId;
/**
* 创建时间
*/
@ApiModelProperty(value="创建时间")
private LocalDateTime createTime;
}
| [
"[email protected]"
] | |
1010448c841644443ad28c967103b7d08438b191 | c45742faa356e4af644885e47bb6486b8e1b8c66 | /src/main/java/com/booky/api/dao/CardQueueDAO.java | 23383362d460b1e76ecb7726159fe2b10910ca75 | [
"MIT"
] | permissive | emmanuelxavier040/booky-service | 3d695e777fa539a3e797c27c460b9a42c4bb8d6c | 3d9dc77b84b05516cc2f59ef7fb54560609932f4 | refs/heads/develop | 2023-01-03T01:41:57.063498 | 2020-10-27T16:15:15 | 2020-10-27T16:15:15 | 293,069,205 | 0 | 0 | null | 2020-09-18T03:54:32 | 2020-09-05T12:14:19 | Java | UTF-8 | Java | false | false | 367 | java | package com.booky.api.dao;
import com.booky.api.model.CardQueue;
import java.util.List;
public interface CardQueueDAO {
List<CardQueue> findAllCardQueuesInGroup(long groupId);
CardQueue createCardQueue(CardQueue cardQueue);
CardQueue findCardQueueById(long id);
void deleteAllCardQueuesForCard(long cardId);
void deleteCardQueueFromQueueById(long id);
}
| [
"[email protected]"
] | |
fd9d78b71ca5040a3fb0366bb421159a1a035347 | abe4b5481efdc8d3c0871d517295bbbfa8cbc5b3 | /wolf_thrift/src/org/apache/wolf/thrift/Deletion.java | 41109318b36ef7005ccfd11370521f5859a9a1fb | [] | no_license | felixlixu/wolf | f062571188d1fab2fb930d7b20318ee293bd2cc9 | c018eb7d5ef7499f7318dd885ae8acc2361ede87 | refs/heads/master | 2016-09-06T03:09:10.852314 | 2014-09-15T08:52:43 | 2014-09-15T08:52:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | true | 19,320 | java | /**
* Autogenerated by Thrift Compiler (0.9.1)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package org.apache.wolf.thrift;
import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;
import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.server.AbstractNonblockingServer.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Note that the timestamp is only optional in case of counter deletion.
*/
public class Deletion implements org.apache.thrift.TBase<Deletion, Deletion._Fields>, java.io.Serializable, Cloneable, Comparable<Deletion> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("Deletion");
private static final org.apache.thrift.protocol.TField TIMESTAMP_FIELD_DESC = new org.apache.thrift.protocol.TField("timestamp", org.apache.thrift.protocol.TType.I64, (short)1);
private static final org.apache.thrift.protocol.TField SUPER_COLUMN_FIELD_DESC = new org.apache.thrift.protocol.TField("super_column", org.apache.thrift.protocol.TType.STRING, (short)2);
private static final org.apache.thrift.protocol.TField PREDICATE_FIELD_DESC = new org.apache.thrift.protocol.TField("predicate", org.apache.thrift.protocol.TType.STRUCT, (short)3);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new DeletionStandardSchemeFactory());
schemes.put(TupleScheme.class, new DeletionTupleSchemeFactory());
}
public long timestamp; // optional
public ByteBuffer super_column; // optional
public SlicePredicate predicate; // optional
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
TIMESTAMP((short)1, "timestamp"),
SUPER_COLUMN((short)2, "super_column"),
PREDICATE((short)3, "predicate");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // TIMESTAMP
return TIMESTAMP;
case 2: // SUPER_COLUMN
return SUPER_COLUMN;
case 3: // PREDICATE
return PREDICATE;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __TIMESTAMP_ISSET_ID = 0;
private byte __isset_bitfield = 0;
private _Fields optionals[] = {_Fields.TIMESTAMP,_Fields.SUPER_COLUMN,_Fields.PREDICATE};
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.TIMESTAMP, new org.apache.thrift.meta_data.FieldMetaData("timestamp", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64)));
tmpMap.put(_Fields.SUPER_COLUMN, new org.apache.thrift.meta_data.FieldMetaData("super_column", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING , true)));
tmpMap.put(_Fields.PREDICATE, new org.apache.thrift.meta_data.FieldMetaData("predicate", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, SlicePredicate.class)));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(Deletion.class, metaDataMap);
}
public Deletion() {
}
/**
* Performs a deep copy on <i>other</i>.
*/
public Deletion(Deletion other) {
__isset_bitfield = other.__isset_bitfield;
this.timestamp = other.timestamp;
if (other.isSetSuper_column()) {
this.super_column = org.apache.thrift.TBaseHelper.copyBinary(other.super_column);
;
}
if (other.isSetPredicate()) {
this.predicate = new SlicePredicate(other.predicate);
}
}
public Deletion deepCopy() {
return new Deletion(this);
}
@Override
public void clear() {
setTimestampIsSet(false);
this.timestamp = 0;
this.super_column = null;
this.predicate = null;
}
public long getTimestamp() {
return this.timestamp;
}
public Deletion setTimestamp(long timestamp) {
this.timestamp = timestamp;
setTimestampIsSet(true);
return this;
}
public void unsetTimestamp() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __TIMESTAMP_ISSET_ID);
}
/** Returns true if field timestamp is set (has been assigned a value) and false otherwise */
public boolean isSetTimestamp() {
return EncodingUtils.testBit(__isset_bitfield, __TIMESTAMP_ISSET_ID);
}
public void setTimestampIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __TIMESTAMP_ISSET_ID, value);
}
public byte[] getSuper_column() {
setSuper_column(org.apache.thrift.TBaseHelper.rightSize(super_column));
return super_column == null ? null : super_column.array();
}
public ByteBuffer bufferForSuper_column() {
return super_column;
}
public Deletion setSuper_column(byte[] super_column) {
setSuper_column(super_column == null ? (ByteBuffer)null : ByteBuffer.wrap(super_column));
return this;
}
public Deletion setSuper_column(ByteBuffer super_column) {
this.super_column = super_column;
return this;
}
public void unsetSuper_column() {
this.super_column = null;
}
/** Returns true if field super_column is set (has been assigned a value) and false otherwise */
public boolean isSetSuper_column() {
return this.super_column != null;
}
public void setSuper_columnIsSet(boolean value) {
if (!value) {
this.super_column = null;
}
}
public SlicePredicate getPredicate() {
return this.predicate;
}
public Deletion setPredicate(SlicePredicate predicate) {
this.predicate = predicate;
return this;
}
public void unsetPredicate() {
this.predicate = null;
}
/** Returns true if field predicate is set (has been assigned a value) and false otherwise */
public boolean isSetPredicate() {
return this.predicate != null;
}
public void setPredicateIsSet(boolean value) {
if (!value) {
this.predicate = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case TIMESTAMP:
if (value == null) {
unsetTimestamp();
} else {
setTimestamp((Long)value);
}
break;
case SUPER_COLUMN:
if (value == null) {
unsetSuper_column();
} else {
setSuper_column((ByteBuffer)value);
}
break;
case PREDICATE:
if (value == null) {
unsetPredicate();
} else {
setPredicate((SlicePredicate)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case TIMESTAMP:
return Long.valueOf(getTimestamp());
case SUPER_COLUMN:
return getSuper_column();
case PREDICATE:
return getPredicate();
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case TIMESTAMP:
return isSetTimestamp();
case SUPER_COLUMN:
return isSetSuper_column();
case PREDICATE:
return isSetPredicate();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof Deletion)
return this.equals((Deletion)that);
return false;
}
public boolean equals(Deletion that) {
if (that == null)
return false;
boolean this_present_timestamp = true && this.isSetTimestamp();
boolean that_present_timestamp = true && that.isSetTimestamp();
if (this_present_timestamp || that_present_timestamp) {
if (!(this_present_timestamp && that_present_timestamp))
return false;
if (this.timestamp != that.timestamp)
return false;
}
boolean this_present_super_column = true && this.isSetSuper_column();
boolean that_present_super_column = true && that.isSetSuper_column();
if (this_present_super_column || that_present_super_column) {
if (!(this_present_super_column && that_present_super_column))
return false;
if (!this.super_column.equals(that.super_column))
return false;
}
boolean this_present_predicate = true && this.isSetPredicate();
boolean that_present_predicate = true && that.isSetPredicate();
if (this_present_predicate || that_present_predicate) {
if (!(this_present_predicate && that_present_predicate))
return false;
if (!this.predicate.equals(that.predicate))
return false;
}
return true;
}
@Override
public int hashCode() {
return 0;
}
@Override
public int compareTo(Deletion other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetTimestamp()).compareTo(other.isSetTimestamp());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetTimestamp()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.timestamp, other.timestamp);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetSuper_column()).compareTo(other.isSetSuper_column());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetSuper_column()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.super_column, other.super_column);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetPredicate()).compareTo(other.isSetPredicate());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetPredicate()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.predicate, other.predicate);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("Deletion(");
boolean first = true;
if (isSetTimestamp()) {
sb.append("timestamp:");
sb.append(this.timestamp);
first = false;
}
if (isSetSuper_column()) {
if (!first) sb.append(", ");
sb.append("super_column:");
if (this.super_column == null) {
sb.append("null");
} else {
org.apache.thrift.TBaseHelper.toString(this.super_column, sb);
}
first = false;
}
if (isSetPredicate()) {
if (!first) sb.append(", ");
sb.append("predicate:");
if (this.predicate == null) {
sb.append("null");
} else {
sb.append(this.predicate);
}
first = false;
}
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
if (predicate != null) {
predicate.validate();
}
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
__isset_bitfield = 0;
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class DeletionStandardSchemeFactory implements SchemeFactory {
public DeletionStandardScheme getScheme() {
return new DeletionStandardScheme();
}
}
private static class DeletionStandardScheme extends StandardScheme<Deletion> {
public void read(org.apache.thrift.protocol.TProtocol iprot, Deletion struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // TIMESTAMP
if (schemeField.type == org.apache.thrift.protocol.TType.I64) {
struct.timestamp = iprot.readI64();
struct.setTimestampIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // SUPER_COLUMN
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.super_column = iprot.readBinary();
struct.setSuper_columnIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 3: // PREDICATE
if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {
struct.predicate = new SlicePredicate();
struct.predicate.read(iprot);
struct.setPredicateIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, Deletion struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.isSetTimestamp()) {
oprot.writeFieldBegin(TIMESTAMP_FIELD_DESC);
oprot.writeI64(struct.timestamp);
oprot.writeFieldEnd();
}
if (struct.super_column != null) {
if (struct.isSetSuper_column()) {
oprot.writeFieldBegin(SUPER_COLUMN_FIELD_DESC);
oprot.writeBinary(struct.super_column);
oprot.writeFieldEnd();
}
}
if (struct.predicate != null) {
if (struct.isSetPredicate()) {
oprot.writeFieldBegin(PREDICATE_FIELD_DESC);
struct.predicate.write(oprot);
oprot.writeFieldEnd();
}
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class DeletionTupleSchemeFactory implements SchemeFactory {
public DeletionTupleScheme getScheme() {
return new DeletionTupleScheme();
}
}
private static class DeletionTupleScheme extends TupleScheme<Deletion> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, Deletion struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
if (struct.isSetTimestamp()) {
optionals.set(0);
}
if (struct.isSetSuper_column()) {
optionals.set(1);
}
if (struct.isSetPredicate()) {
optionals.set(2);
}
oprot.writeBitSet(optionals, 3);
if (struct.isSetTimestamp()) {
oprot.writeI64(struct.timestamp);
}
if (struct.isSetSuper_column()) {
oprot.writeBinary(struct.super_column);
}
if (struct.isSetPredicate()) {
struct.predicate.write(oprot);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, Deletion struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
BitSet incoming = iprot.readBitSet(3);
if (incoming.get(0)) {
struct.timestamp = iprot.readI64();
struct.setTimestampIsSet(true);
}
if (incoming.get(1)) {
struct.super_column = iprot.readBinary();
struct.setSuper_columnIsSet(true);
}
if (incoming.get(2)) {
struct.predicate = new SlicePredicate();
struct.predicate.read(iprot);
struct.setPredicateIsSet(true);
}
}
}
}
| [
"[email protected]"
] | |
39d9eae79759f0af45fb2f294d95048736bb52d8 | 16cb256167102688418e555cc47118a0ddffc94c | /NHSTowerDefense/Enemy.java | c58f576bfc15f9855b02b42fbe778f495bb00af7 | [] | no_license | JeffreyTerry/HighSchoolProjects | 5e7675a1d47624fa647b25b19fadf85d4d28a132 | b95f2a47e4809ec4cc6f5f3a15d16842c3c79131 | refs/heads/master | 2020-06-27T07:30:22.201104 | 2019-07-31T15:43:49 | 2019-07-31T15:43:49 | 199,884,951 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,851 | java | import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
public class Enemy
{
public static Toolkit tk=Toolkit.getDefaultToolkit(); //This toolkit is used to create images throughout the program
public static Thread raySuperpowerThread;
public static boolean rayIsActive=false;
//These images are only created once. They are static. Each object's enemyImages ArrayList will refer to one of these
public static ArrayList<Image> enemyJellyBeanImages=new ArrayList<Image>();
public static ArrayList<Image> enemyStrongJellyBeanImages=new ArrayList<Image>();
public static ArrayList<Image> enemyZombieImages=new ArrayList<Image>();
public static ArrayList<Image> enemyNathanImages=new ArrayList<Image>();
public static ArrayList<Image> enemyRayImages=new ArrayList<Image>();
public static ArrayList<Image> enemyJellyBeanDeathImages=new ArrayList<Image>();
public static ArrayList<Image> enemyStrongJellyBeanDeathImages=new ArrayList<Image>();
public static ArrayList<Image> enemyZombieDeathImages=new ArrayList<Image>();
public static ArrayList<Image> enemyNathanDeathImages=new ArrayList<Image>();
public static ArrayList<Image> enemyRayDeathImages=new ArrayList<Image>();
ArrayList<Image> enemyImages=new ArrayList<Image>(); //The images for the current object
public int numberOfImages=1;
public double imageCounter=0;
public double imageCounterDelay=0.1;
ArrayList<Image> enemyDeathImages=new ArrayList<Image>();
public int numberOfDeathImages=1;
public double deathImageCounter=0;
public double deathImageCounterDelay=0.1;
public static int JellyBeanWidth=50,JellyBeanHeight=50,StrongJellyBeanWidth=60,StrongJellyBeanHeight=60,ZombieWidth=90,ZombieHeight=90,NathanWidth=80,NathanHeight=80,RayWidth=200,RayHeight=300;
public int width,height;
public Path path;
public int indexInPath;
public int x,y;
public int xCenter,yCenter;
public int xOffset,yOffset;
public String type;
public int health,cashValue;
public boolean dead;
public int futureDamage=0;
public int refreshesPerMovement=1; //Is used to change how fast the enemy moves across the screen
public int refreshes=1;
public Enemy(Enemy e)
{
type=e.type;
path=e.path;
indexInPath=0;
x=e.x;
y=e.y;
numberOfImages=e.numberOfImages;
imageCounterDelay=e.imageCounterDelay;
for(Image image: e.enemyImages)
{
enemyImages.add(image);
}
for(Image image: e.enemyDeathImages)
{
enemyDeathImages.add(image);
}
refreshesPerMovement=e.refreshesPerMovement;
health=e.health;
cashValue=e.cashValue;
xOffset=e.xOffset;
yOffset=e.yOffset;
}
public Enemy(String type,Path p)
{
this.type=type;
path=p;
indexInPath=0;
x=path.pointsInPath.get(0).x;
y=path.pointsInPath.get(0).y;
//These if statements set the values for each enemy type. They are very influential
if(type.equals("JellyBean"))
{
refreshesPerMovement=1;
health=4000;
cashValue=4;
width=JellyBeanWidth;
height=JellyBeanHeight;
xOffset=-15;
yOffset=-10;
numberOfImages=11;
imageCounterDelay=0.1;
numberOfDeathImages=11;
deathImageCounterDelay=0.1;
enemyImages=enemyJellyBeanImages;
enemyDeathImages=enemyJellyBeanDeathImages;
}
else if(type.equals("StrongJellyBean"))
{
refreshesPerMovement=2;
health=12000;
cashValue=8;
width=StrongJellyBeanWidth;
height=StrongJellyBeanHeight;
xOffset=-15;
yOffset=-10;
numberOfImages=11;
imageCounterDelay=0.1;
numberOfDeathImages=11;
deathImageCounterDelay=0.1;
enemyImages=enemyStrongJellyBeanImages;
enemyDeathImages=enemyStrongJellyBeanDeathImages;
}
else if(type.equals("Zombie"))
{
refreshesPerMovement=5;
health=30000;
cashValue=10;
width=ZombieWidth;
height=ZombieHeight;
xOffset=-15;
yOffset=-10;
numberOfImages=11;
imageCounterDelay=0.08;
numberOfDeathImages=11;
deathImageCounterDelay=0.1;
enemyImages=enemyZombieImages;
enemyDeathImages=enemyZombieDeathImages;
}
else if(type.equals("Nathan"))
{
refreshesPerMovement=1;
health=20000;
cashValue=10;
width=NathanWidth;
height=NathanHeight;
xOffset=-15;
yOffset=-10;
numberOfImages=11;
imageCounterDelay=0.08;
numberOfDeathImages=7;
deathImageCounterDelay=0.08;
enemyImages=enemyNathanImages;
enemyDeathImages=enemyNathanDeathImages;
}
else if(type.equals("Ray"))
{
refreshesPerMovement=6;
health=1200000;
cashValue=4000;
width=RayWidth;
height=RayHeight;
xOffset=-15;
yOffset=-10;
numberOfImages=8;
imageCounterDelay=0.06;
numberOfDeathImages=8;
deathImageCounterDelay=0.1;
enemyImages=enemyRayImages;
enemyDeathImages=enemyRayDeathImages;
raySuperpowerThread=new Thread(new RaySuperpowerRunner());
}
}
public void moveAlongPath()
{
if(refreshes>=refreshesPerMovement && indexInPath<path.pointsInPath.size())
{
x=path.pointsInPath.get(indexInPath).x;
y=path.pointsInPath.get(indexInPath).y;
indexInPath++;
refreshes=1;
}
else if(indexInPath<path.pointsInPath.size())
{
refreshes++;
}
else
{
if(TowerDefenseFrame.livesLeft<=1) //If there is only one life left and this enemy escapes, there will be zero lives left, which should result in a game over
{
TowerDefenseFrame.livesLeft--;
TowerDefenseFrame.livesLabel.setText("Lives: "+TowerDefenseFrame.livesLeft);
TowerDefenseFrame.lose();
}
else
{
TowerDefenseFrame.livesLeft--;
TowerDefenseFrame.livesLabel.setText("Lives: "+TowerDefenseFrame.livesLeft);
if(type.equals("Ray"))
{
boolean otherRayExists=false;
for(int i=0;i<TowerDefenseFrame.map.enemies.size();i++)
{
if(TowerDefenseFrame.map.enemies.get(i).type.equals("Ray") && TowerDefenseFrame.map.enemies.get(i)!=this)
{
otherRayExists=true;
}
}
if(!otherRayExists) //If there are no other rays alive, stop his superpower
stopRaySuperpower();
}
}
try
{
TowerDefenseFrame.map.enemies.remove(this);
}
catch(ConcurrentModificationException e)
{
System.out.println("Caught");
}
}
}
public void takeHealth(int damage)
{
health-=damage;
if(health<=0)
{
dead=true;
refreshesPerMovement+=2;
TowerDefenseFrame.cashMoneyFlow+=cashValue;
TowerDefenseFrame.cashLabel.setText("Cash: "+TowerDefenseFrame.cashMoneyFlow);
}
}
public void draw(Graphics g)
{
if(!dead && imageCounter<numberOfImages)
{
g.drawImage(enemyImages.get((int)imageCounter),x-width/2,y-height/2,width,height,null);
imageCounter+=imageCounterDelay;
}
else if(!dead)
{
imageCounter=0;
g.drawImage(enemyImages.get((int)imageCounter),x-width/2,y-height/2,width,height,null);
}
if(dead && deathImageCounter<numberOfDeathImages)
{
if(type.equals("Ray") && raySuperpowerThread.isAlive()) //This makes sure that if rayStopIt is true when Ray dies, it makes it false
{
stopRaySuperpower(); //Stops Ray's superpower
//This sleep is for animation effect
try
{
Thread.sleep(200);
}
catch(Exception e){}
}
g.drawImage(enemyDeathImages.get((int)deathImageCounter),x-width/2,y-height/2,width,height,null);
deathImageCounter+=deathImageCounterDelay;
}
else if(dead)
{
TowerDefenseFrame.map.enemies.remove(this);
}
}
//Starts Ray's Superpower
public static void startRaySuperpower()
{
rayIsActive=true;
raySuperpowerThread.start();
}
//Stops Ray's Superpower
public static void stopRaySuperpower()
{
Enemy.rayIsActive=false;
while(raySuperpowerThread.isAlive()) //Waits until the RaySuperpowerRunner stops executing
{
try
{
Thread.sleep(1);
}
catch(Exception e){}
}
TowerDefenseFrame.rayStopIt=false; //Makes absolutely sure rayStopIt isn't true
}
//Should be called once and only once by the map object using it
public static void createEnemyImages()
{
if(enemyNathanImages.size()==0) //This makes sure the method hasn't already been called
{
int numberOfImages=11; //These are local variables, not to be confused with the class variables
int numberOfDeathImages=11;
for(int i=1;i<=numberOfImages;i++)
{
enemyJellyBeanImages.add(tk.createImage("./Images/DelayedMobs/Mob_JellyBean"+i+".png"));
}
for(int i=1;i<=numberOfDeathImages;i++)
{
enemyJellyBeanDeathImages.add(tk.createImage("./Images/DelayedMobs/Mob_JellyBean_Death"+i+".png"));
}
for(int i=1;i<=numberOfImages;i++)
{
enemyStrongJellyBeanImages.add(tk.createImage("./Images/DelayedMobs/Mob_StrongJellyBean"+i+".png"));
}
for(int i=1;i<=numberOfDeathImages;i++)
{
enemyStrongJellyBeanDeathImages.add(tk.createImage("./Images/DelayedMobs/Mob_StrongJellyBean_Death"+i+".png"));
}
for(int i=1;i<=numberOfImages;i++)
{
enemyZombieImages.add(tk.createImage("./Images/DelayedMobs/Mob_Zombie"+i+".png"));
}
for(int i=1;i<=numberOfDeathImages;i++)
{
enemyZombieDeathImages.add(tk.createImage("./Images/DelayedMobs/Mob_Zombie_Death"+i+".png"));
}
for(int i=1;i<=numberOfImages;i++)
{
enemyNathanImages.add(tk.createImage("./Images/DelayedMobs/Mob_Nathan"+i+".png"));
}
numberOfDeathImages=7;
for(int i=1;i<=numberOfDeathImages;i++)
{
enemyNathanDeathImages.add(tk.createImage("./Images/DelayedMobs/Mob_Nathan_Death"+i+".png"));
}
numberOfImages=8;
for(int i=1;i<=numberOfImages;i++)
{
enemyRayImages.add(tk.createImage("./Images/DelayedMobs/Mob_Ray"+i+".png"));
}
numberOfDeathImages=8;
for(int i=1;i<=numberOfDeathImages;i++)
{
enemyRayDeathImages.add(tk.createImage("./Images/DelayedMobs/Mob_RayDeath"+i+".png"));
}
}
}
//This class runs Ray's superpower
public class RaySuperpowerRunner implements Runnable
{
public int counter=0;
public final int TIME_TO_HIDE_STOP_IT=5000;
public final int TIME_TO_SHOW_STOP_IT=6000;
public void run()
{
TowerDefenseFrame.rayStopIt=false;
while(Enemy.rayIsActive && counter<TIME_TO_HIDE_STOP_IT)
{
try
{
Thread.sleep(10);
}
catch(Exception e){}
counter+=10;
}
counter=0;
TowerDefenseFrame.rayStopIt=true;
while(Enemy.rayIsActive && counter<TIME_TO_SHOW_STOP_IT)
{
try
{
Thread.sleep(10);
}
catch(Exception e){}
counter+=10;
}
counter=0;
if(Enemy.rayIsActive)
run();
TowerDefenseFrame.rayStopIt=false;
}
}
}
| [
"[email protected]"
] | |
a6d537960ce3ca65e11337256778f6734b5d4d68 | 892e1b19ba7cbb7ca98045e289e03ea505a18327 | /src/main/java/com/study/java/java8/lambda/MyFun.java | 30ddefc30b8eb94f16df2125cbe93203cb87bf54 | [] | no_license | gaoyuanyuan2/java | fa16fb2d97f2503ffc34091148db96fe946d5f41 | 4154ae235da7ecf21d4f23242729f186d94b413e | refs/heads/master | 2022-06-24T10:25:00.653360 | 2019-12-16T15:58:28 | 2019-12-16T15:58:28 | 134,975,226 | 0 | 0 | null | 2022-06-17T01:55:47 | 2018-05-26T15:58:17 | Java | UTF-8 | Java | false | false | 161 | java | package com.study.java.java8.lambda;
//检查是否为函数式接口
@FunctionalInterface
public interface MyFun {
public Integer getValue(Integer num);
}
| [
"[email protected]"
] | |
395bd23619e6a92ccaa749c1fc2c0619387c1b21 | 38ee31f2027a0e265df337f602e15b7b6d5fd2c9 | /AOPProj2-SpringAOPDecl-ProxyInterface/src/main/java/com/nt/advice/AroundLoggingAdvice.java | 66f81be3924b4785e3115645e175b0bf872a8a20 | [] | no_license | nerdseeker365/NTSP711 | c4d598212bf368577aac3e6821a5a72f19111b8d | 78cae427d0d94f48448e173610c136f41fc914c2 | refs/heads/master | 2022-02-24T11:14:05.519116 | 2019-10-26T17:36:24 | 2019-10-26T17:36:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,052 | java | package com.nt.advice;
import java.util.Arrays;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class AroundLoggingAdvice implements MethodInterceptor {
public Object invoke(MethodInvocation invocation) throws Throwable {
Object retVal=null;
Object args[]=null;
System.out.println("Entering into "+invocation.getMethod().getName()+" with args"+Arrays.toString(invocation.getArguments()));
args=invocation.getArguments();
if(((Float)args[0])<=50000)
args[1]=((Float)args[1])-0.5f; //modifying target method args
if(((Float)args[0])<=0 || ((Float)args[1])<=0 || ((Float)args[2])<=0) //controlling target method
throw new IllegalArgumentException("provide valid inputs");
retVal=invocation.proceed();
retVal=((Float)retVal)+((Float)retVal)*0.01f; //modifying return value..
System.out.println("Exiting from "+invocation.getMethod().getName()+" with args"+Arrays.toString(invocation.getArguments()));
return retVal;
}
}
| [
"admin@DESKTOP-8KUS3QR"
] | admin@DESKTOP-8KUS3QR |
8fa0fc405a9a15df0c12b9d956a3a586558c0d1b | 094f9436fe2c9765f83215404153a91856e3d19b | /src/com/baizhi/action/TypeAction.java | 42ecd9999cf8918086fc7730914f7634f18b51b7 | [] | no_license | GuoJiafeng/DangDang | a45810ed951237f62aa4bc0e579c0c5524a3da83 | d280a46be8fdf49b8a87e119bffc791e460c0a1b | refs/heads/master | 2021-07-15T11:31:41.830679 | 2017-10-23T01:21:03 | 2017-10-23T01:21:03 | 107,784,286 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,941 | java | package com.baizhi.action;
import com.baizhi.entity.Goods;
import com.baizhi.entity.PageBean;
import com.baizhi.entity.TypeFather;
import com.baizhi.entity.TypeSon;
import com.baizhi.service.GoodsService;
import com.baizhi.service.TypeService;
import com.baizhi.service.impl.GoodsServiceImpl;
import com.baizhi.service.impl.TypeServiceImpl;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.util.ValueStack;
import java.util.List;
/**
* @Author :Create by Guo Jiafeng
* @Date : Created in 15:45 2017/9/16
* @Descripon :
*/
public class TypeAction extends ActionSupport {
private Integer fid;
private Integer sid;
private Goods goods;
private TypeFather typeFather;
private List<TypeFather> typeSonList;
private PageBean pageBean;
private Integer pageNum;
public Integer getFid() {
return fid;
}
public void setFid(Integer fid) {
this.fid = fid;
}
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public Goods getGoods() {
return goods;
}
public void setGoods(Goods goods) {
this.goods = goods;
}
public TypeFather getTypeFather() {
return typeFather;
}
public void setTypeFather(TypeFather typeFather) {
this.typeFather = typeFather;
}
public List<TypeFather> getTypeSonList() {
return typeSonList;
}
public void setTypeSonList(List<TypeFather> typeSonList) {
this.typeSonList = typeSonList;
}
public PageBean getPageBean() {
return pageBean;
}
public void setPageBean(PageBean pageBean) {
this.pageBean = pageBean;
}
public Integer getPageNum() {
if (pageNum==null){
pageNum = 1;
}
return pageNum;
}
public void setPageNum(Integer pageNum) {
this.pageNum = pageNum;
}
public String showBookTypeAction() {
TypeService typeService = new TypeServiceImpl();
typeSonList = typeService.showBookType();
ValueStack vs = ActionContext.getContext().getValueStack();
vs.setValue("#request.list", typeSonList);
System.out.println(typeSonList);
return null;
}
public String showFatherTypeById() {
TypeService service = new TypeServiceImpl();
typeFather = service.showFatherTypeById(fid);
ValueStack vs = ActionContext.getContext().getValueStack();
vs.setValue("#request.typeFatherById", typeFather);
System.out.println(typeFather);
return "success";
}
public String showSonTypeById() {
TypeService service = new TypeServiceImpl();
typeFather = service.showSonTypeById(fid, sid);
ValueStack vs = ActionContext.getContext().getValueStack();
vs.setValue("#request.typeSonById", typeFather);
System.out.println(typeFather);
return "success";
}
public String showFatherTypeAndSonType() {
TypeService service = new TypeServiceImpl();
typeFather = service.showFatherTypeAndSonType(fid);
ValueStack vs = ActionContext.getContext().getValueStack();
vs.setValue("#request.typeSonAndFather", typeFather);
System.out.println(typeFather);
return null;
}
public String showBookListAction() {
TypeService typeService = new TypeServiceImpl();
GoodsService goodsService = new GoodsServiceImpl();
if (fid != null && sid == null) {
typeFather = typeService.showFatherTypeById(fid);
ValueStack vs = ActionContext.getContext().getValueStack();
vs.setValue("#request.typeFatherById", typeFather);
PageBean pb = new PageBean(getPageNum(),5,0);
List<Goods> list = goodsService.showBooksByFatherId(fid,pb);
vs.setValue("#request.showBookList", list);
vs.setValue("#request.pb", pb);
System.out.println(typeFather);
System.out.println(list);
}
if (fid != null && sid != null) {
typeFather = typeService.showSonTypeById(fid, sid);
ValueStack vs = ActionContext.getContext().getValueStack();
vs.setValue("#request.typeSonById", typeFather);
PageBean pb = new PageBean(getPageNum(),5,0);
List<Goods> list = goodsService.showBooksBySonId(sid, pb);
vs.setValue("#request.pb", pb);
System.out.println(list);
vs.setValue("#request.showBookList", list);
System.out.println(typeFather);
}
typeFather = typeService.showFatherTypeAndSonType(fid);
ValueStack vs = ActionContext.getContext().getValueStack();
vs.setValue("#request.typeSonAndFather", typeFather);
System.out.println(typeFather);
return "success";
}
}
| [
"[email protected]"
] | |
d8482f7a94d7f4704f4aa3aa580e9d24d858aa71 | 0e8d4d9ae64ff54a0cec344b0184d5035299c9db | /src/SBI_19.java | d600ac33e3f7da3d218cddb9113f1ca6962ca8bb | [] | no_license | Srinivas2911/homework29022020 | b7149b34ac38c561198693411e75e9776657c2fc | 99087f9b4d7f6d77709f19d3e7dfa5b8ffab8f9e | refs/heads/master | 2021-02-13T11:43:21.718455 | 2020-03-03T17:02:25 | 2020-03-03T17:02:25 | 244,693,411 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 201 | java | class SBI_19 extends Bank_19 { // child class SBI_19 extends to Bank_19
public int getRateOfInterest(){ // instance method of int data tyoe with return
return 8;
}
}
| [
"[email protected]"
] | |
a1a5840e59af613e9c66ac78c1318cde3ec78398 | 941143317c6cccab55c8aaca4b7f8b1b853e6545 | /Contentprovider_test/app/src/main/java/com/example/ting/contentprovider_test/MainActivity.java | 940462db6909a2e66ead274e701f27bbece36caf | [] | no_license | StrikeDing/android-study | 21e8a91f669f8ab3234a3dbf45bd9dba6361ef4c | 842aeb9a04350ecc0a5d95ad20c851edc3495359 | refs/heads/master | 2021-01-10T15:09:53.994170 | 2016-05-02T14:58:51 | 2016-05-02T14:58:51 | 55,847,112 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,712 | java | package com.example.ting.contentprovider_test;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
ListView listView;
ArrayAdapter<String> adapter;
List<String> list = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.list);
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list);
listView.setAdapter(adapter);
readContacts();
}
public void readContacts(){
Cursor cursor = null;
try{
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,null,null,null);
while (cursor.moveToNext())
{
String name = cursor.getString(cursor.getColumnIndex
(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number = cursor.getString(cursor.getColumnIndex
(ContactsContract.CommonDataKinds.Phone.NUMBER));
list.add(name+"\n"+number);
}
}catch (Exception e){e.printStackTrace();}
finally {
if (cursor!=null)
cursor.close();
}
}
}
| [
"[email protected]"
] | |
892184d27f180209388b88b8164ebedef368d78d | c4109916a9e64d408dcd08d56843a1153d35dfc1 | /app/src/androidTest/java/woojy/kr/hs/emirim/audiolist/ExampleInstrumentedTest.java | a66a2ddbc9e899a9b60d097e3858060592053943 | [] | no_license | woojaeyun/AudioList | 0a1574185d61a73606a2a6192465ecaf97a3be90 | 1f826adf281d9744a8edf6ba8828302967b55904 | refs/heads/master | 2021-01-21T20:56:23.516348 | 2017-06-19T11:34:15 | 2017-06-19T11:34:15 | 94,764,480 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 760 | java | package woojy.kr.hs.emirim.audiolist;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("woojy.kr.hs.emirim.audiolist", appContext.getPackageName());
}
}
| [
"[email protected]"
] | |
fcd76d7f0b44c60bc43788b2f673f48dd619f8c7 | 78b200df0a21896781c2065529727a1a2201f282 | /Meteor/src/main/java/net/onrc/openvirtex/messages/OVXRoleReply.java | 51137c9090b3af59f1996df5234b330e28a859b5 | [
"Apache-2.0",
"MIT"
] | permissive | yeonhooy/Meteor_Control_Channel_Isolation_SDN_Virtualization | dca8c8ec850a2299b4b5a9c2007f28374c7af347 | a714bab0243d7234d33823c71a4f28450dd75d0f | refs/heads/main | 2023-04-16T10:24:21.791587 | 2023-03-15T09:25:49 | 2023-03-15T09:25:49 | 594,984,714 | 7 | 2 | null | 2023-02-03T16:02:41 | 2023-01-30T06:26:12 | Java | UTF-8 | Java | false | false | 1,381 | java | /*
* ******************************************************************************
* Copyright 2019 Korea University & Open Networking Foundation
*
* 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.
* ******************************************************************************
* Developed by Libera team, Operating Systems Lab of Korea University
* ******************************************************************************
*/
package net.onrc.openvirtex.messages;
import net.onrc.openvirtex.elements.datapath.PhysicalSwitch;
import org.projectfloodlight.openflow.protocol.OFMessage;
public class OVXRoleReply extends OVXMessage implements Virtualizable {
public OVXRoleReply(OFMessage msg) {
super(msg);
}
@Override
public void virtualize(PhysicalSwitch sw) {
OVXMessageUtil.untranslateXidAndSend(this, sw);
}
}
| [
"[email protected]"
] | |
014dc17f06c87c5a3e691971c2e2ccf233f481e0 | 332b2f7d17bdceb708704325da21a441d87501d0 | /src/main/java/com/javaee/klenner/rabbitmq/config/RabbitMQConfig.java | b880d5026587970c1fda2c58b649e5d191e1b1cd | [] | no_license | klenner1/rabbitmq | 78d3a575528f2a15da24439148c978e01e1ba181 | 1e150bf12dba392076087e471759117a9a992a5c | refs/heads/master | 2020-03-22T18:27:07.323823 | 2018-07-10T16:38:47 | 2018-07-10T16:38:47 | 140,461,038 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,363 | java | package com.javaee.klenner.rabbitmq.config;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.ExchangeBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.annotation.RabbitListenerConfigurer;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.RabbitListenerEndpointRegistrar;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.converter.MappingJackson2MessageConverter;
import org.springframework.messaging.handler.annotation.support.DefaultMessageHandlerMethodFactory;
import org.springframework.messaging.handler.annotation.support.MessageHandlerMethodFactory;
@Configuration
public class RabbitMQConfig implements RabbitListenerConfigurer {
public static final String QUEUE_MESSAGES = "messages-queue";
public static final String EXCHANGE_MESSAGES = "messages-exchange";
public static final String QUEUE_DEAD_MESSAGES = "dead-messages-queue";
@Bean
Queue messagesQueue() {
return QueueBuilder.durable(QUEUE_MESSAGES)
.withArgument("x-dead-letter-exchange", "")
.withArgument("x-dead-letter-routing-key", QUEUE_DEAD_MESSAGES)
.withArgument("x-message-ttl", 15000) //if message is not consumed in 15 seconds send to DLQ
.build();
}
@Bean
Queue deadMessagesQueue() {
return QueueBuilder.durable(QUEUE_DEAD_MESSAGES).build();
}
@Bean
Exchange messagesExchange() {
return ExchangeBuilder.topicExchange(EXCHANGE_MESSAGES).build();
}
@Bean
Binding binding(Queue messagesQueue, TopicExchange messagesExchange) {
return BindingBuilder.bind(messagesQueue).to(messagesExchange).with(QUEUE_MESSAGES);
}
@Bean
public RabbitTemplate rabbitTemplate(final ConnectionFactory connectionFactory) {
final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
rabbitTemplate.setMessageConverter(producerJackson2MessageConverter());
return rabbitTemplate;
}
@Bean
public Jackson2JsonMessageConverter producerJackson2MessageConverter() {
return new Jackson2JsonMessageConverter();
}
@Override
public void configureRabbitListeners(RabbitListenerEndpointRegistrar register) {
register.setMessageHandlerMethodFactory(messageHandlerMethodFactory());
}
@Bean
MessageHandlerMethodFactory messageHandlerMethodFactory() {
DefaultMessageHandlerMethodFactory messageHandlerMethodFactory = new DefaultMessageHandlerMethodFactory();
messageHandlerMethodFactory.setMessageConverter(consumerJackson2MessageConverter());
return messageHandlerMethodFactory;
}
@Bean
public MappingJackson2MessageConverter consumerJackson2MessageConverter() {
return new MappingJackson2MessageConverter();
}
}
| [
"[email protected]"
] | |
85be8c84dd75d0d2c9020d47580891bdeec6a529 | ea0abe0b5794f4bef5c037646217d75643cd9625 | /Samridhi2/app/src/main/java/com/example/sandrok/samridhi2/HealthActivity.java | ac1986af3ed4a21cd78a428d8196286b987d098a | [] | no_license | Bengaluru2016/team-8 | 539881261dee915ab2e59031b12672a5983c4514 | 479f6f69080afbc6e97e81c9fc5f942f7dd9c8a6 | refs/heads/master | 2021-01-18T02:38:15.908611 | 2016-07-10T06:37:13 | 2016-07-10T06:37:13 | 62,737,020 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,910 | java | package com.example.sandrok.samridhi2;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
public class HealthActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
EditText name,height,weight,dental,overall;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_health);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
name = (EditText) findViewById(R.id.name);
height = (EditText) findViewById(R.id.height);
weight = (EditText) findViewById(R.id.weight);
dental = (EditText) findViewById(R.id.dental);
overall = (EditText) findViewById(R.id.overall);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new HealthConnection("http://52.77.224.71/Health.php",name.getText().toString(),height.getText().toString(),weight.getText().toString(),dental.getText().toString(),overall.getText().toString()).execute();
Snackbar.make(view, "Updated the student details. Thank you!", Snackbar.LENGTH_LONG)
.setAction("Action", null).show(); }
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.health, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
Intent intent = new Intent(HealthActivity.this,EnterDetailsActivity.class);
startActivity(intent);
} else if (id == R.id.nav_gallery) {
Intent intent = new Intent(HealthActivity.this,MarksActivity.class);
startActivity(intent);
} else if (id == R.id.nav_slideshow) {
}
else if (id == R.id.nav_share){
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "9880290275"));
startActivity(intent);
}
else if (id == R.id.nav_send){
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Join your hands to give a wonderful future to the deserved ones. Invest in the future of India!! Spread the word about Samridhdhi Trust.");
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, "Samridhdhi trust"));
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
| [
"[email protected]"
] | |
1e9c3d6b6f2f4eb5ca12eb4cdff6f91c52bd1c01 | d0b2ba945a711c7b62c403e50be93860ea27bbad | /kobuka-spring/src/main/java/org/swisspush/kobuka/spring/DefaultKafkaConsumerFactoryBuilder.java | ce96ce8b6b379b166efe989540eba260298383d0 | [
"Apache-2.0"
] | permissive | ZhengXinCN/kobuka | ad7288edc6a58fa87b2b76a114d133db5603a763 | d98a987f57e2c7c3f8c2ed87f46675d73d16d899 | refs/heads/master | 2023-07-07T21:59:22.985404 | 2021-09-01T02:33:58 | 2021-09-01T02:33:58 | 400,373,442 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 295 | java | package org.swisspush.kobuka.spring;
import java.util.Map;
public class DefaultKafkaConsumerFactoryBuilder<K, V>
extends AbstractDefaultKafkaConsumerFactoryBuilder<K, V> {
public DefaultKafkaConsumerFactoryBuilder(Map<String, Object> configs) {
configs(configs);
}
}
| [
"[email protected]"
] | |
ddafcca19330cebc3631a5a306ecb92e868a0a35 | 47605674b07c4f1be4c6e08c433715af5eea10d7 | /extensible-logging-framework/src/main/java/com/sa/logprovider/framework/core/LogProviderFactoryImpl.java | a7fcbcaf8ef36163dfc02832fbcf815ea34f85b6 | [] | no_license | soumena/logging-framework | 5fc79d2c64e24c1337c3a917bebd76766dd2e07e | ce4e58fa7725b5a9a158ff5a6648700f3a76a533 | refs/heads/master | 2022-08-27T13:17:34.361712 | 2020-05-18T01:49:22 | 2020-05-18T01:49:22 | 264,760,297 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 990 | java | package com.sa.logprovider.framework.core;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import com.sa.logprovider.framework.enums.LogProviderType;
import com.sa.logprovider.framework.providers.LogProvider;
/**
* @author souadhik
*
*/
@Service
public class LogProviderFactoryImpl extends LogProviderBaseFactory implements LogProviderFactory{
/**
*
*/
private @Autowired @Lazy List<LogProvider> logProviderList;
/**
* Lazy instantiation of the Provider beans based on Provider type
*/
@Override
public LogProvider createProvider(String message,LogProviderType providerType) {
Optional<LogProvider> filteredlogProvider = logProviderList
.stream()
.filter(p->p.getProvideType().equals(providerType)).findFirst();
return filteredlogProvider.isPresent()?filteredlogProvider.get():null;
}
}
| [
"[email protected]"
] | |
a27e2b5f630571146154068bec38f8ca39ba05f0 | 5559e20aca6f7f77d8d683145a0cd7be17f16799 | /PetrifyPlugin/src/org/workcraft/plugins/petrify/commands/StandardCelementSynthesisCommand.java | 8b4a63e18a16c7f34ba8284265958c4adfda4ed2 | [
"MIT"
] | permissive | sefanja/workcraft | 605da242d160ad1af9d74cb28e3a97f7cfbd26b9 | d724afdc9b7ff2f684132c17f3bae10fef577d31 | refs/heads/master | 2020-06-02T16:57:30.896440 | 2019-06-01T11:51:30 | 2019-06-01T11:51:30 | 191,236,899 | 0 | 0 | MIT | 2019-06-16T20:52:53 | 2019-06-10T19:58:45 | Java | UTF-8 | Java | false | false | 710 | java | package org.workcraft.plugins.petrify.commands;
public class StandardCelementSynthesisCommand extends AbstractPetrifySynthesisCommand {
@Override
public String[] getSynthesisParameter() {
return new String[] {"-mc"};
}
@Override
public String getDisplayName() {
return "Standard C-element [Petrify]";
}
@Override
public Position getPosition() {
return Position.BOTTOM_MIDDLE;
}
@Override
public boolean boxSequentialComponents() {
return false;
}
@Override
public boolean boxCombinationalComponents() {
return false;
}
@Override
public boolean sequentialAssign() {
return true;
}
}
| [
"[email protected]"
] | |
466136dbffbb853c1bd71df7e99d190537b33d03 | 04ff09bc1c3178fc020a2d17e318d5b29da599e6 | /main/src/main/java/com/sxjs/jd/composition/message/MessageActivity.java | 4fbf68eb58eb4e0358bf2e8c5eab784fac9d2e99 | [
"Apache-2.0"
] | permissive | XiePengLearn/refactor-frontend-android | b9b820007ed216c20b7b590c39639e161c63bbdc | 5a08db4065ae4d7a9dc676a4d5328c8f928a8167 | refs/heads/master | 2020-07-26T08:45:39.313596 | 2019-09-26T09:00:15 | 2019-09-26T09:00:15 | 208,593,612 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,166 | java | package com.sxjs.jd.composition.message;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.antiless.support.widget.TabLayout;
import com.sxjs.common.base.BaseActivity;
import com.sxjs.common.util.LogUtil;
import com.sxjs.common.util.ResponseCode;
import com.sxjs.common.util.ToastUtil;
import com.sxjs.common.util.statusbar.StatusBarUtil;
import com.sxjs.jd.MainDataManager;
import com.sxjs.jd.R;
import com.sxjs.jd.R2;
import com.sxjs.jd.composition.message.attention.AttentionFragment;
import com.sxjs.jd.composition.message.notification.NotificationFragment;
import com.sxjs.jd.composition.message.warn.WarnFragment;
import com.sxjs.jd.entities.LoginResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* @author xiepeng
*/
@Route(path = "/messageActivity/messageActivity")
public class MessageActivity extends BaseActivity implements MessageContract.View {
@Inject
MessagePresenter presenter;
@BindView(R2.id.fake_status_bar)
View fakeStatusBar;
@BindView(R2.id.jkx_title_left)
TextView jkxTitleLeft;
@BindView(R2.id.jkx_title_left_btn)
Button jkxTitleLeftBtn;
@BindView(R2.id.jkx_title_center)
TextView jkxTitleCenter;
@BindView(R2.id.jkx_title_right_btn)
TextView jkxTitleRightBtn;
@BindView(R2.id.new_message)
TextView newMessage;
@BindView(R2.id.rl_new_message)
RelativeLayout rlNewMessage;
@BindView(R2.id.jkx_title_right)
TextView jkxTitleRight;
@BindView(R2.id.tabLayout)
TabLayout tabLayout;
@BindView(R2.id.jkx_viewpage)
ViewPager jkxViewpage;
@BindView(R2.id.new_message1)
TextView newMessage1;
@BindView(R2.id.new_message2)
TextView newMessage2;
@BindView(R2.id.new_message3)
TextView newMessage3;
private String mXinGeToken;
private static final String TAG = "NationExamActivity";
private Button mLoginEntry;
private LoginResponse loginResponse;
List<Fragment> fragments;
private MessageAdapter adapter;
String[] tabTitle = {"通知", "提醒", "关注"};
private Intent mIntent;
private int mTz;
private int mTx;
private int mGz;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
StatusBarUtil.setImmersiveStatusBar(this, true);
unbinder = ButterKnife.bind(this);
mIntent = getIntent();
mTz = mIntent.getIntExtra("tz", 0);
if (mTz > 0) {
newMessage1.setVisibility(View.VISIBLE);
newMessage1.setText("" + mTz);
} else {
newMessage1.setVisibility(View.INVISIBLE);
}
mTx = mIntent.getIntExtra("tx", 0);
if (mTx > 0) {
newMessage2.setVisibility(View.VISIBLE);
newMessage2.setText("" + mTx);
} else {
newMessage2.setVisibility(View.INVISIBLE);
}
mGz = mIntent.getIntExtra("gz", 0);
if (mGz > 0) {
newMessage3.setVisibility(View.VISIBLE);
newMessage3.setText("" + mGz);
} else {
newMessage3.setVisibility(View.INVISIBLE);
}
initTitle();
initView();
initDataFragment();
}
private void initDataFragment() {
fragments = new ArrayList<>();
NotificationFragment notificationFragment = NotificationFragment.newInstance();
WarnFragment warnFragment = WarnFragment.newInstance();
AttentionFragment attentionFragment = AttentionFragment.newInstance();
fragments.add(notificationFragment);
fragments.add(warnFragment);
fragments.add(attentionFragment);
adapter = new MessageAdapter(getSupportFragmentManager(), fragments, tabTitle);
jkxViewpage.setAdapter(adapter);
jkxViewpage.setOffscreenPageLimit(2);
tabLayout.setupWithViewPager(jkxViewpage);
}
/**
* 初始化title
*/
public void initTitle() {
//返回按钮
jkxTitleLeft.setVisibility(View.VISIBLE);
//标题
jkxTitleCenter.setText("我的消息");
}
private void initView() {
DaggerMessageActivityComponent.builder()
.appComponent(getAppComponent())
.messagePresenterModule(new MessagePresenterModule(this, MainDataManager.getInstance(mDataManager)))
.build()
.inject(this);
}
public void initData(Map<String, String> mapHeaders, Map<String, Object> mapParameters) {
presenter.getLoginData(mapHeaders, mapParameters);
}
@Override
protected void onResume() {
super.onResume();
}
@Override
public void setLoginData(LoginResponse loginResponse) {
this.loginResponse = loginResponse;
try {
String code = loginResponse.getCode();
String msg = loginResponse.getMsg();
if (code.equals(ResponseCode.SUCCESS_OK)) {
LogUtil.e(TAG, "SESSION_ID: " + loginResponse.getData());
// ARouter.getInstance().build("/main/MainActivity").greenChannel().navigation(this);
// finish();
} else if (code.equals(ResponseCode.SEESION_ERROR)) {
//SESSION_ID为空别的页面 要调起登录页面
} else {
if (!TextUtils.isEmpty(msg)) {
ToastUtil.showToast(this.getApplicationContext(), msg);
}
}
} catch (Exception e) {
ToastUtil.showToast(this.getApplicationContext(), "解析数据失败");
}
}
private void LoginMethod() {
Map<String, Object> mapParameters = new HashMap<>(6);
// mapParameters.put("MOBILE", lAccount);
// mapParameters.put("PASSWORD", lPassword);
mapParameters.put("SIGNIN_TYPE", "1");
mapParameters.put("USER_TYPE", "1");
mapParameters.put("MOBILE_TYPE", "1");
mapParameters.put("XINGE_TOKEN", mXinGeToken);
Map<String, String> mapHeaders = new HashMap<>(1);
mapHeaders.put("ACTION", "S002");
// mapHeaders.put("SESSION_ID", TaskManager.SESSION_ID);
initData(mapHeaders, mapParameters);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("loginResponse", loginResponse);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState != null) {
LoginResponse loginResponse = (LoginResponse) savedInstanceState.getSerializable("loginResponse");
this.loginResponse = loginResponse;
}
}
@Override
public void showProgressDialogView() {
showProgressDialog();
}
@Override
public void hiddenProgressDialogView() {
hiddenProgressDialog();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (presenter != null) {
presenter.destory();
}
}
@OnClick({R2.id.jkx_title_left, R2.id.jkx_title_left_btn})
public void onViewClicked(View view) {
int i = view.getId();
if (i == R.id.jkx_title_left) {
finish();
} else if (i == R.id.jkx_title_left_btn) {
}
}
}
| [
"[email protected]"
] | |
19c2b69576b9918084403d1c13a797c4f6173766 | 24d8cf871b092b2d60fc85d5320e1bc761a7cbe2 | /JFreeChart/rev91-389/base-branch-91/tests/org/jfree/chart/renderer/category/junit/AbstractCategoryItemRendererTests.java | 773ab453b546131d743879bde70c6818971f7131 | [] | no_license | joliebig/featurehouse_fstmerge_examples | af1b963537839d13e834f829cf51f8ad5e6ffe76 | 1a99c1788f0eb9f1e5d8c2ced3892d00cd9449ad | refs/heads/master | 2016-09-05T10:24:50.974902 | 2013-03-28T16:28:47 | 2013-03-28T16:28:47 | 9,080,611 | 3 | 2 | null | null | null | null | UTF-8 | Java | false | false | 9,211 | java |
package org.jfree.chart.renderer.category.junit;
import java.text.NumberFormat;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jfree.chart.labels.IntervalCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardCategorySeriesLabelGenerator;
import org.jfree.chart.labels.StandardCategoryToolTipGenerator;
import org.jfree.chart.renderer.category.AbstractCategoryItemRenderer;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.urls.StandardCategoryURLGenerator;
public class AbstractCategoryItemRendererTests extends TestCase {
public static Test suite() {
return new TestSuite(AbstractCategoryItemRendererTests.class);
}
public void testEquals() {
BarRenderer r1 = new BarRenderer();
BarRenderer r2 = new BarRenderer();
assertEquals(r1, r2);
r1.setToolTipGenerator(new StandardCategoryToolTipGenerator());
assertFalse(r1.equals(r2));
r2.setToolTipGenerator(new StandardCategoryToolTipGenerator());
assertTrue(r1.equals(r2));
r1.setSeriesToolTipGenerator(1, new StandardCategoryToolTipGenerator());
assertFalse(r1.equals(r2));
r2.setSeriesToolTipGenerator(1, new StandardCategoryToolTipGenerator());
assertTrue(r1.equals(r2));
r1.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator("{2}",
NumberFormat.getInstance()));
assertFalse(r1.equals(r2));
r2.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator("{2}",
NumberFormat.getInstance()));
assertTrue(r1.equals(r2));
r1.setItemLabelGenerator(new StandardCategoryItemLabelGenerator());
assertFalse(r1.equals(r2));
r2.setItemLabelGenerator(new StandardCategoryItemLabelGenerator());
assertTrue(r1.equals(r2));
r1.setSeriesItemLabelGenerator(1,
new StandardCategoryItemLabelGenerator());
assertFalse(r1.equals(r2));
r2.setSeriesItemLabelGenerator(1,
new StandardCategoryItemLabelGenerator());
assertTrue(r1.equals(r2));
r1.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator(
"{2}", NumberFormat.getInstance()));
assertFalse(r1.equals(r2));
r2.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator(
"{2}", NumberFormat.getInstance()));
assertTrue(r1.equals(r2));
r1.setItemURLGenerator(new StandardCategoryURLGenerator());
assertFalse(r1.equals(r2));
r2.setItemURLGenerator(new StandardCategoryURLGenerator());
assertTrue(r1.equals(r2));
r1.setSeriesItemURLGenerator(1, new StandardCategoryURLGenerator());
assertFalse(r1.equals(r2));
r2.setSeriesItemURLGenerator(1, new StandardCategoryURLGenerator());
assertTrue(r1.equals(r2));
r1.setBaseItemURLGenerator(new StandardCategoryURLGenerator(
"abc.html"));
assertFalse(r1.equals(r2));
r2.setBaseItemURLGenerator(new StandardCategoryURLGenerator(
"abc.html"));
assertTrue(r1.equals(r2));
r1.setLegendItemLabelGenerator(new StandardCategorySeriesLabelGenerator(
"XYZ"));
assertFalse(r1.equals(r2));
r2.setLegendItemLabelGenerator(new StandardCategorySeriesLabelGenerator(
"XYZ"));
assertTrue(r1.equals(r2));
r1.setLegendItemToolTipGenerator(
new StandardCategorySeriesLabelGenerator("ToolTip"));
assertFalse(r1.equals(r2));
r2.setLegendItemToolTipGenerator(
new StandardCategorySeriesLabelGenerator("ToolTip"));
assertTrue(r1.equals(r2));
r1.setLegendItemURLGenerator(
new StandardCategorySeriesLabelGenerator("URL"));
assertFalse(r1.equals(r2));
r2.setLegendItemURLGenerator(
new StandardCategorySeriesLabelGenerator("URL"));
assertTrue(r1.equals(r2));
}
public void testCloning1() {
AbstractCategoryItemRenderer r1 = new BarRenderer();
r1.setItemLabelGenerator(new StandardCategoryItemLabelGenerator());
AbstractCategoryItemRenderer r2 = null;
try {
r2 = (BarRenderer) r1.clone();
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
assertTrue(r1 != r2);
assertTrue(r1.getClass() == r2.getClass());
assertTrue(r1.equals(r2));
r1 = new BarRenderer();
r1.setSeriesItemLabelGenerator(0,
new StandardCategoryItemLabelGenerator());
r2 = null;
try {
r2 = (BarRenderer) r1.clone();
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
assertTrue(r1 != r2);
assertTrue(r1.getClass() == r2.getClass());
assertTrue(r1.equals(r2));
r1 = new BarRenderer();
r1.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
r2 = null;
try {
r2 = (BarRenderer) r1.clone();
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
assertTrue(r1 != r2);
assertTrue(r1.getClass() == r2.getClass());
assertTrue(r1.equals(r2));
}
public void testCloning2() {
BarRenderer r1 = new BarRenderer();
r1.setItemLabelGenerator(new IntervalCategoryItemLabelGenerator());
BarRenderer r2 = null;
try {
r2 = (BarRenderer) r1.clone();
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
assertTrue(r1 != r2);
assertTrue(r1.getClass() == r2.getClass());
assertTrue(r1.equals(r2));
r1 = new BarRenderer();
r1.setSeriesItemLabelGenerator(0,
new IntervalCategoryItemLabelGenerator());
r2 = null;
try {
r2 = (BarRenderer) r1.clone();
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
assertTrue(r1 != r2);
assertTrue(r1.getClass() == r2.getClass());
assertTrue(r1.equals(r2));
r1 = new BarRenderer();
r1.setBaseItemLabelGenerator(new IntervalCategoryItemLabelGenerator());
r2 = null;
try {
r2 = (BarRenderer) r1.clone();
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
assertTrue(r1 != r2);
assertTrue(r1.getClass() == r2.getClass());
assertTrue(r1.equals(r2));
}
public void testCloning_LegendItemLabelGenerator() {
StandardCategorySeriesLabelGenerator generator
= new StandardCategorySeriesLabelGenerator("Series {0}");
BarRenderer r1 = new BarRenderer();
r1.setLegendItemLabelGenerator(generator);
BarRenderer r2 = null;
try {
r2 = (BarRenderer) r1.clone();
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
assertTrue(r1 != r2);
assertTrue(r1.getClass() == r2.getClass());
assertTrue(r1.equals(r2));
assertTrue(r1.getLegendItemLabelGenerator()
!= r2.getLegendItemLabelGenerator());
}
public void testCloning_LegendItemToolTipGenerator() {
StandardCategorySeriesLabelGenerator generator
= new StandardCategorySeriesLabelGenerator("Series {0}");
BarRenderer r1 = new BarRenderer();
r1.setLegendItemToolTipGenerator(generator);
BarRenderer r2 = null;
try {
r2 = (BarRenderer) r1.clone();
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
assertTrue(r1 != r2);
assertTrue(r1.getClass() == r2.getClass());
assertTrue(r1.equals(r2));
assertTrue(r1.getLegendItemToolTipGenerator()
!= r2.getLegendItemToolTipGenerator());
}
public void testCloning_LegendItemURLGenerator() {
StandardCategorySeriesLabelGenerator generator
= new StandardCategorySeriesLabelGenerator("Series {0}");
BarRenderer r1 = new BarRenderer();
r1.setLegendItemURLGenerator(generator);
BarRenderer r2 = null;
try {
r2 = (BarRenderer) r1.clone();
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
assertTrue(r1 != r2);
assertTrue(r1.getClass() == r2.getClass());
assertTrue(r1.equals(r2));
assertTrue(r1.getLegendItemURLGenerator()
!= r2.getLegendItemURLGenerator());
}
}
| [
"[email protected]"
] | |
a66b348ea554f156931b7c5419217118914319dd | 1a6b8550073408e17ea9aa779b454b3308f10514 | /1.5 - 1.7 version/src/com/gmail/filoghost/chestcommands/api/IconMenu.java | 8803d0ff459d1dd06ddd95ad6ae5c64f82c73042 | [] | no_license | eduardo-mior/MambaChestCommands | 33e8e9426ebebe418b16d9857ecb7ba47cc63df9 | 6f3723344dd640be50ca5872dbffa28d78404046 | refs/heads/master | 2020-03-23T00:32:26.426634 | 2018-07-24T02:50:33 | 2018-07-24T02:50:33 | 140,868,944 | 3 | 3 | null | null | null | null | UTF-8 | Java | false | false | 1,867 | java | package com.gmail.filoghost.chestcommands.api;
import java.util.Arrays;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import com.gmail.filoghost.chestcommands.internal.MenuInventoryHolder;
import com.gmail.filoghost.chestcommands.nms.AttributeRemover;
import com.gmail.filoghost.chestcommands.util.Validate;
/*
* MEMO: Raw slot numbers
*
* | 0| 1| 2| 3| 4| 5| 6| 7| 8|
* | 9|10|11|12|13|14|15|16|17|
* ...
*
*/
public class IconMenu {
protected final String title;
protected final Icon[] icons;
public IconMenu(String title, int rows) {
this.title = title;
icons = new Icon[rows * 9];
}
public void setIcon(int slot, Icon icon) {
if (slot >= 0 && slot < icons.length) {
icons[slot] = icon;
}
}
public void setIconRaw(int slot, Icon icon) {
if (slot >= 0 && slot < icons.length) {
icons[slot] = icon;
}
}
public Icon getIcon(int slot) {
if (slot >= 0 && slot < icons.length) {
return icons[slot];
}
return null;
}
public Icon getIconRaw(int slot) {
if (slot >= 0 && slot < icons.length) {
return icons[slot];
}
return null;
}
public int getRows() {
return icons.length / 9;
}
public int getSize() {
return icons.length;
}
public String getTitle() {
return title;
}
public void open(Player player) {
Validate.notNull(player, "O player nao pode ser nulo!");
Inventory inventory = Bukkit.createInventory(new MenuInventoryHolder(this), icons.length, title);
for (int i = 0; i < icons.length; i++) {
if (icons[i] != null) {
inventory.setItem(i, AttributeRemover.hideAttributes(icons[i].createItemstack(player)));
}
}
player.openInventory(inventory);
}
@Override
public String toString() {
return "IconMenu [title=" + title + ", icons=" + Arrays.toString(icons) + "]";
}
}
| [
"[email protected]"
] | |
97a8b9853493ccdd53c3c94a6f5cded6ceea09e3 | 33e569f0dd0662e375438f65826f1883edf3ccca | /4.JavaCollections/src/com/javarush/task/task36/task3613/Solution.java | 930358b3a9dfddbb9e31ab8a198803e7aaefcc1e | [
"MIT"
] | permissive | MariPhoenix/JavaRushTasks | bb288fc0e8517891903b4cb936823ec5b820633d | e56fe4f8926f6afa0b899f812e75b32f69b418b7 | refs/heads/master | 2020-03-21T09:28:13.485928 | 2018-06-28T11:30:53 | 2018-06-28T11:30:53 | 138,401,352 | 0 | 0 | MIT | 2018-06-23T13:01:38 | 2018-06-23T13:01:38 | null | UTF-8 | Java | false | false | 1,501 | java | package com.javarush.task.task36.task3613;
import java.util.concurrent.SynchronousQueue;
/*
Найти класс по описанию
Описание класса:
1. Пакет этого класса java.util.concurrent.
2. Реализует интерфейс BlockingQueue.
3. Используется при работе с трэдами.
4. Является блокирующей очередью, в которой каждая операция добавления должна ждать соответствующей
операции удаления в другом потоке и наоборот.
5. Не имеет никакой внутренней емкости, даже емкости в один элемент.
Метод getExpectedClass() должен вернуть класс в виде XXX.class, где
XXX — название класса.
Требования:
1. В методе getExpectedClass не должны вызываться никакие методы.
2. Метод getExpectedClass должен вернуть правильный тип.
3. Метод main должен вызывать метод getExpectedClass.
4. Метод main должен вывести полученный класс на экран.
*/
public class Solution {
public static void main(String[] args) {
System.out.println(getExpectedClass());
}
public static Class getExpectedClass() {
return SynchronousQueue.class;
}
} | [
"[email protected]"
] | |
033e6f1a508fe32a87b66201fe918dfb791115b5 | bda354b7ff6ad47fb9c29a322a8c2f2ebc4f6be8 | /Zhitingyun/mylibrary/src/main/java/coder/mylibrary/util/DensityUtil.java | 95f97be2db7e0bd9cbb105c9b97c92f13450f740 | [] | no_license | kingTec-org/Zhitingyun | a0f49e73b60a71668a2eab97090c09f735b1402a | 69e730fc1de3c04b979a6a7f2653514b48e2225b | refs/heads/master | 2020-12-02T09:38:21.601854 | 2018-09-17T03:58:47 | 2018-09-17T03:58:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,628 | java | package coder.mylibrary.util;
import android.content.Context;
import android.util.TypedValue;
/**
* 单位转换类
*/
public class DensityUtil {
/**
* cannot be instantiated
*/
private DensityUtil() {
throw new UnsupportedOperationException("cannot be instantiated");
}
/**
* dp转px
*
* @param context
* @param dpVal
* @return
*/
public static int dp2px(Context context, float dpVal) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
dpVal, context.getResources().getDisplayMetrics());
}
/**
* sp转px
*
* @param context
* @param spVal
* @return
*/
public static int sp2px(Context context, float spVal) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
spVal, context.getResources().getDisplayMetrics());
}
/**
* px转dp
*
* @param context
* @param pxVal
* @return
*/
public static float px2dp(Context context, float pxVal) {
final float scale = context.getResources().getDisplayMetrics().density;
return (pxVal / scale);
}
/**
* px转sp
*
* @param context
* @param pxVal
* @return
*/
public static float px2sp(Context context, float pxVal) {
return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
}
public static int dip2px(Context context, double d) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (d * scale + 0.5f);
}
} | [
"[email protected]"
] | |
1d96036c02bcc225e2d352b6e5a1e1873fd5db03 | 2b13cb785c925db0eef1e7b43d7d21e01fd55b7f | /Blog-ejb/src/java/sessionbeans/LikePostBean.java | c39102a5fad124634c9919990049753edda08fee | [] | no_license | Efrem-berhe/Blog | 50efb41c5668c7179f41e238fa1c72f0044c855c | 6b3b1d8a9c96c0d0da48913c3bddf65263ab11b5 | refs/heads/master | 2021-01-20T00:28:27.540635 | 2017-06-18T01:13:37 | 2017-06-18T01:13:37 | 83,797,118 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 901 | java | /*
* 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 sessionbeans;
import entities.Post;
import interceptors.LoggingInterceptor;
import javax.ejb.EJB;
import javax.ejb.Stateful;
import javax.interceptor.Interceptors;
/**
*
* @author Marek
*/
@Stateful
@Interceptors ({LoggingInterceptor.class})
public class LikePostBean implements LikePostBeanLocal {
private boolean alreadyLiked = false;
@EJB
private PostFacadeLocal postFacade;
public void likePostWithId(long postId) {
if (alreadyLiked) {
return;
}
Post post = postFacade.find(postId);
if (post == null) {
return;
}
post.incrementLikes();
alreadyLiked = true;
}
}
| [
"[email protected]"
] | |
fb12de901727a2957b6a3510ce2316f28536f3b7 | ccb245ed48305e404379cf22fa36799f68b3ff2d | /test-user-sesssion-all/yatospace/user/session/application/MongoSessionsTest.java | 879165540f9fbb0c07ef58b217606c5acd50d713 | [] | no_license | mirko2021/EW-005.008_UserSessions | 34f1183bc1dbde0497cc489bb8e3c26c712abba0 | f90945cd1525da3d31e6153b1a04ae850bf449b3 | refs/heads/master | 2023-05-18T13:35:13.722946 | 2021-06-10T20:22:36 | 2021-06-10T20:22:36 | 375,821,146 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,456 | java | package yatospace.user.session.application;
import java.util.List;
import java.util.Scanner;
import yatospace.user.config.center.SessionDocumentConfigCenter;
import yatospace.user.config.engine.SessionDocumentConfigEngine;
import yatospace.user.config.impl.SessionDocumentDatabaseConfig;
import yatospace.user.session.control.MongoSessionController;
import yatospace.user.session.model.Session;
/**
* Тетирање сесеија.
* @author MV
* @version 1.0
*/
public class MongoSessionsTest {
private static SessionDocumentConfigEngine configEngine = SessionDocumentConfigCenter.cofigurationsEngine;
private static SessionDocumentDatabaseConfig config = configEngine.getDatabaseConfigurations();
private static MongoSessionController sessionController = new MongoSessionController(config.getHost(), config.getPort(), config.getDatabase(), config.getCollection());
private static Scanner scanner = new Scanner(System.in);
public static void menu() {
System.out.println("0. Izlaz");
System.out.println("1. Listanje sesija");
System.out.println("2. Dodavanje sesije");
System.out.println("3. Zatvaranje sesije");
System.out.println("4. Zatvaranje sesija");
System.out.println("5. Pregled sesije");
System.out.println("6. Prebrojavanje");
System.out.println("7. Prebrojavanje korisnika");
System.out.println("8. Listanje korisnika");
System.out.println("9. Prebrajanje sesija korisnika");
System.out.println("10. Listanje sesija korisnika");
}
public static void main(String ... args) {
System.out.println("Dorodosli.");
while(true) {
int izbor = -1; menu();
System.out.print("Izbor : ");
try{izbor = Integer.parseInt(scanner.nextLine()); }catch(Exception ex) {}
if(izbor==0) break;
switch(izbor) {
case 1:
System.out.println("LISTANJE SESIJA");
System.out.println();
list();
break;
case 2:
System.out.println("DODAVANJE SESIJE");
System.out.println();
login();
break;
case 3:
System.out.println("ZATVARANJE SESIJE");
System.out.println();
logout();
break;
case 4:
System.out.println("ZATVARANJE SESIJA");
System.out.println();
logoutAll();
break;
case 5:
System.out.println("PREGLED SESIJE");
System.out.println();
preview();
break;
case 6:
System.out.println("PREBROJAVANJE SESIJA");
System.out.println();
count();
break;
case 7:
System.out.println("PREBROJAVANJE PRIJAVLJENIH KORISNIKA");
System.out.println();
countUsers();
break;
case 8:
System.out.println("LISTANJE PRIJAVLJENIH KORISNIKA");
System.out.println();
listUsers();
break;
case 9:
System.out.println("PREBRAJANJE KORISNICKIH SESIJA");
System.out.println();
countUsersSessions();
break;
case 10:
System.out.println("LISTANJE KORISNICKIH SESIJA");
System.out.println();
listUsersSessions();
break;
default:
System.out.println("POGRESAN IZBOR");
System.out.println();
break;
}
System.out.println();
}
System.out.println("Dovidjenja.");
}
public static void list() {
try {
System.out.print("Velicina stranice : ");
int pageSize = Integer.parseInt(scanner.nextLine());
System.out.print("Broj stranice : ");
int pageNo = Integer.parseInt(scanner.nextLine());
System.out.print("Filter pocetka identifikacije sesije : ");
String sessionFilter = scanner.nextLine();
System.out.print("Filter pocetka identifikacije korisnika : ");
String userFilter = scanner.nextLine();
List<Session> sessions = sessionController.getMemoryForSession().list(pageNo, pageSize, sessionFilter, userFilter);
System.out.println();
for(Session s: sessions)
System.out.println(s.getSessionId()+"\t"+s.getUserId());
}catch(Exception ex) {
System.out.println("Greska pri listanju korisnika.");
}
}
public static void login() {
System.out.print("Korisnik : ");
String username = scanner.nextLine();
System.out.print("Sesija : ");
String session = scanner.nextLine();
Session exist = sessionController.getMemoryForSession().get(username);
if(exist!=null) System.out.println("Sesija vec postoji.");
else {
sessionController.getMemoryForSession().login(username, session);
System.out.println("Dodavanje sesije, to jest logovanje je uspjelo.");
}
}
public static void logout() {
System.out.print("Sesija : ");
String session = scanner.nextLine();
Session exist = sessionController.getMemoryForSession().get(session);
if(exist==null) System.out.println("Sesija ne postoji.");
else {
sessionController.getMemoryForSession().logout(session);
System.out.println("Brisanje sesije je izvrseno.");
}
}
public static void logoutAll() {
try {
System.out.print("Korisnik : ");
String username = scanner.nextLine();
for(Session session: sessionController.getMemoryForSession().getFor(username)) {
sessionController.getMemoryForSession().logout(session.getSessionId());
System.out.println("Odjavljen je korisnik na sesiji "+session.getSessionId());
}
}catch(Exception ex) {
System.out.println("Greska pri odjavljivanju korisnika");
}
}
public static void preview() {
System.out.print("Sesija : ");
String session = scanner.nextLine();
Session s = sessionController.getMemoryForSession().get(session);
if(s == null) {System.out.println("Sesija ne postoji."); return;}
System.out.println("Korisnik : "+ s.getUserId());
System.out.println("Sesija : "+s.getSessionId());
}
public static void count() {
System.out.println("Trenutni broj sesija: "+sessionController.getMemoryForSession().count());
}
public static void countUsers() {
System.out.println("Trenutni broj korisnika : "+sessionController.getMemoryForSession().countUsers());
}
public static void listUsers() {
try {
System.out.print("Velicina stranice : ");
int pageSize = Integer.parseInt(scanner.nextLine());
System.out.print("Broj stranice : ");
int pageNo = Integer.parseInt(scanner.nextLine());
System.out.print("Startni filter : ");
String startFilter = scanner.nextLine();
List<String> users = sessionController.getMemoryForSession().listUsers(pageNo, pageSize, startFilter);
System.out.println();
for(String u: users)
System.out.println(u);
}catch(Exception ex) {
System.out.println("Greska pri listanju korisnika.");
}
}
public static void countUsersSessions() {
System.out.print("Unesi korisnicko ime : ");
String username = scanner.nextLine();
System.out.println("Trenutni broj sesija za korisnika je : "+sessionController.getMemoryForSession().countFor(username));
}
public static void listUsersSessions() {
try {
System.out.print("Korisnik : ");
String username = scanner.nextLine();
System.out.print("Velicina stranice : ");
int pageSize = Integer.parseInt(scanner.nextLine());
System.out.print("Broj stranice : ");
int pageNo = Integer.parseInt(scanner.nextLine());
System.out.println("Startni filter : ");
String startFilter = scanner.nextLine();
List<Session> sessions = sessionController.getMemoryForSession().getFor(username, pageNo, pageSize, startFilter);
for(Session s: sessions)
System.out.println(s.getSessionId()+"\t"+s.getUserId());
}catch(Exception ex) {
System.out.println("Greska pri listanju sesija.");
}
}
}
| [
"[email protected]"
] | |
b9daf0e2311acc3ac0acc8fec9148271f51df1c7 | f2372a145608f87cf783a4b3f115a5843c7300ed | /src/MineSweeperMain.java | 33ceaca9bae3d8fd2ab9562500dd4d9a3a176520 | [] | no_license | BarWeiner1/MineSweeper-Project | c1cef89e241a7aa271d88563c509d4f23899150e | 1fbd7baa19e0c568cb89c5178eb277076818a470 | refs/heads/master | 2020-09-22T06:39:09.677552 | 2020-03-27T02:06:45 | 2020-03-27T02:06:45 | 225,090,930 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 858 | java |
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class MineSweeperMain {
public static final JFrame window = new JFrame("MineSweeperGame");
public static void main(String[] args) {
MineSweeperModel gridPanel = new MineSweeperModel();
MineSweeperView painter = new MineSweeperView(gridPanel);
window.setContentPane(painter.getPanel());
Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
window.setSize(600, 400);
window.setLocation( (screensize.width - window.getWidth())/2,
(screensize.height - window.getHeight())/2 -150);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false);
window.setVisible(true);
}
public static void setFrame(int width, int length) {
window.setSize(width, length + 50 + 23);
}
}
| [
"[email protected]"
] | |
2e0c8d5b7da87102e55e5bdf8221a2f078143eb9 | e6b0b6351f984a863249e689d007096e0ad77562 | /study-action-basis/src/main/java/com/study/basis/designpattern/mediator/ch1/Mediator.java | 6d87ed06967d73160c1caa680fb2bf87e4a04ee2 | [] | no_license | valiantzh/study-javademo | c5f7e4bd6fe1c932474b6463dc426e9730b921d6 | 01b4f26beb900948e1203bca308e7a02205d2f9c | refs/heads/master | 2022-11-26T21:51:04.667879 | 2020-01-17T02:40:28 | 2020-01-17T02:40:28 | 152,394,665 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 190 | java | package com.study.basis.designpattern.mediator.ch1;
/**
* @author valiantzh
* @version 1.0
*/
public interface Mediator {
public void createMediator();
public void workAll();
}
| [
"[email protected]"
] | |
260a3dd0d4434acd3ce9e5a1d7bff3b5ba308d36 | c94e29dffa25d3193425c5dce39865ccdffbf717 | /src/java/net/sf/jhunlang/jmorph/util/Comparables.java | aa8c0301c4833ad48412d6121eef4e8ed077706a | [
"CC-BY-4.0",
"CC-BY-2.0"
] | permissive | Zolta/j-morph | aeed832cbb2501db6e22b3fcf4c172c617fc349e | d6d4d0299103a5e19b1464db4b6cd9bfc03e9545 | refs/heads/master | 2021-01-13T02:37:10.227151 | 2009-10-24T17:12:17 | 2009-10-24T17:12:17 | 33,602,699 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,664 | java | package net.sf.jhunlang.jmorph.util;
/**
*
*/
public class Comparables implements Comparable
{
static long id;
protected Comparable a;
protected Comparable b;
protected int hashCode;
protected boolean identified;
protected long lid;
static synchronized long next()
{
return id++;
}
/**
* <code>identified</code> tells if <code>a</code> and <code>b</code>
* together identify this Comparables. Identified Comparables can be used
* to differentiate otherwise equal Comparables instances by ordering them
* by their creation order.
*/
public Comparables(Comparable a, Comparable b, boolean identified)
{
this.a = a;
this.b = b;
this.identified = identified;
hashCode = a.hashCode() * 31 + b.hashCode();
lid = next();
}
public Comparables(Comparable a, long b, boolean identified)
{
this(a, new Long(b), identified);
}
public Comparables(Comparable a, int b, boolean identified)
{
this(a, new Integer(b), identified);
}
public Comparables(long a, long b, boolean identified)
{
this(new Long(a), new Long(b), identified);
}
public Comparables(long a, int b, boolean identified)
{
this(new Long(a), new Integer(b), identified);
}
public Comparable getA()
{
return a;
}
public Comparable getB()
{
return b;
}
/**
* Compare this object with <code>o</o>.
* Throws ClassCastException if o is not a Comparables.
* @param o the other object
* @return the relation of this object and <code>o</code>
*/
public int compareTo(Object o)
{
Comparables oc = (Comparables)o;
int rel = a.compareTo(oc.getA());
if (rel != 0)
{
return rel;
}
rel = b.compareTo(oc.getB());
if (!identified || rel != 0)
{
return rel;
}
// if identified and they are equal then return
// the relation of order of their creation
return lid < oc.lid ? -1 : (lid > oc.lid ? 1 : 0);
}
public int hashCode()
{
return hashCode;
}
public boolean equals(Object o)
{
return
o != null &&
(o instanceof Comparables) &&
hashCode == ((Comparables)o).hashCode &&
compareTo(o) == 0;
}
// utility method for short class name
public String shortClassname()
{
return shorten(getClass().getName());
}
// utility method for short class name
public static String shorten(String s)
{
return s.substring(s.lastIndexOf('.') + 1);
}
public String toString()
{
return a + "\t" + b;
}
}
| [
"bpgergo@4e5a4500-b9a0-11de-a079-5d186ce21964"
] | bpgergo@4e5a4500-b9a0-11de-a079-5d186ce21964 |
c9e5e56c94a90f8f1b8bf79df30ded09a44738d6 | 024d30af7880028470ceb38969079797a434624b | /ssm/src/Bean/Usermessagevo.java | 8c10ba70f4a5a03773a7fb1fe71b3a25e80750bb | [] | no_license | sjdsqw/ssm | 81e3ebcd11f74c3f1cb416bb4db71682356eead4 | af1a876517c12a176cb17bf692251ec323916632 | refs/heads/master | 2020-05-18T04:42:19.577351 | 2019-04-30T03:56:56 | 2019-04-30T03:56:56 | 184,181,825 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 67 | java | package Bean;
public class Usermessagevo extends Usermessage {
}
| [
"[email protected]"
] | |
7d12c08bd06baf62d838c14ad9a8e7afb7c1870c | 8af1164bac943cef64e41bae312223c3c0e38114 | /results-java/elastic--elasticsearch/f6aeb35ce8244f4e60cb827cccb42a359f3a2862/after/StoreTests.java | 7e946af3931909210d71e31eb725b8a97ef3ce78 | [] | no_license | fracz/refactor-extractor | 3ae45c97cc63f26d5cb8b92003b12f74cc9973a9 | dd5e82bfcc376e74a99e18c2bf54c95676914272 | refs/heads/master | 2021-01-19T06:50:08.211003 | 2018-11-30T13:00:57 | 2018-11-30T13:00:57 | 87,353,478 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 52,925 | java | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.store;
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.codecs.CodecUtil;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.SortedDocValuesField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.IndexFormatTooNewException;
import org.apache.lucene.index.IndexFormatTooOldException;
import org.apache.lucene.index.IndexNotFoundException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.KeepOnlyLastCommitDeletionPolicy;
import org.apache.lucene.index.NoDeletionPolicy;
import org.apache.lucene.index.NoMergePolicy;
import org.apache.lucene.index.SegmentInfos;
import org.apache.lucene.index.SnapshotDeletionPolicy;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.AlreadyClosedException;
import org.apache.lucene.store.BaseDirectoryWrapper;
import org.apache.lucene.store.ChecksumIndexInput;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.IOContext;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.store.MockDirectoryWrapper;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.TestUtil;
import org.apache.lucene.util.Version;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.UUIDs;
import org.elasticsearch.common.io.stream.InputStreamStreamInput;
import org.elasticsearch.common.io.stream.OutputStreamStreamOutput;
import org.elasticsearch.common.lucene.Lucene;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.env.ShardLock;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.engine.Engine;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.translog.Translog;
import org.elasticsearch.indices.store.TransportNodesListShardStoreMetaData;
import org.elasticsearch.test.DummyShardLock;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.IndexSettingsModule;
import org.hamcrest.Matchers;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import static java.util.Collections.unmodifiableMap;
import static org.elasticsearch.test.VersionUtils.randomVersion;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
public class StoreTests extends ESTestCase {
private static final IndexSettings INDEX_SETTINGS = IndexSettingsModule.newIndexSettings("index", Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, org.elasticsearch.Version.CURRENT).build());
public void testRefCount() throws IOException {
final ShardId shardId = new ShardId("index", "_na_", 1);
DirectoryService directoryService = new LuceneManagedDirectoryService(random());
IndexSettings indexSettings = INDEX_SETTINGS;
Store store = new Store(shardId, indexSettings, directoryService, new DummyShardLock(shardId));
int incs = randomIntBetween(1, 100);
for (int i = 0; i < incs; i++) {
if (randomBoolean()) {
store.incRef();
} else {
assertTrue(store.tryIncRef());
}
store.ensureOpen();
}
for (int i = 0; i < incs; i++) {
store.decRef();
store.ensureOpen();
}
store.incRef();
store.close();
for (int i = 0; i < incs; i++) {
if (randomBoolean()) {
store.incRef();
} else {
assertTrue(store.tryIncRef());
}
store.ensureOpen();
}
for (int i = 0; i < incs; i++) {
store.decRef();
store.ensureOpen();
}
store.decRef();
assertThat(store.refCount(), Matchers.equalTo(0));
assertFalse(store.tryIncRef());
try {
store.incRef();
fail(" expected exception");
} catch (AlreadyClosedException ex) {
}
try {
store.ensureOpen();
fail(" expected exception");
} catch (AlreadyClosedException ex) {
}
}
public void testVerifyingIndexOutput() throws IOException {
Directory dir = newDirectory();
IndexOutput output = dir.createOutput("foo.bar", IOContext.DEFAULT);
int iters = scaledRandomIntBetween(10, 100);
for (int i = 0; i < iters; i++) {
BytesRef bytesRef = new BytesRef(TestUtil.randomRealisticUnicodeString(random(), 10, 1024));
output.writeBytes(bytesRef.bytes, bytesRef.offset, bytesRef.length);
}
CodecUtil.writeFooter(output);
output.close();
IndexInput indexInput = dir.openInput("foo.bar", IOContext.DEFAULT);
String checksum = Store.digestToString(CodecUtil.retrieveChecksum(indexInput));
indexInput.seek(0);
BytesRef ref = new BytesRef(scaledRandomIntBetween(1, 1024));
long length = indexInput.length();
IndexOutput verifyingOutput = new Store.LuceneVerifyingIndexOutput(new StoreFileMetaData("foo1.bar", length, checksum), dir.createOutput("foo1.bar", IOContext.DEFAULT));
while (length > 0) {
if (random().nextInt(10) == 0) {
verifyingOutput.writeByte(indexInput.readByte());
length--;
} else {
int min = (int) Math.min(length, ref.bytes.length);
indexInput.readBytes(ref.bytes, ref.offset, min);
verifyingOutput.writeBytes(ref.bytes, ref.offset, min);
length -= min;
}
}
Store.verify(verifyingOutput);
try {
appendRandomData(verifyingOutput);
fail("should be a corrupted index");
} catch (CorruptIndexException | IndexFormatTooOldException | IndexFormatTooNewException ex) {
// ok
}
try {
Store.verify(verifyingOutput);
fail("should be a corrupted index");
} catch (CorruptIndexException | IndexFormatTooOldException | IndexFormatTooNewException ex) {
// ok
}
IOUtils.close(indexInput, verifyingOutput, dir);
}
public void testVerifyingIndexOutputOnEmptyFile() throws IOException {
Directory dir = newDirectory();
IndexOutput verifyingOutput = new Store.LuceneVerifyingIndexOutput(new StoreFileMetaData("foo.bar", 0, Store.digestToString(0)),
dir.createOutput("foo1.bar", IOContext.DEFAULT));
try {
Store.verify(verifyingOutput);
fail("should be a corrupted index");
} catch (CorruptIndexException | IndexFormatTooOldException | IndexFormatTooNewException ex) {
// ok
}
IOUtils.close(verifyingOutput, dir);
}
public void testChecksumCorrupted() throws IOException {
Directory dir = newDirectory();
IndexOutput output = dir.createOutput("foo.bar", IOContext.DEFAULT);
int iters = scaledRandomIntBetween(10, 100);
for (int i = 0; i < iters; i++) {
BytesRef bytesRef = new BytesRef(TestUtil.randomRealisticUnicodeString(random(), 10, 1024));
output.writeBytes(bytesRef.bytes, bytesRef.offset, bytesRef.length);
}
output.writeInt(CodecUtil.FOOTER_MAGIC);
output.writeInt(0);
String checksum = Store.digestToString(output.getChecksum());
output.writeLong(output.getChecksum() + 1); // write a wrong checksum to the file
output.close();
IndexInput indexInput = dir.openInput("foo.bar", IOContext.DEFAULT);
indexInput.seek(0);
BytesRef ref = new BytesRef(scaledRandomIntBetween(1, 1024));
long length = indexInput.length();
IndexOutput verifyingOutput = new Store.LuceneVerifyingIndexOutput(new StoreFileMetaData("foo1.bar", length, checksum), dir.createOutput("foo1.bar", IOContext.DEFAULT));
length -= 8; // we write the checksum in the try / catch block below
while (length > 0) {
if (random().nextInt(10) == 0) {
verifyingOutput.writeByte(indexInput.readByte());
length--;
} else {
int min = (int) Math.min(length, ref.bytes.length);
indexInput.readBytes(ref.bytes, ref.offset, min);
verifyingOutput.writeBytes(ref.bytes, ref.offset, min);
length -= min;
}
}
try {
BytesRef checksumBytes = new BytesRef(8);
checksumBytes.length = 8;
indexInput.readBytes(checksumBytes.bytes, checksumBytes.offset, checksumBytes.length);
if (randomBoolean()) {
verifyingOutput.writeBytes(checksumBytes.bytes, checksumBytes.offset, checksumBytes.length);
} else {
for (int i = 0; i < checksumBytes.length; i++) {
verifyingOutput.writeByte(checksumBytes.bytes[i]);
}
}
fail("should be a corrupted index");
} catch (CorruptIndexException | IndexFormatTooOldException | IndexFormatTooNewException ex) {
// ok
}
IOUtils.close(indexInput, verifyingOutput, dir);
}
private void appendRandomData(IndexOutput output) throws IOException {
int numBytes = randomIntBetween(1, 1024);
final BytesRef ref = new BytesRef(scaledRandomIntBetween(1, numBytes));
ref.length = ref.bytes.length;
while (numBytes > 0) {
if (random().nextInt(10) == 0) {
output.writeByte(randomByte());
numBytes--;
} else {
for (int i = 0; i<ref.length; i++) {
ref.bytes[i] = randomByte();
}
final int min = Math.min(numBytes, ref.bytes.length);
output.writeBytes(ref.bytes, ref.offset, min);
numBytes -= min;
}
}
}
public void testVerifyingIndexOutputWithBogusInput() throws IOException {
Directory dir = newDirectory();
int length = scaledRandomIntBetween(10, 1024);
IndexOutput verifyingOutput = new Store.LuceneVerifyingIndexOutput(new StoreFileMetaData("foo1.bar", length, ""), dir.createOutput("foo1.bar", IOContext.DEFAULT));
try {
while (length > 0) {
verifyingOutput.writeByte((byte) random().nextInt());
length--;
}
fail("should be a corrupted index");
} catch (CorruptIndexException | IndexFormatTooOldException | IndexFormatTooNewException ex) {
// ok
}
IOUtils.close(verifyingOutput, dir);
}
public void testNewChecksums() throws IOException {
final ShardId shardId = new ShardId("index", "_na_", 1);
DirectoryService directoryService = new LuceneManagedDirectoryService(random());
Store store = new Store(shardId, INDEX_SETTINGS, directoryService, new DummyShardLock(shardId));
// set default codec - all segments need checksums
IndexWriter writer = new IndexWriter(store.directory(), newIndexWriterConfig(random(), new MockAnalyzer(random())).setCodec(TestUtil.getDefaultCodec()));
int docs = 1 + random().nextInt(100);
for (int i = 0; i < docs; i++) {
Document doc = new Document();
doc.add(new TextField("id", "" + i, random().nextBoolean() ? Field.Store.YES : Field.Store.NO));
doc.add(new TextField("body", TestUtil.randomRealisticUnicodeString(random()), random().nextBoolean() ? Field.Store.YES : Field.Store.NO));
doc.add(new SortedDocValuesField("dv", new BytesRef(TestUtil.randomRealisticUnicodeString(random()))));
writer.addDocument(doc);
}
if (random().nextBoolean()) {
for (int i = 0; i < docs; i++) {
if (random().nextBoolean()) {
Document doc = new Document();
doc.add(new TextField("id", "" + i, random().nextBoolean() ? Field.Store.YES : Field.Store.NO));
doc.add(new TextField("body", TestUtil.randomRealisticUnicodeString(random()), random().nextBoolean() ? Field.Store.YES : Field.Store.NO));
writer.updateDocument(new Term("id", "" + i), doc);
}
}
}
if (random().nextBoolean()) {
DirectoryReader.open(writer).close(); // flush
}
Store.MetadataSnapshot metadata;
// check before we committed
try {
store.getMetadata(null);
fail("no index present - expected exception");
} catch (IndexNotFoundException ex) {
// expected
}
writer.commit();
writer.close();
metadata = store.getMetadata(null);
assertThat(metadata.asMap().isEmpty(), is(false));
for (StoreFileMetaData meta : metadata) {
try (IndexInput input = store.directory().openInput(meta.name(), IOContext.DEFAULT)) {
String checksum = Store.digestToString(CodecUtil.retrieveChecksum(input));
assertThat("File: " + meta.name() + " has a different checksum", meta.checksum(), equalTo(checksum));
assertThat(meta.writtenBy(), equalTo(Version.LATEST));
if (meta.name().endsWith(".si") || meta.name().startsWith("segments_")) {
assertThat(meta.hash().length, greaterThan(0));
}
}
}
assertConsistent(store, metadata);
TestUtil.checkIndex(store.directory());
assertDeleteContent(store, directoryService);
IOUtils.close(store);
}
public void testRenameFile() throws IOException {
final ShardId shardId = new ShardId("index", "_na_", 1);
DirectoryService directoryService = new LuceneManagedDirectoryService(random(), false);
Store store = new Store(shardId, INDEX_SETTINGS, directoryService, new DummyShardLock(shardId));
{
IndexOutput output = store.directory().createOutput("foo.bar", IOContext.DEFAULT);
int iters = scaledRandomIntBetween(10, 100);
for (int i = 0; i < iters; i++) {
BytesRef bytesRef = new BytesRef(TestUtil.randomRealisticUnicodeString(random(), 10, 1024));
output.writeBytes(bytesRef.bytes, bytesRef.offset, bytesRef.length);
}
CodecUtil.writeFooter(output);
output.close();
}
store.renameFile("foo.bar", "bar.foo");
assertThat(numNonExtraFiles(store), is(1));
final long lastChecksum;
try (IndexInput input = store.directory().openInput("bar.foo", IOContext.DEFAULT)) {
lastChecksum = CodecUtil.checksumEntireFile(input);
}
try {
store.directory().openInput("foo.bar", IOContext.DEFAULT);
fail("file was renamed");
} catch (FileNotFoundException | NoSuchFileException ex) {
// expected
}
{
IndexOutput output = store.directory().createOutput("foo.bar", IOContext.DEFAULT);
int iters = scaledRandomIntBetween(10, 100);
for (int i = 0; i < iters; i++) {
BytesRef bytesRef = new BytesRef(TestUtil.randomRealisticUnicodeString(random(), 10, 1024));
output.writeBytes(bytesRef.bytes, bytesRef.offset, bytesRef.length);
}
CodecUtil.writeFooter(output);
output.close();
}
store.renameFile("foo.bar", "bar.foo");
assertThat(numNonExtraFiles(store), is(1));
assertDeleteContent(store, directoryService);
IOUtils.close(store);
}
public void testCheckIntegrity() throws IOException {
Directory dir = newDirectory();
long luceneFileLength = 0;
try (IndexOutput output = dir.createOutput("lucene_checksum.bin", IOContext.DEFAULT)) {
int iters = scaledRandomIntBetween(10, 100);
for (int i = 0; i < iters; i++) {
BytesRef bytesRef = new BytesRef(TestUtil.randomRealisticUnicodeString(random(), 10, 1024));
output.writeBytes(bytesRef.bytes, bytesRef.offset, bytesRef.length);
luceneFileLength += bytesRef.length;
}
CodecUtil.writeFooter(output);
luceneFileLength += CodecUtil.footerLength();
}
final long luceneChecksum;
try (IndexInput indexInput = dir.openInput("lucene_checksum.bin", IOContext.DEFAULT)) {
assertEquals(luceneFileLength, indexInput.length());
luceneChecksum = CodecUtil.retrieveChecksum(indexInput);
}
dir.close();
}
public void testVerifyingIndexInput() throws IOException {
Directory dir = newDirectory();
IndexOutput output = dir.createOutput("foo.bar", IOContext.DEFAULT);
int iters = scaledRandomIntBetween(10, 100);
for (int i = 0; i < iters; i++) {
BytesRef bytesRef = new BytesRef(TestUtil.randomRealisticUnicodeString(random(), 10, 1024));
output.writeBytes(bytesRef.bytes, bytesRef.offset, bytesRef.length);
}
CodecUtil.writeFooter(output);
output.close();
// Check file
IndexInput indexInput = dir.openInput("foo.bar", IOContext.DEFAULT);
long checksum = CodecUtil.retrieveChecksum(indexInput);
indexInput.seek(0);
IndexInput verifyingIndexInput = new Store.VerifyingIndexInput(dir.openInput("foo.bar", IOContext.DEFAULT));
readIndexInputFullyWithRandomSeeks(verifyingIndexInput);
Store.verify(verifyingIndexInput);
assertThat(checksum, equalTo(((ChecksumIndexInput) verifyingIndexInput).getChecksum()));
IOUtils.close(indexInput, verifyingIndexInput);
// Corrupt file and check again
corruptFile(dir, "foo.bar", "foo1.bar");
verifyingIndexInput = new Store.VerifyingIndexInput(dir.openInput("foo1.bar", IOContext.DEFAULT));
readIndexInputFullyWithRandomSeeks(verifyingIndexInput);
try {
Store.verify(verifyingIndexInput);
fail("should be a corrupted index");
} catch (CorruptIndexException | IndexFormatTooOldException | IndexFormatTooNewException ex) {
// ok
}
IOUtils.close(verifyingIndexInput);
IOUtils.close(dir);
}
private void readIndexInputFullyWithRandomSeeks(IndexInput indexInput) throws IOException {
BytesRef ref = new BytesRef(scaledRandomIntBetween(1, 1024));
long pos = 0;
while (pos < indexInput.length()) {
assertEquals(pos, indexInput.getFilePointer());
int op = random().nextInt(5);
if (op == 0) {
int shift = 100 - randomIntBetween(0, 200);
pos = Math.min(indexInput.length() - 1, Math.max(0, pos + shift));
indexInput.seek(pos);
} else if (op == 1) {
indexInput.readByte();
pos++;
} else {
int min = (int) Math.min(indexInput.length() - pos, ref.bytes.length);
indexInput.readBytes(ref.bytes, ref.offset, min);
pos += min;
}
}
}
private void corruptFile(Directory dir, String fileIn, String fileOut) throws IOException {
IndexInput input = dir.openInput(fileIn, IOContext.READONCE);
IndexOutput output = dir.createOutput(fileOut, IOContext.DEFAULT);
long len = input.length();
byte[] b = new byte[1024];
long broken = randomInt((int) len-1);
long pos = 0;
while (pos < len) {
int min = (int) Math.min(input.length() - pos, b.length);
input.readBytes(b, 0, min);
if (broken >= pos && broken < pos + min) {
// Flip one byte
int flipPos = (int) (broken - pos);
b[flipPos] = (byte) (b[flipPos] ^ 42);
}
output.writeBytes(b, min);
pos += min;
}
IOUtils.close(input, output);
}
public void assertDeleteContent(Store store, DirectoryService service) throws IOException {
deleteContent(store.directory());
assertThat(Arrays.toString(store.directory().listAll()), store.directory().listAll().length, equalTo(0));
assertThat(store.stats().sizeInBytes(), equalTo(0L));
assertThat(service.newDirectory().listAll().length, equalTo(0));
}
private static final class LuceneManagedDirectoryService extends DirectoryService {
private final Directory dir;
private final Random random;
public LuceneManagedDirectoryService(Random random) {
this(random, true);
}
public LuceneManagedDirectoryService(Random random, boolean preventDoubleWrite) {
super(new ShardId(INDEX_SETTINGS.getIndex(), 1), INDEX_SETTINGS);
dir = StoreTests.newDirectory(random);
if (dir instanceof MockDirectoryWrapper) {
((MockDirectoryWrapper) dir).setPreventDoubleWrite(preventDoubleWrite);
}
this.random = random;
}
@Override
public Directory newDirectory() throws IOException {
return dir;
}
@Override
public long throttleTimeInNanos() {
return random.nextInt(1000);
}
}
public static void assertConsistent(Store store, Store.MetadataSnapshot metadata) throws IOException {
for (String file : store.directory().listAll()) {
if (!IndexWriter.WRITE_LOCK_NAME.equals(file) && !IndexFileNames.OLD_SEGMENTS_GEN.equals(file) && file.startsWith("extra") == false) {
assertTrue(file + " is not in the map: " + metadata.asMap().size() + " vs. " + store.directory().listAll().length, metadata.asMap().containsKey(file));
} else {
assertFalse(file + " is not in the map: " + metadata.asMap().size() + " vs. " + store.directory().listAll().length, metadata.asMap().containsKey(file));
}
}
}
public void testRecoveryDiff() throws IOException, InterruptedException {
int numDocs = 2 + random().nextInt(100);
List<Document> docs = new ArrayList<>();
for (int i = 0; i < numDocs; i++) {
Document doc = new Document();
doc.add(new StringField("id", "" + i, random().nextBoolean() ? Field.Store.YES : Field.Store.NO));
doc.add(new TextField("body", TestUtil.randomRealisticUnicodeString(random()), random().nextBoolean() ? Field.Store.YES : Field.Store.NO));
doc.add(new SortedDocValuesField("dv", new BytesRef(TestUtil.randomRealisticUnicodeString(random()))));
docs.add(doc);
}
long seed = random().nextLong();
Store.MetadataSnapshot first;
{
Random random = new Random(seed);
IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random)).setCodec(TestUtil.getDefaultCodec());
iwc.setMergePolicy(NoMergePolicy.INSTANCE);
iwc.setUseCompoundFile(random.nextBoolean());
final ShardId shardId = new ShardId("index", "_na_", 1);
DirectoryService directoryService = new LuceneManagedDirectoryService(random);
Store store = new Store(shardId, INDEX_SETTINGS, directoryService, new DummyShardLock(shardId));
IndexWriter writer = new IndexWriter(store.directory(), iwc);
final boolean lotsOfSegments = rarely(random);
for (Document d : docs) {
writer.addDocument(d);
if (lotsOfSegments && random.nextBoolean()) {
writer.commit();
} else if (rarely(random)) {
writer.commit();
}
}
writer.commit();
writer.close();
first = store.getMetadata(null);
assertDeleteContent(store, directoryService);
store.close();
}
long time = new Date().getTime();
while (time == new Date().getTime()) {
Thread.sleep(10); // bump the time
}
Store.MetadataSnapshot second;
Store store;
{
Random random = new Random(seed);
IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random)).setCodec(TestUtil.getDefaultCodec());
iwc.setMergePolicy(NoMergePolicy.INSTANCE);
iwc.setUseCompoundFile(random.nextBoolean());
final ShardId shardId = new ShardId("index", "_na_", 1);
DirectoryService directoryService = new LuceneManagedDirectoryService(random);
store = new Store(shardId, INDEX_SETTINGS, directoryService, new DummyShardLock(shardId));
IndexWriter writer = new IndexWriter(store.directory(), iwc);
final boolean lotsOfSegments = rarely(random);
for (Document d : docs) {
writer.addDocument(d);
if (lotsOfSegments && random.nextBoolean()) {
writer.commit();
} else if (rarely(random)) {
writer.commit();
}
}
writer.commit();
writer.close();
second = store.getMetadata(null);
}
Store.RecoveryDiff diff = first.recoveryDiff(second);
assertThat(first.size(), equalTo(second.size()));
for (StoreFileMetaData md : first) {
assertThat(second.get(md.name()), notNullValue());
// si files are different - containing timestamps etc
assertThat(second.get(md.name()).isSame(md), equalTo(false));
}
assertThat(diff.different.size(), equalTo(first.size()));
assertThat(diff.identical.size(), equalTo(0)); // in lucene 5 nothing is identical - we use random ids in file headers
assertThat(diff.missing, empty());
// check the self diff
Store.RecoveryDiff selfDiff = first.recoveryDiff(first);
assertThat(selfDiff.identical.size(), equalTo(first.size()));
assertThat(selfDiff.different, empty());
assertThat(selfDiff.missing, empty());
// lets add some deletes
Random random = new Random(seed);
IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random)).setCodec(TestUtil.getDefaultCodec());
iwc.setMergePolicy(NoMergePolicy.INSTANCE);
iwc.setUseCompoundFile(random.nextBoolean());
iwc.setOpenMode(IndexWriterConfig.OpenMode.APPEND);
IndexWriter writer = new IndexWriter(store.directory(), iwc);
writer.deleteDocuments(new Term("id", Integer.toString(random().nextInt(numDocs))));
writer.commit();
writer.close();
Store.MetadataSnapshot metadata = store.getMetadata(null);
StoreFileMetaData delFile = null;
for (StoreFileMetaData md : metadata) {
if (md.name().endsWith(".liv")) {
delFile = md;
break;
}
}
Store.RecoveryDiff afterDeleteDiff = metadata.recoveryDiff(second);
if (delFile != null) {
assertThat(afterDeleteDiff.identical.size(), equalTo(metadata.size() - 2)); // segments_N + del file
assertThat(afterDeleteDiff.different.size(), equalTo(0));
assertThat(afterDeleteDiff.missing.size(), equalTo(2));
} else {
// an entire segment must be missing (single doc segment got dropped)
assertThat(afterDeleteDiff.identical.size(), greaterThan(0));
assertThat(afterDeleteDiff.different.size(), equalTo(0));
assertThat(afterDeleteDiff.missing.size(), equalTo(1)); // the commit file is different
}
// check the self diff
selfDiff = metadata.recoveryDiff(metadata);
assertThat(selfDiff.identical.size(), equalTo(metadata.size()));
assertThat(selfDiff.different, empty());
assertThat(selfDiff.missing, empty());
// add a new commit
iwc = new IndexWriterConfig(new MockAnalyzer(random)).setCodec(TestUtil.getDefaultCodec());
iwc.setMergePolicy(NoMergePolicy.INSTANCE);
iwc.setUseCompoundFile(true); // force CFS - easier to test here since we know it will add 3 files
iwc.setOpenMode(IndexWriterConfig.OpenMode.APPEND);
writer = new IndexWriter(store.directory(), iwc);
writer.addDocument(docs.get(0));
writer.close();
Store.MetadataSnapshot newCommitMetaData = store.getMetadata(null);
Store.RecoveryDiff newCommitDiff = newCommitMetaData.recoveryDiff(metadata);
if (delFile != null) {
assertThat(newCommitDiff.identical.size(), equalTo(newCommitMetaData.size() - 5)); // segments_N, del file, cfs, cfe, si for the new segment
assertThat(newCommitDiff.different.size(), equalTo(1)); // the del file must be different
assertThat(newCommitDiff.different.get(0).name(), endsWith(".liv"));
assertThat(newCommitDiff.missing.size(), equalTo(4)); // segments_N,cfs, cfe, si for the new segment
} else {
assertThat(newCommitDiff.identical.size(), equalTo(newCommitMetaData.size() - 4)); // segments_N, cfs, cfe, si for the new segment
assertThat(newCommitDiff.different.size(), equalTo(0));
assertThat(newCommitDiff.missing.size(), equalTo(4)); // an entire segment must be missing (single doc segment got dropped) plus the commit is different
}
deleteContent(store.directory());
IOUtils.close(store);
}
public void testCleanupFromSnapshot() throws IOException {
final ShardId shardId = new ShardId("index", "_na_", 1);
DirectoryService directoryService = new LuceneManagedDirectoryService(random());
Store store = new Store(shardId, INDEX_SETTINGS, directoryService, new DummyShardLock(shardId));
// this time random codec....
IndexWriterConfig indexWriterConfig = newIndexWriterConfig(random(), new MockAnalyzer(random())).setCodec(TestUtil.getDefaultCodec());
// we keep all commits and that allows us clean based on multiple snapshots
indexWriterConfig.setIndexDeletionPolicy(NoDeletionPolicy.INSTANCE);
IndexWriter writer = new IndexWriter(store.directory(), indexWriterConfig);
int docs = 1 + random().nextInt(100);
int numCommits = 0;
for (int i = 0; i < docs; i++) {
if (i > 0 && randomIntBetween(0, 10) == 0) {
writer.commit();
numCommits++;
}
Document doc = new Document();
doc.add(new TextField("id", "" + i, random().nextBoolean() ? Field.Store.YES : Field.Store.NO));
doc.add(new TextField("body", TestUtil.randomRealisticUnicodeString(random()), random().nextBoolean() ? Field.Store.YES : Field.Store.NO));
doc.add(new SortedDocValuesField("dv", new BytesRef(TestUtil.randomRealisticUnicodeString(random()))));
writer.addDocument(doc);
}
if (numCommits < 1) {
writer.commit();
Document doc = new Document();
doc.add(new TextField("id", "" + docs++, random().nextBoolean() ? Field.Store.YES : Field.Store.NO));
doc.add(new TextField("body", TestUtil.randomRealisticUnicodeString(random()), random().nextBoolean() ? Field.Store.YES : Field.Store.NO));
doc.add(new SortedDocValuesField("dv", new BytesRef(TestUtil.randomRealisticUnicodeString(random()))));
writer.addDocument(doc);
}
Store.MetadataSnapshot firstMeta = store.getMetadata(null);
if (random().nextBoolean()) {
for (int i = 0; i < docs; i++) {
if (random().nextBoolean()) {
Document doc = new Document();
doc.add(new TextField("id", "" + i, random().nextBoolean() ? Field.Store.YES : Field.Store.NO));
doc.add(new TextField("body", TestUtil.randomRealisticUnicodeString(random()), random().nextBoolean() ? Field.Store.YES : Field.Store.NO));
writer.updateDocument(new Term("id", "" + i), doc);
}
}
}
writer.commit();
writer.close();
Store.MetadataSnapshot secondMeta = store.getMetadata(null);
if (randomBoolean()) {
store.cleanupAndVerify("test", firstMeta);
String[] strings = store.directory().listAll();
int numChecksums = 0;
int numNotFound = 0;
for (String file : strings) {
if (file.startsWith("extra")) {
continue;
}
assertTrue(firstMeta.contains(file) || file.equals("write.lock"));
if (secondMeta.contains(file) == false) {
numNotFound++;
}
}
assertTrue("at least one file must not be in here since we have two commits?", numNotFound > 0);
} else {
store.cleanupAndVerify("test", secondMeta);
String[] strings = store.directory().listAll();
int numChecksums = 0;
int numNotFound = 0;
for (String file : strings) {
if (file.startsWith("extra")) {
continue;
}
assertTrue(file, secondMeta.contains(file) || file.equals("write.lock"));
if (firstMeta.contains(file) == false) {
numNotFound++;
}
}
assertTrue("at least one file must not be in here since we have two commits?", numNotFound > 0);
}
deleteContent(store.directory());
IOUtils.close(store);
}
public void testOnCloseCallback() throws IOException {
final ShardId shardId = new ShardId(new Index(randomRealisticUnicodeOfCodepointLengthBetween(1, 10), "_na_"), randomIntBetween(0, 100));
DirectoryService directoryService = new LuceneManagedDirectoryService(random());
final AtomicInteger count = new AtomicInteger(0);
final ShardLock lock = new DummyShardLock(shardId);
Store store = new Store(shardId, INDEX_SETTINGS, directoryService, lock, theLock -> {
assertEquals(shardId, theLock.getShardId());
assertEquals(lock, theLock);
count.incrementAndGet();
});
assertEquals(count.get(), 0);
final int iters = randomIntBetween(1, 10);
for (int i = 0; i < iters; i++) {
store.close();
}
assertEquals(count.get(), 1);
}
public void testStoreStats() throws IOException {
final ShardId shardId = new ShardId("index", "_na_", 1);
DirectoryService directoryService = new LuceneManagedDirectoryService(random());
Settings settings = Settings.builder()
.put(IndexMetaData.SETTING_VERSION_CREATED, org.elasticsearch.Version.CURRENT)
.put(Store.INDEX_STORE_STATS_REFRESH_INTERVAL_SETTING.getKey(), TimeValue.timeValueMinutes(0)).build();
Store store = new Store(shardId, IndexSettingsModule.newIndexSettings("index", settings), directoryService, new DummyShardLock(shardId));
long initialStoreSize = 0;
for (String extraFiles : store.directory().listAll()) {
assertTrue("expected extraFS file but got: " + extraFiles, extraFiles.startsWith("extra"));
initialStoreSize += store.directory().fileLength(extraFiles);
}
StoreStats stats = store.stats();
assertEquals(stats.getSize().bytes(), initialStoreSize);
Directory dir = store.directory();
final long length;
try (IndexOutput output = dir.createOutput("foo.bar", IOContext.DEFAULT)) {
int iters = scaledRandomIntBetween(10, 100);
for (int i = 0; i < iters; i++) {
BytesRef bytesRef = new BytesRef(TestUtil.randomRealisticUnicodeString(random(), 10, 1024));
output.writeBytes(bytesRef.bytes, bytesRef.offset, bytesRef.length);
}
length = output.getFilePointer();
}
assertTrue(numNonExtraFiles(store) > 0);
stats = store.stats();
assertEquals(stats.getSizeInBytes(), length + initialStoreSize);
deleteContent(store.directory());
IOUtils.close(store);
}
public static void deleteContent(Directory directory) throws IOException {
final String[] files = directory.listAll();
final List<IOException> exceptions = new ArrayList<>();
for (String file : files) {
try {
directory.deleteFile(file);
} catch (NoSuchFileException | FileNotFoundException e) {
// ignore
} catch (IOException e) {
exceptions.add(e);
}
}
ExceptionsHelper.rethrowAndSuppress(exceptions);
}
public int numNonExtraFiles(Store store) throws IOException {
int numNonExtra = 0;
for (String file : store.directory().listAll()) {
if (file.startsWith("extra") == false) {
numNonExtra++;
}
}
return numNonExtra;
}
public void testMetadataSnapshotStreaming() throws Exception {
Store.MetadataSnapshot outMetadataSnapshot = createMetaDataSnapshot();
org.elasticsearch.Version targetNodeVersion = randomVersion(random());
ByteArrayOutputStream outBuffer = new ByteArrayOutputStream();
OutputStreamStreamOutput out = new OutputStreamStreamOutput(outBuffer);
out.setVersion(targetNodeVersion);
outMetadataSnapshot.writeTo(out);
ByteArrayInputStream inBuffer = new ByteArrayInputStream(outBuffer.toByteArray());
InputStreamStreamInput in = new InputStreamStreamInput(inBuffer);
in.setVersion(targetNodeVersion);
Store.MetadataSnapshot inMetadataSnapshot = new Store.MetadataSnapshot(in);
Map<String, StoreFileMetaData> origEntries = new HashMap<>();
origEntries.putAll(outMetadataSnapshot.asMap());
for (Map.Entry<String, StoreFileMetaData> entry : inMetadataSnapshot.asMap().entrySet()) {
assertThat(entry.getValue().name(), equalTo(origEntries.remove(entry.getKey()).name()));
}
assertThat(origEntries.size(), equalTo(0));
assertThat(inMetadataSnapshot.getCommitUserData(), equalTo(outMetadataSnapshot.getCommitUserData()));
}
protected Store.MetadataSnapshot createMetaDataSnapshot() {
StoreFileMetaData storeFileMetaData1 = new StoreFileMetaData("segments", 1, "666");
StoreFileMetaData storeFileMetaData2 = new StoreFileMetaData("no_segments", 1, "666");
Map<String, StoreFileMetaData> storeFileMetaDataMap = new HashMap<>();
storeFileMetaDataMap.put(storeFileMetaData1.name(), storeFileMetaData1);
storeFileMetaDataMap.put(storeFileMetaData2.name(), storeFileMetaData2);
Map<String, String> commitUserData = new HashMap<>();
commitUserData.put("userdata_1", "test");
commitUserData.put("userdata_2", "test");
return new Store.MetadataSnapshot(unmodifiableMap(storeFileMetaDataMap), unmodifiableMap(commitUserData), 0);
}
public void testUserDataRead() throws IOException {
final ShardId shardId = new ShardId("index", "_na_", 1);
DirectoryService directoryService = new LuceneManagedDirectoryService(random());
Store store = new Store(shardId, INDEX_SETTINGS, directoryService, new DummyShardLock(shardId));
IndexWriterConfig config = newIndexWriterConfig(random(), new MockAnalyzer(random())).setCodec(TestUtil.getDefaultCodec());
SnapshotDeletionPolicy deletionPolicy = new SnapshotDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy());
config.setIndexDeletionPolicy(deletionPolicy);
IndexWriter writer = new IndexWriter(store.directory(), config);
Document doc = new Document();
doc.add(new TextField("id", "1", Field.Store.NO));
writer.addDocument(doc);
Map<String, String> commitData = new HashMap<>(2);
String syncId = "a sync id";
String translogId = "a translog id";
commitData.put(Engine.SYNC_COMMIT_ID, syncId);
commitData.put(Translog.TRANSLOG_GENERATION_KEY, translogId);
writer.setCommitData(commitData);
writer.commit();
writer.close();
Store.MetadataSnapshot metadata;
metadata = store.getMetadata(randomBoolean() ? null : deletionPolicy.snapshot());
assertFalse(metadata.asMap().isEmpty());
// do not check for correct files, we have enough tests for that above
assertThat(metadata.getCommitUserData().get(Engine.SYNC_COMMIT_ID), equalTo(syncId));
assertThat(metadata.getCommitUserData().get(Translog.TRANSLOG_GENERATION_KEY), equalTo(translogId));
TestUtil.checkIndex(store.directory());
assertDeleteContent(store, directoryService);
IOUtils.close(store);
}
public void testStreamStoreFilesMetaData() throws Exception {
Store.MetadataSnapshot metadataSnapshot = createMetaDataSnapshot();
TransportNodesListShardStoreMetaData.StoreFilesMetaData outStoreFileMetaData = new TransportNodesListShardStoreMetaData.StoreFilesMetaData(new ShardId("test", "_na_", 0),metadataSnapshot);
ByteArrayOutputStream outBuffer = new ByteArrayOutputStream();
OutputStreamStreamOutput out = new OutputStreamStreamOutput(outBuffer);
org.elasticsearch.Version targetNodeVersion = randomVersion(random());
out.setVersion(targetNodeVersion);
outStoreFileMetaData.writeTo(out);
ByteArrayInputStream inBuffer = new ByteArrayInputStream(outBuffer.toByteArray());
InputStreamStreamInput in = new InputStreamStreamInput(inBuffer);
in.setVersion(targetNodeVersion);
TransportNodesListShardStoreMetaData.StoreFilesMetaData inStoreFileMetaData = TransportNodesListShardStoreMetaData.StoreFilesMetaData.readStoreFilesMetaData(in);
Iterator<StoreFileMetaData> outFiles = outStoreFileMetaData.iterator();
for (StoreFileMetaData inFile : inStoreFileMetaData) {
assertThat(inFile.name(), equalTo(outFiles.next().name()));
}
assertThat(outStoreFileMetaData.syncId(), equalTo(inStoreFileMetaData.syncId()));
}
public void testMarkCorruptedOnTruncatedSegmentsFile() throws IOException {
IndexWriterConfig iwc = newIndexWriterConfig();
final ShardId shardId = new ShardId("index", "_na_", 1);
DirectoryService directoryService = new LuceneManagedDirectoryService(random());
Store store = new Store(shardId, INDEX_SETTINGS, directoryService, new DummyShardLock(shardId));
IndexWriter writer = new IndexWriter(store.directory(), iwc);
int numDocs = 1 + random().nextInt(10);
List<Document> docs = new ArrayList<>();
for (int i = 0; i < numDocs; i++) {
Document doc = new Document();
doc.add(new StringField("id", "" + i, random().nextBoolean() ? Field.Store.YES : Field.Store.NO));
doc.add(new TextField("body", TestUtil.randomRealisticUnicodeString(random()), random().nextBoolean() ? Field.Store.YES : Field.Store.NO));
doc.add(new SortedDocValuesField("dv", new BytesRef(TestUtil.randomRealisticUnicodeString(random()))));
docs.add(doc);
}
for (Document d : docs) {
writer.addDocument(d);
}
writer.commit();
writer.close();
MockDirectoryWrapper leaf = DirectoryUtils.getLeaf(store.directory(), MockDirectoryWrapper.class);
if (leaf != null) {
leaf.setPreventDoubleWrite(false); // I do this on purpose
}
SegmentInfos segmentCommitInfos = store.readLastCommittedSegmentsInfo();
try (IndexOutput out = store.directory().createOutput(segmentCommitInfos.getSegmentsFileName(), IOContext.DEFAULT)) {
// empty file
}
try {
if (randomBoolean()) {
store.getMetadata(null);
} else {
store.readLastCommittedSegmentsInfo();
}
fail("corrupted segments_N file");
} catch (CorruptIndexException ex) {
// expected
}
assertTrue(store.isMarkedCorrupted());
Lucene.cleanLuceneIndex(store.directory()); // we have to remove the index since it's corrupted and might fail the MocKDirWrapper checkindex call
store.close();
}
public void testCanOpenIndex() throws IOException {
final ShardId shardId = new ShardId("index", "_na_", 1);
IndexWriterConfig iwc = newIndexWriterConfig();
Path tempDir = createTempDir();
final BaseDirectoryWrapper dir = newFSDirectory(tempDir);
assertFalse(Store.canOpenIndex(logger, tempDir, shardId, (id, l) -> new DummyShardLock(id)));
IndexWriter writer = new IndexWriter(dir, iwc);
Document doc = new Document();
doc.add(new StringField("id", "1", random().nextBoolean() ? Field.Store.YES : Field.Store.NO));
writer.addDocument(doc);
writer.commit();
writer.close();
assertTrue(Store.canOpenIndex(logger, tempDir, shardId, (id, l) -> new DummyShardLock(id)));
DirectoryService directoryService = new DirectoryService(shardId, INDEX_SETTINGS) {
@Override
public long throttleTimeInNanos() {
return 0;
}
@Override
public Directory newDirectory() throws IOException {
return dir;
}
};
Store store = new Store(shardId, INDEX_SETTINGS, directoryService, new DummyShardLock(shardId));
store.markStoreCorrupted(new CorruptIndexException("foo", "bar"));
assertFalse(Store.canOpenIndex(logger, tempDir, shardId, (id, l) -> new DummyShardLock(id)));
store.close();
}
public void testDeserializeCorruptionException() throws IOException {
final ShardId shardId = new ShardId("index", "_na_", 1);
final Directory dir = new RAMDirectory(); // I use ram dir to prevent that virusscanner being a PITA
DirectoryService directoryService = new DirectoryService(shardId, INDEX_SETTINGS) {
@Override
public long throttleTimeInNanos() {
return 0;
}
@Override
public Directory newDirectory() throws IOException {
return dir;
}
};
Store store = new Store(shardId, INDEX_SETTINGS, directoryService, new DummyShardLock(shardId));
CorruptIndexException ex = new CorruptIndexException("foo", "bar");
store.markStoreCorrupted(ex);
try {
store.failIfCorrupted();
fail("should be corrupted");
} catch (CorruptIndexException e) {
assertEquals(ex.getMessage(), e.getMessage());
assertEquals(ex.toString(), e.toString());
assertArrayEquals(ex.getStackTrace(), e.getStackTrace());
}
store.removeCorruptionMarker();
assertFalse(store.isMarkedCorrupted());
FileNotFoundException ioe = new FileNotFoundException("foobar");
store.markStoreCorrupted(ioe);
try {
store.failIfCorrupted();
fail("should be corrupted");
} catch (CorruptIndexException e) {
assertEquals("foobar (resource=preexisting_corruption)", e.getMessage());
assertArrayEquals(ioe.getStackTrace(), e.getCause().getStackTrace());
}
store.close();
}
public void testCanReadOldCorruptionMarker() throws IOException {
final ShardId shardId = new ShardId("index", "_na_", 1);
final Directory dir = new RAMDirectory(); // I use ram dir to prevent that virusscanner being a PITA
DirectoryService directoryService = new DirectoryService(shardId, INDEX_SETTINGS) {
@Override
public long throttleTimeInNanos() {
return 0;
}
@Override
public Directory newDirectory() throws IOException {
return dir;
}
};
Store store = new Store(shardId, INDEX_SETTINGS, directoryService, new DummyShardLock(shardId));
CorruptIndexException exception = new CorruptIndexException("foo", "bar");
String uuid = Store.CORRUPTED + UUIDs.randomBase64UUID();
try (IndexOutput output = dir.createOutput(uuid, IOContext.DEFAULT)) {
CodecUtil.writeHeader(output, Store.CODEC, Store.VERSION_STACK_TRACE);
output.writeString(ExceptionsHelper.detailedMessage(exception));
output.writeString(ExceptionsHelper.stackTrace(exception));
CodecUtil.writeFooter(output);
}
try {
store.failIfCorrupted();
fail("should be corrupted");
} catch (CorruptIndexException e) {
assertTrue(e.getMessage().startsWith("[index][1] Preexisting corrupted index [" + uuid +"] caused by: CorruptIndexException[foo (resource=bar)]"));
assertTrue(e.getMessage().contains(ExceptionsHelper.stackTrace(exception)));
}
store.removeCorruptionMarker();
try (IndexOutput output = dir.createOutput(uuid, IOContext.DEFAULT)) {
CodecUtil.writeHeader(output, Store.CODEC, Store.VERSION_START);
output.writeString(ExceptionsHelper.detailedMessage(exception));
CodecUtil.writeFooter(output);
}
try {
store.failIfCorrupted();
fail("should be corrupted");
} catch (CorruptIndexException e) {
assertTrue(e.getMessage().startsWith("[index][1] Preexisting corrupted index [" + uuid + "] caused by: CorruptIndexException[foo (resource=bar)]"));
assertFalse(e.getMessage().contains(ExceptionsHelper.stackTrace(exception)));
}
store.removeCorruptionMarker();
try (IndexOutput output = dir.createOutput(uuid, IOContext.DEFAULT)) {
CodecUtil.writeHeader(output, Store.CODEC, Store.VERSION_START - 1); // corrupted header
CodecUtil.writeFooter(output);
}
try {
store.failIfCorrupted();
fail("should be too old");
} catch (IndexFormatTooOldException e) {
}
store.removeCorruptionMarker();
try (IndexOutput output = dir.createOutput(uuid, IOContext.DEFAULT)) {
CodecUtil.writeHeader(output, Store.CODEC, Store.VERSION+1); // corrupted header
CodecUtil.writeFooter(output);
}
try {
store.failIfCorrupted();
fail("should be too new");
} catch (IndexFormatTooNewException e) {
}
store.close();
}
} | [
"[email protected]"
] | |
13d0b1308fb2b9d8ea4f4a8e6cff05324f5cd1cd | bde39256410cc10a44d49cba0ac86b46bd62f8f3 | /src/main/java/com/vn/controller/web/RegisterController.java | 39126c5387920c7152c9e82e89aa421f1758c224 | [] | no_license | tytung63a/SpringRestAPI | a5ed69dd1f0b356ec614d2764840aba08dda2b42 | d74a6515e93ce5e8b6886d5527bb4916cfcdbf76 | refs/heads/main | 2023-08-30T02:15:33.825323 | 2021-10-26T04:04:06 | 2021-10-26T04:04:06 | 397,516,440 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,506 | java | package com.vn.controller.web;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import com.vn.entities.AppRole;
import com.vn.entities.AppUser;
import com.vn.entities.UserRole;
import com.vn.repository.AppRoleRepository;
import com.vn.repository.AppUserRepository;
import com.vn.repository.UserRoleRepository;
import com.vn.vo.AppUserVO;
@Controller
public class RegisterController {
@Autowired
private AppUserRepository appUserRepository;
@Autowired
private UserRoleRepository userRoleRepository;
@Autowired
private AppRoleRepository appRoleRepository;
@Autowired
private BCryptPasswordEncoder encoder;
@GetMapping("/register")
public String viewRegister(Model model) {
model.addAttribute("registerForm", new AppUserVO());
List<AppRole> list = appRoleRepository.findAll();
model.addAttribute("roles", list);
return "register";
}
@PostMapping("/register")
public String createRegister(Model model, @ModelAttribute("registerForm") AppUserVO vo) {
try {
AppUser appUser = new AppUser();
// register user
BeanUtils.copyProperties(vo, appUser);
String rawPassword = vo.getEncrytedPassword();
String crytPassword = encoder.encode(rawPassword);
appUser.setEncrytedPassword(crytPassword);
appUser = appUserRepository.save(appUser);
vo.setEncrytedPassword(appUser.getEncrytedPassword());
vo.setUserId(appUser.getUserId());
UserRole userRole = new UserRole();
userRole.setAppRole(appRoleRepository.findById(vo.getRole_id()).get());
userRole.setAppUser(appUserRepository.findById(vo.getUserId()).get());
userRoleRepository.save(userRole);
List<AppRole> list = appRoleRepository.findAll();
model.addAttribute("roles", list);
model.addAttribute("message",
"Đăng ký thành công, tk : " + appUser.getUserName() + "mật khẩu : " + appUser.getEncrytedPassword());
} catch (Exception e) {
List<AppRole> list = appRoleRepository.findAll();
model.addAttribute("roles", list);
model.addAttribute("message",
"Đăng ký thất bại, tk đã có trong database");
}
return "register";
}
}
| [
"[email protected]"
] | |
de7f8adc58938c7341890cb8257078cefe52602a | ac7e5d67a9ec07586ee18d0d76d8459ad098dc29 | /light/LiteQuadroo/src/QuadrooqlS.java | 755c988d6ea4d085b5ce83f6c2fac9ec34278c57 | [] | no_license | spicecoder/quadroo | 66f9d989587bb267dba47e59cc5ec13b49dacd06 | 09c205d9716ddef315690581c7de2d8109d6c5c9 | refs/heads/master | 2021-01-19T11:10:22.479875 | 2016-01-15T11:46:20 | 2016-01-15T11:46:20 | 32,121,206 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 36,819 | java | //package coreservlets;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.servlet.*;
import javax.servlet.http.*;
import org.json.JSONObject;
import java.sql.*;
import java.util.Iterator;
/*quadrroql servlet is able to invoke all methods depending on the URL */
public class QuadrooqlS extends HttpServlet {
public ConnectionPool connectionPool;
Statement statement = null;
Connection connection = null;
Quadroopl reqparms;
int rr = -9; String verb;
// all methods we use have no argument
Class params[] = {};
Object paramsObj[] = {};
// doget invokes methods matching the verb extracted from URI
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// a request parameter holder and the result reply holder
Quadroopl reqp = new Quadroopl();
Quadroorl repl = new Quadroorl();
try {
//extract verb and parameters:
//the last part of URI is the verb or the method name
String ruri = request.getRequestURI();
int ms = ruri.lastIndexOf("/");
if ((ms > 0) && (ms < ruri.length())) {
verb = ruri.substring(ms+1);}
System.out.println("encounterd"+ verb+ ":"+request.getParameter("UIdata"));
//next we extract parameters and hold that in the request scope
//the input parameter UIdata holds an json string
//http://localhost:8080/quadrooServer/quadrooql/extractNS?UIdata={W:a.b.c.aword}
JSONObject jObj = new JSONObject(request.getParameter("UIdata")); // this parses the json
Iterator it = jObj.keys();
//gets all the keys
while(it.hasNext())
{
String key = (String)it.next(); // get key
Object o = jObj.get(key); // get value
// session.putValue(key, o); // store in session
System.out.println("json"+ key + "val:" + o.toString());
if (key.equalsIgnoreCase("F"))
reqparms.F = o.toString();
if (key.equalsIgnoreCase("N"))
reqp.N = o.toString();
if (key.equalsIgnoreCase("S"))
reqp.W = o.toString();
if (key.equalsIgnoreCase("U"))
reqp.W = o.toString();
if (key.equalsIgnoreCase("uid"))
reqp.uid =Integer.parseInt(o.toString());
if (key.equalsIgnoreCase("W"))
reqp.W = o.toString();
if (key.equalsIgnoreCase("nW"))
reqp.nW = o.toString();
if (key.equalsIgnoreCase("m"))
reqp.m = o.toString();
}
//
System.out.println("Verb Is"+ verb+"invokedby:"+reqp.W);
//invoke the method
/* switch (verb) {
case "AWord":
repl = AWord(reqp); break;
case "clearTables":
repl.reply = clearTables(); break;
case "extractNS":
repl = extractNS(reqp); break;
case "ANSFromWord":
repl = ANSFromWord(reqp); break;
case "FNSpace":
repl = FNSpace(reqp); break;
case "ANspace":
repl = ANspace(reqp); break;
case "DNspace":
repl = DNspace(reqp); break;
case "CWord":
repl = CWord(reqp); break;
case "DWord":
repl = DWord(reqp); break;
case "FWord":
repl = FWord(reqp); break;
case "GWord":
repl = GWord(reqp); break;
case "AScene":
repl = AScene(reqp); break;
case "DScene":
repl = DScene(reqp); break;
case "FScene":
repl = FScene(reqp); break;
case "AFlow":
repl = AFlow(reqp); break;
case "DFlow":
repl.reply = DFlow(reqp); break;
case "AFlowScene":
repl = AFlowScene(reqp); break;
case "AFScene":
repl = AFScene(reqp); break;
case "DFScene":
repl = DFScene(reqp); break;
case "DFSid":
repl= DFSid(reqp); break;
case "ASceneWord":
repl = ASceneWord(reqp); break;
case "ASWord":
repl = ASWord(reqp); break;
case "DSWord":
repl = DSWord(reqp); break;
case "LSWords":
repl = LSWords(reqp); break;
case "LFScenes":
repl.reply = LFScenes(reqp); break;
case "initialConnections":
repl.rid = initialConnections();
case "maxConnections":
repl.rid = maxConnections();
}
*/
//having executed the sql with the request, we can release the connection so that
// other connections can use it.
// String rt = makeResponse(repl);
connectionPool.free(connection);
System.out.println("why error");
} catch(Exception e) {e.printStackTrace();System.out.println("error x :"+ e.getMessage());
}
String rt = makeResponse(repl);
System.out.println("progressing:"+reqp.W);
//Time to Set up the reply Text
response.setContentType("text/xml");
// Prevent the browser from caching the response. See
// Section 7.2 of Core Servlets and JSP for details.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0
response.setHeader("Cache-Control", "no-cache"); // HTTP 1.1
PrintWriter out = response.getWriter();
// String title = "Connection Pool Test";
// String rt = "<reply>" + repl.reply + "</reply> ";
System.out.println("put out:"+rt);
out.write(rt);
//return(rt);
}
public String makeResponse(Quadroorl rl) {
String rt =
"<Qreply>" +
"<replyint>"+rl.rid+
"</replyint>" +
"<reply>"+rl.reply+
"</reply>" +
"<rfid>"+rl.rfid+
"</rfid>" +
"<rf>"+rl.rf+
"</rf>"+
"<rs>"+rl.rs+
"</rs>"+
"<rsid>"+rl.rsid+
"</rsid>"+
"<rw>"+rl.rw+
"</rw>"+
"<rwid>"+ rl.rwid +
"</rwid>"+
"<rnw>"+ rl.rnw +
"</rnw>"+
"<rnwid>"+ rl.rnwid +
"</rnwid>"+
"</Qreply> ";
return rt ; }
public void init() {
//init is the place to set up url and connection details
String url = "jdbc:sqlite:/qudtes2t.db";
String driver = "org.sqlite.JDBC";
try
{
// create a database connection
// connection = DriverManager.getConnection(url);
connectionPool =
new ConnectionPool(driver,url,null,null,2,10,true);
// connection = connectionPool.getConnection();
} catch(SQLException sqle) {
System.err.println("Error making pool: " + sqle);
getServletContext().log("Error making pool: " + sqle);
connectionPool = null;
}
catch(Exception e) { System.out.println(e.getMessage()) ;
e.printStackTrace();
}
try {
connection = connectionPool.getConnection();
statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// reqparms = new Quadroopl();
//new ConnectionPool();;
//String url = "jdbc:sqlite:sample.db";
//quadrooql constructor defines four tables:
//users,words and quadroo,nspace
clearTables() ;
}
public void destroy() {
connectionPool.closeAllConnections();
}
/** Override this in subclass to change number of initial
* connections.
*/
protected int initialConnections() {
return(10);
}
/** Override this in subclass to change maximum number of
* connections.
*/
protected int maxConnections() {
return(50);
}
//here all the quadroo methods defined
//clear all tables and rebuild
public String clearTables() {
//users hold the user password, user is in the form of email
try
{
statement.executeUpdate("drop table if exists users");
statement.executeUpdate("create table users ( user string primary KEY, passwd string )");
System.out.println("users");
//uid is the rowid of the user, both tables words and quadroo have the creator in uid .
//rule is only creator can update or delete the word or any quadroo entry,administrator can always come in as any user
statement.executeUpdate("drop table if exists nspace");
statement.executeUpdate("create table nspace (nid INTEGER PRIMARY KEY AUTOINCREMENT ,uid integer ,name string Unique )");
System.out.println("nspace");
statement.executeUpdate("drop table if exists words");
statement.executeUpdate("create table words (wid INTEGER PRIMARY KEY AUTOINCREMENT ,uid integer,name string Unique, m varchar(1) )");
statement.executeUpdate("drop table if exists quadroo");
//quadroo is the measure we are storing in the data base;only word by itself measure is just the description of the word,significance of its name;
//word in scene has the measure as the value of the word; in that sense word can not have value without being in a scene.
//flow is the story about how the value changes through scenes.
//only flow and only scene may have measure where they have description about the scene and the flow resp.
statement.executeUpdate("create table quadroo (qid INTEGER PRIMARY KEY AUTOINCREMENT,uid integer, wid INTEGER, sid INTEGER, fid INTEGER,m varchar(1))");
rr = statement.executeUpdate("insert into words(uid,name) values(2,'starter')");
System.out.println("inserted words");
return ("tables recreated");
}
catch(Exception e)
{System.out.println("error x :"+ e.getMessage());
return e.getMessage() ; } }
// public String extractNS(String W)
public Quadroorl extractNS(Quadroopl reqparms)
{ String W = reqparms.W;
Quadroorl repl = new Quadroorl();
System.out.println("invoked extractns:"+W);
int nsi = W.lastIndexOf(".");
if (nsi > 0) {String ns = W.substring(0,nsi+1); repl.rn = ns; repl.reply= ns ;}
else repl.reply = "nonamespace";
return repl;
}
public Quadroorl ANSFromWord(Quadroopl reqparms){
int luid = reqparms.uid;
String W = reqparms.W;
Quadroorl ans = extractNS( reqparms);
reqparms.N = ans.rnw;
if (ans != null ) {
if ((FNSpace(reqparms)).rid == -1 ) {
ANspace(reqparms);
}
}
return ans ;
}
public Quadroorl ANspace(Quadroopl reqparms) {
Quadroorl repl = new Quadroorl();
int luid = reqparms.uid;
String s = reqparms.S;
//only ns is not a word
try {
s.trim();
ResultSet rs = statement.executeQuery("select * from nspace where name =" + "'"+s +"'" );
if (rs.next() ) {
repl.reply = "nspace exists";
// return
}
else
{ // System.out.println("just 2 values");
statement.executeUpdate("insert into nspace('uid','name') values(" + luid +",'"+ s+ "')");
repl.reply = "done";
}
return repl;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
repl.reply ="error";
return repl;
}
}
public Quadroorl FNSpace(Quadroopl reqparms ) {
Quadroorl repl = new Quadroorl();
String W = reqparms.W;
try {
W= W.trim();
ResultSet rs = statement.executeQuery("select * from nspace where name =" + "'"+W +"'");
if (rs.next() ) {
repl.rid = rs.getInt("nid");
repl.reply ="Done";
}
else
{
repl.rid = -1;
repl.reply ="Error";
}
return repl;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
repl.rid = -1;
return repl;
}
}
public Quadroorl DNspace(Quadroopl reqparms) {
Quadroorl repl = new Quadroorl();
String W = reqparms.W;
int luid = reqparms.uid;
try {
W.trim();
ResultSet rs = statement.executeQuery("select * from nspace where name =" + "'"+W +"'");
if (rs.next() ) {
if(rs.getInt("uid") == luid){
ResultSet rn = statement.executeQuery("select * from words where name like " + W +'%');
if ( !rn.next()) {
int rd = statement.executeUpdate("delete from nspace where name ='" + W +"'");
repl.rid = rd;
repl.reply = "done";
}
else { repl.reply = "inUse"; }
}
else
repl.reply = "usermismatch:"+luid+"/"+rs.getInt("uid"); }
else
{
// statement.executeUpdate("insert into words values(1, W)");
repl.reply = "no namespace";
}
return repl;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
repl.reply ="error" + e.getMessage();
return repl;
}
}
public Quadroorl AWord(Quadroopl reqparms) {
Quadroorl repl = new Quadroorl();
String W = reqparms.W;
int luid = reqparms.uid;
String m = reqparms.m;
try {
W.trim();
System.out.println("in AWord:" +W);
ResultSet rs = statement.executeQuery("select * from words where name =" + "'"+W +"'" );
if ((rs != null) && (rs.next()) ) {
repl.reply = "word exists";
return repl; }
else
{ // System.out.println("just 2 values");
statement.executeUpdate("insert into words('uid','name','m') values( " + luid +",'" + W +"','"+ m +" ') " );
// ANSFromWord( );
// statement.executeUpdate("insert into words values(3,'starter4')");
//System.out.println("jinserted 2 values");
repl.reply = "done";
return repl;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
repl.reply = "error:" + e.getMessage();
return repl;
}
}
public Quadroorl CWord(Quadroopl reqparms) {
Quadroorl repl = new Quadroorl();
String W = reqparms.W;
String nW =reqparms.nW;
int luid = reqparms.uid;
try {
W.trim();
ResultSet rs = statement.executeQuery("select * from words where name =" + "'"+W +"'" );
if (rs.next() ) {
if(rs.getInt("uid") == luid){
statement.executeUpdate("update words set name = '" + nW+ "' where name = '" + W + "'");
ANSFromWord(reqparms );
repl.reply = "done";
return repl; }
else {
repl.reply = "usermismatch:"+luid+"/"+rs.getInt("uid");
return repl; }
}
else {
repl.reply = "noword";
return repl;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
repl.reply = "error" + e.getMessage();
return repl;
}
}
public Quadroorl DWord(Quadroopl reqparms ) {
Quadroorl repl = new Quadroorl();
String W = reqparms.W;
int luid = reqparms.uid;
try {
W.trim();
ResultSet rs = statement.executeQuery("select * from words where name =" + "'"+W +"'");
if (rs.next() ) {
if(rs.getInt("uid") == luid){
int rd = statement.executeUpdate("delete from words where name ='" + W +"'");
repl.reply = "done";
}
else
{ repl.reply ="usermismatch:"+luid+"/"+rs.getInt("uid");}
}
else
{
// statement.executeUpdate("insert into words values(1, W)");
repl.reply = "noword";
}
return repl;
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
repl.reply = "error;" + e.getMessage();
return repl;
}
}
public Quadroorl FWord(Quadroopl reqparms) {
String W = reqparms.W;
Quadroorl repl = new Quadroorl();
// int luid = reqparms.uid;
try {
W= W.trim();
ResultSet rs = statement.executeQuery("select * from words where name =" + "'"+W +"'");
if (rs.next() ) {
repl.rwid = rs.getInt("wid");
repl.reply = "Done";
}
else
{
repl.rid = -1 ;
repl.reply = "error";
}
return repl;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
repl.reply = e.getMessage();
return repl;
}
}
public Quadroorl GWord(Quadroopl reqparms ) {
Quadroorl repl = new Quadroorl();
int widi = reqparms.wid;;
try {
ResultSet rs = statement.executeQuery("select name from words where wid =" + widi);
if (rs.next() ) {
repl.rw= rs.getString("name");
repl.reply = "Done";
}
else
{
repl.reply = "not found";
return null;
}
return repl;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
repl.reply = "error:" + e.getMessage();
return repl;
}
}
public Quadroorl AScene( Quadroopl reqparms) {
Quadroorl repl = new Quadroorl();
String W = reqparms.S;
int luid = reqparms.uid;
String m = reqparms.m;
try {
W= W.trim();reqparms.W = W;
int wi = (FWord ( reqparms)).rwid;
//ResultSet rs = statement.executeQuery("select wid from words where name =" + "'"+W +"'");
if (wi > 0) {
int wid = wi;
ResultSet rsc = statement.executeQuery("select sid from quadroo where sid =" + wid + " AND fid=0 AND wid = 0 ");
if (rsc.next() ) {repl.rsid = rsc.getInt(1); repl.reply = "Done";}
else
{
statement.executeUpdate("insert into quadroo('uid','wid','sid','fid','m') values(" + luid +",0,"+ wid +",0,'"+m+"')");
// statement.executeUpdate("create table quadroo (qid INTEGER PRIMARY KEY AUTOINCREMENT,uid integer, wid INTEGER, sid INTEGER, fid INTEGER)");
repl.rsid = wid;
//return wid;
}
}
else
{
statement.executeUpdate("insert into words('uid','name','m') values(" + luid +",'"+ W+ "','" +m + "')");
wi = (FWord (reqparms)).rwid;
// statement.executeUpdate("insert into words values(3,'starter4')");
statement.executeUpdate("insert into quadroo('uid','wid','sid','fid','m') values(" + luid +",0,"+ wi +",0,'"+m+"')");
// statement.executeUpdate("create table quadroo (qid INTEGER PRIMARY KEY AUTOINCREMENT,uid integer, wid INTEGER, sid INTEGER, fid INTEGER)");
repl.rwid = wi;
}
return repl;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
repl.rid = -1;
repl.reply = "error:" + e.getMessage();
return repl;
}
}
public Quadroorl DScene(Quadroopl reqparms ) {
Quadroorl repl = new Quadroorl();
String W = reqparms.S;
int luid = reqparms.uid;
try {
W.trim();
ResultSet rs = statement.executeQuery("select * from words where name =" + "'"+W +"'");
if (rs.next() ) {
if(rs.getInt("uid") == luid){
int wi = rs.getInt("wid");
ResultSet rsc = statement.executeQuery("select qid,sid from quadroo where sid = " + wi+ " AND fid=0 AND wid = 0 ");
if (rsc.next() ) {int qi = rsc.getInt("qid");
int rd = statement.executeUpdate("delete from quadroo where qid =" + qi);
repl.reply = "Done";
//return "done";
}
else
repl.reply = "scene not found";
}
else
repl.reply = "usermismatch:"+luid+"/"+rs.getInt("uid"); }
else
{
// statement.executeUpdate("insert into words values(1, W)");
repl.reply = "noword";
}
return repl;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//return "error";
repl.reply = "error" + e.getMessage();
return repl;
}
}
public Quadroorl FScene(Quadroopl reqparms ) {
Quadroorl repl = new Quadroorl();
String W = reqparms.W;
int luid = reqparms.uid;
try {
W= W.trim();
int wi = (FWord (reqparms)).rwid;
//ResultSet rs = statement.executeQuery("select wid from words where name =" + "'"+W +"'");
if (wi > 0) {
int wid = wi;
ResultSet rsc = statement.executeQuery("select qid from quadroo where sid =wid AND fid=0 AND wid = 0 ");
if (rsc.next() ) {repl.rsid = rsc.getInt("qid") ; repl.reply="Done";}
else
{
repl.reply="error" ;
repl.rid = -1;}
}
else
{repl.reply="error" ;
repl.rid = -2; }
return repl;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
repl.rid = -9;
repl.reply = "error" + e.getMessage();
return repl;
}
}
public Quadroorl AFlow(Quadroopl reqparms ) {
Quadroorl repl = new Quadroorl();
String W = reqparms.W;
int luid = reqparms.uid;
String m = reqparms.m;
try {
W= W.trim();
int wi = (FWord (reqparms)).rwid;
//ResultSet rs = statement.executeQuery("select wid from words where name =" + "'"+W +"'");
if (wi > 0) {
int wid = wi;
ResultSet rsc = statement.executeQuery("select fid from quadroo where fid = " + wid + " AND sid=0 AND wid = 0 ");
if (rsc.next() ) {repl.rid= rsc.getInt(1) ; repl.reply = "exists"; }
else
{
statement.executeUpdate("insert into quadroo('uid','wid','sid','fid','m') values(" + luid +",0,0,"+ wid +"'" + m + "')");
// statement.executeUpdate("create table quadroo (qid INTEGER PRIMARY KEY AUTOINCREMENT,uid integer, wid INTEGER, sid INTEGER, fid INTEGER)");
repl.rwid = wid; repl.reply="Done"; }
}
else
{
statement.executeUpdate("insert into words('uid','name','m') values(" + luid +",'"+ W+ "','" + m + "')");
wi = (FWord (reqparms)).rwid;
// statement.executeUpdate("insert into words values(3,'starter4')");
statement.executeUpdate("insert into quadroo('uid','wid','sid','fid', 'm') values(" + luid +",0,0,"+ wi + ",'"+m+"')");
// statement.executeUpdate("create table quadroo (qid INTEGER PRIMARY KEY AUTOINCREMENT,uid integer, wid INTEGER, sid INTEGER, fid INTEGER)");
repl.rwid = wi;
repl.reply = "Done";
}
return repl;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
repl.rid = -1;
return repl;
}
}
public String DFlow(Quadroopl reqparms ) {
String W = reqparms.W;
int luid = reqparms.uid;
try {
W.trim();
ResultSet rs = statement.executeQuery("select * from words where name =" + "'"+W +"'");
if (rs.next() ) {
if(rs.getInt("uid") == luid){
int wi = rs.getInt("wid");
ResultSet rsc = statement.executeQuery("select qid from quadroo where fid = " + wi+ " AND sid=0 AND wid = 0 ");
if (rsc.next() ) {int qi = rsc.getInt("qid");
int rd = statement.executeUpdate("delete from quadroo where qid =" + qi);
return "done";
}
else
return "flow not found";
}
else
return ("usermismatch:"+luid+"/"+rs.getInt("uid")); }
else
{
// statement.executeUpdate("insert into words values(1, W)");
return "noword";
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "error";
}
}
public Quadroorl FFlow(Quadroopl reqparms ) {
Quadroorl repl = new Quadroorl();
String W = reqparms.W;
// int luid = reqparms.uid;
try {
W= W.trim();
int wi = (FWord (reqparms)).rwid;
//ResultSet rs = statement.executeQuery("select wid from words where name =" + "'"+W +"'");
if (wi > 0) {
int wid = wi;
ResultSet rsc = statement.executeQuery("select qid from quadroo where fid = " + wid + " AND sid=0 AND wid = 0 ");
if (rsc.next() ) {repl.rfid = rsc.getInt("qid") ; }
else
{
repl.rid =-1; repl.reply = "error"; }
}
else
{repl.rid = -1; repl.reply ="error"; }
return repl;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
repl.rid = -1; repl.reply="error:" + e.getMessage();
return repl;
}
}
public Quadroorl AFlowScene(Quadroopl reqparms ) {
String F = reqparms.F;
String W = reqparms.W;
int luid = reqparms.uid;
int fidi = ( AFlow(reqparms)).rfid ;
return (AFScene(reqparms) );
}
public Quadroorl AFScene(Quadroopl reqparms) {
Quadroorl repl = new Quadroorl();
String W = reqparms.W;
int luid = reqparms.uid;
int fidi = reqparms.fid;
try {
W= W.trim();
int wi = (FWord (reqparms)).rwid;
//ResultSet rs = statement.executeQuery("select wid from words where name =" + "'"+W +"'");
if (wi > 0) {
int wid = wi;
ResultSet rsc = statement.executeQuery("select sid from quadroo where sid = "+ wid + " AND fid=0 AND wid = 0 ");
if (rsc.next() ) {
ResultSet rsf = statement.executeQuery("select sid from quadroo where sid =" + wid + " AND fid= "+ fidi );
if (rsf.next() ) {
//return "scene exists in flow" ;
repl.reply = "scene exists in flow" ;
}
else {
ResultSet rsfm = statement.executeQuery("select MAX(wid) from quadroo where fid= " + fidi );
int wp = rsfm.getInt(1);
wp = wp + 1;
statement.executeUpdate("insert into quadroo('uid','wid','sid','fid') values(" + luid +","+wp+","+ wid +","+fidi+")");
repl.reply = "done";
}
}
else
{
statement.executeUpdate("insert into quadroo('uid','wid','sid','fid') values(" + luid +",0,"+ wid +",0)");
ResultSet rsfm = statement.executeQuery("select MAX(wid) from quadroo where fid= " + fidi );
int wp = rsfm.getInt(1);
wp = wp + 1;
statement.executeUpdate("insert into quadroo('uid','wid','sid','fid') values(" + luid +","+wp+","+ wid +","+fidi+")");
repl.reply = "done";
}
}
else
{
statement.executeUpdate("insert into words('uid','name') values(" + luid +",'"+ W+ "')");
wi = (FWord (reqparms)).rwid;
// statement.executeUpdate("insert into words values(3,'starter4')");
statement.executeUpdate("insert into quadroo('uid','wid','sid','fid') values(" + luid +",0,"+ wi +",0 )");
// statement.executeUpdate("create table quadroo (qid INTEGER PRIMARY KEY AUTOINCREMENT,uid integer, wid INTEGER, sid INTEGER, fid INTEGER)");
ResultSet rsfm = statement.executeQuery("select MAX(wid) from quadroo where fid= " + fidi );
int wp = rsfm.getInt(1);
wp = wp + 1;
statement.executeUpdate("insert into quadroo('uid','wid','sid','fid') values(" + luid +","+wp+","+ wi +","+fidi+")");
repl.reply = "done";
}
return repl;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
repl.reply = "error" + e.getMessage();
return repl;
}
}
public Quadroorl DFScene(Quadroopl reqparms) {
Quadroorl repl = new Quadroorl();
String W = reqparms.W;
int luid = reqparms.uid;
int fidi = reqparms.fid;
try {
W= W.trim();
int wi = (FWord (reqparms)).rwid;
if (wi > 0) {
int wid = wi;
ResultSet rsc = statement.executeQuery("select sid from quadroo where sid = " + wid+ " AND fid=0 AND wid = 0 ");
if (rsc.next() ) {
ResultSet rsf = statement.executeQuery("select qid from quadroo where sid = " + wid + " AND fid= " + fidi);
if (rsf.next() ) {
int qi = rsf.getInt("qid");
int rd = statement.executeUpdate("delete from quadroo where qid =" + qi);
repl.reply = "Done"; }
//return "done" ;}
else {
repl.reply = "no scene in flow";
}
}
else
{
repl.reply = "no scene";
}
}
else
{
repl.reply = "no word";
}
return repl;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
repl.reply = "error" + e.getMessage();
return repl;
}
}
public Quadroorl DFSid(Quadroopl reqparms) {
int wi = reqparms.wid;
int luid = reqparms.uid;
int fidi = reqparms.fid;
Quadroorl repl = new Quadroorl();
try {
{
int wid = wi;
ResultSet rsc = statement.executeQuery("select sid from quadroo where sid = " + wid + " AND fid=0 AND wid = 0 ");
if (rsc.next() ) {
ResultSet rsf = statement.executeQuery("select qid from quadroo where sid = " + wid + " AND fid= " + fidi );
if (rsf.next() ) {
int qi = rsf.getInt("qid");
int rd = statement.executeUpdate("delete from quadroo where qid =" + qi);
repl.reply = "done" ;}
else {
repl.reply = "no scene in flow";
}
}
else
{
repl.reply = "no scene";
}
}
return repl;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
repl.reply = "errorr";
return repl;
}
}
public Quadroorl ASceneWord(Quadroopl reqparms) {
Quadroorl repl;
String W = reqparms.W;
int luid = reqparms.uid;
String S = reqparms.S;
int sidi = (AScene( reqparms)).rsid ;
repl = ASWord(reqparms);
return repl;
}
public Quadroorl ASWord(Quadroopl reqparms ) {
Quadroorl repl = new Quadroorl();
String W = reqparms.W;
int luid = reqparms.uid;
int sidi = reqparms.sid;
try {
W= W.trim();
int wi = (FWord (reqparms)).rwid;
//ResultSet rs = statement.executeQuery("select wid from words where name =" + "'"+W +"'");
if (wi > 0) {
int wid = wi;
ResultSet rsc = statement.executeQuery("select sid from quadroo where sid = " + sidi + " AND fid=0 AND wid = 0 ");
if (rsc.next() ) {
statement.executeUpdate("insert into quadroo('uid','wid','sid','fid') values(" + luid +","+wid+","+ sidi +","+"0)");
repl.reply = "Done";
return repl;
}
else
{
repl.reply = "no scene id";
return repl;
}
}
else
{
statement.executeUpdate("insert into words('uid','name') values(" + luid +",'"+ W+ "')");
wi =(FWord ( reqparms)).rwid;
// statement.executeUpdate("insert into words values(3,'starter4')");
statement.executeUpdate("insert into quadroo('uid','wid','sid','fid') values(" + luid +","+wi+","+sidi+",0 )");
// statement.executeUpdate("create table quadroo (qid INTEGER PRIMARY KEY AUTOINCREMENT,uid integer, wid INTEGER, sid INTEGER, fid INTEGER)");
repl.reply = "reply";
return repl;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
repl.reply = "error";
return repl;
}
}
public Quadroorl DSWord(Quadroopl reqparms) {
Quadroorl repl = new Quadroorl();
String W = reqparms.W;
int luid = reqparms.uid;
int sidi = reqparms.sid;
try {
W= W.trim();
int wi = (FWord (reqparms)).rwid;
if (wi > 0) {
int wid = wi;
ResultSet rsc = statement.executeQuery("select qid from quadroo where sid =" + sidi+ " AND fid=0 AND wid = " + wi );
//can check for sceneid
if (rsc.next() ) {
int qi = rsc.getInt("qid");
int rd = statement.executeUpdate("delete from quadroo where qid =" + qi);
repl.reply = "done" ;}
else {
repl.reply = "no word in scene";
}
}
else
{
repl.reply = "no word";
}
return repl;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
repl.reply = "error";
return repl;
}
}
public Quadroorl LSWords( Quadroopl reqparms) {
Quadroorl repl = new Quadroorl();
String W = reqparms.W;
try {
W= W.trim();
int wi = (FWord (reqparms)).rwid;
if (wi > 0) {
int wid = wi;
ResultSet rsc = statement.executeQuery("select wid from quadroo where sid = " + wid + " AND fid=0 AND wid = 0 ");
if (rsc.next() ) { String xml = "<scene name = " + W + ">";
wi = rsc.getInt("wid");reqparms.wid = wi;
String wrd = (GWord(reqparms)).rw;
xml = xml + "<word name=" + wrd+ ">";
while (rsc.next() ){
wi = rsc.getInt("wid");
reqparms.wid = wi;
wrd = (GWord(reqparms)).rw;
xml = xml + "<word name=" + wrd+ ">";
}
xml = xml + "</xml>" ;
repl.rid = 0 ;
repl.reply = xml;
//return xml ;
}
else
{ repl.rid = -2;
repl.reply = "no scene with that name";
}
}
else
{ repl.rid = -2;
repl.reply = "scene name not in dictionary";
}
return repl;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//return "error";
repl.reply = "error:" + e.getMessage();
return repl;
}
}
public String LFScenes(Quadroopl reqparms) {
String W = reqparms.W;
// int luid = reqparms.uid;
// int fidi = reqparms.fid;
try {
W= W.trim();
int wi = (FWord (reqparms)).rwid;
if (wi > 0) {
int wid = wi;
ResultSet rsf = statement.executeQuery("select sid from quadroo where fid=" +wi + "AND wid = 0 ");
if (rsf.next() ) { String xml = "<flow name = " + W + ">";
wi = rsf.getInt("sid");reqparms.wid = wi;
String wrd = (GWord(reqparms)).rw;
xml = xml + "<scene name=" + wrd+ ">";
while (rsf.next() ){
wi = rsf.getInt("sid");
reqparms.wid = wi;
wrd = (GWord(reqparms)).rw;
xml = xml + "<scene name=" + wrd+ ">";
}
xml = xml + "</xml>" ;
return xml ;
}
else
{
return "no flow with that name";
}
}
else
{
return "flow name not in dictionary";
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "error";
}
}
public static void main(String[] args) throws ClassNotFoundException {
String url = "jdbc:sqlite:qudtest.db";
// quadrooql ql = new quadrooql(url);
QuadrooqlS qs = new QuadrooqlS();
int rr = -9; String verb;
// all methods we use have no argument
Class params[] = {};
Object paramsObj[] = {};
Class thisClass = Class.forName("QuadrooqlS");
//ql.AWord(1, "firstword");
//ql.AWord(1, "morning");
qs.init() ;
verb = "AWord";
qs.reqparms.W = "Bright mind";
qs.reqparms.m = "Atest field";
qs.reqparms.uid= 7;
Method thisMethod;
try {
thisMethod = thisClass.getDeclaredMethod(verb, params);
Object rs = thisMethod.invoke(qs, paramsObj);
System.out.println (" execution:" + rs.toString()) ;
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println (thisMethod.invoke(qs, paramsObj).toString());
/*
AWord(1, "goodmorning");
System.out.println("first time:"+ql.AWord(1, "firstword"));
System.out.println("second time:"+ql.AWord(1, "firstword"));
System.out.println("Change result:"+ql.CWord(1,"morning","evening"));
System.out.println("Change result 2nd time:"+ql.CWord(1,"morning","evening"));
System.out.println("Delete result :"+ql.DWord(4,"evening"));
System.out.println("Find result :"+ql.FWord("evening"));
System.out.println("Find result :"+ql.FWord("sianara"));
System.out.println("Scene intro:"+ql.AScene(1, "firstword"));
System.out.println("Scene intro:"+ql.AScene(1, "secondword"));
System.out.println("Scene virgin:"+ql.AScene(1, "virginword"));
System.out.println("Scene find:"+ql.FScene( "virginword"));
System.out.println("Scene delete firstword:"+ql.DScene(1, "firstword"));
System.out.println("namespace from word:"+ql.extractNS("a:b:c:monkey"));
System.out.println("Flow intro:"+ql.AFlow(1, "secondword"));
System.out.println("Flow virgin:"+ql.AFlow(1, "virginword1"));
System.out.println("Flow find fail:"+ql.FFlow( "virginword"));
System.out.println("Flow find success:"+ql.FFlow( "virginword1"));
System.out.println("Flow delete no firstword:"+ql.DFlow(1, "firstword"));
System.out.println("Flow delete secondword:"+ql.DFlow(1, "secondword"));
System.out.println("Flow find after delete secondword:"+ql.FFlow("secondword"));
System.out.println("Scene Add to flow virginword1:"+ql.AFScene(1, 6,"secondword"));
System.out.println("Scene Add to flow new word for scene:"+ql.AFScene(1, 6,"newword"));
System.out.println("Word Add to scene new pie:"+ql.ASWord(1, 7,"pie"));
System.out.println("Scene Add to scene virgin first:"+ql.ASWord(1, 4,"firstword"));
*/ catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| [
"[email protected]"
] | |
cadb38d5d60fb480879e798ba24bbbc84f9631d7 | 0d00bf5cf1e009a773990299527f9ee25dc5e8f7 | /MyPaxos/src/main/java/com/github/luohaha/paxos/main/MyPaxos.java | de722a2dfb7e26eb4b6fa42d41d52e39030e7b17 | [] | no_license | luohaha/MyPaxos | b89b5e28856944f0571ad37ccf1f89d571ab070d | 5a1f362c5bf461464dc45d3c32ab0d6c89fe26c8 | refs/heads/master | 2022-09-09T11:15:22.067378 | 2022-08-25T02:41:39 | 2022-08-25T02:41:39 | 79,129,994 | 154 | 51 | null | null | null | null | UTF-8 | Java | false | false | 4,990 | java | package com.github.luohaha.paxos.main;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.midi.MidiDevice.Info;
import com.github.luohaha.paxos.core.Accepter;
import com.github.luohaha.paxos.core.ConfObject;
import com.github.luohaha.paxos.core.InfoObject;
import com.github.luohaha.paxos.core.Learner;
import com.github.luohaha.paxos.core.PaxosCallback;
import com.github.luohaha.paxos.core.Proposer;
import com.github.luohaha.paxos.packet.Packet;
import com.github.luohaha.paxos.utils.ConfReader;
import com.github.luohaha.paxos.utils.FileUtils;
import com.github.luohaha.paxos.utils.client.ClientImplByLC4J;
import com.github.luohaha.paxos.utils.client.CommClient;
import com.github.luohaha.paxos.utils.client.NonBlockClientImpl;
import com.github.luohaha.paxos.utils.serializable.ObjectSerialize;
import com.github.luohaha.paxos.utils.serializable.ObjectSerializeImpl;
import com.github.luohaha.paxos.utils.server.CommServer;
import com.github.luohaha.paxos.utils.server.CommServerImpl;
import com.github.luohaha.paxos.utils.server.NonBlockServerImpl;
import com.github.luohaha.paxos.utils.server.ServerImplByLC4J;
import com.google.gson.Gson;
public class MyPaxos {
/**
* 全局配置文件信息
*/
private ConfObject confObject;
/**
* 本节点的信息
*/
private InfoObject infoObject;
/**
* 配置文件所在的位置
*/
private String confFile;
private Map<Integer, PaxosCallback> groupidToCallback = new HashMap<>();
private Map<Integer, Proposer> groupidToProposer = new HashMap<>();
private Map<Integer, Accepter> groupidToAccepter = new HashMap<>();
private Map<Integer, Learner> groupidToLearner = new HashMap<>();
private Gson gson = new Gson();
private ObjectSerialize objectSerialize = new ObjectSerializeImpl();
private Logger logger = Logger.getLogger("MyPaxos");
/*
* 客户端
*/
private CommClient client;
public MyPaxos(String confFile) throws IOException {
super();
this.confFile = confFile;
this.confObject = gson.fromJson(FileUtils.readFromFile(this.confFile), ConfObject.class);
this.infoObject = getMy(this.confObject.getNodes());
// 启动客户端
this.client = new ClientImplByLC4J(4);
//this.logger.setLevel(Level.WARNING);
}
/**
* 设置log级别
* @param level
* 级别
*/
public void setLogLevel(Level level) {
this.logger.setLevel(level);
}
/**
* add handler
* @param handler
* handler
*/
public void addLogHandler(Handler handler) {
this.logger.addHandler(handler);
}
/**
*
* @param id
* @param executor
*/
public void setGroupId(int groupId, PaxosCallback executor) {
Accepter accepter = new Accepter(infoObject.getId(), confObject.getNodes(), infoObject, confObject, groupId,
this.client);
Proposer proposer = new Proposer(infoObject.getId(), confObject.getNodes(), infoObject, confObject.getTimeout(),
accepter, groupId, this.client);
Learner learner = new Learner(infoObject.getId(), confObject.getNodes(), infoObject, confObject, accepter,
executor, groupId, this.client);
this.groupidToCallback.put(groupId, executor);
this.groupidToAccepter.put(groupId, accepter);
this.groupidToProposer.put(groupId, proposer);
this.groupidToLearner.put(groupId, learner);
}
/**
* 获得我的accepter或者proposer信息
*
* @param accepters
* @return
*/
private InfoObject getMy(List<InfoObject> infoObjects) {
for (InfoObject each : infoObjects) {
if (each.getId() == confObject.getMyid()) {
return each;
}
}
return null;
}
/**
* 启动paxos服务器
*
* @throws IOException
* @throws InterruptedException
* @throws ClassNotFoundException
*/
public void start() throws IOException, InterruptedException, ClassNotFoundException {
// 启动paxos服务器
CommServer server = new ServerImplByLC4J(this.infoObject.getPort(), 4);
System.out.println("paxos server-" + confObject.getMyid() + " start...");
while (true) {
byte[] data = server.recvFrom();
//Packet packet = gson.fromJson(new String(data), Packet.class);
Packet packet = objectSerialize.byteArrayToObject(data, Packet.class);
int groupId = packet.getGroupId();
Accepter accepter = this.groupidToAccepter.get(groupId);
Proposer proposer = this.groupidToProposer.get(groupId);
Learner learner = this.groupidToLearner.get(groupId);
if (accepter == null || proposer == null || learner == null) {
return;
}
switch (packet.getWorkerType()) {
case ACCEPTER:
accepter.sendPacket(packet.getPacketBean());
break;
case PROPOSER:
proposer.sendPacket(packet.getPacketBean());
break;
case LEARNER:
learner.sendPacket(packet.getPacketBean());
break;
case SERVER:
proposer.sendPacket(packet.getPacketBean());
break;
default:
break;
}
}
}
}
| [
"[email protected]"
] | |
1a07398c12deeefb0020bbbae0e1220b6b7eee52 | 1742b6719b988e5519373002305e31d28b8bd691 | /sdk/java/src/main/java/com/pulumi/aws/budgets/outputs/BudgetAutoAdjustData.java | b7772ae34e7d3a14f6d62df57baf022430dff413 | [
"BSD-3-Clause",
"Apache-2.0",
"MPL-2.0"
] | permissive | pulumi/pulumi-aws | 4f7fdb4a816c5ea357cff2c2e3b613c006e49f1a | 42b0a0abdf6c14da248da22f8c4530af06e67b98 | refs/heads/master | 2023-08-03T23:08:34.520280 | 2023-08-01T18:09:58 | 2023-08-01T18:09:58 | 97,484,940 | 384 | 171 | Apache-2.0 | 2023-09-14T14:48:40 | 2017-07-17T14:20:33 | Java | UTF-8 | Java | false | false | 2,702 | java | // *** WARNING: this file was generated by pulumi-java-gen. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
package com.pulumi.aws.budgets.outputs;
import com.pulumi.aws.budgets.outputs.BudgetAutoAdjustDataHistoricalOptions;
import com.pulumi.core.annotations.CustomType;
import java.lang.String;
import java.util.Objects;
import java.util.Optional;
import javax.annotation.Nullable;
@CustomType
public final class BudgetAutoAdjustData {
private String autoAdjustType;
private @Nullable BudgetAutoAdjustDataHistoricalOptions historicalOptions;
private @Nullable String lastAutoAdjustTime;
private BudgetAutoAdjustData() {}
public String autoAdjustType() {
return this.autoAdjustType;
}
public Optional<BudgetAutoAdjustDataHistoricalOptions> historicalOptions() {
return Optional.ofNullable(this.historicalOptions);
}
public Optional<String> lastAutoAdjustTime() {
return Optional.ofNullable(this.lastAutoAdjustTime);
}
public static Builder builder() {
return new Builder();
}
public static Builder builder(BudgetAutoAdjustData defaults) {
return new Builder(defaults);
}
@CustomType.Builder
public static final class Builder {
private String autoAdjustType;
private @Nullable BudgetAutoAdjustDataHistoricalOptions historicalOptions;
private @Nullable String lastAutoAdjustTime;
public Builder() {}
public Builder(BudgetAutoAdjustData defaults) {
Objects.requireNonNull(defaults);
this.autoAdjustType = defaults.autoAdjustType;
this.historicalOptions = defaults.historicalOptions;
this.lastAutoAdjustTime = defaults.lastAutoAdjustTime;
}
@CustomType.Setter
public Builder autoAdjustType(String autoAdjustType) {
this.autoAdjustType = Objects.requireNonNull(autoAdjustType);
return this;
}
@CustomType.Setter
public Builder historicalOptions(@Nullable BudgetAutoAdjustDataHistoricalOptions historicalOptions) {
this.historicalOptions = historicalOptions;
return this;
}
@CustomType.Setter
public Builder lastAutoAdjustTime(@Nullable String lastAutoAdjustTime) {
this.lastAutoAdjustTime = lastAutoAdjustTime;
return this;
}
public BudgetAutoAdjustData build() {
final var o = new BudgetAutoAdjustData();
o.autoAdjustType = autoAdjustType;
o.historicalOptions = historicalOptions;
o.lastAutoAdjustTime = lastAutoAdjustTime;
return o;
}
}
}
| [
"[email protected]"
] | |
67287193152df04926d90ebf78c80fd9d921a154 | 2fa5603e0f0aef27a1f58b22bbea4790880a1b07 | /src/BPlus.java | 5d0acdc996fae7fbd7d2f384da415e330cff477d | [] | no_license | GBT3101/BplusTree | 4e94870f3a1e3974eb2db55c5d64c0924e0cc119 | 263d8aa0845adfd66f5e8ab5336bd194338b9e12 | refs/heads/master | 2021-01-25T10:07:48.143328 | 2013-09-04T11:54:21 | 2013-09-04T11:54:21 | 12,589,402 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,419 | java | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
public class BPlus {
public static void main (String[] args) {
//Checking that we received exactly four arguments from the user
if(args.length == 4)
{
String tInputFileName = args[0];//Acquiring input file name
int t = Integer.parseInt(args[1]); // represents the maximum size of the nodes in the tree
int oNum = Integer.parseInt(args[2]); // the number that should be Ordered
record oRecord = new record();
//Calling to readFromFile function, which will read the content of the file named fileName and concatenate it to one string, and returns it to the user
String tOutputFileName = args[3];//Acquiring output file name
//String tFileContent = readFromFile(tInputFileName);
String inputFile = readFromFile(tInputFileName).trim(); // deletes spaces
String[] numbers = inputFile.split(" "); // array of strings possesing the numbers
record[] records = new record[numbers.length]; // array of records by the input numbers
Tree T = new Tree(t,records.length);
for(int i=0; i<numbers.length; i++){ // initialize records and inserts them to the tree
records[i] = new record(Integer.parseInt(numbers[i]));
if(oNum==records[i].getNum())
oRecord = records[i]; // the 'Order' record is found and saved
T.Insert(records[i]); // insertion to the tree
}
String Content = ""+T.toString()+"\n"+T.Min_gap()+"\n"+T.Order(oRecord);
System.out.println(T.toString());
System.out.println(T.Min_gap());
System.out.println(T.Order(oRecord));
writeToFile(tOutputFileName, Content);//Calling to writeToFile function which will write the content string to the output file
}
else
{
System.out.println("No args were given , or more than four args");
}
}
public static String readFromFile(String fileName)
{
String tContent = "";
//Must wrap working with files with try/catch
try{
//Creating a file object
File tFile = new File(fileName);
//Init inputstream
FileInputStream fstream = new FileInputStream(tFile);
DataInputStream in = new DataInputStream(fstream);
//Creating a buffered reader.
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null){
tContent = tContent + strLine + " ";//concatenating the line to content string
}
//Close the input stream
in.close();
}
catch(Exception e)//Catch exception if any
{
System.err.println("Error: " + e.getMessage());
}
return tContent;
}
public static void writeToFile(String fileName, String Content){
//Must wrap working with files with try/catch
try {
//Creating a file object
File tFile = new File(fileName);
// if file doesn't exists, then create it
if (!tFile.exists()) {
tFile.createNewFile();
}
//Init fileWriter
FileWriter fw = new FileWriter(tFile.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(Content);
//Close the output stream
bw.close();
} catch (IOException e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
| [
"[email protected]"
] | |
1d11ca82233a8565b4cb2e96b2e6c7980ed3a7de | 34c8b01849d7265c73bcc696e7f0c11312c7f84d | /jelly-tags/junit/src/java/org/apache/commons/jelly/tags/junit/RunTag.java | e20903e832ac232923a2ba70c825ead055808852 | [
"Apache-2.0"
] | permissive | pwntester/jelly | 03ddb422005970ddfc86f0e1cc7c5b5a84f7e431 | cb7966734f339619e5ee8e57b08009acbf5e1d10 | refs/heads/master | 2021-01-16T11:55:47.916026 | 2017-11-27T20:21:47 | 2017-11-27T20:21:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,022 | java | /*
* Copyright 2002,2004 The Apache Software Foundation.
*
* 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.apache.commons.jelly.tags.junit;
import java.io.PrintWriter;
import java.io.StringWriter;
import junit.framework.AssertionFailedError;
import junit.framework.Test;
import junit.framework.TestListener;
import junit.framework.TestResult;
import org.apache.commons.jelly.JellyTagException;
import org.apache.commons.jelly.MissingAttributeException;
import org.apache.commons.jelly.TagSupport;
import org.apache.commons.jelly.XMLOutput;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
/**
* This tag will run the given Test which could be an individual TestCase or a TestSuite.
* The TestResult can be specified to capture the output, otherwise the results are output
* as XML so that they can be formatted in some custom manner.
*
* @author <a href="mailto:[email protected]">James Strachan</a>
* @version $Revision: 155420 $
*/
public class RunTag extends TagSupport {
/** The Log to which logging calls will be made. */
private static final Log log = LogFactory.getLog(RunTag.class);
private Test test;
private TestResult result;
private TestListener listener;
// Tag interface
//-------------------------------------------------------------------------
public void doTag(XMLOutput output) throws MissingAttributeException, JellyTagException {
Test test = getTest();
if ( test == null ) {
test = (Test) context.getVariable("org.apache.commons.jelly.junit.suite");
}
if ( test == null ) {
throw new MissingAttributeException( "test" );
}
TestResult result = getResult();
if ( result == null ) {
result = createResult(output);
}
TestListener listener = getListener();
if ( listener == null ) {
listener = createTestListener(output);
}
result.addListener(listener);
test.run(result);
}
// Properties
//-------------------------------------------------------------------------
/**
* Returns the TestResult used to capture the output of the test.
* @return TestResult
*/
public TestResult getResult() {
return result;
}
/**
* Returns the Test to be ran.
* @return Test
*/
public Test getTest() {
return test;
}
/**
* Sets the JUnit TestResult used to capture the results of the tst
* @param result The TestResult to use
*/
public void setResult(TestResult result) {
this.result = result;
}
/**
* Sets the JUnit Test to run which could be an individual test or a TestSuite
* @param test The test to run
*/
public void setTest(Test test) {
this.test = test;
}
/**
* Returns the listener.
* @return TestListener
*/
public TestListener getListener() {
return listener;
}
/**
* Sets the TestListener.to be used to format the output of running the unit test cases
* @param listener The listener to set
*/
public void setListener(TestListener listener) {
this.listener = listener;
}
// Implementation methods
//-------------------------------------------------------------------------
/**
* Factory method to create a new TestResult to capture the output of
* the test cases
*/
protected TestResult createResult(XMLOutput output) {
return new TestResult();
}
/**
* Factory method to create a new TestListener to capture the output of
* the test cases
*/
protected TestListener createTestListener(final XMLOutput output) {
return new TestListener() {
public void addError(Test test, Throwable t) {
try {
output.startElement("error");
output.startElement("message");
output.write(t.getMessage());
output.endElement("message");
output.startElement("stack");
output.write( stackTraceToString(t) );
output.endElement("stack");
output.endElement("error");
}
catch (SAXException e) {
handleSAXException(e);
}
}
public void addFailure(Test test, AssertionFailedError t) {
try {
output.startElement("failure");
output.startElement("message");
output.write(t.getMessage());
output.endElement("message");
output.startElement("stack");
output.write( stackTraceToString(t) );
output.endElement("stack");
output.endElement("failure");
}
catch (SAXException e) {
handleSAXException(e);
}
}
public void endTest(Test test) {
try {
output.endElement("test");
}
catch (SAXException e) {
handleSAXException(e);
}
}
public void startTest(Test test) {
try {
String name = test.toString();
AttributesImpl attributes = new AttributesImpl();
attributes.addAttribute("", "name", "name", "CDATA", name);
output.startElement("test", attributes);
}
catch (SAXException e) {
handleSAXException(e);
}
}
};
}
/**
* @return the stack trace as a String
*/
protected String stackTraceToString(Throwable t) {
StringWriter writer = new StringWriter();
t.printStackTrace(new PrintWriter(writer));
return writer.toString();
}
/**
* Handles SAX Exceptions
*/
protected void handleSAXException(SAXException e) {
log.error( "Caught: " + e, e );
}
}
| [
"[email protected]"
] | |
95043b6ea782802fb2c339f8b47b8c406cc19f9c | 2fd35234017926beffc1434e287bf2823b7cce36 | /src/main/java/com/medicine/pojo/TbOrderdetail.java | a13f4064d24ba35cb8d1eb4e57cd8071f9737282 | [] | no_license | androidheng/medicine | 173b515c2ffad7a1e815c9cf352431028a1dc002 | 809c6732129b89ae294b789d2510c250a14e3cb8 | refs/heads/master | 2022-12-22T10:54:34.566536 | 2019-05-26T07:43:43 | 2019-05-26T07:43:43 | 188,653,944 | 0 | 0 | null | 2022-12-16T03:31:36 | 2019-05-26T07:40:11 | JavaScript | UTF-8 | Java | false | false | 1,056 | java | package com.medicine.pojo;
public class TbOrderdetail {
private Integer id;
private Integer shopid;
private Integer detailcount;
private String detailprice;
private Integer orderid;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getShopid() {
return shopid;
}
public void setShopid(Integer shopid) {
this.shopid = shopid;
}
public Integer getDetailcount() {
return detailcount;
}
public void setDetailcount(Integer detailcount) {
this.detailcount = detailcount;
}
public String getDetailprice() {
return detailprice;
}
public void setDetailprice(String detailprice) {
this.detailprice = detailprice == null ? null : detailprice.trim();
}
public Integer getOrderid() {
return orderid;
}
public void setOrderid(Integer orderid) {
this.orderid = orderid;
}
} | [
"[email protected]"
] | |
efc1b36329396061dd988b884739dbf598980011 | 029efadd12af79c1803f76fd956318add64d04b4 | /app/src/main/java/lastie_wangechian_Projo/com/StartActivity.java | 32a4f39935f69756740436af5ce99421e52718ad | [] | no_license | MugoSimon/Projo | b10993f162f46c5a60c3070dfc0e7f5d5afd8318 | 9954e5dd196465a5e224de135f9f4c9539102386 | refs/heads/master | 2021-01-06T13:10:20.075727 | 2020-02-18T10:50:21 | 2020-02-18T10:50:21 | 241,336,890 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 989 | java | package lastie_wangechian_Projo.com;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.auth.FirebaseAuth;
public class StartActivity extends AppCompatActivity {
private Button logoutBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
logoutBtn = findViewById(R.id.logutBtn);
logoutBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(StartActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
});
}
}
| [
"[email protected]"
] | |
cc0991f2e1f783c319d09fc8e51a5d73daa91467 | 365ddd9a94d40297b3bfb5fd956ef7509a1e4745 | /app/src/main/java/kr/co/landvibe/handicraft/data/source/auth/AuthDataSource.java | dd2f90e704c1cfee4a947d751ccc7ba8229de3a6 | [] | no_license | TalentDonation/Handicraft-Android | 12be7c8abd1d250cb991518f283dedcd4ee15f70 | 79acc519dc575a69cd177a6e14f266efead362e2 | refs/heads/master | 2020-04-05T13:40:31.778208 | 2017-09-03T23:55:59 | 2017-09-03T23:55:59 | 94,962,930 | 2 | 2 | null | 2017-09-03T23:56:00 | 2017-06-21T04:30:56 | Java | UTF-8 | Java | false | false | 868 | java | package kr.co.landvibe.handicraft.data.source.auth;
import android.support.annotation.NonNull;
import io.reactivex.Maybe;
import kr.co.landvibe.handicraft.data.domain.Member;
import kr.co.landvibe.handicraft.data.domain.NaverOauthInfo;
public interface AuthDataSource {
Maybe<NaverOauthInfo> createAuth(@NonNull NaverOauthInfo naverOauthInfo);
Maybe<NaverOauthInfo> getAuth(@NonNull String uniqueId, @NonNull String accessToken);
Maybe<NaverOauthInfo> updateAuth(@NonNull NaverOauthInfo naverOauthInfo);
Maybe<NaverOauthInfo> updateAuth(@NonNull String uniqueId, @NonNull String accessToken, long expiresAt);
void deleteAuth(@NonNull NaverOauthInfo naverOauthInfo);
void deleteAuth(@NonNull String uniqueId, @NonNull String accessToken);
Maybe<Member> getNaverUserInfo(@NonNull String accessToken, @NonNull String tokenType);
}
| [
"[email protected]"
] | |
d8031a03cb4770c3299e6a051f9d0212d98d7600 | 90bede8139be1cf7bdf2266294bf7e1170471559 | /app/src/main/java/com/example/felix/stuger/HomeFragment.java | 0b33fa3fe3bacc217371089a91ab02d43e5d74b2 | [] | no_license | bryan8288/ITDivisionProject | 50c9e152edd804221bb9beda4cf547f23985f67a | 478746dc1b3aa70065e7d85b42b116a5da42232a | refs/heads/master | 2022-12-17T13:26:11.385392 | 2020-09-25T11:15:50 | 2020-09-25T11:15:50 | 298,544,010 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 590 | java | package com.example.felix.stuger;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class HomeFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_home,container,false);
return v;
}
}
| [
"[email protected]"
] | |
4602639c05173ae354fb8b6d78e9004960f13e38 | a7b868c8c81984dbcb17c1acc09c0f0ab8e36c59 | /src/main/java/com/alipay/api/domain/SsdataDataserviceMetainfoSyncModel.java | 23b1fe7b48f953d88afd38f5eeb6a7f62dd43a5a | [
"Apache-2.0"
] | permissive | 1755616537/alipay-sdk-java-all | a7ebd46213f22b866fa3ab20c738335fc42c4043 | 3ff52e7212c762f030302493aadf859a78e3ebf7 | refs/heads/master | 2023-02-26T01:46:16.159565 | 2021-02-02T01:54:36 | 2021-02-02T01:54:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 611 | java | package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 上数元数据信息同步服务
*
* @author auto create
* @since 1.0, 2020-12-31 13:50:44
*/
public class SsdataDataserviceMetainfoSyncModel extends AlipayObject {
private static final long serialVersionUID = 2563631835438226468L;
/**
* 元数据信息
*/
@ApiField("meta_info")
private String metaInfo;
public String getMetaInfo() {
return this.metaInfo;
}
public void setMetaInfo(String metaInfo) {
this.metaInfo = metaInfo;
}
}
| [
"[email protected]"
] | |
a3c86fa5a715b366381dd650f794a79727ce4048 | a44876c6a866cf88d515b81ff7e677a26f63464e | /test/ar/edu/unq/po2/tp8/ejercicio3/FiltroTestCase.java | 19f191a2bc022fca72b45962ac830b4cd1c0a46b | [] | no_license | LeandroOtel/unqui-po2-otel | f9f4f6ee9e1a26d9be48a759c55ed3571d17e17c | c7b90705500594262b4a29f2e5e3141e3e3b5465 | refs/heads/main | 2023-07-01T02:36:35.590053 | 2021-07-12T21:02:02 | 2021-07-12T21:02:02 | 358,034,654 | 0 | 0 | null | 2021-04-27T18:29:22 | 2021-04-14T20:31:18 | Java | UTF-8 | Java | false | false | 2,719 | java | package ar.edu.unq.po2.tp8.ejercicio3;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
class FiltroTestCase {
private Filtro letraInicial;
private Filtro linkEnComun;
private Filtro propiedadEnComun;
private Pagina p1;
private Pagina p2;
private Pagina p3;
private List<WikipediaPage> listaDeWikipages;
private List<WikipediaPage> links1;
private List<WikipediaPage> links2;
private Map<String, WikipediaPage> info1;
private Map<String, WikipediaPage> info2;
@BeforeEach
public void setUp() {
letraInicial = new MismaLetraInicial();
linkEnComun = new LinkEnComun();
propiedadEnComun = new PropiedadEnComun();
p1 = mock(Pagina.class);
p2 = mock(Pagina.class);
p3 = mock(Pagina.class);
listaDeWikipages = new ArrayList<WikipediaPage>();
links1 = new ArrayList<WikipediaPage>();
links2 = new ArrayList<WikipediaPage>();
info1 = new HashMap<String, WikipediaPage>();
info2 = new HashMap<String, WikipediaPage>();
}
@Test
void mismaLetraInicial() {
when(p1.getTitle()).thenReturn("POO");
when(p2.getTitle()).thenReturn("POO");
when(p3.getTitle()).thenReturn("ASD");
listaDeWikipages.add(p2);
listaDeWikipages.add(p3);
List<WikipediaPage> paginasFiltradas = this.letraInicial.getSimilarPages(p1, listaDeWikipages);
assertTrue(paginasFiltradas.size()==1);
assertTrue(paginasFiltradas.contains(p2));
}
@Test
void linkEnComun() {
links1.add(p1);
links1.add(p2);
links2.add(p3);
when(p1.getLinks()).thenReturn(links1);
when(p2.getLinks()).thenReturn(links1);
when(p3.getLinks()).thenReturn(links2);
listaDeWikipages.add(p2);
listaDeWikipages.add(p3);
List<WikipediaPage> paginasFiltradas = this.linkEnComun.getSimilarPages(p1, listaDeWikipages);
assertTrue(paginasFiltradas.size()==1);
assertTrue(paginasFiltradas.contains(p2));
}
@Test
void propiedadEnComun() {
info1.put("tecnologia", p1);
info1.put("ambiente", p1);
info2.put("arte", p2);
when(p1.getInfobox()).thenReturn(info1);
when(p2.getInfobox()).thenReturn(info1);
when(p3.getInfobox()).thenReturn(info2);
listaDeWikipages.add(p2);
listaDeWikipages.add(p3);
List<WikipediaPage> paginasFiltradas = this.propiedadEnComun.getSimilarPages(p1, listaDeWikipages);
assertTrue(paginasFiltradas.size()==1);
assertTrue(paginasFiltradas.contains(p2));
}
}
| [
"Lea@DESKTOP-LFHUJIE"
] | Lea@DESKTOP-LFHUJIE |
f9fa51d606aa526a1ed5f6f1b8b5faa1ab214422 | f953750a37feefe42e790de8e0fb6476a059e777 | /chapter_004/src/main/java/ru/job4j/Profile.java | d48bfd0d29df6138f8cbce30605edd8a897d5744 | [] | no_license | vitalygilev/job4j | 8d86f8670f627f3e6ffe76b9a1e58ace6522b12b | eea2dceaf1ecb69426e394adab849965b2c24e70 | refs/heads/master | 2022-09-30T10:52:42.397108 | 2020-12-01T06:45:24 | 2020-12-01T06:45:24 | 213,826,827 | 0 | 0 | null | 2022-05-20T21:55:12 | 2019-10-09T05:16:16 | Java | UTF-8 | Java | false | false | 721 | java | package ru.job4j;
import java.util.Objects;
public class Profile {
private Address address;
public Profile(Address address) {
this.address = address;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Profile profile = (Profile) o;
return Objects.equals(address, profile.address);
}
@Override
public int hashCode() {
return Objects.hash(address);
}
}
| [
"[email protected]"
] | |
b67638effe909d4a9387c1ce75541ead5f844dfe | b887d8a656faa86f61a21add6baaafd7969ddf3f | /java/html_to_pdf/src/main/java/com/youdaigc/report/common/ReportDocFileType.java | 6ce171be0a0047d0945efaeb2bbc672d22b7dc77 | [
"MIT"
] | permissive | gwfxp/Tutorial_Projects | 47cbce0eb8882b892158ce8730e03fab5e782f23 | 3b8ae48dfbdb0caabfa8d51103dababb529de94d | refs/heads/master | 2021-07-21T15:25:47.553954 | 2017-11-01T10:32:35 | 2017-11-01T10:32:35 | 108,793,717 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 179 | java | package com.youdaigc.report.common;
/**
* Created by GaoWeiFeng on 2017-08-24.
*/
public enum ReportDocFileType {
PDF,
WORD,
EXCEL,
HTML,
TEXT,
IMAGE
}
| [
"[email protected]"
] | |
49444767e5029fb7ce1e201e5ce28728419dce3a | fc1f483f114b89f9a57401e236914927bfdb8657 | /src/main/java/ShewHeap.java | 919aaed0a76d8b833ccf8933f615f6df0114ed29 | [] | no_license | XIFDF/monkeyking | 2d624730acfdf922d563715ba7cfae912977c3a4 | c1d8c55ff1de8a1f6d08d5389edff0d465e316a3 | refs/heads/master | 2020-04-12T15:20:00.484329 | 2018-12-29T06:36:07 | 2018-12-29T06:36:07 | 162,577,531 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,340 | java | import java.util.Stack;
//斜堆较为完整的定义类,问题解决无需使用此类(核心算法使用迭代)
public class ShewHeap<T extends Comparable<T>> {
// 根节点最大
public ShewHeap(){
root = null;
}
public class Node<T> {
T key;
Node<T> left;
Node<T> right;
Node(T key, Node<T> left, Node<T> right) {
this.key = key;
this.left = left;
this.right = right;
}
Node(T key) {
this(key, null, null);
}
}
private Node<T> root;
public boolean isEmpty() {
return root == null;
}
// 迭代
private Node<T> merge(Node<T> root1,Node<T> root2){
if(root1 == null) return root2;
if(root2 == null) return root1;
Stack<Node<T>> stack = new Stack<Node<T>>();
Node<T> r1 = root1;
Node<T> r2 = root2;
while(r1 != null && r2 != null){
if(r1.key.compareTo(r2.key) > 0){
stack.push(r1);
r1 = r1.right;
}else{
stack.push(r2);
r2 = r2.right;
}
}
Node<T> r = (r1 != null) ? r1 : r2;
while(!stack.isEmpty()){
Node<T> node = stack.pop();
node.right = node.left;
node.left = r;
r = node;
}
return r;
}
// 递归
// private Node<T> merge(Node<T> n1, Node<T> n2) {
// if (n1 == null) return n2;
// if (n2 == null) return n1;
//
// if (n1.key.compareTo(n2.key) <= 0) {
// Node<T> tmp = n1;
// n1 = n2;
// n2 = tmp;
// }
//
// Node<T> tmp = merge(n1.right, n2);
// n1.right = n2.left;
// n1.left = tmp;
//
// return n1;
// }
public int merge(ShewHeap<T> other) {
if(this == other) return -1;
this.root = merge(this.root, other.root);
other.root = null;
return 1;
}
public void insert(T key) {
root = merge(new Node<T>(key), root);
}
public T deleteMax() {
if (isEmpty()) {
throw new Error();
}
T maxItem = root.key;
root = merge(root.right, root.left);
return maxItem;
}
public T getMax() {
return root.key;
}
}
| [
"[email protected]"
] | |
73d487cead052a6af50a65407a8ee18bcf5fdfa3 | d3905f4dc0869daa8410ccad02d41cd0688f3146 | /app/src/main/java/bd/piniti/service_pro/GeyserSecondActivity.java | bdc66dfc4cfcc0385589059d1e1d370ba9ba671b | [] | no_license | Piniti-Project-Development/PinitiServicePro | 1b8874353e05b506dfcb23b144d25340c312e018 | e4828fcc1efc5bfe1e5ea97b2ded210fa8a1750f | refs/heads/master | 2021-04-13T23:42:44.228407 | 2020-03-22T15:44:37 | 2020-03-22T15:44:37 | 249,195,159 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,980 | java | package bd.piniti.service_pro;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import at.grabner.circleprogress.CircleProgressView;
public class GeyserSecondActivity extends AppCompatActivity implements View.OnClickListener {
TextView title, number, number1;
ImageView back_img, search;
CheckBox checkBox1,checkBox2,checkBox3,checkBox4;
Button button;
CircleProgressView circleProgressView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_geyser_second);
circleProgressView = findViewById(R.id.circleView);
circleProgressView.setVisibility(View.VISIBLE);
circleProgressView.setOuterContourColor(getResources().getColor(R.color.blue));
circleProgressView.setTextSize(20);
circleProgressView.setBarColor(getResources().getColor(R.color.blue));
circleProgressView.setSpinBarColor(getResources().getColor(R.color.blue));
circleProgressView.setValue(Float.parseFloat("28"));
title = findViewById(R.id.title);
title.setText("Geyser");
search = findViewById(R.id.search);
search.setVisibility(View.GONE);
back_img = findViewById(R.id.back_img);
back_img.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(GeyserSecondActivity.this,GeyserThreeActivity.class);
startActivity(intent);
}
});
checkBox1 = findViewById(R.id.checkbox1);
checkBox2 = findViewById(R.id.checkbox2);
checkBox3 = findViewById(R.id.checkbox3);
checkBox1.setOnClickListener(this);
checkBox2.setOnClickListener(this);
checkBox3.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.checkbox1:
checkBox1.setChecked(true);
checkBox2.setChecked(false);
checkBox3.setChecked(false);
break;
case R.id.checkbox2:
checkBox1.setChecked(false);
checkBox2.setChecked(true);
checkBox3.setChecked(false);
break;
case R.id.checkbox3:
checkBox1.setChecked(false);
checkBox2.setChecked(false);
checkBox3.setChecked(true);
break;
}
}
}
| [
"[email protected]"
] | |
5b3c72f0d99e1a52d024e09d8b7e2bf3480605f6 | 4d6f449339b36b8d4c25d8772212bf6cd339f087 | /netreflected/src/Framework/System.Workflow.Runtime,Version=4.0.0.0,Culture=neutral,PublicKeyToken=31bf3856ad364e35/system/workflow/runtime/TimerEventSubscription.java | 006818e5cffd75fe8611225bc99c714859253162 | [
"MIT"
] | permissive | lvyitian/JCOReflector | 299a64550394db3e663567efc6e1996754f6946e | 7e420dca504090b817c2fe208e4649804df1c3e1 | refs/heads/master | 2022-12-07T21:13:06.208025 | 2020-08-28T09:49:29 | 2020-08-28T09:49:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,411 | java | /*
* MIT License
*
* Copyright (c) 2020 MASES s.r.l.
*
* 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.
*/
/**************************************************************************************
* <auto-generated>
* This code was generated from a template using JCOReflector
*
* Manual changes to this file may cause unexpected behavior in your application.
* Manual changes to this file will be overwritten if the code is regenerated.
* </auto-generated>
*************************************************************************************/
package system.workflow.runtime;
import org.mases.jcobridge.*;
import org.mases.jcobridge.netreflection.*;
import java.util.ArrayList;
// Import section
import system.Guid;
import system.DateTime;
import system.IComparable;
import system.IComparableImplementation;
/**
* The base .NET class managing System.Workflow.Runtime.TimerEventSubscription, System.Workflow.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35. Extends {@link NetObject}.
* <p>
*
* See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.Workflow.Runtime.TimerEventSubscription" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.Workflow.Runtime.TimerEventSubscription</a>
*/
public class TimerEventSubscription extends NetObject {
/**
* Fully assembly qualified name: System.Workflow.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
*/
public static final String assemblyFullName = "System.Workflow.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";
/**
* Assembly name: System.Workflow.Runtime
*/
public static final String assemblyShortName = "System.Workflow.Runtime";
/**
* Qualified class name: System.Workflow.Runtime.TimerEventSubscription
*/
public static final String className = "System.Workflow.Runtime.TimerEventSubscription";
static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName);
/**
* The type managed from JCOBridge. See {@link JCType}
*/
public static JCType classType = createType();
static JCEnum enumInstance = null;
JCObject classInstance = null;
static JCType createType() {
try {
return bridge.GetType(className + ", " + (JCOBridgeInstance.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName));
} catch (JCException e) {
return null;
}
}
void addReference(String ref) throws Throwable {
try {
bridge.AddReference(ref);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public TimerEventSubscription(Object instance) throws Throwable {
super(instance);
if (instance instanceof JCObject) {
classInstance = (JCObject) instance;
} else
throw new Exception("Cannot manage object, it is not a JCObject");
}
public String getJCOAssemblyName() {
return assemblyFullName;
}
public String getJCOClassName() {
return className;
}
public String getJCOObjectName() {
return className + ", " + (JCOBridgeInstance.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
}
public Object getJCOInstance() {
return classInstance;
}
public void setJCOInstance(JCObject instance) {
classInstance = instance;
super.setJCOInstance(classInstance);
}
public JCType getJCOType() {
return classType;
}
/**
* Try to cast the {@link IJCOBridgeReflected} instance into {@link TimerEventSubscription}, a cast assert is made to check if types are compatible.
*/
public static TimerEventSubscription cast(IJCOBridgeReflected from) throws Throwable {
NetType.AssertCast(classType, from);
return new TimerEventSubscription(from.getJCOInstance());
}
// Constructors section
public TimerEventSubscription() throws Throwable {
}
public TimerEventSubscription(Guid workflowInstanceId, DateTime expiresAt) throws Throwable {
try {
// add reference to assemblyName.dll file
addReference(JCOBridgeInstance.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
setJCOInstance((JCObject)classType.NewObject(workflowInstanceId == null ? null : workflowInstanceId.getJCOInstance(), expiresAt == null ? null : expiresAt.getJCOInstance()));
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public TimerEventSubscription(Guid timerId, Guid workflowInstanceId, DateTime expiresAt) throws Throwable {
try {
// add reference to assemblyName.dll file
addReference(JCOBridgeInstance.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
setJCOInstance((JCObject)classType.NewObject(timerId == null ? null : timerId.getJCOInstance(), workflowInstanceId == null ? null : workflowInstanceId.getJCOInstance(), expiresAt == null ? null : expiresAt.getJCOInstance()));
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
// Methods section
// Properties section
public DateTime getExpiresAt() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject val = (JCObject)classInstance.Get("ExpiresAt");
return new DateTime(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public Guid getSubscriptionId() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject val = (JCObject)classInstance.Get("SubscriptionId");
return new Guid(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public Guid getWorkflowInstanceId() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject val = (JCObject)classInstance.Get("WorkflowInstanceId");
return new Guid(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public IComparable getQueueName() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject val = (JCObject)classInstance.Get("QueueName");
return new IComparableImplementation(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setQueueName(IComparable QueueName) throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("QueueName", QueueName == null ? null : QueueName.getJCOInstance());
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
// Instance Events section
} | [
"[email protected]"
] | |
1ab6efbf671b748e30e8900e09da515fe0046957 | c4dc36a42f3117cee8b74d30682ce1bbdd803a65 | /src/main/java/console/app/Service/PublicationServiceImpl.java | d96895fd4f55882bb4862c9266f4e3ca14668363 | [] | no_license | zhnurbekov/consoleApp | 01b8998605d0e5f1d4a5275e77f6ebde0b9c4a06 | e842bd2b0f7463640d2c48e4c04d69762bfa5e7d | refs/heads/master | 2021-07-22T22:23:31.969006 | 2017-10-31T19:05:26 | 2017-10-31T19:05:26 | 108,812,149 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 15,190 | java | package console.app.Service;
import console.app.database.dao.AbstractDao;
import console.app.database.dao.impl.BookDaoImpl;
import console.app.database.dao.impl.BrochureDaoImpl;
import console.app.database.dao.impl.JournalDaoImpl;
import console.app.database.dao.impl.PublicationsDaoImpl;
import console.app.database.entity.BookEntity;
import console.app.database.entity.BrochureEntity;
import console.app.database.entity.JournalEntity;
import console.app.database.entity.PublicationsEntity;
import java.io.IOException;
import java.util.*;
public class PublicationServiceImpl implements PublicationService {
@Override
public String getCommand() {
List<String> commands = new ArrayList<>();
commands.add("1");
commands.add("2");
commands.add("3");
commands.add("4");
commands.add("5");
System.out.println("Для дальнейших действий выберите пункт и введите цифру\n");
System.out.println("1.Просмотр зарегистрированных изданий в фонде");
System.out.println("2.Добавление нового издания в фонд");
System.out.println("3.Просмотр информации выбранного издания");
System.out.println("4.Удаление выбранного издания");
System.out.println("5.Выход ");
Scanner in = new Scanner(System.in, "cp866");
String inputText = in.nextLine();
while (!commands.contains(inputText)) {
System.out.println("Введенные данные не верны, пожалуйста введите заново");
inputText = in.nextLine();
}
return inputText;
}
@Override
public void getPublicationsList() {
clearScreen();
System.out.println("\nЗарегистрированные изданий в фонде\n");
System.out.println("+----+---------+-------------------+------+----------+-----------------+");
System.out.printf("%-5s%-10s%-20s%-7s%-11s%-15s%n",
"| # ", "| Тип", "| Наименование", "| Год ", "|Кол-во стр", "| Издательство");
PublicationsDaoImpl publicationsDao = new PublicationsDaoImpl();
for (PublicationsEntity list : publicationsDao.getList()) {
String type = publicationsDao.publicationType(list.getPublication_type());
System.out.println("+----+---------+-------------------+------+----------+-----------------+");
System.out.printf("%-5s%-10s%-20s%-7s%-11s%-15s%n",
"| " + list.getId(), "| " + type, "| " + list.getName(), "| " + list.getYear()
, "| " + list.getCount_pages(), "| " + list.getPublishing_house());
}
System.out.println("+----+---------+-------------------+------+----------+-----------------+");
}
@Override
public String getPublications() {
clearScreen();
System.out.println("Введите идентификатор");
Scanner in = new Scanner(System.in, "cp866");
String inputText = in.nextLine();
clearScreen();
try {
AbstractDao abstractDao = new PublicationsDaoImpl();
int publicationId = Integer.parseInt(inputText);
PublicationsEntity pub = (PublicationsEntity) abstractDao.get(publicationId);
if (pub.getPublication_type() == 1) {
abstractDao = new BookDaoImpl();
BookEntity book = (BookEntity) abstractDao.get(publicationId);
System.out.println("+-----------------------------+--------------------------------------+");
System.out.printf("%-30s%-40s%n", "| Идентификатор ", "| " + pub.getId());
System.out.println("+-----------------------------+--------------------------------------+");
System.out.printf("%-30s%-40s%n", "| Автор ", "| " + lineBreak(book.getAuthor()));
System.out.println("+-----------------------------+--------------------------------------+");
System.out.printf("%-30s%-40s%n", "| Наименование книги ", "| " + lineBreak(pub.getName()));
System.out.println("+-----------------------------+--------------------------------------+");
System.out.printf("%-30s%-40s%n", "| Год издательства ", "| " + pub.getYear());
System.out.println("+-----------------------------+--------------------------------------+");
System.out.printf("%-30s%-40s%n", "| Количество страниц ", "| " + pub.getCount_pages());
System.out.println("+-----------------------------+--------------------------------------+");
System.out.printf("%-30s%-40s%n", "| Издательство ", "| " + lineBreak(pub.getPublishing_house()));
System.out.println("+-----------------------------+--------------------------------------+");
System.out.printf("%-30s%-40s%n", "| Жанр книги ", "| " + lineBreak(book.getGenre()));
System.out.println("+-----------------------------+--------------------------------------+");
System.out.printf("%-30s%-40s%n", "| Краткое содержание", "| " + lineBreak(book.getSummary()));
System.out.println("+-----------------------------+--------------------------------------+");
} else if (pub.getPublication_type() == 2) {
abstractDao = new JournalDaoImpl();
JournalEntity journal = (JournalEntity) abstractDao.get(publicationId);
System.out.println("+-----------------------------+--------------------------------------+");
System.out.printf("%-30s%-40s%n", "| Наименование журнала ", "| " + lineBreak(pub.getName()));
System.out.println("+-----------------------------+--------------------------------------+");
System.out.printf("%-30s%-40s%n", "| Год издательства ", "| " + pub.getYear());
System.out.println("+-----------------------------+--------------------------------------+");
System.out.printf("%-30s%-40s%n", "| Месяц издательства ", "| " + pub.getMonth());
System.out.println("+-----------------------------+--------------------------------------+");
System.out.printf("%-30s%-40s%n", "| Количество страниц ", "| " + pub.getCount_pages());
System.out.println("+-----------------------------+--------------------------------------+");
System.out.printf("%-30s%-40s%n", "| Издательство ", "| " + lineBreak(pub.getPublishing_house()));
System.out.println("+-----------------------------+--------------------------------------+");
System.out.printf("%-30s%-40s%n", "| Список статей ", "| " + lineBreak(journal.getArticle_list()));
System.out.println("+-----------------------------+--------------------------------------+");
} else {
abstractDao = new BrochureDaoImpl();
BrochureEntity brochure = (BrochureEntity) abstractDao.get(publicationId);
System.out.println("+-----------------------------+--------------------------------------+");
System.out.printf("%-30s%-40s%n", "| Наименование брошюры ", "| " + lineBreak(pub.getName()));
System.out.println("+-----------------------------+--------------------------------------+");
System.out.printf("%-30s%-40s%n", "| Год издательства ", "| " + pub.getYear());
System.out.println("+-----------------------------+--------------------------------------+");
System.out.printf("%-30s%-40s%n", "| Месяц издательства ", "| " + pub.getMonth());
System.out.println("+-----------------------------+--------------------------------------+");
System.out.printf("%-30s%-40s%n", "| Издательство ", "| " + lineBreak(pub.getPublishing_house()));
System.out.println("+-----------------------------+--------------------------------------+");
System.out.printf("%-30s%-40s%n", "| Краткое описание брошюры ", "| " + lineBreak(brochure.getDescription()));
System.out.println("+-----------------------------+--------------------------------------+");
}
} catch (Exception E) {
System.out.println("Вы ввели неправильный идентификатор");
}
return inputText;
}
@Override
public String insert() {
clearScreen();
System.out.println("Выберите к какой категорий относится издание");
System.out.println("1.Книга");
System.out.println("2.Журнал");
System.out.println("3.Брошюра");
Scanner in = new Scanner(System.in, "cp866");
String inputText = in.nextLine();
int type = Integer.parseInt(inputText);
if (type == 1 || type == 2 || type == 3) {
PublicationsEntity pub = new PublicationsEntity();
PublicationsDaoImpl publicationsDao = new PublicationsDaoImpl();
System.out.println("Введите название ");
pub.setName(in.nextLine());
pub.setYear(getInputInteger("Введите год издательства"));
pub.setPublication_type(type);
if (type == 1) {
pub.setCount_pages(getInputInteger("Введите количество страниц"));
} else if (type == 2) {
pub.setMonth(getInputInteger("Введите месяц издательства в формате '05 , 06 , 07'"));
pub.setCount_pages(getInputInteger("Введите количество страниц"));
} else {
pub.setMonth(getInputInteger("Введите месяц издательства в формате '05 , 06 , 07'"));
}
System.out.println("Введите название издательство");
pub.setPublishing_house(in.nextLine());
int publicationId = publicationsDao.insert(pub);
AbstractDao abstractDao;
switch (type){
case 1:
abstractDao = new BookDaoImpl();
BookEntity bookEntity = new BookEntity();
System.out.println("Введите автора книги");
bookEntity.setAuthor(in.nextLine());
System.out.println("Введите жанр книги");
bookEntity.setGenre(in.nextLine());
System.out.println("Введите краткое содержание");
bookEntity.setSummary(in.nextLine());
bookEntity.setId_publication(publicationId);
abstractDao.insert(bookEntity);
break;
case 2:
abstractDao = new JournalDaoImpl();
JournalEntity journalEntity = new JournalEntity();
System.out.println("Введите список статей опубликованный в данном журнале");
journalEntity.setArticle_list(in.nextLine());
journalEntity.setId_publications(publicationId);
abstractDao.insert(journalEntity);
break;
case 3:
abstractDao = new BrochureDaoImpl();
BrochureEntity brochureEntity = new BrochureEntity();
System.out.println("Введите краткое описание");
brochureEntity.setDescription(in.nextLine());
brochureEntity.setId_publications(publicationId);
abstractDao.insert(brochureEntity);
break;
}
clearScreen();
System.out.println("Издательство успешно добавлено");
} else {
System.out.println("Данные которые вы ввели не правильно");
System.out.println("Введите заново");
}
return inputText;
}
@Override
public void delete() {
clearScreen();
System.out.println("Введите идентификатор издания");
Scanner in = new Scanner(System.in, "cp866");
String inputText = in.nextLine();
clearScreen();
try {
int publicationId = Integer.parseInt(inputText);
AbstractDao abstractDao = new PublicationsDaoImpl();
PublicationsEntity pub = (PublicationsEntity) abstractDao.get(publicationId);
switch (pub.getPublication_type()){
case 1: abstractDao = new BookDaoImpl(); break;
case 2: abstractDao = new JournalDaoImpl(); break;
case 3: abstractDao = new BrochureDaoImpl(); break;
}
abstractDao.delete(publicationId);
abstractDao = new PublicationsDaoImpl();
abstractDao.delete(publicationId);
System.out.println("Издательства успешно удалено");
} catch (Exception e) {
System.out.println("Вы ввели неправильный идентификатор");
System.out.println("Введите заново");
}
}
private int getInputInteger(String text) {
Scanner in = new Scanner(System.in, "cp866");
System.out.println(text);
while (true) {
String inputText = in.nextLine();
try {
return Integer.parseInt(inputText);
} catch (Exception e) {
System.out.println("Не правильный формат введенных данных");
System.out.println("Введите заново");
}
}
}
public static void clearScreen() {
try {
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public String lineBreak(String str) {
String string;
String indentation = "| | ";
if (str.length() < 40) {
string = str;
} else {
String stringOne = str.substring(0, 39);
string = stringOne + "\n" + indentation + str.substring(39, 75) + " ...";
}
return string;
}
}
| [
"[email protected]"
] | |
72672f79eb6b0aefa631307e69d3b4e9ed899e65 | c13ec7e826d23c7efffa6b16bd36723c4660f70f | /Shalom/src/com/yattatech/domain/Husband.java | 5fcffadd0e2f38f9e12cfeedb80999be0d07706e | [
"Apache-2.0"
] | permissive | adrianobragaalencar/ShalomSeminary | e980c3194f6860278c1001e35184019d0e12cc5d | 0fd56f5ef26f5a5bc097690a84a06694ce23f336 | refs/heads/master | 2021-01-13T01:40:23.607705 | 2015-04-28T17:15:27 | 2015-04-28T17:15:27 | 34,743,667 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 328 | java | /*
* Copyright (c) 2013, Yatta Tech and/or its affiliates. All rights reserved.
* YATTATECH PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package com.yattatech.domain;
/**
* Husband domain
*
* @author Adriano Braga Alencar ([email protected])
*/
public final class Husband extends Person {
}
| [
"[email protected]"
] | |
3403362394e4eb0a24d875b576eacb8f1d2ba22e | bef6c8ad3738603b4f0ed9f344c1ca2da263b9a7 | /src/main/java/com/taylietech/engcollege/config/SecurityConfig.java | 6fd61cce27d92d120890cb8ef963a66fa7cc3369 | [] | no_license | BranfordTGbieor/eng-college | b35b13544f8163d09ed3106e9fc86ce419aa8f54 | f87bb02f8bab0dbf61f71cea4508df45e2c817d6 | refs/heads/master | 2020-12-30T08:29:58.959292 | 2020-03-03T14:31:52 | 2020-03-03T14:31:52 | 238,929,831 | 1 | 2 | null | null | null | null | UTF-8 | Java | false | false | 3,437 | java | package com.taylietech.engcollege.config;
import com.taylietech.engcollege.service.impl.UserSecurityService;
import com.taylietech.engcollege.util.LoginHandler;
import com.taylietech.engcollege.util.CustomLogoutHandler;
import com.taylietech.engcollege.util.SecurityUtility;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private Environment env;
@Autowired
private UserSecurityService userSecurityService;
@Autowired
LoginHandler loginHandler;
@Autowired
CustomLogoutHandler customLogoutHandler;
private BCryptPasswordEncoder passwordEncoder() {
return SecurityUtility.passwordEncoder();
}
public static final String[] PUBLIC_MATCHERS = {
"/css/**",
"/js/**",
"/lib/**",
"/images/**",
"/fonts/**",
"/static/**",
"/assets/**",
"/",
"/login",
"/register",
"/about",
"/newUser",
"/contact",
"/resetPasswordPage",
"/userDetails",
"/electrical",
"/civil",
"/geology",
"/mining",
"/research",
"/stem",
"/innovation",
"/resources",
"/blog",
"/campus",
"/sendMessage",
"/subscribe"
};
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.authorizeRequests()
// .antMatchers("/**")
.antMatchers(PUBLIC_MATCHERS)
.permitAll().anyRequest().authenticated();
httpSecurity
.csrf().disable().cors().disable()
.formLogin().failureUrl("/login?error").defaultSuccessUrl("/")
.loginPage("/login").permitAll()
.successHandler(loginHandler)
.and()
.logout().addLogoutHandler(customLogoutHandler)
//.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/?logout").deleteCookies("remember-me").permitAll()
.and()
.rememberMe()
.and()
.httpBasic()
.and()
.sessionManagement()
.maximumSessions(1)
.expiredUrl("/login");
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userSecurityService).passwordEncoder(passwordEncoder());
}
}
| [
"[email protected]"
] | |
4f5e6eab6645c4ad7cba9d6b635840d13f35f88c | b606bb811a26c905726ea6dc10a79307147d4b76 | /src/_23_门面模式/section3/ILetterProcess.java | c8b00de019d62fb00ac9637b21221fe4121ae9c1 | [] | no_license | c437yuyang/ZenOfDesignPatterns | 794a615d2621ac324ce81e8298afc8dcfa3c55e6 | 48d3e71ad1000aec0723125626f3e2a7282098fa | refs/heads/master | 2023-03-17T05:45:31.317055 | 2018-02-03T13:42:50 | 2018-02-03T13:42:50 | 343,474,642 | 0 | 0 | null | null | null | null | GB18030 | Java | false | false | 402 | java | package _23_门面模式.section3;
/**
* @author cbf4Life [email protected]
* I'm glad to share my knowledge with you all.
*/
public interface ILetterProcess {
//首先要写信的内容
public void writeContext(String context);
//其次写信封
public void fillEnvelope(String address);
//把信放到信封里
public void letterInotoEnvelope();
//然后邮递
public void sendLetter();
}
| [
"[email protected]"
] | |
5272a2e617ddad7ec672fcd97eacc0232f3d90de | a8cc5276b1a87793c4340dfa476e0355047a9dce | /src/com/gaodig/source/provider/test.java | 40aabc1513306b491e0398d76dfc447c4fef233c | [] | no_license | vipsql/zkMonitor | c8de7e0b3d39a14f22f6881a27d6395e986148aa | 6486e0faed5b2b3cba5bdfaab780f2d1c8ee0001 | refs/heads/master | 2021-01-09T09:06:30.969446 | 2016-09-19T12:37:36 | 2016-09-19T12:37:36 | 68,597,137 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 220 | java | package com.gaodig.source.provider;
import org.apache.commons.lang3.StringUtils;
public class test {
public static void main(String[] args){
String a = "0.5";
System.out.println(StringUtils.isNumeric(a));
}
}
| [
"[email protected]"
] | |
462c43d2d00ca62ffbdabaf1303505107f81e024 | 5cc166c240bf6e0b319f99beeb9bad3c1f707104 | /src/main/java/com/citi/training/PortfolioManager/services/TransactionService.java | 3a1682891833e7aba50f3ecec26debf78a01b633 | [] | no_license | matthewcaceres/Portfolio-Manager | 4edb5d90927794893dc94e755298bd84141a1810 | 4956aa1b8567902b5fe20e4f603cf1b64a012120 | refs/heads/master | 2023-07-15T13:45:34.281048 | 2021-08-27T18:13:48 | 2021-08-27T18:13:48 | 395,666,169 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 451 | java | package com.citi.training.PortfolioManager.services;
import com.citi.training.PortfolioManager.entities.Transaction;
import java.util.List;
public interface TransactionService {
List<Transaction> getAllTransactions();
Transaction getTransactionById (int id);
Transaction addTransaction (Transaction transaction);
Transaction updateTransaction (Transaction transaction);
void deleteTransaction (Transaction transaction);
}
| [
"[email protected]"
] | |
3d218a249644ab4e732fd5c25b1e1096e14a6c22 | b21bde6568bd9cdf1ab6e00dadc6b05a756f157a | /src/main/java/cn/linter/oasys/mapper/AttendanceMapper.java | a73324b533018da5878b373177e543e7a6743742 | [] | no_license | cctvbtx/OASys | 2b7d9b4aa9bef6d3a4339f15a8519760080f4327 | a49af488c29f2da425a15d70fbc2897a80340d39 | refs/heads/master | 2022-10-06T11:14:25.327251 | 2020-06-07T06:08:58 | 2020-06-07T06:08:58 | 277,034,068 | 1 | 0 | null | 2020-07-04T03:52:43 | 2020-07-04T03:52:42 | null | UTF-8 | Java | false | false | 757 | java | package cn.linter.oasys.mapper;
import cn.linter.oasys.entity.Attendance;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
@Mapper
public interface AttendanceMapper {
void updateAttendanceTime(@Param("begin") String begin, @Param("end") String end);
Map<String, String> selectAttendanceTime();
List<String> selectAttendances(@Param("userId") int userId);
Attendance selectAttendance(@Param("userId") int userId, @Param("date") String date);
void signIn(@Param("userId") int userId, @Param("date") String date, @Param("time") String time);
void signOut(@Param("userId") int userId, @Param("date") String date, @Param("time") String time);
}
| [
"[email protected]"
] | |
451612ffb763e73a99414bf346e4fee3147673ba | 03b48fe109dc65a2b0526104c501756910580cd3 | /Authorization/src/main/java/com/authorizationservice/authorization/repository/AuthRequestRepo.java | 7bb3ebe9652008dfde04c3069a6703045be524f7 | [] | no_license | RishabhGupta15/ReturnOrder | 78b615716eafe71d0fadd0056462d133ec46cd6b | 0055088e12e89daabf57889abd913d8ca50adf2d | refs/heads/main | 2023-08-05T16:29:37.893780 | 2021-10-05T22:08:15 | 2021-10-05T22:08:15 | 412,396,477 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 352 | java | package com.authorizationservice.authorization.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.authorizationservice.authorization.model.AuthenticationRequest;
public interface AuthRequestRepo extends JpaRepository<AuthenticationRequest, String> {
public AuthenticationRequest findByUserName(String userName);
}
| [
"[email protected]"
] | |
b5460fa62bd041b42a1cb96f23771d1b45e2b282 | f3073ed112bf411ceaeafefc482a05604d9c1319 | /app/src/main/java/com/qingwing/safebox/net/response/GetWebTimeResponse.java | a54185b7af5c74c769b303cf5bc3af7f81179750 | [] | no_license | shoxgov/UserApp_AS_2 | ab20fc6935fc99643b167fa227b866d617e0ad24 | ce892818fbc2072fda38aec52c614a9f17f30328 | refs/heads/master | 2021-08-22T12:28:54.632535 | 2017-11-30T06:32:37 | 2017-11-30T06:32:37 | 109,775,934 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 806 | java | package com.qingwing.safebox.net.response;
import com.qingwing.safebox.net.BaseResponse;
public class GetWebTimeResponse extends BaseResponse {
private String message;
private String status;
private DataMap dataMap;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public DataMap getDataMap() {
return dataMap;
}
public void setDataMap(DataMap dataMap) {
this.dataMap = dataMap;
}
public class DataMap{
private String severTime;
public String getSeverTime() {
return severTime;
}
public void setSeverTime(String severTime) {
this.severTime = severTime;
}
}
}
| [
"[email protected]"
] | |
2489f80e90959cdd7a6c444e7e7f276dbf18e29b | f8a7ce11ea86ebc74cfc6843d8f62c1e8c8548d9 | /app/src/main/java/com/odang/beatbot/track/BaseTrack.java | ad7d7cccb6bda540512bf7541c65ae84a735b0ef | [] | no_license | khiner/BeatBot | db4fc8fcda3bf059602010f4b459fca7a5a1a28a | ba09532f64ed18946a8ee378394b6b4ad93bc244 | refs/heads/master | 2022-06-21T07:26:42.639911 | 2022-06-19T03:41:36 | 2022-06-19T03:56:14 | 3,988,954 | 3 | 1 | null | null | null | null | UTF-8 | Java | false | false | 4,752 | java | package com.odang.beatbot.track;
import com.odang.beatbot.effect.Effect;
import com.odang.beatbot.effect.Param;
import com.odang.beatbot.listener.ParamListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static com.odang.beatbot.ui.view.View.context;
public class BaseTrack {
public static final String MASTER_TRACK_NAME = "Master";
protected int id;
protected List<Effect> effects = new ArrayList<>();
public Param volumeParam, panParam, pitchStepParam, pitchCentParam;
public BaseTrack() {
}
public BaseTrack(final int id) {
this.id = id;
volumeParam = new Param(0, "Vol").withUnits("Db").withLevel(Param.dbToView(0));
panParam = new Param(1, "Pan").scale(2).add(-1).withLevel(.5f);
pitchStepParam = new Param(2, "Pit").scale(96).add(-48).withLevel(.5f).snap()
.withUnits("st");
pitchCentParam = new Param(3, "Cent").add(-.5f).withLevel(.5f).withUnits("cent");
volumeParam.addListener(new ParamListener() {
public void onParamChange(Param param) {
setTrackVolume(getId(), param.level);
}
});
panParam.addListener(new ParamListener() {
public void onParamChange(Param param) {
setTrackPan(getId(), param.level);
}
});
pitchStepParam.addListener(new ParamListener() {
public void onParamChange(Param param) {
setTrackPitch(getId(), param.level + pitchCentParam.level);
}
});
pitchCentParam.addListener(new ParamListener() {
public void onParamChange(Param param) {
setTrackPitch(getId(), pitchStepParam.level + param.level);
}
});
}
public void resetToDefaults() {
while (!effects.isEmpty()) {
effects.get(0).destroyWithoutNotify();
}
setLevels(Param.dbToView(0), .5f, .5f, .5f);
}
public int getId() {
return id;
}
public String getName() {
return MASTER_TRACK_NAME;
}
public String getFormattedName() {
return getName();
}
public List<Effect> getEffects() {
return effects;
}
public void addEffect(Effect effect) {
effects.add(effect);
context.getTrackManager().onEffectCreate(this, effect);
}
public void removeEffect(Effect effect) {
removeEffectWithoutNotify(effect);
context.getTrackManager().onEffectDestroy(this, effect);
}
public void removeEffectWithoutNotify(Effect effect) {
effects.remove(effect);
}
public void moveEffect(int oldPosition, int newPosition) {
Effect effect = findEffectByPosition(oldPosition);
if (effect != null) {
effect.setPosition(newPosition);
}
for (Effect other : effects) {
if (other.equals(effect))
continue;
if (other.getPosition() >= newPosition && other.getPosition() < oldPosition) {
other.setPosition(other.getPosition() + 1);
} else if (other.getPosition() <= newPosition && other.getPosition() > oldPosition) {
other.setPosition(other.getPosition() - 1);
}
}
Collections.sort(effects);
Effect.setEffectPosition(id, oldPosition, newPosition);
context.getTrackManager().onEffectOrderChange(this, oldPosition, newPosition);
}
public void quantizeEffectParams() {
for (Effect effect : effects) {
effect.quantizeParams();
}
}
public Effect findEffectByPosition(int position) {
for (Effect effect : effects) {
if (effect.getPosition() == position) {
return effect;
}
}
return null;
}
public Param getVolumeParam() {
return volumeParam;
}
public Param getPanParam() {
return panParam;
}
public Param getPitchParam() {
return pitchStepParam;
}
public Param getPitchCentParam() {
return pitchCentParam;
}
public void select() {
context.getTrackManager().onSelect(this);
}
public void setLevels(float volume, float pan, float pitchStep, float pitchCent) {
context.getTrackManager().notifyTrackLevelsSetEvent(this);
volumeParam.setLevel(volume);
panParam.setLevel(pan);
pitchStepParam.setLevel(pitchStep);
pitchCentParam.setLevel(pitchCent);
}
private native void setTrackVolume(int trackId, float volume);
private native void setTrackPan(int trackId, float pan);
private native void setTrackPitch(int trackId, float pitchSteps);
}
| [
"[email protected]"
] | |
3b0b8ccde5bffdbcffe660bc2231455648276d7f | 12986d42a87934ef711f0b9aa6cdcfd00fb8ca9f | /src/main/java/com/zking/mapper/SysUserMapper.java | aa9fa1790461b231c5b51e91d0577153579fd5a0 | [] | no_license | 9983/IDEA_WorkSpace1 | 3ca3d3473e92b8cd93b16558d6ac82079b6f1640 | 6446cf02ed79968c6e72e48cc49a8c250f3a1293 | refs/heads/master | 2022-11-27T07:17:22.066879 | 2020-08-05T11:27:57 | 2020-08-05T11:27:57 | 285,208,646 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 685 | java | package com.zking.mapper;
import com.zking.model.SysUser;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.Set;
@Repository
public interface SysUserMapper {
int deleteByPrimaryKey(Integer userid);
int insert(SysUser record);
int insertSelective(SysUser record);
SysUser selectByPrimaryKey(Integer userid);
int updateByPrimaryKeySelective(SysUser record);
int updateByPrimaryKey(SysUser record);
SysUser userlogin(@Param("username") String username);
Set<String> findrole(@Param("username") String username);
Set<String> findpermission(@Param("username") String username);
} | [
"[email protected]"
] | |
ef17fa43a33f5a07741cb0609fadb23847c7a954 | a43184ee4bed533202a5f1fa1f62451f1d05eca1 | /problem/2887/src/Main.java | fa955bc45553ff07957c9b7d2903c6943977522f | [] | no_license | seonho-kim/baekjoon | 23eca6d0b15340cb595961d6ab090f7f877349f5 | c69dba333d001bf1bc0204ca4739667d1636c40a | refs/heads/master | 2020-05-09T22:53:16.269380 | 2019-12-04T14:24:11 | 2019-12-04T14:24:11 | 181,484,956 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,986 | java | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;
public class Main {
static int N;
static Planet[] planet;
static int[] p;
static Edge[] e;
public static void main(String[] args) throws IOException {
System.setIn(new FileInputStream("./src/input.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st;
N = Integer.parseInt(br.readLine());
planet = new Planet[N];
p = new int[N];
e = new Edge[3*N-3];
for (int i = 0; i < N; i++) {
int x, y, z;
st = new StringTokenizer(br.readLine());
x = Integer.parseInt(st.nextToken());
y = Integer.parseInt(st.nextToken());
z = Integer.parseInt(st.nextToken());
planet[i] = new Planet(x, y, z, i);
p[i] = -1;
}
Arrays.sort(planet, new Comparator<Planet>() {
@Override
public int compare(Planet o1, Planet o2) {
if (o1.x < o2.x) return -1;
else if (o1.x > o2.x) return 1;
else return 0;
}
});
for (int i = 0; i < N-1; i++) {
e[i] = new Edge(planet[i].num,
planet[i+1].num,
Math.abs(planet[i].x - planet[i+1].x));
}
Arrays.sort(planet, new Comparator<Planet>() {
@Override
public int compare(Planet o1, Planet o2) {
if (o1.y < o2.y) return -1;
else if (o1.y > o2.y) return 1;
else return 0;
}
});
for (int i = 0; i < N-1; i++) {
e[N-1 + i] = new Edge(planet[i].num,
planet[i+1].num,
Math.abs(planet[i].y - planet[i+1].y));
}
Arrays.sort(planet, new Comparator<Planet>() {
@Override
public int compare(Planet o1, Planet o2) {
if (o1.z < o2.z) return -1;
else if (o1.z > o2.z) return 1;
else return 0;
}
});
for (int i = 0; i < N-1; i++) {
e[2*N-2 + i] = new Edge(planet[i].num,
planet[i+1].num,
Math.abs(planet[i].z - planet[i+1].z));
}
Arrays.sort(e);
int result = 0, cnt = 0;
for (int i = 0; ; i++) {
if (union(e[i].u, e[i].v)) {
result += e[i].w;
if (++cnt == N-1) break;
}
}
bw.write(result + "\n");
bw.flush();
}
static int find(int a) {
if (p[a] < 0) return a;
return p[a] = find(p[a]);
}
static boolean union(int a, int b) {
a = find(a);
b = find(b);
if (a == b) return false;
p[b] = a;
return true;
}
static class Edge implements Comparable<Edge> {
int u, v, w;
public Edge(int u, int v, int w) {
this.u = u;
this.v = v;
this.w = w;
}
@Override
public int compareTo(Edge o) {
if (this.w < o.w) return -1;
else if (this.w > o.w) return 1;
else return 0;
}
}
static class Planet {
int x, y, z, num;
public Planet(int x, int y, int z, int num) {
this.x = x;
this.y = y;
this.z = z;
this.num = num;
}
}
} | [
"[email protected]"
] | |
26694d930dc4b0215a35e0d7147381d84ee5d3c4 | fff2cfad9d0b591afad77c3a68cd0e999a368d9b | /src/jpl/mipl/mdms/FileService/komodo/util/InvocationCommandUtil.java | 79386eb6631c98dedffed4fd4c35a7e151083c4d | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | nasa/FEI | 961d8b263c2c6683a006a79467d4b271a1d1da75 | 68a1cd59d354fa807f0316f9d2f092838a391207 | refs/heads/master | 2023-08-17T12:25:32.993256 | 2023-08-09T19:46:00 | 2023-08-09T19:46:00 | 125,108,227 | 4 | 4 | null | null | null | null | UTF-8 | Java | false | false | 7,707 | java | package jpl.mipl.mdms.FileService.komodo.util;
import java.io.File;
import jpl.mipl.mdms.FileService.komodo.api.Result;
/**
* <b>Purpose:</b>
* Utility for invocation commands, primarily creates instances of command
* after substituting command variables with values.
*
* If a variable has not value, then it will be printed as 'NULL'.
*
* <PRE>
* Copyright 2008, California Institute of Technology.
* ALL RIGHTS RESERVED.
* U.S. Government Sponsorship acknowledge. 2008.
* </PRE>
*
* <PRE>
* ============================================================================
* <B>Modification History :</B>
* ----------------------
*
* <B>Date Who What</B>
* ----------------------------------------------------------------------------
* 04/13/2006 Nick Initial Release
* 04/08/2008 Nick Added $fileLocation for server-side file
* path
* ============================================================================
* </PRE>
*
* @author Nicholas Toole ([email protected])
* @version $Id: InvocationCommandUtil.java,v 1.4 2008/04/23 17:57:58 ntt Exp $
*
*/
public class InvocationCommandUtil
{
public static final String NULL_STR = "NULL";
//---------------------------------------------------------------------
//invocation variable regex's
protected static final String REGEX_FILENAME_NO_PATH = "\\$(f|F)(i|I)(l|L)(e|E)(n|N)(a|A)(m|M)(e|E)(n|N)(o|O)(p|P)(a|A)(t|T)(h|H)";
protected static final String REGEX_FILENAME = "\\$(f|F)(i|I)(l|L)(e|E)(n|N)(a|A)(m|M)(e|E)";
protected static final String REGEX_FILEPATH = "\\$(f|F)(i|I)(l|L)(e|E)(p|P)(a|A)(t|T)(h|H)";
protected static final String REGEX_FILETYPE = "\\$(f|F)(i|I)(l|L)(e|E)(t|T)(y|Y)(p|P)(e|E)";
protected static final String REGEX_SERVER_GROUP = "\\$(s|S)(e|E)(r|R)(v|V)(e|E)(r|R)(g|G)(r|R)(o|O)(u|U)(p|P)";
protected static final String REGEX_COMMENT = "\\$(c|C)(o|O)(m|M)(m|M)(e|E)(n|N)(t|T)";
protected static final String REGEX_REMOTE_LOCATION = "\\$(r|R)(e|E)(m|M)(o|O)(t|T)(e|E)(l|L)(o|O)(c|C)(a|A)(t|T)(i|I)(o|O)(n|N)";
//---------------------------------------------------------------------
/**
* Given the invocation string and a set of values, replaces instances of
* variable names in string with corresponding values if provided.
*
* @param command Invocation command string
* @param filenameNoPath Filename without path prefix
* @param filename Complete path of the file
* @param filepath Directory containing file
* @param filetype Name of the FEi filetype
* @param serverGroup Name of the FEI server group
* @param comment Comment associated with file
* @param remoteLocation Server-side filepath location of the file
* @return command string with variable names replaced with values
*/
public static final String buildCommand(String command, String filenameNoPath,
String filename, String filepath,
String filetype, String serverGroup,
String comment, String remoteLocation)
{
//if null command, then can't do anything really, return empty string
if (command == null)
return "";
//check for nulls, replace with null string
if (filetype == null)
filetype = NULL_STR;
if (serverGroup == null)
serverGroup = NULL_STR;
if (comment == null)
comment = NULL_STR;
if (remoteLocation == null)
remoteLocation = NULL_STR;
//see if we can salvage file info from any of the bits
if (filename == null)
{
if (filepath != null && filenameNoPath != null)
filename = filepath + File.separator + filenameNoPath;
}
else if (filepath == null || filenameNoPath == null)
{
File tmpFile = new File(filename);
if (filepath == null)
filepath = tmpFile.getParentFile().getAbsolutePath();
if (filenameNoPath == null)
filenameNoPath = tmpFile.getName();
}
//if any fileparts are still null, then set to null string
if (filename == null)
filename = NULL_STR;
if (filepath == null)
filepath = NULL_STR;
if (filenameNoPath == null)
filenameNoPath = NULL_STR;
//--------------------------
//translate Windows separators to preserve em
filename = filename.replaceAll("\\\\", "\\\\\\\\");
filepath = filepath.replaceAll("\\\\", "\\\\\\\\");
//perform the substitutions
String cmdStr = command;
cmdStr = cmdStr.replaceAll(REGEX_FILENAME_NO_PATH, filenameNoPath);
cmdStr = cmdStr.replaceAll(REGEX_FILENAME, filename);
cmdStr = cmdStr.replaceAll(REGEX_FILEPATH, filepath);
cmdStr = cmdStr.replaceAll(REGEX_FILETYPE, filetype);
cmdStr = cmdStr.replaceAll(REGEX_SERVER_GROUP, serverGroup);
cmdStr = cmdStr.replaceAll(REGEX_COMMENT, comment);
cmdStr = cmdStr.replaceAll(REGEX_REMOTE_LOCATION, remoteLocation);
//return result
return cmdStr;
}
//---------------------------------------------------------------------
/**
* Given the invocation string and a set of values, replaces instances of
* variable names in string with corresponding values if provided.
* @param command Invocation command string
* @param directory Directory containing file (will be overriden if
* result has local location value)
* @param result Result object associated with file
* @return command string with variable names replaced with values
*/
public static final String buildCommand(String command, String directory,
Result result)
{
String cmdStr;
//if null command, then can't do anything really, return empty string
if (command == null || directory == null || result == null)
return "";
String location = directory;
if (result.getLocalLocation() != null)
location = result.getLocalLocation();
//call the other buildCommand with data from result
String name = result.getName();
cmdStr = buildCommand(command, name,
location + File.separator + name,
location, result.getType(),
result.getServerGroup(),
result.getComment(),
result.getRemoteLocation());
//return result
return cmdStr;
}
//---------------------------------------------------------------------
/**
* Given the invocation string and a set of values, replaces instances of
* variable names in string with corresponding values if provided.
* @param command Invocation command string
* @param result Result object associated with file
* @return command string with variable names replaced with values
*/
private static final String buildCommand(String command, Result result)
{
return buildCommand(command, result.getLocalLocation(), result);
}
//---------------------------------------------------------------------
}
| [
"[email protected]"
] | |
e3b11f5b1396f131747b090f847b3b0c257718d2 | 96d8dcbbd1fbb95c63f4b49fd8c66e4b468aa0fa | /src/minecraft/net/minecraft/src/ChunkCoordIntPair.java | 7d831f628f67339273078cb5fe25880fd1d3cd90 | [] | no_license | moderatorman/Client | 381132c36a4ee8d955441a56f939f4fc1e56c8d8 | 354d4a2d3801f8fd45818d823dab9e327b361338 | refs/heads/master | 2022-04-03T21:14:24.768200 | 2020-02-04T03:17:13 | 2020-02-04T03:17:13 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 904 | java | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) braces deadcode
// Source File Name: SourceFile
package net.minecraft.src;
public class ChunkCoordIntPair
{
public ChunkCoordIntPair(int i, int j)
{
chunkXPos = i;
chunkZPos = j;
}
public static int chunkXZ2Int(int i, int j)
{
return (i >= 0 ? 0 : 0x80000000) | (i & 0x7fff) << 16 | (j >= 0 ? 0 : 0x8000) | j & 0x7fff;
}
public int hashCode()
{
return chunkXZ2Int(chunkXPos, chunkZPos);
}
public boolean equals(Object obj)
{
ChunkCoordIntPair chunkcoordintpair = (ChunkCoordIntPair)obj;
return chunkcoordintpair.chunkXPos == chunkXPos && chunkcoordintpair.chunkZPos == chunkZPos;
}
public final int chunkXPos;
public final int chunkZPos;
}
| [
"[email protected]"
] | |
1bbd3b3891789565f5f1552cad01d348734f77ed | ff3ea92c8e8b9f52f0ad88bd22d01928330d00b8 | /Analyst/src/test/java/PathogenScoreListTest.java | 5abe01ae13e1fe2a355a75a43ec93bf85a88d49e | [] | no_license | benarnon/WWH-BioApp | 25b7c4a223c63410fc2a1d5e74771cf7e1fc18a2 | 078d14f3f35be638cdc99cbc9616f9bb48bdeb7b | refs/heads/master | 2021-01-10T14:07:45.932774 | 2015-06-30T10:30:22 | 2015-06-30T10:30:22 | 29,177,312 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,619 | java | import junit.framework.TestCase;
public class PathogenScoreListTest extends TestCase {
public void testAddPathogen() throws Exception {
PathogenScoreList pathogenScoreList = new PathogenScoreList(3);
assertEquals(pathogenScoreList.getNumOfFiles(),3);
pathogenScoreList.addPathogen("testPathogen");
pathogenScoreList.addPathogen("testPathogen2");
PathogenScores tmp = pathogenScoreList.getPathogenScore("testPathogen");
PathogenScores tmp2 = pathogenScoreList.getPathogenScore("testPathogen2");
assertEquals(tmp.getName(),"testPathogen");
assertEquals(tmp2.getName(),"testPathogen2");
}
public void testIsContain() throws Exception {
PathogenScoreList pathogenScoreList = new PathogenScoreList(3);
assertEquals(pathogenScoreList.getNumOfFiles(),3);
pathogenScoreList.addPathogen("testPathogen");
assertEquals(pathogenScoreList.isContain("testPathogen"),0);
assertEquals(pathogenScoreList.isContain("Notexist"),-1);
}
public void testAddScore() throws Exception {
PathogenScoreList pathogenScoreList = new PathogenScoreList(3);
pathogenScoreList.addPathogen("testPathogen");
PathogenScores tmp = pathogenScoreList.getPathogenScore("testPathogen");
float a = (float) 0.5;
pathogenScoreList.addScore("testPathogen",a,1);
assertEquals(pathogenScoreList.getPathogenScore("testPathogen").getScore(1),(float)0.5);
System.out.println();
assertEquals(pathogenScoreList.getPathogenScore("testPathogen").getScore(2),(float)0);
}
} | [
"[email protected]"
] | |
386391a883a502d8557e923503bc2fa905f079e7 | 668496e4beee69591f98c5738a75f972093b805d | /carnival-spring-boot-starter-localization-china/src/main/java/com/github/yingzhuo/carnival/localization/china/jsr349/PhoneNumber.java | c6e3ffedf46561be590fea160913657fe1da6784 | [
"Apache-2.0"
] | permissive | floodboad/carnival | ca1e4b181746f47248b0f3d82a54f6fe4c31b41f | 9e18d5ce4dbc1e518102bc60ac13954156d93bd2 | refs/heads/master | 2023-01-04T07:18:35.514865 | 2020-10-28T04:15:31 | 2020-10-28T04:15:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 924 | java | /*
* ____ _ ____ _ _ _____ ___ _
* / ___| / \ | _ \| \ | |_ _\ \ / / \ | |
* | | / _ \ | |_) | \| || | \ \ / / _ \ | |
* | |___/ ___ \| _ <| |\ || | \ V / ___ \| |___
* \____/_/ \_\_| \_\_| \_|___| \_/_/ \_\_____|
*
* https://github.com/yingzhuo/carnival
*/
package com.github.yingzhuo.carnival.localization.china.jsr349;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
/**
* @author 应卓
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
@Constraint(validatedBy = PhoneNumberValidator.class)
public @interface PhoneNumber {
public String message() default "{com.github.yingzhuo.carnival.localization.china.jsr349.PhoneNumber.message}";
public Class<?>[] groups() default {};
public Class<? extends Payload>[] payload() default {};
}
| [
"[email protected]"
] | |
d025d05b0ca38b7de3f1c5469368d716c30732bf | 10375c8ec06ea434b3ede171c79f1d534249ad3a | /Sachin/app/src/main/java/com/sachin/sachin/Checkout.java | aabc9a089b266f4ae426dbc4f96cce02e7249da7 | [] | no_license | samurailens/LPFS | 1adb9800b1699b86187badb71aa9faf4ccb76608 | 8eb53b954942ad7b1e94e4af18b069ddda18bbb6 | refs/heads/master | 2021-01-10T03:57:19.659029 | 2016-01-11T14:31:21 | 2016-01-11T14:31:21 | 45,131,100 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 13,300 | java | package com.sachin.sachin;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.util.ArrayList;
import java.util.List;
public class Checkout extends Activity {
String selectedSizeTxt ;
String TAG = "Checkout";
ArrayAdapter myAdapter;
ListView orderList;
List< String> orderIdsFromDb;
List<String> listTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checkout);
orderIdsFromDb = new ArrayList<String>();
updateCart();
updateOrderIds();
}
public void updateCart(){
int size = MainActivity.mydbmanager.getAllOrders().size();
List list = MainActivity.mydbmanager.getAllOrders() ;
listTitle = new ArrayList<String>();
if(list.size() > 0 ) {
for (int i = 0; i < size; i++) {
Log.d(TAG, list.get(i).toString());
try {
JSONObject jsonObj = new JSONObject(list.get(i).toString());
//listTitle.add(i, jsonObj.toString());
listTitle.add(jsonObj.toString());
//orderIdsFromDb.add("");
Log.d(TAG, "Add = " + jsonObj.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}else {
Log.d(TAG,"list size is zero ");
}
myAdapter = new shoppingCartCustomArrayAdapter(this, listTitle);
//myAdapter = new ArrayAdapter(this, R.layout.row_layout, R.id.listText, listTitle);
orderList = (ListView) findViewById(R.id.checkoutorderlist);
orderList.setAdapter(myAdapter);
orderList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.d(TAG, "Item clicked position " + String.valueOf(position));
Object dataClicked = (Object) orderList.getItemAtPosition(position);
}
});
//myAdapter = new ArrayAdapter(this, R.layout.row_layout, R.id.listText, listTitle);
//getListView().setOnItemClickListener(this);
//setListAdapter(myAdapter);
}
public void updateOrderIds(){
//Map of OrderIDs
List listOrderIds = MainActivity.mydbmanager.getAllOrdersIds();
if(listOrderIds.size() > 0 ) {
for (int i = 0; i < listOrderIds.size(); i++) {
Log.d(TAG, listOrderIds.get(i).toString());
try {
//JSONObject jsonObj = new JSONObject(listOrderIds.get(i).toString());
//listTitle.add(i, jsonObj.toString());
String s = listOrderIds.get(i).toString();
orderIdsFromDb.add(s);
Log.d(TAG, "Add OrderIds" + s);
} catch (Exception e) {
e.printStackTrace();
}
}
}else {
Log.d(TAG,"listOrderIds size is zero ");
}
}
public void deleteFromCart(View v){
View parentRow = (View) v.getParent();
TextView orderId = (TextView) parentRow.findViewById(R.id.CVtextViewForOrderID);
String id = orderId.getText().toString();
//todo find the id n sendfor delete
int indexofHash = id.lastIndexOf("#");
String orderID = id.substring(indexofHash+1);
Log.d(TAG, "deleteFromCart orderID = " + id + "\t " +orderID);
MainActivity.cartNewOrder.clear();
/*
ListView listView = (ListView) parentRow.getParent();
final int position = listView.getPositionForView(parentRow);
((shoppingCartCustomArrayAdapter)myAdapter).deleteItem(position);
String idToDel = orderIdsFromDb.get(position);
try {
int noofRowsEffected = MainActivity.mydbmanager.deleteOrder(Integer.parseInt(idToDel));
Log.d(TAG, "Delete from DB " + idToDel + "Row Del " + String.valueOf(noofRowsEffected));
}catch (SQLiteException e){
e.printStackTrace();
}
if(position == 0) {
MainActivity.cartNewOrder.clear();
}
updateCart();
Log.d(TAG, "Delete from cart " + String.valueOf(position) );
*/
}
public void selectSize(View v){
String setTxt = "Done";
String btntxt = "";
Button btn = (Button) findViewById(R.id.Sizebtn); //selectSize
btntxt = btn.getText().toString();
if(btntxt.contains("Select Size")){
// previously invisible view
View myView = findViewById(R.id.sizelistView);
// get the center for the clipping circle
int cx = myView.getWidth() / 2;
int cy = myView.getHeight() / 2;
// get the final radius for the clipping circle
int finalRadius = Math.max(myView.getWidth(), myView.getHeight());
// create the animator for this view (the start radius is zero)
Animator anim =
ViewAnimationUtils.createCircularReveal(myView, cx, cy, 0, finalRadius);
// make the view visible and start the animation
myView.setVisibility(View.VISIBLE);
anim.start();
btn.setText(setTxt);
}else {
//Done
// previously visible view
final View myView = findViewById(R.id.sizelistView);
// get the center for the clipping circle
int cx = myView.getWidth() / 2;
int cy = myView.getHeight() / 2;
// get the initial radius for the clipping circle
int initialRadius = myView.getWidth();
// create the animation (the final radius is zero)
Animator anim =
ViewAnimationUtils.createCircularReveal(myView, cx, cy, initialRadius, 0);
// make the view invisible when the animation is done
anim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
myView.setVisibility(View.INVISIBLE);
}
});
// start the animation
anim.start();
RadioGroup radioSexGroup = null;
RadioButton radioSexButton = null;
radioSexGroup=(RadioGroup)findViewById(R.id.radiogroupsizelist);
int selectedId=radioSexGroup.getCheckedRadioButtonId();
radioSexButton=(RadioButton)findViewById(selectedId);
//Toast.makeText(this,radioSexButton.getText(), Toast.LENGTH_SHORT).show();
TextView selectedSize = (TextView) findViewById(R.id.selectedSizetxtView);
if(selectedSize != null && radioSexButton !=null){
selectedSizeTxt = radioSexButton.getText().toString();
selectedSize.setText("Selected " + radioSexButton.getText());
selectedSize.setTextColor(Color.parseColor("#83EB6D"));
selectedSize.setVisibility(View.VISIBLE);
}
//selectedSize.setBackgroundColor(Color.parseColor("#83EB6D"));
btn.setText("Select Size");
}
}
public void placeOrder(View v){
//Go to home
SendMail sendMail = new SendMail();
String orderDetails = "";
String toEmailAddress = MainActivity.activeUserEmail;
if( !toEmailAddress.contains("@")){
Toast.makeText(this, "Sign in to place your order", Toast.LENGTH_LONG).show();
startActivity(new Intent(this, MainActivity.class));
}
listTitle.size();
List<String > OrderListToSend = new ArrayList<String>();
try{
for(int i=0 ; i< listTitle.size(); i++){
Object a = listTitle.get(i);
a.hashCode();
Log.d(TAG, "Object " + a.toString());
Object json = new JSONTokener(a.toString()).nextValue();
if (json instanceof JSONObject) {
//you have an object
Object designName = ((JSONObject) json).get("designName");
Object fabricName = ((JSONObject) json).get("fabricName");
Object fabricFabCost = ((JSONObject) json).get("fabricFabCost");
Object designCost = ((JSONObject) json).get("designCost");
int totalCost = Integer.parseInt(fabricFabCost.toString()) + Integer.parseInt(designCost.toString());
String tempOrder = "\n\n<p> <b> Design : " + designName + " </b> \t Price : <b> Rs."+ designCost + "</b></p>"+ "\n<p><b>Fabric : " + fabricName + "</b>\t Price : <b>Rs." + fabricFabCost + "</b> </p>"+ "\n\n<p>Total : Rs."+ String.valueOf(totalCost) + "</p>\n\n" ;
OrderListToSend.add(tempOrder);
orderDetails += tempOrder ;
//holder.textView.setText("Design: " + designName.toString() + "\nFabric: " + fabricName.toString() ); //+ " Rs." + String.valueOf(i)
//holder.orderCost.setText("Rs."+ String.valueOf(i));
}
else if (json instanceof JSONArray) {
//you have an array
Object b = ((JSONArray) json).get(0);
b.hashCode();
}
}
List listOrderIds = MainActivity.mydbmanager.getAllOrdersIds();
if(listOrderIds.size() > 0 ) {
for (int i = 0; i < listOrderIds.size(); i++) {
MainActivity.mydbmanager.updateStatus(String.valueOf(ORDER_STATUS.ORDER_PLACED_TO_STORE), listOrderIds.get(i).toString());
}
}
//JSONArray ar = new JSONArray(getItem(position));
// KO Object [] a = getItem(position).toArray();
//KO String s = getItem(position).toString();
//KO JSONObject jsonObj = new JSONObject(getItem(position));
/* JSONObject jsonObj = new JSONObject(getItem(position).toString());
holder.textView.setText(jsonObj.getString("designName"));
Log.d(TAG, "Populate the text position: " + String.valueOf(position) + "\t val: " + jsonObj.getString("designName"));
JSON*/
}catch (Exception e){
e.printStackTrace();
}
if(OrderListToSend.size() > 0) {
sendMail.sendMail(toEmailAddress, "Your order on Le Pape store", orderDetails);//orderDetails);
startActivity(new Intent(this, MainActivity.class));
Toast.makeText(this, "Order placed.", Toast.LENGTH_LONG).show();
MainActivity.cartNewOrder.clear();
}else{
Toast.makeText(this, "Nothing to order.", Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_checkout, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed(){
super.onBackPressed();
String oID = MainActivity.cartNewOrder.getOrderID();
Log.d(TAG, "onBackPressed " +oID );
if(oID != null && oID.isEmpty()){
Log.d(TAG, "starting design activity");
Intent intent = new Intent(this, Designs.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
//startActivity(new Intent(this, Designs.class));
}else {
}
}
} | [
"[email protected]"
] | |
d73935f3a1c6a3d97dd51afb50cbd4960a6b754d | b7d1bc22dd82a8899f03db49f3d3ad4593a9774f | /src/top/kaoshanji/source/com/sun/corba/se/spi/activation/InitialNameService.java | 399e0a40b3fb434e11bb7c90cef661abd2c46738 | [] | no_license | kaoshanji/JdkSourceLearn | d238a5f4ac2d790724392c1fbd59164718ebe22d | 8eea2e95b3df18ae114854fd0ea666c0279a53d8 | refs/heads/master | 2021-05-24T09:35:59.348371 | 2020-04-06T13:11:13 | 2020-04-06T13:11:13 | 253,499,639 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 519 | java | package com.sun.corba.se.spi.activation;
/**
* com/sun/corba/se/spi/activation/InitialNameService.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from /HUDSON/workspace/8-2-build-linux-amd64/jdk8u231/13620/corba/src/share/classes/com/sun/corba/se/spi/activation/activation.idl
* Saturday, October 5, 2019 3:01:48 AM PDT
*/
public interface InitialNameService extends InitialNameServiceOperations, org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity
{
} // interface InitialNameService
| [
"[email protected]"
] | |
c2bcc812046448f11cfb8b749840b30ddf107efd | 49e30f1b9927a3f2f34497307913ed6728fb5056 | /src/com/zqds/client/util/DateUtil.java | 907d98382d54ac1cbe01d842a61adace23957677 | [] | no_license | kailIII/android | 579cfcfe9ccebd29bb4c2cc6dc7d30227286d3d9 | 13d0e981ee787bf6e93430e7e7748107f14d5b5e | refs/heads/master | 2020-12-31T03:16:13.265326 | 2015-11-11T03:04:01 | 2015-11-11T03:04:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,380 | java | package com.zqds.client.util;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.Set;
import android.annotation.SuppressLint;
/**
* FileName : DateUtil.java
* Description : 时间工具类
* @Copyright : Keai Software Co.,Ltd.Rights Reserved
* @Company : 可爱医生网络技术有限公司
* @author : 向春发
* @version : 1.0
* Create Date : 2015-7-1
**/
@SuppressLint("ParserError")
public class DateUtil {
public final static String timeFormat1 = "yyyy-MM-dd HH:mm:ss";
public final static String timeFormat2 = "yyyy-MM-dd HH:mm";
public final static String timeFormat3 = "MM-dd HH:mm";
public final static String timeFormat4 = "yyyy";
public final static String timeFormat5 = "HH:mm:ss";
/**
* 将当前时间 转换成 yyyy-MM-dd HH:mm:ss形式输出
* @return
*/
@SuppressLint("SimpleDateFormat")
public static String formatDate() {
String dateStr = "";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
dateStr = df.format(date);
return dateStr;
}
/**
* 日期转换成字符串
* @param date
* @return str
*/
@SuppressLint("SimpleDateFormat")
public static String DateToStr(Date date, String pattern) {
String str = null;
try {
SimpleDateFormat format = new SimpleDateFormat(pattern);
str = format.format(date);
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
/**
* 时间字符串转换成指定格式的时间字符串
*
* @param str 时间字符串
* @param pattern 时间格式
* @return str
*/
public static String strToStr(String time, String pattern) {
return DateToStr(StrToDate(time, pattern), pattern);
}
/**
* 字符串转换成日期
* @param str
* @return date
*/
@SuppressLint("SimpleDateFormat")
public static Date StrToDate(String str) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = format.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
/**
* 字符串转换成指定格式的日期
* @param str
* @return pattern:日期格式
*/
@SuppressLint("SimpleDateFormat")
public static Date StrToDate(String str, String pattern) {
if (str == null || pattern == null) {
return null;
}
SimpleDateFormat format = new SimpleDateFormat(pattern);
Date date = null;
try {
date = format.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
/**
* 将yyyy-MM-dd HH:mm:ss 转换成 yyyy-MM-dd形式输出
* @return
*/
@SuppressLint("SimpleDateFormat")
public static String strTostr1(String time) {
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
String date = null;
try {
date = sdf2.format(sdf2.parse(time));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return date;
}
/**
* 根据用户传入的时间,返回指定格式的时间
* @param time 格式为yyyy-MM-dd HH:mm:ss
* @param sformat 转换后的格式
*
* @return
*/
@SuppressLint("SimpleDateFormat")
public static String getDate(String time,String sformat) {
String dateString = "";
try {
SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date currentTime = formatter.parse(time);
SimpleDateFormat formatterdd = new SimpleDateFormat(sformat);
dateString = formatterdd.format(currentTime);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dateString;
}
public static long addTime(int field, int value) {
Calendar cal = Calendar.getInstance();
cal.add(field, value);
return cal.getTimeInMillis();
}
public static long addTime(Date baseTime, int field, int value) {
return addTime(baseTime.getTime(), field, value);
}
public static long addTime(long baseTime, int field, int value) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(baseTime);
cal.add(field, value);
return cal.getTimeInMillis();
}
public static long dateDiff(long startDate, long endDate) {
return endDate - startDate;
}
//
// public static long dateDiff(java.util.Date startDate, java.util.Date endDate) {
// long d1 = (startDate == null) ? 0 : startDate.getTime();
// long d2 = (endDate == null) ? 0 : endDate.getTime();
// return dateDiff(d1, d2);
// }
public static long dateDiff(String startDate, String endDate) {
long d1 = getTimeMS(startDate), d2 = getTimeMS(endDate);
return dateDiff(d1, d2);
}
/**
* 根据日期格式(yyyy-MM-dd)得到年、月、日
* @param 字段值:年、月、日
*/
@SuppressLint({ "ParserError", "ParserError" })
public static int parseDate(String date,int field){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = GregorianCalendar.getInstance();
try {
calendar.setTime(sdf.parse(date));
} catch (ParseException e) {
System.out.println(e);
}
int size=calendar.get(field);
if(field==Calendar.MONTH){
size+=1;
}
return size;
}
/**
* 日期运算类
* 如果为-1表示是减
*
* @param field
* @param value
* @param date
*/
@SuppressLint("SimpleDateFormat")
public static String addDate(String date, int field, int value) {
GregorianCalendar gc = new GregorianCalendar();
SimpleDateFormat sf = new SimpleDateFormat(timeFormat1);
Date tempDate = null;
try {
tempDate = sf.parse(date);
} catch (ParseException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
gc.setTime(tempDate);
gc.add(field, value);
return sf.format(gc.getTime());
}
/**
* 根据开始时间与结束时间获取月份列表
*
* @param startTime
* 开始时间
* @param endTime
* 结束时间
* @return 月份列表
*/
public static Set<String> getMonths(String startTime, String endTime) {
String time = null;
String mTempTime = DateUtil.getDate(startTime, "yyyy-MM");
Set<String> months = new HashSet<String>();
String mEndTime = DateUtil.getDate(endTime, "yyyy-MM");
while (!mEndTime.equals(mTempTime)) {
months.add(mTempTime);
time = addDate(startTime, 2, 1);
mTempTime = DateUtil.getDate(time, "yyyy-MM");
startTime = time;
}
months.add(mEndTime);
return months;
}
/**
* 获取指定格式的时间
*
* @param format
* 时间格式
*/
@SuppressLint("SimpleDateFormat")
public static String getDate(String format) {
Calendar c = Calendar.getInstance();
SimpleDateFormat f = new SimpleDateFormat(format);
return f.format(c.getTime());
}
/**
* 获取指定格式的时间
*
* @param format 时间格式
*/
@SuppressLint("SimpleDateFormat")
public static String getDate(long time, String format) {
SimpleDateFormat f = new SimpleDateFormat(format);
return f.format(time);
}
/**
* 获取指定时间的毫秒数
*
* @param format 时间格式
*/
@SuppressLint("SimpleDateFormat")
public static long getTimeMS(String time) {
GregorianCalendar gc = new GregorianCalendar();
SimpleDateFormat sf = new SimpleDateFormat(timeFormat1);
Date tempDate = null;
try {
tempDate = sf.parse(time);
} catch (ParseException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
gc.setTime(tempDate);
return gc.getTimeInMillis();
}
/**
* 毫秒转化成时分形式
*/
public static String formatTime(long ms) {
int ss = 1000;
int mi = ss * 60;
int hh = mi * 60;
long hour = ms / hh;
long minute = (ms - hour * hh) / mi;
long second = (ms - minute * mi - hour * hh) / 1000;
return hour + ":" + minute + ":" + second;
}
}
| [
"[email protected]"
] | |
4d6ca94ff0cc1cfbf6d92498c37eacef43fcbbf7 | 8fdd1ed7a7580368ef39f1bfa4d66afdb0798f43 | /dida_demo/src/main/java/com/dida/first/activity/ShaiDanSelectActivity.java | 4699bedd1b436623775597204ae5375298fe3e81 | [] | no_license | KingJA/DidaDemoAS | a0980785700d7299631c9a71f1483e195d93f645 | d68311723a96869acfdcc50e2b3ce27c42c9235c | refs/heads/master | 2021-01-10T16:43:44.882381 | 2016-04-04T09:12:02 | 2016-04-04T09:12:02 | 55,398,031 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,917 | java | /**
*
*/
package com.dida.first.activity;
import com.dida.first.R;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* @author KingJA
* @data 2015-9-7 上午10:00:02
* @use
*
*/
public class ShaiDanSelectActivity extends BackTitleActivity {
private View inflate;
private RelativeLayout rl_info_aa;
private RelativeLayout rl_info_group;
private ImageView iv_info_group;
private ImageView iv_info_aa;
private TextView tv_info_aa;
private TextView tv_info_group;
private Button btn_info_confirm;
private LinearLayout ll_aa_info;
private LinearLayout ll_group_info;
@Override
public void setBackClick() {
finish();
}
public void reSet(){
iv_info_aa.setVisibility(View.GONE);
iv_info_group.setVisibility(View.GONE);
ll_aa_info.setVisibility(View.GONE);
ll_group_info.setVisibility(View.GONE);
tv_info_aa.setTextColor(getResources().getColor(R.color.black));
tv_info_group.setTextColor(getResources().getColor(R.color.black));
}
@Override
public void onChildClick(View v) {
switch (v.getId()) {
case R.id.rl_info_group:
reSet();
iv_info_group.setVisibility(View.VISIBLE);
ll_group_info.setVisibility(View.VISIBLE);
tv_info_group.setTextColor(getResources().getColor(R.color.red));
break;
case R.id.rl_info_aa:
reSet();
iv_info_aa.setVisibility(View.VISIBLE);
ll_aa_info.setVisibility(View.VISIBLE);
tv_info_aa.setTextColor(getResources().getColor(R.color.red));
break;
case R.id.btn_info_confirm:
//TODO 发布拼购的逻辑
Intent intent=new Intent(this,BuyActivity.class);
startActivity(intent);
finish();
break;
default:
break;
}
}
@Override
public View setView() {
inflate = View.inflate(this, R.layout.activity_shaidan_select, null);
return inflate;
}
@Override
public void initView() {
ll_aa_info = (LinearLayout) inflate.findViewById(R.id.ll_aa_info);
ll_group_info = (LinearLayout) inflate.findViewById(R.id.ll_group_info);
rl_info_aa = (RelativeLayout) inflate.findViewById(R.id.rl_info_aa);
rl_info_group = (RelativeLayout) inflate.findViewById(R.id.rl_info_group);
iv_info_group = (ImageView) inflate.findViewById(R.id.iv_info_group);
iv_info_aa = (ImageView) inflate.findViewById(R.id.iv_info_aa);
tv_info_aa = (TextView) inflate.findViewById(R.id.tv_info_aa);
tv_info_group = (TextView) inflate.findViewById(R.id.tv_info_group);
btn_info_confirm = (Button) inflate.findViewById(R.id.btn_info_confirm);
}
@Override
public void initEvent() {
rl_info_aa.setOnClickListener(this);
rl_info_group.setOnClickListener(this);
btn_info_confirm.setOnClickListener(this);
}
@Override
public void initDoNet() {
}
@Override
public void initData() {
setBackTitle("晒单");
}
}
| [
"[email protected]"
] | |
d7feb808402c8448615a951de8dcfbaad3d7e0d7 | 365adc5d80472b06f108a619ffa99d725a83b4d2 | /src/main/java/com/example/HomeController.java | 47d69233813d90bc901d871113fbe53e9c611891 | [] | no_license | muralidhar9e/testing-web | be5ee4a48f1b6f4222990c5712c2b49b405857e8 | 318a3e457d2aebd478d4090572e903ea284acf21 | refs/heads/master | 2022-06-08T01:17:01.148685 | 2020-05-04T11:03:29 | 2020-05-04T11:03:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 268 | java | package com.example;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HomeController {
@GetMapping("/")
public String greeting() {
return "Hello, World";
}
}
| [
"[email protected]"
] | |
ac7a45d1531fb1884f938b0346ae4c3f016f83ea | 3ddd2d12b3e5db7030179c55b100ed60ef9929d2 | /src/HMS/coptions.java | b27b3b507cb2eeedf820dd15547c979181b47350 | [] | no_license | bhargav944/NetBeans-HallManagementSystem | c33232367187fd7a7741812ada062e55d3e8cca2 | 2eb3d407e6dcf3099d9ccedef8b12fbe864f9614 | refs/heads/master | 2020-04-23T21:34:09.512052 | 2019-02-19T12:59:51 | 2019-02-19T12:59:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,048 | java | /*
* 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 HMS;
/**
*
* @author Gurramkonda Bhargav
*/
public class coptions extends javax.swing.JFrame {
/**
* Creates new form coptions
*/
public coptions() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel2 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton7 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
jLabel2.setText("CLUB LOGIN");
jButton1.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
jButton1.setText("VIEW HALLS");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
jButton2.setText("BOOK HALLS");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton7.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
jButton7.setText("Logout");
jButton7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton7ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(200, 200, 200)
.addComponent(jLabel2))
.addGroup(layout.createSequentialGroup()
.addGap(215, 215, 215)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(0, 245, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jButton7)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton7)
.addGap(64, 64, 64)
.addComponent(jLabel2)
.addGap(50, 50, 50)
.addComponent(jButton1)
.addGap(18, 18, 18)
.addComponent(jButton2)
.addContainerGap(168, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
this.hide();
new addhall().setVisible(true);
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
this.hide();
new booklog().setVisible(true);
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
this.hide();
new alog().setVisible(true);
}//GEN-LAST:event_jButton7ActionPerformed
/**
* @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(coptions.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(coptions.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(coptions.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(coptions.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new coptions().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton7;
private javax.swing.JLabel jLabel2;
// End of variables declaration//GEN-END:variables
}
| [
"[email protected]"
] | |
9c47527e853a6a48e5060c363ed02d6a237a8ea9 | 56b5e72b2eabfd1263d7eaa8e1e3cbfcbe201d90 | /src/test/java/net/lafox/demo/kalah/service/GameTestUtils.java | 71879f2097c6f7cf1c9ea96becf086f9684338ef | [] | no_license | AliceLafox/kalah | 790f6926f6356674bada7a54c9ead8c6d1377b72 | 94694b4120bb1fee5eabebefc0066ffeb106bc96 | refs/heads/master | 2021-05-10T13:14:02.141220 | 2018-01-22T19:42:02 | 2018-01-22T19:44:52 | 118,468,092 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 884 | java | package net.lafox.demo.kalah.service;
import net.lafox.demo.kalah.data.Game;
import net.lafox.demo.kalah.data.Player;
public class GameTestUtils {
public static Game createGame(int selectedHouse, int[] houses) {
Game game = new Game();
game.setHouses(houses);
game.setSelectedHouse(selectedHouse);
return game;
}
public static Game createGame(int lastSownHouse, int[] houses, Player player) {
Game game = new Game();
game.setHouses(houses);
game.setLastSownHouse(lastSownHouse);
game.setPlayer(player);
return game;
}
public static Game createGame(int lastSownHouse, int[] houses, int selectedHouse) {
Game game = new Game();
game.setHouses(houses);
game.setLastSownHouse(lastSownHouse);
game.setSelectedHouse(selectedHouse);
return game;
}
}
| [
"[email protected]"
] | |
7616fb6c7486eabe9fcc5fab1a6b057aac6e5f7d | d239bff5ef32a03b92ba7171cf2089d0026ad705 | /abi/src/main/java/org/chain3j/abi/datatypes/generated/Int200.java | 9185c102dedb1b492f819dfa525a0e720e4218c3 | [
"Apache-2.0"
] | permissive | LV0404/chain3j | 68520af0a6740029664cb9c4177a6d05f6fbba0b | 432327dbe41704946759daf6449b76614b594cee | refs/heads/master | 2021-10-19T15:51:26.891721 | 2019-02-22T08:44:45 | 2019-02-22T08:44:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 404 | java | package org.chain3j.abi.datatypes.generated;
import java.math.BigInteger;
import org.chain3j.abi.datatypes.Int;
/**
* Auto generated code.
*/
public class Int200 extends Int {
public static final Int200 DEFAULT = new Int200(BigInteger.ZERO);
public Int200(BigInteger value) {
super(200, value);
}
public Int200(long value) {
this(BigInteger.valueOf(value));
}
}
| [
"[email protected]"
] | |
519aff066e3aa307c4cbb0f1325b78a0115dbb00 | 5626effdabffd347c8c0840fa97ab213618fae04 | /src/com/athensoft/uaas/controller/LoginController.java | 89afe15400a355033da9e9cdc983e3dd7dfadfc5 | [] | no_license | info-athensoft/zshmtl | 06023556eb3e481addf87c770aba667324ebec32 | 5ef0b6411c184ec4180317f07e1e2e9e37d9033e | refs/heads/master | 2022-12-20T09:57:29.740268 | 2019-11-28T04:16:45 | 2019-11-28T04:16:45 | 131,600,907 | 0 | 0 | null | 2022-12-16T09:42:26 | 2018-04-30T13:44:00 | CSS | UTF-8 | Java | false | false | 2,159 | java | package com.athensoft.uaas.controller;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.athensoft.uaas.entity.UserAccount;
import com.athensoft.uaas.model.LoginAccountModel;
import com.athensoft.uaas.service.UserAccountService;
@Controller
public class LoginController {
private static final Logger logger = Logger.getLogger(LoginController.class);
@Autowired
private UserAccountService userAccountService;
@RequestMapping("/login.html")
public String gotoLogin(HttpSession session) {
logger.info("entering... gotoLogin");
String viewName = "member-signin";
logger.info("exiting... gotoLogin");
return viewName;
}
@RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json")
@ResponseBody
public Map<String, Object> doLogin(HttpSession session, @RequestBody LoginAccountModel loginAccount) {
logger.info("entering... doLogin");
UserAccount ua = new UserAccount();
ua.setAcctName(loginAccount.getUserName());
ua.setPassword(loginAccount.getPassword());
UserAccount userAccount = userAccountService.login(ua);
/* assemble data and view */
ModelAndView mav = new ModelAndView();
Map<String, Object> model = mav.getModel();
/* set data */
// model.put("userAccount", userAccount);
session.setAttribute("userAccount", userAccount);
/* set view */
// String viewName = "index";
logger.info("exiting... doLogin");
return model;
}
@RequestMapping("/logout")
public String doLogout(HttpSession session) {
logger.info("entering... doLogout");
session.removeAttribute("userAccount");
String viewName = "redirect:/member-signup.html";
logger.info("exiting... doLogout");
return viewName;
}
}
| [
"[email protected]"
] | |
dc58873a6eac98cd548b03d5d6213ae256ca282d | bccfa86096570c0e853cfa8d1459323971a5e88d | /src/lwjglproject/entities/gui/ButtonRect.java | affcf1844bf6cdb059676f7348f03f03d0198586 | [] | no_license | slow3586/LWJGLProject | 97514a2e23075f3b3e436ab829fc2309e078d042 | ef9c9fc40f7ef705a0598fa9ff98af7b0e0f9754 | refs/heads/main | 2023-08-15T11:20:36.083934 | 2021-10-10T13:23:23 | 2021-10-10T13:23:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 810 | java | package lwjglproject.entities.gui;
import lwjglproject.entities.*;
import lwjglproject.gl.*;
import lwjglproject.gl.shaders.SPSolidColor;
import org.joml.*;
public abstract class ButtonRect extends Button {
Vector4f color = new Vector4f(0.6f,0.6f,0.6f,0.5f);
Vector4f colorActive = new Vector4f(0.7f,0.7f,0.7f,0.7f);
public ButtonRect(Panel parent) {
super(parent);
}
@Override
public void draw(Camera cam){
if (!visible) return;
if(isMouseOver && !isDown){
SPSolidColor.draw(cam.getMat(), mat, colorActive, PanelRect.panelVA);
} else {
SPSolidColor.draw(cam.getMat(), mat, color, PanelRect.panelVA);
}
children.forEach((t) -> {
((Panel) t).draw(cam);
});
}
}
| [
"[email protected]"
] | |
7f7c1d3c64b923dcd095fdc55f35f668b3c9e4ec | 0551a40441b093bc4d61baecae9ab678fc790828 | /gulimall-order/src/main/java/com/james/gulimall/order/service/OrderReturnApplyService.java | 6babcf7600407e1c7d06be2db901e9f6c5b5a8cf | [] | no_license | Jamesjayedm/gulimall | e6496d1510b8c75468cd081c350e919eda68e725 | 4b8817775b5af6932ff155ac07445dbc1c7c87f4 | refs/heads/main | 2023-07-02T05:59:18.322715 | 2021-07-22T12:16:09 | 2021-07-22T12:16:09 | 323,590,406 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 479 | java | package com.james.gulimall.order.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.james.common.utils.PageUtils;
import com.james.gulimall.order.entity.OrderReturnApplyEntity;
import java.util.Map;
/**
* 订单退货申请
*
* @author pyj
* @email [email protected]
* @date 2020-12-28 18:20:44
*/
public interface OrderReturnApplyService extends IService<OrderReturnApplyEntity> {
PageUtils queryPage(Map<String, Object> params);
}
| [
"[email protected]"
] | |
4ae77ea2eddf08217d3b6b38c502f3e0f236755b | 93d880e7cce06430398f1e3af37bebea6eb040e8 | /GestorCitas/app/src/test/java/com/example/rafa/gestorcitas/ExampleUnitTest.java | d37bec8020b8e5dceffbacc980703e55d104df26 | [] | no_license | mapalper/proyectoMAPP | a4d3bb752c3510281750037bfb397c9d8374f948 | 29648f1e62f3ab6b7989926756098705108d760a | refs/heads/master | 2020-05-23T10:44:09.534410 | 2017-03-12T22:54:54 | 2017-03-12T22:54:54 | 84,762,923 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 406 | java | package com.example.rafa.gestorcitas;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
] | |
2d61be3ecb0d05b0d971c22ecef61c6b995b14cb | fcb61da71d618fd73d3f6f621ee60f81cde9e4ca | /src/uaslp/enginering/labs/list/model/Object.java | afe86f85e1a1167b6ac70187842c14ab3f018ce0 | [] | no_license | Nahum-png/ListParentEntity | f8cc49a0006646b24d469c3775a7574e2cc6ac40 | 6dfd1309990e74a625e84eed92b8aa05967888b0 | refs/heads/master | 2022-12-27T09:27:16.609363 | 2020-10-06T02:11:30 | 2020-10-06T02:11:30 | 301,196,183 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 288 | java | package uaslp.enginering.labs.list.model;
public class Object {
private String name;
public Object(String name ) {
this.name=name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
| [
"[email protected]"
] | |
4381d880490f2e2c1415c9ce5406a0a9a7ccf7fa | 096b7e7624ae9e69fd91097e3b0ac1b088631f86 | /Sami/ExercicesVacances/src/applicationIOperationIAffichage/TestComplexe.java | 91c22dc2e1281786a43931f9f326adc498619e55 | [] | no_license | sami-betka/java | 421062110911656d6c0f359020648286916edb44 | d9f689ecf54105b7acde7098f9ed07cde91da29b | refs/heads/master | 2020-04-13T13:02:49.587749 | 2019-01-03T20:29:35 | 2019-01-03T20:29:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 135 | java | package applicationIOperationIAffichage;
public class TestComplexe {
public static void main(String[] args) {
}
}
| [
"[email protected]"
] | |
75744c5c5c1f5988d8135bcf5cf176323da6e8d3 | 6212f1b9a489baba7e454a27e620fb622c68478a | /src/com/ing/zoo/strategies/HerbivorousStrategy.java | 640bcdc7b288e6acc24222b91c1bc7f74ca06e90 | [] | no_license | MauritsioRK/INGZoo | 4bf8d8586d298653a3b8d35785192a6db72b1bd9 | 3f2731787b62468d4c9df4fd6baccfab3acf765e | refs/heads/main | 2023-01-22T20:15:45.071477 | 2020-12-07T17:19:43 | 2020-12-07T17:19:43 | 319,281,615 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 408 | java | package com.ing.zoo.strategies;
public class HerbivorousStrategy implements IEatingStrategy {
public void eat(String food, String eatingPhrase) {
if (food.equals("leaves")) {
System.out.println(eatingPhrase);
} else if (food.equals("meat")) {
// Animal doesn't eat this food
} else {
// Animal doesn't know what this food is
}
}
}
| [
"[email protected]"
] | |
15abc4eca5cfca9b0d937296d8d87c75c8c6a7df | b0328c0b07ad16cf39d190320c1637d74f8049f1 | /AccountSystemLogic/src/main/java/za/ac/nwu/ac/logic/flow/CreateAccountTypeFlow.java | caeca20f1290f4dff017a07b8ec8dcb9d8c16f31 | [] | no_license | itzIggy/Pretorius_I_Project1_CMPG323 | e564fffcfbcd49dd225aafddef761acb6893b897 | dc99419f3a20dea51149c8a1184fc740d0790e8e | refs/heads/main | 2023-08-29T07:05:50.945280 | 2021-10-10T21:22:31 | 2021-10-10T21:22:31 | 409,110,819 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 194 | java | package za.ac.nwu.ac.logic.flow;
import za.ac.nwu.ac.domain.dto.AccountTypeDto;
public interface CreateAccountTypeFlow {
AccountTypeDto createAccountType(AccountTypeDto accountTypeDto);
}
| [
"[email protected]"
] | |
fc140ea4aa81e1974b23e4a7bf52bef6c8cd9e38 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/6/6_23e55d9754598b553377c78f3a39b1a65d9418a5/GradeCalculator/6_23e55d9754598b553377c78f3a39b1a65d9418a5_GradeCalculator_s.java | 258e707989e1b342cbb1484c9acb61183f361bc4 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 4,745 | java | /*
FileName:GradeCalculator
Name: Ryan Quinn
Date: October 30, 2011
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*; // import statement for borders
import javax.swing.event.*; // import statement for JSlider
import java.text.*;
public class GradeCalculator extends JFrame {
//Colors
Color black = new Color(0, 0, 0);
Color white = new Color(255, 255, 255);
JLabel gradeJLabel;
JTextField gradeJTextField;
JLabel enterStartJLabel;
JButton enterJButton;
JButton clearJButton;
int numberOfScores, accumulatorVariable = 0, scoreVariable, k = 0;
double averageScore;
String scoreAmount, score;
public GradeCalculator() {
createUserInterface();
}
private void createUserInterface() {
Container contentPane = getContentPane();
contentPane.setBackground(Color.white);
contentPane.setLayout(null);
gradeJLabel = new JLabel();
gradeJLabel.setBounds(50, 50, 120, 20);
gradeJLabel.setFont(new Font("Default", Font.PLAIN, 12));
gradeJLabel.setText("Grade:");
gradeJLabel.setForeground(black);
gradeJLabel.setHorizontalAlignment(JLabel.LEFT);
contentPane.add(gradeJLabel);
gradeJTextField = new JTextField();
gradeJTextField.setBounds(150, 50, 100, 20);
gradeJTextField.setFont(new Font("Default", Font.PLAIN, 12));
gradeJTextField.setHorizontalAlignment(JTextField.CENTER);
gradeJTextField.setForeground(black);
gradeJTextField.setBackground(white);
gradeJTextField.setEditable(false);
contentPane.add(gradeJTextField);
enterStartJLabel = new JLabel();
enterStartJLabel.setBounds(150, 250, 120, 20);
enterStartJLabel.setFont(new Font("Default", Font.PLAIN, 12));
enterStartJLabel.setText("Click enter to start!");
enterStartJLabel.setForeground(black);
enterStartJLabel.setHorizontalAlignment(JLabel.LEFT);
contentPane.add(enterStartJLabel);
enterJButton = new JButton();
enterJButton.setBounds(100, 300, 100, 20);
enterJButton.setFont(new Font("Default", Font.PLAIN, 9));
enterJButton.setText("Enter");
enterJButton.setForeground(black);
enterJButton.setBackground(white);
contentPane.add(enterJButton);
enterJButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
enterJButtonActionPerformed(event);
}
}
);
clearJButton = new JButton();
clearJButton.setBounds(225, 300, 100, 20);
clearJButton.setFont(new Font("Default", Font.PLAIN, 9));
clearJButton.setText("Clear");
clearJButton.setForeground(black);
clearJButton.setBackground(white);
contentPane.add(clearJButton);
clearJButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
clearJButtonActionPerformed(event);
}
}
);
setTitle("Grade Calculator");
setSize( 400, 400 );
setVisible(true);
}
public static void main(String[] args) {
GradeCalculator application = new GradeCalculator();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void enterJButtonActionPerformed(ActionEvent event) {
numberOfScores = getNumberOfScores();
getScores();
averageScore = calculateAverage();
printResults();
}
public int getNumberOfScores() {
scoreAmount = JOptionPane.showInputDialog("Number of scores to be entered?");
numberOfScores = Integer.parseInt(scoreAmount);
return numberOfScores;
}
public void getScores() {
do{
score = JOptionPane.showInputDialog("Please enter score:");
scoreVariable = Integer.parseInt(score);
accumulatorVariable += scoreVariable;
k++;
}while(k != numberOfScores);
}
public double calculateAverage() {
averageScore = accumulatorVariable / numberOfScores;
return averageScore;
}
public void printResults() {
if(averageScore > 89) {
gradeJTextField.setText("A");
}
else if(averageScore > 79) {
gradeJTextField.setText("B");
}
else if(averageScore > 69) {
gradeJTextField.setText("C");
}
else if(averageScore > 64) {
gradeJTextField.setText("D");
}
else if(averageScore <= 64) {
gradeJTextField.setText("F");
}
}
public void clearJButtonActionPerformed(ActionEvent event)
{
gradeJTextField.setText("");
gradeJTextField.requestFocusInWindow();
}
}
| [
"[email protected]"
] | |
d7c9f8ffba2f39723e73e8c236d8c6e425e0ad68 | aa838de17c9f37ec469689d55eb1f0a0c172ed69 | /eProjectLocal-ejb/src/java/entity/eproject/BrandsFacade.java | b1769a34d1b0fa3e24f6ac171e44adf5e99dd7cd | [] | no_license | lmphuong13100/eProject | 0eef151c5565a6e9a0cb25c8520c63db8221f8bf | eb6bcc0fc97dfbae368a4bd5e196d745aaaa320f | refs/heads/master | 2021-01-20T01:06:20.288390 | 2017-08-25T23:41:45 | 2017-08-25T23:41:45 | 101,280,820 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 733 | java | /*
* 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 entity.eproject;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* @author NONAME
*/
@Stateless
public class BrandsFacade extends AbstractFacade<Brands> implements BrandsFacadeLocal {
@PersistenceContext(unitName = "eProjectLocal-ejbPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public BrandsFacade() {
super(Brands.class);
}
}
| [
"NONAME@NONAME-PC"
] | NONAME@NONAME-PC |
4b142d634b5f9d71c476296294e667bca638926c | f499765fff55c0427eba72f7f9768193c4a4c520 | /cloud-api/src/main/java/cn/luckyqiang/cloudapi/BO/UserServiceBO.java | 98eb82ff28ba2428d68003b9f2562e9f6b704fa0 | [] | no_license | luckyqiang123/spring-cloud-example | d4b07b654dbffa8e248f00337c6b90caa10f64cf | 90c46bce2d5104c675b528acb006afe4d62af96b | refs/heads/master | 2020-07-31T19:47:26.132348 | 2019-09-25T11:02:03 | 2019-09-25T11:02:03 | 210,734,171 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,589 | java | package cn.luckyqiang.cloudapi.BO;
/**
* @author: zhangzj1103
* @company: www.chinaunicom.cn
* @Date: 2019/09/25 10:46
* @Description:
*/
public class UserServiceBO {
private Integer id;
private String userAddress;
private String userid;
private String consignee;
private String phoneNbr;
private String isDefault;
public UserServiceBO(Integer id, String userAddress, String userid, String consignee, String phoneNbr, String isDefault) {
this.id = id;
this.userAddress = userAddress;
this.userid = userid;
this.consignee = consignee;
this.phoneNbr = phoneNbr;
this.isDefault = isDefault;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserAddress() {
return userAddress;
}
public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getConsignee() {
return consignee;
}
public void setConsignee(String consignee) {
this.consignee = consignee;
}
public String getPhoneNbr() {
return phoneNbr;
}
public void setPhoneNbr(String phoneNbr) {
this.phoneNbr = phoneNbr;
}
public String getIsDefault() {
return isDefault;
}
public void setIsDefault(String isDefault) {
this.isDefault = isDefault;
}
}
| [
"[email protected]"
] | |
b0a2accd9aa827b2bc067645a025032780c111a4 | 26baa6a4f0bde23883e93309d9ad28e2feee23d1 | /opennms-dao/src/main/java/org/opennms/netmgt/dao/IpInterfaceDao.java | f2268c22a9bdf8144ec5874c198b40a9531eb077 | [] | no_license | taochong123456/opennms-1.10.12-1 | 6532544405fff3dddd96f1250775e48f2aa38f0f | 0f4c01a8e80e2144125eb189daac38a4e559421a | refs/heads/master | 2020-03-18T12:37:27.510530 | 2018-09-20T17:00:28 | 2018-09-20T17:00:28 | 134,734,970 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,618 | java | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2006-2012 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <[email protected]>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.dao;
import java.net.InetAddress;
import java.util.List;
import java.util.Map;
import org.opennms.netmgt.model.OnmsIpInterface;
import org.opennms.netmgt.model.OnmsNode;
/**
* <p>IpInterfaceDao interface.</p>
*
* @author Ted Kazmark
* @author David Hustace
* @author Matt Brozowski
*/
public interface IpInterfaceDao extends OnmsDao<OnmsIpInterface, Integer> {
/**
* <p>get</p>
*
* @param node a {@link org.opennms.netmgt.model.OnmsNode} object.
* @param ipAddress a {@link java.lang.String} object.
* @return a {@link org.opennms.netmgt.model.OnmsIpInterface} object.
*/
OnmsIpInterface get(OnmsNode node, String ipAddress);
/**
* <p>findByNodeIdAndIpAddress</p>
*
* @param nodeId a {@link java.lang.Integer} object.
* @param ipAddress a {@link java.lang.String} object.
* @return a {@link org.opennms.netmgt.model.OnmsIpInterface} object.
*/
OnmsIpInterface findByNodeIdAndIpAddress(Integer nodeId, String ipAddress);
/**
* <p>findByForeignKeyAndIpAddress</p>
*
* @param foreignSource a {@link java.lang.String} object.
* @param foreignId a {@link java.lang.String} object.
* @param ipAddress a {@link java.lang.String} object.
* @return a {@link org.opennms.netmgt.model.OnmsIpInterface} object.
*/
OnmsIpInterface findByForeignKeyAndIpAddress(String foreignSource, String foreignId, String ipAddress);
/**
* <p>findByIpAddress</p>
*
* @param ipAddress a {@link java.lang.String} object.
* @return a {@link java.util.Collection} object.
*/
List<OnmsIpInterface> findByIpAddress(String ipAddress);
/**
* <p>findByServiceType</p>
*
* @param svcName a {@link java.lang.String} object.
* @return a {@link java.util.Collection} object.
*/
List<OnmsIpInterface> findByServiceType(String svcName);
/**
* <p>findHierarchyByServiceType</p>
*
* @param svcName a {@link java.lang.String} object.
* @return a {@link java.util.Collection} object.
*/
List<OnmsIpInterface> findHierarchyByServiceType(String svcName);
/**
* Returns a map of all IP to node ID mappings in the database.
*
* @return a {@link java.util.Map} object.
*/
Map<InetAddress, Integer> getInterfacesForNodes();
OnmsIpInterface findPrimaryInterfaceByNodeId(Integer nodeId);
}
| [
"[email protected]"
] | |
f531ec3d60d5fb6fa919928210f1601a7be745c6 | 2592887b9df1b328ee1eaa97da803486532c62d4 | /readability_analysis/src/node_count/build_corpus/RankableContent.java | 3c6aebd04795bf532e922a6755c965c8a1b71c84 | [] | no_license | softwarekitty/regex_readability_study | f26cf78dee4c9e214711d32d3646b28d8f145e34 | f31a49b38e6f741f40e525867cb756cb8fdcefe4 | refs/heads/master | 2020-12-31T07:54:49.111082 | 2016-03-11T22:37:55 | 2016-03-11T22:37:55 | 50,367,513 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 216 | java | package node_count.build_corpus;
public interface RankableContent extends Comparable<RankableContent>{
public int getRankableValue();
public String getContent();
public int compareTo(RankableContent other);
}
| [
"[email protected]"
] | |
b41d972f4d6a88e419295767db675ca51ea3c1a0 | 480468b095569576619f0be736b3db20a5295987 | /app/src/main/java/com/coursera/app/pm/mascotitas/PerfilFragment.java | 6d522058afb663ad372f061afafc6fe25f9f3d33 | [] | no_license | calyr/Mascotitas | d44c854c4981e8bea3cb124c3295aa8472f38b86 | d4b4d6a72c5bc4b3e1af96873c45361194a99a4b | refs/heads/master | 2021-01-20T19:59:32.173933 | 2016-07-06T23:10:21 | 2016-07-06T23:10:21 | 62,094,120 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,104 | java | package com.coursera.app.pm.mascotitas;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
/**
* A simple {@link Fragment} subclass.
*/
public class PerfilFragment extends Fragment {
private ArrayList<Mascota> mascotas;
private RecyclerView rv;
public PerfilFragment() {
mascotas = new ArrayList<Mascota>();
mascotas.add(new Mascota(R.drawable.primero, "Rambo", 0));
mascotas.add(new Mascota(R.drawable.segundo, "Dina", 1));
mascotas.add(new Mascota(R.drawable.tercero, "Perla", 2));
mascotas.add(new Mascota(R.drawable.cuarto, "Steben", 3));
mascotas.add(new Mascota(R.drawable.quinto, "Choco", 3));
mascotas.add(new Mascota(R.drawable.sexto, "Filulay", 3));
mascotas.add(new Mascota(R.drawable.septimo, "Betoben", 3));
mascotas.add(new Mascota(R.drawable.octavo, "Mimo", 3));
}
private void inicializarListaMascotas() {
MascotaAdapter ada = new MascotaAdapter(mascotas, 1);
rv.setAdapter(ada);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_perfil, container, false);
rv = (RecyclerView) v.findViewById(R.id.rvMascotasPerfil);
GridLayoutManager glm = new GridLayoutManager(getActivity(), 3);
//LinearLayoutManager llm = new LinearLayoutManager( getActivity() );
//llm.setOrientation( LinearLayoutManager.VERTICAL );
rv.setLayoutManager(glm);
//rv.setLayoutManager(llm);
inicializarListaMascotas();
return v;
}
}
| [
"[email protected]"
] | |
fe28bd5338295f8afadc180c0519bd5b5f33cbb6 | 1e65caf92efccf52e44a65e0c26cf734eb9715f0 | /08_07/src/main/java/com/xzz/shangke/Impl/UserFunctionImpl.java | 18d2f1b49f2cc70a9c3f38e3c77514d2bb1ecd5f | [] | no_license | victory-zz/YQJava | 27207a9ef923a7cd1526261c88249aa89c78a208 | d3ad70d9af1e1982ac0af23bd3acd601d8c13397 | refs/heads/master | 2023-06-30T15:06:12.793337 | 2021-08-10T02:03:21 | 2021-08-10T02:03:21 | 393,585,131 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,884 | java | package com.xzz.shangke.Impl;
import com.xzz.shangke.User;
import com.xzz.until.JDBCUtils;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class UserFunctionImpl implements UserFunction {
/**
* 查询所有用户信息
* @return
* @throws SQLException
*/
@Override
public List<User> findAllUser() throws SQLException {
ResultSet resultSet = null;
String sql = "select * from user";
resultSet = JDBCUtils.select(sql);
List<User> userList = new ArrayList<User>();
while (resultSet.next()) {
User user = new User();
user.setUserId(resultSet.getInt("userId"));
user.setUserName(resultSet.getString("userName"));
user.setPassword(resultSet.getString("password"));
userList.add(user);
}
return userList;
}
/**
* 根据用户名和密码去查询某个用户
* @param uname
* @param pwd
* @return
* @throws SQLException
*/
@Override
public User findUser(String uname, String pwd) throws SQLException {
ResultSet resultSet = null;
User user = new User();
String sql = "select * from user where userName = '" + uname + "' and password = '" + pwd + "'";
resultSet = JDBCUtils.select(sql);
while (resultSet.next()) {
user.setUserId(resultSet.getInt("userId"));
user.setUserName(resultSet.getString("userName"));
user.setPassword(resultSet.getString("password"));
}
return user;
}
/**
* 根据用户的id去查询某个用户
* @param id
* @return
* @throws SQLException
*/
@Override
public User findUserId(int id) throws SQLException {
ResultSet resultSet = null;
User user = new User();
String sql = "select * from user where userId =" + id;
resultSet = JDBCUtils.select(sql);
while (resultSet.next()) {
user.setUserId(resultSet.getInt("userId"));
user.setUserName(resultSet.getString("userName"));
user.setPassword(resultSet.getString("password"));
}
return user;
}
/**
* 登录功能
* @param uname
* @param pwd
* @throws SQLException
*/
@Override
public void userLogin(String uname, String pwd) throws SQLException {
ResultSet resultSet = null;
User user = new User();
String sql = "select * from user where userName = '" + uname + "' and password = '" + pwd + "'";
resultSet = JDBCUtils.select(sql);
while (resultSet.next()) {
user.setUserName(resultSet.getString("userName"));
user.setPassword(resultSet.getString("password"));
}
if (user.getPassword() != null && user.getUserName() != null) {
System.out.println("你好" + user.getUserName() + "登录成功");
} else {
System.out.println("登录失败");
}
}
/**
* 删除用户
* @param id
* @return
*/
@Override
public int deleteUser(int id) throws SQLException {
String sql = "delete from user where userId = "+ id;
int flag = JDBCUtils.update(sql);
return flag;
}
@Override
public int insertUser(User user) throws SQLException {
String sql = "INSERT INTO user(userName,password) VALUES("+user.getUserName()+","+user.getPassword()+")";
int flag = JDBCUtils.update(sql);
return flag;
}
@Override
public int deleteUserByIds(int[] ids) throws Exception {
int i = 0;
for (int id : ids) {
UserFunction uf = new UserFunctionImpl();
int count = uf.deleteUser(id);
i=i+count;
}
return i;
}
}
| [
"[email protected]"
] | |
e35ec740d13464318778b58a56e624f2073b3320 | a72ddd2048e0a7c2e26ad3ee9882a92f516115fa | /app/src/main/java/com/user/sqrfactor/Activities/PostJobActivity.java | be1ceedc0143d9f7bf826258966c819bc43851a6 | [] | no_license | sameer123sqrfactor/SQR_FACTOR_ANDROID-master | ad3dcf2a3a3bc479bda62d96a3da1608525edd44 | 44a549dd18c2999023ced0e7fc25bda7acf35abc | refs/heads/master | 2020-05-01T18:23:35.638086 | 2019-03-14T07:41:43 | 2019-03-14T07:41:43 | 177,623,492 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 26,282 | java | package com.user.sqrfactor.Activities;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.user.sqrfactor.Constants.Constants;
import com.user.sqrfactor.Constants.SPConstants;
import com.user.sqrfactor.Constants.ServerConstants;
import com.user.sqrfactor.Network.MyVolley;
import com.user.sqrfactor.Pojo.Skillsbean;
import com.user.sqrfactor.R;
import com.user.sqrfactor.Storage.MySharedPreferences;
import com.toptoche.searchablespinnerlibrary.SearchableSpinner;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PostJobActivity extends AppCompatActivity implements View.OnClickListener {
Toolbar toolbar;
private MySharedPreferences mSp;
private RequestQueue mRequestQueue;
EditText job_description, min_salary, max_salary, job_skills, job_qual, job_firm, job_expirydate;
TextView job_title;
TextView add_more_s, add_more_q;
Spinner job_category_spinner, job_position_spinner, job_work_exp_spinner, job_currency_unit;
private int cyear, cmonth, cdate;
private SearchableSpinner job_country_spinner;
private SearchableSpinner job_state_spinner;
private SearchableSpinner job_city_spinner;
private ArrayList<String> countries = new ArrayList<>();
private ArrayList<HashMap> countriesMapList = new ArrayList<>();
private ArrayList<String> states = new ArrayList<>();
private ArrayList<HashMap> statesMapList = new ArrayList<>();
private ArrayList<String> cities = new ArrayList<>();
private ArrayList<HashMap> citiesMapList = new ArrayList<>();
String job_titleStr,
descriptionStr,
categoryStr,
type_of_positionStr,
work_experienceStr,
minimumStr,
maximumStr,
salary_typeStr,
skillsStr,
educational_qualificationStr,
firmStr,
countryStr,
stateStr,
cityStr,
datetimepickerStr;
List<Skillsbean> group_feild1 = new ArrayList<>();
List<Skillsbean> group_feild2 = new ArrayList<>();
HashMap<Integer, List<View>> optionItemsMap = new HashMap<>();
HashMap<Integer, List<View>> optionItemsMap2 = new HashMap<>();
private List<View> mLayoutList = new ArrayList<>();
private List<View> mLayoutList2 = new ArrayList<>();
private LayoutInflater inflater;
private LinearLayout mContainerView, mContainerView2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_job);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.back_arrow);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
mSp = MySharedPreferences.getInstance(this);
mRequestQueue = MyVolley.getInstance().getRequestQueue();
mContainerView = (LinearLayout) findViewById(R.id.parentView);
mContainerView2 = (LinearLayout) findViewById(R.id.parentView2);
Calendar calendar = Calendar.getInstance();
cyear = calendar.get(Calendar.YEAR);
cmonth = calendar.get(Calendar.MONTH);
cdate = calendar.get(Calendar.DAY_OF_MONTH);
add_more_s = findViewById(R.id.skills_add_more);
add_more_q = findViewById(R.id.qual_add_more);
add_more_s.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
addMoreSkillsRow(view);
}
});
add_more_q.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
addMoreQulRow(view);
}
});
job_category_spinner = findViewById(R.id.job_category_spinner);
job_position_spinner = findViewById(R.id.job_position_spinner);
job_work_exp_spinner = findViewById(R.id.job_work_exp_spinner);
job_currency_unit = findViewById(R.id.job_currency_unit);
job_title = findViewById(R.id.job_title);
job_description = findViewById(R.id.job_description);
min_salary = findViewById(R.id.min_salary);
max_salary = findViewById(R.id.max_salary);
job_skills = findViewById(R.id.job_skills);
job_qual = findViewById(R.id.job_qual);
job_firm = findViewById(R.id.job_firm);
job_expirydate = findViewById(R.id.job_expirydate);
job_expirydate = findViewById(R.id.job_expirydate);
job_expirydate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new DatePickerDialog(PostJobActivity.this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
job_expirydate.setText(dayOfMonth + "/" + (month + 1) + "/" + year);
}
}, cyear, cmonth, cdate).show();
}
});
job_country_spinner = findViewById(R.id.job_country_spinner);
job_state_spinner = findViewById(R.id.job_state_spinner);
job_city_spinner = findViewById(R.id.job_city_spinner);
getCountryList();
//when any country is selected
job_country_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String idk = (String) countriesMapList.get(position).get("id");
//for states
getStatesList(idk);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//when any state is selected
job_state_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String id = (String) statesMapList.get(i).get("id");
//for cities
getCitiesList(id);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
findViewById(R.id.job_post).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String id_country = countriesMapList.get((int) job_country_spinner.getSelectedItemId()).get("id").toString();
String id_state = statesMapList.get((int) job_state_spinner.getSelectedItemId()).get("id").toString();
String id_city = citiesMapList.get((int) job_city_spinner.getSelectedItemId()).get("id").toString();
String job_cat = job_category_spinner.getSelectedItem().toString();
String job_pos = job_position_spinner.getSelectedItem().toString();
String job_exp = job_work_exp_spinner.getSelectedItem().toString();
String job_unit = job_currency_unit.getSelectedItem().toString();
job_titleStr = job_title.getText().toString();
descriptionStr = job_description.getText().toString();
categoryStr = job_cat;
type_of_positionStr = job_pos;
work_experienceStr = job_exp;
minimumStr = min_salary.getText().toString();
maximumStr = max_salary.getText().toString();
salary_typeStr = job_unit;
skillsStr = job_skills.getText().toString();
educational_qualificationStr = job_qual.getText().toString();
firmStr = job_firm.getText().toString();
countryStr = id_country.replace("\"", "");
stateStr = id_state.replace("\"", "");
cityStr = id_city.replace("\"", "");
datetimepickerStr = job_expirydate.getText().toString();
if (mLayoutList.size() != 0) {
for (int i = 0; i < mLayoutList.size(); i++) {
Skillsbean groupFeildBean = new Skillsbean();
ViewGroup mContainerView = (LinearLayout) findViewById(R.id.parentView);
View v = mContainerView.getChildAt(i);
EditText et1 = v.findViewById(R.id.job_qual);
if (et1.getText().toString().equals("")) {
Toast.makeText(PostJobActivity.this, "Fill all details", Toast.LENGTH_SHORT).show();
} else {
groupFeildBean.setIndex(i + 1);
groupFeildBean.setText(et1.getText().toString().trim());
group_feild1.add(groupFeildBean);
}
}
}
if (mLayoutList2.size() != 0) {
for (int i = 0; i < mLayoutList2.size(); i++) {
Skillsbean groupFeildBean = new Skillsbean();
ViewGroup mContainerView = (LinearLayout) findViewById(R.id.parentView2);
View v = mContainerView.getChildAt(i);
EditText et1 = v.findViewById(R.id.job_qual2);
if (et1.getText().toString().equals("")) {
Toast.makeText(PostJobActivity.this, "Fill all details", Toast.LENGTH_SHORT).show();
} else {
groupFeildBean.setIndex(i + 1);
groupFeildBean.setText(et1.getText().toString().trim());
group_feild2.add(groupFeildBean);
}
}
}
if (job_titleStr.equals("")) {
Toast.makeText(PostJobActivity.this, "Please enter job title", Toast.LENGTH_SHORT).show();
} else if (descriptionStr.equals("")) {
Toast.makeText(PostJobActivity.this, "Please enter description", Toast.LENGTH_SHORT).show();
} else if (categoryStr.equals("")) {
Toast.makeText(PostJobActivity.this, "Please select job category", Toast.LENGTH_SHORT).show();
} else if (type_of_positionStr.equals("")) {
Toast.makeText(PostJobActivity.this, "Please select position", Toast.LENGTH_SHORT).show();
} else if (work_experienceStr.equals("")) {
Toast.makeText(PostJobActivity.this, "Please select work experience", Toast.LENGTH_SHORT).show();
} else if (minimumStr.equals("")) {
Toast.makeText(PostJobActivity.this, "Please enter minimum salary", Toast.LENGTH_SHORT).show();
} else if (maximumStr.equals("")) {
Toast.makeText(PostJobActivity.this, "Please enter maximum salary", Toast.LENGTH_SHORT).show();
} else if (salary_typeStr.equals("")) {
Toast.makeText(PostJobActivity.this, "Please select salary type", Toast.LENGTH_SHORT).show();
} else if (skillsStr.equals("")) {
Toast.makeText(PostJobActivity.this, "Please enter skills", Toast.LENGTH_SHORT).show();
} else if (educational_qualificationStr.equals("")) {
Toast.makeText(PostJobActivity.this, "Please educational qualification", Toast.LENGTH_SHORT).show();
} else if (firmStr.equals("")) {
Toast.makeText(PostJobActivity.this, "Please enter firm", Toast.LENGTH_SHORT).show();
} else if (countryStr.equals("")) {
Toast.makeText(PostJobActivity.this, "Please select country", Toast.LENGTH_SHORT).show();
} else if (stateStr.equals("")) {
Toast.makeText(PostJobActivity.this, "Please select state", Toast.LENGTH_SHORT).show();
} else if (cityStr.equals("")) {
Toast.makeText(PostJobActivity.this, "Please select city", Toast.LENGTH_SHORT).show();
} else if (datetimepickerStr.equals("")) {
Toast.makeText(PostJobActivity.this, "Please select job expire date", Toast.LENGTH_SHORT).show();
} else {
postJob();
}
}
});
}
public void addMoreSkillsRow(View v) {
View view = inflater.inflate(R.layout.multiple_view_layout, null);
final TextView remove = view.findViewById(R.id.remove);
mLayoutList.add(view);
int tagIndex = mLayoutList.size() - 1;
remove.setTag(tagIndex);
remove.setOnClickListener(this);
mContainerView.addView(view);
}
public void addMoreQulRow(View v) {
View view = inflater.inflate(R.layout.multiple_view_layout2, null);
final TextView remove2 = view.findViewById(R.id.remove2);
mLayoutList2.add(view);
int tagIndex = mLayoutList2.size() - 1;
remove2.setTag(tagIndex);
remove2.setOnClickListener(this);
mContainerView2.addView(view);
}
private void getCountryList() {
StringRequest requestCountry = new StringRequest(Request.Method.GET, ServerConstants.EVENT_GET_COUNTRY, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("yyyyyyyyyyyyyyy", "onResponse: Event list response = " + response);
try {
JSONObject responseObject = new JSONObject(response);
final JSONArray countriesArray = responseObject.getJSONArray("countries");
for (int i = 0; i < countriesArray.length(); i++) {
final JSONObject singleObject = countriesArray.getJSONObject(i);
String cId = singleObject.getString("id");
String cName = singleObject.getString("name");
countries.add(cName);
//add to map list
HashMap<String, String> map = new HashMap<>();
map.put("id", cId);
map.put("name", cName);
countriesMapList.add(map);
}
ArrayAdapter<String> country_adapter = new ArrayAdapter<>(PostJobActivity.this, android.R.layout.simple_list_item_1, countries);
job_country_spinner.setAdapter(country_adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//TODO:: handle
}
}) {
@Override
public Map<String, String> getHeaders() {
final Map<String, String> headers = new HashMap<>();
headers.put(getString(R.string.accept), getString(R.string.application_json));
headers.put(getString(R.string.authorization), Constants.AUTHORIZATION_HEADER + mSp.getKey(SPConstants.API_KEY));
Log.d("Country List in Spinner", "getHeaders: api key = " + mSp.getKey(SPConstants.API_KEY));
return headers;
}
};
requestCountry.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
mRequestQueue.add(requestCountry);
}
private void getStatesList(final String c) {
StringRequest requestState = new StringRequest(Request.Method.POST, ServerConstants.EVENT_SET_STATE, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("sssssssssssssssss", "onResponse: Event list response = " + response);
states.clear();
try {
JSONObject responseObject = new JSONObject(response);
final JSONArray statesArray = responseObject.getJSONArray("states");
statesMapList.clear();
for (int i = 0; i < statesArray.length(); i++) {
final JSONObject singleObject = statesArray.getJSONObject(i);
String sId = singleObject.getString("id");
String sName = singleObject.getString("name");
states.add(sName);
//add to map list
HashMap<String, String> map = new HashMap<>();
map.put("id", sId);
map.put("name", sName);
statesMapList.add(map);
}
ArrayAdapter<String> state_adapter = new ArrayAdapter<>(PostJobActivity.this, android.R.layout.simple_list_item_1, states);
job_state_spinner.setAdapter(state_adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//TODO:: handle
}
}) {
@Override
public Map<String, String> getHeaders() {
final Map<String, String> headers = new HashMap<>();
headers.put(getString(R.string.accept), getString(R.string.application_json));
headers.put(getString(R.string.authorization), Constants.AUTHORIZATION_HEADER + mSp.getKey(SPConstants.API_KEY));
Log.d("State List in Spinner", "getHeaders: api key = " + mSp.getKey(SPConstants.API_KEY));
return headers;
}
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("country", c);
return params;
}
};
requestState.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
mRequestQueue.add(requestState);
}
private void getCitiesList(final String s) {
StringRequest requestCity = new StringRequest(Request.Method.POST, ServerConstants.EVENT_SET_CITY, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("cccccccccccccccccccc", "onResponse: Event list response = " + response);
cities.clear();
try {
JSONObject responseObject = new JSONObject(response);
JSONArray citiesArray = responseObject.getJSONArray("cities");
for (int i = 0; i < citiesArray.length(); i++) {
JSONObject singleObject = citiesArray.getJSONObject(i);
String cId = singleObject.getString("id");
String cName = singleObject.getString("name");
cities.add(cName);
//add to map list
HashMap<String, String> map = new HashMap<>();
map.put("id", cId);
map.put("name", cName);
citiesMapList.add(map);
}
ArrayAdapter<String> city_adapter = new ArrayAdapter<>(PostJobActivity.this, android.R.layout.simple_list_item_1, cities);
job_city_spinner.setAdapter(city_adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//TODO:: handle
}
}) {
@Override
public Map<String, String> getHeaders() {
final Map<String, String> headers = new HashMap<>();
headers.put(getString(R.string.accept), getString(R.string.application_json));
headers.put(getString(R.string.authorization), Constants.AUTHORIZATION_HEADER + mSp.getKey(SPConstants.API_KEY));
Log.d("State List in Spinner", "getHeaders: api key = " + mSp.getKey(SPConstants.API_KEY));
return headers;
}
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("state", s);
return params;
}
};
requestCity.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
mRequestQueue.add(requestCity);
}
private void postJob() {
StringRequest request = new StringRequest(Request.Method.POST, ServerConstants.POST_JOB, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("postJobResponse: ", response);
try {
JSONObject responseObject = new JSONObject(response);
Toast.makeText(PostJobActivity.this, responseObject.getString("Message"), Toast.LENGTH_SHORT).show();
onBackPressed();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}) {
@Override
public Map<String, String> getHeaders() {
final Map<String, String> headers = new HashMap<>();
headers.put(getString(R.string.accept), getString(R.string.application_json));
headers.put(getString(R.string.authorization), Constants.AUTHORIZATION_HEADER + mSp.getKey(SPConstants.API_KEY));
return headers;
}
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("job_title", job_titleStr);
params.put("description", descriptionStr);
params.put("category", descriptionStr);
params.put("type_of_position", type_of_positionStr);
params.put("work_experience", work_experienceStr);
params.put("minimum", minimumStr);
params.put("maximum", maximumStr);
params.put("salary_type", salary_typeStr);
params.put("skills[0]", skillsStr);
if (group_feild1.size() != 0) {
for (int i = 0; i < group_feild1.size(); i++) {
params.put("skills[" + group_feild1.get(i).getIndex() + "]", group_feild1.get(i).getText());
}
}
params.put("educational_qualification[0]", educational_qualificationStr);
if (group_feild2.size() != 0) {
for (int i = 0; i < group_feild2.size(); i++) {
params.put("educational_qualification[" + group_feild2.get(i).getIndex() + "]", group_feild2.get(i).getText());
}
}
params.put("firm", firmStr);
params.put("country", countryStr);
params.put("state", stateStr);
params.put("city", cityStr);
params.put("datetimepicker", datetimepickerStr);
return params;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
mRequestQueue.add(request);
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.remove) {
int current = (int) view.getTag();
View currentView = mLayoutList.get(current);
mContainerView.removeView(currentView);
mLayoutList.remove(current);
for (int i = 0; i < mLayoutList.size(); i++) {
TextView deletBtn = mLayoutList.get(i).findViewById(R.id.remove);
deletBtn.setTag(i);
}
optionItemsMap.remove(current);
} else if (view.getId() == R.id.remove2) {
int current = (int) view.getTag();
View currentView = mLayoutList2.get(current);
mContainerView2.removeView(currentView);
mLayoutList2.remove(current);
for (int i = 0; i < mLayoutList2.size(); i++) {
TextView deletBtn = mLayoutList2.get(i).findViewById(R.id.remove2);
deletBtn.setTag(i);
}
optionItemsMap2.remove(current);
}
}
}
| [
"[email protected]"
] | |
91e18b2d4a506967a42034444d8dcbfd29c19743 | 9d8d7244b56352911d919b403919d6415432a95e | /src/com/dynamic/behavior/state/State.java | 7065aea49e4396d6ce9d6766a533757f9ededfec | [
"Apache-2.0"
] | permissive | architect-energy-supply-station/java-desigh-pattern | 2026f3047d51cf68ca66d89283d09255636e57da | d566477bf7718ed941bd006b79998c69170a05d0 | refs/heads/master | 2020-08-06T09:44:13.826415 | 2019-10-05T02:37:36 | 2019-10-05T02:37:36 | 212,929,821 | 0 | 0 | Apache-2.0 | 2019-10-05T02:37:37 | 2019-10-05T01:53:03 | null | UTF-8 | Java | false | false | 421 | java | package com.dynamic.behavior.state;
/**
* @author bill-smith liuwb
* @Package com.dynamic.behavior.state
* @Date 2019/10/1 15:21
* @Version v1.0
* @Copyright @ 2019-2020用友网络科技股份有限公司
* @Email [email protected]
* @Contract https://github.com/BillCindy
* @Blog https://blog.csdn.net/t131452n?viewmode=contents
*/
public abstract class State {
abstract void handle(Context context);
}
| [
"[email protected]"
] | |
c5077fe838f1fbd029f80e6c9dbe5e4c38e1cd33 | 3cd99d0ec4145633d59fdd7f7d427a2a5de93c83 | /app/src/main/java/com/luo/project/coordinator/CoordinatorActivity.java | 6cf9ffd25b6442c8de6ae52d917e6137747cbfc7 | [] | no_license | luoyingxing/LProject | f80d34eb0cae8b0227789c725edf8008df713f25 | 27de822de785a301595882a9839840250846e130 | refs/heads/master | 2020-04-06T23:38:36.899418 | 2019-01-09T07:08:00 | 2019-01-09T07:08:00 | 68,512,931 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,264 | java | package com.luo.project.coordinator;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Window;
import android.widget.Toast;
import com.facebook.drawee.view.SimpleDraweeView;
import com.luo.project.R;
import com.luo.project.db.InfoDB;
import com.luo.project.entity.Info;
import com.luo.project.recycler.DividerItemDecoration;
import com.luo.project.recycler.ViewHolder;
import com.luo.project.recycler.XAdapter;
import java.util.ArrayList;
public class CoordinatorActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private XAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_coordinator);
recyclerView = (RecyclerView) findViewById(R.id.my_list);
mAdapter = new XAdapter<Info>(this, new ArrayList<Info>(), R.layout.item_recycler_view) {
@Override
public void convert(ViewHolder holder, Info info) {
holder.setText(R.id.text, info.getInfoId() + ". " + info.getTitle());
SimpleDraweeView iamgeView = holder.getView(R.id.image);
iamgeView.setImageURI(Uri.parse(info.getUrl()));
}
};
recyclerView.setAdapter(mAdapter);
recyclerView.setItemAnimator(new DefaultItemAnimator());
//TODO 线性布局
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
mAdapter.setOnItemClickListener(new XAdapter.OnItemClickListeners<Info>() {
@Override
public void onItemClick(RecyclerView.ViewHolder holder, Info item, int position) {
Toast.makeText(getApplicationContext(), item.getUrl(), Toast.LENGTH_SHORT).show();
}
});
mAdapter.addAll(InfoDB.getInstance().selectAll(getApplicationContext()));
}
}
| [
"[email protected]"
] | |
96d8b528516b20adb16169a5ef38eca42a2145a1 | 369c9153a526335741311e4f7cf0f341946570dd | /allmycircuits/circuits/Vanne.java | 860b474c35114e8c60f9ca06202243ba6c3f3c25 | [] | no_license | henyxia/bool4noob | 3cd577d771472aa51e79e30dab0a63ed73c126db | 85ac437dcd92cf342eb6d1aa2f5542c333bfc7b9 | refs/heads/master | 2016-08-06T00:00:43.798793 | 2015-05-15T16:50:05 | 2015-05-15T16:50:05 | 33,921,021 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 454 | java | package circuits;
public class Vanne extends Composant
{
private static final long serialVersionUID = 7526471155622776149L;
protected Composant in;
public void setIn(Composant comp)
{
in = comp;
}
public boolean getEtat() throws NonConnecteException
{
if(in == null)
throw new NonConnecteException();
else
return in.getEtat();
}
public String description()
{
//return getId() + " in: " + in.getId();
return getId();
}
}
| [
"[email protected]"
] | |
31d77ff4e85bdd94f313d031d0193ac69ed04f28 | 9d4f36cf72314fb22c5a747f3bb969eb7b8156cb | /src/main/java/ru/arlen/App.java | 228fa9f9d8ad7cd3c2a5e8044a10145926829210 | [] | no_license | arlengur/SpringBatch | 1a046898d26c1206962554a55faf160bfe92f3f8 | 63d445a3ca266e1d725f90e9c75313776f650a3f | refs/heads/master | 2022-07-01T19:58:08.689520 | 2019-09-23T07:58:40 | 2019-09-23T07:58:40 | 209,839,688 | 0 | 0 | null | 2022-06-23T18:12:20 | 2019-09-20T16:53:44 | Java | UTF-8 | Java | false | false | 332 | java | package ru.arlen;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(BatchConfiguration.class);
}
}
| [
"[email protected]"
] | |
53d06dd9a6e80d102d5c0ee47f8816b8777aa640 | 678d1d6c78ff00c1fc2190600ec1774fc13f865b | /api/src/main/java/com/simon/mapper/NewsTagMapper.java | 91d6b9faab67b305288b3072eacbd35ad8e6262b | [
"Apache-2.0"
] | permissive | leafgrey/oauthserver | 6f009bf5e4b5326ba0e57bac0ce2f8bb8f611213 | 07bc8ff43be2177f10a284678ab5d8c08cf2af42 | refs/heads/master | 2022-10-04T19:18:05.476605 | 2019-05-07T16:27:50 | 2019-05-07T16:27:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 161 | java | package com.simon.mapper;
import com.simon.common.mapper.MyMapper;
import com.simon.model.NewsTag;
public interface NewsTagMapper extends MyMapper<NewsTag> {
} | [
"[email protected]"
] | |
98602fc3260596d95d580cd2fd0ec7eec0840490 | cc27af2227b00906ec10703df2249013a690c242 | /UserDaoImpl.java | 956201b2b6099f33a1ff73d634b06198092f0563 | [] | no_license | madhuramhetre1/onlinerepo | 9ae935fa47b1fca5ed371c7e0505bb9402914446 | bab800abc6436cf85fbbc6e9dee5ded3b12fde9f | refs/heads/master | 2021-01-19T19:44:18.717540 | 2017-04-16T19:49:15 | 2017-04-16T19:49:15 | 88,436,914 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 947 | java | package com.shopping.dao;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.shopping.model.User;
@Repository
@Transactional
public class UserDaoImpl implements UserDao{
@Autowired
private SessionFactory sf;
@Override
public User addUser(User u) {
sf.getCurrentSession().persist(u);
return u;
}
@Override
public User validateUser(User user) {
// check for login
System.out.println("inside valid user");
User userlog=(User) sf.getCurrentSession().createQuery("select u from User u where u.userName= :uname and u.password= :pass")
.setParameter("uname", user.getUserName()).setParameter("pass", user.getPassword()).uniqueResult();
System.out.println("dao"+userlog.getUserName());
return userlog;
}
}
| [
"[email protected]"
] | |
2544f8bfa9ae25039b7041eaf1ac249b1c2bca2c | 435a1f478647747b9d53247660ad1fb27b1f3d5a | /vieeo/vieeo-module/src/main/java/com/vieeo/module/dao/hibernate3/visitor/HibernateVisitor.java | f904f3493908fb6dab80099a21ca0b92d6db8dc5 | [] | no_license | happyjianguo/vieeo | 4c008fc18dfab597da4dc91303f7835420671186 | ff7e1195a5441f696a2e38dd3f55af2821a118e0 | refs/heads/master | 2020-06-20T04:22:31.065097 | 2015-04-14T03:01:14 | 2015-04-14T03:01:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,143 | java | package com.vieeo.module.dao.hibernate3.visitor;
import java.util.List;
import com.vieeo.core.condition.BodyCondition;
import com.vieeo.core.condition.Condition;
import com.vieeo.core.condition.Conditions;
import com.vieeo.core.condition.Expression;
import com.vieeo.core.domain.Entity;
import com.vieeo.core.strategy.Visitor;
public class HibernateVisitor implements Visitor<Conditions>{
private Expression baseExpression;
private Class<? extends Entity> clazz;
private Visitor<Condition> hqlVisitor;
private boolean init = false;
public HibernateVisitor(Expression baseExpression,Class<? extends Entity> clazz,String alias) {
this.baseExpression = baseExpression;
this.clazz = clazz;
hqlVisitor = new HQLVisitor(clazz,alias);
}
private void initHql(StringBuilder hql) throws Exception{
BodyCondition condition = new BodyCondition();
condition.addExpressions(baseExpression);
hql.append(hqlVisitor.visit(condition));
init = true;
}
@SuppressWarnings("unchecked")
@Override
public String visit(Conditions visitor)throws Exception {
try {
if(baseExpression == null) throw new Exception("HQL error : baseExpression can not be null");
StringBuilder hql = new StringBuilder();
if(!init) initHql(hql);
if(visitor == null) return hql.toString();
if(visitor.hasAliasExpression()) {
hql.append(hqlVisitor.visit(visitor.getAliasCondition()));
}
//add 'and' conditions
if(visitor.hasAndExpression()) {
hql.append(hqlVisitor.visit(visitor.getAndConditions()));
}
//add 'or' conditions
if(visitor.hasOrExpression()) {
List<Condition> orConditions = visitor.getOrConditions();
for (Condition orCondition : orConditions) { hql.append(hqlVisitor.visit(orCondition)); }
}
//add 'order' conditions
if(visitor.hasOrderExpression()) {
hql.append(hqlVisitor.visit(visitor.getOrderConditions()));
}
return hql.toString();
}catch(Exception e) {
throw new Exception("hql error happened:",e);
}
}
protected Class<? extends Entity> getClazz() {
return clazz;
}
protected void setClazz(Class<? extends Entity> clazz) {
this.clazz = clazz;
}
}
| [
"[email protected]"
] | |
e36904dfe3c4a46af5a588cd1a7255fa45f13d33 | e5eab87c5593aeb5a6f74843d0fe293c4fe1f291 | /ContactsEJB/ejbModule/su/sergey/contacts/phone/valueobjects/impl/DefaultPhoneAttributes.java | 01720bac01666c12c469404de5dd309f11900008 | [] | no_license | seregaizsbera/contacts | 9f7a2d7f10bfc039dc7d85f1914e7bcae7afe75b | 973357dd6a5957e0fe59ac86515419a27303f31f | refs/heads/master | 2020-03-26T19:29:51.804139 | 2018-08-19T02:52:50 | 2018-08-19T02:52:50 | 145,268,347 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,259 | java | package su.sergey.contacts.phone.valueobjects.impl;
import su.sergey.contacts.phone.valueobjects.PhoneAttributes;
import su.sergey.contacts.phone.valueobjects.*;
public class DefaultPhoneAttributes implements PhoneAttributes {
private String phone;
private boolean basic;
private Integer type;
private String note;
/**
* Gets the basic
* @return Returns a boolean
*/
public boolean isBasic() {
return basic;
}
/**
* Sets the basic
* @param basic The basic to set
*/
public void setBasic(boolean basic) {
this.basic = basic;
}
/**
* Gets the phone
* @return Returns a String
*/
public String getPhone() {
return phone;
}
/**
* Sets the phone
* @param phone The phone to set
*/
public void setPhone(String phone) {
this.phone = phone;
}
/**
* Gets the type
* @return Returns a Integer
*/
public Integer getType() {
return type;
}
/**
* Sets the type
* @param type The type to set
*/
public void setType(Integer type) {
this.type = type;
}
/**
* Gets the note
* @return Returns a String
*/
public String getNote() {
return note;
}
/**
* Sets the note
* @param note The note to set
*/
public void setNote(String note) {
this.note = note;
}
}
| [
"[email protected]"
] | |
32e887c2050aced2eb34bb0063ee92fdec5e87f9 | 08151853204409da4eee309a6b8adc2ed70336a9 | /src/main/java/com/chenes/security/intercept/MyIntercept.java | e8625966edb9389cd265c3d133334f37171bfe5b | [] | no_license | loveboycrystal/springSecurity-simple | 4899d61d44f7c5b9c28b35ed9bd8e497aa12eb15 | 62132b17c9bb8cbacc86970b49fbf5e0c6a07ebc | refs/heads/master | 2020-08-26T12:46:10.633983 | 2019-10-24T03:35:41 | 2019-10-24T03:35:41 | 217,013,688 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,735 | java | package com.chenes.security.intercept;
import com.chenes.security.bean.PdspUser;
import com.chenes.security.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @description 拦截器
* @author [email protected]
* @date 2019/10/21
* springSecurity 样例
* 修改记录
* 修改人: 修改日期: 版本: 修改内容:
* chenes 2019/10/21 18:38 1.0 新增
*/
@Component
@Slf4j
public class MyIntercept extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("MyIntercept开始拦截");
PdspUser user = SecurityUtils.getUser();
if(null == user){
log.warn(" 尚未登录,请先登录。");
//return false;
}
return super.preHandle(request, response, handler);
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
super.postHandle(request, response, handler, modelAndView);
log.info("MyIntercept正在拦截");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
super.afterCompletion(request, response, handler, ex);
log.info("MyIntercept拦截完成");
}
}
| [
"[email protected]"
] | |
2b482acddc786c1ff3349a13f31f366836197a7e | 2b12f1da33c555cf5aa6c772603281fd78f7b185 | /TableMetadataDemo/src/com/learning/tablemetadatademo/TableMetadataDemo.java | cf4196f144a3afd7f0e75db0de3aecd0fcf64787 | [] | no_license | prathuk535/Java | fda0598c76b25ae0e8b1814f885a03860cafeeb0 | 2eb6cc846b73eb653386e86a295b78464fc108e7 | refs/heads/main | 2023-06-01T14:29:46.498722 | 2021-06-20T14:00:35 | 2021-06-20T14:00:35 | 337,681,438 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,538 | java | package com.learning.tablemetadatademo;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TableMetadataDemo {
String user="sa";
String password="sasa";
String url="jdbc:sqlserver://localhost:1433;databasename=TestDB";
Connection conn=null;
PreparedStatement pSt=null;
ResultSet rs=null;
int rowsAffected=0;
int id;
boolean getConnected()
{
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn=DriverManager.getConnection(url,user,password);
if(conn!=null)
{
return true;
}
}
catch(ClassNotFoundException e)
{
System.out.println("ClassNotFound: "+e);
}
catch(SQLException e)
{
System.out.println("SQLException in connection: "+e);
}
return false;
}
void dispDB_Metadata()
{
if(getConnected())
{
DatabaseMetaData metaData;
try {
metaData=conn.getMetaData();
String[] tabTypes= {"Table"};
System.out.println("Tables Names");
ResultSet rs=metaData.getTables(null, null, null, tabTypes);
while(rs.next())
{
System.out.println(rs.getString("Table_Name"));
}
}
catch(SQLException e)
{
System.out.println(e);
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
TableMetadataDemo demo=new TableMetadataDemo();
demo.dispDB_Metadata();
}
}
| [
"[email protected]"
] | |
9143c3db461fe2eaf75e005b247b2c9edabe8d10 | d98de110431e5124ec7cc70d15906dac05cfa61a | /public/source/photon/plugins/org.marketcetera.photon.strategy/src/main/java/org/marketcetera/photon/internal/strategy/StrategyEnginesSupport.java | caedf28d3b8ef4bdc0b36270f0fa1e46a00e3607 | [] | no_license | dhliu3/marketcetera | 367f6df815b09f366eb308481f4f53f928de4c49 | 4a81e931a044ba19d8f35bdadd4ab081edd02f5f | refs/heads/master | 2020-04-06T04:39:55.389513 | 2012-01-30T06:49:25 | 2012-01-30T06:49:25 | 29,947,427 | 0 | 1 | null | 2015-01-28T02:54:39 | 2015-01-28T02:54:39 | null | UTF-8 | Java | false | false | 3,167 | java | package org.marketcetera.photon.internal.strategy;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import org.eclipse.core.runtime.Platform;
import org.eclipse.emf.ecore.EObject;
import org.marketcetera.photon.commons.emf.EMFFilePersistence;
import org.marketcetera.photon.commons.emf.IEMFPersistence;
import org.marketcetera.photon.strategy.StrategyUI;
import org.marketcetera.photon.strategy.engine.IStrategyEngines;
import org.marketcetera.photon.strategy.engine.embedded.EmbeddedEngine;
import org.marketcetera.photon.strategy.engine.model.core.StrategyEngine;
import org.marketcetera.photon.strategy.engine.model.sa.StrategyAgentEngine;
import org.marketcetera.photon.strategy.engine.sa.ui.StrategyAgentEnginesSupport;
import org.marketcetera.util.misc.ClassVersion;
import org.osgi.framework.BundleContext;
import com.google.common.base.Predicates;
import com.google.common.collect.Collections2;
/* $License$ */
/**
* Manages the {@link IStrategyEngines} service provided by this bundle.
*
* @author <a href="mailto:[email protected]">Will Horn</a>
* @version $Id: StrategyEnginesSupport.java 10885 2009-11-17 19:22:56Z klim $
* @since 2.0.0
*/
@ClassVersion("$Id: StrategyEnginesSupport.java 10885 2009-11-17 19:22:56Z klim $")
class StrategyEnginesSupport extends StrategyAgentEnginesSupport {
private static final String PERSISTENCE_FILE_NAME = "engines.xml"; //$NON-NLS-1$
/**
* Persistence service that only saves {@link StrategyAgentEngine}.
*/
@ClassVersion("$Id: StrategyEnginesSupport.java 10885 2009-11-17 19:22:56Z klim $")
private final static class Persistence implements IEMFPersistence {
private final IEMFPersistence mDelegate = new EMFFilePersistence(
Platform.getStateLocation(
Platform.getBundle(StrategyUI.PLUGIN_ID)).append(
PERSISTENCE_FILE_NAME).toFile());
@Override
public void save(Collection<? extends EObject> objects)
throws IOException {
mDelegate.save(Collections2.filter(objects, Predicates
.instanceOf(StrategyAgentEngine.class)));
}
@Override
public List<? extends EObject> restore() throws IOException {
return mDelegate.restore();
}
};
/**
* Constructor.
*
* @param context
* the context with which to register the service
* @throws IllegalArgumentException
* if context is null
* @throws IllegalStateException
* if called from a non UI thread
*/
public StrategyEnginesSupport(BundleContext context) {
super(context, new Persistence());
}
@Override
protected void initList(List<StrategyEngine> engines) {
/*
* Put the static embedded engine at the top of the list.
*/
StrategyEngine mEngine = EmbeddedEngine.createEngine(getGuiExecutor(),
true);
engines.add(mEngine);
super.initList(engines);
}
} | [
"[email protected]"
] | |
314dc16e0686c135205e035b351c331975e15d51 | 5efca3e4507628ee8f5b6f36586512a72fa1144b | /Serie 5/Computergrafik-Basecode-master/simple/src/main/java/simple/simple.java | f3347c8baea9feaee3087d5fb468b11dbf7c5bac | [] | no_license | masus04/ComputerGraphics | 3e687f486cdddbe4e4f69a9587286e9b8e0a7d6e | e6ae5827a8552ef5340eebb793b688b5660df6ed | refs/heads/master | 2021-01-19T09:57:34.782664 | 2014-12-17T11:46:17 | 2014-12-17T11:46:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,004 | java | package simple;
import jrtr.*;
import javax.swing.*;
import java.awt.event.*;
import javax.vecmath.*;
import java.util.Timer;
import java.util.TimerTask;
/**
* Implements a simple application that opens a 3D rendering window and shows a
* rotating cube.
*/
public class simple
{
private static RenderPanel renderPanel;
private static RenderContext renderContext;
private static Shader normalShader;
private static Shader diffuseShader;
private static Material material;
private static GraphSceneManager sceneManager;
private static Shape shape;
private static float currentstep, basicstep;
private static float robotScale;
/**
* An extension of {@link GLRenderPanel} or {@link SWRenderPanel} to provide
* a call-back function for initialization. Here we construct a simple 3D
* scene and start a timer task to generate an animation.
*/
public final static class SimpleRenderPanel extends GLRenderPanel
{
/**
* Initialization call-back. We initialize our renderer here.
*
* @param r
* the render context that is associated with this render
* panel
*/
public void init(RenderContext r)
{
// TODO: choose task 1 or 2
int task = 2;
renderContext = r;
sceneManager = new GraphSceneManager();
// -------------------------- robot -------------------------- //
if (task == 1) {
robotScale = 0.5f;
RobotFactory factory = new RobotFactory();
factory.makeRobot(sceneManager.getRoot(), renderContext, robotScale);
sceneManager.getRoot().getTransformation().setTranslation(new Vector3f(3, 0, 0));
}
// -------------------------- robot -------------------------- //
// ------------------------- cuuubes ------------------------- //
if (task == 2) {
Cube cube = new Cube(renderContext);
cube.setScale(0.33f);
Matrix4f translation = new Matrix4f();
translation.setIdentity();
for (int i = -100; i < 100; i += 3) {
for (int j = -100; j < 100; j += 3) {
Matrix4f trans = new Matrix4f(translation);
trans.setTranslation(new Vector3f(i + 0.5f, j, 0)); // world coordinates
GraphShapeNode node = sceneManager.getRoot().add(cube.getShape(), trans);
}
}
}
// ------------------------- cuuubes ------------------------- //
// Add the scene to the renderer
renderContext.setSceneManager(sceneManager);
// Load some more shaders
normalShader = renderContext.makeShader();
try {
normalShader.load("../jrtr/shaders/normal.vert", "../jrtr/shaders/normal.frag");
} catch (Exception e) {
System.out.print("Problem with shader:\n");
System.out.print(e.getMessage());
}
diffuseShader = renderContext.makeShader();
try {
diffuseShader.load("../jrtr/shaders/diffuse.vert", "../jrtr/shaders/diffuse.frag");
} catch (Exception e) {
System.out.print("Problem with shader:\n");
System.out.print(e.getMessage());
}
// Make a material that can be used for shading
material = new Material();
material.shader = diffuseShader;
material.texture = renderContext.makeTexture();
try {
material.texture.load("../textures/plant.jpg");
} catch (Exception e) {
System.out.print("Could not load texture.\n");
System.out.print(e.getMessage());
}
// Register a timer task
Timer timer = new Timer();
basicstep = 0.01f;
currentstep = basicstep;
if (task == 1) {
timer.scheduleAtFixedRate(new RobotAnimationTask(), 0, 10);
}
else if (task == 2)
timer.scheduleAtFixedRate(new CubesAnimationTask(), 0, 10);
}
}
public static class CubesAnimationTask extends TimerTask {
/*
* FpsCounter fpsCounter; fpsCounter = new FpsCounter(250);
* fpsCounter.getFps();
*/
public CubesAnimationTask() {
}
@Override
public void run() {
Matrix4f rotation = new Matrix4f();
rotation.rotY(0.01f);
Matrix4f transformation = sceneManager.getRoot().getTransformation();
rotation.mul(transformation);
sceneManager.getRoot().setTransformation(rotation);
renderPanel.getCanvas().repaint();
}
}
/**
* A timer task that generates an animation. This task triggers the
* redrawing of the 3D scene every time it is executed.
*/
public static class RobotAnimationTask extends TimerTask
{
int steps, limit;
float speed, cycle;
public RobotAnimationTask() {
cycle = 1;
speed = 0.01f;
limit = (int) (cycle / speed);
initAnimation();
}
private void initAnimation() {
moveArms(limit);
// fore arm
Matrix4f rotation = new Matrix4f();
rotation.rotX(-limit);
moveForeArm(sceneManager.getRoot().getGraphGroup(1), rotation);
rotation = new Matrix4f();
rotation.rotX(-limit);
moveForeArm(sceneManager.getRoot().getGraphGroup(2), rotation);
//
moveLegs(-limit);
}
public void run()
{
moveTorso(speed / 2);
if (steps > limit)
steps = -limit;
if (0 < steps && steps < limit) {
moveArms(speed);
moveLegs(-speed);
} else if (-limit < steps && steps < 0) {
moveArms(-speed);
moveLegs(speed);
}
steps++;
}
private void moveTorso(float angleSpeed) {
Matrix4f rotation = new Matrix4f();
rotation.rotY(angleSpeed);
Matrix4f transformation = sceneManager.getRoot().getTransformation();
rotation.mul(transformation);
sceneManager.getRoot().setTransformation(rotation);
renderPanel.getCanvas().repaint();
}
private void moveArms(float speed) {
GraphGroup leftArm = sceneManager.getRoot().getGraphGroup(1);
GraphGroup rightArm = sceneManager.getRoot().getGraphGroup(2);
moveArm(leftArm, speed);
moveArm(rightArm, -speed);
}
private void moveArm(GraphGroup arm, float speed) {
// upper arm
Matrix4f rotation = new Matrix4f();
rotation.rotX(speed);
Matrix4f transformation = arm.getTransformation();
transformation.mul(rotation);
// fore arm
moveForeArm(arm, rotation);
}
private void moveForeArm(GraphGroup arm, Matrix4f rotation) {
Matrix4f transformation;
arm = arm.getGraphGroup(0);
Matrix4f translation = new Matrix4f();
translation.setIdentity();
translation.setTranslation(new Vector3f(0, 0.5f * robotScale, 0));
transformation = arm.getTransformation();
Matrix4f tmp = new Matrix4f();
tmp.mul(rotation, translation);
translation.invert();
rotation.mul(translation, tmp);
rotation.mul(transformation);
arm.setTransformation(rotation);
}
private void moveLegs(float speed) {
GraphGroup leftLeg = sceneManager.getRoot().getGraphGroup(3);
GraphGroup rightLeg = sceneManager.getRoot().getGraphGroup(4);
moveLeg(leftLeg, speed);
moveLeg(rightLeg, -speed);
}
private void moveLeg(GraphGroup leg, float speed) {
Matrix4f rotation = new Matrix4f();
rotation.rotX(speed);
Matrix4f transformation = leg.getTransformation();
transformation.mul(rotation);
}
}
/**
* A mouse listener for the main window of this application. This can be
* used to process mouse events.
*/
public static class SimpleMouseListener implements MouseListener
{
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
}
/**
* A key listener for the main window. Use this to process key events.
* Currently this provides the following controls: 's': stop animation 'p':
* play animation '+': accelerate rotation '-': slow down rotation 'd':
* default shader 'n': shader using surface normals 'm': use a material for
* shading
*/
public static class SimpleKeyListener implements KeyListener
{
public void keyPressed(KeyEvent e)
{
switch (e.getKeyChar())
{
case 's': {
// Stop animation
currentstep = 0;
break;
}
case 'p': {
// Resume animation
currentstep = basicstep;
break;
}
case '+': {
// Accelerate roation
currentstep += basicstep;
break;
}
case '-': {
// Slow down rotation
currentstep -= basicstep;
break;
}
case 'n': {
// Remove material from shape, and set "normal" shader
shape.setMaterial(null);
renderContext.useShader(normalShader);
break;
}
case 'd': {
// Remove material from shape, and set "default" shader
shape.setMaterial(null);
renderContext.useDefaultShader();
break;
}
case 'm': {
// Set a material for more complex shading of the shape
if (shape.getMaterial() == null) {
shape.setMaterial(material);
} else
{
shape.setMaterial(null);
renderContext.useDefaultShader();
}
break;
}
}
// Trigger redrawing
renderPanel.getCanvas().repaint();
}
public void keyReleased(KeyEvent e)
{
}
public void keyTyped(KeyEvent e)
{
}
}
/**
* The main function opens a 3D rendering window, implemented by the class
* {@link SimpleRenderPanel}. {@link SimpleRenderPanel} is then called
* backed for initialization automatically. It then constructs a simple 3D
* scene, and starts a timer task to generate an animation.
*/
public static void main(String[] args)
{
// Make a render panel. The init function of the renderPanel
// (see above) will be called back for initialization.
renderPanel = new SimpleRenderPanel();
// Make the main window of this application and add the renderer to it
JFrame jframe = new JFrame("simple");
jframe.setSize(500, 500);
jframe.setLocationRelativeTo(null); // center of screen
jframe.getContentPane().add(renderPanel.getCanvas());// put the canvas
// into a JFrame
// window
// Add a mouse and key listener
renderPanel.getCanvas().addMouseListener(new SimpleMouseListener());
renderPanel.getCanvas().addKeyListener(new SimpleKeyListener());
renderPanel.getCanvas().setFocusable(true);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setVisible(true); // show window
}
}
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.