text
stringlengths 10
2.72M
|
|---|
package com.nearur.daa;
import android.support.annotation.IntegerRes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Knapsack extends AppCompatActivity {
Button Go,result;
EditText editText;
ListView listView;
MyAdapter myAdapter;
ArrayList<Item> items;
int maxvalue,maxweight;
TextView textView;
EditText capacity;
RadioButton ratio,value,weight;
int option;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_knapsack);
editText=(EditText)findViewById(R.id.editTextnum);
Go=(Button)findViewById(R.id.buttongo);
result=(Button)findViewById(R.id.buttonresult);
textView=(TextView)findViewById(R.id.result);
listView=(ListView)findViewById(R.id.listview);
capacity=(EditText)findViewById(R.id.capacity);
ratio=(RadioButton)findViewById(R.id.bt1);
value=(RadioButton)findViewById(R.id.bt2);
weight=(RadioButton)findViewById(R.id.bt3);
result.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try{
maxvalue=0;
Comparator<Item> com=new Comparator<Item>() {
@Override
public int compare(Item item, Item t1) {
int i=0;
switch (option){
case 1:
i=item.compareratio(t1);
break;
case 2:
i=item.compareValue(t1);
break;
case 3:
i=item.compareWeight(t1);
break;
}
return i;
}
};
Collections.sort(items,com);
int cap=Integer.parseInt(capacity.getText().toString());
maxweight=cap;
for(Item i:items){
if(Integer.parseInt(i.weight.getText().toString())<=cap){
cap=cap-Integer.parseInt(i.weight.getText().toString());
maxvalue+=Integer.parseInt(i.value.getText().toString());
}
}
maxweight=maxweight-cap;
textView.setVisibility(View.VISIBLE);
textView.setText("Max Value is : "+maxvalue+"\n Total Weight : "+maxweight);
}catch (Exception e){
textView.setVisibility(View.VISIBLE);
textView.setText("Error : "+e.toString());
}
}
});
Go.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
create(Integer.parseInt(editText.getText().toString()));
editText.setVisibility(View.GONE);
Go.setVisibility(View.GONE);
result.setVisibility(View.VISIBLE);
capacity.setVisibility(View.VISIBLE);
ratio.setVisibility(View.GONE);
value.setVisibility(View.GONE);
weight.setVisibility(View.GONE);
}
});
}
void create(int n){
items=new ArrayList<>();
for(int i=0;i<n;i++){
items.add(new Item(String.valueOf(i+1),null,null));
}
myAdapter=new MyAdapter(getApplicationContext(),R.layout.item,items);
if(ratio.isChecked()){
option=1;
}else if(weight.isChecked()){
option=3;
}else{
option=2;
}
listView.setAdapter(myAdapter);
}
}
|
package br.com.caelum.financas.teste;
import javax.persistence.EntityManager;
import br.com.caelum.financas.modelo.Conta;
import br.com.caelum.financas.util.JPAUtil;
public class TesteConta {
public static void main(String[] args) {
Conta conta = new Conta(1, "Leonardo", "45620", "Caixa", "054");
EntityManager entityManager = new JPAUtil().getEntityManager();
entityManager.getTransaction().begin();
entityManager.persist(conta);
conta.setBanco("Bradesco");
entityManager.getTransaction().commit();
entityManager.close();
}
}
|
package com.cmpickle.volumize.view.edit;
import android.support.annotation.CallSuper;
import com.cmpickle.volumize.view.BasePresenter;
import icepick.State;
/**
* @author Cameron Pickle
* Copyright (C) Cameron Pickle (cmpickle) on 4/9/2017.
*/
public abstract class EditPresenter extends BasePresenter<EditView> {
@State
boolean hasEnteredData;
private EditView editView;
private EditRouter editRouter;
@CallSuper
@Override
protected void setView(EditView view) {
this.editView = view;
}
protected EditRouter getEditRouter() {
return editRouter;
}
@CallSuper
public void setEditRouter(EditRouter editRouter) {
this.editRouter = editRouter;
}
public void clearEnteredData() {
hasEnteredData = false;
updateSaveButton();
}
protected boolean hasEnteredData() {
return hasEnteredData;
}
protected boolean isSaveable() {
return hasEnteredData();
}
public void onAttemptCancel() {
if(hasEnteredData) {
editView.confirmCancel();
} else {
editRouter.leave();
}
}
public abstract void onAttemptSave();
public void onBackPressed() {
onAttemptCancel();
}
public void onCancelConfirmed() {
editRouter.leave();
}
public void onCreateOptionsMenuFinished() {
updateSaveButton();
}
public void onDeleteConfirmed() {
}
public void onEnteredData() {
hasEnteredData = true;
updateSaveButton();
}
private void updateSaveButton() {
if(isSaveable()) {
editView.enableSaveButton();
} else {
editView.disableSaveButton();
}
}
}
|
/**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2015 Paco Avila & Josep Llort
*
* No bytes were intentionally harmed during the development of this application.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.util.impexp;
import java.util.Comparator;
public class VersionComparator implements Comparator<String> {
private static final Comparator<String> INSTANCE = new VersionComparator();
public static Comparator<String> getInstance() {
return INSTANCE;
}
public int compare(String ver0, String ver1) {
ver0 = ver0.startsWith("v") ? ver0.substring(1) : ver0;
ver1 = ver1.startsWith("v") ? ver1.substring(1) : ver1;
return compare(ver0.split("\\."), ver1.split("\\."), 0);
}
private int compare(String[] ary1, String[] ary2, int index) {
// if arrays do not have equal size then and comparison reached the upper bound of one of them
// then the longer array is considered the bigger ( --> 2.2.0 is bigger then 2.2)
if(ary1.length <= index || ary2.length <= index) return ary1.length - ary2.length;
int result = Integer.parseInt(ary1[index]) - Integer.parseInt(ary2[index]);
return result == 0 ? compare(ary1, ary2, ++index) : result;
}
}
|
package com.booking.hotelapi.exception;
import javax.validation.ConstraintViolationException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import com.booking.hotelapi.util.Constants;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
//BadInputParamException
@ExceptionHandler({ BadInputParamException.class })
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody
public ResponseEntity<Object> handleBadInputParamException(BadInputParamException ex) {
log.error("BadInputParamException ", ex);
Error error = new Error();
error.setCode(Constants.ERROR_CODE_BAD_INPUT_PARAM);
error.setMessage(ex.getMessage());
log.error("RestExceptionInterceptor.handleBadInputParamException(): " + error.toString());
return new ResponseEntity<>(error, createHeader(), HttpStatus.BAD_REQUEST);
}
//ResourceNotFoundException
@ExceptionHandler({ ResourceNotFoundException.class })
@ResponseStatus(value = HttpStatus.NOT_FOUND)
@ResponseBody
public ResponseEntity<Object> handleHttpResourceNotFoundException(ResourceNotFoundException ex) {
log.error("ResourceNotFoundException ", ex);
Error error = new Error();
error.setCode(Constants.ERROR_CODE_RESOURCE_NOT_FOUND);
error.setMessage(ex.getMessage());
log.error("RestExceptionInterceptor.handleHttpResourceNotFoundException(): " + error.toString());
return new ResponseEntity<>(error, createHeader(), HttpStatus.NOT_FOUND);
}
//Exception
@ExceptionHandler(Exception.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
protected ResponseEntity<Object> handleExceptions(Exception e) {
String message;
Throwable cause;
Throwable resultCause = e;
while ((cause = resultCause.getCause()) != null && resultCause != cause) {
resultCause = cause;
}
if (resultCause instanceof ConstraintViolationException) {
message = (((ConstraintViolationException) resultCause).getConstraintViolations()).iterator().next().getMessage();
} else {
message = resultCause.getMessage();
}
Error error = new Error();
error.setCode(Constants.ERROR_CODE_UNKNOWN_FAILURE);
error.setMessage(resultCause.getClass().getName() + " : " + message);
log.error("RestExceptionInterceptor.handleExceptions(): " + error.toString());
return new ResponseEntity<>(error, createHeader(), HttpStatus.INTERNAL_SERVER_ERROR);
}
private HttpHeaders createHeader() {
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json; charset=UTF-8");
return headers;
}
}
|
package com.example.demo.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.dao.ProductDao;
@Service
public class AppService {
//@Inject == > Byte Buddy weaving
@Autowired
private ProductDao productDao;
@Autowired
private EmailService es;
public void doTask(String name) {
this.productDao.addProduct(name);
es.sendEmail(name);
}
}
|
package com.zhouyi.business.core.model;
import java.io.Serializable;
import java.util.Date;
public class LedenEquipmentParets implements Serializable {
private String pkId;
private String nodeCode;
private String paretsName;
private String paretsPlug;
private String equipmentCode;
private String paretsPlugVersion;
private String deleteFlag;
private String annex;
private String createUserId;
private Date createDatetime;
private String updateUserId;
private Date updateDatetime;
private String paretsSerialNumber;
private static final long serialVersionUID = 1L;
public String getParetsSerialNumber() {
return paretsSerialNumber;
}
public void setParetsSerialNumber(String paretsSerialNumber) {
this.paretsSerialNumber = paretsSerialNumber;
}
public String getPkId() {
return pkId;
}
public void setPkId(String pkId) {
this.pkId = pkId;
}
public String getNodeCode() {
return nodeCode;
}
public void setNodeCode(String nodeCode) {
this.nodeCode = nodeCode;
}
public String getParetsName() {
return paretsName;
}
public void setParetsName(String paretsName) {
this.paretsName = paretsName;
}
public String getParetsPlug() {
return paretsPlug;
}
public void setParetsPlug(String paretsPlug) {
this.paretsPlug = paretsPlug;
}
public String getParetsPlugVersion() {
return paretsPlugVersion;
}
public void setParetsPlugVersion(String paretsPlugVersion) {
this.paretsPlugVersion = paretsPlugVersion;
}
public String getDeleteFlag() {
return deleteFlag;
}
public void setDeleteFlag(String deleteFlag) {
this.deleteFlag = deleteFlag;
}
public String getAnnex() {
return annex;
}
public void setAnnex(String annex) {
this.annex = annex;
}
public String getCreateUserId() {
return createUserId;
}
public void setCreateUserId(String createUserId) {
this.createUserId = createUserId;
}
public Date getCreateDatetime() {
return createDatetime;
}
public void setCreateDatetime(Date createDatetime) {
this.createDatetime = createDatetime;
}
public String getUpdateUserId() {
return updateUserId;
}
public void setUpdateUserId(String updateUserId) {
this.updateUserId = updateUserId;
}
public Date getUpdateDatetime() {
return updateDatetime;
}
public void setUpdateDatetime(Date updateDatetime) {
this.updateDatetime = updateDatetime;
}
public String getEquipmentCode() {
return equipmentCode;
}
public void setEquipmentCode(String equipmentCode) {
this.equipmentCode = equipmentCode;
}
@Override
public String toString() {
return "LedenEquipmentParets{" +
"pkId='" + pkId + '\'' +
", nodeCode='" + nodeCode + '\'' +
", paretsName='" + paretsName + '\'' +
", paretsPlug='" + paretsPlug + '\'' +
", equipmentCode='" + equipmentCode + '\'' +
", paretsPlugVersion='" + paretsPlugVersion + '\'' +
", deleteFlag='" + deleteFlag + '\'' +
", annex='" + annex + '\'' +
", createUserId='" + createUserId + '\'' +
", createDatetime=" + createDatetime +
", updateUserId='" + updateUserId + '\'' +
", updateDatetime=" + updateDatetime +
'}';
}
}
|
package com.github.coyclab.hw7_userinterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView listView = (ListView) findViewById(R.id.list_view_posts);
final PostAdapter postAdapter = new PostAdapter();
listView.setAdapter(postAdapter);
startActivity(new Intent(MainActivity.this, UserProfileActivity.class));
}
class PostAdapter extends BaseAdapter {
@Override
public int getCount() {
return 1;
}
@Override
public Object getItem(int pI) {
return null;
}
@Override
public long getItemId(int pI) {
return 0;
}
@Override
public View getView(final int pI, View pView, final ViewGroup pViewGroup) {
pView = getLayoutInflater().inflate(R.layout.post_content, null);
return pView;
}
}
}
|
package com.nerdydev.mtawrapper.web.service;
import com.nerdydev.mtawrapper.web.dto.CheckIndexFileDto;
import com.nerdydev.mtawrapper.web.dto.WtcFolderNameDto;
import com.nerdydev.mtawrapper.web.exceptions.FileStorageException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Service
public class FileService {
@Value("${mta.upload.ear.directory}")
public String uploadDirectory;
@Value("${mta.upload.ear.output}")
public String outputDirectory;
@Value("${mta.bin.path}")
public String mtaBinPath;
@Value("${jgit.src.checkout.dir}")
public String jgitCheckoutDir;
private static final Logger LOGGER = LoggerFactory.getLogger(FileService.class);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
public List<String> getMtaRules() throws IOException, InterruptedException {
String fileName = mtaBinPath + "rules.txt";
List<String> lines = new ArrayList<>();
BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
line = line.replace("\t", "");
lines.add(line);
}
lines = lines.subList(5, lines.size());
bufferedReader.close();
Thread.sleep(1000);
return lines;
}
public WtcFolderNameDto uploadFile(MultipartFile file, String target) {
String fileName = file.getOriginalFilename() + "-" + dateFormat.format(new Date()) + ".report";
String finalOutdir = outputDirectory + fileName;
try {
Path copyLocation = Paths.get( uploadDirectory + File.separator
+ StringUtils.cleanPath(file.getOriginalFilename()));
Files.copy(file.getInputStream(), copyLocation, StandardCopyOption.REPLACE_EXISTING);
String createOutputDirCommand = "mkdir " + finalOutdir;
commandExecutor(fileName, createOutputDirCommand);
String command = mtaBinPath + "mta-cli --input " + uploadDirectory + file.getOriginalFilename()
+ " --output "
+ finalOutdir + " --target " + target + " > " + mtaBinPath + fileName + ".log" ;
commandExecutor(fileName, command);
Thread.sleep(1000);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
throw new FileStorageException("Could not store file " + file.getOriginalFilename() + ". Please try again!");
}
WtcFolderNameDto wtcFolderNameDto = new WtcFolderNameDto(fileName);
return wtcFolderNameDto;
}
public String commandExecutor(String sourceName, String command) {
try {
Runtime.getRuntime().exec("cmd /c start cmd.exe /K \"" + command);
} catch (IOException e) {
e.printStackTrace();
}
return "command executed and output folder will be available at the following directory" + outputDirectory;
}
public CheckIndexFileDto isFolderPresent(String folderName) {
File file = new File(outputDirectory + folderName + "./index.html");
if (file.exists()) {
return new CheckIndexFileDto("index.html exists");
} else {
LOGGER.info("folder not found");
return new CheckIndexFileDto();
}
}
public File[] getDirectoryListByAscendingDate() {
File files[] = FileUtils.dirListByAscendingDate(new File(outputDirectory));
return files;
}
public File[] getDirectoryListByDescendingDate() {
File files[] = FileUtils.dirListByDescendingDate(new File(outputDirectory));
return files;
}
}
|
/*
3. Valósítsuk meg a Unix-szerű rendszerek grep programját! A Grep paraméterül vár egy szöveget és egy fájlnevet. Miközben olvassa a fájlt:
a) kilistázza azokat a sorokat, melyek megegyeznek a paraméter szöveggel.
b) kilistázza azokat a sorokat, melyben a szöveg megtalálható.
c) Szorgalmi feladat. A sor számát is kiírja, amelyben a szöveg megtalálható. Segítség: használjuk a java.io.LineNumberReader-t, hogy megtudjuk, hanyadik sorban járunk!
Például:
$ echo "Hello, World!\n Howdy?" > hello.txt
$ java Grep World hello.txt
Hello, World!
Jelezzük hibaüzenettel, ha a fájl nem található. Ehhez kezeljük le a java.io.FileNotFoundException típusú kivételt!
Ne kezeljük le az java.io.IOException típusú kivételt, hanem specifikáljuk a main() fejlécében!
Gondoskodjunk minden esetben a fájl lezárásáról!
*/
import java.util.Scanner;
import java.io.*;
public class Grep {
public static void main(String[] args) {
try {
Scanner s = new Scanner(new File(args[1]));
while (s.hasNextLine()) {
String line = s.nextLine();
if (args[0].equals(line)) { // line.contains(args[0])
System.out.println(line);
}
}
s.close();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
}
}
}
|
package com.facebook.react.util;
public class RNVersionUtils {
private static String propertyVersion = "0.55.4-LYNX-1.3.0.63-jsc";
public static String getVersion() {
return propertyVersion;
}
}
/* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\reac\\util\RNVersionUtils.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
/*
* Copyright 2013 Cloudera Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kitesdk.morphline.avro;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Parser;
import org.apache.avro.file.DataFileConstants;
import org.apache.avro.file.DataFileReader;
import org.apache.avro.file.SeekableInput;
import org.apache.avro.generic.GenericContainer;
import org.apache.avro.io.DecoderFactory;
import org.apache.avro.io.ResolvingDecoder;
import org.kitesdk.morphline.api.Command;
import org.kitesdk.morphline.api.CommandBuilder;
import org.kitesdk.morphline.api.MorphlineCompilationException;
import org.kitesdk.morphline.api.MorphlineContext;
import org.kitesdk.morphline.api.Record;
import org.kitesdk.morphline.base.Fields;
import org.kitesdk.morphline.stdio.AbstractParser;
import com.google.common.base.Preconditions;
import com.typesafe.config.Config;
/**
* Command that parses an InputStream that contains Avro binary container file data; for each Avro
* datum, the command emits a morphline record containing the datum as an attachment in
* {@link Fields#ATTACHMENT_BODY}.
*
* The Avro schema that was used to write the Avro data is retrieved from the container. Optionally, the
* Avro schema that shall be used for reading can be supplied as well.
*/
public final class ReadAvroContainerBuilder implements CommandBuilder {
/** The MIME type that input attachments shall have */
public static final String MIME_TYPE = "avro/binary";
@Override
public Collection<String> getNames() {
return Collections.singletonList("readAvroContainer");
}
@Override
public Command build(Config config, Command parent, Command child, MorphlineContext context) {
return new ReadAvroContainer(this, config, parent, child, context);
}
///////////////////////////////////////////////////////////////////////////////
// Nested classes:
///////////////////////////////////////////////////////////////////////////////
static class ReadAvroContainer extends AbstractParser {
protected final Schema readerSchema;
protected FastGenericDatumReader<GenericContainer> datumReader;
private final Map<ByteArrayKey, ResolvingDecoder> resolverCache;
public ReadAvroContainer(CommandBuilder builder, Config config, Command parent, Command child, MorphlineContext context) {
super(builder, config, parent, child, context);
String schemaString = getConfigs().getString(config, "readerSchemaString", null);
if (schemaString != null) {
this.readerSchema = new Parser().parse(schemaString);
} else {
String schemaFile = getConfigs().getString(config, "readerSchemaFile", null);
if (schemaFile != null) {
try {
this.readerSchema = new Parser().parse(new File(schemaFile));
} catch (IOException e) {
throw new MorphlineCompilationException("Cannot parse external Avro reader schema file: " + schemaFile, config, e);
}
} else {
this.readerSchema = null;
}
}
if (getClass() == ReadAvroContainer.class) {
resolverCache = new BoundedLRUHashMap(getConfigs().getInt(config, "schemaCacheCapacity", 100));
validateArguments();
} else {
resolverCache = null;
}
}
@Override
protected boolean doProcess(Record inputRecord, InputStream in) throws IOException {
if (datumReader == null) { // reuse for performance
datumReader = new FastGenericDatumReader(null, readerSchema);
}
DataFileReader<GenericContainer> reader = null;
try {
// TODO: for better performance subclass DataFileReader
// to eliminate expensive SchemaParser.parse() on each new file in DataFileReader.initialize().
// Instead replace the parse() with a lookup in the byte[] cache map.
reader = new DataFileReader(new ForwardOnlySeekableInputStream(in), datumReader);
byte[] writerSchemaBytes = reader.getMeta(DataFileConstants.SCHEMA);
Preconditions.checkNotNull(writerSchemaBytes);
ByteArrayKey writerSchemaKey = new ByteArrayKey(writerSchemaBytes);
ResolvingDecoder resolver = resolverCache.get(writerSchemaKey); // cache for performance
if (resolver == null) {
resolver = createResolver(datumReader.getSchema(), datumReader.getExpected());
resolverCache.put(writerSchemaKey, resolver);
datumReader.setResolver(resolver);
}
Record template = inputRecord.copy();
removeAttachments(template);
template.put(Fields.ATTACHMENT_MIME_TYPE, ReadAvroBuilder.AVRO_MEMORY_MIME_TYPE);
while (reader.hasNext()) {
GenericContainer datum = reader.next();
if (!extract(datum, template)) {
return false;
}
}
} finally {
if (reader != null) {
reader.close();
}
}
return true;
}
protected ResolvingDecoder createResolver(Schema writerSchema, Schema readerSchema) throws IOException {
return DecoderFactory.get().resolvingDecoder(
Schema.applyAliases(writerSchema, readerSchema), readerSchema, null);
}
protected boolean extract(GenericContainer datum, Record inputRecord) {
incrementNumRecords();
Record outputRecord = inputRecord.copy();
outputRecord.put(Fields.ATTACHMENT_BODY, datum);
// pass record to next command in chain:
return getChild().process(outputRecord);
}
}
///////////////////////////////////////////////////////////////////////////////
// Nested classes:
///////////////////////////////////////////////////////////////////////////////
private static final class BoundedLRUHashMap<K,V> extends LinkedHashMap<K,V> {
private final int capacity;
private BoundedLRUHashMap(int capacity) {
super(16, 0.5f, true);
this.capacity = capacity;
}
@Override
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > capacity;
}
}
///////////////////////////////////////////////////////////////////////////////
// Nested classes:
///////////////////////////////////////////////////////////////////////////////
private static final class ByteArrayKey {
private byte[] bytes;
public ByteArrayKey(byte[] bytes) {
this.bytes = bytes;
}
@Override
public boolean equals(Object other) {
ByteArrayKey otherKey = (ByteArrayKey) other;
return Arrays.equals(bytes, otherKey.bytes);
}
@Override
public int hashCode() {
return Arrays.hashCode(bytes);
}
}
///////////////////////////////////////////////////////////////////////////////
// Nested classes:
///////////////////////////////////////////////////////////////////////////////
/**
* A {@link SeekableInput} backed by an {@link InputStream} that can only advance
* forward, not backwards.
*/
static final class ForwardOnlySeekableInputStream implements SeekableInput {
// class is public for testing only!
private final InputStream in;
private long pos = 0;
public ForwardOnlySeekableInputStream(InputStream in) {
this.in = in;
}
@Override
public long tell() throws IOException {
return pos;
}
@Override
public int read(byte b[], int off, int len) throws IOException {
int n = in.read(b, off, len);
if (n > 0) {
pos += n;
}
return n;
}
@Override
public long length() throws IOException {
throw new UnsupportedOperationException("Random access is not supported");
}
@Override
public void seek(long p) throws IOException {
long todo = p - pos;
if (todo < 0) {
throw new UnsupportedOperationException("Seeking backwards is not supported");
}
skip(todo);
}
private long skip(long len) throws IOException {
// borrowed from org.apache.hadoop.io.IOUtils.skipFully()
len = Math.max(0, len);
long todo = len;
while (todo > 0) {
long ret = in.skip(todo);
if (ret == 0) {
// skip may return 0 even if we're not at EOF. Luckily, we can
// use the read() method to figure out if we're at the end.
int b = in.read();
if (b == -1) {
throw new EOFException( "Premature EOF from inputStream after " +
"skipping " + (len - todo) + " byte(s).");
}
ret = 1;
}
todo -= ret;
pos += ret;
}
return len;
}
@Override
public void close() throws IOException {
in.close();
}
}
}
|
package nl.jtosti.hermes.security.screen;
import nl.jtosti.hermes.screen.Screen;
import nl.jtosti.hermes.screen.ScreenServiceInterface;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
@Component
public class ScreenAuthenticationProvider implements AuthenticationProvider {
private final ScreenServiceInterface screenService;
private final PasswordEncoder passwordEncoder;
@Autowired
public ScreenAuthenticationProvider(ScreenServiceInterface screenService, PasswordEncoder passwordEncoder) {
this.screenService = screenService;
this.passwordEncoder = passwordEncoder;
}
@Override
public Authentication authenticate(Authentication authentication) {
try {
String screenId = authentication.getName();
String password = authentication.getCredentials().toString();
Screen screen = screenService.getScreenById(Long.parseLong(screenId));
if (screen.isToReceivePassword()) {
throw new ScreenPasswordExpiredException();
}
if (passwordEncoder.matches(password, screen.getPassword())) {
return new UsernamePasswordAuthenticationToken(authentication.getName(), authentication.getCredentials().toString(), screen.getAuthorities());
} else {
throw new BadCredentialsException("");
}
} catch (RuntimeException e) {
return null;
}
}
@Override
public boolean supports(Class<?> auth) {
return auth.equals(UsernamePasswordAuthenticationToken.class);
}
}
|
package com.jk.jkproject.ui.activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.jk.jkproject.utils.ToastUtils;
import com.jk.jkproject.R;
import com.jk.jkproject.base.BActivity;
import com.jk.jkproject.net.AppApis;
import com.jk.jkproject.net.Urls;
import org.json.JSONException;
import org.json.JSONObject;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
/**
* @author Zick
* @params
* @date 2020/7/27 10:04 AM
* @desc 自动回复
*/
public class AutoReplyActivity extends BActivity {
@BindView(R.id.iv_title)
ImageView ivTitle;
@BindView(R.id.tv_left_name)
TextView tvLeftName;
@BindView(R.id.tv_title)
TextView tvTitle;
@BindView(R.id.iv_right_title)
ImageView ivRightTitle;
@BindView(R.id.tv_right_title)
TextView tvRightTitle;
@BindView(R.id.public_top_layout)
RelativeLayout publicTopLayout;
@BindView(R.id.et_int)
EditText etInt;
@BindView(R.id.tv_count)
TextView tvCount;
@BindView(R.id.ll_editor_init)
RelativeLayout llEditorInit;
private Unbinder bind;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto_reply);
bind = ButterKnife.bind(this);
initView();
}
@Override
protected void onStart() {
super.onStart();
initData();
}
private void initData() {
}
private void initView() {
AppApis.getGetAutoReplyInfo(this);
tvRightTitle.setText("保存");
tvRightTitle.setVisibility(View.VISIBLE);
tvTitle.setText("被关注自动回复");
tvTitle.setTextSize(18);
tvTitle.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
tvRightTitle.setTextColor(getResources().getColor(R.color.color_D83FDD));
etInt.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (!s.toString().trim().isEmpty()) {
if (s.toString().trim().length() <= 200) {
tvCount.setText(s.toString().length() + "/200字");
etInt.setFocusable(true);
} else {
ToastUtils.showShortToast("输入字数已达上限");
etInt.setFocusable(false);
}
} else {
tvCount.setText(s.toString().length() + "/200字");
etInt.setFocusable(true);
}
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
bind.unbind();
}
@Override
public void onSuccess(String url, Object obj) {
super.onSuccess(url, obj);
if (url.equals(Urls.GET_AUTO_REPLY)) {
if (obj != null) {
try {
JSONObject object = new JSONObject(obj.toString());
if (object.getInt("code") == 200) {
ToastUtils.showShortToast("保存成功");
finish();
} else {
ToastUtils.showShortToast(object.getString("msg"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} else if (url.equals(Urls.GET_AUTO_REPLY_INFO)) {
if (obj != null) {
try {
JSONObject object = new JSONObject(obj.toString());
if (object.getInt("code") == 200) {
JSONObject object1 = new JSONObject(object.getString("data"));
String reply = object1.getString("reply");
if (!reply.isEmpty()) {
etInt.setText(reply);
etInt.setSelection(reply.length());
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
@OnClick({R.id.iv_title, R.id.tv_right_title})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.iv_title:
finish();
break;
case R.id.tv_right_title:
if (!etInt.getText().toString().trim().isEmpty()) {
AppApis.getGetAutoReply(etInt.getText().toString().trim(), this);
} else {
ToastUtils.showShortToast("回复内容不能为空");
}
break;
}
}
}
|
package cn.edu.nju.se.lawcase.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import cn.edu.nju.se.lawcase.entities.Chapter;
import cn.edu.nju.se.lawcase.entities.Statute;
public class TxtToStatute {
public static List<File> getFileList(String strPath) {
List<File> filelist = new ArrayList<>();
File dir = new File(strPath);
File[] files = dir.listFiles();
//System.out.println(files.length);
if (files != null) {
for (int i = 0; i < files.length; i++) {
String fileName = files[i].getName();
//System.out.println(fileName);
if (files[i].isDirectory()) {
getFileList(files[i].getAbsolutePath());
} else if (fileName.endsWith("txt")) {
filelist.add(files[i]);
} else {
continue;
}
}
}
return filelist;
}
public static Statute transOneTxt(File file) {
Statute statute =new Statute();
statute.setStatuteName(file.getName().substring(0,file.getName().length()-4));
//System.out.println("--------"+file.getName());
StringBuilder result;
try{
BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
String s = null;
List<Chapter> chapters = new ArrayList<Chapter>();
while((s = br.readLine())!=null){
//result.append(System.lineSeparator()+s);
while(s!=null&&s.endsWith("条")){
Chapter tmpChapter = new Chapter();
result = new StringBuilder();
tmpChapter.setChapternumber(s);
System.out.println(s);
System.out.println("-----------");
while((s=br.readLine())!=null){
if(s.endsWith("条")) break;
if(s.startsWith("返")||(s.length()>2&&s.charAt(2)=='章')) break;
result.append(s);
}
tmpChapter.setChaptervalue(result.toString());
chapters.add(tmpChapter);
System.out.println(result.toString());
if(s!=null&&(s.startsWith("返")||(s.length()>2&&s.charAt(2)=='章')))
break;
}
}
statute.setChapters(chapters);
br.close();
}catch(Exception e){
e.printStackTrace();
}
return statute;
}
}
|
package com.framework.service.impl;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.framework.bean.FormProduceInfo;
import com.framework.bean.common.Page;
import com.framework.dao.ProFieldMapper;
import com.framework.dao.ProFormMapper;
import com.framework.model.ProField;
import com.framework.model.ProForm;
import com.framework.service.FormService;
import com.framework.util.CamelCaseUtils;
import com.framework.util.LoginUtils;
import com.framework.util.PageFactory;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
@Service
public class FormServiceImpl implements FormService {
private final Logger logger = Logger.getLogger(getClass());
@Autowired
private ProFieldMapper proFieldMapper;
@Autowired
private ProFormMapper proFormMapper;
@Autowired
private FreeMarkerConfigurer freemarkerConfigurer;
@Override
public List<ProField> getTableFields(String tableName) throws Exception {
List<ProField> fields = proFieldMapper.getTableFields(tableName);
for (ProField proField : fields) {
if(!proField.isPri()){
proField.setGridCol(true);
proField.setFormField(true);
proField.setFieldType("textfield");
}
proField.setQuery(false);
proField.setColumnName(proField.getName());
proField.setName(CamelCaseUtils.toCamelCase(proField.getName()));
}
return fields;
}
@Override
public void saveForm(ProForm proForm, List<ProField> fields) throws Exception {
if(null!=proForm.getId()&&proForm.getId()>0){
//更新
proForm.setModifyBy(LoginUtils.getUserInfo().getPersonCode());
proForm.setModifyDate(new Date());
proFormMapper.updateByPrimaryKeySelective(proForm);
for (ProField proField : fields) {
proField.setModifyBy(LoginUtils.getUserInfo().getPersonCode());
proField.setModifyDate(new Date());
proFieldMapper.updateByPrimaryKeySelective(proField);
}
}else{
//新增
proForm.setCreateBy(LoginUtils.getUserInfo().getPersonCode());
proForm.setCreateDate(new Date());
int version = proFormMapper.getTableFormVersion(proForm.getTableName());
proForm.setVersion(version);
int i = proFormMapper.insert(proForm);
if(i>0&&null!=proForm.getId()){
for (ProField proField : fields) {
proField.setCreateBy(LoginUtils.getUserInfo().getPersonCode());
proField.setCreateDate(new Date());
proField.setFormId(proForm.getId());
proFieldMapper.insert(proField);
}
}
}
}
@Override
public void queryFormList(Page<ProForm> page, ProForm proForm) throws Exception {
com.baomidou.mybatisplus.plugins.Page<ProForm> page2 = PageFactory.createFrom(page);
EntityWrapper<ProForm> entityWrapper = new EntityWrapper<>();
if(StringUtils.isNotEmpty(proForm.getName())){
entityWrapper.like("name", proForm.getName());
}
if(StringUtils.isNotEmpty(proForm.getTableName())){
entityWrapper.like("table_name", proForm.getTableName());
}
List<ProForm> forms = proFormMapper.selectPage(page2, entityWrapper);
page.setRows(forms);
page.setTotal(page2.getTotal());
}
@Override
public ProForm getForm(Integer formId) throws Exception {
return proFormMapper.selectById(formId);
}
@Override
public List<ProField> getFormFields(Integer formId) throws Exception {
EntityWrapper<ProField> wrapper = new EntityWrapper<>();
wrapper.eq("form_id", formId);
return proFieldMapper.selectList(wrapper);
}
@Override
public void produceCodes(FormProduceInfo formProduceInfo) throws Exception {
Configuration configuration = freemarkerConfigurer.getConfiguration();
this.createJavaCodes(formProduceInfo,configuration);
}
/**
*
* @param formProduceInfo
* @param configuration
* @throws Exception
*/
private void createJavaCodes(FormProduceInfo formProduceInfo, Configuration configuration) throws Exception {
Map<String, Object> modelMap = new HashMap<>();
ProForm form = this.getForm(formProduceInfo.getFormId());
List<ProField> fields = this.getFormFields(formProduceInfo.getFormId());
ProField priField = new ProField();
for (ProField proField : fields) {
if("int".equals(proField.getDataType().toLowerCase())
||"bigint".equals(proField.getDataType().toLowerCase())){
proField.setDataType("integer");
}
if("datetime".equals(proField.getDataType().toLowerCase())){
proField.setDataType("timestamp");
}
if("mediumtext".equals(proField.getDataType().toLowerCase())){
proField.setDataType("varchar");
}
if(proField.getDataType().toLowerCase().contains("blob")){
proField.setDataType("blob");
}
if(proField.isPri()){
priField = proField;
}
}
modelMap.put("form", form);
modelMap.put("priField", priField);
modelMap.put("className", formProduceInfo.getClassName());
modelMap.put("packageName", formProduceInfo.getPackageName());
modelMap.put("fieldList", fields);
if(formProduceInfo.getCodeFileType().contains("java")){
String filePath = formProduceInfo.getJavaFilePath();
String packageName = formProduceInfo.getPackageName();
if(StringUtils.isNotEmpty(packageName)){
filePath += ("/"+packageName.replace(".", "/"));
}
String controllerPath = filePath + "/controller/"+formProduceInfo.getClassName()+"Controller.java";
writeCodeFile("default_controller_template.ftl",controllerPath,modelMap);
String servicePath = filePath + "/service/"+formProduceInfo.getClassName()+"Service.java";
writeCodeFile("default_service_template.ftl",servicePath,modelMap);
String modelPath = filePath + "/model/"+formProduceInfo.getClassName()+".java";
writeCodeFile("default_model_template.ftl",modelPath,modelMap);
String voPath = filePath + "/model/vo/"+formProduceInfo.getClassName()+"VO.java";
writeCodeFile("default_vo_template.ftl",voPath,modelMap);
String serviceImplPath = filePath + "/service/impl/"+formProduceInfo.getClassName()+"ServiceImpl.java";
writeCodeFile("default_service_impl_template.ftl",serviceImplPath,modelMap);
String daoPath = filePath + "/dao/"+formProduceInfo.getClassName()+"Mapper.java";
writeCodeFile("default_dao_template.ftl",daoPath,modelMap);
}
if(formProduceInfo.getCodeFileType().contains("mapperXml")){
String filePath = formProduceInfo.getMapperXmlFilePath();
String packageName = formProduceInfo.getPackageName();
if(StringUtils.isNotEmpty(packageName)){
filePath += ("/"+packageName.replace(".", "/"));
}
writeCodeFile("default_mapper_xml_template.ftl",filePath+"/"+formProduceInfo.getClassName()+".xml",modelMap);
}
if(formProduceInfo.getCodeFileType().contains("jsp")){
String filePath = formProduceInfo.getJspFilePath();
String packageName = formProduceInfo.getPackageName();
if(StringUtils.isNotEmpty(packageName)){
filePath += ("/"+packageName.replace(".", "/"));
}
String subPackageName = formProduceInfo.getClassName().substring(0,1).toLowerCase()+formProduceInfo.getClassName().substring(1);
filePath += ("/"+subPackageName);
writeCodeFile("default_jsp_template.ftl",filePath+"/"+subPackageName+"Manage.jsp",modelMap);
}
if(formProduceInfo.getCodeFileType().contains("js")){
String filePath = formProduceInfo.getJsFilePath();
String packageName = formProduceInfo.getPackageName();
if(StringUtils.isNotEmpty(packageName)){
filePath += ("/"+packageName.replace(".", "/"));
}
String subPackageName = formProduceInfo.getClassName().substring(0,1).toLowerCase()+formProduceInfo.getClassName().substring(1);
filePath += ("/"+subPackageName);
writeCodeFile("default_js_template.ftl",filePath+"/"+subPackageName+"Manage.js",modelMap);
}
}
private void writeCodeFile(String tplName, String path, Map<String, Object> modelMap) {
try {
StringWriter swriter = new StringWriter();
Template template = freemarkerConfigurer.getConfiguration().getTemplate(tplName, "UTF-8");
template.process(modelMap, swriter);
File file = new File(path);
FileUtils.writeStringToFile(file, swriter.toString(), "UTF-8");
IOUtils.closeQuietly(swriter);
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new RuntimeException(e.getMessage());
}
}
}
|
package com.tencent.mm.ae;
import android.database.Cursor;
import com.tencent.mm.model.ah;
import com.tencent.mm.model.au;
import com.tencent.mm.model.c;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.ab;
public final class d extends ah {
public final void transfer(int i) {
x.d("MicroMsg.VerifyFlagDataTransfer", "the previous version is %d", new Object[]{Integer.valueOf(i)});
if (gV(i)) {
h.mEJ.e(336, 10, 1);
long currentTimeMillis = System.currentTimeMillis();
au.HU();
if (bi.f((Integer) c.DT().get(86017, null)) == 3) {
x.w("MicroMsg.VerifyFlagDataTransfer", "check old contact not exist");
return;
}
au.HU();
c.FO().fV("rcontact", "update rcontact set verifyflag=0 where verifyflag is null;");
au.HU();
Cursor c = c.FR().c("@all.weixin.android", "", null);
c.moveToFirst();
while (!c.isAfterLast()) {
ab abVar = new ab();
abVar.d(c);
au.HU();
c.FR().c(abVar.field_username, abVar);
c.moveToNext();
}
c.close();
x.d("MicroMsg.VerifyFlagDataTransfer", "update verifyflag from the beginning to update finish use %d ms", new Object[]{Long.valueOf(System.currentTimeMillis() - currentTimeMillis)});
au.HU();
c.DT().set(86017, Integer.valueOf(3));
x.d("MicroMsg.VerifyFlagDataTransfer", "update verifyflag use time " + (System.currentTimeMillis() - currentTimeMillis) + " ms");
return;
}
x.w("MicroMsg.VerifyFlagDataTransfer", "do not need transfer");
}
public final boolean gV(int i) {
return i != 0 && i < 604176383;
}
public final String getTag() {
return "MicroMsg.VerifyFlagDataTransfer";
}
}
|
package edu.temple.convoy.api;
import android.content.Context;
import android.util.Log;
import com.android.volley.Response;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import edu.temple.convoy.utils.Constants;
public class ConvoyAPI extends BaseAPI {
public ConvoyAPI(Context initialContext) {
super(initialContext);
}
@Override
protected String getApiSuffix() {
return "convoy.php";
}
/**
* Create a new convoy using the remote API
*
* @param listener
*/
public void create(String username, String sessionKey, ResultListener listener) {
Map<String, String> params = new HashMap<>();
params.put(Constants.API_KEY_ACTION, Constants.API_ACTION_CREATE);
params.put(Constants.API_KEY_USERNAME, username);
params.put(Constants.API_KEY_SESSION_KEY, sessionKey);
String apiName = "CreateConvoyAPI";
post(params, getListenerForAPI(apiName, listener));
}
/**
* End an existing convoy using the remote API
*
* @param listener
*/
public void end(String username, String sessionKey, String convoyID, ResultListener listener) {
Map<String, String> params = new HashMap<>();
params.put(Constants.API_KEY_ACTION, Constants.API_ACTION_END);
params.put(Constants.API_KEY_USERNAME, username);
params.put(Constants.API_KEY_SESSION_KEY, sessionKey);
params.put(Constants.API_KEY_CONVOY_ID, convoyID);
String apiName = "EndConvoyAPI";
post(params, getListenerForAPI(apiName, listener));
}
/**
* Submits a request for the indicated user to join the indicated convoy
*
* @param username
* @param sessionKey
* @param convoyID
* @param listener
*/
public void join(String username, String sessionKey, String convoyID, ResultListener listener) {
Map<String, String> params = new HashMap<>();
params.put(Constants.API_KEY_ACTION, Constants.API_ACTION_JOIN);
params.put(Constants.API_KEY_USERNAME, username);
params.put(Constants.API_KEY_SESSION_KEY, sessionKey);
params.put(Constants.API_KEY_CONVOY_ID, convoyID);
String apiName = "JoinConvoyAPI";
post(params, getListenerForAPI(apiName, listener));
}
/**
* Submits a request for the indicated user to leave the indicated convoy
*
* @param username
* @param sessionKey
* @param convoyID
* @param listener
*/
public void leave(String username, String sessionKey, String convoyID, ResultListener listener) {
Map<String, String> params = new HashMap<>();
params.put(Constants.API_KEY_ACTION, Constants.API_ACTION_LEAVE);
params.put(Constants.API_KEY_USERNAME, username);
params.put(Constants.API_KEY_SESSION_KEY, sessionKey);
params.put(Constants.API_KEY_CONVOY_ID, convoyID);
String apiName = "LeaveConvoyAPI";
post(params, getListenerForAPI(apiName, listener));
}
/**
* Updates the current user's location with the backend server using the associated API
*
* @param username
* @param sessionKey
* @param convoyID
* @param latitude
* @param longitude
* @param listener
*/
public void updateLocation(String username, String sessionKey, String convoyID,
String latitude, String longitude, ResultListener listener) {
Map<String, String> params = new HashMap<>();
params.put(Constants.API_KEY_ACTION, Constants.API_ACTION_UPDATE);
params.put(Constants.API_KEY_USERNAME, username);
params.put(Constants.API_KEY_SESSION_KEY, sessionKey);
params.put(Constants.API_KEY_CONVOY_ID, convoyID);
params.put(Constants.API_KEY_LATITUDE, latitude);
params.put(Constants.API_KEY_LONGITUDE, longitude);
String apiName = "UpdateLocationConvoyAPI";
post(params, getListenerForAPI(apiName, listener));
}
/**
* Generate a response listener for the provided API Name and results listener
*
* @param apiName
* @param resultListener
* @return
*/
protected Response.Listener<String> getListenerForAPI(String apiName,
AccountAPI.ResultListener resultListener) {
/*
Lambda notation ... takes the place of:
new Response.Listener<String>() {
@Override
public void onResponse(String origResponse) {
*/
Response.Listener<String> listener = origResponse -> {
try {
Log.d(Constants.LOG_TAG, apiName + " - Received response: " + origResponse);
JSONObject response = new JSONObject(origResponse);
String status = response.getString(Constants.API_KEY_STATUS);
if (status.equals(Constants.API_STATUS_SUCCESS)) {
resultListener.onSuccess(response.getString(Constants.API_KEY_CONVOY_ID));
} else if (status.equals(Constants.API_STATUS_ERROR)) {
resultListener.onFailure(response.getString(Constants.API_KEY_MESSAGE));
} else {
Log.e(Constants.LOG_TAG, apiName + " - Unrecognized result status: " + status);
}
} catch (JSONException e) {
Log.e(Constants.LOG_TAG, apiName + " - Unable to parse results from JSON Object");
e.printStackTrace();
}
};
return listener;
}
}
|
package com.example.demo.Mappers;
import com.example.demo.domain.Course;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
public interface CourseMapper {
public Course getByKh(String kh);
public List<Map> getAll();
public boolean insert(@Param("kh") String kh, @Param("km")String km,
@Param("xf")Integer xf, @Param("xs")Integer xs,
@Param("cjRatio")double cjRatio, @Param("yxh")String yxh);
}
|
import java.io.*;
import java.util.*;
class natural
{
public static void main(String args[])
{
int sum=0,r,n;
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
while(n>0)
{
r=n%10;
sum=sum+r;
n=n/10;
}
System.out.println(sum);
}
}
|
package com.tencent.mm.storage;
import com.tencent.mm.a.e;
import com.tencent.mm.kernel.g;
import com.tencent.mm.plugin.report.f;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.smtt.sdk.TbsDownloadConfig;
import java.util.List;
final class al {
protected final long taQ = TbsDownloadConfig.DEFAULT_RETRY_INTERVAL_SEC;
private ak taR = new ak();
public al() {
StringBuilder stringBuilder = new StringBuilder();
g.Ek();
byte[] f = e.f(stringBuilder.append(g.Ei().cachePath).append("checkmsgid.ini").toString(), 0, -1);
if (!bi.bC(f)) {
try {
this.taR.aG(f);
if (clM()) {
clL();
}
} catch (Throwable e) {
x.w("MicroMsg.DelSvrIdMgr", "DelSvrIDs parse Error");
x.e("MicroMsg.DelSvrIdMgr", "exception:%s", bi.i(e));
}
}
}
private void clL() {
x.i("MicroMsg.DelSvrIdMgr", "summerdel toFile tid[%d] [%d, %d ,%d] stack[%s]", Long.valueOf(Thread.currentThread().getId()), Integer.valueOf(this.taR.taN.size()), Integer.valueOf(this.taR.taO.size()), Integer.valueOf(this.taR.taP.size()), bi.cjd());
try {
this.taR.taM.clear();
this.taR.taL.clear();
this.taR.taK.clear();
ak akVar = new ak();
akVar.taN.addAll(this.taR.taN);
akVar.taO.addAll(this.taR.taO);
akVar.taP.addAll(this.taR.taP);
byte[] toByteArray = akVar.toByteArray();
StringBuilder stringBuilder = new StringBuilder();
g.Ek();
e.b(stringBuilder.append(g.Ei().cachePath).append("checkmsgid.ini").toString(), toByteArray, toByteArray.length);
String str = "MicroMsg.DelSvrIdMgr";
String str2 = "summerdel toFile done [%d, %d, %d] data len[%d]";
Object[] objArr = new Object[4];
objArr[0] = Integer.valueOf(akVar.taN.size());
objArr[1] = Integer.valueOf(akVar.taO.size());
objArr[2] = Integer.valueOf(akVar.taP.size());
objArr[3] = Integer.valueOf(toByteArray == null ? -1 : toByteArray.length);
x.i(str, str2, objArr);
} catch (Throwable e) {
f.mDy.a(111, 168, 1, false);
x.printErrStackTrace("MicroMsg.DelSvrIdMgr", e, "summerdel ", new Object[0]);
}
}
protected final boolean gm(long j) {
if (clM()) {
clL();
}
return this.taR.taN.contains(Long.valueOf(j)) || this.taR.taO.contains(Long.valueOf(j)) || this.taR.taP.contains(Long.valueOf(j));
}
protected final void j(int i, long j, long j2) {
a(i, j, j2, true);
}
protected final void a(int i, long j, long j2, boolean z) {
if (j != 0) {
if (z) {
clM();
}
switch (i - ((int) (j2 / TbsDownloadConfig.DEFAULT_RETRY_INTERVAL_SEC))) {
case 0:
this.taR.taN.add(Long.valueOf(j));
break;
case 1:
this.taR.taO.add(Long.valueOf(j));
break;
case 2:
this.taR.taP.add(Long.valueOf(j));
break;
default:
x.e("MicroMsg.DelSvrIdMgr", "should not add to thease lists, dayIndex:%d", Integer.valueOf(i - ((int) (j2 / TbsDownloadConfig.DEFAULT_RETRY_INTERVAL_SEC))));
break;
}
if (z) {
clL();
}
}
}
protected final void h(List<Integer> list, List<Long> list2) {
x.i("MicroMsg.DelSvrIdMgr", "add size:%d", Integer.valueOf(list.size()));
clM();
int VE = (int) (bi.VE() / TbsDownloadConfig.DEFAULT_RETRY_INTERVAL_SEC);
for (int i = 0; i < list.size(); i++) {
a(VE, (long) ((Integer) list.get(i)).intValue(), ((Long) list2.get(i)).longValue(), false);
}
clL();
}
private boolean clM() {
x.v("MicroMsg.DelSvrIdMgr", "checkOldData todayIndex:%d, t0Size:%d, t1Size:%d, t2Size:%d", Integer.valueOf(this.taR.taJ), Integer.valueOf(this.taR.taN.size()), Integer.valueOf(this.taR.taO.size()), Integer.valueOf(this.taR.taP.size()));
int VE = (int) (bi.VE() / TbsDownloadConfig.DEFAULT_RETRY_INTERVAL_SEC);
int i = VE - this.taR.taJ;
this.taR.taJ = VE;
switch (i) {
case 0:
return false;
case 1:
this.taR.taP = this.taR.taO;
this.taR.taO = this.taR.taN;
this.taR.taN.clear();
return true;
case 2:
this.taR.taP = this.taR.taN;
this.taR.taO.clear();
this.taR.taN.clear();
return true;
default:
this.taR.taP.clear();
this.taR.taO.clear();
this.taR.taN.clear();
return true;
}
}
}
|
package edu.floridapoly.polycamsportal.Database;
/*
public static final String SCHEDULE_COL_ID = "ID";
public static final String SCHEDULE_COL_USER = "user";
public static final String SCHEDULE_COL_NAME = "name";
*/
public class ScheduleItem {
private String title;
private String name;
private String user;
public ScheduleItem() {
this("Schedule", "user");
}
public ScheduleItem(String title, String user) {
this.title = title;
this.name = title;
this.user = user;
}
public String getTitle() {
return title;
}
public String getName() {
return title;
}
public String getUser() {
return user;
}
}
|
package com.angrykings;
import com.badlogic.gdx.math.Vector2;
import org.json.JSONException;
import org.json.JSONObject;
public class KeyframeData implements IJsonSerializable {
public int entityId;
public Vector2 position;
public float angle;
public KeyframeData() {
this.position = new Vector2();
}
public KeyframeData(JSONObject json) throws JSONException {
this();
this.fromJson(json);
}
private float lerp(float v0, float v1, float t) {
return v0+(v1-v0)*t;
}
public KeyframeData interpolate(KeyframeData data, float t) {
KeyframeData interpolated = new KeyframeData();
interpolated.position.x = lerp(this.position.x, data.position.x, t);
interpolated.position.y = lerp(this.position.y, data.position.y, t);
interpolated.angle = lerp(this.angle, data.angle, t);
return interpolated;
}
@Override
public JSONObject toJson() throws JSONException {
JSONObject json = new JSONObject();
json.put("i", this.entityId);
json.put("x", this.position.x);
json.put("y", this.position.y);
json.put("a", this.angle);
return json;
}
@Override
public void fromJson(JSONObject json) throws JSONException {
this.entityId = json.getInt("i");
this.position = new Vector2((float) json.getDouble("x"), (float) json.getDouble("y"));
this.angle = (float) json.getDouble("a");
}
}
|
package com.batiaev.java3.lesson7;
import org.junit.Test;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Lesson7Annotation {
Class<? extends Throwable> expected() default Test.None.class;
}
|
package de.rwth.i9.palm.persistence;
import de.rwth.i9.palm.model.Role;
public interface RoleDAO extends GenericDAO<Role>, InstantiableDAO
{
public Role getRoleByName( String roleName );
}
|
package com.coalesce.config;
import java.util.List;
public interface IEntry {
/**
* Gets a value from a config entry.
*
* @return A string from the specified path.
*/
String getString();
/**
* Gets a value from a config entry.
*
* @return A double from the specified path.
*/
double getDouble();
/**
* Gets a value from a config entry.
*
* @return An integer from the specified path.
*/
int getInt();
/**
* Gets a value from a config entry.
*
* @return A long from the specified path.
*/
long getLong();
/**
* Gets a value from a config entry.
*
* @return A boolean from the specified path.
*/
boolean getBoolean();
/**
* Gets a value from a config entry.
*
* @return A list from the specified path.
*/
List<?> getList();
/**
* Gets a string list from an entry.
*
* @return The String list.
*/
List<String> getStringList();
/**
* Gets the path of this entry.
*
* @return The path in the config.
*/
String getPath();
/**
* Gets the value of this entry.
*
* @return The value of this entry.
*/
Object getValue();
/**
* Sets the path of this entry.
*
* @param newpath The new path this entry will have.
*/
IEntry setPath(String newpath);
/**
* Sets the value of this entry.
*
* @param value The new value of this entry.
*/
IEntry setValue(Object value);
/**
* Gets the database this entry is held in.
*
* @return The entry's database.
*/
IConfig getConfig();
/**
* Gets the name of this entry.
*
* @return The entry name.
*/
String getName();
/**
* Allows quick removal and moving of an Entry to another configuration file.
*
* @param config The new configuration file.
* @return The new entry.
*/
IEntry setConfig(IConfig config);
/**
* Removes the entry.
*/
void remove();
}
|
package com.cn.jingfen.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.cn.jingfen.service.UserService;
import com.cn.jingfen.vo.Muser;
import com.cn.jingfen.vo.User;
@Controller
public class UserController {
@Autowired
private UserService userService;
//查询所有用户
@RequestMapping("/queryUser")
@ResponseBody
public JSONObject queryUser(HttpServletRequest request,HttpServletResponse response) {
JSONObject json=new JSONObject();
String username = request.getParameter("username");
User user = userService.findUserByUserName(username);
json.put("user", user);
json.put("status", "success");
json.put("message", "查询成功");
return json;
}
//查询所有用户
@RequestMapping("/queryallUser")
@ResponseBody
public JSONObject queryallUser(HttpServletRequest request,HttpServletResponse response) {
JSONObject json=new JSONObject();
List<Muser> list = userService.findAll();
json.put("users", list);
json.put("status", "success");
json.put("message", "查询成功");
return json;
}
}
|
package com.wonders.task.audit.dbx.service.impl;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.wonders.task.audit.dbx.dao.DbxDao;
import com.wonders.task.audit.dbx.service.DbxService;
@Transactional(value = "txManager2", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
@Repository("dbxService")
@Scope("prototype")
public class DbxServiceImpl implements DbxService{
private DbxDao dbxDao;
public DbxDao getDbxDao() {
return dbxDao;
}
@Autowired(required = false)
public void setDbxDao(@Qualifier(value = "dbxDao") DbxDao dbxDao) {
this.dbxDao = dbxDao;
}
public List<String[]> findTasksingByLoginName(String loginName){
return dbxDao.findTasksingByLoginName(loginName);
}
public Map<Long,Integer> getDeptsLevel(List<String> deptIds){
return dbxDao.getDeptsLevel(deptIds);
}
public String countTimeOut(String loginName){
return dbxDao.countTimeOut(loginName);
}
public int getUrgeCount(String userName,String nowDeptId,boolean falg,List<String> deptIds){
return dbxDao.getUrgeCount(userName, nowDeptId, falg, deptIds);
}
public long countMessage(String login_name){
return dbxDao.countMessage(login_name);
}
public int countJbx(String loginName,String dept_id){
return dbxDao.countJbx(loginName, dept_id);
}
}
|
package app.election;
import app.enums.ElectionType;
import app.enums.Parties;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class ElectionData {
//ElectionData needs to be preprocessed before hand
private HashMap<Parties, Integer> voterDistribution;
private int electionYear;
private ElectionType electionType;
private int totalVotes;
private List<Representative> reps;
private Parties winner;
public ElectionData(){
this.voterDistribution = new HashMap<>();
this.reps = new ArrayList<>();
this.totalVotes = 0;
}
public void addRepresentative(Representative rep){
reps.add(rep);
}
public int getNumVotesForDem() {
return voterDistribution.get(Parties.DEMOCRATIC);
}
public int getNumVotesForRep() {
return voterDistribution.get(Parties.REPUBLICAN);
}
public HashMap<Parties, Integer> getVoterDistribution() {
return voterDistribution;
}
public int getElectionYear(){
return electionYear;
}
public ElectionType getElectionType() {
return electionType;
}
public int getTotalVotes() {
return totalVotes;
}
public List<Representative> getReps() {
return reps;
}
public Parties getWinner() {
return winner;
}
public void addTotalVotes(int votes){
this.totalVotes += votes;
}
public void setVoterDistribution(HashMap<Parties, Integer> voterDistribution) {
this.voterDistribution = voterDistribution;
}
public void setTotalVotes(int totalVotes) {
this.totalVotes = totalVotes;
}
public void setReps(List<Representative> reps) {
this.reps = reps;
}
public void setWinner(Parties winner) {
this.winner = winner;
}
public void setYear(int year){
this.electionYear = year;
}
public void setElectionType(ElectionType type){
this.electionType = type;
}
}
|
package com.opensource.redisaux.bloomfilter.core.filter;
import java.util.concurrent.TimeUnit;
class InnerInfo {
private double fpp;
private long exceptionInsert;
private String keyPrefix;
private String keyName;
private long timeout;
private TimeUnit timeUnit;
private boolean enableGrow;
private double growRate;
public InnerInfo(AddCondition addCondition) {
this.fpp = addCondition.fpp;
this.exceptionInsert = addCondition.exceptionInsert;
this.keyPrefix = addCondition.keyPrefix;
this.keyName = addCondition.keyName;
this.timeout = addCondition.timeout;
this.timeUnit = addCondition.timeUnit;
this.growRate=addCondition.growRate;
this.enableGrow=addCondition.enableGrow;
}
public InnerInfo(ExpireCondition expireCondition){
this.keyPrefix = expireCondition.keyPrefix;
this.keyName = expireCondition.keyName;
this.timeout = expireCondition.timeout;
this.timeUnit = expireCondition.timeUnit;
}
public InnerInfo(BaseCondition condition){
this.keyPrefix = condition.keyPrefix;
this.keyName = condition.keyName;
}
public double getFpp() {
return fpp;
}
public double getGrowRate(){return growRate;}
public long getExceptionInsert() {
return exceptionInsert;
}
public String getKeyPrefix() {
return keyPrefix;
}
public String getKeyName() {
return keyName;
}
public long getTimeout() {
return timeout;
}
public TimeUnit getTimeUnit() {
return timeUnit;
}
public boolean isEnableGrow(){return enableGrow;}
}
|
package com.dvt.example.producer;
public class RestApplication {
}
|
package com.rs.utils;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import com.rs.game.player.Player;
import com.rs.utils.SerializableFilesManager;
public class SaveEditor extends JFrame {
private static final long serialVersionUID = 147116517709513176L;
private static final int FRAME_WIDTH = 250;
private static final int FRAME_HEIGHT = 300;
private static final String TITLE = "718+ player save editor";
private Player playerToEdit;
private static Map<String, Component> components;
public static Map<String, Component> getComponents1() {
return components;
}
private Method[] playerMethods;
private void addTextField(String name, Object value) {
JFormattedTextField textField = new JFormattedTextField(value);
textField.setColumns(15);
addLabel(name + "label", name + ":");
components.put(name, textField);
}
private JMenuBar addMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem save = new JMenuItem("Save");
save.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
savePlayer();
}
});
JMenuItem load = new JMenuItem("Load");
load.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
loadPlayer();
}
});
file.add(save);
file.add(load);
menuBar.add(file);
return menuBar;
}
private void addLabel(String name, String text) {
JLabel label = new JLabel(text);
components.put(name, label);
}
private boolean validReturnType(String returnType) {
return returnType.equals("int") ||
returnType.equals("long") ||
returnType.equals("boolean") ||
returnType.equals("double") ||
returnType.equals("float") ||
returnType.equals("char") ||
returnType.equals("byte") ||
returnType.equals("short") ||
returnType.equals("class java.lang.String");
}
private JLabel statusLabel = new JLabel();
public static JPanel editorContainer = new JPanel();
private void addComponents() {
if (playerToEdit == null) {
return;
}
statusLabel.setText("Currently editing: " + playerToEdit.getUsername());
this.add(statusLabel, BorderLayout.NORTH);
for (Method method : playerMethods) {
try {
Object methodValue = method.invoke(playerToEdit);
String methodName = method.getName();
if (methodName.equals("toString") || methodName.contains("packet") || methodName.equals("getUsername")
|| methodName.equals("getPassword") || methodName.contains("MapSize") || methodName.contains("getClientIndex")
|| methodName.contains("getIndex") || methodName.contains("getNextFaceEntity")) {
continue;
}
if (methodValue == null) {
continue;
}
if (!validReturnType(method.getReturnType().toString())) {
continue;
}
addTextField(methodName, method.invoke(playerToEdit));
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
continue;
}
}
editorContainer.setLayout(new GridLayout(0, 1, 0, 5));
for (Map.Entry<String, Component> entry : components.entrySet()) {
editorContainer.add(entry.getValue());
}
JScrollPane scrollPane = new JScrollPane(editorContainer);
scrollPane.setBounds(1, 20, FRAME_WIDTH - 5, FRAME_HEIGHT - 5);
this.add(scrollPane);
this.add(new SearchPanel(), BorderLayout.SOUTH);
this.revalidate();
}
private void updateComponents() {
statusLabel.setText("Currently editing: " + playerToEdit.getUsername());
for (Entry<String, Component> entry : components.entrySet()) {
if (entry.getKey().contains("label")) {
continue;
}
if (entry.getValue() instanceof JLabel) {
continue;
}
for (Method method : playerMethods) {
if (!entry.getKey().equals(method.getName())) {
continue;
}
if (method.getParameterTypes().length > 0) {
continue;
}
if (method.getName().equals("hasWalkSteps")) {
continue;
}
try {
((JFormattedTextField) entry.getValue()).setValue(method.invoke(playerToEdit));
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
public SaveEditor() {
super(TITLE);
this.setUndecorated(false);
this.setResizable(false);
this.setSize(FRAME_WIDTH, FRAME_HEIGHT);
this.setLayout(new BorderLayout());
this.setEnabled(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
components = new LinkedHashMap<String, Component>();
this.setJMenuBar(addMenuBar());
this.setVisible(true);
}
private void loadPlayer() {
final String playerName = JOptionPane.showInputDialog(null, "Enter the name of the player you wish to edit: ", "718+ player save editor", JOptionPane.INFORMATION_MESSAGE);
playerToEdit = SerializableFilesManager.loadPlayer(playerName);
if (playerToEdit == null) {
JOptionPane.showMessageDialog(null, "No such player save.");
return;
}
playerMethods = playerToEdit.getClass().getMethods();
if (components.size() == 0) {
addComponents();
} else {
updateComponents();
}
}
private void savePlayer() {
if (playerToEdit == null) {
return;
}
for (Method method : playerMethods) {
String methodName = method.getName();
if (!methodName.startsWith("set")) {
continue;
}
String getter = methodName.replace("set", "get");
if (!components.containsKey(getter)) {
getter = methodName.replace("set", "is");
if (!components.containsKey(getter)) {
getter = methodName.replace("set", "has");
if (!components.containsKey(getter)) {
continue;
}
}
}
Object value = ((JFormattedTextField) components.get(getter)).getValue();
try {
if (value != null) {
method.invoke(playerToEdit, value);
}
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
System.out.println("Incorrect parameter type: " + method.getName() + ", type: " + value.getClass() + ", required type: " + method.getParameterTypes()[0]);
e.printStackTrace();
}
}
SerializableFilesManager.savePlayer(playerToEdit);
JOptionPane.showMessageDialog(null, playerToEdit.getUsername() + " has been saved!");
}
public static void main(String[] args) {
new SaveEditor();
}
}
class SearchPanel extends JPanel {
private static final long serialVersionUID = -5097053212702527694L;
public static final JTextField searchTextField = new JTextField(15);
public SearchPanel() {
super();
this.add(new JLabel("Search: "), BorderLayout.EAST);
searchTextField.addKeyListener(KEY_LISTENER);
this.add(searchTextField, BorderLayout.WEST);
}
private final static KeyListener KEY_LISTENER = new KeyListener() {
@Override
public void keyPressed(KeyEvent event) {
}
@Override
public void keyReleased(KeyEvent event) {
for (Entry<String, Component> entry : SaveEditor.getComponents1().entrySet()) {
if (entry.getKey().toLowerCase().contains(searchTextField.getText().toLowerCase())) {
SaveEditor.editorContainer.add(entry.getValue());
} else {
SaveEditor.editorContainer.remove(entry.getValue());
}
}
SaveEditor.editorContainer.revalidate();
}
@Override
public void keyTyped(KeyEvent event) {
}
};
}
|
package vegoo.newstock.persistent.redis.impl;
import java.util.Collection;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.osgi.framework.BundleContext;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
import org.osgi.service.component.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Strings;
import vegoo.newstock.core.bo.Block;
import vegoo.newstock.core.bo.Stock;
import vegoo.newstock.core.services.StockDataService;
import vegoo.newstock.persistent.redis.RedisService;
import vegoo.newstock.persistent.redis.core.RedisServiceImpl;
@Component(
name="StockDataService",
immediate=true,
configurationPid = "vegoo.redis",
service = {StockDataService.class}
)
public class StockDataServiceImpl extends StockDataServiceRedis {
private static final Logger logger = LoggerFactory.getLogger(StockDataServiceImpl.class);
static final String PN_HOST = "host";
static final String PN_PORT = "port";
static final String PN_PASSWORD = "password";
private Map<String, Block> _block_Cache = null;
private Map<String, Stock> _stock_Cache = null;
private RedisService redis;
private String host = "127.0.0.1";
private String password;
private int port = 6379;
public StockDataServiceImpl() {
System.out.println("StockDataServiceImpl created......");
}
@Modified
public void updated(BundleContext context, Map<String, String> properties){
System.out.println("StockDataServiceImpl updated......");
this.password = properties.get(PN_PASSWORD);
String shost = properties.get(PN_HOST);
if(Strings.isNullOrEmpty(shost)) {
this.host = shost;
}
try {
String sport = (String) properties.get(PN_PORT);
this.port = Integer.parseInt(sport);
}catch(Exception e) {
}
}
@Deactivate
public void deactivate() {
if(redis!=null) {
((RedisServiceImpl)redis).destroyJedis();
}
}
private RedisService createRedisService(String host, int port, String password) {
RedisServiceImpl result = new RedisServiceImpl();
result.initJedis(host, port, password);
return result;
}
@Override
protected RedisService getRedis() {
if(redis==null) {
this.redis = createRedisService(host, port, password);
}
return redis;
}
@Override
public Block getBlock(String blockCode) {
if(_block_Cache == null) {
_block_Cache = loadBlocks();
}
return _block_Cache.get(blockCode);
}
@Override
public Stock getStock(String stockCode) {
if(_stock_Cache == null) {
_stock_Cache = loadStocks();
}
return _stock_Cache.get(stockCode);
}
protected Map<String, Block> loadBlocks() {
Map<String, Block> result = new HashMap<>();
Set<String> blkCodes = BlockImpl.getBlockUCodes(getRedis());
blkCodes.forEach((blkCode)->{
result.put(blkCode, new BlockImpl(blkCode, this));
});
return result;
}
protected Map<String, Stock> loadStocks() {
Map<String, Stock> result = new HashMap<>();
Set<String> stkCodes = StockImpl.getStocks(getRedis());
stkCodes.forEach((code)->{
result.put(code, new StockImpl(code, this));
});
return result;
}
@Override
public Collection<Stock> getStocksOfBlock(String blockCode) {
Block block = getBlock(blockCode);
if(block==null) {
return null;
}
return block.getStocks();
}
}
|
package FShareServer;
import java.io.*;
import java.util.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.*;
import FShareCommon.*;
public class ServerMain {
public static void main(String[] argv) {
ArrayList<FileHaveIndex> fileIndex = new ArrayList<>();
ArrayList<ThreadServer> connectedNode = new ArrayList<>();
try {
ServerSocket serversocket = new ServerSocket(1234);
while (true) {
Socket clientsocket = serversocket.accept();
System.out.println("Accepted connection at" + clientsocket.getRemoteSocketAddress().toString());
ThreadServer thread = new ThreadServer(clientsocket);
connectedNode.add(thread);
thread.setIndex(fileIndex);
thread.run();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.webbeans.portable;
import java.util.Map;
import jakarta.enterprise.inject.spi.Interceptor;
import jakarta.inject.Provider;
import org.apache.webbeans.config.WebBeansContext;
import org.apache.webbeans.context.creational.CreationalContextImpl;
import org.apache.webbeans.proxy.NormalScopeProxyFactory;
import org.apache.webbeans.util.WebBeansUtil;
public class ProviderBasedProducer<T> extends AbstractProducer<T>
{
private WebBeansContext webBeansContext;
private Class<T> returnType;
private Provider<T> provider;
private T proxyInstance;
private boolean proxy;
public ProviderBasedProducer(WebBeansContext webBeansContext, Class<T> returnType, Provider<T> provider, boolean proxy)
{
this.webBeansContext = webBeansContext;
this.returnType = returnType;
this.provider = provider;
this.proxy = proxy;
}
@Override
protected T produce(Map<Interceptor<?>, ?> interceptors, CreationalContextImpl<T> creationalContext)
{
if (proxyInstance == null)
{
if (proxy)
{
NormalScopeProxyFactory proxyFactory = webBeansContext.getNormalScopeProxyFactory();
ClassLoader loader = webBeansContext.getApplicationBoundaryService().getBoundaryClassLoader(returnType);
if (loader == null)
{
loader = WebBeansUtil.getCurrentClassLoader();
}
Class<T> proxyClass = proxyFactory.createProxyClass(loader, returnType);
proxyInstance = proxyFactory.createProxyInstance(proxyClass, provider);
}
else
{
proxyInstance = provider.get();
}
}
return proxyInstance;
}
}
|
package com.smxknife.java2.serializable;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
/**
* @author smxknife
* 2018/11/2
*/
public class EmployeeSerializableDemo {
public static void main(String[] args) {
Employee e = new Employee();
e.name = "test";
e.address = "hangzhou";
e.SSN = 12345678;
e.number = 110;
e.staticAttr = "static-attr";
Employee.staticAttr = "class-static";
e.identity = 1000;
try {
FileOutputStream fos = new FileOutputStream("./employee.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(e);
oos.close();
fos.close();
System.out.println("saved");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
|
/**
* A special implementation of the Node class used in
* HashMaps, as the key must also be stored with the object
* to resolve Hash Collisions.
*
* IMPORTANT NOTE: It seemed more elegant to make HNode inherit Node,
* and it does indeed avoid a fair bit of code duplication. HOWEVER, because
* the super constructor takes objects of type Node rather than HNode, whenever
* you use getNext() on a HNode, you must cast it to HNode to have access to the key,
* which is the entire point of this class. There is probably a better way to do this,
* and I am very much not a fan of casting when you don't absolutely need to,
* but I haven't found one yet.
*
* @author (Samuel Cox)
* @version (09/06/2015)
*/
public class HNode<E> extends Node<E>
{
//A string that represents the key the stored Object was mapped to,
//used to ensure the right item is returned in the case of Hash collisons.
private String key;
/**
* Constructs a HNode object.
* Calls the super constructor,
* and initialises the key field to the given parameter.
* @param next The next HNode in the Linked List.
* @param key The key the object was mapped to in the HashMap.
* @param The object to be stored.
*/
public HNode(HNode next, String key, Object data)
{
// initialise instance variables
super(next, data);
this.key = key;
}
/**
* A method that returns the key the object was mapped to.
* @return The string the object was mapped to.
*/
public String getKey()
{
return this.key;
}
}
|
class Test_Perc2{
public static void main(String ag[]){
int a=30;
int b=40;
double tot=a+b;
double percA=a/tot*100.0;
double percB=b/tot*100.0;
System.out.println("perc of A is "+percA+"%");
System.out.println("perc of B is "+percB+"%");
}
}
|
package Task3;
public class Main {
public static void main(String[] args) {
Student[] students = {new Student(), new Aspirant()};
students[0].setAvgMark(4.9);
students[0].setLastName("Flash Thompson");
students[1].setAvgMark(5);
students[1].setLastName("Peter Parker");
for(Student student: students){
System.out.println(student.getLastName()+ " " + student.getScholarship());
}
}
}
|
/**
* Helios, OpenSource Monitoring
* Brought to you by the Helios Development Group
*
* Copyright 2007, Helios Development Group and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*
*/
package com.heliosapm.script.executable;
import java.util.Map;
import java.util.Set;
import com.heliosapm.script.DeployedScript;
import com.heliosapm.script.DeployedScriptMXBean;
/**
* <p>Title: DeployedExecutableMXBean</p>
* <p>Description: JMX MXBean interface for {@link DeployedScript}s</p>
* <p>Company: Helios Development Group LLC</p>
* @author Whitehead (nwhitehead AT heliosdev DOT org)
* <p><code>com.heliosapm.script.DeployedScriptMXBean</code></p>
*/
public interface DeployedExecutableMXBean extends DeployedScriptMXBean {
/**
* Returns a map of pending dependencies as a map of types keyed by the config key
* @return a map of pending dependencies as a map of types keyed by the config key
*/
public Map<String, String> getPendingDependencies();
/**
* Returns the execution timeout for this script in ms.
* @return the execution timeout in ms.
*/
public long getExecutionTimeout();
/**
* Sets the execution timeout for this script
* @param timeout the timeout in ms.
*/
public void setExecutionTimeout(long timeout);
/**
* Returns a set of the names of sub-invocables in the executable
* @return a set of the names of sub-invocables in the executable
*/
public Set<String> getInvocables();
/**
* Returns the status name of the deployment
* @return the status name of the deployment
*/
public String getStatusName();
/**
* Returns the elapsed time of the most recent execution in ms.
* @return the elapsed time of the most recent execution in ms.
*/
public long getLastExecElapsed();
/**
* Returns the timestamp of the last execution
* @return the timestamp of the last execution
*/
public long getLastExecTime();
/**
* Returns the timestamp of the last error
* @return the timestamp of the last error
*/
public long getLastErrorTime();
/**
* Returns the total number of executions since the last reset
* @return the total number of executions since the last reset
*/
public long getExecutionCount();
/**
* Returns the total number of errors since the last reset
* @return the total number of errors since the last reset
*/
public long getErrorCount();
/**
* Executes the underlying executable script and returns the result as a string
* @return the execution return value
*/
public String executeForString();
/**
* Returns the deployment's scheduled execution definition,
* as specified in {@link com.heliosapm.jmx.execution.ExecutionSchedule}
* @return the scheduled execution definition,
*/
public String getSchedule();
/**
* Sets the deployment's scheduled execution period
* @param scheduleExpression A schedule expression as specified in {@link com.heliosapm.jmx.execution.ExecutionSchedule}
*/
public void setExecutionSchedule(String scheduleExpression);
/**
* Stops scheduled executions, but remembers the schedule so it can be resumed
*/
public void pauseScheduledExecutions();
/**
* Resumes scheduled executions
* @return the schedule expression that was activated
*/
public String resumeScheduledExecutions();
/**
* Pauses the deployment, meaning it will not be invoked by the scheduler
*/
public void pause();
/**
* Resumes a paused executable
*/
public void resume();
//==============================================================================================
// /**
// * Initializes the config
// */
// public void initConfig();
//
//
// /**
// * Indicates if the deployment can be executed (manually)
// * @return true if the deployment can be executed, false otherwise
// */
// public boolean isExecutable();
//
// /**
// * Indicates if the deployment can be executed by the scheduler
// * @return true if the deployment can be executed by the scheduler, false otherwise
// */
// public boolean isScheduleExecutable();
// /**
// * Determines if this configuration is applicable for the passed deployment
// * @param deployment The absolute name of the deployment source file to test for
// * @return true if this configuration is applicable for the passed deployment, false otherwise
// */
// public boolean isConfigFor(String deployment);
}
|
package uw.cse.dineon.restaurant;
import java.util.Collection;
import java.util.List;
import uw.cse.dineon.library.CustomerRequest;
import uw.cse.dineon.library.DiningSession;
import uw.cse.dineon.library.Order;
import uw.cse.dineon.library.Reservation;
import uw.cse.dineon.library.Restaurant;
import uw.cse.dineon.library.UserInfo;
import uw.cse.dineon.library.android.DineOnStandardActivity;
import uw.cse.dineon.library.util.Utility;
import uw.cse.dineon.restaurant.RestaurantSatellite.SateliteListener;
import uw.cse.dineon.restaurant.login.RestaurantLoginActivity;
import uw.cse.dineon.restaurant.profile.ProfileActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.Window;
import android.widget.Toast;
import com.parse.ParseException;
import com.parse.SaveCallback;
/**
* General Fragment Activity class that pertains to a specific Restaurant
* client. Once the Restaurant logged in then they are allowed specific
* information related to the restaurant
* @author mhotan
*/
public class DineOnRestaurantActivity extends DineOnStandardActivity
implements SateliteListener {
/**
* member that defines this restaurant user
* This encapsulated this user with this restaurant instance only
* Another Activity (like LoginActivity) does the work of
* authenticating and creating an account.
*
* Abstract Function
* mRestaurant != null if and only if this user is logged in
* with a proper Restaurant account
*/
protected static final String TAG = DineOnRestaurantActivity.class.getSimpleName();
/**
* Progress bar dialog for showing user progress.
*/
private ProgressDialog mProgressDialog;
/**
* Satellite to communicate through.
*/
private RestaurantSatellite mSatellite;
/**
* The underlying restaurant instance.
*/
protected Restaurant mRestaurant;
/**
* Reference to this activity for inner class listeners.
*/
private DineOnRestaurantActivity thisResActivity;
/**
* Location Listener for location based services.
*/
// private RestaurantLocationListener mLocationListener;
/**
* This is a very important call that serves as a notification
* that the state of the Restaurant has changed.
* Updates the UI based on the state of this activity.
*/
protected void updateUI() {
// Lets invalidate the options menu so it shows the correct buttons
// Destroy any progress dailog if it exists
destroyProgressDialog();
invalidateOptionsMenu();
// TODO Initialize the UI based on the state of the application
// ...
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setProgressBarIndeterminateVisibility(true);
// Initialize the satellite
mSatellite = new RestaurantSatellite();
// retrieve necessary references.
thisResActivity = this;
mRestaurant = DineOnRestaurantApplication.getRestaurant();
if (mRestaurant == null) {
Utility.getGeneralAlertDialog(getString(R.string.uh_oh),
getString(R.string.not_logged_in)
, this).show();
}
}
@Override
protected void onResume() {
super.onResume();
mSatellite.register(mRestaurant, thisResActivity);
updateUI(); // This is the call that should trigger a lot of UI changes.
}
@Override
protected void onPause() {
destroyProgressDialog();
mSatellite.unRegister();
super.onPause();
}
/**
* Notifies all the users that a Change in this restaurant has changed.
*/
protected void notifyAllRestaurantChange() {
for (DiningSession session: mRestaurant.getSessions()) {
notifyGroupRestaurantChange(session);
}
}
/**
* Notifies all the groups of the Dining Session that
* a change has occured.
* @param session Dining Session that includes users to notify.
*/
protected void notifyGroupRestaurantChange(DiningSession session) {
for (UserInfo user: session.getUsers()) {
mSatellite.notifyChangeRestaurantInfo(mRestaurant.getInfo(), user);
}
}
/**
* Adds a dining session to the restaurant.
* @param session Dining Session to add
*/
protected void addDiningSession(DiningSession session) {
mRestaurant.addDiningSession(session);
mRestaurant.saveInBackGround(null);
}
/**
* Removes dining session from restaurant.
* @param user Dining Session to add
*/
protected void removeUser(UserInfo user) {
DiningSession session = mRestaurant.getDiningSession(user);
if (session == null) {
Log.w(TAG, "Customer " + user.getName() + " request check out but no dining session");
return;
}
// Remove the user from the current dining session
session.removeUser(user);
List<UserInfo> remainingUsers = session.getUsers();
if (remainingUsers.isEmpty()) {
// Delete the dining session.
// We have to iterate through all the orders pertaining to
// this dining session and remove it from the pending list
removeCustomerRequests(session.getRequests());
// Cancel any pending orders for the restaurant.
for (Order pendingOrder: session.getOrders()) {
mRestaurant.cancelPendingOrder(pendingOrder);
}
// Finally remove the diningsession
mRestaurant.removeDiningSession(session);
session.deleteFromCloud();
} else {
session.saveInBackGround(null);
}
mRestaurant.saveInBackGround(null);
}
/**
* Returns a list of sessions.
* @return a list of sessions
*/
public List<DiningSession> getCurrentSessions() {
if (mRestaurant == null) {
mRestaurant = DineOnRestaurantApplication.getRestaurant();
}
return mRestaurant.getSessions();
}
/**
* Adds an Order to the state of this restaurant.
* @param order Order that is being added to the restaurant.
*/
protected void addOrder(Order order) {
// Add the order to this restaurant.
mRestaurant.addOrder(order);
mRestaurant.saveInBackGround(null);
}
/**
* Adds a dining session to the restaurant.
* @param order Order that was completed
*/
protected void completeOrder(Order order) {
mRestaurant.completeOrder(order);
mRestaurant.saveInBackGround(null);
}
/**
* Returns a list of pending orders.
* @return a list of pending orders
*/
protected List<Order> getPendingOrders() {
if (mRestaurant == null) {
mRestaurant = DineOnRestaurantApplication.getRestaurant();
}
return mRestaurant.getPendingOrders();
}
/**
* Adds a customer request to the restaurant.
* @param request Customer Request to add
*/
protected void addCustomerRequest(CustomerRequest request) {
// reference our mRestaurant object
mRestaurant.addCustomerRequest(request);
mRestaurant.saveInBackGround(null);
}
/**
* Attempts to remove the requests from the restaurant.
* @param requests Requests to remove from Restaurant
*/
private void removeCustomerRequests(Collection<CustomerRequest> requests) {
for (CustomerRequest request: requests) {
mRestaurant.removeCustomerRequest(request);
}
mRestaurant.saveInBackGround(null);
}
/**
* Removes the request from the restaurant pending request record.
*
* Any class that overrides this method should call super.removeCustomerRequest
* at the end of the function block.
*
* @param request Request to delete.
*/
protected void removeCustomerRequest(CustomerRequest request) {
// Remove the customer request from the
// restaurant permanently.
mRestaurant.removeCustomerRequest(request);
mRestaurant.saveInBackGround(null);
}
/**
* Returns a list of customer requests.
* @return a list of customer requests
*/
protected List<CustomerRequest> getCurrentRequests() {
if (mRestaurant == null) {
mRestaurant = DineOnRestaurantApplication.getRestaurant();
}
return mRestaurant.getCustomerRequests();
}
/**
* Adds a reservation to the state of this restaurant.
* @param reservation reservation that is being added to the restaurant.
*/
protected void addReservation(Reservation reservation) {
// Add the order to this restaurant.
mRestaurant.addReservation(reservation);
mRestaurant.saveInBackGround(null);
}
/**
* Removes the reservation from this restaurant.
* @param reservation resrvation to remove.
*/
protected void removeReservation(Reservation reservation) {
mRestaurant.removeReservation(reservation);
mRestaurant.saveInBackGround(null);
}
/**
* Returns whether the user is logged in.
* This function can be used to determine the state
* of the application.
* @return whether a user is logged in
*/
protected boolean isLoggedIn() {
// That the user is logged in via Parse
// Then check if we have a associated restaurant
return mRestaurant != null;
}
////////////////////////////////////////////////
///// Satelite Listener Callbacks
/////////////////////////////////////////////////
@Override
public void onFail(String message) {
Toast.makeText(this, getString(R.string.failed) + message, Toast.LENGTH_LONG).show();
}
@Override
public void onUserCheckedIn(UserInfo user, int tableID) {
// Check if there is already a dining session for this user.
// If there is a dining session with that user then check
// if that session has the same table ID
DiningSession existing = mRestaurant.getDiningSession(user);
if (existing != null) {
// Different table numbers
if (existing.getTableID() != tableID) {
// TODO Handle the case where the user is attempting to
// check in at a restaurant multiple times at a different table
// TODO send back a message asking wtf?
// TODO Remove this. temporary just returning the current ds where user
// is currently still active.
mSatellite.confirmDiningSession(existing);
} else {
// Same Table IDs. This indicates a duplicate check in request
mSatellite.confirmDiningSession(existing);
}
return; // Don't need to save because state has not changed
}
existing = mRestaurant.getDiningSession(tableID);
final DiningSession DS;
if (existing != null) {
// Here the user is adding himself to a currently active dining session.
// Now this dining session will have one plus user.
existing.addUser(user);
DS = existing;
} else {
// Here we have a completely new user with a whole new dining session.
DS = new DiningSession(tableID, user, mRestaurant.getInfo());
}
DS.saveInBackGround(new SaveCallback() {
@Override
public void done(ParseException e) {
if (e == null) {
// Notify the user that the we have satisfied there request
mSatellite.confirmDiningSession(DS);
// Adds the dining session to the restaurant
addDiningSession(DS);
} else {
Log.e(TAG, getString(R.string.unable_to_confirm_dining_session)
+ e.getMessage());
}
}
});
Toast.makeText(this, getString(R.string.checked_in), Toast.LENGTH_SHORT).show();
}
@Override
public void onUserChanged(UserInfo user) {
Toast.makeText(this, getString(R.string.user_changed), Toast.LENGTH_SHORT).show();
if (mRestaurant == null) {
Log.e(TAG, getString(R.string.null_restaurant));
// TODO What do we do in this case queue the request ???
return;
}
// TODO Update the current restaurant
mRestaurant.updateUser(user);
// Save the changes and notify user
mRestaurant.saveInBackGround(null);
}
@Override
public void onOrderRequest(final Order order, String sessionID) {
Toast.makeText(this, getString(R.string.order_request), Toast.LENGTH_SHORT).show();
// TODO Validate Order
for (final DiningSession SESSION: mRestaurant.getSessions()) {
if (SESSION.getObjId().equals(sessionID)) {
// Found the correct session.
// Add the Order to the session
SESSION.addPendingOrder(order);
SESSION.saveInBackGround(new SaveCallback() {
@Override
public void done(ParseException e) {
if (e == null) {
// Tell the customer that we have received their order
mSatellite.confirmOrder(SESSION, order);
// Add the order to our restaurant
addOrder(order);
} else {
Log.e(TAG, getString(R.string.error_saving_dining_session)
+ e.getMessage());
}
}
});
// We are done there can be no duplicate
break;
}
}
}
@Override
public void onCustomerRequest(final CustomerRequest request, String sessionID) {
Toast.makeText(this, getString(R.string.order_request), Toast.LENGTH_SHORT).show();
// TODO Validate Request
for (final DiningSession SESSION: mRestaurant.getSessions()) {
if (SESSION.getObjId().equals(sessionID)) {
// Found the correct session.
// Add the Order to the session
SESSION.addRequest(request);
SESSION.saveInBackGround(new SaveCallback() {
@Override
public void done(ParseException e) {
if (e == null) {
// Tell the customer we have received their request
mSatellite.confirmCustomerRequest(SESSION, request);
// Update our state as well
addCustomerRequest(request);
} else {
Log.e(TAG, getString(R.string.error_saving_dining_session)
+ e.getMessage());
}
}
});
// We are done there can be no duplicate
break;
}
}
}
@Override
public void onReservationRequest(Reservation reservation) {
Toast.makeText(this, getString(R.string.reservation_request), Toast.LENGTH_SHORT).show();
if (mRestaurant == null) {
Log.e(TAG, "Null Restaurant when accepting customer request.");
return;
}
// TODO Validate Reservation
mSatellite.confirmReservation(reservation.getUserInfo(), reservation);
// We are not updating the dining session
// because there is no dining session with this reservation.
addReservation(reservation);
}
@Override
public void onCheckedOut(UserInfo user) {
// TODO Auto-generated method stub
Toast.makeText(this, getString(R.string.checked_out)
+ user.getName(), Toast.LENGTH_SHORT).show();
// All we do is call the
removeUser(user);
}
////////////////////////////////////////////////
///// Establish Menu
/////////////////////////////////////////////////
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
// Note that override this method does not mean the actualy
// UI Menu is updated this is done manually
// See basic_menu under res/menu for ids
inflater.inflate(R.menu.basic_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item_restaurant_profile:
startProfileActivity();
return true;
case R.id.item_logout:
if (mRestaurant != null) {
createProgressDialog(true, getString(R.string.saving),
getString(R.string.logging_out));
mRestaurant.saveInBackGround(new SaveCallback() {
@Override
public void done(ParseException e) {
destroyProgressDialog();
DineOnRestaurantApplication.logOut(thisAct);
startLoginActivity();
}
});
}
return true;
case R.id.item_restaurant_menu:
startProfileActivity();
return true;
default:
}
return false;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// Depending on the state of the current application
// Adjust what is presented to the user
if (!isLoggedIn()) {
setMenuToNonUser(menu);
}
MenuItem progressbar = menu.findItem(R.id.item_progress);
if (progressbar != null) {
progressbar.setEnabled(false);
progressbar.setVisible(false);
}
return true;
}
/**
* Given a menu set set this menu to show.
* that the user is not logged in
* @param menu to display
*/
private void setMenuToNonUser(Menu menu) {
MenuItem itemProfile = menu.findItem(R.id.item_restaurant_profile);
if (itemProfile != null) {
itemProfile.setEnabled(false);
itemProfile.setVisible(false);
}
MenuItem itemLogout = menu.findItem(R.id.item_logout);
if (itemLogout != null) {
itemLogout.setEnabled(false);
itemLogout.setVisible(false);
}
// Add a ability to log in
MenuItem item = menu.add(getString(R.string.login));
item.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
startLoginActivity();
return false;
}
});
}
/**
* Start log in activity.
* Clears the back stack so user can't push back to go to their last page.
*/
public void startLoginActivity() {
Intent i = new Intent(this, RestaurantLoginActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
/**
* Starts the activity that lets the user look at the restaurant profile.
*/
public void startProfileActivity() {
Intent i = new Intent(this, ProfileActivity.class);
startActivity(i);
}
// //////////////////////////////////////////////////////////////////////
// /// UI Specific methods
// //////////////////////////////////////////////////////////////////////
/**
* Instantiates a new progress dialog and shows it on the screen.
* @param cancelable Allows the progress dialog to be cancelable.
* @param title Title to show in dialog
* @param message Message to show in box
*/
protected void createProgressDialog(boolean cancelable, String title, String message) {
if (mProgressDialog != null) {
return;
}
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setTitle(title);
mProgressDialog.setMessage(message);
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(cancelable);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.show();
}
/**
* Hides the progress dialog if there is one.
*/
protected void destroyProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
// /**
// * Listener for getting restaurant location at creation time.
// * @author mtrathjen08
// *
// */
// private class RestaurantLocationListener implements android.location.LocationListener {
//
// /**
// * Location Manager for location services.
// */
// private LocationManager mLocationManager;
//
// /**
// * Last received location from mananger. Initially null.
// */
// private Location mLocation;
//
// /**
// * Constructor for the location listener.
// */
// public RestaurantLocationListener() {
// this.mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// this.mLocation = null;
// }
//
// /**
// * Return the last recorder location of the user. Null if no update.
// * @return last recorder location.
// */
// Location getLastLocation() {
// return this.mLocation;
// // TODO add support for gps
// }
//
// /**
// * Request a location reading from the Location Manager.
// */
// private void requestLocationUpdate() {
// this.mLocationManager.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, this, null);
// // TODO add support for gps
// }
//
// @Override
// public void onLocationChanged(Location loc) {
// this.mLocation = loc;
// }
//
// @Override
// public void onProviderDisabled(String arg0) {
// // Do nothing
// }
//
// @Override
// public void onProviderEnabled(String arg0) {
// // Do nothing
// }
//
// @Override
// public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// // Do nothing
// }
// }
}
|
package com.penzias.controller;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.penzias.core.commons.BaseController;
import com.penzias.dictionary.DiseaseType;
import com.penzias.dictionary.MRSType;
import com.penzias.dictionary.OtherType;
import com.penzias.entity.ApoplexyConclusionInfo;
import com.penzias.entity.ApoplexyConclusionInfoExample;
import com.penzias.entity.BloodFatHistory;
import com.penzias.entity.BloodFatHistoryExample;
import com.penzias.entity.BloodGlucoseExamInfo;
import com.penzias.entity.BrainBloodHistory;
import com.penzias.entity.BrainBloodHistoryExample;
import com.penzias.entity.DiabetesHistory;
import com.penzias.entity.DiabetesHistoryExample;
import com.penzias.entity.ElectrocardiogramExamInfo;
import com.penzias.entity.ElectrocardiogramExamInfoExample;
import com.penzias.entity.HeartDiseaseHistory;
import com.penzias.entity.HeartDiseaseHistoryExample;
import com.penzias.entity.HistoryPharmacy;
import com.penzias.entity.HypertensionHistory;
import com.penzias.entity.HypertensionHistoryExample;
import com.penzias.entity.InstitutionCrowdBaseInfo;
import com.penzias.entity.InstitutionCrowdBaseInfoExample;
import com.penzias.entity.InstitutionCrowdFamilyInfo;
import com.penzias.entity.InstitutionCrowdFamilyInfoExample;
import com.penzias.entity.InstitutionCrowdLifestyleInfo;
import com.penzias.entity.InstitutionCrowdLifestyleInfoExample;
import com.penzias.entity.KidneyDiseaseHostory;
import com.penzias.entity.KidneyDiseaseHostoryExample;
import com.penzias.entity.OtherHistory;
import com.penzias.entity.OtherHistoryExample;
import com.penzias.entity.PhysiqueExamInfo;
import com.penzias.entity.PhysiqueExamInfoExample;
import com.penzias.entity.PulmonaryDiseaseHistory;
import com.penzias.entity.PulmonaryDiseaseHistoryExample;
import com.penzias.entity.SmCodeitem;
import com.penzias.entity.SmCodeitemKey;
import com.penzias.interfaces.IDictionaryItem;
import com.penzias.service.ApoplexyConclusionInfoService;
import com.penzias.service.BloodFatExamInfoService;
import com.penzias.service.BloodFatHistoryService;
import com.penzias.service.BloodGlucoseExamInfoService;
import com.penzias.service.BrainBloodHistoryService;
import com.penzias.service.DiabetesHistoryService;
import com.penzias.service.ElectrocardiogramExamInfoService;
import com.penzias.service.HeartDiseaseHistoryService;
import com.penzias.service.HistoryControlService;
import com.penzias.service.HistoryPharmacyService;
import com.penzias.service.HomocysteineExamInfoService;
import com.penzias.service.HypertensionHistoryService;
import com.penzias.service.InstitutionCrowdBaseInfoService;
import com.penzias.service.InstitutionCrowdFamilyInfoService;
import com.penzias.service.InstitutionCrowdLifestyleInfoService;
import com.penzias.service.KidneyDiseaseHostoryService;
import com.penzias.service.OtherHistoryService;
import com.penzias.service.PhysiqueExamInfoService;
import com.penzias.service.PulmonaryDiseaseHistoryService;
import com.penzias.vo.ControlHistoryVO;
import com.penzias.vo.InnerCheckVO;
import com.penzias.vo.InstitutionCrowdFamilyInfoVO;
import com.penzias.vo.OtherHistoryVO;
/**
* 描述:人群筛查<br/>
* 作者:Bob <br/>
* 修改日期:2015年12月21日 - 上午10:27:55<br/>
*/
@SuppressWarnings("unchecked")
@Controller
@RequestMapping("archives")
public class ArchivesController extends BaseController{
//机构人群基本信息service
@Resource
private InstitutionCrowdBaseInfoService institutionCrowdBaseInfoService;
@Resource
private InstitutionCrowdLifestyleInfoService InstitutionCrowdLifestyleInfoService;
@Resource
private InstitutionCrowdFamilyInfoService InstitutionCrowdFamilyInfoService;
@Resource
private BrainBloodHistoryService brainBloodHistoryService;
@Resource
private HeartDiseaseHistoryService heartDiseaseHistoryService;
@Resource
private HypertensionHistoryService hypertensionHistoryService;
@Resource
private BloodFatHistoryService bloodFatHistoryService;
@Resource
private DiabetesHistoryService diabetesHistoryService;
@Resource
private KidneyDiseaseHostoryService kidneyDiseaseHostoryService;
@Resource
private OtherHistoryService otherHistoryService;
@Resource
private PulmonaryDiseaseHistoryService pulmonaryDiseaseHistoryService;
@Resource
private HistoryControlService historyControlService;
@Resource
private PhysiqueExamInfoService physiqueExamInfoService;
@Resource
private ApoplexyConclusionInfoService apoplexyConclusionInfoService;
@Resource
private ElectrocardiogramExamInfoService electrocardiogramExamInfoService;
@Resource
private BloodGlucoseExamInfoService bloodGlucoseExamInfoService;
@Resource
private BloodFatExamInfoService bloodFatExamInfoService;
@Resource
private HomocysteineExamInfoService homocysteineExamInfoService;
@Resource
private HistoryPharmacyService historyPharmacyService;
@Resource
private IDictionaryItem iDctionaryItem;
/**
* @author: Bob
* 修改时间:2015年12月3日 - 下午3:37:29<br/>
* 功能说明:人群筛查<br/>
* @param currentPage
* @param name
* @param phone
* @param model
* @return
*/
@RequestMapping("crowsfilter")
public String index(Integer currentPage,String name,String phone, Model model){
if(null==currentPage){
currentPage = 1;
}
Integer pageSize = getPageSize();
InstitutionCrowdBaseInfoExample example = new InstitutionCrowdBaseInfoExample();
com.penzias.entity.InstitutionCrowdBaseInfoExample.Criteria criteria = example.createCriteria();
if(!StringUtils.isEmpty(name)){
criteria.andFullnameLike("%"+ name +"%");
model.addAttribute("name", name);
}
if(!StringUtils.isEmpty(phone)){
criteria.andMobileLike("%"+ phone +"%");
model.addAttribute("phone", phone);
}
example.setOrderByClause(" FullName desc");
PageHelper.startPage(currentPage,pageSize);
List<InstitutionCrowdBaseInfo> list = this.institutionCrowdBaseInfoService.list(example);
long nowNo = System.currentTimeMillis();
SmCodeitemKey itemKey = new SmCodeitemKey();
itemKey.setCodeid("ZE");
for(InstitutionCrowdBaseInfo info : list){
itemKey.setCode(info.getStates());
info.setStates(((SmCodeitem) this.iDctionaryItem.queryOne(itemKey)).getDescription());
Date birth = info.getBirthdate();
if(null!=birth){
long birthNo = birth.getTime();
long bt = nowNo - birthNo;
int age = (int) (bt / (1000*60*60*24*365));
info.setAge(age);
}
}
PageInfo<InstitutionCrowdBaseInfo> pageinfo = new PageInfo<InstitutionCrowdBaseInfo>(list);
model.addAttribute("page", pageinfo);
return "archives/filter_list";
}
/**
* @author: Bob
* 修改时间:2015年12月3日 - 下午3:37:46<br/>
* 功能说明:人群检验<br/>
* @param currentPage
* @param name
* @param phone
* @param model
* @return
*/
@RequestMapping("crowscheck")
public String check(Integer currentPage,String name,String phone, Model model){
if(null==currentPage){
currentPage = 1;
}
Integer pageSize = getPageSize();
InstitutionCrowdBaseInfoExample example = new InstitutionCrowdBaseInfoExample();
com.penzias.entity.InstitutionCrowdBaseInfoExample.Criteria criteria = example.createCriteria();
if(!StringUtils.isEmpty(name)){
criteria.andFullnameLike("%"+ name +"%");
model.addAttribute("name", name);
}
if(!StringUtils.isEmpty(phone)){
criteria.andMobileLike("%"+ phone +"%");
model.addAttribute("phone", phone);
}
example.setOrderByClause(" FullName desc");
PageHelper.startPage(currentPage,pageSize);
List<InstitutionCrowdBaseInfo> list = this.institutionCrowdBaseInfoService.list(example);
long nowNo = System.currentTimeMillis();
SmCodeitemKey itemKey = new SmCodeitemKey();
itemKey.setCodeid("ZE");
for(InstitutionCrowdBaseInfo info : list){
itemKey.setCode(info.getStates());
info.setStates(((SmCodeitem) this.iDctionaryItem.queryOne(itemKey)).getDescription());
Date birth = info.getBirthdate();
if(null!=birth){
long birthNo = birth.getTime();
long bt = nowNo - birthNo;
int age = (int) (bt / (1000*60*60*24*365));
info.setAge(age);
}
}
PageInfo<InstitutionCrowdBaseInfo> pageinfo = new PageInfo<InstitutionCrowdBaseInfo>(list);
model.addAttribute("page", pageinfo);
return "archives/check_list";
}
/**
* 方法名称: crowsList<br>
* 描述:人群档案
* 作者: Bob
* 修改日期:2016年2月23日上午11:28:29
* @param currentPage
* @param name
* @param phone
* @param manage
* @param zf
* @param ze
* @param model
* @return
*
*/
@RequestMapping("crowsinfos")
public String crowsList(Integer currentPage,String name,String phone, String manage, String zf,String ze, Model model){
if(null==currentPage){
currentPage = 1;
}
Integer pageSize = getPageSize();
InstitutionCrowdBaseInfoExample example = new InstitutionCrowdBaseInfoExample();
com.penzias.entity.InstitutionCrowdBaseInfoExample.Criteria criteria = example.createCriteria();
if(!StringUtils.isEmpty(name)){
criteria.andFullnameLike("%"+ name +"%");
model.addAttribute("name", name);
}
if(!StringUtils.isEmpty(phone)){
criteria.andMobileLike("%"+ phone +"%");
model.addAttribute("phone", phone);
}
if(!StringUtils.isEmpty(manage)){
if("01".equals(manage)){
criteria.andGradeEqualTo("01");
}else if("02".equals(manage)){
criteria.andGradeEqualTo("02");
}else{
List<String> gradeList = new ArrayList<String>();
gradeList.add("03");
gradeList.add("04");
gradeList.add("05");
criteria.andGradeIn(gradeList);
}
model.addAttribute("manage", manage);
}
if(!StringUtils.isEmpty(zf)){
criteria.andGradeEqualTo(zf);
model.addAttribute("zf", zf);
}
if(!StringUtils.isEmpty(ze)){
criteria.andStatesEqualTo(ze);
model.addAttribute("ze", ze);
}
example.setOrderByClause(" FullName desc");
PageHelper.startPage(currentPage,pageSize);
List<InstitutionCrowdBaseInfo> list = this.institutionCrowdBaseInfoService.list(example);
long nowNo = System.currentTimeMillis();
Map<String, SmCodeitem> mapZF = (Map<String, SmCodeitem>) this.iDctionaryItem.queryGroup("ZF");
Map<String, SmCodeitem> mapZE = (Map<String, SmCodeitem>) this.iDctionaryItem.queryGroup("ZE");
for(InstitutionCrowdBaseInfo info : list){
info.setStates(mapZE.get(info.getStates()).getDescription());
String grade = info.getGrade();
info.setGradeInfo(mapZF.get(grade).getDescription());
if(!StringUtils.isEmpty(grade)){
if("01".equals(grade)){
info.setGradeColor(1);
}else if("02".equals(grade)){
info.setGradeColor(2);
}else{
info.setGradeColor(3);
}
}
Date birth = info.getBirthdate();
if(null!=birth){
long birthNo = birth.getTime();
long bt = nowNo - birthNo;
int age = (int) (bt / (1000*60*60*24*365));
info.setAge(age);
}
}
PageInfo<InstitutionCrowdBaseInfo> pageinfo = new PageInfo<InstitutionCrowdBaseInfo>(list);
model.addAttribute("page", pageinfo);
//管理分级
List<SmCodeitem> manageLevel = new ArrayList<SmCodeitem>();
Map<String, SmCodeitem> map = (Map<String, SmCodeitem>) this.iDctionaryItem.queryGroup("YF");
map.forEach((key, item) ->{
manageLevel.add(item);
});
model.addAttribute("manageLevel", manageLevel);
//风险等级
List<SmCodeitem> zfLevel = new ArrayList<SmCodeitem>();
mapZF.forEach((key, item) ->{
zfLevel.add(item);
});
model.addAttribute("zfLevel", zfLevel);
//病历状态
List<SmCodeitem> zeLevel = new ArrayList<SmCodeitem>();
mapZE.forEach((key, item) ->{
zeLevel.add(item);
});
model.addAttribute("zeLevel", zeLevel);
return "archives/infos_list";
}
/**
* @author: Bob
* 修改时间:2015年12月4日 - 上午11:27:57<br/>
* 功能说明:跳转人群新增页面<br/>
* @param model
* @return
*/
//@RequestMapping("add")
@Deprecated
public String crowsAdd(Model model){
return "archives/crows_add";
}
/**
* @author: Bob
* 修改时间:2015年12月8日 - 上午10:09:27<br/>
* 功能说明:基本信息页面<br/>
* @param model
* @return
*/
@RequestMapping("baseinfo")
public String baseInfo(Model model){
//民族词典
List<SmCodeitem> nationList = new ArrayList<SmCodeitem>();
Map<String, SmCodeitem> nationMap = (Map<String, SmCodeitem>) this.iDctionaryItem.queryGroup("ZH");
nationMap.forEach((key, item) ->{
nationList.add(item);
});
model.addAttribute("nationList", nationList);
//教育程度
List<SmCodeitem> educationList = new ArrayList<SmCodeitem>();
Map<String, SmCodeitem> educationMap = (Map<String, SmCodeitem>) this.iDctionaryItem.queryGroup("ZI");
educationMap.forEach((key, item) ->{
educationList.add(item);
});
model.addAttribute("educationList", educationList);
//职业
List<SmCodeitem> occupationList = new ArrayList<SmCodeitem>();
Map<String, SmCodeitem> occupationMap = (Map<String, SmCodeitem>) this.iDctionaryItem.queryGroup("ZJ");
occupationMap.forEach((key, item) ->{
occupationList.add(item);
});
model.addAttribute("occupationList", occupationList);
//收入
List<SmCodeitem> incomeList = new ArrayList<SmCodeitem>();
Map<String, SmCodeitem> incomeMap = (Map<String, SmCodeitem>) this.iDctionaryItem.queryGroup("ZK");
incomeMap.forEach((key, item) ->{
incomeList.add(item);
});
model.addAttribute("incomeList", incomeList);
//主要医疗付费方式
List<SmCodeitem> payList = new ArrayList<SmCodeitem>();
Map<String, SmCodeitem> payMap = (Map<String, SmCodeitem>)this.iDctionaryItem.queryGroup("ZL");
payMap.forEach((key, item) ->{
payList.add(item);
});
model.addAttribute("payList", payList);
//与本人关系
List<SmCodeitem> shipList = new ArrayList<SmCodeitem>();
Map<String, SmCodeitem> shipMap = (Map<String, SmCodeitem>) this.iDctionaryItem.queryGroup("ZM");
shipMap.forEach((key, item) ->{
shipList.add(item);
});
model.addAttribute("shipList", shipList);
return "archives/baseinfo_ae";
}
/**
* 方法名称: saveBaseInfo<br/>
* 描述:保存基本信息<br/>
* 作者: ruibo<br/>
* 修改日期:2015年12月12日-下午2:31:43<br/>
* @param baseinfo
* @param model
* @param request
* @return
*/
@RequestMapping("saveBaseinfo")
public String saveBaseInfo(InstitutionCrowdBaseInfo baseinfo, Model model){
//性别
if(StringUtils.isEmpty(baseinfo.getSex())){
baseinfo.setSex("2");
}
//处理其他关系
if(!"05".equals(baseinfo.getRelationship())){
baseinfo.setFlag(null);
}
//处理年龄
Integer age = baseinfo.getAge();
long nowTime = System.currentTimeMillis();
long ageTime = age.longValue() * 365 * 24 * 60 * 60 * 1000;
long birthTime = nowTime - ageTime;
Date brith = new Date(birthTime);
baseinfo.setBirthdate(brith);
if(null!=baseinfo.getCrowdid()){
this.institutionCrowdBaseInfoService.updateById(baseinfo);
}else{
this.institutionCrowdBaseInfoService.add(baseinfo);
}
return "redirect:/archives/lifestyle.htm?cid="+baseinfo.getCrowdid().intValue();
}
/**
* 方法名称: lifeStryle<br/>
* 描述:生活方式<br/>
* 作者: ruibo<br/>
* 修改日期:2015年12月6日-下午5:07:17<br/>
* @param model
* @return
*/
@RequestMapping("lifestyle")
public String lifeStryle(Integer cid, Model model){
if(null!=cid){
InstitutionCrowdLifestyleInfoExample example = new InstitutionCrowdLifestyleInfoExample();
example.createCriteria().andCrowdidEqualTo(cid);
List<InstitutionCrowdLifestyleInfo> list = this.InstitutionCrowdLifestyleInfoService.list(example);
if(list.size()>0){
model.addAttribute("lifestyle",list.get(0));
}
model.addAttribute("cid",cid);
}
return "archives/lifestyle_ae";
}
/**
* 方法名称: saveLisfeStyle<br/>
* 描述:保存生活方式<br/>
* 作者: ruibo<br/>
* 修改日期:2015年12月12日-下午3:47:41<br/>
* @param lifestyle
* @param model
* @return
*/
@RequestMapping("savels")
public String saveLisfeStyle(InstitutionCrowdLifestyleInfo lifestyle, Model model){
//不抽烟
if("01".equals(lifestyle.getIsSmokeFlag())){
if("0102".equals(lifestyle.getIsSecondSmokenFlag())){
lifestyle.setIsSmokeFlag(lifestyle.getIsSecondSmokenFlag());
lifestyle.setSmokeyear(lifestyle.getSecondSmokenYear());
}
}else{
if(!StringUtils.isEmpty(lifestyle.getDontSmokeYear())){
lifestyle.setIsSmokeFlag("0202");
lifestyle.setSmokeyear(lifestyle.getSmokenYear());
}else{
lifestyle.setIsSmokeFlag("0201");
lifestyle.setSmokeyear(lifestyle.getSmokingYear());
}
}
//饮酒
if("01".equals(lifestyle.getWine())){
lifestyle.setWineyear(null);
}else if("02".equals(lifestyle.getWine())){
lifestyle.setWineyear(lifestyle.getLittleDrinkMountYear());
}else if("03".equals(lifestyle.getWine())){
lifestyle.setWineyear(lifestyle.getLotDrinkMountYear());
}
//sport
if("01".equals(lifestyle.getSports())){
lifestyle.setSportsyear(lifestyle.getHasSportYear());
}else if("02".equals(lifestyle.getSports())){
lifestyle.setSportsyear(lifestyle.getHasNoSportYear());
}
if(null!=lifestyle.getCrowdid()){
this.InstitutionCrowdLifestyleInfoService.updateById(lifestyle);
}else{
this.InstitutionCrowdLifestyleInfoService.add(lifestyle);
}
return "redirect:/archives/family.htm?cid="+lifestyle.getCrowdid();
}
/**
*
* 方法名称: familyInfo<br/>
* 描述:家族史<br/>
* 作者: ruibo<br/>
* 修改日期:2015年12月6日-下午5:07:40<br/>
* @param model
* @return
*/
@RequestMapping("family")
public String familyInfo(Integer cid, Model model){
if(null!=cid){
InstitutionCrowdFamilyInfoExample example = new InstitutionCrowdFamilyInfoExample();
example.createCriteria().andCrowdidEqualTo(cid);
example.setOrderByClause(" DiseaseType asc");
List<InstitutionCrowdFamilyInfo> list = this.InstitutionCrowdFamilyInfoService.list(example);
for(InstitutionCrowdFamilyInfo info:list){
String type = info.getDiseasetype();
if(type.equals(DiseaseType.zr_brain.getValue())){
model.addAttribute("zr_brain",info);
}else if(type.equals(DiseaseType.zr_diabetes.getValue())){
model.addAttribute("zr_diabetes",info);
}else if(type.equals(DiseaseType.zr_dyslipidemia.getValue())){
model.addAttribute("zr_dyslipidemia",info);
}else if(type.equals(DiseaseType.zr_heart.getValue())){
model.addAttribute("zr_heart",info);
}else if(type.equals(DiseaseType.zr_highblood.getValue())){
model.addAttribute("zr_highblood",info);
}
}
model.addAttribute("cid",cid);
}else{
InstitutionCrowdFamilyInfo info = new InstitutionCrowdFamilyInfo();
model.addAttribute("zr_brain",info);
model.addAttribute("zr_diabetes",info);
model.addAttribute("zr_dyslipidemia",info);
model.addAttribute("zr_heart",info);
model.addAttribute("zr_highblood",info);
}
return "archives/familyhistory_ae";
}
/**
* 方法名称: saveFamilyInfo<br/>
* 描述:家族史<br/>
* 作者: ruibo<br/>
* 修改日期:2015年12月12日-下午9:01:18<br/>
* @param institutionCrowdFamilyInfo
* @param model
* @return
*/
@RequestMapping("savefi")
public String saveFamilyInfo(Integer cid, InstitutionCrowdFamilyInfoVO institutionCrowdFamilyInfoVO, Model model){
if(null!=cid){
if(null!=institutionCrowdFamilyInfoVO.getArrays()[0].getFamilyid()){
//update data
this.InstitutionCrowdFamilyInfoService.updateBatch(institutionCrowdFamilyInfoVO.getArrays());
}else{
//new data
institutionCrowdFamilyInfoVO.setCrowdid(cid);
this.InstitutionCrowdFamilyInfoService.addBatch(institutionCrowdFamilyInfoVO.getArrays());
}
}
return "redirect:/archives/control.htm?cid="+cid;
}
/**
*
* 方法名称: controlInfo<br/>
* 描述:既往病史及控制情况<br/>
* 作者: ruibo<br/>
* 修改日期:2015年12月6日-下午5:07:55<br/>
* @param model
* @return
*/
@RequestMapping("control")
public String controlInfo(Integer cid, Model model){
if(null!=cid){
BrainBloodHistoryExample example = new BrainBloodHistoryExample();
example.createCriteria().andCrowdidEqualTo(cid);
List<BrainBloodHistory> list = this.brainBloodHistoryService.list(example);
if(list.size()>0){
BrainBloodHistory brainBloodHistory = list.get(0);
model.addAttribute("brainBloodHistory",brainBloodHistory);
}
HeartDiseaseHistoryExample hExample = new HeartDiseaseHistoryExample();
hExample.createCriteria().andCrowdidEqualTo(cid);
List<HeartDiseaseHistory> hList = this.heartDiseaseHistoryService.list(hExample);
if(hList.size()>0){
model.addAttribute("heartDiseaseHistory",hList.get(0));
}
HypertensionHistoryExample hypertensionHistoryExample = new HypertensionHistoryExample();
hypertensionHistoryExample.createCriteria().andCrowdidEqualTo(cid);
List<HypertensionHistory> hypertensionHistoryList = this.hypertensionHistoryService.list(hypertensionHistoryExample);
if(hypertensionHistoryList.size()>0){
model.addAttribute("hypertensionHistory",hypertensionHistoryList.get(0));
}
BloodFatHistoryExample bloodFatHistoryExample = new BloodFatHistoryExample();
bloodFatHistoryExample.createCriteria().andCrowdidEqualTo(cid);
List<BloodFatHistory> bloodFatHistoryList = this.bloodFatHistoryService.list(bloodFatHistoryExample);
if(bloodFatHistoryList.size()>0){
model.addAttribute("bloodFatHistory",bloodFatHistoryList.get(0));
}
DiabetesHistoryExample diabetesHistoryExample = new DiabetesHistoryExample();
diabetesHistoryExample.createCriteria().andCrowdidEqualTo(cid);
List<DiabetesHistory> diabetesHistoryList = this.diabetesHistoryService.list(diabetesHistoryExample);
if(diabetesHistoryList.size()>0){
model.addAttribute("diabetesHistory",diabetesHistoryList.get(0));
}
KidneyDiseaseHostoryExample kidneyDiseaseHostoryExample = new KidneyDiseaseHostoryExample();
kidneyDiseaseHostoryExample.createCriteria().andCrowdidEqualTo(cid);
List<KidneyDiseaseHostory> kidneyDiseaseHostoryList = this.kidneyDiseaseHostoryService.list(kidneyDiseaseHostoryExample);
if(kidneyDiseaseHostoryList.size()>0){
model.addAttribute("kidneyDiseaseHostory",kidneyDiseaseHostoryList.get(0));
}
PulmonaryDiseaseHistoryExample pulmonaryDiseaseHistoryExample = new PulmonaryDiseaseHistoryExample();
pulmonaryDiseaseHistoryExample.createCriteria().andCrowdidEqualTo(cid);
List<PulmonaryDiseaseHistory> pulmonaryDiseaseHistoryList = this.pulmonaryDiseaseHistoryService.list(pulmonaryDiseaseHistoryExample);
if(pulmonaryDiseaseHistoryList.size()>0){
model.addAttribute("pulmonaryDiseaseHistory",pulmonaryDiseaseHistoryList.get(0));
}
OtherHistoryExample otherHistoryExample = new OtherHistoryExample();
otherHistoryExample.createCriteria().andCrowdidEqualTo(cid);
List<OtherHistory> otherHistoryList = this.otherHistoryService.list(otherHistoryExample);
if(otherHistoryList.size()>0){
for(OtherHistory his:otherHistoryList){
String type = his.getOthertype();
if(type.equals(OtherType.yb_xiazhidongmai.getValue())){
model.addAttribute(OtherType.yb_xiazhidongmai.name(), his);
}else if(type.equals(OtherType.yb_yandixuguan.getValue())){
model.addAttribute(OtherType.yb_yandixuguan.name(), his);
}else if(type.equals(OtherType.yb_kouqiang.getValue())){
model.addAttribute(OtherType.yb_kouqiang.name(), his);
}else if(type.equals(OtherType.yb_kouqiang.getValue())){
model.addAttribute(OtherType.yb_kouqiang.name(), his);
}
}
}
model.addAttribute("cid", cid);
//字典数据
Map<String, SmCodeitem> occupationMap = (Map<String, SmCodeitem>) this.iDctionaryItem.queryGroup("ZU");
List<SmCodeitem> listZU0502 = new ArrayList<SmCodeitem>();
List<SmCodeitem> listZU0501 = new ArrayList<SmCodeitem>();
List<SmCodeitem> listZU01 = new ArrayList<SmCodeitem>();
List<SmCodeitem> listZU02 = new ArrayList<SmCodeitem>();
List<SmCodeitem> listZU03 = new ArrayList<SmCodeitem>();
List<SmCodeitem> listZU04 = new ArrayList<SmCodeitem>();
occupationMap.forEach((key, item) ->{
if(item.getPptr().equals("0502")){
listZU0502.add(item);
}else if(item.getPptr().equals("0501")){
listZU0501.add(item);
}else if("01".equals(item.getPptr())){
listZU01.add(item);
}else if("02".equals(item.getPptr())){
listZU02.add(item);
}else if("03".equals(item.getPptr())){
listZU03.add(item);
}else if("04".equals(item.getPptr())){
listZU04.add(item);
}
});
model.addAttribute("listZU0502", listZU0502);
model.addAttribute("listZU0501", listZU0502);
model.addAttribute("listZU01", listZU01);
model.addAttribute("listZU02", listZU02);
model.addAttribute("listZU03", listZU03);
model.addAttribute("listZU04", listZU04);
}
return "archives/control_ae";
}
/**
* @author: Bob
* 修改时间:2015年12月15日 - 上午10:31:44<br/>
* 功能说明:保存既往病史<br/>
* @param cid
* @param brainBloodHistory
* @param model
* @return
*/
@RequestMapping("savecontrol")
public String saveControl(Integer cid, ControlHistoryVO controlHistoryVO,OtherHistoryVO otherVO,
String[] pharmacytype, String[] pharmacyname, String[] pharmacyyear, String[] pharmacysituation,
Model model){
if(null!=cid){
//先处理新增
controlHistoryVO.setCrowdid(cid);
controlHistoryVO.getBrainBloodHistory().setMrsvalue(MRSType.getScore(controlHistoryVO.getBrainBloodHistory().getMrsoption())+"");
int length = pharmacytype.length;
HistoryPharmacy[] historyPharmacys = new HistoryPharmacy[length];
for(int i=0;i<length;i++){
HistoryPharmacy historyPharmacy = new HistoryPharmacy();
historyPharmacy.setCrowdid(cid);
historyPharmacy.setPharmacytype(pharmacytype[i]);
historyPharmacy.setPharmacyname(pharmacyname[i]);
historyPharmacy.setPharmacyyear(pharmacyyear[i]);
historyPharmacy.setPharmacysituation(pharmacysituation[i]);
historyPharmacys[i] = historyPharmacy;
}
this.historyControlService.add(controlHistoryVO.getBrainBloodHistory(),controlHistoryVO.getHeartDiseaseHistory(),
controlHistoryVO.getHypertensionHistory(),controlHistoryVO.getBloodFatHistory(),
controlHistoryVO.getDiabetesHistory(),
controlHistoryVO.getKidneyDiseaseHostory(),controlHistoryVO.getPulmonaryDiseaseHistory(),
historyPharmacys, otherVO);
}
return "redirect:/archives/body.htm?cid="+cid;
}
/**
*
* 方法名称: bodyCheck<br/>
* 描述:体格检查<br/>
* 作者: ruibo<br/>
* 修改日期:2015年12月6日-下午5:08:24<br/>
* @param model
* @return
*/
@RequestMapping("body")
public String bodyCheck(Integer cid, Model model){
if(null!=cid){
PhysiqueExamInfoExample example = new PhysiqueExamInfoExample();
example.createCriteria().andCrowdidEqualTo(cid);
List<PhysiqueExamInfo> list = this.physiqueExamInfoService.list(example);
if(list.size()>0){
PhysiqueExamInfo physiqueExamInfo = list.get(0);
model.addAttribute("physiqueExamInfo",physiqueExamInfo);
}else{
model.addAttribute("physiqueExamInfo",new PhysiqueExamInfo());
}
model.addAttribute("cid",cid);
}else{
model.addAttribute("physiqueExamInfo",new PhysiqueExamInfo());
}
return "archives/body_ae";
}
/**
* @author: Bob
* 修改时间:2015年12月16日 - 上午11:20:50<br/>
* 功能说明:保存体格检查<br/>
* @param cid
* @param physiqueExamInfo
* @param model
* @return
*/
@RequestMapping("savebody")
public String saveBodyCheck(Integer cid, PhysiqueExamInfo physiqueExamInfo){
if(null!=cid){
if(null!=physiqueExamInfo.getPhysiqueexamid()){
this.physiqueExamInfoService.updateById(physiqueExamInfo);
}else{
physiqueExamInfo.setCrowdid(cid);
this.physiqueExamInfoService.add(physiqueExamInfo);
}
}
return "redirect:/archives/heartinfo.htm?cid="+cid;
}
/**
* 方法名称: heartInfo<br/>
* 描述:心电图<br/>
* 作者: ruibo<br/>
* 修改日期:2015年12月6日-下午5:09:00<br/>
* @param model
* @return
*/
@RequestMapping("heartinfo")
public String heartInfo(Integer cid, Model model){
ElectrocardiogramExamInfo electrocardiogramExamInfo = null;
if(null!=cid){
ElectrocardiogramExamInfoExample example = new ElectrocardiogramExamInfoExample();
example.createCriteria().andCrowdidEqualTo(cid);
List<ElectrocardiogramExamInfo> list = this.electrocardiogramExamInfoService.list(example);
if(list.size()>0){
electrocardiogramExamInfo = list.get(0);
}else{
electrocardiogramExamInfo = new ElectrocardiogramExamInfo();
}
model.addAttribute("cid",cid);
}else{
electrocardiogramExamInfo = new ElectrocardiogramExamInfo();
}
model.addAttribute("electrocardiogramExamInfo", electrocardiogramExamInfo);
return "archives/heart_ae";
}
/**
* @author: Bob
* 修改时间:2015年12月16日 - 下午2:00:12<br/>
* 功能说明:保存心电图检查<br/>
* @return
*/
@RequestMapping("saveheart")
public String saveHeart(Integer cid,ElectrocardiogramExamInfo electrocardiogramExamInfo, Model model){
if(null!=cid){
if(null!=electrocardiogramExamInfo.getElectrocardiogramexanid()){
this.electrocardiogramExamInfoService.updateById(electrocardiogramExamInfo);
}else{
electrocardiogramExamInfo.setCrowdid(cid);
this.electrocardiogramExamInfoService.add(electrocardiogramExamInfo);
}
}
return "redirect:/archives/innercheck.htm?cid="+cid;
}
/**
*
* 方法名称: innerCheck<br/>
* 描述:实验室检查<br/>
* 作者: ruibo<br/>
* 修改日期:2015年12月6日-下午5:09:13<br/>
* @param model
* @return
*/
@RequestMapping("innercheck")
public String innerCheck(Integer cid, Model model){
if(null!=cid){
model.addAttribute("cid",cid);
}
return "archives/inner_check_ae";
}
/**
* @author: Bob
* 修改时间:2015年12月16日 - 下午3:20:40<br/>
* 功能说明:保存实验室检查<br/>
* @return
*/
@RequestMapping("saveic")
public String saveInnerCheck(Integer cid, InnerCheckVO entity, Model model){
if(null!=cid){
//此处只考虑新增
for(BloodGlucoseExamInfo info : entity.getBloodGlucoseExamInfos()){
info.setCrowdid(cid);
this.bloodGlucoseExamInfoService.add(info);
}
entity.getBloodFatExamInfo().setCrowdid(cid);
this.bloodFatExamInfoService.add(entity.getBloodFatExamInfo());
entity.getHomocysteineExamInfo().setCrowdid(cid);
this.homocysteineExamInfoService.add(entity.getHomocysteineExamInfo());
}
//return "redirect:/archives/bblood.htm?cid="+cid;
return "redirect:/archives/brainlevel.htm?cid="+cid;
}
/**
* 方法名称: bSuperBlood<br/>
* 描述:颈部血管超声<br/>
* 作者: ruibo<br/>
* 修改日期:2015年12月6日-下午5:09:29<br/>
* @param model
* @return
*/
@RequestMapping("bblood")
public String bSuperBlood(Integer cid, Model model){
if(null!=cid){
model.addAttribute("cid",cid);
}
return "archives/blood_ae";
}
/**
* @author: Bob
* 修改时间:2015年12月16日 - 下午4:12:55<br/>
* 功能说明:保存颈部血管超声<br/>
* @param cid
* @param model
* @return
*/
@RequestMapping("savebb")
public String saveBBlood(Integer cid, Model model){
if(null!=cid){
}
return "redirect:/archives/brainlevel.htm?cid="+cid;
}
/**
* 方法名称: brainLevel<br/>
* 描述:脑卒中风险评级<br/>
* 作者: ruibo<br/>
* 修改日期:2015年12月6日-下午5:08:41<br/>
* @param model
* @return
*/
@RequestMapping("brainlevel")
public String brainLevel(Integer cid, Model model){
ApoplexyConclusionInfo apoplexyConclusionInfo = new ApoplexyConclusionInfo();
if(null!=cid){
model.addAttribute("cid",cid);
ApoplexyConclusionInfoExample example = new ApoplexyConclusionInfoExample();
example.createCriteria().andCrowdidEqualTo(cid);
List<ApoplexyConclusionInfo> list = this.apoplexyConclusionInfoService.list(example);
if(list.size()>0){
model.addAttribute("apoplexyConclusionInfo", list.get(0));
}
}else{
//需要传入默认对象
model.addAttribute("apoplexyConclusionInfo",apoplexyConclusionInfo);
}
return "archives/brain_level_ae";
}
/**
* @author: Bob
* 修改时间:2015年12月16日 - 下午4:43:39<br/>
* 功能说明:保存评级结果<br/>
* @param cid
* @param model
* @return
*/
@RequestMapping("saveres")
public String saveResult(Integer cid, ApoplexyConclusionInfo apoplexyConclusionInfo, Model model){
if(null!=cid){
if(null!=apoplexyConclusionInfo.getApoplexyconclusionid()){
this.apoplexyConclusionInfoService.updateById(apoplexyConclusionInfo);
}else{
apoplexyConclusionInfo.setCrowdid(cid);
this.apoplexyConclusionInfoService.add(apoplexyConclusionInfo);
}
}
return "redirect:/archives.htm";
}
/**
* @author: Bob
* 修改时间:2015年12月15日 - 下午2:21:30<br/>
* 功能说明:处理时间字符串<br/>
* @param binder
*/
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd" );
dateFormat.setLenient( false);
binder.registerCustomEditor(Date. class, new CustomDateEditor(dateFormat, false ));
}
}
|
package itri.io.emulator.experiment;
public class BlockWithFrequency extends Block implements Comparable<BlockWithFrequency> {
private long frequency;
public BlockWithFrequency(long id) {
super(id);
this.frequency = 0;
}
public void updateFrequency() {
this.frequency++;
}
public long getFrequency() {
return frequency;
}
@Override
public int compareTo(BlockWithFrequency o) {
return Long.compare(this.frequency, o.frequency);
}
}
|
package com.ybh.front.model;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Product_IDC_repairExample {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table FreeHost_Product_IDC_repair
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
protected String orderByClause;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table FreeHost_Product_IDC_repair
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
protected boolean distinct;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table FreeHost_Product_IDC_repair
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
protected List<Criteria> oredCriteria;
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table FreeHost_Product_IDC_repair
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public Product_IDC_repairExample() {
oredCriteria = new ArrayList<Criteria>();
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table FreeHost_Product_IDC_repair
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table FreeHost_Product_IDC_repair
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public String getOrderByClause() {
return orderByClause;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table FreeHost_Product_IDC_repair
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table FreeHost_Product_IDC_repair
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public boolean isDistinct() {
return distinct;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table FreeHost_Product_IDC_repair
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table FreeHost_Product_IDC_repair
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table FreeHost_Product_IDC_repair
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table FreeHost_Product_IDC_repair
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table FreeHost_Product_IDC_repair
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table FreeHost_Product_IDC_repair
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table FreeHost_Product_IDC_repair
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(Integer value) {
addCriterion("id =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Integer value) {
addCriterion("id <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(Integer value) {
addCriterion("id >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Integer value) {
addCriterion("id >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(Integer value) {
addCriterion("id <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Integer value) {
addCriterion("id <=", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<Integer> values) {
addCriterion("id in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<Integer> values) {
addCriterion("id not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Integer value1, Integer value2) {
addCriterion("id between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Integer value1, Integer value2) {
addCriterion("id not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andUsernameIsNull() {
addCriterion("username is null");
return (Criteria) this;
}
public Criteria andUsernameIsNotNull() {
addCriterion("username is not null");
return (Criteria) this;
}
public Criteria andUsernameEqualTo(String value) {
addCriterion("username =", value, "username");
return (Criteria) this;
}
public Criteria andUsernameNotEqualTo(String value) {
addCriterion("username <>", value, "username");
return (Criteria) this;
}
public Criteria andUsernameGreaterThan(String value) {
addCriterion("username >", value, "username");
return (Criteria) this;
}
public Criteria andUsernameGreaterThanOrEqualTo(String value) {
addCriterion("username >=", value, "username");
return (Criteria) this;
}
public Criteria andUsernameLessThan(String value) {
addCriterion("username <", value, "username");
return (Criteria) this;
}
public Criteria andUsernameLessThanOrEqualTo(String value) {
addCriterion("username <=", value, "username");
return (Criteria) this;
}
public Criteria andUsernameLike(String value) {
addCriterion("username like", value, "username");
return (Criteria) this;
}
public Criteria andUsernameNotLike(String value) {
addCriterion("username not like", value, "username");
return (Criteria) this;
}
public Criteria andUsernameIn(List<String> values) {
addCriterion("username in", values, "username");
return (Criteria) this;
}
public Criteria andUsernameNotIn(List<String> values) {
addCriterion("username not in", values, "username");
return (Criteria) this;
}
public Criteria andUsernameBetween(String value1, String value2) {
addCriterion("username between", value1, value2, "username");
return (Criteria) this;
}
public Criteria andUsernameNotBetween(String value1, String value2) {
addCriterion("username not between", value1, value2, "username");
return (Criteria) this;
}
public Criteria andPdidIsNull() {
addCriterion("PDID is null");
return (Criteria) this;
}
public Criteria andPdidIsNotNull() {
addCriterion("PDID is not null");
return (Criteria) this;
}
public Criteria andPdidEqualTo(Integer value) {
addCriterion("PDID =", value, "pdid");
return (Criteria) this;
}
public Criteria andPdidNotEqualTo(Integer value) {
addCriterion("PDID <>", value, "pdid");
return (Criteria) this;
}
public Criteria andPdidGreaterThan(Integer value) {
addCriterion("PDID >", value, "pdid");
return (Criteria) this;
}
public Criteria andPdidGreaterThanOrEqualTo(Integer value) {
addCriterion("PDID >=", value, "pdid");
return (Criteria) this;
}
public Criteria andPdidLessThan(Integer value) {
addCriterion("PDID <", value, "pdid");
return (Criteria) this;
}
public Criteria andPdidLessThanOrEqualTo(Integer value) {
addCriterion("PDID <=", value, "pdid");
return (Criteria) this;
}
public Criteria andPdidIn(List<Integer> values) {
addCriterion("PDID in", values, "pdid");
return (Criteria) this;
}
public Criteria andPdidNotIn(List<Integer> values) {
addCriterion("PDID not in", values, "pdid");
return (Criteria) this;
}
public Criteria andPdidBetween(Integer value1, Integer value2) {
addCriterion("PDID between", value1, value2, "pdid");
return (Criteria) this;
}
public Criteria andPdidNotBetween(Integer value1, Integer value2) {
addCriterion("PDID not between", value1, value2, "pdid");
return (Criteria) this;
}
public Criteria andIdctitleIsNull() {
addCriterion("idctitle is null");
return (Criteria) this;
}
public Criteria andIdctitleIsNotNull() {
addCriterion("idctitle is not null");
return (Criteria) this;
}
public Criteria andIdctitleEqualTo(String value) {
addCriterion("idctitle =", value, "idctitle");
return (Criteria) this;
}
public Criteria andIdctitleNotEqualTo(String value) {
addCriterion("idctitle <>", value, "idctitle");
return (Criteria) this;
}
public Criteria andIdctitleGreaterThan(String value) {
addCriterion("idctitle >", value, "idctitle");
return (Criteria) this;
}
public Criteria andIdctitleGreaterThanOrEqualTo(String value) {
addCriterion("idctitle >=", value, "idctitle");
return (Criteria) this;
}
public Criteria andIdctitleLessThan(String value) {
addCriterion("idctitle <", value, "idctitle");
return (Criteria) this;
}
public Criteria andIdctitleLessThanOrEqualTo(String value) {
addCriterion("idctitle <=", value, "idctitle");
return (Criteria) this;
}
public Criteria andIdctitleLike(String value) {
addCriterion("idctitle like", value, "idctitle");
return (Criteria) this;
}
public Criteria andIdctitleNotLike(String value) {
addCriterion("idctitle not like", value, "idctitle");
return (Criteria) this;
}
public Criteria andIdctitleIn(List<String> values) {
addCriterion("idctitle in", values, "idctitle");
return (Criteria) this;
}
public Criteria andIdctitleNotIn(List<String> values) {
addCriterion("idctitle not in", values, "idctitle");
return (Criteria) this;
}
public Criteria andIdctitleBetween(String value1, String value2) {
addCriterion("idctitle between", value1, value2, "idctitle");
return (Criteria) this;
}
public Criteria andIdctitleNotBetween(String value1, String value2) {
addCriterion("idctitle not between", value1, value2, "idctitle");
return (Criteria) this;
}
public Criteria andIdctypeIsNull() {
addCriterion("idctype is null");
return (Criteria) this;
}
public Criteria andIdctypeIsNotNull() {
addCriterion("idctype is not null");
return (Criteria) this;
}
public Criteria andIdctypeEqualTo(String value) {
addCriterion("idctype =", value, "idctype");
return (Criteria) this;
}
public Criteria andIdctypeNotEqualTo(String value) {
addCriterion("idctype <>", value, "idctype");
return (Criteria) this;
}
public Criteria andIdctypeGreaterThan(String value) {
addCriterion("idctype >", value, "idctype");
return (Criteria) this;
}
public Criteria andIdctypeGreaterThanOrEqualTo(String value) {
addCriterion("idctype >=", value, "idctype");
return (Criteria) this;
}
public Criteria andIdctypeLessThan(String value) {
addCriterion("idctype <", value, "idctype");
return (Criteria) this;
}
public Criteria andIdctypeLessThanOrEqualTo(String value) {
addCriterion("idctype <=", value, "idctype");
return (Criteria) this;
}
public Criteria andIdctypeLike(String value) {
addCriterion("idctype like", value, "idctype");
return (Criteria) this;
}
public Criteria andIdctypeNotLike(String value) {
addCriterion("idctype not like", value, "idctype");
return (Criteria) this;
}
public Criteria andIdctypeIn(List<String> values) {
addCriterion("idctype in", values, "idctype");
return (Criteria) this;
}
public Criteria andIdctypeNotIn(List<String> values) {
addCriterion("idctype not in", values, "idctype");
return (Criteria) this;
}
public Criteria andIdctypeBetween(String value1, String value2) {
addCriterion("idctype between", value1, value2, "idctype");
return (Criteria) this;
}
public Criteria andIdctypeNotBetween(String value1, String value2) {
addCriterion("idctype not between", value1, value2, "idctype");
return (Criteria) this;
}
public Criteria andStatusIsNull() {
addCriterion("status is null");
return (Criteria) this;
}
public Criteria andStatusIsNotNull() {
addCriterion("status is not null");
return (Criteria) this;
}
public Criteria andStatusEqualTo(String value) {
addCriterion("status =", value, "status");
return (Criteria) this;
}
public Criteria andStatusNotEqualTo(String value) {
addCriterion("status <>", value, "status");
return (Criteria) this;
}
public Criteria andStatusGreaterThan(String value) {
addCriterion("status >", value, "status");
return (Criteria) this;
}
public Criteria andStatusGreaterThanOrEqualTo(String value) {
addCriterion("status >=", value, "status");
return (Criteria) this;
}
public Criteria andStatusLessThan(String value) {
addCriterion("status <", value, "status");
return (Criteria) this;
}
public Criteria andStatusLessThanOrEqualTo(String value) {
addCriterion("status <=", value, "status");
return (Criteria) this;
}
public Criteria andStatusLike(String value) {
addCriterion("status like", value, "status");
return (Criteria) this;
}
public Criteria andStatusNotLike(String value) {
addCriterion("status not like", value, "status");
return (Criteria) this;
}
public Criteria andStatusIn(List<String> values) {
addCriterion("status in", values, "status");
return (Criteria) this;
}
public Criteria andStatusNotIn(List<String> values) {
addCriterion("status not in", values, "status");
return (Criteria) this;
}
public Criteria andStatusBetween(String value1, String value2) {
addCriterion("status between", value1, value2, "status");
return (Criteria) this;
}
public Criteria andStatusNotBetween(String value1, String value2) {
addCriterion("status not between", value1, value2, "status");
return (Criteria) this;
}
public Criteria andAddtimeIsNull() {
addCriterion("addtime is null");
return (Criteria) this;
}
public Criteria andAddtimeIsNotNull() {
addCriterion("addtime is not null");
return (Criteria) this;
}
public Criteria andAddtimeEqualTo(Date value) {
addCriterion("addtime =", value, "addtime");
return (Criteria) this;
}
public Criteria andAddtimeNotEqualTo(Date value) {
addCriterion("addtime <>", value, "addtime");
return (Criteria) this;
}
public Criteria andAddtimeGreaterThan(Date value) {
addCriterion("addtime >", value, "addtime");
return (Criteria) this;
}
public Criteria andAddtimeGreaterThanOrEqualTo(Date value) {
addCriterion("addtime >=", value, "addtime");
return (Criteria) this;
}
public Criteria andAddtimeLessThan(Date value) {
addCriterion("addtime <", value, "addtime");
return (Criteria) this;
}
public Criteria andAddtimeLessThanOrEqualTo(Date value) {
addCriterion("addtime <=", value, "addtime");
return (Criteria) this;
}
public Criteria andAddtimeIn(List<Date> values) {
addCriterion("addtime in", values, "addtime");
return (Criteria) this;
}
public Criteria andAddtimeNotIn(List<Date> values) {
addCriterion("addtime not in", values, "addtime");
return (Criteria) this;
}
public Criteria andAddtimeBetween(Date value1, Date value2) {
addCriterion("addtime between", value1, value2, "addtime");
return (Criteria) this;
}
public Criteria andAddtimeNotBetween(Date value1, Date value2) {
addCriterion("addtime not between", value1, value2, "addtime");
return (Criteria) this;
}
public Criteria andOpusernameIsNull() {
addCriterion("opusername is null");
return (Criteria) this;
}
public Criteria andOpusernameIsNotNull() {
addCriterion("opusername is not null");
return (Criteria) this;
}
public Criteria andOpusernameEqualTo(String value) {
addCriterion("opusername =", value, "opusername");
return (Criteria) this;
}
public Criteria andOpusernameNotEqualTo(String value) {
addCriterion("opusername <>", value, "opusername");
return (Criteria) this;
}
public Criteria andOpusernameGreaterThan(String value) {
addCriterion("opusername >", value, "opusername");
return (Criteria) this;
}
public Criteria andOpusernameGreaterThanOrEqualTo(String value) {
addCriterion("opusername >=", value, "opusername");
return (Criteria) this;
}
public Criteria andOpusernameLessThan(String value) {
addCriterion("opusername <", value, "opusername");
return (Criteria) this;
}
public Criteria andOpusernameLessThanOrEqualTo(String value) {
addCriterion("opusername <=", value, "opusername");
return (Criteria) this;
}
public Criteria andOpusernameLike(String value) {
addCriterion("opusername like", value, "opusername");
return (Criteria) this;
}
public Criteria andOpusernameNotLike(String value) {
addCriterion("opusername not like", value, "opusername");
return (Criteria) this;
}
public Criteria andOpusernameIn(List<String> values) {
addCriterion("opusername in", values, "opusername");
return (Criteria) this;
}
public Criteria andOpusernameNotIn(List<String> values) {
addCriterion("opusername not in", values, "opusername");
return (Criteria) this;
}
public Criteria andOpusernameBetween(String value1, String value2) {
addCriterion("opusername between", value1, value2, "opusername");
return (Criteria) this;
}
public Criteria andOpusernameNotBetween(String value1, String value2) {
addCriterion("opusername not between", value1, value2, "opusername");
return (Criteria) this;
}
public Criteria andAgent1IsNull() {
addCriterion("agent1 is null");
return (Criteria) this;
}
public Criteria andAgent1IsNotNull() {
addCriterion("agent1 is not null");
return (Criteria) this;
}
public Criteria andAgent1EqualTo(String value) {
addCriterion("agent1 =", value, "agent1");
return (Criteria) this;
}
public Criteria andAgent1NotEqualTo(String value) {
addCriterion("agent1 <>", value, "agent1");
return (Criteria) this;
}
public Criteria andAgent1GreaterThan(String value) {
addCriterion("agent1 >", value, "agent1");
return (Criteria) this;
}
public Criteria andAgent1GreaterThanOrEqualTo(String value) {
addCriterion("agent1 >=", value, "agent1");
return (Criteria) this;
}
public Criteria andAgent1LessThan(String value) {
addCriterion("agent1 <", value, "agent1");
return (Criteria) this;
}
public Criteria andAgent1LessThanOrEqualTo(String value) {
addCriterion("agent1 <=", value, "agent1");
return (Criteria) this;
}
public Criteria andAgent1Like(String value) {
addCriterion("agent1 like", value, "agent1");
return (Criteria) this;
}
public Criteria andAgent1NotLike(String value) {
addCriterion("agent1 not like", value, "agent1");
return (Criteria) this;
}
public Criteria andAgent1In(List<String> values) {
addCriterion("agent1 in", values, "agent1");
return (Criteria) this;
}
public Criteria andAgent1NotIn(List<String> values) {
addCriterion("agent1 not in", values, "agent1");
return (Criteria) this;
}
public Criteria andAgent1Between(String value1, String value2) {
addCriterion("agent1 between", value1, value2, "agent1");
return (Criteria) this;
}
public Criteria andAgent1NotBetween(String value1, String value2) {
addCriterion("agent1 not between", value1, value2, "agent1");
return (Criteria) this;
}
public Criteria andAgent2IsNull() {
addCriterion("agent2 is null");
return (Criteria) this;
}
public Criteria andAgent2IsNotNull() {
addCriterion("agent2 is not null");
return (Criteria) this;
}
public Criteria andAgent2EqualTo(String value) {
addCriterion("agent2 =", value, "agent2");
return (Criteria) this;
}
public Criteria andAgent2NotEqualTo(String value) {
addCriterion("agent2 <>", value, "agent2");
return (Criteria) this;
}
public Criteria andAgent2GreaterThan(String value) {
addCriterion("agent2 >", value, "agent2");
return (Criteria) this;
}
public Criteria andAgent2GreaterThanOrEqualTo(String value) {
addCriterion("agent2 >=", value, "agent2");
return (Criteria) this;
}
public Criteria andAgent2LessThan(String value) {
addCriterion("agent2 <", value, "agent2");
return (Criteria) this;
}
public Criteria andAgent2LessThanOrEqualTo(String value) {
addCriterion("agent2 <=", value, "agent2");
return (Criteria) this;
}
public Criteria andAgent2Like(String value) {
addCriterion("agent2 like", value, "agent2");
return (Criteria) this;
}
public Criteria andAgent2NotLike(String value) {
addCriterion("agent2 not like", value, "agent2");
return (Criteria) this;
}
public Criteria andAgent2In(List<String> values) {
addCriterion("agent2 in", values, "agent2");
return (Criteria) this;
}
public Criteria andAgent2NotIn(List<String> values) {
addCriterion("agent2 not in", values, "agent2");
return (Criteria) this;
}
public Criteria andAgent2Between(String value1, String value2) {
addCriterion("agent2 between", value1, value2, "agent2");
return (Criteria) this;
}
public Criteria andAgent2NotBetween(String value1, String value2) {
addCriterion("agent2 not between", value1, value2, "agent2");
return (Criteria) this;
}
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table FreeHost_Product_IDC_repair
*
* @mbg.generated do_not_delete_during_merge Fri May 11 11:16:07 CST 2018
*/
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table FreeHost_Product_IDC_repair
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
|
package mando.sirius.bot;
import com.eu.habbo.Emulator;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.TextChannel;
import java.time.Instant;
public class Logging {
public static void error(Exception e) {//Todo: make this
Emulator.getLogging().handleException(e);
if (Constants.LOG_CHANNEL_ID > 0L) {
TextChannel channel = Sirius.getJda().getTextChannelById(Constants.LOG_CHANNEL_ID);
if (channel == null)
return;
EmbedBuilder builder = new EmbedBuilder()
.setTitle("Error")
.appendDescription(e.getLocalizedMessage())
.setTimestamp(Instant.now());
channel.sendMessage(builder.build()).queue();
}
}
}
|
package leetcode;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* @author kangkang lou
*/
class PeekingIterator implements Iterator<Integer> {
List<Integer> list = new LinkedList<>();
public PeekingIterator(Iterator<Integer> iterator) {
// initialize any member here.
while (iterator.hasNext()) {
list.add(iterator.next());
}
}
// Returns the next element in the iteration without advancing the iterator.
public Integer peek() {
return list.get(0);
}
// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
@Override
public Integer next() {
return list.remove(0);
}
@Override
public boolean hasNext() {
return list.size() > 0;
}
}
public class Main_284 {
}
|
package IB;
/**
* Created by Admin on 22-01-2017.
*/
public class squareroot {
public int sqrt(int a) {
int result = 0;
if(a==0 || a==1){
return a;
}
int start = 1;
int end = a;
int mid;
while(start <= end){
mid = (start+end)/2;
if(mid == a/mid && a%mid ==0){
return mid;
}
else if(mid <= a/mid){
start = mid+1;
result = mid;
}
else{
end = mid-1;
}
}
return result;
}
public static void main(String[] args) {
squareroot s = new squareroot();
int k = s.sqrt(2147483647);
System.out.println(k);
}
}
|
package com.boot.spring.model;
public class Avatar {
}
|
package com.tencent.mm.plugin.hce.ui;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
class HCETransparentUI$2 implements OnClickListener {
final /* synthetic */ HCETransparentUI kjt;
HCETransparentUI$2(HCETransparentUI hCETransparentUI) {
this.kjt = hCETransparentUI;
}
public final void onClick(DialogInterface dialogInterface, int i) {
HCETransparentUI.f(this.kjt);
}
}
|
package old.utility;
import static org.testng.Assert.assertTrue;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class Commonsutility {
public static void checkEnabledAndDisplayed(WebElement... elements) {
for (WebElement element : elements) {
assertTrue(element.isDisplayed(), "element expeceted to display");
assertTrue(element.isEnabled(), "element expected to enable");
}
}
@FindBy(id="idLbl") WebElement idlabel;
@FindBy(id="desigLbl") WebElement designationlabel1;
@FindBy(id="fNameLbl") WebElement fnamelabel;
@FindBy(id="lNameLbl") WebElement lnamelabel;
@FindBy(id="genderLbl") WebElement gendlabel;
@FindBy(id="deptNameLbl") WebElement deptnamelabel;
@FindBy(id="managerLbl") WebElement managerlabel1;
@FindBy(id="loginNameLbl") WebElement loginlabel;
@FindBy(id="dobLbl") WebElement dateblabel;
@FindBy(id="dojLbl") WebElement dateofjlabel;
@FindBy(id="mnoLbl") WebElement mobilelabel;
@FindBy(id="maritalStatusLbl") WebElement maritalstatuslabel1;
@FindBy(id="statusLbl") WebElement statuslabel1;
public static void aftercreate() {
}
}
|
package com.foosbot.service.handlers;
import com.foosbot.service.handlers.payloads.NewSeasonPayload;
import com.foosbot.service.model.Model;
import java.util.Map;
public class NewSeasonHandler extends AbstractRequestHandler<NewSeasonPayload> {
public NewSeasonHandler(final Model model) {
super(NewSeasonPayload.class, model);
}
@Override
protected Answer processImpl(final NewSeasonPayload value, final Map<String, String> urlParams) {
return null;
}
}
|
package com.sunteam.library.activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.FrameLayout;
import com.sunteam.common.menu.BaseActivity;
import com.sunteam.common.menu.MenuConstant;
import com.sunteam.common.tts.TtsListener;
import com.sunteam.common.tts.TtsUtils;
import com.sunteam.library.R;
import com.sunteam.library.utils.LogUtils;
import com.sunteam.library.view.LibrarySearchView;
public class SearchActivity extends BaseActivity {
private FrameLayout mFlContainer = null;
private LibrarySearchView mMainView = null;
private Boolean hasCreated = false;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.common_menu_activity);
initView();
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
if(!hasCreated){
hasCreated = true;
// 在平板电脑上运行时,若在onCreate()中,会出现java.lang.NullPointerException异常
mFlContainer.removeAllViews();
mFlContainer.addView(mMainView.getView());
// mMainView.calcItemCount();
}
}
}
@Override
protected void onResume() {
super.onResume();
if (null != mMainView) {
mMainView.onResume();
}
TtsUtils.getInstance(this, mTtsListener);
}
@Override
protected void onDestroy() {
super.onDestroy();
}
private void initView() {
// this.getWindow().setBackgroundDrawable(new ColorDrawable(new Tools(this).getBackgroundColor()));
mFlContainer = (FrameLayout) this.findViewById(R.id.common_menu_fl_container);
Intent intent = getIntent();
String mTitle = intent.getStringExtra(MenuConstant.INTENT_KEY_TITLE);
try {
mMainView = new LibrarySearchView(this, mTitle);
} catch (Exception e) {
e.printStackTrace();
finish();
}
/*// 在平板电脑上运行时,会出现java.lang.NullPointerException异常,可把这两行放到onWindowFocusChanged()中
mFlContainer.removeAllViews();
mFlContainer.addView(mMainView.getView());*/
/*Global.setHandler(mHandler);
Global.setContext(this);*/
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
boolean ret = false;
try {
ret = mMainView.onKeyDown(keyCode, event);
LogUtils.d("[MainActivity] onKeyDown(): keyCode = " + keyCode + ", ret = " + ret);
} catch (Exception e) {
e.printStackTrace();
}
if (!ret) {
ret = super.onKeyDown(keyCode, event);
}
return ret;
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
boolean ret = false;
try {
ret = mMainView.onKeyUp(keyCode, event);
LogUtils.d("[MainActivity] onKeyDown(): onKeyUp = " + keyCode + ", ret = " + ret);
} catch (Exception e) {
e.printStackTrace();
}
if (!ret) {
ret = super.onKeyUp(keyCode, event);
}
return ret;
}
private TtsListener mTtsListener = new TtsListener() {
@Override
public void onSpeakResumed() {
}
@Override
public void onSpeakProgress(int percent, int beginPos, int endPos) {
}
@Override
public void onSpeakPaused() {
}
@Override
public void onSpeakBegin() {
}
@Override
public void onInit(int code) {
}
@Override
public void onCompleted(String error) {
mMainView.processLongKey();
}
@Override
public void onBufferProgress(int percent, int beginPos, int endPos, String info) {
}
};
}
|
package com.hs.example.javaproxy.service.impl;
import com.hs.example.javaproxy.service.HelloService;
/**
* 静态代理类
*/
public class HelloServiceStaticProxy implements HelloService{
private HelloService helloService;
public HelloServiceStaticProxy(HelloService helloService){
this.helloService = helloService;
}
@Override
public void sayHello(String name) {
System.out.println("before sayHello......");
helloService.sayHello(name);
System.out.println("after sayHello......");
}
public static void main(String[] args) {
HelloService helloService = new HelloServiceStaticProxy(new HelloServiceImpl());
helloService.sayHello("zs");
}
}
|
package ru.kappers.model.dto.leon;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* DTO сущность участника соревнования в событии
* */
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class CompetitorLeonDTO {
private long id;
private String name;
private String homeAway;
private String type;
private String logo;
}
|
package com.vladan.mymovies.ui.main.search;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.ViewModel;
import com.vladan.mymovies.data.AppDataManager;
import com.vladan.mymovies.data.model.Movie;
import com.vladan.mymovies.data.model.Response;
import java.util.Collections;
import java.util.List;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
/**
* Created by Vladan on 10/21/2017.
*/
public class SearchViewModel extends ViewModel {
private AppDataManager appDataManager;
private final MutableLiveData<Boolean> loadingLiveData = new MutableLiveData<>();
private MutableLiveData<Response<List<Movie>>> popularMoviesLiveData;
private MutableLiveData<Response<List<Movie>>> topRatedMoviesLiveData;
private MutableLiveData<Response<List<Movie>>> upcomingMoviesLiveData;
private MutableLiveData<Response<List<Movie>>> searchedMovies;
public SearchViewModel(AppDataManager appDataManager) {
this.appDataManager = appDataManager;
}
LiveData<Response<List<Movie>>> getMoviesList() {
if (popularMoviesLiveData == null) {
popularMoviesLiveData = new MutableLiveData<>();
appDataManager.popularMovies()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(disposable -> loadingLiveData.setValue(true))
.doAfterTerminate(() -> loadingLiveData.setValue(false))
.subscribe(
movies -> popularMoviesLiveData.setValue(Response.success(movies)),
throwable -> popularMoviesLiveData.setValue(Response.error(throwable))
);
}
return popularMoviesLiveData;
}
LiveData<Response<List<Movie>>> getTopRatedMovies() {
if (topRatedMoviesLiveData == null) {
topRatedMoviesLiveData = new MutableLiveData<>();
appDataManager.topRatedMovies()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(disposable -> loadingLiveData.setValue(true))
.doAfterTerminate(() -> loadingLiveData.setValue(false))
.subscribe(
movies -> topRatedMoviesLiveData.setValue(Response.success(movies)),
throwable -> topRatedMoviesLiveData.setValue(Response.error(throwable))
);
}
return topRatedMoviesLiveData;
}
LiveData<Response<List<Movie>>> getUpcomingMovies() {
if (upcomingMoviesLiveData == null) {
upcomingMoviesLiveData = new MutableLiveData<>();
appDataManager.upcomingMovies()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(disposable -> loadingLiveData.setValue(true))
.doAfterTerminate(() -> loadingLiveData.setValue(false))
.subscribe(
movies -> upcomingMoviesLiveData.setValue(Response.success(movies)),
throwable -> upcomingMoviesLiveData.setValue(Response.error(throwable))
);
}
return upcomingMoviesLiveData;
}
LiveData<Response<List<Movie>>> getSearchedMovies(String search) {
searchedMovies = new MutableLiveData<>();
appDataManager.searchMovies(search)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(disposable -> loadingLiveData.setValue(true))
.doAfterTerminate(() -> loadingLiveData.setValue(false))
.subscribe(
movies -> searchedMovies.setValue(Response.success(movies)),
throwable -> searchedMovies.setValue(Response.error(throwable))
);
return searchedMovies;
}
}
|
package com.tencent.mm.g.a;
import java.util.Set;
public final class ms$a {
public Set bXI;
public String filePath;
}
|
package uk.co.samwho.modopticon;
import java.util.Set;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.google.common.flogger.FluentLogger;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.core.hooks.ListenerAdapter;
import uk.co.samwho.modopticon.storage.Users;
@Singleton
public final class Backfiller implements Runnable {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private final JDA jda;
private final Set<? extends ListenerAdapter> listeners;
@Inject
public Backfiller(JDA jda, Set<? extends ListenerAdapter> listeners) {
this.jda = jda;
this.listeners = listeners;
}
@Override
public void run() {
logger.atInfo().log("starting backfill");
jda.getGuilds().stream().parallel().forEach(guild -> {
logger.atInfo().log("backfilling channel data for guild %s", guild.getName());
guild.getTextChannels().stream().parallel().forEach(channel -> {
if (!guild.getSelfMember().hasPermission(channel, Permission.MESSAGE_HISTORY)) {
return;
}
channel.getIterableHistory().limit(100).cache(false).stream().limit(100).forEach(message -> {
if (Users.isDeleted(message)) {
return;
}
GuildMessageReceivedEvent event = new GuildMessageReceivedEvent(jda, -1, message);
listeners.forEach(l -> l.onGuildMessageReceived(event));
});
});
});
logger.atInfo().log("backfill finished");
}
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;
/**
* JbpmDelegation generated by hbm2java
*/
public class JbpmDelegation implements java.io.Serializable {
private BigDecimal id;
private JbpmProcessdefinition jbpmProcessdefinition;
private String classname;
private String configuration;
private String configtype;
private Set jbpmSwimlanes = new HashSet(0);
private Set jbpmActions = new HashSet(0);
private Set jbpmNodes = new HashSet(0);
private Set jbpmTasks = new HashSet(0);
private Set jbpmTaskcontrollers = new HashSet(0);
public JbpmDelegation() {
}
public JbpmDelegation(BigDecimal id) {
this.id = id;
}
public JbpmDelegation(BigDecimal id, JbpmProcessdefinition jbpmProcessdefinition, String classname,
String configuration, String configtype, Set jbpmSwimlanes, Set jbpmActions, Set jbpmNodes, Set jbpmTasks,
Set jbpmTaskcontrollers) {
this.id = id;
this.jbpmProcessdefinition = jbpmProcessdefinition;
this.classname = classname;
this.configuration = configuration;
this.configtype = configtype;
this.jbpmSwimlanes = jbpmSwimlanes;
this.jbpmActions = jbpmActions;
this.jbpmNodes = jbpmNodes;
this.jbpmTasks = jbpmTasks;
this.jbpmTaskcontrollers = jbpmTaskcontrollers;
}
public BigDecimal getId() {
return this.id;
}
public void setId(BigDecimal id) {
this.id = id;
}
public JbpmProcessdefinition getJbpmProcessdefinition() {
return this.jbpmProcessdefinition;
}
public void setJbpmProcessdefinition(JbpmProcessdefinition jbpmProcessdefinition) {
this.jbpmProcessdefinition = jbpmProcessdefinition;
}
public String getClassname() {
return this.classname;
}
public void setClassname(String classname) {
this.classname = classname;
}
public String getConfiguration() {
return this.configuration;
}
public void setConfiguration(String configuration) {
this.configuration = configuration;
}
public String getConfigtype() {
return this.configtype;
}
public void setConfigtype(String configtype) {
this.configtype = configtype;
}
public Set getJbpmSwimlanes() {
return this.jbpmSwimlanes;
}
public void setJbpmSwimlanes(Set jbpmSwimlanes) {
this.jbpmSwimlanes = jbpmSwimlanes;
}
public Set getJbpmActions() {
return this.jbpmActions;
}
public void setJbpmActions(Set jbpmActions) {
this.jbpmActions = jbpmActions;
}
public Set getJbpmNodes() {
return this.jbpmNodes;
}
public void setJbpmNodes(Set jbpmNodes) {
this.jbpmNodes = jbpmNodes;
}
public Set getJbpmTasks() {
return this.jbpmTasks;
}
public void setJbpmTasks(Set jbpmTasks) {
this.jbpmTasks = jbpmTasks;
}
public Set getJbpmTaskcontrollers() {
return this.jbpmTaskcontrollers;
}
public void setJbpmTaskcontrollers(Set jbpmTaskcontrollers) {
this.jbpmTaskcontrollers = jbpmTaskcontrollers;
}
}
|
package ro.halic.catalin.mvptutorial.main.view;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import ro.halic.catalin.mvptutorial.R;
import ro.halic.catalin.mvptutorial.main.MainMVP;
public class MainActivity extends AppCompatActivity implements MainMVP.RequiredViewOps{
private MainMVP.PresenterOps presenterOps;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void setup() {
}
}
|
package controller;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import model.Artigo;
import model.AtuacaoProfissional;
import model.Candidato;
import model.Conferencia;
import model.Evento;
import model.FormacaoAcademica;
import model.Periodico;
import model.Premio;
import model.ProjetoPesquisa;
import model.QualisEnum;
import model.Vinculo;
import utils.Constantes;
import utils.XmlUtils;
/**
* Classe para carregar um candidato a partir do arquivo XML.
*
*/
public class CandidatoXMLController {
/**
* Implementacao do Singleton.
*/
private static CandidatoXMLController unicaInstancia;
private CandidatoXMLController() {}
public static CandidatoXMLController getInstancia() {
if (unicaInstancia == null) {
unicaInstancia = new CandidatoXMLController();
}
return unicaInstancia;
}
// Funcao para carregar o Nome do candidato com base do arquivo lattes.
private void carregarNome(Candidato candidato, Document lattes) {
candidato.setNome(XmlUtils.getValorAtributo(lattes, "DADOS-GERAIS", "NOME-COMPLETO"));
}
/**
* Numero de premios recebidos nos ultimos 10 anos.
* Itens na secao "PREMIOS-TITULOS" do lattes.
*/
public void carregarPremios(Candidato candidato, Document lattes) {
NodeList nos = XmlUtils.getNos(lattes, "PREMIO-TITULO");
for (int contador = 0; contador < nos.getLength(); contador++) {
Node no = nos.item(contador);
// Dados do premio:
String nome = XmlUtils.getValorAtributo(no, "NOME-DO-PREMIO-OU-TITULO");
String anoPremiacao = XmlUtils.getValorAtributo(no, "ANO-DA-PREMIACAO");
int ano = Constantes.ANO_INICIAL_PADRAO;
if (anoPremiacao != null) {
ano = Integer.parseInt(anoPremiacao);
}
if (ano >= Constantes.ANO_LIMITE) {
candidato.addPremio(new Premio(ano, nome));
}
}
}
/**
* Adiciona artigos publicados em periodicos ao ArrayList<Artigo> artigos.
*/
private void adicionarArtigosPeriodicos(Candidato candidato, Document lattes) {
NodeList nos = XmlUtils.getNos(lattes, "ARTIGO-PUBLICADO");
for (int contador = 0; contador < nos.getLength(); contador++) {
Node no = nos.item(contador);
Node dadosBasicos = no.getFirstChild();
String natureza = XmlUtils.getValorAtributo(dadosBasicos, "NATUREZA");
if (natureza.equals("COMPLETO")) {
// Dados do Artigo:
String anoPublicacao = XmlUtils.getValorAtributo(dadosBasicos, "ANO-DO-ARTIGO");
String titulo = XmlUtils.getValorAtributo(dadosBasicos, "TITULO-DO-ARTIGO");
// Dados do Periodico:
Node detalhes = dadosBasicos.getNextSibling();
String nomePeriodico = XmlUtils.getValorAtributo(detalhes, "TITULO-DO-PERIODICO-OU-REVISTA");
String issn = XmlUtils.getValorAtributo(detalhes, "ISSN");
Periodico periodico = new Periodico(issn, nomePeriodico);
int ano = Constantes.ANO_INICIAL_PADRAO;
if (anoPublicacao != null) {
ano = Integer.parseInt(anoPublicacao);
}
if (ano >= Constantes.ANO_LIMITE) {
candidato.addArtigoCompleto(new Artigo(titulo, periodico, ano));
}
}
}
}
/**
* Adiciona artigos publicados em conferencias ao ArrayList<Artigo> artigos.
*/
private void adicionarArtigosConferencias(Candidato candidato, Document lattes) {
NodeList nos = XmlUtils.getNos(lattes, "TRABALHO-EM-EVENTOS");
for (int contador = 0; contador < nos.getLength(); contador++) {
Node no = nos.item(contador);
Node dadosBasicos = no.getFirstChild();
String natureza = XmlUtils.getValorAtributo(dadosBasicos, "NATUREZA");
if (natureza.equals("COMPLETO")) {
// Dados do Artigo:
String anoPublicacao = XmlUtils.getValorAtributo(dadosBasicos, "ANO-DO-TRABALHO");
String titulo = XmlUtils.getValorAtributo(dadosBasicos, "TITULO-DO-TRABALHO");
// Dados da Conferencia:
Node detalhes = dadosBasicos.getNextSibling();
String nomeEvento = XmlUtils.getValorAtributo(detalhes, "NOME-DO-EVENTO");
Conferencia conferencia = new Conferencia(nomeEvento);
int ano = Constantes.ANO_INICIAL_PADRAO;
if (anoPublicacao != null) {
ano = Integer.parseInt(anoPublicacao);
}
if (ano >= Constantes.ANO_LIMITE) {
candidato.addArtigoCompleto(new Artigo(titulo, conferencia, ano));
}
}
}
}
/**
* Captura todos os artigos do lattes e divide entre os
* que sao qualis restrito e qualis completo.
*/
private void carregarArtigosCompletos(Candidato candidato, Document lattes) {
adicionarArtigosPeriodicos(candidato, lattes);
adicionarArtigosConferencias(candidato, lattes);
// Divide em qualis restrito e completo e
// separa nos ArrayLists especificos:
for (Artigo artigo : candidato.getArtigosCompletos()) {
QualisEnum qualis = artigo.getQualis();
if (qualis == QualisEnum.A1 ||
qualis == QualisEnum.A2 ||
qualis == QualisEnum.B1) {
candidato.addArtigoCompletoQualisRestrito(artigo);
}
if (qualis == QualisEnum.B2 ||
qualis == QualisEnum.B3 ||
qualis == QualisEnum.B4 ||
qualis == QualisEnum.B5) {
candidato.addArtigosCompletosQualisCompleto(artigo);
}
}
}
/**
* Funcao auxiliar para adicionar nos do XML lattes no ArrayList<Evento> do candidato.
* @param nos - NodeList, nos contendo eventos de varios tipos.
*/
private void adicionarEventosListaEventos(Candidato candidato, NodeList nos) {
Node no;
for (int contador = 0; contador < nos.getLength(); contador++) {
no = nos.item(contador);
Node dadosBasicos = no.getPreviousSibling();
// Qualquer tipo de Evento tem ano e nome.
String ano = XmlUtils.getValorAtributo(dadosBasicos, "ANO");
String nome = XmlUtils.getValorAtributo(no, "NOME-DO-EVENTO");
if (ano == null || ano == "") {
ano = String.valueOf(Constantes.ANO_INICIAL_PADRAO);
}
Evento evento = new Evento(Integer.parseInt(ano), nome);
QualisEnum qualis = evento.getQualis();
// Tem classificacao de A1 a B5.
if (qualis != null) {
candidato.addEvento(evento);
}
}
}
/**
* Adiciona Eventos no ArrayList<Evento>, separando e adicionando
* os Eventos por tipo: congresso, simposio, encontro ou outro.
*/
private void carregarEventos(Candidato candidato, Document lattes) {
adicionarEventosListaEventos(candidato, XmlUtils.getNos(lattes, "DETALHAMENTO-DA-PARTICIPACAO-EM-SIMPOSIO"));
adicionarEventosListaEventos(candidato, XmlUtils.getNos(lattes, "DETALHAMENTO-DA-PARTICIPACAO-EM-CONGRESSO"));
adicionarEventosListaEventos(candidato, XmlUtils.getNos(lattes, "DETALHAMENTO-DA-PARTICIPACAO-EM-ENCONTRO"));
adicionarEventosListaEventos(candidato, XmlUtils.getNos(lattes, "DETALHAMENTO-DE-OUTRAS-PARTICIPACOES-EM-EVENTOS-CONGRESSOS"));
}
/**
* Projetos dos ultimos 10 anos.
*/
private void carregarProjetosPesquisa(Candidato candidato, Document lattes) {
NodeList nos = XmlUtils.getNos(lattes, "PROJETO-DE-PESQUISA");
for (int contador = 0; contador < nos.getLength(); contador++) {
Node no = nos.item(contador);
String anoVinculo = XmlUtils.getValorAtributo(no, "ANO-INICIO");
String titulo = XmlUtils.getValorAtributo(no, "NOME-DO-PROJETO");
String coordenadorProjeto = "";
NodeList integrantes = no.getFirstChild().getChildNodes(); // EQUIPE-DO-PROJETO -> INTEGRANTES-DO-PROJETO
for (int contador2 = 0; contador2 < integrantes.getLength(); contador2++) {
Node integrante = integrantes.item(contador2);
String nome = XmlUtils.getValorAtributo(integrante, "NOME-COMPLETO");
String ehCoordenador = XmlUtils.getValorAtributo(integrante, "FLAG-RESPONSAVEL");
if (ehCoordenador.equals("SIM")) {
coordenadorProjeto = nome;
}
}
if (anoVinculo == null || anoVinculo == "") {
anoVinculo = String.valueOf(Constantes.ANO_INICIAL_PADRAO);
}
int ano = Integer.parseInt(anoVinculo);
if (ano >= Constantes.ANO_LIMITE) {
candidato.addProjetoPesquisa(new ProjetoPesquisa(ano, titulo, coordenadorProjeto));
}
}
}
/**
* Ano de formacao nos ultimos 10 anos.
*/
private void carregarFormacoesAcademicas(Candidato candidato, Document lattes) {
NodeList nos = XmlUtils.getNos(lattes, "FORMACAO-ACADEMICA-TITULACAO");
if (nos.getLength() > 0) {
NodeList formacoes = nos.item(0).getChildNodes();
for (int contador = 0; contador < formacoes.getLength(); contador++) {
Node no = formacoes.item(contador);
String dataFormacao = XmlUtils.getValorAtributo(no, "ANO-DE-CONCLUSAO");
String nomeUniversidade = XmlUtils.getValorAtributo(no, "NOME-INSTITUICAO");
String titulo = no.getNodeName();
if (dataFormacao == null || dataFormacao == "") {
dataFormacao = String.valueOf(Constantes.ANO_FINAL_PADRAO);
}
int ano = Integer.parseInt(dataFormacao);
if (ano >= Constantes.ANO_LIMITE) {
candidato.addFormacaoAcademica(new FormacaoAcademica(ano, nomeUniversidade, titulo));
}
}
}
}
/**
* Atuacoes nos ultimos 10 anos, ou atuais.
*/
private void carregarAtuacoesProfissionais(Candidato candidato, Document lattes) {
NodeList nos = XmlUtils.getNos(lattes, "VINCULOS"); // ATUACAO-PROFISSIONAL -> VINCULOS
for (int contador = 0; contador < nos.getLength(); contador++) {
Node no = nos.item(contador);
String anoInicio = XmlUtils.getValorAtributo(no, "ANO-INICIO");
String anoFim = XmlUtils.getValorAtributo(no, "ANO-FIM");
String localAtuacao = XmlUtils.getValorAtributo(no.getParentNode(), "NOME-INSTITUICAO");
String descricaoVinculo =
XmlUtils.getValorAtributo(no, "TIPO-DE-VINCULO") + " - " +
XmlUtils.getValorAtributo(no, "OUTRO-VINCULO-INFORMADO") + " - " +
XmlUtils.getValorAtributo(no, "OUTRO-ENQUADRAMENTO-FUNCIONAL-INFORMADO");
if (anoInicio == null || anoInicio == "") {
anoInicio = String.valueOf(Constantes.ANO_INICIAL_PADRAO);
}
// Pode ser uma atuacao vigente, sem ano final.
if (anoFim == null || anoFim == "") {
anoFim = String.valueOf(Constantes.ANO_FINAL_PADRAO);
}
int anoFinal = Integer.parseInt(anoFim);
if (anoFinal >= Constantes.ANO_LIMITE) {
candidato.addAtuacaoProfissional(new AtuacaoProfissional(Integer.parseInt(anoInicio), anoFinal, localAtuacao, descricaoVinculo));
}
}
}
/**
* Altera a variavel possuiVinculoInstituicao para true se nos ultimos 10 anos o candidato:
* 1. Participou em projetos cujo coordenador eh um professor da UNIRIO.
* 2. Tem formacao academica/bolsas cuja instituicao eh a UNIRIO.
* 3. Possui alguma atuacao profissional cuja instituicao eh a UNIRIO (aqui estao
* inclusas representacao discente ou outras).
*/
private void carregarVinculoInstituicao(Candidato candidato) {
// Projetos:
for (ProjetoPesquisa projeto : candidato.getProjetosPesquisa()) {
if (ProfessorController.getInstancia().ehProfessorUnirio(projeto.getCoordenadorProjeto())) {
candidato.addVinculo(new Vinculo(projeto.getAnoVinculo(), projeto.getTitulo(), "Projeto de Pesquisa"));
}
}
// Formacao academica:
for (FormacaoAcademica formacao : candidato.getFormacoesAcademicas()) {
if (formacao.getNomeUniversidade().contains("Universidade Federal do Estado do Rio de Janeiro")) {
candidato.addVinculo(new Vinculo(formacao.getDataFormacao(), formacao.getTitulo(), "Formacao academica"));
}
}
// Atuacao profissional:
for (AtuacaoProfissional atuacao : candidato.getAtuacoesProfissionais()) {
if (atuacao.getLocalAtuacao().contains("Universidade Federal do Estado do Rio de Janeiro")) {
candidato.addVinculo(new Vinculo(atuacao.getAnoFim(), atuacao.getDescricaoVinculo(), "Atuacao profissional"));
}
}
if (candidato.getVinculos().size() > 0) {
candidato.setPossuiVinculoInstituicao(true);
}
}
// Construtor. Le o lattes e o numero de semestre sem reprovacoes,
// calculando os demais campos da classe.
public Candidato carregarCandidatoCompleto(Candidato candidato, String caminhoXml) {
try {
Document lattes = XmlUtils.lerXml(caminhoXml, "CURRICULO-VITAE");
carregarNome(candidato, lattes);
carregarPremios(candidato, lattes);
carregarArtigosCompletos(candidato, lattes);
carregarAtuacoesProfissionais(candidato, lattes);
carregarEventos(candidato, lattes);
carregarFormacoesAcademicas(candidato, lattes);
carregarProjetosPesquisa(candidato, lattes);
carregarVinculoInstituicao(candidato);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Erro na leitura do lattes.");
}
return candidato;
}
}
|
class Phone{
String model;//멤버변수
int value;
void print() {
System.out.println(value+"만원짜리"+model+"스마트폰");
}
}
public class PhoneDemo{
public static void main(String args[]) {
Phone myPhone = new Phone();
myPhone.model = "갤럭시 S9";
myPhone.value = 100;
myPhone.print();
}
}
|
package com.aprendoz_test.data;
/**
* aprendoz_test.AprEsperados
* 01/19/2015 07:58:52
*
*/
public class AprEsperados {
private AprEsperadosId id;
public AprEsperadosId getId() {
return id;
}
public void setId(AprEsperadosId id) {
this.id = id;
}
}
|
package com.sinata.rwxchina.basiclib.basic.basicmap;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.PoiItem;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jaeger.library.StatusBarUtil;
import com.sinata.rwxchina.basiclib.HttpPath;
import com.sinata.rwxchina.basiclib.R;
import com.sinata.rwxchina.basiclib.base.BaseActivity;
import com.sinata.rwxchina.basiclib.commonclass.entity.ScenicEntity;
import com.sinata.rwxchina.basiclib.entity.BaseShopInfo;
import com.sinata.rwxchina.basiclib.utils.amaputils.LocationUtils;
import com.sinata.rwxchina.basiclib.utils.amaputils.NativeUtils;
import com.sinata.rwxchina.basiclib.utils.imageUtils.ImageUtils;
import com.sinata.rwxchina.basiclib.utils.immersionutils.ImmersionUtils;
import com.sinata.rwxchina.basiclib.utils.retrofitutils.ApiManager;
import com.sinata.rwxchina.basiclib.utils.retrofitutils.callback.StringCallBack;
import com.sinata.rwxchina.basiclib.utils.retrofitutils.entity.PageInfo;
import com.sinata.rwxchina.basiclib.view.ActionSheetDialog;
import com.sinata.rwxchina.retrofitutils.exception.ApiException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import rx.Observable;
import rx.Observer;
import rx.functions.Action1;
import rx.observables.SyncOnSubscribe;
import rx.schedulers.Schedulers;
/**
* @author HRR
* @datetime 2017/12/21
* @describe 商铺列表地图页面
* @modifyRecord
*/
public class BasicShopListMapActivity extends BaseActivity {
/**
* 地图
*/
private MapView mMapView;
/**
* 初始化地图控制器对象
*/
private AMap aMap;
/**
* 标题
*/
private ImageView back;
private TextView title;
private View statusBar;
/**
* 店铺信息
*/
private ImageView logo;
private TextView name, address, makerName;
private LinearLayout goMap, shopname, mapMarker;
private boolean isNearbyService, isScenic;
private Map<String, String> param;
private List<PoiItem> list;
private String shopaddress, lat, lng, shoptype;
private List<Marker> markerList;
private boolean iszoom;
private int zoom;
@Override
public void initParms(Bundle params) {
param = new HashMap<>();
markerList = new ArrayList<>();
isNearbyService = params.getBoolean("isNearbyService", false);
isScenic = params.getBoolean("isScenic", false);
if (isNearbyService) {
list = params.getParcelableArrayList("nearbyService");
} else {
if (!isScenic) {
param.put("shop_type", params.getString("shopType"));
shoptype = params.getString("shopType");
if (shoptype.equals("1"))
param.put("shop_type_labels", params.getString("shop_type_labels"));
}
param.put("distance_max", "15");
}
iszoom = false;
setSetStatusBar(true);
}
@Override
public View bindView() {
return null;
}
@Override
public int bindLayout() {
return R.layout.activity_shopmap;
}
@Override
public void initView(View view, Bundle savedInstanceState) {
mMapView = findViewById(R.id.shop_map);
back = findViewById(R.id.food_comment_back);
title = findViewById(R.id.food_comment_title_tv);
statusBar = findViewById(R.id.normal_fakeview);
title.setText("地图");
logo = findViewById(R.id.shopMap_logo);
name = findViewById(R.id.shopMap_shopName);
address = findViewById(R.id.shopMap_shopAddress);
goMap = findViewById(R.id.shopMap_go);
shopname = findViewById(R.id.shopMap_shopName_ll);
mMapView.onCreate(savedInstanceState);
mapMarker = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.map_marker, null);
makerName = mapMarker.findViewById(R.id.marker_shopName_tv);
if (aMap == null) {
aMap = mMapView.getMap();
}
aMap.moveCamera(CameraUpdateFactory.zoomTo(14));
zoom = 14;
}
@Override
public void setListener() {
aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
initMaker();
if (marker.getObject() instanceof PoiItem) {
PoiItem p = (PoiItem) marker.getObject();
if (p.getPhotos().size() > 0)
setShop(p.getPhotos().get(0).getUrl(), p.getTitle(), p.getSnippet(), p.getLatLonPoint().getLatitude() + "", p.getLatLonPoint().getLongitude() + "");
else
setShop("", p.getTitle(), p.getSnippet(), p.getLatLonPoint().getLatitude() + "", p.getLatLonPoint().getLongitude() + "");
changeMaker(marker,p.getTitle());
} else if (marker.getObject() instanceof BaseShopInfo) {
BaseShopInfo b = (BaseShopInfo) marker.getObject();
setShop(b.getShop_logo(), b.getShop_name(), b.getShop_address(), b.getShop_lat(), b.getShop_lng());
changeMaker(marker,b.getShop_name());
if (shoptype.equals("1")) {
jumpActivity(b.getShopid(), b.getShop_name(), b.getM_shop_type_labels(), null);
} else {
jumpActivity(b.getShopid(), b.getShop_name(), null, null);
}
} else if (marker.getObject() instanceof ScenicEntity) {
ScenicEntity s = (ScenicEntity) marker.getObject();
setShop(s.getDefault_image(), s.getGoods_name(), s.getGoods_address(), s.getGoods_lat(), s.getGoods_lng());
jumpActivity(s.getGoods_id(), s.getGoods_name(), null, s);
changeMaker(marker,s.getGoods_name());
}
return true;
}
});
aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition cameraPosition) {
}
@Override
public void onCameraChangeFinish(CameraPosition cameraPosition) {
zoom = (int) cameraPosition.zoom;
if (zoom >15) {
if (!iszoom) {
changeZoomMaker();
iszoom = true;
}
} else {
if (iszoom) {
for (int i = 0; i < markerList.size(); i++) {
markerList.get(i).setIcon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.marker_unselect)));
}
iszoom = false;
}
}
}
});
back.setOnClickListener(this);
goMap.setOnClickListener(this);
}
@Override
public void widgetClick(View v) {
int id = v.getId();
if (id == R.id.food_comment_back) {
finish();
} else if (id == R.id.shopMap_go) {
goMap();
}
}
public Bitmap convertViewToBitmap(View view) {
view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
return bitmap;
}
private void initMaker() {
if (zoom > 14) {
changeZoomMaker();
} else {
for (int i = 0; i < markerList.size(); i++) {
markerList.get(i).setIcon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.marker_unselect)));
}
}
}
private void changeMaker(Marker marker,String name) {
if (zoom > 14) {
makerName.setBackgroundResource(R.drawable.bubble);
makerName.setText(name);
marker.setIcon(BitmapDescriptorFactory.fromBitmap(convertViewToBitmap(makerName)));
} else {
marker.setIcon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.marker_select)));
}
}
private void changeZoomMaker(){
makerName.setBackgroundResource(R.drawable.bubble_gray);
for (int i = 0; i < markerList.size(); i++) {
if (markerList.get(i).getObject() instanceof PoiItem) {
PoiItem poiItem = (PoiItem) markerList.get(i).getObject();
makerName.setText(poiItem.getTitle());
} else if (markerList.get(i).getObject() instanceof BaseShopInfo) {
BaseShopInfo baseShopInfo = (BaseShopInfo) markerList.get(i).getObject();
makerName.setText(baseShopInfo.getShop_name());
} else if (markerList.get(i).getObject() instanceof ScenicEntity) {
ScenicEntity scenicEntity = (ScenicEntity) markerList.get(i).getObject();
makerName.setText(scenicEntity.getGoods_name());
}
markerList.get(i).setIcon(BitmapDescriptorFactory.fromBitmap(convertViewToBitmap(makerName)));
}
}
/**
* 跳转店铺详情
*
* @param shopID
* @param shopnames
* @param type_labels
* @param scenicEntity
*/
private void jumpActivity(String shopID, String shopnames, @Nullable final String type_labels, @Nullable final ScenicEntity scenicEntity) {
final Bundle bundle = new Bundle();
if (!isNearbyService) {
bundle.putString("shopid", shopID);
bundle.putString("shop_name", shopnames);
if (type_labels != null)
bundle.putString("m_shop_type_labels", type_labels);
shopname.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!isScenic) {
switch (shoptype) {
case "2"://酒店
startActivityRuntime("com.sinata.rwxchina.component_basic.hotel.activity.HotelActivity", bundle);
break;
case "3"://美食
startActivityRuntime("com.sinata.rwxchina.component_basic.finefood.activity.FoodActivity", bundle);
break;
case "4"://KTV
startActivityRuntime("com.sinata.rwxchina.component_basic.ktv.activity.KTVActivity", bundle);
break;
case "1"://汽车
startActivityRuntime("com.sinata.rwxchina.component_basic.car.activity.CleanCarActivity", bundle);
break;
case "6"://养生
startActivityRuntime("com.sinata.rwxchina.component_basic.regimen.activity.HealthActivity", bundle);
break;
}
} else {
bundle.putSerializable("scenic", scenicEntity);
startActivityRuntime("com.sinata.rwxchina.component_basic.scenic.activity.ScenicActivity", bundle);
}
}
});
}
}
/**
* 设置店铺信息
*/
private void setShop(String url, String shopName, String shopaddress, String lat, String lng) {
if (isNearbyService) {
ImageUtils.showImage(this, url, logo);
} else if (!isNearbyService) {
ImageUtils.showImage(this, HttpPath.IMAGEURL + url, logo);
}
name.setText(shopName);
address.setText(shopaddress);
this.shopaddress = shopaddress;
this.lat = lat;
this.lng = lng;
}
@Override
public void doBusiness(Context mContext) {
setTitleBarView();
setBlueLocation();
if (isNearbyService) {
for (int i = 0; i < list.size(); i++) {
showMarker(list.get(i).getLatLonPoint().getLatitude() + "", list.get(i).getLatLonPoint().getLongitude() + "", list.get(i).getTitle(), list.get(i).getSnippet(), list.get(i));
}
if (list.get(0).getPhotos().size() > 0)
setShop(list.get(0).getPhotos().get(0).getUrl(), list.get(0).getTitle(), list.get(0).getSnippet(), list.get(0).getLatLonPoint().getLatitude() + "", list.get(0).getLatLonPoint().getLongitude() + "");
else
setShop("", list.get(0).getTitle(), list.get(0).getSnippet(), list.get(0).getLatLonPoint().getLatitude() + "", list.get(0).getLatLonPoint().getLongitude() + "");
} else {
getShoplist();
}
}
/**
* 设置店铺Marker
*/
private void showMarker(String lat, String lng, String shopName, String address, Object o) {
//绘制marker
Marker marker = aMap.addMarker(new MarkerOptions()
.position(new LatLng(Double.parseDouble(lat), Double.parseDouble(lng)))
.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.marker_unselect)))
.draggable(false));
marker.setObject(o);
markerList.add(marker);
}
/**
* 获取店铺信息
*/
private void getShoplist() {
ApiManager api = new ApiManager(this, new StringCallBack() {
@Override
public void onResultNext(String result, String method, int code, String msg, PageInfo pageInfo) throws Exception {
if (isScenic) {//获取景区
List<ScenicEntity> list = new Gson().fromJson(result, new TypeToken<List<ScenicEntity>>() {
}.getType());
for (int i = 0; i < list.size(); i++) {
showMarker(list.get(i).getGoods_lat(), list.get(i).getGoods_lng(), list.get(i).getGoods_name(), list.get(i).getGoods_address(), list.get(i));
}
setShop(list.get(0).getDefault_image(), list.get(0).getGoods_name(), list.get(0).getGoods_address(), list.get(0).getGoods_lat(), list.get(0).getGoods_lng());
jumpActivity(list.get(0).getGoods_id(), list.get(0).getGoods_name(), null, list.get(0));
} else {//获取非景区店铺
List<BaseShopInfo> list = new Gson().fromJson(result, new TypeToken<List<BaseShopInfo>>() {
}.getType());
for (int i = 0; i < list.size(); i++) {
showMarker(list.get(i).getShop_lat(), list.get(i).getShop_lng(), list.get(i).getShop_name(), list.get(i).getShop_address(), list.get(i));
}
setShop(list.get(0).getShop_logo(), list.get(0).getShop_name(), list.get(0).getShop_address(), list.get(0).getShop_lat(), list.get(0).getShop_lng());
if (shoptype.equals("1")) {
jumpActivity(list.get(0).getShopid(), list.get(0).getShop_name(), list.get(0).getM_shop_type_labels(), null);
} else {
jumpActivity(list.get(0).getShopid(), list.get(0).getShop_name(), null, null);
}
}
}
@Override
public void onResultError(ApiException e, String method) {
}
});
if (isScenic)
api.get(HttpPath.GETSCENIC, param);
else
api.get(HttpPath.GETSHOPLIST, param);
}
/**
* 设置定位小蓝点
*/
private void setBlueLocation() {
MyLocationStyle myLocationStyle;
myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点,定位点依照设备方向旋转,并且会跟随设备移动。(1秒1次定位)如果不设置myLocationType,默认也会执行此种模式。
myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);//定位一次,且将视角移动到地图中心点。
aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点,false表示隐藏定位蓝点并不进行定位,默认是false。
}
private void goMap() {
new ActionSheetDialog(this)
.builder()
.setCancelable(false)
.setCanceledOnTouchOutside(false)
.addSheetItem("百度地图", ActionSheetDialog.SheetItemColor.Blue,
new ActionSheetDialog.OnSheetItemClickListener() {
@Override
public void onClick(int which) {
NativeUtils.invokingBD(BasicShopListMapActivity.this, shopaddress, LocationUtils.getCity(BasicShopListMapActivity.this));
}
})
.addSheetItem("高德地图", ActionSheetDialog.SheetItemColor.Blue,
new ActionSheetDialog.OnSheetItemClickListener() {
@Override
public void onClick(int which) {
NativeUtils.invokingGD(BasicShopListMapActivity.this, lat, lng);
}
}).show();
}
/**
* 设置标题栏
*/
private void setTitleBarView() {
ImmersionUtils.setListImmersion(getWindow(), this, statusBar);
}
@Override
public void steepStatusBar() {
super.steepStatusBar();
//状态栏透明
StatusBarUtil.setTranslucentForImageViewInFragment(BasicShopListMapActivity.this, null);
}
@Override
protected void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
@Override
protected void onResume() {
super.onResume();
mMapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mMapView.onPause();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mMapView.onSaveInstanceState(outState);
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi.d;
import com.tencent.mm.plugin.appbrand.jsapi.a;
import com.tencent.mm.plugin.appbrand.jsapi.c;
import com.tencent.mm.plugin.appbrand.l;
import com.tencent.mm.plugin.appbrand.page.p;
import org.json.JSONException;
import org.json.JSONObject;
public final class b extends a {
public static final int CTRL_INDEX = 70;
public static final String NAME = "hideKeyboard";
public final void a(p pVar, JSONObject jSONObject, int i) {
b(pVar, jSONObject, i);
}
public final void a(l lVar, JSONObject jSONObject, int i) {
b(lVar, jSONObject, i);
}
private void b(c cVar, JSONObject jSONObject, int i) {
Integer num = null;
try {
num = Integer.valueOf(jSONObject.getInt("inputId"));
} catch (JSONException e) {
}
com.tencent.mm.plugin.appbrand.r.c.runOnUiThread(new 1(this, cVar, num, i));
}
}
|
package com.ddt.serviceInter;
import java.util.List;
import com.ddt.bean.Userinfo;
//import Bean.UserInfo;
public interface UserServiceInter {
// 增加用户信息
public void addUser(Userinfo user);
// 查找全部用户信息
public List findAllUser();
//按条件id查找部分学生
// public Student findUserById(Student stu);
//修改用户信息
public void updateUser(Userinfo user);
//删除用户信息
public void deleteUser(Userinfo user);
//验证用户登陆信息
public boolean login(String username, String password, int identify);
}
|
/**
*
*/
package br.com.nozinho.ejb.dao.impl;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import org.apache.commons.collections.FastHashMap;
import br.com.nozinho.ejb.dao.GenericDAO;
/**
* @author AndreLA
*
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public abstract class DAOFactoryServiceImpl {
private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(DAOFactoryServiceImpl.class);
private static final String SUFIXE_NAME_SEVICE = "Service";
private static final String SUFIXE_NAME_DAO = "DAO";
private static final String PART_PACKAGE_PATH_SERVICE = ".ejb.service.";
private static final String PART_PACKAGE_PATH_DAO = ".dao.";
private static FastHashMap mapaDAO = new FastHashMap();
public abstract EntityManager getEntityManager();
public final GenericDAO getDAO(final Object serviceClass) {
return lookupDAO(getDAOName(serviceClass));
}
public GenericDAO getGenericDAO(Class classeEntidade) {
GenericDAO dao = instanciarDAO(GenericDAOImpl.class);
dao.setEntityClass(classeEntidade);
return dao;
}
/**
* Método que busca o nome do DAO.
*
* @param serviceObject
* @return {@link Class}
*/
private static Class getDAOName(final Object serviceObject) {
String nomeServico = serviceObject.getClass().getName();
Class classDAO = (Class) mapaDAO.get(nomeServico);
/*
* DAO não foi instânciado ainda
*/
if (classDAO == null) {
String classe = serviceObject.getClass().getName();
classe = classe.replace(PART_PACKAGE_PATH_SERVICE, PART_PACKAGE_PATH_DAO);
classe = classe.replace(SUFIXE_NAME_SEVICE, SUFIXE_NAME_DAO);
try {
classDAO = Class.forName(classe);
} catch (ClassNotFoundException e) {
LOG.error("Classe não encontrada para o serviço " + nomeServico, e);
}
mapaDAO.put(nomeServico, classDAO);
}
return classDAO;
}
private GenericDAO instanciarDAO(Class classeDAO) {
GenericDAO genericDAO = null;
genericDAO = (GenericDAO) ReflectionUtil.newInstance(classeDAO);
genericDAO.setEntityManager(getEntityManager());
return genericDAO;
}
private GenericDAO lookupDAO(Class classeDAO) {
GenericDAO genericDAO = null;
InitialContext ic;
try {
ic = new InitialContext();
//ic.unbind(classeDAO.getSimpleName() + "/local");
genericDAO = (GenericDAO) ic.lookup(classeDAO.getSimpleName() + "/local");
genericDAO.setEntityManager(getEntityManager());
} catch (NamingException e) {
return instanciarDAO(classeDAO);
}
return genericDAO;
}
}
|
package Pessoa;
import Exceptions.*;
public class CadastroPessoa {
private RepositorioPessoa repositorioPessoa;
public CadastroPessoa(RepositorioPessoaLista repositorioPessoa){
this.repositorioPessoa = repositorioPessoa;
}
public CadastroPessoa(RepositorioPessoaArray repositorioPessoa){
this.repositorioPessoa = repositorioPessoa;
}
public void inserirPessoa(Pessoa pessoa) throws PessoaJaExistenteException{
if (repositorioPessoa.procurar(pessoa) == false) {
repositorioPessoa.inserir(pessoa);
}
else {
throw new PessoaJaExistenteException();
}
}
public boolean procurarPessoa(Pessoa pessoa) {
return repositorioPessoa.procurar(pessoa);
}
public void atualizarPessoa(Pessoa novo) throws PessoaNaoEncontradaException{
if (repositorioPessoa.procurar(novo) == true) {
repositorioPessoa.atualizar(novo);
}
else {
throw new PessoaNaoEncontradaException();
}
}
public void removerPessoa(Pessoa pessoa) throws PessoaNaoEncontradaException{
if (repositorioPessoa.procurar(pessoa) == true) {
repositorioPessoa.remover(pessoa);
}
else {
throw new PessoaNaoEncontradaException();
}
}
}
|
package com.hanbit.gms.controller;
import com.hanbit.gms.constant.Butt;
import com.hanbit.gms.domain.ArticleBean;
import com.hanbit.gms.service.ArticleService;
import com.hanbit.gms.service.ArticleServiceImpl;
import oracle.net.ano.Service;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class BoardController {
public static void main(String[] args) {
Butt[] buttons = {Butt.EXIT,Butt.ADD,Butt.LIST,Butt.FIND_ID,Butt.FIND_SEQ,Butt.COUNT,Butt.UPDATE,Butt.DEL};
ArticleBean bean = new ArticleBean();
List<ArticleBean> list = new ArrayList<>();
do{
flag:
switch((Butt)JOptionPane.showInputDialog(null, "MEMBER ADMIN","SELECT MENU", JOptionPane.QUESTION_MESSAGE,null, buttons,buttons[1])) {
case EXIT:
return;
case ADD:
String[] arr = (JOptionPane.showInputDialog("id/글제목/내용")).split("/");
bean.setId(arr[0]);
bean.setTitle(arr[1]);
bean.setContent(arr[2]);
JOptionPane.showMessageDialog(null, ArticleServiceImpl.getInstance().write(bean));
break flag;
case COUNT:
JOptionPane.showMessageDialog(null, ArticleServiceImpl.getInstance().count());
break flag;
case LIST:
JOptionPane.showMessageDialog(null, ArticleServiceImpl.getInstance().list());
break flag;
case FIND_ID:
JOptionPane.showMessageDialog(null, ArticleServiceImpl.getInstance().findById(JOptionPane.showInputDialog("작성자 ID를 입력하세요.")));
break flag;
case FIND_SEQ:
JOptionPane.showMessageDialog(null, ArticleServiceImpl.getInstance().findBySeq(Integer.parseInt(JOptionPane.showInputDialog("작성글 번호를 입력하세요."))));
break flag;
case UPDATE:
bean.setArticleSeq(Integer.parseInt(JOptionPane.showInputDialog("글번호를 입력하세요")));
bean.setTitle(JOptionPane.showInputDialog("제목을 입력하세요"));
bean.setContent(JOptionPane.showInputDialog("수정내용을 입력하세요"));
JOptionPane.showMessageDialog(null, ArticleServiceImpl.getInstance().modify(bean));
break flag;
case DEL:
ArticleServiceImpl.getInstance().remove(Integer.parseInt(JOptionPane.showInputDialog("삭제할 게시글 번호를 입력하세요.")));
JOptionPane.showMessageDialog(null, "삭제완료");
break flag;
}
}while(true);
}
}
|
package mg.egg.eggc.compiler.libegg.mig;
import mg.egg.eggc.compiler.libegg.base.TERMINAL;
import mg.egg.eggc.runtime.libjava.EGGException;
public class TMig {
private TERMINAL terminal;
public String getNom() {
return terminal.getNom();
}
private StringBuffer entete;
public StringBuffer getEntete() {
return entete;
}
public void setEntete() {
entete = new StringBuffer();
String comm = terminal.getComm();
if (comm != null)
entete.append(terminal.getComm() + '\n');
switch (terminal.getType()) {
case TERMINAL.SPACE:
entete.append("space " + terminal.getNom() + " is \""
+ terminal.get_expreg() + "\"");
break;
case TERMINAL.SUGAR:
entete.append("sugar " + terminal.getNom() + " is \""
+ terminal.get_expreg() + "\"");
break;
case TERMINAL.TERM:
entete.append("term " + terminal.getNom() + " is \""
+ terminal.get_expreg() + "\"");
break;
case TERMINAL.MACRO:
entete.append("macro " + terminal.getNom() + " is \""
+ terminal.get_expreg() + "\"");
break;
case TERMINAL.COMM:
entete.append("comment " + terminal.getNom() + " is \""
+ terminal.get_expreg() + "\"");
break;
}
if (terminal.getNames().size() != 0) {
boolean premier = true;
entete.append("\taka\t");
for (String a : terminal.getNames()) {
if (premier) {
premier = false;
} else {
entete.append(", ");
}
entete.append("$" + a + "$");
}
}
entete.append(";\n");
}
public TMig(TERMINAL t) {
terminal = t;
}
public String finaliser() throws EGGException {
return entete.toString();
}
}
|
package org.study.design_patterns.factory.solution;
/**
* Created by iovchynnikov on 7/27/2015.
*/
public class Product2 extends Product implements ProductInterface {
@Override
public String getTitle() {
return "This is product2";
}
}
|
package edu.iit.cs445.StateParking.REST;
import java.util.*;
import edu.iit.cs445.StateParking.Objects.*;
import edu.iit.cs445.StateParking.ObjectsEnum.*;
public class ParkPresenterWithGeo {
public String pid;
public location_info location_info;
public HashMap<String, ArrayList<Double>> payment_info;
public ParkPresenterWithGeo(ParkBoundaryInterface park) {
this.pid = Integer.toString(park.getPid());
this.location_info = new location_info(park);
this.payment_info = setPayment(park);
}
private HashMap<String, ArrayList<Double>> setPayment(ParkBoundaryInterface park) {
HashMap<VehicleType, ArrayList<Double>> P = park.getAdmFee();
HashMap<String, ArrayList<Double>> result = new HashMap<String, ArrayList<Double>>();
Iterator<VehicleType> it = P.keySet().iterator();
String type;
ArrayList<Double> price;
while(it.hasNext()) {
VehicleType a = it.next();
price = P.get(a);
type = a.toString();
result.put(type, price);
}
return result;
}
public class location_info{
public String name;
public String address;
public String phone;
public String web;
public String region;
public geo geo;
public location_info(ParkBoundaryInterface park) {
this.name = park.getName();
String ad = park.getAddress().getStreet()+","+
park.getAddress().getCity()+", "+park.getAddress().getState().toString()+
" "+park.getAddress().getZipcode();
this.address = ad;
this.phone = park.getPhone();
this.web = park.getWeb();
this.geo = park.getGeo();
this.region = park.getRegion();
}
}
}
|
/*
* Copyright (c) 2012-2019 Snowflake Computing Inc. All rights reserved.
*/
package net.snowflake.client.core;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import net.snowflake.client.category.TestCategoryArrow;
import net.snowflake.client.jdbc.ArrowResultChunk;
import net.snowflake.client.jdbc.ErrorCode;
import net.snowflake.client.jdbc.SnowflakeResultChunk;
import net.snowflake.client.jdbc.SnowflakeResultSetSerializableV1;
import net.snowflake.client.jdbc.SnowflakeSQLException;
import net.snowflake.client.jdbc.telemetry.NoOpTelemetryClient;
import org.apache.arrow.memory.BufferAllocator;
import org.apache.arrow.memory.RootAllocator;
import org.apache.arrow.vector.FieldVector;
import org.apache.arrow.vector.IntVector;
import org.apache.arrow.vector.VectorSchemaRoot;
import org.apache.arrow.vector.dictionary.DictionaryProvider;
import org.apache.arrow.vector.ipc.ArrowStreamWriter;
import org.apache.arrow.vector.ipc.ArrowWriter;
import org.apache.arrow.vector.types.Types;
import org.apache.arrow.vector.types.pojo.Field;
import org.apache.arrow.vector.types.pojo.FieldType;
import org.apache.arrow.vector.types.pojo.Schema;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TemporaryFolder;
@Category(TestCategoryArrow.class)
public class SFArrowResultSetIT {
private Random random = new Random();
/** allocator for arrow */
private BufferAllocator allocator = new RootAllocator(Long.MAX_VALUE);
/** temporary folder to store result files */
@Rule public TemporaryFolder resultFolder = new TemporaryFolder();
/** Test the case that all results are returned in first chunk */
@Test
public void testNoOfflineData() throws Throwable {
List<Field> fieldList = new ArrayList<>();
Map<String, String> customFieldMeta = new HashMap<>();
customFieldMeta.put("logicalType", "FIXED");
customFieldMeta.put("scale", "0");
FieldType type = new FieldType(false, Types.MinorType.INT.getType(), null, customFieldMeta);
fieldList.add(new Field("", type, null));
Schema schema = new Schema(fieldList);
Object[][] data = generateData(schema, 1000);
File file = createArrowFile("testNoOfflineData_0_0_0", schema, data, 10);
int dataSize = (int) file.length();
byte[] dataBytes = new byte[dataSize];
InputStream is = new FileInputStream(file);
is.read(dataBytes, 0, dataSize);
SnowflakeResultSetSerializableV1 resultSetSerializable = new SnowflakeResultSetSerializableV1();
resultSetSerializable.setRootAllocator(new RootAllocator(Long.MAX_VALUE));
resultSetSerializable.setFristChunkStringData(Base64.getEncoder().encodeToString(dataBytes));
resultSetSerializable.setChunkFileCount(0);
SFArrowResultSet resultSet =
new SFArrowResultSet(resultSetSerializable, new NoOpTelemetryClient(), false);
int i = 0;
while (resultSet.next()) {
int val = resultSet.getInt(1);
assertThat(val, equalTo(data[0][i]));
i++;
}
// assert that total rowcount is 1000
assertThat(i, is(1000));
}
@Test
public void testEmptyResultSet() throws Throwable {
SnowflakeResultSetSerializableV1 resultSetSerializable = new SnowflakeResultSetSerializableV1();
resultSetSerializable.setFristChunkStringData(
Base64.getEncoder().encodeToString("".getBytes(StandardCharsets.UTF_8)));
resultSetSerializable.setChunkFileCount(0);
SFArrowResultSet resultSet =
new SFArrowResultSet(resultSetSerializable, new NoOpTelemetryClient(), false);
assertThat(resultSet.next(), is(false));
assertThat(resultSet.isLast(), is(false));
assertThat(resultSet.isAfterLast(), is(true));
resultSetSerializable.setFristChunkStringData(null);
resultSet = new SFArrowResultSet(resultSetSerializable, new NoOpTelemetryClient(), false);
assertThat(resultSet.next(), is(false));
assertThat(resultSet.isLast(), is(false));
assertThat(resultSet.isAfterLast(), is(true));
}
/** Testing the case that all data comes from chunk downloader */
@Test
public void testOnlyOfflineData() throws Throwable {
final int colCount = 2;
final int chunkCount = 10;
// generate data
List<Field> fieldList = new ArrayList<>();
Map<String, String> customFieldMeta = new HashMap<>();
customFieldMeta.put("logicalType", "FIXED");
customFieldMeta.put("scale", "0");
FieldType type = new FieldType(false, Types.MinorType.INT.getType(), null, customFieldMeta);
for (int i = 0; i < colCount; i++) {
fieldList.add(new Field("col_" + i, type, null));
}
Schema schema = new Schema(fieldList);
// genreate 10 chunk of data
List<Object[][]> dataLists = new ArrayList<>();
List<File> fileLists = new ArrayList<>();
for (int i = 0; i < chunkCount; i++) {
Object[][] data = generateData(schema, 500);
File file = createArrowFile("testOnlyOfflineData_" + i, schema, data, 10);
dataLists.add(data);
fileLists.add(file);
}
SnowflakeResultSetSerializableV1 resultSetSerializable = new SnowflakeResultSetSerializableV1();
resultSetSerializable.setChunkDownloader(new MockChunkDownloader(fileLists));
resultSetSerializable.setChunkFileCount(chunkCount);
SFArrowResultSet resultSet =
new SFArrowResultSet(resultSetSerializable, new NoOpTelemetryClient(), false);
int index = 0;
while (resultSet.next()) {
for (int i = 0; i < colCount; i++) {
int val = resultSet.getInt(i + 1);
Integer expectedVal = (Integer) dataLists.get(index / 500)[i][index % 500];
assertThat(val, is(expectedVal));
}
index++;
}
// assert that total rowcount is 5000
assertThat(index, is(5000));
}
/** Testing the case that all data comes from chunk downloader */
@Test
public void testFirstResponseAndOfflineData() throws Throwable {
final int colCount = 2;
final int chunkCount = 10;
// generate data
List<Field> fieldList = new ArrayList<>();
Map<String, String> customFieldMeta = new HashMap<>();
customFieldMeta.put("logicalType", "FIXED");
customFieldMeta.put("scale", "0");
FieldType type = new FieldType(false, Types.MinorType.INT.getType(), null, customFieldMeta);
for (int i = 0; i < colCount; i++) {
fieldList.add(new Field("col_" + i, type, null));
}
Schema schema = new Schema(fieldList);
// genreate 10 chunk of data
List<Object[][]> dataLists = new ArrayList<>();
List<File> fileLists = new ArrayList<>();
// first chunk set to base64 rowset
Object[][] firstChunkData = generateData(schema, 500);
File arrowFile = createArrowFile("testOnlyOfflineData_0", schema, firstChunkData, 10);
dataLists.add(firstChunkData);
int dataSize = (int) arrowFile.length();
byte[] dataBytes = new byte[dataSize];
InputStream is = new FileInputStream(arrowFile);
is.read(dataBytes, 0, dataSize);
SnowflakeResultSetSerializableV1 resultSetSerializable = new SnowflakeResultSetSerializableV1();
resultSetSerializable.setFristChunkStringData(Base64.getEncoder().encodeToString(dataBytes));
resultSetSerializable.setChunkFileCount(chunkCount);
resultSetSerializable.setRootAllocator(new RootAllocator(Long.MAX_VALUE));
// build chunk downloader
for (int i = 0; i < chunkCount; i++) {
Object[][] data = generateData(schema, 500);
File file = createArrowFile("testOnlyOfflineData_" + (i + 1), schema, data, 10);
dataLists.add(data);
fileLists.add(file);
}
resultSetSerializable.setChunkDownloader(new MockChunkDownloader(fileLists));
SFArrowResultSet resultSet =
new SFArrowResultSet(resultSetSerializable, new NoOpTelemetryClient(), false);
int index = 0;
while (resultSet.next()) {
for (int i = 0; i < colCount; i++) {
int val = resultSet.getInt(i + 1);
Integer expectedVal = (Integer) dataLists.get(index / 500)[i][index % 500];
assertThat(val, is(expectedVal));
}
index++;
}
// assert that total rowcount is 5500
assertThat(index, is(5500));
}
/** Class to mock chunk downloader. It is just reading data from tmp directory one by one */
private class MockChunkDownloader implements ChunkDownloader {
private List<File> resultFileNames;
private int currentFileIndex;
private RootAllocator rootAllocator = new RootAllocator(Long.MAX_VALUE);
MockChunkDownloader(List<File> resultFileNames) {
this.resultFileNames = resultFileNames;
this.currentFileIndex = 0;
}
@Override
public SnowflakeResultChunk getNextChunkToConsume() throws SnowflakeSQLException {
if (currentFileIndex < resultFileNames.size()) {
ArrowResultChunk resultChunk = new ArrowResultChunk("", 0, 0, 0, rootAllocator, null);
try {
InputStream is = new FileInputStream(resultFileNames.get(currentFileIndex));
resultChunk.readArrowStream(is);
currentFileIndex++;
return resultChunk;
} catch (IOException e) {
throw new SnowflakeSQLException(ErrorCode.INTERNAL_ERROR, "Failed " + "to read data");
}
} else {
return null;
}
}
@Override
public DownloaderMetrics terminate() {
return null;
}
}
private Object[][] generateData(Schema schema, int rowCount) {
Object[][] data = new Object[schema.getFields().size()][rowCount];
for (int i = 0; i < schema.getFields().size(); i++) {
Types.MinorType type = Types.getMinorTypeForArrowType(schema.getFields().get(i).getType());
switch (type) {
case INT:
{
for (int j = 0; j < rowCount; j++) {
data[i][j] = random.nextInt();
}
break;
}
// add other data types as needed later
}
}
return data;
}
private File createArrowFile(
String fileName, Schema schema, Object[][] data, int rowsPerRecordBatch) throws IOException {
File file = resultFolder.newFile(fileName);
VectorSchemaRoot root = VectorSchemaRoot.create(schema, allocator);
try (ArrowWriter writer =
new ArrowStreamWriter(
root, new DictionaryProvider.MapDictionaryProvider(), new FileOutputStream(file))) {
writer.start();
for (int i = 0; i < data[0].length; ) {
int rowsToAppend = Math.min(rowsPerRecordBatch, data[0].length - i);
root.setRowCount(rowsToAppend);
for (int j = 0; j < data.length; j++) {
FieldVector vector = root.getFieldVectors().get(j);
switch (vector.getMinorType()) {
case INT:
writeIntToField(vector, data[j], i, rowsToAppend);
break;
}
}
writer.writeBatch();
i += rowsToAppend;
}
}
return file;
}
private void writeIntToField(
FieldVector fieldVector, Object[] data, int startIndex, int rowsToAppend) {
IntVector intVector = (IntVector) fieldVector;
intVector.setInitialCapacity(rowsToAppend);
intVector.allocateNew();
for (int i = 0; i < rowsToAppend; i++) {
intVector.setSafe(i, 1, (int) data[startIndex + i]);
}
// how many are set
fieldVector.setValueCount(rowsToAppend);
}
}
|
package com.tencent.mm.plugin.chatroom.ui;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import com.tencent.mm.R;
import com.tencent.mm.model.au;
import com.tencent.mm.plugin.chatroom.d.d;
import com.tencent.mm.plugin.chatroom.d.k;
import com.tencent.mm.ui.base.h;
import java.util.ArrayList;
import java.util.List;
class ChatroomInfoUI$21 implements OnClickListener {
final /* synthetic */ ChatroomInfoUI hLX;
final /* synthetic */ d hMd;
final /* synthetic */ List hMe;
final /* synthetic */ List hMf;
final /* synthetic */ List hMg;
ChatroomInfoUI$21(ChatroomInfoUI chatroomInfoUI, d dVar, List list, List list2, List list3) {
this.hLX = chatroomInfoUI;
this.hMd = dVar;
this.hMe = list;
this.hMf = list2;
this.hMg = list3;
}
public final void onClick(DialogInterface dialogInterface, int i) {
ChatroomInfoUI.a(this.hLX, this.hMd.chatroomName, this.hMe);
List arrayList = new ArrayList();
arrayList.addAll(this.hMf);
arrayList.addAll(this.hMg);
k kVar = new k(ChatroomInfoUI.b(this.hLX), arrayList);
au.DF().a(kVar, 0);
ChatroomInfoUI chatroomInfoUI = this.hLX;
ChatroomInfoUI chatroomInfoUI2 = this.hLX;
this.hLX.getString(R.l.app_tip);
ChatroomInfoUI.b(chatroomInfoUI, h.a(chatroomInfoUI2, this.hLX.getString(R.l.room_invite_member), true, new 1(this, kVar)));
}
}
|
/* 1: */ package com.kaldin.questionbank.technology.dto;
/* 2: */
/* 3: */ public class CompTechInfoDTO
/* 4: */ {
/* 5: */ private int ctechId;
/* 6: */ private String technology;
/* 7: */ private int companyId;
/* 8: */
/* 9: */ public int getCtechId()
/* 10: */ {
/* 11: 9 */ return this.ctechId;
/* 12: */ }
/* 13: */
/* 14: */ public void setCtechId(int ctechId)
/* 15: */ {
/* 16:13 */ this.ctechId = ctechId;
/* 17: */ }
/* 18: */
/* 19: */ public String getTechnology()
/* 20: */ {
/* 21:17 */ return this.technology;
/* 22: */ }
/* 23: */
/* 24: */ public void setTechnology(String technology)
/* 25: */ {
/* 26:21 */ this.technology = technology;
/* 27: */ }
/* 28: */
/* 29: */ public int getCompanyId()
/* 30: */ {
/* 31:25 */ return this.companyId;
/* 32: */ }
/* 33: */
/* 34: */ public void setCompanyId(int companyId)
/* 35: */ {
/* 36:29 */ this.companyId = companyId;
/* 37: */ }
/* 38: */ }
/* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip
* Qualified Name: kaldin.questionbank.technology.dto.CompTechInfoDTO
* JD-Core Version: 0.7.0.1
*/
|
package capitulo07;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class DrawSpiral extends JPanel {
public void paintComponent(Graphics g) {
int x = getSize().width / 2 - 10;
int y = getSize().height/ 2 - 10;
int width = 20;
int height = 20;
int startAngle = 0;
int arcAngle = 180;
int depth = 7;
for (int i = 0; i < 30; i++) {
if (i % 2 == 0) {
// g.drawArc(x + 10, y + 10, width, height, startAngle + 10, -arcAngle);
// x = x - 5;
y = y - depth;
width = width + 2 * depth;
height = height + 2 * depth;
g.drawArc(x, y, width, height, startAngle, -arcAngle);
} else {
// g.drawArc(x + 10, y + 10, width, height, startAngle + 10, arcAngle);
x = x - 2 * depth;
y = y - depth;
width = width + 2 * depth;
height = height + 2 * depth;
g.drawArc(x, y, width, height, startAngle, arcAngle);
}
}
}
}
|
package com.jlgproject.activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import com.jlgproject.R;
import com.jlgproject.base.BaseActivity;
import com.jlgproject.util.ScreenUtil;
public class TwoCodeDialogActivity extends BaseActivity {
private ImageView iv_close;
@Override
protected void onCreate(Bundle savedInstanceState) {
// 去除Activity的标题栏
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
}
@Override
public int loadWindowLayout() {
return R.layout.activity_two_code_dialog;
}
@Override
public void initViews() {
dialogActivityInit();
iv_close= (ImageView) findViewById(R.id.iv_close);
iv_close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
/**
* ActivityDialog 初始化配置
*/
public void dialogActivityInit() {
WindowManager windowManager = getWindowManager();
// 获取对话框当前的参数值
WindowManager.LayoutParams p = getWindow().getAttributes();
// 宽度设置为屏幕的1
p.width = (int) (ScreenUtil.getScreenWidth(TwoCodeDialogActivity.this) * 0.9);
// 设置透明度,0.0为完全透明,1.0为完全不透明
p.alpha = 0.95f;
p.height=(int) (ScreenUtil.getScreenHeight(TwoCodeDialogActivity.this) * 0.9);
// 设置布局参数
getWindow().setAttributes(p);
// 设置点击弹框外部不可消失
setFinishOnTouchOutside(false);
}
}
|
package org.dkni.experimental.dao;
import org.dkni.experimental.domain.City;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import java.util.List;
/**
* Created by DK on 08.01.2016.
*/
@Repository("cityDao")
public class CityDaoImpl implements CityDao {
@PersistenceContext
private EntityManager em;
@Transactional
public void addCity(City city) {
em.persist(city);
}
public City getCityById(Long id) {
return em.find(City.class, id);
}
public List<City> getAllCities() {
return em.createQuery("from city", City.class).getResultList();
}
}
|
package com.rishi.baldawa.iq;
import java.util.function.BinaryOperator;
/*
Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100),
return 964176192 (represented in binary as 00111001011110000010100101000000).
Follow up:
If this function is called many times, how would you optimize it?
*/
public class ReverseBinaryBits {
public int reverseBits(int n) {
StringBuilder builder = new StringBuilder()
.append(Integer.toBinaryString(n))
.reverse();
int remainder = 32 - builder.length();
while (remainder > 0) {
builder.append('0');
remainder -= 1;
}
return Long.valueOf(builder.toString(), 2).intValue();
}
public int reverseBitsViaBinaryOperators(int n) {
int reverse = 0;
for(int i = 0; i < 32; i ++) {
reverse = (reverse << 1) | (n & 1);
n >>= 1;
}
return reverse;
}
}
|
package com.example.study.broadcast;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import com.example.study.R;
public class BroadcastIndexActivity extends AppCompatActivity implements View.OnClickListener {
private IntentFilter intentFilter;
private LocalBroadcastReceiver localBroadcastReceiver;
private LocalBroadcastManager localBroadcastManager;
public static void startAction(Context context) {
context.startActivity(new Intent(context, BroadcastIndexActivity.class));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_broadcast_index);
findViewById(R.id.btn_dynamic_broadcast).setOnClickListener(this);
findViewById(R.id.btn_standard_broadcast).setOnClickListener(this);
findViewById(R.id.btn_ordered_broadcast).setOnClickListener(this);
findViewById(R.id.btn_local_broadcast).setOnClickListener(this);
this.intentFilter = new IntentFilter();
this.intentFilter.addAction("com.example.broadcast.MY_LOCAL_BROADCAST");
this.localBroadcastManager = LocalBroadcastManager.getInstance(this);
this.localBroadcastReceiver = new LocalBroadcastReceiver();
this.localBroadcastManager.registerReceiver(this.localBroadcastReceiver, this.intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
this.localBroadcastManager.unregisterReceiver(this.localBroadcastReceiver);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_dynamic_broadcast:
BroadcastDynamicSystemActivity.startAction(this);
break;
case R.id.btn_standard_broadcast:
sendBroadcast(new Intent("com.example.broadcast.MY_BROADCAST"));
break;
case R.id.btn_ordered_broadcast:
sendOrderedBroadcast(new Intent("com.example.broadcast.MY_BROADCAST"), null);
break;
case R.id.btn_local_broadcast:
this.localBroadcastManager.sendBroadcast(new Intent("com.example.broadcast.MY_LOCAL_BROADCAST"));
break;
default:
break;
}
}
}
|
package com.redbus.pages;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class HomePage {
// ---------------Page Factory--------------------
// To navigate the rcarebus page
@FindBy(how = How.XPATH, using = "//span[contains(text(),'redBus Cares')]")
public WebElement rbus_cares;
// To select the amount for donation
@FindBy(how = How.XPATH, using = "//span[contains(text(),'2000')]")
public WebElement donate;
// Mode of donation
@FindBy(how = How.XPATH, using = "//body[1]/div[1]/div[1]/div[2]/div[2]/div[6]/ul[1]/li[2]/span[1]/ul[1]/li[1]/span[1]")
public WebElement modeofdonation;
// click donate button
@FindBy(how = How.CLASS_NAME, using = "donateBtn")
public WebElement donateButton;
// To enter the phone number
@FindBy(how = How.ID, using = "smsTXTBOX")
public WebElement sms;
// To get the error_msg
@FindBy(how = How.XPATH, using = "//span[contains(text(),'Invalid Mobile No')]")
public WebElement error_msg;
// To click on send link button
@FindBy(how = How.ID, using = "sendLinkButton")
public WebElement sendLink;
// To get the error_msg
@FindBy(how = How.XPATH, using = "//*[@id=\"phoneWrapper\"]/div[1]/span")
public WebElement error_msg2;
// To donate the custom amount
@FindBy(how = How.ID, using = "otherAmount")
public WebElement customAmount;
// To select the mode of Payment
@FindBy(how = How.XPATH, using = "//div[contains(text(),'Net Banking')]")
public WebElement paymentmode;
// To verify the nextpage after donationclick
@FindBy(how = How.XPATH, using = "//div[contains(text(),'Select a payment option')]")
public WebElement PaymentOption;
// To selects the Bank
@FindBy(how = How.XPATH, using = "//*[@id=\"reactContentMount\"]/div/div[2]/div[2]/div[3]/div[3]/div[2]/div/div[1]/div[4]/div")
public WebElement selectbank;
// To click on PayNow button
@FindBy(how = How.XPATH, using = "//button[contains(text(),'PAY NOW')]")
public WebElement payNow;
// initializing constructor
WebDriver driver;
public HomePage(WebDriver driver) {
PageFactory.initElements(driver, this);
this.driver = driver;
}
// ---------------------PAGE ACTIONS-------------------------
// To navigate the rcarebus page
public void click_rbus_care() {
rbus_cares.click();
}
// To select the amount for donation
public void click_donateAmount() {
new WebDriverWait(driver, 30).ignoring(StaleElementReferenceException.class)
.until(ExpectedConditions.elementToBeClickable(donate));
donate.click();
}
// Mode of donation
public void modeofdonation_anonymously() {
new WebDriverWait(driver, 30).ignoring(StaleElementReferenceException.class)
.until(ExpectedConditions.elementToBeClickable(modeofdonation));
modeofdonation.click();
}
// click donate button
public void click_donatebtn() {
new WebDriverWait(driver, 30).ignoring(StaleElementReferenceException.class)
.until(ExpectedConditions.elementToBeClickable(donateButton));
donateButton.click();
}
// To enter the phone number
public void enter_ph(String phone) {
new WebDriverWait(driver, 30).ignoring(StaleElementReferenceException.class)
.until(ExpectedConditions.elementToBeClickable(sms));
sms.sendKeys(phone);
}
// To click on send button
public void click_sendLinkbtn() {
sendLink.click();
}
// To get the error_msg
public String get_error_msg() {
new WebDriverWait(driver, 30).ignoring(StaleElementReferenceException.class)
.until(ExpectedConditions.elementToBeClickable(error_msg));
return error_msg.getText();
}
// To get the error_msg
public String get_error_msg2() {
new WebDriverWait(driver, 30).ignoring(StaleElementReferenceException.class)
.until(ExpectedConditions.elementToBeClickable(error_msg2));
return error_msg2.getText();
}
// To donate the custom amount
public void otherAmount(String amount) {
new WebDriverWait(driver, 30).ignoring(StaleElementReferenceException.class)
.until(ExpectedConditions.elementToBeClickable(customAmount));
customAmount.sendKeys(amount);
}
// To select the mode of Payment
public void Select_paymentMode() {
new WebDriverWait(driver, 30).ignoring(StaleElementReferenceException.class)
.until(ExpectedConditions.elementToBeClickable(paymentmode)).click();
}
// To verify the nextpage after donationclick
public String get_PaymentOption() {
new WebDriverWait(driver, 30).ignoring(StaleElementReferenceException.class)
.until(ExpectedConditions.elementToBeClickable(PaymentOption));
return PaymentOption.getText();
}
// To selects the Bank
public void Select_bank() {
new WebDriverWait(driver, 30).ignoring(StaleElementReferenceException.class)
.until(ExpectedConditions.elementToBeClickable(selectbank)).click();
}
// To click on PayNow Button
public void click_paynow() {
new WebDriverWait(driver, 30).ignoring(StaleElementReferenceException.class)
.until(ExpectedConditions.elementToBeClickable(payNow)).click();
}
}
|
package bootcamp.selenium.intermediate;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import bootcamp.selenium.basic.LaunchBrowser;
public class ClickWithJS {
public static void main(String[] args) {
WebDriver driver = LaunchBrowser.launch("https://demoqa.com/buttons");
WebElement ele = driver.findElement(By.xpath(".//button[text()='Click Me']"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", ele);
}
}
|
package com.appdear.client.commctrls;
interface ListViewChangedCallback {
public void onChanged();
}
|
package a.b.c;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.DialogInterface;
import android.media.MediaPlayer;
//import android.content.Intent;
//import a.b.c.R;
import android.os.Bundle;
import android.os.Environment;
import android.text.Html;
import android.text.InputType;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
public class Splash extends Activity{
// @Override
//ImageButton smsNews, smsTut; // bnt --> button for news text, bna --> button for news audio
TextView newsBtn1, newsBtn2, tutBtn1, tutBtn2;
TextView txt;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
// txt = (TextView)findViewById(R.id.textView2);
// Intent getIndent = new Intent();
// go.getExtras("Date");
// go.getExtra
String date = null,state = null;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
date= null;
state = null;
} else {
date= extras.getString("Date");
state = extras.getString("State");
}
} else {
date = (String) savedInstanceState.getSerializable("STRING_I_NEED");
state = (String) savedInstanceState.getSerializable("STRING_I_NEED");
}
// TextView textView =(TextView)findViewById(R.id.textView);
// textView.setClickable(true);
// textView.setMovementMethod(LinkMovementMethod.getInstance());
// String text = "<a href='http://www.google.com'> Google </a>";
// textView.setText(Html.fromHtml(text));
// txt = (TextView)findViewById(R.id.textView1);
// txt.setClickable(true);
// txt.setMovementMethod(LinkMovementMethod.getInstance());
// String link = "<a href='https://drive.google.com/uc?export=download&id=0B0cs60cMbG4xci1LQ3pMUTJCVW8'>Download Link</a>";
// txt.setText(Html.fromHtml(link));
// MediaPlayer mp = new MediaPlayer();
newsBtn1 = (TextView) findViewById(R.id.newsBtn1);
newsBtn2 = (TextView) findViewById(R.id.newsBtn2);
tutBtn1 = (TextView) findViewById(R.id.tutBtn1);
tutBtn2 = (TextView) findViewById(R.id.tutBtn2);
newsBtn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// String url = "https://drive.google.com/uc?export=download&id=0B3WMDQhlZL_7ZUxjeGg3TjE1SUE";
newsBtn1.setClickable(true);
newsBtn1.setMovementMethod(LinkMovementMethod.getInstance());
String text = "<a href='https://drive.google.com/uc?export=download&id=0B3WMDQhlZL_7ZUxjeGg3TjE1SUE'> Audio News </a>";
newsBtn1.setText(Html.fromHtml(text));
// TextView textView =(TextView)findViewById(R.id.newsBtn1);
// textView.setClickable(true);
// textView.setMovementMethod(LinkMovementMethod.getInstance());
}
});
newsBtn2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
newsBtn2.setClickable(true);
newsBtn2.setMovementMethod(LinkMovementMethod.getInstance());
// TODO Auto-generated method stub
// String url = "https://drive.google.com/uc?export=download&id=0B3WMDQhlZL_7c0ZOWkJhOTlKdFk";
String text = "<a href='https://drive.google.com/uc?export=download&id=0B3WMDQhlZL_7c0ZOWkJhOTlKdFk'> PDF News </a>";
newsBtn2.setText(Html.fromHtml(text));
}
});
tutBtn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
tutBtn1.setClickable(true);
tutBtn1.setMovementMethod(LinkMovementMethod.getInstance());
// TODO Auto-generated method stub
// String url = "https://drive.google.com/uc?export=download&id=0B3WMDQhlZL_7WmtBMWpUeHBTaE0";
String text = "<a href='https://drive.google.com/uc?export=download&id=0B3WMDQhlZL_7WmtBMWpUeHBTaE0'> Audio Tutorial </a>";
tutBtn1.setText(Html.fromHtml(text));
}
});
tutBtn2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
tutBtn2.setClickable(true);
tutBtn2.setMovementMethod(LinkMovementMethod.getInstance());
// TODO Auto-generated method stub
// String url = "https://drive.google.com/uc?export=download&id=0B3WMDQhlZL_7aUxFaExTR24teE0";
String text = "<a href='https://drive.google.com/uc?export=download&id=0B3WMDQhlZL_7aUxFaExTR24teE0'> PDF Tutorial </a>";
tutBtn2.setText(Html.fromHtml(text));
}
});
}
}
|
package com.rockwellcollins.atc.limp.translate.basicblocks.limp;
import java.util.LinkedHashMap;
import java.util.Map;
import jkind.lustre.Equation;
import com.rockwellcollins.atc.limp.Statement;
import com.rockwellcollins.atc.limp.translate.basicblocks.lustre.ExtendedEquation;
import com.rockwellcollins.atc.limp.translate.basicblocks.lustre.LustreBasicBlock;
import com.rockwellcollins.atc.limp.translate.basicblocks.lustre.LustreBlockEdge;
import com.rockwellcollins.atc.limp.translate.lustre.limp2lustre.LimpExprToLustreExpr;
import com.rockwellcollins.atc.limp.translate.lustre.limp2lustre.LimpStatementToLustreEquation;
import com.rockwellcollins.atc.limp.translate.lustre.limp2lustre.LocalProcedureToLustre;
/**
* TranslateBasicBlocks
*
* This translates a linked list of Limp BasicBlocks and returns a linked list of LustreBasicBlocks.
*
* In this translation we change every Limp statement into a Lustre equation. In addition we add
* infrastructure here to support unique naming, SSA transformations, and other general translation
* artifacts.
*
* triggerId - the name of the node triggering signal
* nodeName - the unique name of the node
* stateInputId - the name of the input state record
* stateOutputId - the name of the output state record
* globalInputId - the name of the input global record
* globalOutputId - the name of the output global record
* preconditionId - the name of the precondition aggregator signal
* postconditionId - the name of the postcondition aggregator signal
*/
public class TranslateBasicBlocks {
public static LustreBasicBlock translate(BasicBlock first,LocalProcedureToLustre p2l) {
return new TranslateBasicBlocks(p2l).translateBlock(first);
}
private TranslateBasicBlocks(LocalProcedureToLustre p2l) {
this.procedureToLustre = p2l;
}
private Map<BasicBlock,LustreBasicBlock> map = new LinkedHashMap<>();
private Integer id = 0;
private LocalProcedureToLustre procedureToLustre;
private LustreBasicBlock translateBlock(BasicBlock bb) {
if(map.containsKey(bb)) {
return map.get(bb);
}
LustreBasicBlock lustreBlock = new LustreBasicBlock(id++,bb.parent);
map.put(bb, lustreBlock);
lustreBlock.usedIds.addAll(procedureToLustre.getGlobalIdentifiers());
lustreBlock.usedIds.addAll(procedureToLustre.getLocalIdentifiers());
//these must come after we set the usedIds
lustreBlock.triggerId = lustreBlock.getUniqueID("trigger");
lustreBlock.nodeName = lustreBlock.getUniqueID(lustreBlock.parent.getName() + "_block_" + lustreBlock.id);
lustreBlock.stateInputId = lustreBlock.getUniqueID("state_in");
lustreBlock.stateOutputId = lustreBlock.getUniqueID("state_out");
lustreBlock.globalInputId = lustreBlock.getUniqueID("globals_in");
lustreBlock.globalOutputId = lustreBlock.getUniqueID("globals_out");
lustreBlock.preconditionId = lustreBlock.getUniqueID("precondition");
lustreBlock.postconditionId = lustreBlock.getUniqueID("postcondition");
for(Statement s : bb.statements) {
Equation eq = LimpStatementToLustreEquation.translate(s);
ExtendedEquation eeq = new ExtendedEquation(eq);
lustreBlock.equations.add(eeq);
}
for(BlockEdge be : bb.conditionalExits) {
LustreBlockEdge lbe = translateBlockEdge(be);
lustreBlock.conditionalExits.add(lbe);
}
lustreBlock.unconditionalExit = translateBlockEdge(bb.unconditionalExit);
return lustreBlock;
}
private LustreBlockEdge translateBlockEdge(BlockEdge blockEdge) {
if(blockEdge == null) {
return null;
}
LustreBlockEdge lustreBlockEdge = new LustreBlockEdge();
lustreBlockEdge.setDestination(translateBlock(blockEdge.destination));
if(!blockEdge.isUnconditional()) {
lustreBlockEdge.setCondition(LimpExprToLustreExpr.translate(blockEdge.condition));
}
return lustreBlockEdge;
}
}
|
package com.bass.shop.action;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import com.bass.common.base.BaseStruts2Action;
import com.bass.shop.model.MessageBoard;
import com.bass.shop.service.MessageBoardService;
@Controller(value = "messageBoardAction")
public class MessageBoardAction extends BaseStruts2Action {
/**
* 留言板Action
*/
private static final long serialVersionUID = 1L;
@Resource(name = "messageBoardService")
private MessageBoardService messageBoardService;
private String messageUser;
private String messagemail;
private String subject;
private String message;
private boolean commitStatu;// 返回提交状态
public String getMessageUser() {
return messageUser;
}
public void setMessageUser(String mslist) {
this.messageUser = mslist;
}
public String getMessagemail() {
return messagemail;
}
public void setMessagemail(String mslist) {
this.messagemail = mslist;
}
public String getSubject() {
return subject;
}
public void setSubject(String mslist) {
this.subject = mslist;
}
public String getMessage() {
return message;
}
public void setMessage(String mslist) {
this.message = mslist;
}
public boolean isCommitStatu() {
return commitStatu;
}
public void setCommitStatu(Boolean mslist) {
this.commitStatu =mslist;
}
public String findmessageboard() {
// System.out.println(getMessageUser());
// System.out.println(getMessagemail());
// System.out.println(getSubject());
// System.out.println(getMessage());
MessageBoard mes=new MessageBoard();
mes.setMessageUser(messageUser);
mes.setMessagemail(messagemail);
mes.setSubject(subject);
mes.setMessage(message);
messageBoardService.findmessageboard(mes);
// Serializable mslist = messageBoardService.findmessageboard(mes);
this.setCommitStatu(true);
return SUCCESS;
}
}
|
package com.qualcomm.snapdragon.sdk.recognition.sample;
import com.avos.avoscloud.AVClassName;
import com.avos.avoscloud.AVObject;
@AVClassName("People")
public class People extends AVObject {
@Override
public String toString() {
// return super.toString();
return getString("name");
}
public String getId() {
return getString("objectId");
}
}
|
package com.notifica.core.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class LocalDateParser {
public static LocalDate parseString(String date){
return LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
}
public static Date parseJavaScriptDate(String date) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
return sdf.parse(date);
}
public static Gson getNewGson() {
return new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
.create();
}
public static LocalDate tryParse(String date) throws Exception{
try{
return LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
}catch (Exception e) {
try {
return LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"));
} catch (Exception e1) {
try {
return LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"));
} catch (Exception e2) {
try {
return LocalDate.parse(date, DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"));
} catch (Exception e3) {
try {
return LocalDate.parse(date, DateTimeFormatter.ofPattern("dd/MM/yyyy"));
} catch (Exception e4) {
throw new Exception("Não foi possivel formatar a data", e4);
}
}
}
}
}
}
public static Date tryParseToDate(String date) throws Exception{
try{
return Date.from(LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay(ZoneId.systemDefault()).toInstant());
}catch (Exception e) {
try {
return Date.from(LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S")).atStartOfDay(ZoneId.systemDefault()).toInstant());
} catch (Exception e1) {
try {
return Date.from(LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")).atStartOfDay(ZoneId.systemDefault()).toInstant());
} catch (Exception e2) {
try {
return Date.from(LocalDate.parse(date, DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss")).atStartOfDay(ZoneId.systemDefault()).toInstant());
} catch (Exception e3) {
try {
return Date.from(LocalDate.parse(date, DateTimeFormatter.ofPattern("dd/MM/yyyy")).atStartOfDay(ZoneId.systemDefault()).toInstant());
} catch (Exception e4) {
throw new Exception("Não foi possivel formatar a data", e4);
}
}
}
}
}
}
}
|
package com.tencent.mm.plugin.remittance.ui;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
class RemittanceResultNewUI$2 implements OnClickListener {
final /* synthetic */ RemittanceResultNewUI mDp;
RemittanceResultNewUI$2(RemittanceResultNewUI remittanceResultNewUI) {
this.mDp = remittanceResultNewUI;
}
public final void onClick(DialogInterface dialogInterface, int i) {
RemittanceResultNewUI.b(this.mDp);
}
}
|
package dev.borowiecki.home.after_week_1.solutions;
import java.util.Arrays;
public class Ex8 {
public static void main(String[] args) {
// rozwiazanie dla macierzy kwadratowej, i bez uzycia tablicy pomocniczej
int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
final int L = array.length;
for(int i = 0; i < L;i++) {
for (int j = i; j < L; j++) {
System.out.println(String.format("Swap %d %d", i, j));
int temp = array[i][j];
System.out.println(String.format("%d %d", array[i][j], array[j][i]));
array[i][j] = array[j][i];
array[j][i] = temp;
}
}
for (int i = 0; i < L; i++) {
System.out.println(Arrays.toString(array[i]));
}
// rozwiazanie dla macierzy nie kwadratowej, i z uzyciem tablicy pomocniczej,
// ps: musimy utworzyc nowa tablice o innych wymiarach
int[][] rectangle = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};
int[][] rectangleFinal = new int[rectangle[0].length][rectangle.length];
for (int i = 0; i < rectangle.length; i++) {
for (int j = 0; j < rectangle[i].length; j++) {
rectangleFinal[j][i] = rectangle[i][j];
}
}
for (int i = 0; i < rectangleFinal.length; i++) {
System.out.println(Arrays.toString(rectangleFinal[i]));
}
}
}
|
package com.deltastuido.store;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import com.deltastuido.project.Project;
import com.deltastuido.project.ProjectBuilder;
import com.deltastuido.store.Item;
import com.deltastuido.store.Product;
import com.deltastuido.store.ShoppingList;
import com.deltastuido.store.ShoppingListItem;
import com.deltastuido.user.User;
public class ShoppingListTest {
private ShoppingList sl;
private Project p;
private int quantity;
private String userId;
private ShoppingGuide guide;
@Before
public void setUp() {
quantity = 20;
userId = "zy";
sl = new ShoppingList();
p = new ProjectBuilder().withAssure("肯定靠谱").withBlurb("吧啦吧啦吧啦吧").withCatalogue("T")
.withDeadline(Timestamp.from(Instant.now().plus(7, ChronoUnit.DAYS))).withId("p1").withName("大力出奇迹")
.withPic("/media/2.png").withPrice(BigDecimal.valueOf(201.12)).withPublisher(new User())
.withSalesIndicator(200).build();
guide = new ShoppingGuide();
guide.setProject(p);
Product prdt = p.getProduct();
Map<String, String> props = new HashMap<>();
props.put("style", "nima");
props.put("size", "XL");
props.put("color", "red");
List<String> pics = new ArrayList<>();
pics.add("/media/1.jpg");
pics.add("/media/2.jpg");
Item item = new Item("1", prdt, props, pics);
prdt.addItem(item);
props = new HashMap<>();
props.put("style", "nv");
props.put("size", "X");
props.put("color", "yellow");
pics = new ArrayList<>();
pics.add("/media/33.jpg");
pics.add("/media/3.jpg");
item = new Item("2", prdt, props, pics);
prdt.addItem(item);
}
@Test
public void testAddItem() {
Product prdt = p.getProduct();
Item item = prdt.getItems().get(0);
sl.addItem(p, item, quantity, userId);
ShoppingListItem si = sl.getShoppingListItems().get(0);
assertNotNull(si);
assertEquals(quantity, si.getQuantity());
assertEquals(userId, si.getUserId());
}
@Test
public void testAddMultipleItems() {
Product prdt = p.getProduct();
Item item = prdt.getItems().get(0);
sl.addItem(p, item, quantity, userId);
assertEquals(1, sl.getShoppingListItems().size());
item = prdt.getItems().get(1);
sl.addItem(p, item, quantity, userId);
assertEquals(2, sl.getShoppingListItems().size());
for (ShoppingListItem i : sl.getShoppingListItems()) {
assertEquals(quantity, i.getQuantity());
}
}
@Test
public void testAddSameSkuWithDiffentIds() {
Product prdt = p.getProduct();
Item item = prdt.getItems().get(0);
sl.addItem(p, item, quantity, userId);
sl.addItem(p, item, quantity, "xxx");
assertEquals(2, sl.getShoppingListItems().size());
for (ShoppingListItem i : sl.getShoppingListItems()) {
assertEquals(item, i.getItem());
}
for (ShoppingListItem i : sl.getShoppingListItems()) {
assertEquals(quantity, i.getQuantity());
}
}
@Test
public void testAddSameItems() {
Product prdt = p.getProduct();
Item sku = prdt.getItems().get(0);
for (int i = 0; i < 3; i++) {
sl.addItem(p, sku, quantity, userId);
}
assertEquals(1, sl.getShoppingListItems().size());
assertEquals(quantity * 3, sl.getShoppingListItems().get(0).getQuantity());
}
@Test
public void testDeleteItem() {
Product prdt = p.getProduct();
Item item = prdt.getItems().get(0);
sl.addItem(p, item, quantity, userId);
ShoppingListItem si = sl.getShoppingListItems().get(0);
sl.delete(si.getId());
assertEquals(0, sl.getShoppingListItems().size());
}
@Test
public void testEditItem1() {
Product prdt = p.getProduct();
Item item = prdt.getItems().get(0);
sl.addItem(p, item, quantity, userId);
ShoppingListItem si = sl.getShoppingListItems().get(0);
sl.edit(si.getId(), 20, null);
assertEquals(1, sl.getShoppingListItems().size());
assertTrue(si.getUserId().isEmpty());
}
@Test
public void testEditItem2() {
Product prdt = p.getProduct();
Item sku = prdt.getItems().get(0);
sl.addItem(p, sku, quantity, userId);
ShoppingListItem item = sl.getShoppingListItems().get(0);
sl.edit(item.getId(), 20, "x");
assertEquals("x", item.getUserId());
assertEquals(20, item.getQuantity());
}
@Test
public void testEditItem3() {
Product prdt = p.getProduct();
Item item = prdt.getItems().get(0);
sl.addItem(p, item, 2, userId);
ShoppingListItem si = sl.getShoppingListItems().get(0);
sl.edit(si.getId(), 20, "zyang32");
assertEquals("zyang32", si.getUserId());
assertEquals(20, si.getQuantity());
}
@Test
public void testTotalPrice() {
Product prdt = p.getProduct();
Item item = prdt.getItems().get(0);
sl.addItem(p, item, quantity, userId);
assertEquals(prdt.getPrice().multiply(BigDecimal.valueOf(quantity)), sl.getAmount());
}
@Test
public void testTotalPrice2() {
Product prdt = p.getProduct();
Item item = prdt.getItems().get(0);
sl.addItem(p, item, quantity, userId);
sl.addItem(p, item, quantity, "xxx");
assertEquals(prdt.getPrice().multiply(BigDecimal.valueOf(quantity * 2)), sl.getAmount());
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.webbeans.context;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import jakarta.enterprise.context.ContextNotActiveException;
import jakarta.enterprise.context.spi.AlterableContext;
import jakarta.enterprise.context.spi.Contextual;
import jakarta.enterprise.context.spi.CreationalContext;
import org.apache.webbeans.container.SerializableBean;
import org.apache.webbeans.container.SerializableBeanVault;
import org.apache.webbeans.context.creational.BeanInstanceBag;
/**
* Abstract implementation of the {@link jakarta.enterprise.context.spi.Context} interfaces.
*
* @see jakarta.enterprise.context.spi.Context
* @see RequestContext
* @see DependentContext
* @see SessionContext
* @see ApplicationContext
* @see ConversationContext
*/
public abstract class AbstractContext implements AlterableContext, Serializable
{
private static final long serialVersionUID = 2357678967444477818L;
/**Context status, active or not*/
protected volatile boolean active;
/**Context contextual instances*/
protected Map<Contextual<?>, BeanInstanceBag<?>> componentInstanceMap;
/**Contextual Scope Type*/
protected Class<? extends Annotation> scopeType;
@SuppressWarnings("unchecked")
private <T> BeanInstanceBag<T> createContextualBag(Contextual<T> contextual, CreationalContext<T> creationalContext)
{
BeanInstanceBag<T> bag = new BeanInstanceBag<>(creationalContext);
if(componentInstanceMap instanceof ConcurrentMap)
{
BeanInstanceBag<?> existingBag = ((ConcurrentMap<Contextual<?>, BeanInstanceBag<?>>) componentInstanceMap).putIfAbsent(contextual, bag);
if (existingBag != null)
{
bag = (BeanInstanceBag<T>) existingBag;
}
}
else
{
componentInstanceMap.put(contextual, bag);
}
return bag;
}
/**
* Creates a new context with given scope type.
*
* @param scopeType context scope type
*/
protected AbstractContext(Class<? extends Annotation> scopeType)
{
this.scopeType = scopeType;
setComponentInstanceMap();
}
/**
* {@inheritDoc}
*/
@Override
@SuppressWarnings("unchecked")
public <T> T get(Contextual<T> component)
{
checkActive();
BeanInstanceBag bag = componentInstanceMap.get(component);
if(bag != null)
{
return (T) bag.getBeanInstance();
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext)
{
checkActive();
return getInstance(contextual, creationalContext);
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
protected <T> T getInstance(Contextual<T> contextual, CreationalContext<T> creationalContext)
{
T instance;
//Look for bag
BeanInstanceBag<T> bag = (BeanInstanceBag<T>)componentInstanceMap.get(contextual);
if(bag == null)
{
bag = createContextualBag(contextual, creationalContext);
}
//Look for instance
instance = bag.getBeanInstance();
if (instance != null)
{
return instance;
}
else
{
if(creationalContext == null)
{
return null;
}
else
{
instance = bag.create(contextual);
}
}
return instance;
}
@Override
public void destroy(Contextual<?> contextual)
{
destroyInstance(contextual);
}
/**
* Internal destroy method.
*/
public void destroyInstance(Contextual<?> contextual)
{
BeanInstanceBag<?> instance = componentInstanceMap.get(contextual);
if (instance == null)
{
// just exit if people manually invoke destroy after the bean already got ditched
return;
}
//Get creational context
CreationalContext<Object> cc = (CreationalContext<Object>)instance.getBeanCreationalContext();
//Destroy instance
Object beanInstance = instance.getBeanInstance();
if (beanInstance != null)
{
destroyInstance((Contextual<Object>)contextual, beanInstance, cc);
}
}
/**
* Destroy the given web beans component instance.
*
* @param <T>
* @param component web beans component
* @param instance component instance
*/
private <T> void destroyInstance(Contextual<T> component, T instance, CreationalContext<T> creationalContext)
{
//Destroy component
component.destroy(instance,creationalContext);
componentInstanceMap.remove(component);
}
/**
* {@inheritDoc}
*/
public void destroy()
{
Set<Contextual<?>> keySet = new HashSet<>(componentInstanceMap.keySet());
for (Contextual<?> contextual: keySet)
{
destroyInstance(contextual);
}
setActive(false);
}
/**
* Gets context active flag.
*
* @return active flag
*/
@Override
public boolean isActive()
{
return active;
}
/**
* Set component active flag.
*
* @param active active flag
*/
public void setActive(boolean active)
{
this.active = active;
}
/**
* {@inheritDoc}
*/
@Override
public Class<? extends Annotation> getScope()
{
return scopeType;
}
/**
* {@inheritDoc}
*/
protected abstract void setComponentInstanceMap();
/**
* Check that context is active or throws exception.
*/
protected void checkActive()
{
if (!active)
{
throw new ContextNotActiveException("WebBeans context with scope annotation @" + getScope().getName() + " is not active with respect to the current thread");
}
}
/**
* Write Object.
*/
private void writeObject(ObjectOutputStream s)
throws IOException
{
s.writeObject(scopeType);
s.writeBoolean(active);
// we need to repack the Contextual<T> from the componentInstanceMap into Serializable ones
if (componentInstanceMap != null)
{
SerializableBeanVault sbv = org.apache.webbeans.config.WebBeansContext.getInstance().getSerializableBeanVault();
Map<Contextual<?>, BeanInstanceBag<?>> serializableInstanceMap =
new HashMap<>();
for (Map.Entry<Contextual<?>, BeanInstanceBag<?>> componentInstanceMapEntry : componentInstanceMap.entrySet())
{
serializableInstanceMap.put(sbv.getSerializableBean(componentInstanceMapEntry.getKey()),
componentInstanceMapEntry.getValue());
}
s.writeObject(serializableInstanceMap);
}
else
{
s.writeObject(null);
}
}
/**
* Read object.
*/
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException
{
scopeType = (Class<? extends Annotation>) s.readObject();
active = s.readBoolean();
HashMap<Contextual<?>, BeanInstanceBag<?>> serializableInstanceMap =
(HashMap<Contextual<?>, BeanInstanceBag<?>>) s.readObject();
if (serializableInstanceMap != null)
{
setComponentInstanceMap();
if (componentInstanceMap == null)
{
throw new NotSerializableException("componentInstanceMap not initialized!");
}
for (Map.Entry<Contextual<?>, BeanInstanceBag<?>> serializableInstanceMapEntry : serializableInstanceMap.entrySet())
{
Contextual<?> bean = serializableInstanceMapEntry.getKey();
if (bean instanceof SerializableBean)
{
componentInstanceMap.put(((SerializableBean<?>)bean).getBean(), serializableInstanceMapEntry.getValue());
}
else
{
componentInstanceMap.put(bean, serializableInstanceMapEntry.getValue());
}
}
}
}
}
|
package com.qd.mystudy.misc;
import java.util.concurrent.*;
/**
* Created by liqingdong911 on 2015/6/2.
*/
public class TestExecutor {
public static void main(String[] args){
ExecutorService executorService = new ThreadPoolExecutor(0, 2, 60000L, TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>());
executorService.submit(new Runnable() {
@Override
public void run() {
System.out.println("got it");
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
executorService.submit(new Runnable() {
@Override
public void run() {
System.out.println("got it");
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
executorService.submit(new Runnable() {
@Override
public void run() {
System.out.println("got it");
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
|
package com.gyk.s2h.varmisin;
/**
* Created by HULYA on 27.08.2017.
*/
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;
import android.content.Context;
import android.graphics.Color;
import android.net.Uri;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class VarmisinYIstekleriAdapter extends BaseAdapter {
LayoutInflater layoutInflater;
ArrayList<YuruyusModel> vIstekleri;
TextView isim, iddia;
ImageView resim;
FirebaseDatabase database;
private String userID;
private DatabaseReference mDatabase;
FloatingActionButton onay,sil;
public VarmisinYIstekleriAdapter(FragmentActivity activity, ArrayList<YuruyusModel> vIstekleri) {
layoutInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.vIstekleri = vIstekleri;
}
@Override
public int getCount() {
return vIstekleri.size();
}
@Override
public Object getItem(int i) {
return vIstekleri.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(final int i, View view, ViewGroup viewGroup) {
final YuruyusModel kisiModel = vIstekleri.get(i);
final View satir = layoutInflater.inflate(R.layout.banagelen_list_item, null);
database = FirebaseDatabase.getInstance();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
userID = user.getUid();
Log.d("userID:", userID);
mDatabase = FirebaseDatabase.getInstance().getReference();
isim=(TextView)satir.findViewById(R.id.adSoyad);
iddia=(TextView)satir.findViewById(R.id.iddia);
onay=(FloatingActionButton)satir.findViewById(R.id.onay);
sil=(FloatingActionButton)satir.findViewById(R.id.sil);
onay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mDatabase.child("adimIddia").child(kisiModel.getUid()).child(userID).child("istek").setValue("kabul");
mDatabase.child("Yapilacaklar").child(userID).child(kisiModel.getUid()).child("sure").setValue(kisiModel.getSure());
mDatabase.child("Yapilacaklar").child(userID).child(kisiModel.getUid()).child("adimS").setValue(kisiModel.getAdimS());
mDatabase.child("Yapilacaklar").child(userID).child(kisiModel.getUid()).child("isim").setValue(kisiModel.getIsim());
mDatabase.child("Yapilacaklar").child(userID).child(kisiModel.getUid()).child("uid").setValue(kisiModel.getUid());
mDatabase.child("Yapilacaklar").child(userID).child(kisiModel.getUid()).child("durum").setValue("kabul");
final DatabaseReference dbRef=FirebaseDatabase.getInstance().getReference().child("adimIstek").child(userID);
dbRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
String key =ds.getKey().toString();
if(key.equals(kisiModel.getUid())){
ds.getRef().removeValue();
Toast.makeText(satir.getContext(), "İstek kabul edildi.", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
sil.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final DatabaseReference dbRef1=FirebaseDatabase.getInstance().getReference().child("adimIddia").child(kisiModel.getUid());
dbRef1.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
String key =ds.getKey().toString();
if(key.equals(userID)){
ds.getRef().removeValue();
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
final DatabaseReference dbRef=FirebaseDatabase.getInstance().getReference().child("adimIstek").child(userID);
dbRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
String key =ds.getKey().toString();
if(key.equals(kisiModel.getUid())){
ds.getRef().removeValue();
Toast.makeText(satir.getContext(), "İstek reddedildi.", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
isim.setText(kisiModel.getIsim());
iddia.setText(kisiModel.getSure()+" saat sürede "+kisiModel.getAdimS()+" adım atmaya var mısın?");
return satir;
}
}
|
package com.example.grduationproject;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import androidx.annotation.ContentView;
import androidx.annotation.Nullable;
public class Database extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "EcoHome.db";
public Database(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table admins " +
"(id integer primary key AUTOINCREMENT," +
"name text," +
"phone text)");
db.execSQL("create table applications (id integer primary key AUTOINCREMENT, mobile text)");
db.execSQL("create table request " +
"(id integer primary key AUTOINCREMENT," +
"mobile text," +
"service text," +
"info text,"+
"time text," +
"served boolean DEFAULT 0," +
"date text)");
db.execSQL("create table customers " +
"(id integer primary key AUTOINCREMENT," +
"name text," +
"phone text," +
"address text)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public boolean addCustomer(String name, String phoneNumbet, String address) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentVals = new ContentValues();
contentVals.put("name", name);
contentVals.put("phone", phoneNumbet);
contentVals.put("address", address);
long result = db.insert("customers", null, contentVals);
if (result == -1) {
Log.e("Database logs"," adding customer failed" );
}
else {
Log.d("Database logs"," adding customer done" );
}
return result== -1? false: true;
}
}
|
/*
* 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 bbc.karate.club;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JOptionPane;
/**
*
* @author Abhirham
*/
public class classtime extends javax.swing.JFrame {
Connection conn = null;
ResultSet rs = null;
PreparedStatement pst = null;
/**
* Creates new form classtime
*/
public classtime() {
initComponents();
try {
conn = sqlcon.connecrDB();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "JDBC connction failed");
}
}
/**
* 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() {
jLabel7 = new javax.swing.JLabel();
jTextField4 = new javax.swing.JTextField();
jPanel2 = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
hours = new javax.swing.JSpinner();
jLabel3 = new javax.swing.JLabel();
mins = new javax.swing.JSpinner();
jLabel4 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
weekno = new javax.swing.JTextField();
level = new javax.swing.JComboBox<>();
jLabel5 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
loc = new javax.swing.JTextField();
cid = new javax.swing.JComboBox<>();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jLabel7.setText("jLabel7");
jTextField4.setText("jTextField4");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("CLASS");
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Class time"));
jLabel2.setText("Hours:");
hours.setModel(new javax.swing.SpinnerNumberModel(7, 6, 23, 1));
jLabel3.setText("Mins:");
mins.setModel(new javax.swing.SpinnerNumberModel(0, 0, 60, 1));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(hours, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(mins, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(hours, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(mins, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jLabel4.setText("Location:");
jLabel6.setText("Level:");
level.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "BEGINNER", "INTERMEDIATE", "ADVANCE" }));
jLabel5.setText("Week no:");
jLabel1.setText("Class id:");
cid.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "100", "103", "105" }));
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(32, 32, 32)
.addComponent(jLabel1)
.addGap(31, 31, 31)
.addComponent(cid, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(17, 17, 17)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(jLabel5)
.addComponent(jLabel6))
.addGap(36, 36, 36)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(loc)
.addComponent(weekno)
.addComponent(level, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE))))))
.addGap(71, 71, 71))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(cid, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(loc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(weekno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(level, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jButton1.setText("Add");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Back");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(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()
.addGap(57, 57, 57)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(84, 84, 84)
.addComponent(jButton1)
.addGap(69, 69, 69)
.addComponent(jButton2)))
.addContainerGap(56, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(19, 19, 19)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2))
.addContainerGap(66, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
String lev = level.getSelectedItem().toString();
String classid = cid.getSelectedItem().toString();
String h = hours.getValue().toString();
String m = mins.getValue().toString();
String time = h+":"+m+":"+"00";
try {
String sql = "insert into class values (?,303,?,?,?,?)";
pst = conn.prepareStatement(sql);
pst.setString(1, classid);
pst.setString(2, time);
pst.setString(3, loc.getText());
pst.setString(4, weekno.getText());
pst.setString(5, lev);
pst.execute();
JOptionPane.showMessageDialog(null, "Class added sucessfully");
classtime a = new classtime();
a.setVisible(true);
this.dispose();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "failed to add class");
} // TODO add your handling code here:
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
try {
conn.close();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "jdbc closing failed");
}
home a = new home();
a.setVisible(true);
this.dispose();
// TODO add your handling code here:
}//GEN-LAST:event_jButton2ActionPerformed
/**
* @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(classtime.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(classtime.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(classtime.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(classtime.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 classtime().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JComboBox<String> cid;
private javax.swing.JSpinner hours;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JTextField jTextField4;
private javax.swing.JComboBox<String> level;
private javax.swing.JTextField loc;
private javax.swing.JSpinner mins;
private javax.swing.JTextField weekno;
// End of variables declaration//GEN-END:variables
}
|
package com.meebu;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import com.meebu.databinding.ActivityReviewsBinding;
import com.meebu.databinding.ActivitySavedAddressBinding;
public class SavedAddressActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivitySavedAddressBinding binding= DataBindingUtil.setContentView(SavedAddressActivity.this,R.layout.activity_saved_address);
binding.back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
binding.addMorePlace.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(SavedAddressActivity.this,AddNewAddressActivity
.class));
overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
}
});
}
@Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
}
}
|
/* good comment */
/** good comment */
/*/ good comment */
/*/ good comment /*/
/*
* comment /*
*/
/*/
* comment /*
*/
/* // wuff */
/* ** */
/*
/** * / / * // /*
*/
/*****/
/**/
/** **/
/*
*/
/**
*/
int main() {
return 0;
}
|
package com.mockito.v4_v5_stubbing_expect;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.fail;
// @RunWith(MockitoJUnitRunner.class)
public class StubbingTest {
private List<String> list;
@BeforeEach
public void init_like_cpp_TearUp() {
this.list = Mockito.mock(ArrayList.class);
}
@Test
public void howToUseStubbing() {
Mockito.when(list.get(0)).thenReturn("first");
Assertions.assertEquals(list.get(0), "first");
Mockito.when(list.get(ArgumentMatchers.anyInt())).thenThrow(RuntimeException.class);
try {
list.get(0);
// fail(); //
} catch (Exception e) {
// Assertions.assertTrue(e instanceof RuntimeException.class);
Assertions.assertEquals(e.getClass(), RuntimeException.class);
}
}
@Test
public void howToUseSubbingVoidMethod() {
Mockito.doNothing().when(list).clear();
list.clear();
Mockito.verify(list, Mockito.times(1)).clear();
Mockito.doThrow(RuntimeException.class).when(list).clear();
try {
list.clear();
fail();
} catch (Exception e) {
Assertions.assertEquals(e.getClass(), RuntimeException.class);
}
}
@Test
public void stubbingDoReturn() {
// 以下两行写法等价
Mockito.when(list.get(0)).thenReturn("first");
Mockito.doReturn("second").when(list).get(1);
Assertions.assertEquals(list.get(0), "first");
Assertions.assertEquals(list.get(1), "second");
}
@Test
public void stubbingWithIterate() {
Mockito.when(list.size()).thenReturn(1, 2, 3, 4);
Assertions.assertEquals(list.size(), 1);
Assertions.assertEquals(list.size(), 2);
Assertions.assertEquals(list.size(), 3);
Assertions.assertEquals(list.size(), 4);
}
@Test
public void stubbingWithAnswer() {
// when(list.get(anyInt())).thenAnswer(new Answer<Object>() {
// @Override
// public String answer(InvocationOnMock invocationOnMock) throws Throwable {
// Integer index = invocationOnMock.getArgumentAt(0, Integer.class);
// return String.valueOf(index * 10);
// }
// });
// when(list.get(anyInt())).thenAnswer(invocationOnMock -> {
// Integer index = invocationOnMock.getArgumentAt(0, Integer.class);
// return String.valueOf(index * 10);
// });
// Assertions.assertEquals(list.get(0), "0");
// Assertions.assertEquals(list.get(888), "8880");
}
@Test
public void stubbingWithRealCall() {
StubbingService service = Mockito.mock(StubbingService.class);
Mockito.when(service.runStubbingMethod()).thenReturn("stubbing----------Method");
Assertions.assertEquals(service.runStubbingMethod(), "stubbing----------Method");
Mockito.when(service.runRealMethod()).thenCallRealMethod();
Assertions.assertEquals(service.runRealMethod(), "runRealMethod");
}
@AfterEach
public void destroy_like_cpp_TearDown() {
Mockito.reset(this.list);
}
}
|
/*
* Copyright (c) 2019 Eshel.
*
* 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 game.eshel.pushbox;
import android.support.annotation.NonNull;
/**
* <br>createBy guoshiwen
* <br>createTime: 2019/10/30 20:52
* <br>desc: 计步器
*/
public class History {
//回退栈
// private Stack<Step> mBackStack = new Stack<>();
//前进栈
// private Stack<Step> mForwardStack = new Stack<>();
private Step firstStep;
private Step currentStep;
private int size;
private StepChangeListener mStepChangeListener;
public Step saveBefore(Grid boy){
Step step = new Step(boy);
linkStep(step);
size++;
if(mStepChangeListener != null) mStepChangeListener.stepChanged(getSteps());
return step;
}
public Step saveBefore(Grid boy, Grid box){
Step step = new Step(boy, box);
linkStep(step);
size++;
if(mStepChangeListener != null) mStepChangeListener.stepChanged(getSteps());
return step;
}
public void saveAfter(Step step, char type){
step.after(type);
}
// 回退
public void backward(){
if(currentStep == null)
return;
boolean success = currentStep.backward();
if(success){
size--;
if(mStepChangeListener != null) mStepChangeListener.stepChanged(getSteps());
Step last = currentStep.last;
if(last == null)
return;
currentStep = last;
}
}
//前进
public void forward(){
if(currentStep == null)
return;
boolean success = currentStep.forward();
if(success){
size++;
if(mStepChangeListener != null) mStepChangeListener.stepChanged(getSteps());
Step next = currentStep.next;
if(next == null)
return;
currentStep = next;
}
}
public void setStepChangeListener(StepChangeListener stepChangeListener) {
mStepChangeListener = stepChangeListener;
}
private void linkStep(Step step) {
if (firstStep == null) {
firstStep = step;
currentStep = firstStep;
} else {
currentStep.next = step;
step.last = currentStep;
currentStep = step;
}
}
public int getSteps(){
return size;
}
@NonNull
@Override
public String toString() {
if(firstStep == null)
return "";
StringBuilder sb = new StringBuilder();
Step step = firstStep;
while (step != null){
sb.append(step.getType());
step = step.next;
}
return sb.toString();
}
public interface StepChangeListener{
void stepChanged(int step);
}
}
|
package com.example.healthmanage.ui.activity.famousDoctorHall.response;
import java.util.List;
/**
* desc:
* date:2021/7/2 14:20
* author:bWang
*/
public class ChinaCityDataBean {
/**
* id : 110000
* name : 北京市
* cityList : [{"id":"110000","name":"北京市","cityList":[{"id":"110101","name":"东城区"},{"id":"110102","name":"西城区"},{"id":"110105","name":"朝阳区"},{"id":"110106","name":"丰台区"},{"id":"110107","name":"石景山区"},{"id":"110108","name":"海淀区"},{"id":"110109","name":"门头沟区"},{"id":"110111","name":"房山区"},{"id":"110112","name":"通州区"},{"id":"110113","name":"顺义区"},{"id":"110114","name":"昌平区"},{"id":"110115","name":"大兴区"},{"id":"110116","name":"怀柔区"},{"id":"110117","name":"平谷区"},{"id":"110118","name":"密云区"},{"id":"110119","name":"延庆区"}]}]
*/
private String id;
private String name;
private boolean isSelect;
public ChinaCityDataBean(String name) {
this.name = name;
}
/**
* id : 110000
* name : 北京市
* cityList : [{"id":"110101","name":"东城区"},{"id":"110102","name":"西城区"},{"id":"110105","name":"朝阳区"},{"id":"110106","name":"丰台区"},{"id":"110107","name":"石景山区"},{"id":"110108","name":"海淀区"},{"id":"110109","name":"门头沟区"},{"id":"110111","name":"房山区"},{"id":"110112","name":"通州区"},{"id":"110113","name":"顺义区"},{"id":"110114","name":"昌平区"},{"id":"110115","name":"大兴区"},{"id":"110116","name":"怀柔区"},{"id":"110117","name":"平谷区"},{"id":"110118","name":"密云区"},{"id":"110119","name":"延庆区"}]
*/
private List<CityListBean> cityList;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isSelect() {
return isSelect;
}
public void setSelect(boolean select) {
isSelect = select;
}
public List<CityListBean> getCityList() {
return cityList;
}
public void setCityList(List<CityListBean> cityList) {
this.cityList = cityList;
}
public static class CityListBean {
private String id;
private String name;
private boolean isSelect;
/**
* id : 110101
* name : 东城区
*/
private List<AreaListBean> cityList;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isSelect() {
return isSelect;
}
public void setSelect(boolean select) {
isSelect = select;
}
public List<AreaListBean> getCityList() {
return cityList;
}
public void setCityList(List<AreaListBean> cityList) {
this.cityList = cityList;
}
public static class AreaListBean {
private String id;
private String name;
private boolean isSelect;
public boolean isSelect() {
return isSelect;
}
public void setSelect(boolean select) {
isSelect = select;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.