text stringlengths 10 2.72M |
|---|
package com.citibank.ods.entity.pl.valueobject;
import java.util.Date;
/**
* @version 1.0
* @author Hamilton Matos,Jul 26, 2007
*/
public class TplCustomerBrokerHistEntityVO extends
BaseTplCustomerBrokerEntityVO
{
/**
* Data e Hora que o usuario aprovou o registro cadastrado
*
* @generated "UML to Java
* (com.ibm.xtools.transform.uml2.java.internal.UML2JavaTransform)"
*/
private Date m_lastAuthDate;
/**
* Codigo do usuario (SOE ID) que aprovou o cadastro do registro
*
* @generated "UML to Java
* (com.ibm.xtools.transform.uml2.java.internal.UML2JavaTransform)"
*/
private String m_lastAuthUserId;
/**
* Status Registro - Identifica se o registro esta ativo, inativo ou aguar
* dando aprovacao"
*
* @generated "UML to Java
* (com.ibm.xtools.transform.uml2.java.internal.UML2JavaTransform)"
*/
private String m_recStatCode;
/**
* Data de Referencia do registro no historico.
*
* @generated "UML to Java
* (com.ibm.xtools.transform.uml2.java.internal.UML2JavaTransform)"
*/
private Date m_bkrCustRefDate;
} |
package com.xiaole.hdfs;
import com.xiaole.mvc.model.LogFilter;
import com.xiaole.mvc.model.NormalLog;
import com.xiaole.mvc.model.checker.InvalidLogChecker;
import com.xiaole.mvc.model.checker.SdkLogChecker;
import com.xiaole.mvc.model.checker.simpleChecker.CheckSimpleInterface;
import com.xiaole.mvc.model.checker.simpleChecker.SimpleCheckerFactory;
import com.xiaole.mvc.model.comparator.LogComparator;
import com.xiaole.mvc.model.comparator.MyComparator;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.log4j.Logger;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.security.PrivilegedExceptionAction;
import java.util.*;
/**
* Created by llc on 16/11/16.
*/
public class HDFSManager {
private static final Logger logger = Logger.getLogger(HDFSManager.class);
// initialization
static Configuration conf = new Configuration();
static FileSystem hdfs;
// private static final String logAddress = "101.201.103.114"; // 公网ip
private static final String logAddress = "10.252.0.171"; // 内网ip
private static final String hadoopUser = "hadoop";
private static final String hdfsAddress = "hdfs://" + logAddress + ":19000/";
static {
UserGroupInformation ugi = UserGroupInformation
.createRemoteUser(hadoopUser);
try {
ugi.doAs(new PrivilegedExceptionAction<Void>() {
public Void run() throws Exception {
Configuration conf = new Configuration();
conf.set("fs.defaultFS", hdfsAddress);
conf.set("hadoop.job.ugi", hadoopUser);
Path path = new Path(hdfsAddress);
hdfs = FileSystem.get(path.toUri(), conf);
//hdfs = path.getFileSystem(conf); // 这个也可以
//hdfs = FileSystem.get(conf); //这个不行,这样得到的hdfs所有操作都是针对本地文件系统,而不是针对hdfs的,原因不太清楚
return null;
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// create a direction
public void createDir(String dir) throws IOException {
Path path = new Path(dir);
if (hdfs.exists(path)) {
System.out.println("dir \t" + conf.get("fs.default.name") + dir
+ "\t already exists");
return;
}
hdfs.mkdirs(path);
System.out.println("new dir \t" + conf.get("fs.default.name") + dir);
}
// copy from local file to HDFS file
public void copyFile(String localSrc, String hdfsDst) throws IOException {
Path src = new Path(localSrc);
Path dst = new Path(hdfsDst);
if (!(new File(localSrc)).exists()) {
System.out.println("Error: local dir \t" + localSrc
+ "\t not exists.");
return;
}
if (!hdfs.exists(dst)) {
System.out.println("Error: dest dir \t" + dst.toUri()
+ "\t not exists.");
return;
}
String dstPath = dst.toUri() + "/" + src.getName();
if (hdfs.exists(new Path(dstPath))) {
System.out.println("Warn: dest file \t" + dstPath
+ "\t already exists.");
}
hdfs.copyFromLocalFile(src, dst);
// list all the files in the current direction
FileStatus files
[] = hdfs.listStatus(dst);
System.out.println("Upload to \t" + conf.get("fs.default.name")
+ hdfsDst);
for (FileStatus file : files) {
System.out.println(file.getPath());
}
}
// create a new file
public void createFile(String fileName, String fileContent)
throws IOException {
Path dst = new Path(fileName);
byte[] bytes = fileContent.getBytes();
FSDataOutputStream output = hdfs.create(dst);
output.write(bytes);
System.out.println("new file \t" + conf.get("fs.default.name")
+ fileName);
}
// create a new file
public void appendFile(String fileName, String fileContent)
throws IOException {
Path dst = new Path(fileName);
byte[] bytes = fileContent.getBytes();
if (!hdfs.exists(dst)) {
createFile(fileName, fileContent);
return;
}
FSDataOutputStream output = hdfs.append(dst);
output.write(bytes);
System.out.println("append to file \t" + conf.get("fs.default.name")
+ fileName);
}
// list all files
public void listFiles(String dirName) throws IOException {
Path f = new Path(dirName);
FileStatus[] status = hdfs.listStatus(f);
System.out.println(dirName + " has all files:");
for (int i = 0; i < status.length; i++) {
System.out.println(status[i].getPath().toString());
}
}
// judge a file existed? and delete it!
public void deleteFile(String fileName) throws IOException {
Path f = new Path(fileName);
boolean isExists = hdfs.exists(f);
if (isExists) { // if exists, delete
boolean isDel = hdfs.delete(f, true);
System.out.println(fileName + " delete? \t" + isDel);
} else {
System.out.println(fileName + " exist? \t" + isExists);
}
}
// read a file if existed
public void readFile(String fileName) throws IOException {
try{
FSDataInputStream inStream = hdfs.open(new Path(fileName));
BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream));
String line = "";
while ((line = bReader.readLine()) != null){
System.out.println(line);
}
} catch (Exception e){
e.printStackTrace();
}
}
// readLines method given a file
public List<String> readLines(String fileName, String module, String memberId, String env, String level)
throws IOException{
FSDataInputStream inStream = hdfs.open(new Path(fileName));
BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream));
String line = "";
LogFilter logFilter = new LogFilter(memberId, module, env, level);
List<String> logList = new ArrayList<String>();
if (logFilter.isHasFilter()){
while ((line = bReader.readLine()) != null){
if (logFilter.filter(line) && InvalidLogChecker.check(line)) {
logList.add(line);
}
}
}
else{
while ((line = bReader.readLine()) != null){
if (InvalidLogChecker.check(line))
logList.add(line);
}
}
return logList;
}
public List<String> readBevaLines(String fileName, String module, String memberId, String env, String level) throws IOException {
FSDataInputStream inStream = hdfs.open(new Path(fileName));
BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream));
String line = "";
LogFilter logFilter = new LogFilter(memberId, module, env, level);
List<String> logList = new ArrayList<String>();
if (logFilter.isHasFilter()){
while ((line = bReader.readLine()) != null){
if (logFilter.filter(line) && InvalidLogChecker.check(line) && SdkLogChecker.check(line)) {
logList.add(line);
}
}
}
else{
while ((line = bReader.readLine()) != null){
if (InvalidLogChecker.check(line) && SdkLogChecker.check(line))
logList.add(line);
}
}
return logList;
}
// Read simple lines from given file
public List<String> readSimpleLines(String fileName, String module, String memberId, String env, String level,
String src)
throws IOException{
FSDataInputStream inStream = hdfs.open(new Path(fileName));
BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream));
String line = "";
LogFilter logFilter = new LogFilter(memberId, module, env, level);
List<String> logList = new ArrayList<String>();
int queueSize = 100;
Queue<NormalLog> pq = new PriorityQueue<>(queueSize, new LogComparator());
NormalLog log;
CheckSimpleInterface simpleChecker = SimpleCheckerFactory.genSimpleChecker(src);
if (logFilter.isHasFilter()){
while ((line = bReader.readLine()) != null){
try {
log = new NormalLog(line);
}catch (Exception e){
logger.error("Parse log error: " + e.getMessage() + "log:" + line);
continue;
}
if (logFilter.filter(log) && simpleChecker.checkSimple(line)) {
pq.add(log);
if (pq.size() == queueSize) {
logList.addAll(pq.poll().toNewSimpleFormat());
}
}
}
}
else{
while ((line = bReader.readLine()) != null){
if (simpleChecker.checkSimple(line)) {
try {
log = new NormalLog(line);
}catch (Exception e){
logger.error("Parse log error: " + e.getMessage() + "log:" + line);
continue;
}
pq.add(log);
if (pq.size() == queueSize) {
logList.addAll(pq.poll().toNewSimpleFormat());
}
}
}
}
// 将队列中剩余的日志按顺序加入logList
for (NormalLog leftLog : pq) {
logList.addAll(leftLog.toNewSimpleFormat());
}
return logList;
}
// read all users simple logs from given file
public Map<String, List<String> > readAllUserSimpleLines(String fileName, String module, String env, String level,
String src)
throws IOException {
FSDataInputStream inStream = hdfs.open(new Path(fileName));
BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream));
String line = "";
LogFilter logFilter = new LogFilter("all", module, env, level);
int queueSize = 100;
Queue<NormalLog> pq = new PriorityQueue<>(queueSize, new LogComparator());
NormalLog log;
Map<String, List<String> > map = new HashMap<>();
CheckSimpleInterface simpleChecker = SimpleCheckerFactory.genSimpleChecker(src);
if (logFilter.isHasFilter()){
while ((line = bReader.readLine()) != null){
try {
log = new NormalLog(line);
}catch (Exception e){
logger.error("Parse log error: " + e.getMessage() + "log:" + line);
continue;
}
if (logFilter.filter(log) && simpleChecker.checkSimple(line)) {
pq.add(log);
if (pq.size() == queueSize) {
NormalLog topLog = pq.poll();
if (!map.containsKey(topLog.getMember_id())) {
logger.info("map add new memberId: " + topLog.getMember_id());
map.put(topLog.getMember_id(), new ArrayList<>());
}
map.get(topLog.getMember_id()).addAll(topLog.toNewSimpleFormat());
}
}
}
}
else{
while ((line = bReader.readLine()) != null){
if (simpleChecker.checkSimple(line)) {
try {
log = new NormalLog(line);
}catch (Exception e){
logger.error("Parse log error: " + e.getMessage() + "log:" + line);
continue;
}
pq.add(log);
if (pq.size() == queueSize) {
NormalLog topLog = pq.poll();
if (!map.containsKey(topLog.getMember_id())) {
map.put(topLog.getMember_id(), new ArrayList<>());
}
map.get(topLog.getMember_id()).addAll(topLog.toNewSimpleFormat());
}
}
}
}
// 将队列中剩余的日志按顺序加入logList
for (NormalLog leftLog : pq) {
if (!map.containsKey(leftLog.getMember_id())) {
map.put(leftLog.getMember_id(), new ArrayList<>());
}
map.get(leftLog.getMember_id()).addAll(leftLog.toNewSimpleFormat());
}
return map;
}
public List<String> getLogByDate(String date, String module, String memberId, String env, String level, String src){
String fileName = "/data/logstash/stats/" + date + ".log";
List<String> logList = new ArrayList<String>();
try {
if (src.equals("xiaole")) {
logList = readLines(fileName, module, memberId, env, level);
} else {
logList = readBevaLines(fileName, module, memberId, env, level);
}
} catch (Exception e) {
logger.error("error occurs: " + e.getMessage());
}
return logList;
}
public List<String> getSimpleLogByDate(String date, String module, String memberId, String env, String level,
String src){
String fileName = "/data/logstash/stats/" + date + ".log";
List<String> logList = new ArrayList<String>();
try {
logList = readSimpleLines(fileName, module, memberId, env, level, src);
} catch (Exception e) {
logger.error("error occurs: " + e.getMessage());
}
return logList;
}
public Map<String, List<String> > getAllUserSimpleLog(String date, String module, String env, String level,
String src) {
String fileName = "/data/logstash/stats/" + date + ".log";
Map<String, List<String> > map = new HashMap<>();
try {
map = readAllUserSimpleLines(fileName, module, env, level, src);
} catch (Exception e) {
logger.error("error occurs: " + e.getMessage());
}
return map;
}
public void downloadLog(String date, String saveName, HttpServletResponse response) throws IOException {
String fileName = "/data/logstash/stats/" + date + ".log";
FSDataInputStream in = hdfs.open(new Path(fileName));
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(saveName, "UTF-8"));
OutputStream out = response.getOutputStream();
IOUtils.copyBytes(in, out, 4096, true);
}
public static void main(String[] args) {
Queue<Integer> pq = new java.util.PriorityQueue<>(4, new MyComparator());
// pq.add(3);
// pq.add(6);
// pq.add(1);
// pq.add(0);
// pq.add(5);
// for (int i : pq) {
// System.out.println(i);
// }
System.out.println("123".compareTo("124"));
}
}
|
package mx.com.otss.saec_registro;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import mx.com.otss.saec_registro.auxiliares.ListadoReporteActivity;
import mx.com.otss.saec_registro.request.ReporteRegistrarRequest;
import mx.com.otss.saec_registro.request.RegistrarSalidaRequest;
import mx.com.otss.saec_registro.auxiliares.IntentIntegrator;
import mx.com.otss.saec_registro.auxiliares.IntentResult;
import static mx.com.otss.saec_registro.auxiliares.Red.verificaConexion;
public class RegistrarSalidaActivity extends AppCompatActivity implements View.OnClickListener {
private Button scanBoton;
private TextView formatoTxt, matriculatxt,detalle;
private String scanContent,user;
private Menu menu;
private MenuItem menuItem;
private BottomNavigationView navigation;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_inferior_inicio:
Intent intent1=new Intent(getApplication(),RegistrarActivity.class);
finish();
startActivity(intent1);
return true;
case R.id.menu_inferior_entrada:
Intent intent2=new Intent(getApplication(),RegistrarEntradaActivity.class);
finish();
startActivity(intent2);
return true;
case R.id.menu_inferior_salida:
Intent intent3=new Intent(getApplication(),RegistrarSalidaActivity.class);
finish();
startActivity(intent3);
return true;
case R.id.menu_inferior_reporte:
if (!verificaConexion(getApplication())) {
Toast.makeText(getBaseContext(),
"Comprueba tu conexión a Internet.... ", Toast.LENGTH_SHORT)
.show();
}else {
final ArrayList<String> arrayList = new ArrayList<>();
String user = "";
Response.Listener<String> responseListener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
Log.i("Info", "" + jsonResponse.toString());
List<String> list = new ArrayList<String>();
JSONArray array = jsonResponse.getJSONArray("registro_diario");
for(int i = 0 ; i < array.length() ; i++){
list.add(array.getJSONObject(i).getString("id"));
list.add(array.getJSONObject(i).getString("nombre"));
list.add(array.getJSONObject(i).getString("dia"));
list.add(array.getJSONObject(i).getString("hora_entrada"));
list.add(array.getJSONObject(i).getString("hora_salida"));
}
Log.i("llego", "Llego"+ list.toString());
Intent intentPrincipal = new Intent(getApplicationContext(), ListadoReporteActivity.class);
intentPrincipal.putStringArrayListExtra("data", (ArrayList<String>) list);
finish();
startActivity(intentPrincipal);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(RegistrarSalidaActivity.this, "No hay registros", Toast.LENGTH_SHORT).show();
}
}
};
ReporteRegistrarRequest reporteRegistrarRequest = new ReporteRegistrarRequest(user, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegistrarSalidaActivity.this);
queue.add(reporteRegistrarRequest);
}
return true;
case R.id.menu_inferior_salir:
Intent intent5=new Intent(getApplication(),SalirActivity.class);
finish();
startActivity(intent5);
return true;
}
return false;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registrar_salida);
navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
menu = navigation.getMenu();
menuItem = menu.getItem(2);
menuItem.setChecked(true);
scanBoton = (Button)findViewById(R.id.btn_registrar_salida_scaneo);
detalle = (TextView)findViewById(R.id.registrar_salida_detalles);
matriculatxt = (TextView)findViewById(R.id.registrar_salida_matricula);
scanBoton.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if(view.getId()==R.id.btn_registrar_salida_scaneo){
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (!verificaConexion(getApplication())) {
Toast.makeText(getBaseContext(),
"Comprueba tu conexión a Internet.... ", Toast.LENGTH_SHORT)
.show();
}else {
if (scanningResult != null) {
scanContent = scanningResult.getContents();
detalle.setText(getText(R.string.detalles));
matriculatxt.setText("Matricula: " + scanContent);
user=scanContent;
Response.Listener<String> responseListener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonResponse=new JSONObject(response);
Log.i("Info", ""+ jsonResponse.toString());
boolean success=jsonResponse.getBoolean("success");
if (success==true) {
Toast.makeText(getApplication(),"registro actualizado correcto",Toast.LENGTH_SHORT).show();
}else {
AlertDialog.Builder builder=new AlertDialog.Builder(RegistrarSalidaActivity.this);
builder.setMessage("error en el registro")
.setNegativeButton("Retry",null)
.create().show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(RegistrarSalidaActivity.this, "Error " + e, Toast.LENGTH_SHORT).show();
}
}
};
RegistrarSalidaRequest registrarEntradaRequest = new RegistrarSalidaRequest(user, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegistrarSalidaActivity.this);
queue.add(registrarEntradaRequest);
}else{
Toast toast = Toast.makeText(getApplicationContext(),
"No se ha recibido datos del scaneo!", Toast.LENGTH_SHORT);
toast.show();
}
}
}
}
|
import java.util.ArrayList;
/**
* Interface for a map creator
* @author Yujin, Luke, Steele, Michael
*
*/
public interface MapCreator {
ArrayList<Entity> create();
int getHeight();
int getWidth();
}
|
package org.openmrs.module.mirebalais.apploader;
import org.openmrs.module.allergyui.AllergyUIConstants;
import org.openmrs.module.coreapps.CoreAppsConstants;
import org.openmrs.module.pihcore.metadata.core.program.ANCProgram;
import org.openmrs.module.pihcore.metadata.core.program.AsthmaProgram;
import org.openmrs.module.pihcore.metadata.core.program.DiabetesProgram;
import org.openmrs.module.pihcore.metadata.core.program.EpilepsyProgram;
import org.openmrs.module.pihcore.metadata.core.program.HIVProgram;
import org.openmrs.module.pihcore.metadata.core.program.HypertensionProgram;
import org.openmrs.module.pihcore.metadata.core.program.MalnutritionProgram;
import org.openmrs.module.pihcore.metadata.core.program.MentalHealthProgram;
import org.openmrs.module.pihcore.metadata.core.program.NCDProgram;
import org.openmrs.module.pihcore.metadata.core.program.MCHProgram;
import org.openmrs.module.pihcore.metadata.core.program.ZikaProgram;
import org.openmrs.module.pihcore.metadata.core.program.Covid19Program;
import org.openmrs.module.pihcore.metadata.core.program.OncologyProgram;
import org.openmrs.module.registrationapp.RegistrationAppConstants;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CustomAppLoaderConstants {
public static final class Apps {
// TODO would be nice to rename this to "pih.checkin"--would need to change CheckInAppWorkflowController in pihcore
// TODO for checkin would need to fix requestRecord.gsp:69
public static final String CHECK_IN = "mirebalais.liveCheckin";
public static final String UHM_VITALS = "pih.uhm.app.vitals";
public static final String VITALS = "pih.app.vitals";
public static final String AWAITING_ADMISSION = CoreAppsConstants.AWAITING_ADMISSION;
public static final String ACTIVE_VISITS = "pih.app.activeVisits";
public static final String ARCHIVES_ROOM = "paperrecord.app.archivesRoom";
public static final String SYSTEM_ADMINISTRATION = "coreapps.app.systemAdministration";
public static final String APPOINTMENT_SCHEDULING_HOME = "appointmentschedulingui.app";
public static final String DISPENSING = "dispensing.app";
public static final String DISPENSING_SUMMARY = "pih.app.dispensing.summary";
public static final String VITALS_SUMMARY = "pih.app.vitals.summary";
public static final String SCHEDULE_APPOINTMENT = "appointmentschedulingui.schedulingAppointmentApp";
public static final String MY_ACCOUNT = "emr.myAccount";
public static final String REPORTS = "reportingui.reports";
public static final String INPATIENTS = "mirebalaisreports.inpatients";
public static final String ACTIVE_VISITS_LIST = "mirebalaisreports.activeVisitsList";
public static final String PATIENT_REGISTRATION = "registrationapp.registerPatient";
public static final String CLINICIAN_DASHBOARD = "pih.app.clinicianDashboard";
public static final String VISITS_SUMMARY = "coreapps.clinicianfacing.visits";
public static final String HOME_VISITS_SUMMARY = "coreapps.home.visits";
public static final String WAITING_FOR_CONSULT = "pih.app.waitingForConsult";
public static final String CHW_MGMT = "chw.app.mgmt";
public static final String ED_TRIAGE = "edtriageapp.app.edTriage";
public static final String ED_TRIAGE_QUEUE = "edtriageapp.app.triageQueue";
public static final String EPILEPSY_SUMMARY = "pih.app.epilepsy.summary";
public static final String EPILEPSY_SEIZURES = "pih.app.epilepsy.seizures";
public static final String TODAYS_VISITS = "pih.app.todaysVisits";
public static final String PATHOLOGY_TRACKING = "labtracking.app.monitorOrders";
public static final String LAB_TRACKING = "pih.app.labtracking";
public static final String LABS = "pih.app.labs.label";
public static final String ORDER_LABS = "pih.app.labs.ordering";
public static final String PROGRAMS_LIST = "coreapps.app.programsList";
public static final String RELATIONSHIPS_REGISTRATION_SUMMARY = "pih.app.relationships.registrationSummary";
public static final String PROVIDER_RELATIONSHIPS_REGISTRATION_SUMMARY = "pih.app.relationships.providers.registrationSummary";
public static final String RELATIONSHIPS_CLINICAL_SUMMARY = "pih.app.relationships.clinicalSummary";
public static final String PROVIDER_RELATIONSHIPS_CLINICAL_SUMMARY = "pih.app.relationships.providers.clinicalSummary";
public static final String PROGRAM_SUMMARY_LIST = "pih.app.programSummaryList";
public static final String HIV_SUMMARY = "pih.app.hiv.summary";
public static final String HIV_ALERTS = "pih.app.hiv.alerts";
public static final String HIV_CD4_GRAPH = "pih.app.hiv.cd4Graph";
public static final String HIV_VL_GRAPH = "pih.app.hiv.vlGraph";
public static final String HIV_OBS_CHART = "pih.app.hiv.obsChart";
public static final String HIV_CONDITION_LIST = "pih.app.hiv.conditionList";
public static final String HIV_VISIT_SUMMARY = "pih.app.hiv.visitSummary";
public static final String HIV_LAST_VITALS = "pih.app.hiv.lastVitals";
public static final String HIV_DISPENSING = "pih.app.hiv.dispensing";
public static final String PATIENT_DOCUMENTS = "attachments.app.patientDocuments";
public static final String CONDITION_LIST = "coreapps.conditionList";
public static final String ACTIVE_DRUG_ORDERS = "coreapps.activeDrugOrders";
public static final String BLOOD_PRESSURE_GRAPH = "pih.app.bloodPressure.graph";
public static final String BLOOD_PRESSURE_OBS_TABLE = "pih.app.bloodPressure.obsTable";
public static final String ASTHMA_SYMPTOMS_OBS_TABLE = "pih.app.asthma.symptomsObsTable";
public static final String GLUCOSE_GRAPH = "pih.app.glucoseGraph";
public static final String HBA1C_GRAPH = "pih.app.hba1cGraph";
public static final String HEAD_CIRCUMFERENCE_GRAPH = "pih.app.headCircumferenceGraph";
public static final String BMI_GRAPH = "pih.app.bmiGraph";
public static final String ABDOMINAL_CIRCUMFERENCE_GRAPH = "pih.app.abdominalCircumferenceGraph";
public static final String FOOT_EXAM_OBS_TABLE = "pih.app.diabetes.footExamObsTable";
public static final String URINARY_ALBUMIN_OBS_TABLE = "pih.app.diabetes.urinaryAlbuminObsTable";
public static final String ALC_TOBAC_USE_SUMMARY = "pih.app.alcTobacUse.summary";
public static final String CHOLESTEROL_GRAPH = "pih.app.cholesterol.graph";
public static final String PHQ9_GRAPH = "pih.app.phq9.graph";
public static final String GAD7_GRAPH = "pih.app.gad7.graph";
public static final String WHODAS_GRAPH = "pih.app.whodas.graph";
public static final String ZLDSI_GRAPH = "pih.app.zldsi.graph";
public static final String SEIZURE_FREQUENCY_GRAPH = "pih.app.seizure.frequency.graph.title";
public static final String J9_REFERRALS = "pih.app.j9Referrals";
public static final String COVID_LAB_RESULTS = "pih.app.covidLabResults";
public static final String ADD_LAB_RESULTS = "pih.app.addLabResults";
public static final String MANAGE_ACCOUNTS = "emr.account.manageAccounts";
public static final String PRINTER_ADMINISTRATION = "printer.printerAdministration";
public static final String MERGE_PATIENTS = "coreapps.mergePatients";
public static final String FEATURE_TOGGLES = "pih.featureToggles";
public static final String PATIENT_EXPORT = "pih.exportPatients";
public static final String PATIENT_IMPORT = "pih.importPatients";
public static final String ADDITIONAL_IDENTIFIERS = "registrationapp.additionalIdentifiers";
public static final String MOST_RECENT_VITALS = "coreapps.mostRecentVitals";
public static final String MOST_RECENT_REGISTRATION = "coreapps.mostRecentRegistration";
public static final String MOST_RECENT_REGISTRATION_SUMMARY = "coreapps.mostRecentRegistrationSummary";
public static final String MOST_RECENT_REGISTRATION_SOCIAL = "coreapps.mostRecentRegistrationSocial";
public static final String MOST_RECENT_REGISTRATION_EBOLA_SCREENING = "mirebalais.mostRecentRegistrationEbolaScreening";
public static final String MOST_RECENT_REGISTRATION_INSURANCE = "coreapps.mostRecentRegistrationInsurance";
public static final String MOST_RECENT_REGISTRATION_CONTACT = "coreapps.mostRecentRegistrationContact";
public static final String MOST_RECENT_CHECK_IN = "coreapps,mostRecentCheckIn";
public static final String ALLERGY_SUMMARY = "allergyui.allergySummary";
public static final String PATHOLOGY_SUMMARY = "labtrackingapp.labSummary";
public static final String ID_CARD_PRINTING_STATUS = "mirebalais.idCardPrintingStatus";
public static final String BIOMETRICS_SUMMARY = "registrationapp.biometricsSummary";
public static final String LEGACY_MPI = "mirebalais.mpi";
public static final String RADIOLOGY_APP = "radiology.app";
public static final String RADIOLOGY_ORDERS_APP = "radiology.orders.app";
public static final String COHORT_BUILDER_APP = "cohortBuilder.app";
}
public static final class Extensions {
public static final String CHECK_IN_VISIT_ACTION = "pih.checkin.visitAction";
public static final String CHECK_IN_REGISTRATION_ACTION = "pih.checkin.registrationAction";
public static final String VITALS_CAPTURE_VISIT_ACTION = "pih.form.vitals";
public static final String CONSULT_NOTE_VISIT_ACTION = "pih.form.consult";
public static final String ADMISSION_NOTE_VISIT_ACTION = "pih.form.admission";
public static final String DISPENSE_MEDICATION_VISIT_ACTION = "dispensing.form";
public static final String ED_CONSULT_NOTE_VISIT_ACTION = "pih.form.edConsult";
public static final String SURGICAL_NOTE_VISIT_ACTION = "pih.form.surgicalNote";
public static final String ONCOLOGY_CONSULT_NOTE_VISIT_ACTION = "pih.form.oncologyNote";
public static final String ONCOLOGY_INITIAL_VISIT_ACTION = "pih.form.oncologyIntake";
public static final String CHEMOTHERAPY_VISIT_ACTION = "pih.form.chemotherapy";
public static final String LAB_RESULTS_OVERALL_ACTION = "pih.form.labResults";
public static final String NCD_INITIAL_VISIT_ACTION = "pih.form.ncdAdultInitial";
public static final String NCD_FOLLOWUP_VISIT_ACTION = "pih.form.ncdAdultFollowup";
public static final String ECHO_VISIT_ACTION = "pih.form.echoConsult";
public static final String VACCINATION_VISIT_ACTION = "pih.form.vaccination";
public static final String COVID19_INITIAL_VISIT_ACTION = "pih.form.covid19Admission";
public static final String COVID19_FOLLOWUP_VISIT_ACTION = "pih.form.covid19Progress";
public static final String COVID19_DISCHARGE_VISIT_ACTION = "pih.form.covid19Discharge";
public static final String HIV_ZL_INITIAL_VISIT_ACTION = "pih.form.hivZLAdultInitial";
public static final String HIV_ZL_FOLLOWUP_VISIT_ACTION = "pih.form.hivZLAdultFollowup";
public static final String HIV_ZL_DISPENSING_VISIT_ACTION = "pih.form.hivZLDispensing";
public static final String OVC_INITIAL_VISIT_ACTION = "pih.form.ovcInitial";
public static final String OVC_FOLLOWUP_VISIT_ACTION = "pih.form.ovcFollowup";
public static final String TB_INITIAL_VISIT_ACTION = "pih.form.tbInitial";
public static final String HIV_ADULT_INITIAL_VISIT_ACTION = "pih.form.hivAdultInitial";
public static final String HIV_ADULT_FOLLOWUP_VISIT_ACTION = "pih.form.hivAdultFollowup";
public static final String HIV_PEDS_INITIAL_VISIT_ACTION = "pih.form.hivPedsInitial";
public static final String HIV_PEDS_FOLLOWUP_VISIT_ACTION = "pih.form.hivPedsFollowup";
public static final String HIV_ADHERENCE_VISIT_ACTION = "pih.form.hivAdherence";
public static final String MCH_ANC_INTAKE_VISIT_ACTION = "pih.form.ancIntake";
public static final String MCH_ANC_FOLLOWUP_VISIT_ACTION = "pih.form.ancFollowup";
public static final String MCH_PEDS_ACTION = "pih.form.peds";
public static final String MCH_DELIVERY_VISIT_ACTION = "pih.form.delivery";
public static final String OB_GYN_VISIT_ACTION = "pih.form.obGyn";
public static final String MENTAL_HEALTH_VISIT_ACTION = "pih.form.mentalHealth";
public static final String VCT_VISIT_ACTION = "pih.form.vct";
public static final String SOCIO_ECONOMICS_VISIT_ACTION = "pih.form.socioEconomics";
public static final String ORDER_XRAY_VISIT_ACTION = "radiologyapp.orderXray";
public static final String ORDER_CT_VISIT_ACTION = "radiologyapp.orderCT";
public static final String ORDER_ULTRASOUND_VISIT_ACTION = "radiologyapp.orderUS";
public static final String REGISTRATION_SUMMARY_OVERALL_ACTION = "registrationapp.registrationSummary.link";
public static final String PRIMARY_CARE_PEDS_INITIAL_VISIT_ACTION = "pih.primaryCare.pedsInitial";
public static final String PRIMARY_CARE_PEDS_FOLLOWUP_VISIT_ACTION = "pih.primaryCare.pedsFollowup";
public static final String PRIMARY_CARE_ADULT_INITIAL_VISIT_ACTION = "pih.primaryCare.adultInitial";
public static final String PRIMARY_CARE_ADULT_FOLLOWUP_VISIT_ACTION = "pih.primaryCare.adultFollowup";
public static final String ED_TRIAGE_VISIT_ACTION = "edtriageapp.edTriageNote";
public static final String ORDER_LAB_VISIT_ACTION = "labtrackingapp.orderLab";
public static final String CHEMO_ORDERING_VISIT_ACTION = "oncology.orderChemo";
public static final String CHEMO_RECORDING_VISIT_ACTION = "oncology.recordChemo";
public static final String MEXICO_CONSULT_ACTION = "pih.mexicoConsult";
public static final String SIERRA_LEONE_OUTPATIENT_INITIAL_VISIT_ACTION = "pih.sierraLeone.outpatient.initial";
public static final String SIERRA_LEONE_OUTPATIENT_FOLLOWUP_VISIT_ACTION = "pih.sierraLeone.outpatient.followup";
public static final String ADMISSION_FORM_AWAITING_ADMISSION_ACTION = "pih.form.admit";
public static final String DENY_ADMISSION_FORM_AWAITING_ADMISSION_ACTION = "pih.form.deny";
public static final String REQUEST_PAPER_RECORD_OVERALL_ACTION = "paperrecord.requestPaperRecord";
public static final String REQUEST_APPOINTMENT_OVERALL_ACTION = "appointmentschedulingui.requestAppointment";
public static final String SCHEDULE_APPOINTMENT_OVERALL_ACTION = "appointmentschedulingui.scheduleAppointment";
public static final String PRINT_ID_CARD_OVERALL_ACTION = "paperrecord.printIdCardLabel";
public static final String PRINT_PAPER_FORM_LABEL_OVERALL_ACTION = "paperrecord.printPaperFormLabel";
public static final String PRINT_WRISTBAND_OVERALL_ACTION = "pih.wristband.print";
public static final String CREATE_VISIT_OVERALL_ACTION = "coreapps.createVisit";
public static final String CREATE_HIV_VISIT_OVERALL_ACTION = "coreapps.hiv.createVisit";
public static final String CREATE_RETROSPECTIVE_VISIT_OVERALL_ACTION = "coreapps.createRetrospectiveVisit";
public static final String MERGE_VISITS_OVERALL_ACTION = "coreapps.mergeVisits";
public static final String DEATH_CERTIFICATE_OVERALL_ACTION = "pih.haiti.deathCertificate";
public static final String CHART_SEARCH_OVERALL_ACTION = "chartsearch.overallAction";
public static final String PATIENT_DOCUMENTS_OVERALL_ACTION = "attachments.patientDocuments.overallAction";
public static final String ORDER_LABS_OVERALL_ACTION = "orderentryowa.orderLabs";
public static final String VIEW_LABS_OVERALL_ACTION = "labworkflowowa.viewLabs";
public static final String VIEW_GROWTH_CHART_ACTION = "growthchart.viewChart";
public static final String MARK_PATIENT_DEAD_OVERALL_ACTION = "coreapps.markPatientDied";
public static final String PAPER_RECORD_ACTIONS_INCLUDES = "paperrecord.patientDashboard.includes";
public static final String PRINT_WRISTBAND_ACTION_INCLUDES = "pih.wristband.patientDashboard.includes";
public static final String VISIT_ACTIONS_INCLUDES = "coreapps.patientDashboard.includes";
public static final String HIV_DASHBOARD_VISIT_INCLUDES = "pih.hivPatientDashboard.includes";
public static final String RADIOLOGY_TAB = "radiologyapp.tab";
public static final String APPOINTMENTS_TAB = "appointmentschedulingui.tab";
public static final String EDIT_PATIENT_CONTACT_INFO = "registrationapp.editPatientContactInfo";
public static final String EDIT_PATIENT_DEMOGRAPHICS = "registrationapp.editPatientDemographics";
public static final String CLINICIAN_FACING_PATIENT_DASHBOARD = "coreapps.clinicianFacingPatientDashboardApp";
public static final String REGISTER_NEW_PATIENT = "registrationapp.registerNewPatient";
public static final String MERGE_INTO_ANOTHER_PATIENT = "registrationapp.mergePatient";
public static final String PRINT_PAPER_FORM_LABEL = "registrationapp.printPaperFormLabel";
public static final String PRINT_ID_CARD_REGISTRATION_ACTION = "mirebalais.printIdCard";
public static final String VISITS_DASHBOARD = "coreapps.visitsDashboard";
public static final String BIOMETRICS_FIND_PATIENT = "biometrics.findPatient";
public static final String PIH_HEADER_EXTENSION = "pih.header";
public static final String DEATH_CERTIFICATE_HEADER_EXTENSION = "pih.header.deathCertificate";
public static final String REPORTING_AD_HOC_ANALYSIS = "reportingui.dataExports.adHoc";
public static final String ALLERGY_UI_VISIT_NOTE_NEXT_SUPPORT = "allergyui.allergires.visitNoteNextSupport";
// Reports
public static final String REGISTRATION_SUMMARY_BY_AGE_REPORT = "mirebalaisreports.overview.registrationsByAge";
public static final String CHECK_IN_SUMMARY_BY_AGE_REPORT = "mirebalaisreports.overview.checkinsByAge";
public static final String DAILY_INPATIENTS_OVERVIEW_REPORT = "mirebalaisreports.overview.inpatientDaily";
public static final String MONTHLY_INPATIENTS_OVERVIEW_REPORT = "mirebalaisreports.overview.inpatientMonthly";
public static final String NON_CODED_DIAGNOSES_DATA_QUALITY_REPORT = "mirebalaisreports.dataQuality.nonCodedDiagnoses";
public static final String LQAS_DATA_EXPORT = "mirebalaisreports.dataExports.lqasDiagnoses";
}
public static final class ExtensionPoints {
public static final String OVERALL_ACTIONS = "patientDashboard.overallActions";
public static final String OVERALL_REGISTRATION_ACTIONS = "registrationSummary.overallActions";
public static final String VISIT_ACTIONS = "patientDashboard.visitActions";
public static final String AWAITING_ADMISSION_ACTIONS = "coreapps.app.awaitingAdmissionActions";
public static final String ENCOUNTER_TEMPLATE = "org.openmrs.referenceapplication.encounterTemplate";
public static final String HOME_PAGE = "org.openmrs.referenceapplication.homepageLink";
public static final String PROGRAM_SUMMARY_LIST = Apps.PROGRAM_SUMMARY_LIST + ".apps";
public static final String DEATH_INFO_HEADER = "patientHeader.deathInfo";
public static final String DASHBOARD_TAB = "patientDashboard.tabs";
public static final String DASHBOARD_INCLUDE_FRAGMENTS = "patientDashboard.includeFragments";
public static final String SYSTEM_ADMINISTRATION_PAGE = "systemAdministration.apps";
public static final String REPORTING_DATA_EXPORT = "org.openmrs.module.reportingui.reports.dataexport";
public static final String REPORTING_OVERVIEW_REPORTS = "org.openmrs.module.reportingui.reports.overview";
public static final String REPORTING_DATA_QUALITY = "org.openmrs.module.reportingui.reports.dataquality";
public static final String REPORTING_MONITORING = "org.openmrs.module.reportingui.reports.monitoring";
public static final String PATIENT_HEADER_PATIENT_CONTACT_INFO = "patientHeader.editPatientContactInfo";
public static final String PATIENT_HEADER_PATIENT_DEMOGRAPHICS = "patientHeader.editPatientDemographics";
public static final String CLINICIAN_DASHBOARD_FIRST_COLUMN = "patientDashboard.firstColumnFragments";
public static final String CLINICIAN_DASHBOARD_SECOND_COLUMN = "patientDashboard.secondColumnFragments";
public static final String REGISTRATION_SUMMARY_CONTENT = "registrationSummary.contentFragments";
public static final String REGISTRATION_SUMMARY_SECOND_COLUMN_CONTENT = "registrationSummary.secondColumnContentFragments";
public static final String REGISTRATION_FIND_PATIENT_FRAGMENTS = RegistrationAppConstants.FIND_PATIENT_FRAGMENTS_EXTENSION_POINT;
public static final String ALLERGIES_PAGE_INCLUDE_PAGE = AllergyUIConstants.ALLERGIES_PAGE_INCLUDE_FRAGMENT_EXTENSION_POINT;
public static final String PATIENT_SEARCH = "coreapps.patientSearch.extension";
}
// TODO are these still used once we switch to the new visit dashboard?
public static final class EncounterTemplates {
public static final String DEFAULT = "defaultEncounterTemplate";
public static final String CONSULT = "consultEncounterTemplate";
public static final String NO_DETAILS = "noDetailsEncounterTemplate";
public static final String ED_TRIAGE = "edtriageEncounterTemplate";
}
// order of lists define the order apps and extensions appear
public static final List<String> HOME_PAGE_APPS_ORDER = Arrays.asList(
Apps.ACTIVE_VISITS,
Apps.PATIENT_REGISTRATION,
Apps.CHECK_IN,
Apps.AWAITING_ADMISSION,
Apps.UHM_VITALS,
Apps.VITALS,
Apps.WAITING_FOR_CONSULT,
Apps.TODAYS_VISITS,
Apps.APPOINTMENT_SCHEDULING_HOME,
Apps.ARCHIVES_ROOM,
Apps.INPATIENTS,
Apps.HIV_DISPENSING,
Apps.LABS,
Apps.PATHOLOGY_TRACKING,
Apps.ADD_LAB_RESULTS,
Apps.PROGRAM_SUMMARY_LIST,
Apps.REPORTS,
Apps.DISPENSING,
Apps.ED_TRIAGE,
Apps.ED_TRIAGE_QUEUE,
Apps.CHW_MGMT,
Apps.COHORT_BUILDER_APP,
Apps.J9_REFERRALS,
Apps.LEGACY_MPI,
Apps.MY_ACCOUNT,
Apps.SYSTEM_ADMINISTRATION);
// The idiosyncratic ordering of these items is due to the fact that the ones used
// in English and French -speaking places are alphebetized in English and the ones
// used in Spanish-speaking places are alphebetized in Spanish.
public static final List<String> PROGRAM_SUMMARY_LIST_APPS_ORDER = Arrays.asList(
"pih.app." + AsthmaProgram.ASTHMA.uuid() + ".programSummary.dashboard",
"pih.app." + MalnutritionProgram.MALNUTRITION.uuid() + ".programSummary.dashboard",
"pih.app." + DiabetesProgram.DIABETES.uuid() + ".programSummary.dashboard",
"pih.app." + EpilepsyProgram.EPILEPSY.uuid() + ".programSummary.dashboard",
"pih.app." + HIVProgram.HIV.uuid() + ".programSummary.dashboard",
"pih.app." + HypertensionProgram.HYPERTENSION.uuid() + ".programSummary.dashboard",
"pih.app." + ANCProgram.ANC.uuid() + ".programSummary.dashboard",
"pih.app." + MCHProgram.MCH.uuid() + ".programSummary.dashboard",
"pih.app." + MentalHealthProgram.MENTAL_HEALTH.uuid() + ".programSummary.dashboard",
"pih.app." + NCDProgram.NCD.uuid() + ".programSummary.dashboard",
"pih.app." + OncologyProgram.ONCOLOGY.uuid() + ".programSummary.dashboard",
"pih.app." + Covid19Program.COVID19.uuid() + ".programSummary.dashboard",
"pih.app." + ZikaProgram.ZIKA.uuid() + ".programSummary.dashboard"
);
public static final List<String> SYSTEM_ADMINISTRATION_APPS_ORDER = Arrays.asList(
Apps.MANAGE_ACCOUNTS,
Apps.PRINTER_ADMINISTRATION,
Apps.MERGE_PATIENTS,
Apps.FEATURE_TOGGLES);
public static final List<String> OVERALL_ACTIONS_ORDER = Arrays.asList(
Extensions.CREATE_VISIT_OVERALL_ACTION,
Extensions.CREATE_RETROSPECTIVE_VISIT_OVERALL_ACTION,
Extensions.VIEW_GROWTH_CHART_ACTION,
Extensions.ORDER_LABS_OVERALL_ACTION,
Extensions.VIEW_LABS_OVERALL_ACTION,
Extensions.LAB_RESULTS_OVERALL_ACTION,
Extensions.REQUEST_PAPER_RECORD_OVERALL_ACTION,
Extensions.PRINT_PAPER_FORM_LABEL_OVERALL_ACTION,
Extensions.PRINT_ID_CARD_OVERALL_ACTION,
Extensions.PRINT_WRISTBAND_OVERALL_ACTION,
Extensions.REQUEST_APPOINTMENT_OVERALL_ACTION,
Extensions.SCHEDULE_APPOINTMENT_OVERALL_ACTION,
Extensions.MERGE_VISITS_OVERALL_ACTION,
Extensions.REGISTRATION_SUMMARY_OVERALL_ACTION,
Extensions.DEATH_CERTIFICATE_OVERALL_ACTION,
Extensions.PATIENT_DOCUMENTS_OVERALL_ACTION,
Extensions.CHEMO_ORDERING_VISIT_ACTION,
Extensions.EDIT_PATIENT_DEMOGRAPHICS,
Extensions.EDIT_PATIENT_CONTACT_INFO,
Extensions.CHART_SEARCH_OVERALL_ACTION,
Extensions.MARK_PATIENT_DEAD_OVERALL_ACTION); // TODO remember to permission chart search in Custom App Loader Factory
public static final List<String> VISIT_ACTIONS_ORDER = Arrays.asList(
Extensions.CHECK_IN_VISIT_ACTION,
Extensions.VITALS_CAPTURE_VISIT_ACTION,
Extensions.CONSULT_NOTE_VISIT_ACTION,
Extensions.MEXICO_CONSULT_ACTION,
Extensions.ADMISSION_NOTE_VISIT_ACTION, // ToDo: Don't think this is in use from action list
Extensions.PRIMARY_CARE_ADULT_INITIAL_VISIT_ACTION,
Extensions.PRIMARY_CARE_ADULT_FOLLOWUP_VISIT_ACTION,
Extensions.PRIMARY_CARE_PEDS_INITIAL_VISIT_ACTION,
Extensions.PRIMARY_CARE_PEDS_FOLLOWUP_VISIT_ACTION,
Extensions.VACCINATION_VISIT_ACTION,
Extensions.ED_TRIAGE_VISIT_ACTION,
Extensions.ED_CONSULT_NOTE_VISIT_ACTION,
Extensions.DISPENSE_MEDICATION_VISIT_ACTION,
Extensions.SURGICAL_NOTE_VISIT_ACTION,
Extensions.NCD_INITIAL_VISIT_ACTION,
Extensions.NCD_FOLLOWUP_VISIT_ACTION,
Extensions.ECHO_VISIT_ACTION,
Extensions.MCH_ANC_INTAKE_VISIT_ACTION,
Extensions.MCH_ANC_FOLLOWUP_VISIT_ACTION,
Extensions.MCH_DELIVERY_VISIT_ACTION,
Extensions.OB_GYN_VISIT_ACTION,
Extensions.MENTAL_HEALTH_VISIT_ACTION,
Extensions.SOCIO_ECONOMICS_VISIT_ACTION,
Extensions.VCT_VISIT_ACTION,
Extensions.HIV_ZL_INITIAL_VISIT_ACTION,
Extensions.HIV_ZL_FOLLOWUP_VISIT_ACTION,
Extensions.HIV_ZL_DISPENSING_VISIT_ACTION,
Extensions.HIV_ADHERENCE_VISIT_ACTION,
Extensions.ONCOLOGY_CONSULT_NOTE_VISIT_ACTION,
Extensions.ONCOLOGY_INITIAL_VISIT_ACTION,
Extensions.CHEMOTHERAPY_VISIT_ACTION,
Extensions.CHEMO_RECORDING_VISIT_ACTION,
Extensions.COVID19_INITIAL_VISIT_ACTION,
Extensions.COVID19_FOLLOWUP_VISIT_ACTION,
Extensions.COVID19_DISCHARGE_VISIT_ACTION,
Extensions.ORDER_XRAY_VISIT_ACTION,
Extensions.ORDER_CT_VISIT_ACTION,
Extensions.ORDER_ULTRASOUND_VISIT_ACTION,
Extensions.ORDER_LAB_VISIT_ACTION);
public static final List<String> HIV_VISIT_ACTIONS_ORDER = Arrays.asList(
Extensions.HIV_ZL_INITIAL_VISIT_ACTION + ".hiv",
Extensions.HIV_ZL_FOLLOWUP_VISIT_ACTION + ".hiv",
Extensions.HIV_ZL_DISPENSING_VISIT_ACTION + ".hiv",
Extensions.VITALS_CAPTURE_VISIT_ACTION + ".hiv");
public static final List<String> ONCOLOGY_VISIT_ACTIONS_ORDER = Arrays.asList(
Extensions.CHEMO_RECORDING_VISIT_ACTION + "oncology"
);
public static final List<String> ONCOLOGY_OVERALL_ACTIONS_ORDER = Arrays.asList(
Extensions.CHEMO_ORDERING_VISIT_ACTION + ".oncology"
);
public static final List<String> AWAITING_ADMISSION_ACTIONS_ORDER = Arrays.asList(
Extensions.ADMISSION_FORM_AWAITING_ADMISSION_ACTION,
Extensions.DENY_ADMISSION_FORM_AWAITING_ADMISSION_ACTION);
public static final List<String> CLINICIAN_DASHBOARD_FIRST_COLUMN_ORDER = Arrays.asList(
Apps.CONDITION_LIST,
Apps.VISITS_SUMMARY,
Apps.HOME_VISITS_SUMMARY,
Apps.COVID_LAB_RESULTS,
Apps.APPOINTMENT_SCHEDULING_HOME,
Apps.PROVIDER_RELATIONSHIPS_CLINICAL_SUMMARY,
Apps.RADIOLOGY_APP,
Apps.RADIOLOGY_ORDERS_APP,
Apps.BMI_GRAPH + ExtensionPoints.CLINICIAN_DASHBOARD_FIRST_COLUMN,
Apps.VITALS_SUMMARY,
Apps.DISPENSING_SUMMARY
);
public static final List<String> CLINICIAN_DASHBOARD_SECOND_COLUMN_ORDER = Arrays.asList(
Apps.ALLERGY_SUMMARY,
Apps.MOST_RECENT_VITALS,
Apps.PATHOLOGY_SUMMARY,
Apps.PROGRAMS_LIST,
Apps.PATIENT_DOCUMENTS,
Apps.RELATIONSHIPS_CLINICAL_SUMMARY,
Apps.MOST_RECENT_REGISTRATION,
Apps.ACTIVE_DRUG_ORDERS);
public static final List<String> REGISTRATION_SUMMARY_FIRST_COLUMN_ORDER = Arrays.asList(
Apps.MOST_RECENT_REGISTRATION_SUMMARY,
Apps.MOST_RECENT_REGISTRATION_INSURANCE,
Apps.MOST_RECENT_REGISTRATION_SOCIAL
);
public static final List<String> REGISTRATION_SUMMARY_SECOND_COLUMN_ORDER = Arrays.asList(
Apps.ADDITIONAL_IDENTIFIERS,
Apps.MOST_RECENT_REGISTRATION_CONTACT,
Apps.BIOMETRICS_SUMMARY,
Apps.PROVIDER_RELATIONSHIPS_REGISTRATION_SUMMARY,
Apps.RELATIONSHIPS_REGISTRATION_SUMMARY,
Apps.MOST_RECENT_CHECK_IN,
Apps.ID_CARD_PRINTING_STATUS
);
public static final Map<String, List<String>> PROGRAM_DASHBOARD_FIRST_COLUMN_ORDER;
static {
Map<String, List<String>> PROGRAM_DASHBOARD_FIRST_COLUMN_ORDER_TEMP = new HashMap<String, List<String>>();
PROGRAM_DASHBOARD_FIRST_COLUMN_ORDER_TEMP.put(HIVProgram.HIV.uuid(),
Arrays.asList(
// ToDo: Move Program enrollment is first?
"pih.app." + HIVProgram.HIV.uuid() + "patientProgramSummary",
"pih.app." + HIVProgram.HIV.uuid() + ".patientProgramHistory",
Apps.HIV_SUMMARY,
Apps.HIV_VL_GRAPH,
// Add Meds
Apps.HIV_OBS_CHART
));
PROGRAM_DASHBOARD_FIRST_COLUMN_ORDER = Collections.unmodifiableMap(PROGRAM_DASHBOARD_FIRST_COLUMN_ORDER_TEMP);
}
public static final Map<String, List<String>> PROGRAM_DASHBOARD_SECOND_COLUMN_ORDER;
static {
Map<String, List<String>> PROGRAM_DASHBOARD_SECOND_COLUMN_ORDER_TEMP = new HashMap<String, List<String>>();
PROGRAM_DASHBOARD_SECOND_COLUMN_ORDER_TEMP.put(HIVProgram.HIV.uuid(),
Arrays.asList(
Apps.HIV_ALERTS,
Apps.CONDITION_LIST,
// Add Apps.LAB_SUMMARY
// Apps.HIV_CD4_GRAPH,
Apps.HIV_VISIT_SUMMARY,
Apps.BMI_GRAPH,
// Adverse events & allergies
Apps.ALLERGY_SUMMARY,
Apps.HIV_LAST_VITALS
));
PROGRAM_DASHBOARD_SECOND_COLUMN_ORDER = Collections.unmodifiableMap(PROGRAM_DASHBOARD_SECOND_COLUMN_ORDER_TEMP);
}
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.util.concurrent;
import reactor.core.publisher.Mono;
/**
* Adapts a {@link Mono} into a {@link ListenableFuture} by obtaining a
* {@code CompletableFuture} from the {@code Mono} via {@link Mono#toFuture()}
* and then adapting it with {@link CompletableToListenableFutureAdapter}.
*
* @author Rossen Stoyanchev
* @author Stephane Maldini
* @since 5.1
* @param <T> the object type
* @deprecated as of 6.0, in favor of {@link Mono#toFuture()}
*/
@Deprecated(since = "6.0")
public class MonoToListenableFutureAdapter<T> extends CompletableToListenableFutureAdapter<T> {
public MonoToListenableFutureAdapter(Mono<T> mono) {
super(mono.toFuture());
}
}
|
package com.javawebtutor;
import java.util.ArrayList;
import java.util.List;
import com.javawebtutor.Entities.Firma;
import com.javawebtutor.Entities.Ugovor;
public interface AdministracijaService {
public void noviUgovor(Ugovor u);
public List<Ugovor> vratiSveUgovore(Firma f);
public Ugovor vratiUgovor(int id);
public void obrisiUgovor(int id);
public void obrisiSveUgovore(Firma f);
}
|
package com.openfeint.game.archaeology.message;
import com.openfeint.game.message.GenericMessage;
public class SandStormMessage extends GenericMessage {
/**
* @param playerId. id of the player who found the sand storm card
*/
public SandStormMessage(String playerId) {
setFrom(playerId);
}
}
|
package cn.swsk.rgyxtqapp;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import cn.swsk.rgyxtqapp.custom.ProgressDialog;
import cn.swsk.rgyxtqapp.utils.CommonUtils;
import cn.swsk.rgyxtqapp.utils.HttpUtils;
import cn.swsk.rgyxtqapp.utils.JsonTools;
import cn.swsk.rgyxtqapp.utils.NetworkUtils;
import cn.swsk.rgyxtqapp.utils.PushUtils;
import cn.swsk.rgyxtqapp.utils.UpdateManager;
public class LoginActivity extends Activity {
private EditText txt_userName, txt_password;
private CheckBox remenber_pwd, auto_login;
private Button btn_login, btn_cancle;
private String userNameValue, passwordValue;
private SharedPreferences sharedPreferences;
private int setCheckNum = 0; //设置按钮点击次数
private ProgressDialog dialog = null; //等待状态提示框
@Override
protected void onResume() {
super.onResume();
CommonUtils.log(UpdateManager.updating+"");
// 检查软件更新
if(NetworkUtils.isNetworkAvailable(this)) {
UpdateManager manager = new UpdateManager(LoginActivity.this);
manager.checkUpdate(false, this);
}else{
Toast.makeText(this,"网络不可用",Toast.LENGTH_SHORT).show();
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
init();
UpdateManager.updating=false;
//如果服务端IP为空时设置默认地址
String ipStr = PushUtils.getServerIPText(this);
if("".equals(ipStr)) {
ipStr = "61.154.9.242:5551";
PushUtils.setServerIPText(LoginActivity.this, ipStr);
}
//获取实例对象
sharedPreferences = this.getSharedPreferences("userInfo", 1);
txt_userName = (EditText) findViewById(R.id.et_userName);
txt_password = (EditText) findViewById(R.id.et_password);
remenber_pwd = (CheckBox) findViewById(R.id.cb_remenber);
auto_login = (CheckBox) findViewById(R.id.cb_auto);
btn_login = (Button) findViewById(R.id.btn_login);
ImageButton btn_settings = (ImageButton) findViewById(R.id.btn_settings);
btn_settings.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setCheckNum++;
if(setCheckNum >= 5) {
setCheckNum = 0;
Intent intent = new Intent();
intent.setClass(LoginActivity.this, SettingsActivity.class);
intent.putExtra("title", "设置");
startActivity(intent);
}
}
});
//判断记住密码多选框的状态
if (sharedPreferences.getBoolean("REMENBER_ISCHECK", false)) {
//设置默认是记录密码状态
remenber_pwd.setChecked(true);
txt_userName.setText(sharedPreferences.getString("USER_NAME", ""));
txt_password.setText(sharedPreferences.getString("PASSWORD", ""));
//判断自动登陆多选框状态
if (sharedPreferences.getBoolean("AUTO_ISCHECK", false)) {
//设置默认是自动登录状态
auto_login.setChecked(true);
//跳转界面
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
LoginActivity.this.startActivity(intent);
}
}
class TomAsyncTask extends AsyncTask<String, Void, Map<String, Object>> {
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog.showDialog();
}
@Override
protected void onPostExecute(Map<String, Object> stringObjectMap) {
dialog.cancelDialog();//关闭ProgressDialog
if(stringObjectMap == null){
Toast.makeText(LoginActivity.this, "无法连接到服务器!", Toast.LENGTH_LONG).show();
return;
}
//获取状态值
String status = stringObjectMap.containsKey("status")?stringObjectMap.get("status").toString() : "";
if ("1".equals(status)) {
PushUtils.token =stringObjectMap.get("token").toString();
Map<String, Object> userInfoMap = ((Map<String, Object>)stringObjectMap.get("userInfo"));
PushUtils.userId = userInfoMap.get("ID").toString();
PushUtils.userName= userInfoMap.get("NAME").toString();
PushUtils.userUnit= userInfoMap.get("BELONGS_UNIT").toString();
PushUtils.sysTitle= userInfoMap.get("TITLE").toString();
if(userInfoMap.containsKey("TERMINAL_PHONE") && userInfoMap.get("TERMINAL_PHONE") != null){
PushUtils.terminalPhone = userInfoMap.get("TERMINAL_PHONE").toString();
}else{
PushUtils.terminalPhone = "";
}
if (PushUtils.getServerIPText(LoginActivity.this) == "") {
PushUtils.setServerIPText(LoginActivity.this, "192.168.1.129:8080");
}
//Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
//登录成功和记住密码框为选中状态才保存用户信息
if (remenber_pwd.isChecked()) {
//记住用户名、密码、
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("USER_NAME", txt_userName.getText().toString());
editor.putString("PASSWORD", txt_password.getText().toString());
editor.putString("FILL_UNITS", passwordValue);
editor.commit();
}
PushUtils.setWareHouse(null);
Intent intent=null;
//跳转界面
intent = new Intent(LoginActivity.this, MenuActivity.class);
startActivity(intent);
//将当前Activity移出栈
finish();
}else if("00".equals(status)){
PushUtils.token =stringObjectMap.get("token").toString();
Map<String, Object> userInfoMap = ((Map<String, Object>)stringObjectMap.get("userInfo"));
PushUtils.userId = userInfoMap.get("ID").toString();
PushUtils.userName= userInfoMap.get("NAME").toString();
PushUtils.setWareHouse(stringObjectMap.get("wareHouse"));
// PushUtils.userUnit= userInfoMap.get("BELONGS_UNIT").toString();
// PushUtils.sysTitle= userInfoMap.get("TITLE").toString();
if(userInfoMap.containsKey("TERMINAL_PHONE") && userInfoMap.get("TERMINAL_PHONE") != null){
PushUtils.terminalPhone = userInfoMap.get("TERMINAL_PHONE").toString();
}else{
PushUtils.terminalPhone = "";
}
if (PushUtils.getServerIPText(LoginActivity.this) == "") {
PushUtils.setServerIPText(LoginActivity.this, "192.168.1.129:8080");
}
//Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
//登录成功和记住密码框为选中状态才保存用户信息
if (remenber_pwd.isChecked()) {
//记住用户名、密码、
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("USER_NAME", txt_userName.getText().toString());
editor.putString("PASSWORD", txt_password.getText().toString());
editor.putString("FILL_UNITS", passwordValue);
editor.commit();
}
Intent intent=null;
intent=new Intent(LoginActivity.this,SafeManagerActivity.class);
intent.putExtra("title", "安全管理");
intent.putExtra("root", true);
startActivity(intent);
//将当前Activity移出栈
finish();
} else if("2".equals(status)) {
Toast.makeText(LoginActivity.this, stringObjectMap.get("errmsg").toString(), Toast.LENGTH_LONG).show();
} else if("9999".equals(status)) {
Toast.makeText(LoginActivity.this, stringObjectMap.get("errmsg").toString(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(LoginActivity.this, "未知错误!", Toast.LENGTH_LONG).show();
}
}
@Override
protected Map<String, Object> doInBackground(String... params) {
String path = params[0];
String jsonString1 = HttpUtils.getJsonContent(path);
if (jsonString1 == null) {
return null;
}
Map<String, Object> map = JsonTools.getMap(jsonString1);
return map;
}
}
//登录监听事件,现在默认用户admin,密码123
btn_login.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
if ("".equals(txt_userName.getText().toString())){
Toast.makeText(LoginActivity.this, "请输入账号", Toast.LENGTH_LONG).show();
return;
}
if ("".equals(txt_password.getText().toString())){
Toast.makeText(LoginActivity.this, "请输入密码!", Toast.LENGTH_LONG).show();
return;
}
boolean isHas = NetworkUtils.isNetworkAvailable(LoginActivity.this);
if (isHas == false) {
Toast.makeText(LoginActivity.this, "网络未打开,请检查网络。", Toast.LENGTH_SHORT).show();
return;
}
if (PushUtils.getServerIPText(LoginActivity.this) == "") {
Toast.makeText(LoginActivity.this, "服务IP和端口为空!请重新设置", Toast.LENGTH_SHORT).show();
return;
}
try {
userNameValue = URLEncoder.encode(txt_userName.getText().toString(), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
passwordValue = txt_password.getText().toString();
String PATH = "http://" + PushUtils.getServerIPText(LoginActivity.this) + "/rgyx/appUser/login";
String path = PATH + "?name=" + userNameValue + "&password=" + passwordValue;
new TomAsyncTask().execute(path);
}
}
);
//监听记住密码多选框按钮事件
remenber_pwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (remenber_pwd.isChecked()) {
System.out.println("记住密码已选中");
sharedPreferences.edit().putBoolean("REMENBER_ISCHECK", true).commit();
} else {
System.out.println("记住密码没有选中");
sharedPreferences.edit().putBoolean("REMENBER_ISCHECK", false).commit();
}
}
});
//监听自动登录多选框事件
auto_login.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (auto_login.isChecked()) {
System.out.println("自动登录已选中");
sharedPreferences.edit().putBoolean("AUTO_ISCHECK", true).commit();
} else {
System.out.println("自动登录没有选中");
sharedPreferences.edit().putBoolean("AUTO_ISCHECK", false).commit();
}
}
});
}
/**
* 初始化
*/
private void init(){
dialog = new ProgressDialog(LoginActivity.this);
}
}
|
package Utils;
import java.util.ArrayList;
public class UserItermC {
private int id;
private ArrayList<Item> set ;
public UserItermC(int id, ArrayList<Item> set) {
this.id = id;
this.set = set;
}
public ArrayList<Item> getSet(){
return set;
}
public void setSet(ArrayList<Item> set){
this.set = set;
}
}
|
package matthbo.mods.darkworld.block;
import matthbo.mods.darkworld.init.ModBlocks;
import matthbo.mods.darkworld.init.ModItems;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.state.BlockState;
import net.minecraft.block.state.IBlockState;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import java.util.List;
import java.util.Random;
public class BlockDarkLeaves extends BlockLeavesDarkWorld {
public BlockDarkLeaves(){
super();
this.setUnlocalizedName("darkleaves");
this.setDefaultState(this.blockState.getBaseState().withProperty(CHECK_DECAY, Boolean.valueOf(true)).withProperty(DECAYABLE, Boolean.valueOf(true)));
}
public Item getItemDropped(IBlockState state_, Random rand, int fortune)
{
return Item.getItemFromBlock(ModBlocks.darkSapling);
}
protected void dropApple(World worldIn, BlockPos pos, IBlockState state, int chance)
{
if (worldIn.rand.nextInt(chance) == 0)
{
spawnAsEntity(worldIn, pos, new ItemStack(ModItems.darkApple, 1, 0));
}
}
protected int func_150123_b(int p_150123_1_)
{
int j = super.func_150123_b(p_150123_1_);
if ((p_150123_1_ & 3) == 3)
{
j = 40;
}
return j;
}
public BlockDarkPlanks.EnumType getDarkWoodType(int meta)
{
return BlockDarkPlanks.EnumType.byMetadata((meta & 3) % 4);
}
@Override
public List<ItemStack> onSheared(ItemStack item, IBlockAccess world, BlockPos pos, int fortune)
{
IBlockState state = world.getBlockState(pos);
return new java.util.ArrayList(java.util.Arrays.asList(new ItemStack(this, 1, 0)));
}
public IBlockState getStateFromMeta(int meta)
{
return this.getDefaultState().withProperty(DECAYABLE, Boolean.valueOf((meta & 4) == 0)).withProperty(CHECK_DECAY, Boolean.valueOf((meta & 8) > 0));
}
public int getMetaFromState(IBlockState state)
{
byte b0 = 0;
int i = b0;
if (!((Boolean)state.getValue(DECAYABLE)).booleanValue())
{
i |= 4;
}
if (((Boolean)state.getValue(CHECK_DECAY)).booleanValue())
{
i |= 8;
}
return i;
}
protected BlockState createBlockState()
{
return new BlockState(this, new IProperty[] {CHECK_DECAY, DECAYABLE});
}
}
|
package br.com.mixfiscal.prodspedxnfe.domain.own;
import java.io.Serializable;
import java.util.Objects;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name = "fornecedor")
public class Fornecedor implements Serializable {
private static final long serialVersionUID = 3178510431626738850L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_fornecedor")
private Integer id;
@Column(name = "nome")
private String nome;
@Column(name = "cnpj")
private String cnpj;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "fornecedor")
private Set<RelacaoProdutoFornecedor> produtosDeEmpresas;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCnpj() {
return cnpj;
}
public void setCnpj(String cnpj) {
this.cnpj = cnpj;
}
public Set<RelacaoProdutoFornecedor> getProdutosDeEmpresas() {
return produtosDeEmpresas;
}
public void setProdutosDeEmpresas(Set<RelacaoProdutoFornecedor> produtosDeEmpresas) {
this.produtosDeEmpresas = produtosDeEmpresas;
}
@Override
public int hashCode() {
int hash = 3;
hash = 71 * hash + Objects.hashCode(this.id);
hash = 71 * hash + Objects.hashCode(this.nome);
hash = 71 * hash + Objects.hashCode(this.cnpj);
hash = 71 * hash + Objects.hashCode(this.produtosDeEmpresas);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Fornecedor other = (Fornecedor) obj;
if (!Objects.equals(this.nome, other.nome)) {
return false;
}
if (!Objects.equals(this.cnpj, other.cnpj)) {
return false;
}
if (!Objects.equals(this.id, other.id)) {
return false;
}
if (!Objects.equals(this.produtosDeEmpresas, other.produtosDeEmpresas)) {
return false;
}
return true;
}
}
|
/**
*
*/
package com.zh.common.utils;
/**
* @author ZH
*
*/
public class Base64 {
@SuppressWarnings("restriction")
public static String getBase64(String s) {
if (s == null)
return null;
return (new sun.misc.BASE64Encoder()).encode(s.getBytes());
}
@SuppressWarnings("restriction")
public static String getFromBase64(String s) {
if (s == null) return null;
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
try {
byte[] b = decoder.decodeBuffer(s);
return new String(b);
} catch (Exception e) {
return "Error";
}
}
}
|
package src.modulo8.complementos;
import java.io.*;
import java.nio.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.color.ColorSpace;
import java.awt.geom.AffineTransform;
import javax.media.opengl.*;
class Imaging {
//////////////// Variables /////////////////////////
final String defaultImageFilename =
new String("duke_wave.gif");
final String defaultFrameImageFilename =
new String("frame.png");
// Databuffer that holds the loaded image.
byte[] imgRGBA = null;
// Image size retrieved durung loading,
// re-used when image is drawn.
int imgHeight;
int imgWidth;
// To copy the content of the current frame.
int frameWidth;
int frameHeight;
///////////////// Functions /////////////////////////
public Imaging() {}
public void init( int width, int height )
{
frameWidth = width;
frameHeight = height;
File outputFile = new File( defaultFrameImageFilename );
if( outputFile.exists() ) { outputFile.delete(); }
}
///////////// load Image ////////////////////////////////////
// Format: int[] of pixels from a Java
// image with BufferedImage.getRGB()
// returns data in Java's default ARGB format, meaning
// the 32-bit ints are packed with 8 bits each of alpha
// mask (translucency): red, green, and blue, in that
// order. GL does not define a constant for this color
// model.
//
// Moreover, the use of int is potentially hazardous on
// machines with "little-endian" architectures, such as
// Intel x86 CPUs. In the "little-endian" world, the least
// significant 16 bits of a 32-bit integer come first,
// followed by the most significant 16 bits. It is not a
// problem when we are entirely in Java, but when we pass
// such an array from Java to the native OpenGL, the
// endianness can turn what we thought was ARGB into GBAR,
// meaning our colors and transparency get scrambled.
//
// One more problem: OpenGL puts (0,0) at the bottom
// left. Java images have (0,0) at the upper left, what
// makes the image look upside down in the OpenGL world.
//
// To provide glDrawPixels() with a suitable array,
// we need to do the following:
// 1. Convert to a color model that OpenGL understands.
// 2. Use a byte array to keep the color values
// properly arranged.
// 3. Flip the image vertically so that the row order
// puts the bottom of the image on the first row.
//
// to flip the image, we define an AffineTransform that
// moves the image into negative y coefficients, then
// scales the pixels into a reverse ordering by
// multiplying their y coefficients by -1, which also
// moves them back into positive values. This
// transformation is applied to the BufferedImage
// offscreen Graphics2D, and the image is drawn into the
// Graphics2D, picking up the transformation in the
// process.
//
// Objects in the Processing chain:
// img -> bufImg(raster, colorModel) -> imgBuf -> imgRGBA
//
public void loadImage( String filename )
{
// Load image and get height and width for raster.
//
if( filename == null ) {
filename = new String( defaultImageFilename );
}
Image img = Toolkit.getDefaultToolkit().createImage( filename );
MediaTracker tracker = new MediaTracker(new Canvas());
tracker.addImage ( img, 0 );
try {
//Starts loading all images tracked by
// this media tracker (wait max para ms).
tracker.waitForAll( 1000 );
} catch (InterruptedException ie) {
System.out.println("MediaTracker Exception");
}
imgHeight = img.getHeight(null);
imgWidth = img.getWidth(null);
System.out.println( "Image, width=" + imgWidth +
", height=" + imgHeight ); //ddd
// Create a raster with correct size,
// and a colorModel and finally a bufImg.
//
WritableRaster raster = Raster.createInterleavedRaster( DataBuffer.TYPE_BYTE, imgWidth, imgHeight,4, null );
ComponentColorModel colorModel = new ComponentColorModel( ColorSpace.getInstance(ColorSpace.CS_sRGB),
new int[] {8,8,8,8},
true,
false,
ComponentColorModel.TRANSLUCENT,
DataBuffer.TYPE_BYTE );
BufferedImage bufImg = new BufferedImage (colorModel, // color model
raster,
false, // isRasterPremultiplied
null); // properties
// Filter img into bufImg and perform
// Coordinate Transformations on the way.
//
Graphics2D g = bufImg.createGraphics();
AffineTransform gt = new AffineTransform();
gt.translate (0, imgHeight);
gt.scale (1, -1d);
g.transform ( gt );
g.drawImage ( img, null, null );
// Retrieve underlying byte array (imgBuf)
// from bufImg.
DataBufferByte imgBuf = (DataBufferByte)raster.getDataBuffer();
imgRGBA = imgBuf.getData();
g.dispose();
}
///////////// save Image ///////////////////////////////
private ByteBuffer getFrameData( GL gl,
ByteBuffer pixelsRGB )
{
// Read Frame back into our ByteBuffer.
gl.glReadBuffer( GL.GL_BACK );
gl.glPixelStorei( GL.GL_PACK_ALIGNMENT, 1 );
gl.glReadPixels( 0, 0, frameWidth, frameHeight,
GL.GL_RGB, GL.GL_UNSIGNED_BYTE,
pixelsRGB );
return pixelsRGB;
}
private BufferedImage copyFrame( GL gl )
{
// Create a ByteBuffer to hold the frame data.
java.nio.ByteBuffer pixelsRGB =
//BufferUtils.newByteBuffer
ByteBuffer.allocateDirect
( frameWidth * frameHeight * 3 );
// Get date from frame as ByteBuffer.
getFrameData( gl, pixelsRGB );
return transformPixelsRGBBuffer2ARGB_ByHand
( pixelsRGB );
}
// Copies the Frame to an integer array.
// Do the necessary conversion by hand.
//
private BufferedImage transformPixelsRGBBuffer2ARGB_ByHand
( ByteBuffer pixelsRGB)
{
// Transform the ByteBuffer and get it as pixeldata.
int[] pixelInts = new int[ frameWidth * frameHeight ];
// Convert RGB bytes to ARGB ints with no transparency.
// Flip image vertically by reading the
// rows of pixels in the byte buffer in reverse
// - (0,0) is at bottom left in OpenGL.
//
// Points to first byte (red) in each row.
int p = frameWidth * frameHeight * 3;
int q; // Index into ByteBuffer
int i = 0; // Index into target int[]
int w3 = frameWidth * 3; // Number of bytes in each row
for (int row = 0; row < frameHeight; row++) {
p -= w3;
q = p;
for (int col = 0; col < frameWidth; col++) {
int iR = pixelsRGB.get(q++);
int iG = pixelsRGB.get(q++);
int iB = pixelsRGB.get(q++);
pixelInts[i++] =
0xFF000000 | ((iR & 0x000000FF) << 16) |
((iG & 0x000000FF) << 8) | (iB & 0x000000FF);
}
}
// Create a new BufferedImage from the pixeldata.
BufferedImage bufferedImage =
new BufferedImage( frameWidth, frameHeight,
BufferedImage.TYPE_INT_ARGB);
bufferedImage.setRGB( 0, 0, frameWidth, frameHeight,
pixelInts, 0, frameWidth );
return bufferedImage;
}
// Function returns if filename already exsits.
// In this way it does not save each frame, when
// calles from the display() function.
public void saveFrameAsPNG( GL gl, String fileName )
{
// Open File
if( fileName == null ) {
fileName = new String( defaultFrameImageFilename ); }
File outputFile = new File( fileName );
// Do not overwrite existing image file.
if( outputFile.exists() ) { return; }
// Write file.
try {
javax.imageio.ImageIO.write(
copyFrame( gl ), "PNG", outputFile );
} catch (IOException e) {
System.out.println( "Error: ImageIO.write." );
e.printStackTrace();
}
}
///////////// draw /////////////////////////////////////
public void draw( GL gl )
{
// Load image, if necessary.
if( imgRGBA == null ) {
loadImage( defaultImageFilename ); }
gl.glPushAttrib( GL.GL_DEPTH_BUFFER_BIT );
gl.glPushAttrib( GL.GL_COLOR_BUFFER_BIT ); {
gl.glDisable( GL.GL_DEPTH_TEST );
// enable alpha mask (import from gif sets alpha bits)
gl.glEnable (GL.GL_BLEND);
gl.glBlendFunc (GL.GL_SRC_ALPHA,
GL.GL_ONE_MINUS_SRC_ALPHA);
// Draw a rectangle under part of image
// to prove alpha works.
gl.glColor4f( .5f, 0.1f, 0.2f, .5f );
gl.glRecti( 0, 0, 100, 330 );
gl.glColor3f( 0.0f, 0.0f, 0.0f );
// Draw image as bytes.
// gl.glRasterPos2i( 150, 100 );
gl.glWindowPos2i( 600, 600 );
gl.glPixelZoom( 1.0f, 1.0f ); // x-factor, y-factor
gl.glDrawPixels( imgWidth, imgHeight,
gl.GL_RGBA, gl.GL_UNSIGNED_BYTE,
imgRGBA );
gl.glPixelZoom( -2.0f, 3.0f ); // x-factor, y-factor
gl.glWindowPos2i( 600, 300 );
gl.glDrawPixels( imgWidth, imgHeight,
gl.GL_RGBA, gl.GL_UNSIGNED_BYTE,
imgRGBA );
// // Draw a rectangle under part of image
// // to prove alpha works.
// gl.glColor4f( .5f, 0.1f, 0.2f, .5f );
// gl.glRecti( 0, 0, 100, 330 );
// Copy the Image: FrameBuf to FrameBuf
gl.glPixelZoom( 1.0f, 1.0f ); // x-factor, y-factor
gl.glWindowPos2i( 500, 0 );
gl.glCopyPixels( 400, 300, 500, 600, GL.GL_COLOR );
} gl.glPopAttrib();
gl.glPopAttrib();
}
}
|
package dbAssignment.opti_home_shop;
import java.util.Iterator;
import java.util.List;
public class App {
public static void main(String[] args) {
System.out.println("Hello! Please execute the provided tests!");
}
}
|
package web;
import dao.UsersDao;
import model.User;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.sql.SQLException;
import javax.servlet.annotation.WebServlet;
@WebServlet(name = "creatUser")
public class UserController extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF8");
String name = request.getParameter("name");
String password = request.getParameter("password");
String email = request.getParameter("email");
System.out.println("Name " + " POST-1 " + name);
System.out.println("Password " + " POST-1 " + password);
System.out.println("Email " + " POST-1" + email);
PrintWriter out = response.getWriter();
out.println("<h3> CreateUser </h3>");
out.println("<h3> Вы вели значение.POST-1 " + name + "</h3>");
out.println("<h3> Вы вели значение.POS-1 " + password + "</h3>");
out.println("<h3> Вы вели значение.POST-1 " + email + "</h3>");
try {
if (name != " " & password !=" ") {
// System.out.println("********************************************");
User user = new User(name, password, email);
// System.out.println("USER NAME " + user.getName());
// System.out.println("USER PASSWORD " + user.getPassword());
// System.out.println("USER EMAIL " + user.getEmail());
// System.out.println("********************************************");
UsersDao usersDao = new UsersDao();
usersDao.saveUser(user);
RequestDispatcher requestDispatcher = request.getRequestDispatcher("aut.jsp");
requestDispatcher.forward(request, response);
} else {
RequestDispatcher requestDispatcher = request.getRequestDispatcher("error500.jsp");
requestDispatcher.forward(request, response);
}
} catch (IOException | SQLException e) {
System.out.println("Исключение выброшено UserController");
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
} |
package com.sunny.rpc.netty;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import java.util.Date;
import java.util.concurrent.TimeUnit;
/**
* <Description> <br>
*
* @author Sunny<br>
* @version 1.0<br>
* @taskId: <br>
* @createDate 2018/10/17 14:13 <br>
* @see com.sunny.rpc.netty <br>
*/
public class NettyClient {
public static void main(String[] args) throws InterruptedException {
Bootstrap bootstrap = new Bootstrap();
NioEventLoopGroup group = new NioEventLoopGroup();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) throws Exception {
channel.pipeline().addLast(new StringEncoder());
}
});
Channel channel = bootstrap.connect("127.0.0.1", 8000).channel();
while (true) {
channel.writeAndFlush(new Date() + ": hello world!");
//Thread.sleep(2000);
TimeUnit.MILLISECONDS.sleep(2000);
}
}
}
|
package org.michenux.drodrolib;
import org.michenux.drodrolib.db.sqlite.SQLiteDatabaseFactory;
import org.michenux.drodrolib.network.volley.BitmapCacheHolder;
import dagger.Module;
@Module(injects = { SQLiteDatabaseFactory.class, BitmapCacheHolder.class })
public class MCXModule {
}
|
package test;
import java.text.SimpleDateFormat;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import dao.BookDao;
import dto.Book;
import utils.HBUtils;
public class Program
{
static SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-YYYY");
public static void main(String[] args)
{
SessionFactory factory = HBUtils.getSessionFactory();
try
{
Book book = new Book("Let Us C", "Yashwant Kanetkar", 550.50f, sdf.parse("12-7-2015"));
BookDao dao = new BookDao();
dao.insertBook(book);
}
catch( Exception ex )
{
ex.printStackTrace();
}
factory.close();
}
}
|
package part1_processing;
import java.awt.Rectangle;
import java.util.ArrayList;
import processing.core.PApplet;
import processing.core.PVector;
public class Processing extends PApplet {
Rectangle g;
Rectangle c;
Rectangle ob;
PVector pos;
float velx;
float vely;
float rVelx;
float rVely;
double gravity;
boolean justCol = false;
float moving = 0;
float walk = 5;
boolean collidingP = false;
boolean walking = false;
int x1 = 30;
int y1 = 840;
boolean jump;
boolean re;
float rC;
float gC;
float bC;
ArrayList<Rectangle> rect = new ArrayList<Rectangle>();
float velxs[];
float velys[];
Rectangle player;
public static void main ( final String[] args ) {
PApplet.main( "part1_processing.Processing" );
}
@Override
public void settings () {
size( 1300, 900 );
}
@Override
public void setup () {
pos = new PVector( width / 2 + 40, height / 2 - 100 );
vely = 3;
velx = 0;
rVely = 0;
rVelx = 0;
re = false;
rC = random( 0, 255 );
gC = random( 0, 255 );
bC = random( 0, 255 );
velxs = new float[10];
velys = new float[10];
for ( int i = 0; i < 7; i++ ) {
velxs[i] = random( -5, 5 );
velys[i] = random( -5, 5 );
}
gravity = 0.5;
rect.add( new Rectangle( 60, 800, 32, 32 ) );
rect.add( new Rectangle( 160, 800, 32, 32 ) );
rect.add( new Rectangle( 260, 800, 32, 32 ) );
rect.add( new Rectangle( 560, 800, 32, 32 ) );
rect.add( new Rectangle( 960, 800, 32, 32 ) );
rect.add( new Rectangle( 1060, 800, 32, 32 ) );
rect.add( new Rectangle( 1160, 800, 32, 32 ) );
c = new Rectangle( 0, 0, 1300, 10 );
// rect.add( new Rectangle( 0, 890, 900, 10) );
x1 = (int) pos.x;
y1 = (int) pos.y;
ob = new Rectangle( 30, 800, 100, 100 );
g = new Rectangle( 0, 890, 1300, 10 );
player = new Rectangle( x1, y1, 32, 32 );
// fill( 120, 50, 240 );
}
@Override
public void draw () {
background( 51 );
if ( re ) {
velx = 0;
}
re = false;
collidingP = false;
vely += gravity;
player.y += vely;
if ( vely > 5 ) {
vely = 5;
}
if ( g.intersects( player ) ) {
collidingP = true;
player.y = g.y - 32;
}
if ( player.intersects( ob ) ) {
if ( player.y > ob.y ) {
if ( player.y > ob.y && player.y < ob.y + 100 ) {
velx *= -1;
}
else {
vely *= -1;
velx *= -1;
}
re = true;
}
else {
collidingP = true;
player.y = ob.y - 32;
vely = 0;
}
}
fill( 0, 0, 0 );
rect( ob.x, ob.y, 100, 100 );
rect( g.x, g.y, 1300, 10 );
rect( c.x, c.y, 1300, 10 );
stroke( 0 );
fill( 255, 0, 0 );
rect( player.x, player.y, 32, 32 );
player.x += velx;
if ( player.x > width ) {
player.x = -31;
}
if ( player.x < -32 ) {
player.x = width - 1;
}
if ( collidingP && jump != false ) {
vely = -10;
}
for ( int i = 0; i < rect.size(); i++ ) {
final Rectangle r = rect.get( i );
if ( r.intersects( player ) ) {
if ( velxs[i] < 0 && velx < 0 ) {
velxs[i] += velx;
}
else if ( velxs[i] > 0 && velx > 0 ) {
velxs[i] += velx;
}
else {
velxs[i] *= -1;
velxs[i] += velx;
}
if ( velys[i] < 0 && vely < 0 ) {
velys[i] += vely;
}
else if ( velys[i] > 0 && vely > 0 ) {
velys[i] += vely;
}
else {
velys[i] *= -1;
velys[i] += vely;
}
// rVely *= -1;
justCol = true;
}
for ( int j = 0; j < rect.size(); j++ ) {
if ( j != i ) {
if ( r.intersects( rect.get( j ) ) ) {
if ( velys[i] == 0 && velys[j] == 0 ) {
velys[i] += 1;
velys[j] += 1;
}
if ( velys[i] == 0 ) {
velys[i] += velys[j];
}
if ( velys[j] == 0 ) {
velys[j] += velys[i];
}
velxs[i] *= -1;
velxs[j] *= -1;
velys[i] *= -1;
velys[j] *= -1;
}
}
}
// rVely += gravity;
if ( velxs[i] > 7 ) {
velxs[i] = 7;
}
if ( velxs[i] < -7 ) {
velxs[i] = -7;
}
if ( velys[i] > 7 ) {
velys[i] = 7;
}
if ( velys[i] < -7 ) {
velys[i] = -7;
}
if ( r.y > 858 ) {
r.y = 858;
}
if ( r.y < 10 ) {
r.y = 10;
velys[i] += 1;
}
r.y += velys[i];
if ( g.intersects( r ) ) {
velys[i] *= -1;
}
if ( c.intersects( r ) ) {
velys[i] *= -1;
}
if ( r.x > width ) {
r.x = -32;
}
if ( r.x < -32 ) {
r.x = width;
}
r.x += velxs[i];
fill( rC, gC, bC );
rect( r.x, r.y, r.width, r.height );
}
}
@Override
public void keyPressed () {
if ( key == 'a' ) {
if ( !re ) {
velx = -walk;
walking = true;
}
}
if ( key == 'd' ) {
velx = walk;
walking = true;
}
if ( key == ' ' ) {
if ( collidingP ) {
jump = true;
}
}
}
@Override
public void keyReleased () {
if ( key == 'a' ) {
velx = 0;
walking = false;
}
if ( key == 'd' ) {
velx = 0;
walking = false;
}
if ( key == ' ' ) {
jump = false;
}
}
}
|
package org.sultangazibelediye.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/books")
public class Deneme {
@GetMapping("/novel")
public String getValues() {
return "{\n" +
" \"name\": \"Araba Sevdası\",\n" +
" \"author\": \"Recaizade Mahmut Ekrem\",\n" +
" \"hasbook\": 1\n" +
"}";
}
}
|
package LinkedList;
import java.util.*;
/*
链表求和
445. Add Two Numbers II (Medium)
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
*/
public class AddTwoNumbersII {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Stack<Integer> l1Stack = buildStack(l1);
Stack<Integer> l2Stack = buildStack(l2);
ListNode head = new ListNode(-1);
int carry = 0;
while(!l1Stack.empty() || !l2Stack.empty() || carry != 0) {
int x = l1Stack.empty() ? 0 : l1Stack.pop();
int y = l2Stack.empty() ? 0 : l2Stack.pop();
int sum = x + y + carry;
ListNode node = new ListNode(sum % 10);
node.next = head.next;
head.next = node;
carry = sum / 10;
}
return head.next;
}
public Stack<Integer> buildStack(ListNode l) {
Stack<Integer> stack = new Stack<>();
while(l != null) {
stack.push(l.val);
l = l.next;
}
return stack;
}
}
|
package com.baiwang.custom.common.dao;
import com.baiwang.custom.common.model.MGAccountResqust;
import com.baiwang.custom.common.model.MGInvoiceModel;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* @Description: 发票记账接口
* @Author: Guoyongzheng
* @Date: 2018/10/15-10:21
*/
@Mapper
public interface MGAccountMapper {
//查询主表
List<MGInvoiceModel> queryInvTVM(List<MGInvoiceModel> params);
//查询拓展表
List<MGInvoiceModel> queryInvExtend(List<MGInvoiceModel> params);
List<MGInvoiceModel> findExtendByVoucherNo(MGAccountResqust params);
//批量插库
boolean batchInsertReimburseInfo(List<MGInvoiceModel> params);
//批量更新 -- 标识1为更新 标识2为作废
boolean batchUpdateReimburseInfo(List<MGInvoiceModel> params);
//单条更新列表
boolean updateReimburseInfo(MGInvoiceModel params );
//通过凭证号删除发票信息
boolean DeleteByVoucherNo(MGAccountResqust params );
}
|
package dlmbg.pckg.sistem.akademik;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
public class TranskripActivity extends Activity {
public String nim;
JSONArray str_login = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.panel_transkrip);
Bundle b = getIntent().getExtras();
nim = b.getString("par_kode");
String link_url = "http://10.0.2.2/siakad-andro/transkrip.php?nim="+nim;
//String link_url = "http://10.0.2.2/siakad-andro/transkrip.php?nim=1109100350";
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(link_url);
try {
str_login = json.getJSONArray("trns");
String transkrip = "";
TextView isi = (TextView) findViewById(R.id.tnilai);
for(int i = 0; i < str_login.length(); i++){
JSONObject ar = str_login.getJSONObject(i);
transkrip += "MK : "+ar.getString("mk")+"\n"+"Jumlah SKS : "+ar.getString("sks")+"\n"+"Semester : "+ar.getString("smt")+"\n"+"Nilai : "+ar.getString("nilai")+"\n\n";
}
isi.setText(transkrip);
} catch (JSONException e) {
e.printStackTrace();
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.opt_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.url:
Intent intent = null;
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://stikombanyuwangi.ac.id"));
startActivity(intent);
return true;
case R.id.tentang:
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("SIAKAD STIKOM BANYUWANGI");
alertDialog.setMessage("Aplikasi SIAKAD berbasis Android ini merupakan salah satu dari sekian banyak proyek 2M" +
" serta segelintir penelitian yang saya kerjakan di kampus. Semoga aplikasi ini bisa bermanfaat untuk " +
" kita semua.\n\nSalam, Gede Lumbung\nhttp://gedelumbung.com");
alertDialog.setButton("#OKOK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
|
package com.github.tobby48.java.scene4;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/**
* <pre>
* com.github.tobby48.java.scene4
* FileCharacterStreamRead.java
*
* 설명 : 파일 입출력 - Character Stream 으로 파일읽기
* </pre>
*
* @since : 2017. 11. 17.
* @author : Administrator
* @version : v1.0
*/
public class FileCharacterStreamRead {
public static void main(String[] args) throws IOException {
// 파일 내용을 라인단위로 읽어오기 위해 버퍼에 라인별로 저장
BufferedReader br = new BufferedReader(new FileReader("c:/text.txt"));
while(true) {
String line = br.readLine();
if (line==null) break; // 파일의 끝일 경우 null
System.out.println(line);
}
br.close();
}
}
|
package pl.herbata.project.mvc.mainframe;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.DefaultTableModel;
import pl.herbata.project.ParticipingPlayer;
import pl.herbata.project.Player;
import pl.herbata.project.Tournament;
import pl.herbata.project.mvc.Model;
public class MainFrameModel implements Model {
private List<Player> players;
private Tournament tournament;
private static final String[] playerDataTableColumnNames = {
"ID", "Nazwa gracza"
};
private static final Class<?>[] playerDataTableColumnTypes = {
Integer.class, String.class
};
private static final boolean[] playerDataTableColumnEditable = {
false, false
};
private static final int[] playerDataTableColumnWidths = {
30, 200
};
private DefaultTableModel playerDataTableModel;
private static final String[] playerSelectionTableColumnNames = {
"ID gracza", "Nazwa gracza", "Wybór"
};
private static final Class<?>[] playerSelectionTableColumnTypes = {
Integer.class, String.class, Boolean.class
};
private static final boolean[] playerSelectionTableColumnEditable = {
false, false, true
};
private static final int[] playerSelectionTableColumnWidths = {
30, 200, 40
};
private DefaultTableModel playerSelectionTableModel;
private static final String[] tournamentTableColumnNames = {
"Grupa", "Gracz", "ID gracza",
"Ranking", "Punkty łącznie", "Wynik rundy"
};
private static final Class<?>[] tournamentTableColumnTypes = {
Integer.class, String.class, Integer.class,
Integer.class, Integer.class, Integer.class
};
private static final boolean[] tournamentTableColumnEditable = {
false, false, false, false, false, true
};
private static final int[] tournamentTableColumnWidths = {
30, 200, 30, 30, 30, 30
};
private DefaultTableModel tournamentTableModel;
public MainFrameModel() {
players = new ArrayList<Player>();
playerDataTableModel = new DefaultTableModel(
createPlayerDataObjectTable(), playerDataTableColumnNames) {
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return playerDataTableColumnEditable[columnIndex];
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return playerDataTableColumnTypes[columnIndex];
}
};
playerSelectionTableModel = new DefaultTableModel(
createPlayerSelectionObjectTable(),
playerSelectionTableColumnNames) {
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return playerSelectionTableColumnEditable[columnIndex];
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return playerSelectionTableColumnTypes[columnIndex];
}
};
tournamentTableModel = new DefaultTableModel(
createTournamentObjectTable(),
tournamentTableColumnNames) {
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
if ((Integer)getValueAt(rowIndex, 0) == 0) {
return false;
}
return tournamentTableColumnEditable[columnIndex];
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return tournamentTableColumnTypes[columnIndex];
}
@Override
public void setValueAt(
Object aValue, int rowIndex, int columnIndex) {
if (aValue == null) {
return;
}
super.setValueAt(aValue, rowIndex, columnIndex);
if (tournament.getCurrentRound() <= tournament.getTotalRounds()) {
if (columnIndex == 5) {
int tournamentPlayerCount = tournament.getPlayerCount();
int currentGroup = (Integer)getValueAt(rowIndex, 0);
for (int i = 0; i < tournamentPlayerCount; ++i) {
if ((Integer)getValueAt(i, 0) == currentGroup
&& i != rowIndex) {
String round = (String)getValueAt(rowIndex, 5);
setOppositeRoundResult(round, i);
}
}
}
}
}
private void setOppositeRoundResult(String roundRes, int rowIndex) {
if (roundRes.equals(Tournament.ROUND_RESULTS[0])) {
super.setValueAt(Tournament.ROUND_RESULTS[2], rowIndex, 5);
} else if (roundRes.equals(Tournament.ROUND_RESULTS[1])) {
super.setValueAt(Tournament.ROUND_RESULTS[1], rowIndex, 5);
} else if (roundRes.equals(Tournament.ROUND_RESULTS[2])) {
super.setValueAt(Tournament.ROUND_RESULTS[0], rowIndex, 5);
}
}
};
tournament = null;
}
public void addPlayer(Player player) {
players.add(player);
Object[] data = { player.getId(), player.getNickname() };
Object[] selection = { player.getId(), player.getNickname(), false };
playerDataTableModel.addRow(data);
playerSelectionTableModel.addRow(selection);
}
public void removePlayer(Player player) {
players.remove(player);
int rowCount = playerDataTableModel.getRowCount();
for (int i = 0; i < rowCount; ++i) {
if (playerDataTableModel.getValueAt(i, 0).equals(player.getId())) {
playerDataTableModel.removeRow(i);
playerSelectionTableModel.removeRow(i);
break;
}
}
}
public void updatePlayer(Player player) {
int size = players.size();
Player selectedPlayer;
for (int i = 0; i < size; ++i) {
if (players.get(i).getId() == player.getId()) {
selectedPlayer = players.get(i);
selectedPlayer.setNickname(player.getNickname());
break;
}
}
int rowCount = playerDataTableModel.getRowCount();
for (int i = 0; i < rowCount; ++i) {
if (playerDataTableModel.getValueAt(i, 0).equals(player.getId())) {
String nickname = player.getNickname();
playerDataTableModel.setValueAt(nickname, i, 1);
playerSelectionTableModel.setValueAt(nickname, i, 1);
break;
}
}
}
public int extractIdFromRow(int rowIndex) {
int playersId = (Integer)playerDataTableModel.getValueAt(rowIndex, 0);
return playersId;
}
public void setPlayers(List<Player> players) {
this.players.clear();
this.players.addAll(players);
}
public void refreshPlayerSelectionTableData() {
playerDataTableModel.setRowCount(0);
int rowCount = players.size();
for (int i = 0; i < rowCount; ++i) {
addPlayerToModel(players.get(i));
}
}
public void setAllPlayersSelected(boolean selected) {
int playerCount = players.size();
for (int i = 0; i < playerCount; ++i) {
playerSelectionTableModel.setValueAt(selected, i, 2);
}
}
public DefaultTableModel getPlayerDataTableModel() {
return playerDataTableModel;
}
public int[] getPlayerDataTableColumnWidths() {
return playerDataTableColumnWidths;
}
public DefaultTableModel getPlayerSelectionTableModel() {
return playerSelectionTableModel;
}
public int[] getPlayerSelectionTableColumnWidths() {
return playerSelectionTableColumnWidths;
}
public DefaultTableModel getTournamentTableModel() {
return tournamentTableModel;
}
public int[] getTournamentTableColumnWidths() {
return tournamentTableColumnWidths;
}
public String[] getPlayerDataTableColumnNames() {
return playerDataTableColumnNames;
}
public Class<?>[] getPlayerDataTableColumnTypes() {
return playerDataTableColumnTypes;
}
private Object[][] createPlayerDataObjectTable() {
Object[][] playerDataTable = new Object[players.size()][2];
for (int i = 0; i < players.size(); ++i) {
playerDataTable[i][0] = players.get(i).getId();
playerDataTable[i][1] = players.get(i).getNickname();
}
return playerDataTable;
}
private Object[][] createPlayerSelectionObjectTable() {
Object[][] playerSelectionTable = new Object[players.size()][3];
for (int i = 0; i < players.size(); ++i) {
playerSelectionTable[i][0] = players.get(i).getId();
playerSelectionTable[i][1] = players.get(i).getNickname();
playerSelectionTable[i][2] = false;
}
return playerSelectionTable;
}
private Object[][] createTournamentObjectTable() {
Object[][] tournamentTable = new Object[0][5];
return tournamentTable;
}
private Object[][] createTournamentObjectTable(
List<ParticipingPlayer> players) {
int rowCount = players.size();
Object[][] tournamentTable = new Object[rowCount][5];
for (int i = 0; i < rowCount; ++i) {
tournamentTable[i][0] = players.get(i).getGroup();
tournamentTable[i][1] = players.get(i).getNickname();
tournamentTable[i][2] = players.get(i).getId();
tournamentTable[i][3] = players.get(i).getRanking();
tournamentTable[i][4] = players.get(i).getPoints();
}
return tournamentTable;
}
private void addPlayerToModel(Player player) {
Object[] data = { player.getId(), player.getNickname() };
Object[] selection = { player.getId(), player.getNickname(), false };
playerDataTableModel.addRow(data);
playerSelectionTableModel.addRow(selection);
}
public boolean createNewTournament() {
ArrayList<Player> selectedPlayers = getPlayersSelectedToATournament();
if (selectedPlayers.size() < 4) {
return false;
}
ArrayList<ParticipingPlayer> participingPlayers
= new ArrayList<ParticipingPlayer>();
for (Player player : selectedPlayers) {
participingPlayers.add(new ParticipingPlayer(player));
}
Object[][] tournamentObjectTable
= createTournamentObjectTable(participingPlayers);
tournament = new Tournament(participingPlayers);
tournament.calculateTotalRounds();
if (tournamentTableModel.getRowCount() != 0) {
tournamentTableModel.setRowCount(0);
}
for (Object[] obj : tournamentObjectTable) {
tournamentTableModel.addRow(obj);
}
return true;
}
public boolean beginNextRound() {
if (!tournament.beginNextRound()) {
return false;
}
int participingPlayers = tournament.getPlayerCount();
String[] roundResults = new String[participingPlayers];
String win = Tournament.ROUND_RESULTS[0];
String draw = Tournament.ROUND_RESULTS[1];
String lose = Tournament.ROUND_RESULTS[2];
if (tournament.getCurrentRound() != 1) {
for (int i = 0; i < participingPlayers; ++i) {
roundResults[i]
= (String)tournamentTableModel.getValueAt(i, 5);
// If user didn't set points for all participing players, next
// round cannot be started.
if (roundResults[i] == null) {
return false;
}
}
for (int i = 0; i < participingPlayers; ++i) {
int playersId = (Integer)tournamentTableModel.getValueAt(i, 2);
if (roundResults[i].equals(win)) {
tournament.getPlayerOnId(playersId).incrementTotalWins();
} else if (roundResults[i].equals(draw)) {
tournament.getPlayerOnId(playersId).incrementTotalDraws();
} else if (roundResults[i].equals(lose)) {
tournament.getPlayerOnId(playersId).incrementTotalLoses();
}
}
tournament.calculateRanking();
}
tournament.generatePairs();
Object[][] tournamentObjectTable
= createTournamentObjectTable(tournament.getPlayers());
tournamentTableModel.setRowCount(0);
for (Object[] obj : tournamentObjectTable) {
tournamentTableModel.addRow(obj);
}
if (tournament.getCurrentRound() <= tournament.getTotalRounds()) {
for (int i = 0; i < participingPlayers; ++i) {
if (tournament.getPlayerOnIndex(i).getGroup() == 0) {
tournamentTableModel.setValueAt(win, i, 5);
}
}
}
return true;
}
public boolean isTournamentFinished() {
boolean result = false;
if (tournament.getCurrentRound() > tournament.getTotalRounds()) {
result = true;
}
return result;
}
public int getCurrentTournamentRound() {
int result = -1;
if (tournament != null) {
result = tournament.getCurrentRound();
if (result > tournament.getTotalRounds()) {
result = -1;
}
}
return result;
}
public int getTotalTournamentRounds() {
int result = -1;
if (tournament != null) {
result = tournament.getTotalRounds();
}
return result;
}
private ArrayList<Player> getPlayersSelectedToATournament() {
ArrayList<Player> result = new ArrayList<Player>();
for (int i = 0; i < players.size(); ++i) {
if (playerSelectionTableModel.getValueAt(i, 2).equals(true)) {
result.add(players.get(i));
}
}
return result;
}
private static int closestOddNumber(int number) {
int result;
if (number % 2 == 0) {
result = number + 1;
} else {
result = number;
}
return result;
}
}
|
package egovframework.adm.lcms.cts.controller;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import egovframework.adm.lcms.cts.service.LcmsFileService;
import egovframework.com.cmm.EgovMessageSource;
import egovframework.com.pag.controller.PagingManageController;
import egovframework.rte.fdl.property.EgovPropertyService;
@Controller
public class LcmsFileController {
/** log */
protected static final Log LOG = LogFactory.getLog( LcmsItemController.class);
/** EgovPropertyService */
@Resource(name = "propertiesService")
protected EgovPropertyService propertiesService;
/** EgovMessageSource */
@Resource(name="egovMessageSource")
EgovMessageSource egovMessageSource;
/** PagingManageController */
@Resource(name = "pagingManageController")
private PagingManageController pagingManageController;
/** lcmsFileService */
@Resource(name = "lcmsFileService")
private LcmsFileService lcmsFileService;
@RequestMapping(value="/adm/cts/LcmsFileInsert.do")
public String insert( HttpServletRequest request, HttpServletResponse response,
Map<String, Object> commandMap, ModelMap model) throws Exception {
String resultMsg = "";
lcmsFileService.insertLcmsFile(commandMap);
model.addAttribute("resultMsg", resultMsg);
model.addAllAttributes(commandMap);
return "";
}
}
|
package cqut.syntaxAnalyzer.util;
public class StringUtil {
/**
* 判断参数中字符串大写字母的起始位置,若没有大写字母则返回-1
*
* @param str
* @return
*/
public static int indexOf(String str) {
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (chars[i] <= 'Z' && chars[i] >= 'A') {
return i;
}
}
return -1;
}
public static void main(String[] args) {
System.out.println(indexOf("ddD23"));
System.out.println(indexOf("dd23"));
}
}
|
package com.neusoft.oa.model;
import org.apache.ibatis.type.Alias;
//系统功能Model类
@Alias("Function")
public class FunctionModel {
private int no=0;
private String name=null; //功能名称
private String url=null; //功能主页的请求地址
private ModuleModel module=null; //功能所在的模块
//
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public ModuleModel getModule() {
return module;
}
public void setModule(ModuleModel module) {
this.module = module;
}
}
|
package info.datacluster.crawler.mapper;
import info.datacluster.crawler.entity.CrawlerTaskResult;
public interface CrawlerTaskResultMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table crawler_task_result
*
* @mbg.generated Mon Aug 26 23:04:46 CST 2019
*/
int deleteByPrimaryKey(Long id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table crawler_task_result
*
* @mbg.generated Mon Aug 26 23:04:46 CST 2019
*/
int insert(CrawlerTaskResult record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table crawler_task_result
*
* @mbg.generated Mon Aug 26 23:04:46 CST 2019
*/
int insertSelective(CrawlerTaskResult record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table crawler_task_result
*
* @mbg.generated Mon Aug 26 23:04:46 CST 2019
*/
CrawlerTaskResult selectByPrimaryKey(Long id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table crawler_task_result
*
* @mbg.generated Mon Aug 26 23:04:46 CST 2019
*/
int updateByPrimaryKeySelective(CrawlerTaskResult record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table crawler_task_result
*
* @mbg.generated Mon Aug 26 23:04:46 CST 2019
*/
int updateByPrimaryKey(CrawlerTaskResult record);
} |
// https://leetcode.com/problems/jewels-and-stones/
// #hash-table
class Solution {
public int numJewelsInStones(String J, String S) {
int[] source = new int['z' - 'A' + 1];
for (char c : S.toCharArray()) {
source[c - 'A'] += 1;
}
int ret = 0;
for (char c : J.toCharArray()) {
ret += source[c - 'A'];
}
return ret;
}
}
|
package cz.metacentrum.perun.spRegistration.persistence.managers;
import cz.metacentrum.perun.spRegistration.common.exceptions.InternalErrorException;
import cz.metacentrum.perun.spRegistration.common.models.AuditLogDTO;
import java.util.List;
import lombok.NonNull;
public interface AuditLogsManager {
AuditLogDTO insert(@NonNull AuditLogDTO log) throws InternalErrorException;
List<AuditLogDTO> getAll();
AuditLogDTO getById(@NonNull Long id);
List<AuditLogDTO> getForRequest(@NonNull Long requestId);
List<AuditLogDTO> getForFacility(@NonNull Long facilityId);
}
|
package com.dream.utils;
import android.content.Context;
public class PreferUtil {
public static boolean saveString(Context context, String key, String value) {
context.getSharedPreferences(Constant.COOKIESTR, Context.MODE_PRIVATE).edit().putString(key, value).commit();
return true;
}
public static String getString(Context context, String key) {
return context.getSharedPreferences(Constant.COOKIESTR, Context.MODE_PRIVATE).getString(key, "0");
}
}
|
package pp;
import pp.model.Glad;
import pp.model.IModel;
/**
* @author alexander.sokolovsky.a@gmail.com
*/
public class GladModelFactory implements ModelFactory {
private static final GladModelFactory INSTANCE = new GladModelFactory();
public static final GladModelFactory getInstance() {
return INSTANCE;
}
public IModel getNewModel() {
return new Glad();
}
public void merge(final IModel source, final IModel destination) {
final Glad src = (Glad) source;
final Glad dst = (Glad) destination;
if (src.getOwnerID() != null) dst.setOwnerID(src.getOwnerID());
if (src.getName() != null) dst.setName(src.getName());
if (src.getType() != null) dst.setType(src.getType());
if (src.getStatus() != null) dst.setStatus(src.getStatus());
if (src.getHealth() != null) dst.setHealth(src.getHealth());
if (src.getMaxHealth() != null) dst.setMaxHealth(src.getMaxHealth());
if (src.getMorale() != null) dst.setMorale(src.getMorale());
if (src.getInjury() != null) dst.setInjury(src.getInjury());
if (src.getAge() != null) dst.setAge(src.getAge());
if (src.getTalent() != null) dst.setTalent(src.getTalent());
if (src.getExp() != null) dst.setExp(src.getExp());
if (src.getExpToLvl() != null) dst.setExpToLvl(src.getExpToLvl());
if (src.getLvl() != null) dst.setLvl(src.getLvl());
if (src.getLvlUp() != null) dst.setLvlUp(src.getLvlUp());
if (src.getVitality() != null) dst.setVitality(src.getVitality());
if (src.getDexterity() != null) dst.setDexterity(src.getDexterity());
if (src.getAccuracy() != null) dst.setAccuracy(src.getAccuracy());
if (src.getStrength() != null) dst.setStrength(src.getStrength());
if (src.getNation() != null) dst.setNation(src.getNation());
if (src.getHeight() != null) dst.setHeight(src.getHeight());
if (src.getWeight() != null) dst.setWeight(src.getWeight());
if (src.getPrice() != null) dst.setPrice(src.getPrice());
if (src.getRetirement() != null) dst.setDexterity(src.getDexterity());
if (src.getVictories() != null) dst.setVictories(src.getVictories());
if (src.getDefeat() != null) dst.setDefeat(src.getDefeat());
if (src.getHpPercent() != null) dst.setHpPercent(src.getHpPercent());
}
}
|
package factoring;
import java.util.Collection;
/**
* This is a generic interface for classes which can find some factors of a number up to a certain factor.
* This maximal factor can be given by {@link #setMaxFactor(int)}.
* The implementation can either return prime or composite factors of the number.
* It can also choose if it only gives back one factor per call to {@link #findFactors(long, Collection)} as a return value,
* or stores every factor it finds in the collection.
*
* @author thiloharich
*
*/
public interface FactorFinder {
/**
* Sets the maximal factor the FactorFinder should look for factors.
* @param maximalFactor
*/
default void setMaxFactor(int maximalFactor)
{
}
// /**
// * Get the maximal factor the FactorFinder searches for.
// * @return
// */
// default int getMaxFactor() {
// return -1;
// }
/**
* retuns a factor of n, if there is any. If n is a prime n will be returned.
* Only if {@link #findsPrimesOnly()} is true this factors needs to be a prime.
* @param n
* @return
*/
default long findFactor (long n) {
return findFactors (n, null);
}
/**
* Gives back at least one factor of the number n, if there is any.
* If {@link #setMaxFactor(int) maxFactor} is called, it will only check for numbers below maxFactor.
* If {@link #returnsCompositeOnly()} is true, the factor will be returned by the return of the function. In this case the prime factors
* parameter will not be used. If {@link #returnsCompositeOnly()} is false the prime factors can be stored in the prime factors collection.
* If {@link #findsPrimesOnly()} is true the implementation should return only prime factors (either as return value or in the factors collection).
* If {@link #setMaxFactor(int)} is called,
*
* @param n the number to be factorized.
* @param primeFactors A container for storing (prime) factors. If this parameter is not given, the algorithm has to return a (composite)
* factor as return value, since it can not store other factors. If the caller provides a non null Collection possible primes might be stored
* in the collection. If {@link #setMaxFactor(int)} was called only prime factors below maxFactor will be returned.
* Only If {@link #returnsCompositeOnly()} is true the prime factors collection will not be used. In this case factors can be null.
* It will not necessary add all prime factors in this collection.
* @return a factor of the number n.
* If {@link #returnsCompositeOnly()} is true it will return a factor of the number n.
* If {@link #returnsCompositeOnly()} is false, the return is n divided by the prime factors of n added to the prime factors collection.
* If n is prime n will be returned. If 1 is returned the number is factorized completely.
*/
long findFactors (long n, Collection<Long> primeFactors);
/**
* Indicates that the implementation will only return prime factors of the number in {@link #findFactors(long, Collection)}
* as return value and in the prime factor collection as well. The prime factors in the collection and the prime factor returned
* multiply up to n.
*
* @return
*/
default boolean findsPrimesOnly() {
return true;
}
/**
* If the implementation will only return one factor as return value of {@link #findFactors(long, Collection)} this
* function returns true. In this case it will not use the prime factor collection to store primes.
* If this returns false, in {@link #findFactors(long, Collection)} the possible prime factors will be stored in the second parameter.
*
* @return
*/
default boolean returnsCompositeOnly() {
return false;
}
}
|
package slicktest;
import org.newdawn.slick.BasicGame;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import entities.Character;
/**
* This class represents the game itself. It is encapsulated within the Application class.
* It handles the game update, the screen rendering and the user input.
* @author Strift
*
*/
public class Game extends BasicGame {
private Environment environment;
Camera camera;
boolean running;
/**
* Default constructor
* @param title
*/
public Game(String title) {
super(title);
running = true;
}
@Override
public void init(GameContainer gc) throws SlickException {
environment = new Environment();
camera = new Camera(gc);
camera.setEnvironment(environment);
camera.setVerticalCentering(false);
}
@Override
public void update(GameContainer gc, int delta) throws SlickException {
if (running == false){
gc.exit();
return;
}
environment.update(delta);
}
@Override
public void render(GameContainer gc, Graphics g) throws SlickException {
camera.center();
g.translate(-camera.getX(), -camera.getY());
environment.render(g);
g.setColor(Color.red);
g.drawString("FPS: " + gc.getFPS(), environment.getPlayer().getPosition().x, environment.getPlayer().getPosition().y - 10);
}
@Override
public void keyPressed(int key, char c) {
switch (key) {
case Input.KEY_LEFT:
environment.getPlayer().startWalking(Character.Direction.Left);
break;
case Input.KEY_RIGHT:
environment.getPlayer().startWalking(Character.Direction.Right);
break;
case Input.KEY_SPACE:
environment.getPlayer().jump();
break;
case Input.KEY_LSHIFT:
environment.getPlayer().setRunning(true);
break;
case Input.KEY_ESCAPE:
running = false;
break;
}
};
@Override
public void keyReleased(int key, char c) {
switch (key) {
case Input.KEY_LEFT:
environment.getPlayer().stopWalking(Character.Direction.Left);
break;
case Input.KEY_RIGHT:
environment.getPlayer().stopWalking(Character.Direction.Right);
break;
case Input.KEY_LSHIFT:
environment.getPlayer().setRunning(false);
break;
}
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.scheduling.concurrent;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.SmartLifecycle;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.core.task.TaskRejectedException;
import org.springframework.lang.Nullable;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.support.TaskUtils;
import org.springframework.util.ErrorHandler;
/**
* A simple implementation of Spring's {@link TaskScheduler} interface, using
* a single scheduler thread and executing every scheduled task in an individual
* separate thread. This is an attractive choice with virtual threads on JDK 21,
* expecting common usage with {@link #setVirtualThreads setVirtualThreads(true)}.
*
* <p>Supports a graceful shutdown through {@link #setTaskTerminationTimeout},
* at the expense of task tracking overhead per execution thread at runtime.
* Supports limiting concurrent threads through {@link #setConcurrencyLimit}.
* By default, the number of concurrent task executions is unlimited.
* This allows for dynamic concurrency of scheduled task executions, in contrast
* to {@link ThreadPoolTaskScheduler} which requires a fixed pool size.
*
* <p><b>NOTE: This implementation does not reuse threads!</b> Consider a
* thread-pooling TaskScheduler implementation instead, in particular for
* scheduling a large number of short-lived tasks. Alternatively, on JDK 21,
* consider setting {@link #setVirtualThreads} to {@code true}.
*
* <p>Extends {@link SimpleAsyncTaskExecutor} and can serve as a fully capable
* replacement for it, e.g. as a single shared instance serving as a
* {@link org.springframework.core.task.TaskExecutor} as well as a {@link TaskScheduler}.
* This is generally not the case with other executor/scheduler implementations
* which tend to have specific constraints for the scheduler thread pool,
* requiring a separate thread pool for general executor purposes in practice.
*
* <p>As an alternative to the built-in thread-per-task capability, this scheduler
* can also be configured with a separate target executor for scheduled task
* execution through {@link #setTargetTaskExecutor}: e.g. pointing to a shared
* {@link ThreadPoolTaskExecutor} bean. This is still rather different from a
* {@link ThreadPoolTaskScheduler} setup since it always uses a single scheduler
* thread while dynamically dispatching to the target thread pool which may have
* a dynamic core/max pool size range, participating in a shared concurrency limit.
*
* @author Juergen Hoeller
* @since 6.1
* @see #setVirtualThreads
* @see #setTaskTerminationTimeout
* @see #setConcurrencyLimit
* @see SimpleAsyncTaskExecutor
* @see ThreadPoolTaskScheduler
*/
@SuppressWarnings("serial")
public class SimpleAsyncTaskScheduler extends SimpleAsyncTaskExecutor implements TaskScheduler,
ApplicationContextAware, SmartLifecycle, ApplicationListener<ContextClosedEvent> {
private static final TimeUnit NANO = TimeUnit.NANOSECONDS;
private final ScheduledExecutorService scheduledExecutor = createScheduledExecutor();
private final ExecutorLifecycleDelegate lifecycleDelegate = new ExecutorLifecycleDelegate(this.scheduledExecutor);
private Clock clock = Clock.systemDefaultZone();
private int phase = DEFAULT_PHASE;
@Nullable
private Executor targetTaskExecutor;
@Nullable
private ApplicationContext applicationContext;
/**
* Set the clock to use for scheduling purposes.
* <p>The default clock is the system clock for the default time zone.
* @since 5.3
* @see Clock#systemDefaultZone()
*/
public void setClock(Clock clock) {
this.clock = clock;
}
@Override
public Clock getClock() {
return this.clock;
}
/**
* Specify the lifecycle phase for pausing and resuming this executor.
* The default is {@link #DEFAULT_PHASE}.
* @see SmartLifecycle#getPhase()
*/
public void setPhase(int phase) {
this.phase = phase;
}
/**
* Return the lifecycle phase for pausing and resuming this executor.
* @see #setPhase
*/
@Override
public int getPhase() {
return this.phase;
}
/**
* Specify a custom target {@link Executor} to delegate to for
* the individual execution of scheduled tasks. This can for example
* be set to a separate thread pool for executing scheduled tasks,
* whereas this scheduler keeps using its single scheduler thread.
* <p>If not set, the regular {@link SimpleAsyncTaskExecutor}
* arrangements kicks in with a new thread per task.
*/
public void setTargetTaskExecutor(Executor targetTaskExecutor) {
this.targetTaskExecutor = (targetTaskExecutor == this ? null : targetTaskExecutor);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
private ScheduledExecutorService createScheduledExecutor() {
return new ScheduledThreadPoolExecutor(1, this::newThread) {
@Override
protected void beforeExecute(Thread thread, Runnable task) {
lifecycleDelegate.beforeExecute(thread);
}
@Override
protected void afterExecute(Runnable task, Throwable ex) {
lifecycleDelegate.afterExecute();
}
};
}
@Override
protected void doExecute(Runnable task) {
if (this.targetTaskExecutor != null) {
this.targetTaskExecutor.execute(task);
}
else {
super.doExecute(task);
}
}
private Runnable scheduledTask(Runnable task) {
return () -> execute(task);
}
@Override
@Nullable
public ScheduledFuture<?> schedule(Runnable task, Trigger trigger) {
try {
Runnable delegate = scheduledTask(task);
ErrorHandler errorHandler = TaskUtils.getDefaultErrorHandler(true);
return new ReschedulingRunnable(
delegate, trigger, this.clock, this.scheduledExecutor, errorHandler).schedule();
}
catch (RejectedExecutionException ex) {
throw new TaskRejectedException(this.scheduledExecutor, task, ex);
}
}
@Override
public ScheduledFuture<?> schedule(Runnable task, Instant startTime) {
Duration delay = Duration.between(this.clock.instant(), startTime);
try {
return this.scheduledExecutor.schedule(scheduledTask(task), NANO.convert(delay), NANO);
}
catch (RejectedExecutionException ex) {
throw new TaskRejectedException(this.scheduledExecutor, task, ex);
}
}
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Instant startTime, Duration period) {
Duration initialDelay = Duration.between(this.clock.instant(), startTime);
try {
return this.scheduledExecutor.scheduleAtFixedRate(scheduledTask(task),
NANO.convert(initialDelay), NANO.convert(period), NANO);
}
catch (RejectedExecutionException ex) {
throw new TaskRejectedException(this.scheduledExecutor, task, ex);
}
}
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Duration period) {
try {
return this.scheduledExecutor.scheduleAtFixedRate(scheduledTask(task),
0, NANO.convert(period), NANO);
}
catch (RejectedExecutionException ex) {
throw new TaskRejectedException(this.scheduledExecutor, task, ex);
}
}
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Instant startTime, Duration delay) {
Duration initialDelay = Duration.between(this.clock.instant(), startTime);
try {
return this.scheduledExecutor.scheduleWithFixedDelay(scheduledTask(task),
NANO.convert(initialDelay), NANO.convert(delay), NANO);
}
catch (RejectedExecutionException ex) {
throw new TaskRejectedException(this.scheduledExecutor, task, ex);
}
}
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Duration delay) {
try {
return this.scheduledExecutor.scheduleWithFixedDelay(scheduledTask(task),
0, NANO.convert(delay), NANO);
}
catch (RejectedExecutionException ex) {
throw new TaskRejectedException(this.scheduledExecutor, task, ex);
}
}
@Override
public void start() {
this.lifecycleDelegate.start();
}
@Override
public void stop() {
this.lifecycleDelegate.stop();
}
@Override
public void stop(Runnable callback) {
this.lifecycleDelegate.stop(callback);
}
@Override
public boolean isRunning() {
return this.lifecycleDelegate.isRunning();
}
@Override
public void onApplicationEvent(ContextClosedEvent event) {
if (event.getApplicationContext() == this.applicationContext) {
this.scheduledExecutor.shutdown();
}
}
@Override
public void close() {
for (Runnable remainingTask : this.scheduledExecutor.shutdownNow()) {
if (remainingTask instanceof Future<?> future) {
future.cancel(true);
}
}
super.close();
}
}
|
package ITMO_LAB3;
import java.util.Objects;
public abstract class Person{
private String Name;
private String Mood;
private Locations location;
static String glad(){
return ("Everyone is glad that the Dragon was gone");
}
public void setLocation(Locations location) {
this.location = location;
}
public Locations getLocation() {
return location;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public void setMood(String mood) {
Mood = mood;
}
public String getMood() {
return Mood;
}
}
|
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
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 java.util.Random;
import java.util.UUID;
/**
* @author Frode Fan
* @version 1.0
* @since 2019/9/20
*/
public class Website {
private static String cookie = "57838640";
public static void main(String[] args) throws IOException {
get();
}
public static String get() throws IOException {
InputStream in = null;
BufferedOutputStream out = null;
String uri = "http://dxpvote.svccloud.cn/vote/get/imgCode";
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "image/webp,image/apng,image/*,*/*;q=0.8");
con.setRequestProperty("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
con.setRequestProperty("Accept-Encoding", "gzip, deflate");
con.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");
con.setRequestProperty("Connection", "keep-alive");
con.setRequestProperty("Cookie", "insert_cookie=57838640");
con.setRequestProperty("Host", "dxpvote.svccloud.cn");
con.setRequestProperty("Referer", "http://vweb.svccloud.cn/");
con.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
con.connect();// 获取连接
in = con.getInputStream();
String filename = "d:\\imageTotal\\imageCode.gif";
File file = new File(filename);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
FileOutputStream fileOutputStream = new FileOutputStream(filename);
in = new BufferedInputStream(in);
out = new BufferedOutputStream(fileOutputStream);
int len;
byte[] b = new byte[1024];
while ((len = in.read(b)) != -1) {
out.write(b, 0, len);
}
// url = new URL("http://dxpvote.svccloud.cn/vote/save?choice_id=19&poll_id=2&uuid="+ UUID.randomUUID() +"&img_code=n44m");
// con = (HttpURLConnection) url.openConnection();
// con.setRequestMethod("POST");
// con.setRequestProperty("Accept", "image/webp,image/apng,image/*,*/*;q=0.8");
// con.setRequestProperty("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
// con.setRequestProperty("Accept-Encoding", "gzip, deflate");
// con.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");
// con.setRequestProperty("Connection", "keep-alive");
// con.setRequestProperty("Cookie", "insert_cookie=57838640");
// con.setRequestProperty("Host", "dxpvote.svccloud.cn");
// con.setRequestProperty("Referer", "http://vweb.svccloud.cn/");
// con.setRequestProperty("User-Agent",
// "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
// con.connect();// 获取连接
//
// in = con.getInputStream();
// byte[] buf = new byte[1024];
//
// String str = "";
// while (in.read(buf) != -1) {
// str += new String(buf);
// }
// System.out.println(str);
return filename;
} finally {
if (out != null) {
out.close();
}
if (null != in)
in.close();
}
}
/**
* 返回图片byte数组
*
* @return
* @throws IOException
*/
public static byte[] getImageBytes() throws IOException {
System.out.println("获取验证码");
String uri = "http://vweb.svccloud.cn/#/mainIndex";
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "*/*;");
con.setRequestProperty("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
con.setRequestProperty("Accept-Encoding", "gzip, deflate");
con.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");
con.setRequestProperty("Connection", "keep-alive");
con.setRequestProperty("Host", "dxpvote.svccloud.cn");
con.setRequestProperty("Referer", "http://vweb.svccloud.cn/");
con.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
con.connect();// 获取连接
while (new BufferedInputStream(con.getInputStream()).read(new byte[1024]) != -1) {
}
con.disconnect();
uri = "http://dxpvote.svccloud.cn/vote/get/imgCode";
url = new URL(uri);
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "image/webp,image/apng,image/*,*/*;q=0.8");
con.setRequestProperty("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
con.setRequestProperty("Accept-Encoding", "gzip, deflate");
con.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");
con.setRequestProperty("Connection", "keep-alive");
// con.setRequestProperty("Cookie", String.format("insert_cookie=%s", cookie));
con.setRequestProperty("Host", "dxpvote.svccloud.cn");
con.setRequestProperty("Referer", "http://vweb.svccloud.cn/");
con.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
con.connect();// 获取连接
try (InputStream in = new BufferedInputStream(con.getInputStream())) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
int len;
byte[] b = new byte[1024];
while ((len = in.read(b)) != -1) {
out.write(b, 0, len);
}
return out.toByteArray();
}
}
public static String vote(String code) {
//全国
// String uri = "http://dxpvote.svccloud.cn/vote/save?choice_id=36&poll_id=2&uuid=" + UUID.randomUUID() + "&img_code=" + code;
//福建
String uri = "http://dxpvote.svccloud.cn/vote/save?choice_id=19&poll_id=2&uuid=" + UUID.randomUUID() + "&img_code=" + code;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/json, text/plain, */*");
con.setRequestProperty("Accept-Encoding", "gzip, deflate");
con.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");
con.setRequestProperty("Connection", "keep-alive");
con.setRequestProperty("Content-Length", "0");
// con.setRequestProperty("Cookie", String.format("insert_cookie=%s", cookie));
con.setRequestProperty("Host", "dxpvote.svccloud.cn");
con.setRequestProperty("Origin", "http://vweb.svccloud.cn");
con.setRequestProperty("Referer", "http://vweb.svccloud.cn/");
con.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
con.connect();// 获取连接
try (InputStream in = con.getInputStream()) {
// 1.创建内存输出流,将读到的数据写到内存输出流中
ByteArrayOutputStream bos = new ByteArrayOutputStream();
// 2.创建字节数组
byte[] arr = new byte[1024];
int len;
while (-1 != (len = in.read(arr))) {
bos.write(arr, 0, len);
}
// 3.将内存输出流的数据全部转换为字符串
String s = bos.toString("utf-8");
System.out.println("s = " + s);
// System.out.println(cookie);
if (s.contains("验证码输入错误")) {
return "验证码输入错误";
} else if (s.contains("验证码已失效")) {
return "验证码已失效";
} else if (s.contains("false")) {
return String.format("投票失败:%s", s);
} else {
return "投票成功";
}
}
} catch (IOException e) {
return "投票失败:服务器异常";
}
}
public synchronized static void generateCookie() {
StringBuilder str = new StringBuilder();
for (int i = 0; i < 8; i++) {
if (i == 0) {
str.append(new Random().nextInt(4) + 4);
} else {
str.append(new Random().nextInt(10));
}
}
cookie = str.toString();
}
}
|
package com.shangdao.phoenix.entity.report.strategy;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shangdao.phoenix.entity.apisearch.APISearchRepository;
import com.shangdao.phoenix.entity.report.Report;
import com.shangdao.phoenix.entity.report.module.BaseModule;
import com.shangdao.phoenix.entity.report.module.CourtRuledDetail;
import com.shangdao.phoenix.entity.report.module.CourtRuledMoudle;
import com.shangdao.phoenix.entity.supplyAPI.SupplyAPI;
import com.shangdao.phoenix.entity.supplyAPI.SupplyAPIRepository;
import com.shangdao.phoenix.enums.Color;
import com.shangdao.phoenix.util.AliyunCallable;
import com.shangdao.phoenix.util.XinShuCallable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class CourtRuledSuspectedStrategy extends BaseStrategy {
private static final Logger logger = LoggerFactory.getLogger(CourtRuledStrategy.class);
private final static long COURT_API_ID = 19L;
private final static long IDCARD_API_ID = 1L;
private final SupplyAPI idcard_api;
private final SupplyAPI court_api;
private JSONObject idcardResponse;
private JSONObject courtResponse;
public CourtRuledSuspectedStrategy(Report report, SupplyAPIRepository supplyAPIRepository,
APISearchRepository apiSearchRepository) {
super(report, supplyAPIRepository, apiSearchRepository);
this.idcard_api = supplyAPIRepository.findOne(IDCARD_API_ID);
this.court_api = supplyAPIRepository.findOne(COURT_API_ID);
}
@Override
public boolean isAPIActive() {
return idcard_api.getEnabled() && court_api.getEnabled();
}
@Override
public boolean isContainsAPI(Map<String, JSONObject> pool) {
return pool.containsKey(idcard_api.getCode()) && pool.containsKey(court_api.getCode());
}
@Override
public boolean isAPIUnfinished(Map<String, JSONObject> pool) {
return EMPTY_JSON.equals(pool.get(idcard_api.getCode())) || EMPTY_JSON.equals(pool.get(court_api.getCode()));
}
private boolean isParameterComplete() {
return super.report.getCustomerName() != null && super.report.getCustomerIdCard() != null;
}
@Override
public void tryPutEmptyAPI(Map<String, JSONObject> pool) {
pool.put(idcard_api.getCode(), EMPTY_JSON);
pool.put(court_api.getCode(), EMPTY_JSON);
}
@Override
public void removeEmptyAPI(Map<String, JSONObject> pool) {
pool.remove(idcard_api.getCode());
pool.remove(court_api.getCode());
}
@Override
public void putAPIResponseIntoPool(Map<String, JSONObject> pool) {
if (idcardResponse != null && !EMPTY_JSON.equals(idcardResponse)) {
pool.put(idcard_api.getCode(), idcardResponse);
}
if (courtResponse != null && !EMPTY_JSON.equals(courtResponse)) {
pool.put(court_api.getCode(), courtResponse);
}
}
@Override
public boolean fetchData(Map<String, JSONObject> pool) {
JSONObject idcardResponse = pool.get(idcard_api.getCode());
JSONObject courtResponse = pool.get(court_api.getCode());
boolean isIdcardFetched = false;
boolean isCourtFetched = false;
if (idcardResponse != null && !EMPTY_JSON.equals(idcardResponse)) {
this.idcardResponse = idcardResponse;
isIdcardFetched = true;
}
if (courtResponse != null && !EMPTY_JSON.equals(courtResponse)) {
this.courtResponse = courtResponse;
isCourtFetched = true;
}
if (isIdcardFetched && isCourtFetched) {
return true;
}
if (!isIdcardFetched) {
API api = new API();
api.setSupplyAPI(idcard_api);
api.getParameters().put("idcard", super.report.getCustomerIdCard());
JSONObject cacheData = getCache(api);
if (cacheData != null) {
logger.info("缓存查询" + idcard_api.getCode());
} else {
logger.info("即时查询" + idcard_api.getCode());
AliyunCallable aliyunCallable = new AliyunCallable(api.getSupplyAPI(), new HashMap<>(),
api.getParameters(), "", supplyAPIRepository);
cacheData = aliyunCallable.call();
logger.info(this.idcard_api.getCode() + " response:" + cacheData);
if (cacheData != null && "0".equals(cacheData.getString("status"))) {
putCache(api, cacheData);
}
}
if (cacheData != null) {
isIdcardFetched = true;
this.idcardResponse = cacheData;
}
}
if (!isCourtFetched) {
API api = new API();
api.setSupplyAPI(court_api);
api.getParameters().put("q", super.report.getCustomerName());
api.getParameters().put("pageno", "1");
api.getParameters().put("range", "100");
api.getParameters().put("datatype", "");
JSONObject cacheData = getCache(api);
if (cacheData != null) {
logger.info("缓存查询" + court_api.getCode());
} else {
logger.info("即使查询" + court_api.getCode());
XinShuCallable xinShuCallable = new XinShuCallable(api.getSupplyAPI(), new HashMap<>(),
api.getParameters(), "", supplyAPIRepository);
cacheData = xinShuCallable.call();
logger.info(this.court_api.getCode() + "response:" + cacheData);
if (cacheData != null
&& ("0000".equals(cacheData.getString("rc")) || "0001".equals(cacheData.getString("rc")))) {
putCache(api, cacheData);
}
}
if (cacheData != null) {
isCourtFetched = true;
this.courtResponse = cacheData;
}
}
return !(!isIdcardFetched && !isCourtFetched);
}
@Override
public BaseModule analyseData() {
CourtRuledMoudle courtRuledMoudle = new CourtRuledMoudle(Color.SUCCESS);
if (courtResponse != null) {
if ("0000".equals(courtResponse.getString("rc"))) {
JSONObject data = courtResponse.getJSONObject("data");
JSONArray allList = data.getJSONArray("allList");
Set<CourtRuledDetail> courtRuledDetails = selectAllList(allList, courtRuledMoudle);
courtRuledMoudle.setCourtRuledDetails(courtRuledDetails);
courtRuledMoudle.setCount(courtRuledDetails.size());
} else if ("0001".equals(courtResponse.getString("rc"))) {
courtRuledMoudle.setCount(0);
} else {
courtRuledMoudle.setColor(Color.ERROR);
}
} else {
courtRuledMoudle.setColor(Color.TIMEOUT);
}
return courtRuledMoudle;
}
@Override
public void setModuleIntoReport(BaseModule module) {
CourtRuledMoudle courtRuleSuspecteddMoudle = (CourtRuledMoudle) module;
super.report.setCourtRuledSuspectedMoudle(courtRuleSuspecteddMoudle);
}
////////////////////////////////////////////////////////////////////////////////////////////////
// 后续处理疑似案件
private Set<CourtRuledDetail> selectAllList(JSONArray suspectedArray, CourtRuledMoudle moudle) {
Set<CourtRuledDetail> courtRuledDetails = new HashSet<CourtRuledDetail>();
if (suspectedArray != null && suspectedArray.size() > 0) {
for (Object object : suspectedArray) {
JSONObject suspectedObject = (JSONObject) object;
if (suspectedObject.containsKey("cpwsId") && analyCpws(suspectedObject)) {
CourtRuledDetail cpwsdDetail = new CourtRuledDetail(suspectedObject, moudle);
courtRuledDetails.add(cpwsdDetail);
continue;
} else if (suspectedObject.containsKey("ktggId") && analyKtgg(suspectedObject)) {
CourtRuledDetail ktggDetail = new CourtRuledDetail(suspectedObject, moudle);
courtRuledDetails.add(ktggDetail);
continue;
} else if (suspectedObject.containsKey("zxggId") && analyZxgg(suspectedObject)) {
CourtRuledDetail zxggdDetail = new CourtRuledDetail(suspectedObject, moudle);
courtRuledDetails.add(zxggdDetail);
continue;
} else if (suspectedObject.containsKey("sxggId") && analySxgg(suspectedObject)) {
CourtRuledDetail sxggdDetail = new CourtRuledDetail(suspectedObject, moudle);
courtRuledDetails.add(sxggdDetail);
continue;
} else if (suspectedObject.containsKey("fyggId") && analyFygg(suspectedObject)) {
CourtRuledDetail fyggdDetail = new CourtRuledDetail(suspectedObject, moudle);
courtRuledDetails.add(fyggdDetail);
continue;
}
}
}
return courtRuledDetails;
}
//////////////////具体处理疑似案件的方法
private boolean analyCpws(JSONObject cpws) {
return false;
}
private boolean analyKtgg(JSONObject ktgg) {
return false;
}
private boolean analySxgg(JSONObject sxgg) {
return false;
}
private boolean analyZxgg(JSONObject zxgg) {
return false;
}
private boolean analyFygg(JSONObject fygg) {
return false;
}
}
|
/*
* (C) Mississippi State University 2009
*
* The WebTOP employs two licenses for its source code, based on the intended use. The core license for WebTOP applications is
* a Creative Commons GNU General Public License as described in http://*creativecommons.org/licenses/GPL/2.0/. WebTOP libraries
* and wapplets are licensed under the Creative Commons GNU Lesser General Public License as described in
* http://creativecommons.org/licenses/*LGPL/2.1/. Additionally, WebTOP uses the same licenses as the licenses used by Xj3D in
* all of its implementations of Xj3D. Those terms are available at http://www.xj3d.org/licenses/license.html.
*/
package org.webtop.module.threemedia;
import org.webtop.x3d.X3DObject;
import org.web3d.x3d.sai.*;
import org.webtop.component.*;
import org.webtop.util.*;
import org.webtop.x3d.*;
public abstract class WaveSource extends X3DObject {
static protected float speed = 1;
protected float amplitude;
protected float wavelength;
protected float phase;
protected float X;
protected float Y;
protected float k;
protected boolean widgetVisible = false;
protected Engine engine;
protected SourcePanel sourcePanel;
protected StatusBar statusBar;
protected SFBool set_enabled;
protected SFFloat set_amplitude;
protected SFFloat set_wavelength;
protected SFFloat set_phase;
protected SFVec3f set_position;
protected SFBool set_widgetVisible;
public static final float MAX_AMPLITUDE = 10.0f;
public static final float MAX_WAVELENGTH = 50.0f;
public static final float MAX_PHASE = (float) (4.0 * Math.PI);
public static final int TYPE_NONE = 0;
public static final int TYPE_LINEAR = 1;
protected String id;
//Constructor
public WaveSource(Engine e, SourcePanel panel, StatusBar bar) {
super(e.getSAI(),e.getSAI().getNode("Widget-TRANSFORM"));
amplitude = wavelength = phase = k = 0.0f;
engine = e;
sourcePanel = panel;
statusBar = bar;
}
//Constructor 2
public WaveSource(Engine e, SourcePanel panel, StatusBar bar, float A, float L, float E, float x, float y) {
super(e.getSAI(),e.getSAI().getNode("Widget-TRANSFORM"));
engine = e;
sourcePanel = panel;
statusBar = bar;
amplitude = A;
wavelength = L;
phase = E;
X = x;
Y = y;
k = (float) (2 * Math.PI / wavelength);
}
public String getID() {
return id;
}
public void setID(String ID) {
id = ID;
}
public float getAmplitude() {
return amplitude;
}
public float getWavelength() {
return wavelength;
}
public float getPhase() {
return phase;
}
public float getX() {
return X;
}
public float getY() {
return Y;
}
public void setAmplitude(float A, boolean setVRML) {
amplitude = A;
if(amplitude<0) amplitude=0;
else if(amplitude>MAX_AMPLITUDE) amplitude = MAX_AMPLITUDE;
if(setVRML) set_amplitude.setValue(amplitude);
}
public void setWavelength(float L, boolean setVRML) {
wavelength = L;
if(wavelength<0) wavelength = 0;
else if(wavelength>MAX_WAVELENGTH) wavelength = MAX_WAVELENGTH;
k = (float) (2 * Math.PI / wavelength);
if(setVRML) {
set_wavelength.setValue(wavelength);
}
}
public void setPhase(float E, boolean setVRML) {
phase = E;
if(phase<0) phase = 0;
else if(phase>MAX_PHASE) phase = MAX_PHASE;
if(setVRML) set_phase.setValue(phase);
}
public void setXY(float xy[], boolean setVRML) {
float xyz[] = new float[3];
if(xy[0]<-50) xy[0] = -50;
else if(xy[0]>50) xy[0] = 50;
if(xy[1]<-50) xy[1] = -50;
else if(xy[1]>50) xy[1] = 50;
X = xyz[0] = xy[0];
Y = xyz[1] = xy[1];
xyz[2] = 0;
if(setVRML) set_position.setValue(xyz);
}
public void setXY(float x, float y, boolean setVRML) {
float xyz[] = new float[3];
if(x<-50) x = -50;
else if(x>50) x = 50;
if(y<-50) y = -50;
else if(y>50) y = 50;
X = xyz[0] = x;
Y = xyz[1] = y;
xyz[2] = 0;
if(setVRML) set_position.setValue(xyz);
}
public void setX(float x, boolean setVRML) {
float xyz[] = new float[3];
if(x<-50) x = -50;
else if(x>50) x = 50;
X = xyz[0] = x;
xyz[1] = Y;
xyz[2] = 0;
if(setVRML) set_position.setValue(xyz);
}
public void setY(float y, boolean setVRML) {
float xyz[] = new float[3];
if(y<-50) y = -50;
else if(y>50) y = 50;
xyz[0] = X;
Y = xyz[1] = y;
xyz[2] = 0;
if(setVRML) set_position.setValue(xyz);
}
public void setEnabled(boolean enabled) {
set_enabled.setValue(enabled);
}
public void showWidgets() {
set_widgetVisible.setValue(true);
widgetVisible = true;
}
public void hideWidgets() {
set_widgetVisible.setValue(false);
widgetVisible = false;
}
public boolean getWidgetVisible() {
return widgetVisible;
}
public abstract float getValue(float x, float y, float t);
//Oh, this is really brilliant! Who knew that every LinearSource was equivalent to every other? [Davis]
public boolean equals(Object obj) {return obj instanceof LinearSource && this instanceof LinearSource;}
}
|
/*
* ============================================================================
* = COPYRIGHT
* PAX TECHNOLOGY, Inc. PROPRIETARY INFORMATION
* This software is supplied under the terms of a license agreement or
* nondisclosure agreement with PAX Technology, Inc. and may not be copied
* or disclosed except in accordance with the terms in that agreement.
* Copyright (C) 2009-2020 PAX Technology, Inc. All rights reserved.
* ============================================================================
*/
package com.xzm.app.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import org.springframework.security.core.GrantedAuthority;
@Entity(name="authority")
public class Authority extends BaseModel implements GrantedAuthority{
private static final long serialVersionUID = 1L;
@Column(name="name",nullable=false,unique=true,columnDefinition="varchar(255)")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String getAuthority() {
return name;
}
}
|
package com.distribute.TeamDistribute.service;
import java.awt.PageAttributes.MediaType;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.distribute.TeamDistribute.Global;
import com.distribute.TeamDistribute.model.Node;
@Service
public class RegisterService {
public Map<String, String> registerNode(String ip,String port,Map<String, String> message) {
Map<String, String> result = new HashMap<>();
DatagramSocket receiveSock = null;
try{
receiveSock = new DatagramSocket(Integer.parseInt(Global.nodePort)+2);
receiveSock.setSoTimeout(10000);
byte[] buffer = new byte[65536];
DatagramPacket incoming = new DatagramPacket(buffer, buffer.length);
String init_request = "REG " + ip + " " + port + " " + message.get("user");
int length = init_request.length() + 5;
init_request = String.format("%04d", length) + " " + init_request;
DatagramPacket regrequest = new DatagramPacket(init_request.getBytes(), init_request.getBytes().length,
InetAddress.getByName(Global.bootstrapServerIp), Global.bootstrapServerPort);
receiveSock.send(regrequest);
receiveSock.receive(incoming);
receiveSock.close();
byte[] data = incoming.getData();
String s = new String(data, 0, incoming.getLength());
System.out.println(s);
String[] values = s.split(" ");
String command = values[1];
if(command.equals("REGOK")){
int noOfNodes = Integer.parseInt(values[2]);
if(noOfNodes == 0){
Global.startHeartBeat();
result.put("success", "true");
result.put("result", "Node Successfully registered");
}
else if(noOfNodes == 9999) {
result.put("success", "false");
result.put("result", "There is some error in the command");
}
else if(noOfNodes == 9998) {
result.put("success", "false");
result.put("result", "Already registered you, unregister first");
}
else if(noOfNodes == 9997) {
result.put("success", "false");
result.put("result", "Registered to another user, try a different IP and port");
}
else if(noOfNodes == 9996) {
result.put("success", "false");
result.put("result", "Can’t register, BS full");
}
else if(noOfNodes==1) {
String neighbourIp = values[3];
String neighbourPort = values[4];
String uri="http://"+neighbourIp+":"+neighbourPort+"/join";
RestTemplate restTemplate = new RestTemplate();
Map<String,String> node=new HashMap<>();
node.put("ip", Global.nodeIp);
node.put("port", Global.nodePort);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(org.springframework.http.MediaType.APPLICATION_JSON);
HttpEntity<Map> entity = new HttpEntity<Map>(node,headers);
int answer = 1;
try{
answer = restTemplate.postForObject(uri, entity, Integer.class);
}
catch(Exception e){
e.printStackTrace();
}
node.put("ip", neighbourIp);
node.put("port", neighbourPort);
if(answer==0) {
Global.neighborTable.add(node);
}
System.out.println("Neighbour value "+node.get("ip")+" "+node.get("port"));
result.put("success", "true");
result.put("result", "Node Successfully registered");
Global.startHeartBeat();
}
else {
String neighbourIp = values[3];
String neighbourPort = values[4];
String uri="http://"+neighbourIp+":"+neighbourPort+"/join";
RestTemplate restTemplate = new RestTemplate();
Map<String,String> node=new HashMap<>();
node.put("ip", Global.nodeIp);
node.put("port", Global.nodePort);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(org.springframework.http.MediaType.APPLICATION_JSON);
HttpEntity<Map> entity = new HttpEntity<Map>(node,headers);
int answer = 1;
try{
answer = restTemplate.postForObject(uri, entity, Integer.class);
}
catch(Exception e){
e.printStackTrace();
}
Map<String, String> neighbour = new HashMap<String,String>();
if(answer==0) {
neighbour.put("ip", neighbourIp);
neighbour.put("port", neighbourPort);
Global.neighborTable.add(neighbour);
}
System.out.println("My value "+node.get("ip")+" "+node.get("port"));
neighbourIp = values[5];
neighbourPort = values[6];
uri="http://"+neighbourIp+":"+neighbourPort+"/join";
try{
answer = restTemplate.postForObject(uri, entity, Integer.class);
}
catch(Exception e){
answer = 1;
e.printStackTrace();
}
if(answer==0) {
Map<String, String> neighbour2 = new HashMap<String,String>();
neighbour2.put("ip", neighbourIp);
neighbour2.put("port", neighbourPort);
Global.neighborTable.add(neighbour2);
}
System.out.println("My value "+node.get("ip")+" "+node.get("port"));
result.put("success", "true");
result.put("result", "Node Successfully registered");;
Global.startHeartBeat();
}
}
}
catch (SocketException e) {
e.printStackTrace();
receiveSock.close();
result.put("success", "false");
result.put("result", e.toString());
} catch (IOException e) {
e.printStackTrace();
receiveSock.close();
result.put("success", "false");
result.put("result", e.toString());
}
return result;
}
}
|
package com.bcreagh.data;
public class NodeInfo {
private int blockNumber;
private int positionNumber;
public int getBlockNumber() {
return blockNumber;
}
public void setBlockNumber(int blockNumber) {
this.blockNumber = blockNumber;
}
public int getPositionNumber() {
return positionNumber;
}
public void setPositionNumber(int positionNumber) {
this.positionNumber = positionNumber;
}
}
|
package googlemaps.learn.smktelkom_mlg.sch.id.googlemapsxiirpl117;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import static googlemaps.learn.smktelkom_mlg.sch.id.googlemapsxiirpl117.MainActivity.JUDUL;
public class PlaceMarkerActivity extends AppCompatActivity implements OnMapReadyCallback {
static final CameraPosition SMKTELKOMMALANG = CameraPosition.builder()
.target(new LatLng(-7.97683, 112.6567693))
.zoom(14)
.bearing(0)
.tilt(45)
.build();
GoogleMap m_map;
boolean mapReady = false;
MarkerOptions masjid;
MarkerOptions roker;
MarkerOptions cafe;
MarkerOptions bni;
MarkerOptions bpbd;
@Override
public Resources getResources() {
return super.getResources();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place_marker);
Intent intent = getIntent();
String judul = intent.getStringExtra(JUDUL);
setTitle(judul);
masjid = new MarkerOptions()
.position(new LatLng(-7.97683, 112.6567693))
.title("Masjid Manarul Islam")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher));
bni = new MarkerOptions()
.position(new LatLng(-7.97683, 112.6567693))
.title("Pasar Sawojajar")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher));
roker = new MarkerOptions()
.position(new LatLng(-7.97683, 112.6567693))
.title("Warung Ayam Roker")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher));
cafe = new MarkerOptions()
.position(new LatLng(-7.97683, 112.6567693))
.title("Urban Pop Cafe")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher));
bni = new MarkerOptions()
.position(new LatLng(-7.97683, 112.6567693))
.title("BNI Sawojajar")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher));
bpbd = new MarkerOptions()
.position(new LatLng(-7.97683, 112.6567693))
.title("BPBD Kota Malang")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher));
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap map) {
//MapsInitializer.initialize(getApplicationContext());
mapReady = true;
m_map = map;
m_map.addMarker(masjid);
m_map.addMarker(bni);
m_map.addMarker(roker);
m_map.addMarker(cafe);
m_map.addMarker(bni);
m_map.addMarker(bpbd);
flyTo(SMKTELKOMMALANG);
}
private void flyTo(CameraPosition target) {
m_map.moveCamera(CameraUpdateFactory.newCameraPosition(target));
}
}
|
package swissre;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import swissre.model.CurrencyCode;
import swissre.model.ExchangeRateChange;
import swissre.model.FlaggedChange;
import swissre.parser.InvalidExchangeRateFileException;
import swissre.parser.Parser;
import swissre.parser.StringParser;
import swissre.persistence.DataStore;
import java.time.LocalDateTime;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
class StringParserTest {
private Parser<String> stringParser;
private DataStore dataStoreStub;
@BeforeEach
void setUp() {
// simple stub just to record the data passed to the store, obviously would usually be mocked.
this.dataStoreStub = new DataStore() {
Set<ExchangeRateChange> recordedExchangeRates = new HashSet<>();
@Override
public Set<ExchangeRateChange> getExchangeRateChanges() {
return recordedExchangeRates;
}
@Override
public void record(ExchangeRateChange exchangeRateChange) {
recordedExchangeRates.add(exchangeRateChange);
}
@Override
public List<FlaggedChange> getFlaggedChanges() {
return null;//ignored
}
@Override
public Map<String, Double> getAveragesByMonth(CurrencyCode currencyCode) {
return null;//ignored
}
@Override
public Map<Integer, Double> getAveragesByYear(CurrencyCode currencyCode) {
return null;//ignored
}
};
this.stringParser = new StringParser(dataStoreStub);
}
@Test
void shouldFailToReceiveFileWithoutStartOfFile() {
String emptyFirstLine = "invalid value";
InvalidExchangeRateFileException exception = callReceiveAndCaptureException(emptyFirstLine);
String message = exception.getMessage();
assertEquals("Expected 'START-OF-FILE' on line 1, found 'invalid value'", message);
}
/**
* For the purpose of the exercise I am assuming that the field list wouldn't change order, nor would fields
* be added or removed.
*/
@Test
void shouldReceiveFileGivenTrailingAdditionalParameters() throws InvalidExchangeRateFileException {
stringParser.receiveFile("START-OF-FILE\n" +
"DATE=20181015\n" +
"ADDITIONAL=parameter\n" +
"START-OF-FIELD-LIST\n" +
"CURRENCY\n" +
"EXCHANGE_RATE\n" +
"LAST_UPDATE\n" +
"END-OF-FIELD-LIST\n" +
"START-OF-EXCHANGE-RATES\n" +
"CHF|0.9832|17:12:59 10/14/2018|\n" +
"END-OF-EXCHANGE-RATES\n" +
"END-OF-FILE");
assertEquals(1, dataStoreStub.getExchangeRateChanges().size());
}
@Test
void shouldReceiveFileGivenBlankLinesInFile() throws InvalidExchangeRateFileException {
stringParser.receiveFile("\nSTART-OF-FILE\n\n" +
"DATE=20181015\n\n" +
"ADDITIONAL=parameter\n\n" +
"START-OF-FIELD-LIST\n\n" +
"CURRENCY\n\n" +
"EXCHANGE_RATE\n\n" +
"LAST_UPDATE\n\n" +
"END-OF-FIELD-LIST\n\n" +
"START-OF-EXCHANGE-RATES\n\n" +
"CHF|0.9832|17:12:59 10/14/2018|\n\n" +
"END-OF-EXCHANGE-RATES\n\n" +
"END-OF-FILE\n\n");
assertEquals(1, dataStoreStub.getExchangeRateChanges().size());
}
@Test
void shouldReceiveFileGivenWindowsStyleLineEndings() throws InvalidExchangeRateFileException {
stringParser.receiveFile("START-OF-FILE\r\n" +
"DATE=20181015\r\n" +
"ADDITIONAL=parameter\r\n" +
"START-OF-FIELD-LIST\r\n" +
"CURRENCY\r\n" +
"EXCHANGE_RATE\r\n" +
"LAST_UPDATE\r\n" +
"END-OF-FIELD-LIST\r\n" +
"START-OF-EXCHANGE-RATES\r\n" +
"CHF|0.9832|17:12:59 10/14/2018|\r\n" +
"END-OF-EXCHANGE-RATES\r\n" +
"END-OF-FILE\r\n");
assertEquals(1, dataStoreStub.getExchangeRateChanges().size());
}
@SuppressWarnings("unchecked")
@Test
void shouldReceiveFileGivenManyRateChanges() throws InvalidExchangeRateFileException {
stringParser.receiveFile("START-OF-FILE\n" +
"DATE=20181015\n" +
"START-OF-FIELD-LIST\n" +
"CURRENCY\n" +
"EXCHANGE_RATE\n" +
"LAST_UPDATE\n" +
"END-OF-FIELD-LIST\n" +
"START-OF-EXCHANGE-RATES\n" +
"CHF|0.9832|17:12:59 10/14/2018|\n" +
"GBP|0.7849|17:12:59 10/14/2018|\n" +
"EUR|0.8677|17:13:00 10/14/2018|\n" +
"CAD|0.9999|13:13:00 02/11/2019|\n" +
"END-OF-EXCHANGE-RATES\n" +
"END-OF-FILE");
Set<ExchangeRateChange> exchangeRateChanges = new HashSet(Arrays.asList(
new ExchangeRateChange(
"CHF",
LocalDateTime.parse("2018-10-14T17:12:59"),
0.9832),
new ExchangeRateChange(
"GBP",
LocalDateTime.parse("2018-10-14T17:12:59"),
0.7849),
new ExchangeRateChange(
"EUR",
LocalDateTime.parse("2018-10-14T17:13:00"),
0.8677),
new ExchangeRateChange(
"CAD",
LocalDateTime.parse("2019-02-11T13:13:00"),
0.9999)
));
assertTrue(dataStoreStub.getExchangeRateChanges().containsAll(exchangeRateChanges));
assertEquals(4, dataStoreStub.getExchangeRateChanges().size());
}
@Test
void shouldFailToReceiveGivenMissingEndOfExchangeRates() {
String fileWithMissingEndOfExchangeRates = "START-OF-FILE\n" +
"DATE=20181015\n" +
"START-OF-EXCHANGE-RATES\n" +
"CHF|0.9832|17:12:59 10/14/2018|\n" +
"END-OF-FILE";
InvalidExchangeRateFileException exception = callReceiveAndCaptureException(fileWithMissingEndOfExchangeRates);
String message = exception.getMessage();
assertEquals("Unexpected exchange rate format found unable to parse 'END-OF-FILE' on line 5", message);
}
@Test
void shouldFailToReceiveGivenMissingEndOfFile() {
String fileWithMissingEndOfExchangeRates = "START-OF-FILE\n" +
"DATE=20181015\n" +
"START-OF-EXCHANGE-RATES\n" +
"CHF|0.9832|17:12:59 10/14/2018|\n" +
"END-OF-EXCHANGE-RATES";
InvalidExchangeRateFileException exception = callReceiveAndCaptureException(fileWithMissingEndOfExchangeRates);
String message = exception.getMessage();
assertEquals("Unexpected end of file", message);
}
private InvalidExchangeRateFileException callReceiveAndCaptureException(String file) {
return assertThrows(InvalidExchangeRateFileException.class, () -> stringParser.receiveFile(file));
}
} |
package stormedpanda.simplyjetpacks.client.particle;
import net.minecraft.client.Minecraft;
import net.minecraft.client.particle.ParticleManager;
import net.minecraft.particles.BasicParticleType;
import net.minecraft.particles.ParticleType;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.ParticleFactoryRegisterEvent;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import stormedpanda.simplyjetpacks.SimplyJetpacks;
@Mod.EventBusSubscriber(modid = SimplyJetpacks.MODID, bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT)
public class SJParticles {
public static final BasicParticleType RAINBOW = new BasicParticleType(false);
@SubscribeEvent
public static void registerParticleTypes(RegistryEvent.Register<ParticleType<?>> evt) {
RAINBOW.setRegistryName(SimplyJetpacks.MODID, "rainbow");
evt.getRegistry().registerAll(RAINBOW);
}
@SubscribeEvent
public static void registerParticleFactories(ParticleFactoryRegisterEvent event) {
ParticleManager manager = Minecraft.getInstance().particles;
manager.registerFactory(SJParticles.RAINBOW, ParticleRainbow.Factory::new);
}
} |
package com.epam.excercise.excelToXml.service;
import com.epam.excercise.excelToXml.model.Product;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ExcelToProductExtractor {
public List<Product> extract(File excelFile) throws EncryptedDocumentException,
InvalidFormatException, IOException {
List<Product> products = new ArrayList<>();
Workbook workbook = WorkbookFactory.create(excelFile);
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
if (!isHeader(row)) {
Product product = createProductFromRow(row);
products.add(product);
}
}
workbook.close();
return products;
}
private boolean isHeader(Row row) {
return row.getRowNum() == 0;
}
private Product createProductFromRow(Row row) {
String name = row.getCell(0).getStringCellValue();
double price = row.getCell(1).getNumericCellValue();
int amount = (int) row.getCell(2).getNumericCellValue();
return new Product(name, price, amount);
}
}
|
package org.rundeck.client.tool.commands.enterprise.api.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import org.rundeck.client.util.DataOutput;
import java.util.HashMap;
import java.util.Map;
@JsonIgnoreProperties(ignoreUnknown = true)
@Getter @Setter
public class LicenseStoreResponse
implements DataOutput
{
String error;
String message;
String licenseAgreement;
@Override
public Map<?, ?> asMap() {
HashMap<String, String> map = new HashMap<>();
map.put("error", error);
map.put("message", message);
map.put("licenseAgreement", licenseAgreement);
return map;
}
}
|
package com.baidu.timework;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.baidu.serivce.UpdateServerInfosService;
/**
* <p>
* Created by mayongbin01 on 2017/1/23.</p>
*/
@Component
public class ScheduledTasks {
private static Logger logger = LoggerFactory.getLogger(ScheduledTasks.class);
@Autowired
private UpdateServerInfosService updateServerInfosService;
@Scheduled(fixedDelay = 24 * 60 * 60 * 24000)
public void updateServers() {
updateServerInfosService.autoUpdate();
logger.info("auto update!......");
}
}
|
package com.maliang.core.service;
/**
* Map Reader
* **/
public class MR {
public static Object readValue(Object obj,String fname){
return MapHelper.readValue(obj, fname);
}
public static void setValue(Object obj,String name,Object keyValue){
MapHelper.setValue(obj, name, keyValue);
}
}
|
package com.metoo.module.app.test.httpclient;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import com.google.gson.Gson;
/**
* <p>
* @Title: HttpRestTemplate.java
* </p>
*
* <p>
* @description: 0,使用 application/x-www-form-urlencoded 这个请求头 会对数据镜像 url 编码;可以传递 非 字符串类型的数据!
* 1,exchange()可以指定HttpMethod,请求体requestEntity,建议在开发中使用exchange方法
* 2,https://docs.spring.io/spring-framework/docs/current/reference/html/integration.html#rest-resttemplate
*
* </P>
* @author 46075
*
*/
@Component
public class HttpRestTemplateUtil {
@Autowired
private HttpUtil httpUtil;
// 建议以注入方式使用 @Configuration
public String restTemplate(String url, String content, String mobile) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
// headers.add("Content-Type", "application/x-www-form-urlencoded");
// timestamp:long类型时间戳--转String
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<Object, Object> params = new LinkedMultiValueMap<Object, Object>();
params.add("smsContent", content);
long timestamp = this.httpUtil.getTimestamp();
params.add("to", mobile);
params.add("timestamp", String.valueOf(timestamp));
String sig = this.httpUtil.getMD5("d5318078b04d4a7b94502a38d8ca34d8", timestamp);
params.add("sig", sig);
params.add("accountSid", "d5318078b04d4a7b94502a38d8ca34d8");
HttpEntity<MultiValueMap<Object, Object>> httpEntity = new HttpEntity<MultiValueMap<Object, Object>>(params, headers);
ResponseEntity<String> exchange = restTemplate.postForEntity(url, httpEntity, String.class);
return exchange.getBody().toString();
}
}
|
package by.htp.airline10.main;
import java.util.List;
import java.util.ArrayList;
public class Group {
private List<Airline> airline;
public Group() {
airline = new ArrayList<Airline>();
}
public List<Airline> add(Airline newAirline) {
airline.add(newAirline);
return airline;
}
public List<Airline> getAirline() {
return airline;
}
public void setAirline(List<Airline> airline) {
this.airline = airline;
}
}
|
package smallTest;
import java.io.FileInputStream;
import java.util.Scanner;
import java.util.Stack;
public class Test1 {
static int N;
static int AnswerN;
public static void main(String[] args) throws Exception {
System.setIn(new FileInputStream("src\\inputText.txt"));
Scanner s = new Scanner(System.in);
int T;
T = s.nextInt(); // T = 5
for (int test_case = 1; test_case <= T; test_case++) {
N = s.nextInt();
char[] E = s.nextLine().toCharArray();
// System.out.println(N);
// System.out.println(E.length);
Stack<String> stack = new Stack<String>();
for (int i = N; i < E.length; i++) {
if (E[i] == '(') {
stack.push(String.valueOf(E[i]));
} System.out.println(stack);
}
}
}
} |
package training.arraylist;
import java.util.*;
/**
* @author Hurt Yevhenii
*/
public class MyArrayList <E> implements List <E> {
public static final int DEFAULT_CAPACITY = 10;
private int modificationCount;
private int size;
Object[] arr;
public MyArrayList() {
size = 0;
arr = new Object[DEFAULT_CAPACITY];
modificationCount = 0;
}
public MyArrayList(int initialSize) {
if(initialSize < 0) {
throw new IllegalArgumentException();
} else {
size = 0;
arr = new Object[initialSize];
modificationCount = 0;
}
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public boolean contains(Object o) {
if(o == null) {
for (int i = 0; i < size; i++) {
if(arr[i] == null) {
return true;
}
}
} else {
for (int i = 0; i < size; i++) {
if (o.equals(arr[i])) {
return true;
}
}
}
return false;
}
@Override
public Iterator iterator() {
return new MyIterator();
}
@Override
public Object[] toArray() {
Object[] result = new Object[size];
System.arraycopy(this.arr, 0, result, 0, size);
return result;
}
@Override
public boolean add(Object o) {
ensureCapacity(this.size + 1);
arr[size] = o;
size++;
return true;
}
public void ensureCapacity(int requiredCapacity) {
modificationCount++;
if(requiredCapacity == arr.length) {
Object[] newArr = new Object[3 * arr.length / 2 + 1];
System.arraycopy(this.arr, 0, newArr, 0, arr.length);
this.arr = newArr;
}
}
@Override
public boolean remove(Object o) {
modificationCount++;
if(o == null) {
for(int i = 0; i < size; i++) {
if(arr[i] == null) {
fastRemove(i);
return true;
}
}
} else {
for(int i = 0; i < size; i++) {
if(o.equals(arr[i])) {
fastRemove(i);
return true;
}
}
}
return false;
}
public void fastRemove(int index) {
int numberOfMoves = size - index - 1;
if (numberOfMoves > 0) {
System.arraycopy(arr, index + 1, arr, index, numberOfMoves);
}
arr[--size] = null;
}
@Override
public boolean addAll(Collection<? extends E> c) {
c.stream().forEach(this::add);
return true;
}
@Override
public boolean addAll(int index, Collection<? extends E> c) {
checkIndexForAdd(index);
int i = index;
for (E element : c) {
this.add(i, element);
i++;
}
return true;
}
@Override
public void clear() {
modificationCount++;
arr = new Object[DEFAULT_CAPACITY];
size = 0;
}
@Override
public E get(int index) {
checkIndex(index);
return (E) arr[index];
}
@Override
public E set(int index, E element) {
checkIndex(index);
modificationCount++;
E objForReturn = (E) arr[index];
arr[index] = element;
return objForReturn;
}
@Override
public void add(int index, Object element) {
checkIndexForAdd(index);
ensureCapacity(size + 1);
System.arraycopy(arr, index, arr, index + 1, size - index);
arr[index] = element;
size++;
}
@Override
public E remove(int index) {
checkIndex(index);
modificationCount++;
E objForReturn = (E) arr[index];
fastRemove(index);
return objForReturn;
}
@Override
public int indexOf(Object o) {
if(o == null) {
for (int i = 0; i < size; i++) {
if(arr[i] == null) {
return i;
}
}
} else {
for (int i = 0; i < size; i++) {
if (o.equals(arr[i])) {
return i;
}
}
}
return -1;
}
@Override
public int lastIndexOf(Object o) {
int index = -1;
if(o == null) {
for (int i = 0; i < size; i++) {
if(arr[i] == null) {
index = i;
}
}
} else {
for (int i = 0; i < size; i++) {
if (o.equals(arr[i])) {
index = i;
}
}
}
return index;
}
@Override
public ListIterator listIterator() {
return new MyListIterator();
}
@Override
public ListIterator listIterator(int index) {
return new MyListIterator(index);
}
@Override
public List subList(int fromIndex, int toIndex) {
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> c) {
modificationCount++;
int oldSize = size;
Iterator iterator = this.iterator();
while (iterator.hasNext()) {
if(!c.contains(iterator.next())) {
iterator.remove();
}
}
return size != oldSize;
}
@Override
public boolean removeAll(Collection c) {
modificationCount++;
int oldSize = size;
Iterator iterator = this.iterator();
while (iterator.hasNext()) {
if (c.contains(iterator.next())) {
iterator.remove();
}
}
return size != oldSize;
}
@Override
public boolean containsAll(Collection<?> c) {
for (Object element : c) {
if (!contains(element)) {
return false;
}
}
return true;
}
@Override
public Object[] toArray(Object[] a) {
throw new UnsupportedOperationException();
}
@Override
public String toString() {
StringBuilder result = new StringBuilder("[");
for (int i = 0; i < size; i++) {
result.append(arr[i]);
if (i < size - 1) {
result.append(", ");
}
}
result.append("]");
return result.toString();
}
private boolean checkIndex(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
} else {
return true;
}
}
private boolean checkIndexForAdd(int index) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException();
} else {
return true;
}
}
private class MyIterator implements Iterator<E> {
int cursor;
int lastReturned = -1;
int expectedModCount = modificationCount;
@Override
public boolean hasNext() {
return cursor != size;
}
@Override
public E next() {
checkForModCount();
if (cursor >= size) {
throw new NoSuchElementException();
}
if (cursor >= MyArrayList.this.arr.length) {
throw new ConcurrentModificationException();
}
lastReturned = cursor;
cursor++;
return (E) MyArrayList.this.arr[lastReturned];
}
@Override
public void remove() {
if (lastReturned < 0) {
throw new IllegalStateException();
}
checkForModCount();
try {
MyArrayList.this.remove(lastReturned);
cursor = lastReturned;
lastReturned = -1;
expectedModCount = modificationCount;
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}
void checkForModCount() {
if (modificationCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
}
private class MyListIterator extends MyIterator implements ListIterator<E> {
MyListIterator() {
}
MyListIterator(int index) {
checkIndex(index);
cursor = index;
}
@Override
public boolean hasPrevious() {
return cursor != 0;
}
@Override
public E previous() {
checkForModCount();
if (cursor - 1 < 0) {
throw new NoSuchElementException();
}
if (cursor - 1 >= MyArrayList.this.arr.length) {
throw new ConcurrentModificationException();
}
cursor--;
lastReturned = cursor;
return (E) MyArrayList.this.arr[lastReturned];
}
@Override
public int nextIndex() {
return cursor;
}
@Override
public int previousIndex() {
return cursor - 1;
}
@Override
public void set(E e) {
if (lastReturned < 0) {
throw new IllegalStateException();
}
checkForModCount();
try {
MyArrayList.this.set(lastReturned, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
@Override
public void add(E e) {
checkForModCount();
try {
MyArrayList.this.add(cursor, e);
cursor++;
lastReturned = -1;
expectedModCount = modificationCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
}
}
|
package it.unibo.bd1819.job2.mappers;
import it.unibo.bd1819.job2.utils.FileParser;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import java.io.IOException;
import java.util.List;
public class CounterRatingMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
/**
* This class does a mapping from the line read from reating.csv and a pair
* id_book as key and rating as value
* @param key offset
* @param value csv line
* @param context
* @throws IOException
* @throws InterruptedException
*/
public void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
List<String> values = FileParser.parseCSVLine(value.toString());
String idBook = values.get(1);
if (!values.get(2).equals("rating")) {
IntWritable rating = new IntWritable(Integer.parseInt(values.get(2)));
context.write(new Text(idBook), rating);
}
}
}
|
package de.varylab.discreteconformal.math;
import java.math.BigDecimal;
import java.math.MathContext;
import org.junit.Assert;
import org.junit.Test;
import de.jreality.math.P2;
import de.jreality.math.Pn;
public class P2BigTest {
public static MathContext
context = new MathContext(50);
public BigDecimal b(double v) {
return new BigDecimal(v);
}
@Test
public void testMakeDirectIsometryFromFramesEuclidean() throws Exception {
double[] s1 = {-1.4142135623730963, 0.0, 1.0};
double[] s2 = {1.4142135623730951, 0.0, 1.0};
double[] t1 = {-2.828427124746189, 2.4494897427831805, 1.0};
double[] t2 = {0.0, 2.4494897427831783, 1.0};
double[] T = P2.makeDirectIsometryFromFrames(null, s1, s2, t1, t2, Pn.EUCLIDEAN);
BigDecimal[] s1Big = {b(-1.4142135623730963), b(0.0), b(1.0)};
BigDecimal[] s2Big = {b(1.4142135623730951), b(0.0), b(1.0)};
BigDecimal[] t1Big = {b(-2.828427124746189), b(2.4494897427831805), b(1.0)};
BigDecimal[] t2Big = {b(0.0), b(2.4494897427831783), b(1.0)};
BigDecimal[] TBig = P2Big.makeDirectIsometryFromFrames(null, s1Big, s2Big, t1Big, t2Big, Pn.EUCLIDEAN, context);
for (int i = 0; i < TBig.length; i++) {
Assert.assertEquals(T[i], TBig[i].doubleValue(), 1E-10);
}
}
@Test
public void testPerpendicularBisector() {
double[] p1 = {0.5,0,1};
double[] q1 = {0,0.5,1};
Assert.assertArrayEquals(new double[]{0.5,-0.5,0}, P2.perpendicularBisector(null, p1, q1, Pn.EUCLIDEAN), 1E-10);
}
@Test
public void testPerpendicularBisectorIntersection() {
double[] p1 = {0.5,0,1};
double[] q1 = {0,1,1};
double[] p2 = {1,0,1};
double[] q2 = {0,1.5,1};
double[] o = P2.pointFromLines(null, P2.perpendicularBisector(null, p1, q1, Pn.EUCLIDEAN), P2.perpendicularBisector(null, p2, q2, Pn.EUCLIDEAN));
Assert.assertEquals(Pn.distanceBetween(p1, o, Pn.EUCLIDEAN), Pn.distanceBetween(q1, o, Pn.EUCLIDEAN), 1E-10);
Assert.assertEquals(Pn.distanceBetween(p2, o, Pn.EUCLIDEAN), Pn.distanceBetween(q2, o, Pn.EUCLIDEAN), 1E-10);
}
}
|
package com.xwolf.eop.system.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* @author xwolf
* @date 2016-12-13 12:37
* @since V1.0.0
*/
@Controller
@Slf4j
public class IndexController {
/**
* 首页
* @param ua
* @return
*/
@RequestMapping(value ="index")
public String toIndex(@RequestHeader("User-Agent")String ua){
log.info("ua:{}",ua);
return "system/index";
}
/**
* 授权失败
* @return
*/
@RequestMapping(value = "unAuth",method = RequestMethod.POST)
public String toUnAuth(){
return "system/error/unauthorized";
}
}
|
package com.ai.platform.agent.client;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.ai.platform.agent.client.incoming.AgentClientInitializer;
import com.ai.platform.agent.client.outgoing.AuthDataPacket;
import com.ai.platform.agent.client.util.ShellChannelCollectionUtil;
import com.ai.platform.agent.entity.AgentConfigInfoServer;
import com.ai.platform.agent.exception.AgentServerException;
import com.ai.platform.agent.util.AgentConstant;
public class ClientMain {
static Logger logger = LogManager.getLogger(ClientMain.class);
public static void main(String[] args) throws AgentServerException {
AgentConfigInfoServer agentConfigInfoServer = new AgentConfigInfoServer();
//
String serverAddr = agentConfigInfoServer.getAgentConfigInfo().getAgentServerIp();//ConfigInit.serverConstant.get(AgentConstant.SERVER_IP);
int port = Integer.valueOf(agentConfigInfoServer.getAgentConfigInfo().getAgentServerPort());//Integer.valueOf(ConfigInit.serverConstant.get(AgentConstant.SERVER_PORT));
while (true) {
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
.option(ChannelOption.SO_KEEPALIVE, true).handler(new AgentClientInitializer());
try {
// 发起异步链接操作
ChannelFuture channelFuture = bootstrap.connect(serverAddr, port);
channelFuture.sync();
// 向服务器发送身份验证信息
AuthDataPacket adp = new AuthDataPacket();
//
String agentClientInfo = agentConfigInfoServer.getAgentConfigInfo().getAgentClientInfo();
//
byte[] authPacket = adp.genDataPacket(null,agentClientInfo);
channelFuture.channel().writeAndFlush(authPacket);
logger.info("agent client [{}] Launch on-line operation , Send authentication information:{}",
adp.getAuthJson().getString(AgentConstant.CHANNEL_SHOW_KEY), adp.getAuthJson());
channelFuture.channel().closeFuture().sync();
} catch (Exception e) {
logger.error(e);
} finally {
try {
Thread.sleep(5 * 1000);
} catch (InterruptedException e) {
logger.error("sleep fail,{}", e);
}
ShellChannelCollectionUtil.userChannelMap.clear();
group.shutdownGracefully();
}
}
}
}
|
/*
* 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 com.innovaciones.reporte.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author pisama
*/
@Entity
@Table(name = "usuarios")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Usuarios.findAll", query = "SELECT u FROM Usuarios u")})
public class Usuarios implements Serializable, Cloneable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Size(max = 50)
@Column(name = "dni")
private String dni;
@Size(max = 50)
@Column(name = "codigo")
private String codigo;
@Size(max = 150)
@Column(name = "nombre")
private String nombre;
@Size(max = 150)
@Column(name = "apellido")
private String apellido;
@Size(max = 50)
@Column(name = "telefono")
private String telefono;
@Size(max = 50)
@Column(name = "celular")
private String celular;
@Size(max = 150)
@Column(name = "mail")
private String mail;
@Size(max = 250)
@Column(name = "direccion")
private String direccion;
@Size(max = 50)
@Column(name = "usuario")
private String usuario;
@Basic(optional = false)
@NotNull
@Column(name = "clave")
private String clave;
@Basic(optional = false)
@NotNull
@Column(name = "estado")
private Integer estado;
@Lob
@Size(max = 65535)
@Column(name = "firma_base64")
private String firmaBase64;
@Lob
@Size(max = 65535)
@Column(name = "firma")
private String firma;
@Lob
@Column(name = "imagen", columnDefinition = "LONGVARBINARY")
private byte[] imagen;
@JsonIgnore
@OneToMany(cascade = CascadeType.ALL, mappedBy = "idUsuario", fetch = FetchType.EAGER)
private List<UsuarioRoles> usuarioRolesList;
@JsonIgnore
@OneToMany(cascade = CascadeType.ALL, mappedBy = "idUsuario", fetch = FetchType.EAGER)
private List<Reporte> reporteList;
@JsonIgnore
@OneToMany(mappedBy = "idUsuarioAtencion")
private List<AsignacionReparacion> asignacionReparacionList;
@JsonIgnore
@OneToMany(mappedBy = "idBodeguero")
private List<Bodega> bodegaList;
@JsonIgnore
@JoinColumn(name = "id_cliente", referencedColumnName = "id")
@ManyToOne
private Cliente idCliente;
@Column(name = "fecha_invitacion")
@Temporal(TemporalType.TIMESTAMP)
private Date fechaInvitacion;
@Transient
private String nombreCompleto;
public Usuarios() {
this.nombre = this.apellido = "";
}
public Usuarios(Integer id) {
this.id = id;
this.nombre = this.apellido = "";
}
public Usuarios(String usuario, Integer estado) {
this.usuario = usuario;
this.estado = estado;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDni() {
return dni;
}
public void setDni(String dni) {
this.dni = dni;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellido() {
return apellido;
}
public void setApellido(String apellido) {
this.apellido = apellido;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public String getCelular() {
return celular;
}
public void setCelular(String celular) {
this.celular = celular;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public String getUsuario() {
return usuario;
}
public void setUsuario(String usuario) {
this.usuario = usuario;
}
public String getClave() {
return clave;
}
public void setClave(String clave) {
this.clave = clave;
}
public Integer getEstado() {
return estado;
}
public void setEstado(Integer estado) {
this.estado = estado;
}
public String getFirmaBase64() {
return firmaBase64;
}
public void setFirmaBase64(String firmaBase64) {
this.firmaBase64 = firmaBase64;
}
public String getFirma() {
return firma;
}
public void setFirma(String firma) {
this.firma = firma;
}
public String getNombreCompleto() {
this.nombreCompleto = nombre + " " + apellido;
return nombreCompleto;
}
public void setNombreCompleto(String nombreCompleto) {
this.nombreCompleto = nombreCompleto;
}
@XmlTransient
public List<Bodega> getBodegaList() {
return bodegaList;
}
public void setBodegaList(List<Bodega> bodegaList) {
this.bodegaList = bodegaList;
}
@XmlTransient
public List<UsuarioRoles> getUsuarioRolesList() {
return usuarioRolesList;
}
public void setUsuarioRolesList(List<UsuarioRoles> usuarioRolesList) {
this.usuarioRolesList = usuarioRolesList;
}
@XmlTransient
public List<Reporte> getReporteList() {
return reporteList;
}
public void setReporteList(List<Reporte> reporteList) {
this.reporteList = reporteList;
}
@XmlTransient
public List<AsignacionReparacion> getAsignacionReparacionList() {
return asignacionReparacionList;
}
public void setAsignacionReparacionList(List<AsignacionReparacion> asignacionReparacionList) {
this.asignacionReparacionList = asignacionReparacionList;
}
public byte[] getImagen() {
return imagen;
}
public Cliente getIdCliente() {
return idCliente;
}
public void setIdCliente(Cliente idCliente) {
this.idCliente = idCliente;
}
public void setImagen(byte[] imagen) {
this.imagen = imagen;
}
public Date getFechaInvitacion() {
return fechaInvitacion;
}
public void setFechaInvitacion(Date fechaInvitacion) {
this.fechaInvitacion = fechaInvitacion;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Usuarios)) {
return false;
}
Usuarios other = (Usuarios) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public String toString() {
return "Usuarios{" + "id=" + id + ", dni=" + dni + ", codigo=" + codigo + ", nombre=" + nombre + ", apellido=" + apellido
+ ", telefono=" + telefono + ", celular=" + celular + ", mail=" + mail + ", direccion=" + direccion
+ ", usuario=" + usuario + ", clave=" + clave + ", estado=" + estado
+ ", nombreCompleto=" + nombreCompleto + "" + '}';
}
}
|
package com.baopinghui.bin.controller;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.baopinghui.bin.dto.ResultDto;
import com.baopinghui.bin.entity.ActiveEntity;
import com.baopinghui.bin.entity.CourseEntity;
import com.baopinghui.bin.entity.DianMianEntity;
import com.baopinghui.bin.mapper.app.ActiveMapper;
import com.baopinghui.bin.mapper.app.CourseMapper;
import com.baopinghui.bin.mapper.app.DianMianMapper;
import com.baopinghui.bin.service.ActiveService;
import com.baopinghui.bin.service.CourseService;
import com.baopinghui.bin.service.DianMianService;
import com.baopinghui.bin.service.impl.DianmianServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
@Api(description="活动")
@RequestMapping("wd_Active")
@CrossOrigin
@Controller
public class ActiveController {
@Autowired
private ActiveService activeService;
@Autowired
private ActiveMapper activeMapper;
@ApiOperation(value="添加活动")
@RequestMapping(value="/insertActive",method=RequestMethod.POST)
@ResponseBody
public ResultDto insertActive(
@ApiParam(value="活动名 required=必填",defaultValue="数学") @RequestParam(required=true)String active_name,
@ApiParam(value="活动描述",defaultValue="上啥地方好说") @RequestParam(required=false)String active_desc,
@ApiParam(value="活动地址 required=必填",defaultValue="12222222222")@RequestParam(required=true)String address,
@ApiParam(value="花絮图片",defaultValue="没什么好说的")@RequestParam(required=false)String huaxu_url,
@ApiParam(value="活动封面图 ",defaultValue="")@RequestParam(required=false)String active_url,
@ApiParam(value="活动时间范围 ",defaultValue="")@RequestParam(required=false)String active_date
){
ActiveEntity a=new ActiveEntity();
a.setActive_desc(active_desc);
a.setActive_name(active_name);
a.setActive_url(active_url);
a.setAddress(address);
a.setHuaxu_url(huaxu_url);
a.setActive_date(active_date);
// System.out.println(dianMianEntity);
Integer b=activeService.insertActive(a);
// Integer b=dianMianMapper.insertDianMian(dianMianEntity);
return ResultDto.createSuccess(b);
}
@ApiOperation(value="更新活动")
@RequestMapping(value="/updateActive",method=RequestMethod.POST)
@ResponseBody
public ResultDto updateActive(
@ApiParam(value="活动名id required=必填",defaultValue="数学") @RequestParam(required=true)int id,
@ApiParam(value="活动名 required=必填",defaultValue="数学") @RequestParam(required=true)String active_name,
@ApiParam(value="活动描述",defaultValue="上啥地方好说") @RequestParam(required=false)String active_desc,
@ApiParam(value="活动地址 required=必填",defaultValue="12222222222")@RequestParam(required=true)String address,
@ApiParam(value="花絮图片",defaultValue="没什么好说的")@RequestParam(required=false)String huaxu_url,
@ApiParam(value="活动封面图 ",defaultValue="")@RequestParam(required=false)String active_url,
@ApiParam(value="活动时间范围 ",defaultValue="")@RequestParam(required=false)String active_date
){
ActiveEntity a=new ActiveEntity();
a.setId(id);
a.setActive_desc(active_desc);
a.setActive_name(active_name);
a.setActive_url(active_url);
a.setAddress(address);
a.setHuaxu_url(huaxu_url);
a.setActive_date(active_date);
// System.out.println(dianMianEntity);
Integer b=activeService.updateActive(a);
// Integer b=dianMianMapper.insertDianMian(dianMianEntity);
return ResultDto.createSuccess(b);
}
@ApiOperation(value="删除活动")
@RequestMapping(value="/deleteActive",method=RequestMethod.POST)
@ResponseBody
public ResultDto deleteActive(
@ApiParam(value="活动id required=必填")@RequestParam(required=true)int id
){
Integer b=activeService.deleteActive(id);
activeMapper.deleteACbyId(id);
return ResultDto.createSuccess(b);
}
@ApiOperation(value="查询所有活动")
@RequestMapping(value="/selectActive",method=RequestMethod.POST)
@ResponseBody
public ResultDto selectActive(
){
List<Map<String,Object>> b=activeService.selectActive();
return ResultDto.createSuccess(b);
}
@ApiOperation(value="根据id查询活动详情")
@RequestMapping(value="/selectActive2",method=RequestMethod.POST)
@ResponseBody
public ResultDto selectActive2(
@ApiParam(value="活动id required=必填")@RequestParam(required=true)int id
){
Map<String,Object> b=activeMapper.selectActive2(id);
long count=(long)activeMapper.selectActiveCountbyid(id).get("count");
b.put("count",count);
return ResultDto.createSuccess(b);
}
@ApiOperation(value="更新根据id活动的封面图")
@RequestMapping(value="/updateActiveUrlbyid",method=RequestMethod.GET)
@ResponseBody
public ResultDto updateActiveUrlbyid(
@ApiParam(value="活动id required=必填")@RequestParam(required=true)int id,
@ApiParam(value="活动封面图",defaultValue="12222222222")@RequestParam(required=false)String active_url
){
Integer b=activeMapper.updateActiveUrlbyid(id, active_url);
return ResultDto.createSuccess(b);
}
@ApiOperation(value="更新根据id活动的花絮")
@RequestMapping(value="/updateHuaxuUrlbyid",method=RequestMethod.GET)
@ResponseBody
public ResultDto updateHuaxuUrlbyid(
@ApiParam(value="活动id required=必填")@RequestParam(required=true)int id,
@ApiParam(value="活动封面图",defaultValue="12222222222")@RequestParam(required=false)String huaxu_url
){
Integer b=activeMapper.updateHuaxuUrlbyid(id, huaxu_url);
return ResultDto.createSuccess(b);
}
}
|
package com.gxjtkyy.standardcloud.admin.domain.vo;
import com.gxjtkyy.standardcloud.common.domain.vo.BaseVO;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.Date;
/**
* 字典详细
* @Package com.gxjtkyy.standardcloud.admin.domain.vo
* @Author lizhenhua
* @Date 2018/7/2 10:49
*/
@Setter
@Getter
@ToString(callSuper = true)
public class DictDetailVO extends BaseVO{
/**序号*/
private Integer id;
/**字典码*/
private String dictCode;
/**字典类型*/
private Integer dictType;
/**字典名称*/
private String dictName;
/**字典描述*/
private String dictDesc;
/**操作员*/
private String operator;
/**操作员ID*/
private String operatorId;
/**创建时间*/
private Date createTime;
/**更新时间*/
private Date updateTime;
}
|
package com.hcl.neo.eloader.microservices.configuration;
import java.util.logging.Logger;
import javax.jms.ConnectionFactory;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.orm.jpa.EntityScan;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.web.client.RestTemplate;
/**
* The accounts Spring configuration.
*
* @author Souvik Das
*/
@Configuration
@ComponentScan("com.hcl.neo.eloader")
@EntityScan("com.hcl.neo.eloader")
@EnableMongoRepositories("com.hcl.neo.eloader")
public class EloaderConfiguration {
protected Logger logger;
@Value("${spring.activemq.broker-url}")
private String JMS_BROKER_URL;
public EloaderConfiguration() {
logger = Logger.getLogger(getClass().getName());
}
@Bean
public ConnectionFactory connectionFactory() {
return new ActiveMQConnectionFactory(JMS_BROKER_URL);
}
@LoadBalanced
@Bean
RestTemplate restTemplate() {
return new RestTemplate();
}
}
|
/*
* Copyright 2016 CIRDLES.
*
* 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.
*
*
* This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
* See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
* Any modifications to this file will be lost upon recompilation of the source schema.
* Generated on: 2016.03.03 at 09:06:25 AM EST
*/
package org.geosamples.samples;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>
* Java class for MetamorphicDetails.
*
* <p>
* The following schema fragment specifies the expected content contained within
* this class.
*
* <pre>
* {@code
* <xml>
* <simpleType name="MetamorphicDetails">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="Calc-Silicate"/>
* <enumeration value="Eclogite"/>
* <enumeration value="Gneiss"/>
* <enumeration value="Granofels"/>
* <enumeration value="Granulite"/>
* <enumeration value="MechanicallyBroken"/>
* <enumeration value="Meta-Carbonate"/>
* <enumeration value="Meta-Ultramafic"/>
* <enumeration value="Metasedimentary"/>
* <enumeration value="Metasomatic"/>
* <enumeration value="Schist"/>
* <enumeration value="Slate"/>
* </restriction>
* </simpleType>
* </xml>
* }
* </pre>
*
*/
@XmlType(name = "MetamorphicDetails")
@XmlEnum
public enum MetamorphicDetails {
@XmlEnumValue("Calc-Silicate")
CALC_SILICATE("Calc-Silicate"),
@XmlEnumValue("Eclogite")
ECLOGITE("Eclogite"),
@XmlEnumValue("Gneiss")
GNEISS("Gneiss"),
@XmlEnumValue("Granofels")
GRANOFELS("Granofels"),
@XmlEnumValue("Granulite")
GRANULITE("Granulite"),
@XmlEnumValue("MechanicallyBroken")
MECHANICALLY_BROKEN("MechanicallyBroken"),
@XmlEnumValue("Meta-Carbonate")
META_CARBONATE("Meta-Carbonate"),
@XmlEnumValue("Meta-Ultramafic")
META_ULTRAMAFIC("Meta-Ultramafic"),
@XmlEnumValue("Metasedimentary")
METASEDIMENTARY("Metasedimentary"),
@XmlEnumValue("Metasomatic")
METASOMATIC("Metasomatic"),
@XmlEnumValue("Schist")
SCHIST("Schist"),
@XmlEnumValue("Slate")
SLATE("Slate");
private final String value;
MetamorphicDetails(String v) {
value = v;
}
public String value() {
return value;
}
public static MetamorphicDetails fromValue(String v) {
for (MetamorphicDetails c : MetamorphicDetails.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
|
/*
MusicalScales -- a class within the Cellular Automaton Explorer.
Copyright (C) 2005 David B. Bahr (http://academic.regis.edu/dbahr/)
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 cellularAutomata.util.music;
/**
* Contains methods that convert the number of a note on a scale into a piano's
* key number. For example, in the C major scale, the scale number 0 would be a
* C, the scale number 1 would be a D, the scale number 2 would be an E, the
* scale number 3 would be an F, etc. The piano's keys are numbered from 0 to 87
* with 39 as middle C. So in the C major scale, the scale number 0 maps to a C
* which is the piano key number 39. And in the C major scale, the scale number
* 1 maps to a D which is the piano key number 41. (Note that the C major scale
* skips the C# which is key number 40).
* <p>
* In the C blues scale, the scale number 0 is a C, which is key number 39 on
* the piano. But in the C blues scale the scale number 1 is an Eb, which is
* piano key number 42.
*
* @author David Bahr
*/
public class MusicalScales
{
/**
* Value corresponding to an approximate soprano range.
*/
public static final int SOPRANO = +36;
/**
* Value corresponding to an approximate mezzo-soprano range.
*/
public static final int MEZZO_SOPRANO = +24;
/**
* Value corresponding to an approximate alto range.
*/
public static final int ALTO = +12;
/**
* Value corresponding to an approximate tenor range.
*/
public static final int TENOR = 0;
/**
* Value corresponding to an approximate baritone range.
*/
public static final int BARITONE = -12;
/**
* Value corresponding to an approximate bass range.
*/
public static final int BASSO = -24;
/**
* Value corresponding to an approximate basso profundo range.
*/
public static final int BASSO_PROFUNDO = -36;
// length of the blues scale
private static final int BLUES_SCALE_LENGTH_ONE_OCTAVE = 7;
// length of the major scale
private static final int MAJOR_SCALE_LENGTH_ONE_OCTAVE = 8;
// length of the harmonic minor scale
private static final int MINOR_SCALE_LENGTH_ONE_OCTAVE = 8;
// length of the pentatonic scale
private static final int PENTATONIC_SCALE_LENGTH_ONE_OCTAVE = 6;
// Unnecessary. All methods are static.
private MusicalScales()
{
}
/**
* For any given beat constructs an appropriate chord for the C blues.
*
* @param currentBeat
* The current beat.
*
* @param octave
* The octave of notes that will be returned. Possible values
* include TENOR, BASSO, ALTO, etc.
*
* @return An array of the pian key numbers that correspond to a chord.
*/
public static int[] getCBluesChord(long currentBeat, int octave)
{
// the array of notes that will be returned
int[] chord = null;
// just in case
if(currentBeat < 1)
{
currentBeat = 1;
}
// there are 12 measures times 4 beats/measure, or
// 48 beats per refrain in the blues
int beat = (int) (currentBeat % 48);
// play a chord on the first beat of each measure
if(beat % 4 == 0)
{
// C, F7, C, C7, F7, F7, C, C, G7, F7, C, C
switch(beat)
{
// C chord
case 0:
chord = new int[3];
chord[0] = 39;
chord[1] = 43;
chord[2] = 46;
break;
// F7 chord
case 4:
chord = new int[4];
chord[0] = 44;
chord[1] = 48;
chord[2] = 51;
chord[3] = 54;
break;
// C chord
case 8:
chord = new int[3];
chord[0] = 39;
chord[1] = 43;
chord[2] = 46;
break;
// C7 chord
// case 12:
// chord = new int[4];
// chord[0] = 39;
// chord[1] = 43;
// chord[2] = 46;
// chord[3] = 49;
// F7 chord
case 16:
chord = new int[4];
chord[0] = 44;
chord[1] = 48;
chord[2] = 51;
chord[3] = 54;
break;
// F7 chord
// case 20:
// chord = new int[4];
// chord[0] = 44;
// chord[1] = 48;
// chord[2] = 51;
// chord[3] = 54;
// break;
// C chord
case 24:
chord = new int[3];
chord[0] = 39;
chord[1] = 43;
chord[2] = 46;
break;
// C chord
// case 28:
// chord = new int[3];
// chord[0] = 39;
// chord[1] = 43;
// chord[2] = 46;
// break;
// G7 chord
case 32:
chord = new int[4];
chord[0] = 46;
chord[1] = 50;
chord[2] = 53;
chord[3] = 56;
break;
// F7 chord
case 36:
chord = new int[4];
chord[0] = 44;
chord[1] = 48;
chord[2] = 51;
chord[3] = 54;
break;
// C chord
case 40:
chord = new int[3];
chord[0] = 39;
chord[1] = 43;
chord[2] = 46;
break;
// C chord
// case 44:
// chord = new int[3];
// chord[0] = 39;
// chord[1] = 43;
// chord[2] = 46;
// break;
}
}
// change the octave
if(chord != null)
{
for(int i = 0; i < chord.length; i++)
{
chord[i] += octave;
}
}
return chord;
}
/**
* For the given number of the note in the C blues scale, this returns the
* piano key. For the TENOR octave, this scale starts at key number 39
* (middle C), and ends at key number 50 (C an octave higher). See class
* description for more details.
*
* @param scaleNumber
* The number of the note on the scale. Values outside 0 to 6 are
* reassigned to the absolute value of modulo 7 (so for example,
* a -1 corresponds to a 1, and a 9 corresponds to a 3).
*
* @param octave
* The octave of notes that will be returned. Possible values
* include TENOR, BASSO, ALTO, etc.
*
* @return The piano's corresponding key number.
*/
public static int getCBluesScaleOneOctave(int scaleNumber, int octave)
{
// the note that will be returned
int note = 39;
// the length of the scale
int scaleLength = BLUES_SCALE_LENGTH_ONE_OCTAVE;
// make sure the number is within range
scaleNumber = Math.abs(scaleNumber % scaleLength);
// the conversion to a C major scale starting at middle C
switch(scaleNumber)
{
// middle C
case 0:
note = 39;
break;
// Eb
case 1:
note = 42;
break;
// F
case 2:
note = 44;
break;
// Gb
case 3:
note = 45;
break;
// G
case 4:
note = 46;
break;
// Bb
case 5:
note = 49;
break;
// C
case 6:
note = 51;
break;
}
// change the octave
note += octave;
return note;
}
/**
* The length of the blues scale (for one octave).
*
* @return The length of the one-octave blues scale.
*/
public static int getCBluesScaleOneOctaveLength()
{
return BLUES_SCALE_LENGTH_ONE_OCTAVE;
}
/**
* For the given number of the note in the C major scale, this returns the
* piano key. This scale starts at key number 39 (middle C), and ends at key
* number 50 (C an octave higher). See class description for more details.
*
* @param scaleNumber
* The number of the note on the scale. Values outside 0 to 7 are
* reassigned to the absolute value of modulo 8 (so for example,
* a -1 corresponds to a 1, and a 9 corresponds to a 2).
* @param octave
* The octave of notes that will be returned. Possible values
* include TENOR, BASSO, ALTO, etc.
*
* @return The piano's corresponding key number.
*/
public static int getCMajorScaleOneOctave(int scaleNumber, int octave)
{
// the note that will be returned
int note = 39;
// the length of the scale
int scaleLength = MAJOR_SCALE_LENGTH_ONE_OCTAVE;
// make sure the number is within range
scaleNumber = Math.abs(scaleNumber % scaleLength);
// the conversion to a C major scale starting at middle C
switch(scaleNumber)
{
// middle C
case 0:
note = 39;
break;
// D
case 1:
note = 41;
break;
// E
case 2:
note = 43;
break;
// F
case 3:
note = 44;
break;
// G
case 4:
note = 46;
break;
// A
case 5:
note = 48;
break;
// B
case 6:
note = 50;
break;
// C
case 7:
note = 51;
break;
}
// change the octave
note += octave;
return note;
}
/**
* The length of the C major scale (for one octave).
*
* @return The length of the one-octave c-major scale.
*/
public static int getCMajorScaleOneOctaveLength()
{
return MAJOR_SCALE_LENGTH_ONE_OCTAVE;
}
/**
* For the given number of the note in the C harmonic minor scale, this
* returns the piano key. This scale starts at key number 39 (middle C), and
* ends at key number 50 (C an octave higher). See class description for
* more details.
*
* @param scaleNumber
* The number of the note on the scale. Values outside 0 to 7 are
* reassigned to the absolute value of modulo 8 (so for example,
* a -1 corresponds to a 1, and a 9 corresponds to a 2).
* @param octave
* The octave of notes that will be returned. Possible values
* include TENOR, BASSO, ALTO, etc.
*
* @return The piano's corresponding key number.
*/
public static int getCHarmonicMinorScaleOneOctave(int scaleNumber, int octave)
{
// the note that will be returned
int note = 39;
// the length of the scale
int scaleLength = MINOR_SCALE_LENGTH_ONE_OCTAVE;
// make sure the number is within range
scaleNumber = Math.abs(scaleNumber % scaleLength);
// the conversion to a C major scale starting at middle C
switch(scaleNumber)
{
// middle C
case 0:
note = 39;
break;
// D
case 1:
note = 41;
break;
// Eb
case 2:
note = 42;
break;
// F
case 3:
note = 44;
break;
// G
case 4:
note = 46;
break;
// Ab
case 5:
note = 47;
break;
// B
case 6:
note = 50;
break;
// C
case 7:
note = 51;
break;
}
// change the octave
note += octave;
return note;
}
/**
* The length of the C harmonic minor scale (for one octave).
*
* @return The length of the one-octave c-harmonic-minor scale.
*/
public static int getCHarmonicMinorScaleOneOctaveLength()
{
return MINOR_SCALE_LENGTH_ONE_OCTAVE;
}
/**
* For the given number of the note in the C pentatonic scale, this returns
* the piano key. This scale starts at key number 39 (middle C), and ends at
* key number 50 (C an octave higher). See class description for more
* details.
*
* @param scaleNumber
* The number of the note on the scale. Values outside 0 to 5 are
* reassigned to the absolute value of modulo 6 (so for example,
* a -1 corresponds to a 1, and an 8 corresponds to a 2).
* @param octave
* The octave of notes that will be returned. Possible values
* include TENOR, BASSO, ALTO, etc.
*
* @return The piano's corresponding key number.
*/
public static int getCPentatonicScaleOneOctave(int scaleNumber, int octave)
{
// the note that will be returned
int note = 39;
// the length of the scale
int scaleLength = MINOR_SCALE_LENGTH_ONE_OCTAVE;
// make sure the number is within range
scaleNumber = Math.abs(scaleNumber % scaleLength);
// the conversion to a C major scale starting at middle C
switch(scaleNumber)
{
// middle C
case 0:
note = 39;
break;
// D
case 1:
note = 41;
break;
// F
case 2:
note = 44;
break;
// G
case 3:
note = 46;
break;
// A
case 4:
note = 48;
break;
// C
case 5:
note = 51;
break;
}
// change the octave
note += octave;
return note;
}
/**
* The length of the C pentatonic scale (for one octave).
*
* @return The length of the one-octave c-pentatonic scale.
*/
public static int getCPentatonicScaleOneOctaveLength()
{
return PENTATONIC_SCALE_LENGTH_ONE_OCTAVE;
}
/**
* UNFINISHED! For the given number of the note in the scale, this returns
* the piano key. This scale starts at the specified note, but the scale is
* always in the key of C. So, for example, if the scale starts at D (but is
* in the key of C), then this is really the D Dorian scale. See class
* description for more details.
*
* @param scaleNumber
* The number of the note on the scale. Values outside 0 to 7 are
* reassigned to the absolute value of modulo 8 (so for example,
* a -1 corresponds to a 1, and a 9 corresponds to a 2).
*
* @param numberOfNotes
* The number of notes that are in the scale. For example, 15
* covers two octaves. Must be between 1 and 88 (the number of
* keys on a piano).
*
* @param firstNote
* The first note of the scale. Must be between 0 and 87 (the
* number of keys on a piano). A 4039 is middle C, a 41 is middle
* D, etc.
*
* @return The piano's corresponding key number.
*/
public static int getCModalScale(int scaleNumber, int numberOfNotes,
int firstNote)
{
// the note that will be returned
int note = firstNote;
// the length of the scale
int scaleLength = numberOfNotes;
// adjust the note to account for the starting position. For, example if
// the first note is a D (41), then this adds 2.
scaleNumber += (firstNote - 39);
// make sure the number is within range
scaleNumber = Math.abs(scaleNumber % scaleLength);
// the conversion to a C major scale starting at the first note
switch(scaleNumber)
{
// middle C
case 0:
note = 39;
break;
// D
case 1:
note = 41;
break;
// E
case 2:
note = 43;
break;
// F
case 3:
note = 44;
break;
// G
case 4:
note = 46;
break;
// A
case 5:
note = 48;
break;
// B
case 6:
note = 50;
break;
// C
case 7:
note = 51;
break;
}
return note;
}
}
|
/**
* This class is generated by jOOQ
*/
package schema.tables.records;
import java.sql.Timestamp;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record5;
import org.jooq.Row5;
import org.jooq.impl.UpdatableRecordImpl;
import schema.tables.CourseCreatorsCoursecreator;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.8.4"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class CourseCreatorsCoursecreatorRecord extends UpdatableRecordImpl<CourseCreatorsCoursecreatorRecord> implements Record5<Integer, Timestamp, String, String, Integer> {
private static final long serialVersionUID = 1814559510;
/**
* Setter for <code>bitnami_edx.course_creators_coursecreator.id</code>.
*/
public void setId(Integer value) {
set(0, value);
}
/**
* Getter for <code>bitnami_edx.course_creators_coursecreator.id</code>.
*/
public Integer getId() {
return (Integer) get(0);
}
/**
* Setter for <code>bitnami_edx.course_creators_coursecreator.state_changed</code>.
*/
public void setStateChanged(Timestamp value) {
set(1, value);
}
/**
* Getter for <code>bitnami_edx.course_creators_coursecreator.state_changed</code>.
*/
public Timestamp getStateChanged() {
return (Timestamp) get(1);
}
/**
* Setter for <code>bitnami_edx.course_creators_coursecreator.state</code>.
*/
public void setState(String value) {
set(2, value);
}
/**
* Getter for <code>bitnami_edx.course_creators_coursecreator.state</code>.
*/
public String getState() {
return (String) get(2);
}
/**
* Setter for <code>bitnami_edx.course_creators_coursecreator.note</code>.
*/
public void setNote(String value) {
set(3, value);
}
/**
* Getter for <code>bitnami_edx.course_creators_coursecreator.note</code>.
*/
public String getNote() {
return (String) get(3);
}
/**
* Setter for <code>bitnami_edx.course_creators_coursecreator.user_id</code>.
*/
public void setUserId(Integer value) {
set(4, value);
}
/**
* Getter for <code>bitnami_edx.course_creators_coursecreator.user_id</code>.
*/
public Integer getUserId() {
return (Integer) get(4);
}
// -------------------------------------------------------------------------
// Primary key information
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Record1<Integer> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record5 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Row5<Integer, Timestamp, String, String, Integer> fieldsRow() {
return (Row5) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public Row5<Integer, Timestamp, String, String, Integer> valuesRow() {
return (Row5) super.valuesRow();
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field1() {
return CourseCreatorsCoursecreator.COURSE_CREATORS_COURSECREATOR.ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Timestamp> field2() {
return CourseCreatorsCoursecreator.COURSE_CREATORS_COURSECREATOR.STATE_CHANGED;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field3() {
return CourseCreatorsCoursecreator.COURSE_CREATORS_COURSECREATOR.STATE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field4() {
return CourseCreatorsCoursecreator.COURSE_CREATORS_COURSECREATOR.NOTE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field5() {
return CourseCreatorsCoursecreator.COURSE_CREATORS_COURSECREATOR.USER_ID;
}
/**
* {@inheritDoc}
*/
@Override
public Integer value1() {
return getId();
}
/**
* {@inheritDoc}
*/
@Override
public Timestamp value2() {
return getStateChanged();
}
/**
* {@inheritDoc}
*/
@Override
public String value3() {
return getState();
}
/**
* {@inheritDoc}
*/
@Override
public String value4() {
return getNote();
}
/**
* {@inheritDoc}
*/
@Override
public Integer value5() {
return getUserId();
}
/**
* {@inheritDoc}
*/
@Override
public CourseCreatorsCoursecreatorRecord value1(Integer value) {
setId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public CourseCreatorsCoursecreatorRecord value2(Timestamp value) {
setStateChanged(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public CourseCreatorsCoursecreatorRecord value3(String value) {
setState(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public CourseCreatorsCoursecreatorRecord value4(String value) {
setNote(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public CourseCreatorsCoursecreatorRecord value5(Integer value) {
setUserId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public CourseCreatorsCoursecreatorRecord values(Integer value1, Timestamp value2, String value3, String value4, Integer value5) {
value1(value1);
value2(value2);
value3(value3);
value4(value4);
value5(value5);
return this;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached CourseCreatorsCoursecreatorRecord
*/
public CourseCreatorsCoursecreatorRecord() {
super(CourseCreatorsCoursecreator.COURSE_CREATORS_COURSECREATOR);
}
/**
* Create a detached, initialised CourseCreatorsCoursecreatorRecord
*/
public CourseCreatorsCoursecreatorRecord(Integer id, Timestamp stateChanged, String state, String note, Integer userId) {
super(CourseCreatorsCoursecreator.COURSE_CREATORS_COURSECREATOR);
set(0, id);
set(1, stateChanged);
set(2, state);
set(3, note);
set(4, userId);
}
}
|
package cc.byod.p5.dpc;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void GoToPolicyManager(View view){
Intent intentGoToSettings = new Intent(this, PolicyManager.class);
startActivity(intentGoToSettings);
}
public void GoToWorkApps(View view){
Intent intentGoToWorkApps = new Intent(this, WorkApps.class);
startActivity(intentGoToWorkApps);
}
}
|
package com.metoo.module.chatting.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import com.metoo.core.constant.Globals;
import com.metoo.core.domain.IdEntity;
/**
*
* <p>
* Title: Chatting.java
* </p>
*
* <p>
* Description: 每个店铺或者平台的聊天组件信息设置类,可以设置的内容包括客服名称,自动回复内容、字体、字体大小、字体颜色
* </p>
*
* <p>
* Copyright: Copyright (c) 2015
* </p>
*
* <p>
* Company: 沈阳网之商科技有限公司 www.koala.com
* </p>
*
* @author hezeng
*
* @date 2014年5月26日
*
* @version koala_b2b2c 2.0
*/
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@Entity
@Table(name = Globals.DEFAULT_TABLE_SUFFIX + "chatting_config")
public class ChattingConfig extends IdEntity {
private Long store_id;// 对应店铺id,每个店铺只对应一个ChattingConfig
private String kf_name;// 客服自定义名称,
@Column(columnDefinition = "LongText")
private String quick_reply_content;// 客服快速回复信息
@Column(columnDefinition = "int default 0")
private int quick_reply_open;// 自动回复是否开启,0为未开启,1为开启
@Column(columnDefinition = "int default 0")
private int config_type;// 类型,0为商家,1为平台,当为1时store_id为空
private String font;// 字体,商家发布保存信息是保存该信息
private String font_size;// 字体大小
private String font_colour;// 字体颜色
public String getFont() {
return font;
}
public void setFont(String font) {
this.font = font;
}
public String getFont_size() {
return font_size;
}
public void setFont_size(String font_size) {
this.font_size = font_size;
}
public String getFont_colour() {
return font_colour;
}
public void setFont_colour(String font_colour) {
this.font_colour = font_colour;
}
public String getQuick_reply_content() {
return quick_reply_content;
}
public void setQuick_reply_content(String quick_reply_content) {
this.quick_reply_content = quick_reply_content;
}
public int getConfig_type() {
return config_type;
}
public void setConfig_type(int config_type) {
this.config_type = config_type;
}
public Long getStore_id() {
return store_id;
}
public void setStore_id(Long store_id) {
this.store_id = store_id;
}
public String getKf_name() {
return kf_name;
}
public void setKf_name(String kf_name) {
this.kf_name = kf_name;
}
public int getQuick_reply_open() {
return quick_reply_open;
}
public void setQuick_reply_open(int quick_reply_open) {
this.quick_reply_open = quick_reply_open;
}
}
|
package com.serotonin.modbus4j.base;
/**
* Class for maintaining the profile of a slave device on the master side. Initially, we assume that the device is
* fully featured, and then we note function failures so that we know how requests should subsequently be sent.
*
* @author mlohbihler
*/
public class SlaveProfile {
private boolean writeMaskRegister = true;
public void setWriteMaskRegister(boolean writeMaskRegister) {
this.writeMaskRegister = writeMaskRegister;
}
public boolean getWriteMaskRegister() {
return writeMaskRegister;
}
}
|
package com.londonappbrewery.destini;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
// TODO: Steps 4 & 8 - Declare member variables here:
TextView mStoryTextView;
Button mButtonTop;
Button mButtonBottom;
int mStoryIndex=1;
/*String[] mStringStoryTextView = new String[] {
getString(R.string.T1_Story),
getString(R.string.T2_Story),
getString(R.string.T3_Story)
};*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStoryTextView = (TextView) findViewById(R.id.storyTextView);
mButtonTop = (Button) findViewById(R.id.buttonTop);
mButtonBottom = (Button) findViewById(R.id.buttonBottom);
// TODO: Step 5 - Wire up the 3 views from the layout to the member variables:
// TODO: Steps 6, 7, & 9 - Set a listener on the top button:
// TODO: Steps 6, 7, & 9 - Set a listener on the bottom button:
mButtonTop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
updateQuestion(true);
}
});
mButtonBottom.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
updateQuestion(false);
}
});
}
private void updateQuestion(boolean userSelection) {
int updateIndex = mStoryIndex;
if((updateIndex==1)&&userSelection) {
mStoryIndex=3;
mStoryTextView.setText(R.string.T3_Story);
mButtonTop.setText(R.string.T3_Ans1);
mButtonBottom.setText(R.string.T3_Ans2);
} else if((updateIndex==1)&& !userSelection) {
mStoryIndex=2;
mStoryTextView.setText(getString(R.string.T2_Story));
mButtonTop.setText(R.string.T2_Ans1);
mButtonBottom.setText(R.string.T2_Ans2);
}
//mStoryIndex==2"
if((updateIndex==2)&&userSelection) {
mStoryIndex=3;
mStoryTextView.setText(R.string.T3_Story);
mButtonTop.setText(R.string.T3_Ans1);
mButtonBottom.setText(R.string.T3_Ans2);
} else if((updateIndex==2)&& !userSelection) {
mStoryIndex=4;
mStoryTextView.setText(getString(R.string.T4_End));
mButtonTop.setVisibility(View.GONE);
mButtonBottom.setVisibility(View.GONE);
}
//mStoryIndex==3"
if((updateIndex==3)&&userSelection) {
mStoryIndex=6;
mStoryTextView.setText(getString(R.string.T6_End));
mButtonTop.setVisibility(View.GONE);
mButtonBottom.setVisibility(View.GONE);
} else if((updateIndex==3)&& !userSelection) {
mStoryIndex=5;
mStoryTextView.setText(getString(R.string.T5_End));
mButtonTop.setVisibility(View.GONE);
mButtonBottom.setVisibility(View.GONE);
}
// //TODO
// When the user gets to the end of the story,
// hide the buttons with [YourButtonName].setVisibility(View.GONE);
}
}
|
package com.vipvideo.ui.login;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.lixh.base.BaseActivity;
import com.lixh.utils.Alert;
import com.lixh.utils.LocalAppInfo;
import com.lixh.utils.UToast;
import com.lixh.view.LoadView;
import com.lixh.view.UToolBar;
import com.vipvideo.R;
import com.vipvideo.bean.UserBean;
import com.vipvideo.presenter.LoginPresenter;
import com.vipvideo.util.UserInfoUtils;
import butterknife.Bind;
import butterknife.OnClick;
/**
* author: rsw
* created on: 2018/10/21 下午1:35
* description: 登录页面
*/
public class LoginActivity extends BaseActivity<LoginPresenter> implements TextWatcher {
LoginPresenter loginPresenter;
@Bind(R.id.edit_account)
EditText editAccount;
@Bind(R.id.edit_password)
EditText editPassword;
@Bind(R.id.btn_login)
Button btnLogin;
private String username;
private String password;
@Override
public void initTitle(UToolBar toolBar) {
}
@Override
public void initLoad(LoadView.Builder builder) {
builder.swipeBack = true;
builder.hasToolbar = false;
}
@Override
public void init(Bundle savedInstanceState) {
super.init(savedInstanceState);
editAccount.addTextChangedListener(this);
editPassword.addTextChangedListener(this);
loginPresenter = getPresenter();
}
@Override
public int getLayoutId() {
return R.layout.layout_login;
}
@OnClick({R.id.image_back, R.id.text_forget_password, R.id.btn_login, R.id.text_register})
public void onClick(View view) {
switch (view.getId()) {
case R.id.image_back:
finish();
break;
case R.id.text_register:
intent.go(RegisterActivity.class);
break;
case R.id.text_forget_password:
intent.go(ForgetPasswordActivity.class);
break;
case R.id.btn_login:
username = editAccount.getText().toString();
password = editPassword.getText().toString();
if (TextUtils.isEmpty(username)) {
Alert.displayAlertDialog(this, "请输入手机号");
return;
}
if (TextUtils.isEmpty(password)) {
Alert.displayAlertDialog(this, "请输入密码");
return;
}
if (password.length() < 6) {
Alert.displayAlertDialog(this, "请输入6位以上密码");
return;
}
loginPresenter.login(username, password, LocalAppInfo.getLocalAppInfo().getIMei());
break;
}
}
/**
* 登录成功
*/
public void loginSuccess(UserBean userInfoBean) {
userInfoBean.setUsername(username);
userInfoBean.setPassword(password);
UserInfoUtils.saveUserInfo(userInfoBean);
UToast.showShort("登录成功");
finish();
}
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
btnLogin.setEnabled(!TextUtils.isEmpty(editAccount.getText().toString()) && !TextUtils.isEmpty(editPassword.getText().toString()));
}
}
|
package utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.Sets;
import com.google.common.collect.Sets.SetView;
import com.google.common.io.Files;
public class QueueUtils {
public static void getQueueStrings(File inputFile, File outputFile) {
try {
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
String line;
while ((line = reader.readLine()) != null) {
String[] parts = line.split("\t");
if (parts.length == 3) {
try {
writer.write(parts[1]);
writer.newLine();
} catch (IOException e) {
e.printStackTrace();
}
}
}
writer.flush();
reader.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static Set<String> getFileDifference(File file1, File file2) {
try {
BufferedReader reader1 = new BufferedReader(new FileReader(file1));
BufferedReader reader2 = new BufferedReader(new FileReader(file2));
Set<String> set1 = new HashSet<String>();
Set<String> set2 = new HashSet<String>();
String line;
while ((line = reader1.readLine()) != null) {
set1.add(line);
}
while ((line = reader2.readLine()) != null) {
set2.add(line);
}
SetView<String> diff = Sets.difference(set1, set2);
reader1.close();
reader2.close();
return diff;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static void removeUndone(File done, File folder) {
try {
BufferedReader reader = new BufferedReader(new FileReader(done));
Set<String> files = new HashSet<String>();
String line;
while ((line = reader.readLine()) != null) {
String fileName = line.substring(line.lastIndexOf("/") + 1);
fileName = fileName.substring(0, fileName.indexOf("."));
files.add(fileName);
}
for (File subFile: folder.listFiles()) {
if (subFile.isFile() && !files.contains(subFile.getName())) {
subFile.delete();
}
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void deleteLastLine(File inputDir, File outputDir) {
File[] files = inputDir.listFiles();
int lastP = -1;
for(int i = 0; i < files.length; i++) {
if (!files[i].isFile()) {
continue;
}
if (i * 100 / files.length > lastP) {
lastP = i * 100 / files.length;
System.out.println(lastP + "%");
}
try {
RandomAccessFile f = new RandomAccessFile(files[i], "rw");
long pos = f.length() - 1;
while (pos >= 0) {
f.seek(pos);
if (f.readByte() == 10) {
if (pos > 0) {
f.seek(pos - 1);
if (f.readByte() == 13) {
pos -= 1;
}
}
f.setLength(pos);
break;
}
pos--;
}
f.close();
Files.move(files[i], outputDir.toPath().resolve(files[i].getName()).toFile());
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("100%");
}
public static void getRemaingTodos(List<String> done, List<String> todos, File output) {
Map<String, String> map = new HashMap<String, String>();
for (String todo: todos) {
map.put(CommonCrawlSource.getFileNameFromUrl(todo), todo);
}
for (String file: done) {
map.remove(file);
}
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(output));
for (String file: map.values()) {
writer.write(file);
writer.newLine();
}
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package com.rengu.operationsoanagementsuite.Repository;
import com.rengu.operationsoanagementsuite.Entity.ComponentDetailEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
@Repository
public interface ComponentDetailRepository extends JpaRepository<ComponentDetailEntity, String>, JpaSpecificationExecutor<ComponentDetailEntity> {
}
|
package com.partnertap.cache.controller;
import com.partnertap.cache.service.AdminCannedService;
import com.partnertap.cache.model.ReportsRepDetails;
import com.partnertap.cache.model.api.ReportsRepDetailsInterface;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.Advised;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.rest.webmvc.ResourceNotFoundException;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/canned", produces = MediaType.APPLICATION_JSON_VALUE)
public class AdminCannedController {
private final static Logger logger = LoggerFactory.getLogger(AdminCannedController.class);
@Autowired
private AdminCannedService reportsService;
@RequestMapping(value = "/samplerepslist", method = RequestMethod.GET)
public List<ReportsRepDetails> getSampleReps(
@RequestParam(value = "managerId") String managerId ) {
logger.info("Retrieving All Reps for managerId {}",
managerId);
long startTime = System.currentTimeMillis();
List<ReportsRepDetails> allReps = reportsService.getAllReps(managerId);
long endTime = System.currentTimeMillis();
logger.info("getAllReps: time taken {}", (endTime - startTime));
for (ReportsRepDetails repDetail : allReps) {
logger.info("email-> {}", repDetail.getEmailAddress());
}
return Optional.ofNullable(allReps).orElseThrow(ResourceNotFoundException::new);
}
@RequestMapping(value = "/allrepslist", method = RequestMethod.GET)
public List<ReportsRepDetailsInterface> getAllReps(
@RequestParam(value = "managerId") String managerId ) {
logger.info("Retrieving All Reps for managerId {}",
managerId);
long startTime = System.currentTimeMillis();
List<ReportsRepDetailsInterface> allReps = reportsService.getAllRepsFromDB(managerId);
long endTime = System.currentTimeMillis();
logger.info("getAllReps: time taken {}", (endTime - startTime));
for (ReportsRepDetailsInterface repDetail : allReps) {
logger.info("email-> {}", repDetail.getEmailAddress());
}
return Optional.ofNullable(allReps).orElseThrow(ResourceNotFoundException::new);
}
}
|
package java8;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.partitioningBy;
/**
* Created by RENT on 2017-03-18.
*/
public class LambdaPersons {
public static void main(String[] args) {
List<Person> personList = new ArrayList<>();
personList.add(new Person("Adam", "Nowak", "Wrocław",1));
personList.add(new Person("Adam", "Kowalska", "Warszawa",2));
personList.add(new Person("Karolina", "Iłak", "Warszawa",3));
int lookingFor =1;
personList.stream().filter(p->p.getId()==lookingFor).forEach(p->System.out.println(p.toString()));
// Map<String,List<Person>>groupByNames = personList.stream().collect(groupingBy(p->p.getFirsName()));
// groupByNames.entrySet().stream().forEach(e->{
// System.out.println(e.getKey());
// System.out.println(e.getValue().stream().peek(p->p.getCity()).count());
// });
//
// Map<String,List <Person>> groupByCities = personList.stream().collect(groupingBy(p->p.getCity()));
// groupByCities.entrySet().stream().forEach(entry->{
// System.out.println(entry.getKey().toUpperCase());
// System.out.println(entry.getValue().stream().count());
// });
// for (Map.Entry<String, List<Person>> entry: groupByCities.entrySet()){
// System.out.println("Map key: " + entry.getKey());
// System.out.println("Value key " + entry.getValue());
// }
////partitionigBy
// Map<Boolean, List<Person>> adam = personList.stream()
// .collect(partitioningBy(p->p.getFirsName().equals("Adam")));
//
// List<Person>people = adam.get(false); // nie spelnia warunku
// List<Person>peopleAdam = adam.get(true); // spełnia warunek
//
// //groupingBy
// Map<String,List<Person>> firstNamesMap= personList.stream().collect(groupingBy(p->p.getFirsName()));
// List<Person> adam1= firstNamesMap.get("Adam"); //zwroci nam osoby o imieniu Adam
//
// // przechodzenie po mapie
// for (Map.Entry<String, List<Person>> entry : firstNamesMap.entrySet()){
// System.out.println("Map key: " + entry.getKey());
// System.out.println("Map value: " + entry.getValue());
//
// }
//
//
// double size = personList.stream().mapToInt(p->p.getLastName().length()).summaryStatistics().getAverage();
// System.out.println(size);
//
// String result = personList.stream()
// .map(person -> person.toString())
// .collect(Collectors.joining("\n", "START\n", "\nKONIEC"));
// System.out.println(result);
//
//
// personList.stream().peek(person -> System.out.println(person.toString()))
// .filter(person -> person.getCity().equals("Warszawa"))
// .map(person -> person.getLastName() + " " + person.getFirsName() + "," + person.getCity().toUpperCase())
// .forEach(person -> System.out.println(person));
//
// personList.stream().filter(person -> person.getCity().equals("Warszawa")).forEach(person -> System.out.println(person));
// personList.stream().filter(person -> person.getCity().equals("Warszawa")).
// map(person -> person.getFirsName() + " " + person.getLastName() + " " + person.getCity());
// personList.stream().sorted(Comparator.comparing(person -> person.getLastName())).forEach(person -> System.out.println(person.getLastName()));
//
// int number = 9;
// boolean firstNumber = IntStream.range(2, number / 2 + 1).noneMatch(n -> number % n == 0);
// System.out.println("Jest liczbą pierwszą " + firstNumber);
//
// IntStream.range(2, 100)
// .filter(x -> IntStream.range(2, number / 2 + 1)
// .noneMatch(n -> number % n == 0))
// .forEach(x -> System.out.println(x));
}
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.springframework.lang.Nullable;
/**
* Abstract implementation of the {@link PropertyAccessor} interface.
* Provides base implementations of all convenience methods, with the
* implementation of actual property access left to subclasses.
*
* @author Juergen Hoeller
* @author Stephane Nicoll
* @since 2.0
* @see #getPropertyValue
* @see #setPropertyValue
*/
public abstract class AbstractPropertyAccessor extends TypeConverterSupport implements ConfigurablePropertyAccessor {
private boolean extractOldValueForEditor = false;
private boolean autoGrowNestedPaths = false;
boolean suppressNotWritablePropertyException = false;
@Override
public void setExtractOldValueForEditor(boolean extractOldValueForEditor) {
this.extractOldValueForEditor = extractOldValueForEditor;
}
@Override
public boolean isExtractOldValueForEditor() {
return this.extractOldValueForEditor;
}
@Override
public void setAutoGrowNestedPaths(boolean autoGrowNestedPaths) {
this.autoGrowNestedPaths = autoGrowNestedPaths;
}
@Override
public boolean isAutoGrowNestedPaths() {
return this.autoGrowNestedPaths;
}
@Override
public void setPropertyValue(PropertyValue pv) throws BeansException {
setPropertyValue(pv.getName(), pv.getValue());
}
@Override
public void setPropertyValues(Map<?, ?> map) throws BeansException {
setPropertyValues(new MutablePropertyValues(map));
}
@Override
public void setPropertyValues(PropertyValues pvs) throws BeansException {
setPropertyValues(pvs, false, false);
}
@Override
public void setPropertyValues(PropertyValues pvs, boolean ignoreUnknown) throws BeansException {
setPropertyValues(pvs, ignoreUnknown, false);
}
@Override
public void setPropertyValues(PropertyValues pvs, boolean ignoreUnknown, boolean ignoreInvalid)
throws BeansException {
List<PropertyAccessException> propertyAccessExceptions = null;
List<PropertyValue> propertyValues = (pvs instanceof MutablePropertyValues mpvs ?
mpvs.getPropertyValueList() : Arrays.asList(pvs.getPropertyValues()));
if (ignoreUnknown) {
this.suppressNotWritablePropertyException = true;
}
try {
for (PropertyValue pv : propertyValues) {
// setPropertyValue may throw any BeansException, which won't be caught
// here, if there is a critical failure such as no matching field.
// We can attempt to deal only with less serious exceptions.
try {
setPropertyValue(pv);
}
catch (NotWritablePropertyException ex) {
if (!ignoreUnknown) {
throw ex;
}
// Otherwise, just ignore it and continue...
}
catch (NullValueInNestedPathException ex) {
if (!ignoreInvalid) {
throw ex;
}
// Otherwise, just ignore it and continue...
}
catch (PropertyAccessException ex) {
if (propertyAccessExceptions == null) {
propertyAccessExceptions = new ArrayList<>();
}
propertyAccessExceptions.add(ex);
}
}
}
finally {
if (ignoreUnknown) {
this.suppressNotWritablePropertyException = false;
}
}
// If we encountered individual exceptions, throw the composite exception.
if (propertyAccessExceptions != null) {
PropertyAccessException[] paeArray = propertyAccessExceptions.toArray(new PropertyAccessException[0]);
throw new PropertyBatchUpdateException(paeArray);
}
}
// Redefined with public visibility.
@Override
@Nullable
public Class<?> getPropertyType(String propertyPath) {
return null;
}
/**
* Actually get the value of a property.
* @param propertyName name of the property to get the value of
* @return the value of the property
* @throws InvalidPropertyException if there is no such property or
* if the property isn't readable
* @throws PropertyAccessException if the property was valid but the
* accessor method failed
*/
@Override
@Nullable
public abstract Object getPropertyValue(String propertyName) throws BeansException;
/**
* Actually set a property value.
* @param propertyName name of the property to set value of
* @param value the new value
* @throws InvalidPropertyException if there is no such property or
* if the property isn't writable
* @throws PropertyAccessException if the property was valid but the
* accessor method failed or a type mismatch occurred
*/
@Override
public abstract void setPropertyValue(String propertyName, @Nullable Object value) throws BeansException;
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.format.datetime.standard;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Locale;
import java.util.TimeZone;
import org.junit.jupiter.api.Test;
import org.springframework.format.annotation.DateTimeFormat.ISO;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Phillip Webb
* @author Sam Brannen
*/
public class DateTimeFormatterFactoryTests {
// Potential test timezone, both have daylight savings on October 21st
private static final TimeZone ZURICH = TimeZone.getTimeZone("Europe/Zurich");
private static final TimeZone NEW_YORK = TimeZone.getTimeZone("America/New_York");
// Ensure that we are testing against a timezone other than the default.
private static final TimeZone TEST_TIMEZONE = (ZURICH.equals(TimeZone.getDefault()) ? NEW_YORK : ZURICH);
private DateTimeFormatterFactory factory = new DateTimeFormatterFactory();
private LocalDateTime dateTime = LocalDateTime.of(2009, 10, 21, 12, 10, 00, 00);
@Test
public void createDateTimeFormatter() {
assertThat(factory.createDateTimeFormatter().toString()).isEqualTo(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).toString());
}
@Test
public void createDateTimeFormatterWithPattern() {
factory = new DateTimeFormatterFactory("yyyyMMddHHmmss");
DateTimeFormatter formatter = factory.createDateTimeFormatter();
assertThat(formatter.format(dateTime)).isEqualTo("20091021121000");
}
@Test
public void createDateTimeFormatterWithNullFallback() {
DateTimeFormatter formatter = factory.createDateTimeFormatter(null);
assertThat(formatter).isNull();
}
@Test
public void createDateTimeFormatterWithFallback() {
DateTimeFormatter fallback = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
DateTimeFormatter formatter = factory.createDateTimeFormatter(fallback);
assertThat(formatter).isSameAs(fallback);
}
@Test
public void createDateTimeFormatterInOrderOfPropertyPriority() {
factory.setStylePattern("SS");
String value = applyLocale(factory.createDateTimeFormatter()).format(dateTime);
assertThat(value).startsWith("10/21/09");
assertThat(value).endsWith("12:10 PM");
factory.setIso(ISO.DATE);
assertThat(applyLocale(factory.createDateTimeFormatter()).format(dateTime)).isEqualTo("2009-10-21");
factory.setPattern("yyyyMMddHHmmss");
assertThat(factory.createDateTimeFormatter().format(dateTime)).isEqualTo("20091021121000");
}
@Test
public void createDateTimeFormatterWithTimeZone() {
factory.setPattern("yyyyMMddHHmmss Z");
factory.setTimeZone(TEST_TIMEZONE);
ZoneId dateTimeZone = TEST_TIMEZONE.toZoneId();
ZonedDateTime dateTime = ZonedDateTime.of(2009, 10, 21, 12, 10, 00, 00, dateTimeZone);
String offset = (TEST_TIMEZONE.equals(NEW_YORK) ? "-0400" : "+0200");
assertThat(factory.createDateTimeFormatter().format(dateTime)).isEqualTo("20091021121000 " + offset);
}
private DateTimeFormatter applyLocale(DateTimeFormatter dateTimeFormatter) {
return dateTimeFormatter.withLocale(Locale.US);
}
}
|
package dk.aau.oose;
import org.lwjgl.util.vector.Vector2f;
import org.newdawn.slick.Color;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import dk.aau.oose.core.GameElement;
import dk.aau.oose.core.GameWorld;
public class Points extends GameElement {
public Points() throws SlickException{
super(null);
size=new Vector2f(100,500);
}
/**
*
*/
public int totalPoints=0; // defines amount of totalpoints acquired
private String text=""; // used to export amount of points ot the console
public void updatePoints (int points){
totalPoints+=points;
text=Integer.toString(totalPoints); // if amount of points updates - a new amount of points is calculated and outputted to the console
}
@Override
public void draw() {
Graphics g=GameWorld.getGameContainer().getGraphics();
g.setColor(Color.white);
g.drawString(text, 100, 500); // tries to draw score into the screen, NEEDS TO BE FIXED
}
@Override
public void update() {
}
}
|
package br.com.fiap.fiapinteliBe21.controller.exception;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import br.com.fiap.fiapinteliBe21.service.exception.DataIntegrityException;
import br.com.fiap.fiapinteliBe21.service.exception.ObjectNotFoundException;
@ControllerAdvice
public class ResourceExceptionHandler {
@ExceptionHandler(ObjectNotFoundException.class)
public ResponseEntity<StandardErrorMain> objectNotFound (ObjectNotFoundException e, HttpServletRequest request){
StandardErrorMain err = new StandardErrorMain(HttpStatus.NOT_FOUND.value(), e.getMessage(), System.currentTimeMillis());
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(err);
}
@ExceptionHandler(DataIntegrityException.class)
public ResponseEntity<StandardErrorMain> DataIntegrity (DataIntegrityException e, HttpServletRequest request){
StandardErrorMain err = new StandardErrorMain(HttpStatus.BAD_REQUEST.value(), e.getMessage(), System.currentTimeMillis());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(err);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<StandardErrorMain> validation (MethodArgumentNotValidException e, HttpServletRequest request){
ValidationError err = new ValidationError(HttpStatus.BAD_REQUEST.value(), "Erro de validação", System.currentTimeMillis());
for (FieldError x : e.getBindingResult().getFieldErrors()) {
err.addError(x.getField(), x.getDefaultMessage());
}
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(err);
}
}
|
package com.leejua.myproject.members;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
@Repository
public interface MemberRepository extends JpaRepository<Member, Long> {
@Transactional
@Modifying
public void deleteByEmail(String email);
@Transactional
@Modifying(clearAutomatically=true, flushAutomatically=true)
@Query(value="update member m set m.passwd = :passwd where m.email like :email" , nativeQuery=true)
public void updatePasswd(@Param("email")String email,@Param("passwd")String passwd);
}
|
package com.aim.project.pwp.heuristics;
import java.util.Random;
import com.aim.project.pwp.PWPObjectiveFunction;
import com.aim.project.pwp.interfaces.HeuristicInterface;
import com.aim.project.pwp.interfaces.PWPSolutionInterface;
public class InversionMutation extends HeuristicOperators implements HeuristicInterface {
private final Random oRandom;
public InversionMutation(Random oRandom) {
super();
this.oRandom = oRandom;
}
@Override
public double apply(PWPSolutionInterface oSolution, double dDepthOfSearch, double dIntensityOfMutation) {
//Get length of solution
int solutionLength = oSolution.getNumberOfLocations() - 2;
//Calculate apply times
int times = getTimes(dIntensityOfMutation);
double currentOFV = oSolution.getObjectiveFunctionValue();
for (int i = 0; i < times; i++) {
//Generate two distinct index
int startIndex = oRandom.nextInt(solutionLength);
int endIndex = oRandom.nextInt(solutionLength);
while (startIndex == endIndex) {
endIndex = oRandom.nextInt(solutionLength);
}
int temp = 0;
//Set start & end to respective location
if(startIndex > endIndex) {
temp = startIndex;
startIndex = endIndex;
endIndex = temp;
}
//Calculate OFV value
currentOFV = deltaIM(oSolution, currentOFV, startIndex, endIndex);
//Swap each node between start & end
for (int j = 0; j < (endIndex + 1 - startIndex) / 2; i++) {
swap(oSolution, startIndex + j, endIndex - j);
}
//Update OFV value
oSolution.setObjectiveFunctionValue(currentOFV);
}
return oSolution.getObjectiveFunctionValue();
}
@Override
public boolean isCrossover() {
return false;
}
@Override
public boolean usesIntensityOfMutation() {
return true;
}
@Override
public boolean usesDepthOfSearch() {
return false;
}
}
|
/*
* Created on 2004-11-10
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.aof.webapp.form;
/**
* @author shilei
*
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Style - Code Templates
*/
public class FormattingException extends RuntimeException {
private Throwable cause;
public FormattingException(String message) {
super(message);
}
public FormattingException(String message, Throwable cause) {
super(message);
this.cause = cause;
}
public void setCause(Throwable cause) {
this.cause = cause;
}
public Throwable getCause() {
return cause;
}
public String toString() {
return super.toString()
+ (cause == null ? "" : "\nOriginal Cause:\n"
+ cause.toString());
}
public void printStackTrace() {
super.printStackTrace();
if (cause != null) {
cause.printStackTrace();
}
}
private Formatter formatter;
public Formatter getFormatter() {
return formatter;
}
public void setFormatter(Formatter formatter) {
this.formatter = formatter;
}
} |
import java.io.Serializable;
public class Bil implements Serializable {
private static final long serialVersionUID = 1L;
private String kjennetegn;
private String merke_type;
private int forstereg;
Bil neste;
public Bil(String kjennetegn, String merke_type, int forstereg) {
this.kjennetegn=kjennetegn;
this.merke_type=merke_type;
this.forstereg=forstereg;
}
public String getKjennetegn() {
return this.kjennetegn;
}
public String toString() {
return "Kjennetegn: " +kjennetegn+ ".\nMerke: " +merke_type+ ".\nRegistert første gang: " +forstereg+ ".";
}
}
|
package com.example.laurentiuolteanu.victorycuprefereeassistant;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.laurentiuolteanu.victorycuprefereeassistant.bl.Game;
import com.example.laurentiuolteanu.victorycuprefereeassistant.bl.Team;
import com.example.laurentiuolteanu.victorycuprefereeassistant.dal.TeamSingleton;
import java.util.List;
public class GamesListAdapter extends RecyclerView.Adapter<GamesListAdapter.GamesListAdapterViewHolder> {
private List<Game> games;
public GamesListAdapter(List<Game> g){
games = g;
}
@NonNull
@Override
public GamesListAdapterViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_games_item, parent, false);
return new GamesListAdapterViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull GamesListAdapterViewHolder holder, int position) {
holder.bindData(games.get(position));
}
@Override
public int getItemCount() {
return games.size();
}
public class GamesListAdapterViewHolder extends RecyclerView.ViewHolder {
private TextView fieldTextView;
private TextView leagueTextView;
private TextView team1TextView;
private TextView team2TextView;
private TextView scoreTimeTextView;
private ImageView team1ImageView;
private ImageView team2ImageView;
private ImageView matchStatusImageView;
public GamesListAdapterViewHolder(final View itemView) {
super(itemView);
fieldTextView = itemView.findViewById(R.id.fieldTextView);
leagueTextView = itemView.findViewById(R.id.txtMinute);
team1TextView = itemView.findViewById(R.id.team1TextView);
team2TextView = itemView.findViewById(R.id.txtNamePlayerGuest);
scoreTimeTextView = itemView.findViewById(R.id.txtScore);
team1ImageView = itemView.findViewById(R.id.imageViewActionHost);
team2ImageView = itemView.findViewById(R.id.imageViewActionGuest);
matchStatusImageView = itemView.findViewById(R.id.matchStatusImageView);
}
public void bindData(final Game game) {
Team team1 = TeamSingleton.getInstance().getTeamById(game.getHostID());
Team team2 = TeamSingleton.getInstance().getTeamById(game.getGuestID());
setMatchTeamsPreferences(team1, team2);
setGameStatistics(game);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SelectMatch(view, game);
}
});
}
private void setMatchTeamsPreferences(Team team1, Team team2) {
team1TextView.setText(team1.getName());
team2TextView.setText(team2.getName());
Context context = team1ImageView.getContext();
int id = context.getResources().getIdentifier(team1.getLogo(), "drawable", context.getPackageName());
team1ImageView.setImageResource(id);
id = context.getResources().getIdentifier(team2.getLogo(), "drawable", context.getPackageName());
team2ImageView.setImageResource(id);
}
private void setGameStatistics(Game game) {
fieldTextView.setText(game.getField());
leagueTextView.setText(game.getLeague());
switch (game.getStatus()){
case Game.GAME_ENDED:
scoreTimeTextView.setText(game.getScore());
matchStatusImageView.setImageResource(R.drawable.ic_match_ended);
break;
case Game.GAME_NOT_STARTED:
scoreTimeTextView.setText(game.getTime());
matchStatusImageView.setImageResource(R.drawable.ic_match_ready);
break;
case Game.GAME_IN_PROGRESS:
scoreTimeTextView.setText("Se Joaca");
matchStatusImageView.setImageResource(R.drawable.ic_match_in_progress);
}
}
private void SelectMatch(View view, Game game){
if(game.getStatus() == Game.GAME_NOT_STARTED) {
Intent i = new Intent(view.getContext(), PlayersAttendanceActivity.class);
i.putExtra("matchId", game.getId());
view.getContext().startActivity(i);
} else {
Intent i = new Intent(view.getContext(), MatchActivity.class);
i.putExtra("matchId", game.getId());
view.getContext().startActivity(i);
}
}
}
} |
package section4;
import javax.swing.JOptionPane;
public class QuizGame {
public static void main(String[] args) {
// 1. Create a variable to hold the user's score
int userScore = 0;
// 2. Ask the user a question
String answer1 = JOptionPane.showInputDialog("If x=7, then what is 2x - 3x + (9/3)?");
// 3. Use an if statement to check if their answer is correct
if(answer1.equals("-4")) {
// 4. if the user's answer was correct, add one to their score
userScore += 1;
}
// 5. Create more questions by repeating steps 1, 2, and 3 below.
String answer2 = JOptionPane.showInputDialog("How far away do you have to be to meet the social distancing guidelines?");
// 6. After all the questions have been asked, print the user's score
if(answer2.equals("6 feet")) {
userScore += 1;
}
String answer3 = JOptionPane.showInputDialog("Who is the male who had two number one songs in 2019?");
if(answer3.equals("Post Malone")) {
userScore += 1;
}
JOptionPane.showMessageDialog(null, "Your final score is " + userScore + "!");
}
}
|
package DataStructures.arrays;
import java.util.ArrayList;
/**
* Created by senthil on 21/8/16.
*/
public class AntiDiagonals {
public ArrayList<ArrayList<Integer>> diagonal(ArrayList<ArrayList<Integer>> A) {
int l = A.size();
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < 2 * l - 1; ++i) {
int offset = i < l ? 0 : i - l + 1;
ArrayList<Integer> row = new ArrayList<Integer>();
for (int j = offset; j <= i - offset; ++j) {
row.add(A.get(j).get(i - j));
}
res.add(row);
}
return res;
}
public static void main(String ar[]) {
AntiDiagonals ad = new AntiDiagonals();
ArrayList<ArrayList<Integer>> l1 = new ArrayList<>();
ArrayList<Integer> list = new ArrayList<>();
ArrayList<Integer> list1 = new ArrayList<>();
ArrayList<Integer> list2 = new ArrayList<>();
list.add(1);list.add(2);list.add(3);
list1.add(4);list1.add(5);list1.add(6);
list2.add(7);list2.add(8);list2.add(9);
l1.add(list);
l1.add(list1);
l1.add(list2);
ad.diagonal(l1);
}
} |
package com.alexlionne.apps.avatars.Tour;
import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import com.alexlionne.apps.avatars.MainActivity;
import com.alexlionne.apps.avatars.R;
import com.heinrichreimersoftware.materialintro.app.IntroActivity;
import com.heinrichreimersoftware.materialintro.slide.SimpleSlide;
import com.heinrichreimersoftware.materialintro.slide.Slide;
public class MainIntroActivity extends IntroActivity {
public static final String EXTRA_FULLSCREEN = "com.heinrichreimersoftware.materialintro.demo.EXTRA_FULLSCREEN";
public static final String EXTRA_SCROLLABLE = "com.heinrichreimersoftware.materialintro.demo.EXTRA_SCROLLABLE";
public static final String EXTRA_CUSTOM_FRAGMENTS = "com.heinrichreimersoftware.materialintro.demo.EXTRA_CUSTOM_FRAGMENTS";
public static final String EXTRA_PERMISSIONS = "com.heinrichreimersoftware.materialintro.demo.EXTRA_PERMISSIONS";
public static final String EXTRA_SKIP_ENABLED = "com.heinrichreimersoftware.materialintro.demo.EXTRA_SKIP_ENABLED";
public static final String EXTRA_FINISH_ENABLED = "com.heinrichreimersoftware.materialintro.demo.EXTRA_FINISH_ENABLED";
@Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
boolean fullscreen = intent.getBooleanExtra(EXTRA_FULLSCREEN, false);
boolean scrollable = intent.getBooleanExtra(EXTRA_SCROLLABLE, false);
boolean customFragments = intent.getBooleanExtra(EXTRA_CUSTOM_FRAGMENTS, true);
boolean permissions = intent.getBooleanExtra(EXTRA_PERMISSIONS, true);
boolean skipEnabled = intent.getBooleanExtra(EXTRA_SKIP_ENABLED, false);
boolean finishEnabled = intent.getBooleanExtra(EXTRA_FINISH_ENABLED, false);
setFullscreen(fullscreen);
super.onCreate(savedInstanceState);
setSkipEnabled(skipEnabled);
setFinishEnabled(finishEnabled);
startNextMatchingActivity(new Intent(MainIntroActivity.this, MainActivity.class));
addSlide(new SimpleSlide.Builder()
.title(R.string.title)
.description(R.string.desc)
.image(R.drawable.moto360)
.background(R.color.primary)
.backgroundDark(R.color.primary_dark)
.scrollable(scrollable)
.build());
addSlide(new SimpleSlide.Builder()
.title(R.string.title)
.description(R.string.desc)
.image(R.drawable.moto360)
.background(R.color.primary)
.backgroundDark(R.color.primary_dark)
.scrollable(scrollable)
.build());
final Slide permissionsSlide;
if (permissions) {
permissionsSlide = new SimpleSlide.Builder()
.title(R.string.title)
.description(R.string.intro_latest_step)
.background(R.color.primary)
.backgroundDark(R.color.primary_dark)
.scrollable(scrollable)
.permission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
.build();
addSlide(permissionsSlide);
} else {
permissionsSlide = null;
}
}
} |
package org.example.common.url;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import java.io.IOException;
import java.io.InputStream;
public class BaseServletInputStream extends ServletInputStream {
private InputStream stream;
public BaseServletInputStream(InputStream stream) {
this.stream = stream;
}
public void setStream(InputStream stream) {
this.stream = stream;
}
@Override
public int read() throws IOException {
return stream.read();
}
@Override
public boolean isFinished() {
return true;
}
@Override
public boolean isReady() {
return true;
}
@Override
public void setReadListener(ReadListener readListener) {
}
}
|
package io.zipcoder.interfaces;
import java.util.HashMap;
import java.util.Map;
public final class ZipCodeWilmington {
private static final ZipCodeWilmington INSTANCE = new ZipCodeWilmington();
Students students = Students.getInstance();
Instructors instructors = Instructors.getInstance();
Map<Student, Double> studyMap;
public ZipCodeWilmington() {
studyMap = new HashMap<Student, Double>();
}
public void hostLecture(Teacher teacher, double numberOfHours) {
teacher.lecture(students.getArray(), numberOfHours);
}
public void hostLecture(Long id, double numberOfHours) {
Teacher teacher = instructors.findById(id);
teacher.lecture(students.getArray(), numberOfHours);
}
public Map<Student, Double> getStudyMap() {
for (Student student : students) {
studyMap.put(student, student.getTotalStudyTime());
}
return studyMap;
}
public static ZipCodeWilmington getInstance(){
return INSTANCE;
}
}
|
package com.esum.comp.uakt.outbound;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.Socket;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.esum.comp.uakt.UaKTCode;
import com.esum.comp.uakt.UaKTConfig;
import com.esum.comp.uakt.UaKTException;
import com.esum.comp.uakt.table.UaKTInfoRecord;
import com.esum.framework.common.util.DateUtil;
import com.esum.framework.common.util.FileUtil;
import com.esum.framework.core.event.message.MessageEvent;
/**
* 새로운키를 생성하여 발송하고, 발송 성공시 생성하여 전송한 키를 반환하도록함.
*
* Copyright(c) eSum Technologies, Inc. All rights reserved.
*/
public class UaSendProcessor {
private Logger log = LoggerFactory.getLogger(UaSendProcessor.class);
// Transaction Code
private String trCode;
private InetAddress ip;
private int port;
private String id;
private String password;
private int timeout;
private int networkBandwidth;
private Socket clientSocket;
private InputStreamReader inStream;
private OutputStreamWriter outStream;
private String readData;
private byte [] sendMsg;
private String uniId;
private boolean useBackup;
private File backupPath;
private File errBackupPath;
private MessageEvent messageEvent;
private String traceId;
public UaSendProcessor(String trCode, UaKTInfoRecord uaInfo, MessageEvent msgEvent) throws Exception {
if (trCode == null)
this.trCode = getTRCode();
else
this.trCode = trCode;
this.messageEvent = msgEvent;
byte [] data = msgEvent.getMessage().getPayload().getData();
uniId = getUniqueID();
this.sendMsg = zip(uniId, data);
ip = Inet4Address.getByName(uaInfo.getOutboundIp());
port = uaInfo.getOutboundPort();
timeout = uaInfo.getOutboundTimeout();
id = uaInfo.getOutboundId();
password = uaInfo.getOutboundPwd();
networkBandwidth = uaInfo.getOutboundNetworkWidth();
useBackup = uaInfo.isOutboundUseBackup();
if(useBackup) {
backupPath = new File(uaInfo.getOutboundBackupPath());
errBackupPath = new File(backupPath + "/error");
if(!backupPath.exists())
backupPath.mkdirs();
}
}
public String getUniId(){
return uniId;
}
/**
* create Unique ID
*/
public static synchronized String getUniqueID() {
return DateUtil.format("MMddHHmmssS");
}
/**
* Get TR Code
*/
public static synchronized String getTRCode() {
return DateUtil.format("ddHHmmss") + "0";
}
/**
* zip data for send
*/
public byte[] zip(String name, byte [] data) throws IOException {
ZipOutputStream zos = null;
ByteArrayOutputStream bo = null;
try {
bo = new ByteArrayOutputStream();
zos = new ZipOutputStream(bo);
ZipEntry entry = new ZipEntry(name);
entry.setTime(System.currentTimeMillis());
zos.putNextEntry(entry);
zos.write(data);
zos.flush();
zos.close();
return bo.toByteArray();
} finally {
if(zos != null){
zos.close();
}
if(bo != null){
bo.close();
}
zos = null;
bo = null;
}
}
/**
* Fill field with filler
*/
private String fillField(String data, int len, String filler) {
if (filler == null) filler = " ";
data = data.trim();
int dataLen = data.length();
if (dataLen < len)
{
for(int i = dataLen; i < len; ++i)
{
data = data + filler;
}
}
else data = data.substring(0, len);
return data;
}
/**
* Write to Server
*/
private boolean doRequest(String msgCode, String errorCode, String msg) {
try {
outStream.write(msg);
outStream.flush();
log.debug(traceId+"trCode : "+trCode+", msgCode : "+msgCode+", errorCode : "+errorCode+", msg : "+msg);
} catch (IOException ex) {
log.error(traceId+"trCode : "+trCode+", msgCode : "+msgCode+", errorCode : "+errorCode+
", msg : It failed that client send to server with the request message.");
log.error(traceId+"doRequest()", ex);
return false;
}
return true;
}
/**
* Read from Server
*/
private boolean doResponse() throws Exception {
// Read Data
char [] msg = new char[UaKTConfig.BUFFER_SIZE];
int msgLength = inStream.read(msg, 0, UaKTConfig.BUFFER_SIZE); // Server Response Message Length
log.debug(traceId+"Buffer Size: " + UaKTConfig.BUFFER_SIZE + ", Bandwidth: " + networkBandwidth + "kbps");
if (msgLength != -1)
log.debug(traceId+"Received Message Length: " + msgLength + "bytes");
else
return false;
// Convert Char Data to String Data
readData = (new String(msg)).substring(0, msgLength);
log.debug(traceId+"Read Data: " + readData);
return true;
}
/**
* Check Transaction Code
*/
private boolean checkTRCode(String msgCode, String code) {
if (readData.substring(0, 9).equalsIgnoreCase(code))
return true;
else {
log.error(traceId+"trCode : "+trCode+", msgCode : "+msgCode+", errorCode : 008"+
", msg : The TR CODE(" + readData.substring(0, 9) + ") is abnormal.");
return false;
}
}
/**
* Check Response Code
*/
private boolean checkMessageCode(String msgCode, String code) {
if (readData.substring(9, 12).equalsIgnoreCase(code))
return true;
else {
log.error(traceId+"trCode : "+trCode+", msgCode : "+msgCode+", errorCode : 008"+
", msg : The Message CODE(" + readData.substring(9, 12) + ") is abnormal.");
return false;
}
}
/**
* Check Response Code
*/
private boolean checkResponseCode(String msgCode, String code) throws Exception {
String respCode = readData.substring(12, 15).trim();
if (respCode.equalsIgnoreCase(code))
return true;
else {
log.error(traceId+"trCode : "+trCode+", msgCode : "+msgCode+", errorCode : "+respCode+", msg : "+UaKTCode.getRespCode(respCode));
String errMsg = "ResponseCode ["+respCode+ "] : "+ UaKTCode.getRespCode(respCode);
throw new UaKTException(UaKTCode.ERROR_COMM_KT, "UASendProcessor.run()", errMsg, respCode);
}
}
/**
* LOGIN Request
*/
private boolean loginRequest() {
String header = null;
String requestMsg = null;
String reserved = fillField("", 25, "R"); //예비 필드
String bodyMsg = null;
// 헤더 길이 40Bytes
header = trCode + "003" + "000" + reserved;
if (header.length() != 40) return false;
// 바디 길이 110Bytes
// LoginID | LoginPassword | Job Type(SD) | Data Type | Filler
bodyMsg = fillField(id, 20, null) + fillField(password, 8, null) + "SD" + fillField("", 6 , null) + fillField("", 14 , "F");
// Flag | Start Time | End Time
bodyMsg = bodyMsg + fillField("", 1, null) + fillField("", 12, null) + fillField("", 12, null);
// Password Change | New Password | Comm Size
bodyMsg = bodyMsg + fillField("", 1, null) + fillField("", 8, null) + fillField(String.valueOf(networkBandwidth), 4, null);
// RemoteID | Filler
bodyMsg = bodyMsg + fillField("", 20, null) + fillField("", 2, "F");
// 메시지(헤더+바디) 길이 150Bytes
requestMsg = header + bodyMsg;
// log.info("Login Request Msg: " + requestMsg);
// Login Request Message to Server
if (!doRequest("003", "000", requestMsg)) {
requestMsg = null;
return false;
}
requestMsg = null;
return true;
}
/**
* LOGIN Response
*/
private boolean loginResponse() throws Exception {
if (!doResponse()) return false;
if (!checkTRCode("030", trCode)) return false;
if (!checkMessageCode("030", "030")) return false;
if (!checkResponseCode("030", "000")) return false;
return true;
}
/**
* Transmission File Notify(100)
*/
private boolean transFileNotify(int last) {
String header = null;
String requestMsg = null;
String reserved = fillField("", 25, "R"); //예비 필드
String bodyMsg = null;
String lastFlag = null;
if (last == 1) lastFlag = "END";
else lastFlag = "NXT";
// 헤더 길이 40Bytes
header = trCode + "100" + "000" + reserved;
// 바디 길이 110Bytes
bodyMsg = fillField(uniId, 20, null) + fillField(String.valueOf(sendMsg.length), 10, null) + fillField("", 20, null);
bodyMsg = bodyMsg + fillField("", 20, null) + fillField("" , 1, "F") + fillField("", 10, "F");
bodyMsg = bodyMsg + lastFlag + "NEW" + fillField("" , 1, "F") + fillField("", 22, "F");
// 메시지(헤더+바디) 길이 150Bytes
requestMsg = header + bodyMsg;
// Transmission File Notify Message to Server
if (!doRequest("100", "000", requestMsg)) {
requestMsg = null;
return false;
}
requestMsg = null;
return true;
}
/**
* Transmission File Notify Response(110)
*/
private boolean transFileNotifyResponse() throws Exception {
if (!doResponse()) return false;
if (!checkTRCode("110", trCode)) return false;
if (!checkMessageCode("110", "110")) return false;
if (!checkResponseCode("110", "000")) return false;
return true;
}
/**
* Data Transmission
*/
private boolean dataTransmission() {
DataOutputStream out = null;
ByteArrayInputStream in = null;
byte[] sendMsgBf = new byte[UaKTConfig.BUFFER_SIZE];
int msgLength = -1;
long sendMsgLength = 0;
try{
out = new DataOutputStream(clientSocket.getOutputStream());
in = new ByteArrayInputStream(sendMsg);
while((msgLength = in.read(sendMsgBf, 0, sendMsgBf.length))!= -1) {
log.debug(traceId+"Read Data Length: " + msgLength + "bytes");
sendMsgLength += msgLength;
out.write(sendMsgBf, 0, msgLength);
out.flush();
log.debug(traceId+"Transfer Data Size: " + sendMsgLength + "/" + sendMsg.length + "bytes");
}
log.info(traceId+"Send data(" + sendMsg.length + " byte).");
} catch(Exception e) {
log.error(traceId+"dataTransmission()", e);
return false;
} finally {
IOUtils.closeQuietly(in);
in = null;
}
return true;
}
/**
* File Reception Confirmation
*/
private boolean recvConfirm() throws Exception {
if(useBackup){
String oldFileName = messageEvent.getMessageControlId();
String storeFileName = oldFileName + "_" + getUniqueID();
byte[] payload = messageEvent.getMessage().getPayload().getData();
try {
// Get Today Date
String today = DateUtil.getCYMD();
File todayOutBoundPath = new File(backupPath, today);
if (!todayOutBoundPath.exists()) {
if (!todayOutBoundPath.mkdirs()){
throw new Exception(todayOutBoundPath.getAbsolutePath() + " can not be make.");
}
}
FileUtil.writeToFile(new File(todayOutBoundPath, storeFileName), payload);
log.info(traceId+oldFileName + " is moved to the result directory.");
}catch (Exception ex){
try {
FileUtil.writeToFile( new File(errBackupPath, storeFileName),payload);
log.error(traceId+"recvConfirm()", ex);
} catch (IOException e){
log.error(traceId+"can not be saved to the result directory.", e);
throw e;
}
return false;
}
}
if (!doResponse()) return false;
if (!checkTRCode("130", trCode)) return false;
if (!checkMessageCode("130", "130")) return false;
if (!checkResponseCode("130", "000")) return false;
return true;
}
/**
* Transmission Process
*/
private boolean transmissionProcess() throws Exception {
log.info(traceId+"Data Transmission Process Start ...");
if (!transFileNotify(1)) {
log.error(traceId+"The client can not process normally the Transmission File Notify message.");
return false;
} else
log.info(traceId+"Sent the Transmission File Notify message.");
// Transmission File Notify Response Message(110)
if (!transFileNotifyResponse()) {
log.error(traceId+"The client can not process normally the Transmission File Response message.");
return false;
} else
log.info(traceId+"Received the Transmission File Response message.");
// Data Transmission(120)
if (!dataTransmission()) {
log.error(traceId+"The client can not process normally the Transmission DATA.");
return false;
} else
log.info(traceId+"Sent the Transmission DATA.");
log.info(traceId+"The server is processing the data from the client.");
// File Reception Confirmation(130)
if (!recvConfirm()) {
log.error(traceId+"The client can not process normally the Reception Confirmation message.");
return false;
} else
log.info(traceId+"Received the Reception Confirmation message.");
log.info(traceId+"Data Transmission Process Stop ...");
return true;
}
/**
* Logout Request
*/
private boolean logoutRequest() {
String header = null;
String requestMsg = null;
String reserved = fillField("", 25, "R"); //예비 필드
String bodyMsg = null;
// 헤더 길이 40Bytes
header = trCode + "007" + "000" + reserved;
// 바디 길이 110Bytes
// LoginID | LoginPassword | Job Type(SD) | Data Type | Filler
bodyMsg = fillField(id, 20, null) + fillField(password, 8, null) + "SD" + fillField("", 6 , null) + fillField("", 14 , "F");
// Flag | Start Time | End Time
bodyMsg = bodyMsg + fillField("", 1, null) + fillField("", 12, null) + fillField("", 12, null);
// RemoteID | Filler
bodyMsg = bodyMsg + fillField("", 20, null) + fillField("", 15, "F");
// 메시지(헤더+바디) 길이 150Bytes
requestMsg = header + bodyMsg;
// Logout Request Message to Server
if (!doRequest("003", "000", requestMsg)) {
requestMsg = null;
return false;
}
requestMsg = null;
return true;
}
/**
* Logout Response
*/
private boolean logoutResponse() throws Exception {
if (!doResponse()) return false;
if (!checkTRCode("070", trCode)) return false;
if (!checkMessageCode("070", "070")) return false;
if (!checkResponseCode("070", "000")) return false;
return true;
}
/**
* execute method
*/
public String process() throws Exception {
traceId = "["+trCode+"]["+messageEvent.getMessageControlId()+"] ";
try {
//1. create to Server
try{
// Create Socket Object
clientSocket = new Socket(ip, port);
log.info(traceId+"Connected to the server(" + ip.getHostAddress() + ":" + port + ").");
// Set Connection TimeOut
clientSocket.setSoTimeout(timeout);
log.debug(traceId+"Connection TimeOut: " + String.valueOf(timeout));
// Set Socket Stream
outStream = new OutputStreamWriter(clientSocket.getOutputStream());
inStream = new InputStreamReader(clientSocket.getInputStream());
} catch(Exception e) {
throw new UaKTException(UaKTCode.ERROR_CONN_KT, "UASendProcessor.run()", e.getMessage());
}
//2. Login Request Process
if(loginRequest()){
log.info(traceId+"Sent the Login Request message.");
}else{
throw new Exception("The client can not process normally the Login Request message.");
}
//3. Login Response Process
if(loginResponse()){
log.info(traceId+"Received the Login Response message.");
}else{
throw new Exception("The client can not process normally the Login Response message.");
}
//4. Transmission Process
if (transmissionProcess()){
log.info(traceId+"Sent the transmission data.");
}else{
throw new Exception("The client can not process normally the transmission data.");
}
//5. Logout Request Process
if (logoutRequest()){
log.info(traceId+"Sent the Logout Request message.");
}else{
throw new Exception("The client can not process normally the Logout Request message.");
}
//6. Logout Response Process
if (logoutResponse()){
log.info(traceId+"Received the Logout Response message.");
}else{
throw new Exception("The client can not process normally the Logout Response message.");
}
} finally {
if (clientSocket != null){
try {
clientSocket.close();
} catch (IOException ioex){
log.error(traceId+"The client socket is not closed.", ioex);
throw ioex;
}
clientSocket = null;
}
log.debug(traceId+"The client socket was closed normally.");
log.debug(traceId+"Sender Message Processor Stop ...");
log.info(traceId+"Transaction Stop: Code- " + trCode);
}
return uniId;
}
} |
package sr.hakrinbank.intranet.api.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import sr.hakrinbank.intranet.api.model.Nationality;
import java.util.List;
@Repository
public interface NationalityRepository extends JpaRepository<Nationality, Long> {
@Query("SELECT a FROM Nationality a WHERE a.deleted = 0 ORDER BY a.name ASC")
List<Nationality> findActiveNationalities();
@Query("select a from Nationality a where (a.name LIKE '%' || :qry || '%') AND a.deleted = 0")
List<Nationality> findAllActiveNationalitiesBySearchQuery(@Param("qry") String qry);
List<Nationality> findByName(String title);
}
|
package week9.homework;
import java.lang.reflect.Field;
public class JSONSerializer implements Serializer {
@Override
public void elemPostprocessing(StringBuilder writer, StringBuilder tabCount) {
writer.append(tabCount.toString())
.append("}");
}
public void elemStylePostProcessing(Object obj, StringBuilder writer, StringBuilder tabCount, Field[] fields, int i) {
if (i < fields.length - 1) writer.append(",");
writer.append("\n");
}
@Override
public void elemPreprocessing(StringBuilder writer, StringBuilder tabCount) {
writer.append(tabCount.toString())
.append("{")
.append("\n");
}
public String elemStyleProcessing(String element) {
StringBuilder writer = new StringBuilder();
return writer.append("\"")
.append(toStrategyStyle(element))
.append("\"")
.append(":").toString();
}
public void nullStrategyProcessing(StringBuilder writer) {
writer.append("\"").append("null").append("\"");
}
public void wrapperStrategyProcessing(Object obj, StringBuilder writer) {
writer.append("\"").append(obj).append("\"");
}
@Override
public String toStrategyStartingStyle() {
return "";
}
public void printLastArrayElement(StringBuilder writer, int length, int i) {
if (i < length - 1) writer.append(",");
}
public void printArrayPostProcessing(StringBuilder tabCount, StringBuilder writer) {
writer.append(tabCount).append("]");
}
public void printArrayPreProcessing(StringBuilder tabCount, StringBuilder writer) {
writer.append(tabCount).append("[").append("\n");
}
public String toStrategyStyle(String element) {
return "";
}
public String toStrategyStartingStyle(String element) {
return "";
}
}
|
/*
* $Id: WheatBeer.java,v 1.1.1.1 2004/12/21 14:00:17 mfuchs Exp $
*
* ### Copyright (C) 2004 Michael Fuchs ###
* ### All Rights Reserved. ###
*
* Author: Michael Fuchs
* E-Mail: michael.fuchs@unico-group.com
*
* Unico Media GmbH, Görresstr. 12, 80798 München, Germany
* http://www.unico-group.com
*
* RCS Information
* Author..........: $Author: mfuchs $
* Date............: $Date: 2004/12/21 14:00:17 $
* Revision........: $Revision: 1.1.1.1 $
* State...........: $State: Exp $
*/
package org.dbdoclet.test.sample;
/**
* Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium
* doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore
* veritatis et quasi architecto beatae vitae dicta sunt explicabo.
*/
public class WheatBeer extends Beer {
@Override public void drink(int num) {
}
}
|
package com.icanit.app_v2.adapter;
import java.util.List;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.icanit.app_v2.R;
import com.icanit.app_v2.entity.UserContact;
public class UserInfoListAdapter extends MyBaseAdapter {
public static final int[] colorCycle=new int[]{Color.rgb(0xff, 0xaa, 0xaa),Color.rgb(0xee,0xee,0),
Color.rgb(0xc1,0xff,0xc1),Color.rgb(0x90, 0xee, 0x90),Color.rgb(0xa4, 0xd3, 0xee)};
private Context context;
private LayoutInflater inflater;
private int resId=R.layout.item4lv_userinfo;
private List<UserContact> contactList;
public UserInfoListAdapter(Context context){
super();this.context=context;inflater=LayoutInflater.from(context);
}
public int getCount() {
if(contactList==null||contactList.isEmpty()) return 0;
return contactList.size();
}
public Object getItem(int arg0) {
return contactList.get(arg0);
}
public long getItemId(int arg0) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
UserContact contact=contactList.get(contactList.size()-position-1);
if(convertView!=null) holder=(ViewHolder)convertView.getTag();
if(convertView==null||holder==null){
holder=new ViewHolder();convertView=inflater.inflate(resId, parent,false);
convertView.setTag(holder);holder.color=convertView.findViewById(R.id.view1);
holder.info=(TextView)convertView.findViewById(R.id.textView1);
}
holder.info.setText("µç»°£º"+contact.phoneNum+"\nÐÕÃû£º"+
contact.username+"\nµØÖ·£º"+contact.address);
holder.color.setBackgroundColor(colorCycle[position%colorCycle.length]);
return convertView;
}
class ViewHolder {
public TextView info;public View color;
}
public List<UserContact> getContactList() {
return contactList;
}
public void setContactList(List<UserContact> contactList) {
this.contactList = contactList;
notifyDataSetChanged();
}
}
|
/*
* Copyright © 2018 www.noark.xyz All Rights Reserved.
*
* 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 !
* 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件:
*
* http://www.noark.xyz/LICENSE
*
* 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播;
* 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本;
* 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利;
* 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明!
*/
package xyz.noark.log.pattern;
import xyz.noark.log.LogEvent;
import java.time.format.DateTimeFormatter;
/**
* 日期样式格式化实现
*
* @author 小流氓[176543888@qq.com]
* @since 3.4.3
*/
class DatePatternFormatter extends AbstractPatternFormatter {
/**
* 日志中输出的时间格式
*/
private final DateTimeFormatter formatter;
public DatePatternFormatter(FormattingInfo formattingInfo, String options) {
super(formattingInfo, options);
// 没有指定格式,给个默认的
if (options == null) {
this.formatter = DateTimeFormatter.ISO_DATE;
}
// 使用指定的日期格式
else {
this.formatter = DateTimeFormatter.ofPattern(options);
}
}
@Override
public void doFormat(LogEvent event, StringBuilder toAppendTo) {
toAppendTo.append(formatter.format(event.getEventTime()));
}
}
|
package com.yc.education.mapper.stock;
import com.yc.education.model.stock.PurchaseStock;
import com.yc.education.util.MyMapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface PurchaseStockMapper extends MyMapper<PurchaseStock> {
/**
* @Description 查找未成本核算的采购入库单
* @param orders 入库单号
* @Author BlueSky
* @Date 17:27 2019/5/4
**/
List<PurchaseStock> listPurchaseStock(@Param("orders") String orders);
/**
* @param currentDate
* @return
*/
String selectMaxIdnum(String currentDate);
//查询所有采购入库单
List<PurchaseStock> findPurchaseStock();
//供应商交易单据
List<PurchaseStock> findPurchaseStockBySupplier(@Param("supplier") String supplier, @Param("startTime")String startTime, @Param("endTime")String endTime);
/**
* 根据入库单号查询
* @param orderno 入库单号
* @return
*/
PurchaseStock findPurchaseStockByNo(@Param("orderno") String orderno);
List<PurchaseStock> findPurchaseStockByOrders(@Param("orders") String orders);
/**
* 应付账款条件查询
* @param supplier 供应商编号
* @param supplierEnd 供应商编号
* @param invoice 进项发票号
* @param invoiceEnd 进项发票号
* @param invoiceDate 发票日期
* @param invoiceDateEnd 发票日期
* @return
*/
List<PurchaseStock> listPurchaseStockByPayment(@Param("supplier")String supplier, @Param("supplierEnd")String supplierEnd, @Param("invoice")String invoice, @Param("invoiceEnd")String invoiceEnd, @Param("invoiceDate")String invoiceDate, @Param("invoiceDateEnd")String invoiceDateEnd);
/**
* 查询为审核的单据
* @return
*/
List<PurchaseStock> findPurchanseStockNotSh();
/**
* 根据在途库存编号查询入库单
* @param boxNum
* @return
*/
PurchaseStock findPurchanseStockBoxNum(@Param("boxNum")String boxNum);
} |
package xhu.wncg.firesystem.modules.pojo;
import java.io.Serializable;
import java.util.Date;
/**
* 日常检查表
*
* @author zhaobo
* @email 15528330581@163.com
* @version 2017-11-02 15:58:16
*/
public class DailyTable implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 日常检查记录表id
*/
private Integer dailyTableId;
/**
* 检查人员id
*/
private String policeId;
/**
* 场所id
*/
private Integer unitId;
/**
* 检查人员名称
*/
private String checker;
/**
* 陪同检查人员
*/
private String otherChecker;
/**
* 存在问题
*/
private String problem;
/**
* 备注
*/
private String remark;
/**
* 创建日期
*/
private Date createDate;
/**
* 是否通过 0未通过,1通过
*/
private Integer status;
/**
* 设置:日常检查记录表id
*/
public void setDailyTableId(Integer dailyTableId) {
this.dailyTableId = dailyTableId;
}
/**
* 获取:日常检查记录表id
*/
public Integer getDailyTableId() {
return dailyTableId;
}
/**
* 设置:检查人员id
*/
public void setPoliceId(String policeId) {
this.policeId = policeId;
}
/**
* 获取:检查人员id
*/
public String getPoliceId() {
return policeId;
}
/**
* 设置:场所id
*/
public void setUnitId(Integer unitId) {
this.unitId = unitId;
}
/**
* 获取:场所id
*/
public Integer getUnitId() {
return unitId;
}
/**
* 设置:检查人员名称
*/
public void setChecker(String checker) {
this.checker = checker;
}
/**
* 获取:检查人员名称
*/
public String getChecker() {
return checker;
}
/**
* 设置:陪同检查人员
*/
public void setOtherChecker(String otherChecker) {
this.otherChecker = otherChecker;
}
/**
* 获取:陪同检查人员
*/
public String getOtherChecker() {
return otherChecker;
}
/**
* 设置:存在问题
*/
public void setProblem(String problem) {
this.problem = problem;
}
/**
* 获取:存在问题
*/
public String getProblem() {
return problem;
}
/**
* 设置:备注
*/
public void setRemark(String remark) {
this.remark = remark;
}
/**
* 获取:备注
*/
public String getRemark() {
return remark;
}
/**
* 设置:创建日期
*/
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
/**
* 获取:创建日期
*/
public Date getCreateDate() {
return createDate;
}
/**
* 设置:是否通过 0未通过,1通过
*/
public void setStatus(Integer status) {
this.status = status;
}
/**
* 获取:是否通过 0未通过,1通过
*/
public Integer getStatus() {
return status;
}
}
|
package com.project.springboot.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.project.springboot.entity.ServiceType;
public interface ServiceTypeRepository extends JpaRepository<ServiceType, Integer>{
}
|
package de.trispeedys.resourceplanning.messaging;
import de.trispeedys.resourceplanning.entity.Helper;
import de.trispeedys.resourceplanning.entity.MessagingType;
import de.trispeedys.resourceplanning.entity.misc.MessagingFormat;
import de.trispeedys.resourceplanning.util.HtmlGenerator;
public class ConfirmPauseMailTemplate extends AbstractMailTemplate
{
public ConfirmPauseMailTemplate(Helper aHelper)
{
super(aHelper, null, null);
}
public String constructBody()
{
return new HtmlGenerator(true).withParagraph("Hallo " + getHelper().getFirstName() + "!")
.withParagraph("Schade, dass Du uns dieses Mal nicht helfen kannst. Bis zum nächsten Mal (?)!")
.withParagraph("Deine Tri-Speedys.")
.render();
}
public String constructSubject()
{
return "Bestätigung Deiner Absage";
}
public MessagingFormat getMessagingFormat()
{
return MessagingFormat.HTML;
}
public MessagingType getMessagingType()
{
return MessagingType.PAUSE_CONFIRM;
}
} |
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.technotalkative.daydreamexample;
import android.os.IInterface;
public interface ITelephony
extends IInterface
{
public abstract void answerRingingCall();
public abstract void dial(String s);
public abstract boolean endCall();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.