text stringlengths 10 2.72M |
|---|
package collection.visualizer.common;
import bus.uigen.shapes.Shape;
public class Util {
@SuppressWarnings("rawtypes")
public static Class convertWrapperClassToPrimitiveClass(Class c) {
if (c.equals(Integer.class)) {
return int.class;
}
if (c.equals(Byte.class)) {
return byte.class;
}
if (c.equals(Short.class)) {
return short.class;
}
if (c.equals(Long.class)) {
return long.class;
}
if (c.equals(Float.class)) {
return float.class;
}
if (c.equals(Double.class)) {
return double.class;
}
if (c.equals(Boolean.class)) {
return boolean.class;
}
if (c.equals(Character.class)) {
return char.class;
}
return c;
}
public static ListenableVector<Shape> copyVector(ListenableVector<Shape> original) {
ListenableVector<Shape> retVal = new AListenableVector<Shape>();
for (Shape s : original) {
try {
Shape newShape = s.getClass().newInstance();
newShape.setX(s.getX());
newShape.setY(s.getY());
newShape.setWidth(s.getWidth());
newShape.setHeight(s.getHeight());
newShape.setFilled(s.isFilled());
retVal.add(newShape);
} catch (Exception e) {
e.printStackTrace();
}
}
return retVal;
}
public static int findLeadingSpaces(String s) {
if(s.isEmpty()){
return 0;
}
int numSpaces = 0;
int index = 0;
int currentChar = s.charAt(index);
while (currentChar == ' ' || currentChar == '\t') {
if (currentChar == ' ') {
numSpaces += 4;
}
if (currentChar == '\t') {
numSpaces += 16;
}
index++;
currentChar = s.charAt(index);
}
return numSpaces;
}
}
|
package com.stryksta.swtorcentral.ui.activities;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;
import com.stryksta.swtorcentral.R;
import com.stryksta.swtorcentral.models.AdvancedClassItem;
import com.stryksta.swtorcentral.util.database.ClassesDatabase;
import java.util.ArrayList;
public class ClassActivity extends AppCompatActivity {
String txtClassName;
int clsFaction;
int txtIcon;
String txtDescription;
String txtResource;
String txtCombatRole;
String txtStory;
String txtAbilities;
String txtEquipment;
String txtApc;
String txtNode;
private ClassesDatabase classDB;
ArrayList<AdvancedClassItem> advClassItems;
private Toolbar mToolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.class_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
if (mToolbar != null) {
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
if (Build.VERSION.SDK_INT >= 21) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimary));
}
Bundle bundle = getIntent().getExtras();
if ( bundle != null ) {
txtClassName = bundle.getString("txtClassName");
clsFaction = bundle.getInt("clsFaction");
txtIcon = bundle.getInt("txtIcon");
txtDescription = bundle.getString("txtDescription");
txtResource = bundle.getString("txtResource");
txtCombatRole = bundle.getString("txtCombatRole");
txtStory = bundle.getString("txtStory");
txtAbilities = bundle.getString("txtAbilities");
txtEquipment = bundle.getString("txtEquipment");
txtApc = bundle.getString("txtApc");
txtNode = bundle.getString("txtNode");
}
getSupportActionBar().setTitle(txtClassName);
TextView txtViewClass = (TextView) findViewById(R.id.txtClass);
txtViewClass.setText(txtClassName);
TextView txtViewDescription = (TextView) findViewById(R.id.txtDescription);
txtViewDescription.setText(txtDescription);
TextView txtViewStory = (TextView) findViewById(R.id.txtStory);
txtViewStory.setText(Html.fromHtml(txtStory));
TextView txtViewFaction = (TextView) findViewById(R.id.txtFaction);
if (clsFaction == 1) {
txtViewFaction.setText("Republic");
} else {
txtViewFaction.setText("Empire");
}
ImageView imgViewIcon = (ImageView) findViewById(R.id.imgClass);
imgViewIcon.setImageResource(txtIcon);
//set advanced classes
classDB = new ClassesDatabase(ClassActivity.this);
advClassItems = classDB.getAdvancedClasses(txtClassName);
String advClass1 = advClassItems.get(0).getAdvClassName();
int advClassIMG1 = advClassItems.get(0).getAdvAdvancedClassIcon();
//Set Advanced Class 1 Text
TextView txtViewAdvanced1 = (TextView) findViewById(R.id.txtAdvancedClass1);
txtViewAdvanced1.setText(advClass1);
//Set Advanced Class 1 Icon
ImageButton imgViewAdvanced1 = (ImageButton) findViewById(R.id.imgAdvancedClass1);
imgViewAdvanced1.setImageResource(advClassIMG1);
imgViewAdvanced1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Bundle bundle = new Bundle();
bundle.putInt("advID", advClassItems.get(0).getAdvancedID());
bundle.putString("advClassName", advClassItems.get(0).getAdvClassName());
bundle.putString("clsName", txtClassName);
bundle.putString("advDescription", advClassItems.get(0).getAdvDescription());
bundle.putString("advRole", advClassItems.get(0).getAdvRole());
bundle.putString("advArmor", advClassItems.get(0).getAdvArmor());
bundle.putString("advWeapons", advClassItems.get(0).advWeapons);
bundle.putString("advPriAttribute", advClassItems.get(0).getAdvPriAttribute());
bundle.putInt("advAdvanced_class_icon", advClassItems.get(0).getAdvAdvancedClassIcon());
bundle.putString("advAPN", advClassItems.get(0).getAdvAPN());
bundle.putString("advAPC", advClassItems.get(0).getAdvAPC());
Intent intent = new Intent(ClassActivity.this, AdvancedClassActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
});
/************ Advanced Class 2 **********/
String advClass2 = advClassItems.get(1).getAdvClassName();
int advClassIMG2 = advClassItems.get(1).getAdvAdvancedClassIcon();
//Set Advanced Class 2 Text
TextView txtViewAdvanced2 = (TextView) findViewById(R.id.txtAdvancedClass2);
txtViewAdvanced2.setText(advClass2);
//Set Advanced Class 2 Icon
ImageButton imgViewAdvanced2 = (ImageButton) findViewById(R.id.imgAdvancedClass2);
imgViewAdvanced2.setImageResource(advClassIMG2);
imgViewAdvanced2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Bundle bundle = new Bundle();
bundle.putInt("advID", advClassItems.get(1).getAdvancedID());
bundle.putString("advClassName", advClassItems.get(1).getAdvClassName());
bundle.putString("advDescription", advClassItems.get(1).getAdvDescription());
bundle.putString("advRole", advClassItems.get(1).getAdvRole());
bundle.putString("advArmor", advClassItems.get(1).getAdvArmor());
bundle.putString("advWeapons", advClassItems.get(1).advWeapons);
bundle.putString("advPriAttribute", advClassItems.get(1).getAdvPriAttribute());
bundle.putInt("advAdvanced_class_icon", advClassItems.get(1).getAdvAdvancedClassIcon());
bundle.putString("advAPN", advClassItems.get(1).getAdvAPN());
bundle.putString("advAPC", advClassItems.get(1).getAdvAPC());
Intent intent = new Intent(ClassActivity.this, AdvancedClassActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
});
FloatingActionMenu fabMenu = (FloatingActionMenu) findViewById(R.id.class_menu_fab);
fabMenu.setIconAnimated(false);
FloatingActionButton fabAbilities = (FloatingActionButton) findViewById(R.id.fabAbilities);
fabAbilities.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle bundle = new Bundle();
bundle.putString("clsApc", txtApc);
bundle.putString("clsName", txtClassName);
bundle.putString("clsAbility", txtAbilities);
Intent intent = new Intent(ClassActivity.this, AbilitiesActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
});
FloatingActionButton fabCompanions = (FloatingActionButton) findViewById(R.id.fabCompanions);
fabCompanions.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle bundle = new Bundle();
bundle.putString("clsApc", txtApc);
bundle.putString("clsName", txtClassName);
bundle.putString("clsAbility", txtAbilities);
bundle.putString("txtNode", txtNode);
Intent intent = new Intent(ClassActivity.this, CompanionsActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
this.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
} |
package com.tencent.mm.plugin.appbrand.appcache.a.d;
import android.util.Pair;
import com.tencent.mm.plugin.appbrand.p.c;
import com.tencent.mm.protocal.c.aql;
import com.tencent.mm.sdk.e.i;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import java.util.List;
public class e extends c<f> {
public static final String[] dzV = new String[]{i.a(f.dzU, "PredownloadIssueLaunchWxaAppResponse")};
public e(com.tencent.mm.sdk.e.e eVar) {
super(eVar, f.dzU, "PredownloadIssueLaunchWxaAppResponse", f.ciG);
}
public final boolean a(byte[] bArr, String str, List<Integer> list, long j, long j2) {
if (bi.bC(bArr) || bi.oW(str)) {
x.i("MicroMsg.AppBrand.Predownload.DuplicateLaunchWxaAppCacheStorage", "setLaunchData, invalid input %s", new Object[]{str});
return false;
} else if (bi.cX(list)) {
x.e("MicroMsg.AppBrand.Predownload.DuplicateLaunchWxaAppCacheStorage", "setLaunchData, appId %s, empty sceneList", new Object[]{str});
return false;
} else {
boolean z = true;
for (Integer intValue : list) {
int intValue2 = intValue.intValue();
f fVar = new f();
fVar.field_appId = str;
fVar.field_scene = intValue2;
boolean b = b(fVar, new String[0]);
fVar.field_launchProtoBlob = bArr;
fVar.field_startTime = j;
fVar.field_endTime = j2;
z = (b ? c(fVar, new String[0]) : b(fVar)) & z;
}
x.i("MicroMsg.AppBrand.Predownload.DuplicateLaunchWxaAppCacheStorage", "setLaunchData, appId %s, sceneList %d, setOk %b", new Object[]{str, Integer.valueOf(list.size()), Boolean.valueOf(z)});
return z;
}
}
public final Pair<aql, Long> am(String str, int i) {
try {
long VE = bi.VE();
f fVar = new f();
fVar.field_appId = str;
fVar.field_scene = i;
if (b(fVar, new String[0])) {
x.i("MicroMsg.AppBrand.Predownload.DuplicateLaunchWxaAppCacheStorage", "found info with appId(%s) scene(%d), [%d, %d]", new Object[]{str, Integer.valueOf(i), Long.valueOf(fVar.field_startTime), Long.valueOf(fVar.field_endTime)});
if (fVar.field_startTime <= VE && VE <= fVar.field_endTime) {
aql aql = new aql();
aql.aG(fVar.field_launchProtoBlob);
if (aql.rSV.rsl.lR.length > 0) {
return Pair.create(aql, Long.valueOf(fVar.field_reportId));
}
x.e("MicroMsg.AppBrand.Predownload.DuplicateLaunchWxaAppCacheStorage", "found into with appId(%s) scene(%d), but jsapi_control_bytes invalid", new Object[]{str, Integer.valueOf(i)});
}
}
return Pair.create(null, Long.valueOf(-1));
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.AppBrand.Predownload.DuplicateLaunchWxaAppCacheStorage", e, "get with appId(%s) scene(%d)", new Object[]{str, Integer.valueOf(i)});
return Pair.create(null, Long.valueOf(-1));
}
}
public static void act() {
}
}
|
package com.lizogub.HomeWork4;
public class Codingbat {
/**
* Given 2 int values, return true if they are both
* in the range 30..40 inclusive, or they are both
* in the range 40..50 inclusive.
*/
public boolean in3050(int a, int b) {
int minRange1 = 30;
int maxRange1 = 40;
int minRange2 = 40;
int maxRange2 = 50;
if((a <= maxRange1) && (b <= maxRange1)){
if((a >= minRange1) && (b >= minRange1)){
return true;
}
}
if((a <= maxRange2) && (b <= maxRange2)){
if((a >= minRange2) && (b >= minRange2)){
return true;
}
}
return false;
}
/**
* You have a green lottery ticket, with ints a, b, and c on it.
* If the numbers are all different from each other, the result is 0.
* If all of the numbers are the same, the result is 20.
* If two of the numbers are the same, the result is 10.
* */
public int greenTicket(int a, int b, int c) {
if((a == b) || (b == c) || (a == c)){
if((a == b) && (b == c)){
return 20;
}
return 10;
}
return 0;
}
/**
* Given a day of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat,
* and a boolean indicating if we are on vacation,
* return a string of the form "7:00" indicating when the alarm clock should ring.
* Weekdays, the alarm should be "7:00" and on the weekend it should be "10:00".
* Unless we are on vacation -- then on weekdays it should be "10:00" and weekends it should be "off".
* */
public String alarmClock(int day, boolean vacation) {
String alarm = "";
switch(day){
case 0: alarm = setAlarm(false,vacation);
break;
case 1:
case 2:
case 3:
case 4:
case 5: alarm = setAlarm(true,vacation);
break;
case 6: alarm = setAlarm(false,vacation);
}
return alarm;
}
protected String setAlarm(boolean isWeekday, boolean vacation){
if(isWeekday){
if(vacation){
return "10:00";
}
return "7:00";
} else {
if(vacation){
return "off";
}
return "10:00";
}
}
}
|
package edu.kalum.notas.core.controllers;
import edu.kalum.notas.core.models.dao.services.IAlumnoService;
import edu.kalum.notas.core.models.entities.Alumno;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping(value = "/kalum-notas/v1")
public class AlumnoController {
private Logger logger = LoggerFactory.getLogger(AlumnoController.class);
@Autowired
private IAlumnoService alumnoService;
@GetMapping("/alumnos")
public ResponseEntity<?> listarAlumnos(){
Map<String,Object> response = new HashMap<>();
logger.debug("Iniciando el proceso de la consulta de los alumnos en la base de datos");
try{
logger.debug("Iniciando la consulta a la base de datos");
List<Alumno> listaAlumnos = alumnoService.findAll();
if(listaAlumnos == null || listaAlumnos.size() == 0){
logger.warn("No existen registros en la tabla alumnos");
response.put("Mensaje","No existen registros en la tabla alumnos");
return new ResponseEntity<Map<String,Object>>(response,HttpStatus.NO_CONTENT);
}else{
logger.info("Obteniendo listado de la información de alumnos");
return new ResponseEntity<List<Alumno>>(listaAlumnos,HttpStatus.OK);
}
}catch (CannotCreateTransactionException e){
logger.error("Error al momento de conectarse a la base de datos");
response.put("Mensaje","Error al momento de conectarse a la base de datos");
response.put("Error",e.getMessage().concat(": ").concat(e.getMostSpecificCause().getMessage()));
return new ResponseEntity<Map<String,Object>>(response, HttpStatus.SERVICE_UNAVAILABLE);
}catch (DataAccessException e){
logger.error("Error al momento de consultar la información a la base de datos");
response.put("Mensaje","Error al momento de consultar la información a la base de datos");
response.put("Error",e.getMessage().concat(": ").concat(e.getMostSpecificCause().getMessage()));
return new ResponseEntity<Map<String,Object>>(response,HttpStatus.SERVICE_UNAVAILABLE);
}
}
@GetMapping("/alumnos/{carne}")
public ResponseEntity<?> showAlumno(@PathVariable String carne){
Map<String,Object> response = new HashMap<>();
logger.debug("Iniciando el proceso de la consulta de los alumnos en la base de datos");
try{
logger.debug("iniciando la consulta de alumno por número de carné ".concat(carne));
Alumno alumno = alumnoService.findByCarne(carne);
if(alumno == null){
logger.warn("No existe registro en tabla alumno con el carné ".concat(carne));
response.put("Mensaje","No existe registro en tabla alumno con el carné ".concat(carne));
return new ResponseEntity<Map<String,Object>>(response,HttpStatus.NOT_FOUND);
}else{
logger.info("Obteniendo la información del alumno con el carné ".concat(carne));
return new ResponseEntity<Alumno>(alumno,HttpStatus.OK);
}
}catch (CannotCreateTransactionException e){
logger.error("Error al momento de conectarse a la base de datos");
response.put("Mensaje","Error al momento de conectarse a la base de datos");
response.put("Error",e.getMessage().concat(": ").concat(e.getMostSpecificCause().getMessage()));
return new ResponseEntity<Map<String,Object>>(response, HttpStatus.SERVICE_UNAVAILABLE);
}catch (DataAccessException e){
logger.error("Error al momento de consultar la información a la base de datos");
response.put("Mensaje","Error al momento de consultar la información a la base de datos");
response.put("Error",e.getMessage().concat(": ").concat(e.getMostSpecificCause().getMessage()));
return new ResponseEntity<Map<String,Object>>(response,HttpStatus.SERVICE_UNAVAILABLE);
}
}
}
|
package api.longpoll.bots.methods.impl.stories;
import api.longpoll.bots.adapters.deserializers.StoriesGetViewersResultDeserializer;
import api.longpoll.bots.http.params.BoolInt;
import api.longpoll.bots.methods.AuthorizedVkApiMethod;
import api.longpoll.bots.methods.VkApiProperties;
import api.longpoll.bots.model.objects.additional.VkList;
import api.longpoll.bots.model.response.GenericResponse;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import java.util.Arrays;
import java.util.List;
/**
* Implements <b>messages.getById</b> method.
* <p>
* Returns messages by their IDs.
*
* @see <a href="https://vk.com/dev/messages.getById">https://vk.com/dev/messages.getById</a>
*/
public class GetViewers extends AuthorizedVkApiMethod<GetViewers.Response> {
public GetViewers(String accessToken) {
super(accessToken);
}
@Override
protected String getUrl() {
return VkApiProperties.get("stories.getViewers");
}
@Override
protected Class<Response> getResponseType() {
return Response.class;
}
public GetViewers setMessageIds(Integer... messageIds) {
return setMessageIds(Arrays.asList(messageIds));
}
public GetViewers setMessageIds(List<Integer> messageIds) {
return addParam("message_ids", messageIds);
}
public GetViewers setPreviewLength(int previewLength) {
return addParam("preview_length", previewLength);
}
public GetViewers setExtended(boolean extended) {
return addParam("extended", new BoolInt(extended));
}
public GetViewers setFields(String... fields) {
return setFields(Arrays.asList(fields));
}
public GetViewers setFields(List<String> fields) {
return addParam("fields", fields);
}
public GetViewers setGroupId(int groupId) {
return addParam("group_id", groupId);
}
@Override
public GetViewers addParam(String key, Object value) {
return (GetViewers) super.addParam(key, value);
}
/**
* Response to <b>stories.getViewers</b>.
*/
@JsonAdapter(StoriesGetViewersResultDeserializer.class)
public static class Response extends GenericResponse<VkList<Object>> {
/**
* Response item.
*/
public static class ResponseObject {
/**
* Whether the story is liked.
*/
@SerializedName("is_liked")
private Boolean isLiked;
/**
* User ID.
*/
@SerializedName("user_id")
private Integer userId;
public Boolean getLiked() {
return isLiked;
}
public void setLiked(Boolean liked) {
isLiked = liked;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
@Override
public String toString() {
return "ResponseObject{" +
"isLiked=" + isLiked +
", userId=" + userId +
'}';
}
}
}
}
|
package com.pajk.examples.kafka;
import kafka.consumer.ConsumerIterator;
import kafka.consumer.KafkaStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by liqingdong911 on 2015/8/10.
*/
public class ConsumerMsgTask implements Runnable {
private static final Logger logger = LoggerFactory.getLogger(ConsumerMsgTask.class);
private KafkaStream m_stream;
private int m_threadNumber;
public ConsumerMsgTask(KafkaStream stream, int threadNumber) {
m_threadNumber = threadNumber;
m_stream = stream;
}
public void run() {
ConsumerIterator<byte[], byte[]> it = m_stream.iterator();
while (it.hasNext()) {
logger.info("Thread " + m_threadNumber + ": "
+ new String(it.next().message()));
}
logger.info("Shutting down Thread: " + m_threadNumber);
}
}
|
/*
* Eduardo Cortes - t11m013
* Ignacio Amaya - t11m021
* GRUPO MI
*/
import es.upm.babel.cclib.Monitor;
import es.upm.babel.cclib.Monitor.Cond;
public class GestorDeEventosMonitor implements GestorDeEventos{
//Vamos a crear las variables que usaremos para controlar que se cumpla la especificacion formal que nos daban.
//Matriz de enteros que relaciona los eventos con los observadores que estan subscritos a estos
//(un 0 si no esta subscrito y un 1 si esta subscrito)
int [][] subscritos;
//Matriz de enteros que relaciona los observadores con los eventos que tienen que escuchar
//(un 1 si lo tiene que escuchar y un 0 si no)
int [][] porEscuchar;
//Monitor con el que trabajeremos y nos asegurara exclusion mutua
Monitor mutex = new Monitor();
//Array de conditions que nos permitira cumplir la CPRE asegurando que el metodo escuchar solo se realice
//cuando un observador tenga al menos un evento por escuchar. El tamano del array sera el mismo que el
//de el numero de observadores.
Monitor.Cond[] condiciones;
//Constructor de la clase. Inicializamos la matriz de enteros a cero y asociamos la de condiciones a nuestro monitor.
public GestorDeEventosMonitor(){
this.subscritos = new int [N_EVENTOS][N_OBSERVADORES];
this.porEscuchar = new int [N_EVENTOS][N_OBSERVADORES];
this.condiciones = new Monitor.Cond [N_OBSERVADORES];
for(int i = 0; i < N_EVENTOS; i++){
for(int j = 0; j < N_OBSERVADORES; j++){
this.subscritos[i][j] = 0;
this.porEscuchar[i][j] = 0;
}
}
for(int i = 0; i < N_OBSERVADORES; i++){
this.condiciones[i] = mutex.newCond();
}
}
//Busca en la matriz porEscuchar en la columna con identificador pid si existe por lo menos un uno.
public boolean tieneUno(int pid){
boolean terminado = false;
for(int j = 0; !terminado && j < N_EVENTOS; j++){
if(this.porEscuchar[j][pid] == 1){
terminado = true;
}
}
return terminado;
}
//Metodo que escribe un uno en los eventos de la matriz porEscuchar en los que hay alguien subscrito(y no esten ya
//por escuchar).
//Para ello buscamos previamente cuales estan subscritos en la matriz subscritos. Ademas hacemos un signal en nuestro
//array de conditions siempre y cuando no haya ningun 1 en esa columna de porEscuchar, ya que el unico
//caso en el que se hace el await en escuchar es cuando un observador no tiene ningun evento por escuchar.
@Override
public void emitir(int eid) {
mutex.enter();
for(int i = 0; i < N_OBSERVADORES; i++){
if(this.subscritos[eid][i] == 1 && this.porEscuchar[eid][i] == 0){
if(!this.tieneUno(i)){
this.condiciones[i].signal();
}
this.porEscuchar[eid][i] = 1;
}
}
mutex.leave();
}
//Actualiza la matriz de subcritos en la posicion acorde a los parametros de entrada con un 1, lo que significa que
//la persona con identificador pid esta subscrita al evento de identificador eid
@Override
public void subscribir(int pid, int eid) {
mutex.enter();
this.subscritos[eid][pid] = 1;
mutex.leave();
}
//Actualiza las matrices porEscuchar y subscitos con un cero en la posicion que nos indican.
@Override
public void desubscribir(int pid, int eid) {
mutex.enter();
this.subscritos[eid][pid] = 0;
if(this.porEscuchar[eid][pid] != 0){
this.porEscuchar[eid][pid] = 0;
}
mutex.leave();
}
//Si la id del observador que nos dan no tiene asociado ningun evento, su condition asociado hace un await para
//esperar a que se cumpla la CPRE. Despues escucha uno y pone un cero en esa posicion de porEscuchar.
@Override
public int escuchar(int pid) {
mutex.enter();
if(!this.tieneUno(pid)){
this.condiciones[pid].await();
}
int eid = 0;
for(int i = 0; this.porEscuchar[i][pid] == 0; i++){
eid = i + 1;
}
this.porEscuchar[eid][pid] = 0;
mutex.leave();
return eid;
}
}
|
/*
* 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.tarkesh.job_role;
import com.tarkesh.entity.JobRole;
import com.tarkesh.operation.Operations;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Abhishek.Sehgal
*/
@WebServlet(name = "AddJobRole", urlPatterns = {"/AddJobRole"})
public class AddJobRole extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("Adding Job Role");
String type = request.getParameter("type");
Boolean booltype;
if (type == null) {
booltype = Boolean.FALSE;
} else {
booltype = Boolean.TRUE;
}
System.out.println("Type " + type);
String ssc = request.getParameter("ssc");
String jobrole = request.getParameter("jobrole");
String qp_code = request.getParameter("qp_code");
String industry_type = request.getParameter("industry_type");
String training_type = request.getParameter("training_type");
Integer industry_visit = Integer.parseInt(request.getParameter("industry_visit"));
Integer nsqf = Integer.parseInt(request.getParameter("nsqf"));
Integer theory = Integer.parseInt(request.getParameter("theory"));
Integer practical = Integer.parseInt(request.getParameter("practical"));
Integer add_duration = Integer.parseInt(request.getParameter("add_duration"));
Integer digital = Integer.parseInt(request.getParameter("digital"));
Integer total_hours = Integer.parseInt(request.getParameter("total_hours"));
JobRole jobRole = new JobRole();
jobRole.setPaid(booltype);
jobRole.setSsc(ssc);
jobRole.setName(jobrole);
jobRole.setQp_code(qp_code);
jobRole.setIndustry_type(industry_type);
jobRole.setTraining_type(training_type);
jobRole.setIndustry_visit(industry_visit);
jobRole.setNsqf_level(nsqf);
jobRole.setTheory(theory);
jobRole.setPractical(practical);
jobRole.setAditional_duration(add_duration);
jobRole.setDegital_literacy(digital);
jobRole.setTotal_hours(total_hours);
Operations.addJobRole(jobRole);
response.sendRedirect("addJobRole.jsp");
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet AddJobRole</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet AddJobRole at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
package com.thoughtworks.data.product;
/**
* Created on 15-06-2018.
*/
class ProductDetailEntity {
}
|
import java.net.URI;
import java.net.URISyntaxException;
import microsoft.exchange.webservices.data.*;
/**
* <pre>
* <B>Copyright:</B> Izik Golan
* <B>Owner:</B> <a href="mailto:golan2@hotmail.com">Izik Golan</a>
* <B>Creation:</B> 15/08/14 11:09
* <B>Since:</B> BSM 9.21
* <B>Description:</B>
*
* Download WSDL:
* https://sync.austin.hp.com/ews/Services.wsdl
* https://sync.austin.hp.com/ews/Exchange.asmx
* https://casarray1.austin.hp.com/EWS/Exchange.asmx
*
* </pre>
*/
public class Connect2Exchange {
public static void main(String[] args) {
}
public static void testMethod() {
ExchangeService service = new ExchangeService(
ExchangeVersion.Exchange2007_SP1);
ExchangeCredentials credentials = new WebCredentials("username",
"password");
service.setCredentials(credentials);
try {
service.setUrl(new URI("https://domain/EWS/Exchange.asmx"));
} catch (URISyntaxException e) {
e.printStackTrace();
}
EmailMessage msg;
try {
msg = new EmailMessage(service);
msg.setSubject("hello world");
msg.setBody(MessageBody
.getMessageBodyFromText("Sent using the EWS API"));
msg.getToRecipients().add("test@test.com");
msg.send();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package unalcol.types.collection;
/**
* @author jgomez
*/
public interface KeyMap<K, T> {
public T get(K key, Collection<T> collection);
public K key(T obj, Collection<T> collection);
}
|
package com.tencent.mm.plugin.messenger.foundation.a;
import com.tencent.mm.protocal.c.aue;
import com.tencent.mm.storage.ab;
public interface c {
void a(ab abVar, ab abVar2, aue aue, byte[] bArr, boolean z);
void b(ab abVar, ab abVar2, aue aue, byte[] bArr, boolean z);
}
|
/*
* 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 Vista;
import Controlador.GestionSupermercado;
import Controlador.Principal;
import Modelo.Reposicion;
import Modelo.Supermercado;
import Modelo.Venta;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
/**
*
* @author Jorge Herrera - Sergio Ruiz
*/
public class Acciones extends javax.swing.JDialog {
GestionSupermercado con = new GestionSupermercado();
ArrayList<Venta> lisVenta = new ArrayList(); //ArrayList de la tabla Venta
ArrayList<Reposicion> lisRepo = new ArrayList(); //ArrayList de la tabla Venta
DefaultTableModel modelo, modelo1; //Declaracion de los modelos
private int directorActual;
public Acciones(java.awt.Frame parent, boolean modal, int codDir) throws SQLException {
super(parent, modal);
initComponents();
modelo = (DefaultTableModel) jTable1.getModel(); //modelo para el JTable1
modelo1 = (DefaultTableModel) jTable2.getModel(); //modelo para el JTable1
rellenarTablaVenta(codDir); //Metodo para rellenar tabla Venta
rellenarTablaRepo(codDir); //Metodo para rellenar tabla Reposicion
directorActual = codDir;
jLabel1.setText("Actividades del Director de codigo "+codDir);
}
//Metodo para rellenar tabla Venta
private void rellenarTablaVenta(int codigo) throws SQLException
{
lisVenta = con.crearListaVenta(codigo); //Llamamos al metodo de la clase Gestion Supermercado que nos devuelve una lista
Object vector[]; //Creamos un vector de tipo objeto
int i=0;
while (i<lisVenta.size()) //Mientras no se llegue al final
{
vector = obtenerDatos(lisVenta.get(i)); //El vector se rellena
modelo.addRow(vector); //Se añade al modelo
i++; //Se suma al contador
}
jTable1.setModel(modelo); //El modelo se le aplica al JTable
}
//Metodo para rellenar tabla Reposicion (Explicacion en el metodo anterior)
private void rellenarTablaRepo(int codigo) throws SQLException
{
lisRepo = con.crearListaRepo(codigo);
Object vector[];
int i=0;
while (i<lisRepo.size())
{
vector = obtenerDatos(lisRepo.get(i));
modelo1.addRow(vector);
i++;
}
jTable2.setModel(modelo1);
}
private Object[] obtenerDatos(Supermercado objeto) //Objeto de tipo Supermercado
{
Object vector[] = new Object[2]; //Creamos un vector del mismo numero de campos que la tabla
vector[0] = objeto.getCod_sup(); //La primera celda es el codigo de Supermercado
if (objeto instanceof Venta) //Se hace un casting
vector[1] = ( (Venta) objeto).getGanancias(); //Se guardara las ganancias
else
vector[1] = ( (Reposicion) objeto).getInversion(); // O las inversiones
return vector;
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
botonAtras = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
jTable2 = new javax.swing.JTable();
añadirActividad = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Codigo Venta", "Ganancias"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(jTable1);
botonAtras.setText("ATRAS");
botonAtras.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonAtrasActionPerformed(evt);
}
});
jTable2.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Codigo Reposicion", "Inversion"
}
));
jScrollPane2.setViewportView(jTable2);
añadirActividad.setText("Añadir");
añadirActividad.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
añadirActividadActionPerformed(evt);
}
});
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("jLabel1");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(botonAtras)
.addGap(38, 38, 38))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(añadirActividad)
.addGap(130, 130, 130))))
.addGroup(layout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 371, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(29, 227, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 368, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(17, 17, 17)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(8, 8, 8)
.addComponent(añadirActividad)
.addGap(15, 15, 15)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(3, 3, 3)
.addComponent(botonAtras)
.addContainerGap(57, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
//El boton atras hace que se cierre al ventana
private void botonAtrasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonAtrasActionPerformed
dispose();
}//GEN-LAST:event_botonAtrasActionPerformed
//Si el usuario pulsa en el boton de añadir una nueva actividad, se crea un JDialog
private void añadirActividadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_añadirActividadActionPerformed
NuevaActividad p1 = new NuevaActividad(Principal.devolverVentana(), true, directorActual); // Se le pasa el codigo de Director
p1.setTitle("Inserción de actividad");
p1.setVisible(true);
modelo.setRowCount(0); //Se resetean los modelos
modelo1.setRowCount(0); //Se resetena los modelos
try {
rellenarTablaVenta(directorActual); //Se rellena la tabla venta con el director que se le pasa como parametro
} catch (SQLException ex) {
Logger.getLogger(Acciones.class.getName()).log(Level.SEVERE, null, ex);
}
try {
rellenarTablaRepo(directorActual);//Se rellena la tabla venta con el director que se le pasa como parametro
} catch (SQLException ex) {
Logger.getLogger(Acciones.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_añadirActividadActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton añadirActividad;
private javax.swing.JButton botonAtras;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable jTable1;
private javax.swing.JTable jTable2;
// End of variables declaration//GEN-END:variables
}
|
import javax.swing.*;
import java.awt.event.ActionListener;
public interface MainForm {
JPanel getContent();
JButton getButton();
JTextField [] getTextFields();
void setTextField(String[] names);
void setListener(ActionListener listener);
}
|
package com.vishant.sandwichtechnologies;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface DogRepository extends MongoRepository<Dog, String> {
public Dog findByDogName(String dogName);
public List<Dog> findByDogBreed(String dogBreed);
}
|
/*
* Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.management.request;
import com.eclipsesource.json.JsonArray;
import com.eclipsesource.json.JsonObject;
import com.eclipsesource.json.JsonValue;
import com.hazelcast.instance.Node;
import com.hazelcast.logging.SystemLogRecord;
import com.hazelcast.logging.SystemLogService;
import com.hazelcast.management.ManagementCenterService;
import com.hazelcast.nio.Address;
import com.hazelcast.util.JsonUtil;
import java.util.LinkedList;
import java.util.List;
/**
* Request for fetching system log records.
*/
public class GetLogsRequest implements ConsoleRequest {
public GetLogsRequest() {
}
@Override
public int getType() {
return ConsoleRequestConstants.REQUEST_TYPE_LOGS;
}
@Override
public Object readResponse(JsonObject json) {
List<SystemLogRecord> list = new LinkedList<SystemLogRecord>();
String node = JsonUtil.getString(json, "node", "");
final JsonArray logs = JsonUtil.getArray(json, "logs", new JsonArray());
for (JsonValue log : logs) {
SystemLogRecord systemLogRecord = new SystemLogRecord();
systemLogRecord.fromJson(log.asObject());
systemLogRecord.setNode(node);
list.add(systemLogRecord);
}
return list;
}
@Override
public void writeResponse(ManagementCenterService mcs, JsonObject root) throws Exception {
final JsonObject result = new JsonObject();
Node node = mcs.getHazelcastInstance().node;
SystemLogService systemLogService = node.getSystemLogService();
List<SystemLogRecord> logBundle = systemLogService.getLogBundle();
Address address = node.getThisAddress();
result.add("node", address.getHost() + ":" + address.getPort());
JsonArray logs = new JsonArray();
for (SystemLogRecord systemLogRecord : logBundle) {
logs.add(systemLogRecord.toJson());
}
result.add("logs", logs);
root.add("result", result);
}
@Override
public JsonObject toJson() {
return new JsonObject();
}
@Override
public void fromJson(JsonObject json) {
}
}
|
package zystudio.demo.multigate2;
public class RequestGenerator {
}
|
package com.rofour.baseball.dao.user.bean;
import java.io.Serializable;
import java.util.Date;
/**
* @ClassName: FeedBackBean
* @Description: 反馈信息实体类
* @author sdd
* @date 2016年3月27日 下午6:39:09
*
*/
public class FeedBackBean implements Serializable{
private static final long serialVersionUID = -2550432487132921383L;
/**
* 用户反馈信息编号(主键)
*/
private Long feedbackId;
/**
* 用户id
*/
private Long userId;
/**
* 用户姓名
*/
private String name;
/**
* 用户联系方式
*/
private String phone;
/**
* 反馈信息内容
*/
private String content;
/**
* 本地IP地址
*/
private String ip;
/**
* 反馈信息提交时间
*/
private Date submittedTime;
public FeedBackBean(Long feedbackId, Long userId, String name, String phone, String content, String ip, Date submittedTime) {
this.feedbackId = feedbackId;
this.userId = userId;
this.name = name;
this.phone = phone;
this.content = content;
this.ip = ip;
this.submittedTime = submittedTime;
}
public FeedBackBean() {
super();
}
public Long getFeedbackId() {
return feedbackId;
}
public void setFeedbackId(Long feedbackId) {
this.feedbackId = feedbackId;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone == null ? null : phone.trim();
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content == null ? null : content.trim();
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip == null ? null : ip.trim();
}
public Date getSubmittedTime() {
return submittedTime;
}
public void setSubmittedTime(Date submittedTime) {
this.submittedTime = submittedTime;
}
} |
package com.tencent.mm.plugin.traceroute.ui;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.tencent.mm.R;
import com.tencent.mm.a.e;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.ui.MMActivity;
import java.io.File;
public class NetworkDiagnoseReportUI extends MMActivity {
private static String oDd;
private boolean oDR = false;
private Button oDS;
private Button oDT;
private ImageView oDU;
private TextView oDV;
private TextView oDW;
private TextView oDX;
static /* synthetic */ String a(NetworkDiagnoseReportUI networkDiagnoseReportUI) {
String string = networkDiagnoseReportUI.getString(R.l.report_mail_subject);
File file = new File(oDd);
if (!file.exists()) {
return string;
}
String name = file.getName();
if (bi.oW(name)) {
return string;
}
int indexOf = name.indexOf(".");
StringBuilder append = new StringBuilder().append(string).append("_");
if (indexOf <= 0) {
indexOf = name.length();
}
return append.append(name.substring(0, indexOf)).toString();
}
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
initView();
}
protected final void initView() {
setMMTitle("");
this.oDU = (ImageView) findViewById(R.h.report_result_iv);
this.oDV = (TextView) findViewById(R.h.report_result_tv);
this.oDW = (TextView) findViewById(R.h.report_result_tip_tv);
this.oDR = getIntent().getBooleanExtra("diagnose_result", false);
if (this.oDR) {
this.oDU.setImageResource(R.g.net_connectreport_success);
this.oDV.setText(getString(R.l.upload_report_success));
this.oDW.setVisibility(0);
addTextOptionMenu(0, getString(R.l.diagnose_finish), new 1(this));
return;
}
setBackBtn(new 2(this));
oDd = getIntent().getStringExtra("diagnose_log_file_path");
this.oDU.setImageResource(R.g.net_connectreport_fail);
this.oDV.setText(getString(R.l.upload_report_failed));
if (oDd != null && e.cm(oDd) > 0) {
this.oDX = (TextView) findViewById(R.h.report_result_on_sdcard);
this.oDX.setText(getString(R.l.report_on_sdcard, new Object[]{oDd.replace("mnt/", "")}));
findViewById(R.h.report_result_on_sdcard).setVisibility(0);
findViewById(R.h.send_mail_tip).setVisibility(0);
this.oDS = (Button) findViewById(R.h.send_report_by_email);
this.oDS.setVisibility(0);
this.oDS.setOnClickListener(new 3(this));
this.oDT = (Button) findViewById(R.h.view_log);
this.oDT.setVisibility(0);
this.oDT.setOnClickListener(new 4(this));
}
}
protected final int getLayoutId() {
return R.i.network_diagnose_report;
}
}
|
package androidjsoupparser.inducesmile.com.url_links;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.AsyncTask;
import android.util.Log;
import java.lang.*;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
import java.util.*;
import java.util.HashSet;
import java.util.List;
import static androidjsoupparser.inducesmile.com.url_links.Load_Urlevents.loadevent;
import static java.lang.System.*;
import androidjsoupparser.inducesmile.com.url_links.Load_Urlevents;
public class MainActivity extends AppCompatActivity {
ListView listViewEvents;
List<EventUrl>eventlist;
// public static int i = 1;
// public static int offset = 0;
public static ArrayList<String> urls;
// public static Document doc, doc1;
// public static ArrayList<String> arr_linkText;
// public static ArrayList<String> arr_titleText;
// public static ArrayList<String> arr_dayText;
// public static ArrayList<String> arr_timestartText;
// public static ArrayList<String> arr_timeendText;
// public static ArrayList<String> arr_summaryText ;
// public static ArrayList<String> arr_location ;
public DatabaseReference rootRef, demoRef;
public static ArrayList<EventUrl> listOfEvents;
// public String Url = "https://news.dartmouth.edu/events";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rootRef = FirebaseDatabase.getInstance().getReference("Events");
loadevent();
listOfEvents = new ArrayList<>();
// urls = new ArrayList<>();
// arr_linkText = new ArrayList<>();
// arr_titleText = new ArrayList<>();
// arr_dayText = new ArrayList<>();
// arr_timestartText = new ArrayList<>();
// arr_timeendText = new ArrayList<>();
// arr_summaryText = new ArrayList<>();
// arr_location = new ArrayList<>();
setContentView(R.layout.activity_main);
// //loads first 6 pages
// while(offset<51)
// {
// Url = "https://news.dartmouth.edu/events?"+"offset="+Integer.toString(offset)+"&audience_ids=3";
// Log.d("show",Url);
// urls.add(Url);
// offset +=10;
// }
// JsoupAsyncTask jsoupAsyncTask = new JsoupAsyncTask();
// jsoupAsyncTask.execute();
listViewEvents = (ListView) findViewById(R.id.listViewEvents);
}
@Override
protected void onStart() {
super.onStart();
rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// eventlist = new ArrayList<>();
for(DataSnapshot eventSnapshot: dataSnapshot.getChildren())
{
Map<String,Object> singleRun = (Map<String, Object>) eventSnapshot.getValue();
// eventlist.clear();
// Log.d("Data.....", String.valueOf(singleRun.size()));
// Log.d("KeySet.....", singleRun.keySet().toString());
// Log.d("Errorrr.....", singleRun.values().toString());
EventUrl eventurl = new EventUrl();
// Log.d("Errorrr.....", String.valueOf(singleRun.get("Description")));
eventurl.setDescription(singleRun.get("Description").toString());
eventurl.setStart(singleRun.get("Start").toString());
eventurl.setTitle(singleRun.get("Title").toString());
eventurl.setEnd(singleRun.get("End").toString());
eventurl.setDate(singleRun.get("Date").toString());
eventurl.setUrl(singleRun.get("Url").toString());
eventurl.setLocation(singleRun.get("Location").toString());
listOfEvents.add(eventurl);
// EventUrl event1 = eventSnapshot.getValue(EventUrl.class);
// eventlist.add(event1);
// listOfEvents.add(singleRun.get("Description"));
}
// Event_list adapter = new Event_list(MainActivity.this, eventlist);
// listViewEvents.setAdapter(adapter);
Log.d("Data.....", String.valueOf(listOfEvents.size()));
Log.d("Data.....First Value", String.valueOf(listOfEvents.get(0)));
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
//parse and store url in Firebase
// private class JsoupAsyncTask extends AsyncTask<Void, Void, ArrayList<String>> {
// ArrayList<String> arr_final = new ArrayList<>();
// @Override
// protected ArrayList<String> doInBackground(Void... params) {
// String linkText = "";
// try {
// for(String temp: urls) {
// doc = Jsoup.connect(temp).get();
// Elements title = doc.select("h2.title");
// Elements day = doc.select("h3.event-day");
// Elements time = doc.select("h3.event-time");
// Elements summary = doc.select("p.summary");
// Elements hre = doc.select("h2.title,abs.href");
// //parse url text
// for (Element link : hre) {
// linkText = link.html();
// String s1 = linkText.substring(linkText.indexOf('/', 0), linkText.indexOf('>', 0) - 1);
//
// String s2 = "https://news.dartmouth.edu" + s1;
//
//
// arr_linkText.add(s2);
// }
//// parse location from each href
// for (int j = 0; j < arr_linkText.size(); j++) {
// String newlink = arr_linkText.get(j);
// doc1 = Jsoup.connect(newlink).get();
// Elements location = doc1.getElementsByAttributeValue("class", "location");
// for (Element a : location) {
// String lo = a.text();
// arr_location.add(lo);
// break;
// }
//
// }
//
// //parse event title
// for (Element link : title) {
// linkText = link.text();
//
// arr_titleText.add(linkText);
// }
// for (Element link : day) {
// linkText = link.html();
// arr_dayText.add(linkText);
// }
// //parse start-time
// for (Element link : time) {
// linkText = link.text();
// if (linkText.contains("All")) {
// arr_timestartText.add(linkText);
// } else {
// String s1 = linkText.substring(linkText.indexOf(':') - 1, linkText.indexOf('-', 0));
// arr_timestartText.add(s1);
// }
//
// }
// //parse end-time
// for (Element link : time) {
// linkText = link.text();
// if (linkText.contains("All")) {
// arr_timeendText.add("");
// } else {
// String s1 = linkText.substring(linkText.indexOf('-', 0) + 1, linkText.lastIndexOf('m') + 1);
// arr_timeendText.add(s1);
// }
// }
// //parse summary
// for (Element link : summary) {
// linkText = link.text();
// arr_summaryText.add(linkText);
// }
//
// for (int j = 0; j < arr_summaryText.size(); j++) {
//
// String url1 = arr_linkText.get(j);
// String title1 = arr_titleText.get(j);
// String start1 = arr_timestartText.get(j);
// String end1 = arr_timeendText.get(j);
// String day1 = arr_dayText.get(j);
// String summary1 = arr_summaryText.get(j);
// String loc1 = arr_location.get(j);
//
// String addn = url1 + "::" + title1 + "::" + start1 + "::" + end1 + "::" + day1 + "::" + summary1 + "::" + loc1;
//
// if (!arr_final.contains(addn))
// arr_final.add(addn);
// Log.d("String returning value", addn);
// }
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
//
//
// return arr_final;
//
// }
//
// @Override
// protected void onPostExecute(ArrayList<String> result) {
// // DatabaseReference rootRef, demoRef;
//
// for (String temp_result : result) {
//
// String str = temp_result;
// List<String> finalList = Arrays.asList(str.split("::"));
//
// rootRef = FirebaseDatabase.getInstance().getReference();
// String x = Integer.toString(i);
// demoRef = rootRef.child("Events").child(x).child("Url");
// demoRef.push().setValue(finalList.get(0));
// demoRef = rootRef.child("Events").child(x).child("Title");
// demoRef.push().setValue(finalList.get(1));
// demoRef = rootRef.child("Events").child(x).child("Start");
// demoRef.push().setValue(finalList.get(2));
// demoRef = rootRef.child("Events").child(x).child("End");
// demoRef.push().setValue(finalList.get(3));
// demoRef = rootRef.child("Events").child(x).child("Date");
// demoRef.push().setValue(finalList.get(4));
// demoRef = rootRef.child("Events").child(x).child("Description");
// demoRef.push().setValue(finalList.get(5));
// demoRef = rootRef.child("Events").child(x).child("Location");
// demoRef.push().setValue(finalList.get(6));
//
// i = i + 1;
//
//
// }
// }
// }
}
|
package cityUnknown;
public class Store {
}
|
public class Test{
public static void main(String[] args){
//allocate array memory
Employee employee=new Employee();
employee.name="Falcao";
employee.hours=40;
employee.rate=15.50;
employee.address=new Address[5];
//initialize first element
employee.address[0]=new Address("Queen", 48, "K1P1N2");
employee.address[1]=new Address("King Edward", 800, "K1N6N5");
//print check
System.out.println(employee.getName());
System.out.println(employee.getHours());
System.out.println(employee.getRate());
//address0
System.out.println(employee.address[0].getStreet());
System.out.println(employee.address[0].getNumber());
System.out.println(employee.address[0].getPostal());
//address1
System.out.println(employee.address[1].getStreet());
System.out.println(employee.address[1].getNumber());
System.out.println(employee.address[1].getPostal());
}
} |
package com.bts.essentials.authentication;
import com.bts.essentials.BaseIntegrationTest;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static org.mockito.Mockito.*;
/**
* Created by wagan8r on 8/19/18.
*/
public class JwtAuthenticationEntryPointTest extends BaseIntegrationTest {
@Autowired
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
@Test
public void commence() throws Exception {
HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
HttpServletResponse httpServletResponse = mock(HttpServletResponse.class);
AuthenticationException authenticationException = mock(AuthenticationException.class);
jwtAuthenticationEntryPoint.commence(httpServletRequest, httpServletResponse, authenticationException);
verify(httpServletResponse, times(1)).sendError(HttpServletResponse.SC_UNAUTHORIZED, "You are unauthorized to view this resource");
}
}
|
package ad.joyplus.com.myapplication.AppUtil.glide.request.target;
import android.graphics.drawable.Drawable;
import android.widget.ImageView;
import ad.joyplus.com.myapplication.AppUtil.glide.request.target.*;
/**
* A target for display {@link Drawable} objects in {@link ImageView}s.
*/
public class DrawableImageViewTarget extends ad.joyplus.com.myapplication.AppUtil.glide.request.target.ImageViewTarget<Drawable> {
public DrawableImageViewTarget(ImageView view) {
super(view);
}
@Override
protected void setResource(Drawable resource) {
view.setImageDrawable(resource);
}
}
|
/* */ package de.stuuupiiid.dungeonpack;
/* */
/* */ import java.util.Random;
import net.minecraft.util.ResourceLocation;
/* */
/* */ public class DungeonGeneratorTreeHouse
/* */ extends DungeonGenerator
/* */ {
/* */ public boolean generate(Random random, int par1, int par2, int par3)
/* */ {
/* 10 */ par2 = getTop(par1, par3) - 1;
/* */
/* */
/* */
/* 14 */ for (int i = -3; i < 4; i++) {
/* 15 */ for (int rand = -3; rand < 4; rand++) {
/* 16 */ addBlockAndMetadata(par1 + i, par2, par3 + rand, 5, 3);
/* */ }
/* */ }
/* */
/* 20 */ for (int i = -3; i < 1; i++) {
/* 21 */ for (int rand = -3; rand < 4; rand++) {
/* 22 */ addBlockAndMetadata(par1 + 3, par2 + i + 3, par3 + rand, 5, 3);
/* 23 */ if (random.nextInt(4) == 0) {
/* 24 */ addAir(par1 + 3, par2 + i + 3, par3 + rand);
/* */ }
/* */
/* 27 */ addBlockAndMetadata(par1 - 3, par2 + i + 3, par3 + rand, 5, 3);
/* 28 */ if (random.nextInt(4) == 0) {
/* 29 */ addAir(par1 - 3, par2 + i + 3, par3 + rand);
/* */ }
/* */
/* 32 */ addBlockAndMetadata(par1 + rand, par2 + i + 3, par3 + 3, 5, 3);
/* 33 */ if (random.nextInt(4) == 0) {
/* 34 */ addAir(par1 + rand, par2 + i + 3, par3 + 3);
/* */ }
/* */
/* 37 */ addBlockAndMetadata(par1 + rand, par2 + i + 3, par3 - 3, 5, 3);
/* 38 */ if (random.nextInt(4) == 0) {
/* 39 */ addAir(par1 + rand, par2 + i + 3, par3 - 3);
/* */ }
/* */ }
/* */ }
/* */
/* 44 */ addMobSpawner(par1, par2 + 1, par3, new ResourceLocation("Zombie"));
/* */
/* 46 */ for (int i = 0; i < 2; i++) {
/* 47 */ int rand = random.nextInt(3);
/* */
/* */
/* */
/* */
/* 52 */ if (rand == 0) {
/* 53 */ int kor = random.nextInt(2) - 1;
/* 54 */ int x = par1 + 2;
/* 55 */ int y = par2 + 1;
/* 56 */ int z = par3 + kor;
/* 57 */ if (isAir(x, y, z)) {
/* 58 */ addChestWithDefaultLoot(random, x, y, z);
/* */ }
/* */ }
/* */
/* 62 */ if (rand == 1) {
/* 63 */ int kor = random.nextInt(2) - 1;
/* 64 */ int x = par1 - 2;
/* 65 */ int y = par2 + 1;
/* 66 */ int z = par3 + kor;
/* 67 */ if (isAir(x, y, z)) {
/* 68 */ addChestWithDefaultLoot(random, x, y, z);
/* */ }
/* */ }
/* */
/* 72 */ if (rand == 2) {
/* 73 */ int kor = random.nextInt(2) - 1;
/* 74 */ int x = par1 + kor;
/* 75 */ int y = par2 + 1;
/* 76 */ int z = par3 + 2;
/* 77 */ if (isAir(x, y, z)) {
/* 78 */ addChestWithDefaultLoot(random, x, y, z);
/* */ }
/* */ }
/* */
/* 82 */ if (rand == 3) {
/* 83 */ int kor = random.nextInt(2) - 1;
/* 84 */ int x = par1 + kor;
/* 85 */ int y = par2 + 1;
/* 86 */ int z = par3 - 2;
/* 87 */ if (isAir(x, y, z)) {
/* 88 */ addChestWithDefaultLoot(random, x, y, z);
/* */ }
/* */ }
/* */ }
/* */
/* 93 */ return true;
/* */ }
/* */ }
/* Location: C:\Users\IyadE\Desktop\Mod Porting Tools\dungeonpack-1.8.jar!\de\stuuupiiid\dungeonpack\DungeonGeneratorTreeHouse.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ |
package com.lubarov.daniel.web.http.parsing;
import com.lubarov.daniel.data.dictionary.KeyValuePair;
import com.lubarov.daniel.data.option.Option;
import com.lubarov.daniel.data.util.ArrayUtils;
import com.lubarov.daniel.parsing.ParseResult;
import com.lubarov.daniel.parsing.Parser;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
/**
* Parses a key/value pair in a cookie header, for example "$Version=1".
*/
public final class CookieKvpParser extends Parser<KeyValuePair<String, String>> {
public static final CookieKvpParser singleton = new CookieKvpParser();
private CookieKvpParser() {}
@Override
public Option<ParseResult<KeyValuePair<String, String>>> tryParse(byte[] data, int p) {
int pEquals = ArrayUtils.firstIndexOf((byte) '=', data, p).getOrDefault(-1);
if (pEquals <= 0)
return Option.none();
String cookieName = new String(data, p, pEquals - p);
p = pEquals + 1;
ParseResult<String> resValue = LenientTokenOrQuotedStringParser.singleton.tryParse(data, p)
.getOrThrow("No cookie value found.");
p = resValue.getRem();
String value;
try {
value = URLDecoder.decode(resValue.getValue(), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new AssertionError("wtf?");
}
KeyValuePair<String, String> result = new KeyValuePair<>(cookieName, value);
return Option.some(new ParseResult<>(result, p));
}
}
|
package com.trantienptit.sev_user.chatbot23.model;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.trantienptit.sev_user.chatbot23.R;
import com.trantienptit.sev_user.chatbot23.adapter.ChatAdapter;
import com.trantienptit.sev_user.chatbot23.bubble.BubbleLayout;
import com.trantienptit.sev_user.chatbot23.bubble.BubblesManager;
import com.trantienptit.sev_user.chatbot23.bubble.BubblesService;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.MarshalFloat;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
/**
* Created by SEV_USER on 9/19/2016.
*/
public class MyBubble {
private Context context;
private BubbleLayout bubbleLayout;
private static BubblesManager bubblesManager;
public static boolean isOpenBubble = true;
private RelativeLayout llContent;
public static MyBubble myBubble;
public ListView listView;
public ImageButton btnSend;
public EditText edtMsg;
public ChatAdapter adapter;
public ArrayList<ChatMessage> chatHistory;
public static ImageView ic_help;
public static MyBubble getInstance(Context context, ArrayList<ChatMessage> chatHistory, ChatAdapter adapter) {
if (myBubble != null) {
myBubble.setChatHistory(chatHistory);
return myBubble;
}
bubblesManager = new BubblesManager.Builder(context)
.setTrashLayout(R.layout.notification_trash_layout)
.build();
bubblesManager.initialize();
myBubble = new MyBubble(context, chatHistory, adapter);
return myBubble;
}
public MyBubble(Context context, ArrayList<ChatMessage> chatHistory, ChatAdapter adapter) {
this.context = context;
this.chatHistory = chatHistory;
this.adapter = adapter;
addNewNotification();
initControls();
}
public void setChatHistory(ArrayList<ChatMessage> chatHistory) {
this.chatHistory = chatHistory;
}
public void addBubble() {
// add bubble view into bubble manager
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;
bubblesManager.addBubble(bubbleLayout, width, height/4);
// loadDummyHistory();
}
public void addNewNotification() {
bubbleLayout = (BubbleLayout) LayoutInflater.from(context)
.inflate(R.layout.notification_layout, null);
// this method call when user remove notification layout
llContent = (RelativeLayout) bubbleLayout.findViewById(R.id.llContent);
ic_help= (ImageView) bubbleLayout.findViewById(R.id.ic_help);
ic_help.setColorFilter(Color.RED);
llContent.setVisibility(View.GONE);
bubbleLayout.setOnBubbleRemoveListener(new BubbleLayout.OnBubbleRemoveListener() {
@Override
public void onBubbleRemoved(BubbleLayout bubble) {
Toast.makeText(context, "Bubble removed !",
Toast.LENGTH_SHORT).show();
}
});
// this methoid call when cuser click on the notification layout( bubble layout)
bubbleLayout.setOnBubbleClickListener(new BubbleLayout.OnBubbleClickListener() {
@Override
public void onBubbleClick(BubbleLayout bubble) {
Toast.makeText(context, "Clicked !",
Toast.LENGTH_SHORT).show();
if (isOpenBubble) {
WindowManager.LayoutParams params = (WindowManager.LayoutParams) bubbleLayout.getLayoutParams();
params.width = WindowManager.LayoutParams.MATCH_PARENT;
params.height = WindowManager.LayoutParams.MATCH_PARENT;
params.flags= WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE;
params.format= PixelFormat.TRANSPARENT;
bubbleLayout.setLayoutParams(params);
llContent.setVisibility(View.VISIBLE);
edtMsg.requestFocus();
InputMethodManager imm = (InputMethodManager)
context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(edtMsg, InputMethodManager.SHOW_IMPLICIT);
ic_help.setColorFilter(Color.GREEN);
isOpenBubble = false;
} else {
llContent.setVisibility(View.GONE);
WindowManager.LayoutParams params = (WindowManager.LayoutParams) bubbleLayout.getLayoutParams();
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.flags= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
params.format= PixelFormat.TRANSLUCENT;
ic_help.setColorFilter(Color.RED);
bubbleLayout.setLayoutParams(params);
isOpenBubble = true;
}
}
});
}
/**
* Configure the trash layout with your BubblesManager builder.
*/
private void initializeBubbleManager() {
bubblesManager = new BubblesManager.Builder(context)
.setTrashLayout(R.layout.notification_trash_layout)
.build();
bubblesManager.initialize();
}
public void hideBubble() {
if (bubbleLayout != null)
bubblesManager.removeBubble(bubbleLayout);
Intent intent=new Intent(context,BubblesService.class);
context.stopService(intent);
}
private void initControls() {
listView = (ListView) bubbleLayout.findViewById(R.id.messagesContainer);
edtMsg = (EditText) bubbleLayout.findViewById(R.id.messageEdit);
btnSend = (ImageButton) bubbleLayout.findViewById(R.id.chatSendButton);
edtMsg.requestFocus();
edtMsg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(context, "Enter message ", Toast.LENGTH_LONG).show();
Log.i("TAG-KEY", "OP");
}
});
listView.setAdapter(adapter);
btnSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(context, "Send ", Toast.LENGTH_LONG).show();
String messageText = edtMsg.getText().toString();
// messageText = "Lỗi";
if (TextUtils.isEmpty(messageText)) {
return;
}
ChatMessage chatMessage = new ChatMessage();
chatMessage.setId(122);//dummy
chatMessage.setMessage(messageText);
chatMessage.setDate(DateFormat.getDateTimeInstance().format(new Date()));
chatMessage.setMe(true);
edtMsg.setText("");
displayMessage(chatMessage);
new AsyncLoad().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, messageText);
}
});
}
public void displayMessage(ChatMessage message) {
adapter.add(message);
adapter.notifyDataSetChanged();
scroll();
}
private void scroll() {
listView.setSelection(listView.getCount() - 1);
}
private void loadDummyHistory() {
for (int i = 0; i < chatHistory.size(); i++) {
ChatMessage message = chatHistory.get(i);
displayMessage(message);
}
}
private String getTokenizer(String s) {
String result = "";
String NAMESPACE = context.getResources().getString(R.string.NAME_SPACE);
String URL = context.getResources().getString(R.string.URL);
String SOAP_METHOD = "tokenizerService";
String SOAP_ACTION = NAMESPACE + SOAP_METHOD;
SoapObject request = new SoapObject(NAMESPACE, SOAP_METHOD);
request.addProperty("sequence", s);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.implicitTypes = true;
MarshalFloat marshal = new MarshalFloat();
marshal.register(envelope);
// HttpTransportSE httpTransportSE=new HttpTransportSE(URL);
AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);
try {
// httpTransportSE.call(SOAP_ACTION,envelope);
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
result = response.toString();
} catch (IOException e) {
Log.e("TAG", e.getMessage());
} catch (XmlPullParserException e) {
Log.e("TAG", e.getMessage());
}
return result;
}
public class AsyncLoad extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String result = getTokenizer(params[0]);
return result;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s == null || s.isEmpty())
s = "Đang có lỗi xảy ra";
ChatMessage msg = new ChatMessage();
msg.setId(1);
msg.setMe(false);
msg.setMessage(s);
msg.setDate(DateFormat.getDateTimeInstance().format(new Date()));
adapter.add(msg);
adapter.notifyDataSetChanged();
}
}
public ChatAdapter getAdapter() {
return adapter;
}
public void setAdapter(ChatAdapter adapter) {
this.adapter = adapter;
}
public ArrayList<ChatMessage> getChatHistory() {
return chatHistory;
}
}
|
package com.tfjybj.integral.model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.Accessors;
import java.util.List;
@ApiModel(value="WeekTomatoModel:返回的-周-番茄信息")
@NoArgsConstructor
@Data
@Accessors(chain=true)
@ToString(callSuper=true)
/**
* @Description: 返回的-周-番茄信息
* @Param:
* @return:
* @Author: 张文慧
* @Date: 2019/9/15
*/
public class WeekTomatoModel {
private Integer thisIntegral;
private Integer beforeIntegral;
private String week;
}
|
package graphana.script.bindings.basictypes;
import scriptinterface.ScriptType;
import scriptinterface.execution.returnvalues.ExecutionResult;
/**
* Script type wrapper for the closure of an operation call.
*
* @author Andreas Fender
*/
public class GExecuterCall extends ExecutionResult<ExecuterCallData> {
private static final ScriptType TYPE = new ScriptType("ExecuterCall", "ExecCall");
private ExecuterCallData execData;
public GExecuterCall(ExecuterCallData execData) {
this.execData = execData;
}
public GExecuterCall() {
this(null);
}
@Override
public ExecuterCallData getValue() {
return execData;
}
@Override
public void setValue(ExecuterCallData executer) {
this.execData = executer;
}
@Override
public ScriptType getType() {
return TYPE;
}
@Override
public GExecuterCall clone() {
return new GExecuterCall(execData);
}
}
|
package com.tencent.mm.plugin.appbrand.canvas;
import android.graphics.Bitmap;
import com.tencent.mm.modelappbrand.b.b.h;
import com.tencent.mm.plugin.appbrand.canvas.g.a;
class j$1 implements h {
final /* synthetic */ a fno;
final /* synthetic */ j fnp;
final /* synthetic */ String sk;
final /* synthetic */ String val$url;
j$1(j jVar, a aVar, String str, String str2) {
this.fnp = jVar;
this.fno = aVar;
this.sk = str;
this.val$url = str2;
}
public final void Kc() {
}
public final void n(Bitmap bitmap) {
if (this.fno != null && bitmap != null && !bitmap.isRecycled()) {
this.fno.adn();
}
}
public final void Kd() {
}
public final String Ke() {
return "WxaIcon";
}
}
|
package com.kmilewsk.github;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@SpringBootTest
class GitHubApplicationTests {
@Autowired
ApplicationContext applicationContext;
@Test
void contextLoads() {
assertNotNull(applicationContext);
}
}
|
package com.travelportal.controllers;
import java.util.HashMap;
import java.util.List;
import play.data.DynamicForm;
import play.db.jpa.Transactional;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.home;
import com.travelportal.domain.HotelRegistration;
import com.travelportal.domain.Permissions;
import com.travelportal.domain.agent.AgentRegistration;
public class SupplierLoginthroughAdminController extends Controller {
/*@Transactional
public static Result getsupplierLogin(String supplierCode,String supplierName) {
HotelRegistration user = HotelRegistration.findSupplier(supplierCode,supplierName);
if(user != null) {
//session().put("SUPPLIER", user.getSupplierCode());
long code = Long.parseLong(user.getSupplierCode());
return ok(home.render("Home Page", code));
}
return ok(views.html.adminHome.render());
}*/
@Transactional
public static Result getsupplierLogin() {
DynamicForm form = DynamicForm.form().bindFromRequest();
HotelRegistration user = HotelRegistration.findSupplier(form.get("supplierCode"),form.get("hotelNm"));
long supplierpending = HotelRegistration.pendingData();
long agentpending = AgentRegistration.pendingData();
System.out.println("SESSION VALUE "+session().get("NAME"));
if(user != null) {
//session().put("SUPPLIER", user.getSupplierCode());
long code = Long.parseLong(user.getSupplierCode());
HashMap<String , String> permission = new HashMap<>();
List<Permissions> permissions = Permissions.getPermission();
for(Permissions permissions2 : permissions){
permission.put(permissions2.getName() , String.valueOf(user.getPermissions().contains(permissions2)));
}
return ok(home.render("Home Page", code,Json.stringify(Json.toJson(permission))));
}
//return ok();
return ok(views.html.adminHome.render(String.valueOf(supplierpending), String .valueOf(agentpending)));
}
@Transactional
public static Result getfindSupplier(String SupplierCode,String SupplierName) {
String successdata="";
HotelRegistration hotelRegistration = HotelRegistration.findSupplier(SupplierCode,SupplierName);
if(hotelRegistration != null)
{
successdata = "true";
}
else
{
successdata = "false";
}
return ok(successdata);
}
}
|
package top.kylewang.bos.web.controller.system;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.kylewang.bos.domain.system.Permission;
import top.kylewang.bos.service.system.PermissionService;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/**
* @author Kyle.Wang
* 2018/1/10 0010 19:56
*/
@Controller
public class PermissionController{
@Autowired
private PermissionService permissionService;
/**
* 权限列表查询
* @return
*/
@RequestMapping("/permission_list.action")
@ResponseBody
public List<Permission> pageQuery(){
List<Permission> list = permissionService.findAll();
return list;
}
/**
* 新增权限
* @param permission
* @param response
* @throws IOException
*/
@RequestMapping("/permission_save.action")
public void save(Permission permission, HttpServletResponse response) throws IOException {
permissionService.save(permission);
response.sendRedirect("./pages/system/permission.html");
}
}
|
package com.nt.as;
public class ServletClass {
}
|
package com.avalara.avatax.services.base;
import javax.xml.soap.SOAPException;
/**
* Interface for the basic Web service functionality shared by the Address and Tax Service --
* essentially setting the connection and authentication information necessary for
* both service proxies to connect to Avalara's Web services.
*
* <pre>
* <b>Example:</b>
* EngineConfiguration config = new FileProvider("avatax4j.wsdd");
*
* AddressSvcLocator svcLoc = new AddressSvcLocator(config);
* AddressSvcSoap svc = svcLoc.getAddressSvcSoap(new URL("http://www.avalara.com/services/"));
*
* // Set the profile
* Profile profile = new Profile();
* profile.setClient("AddressSvcTest,4.0.0.0");
* svc.setProfile(profile);
*
* // Set security
* Security security = new Security();
* security.setAccount("account");
* security.setLicense("license number");
* svc.setSecurity(security);
*
* PingResult result = svc.ping("");
* </pre>
*
* @author brianh
* Copyright (c) 2005, Avalara. All rights reserved.
*/
public interface BaseSvcSoap extends java.rmi.Remote
{
/**
* Set the Profile information for the service.
* @param profile
* @throws SOAPException
*/
public void setProfile(Profile profile) throws SOAPException;
/**
* Get the Profile information for the service.
*
* @return Profile object
*/
public Profile getProfile();
/**
* Set the authentication information via a {@link Security} object.
* @param security
*/
public void setSecurity(Security security);
/**
* Get the authentication information via a {@link Security} object.
*
* @return Security
*/
public Security getSecurity();
}
|
package com.rsm.yuri.projecttaxilivredriver.editprofile.di;
import com.rsm.yuri.projecttaxilivredriver.TaxiLivreDriverAppModule;
import com.rsm.yuri.projecttaxilivredriver.domain.di.DomainModule;
import com.rsm.yuri.projecttaxilivredriver.editprofile.ui.EditProfileActivity;
import com.rsm.yuri.projecttaxilivredriver.lib.di.LibsModule;
import javax.inject.Singleton;
import dagger.Component;
/**
* Created by yuri_ on 14/03/2018.
*/
@Singleton
@Component(modules = {EditProfileModule.class, DomainModule.class, LibsModule.class, TaxiLivreDriverAppModule.class})
public interface EditProfileComponent {
void inject(EditProfileActivity activity);
}
|
import java.util.HashMap;
import java.util.Set;
/**
* Class Room - a room in an adventure game.
*
* This class is part of the "World of Zuul" application.
* "World of Zuul" is a very simple, text based adventure game.
*
* A "Room" represents one location in the scenery of the game. It is
* connected to other rooms via exits. The exits are labelled north,
* east, south, west. For each direction, the room stores a reference
* to the neighboring room, or null if there is no exit in that direction.
*
* @author Michael Kölling and David J. Barnes
* @version 2011.07.31
*/
public class Room
{
private String description;
private HashMap<String, Room> exits;
/**
* Create a room described "description". Initially, it has
* no exits. "description" is something like "a kitchen" or
* "an open court yard".
* @param description The room's description.
*/
public Room(String description, Item item)
{
this.description = description;
exits = new HashMap<>();
}
/**
* Define the exits of this room. Every direction either leads
* to another room or is null (no exit there).
* @param north The north exit.
* @param east The east east.
* @param south The south exit.
* @param west The west exit.
*/
public void setExits(Room north, Room east, Room south, Room west, Room southEast, Room northWest)
{
if(north != null)
exits.put("north", north);
if(east != null)
exits.put("east", east);
if(south != null)
exits.put("south", south);
if(west != null)
exits.put("west", west);
if(southEast != null)
exits.put("southEast", southEast);
if(northWest != null)
exits.put("northWest", northWest);
}
/**
* Define una salida para la habitacion.
* @param direction El nombre de la direccion de la salida
* @param neighbor La habitacion a la que se llega usando esa salida
*/
public void setExit(String direction, Room neighbor){
exits.put(direction, neighbor);
}
/**
* @return The description of the room.
*/
public String getDescription()
{
return description;
}
public Room getExit(String direction){
return exits.get(direction);
}
/**
* Devuelve la información de las salidas existentes
* Por ejemplo: "Exits: north east west"
*
* @return Una descripción de las salidas existentes.
*/
public String getExitString(){
Set<String> direccion = exits.keySet();
String descripcion = "Exit: ";
for(String direccionActual : direccion){
descripcion += direccionActual + " ";
}
return descripcion;
}
/**
* Devuelve un texto con la descripcion larga de la habitacion del tipo:
* You are in the 'name of room'
* Exits: north west southwest
* @return Una descripcion de la habitacion incluyendo sus salidas
*/
public String getLongDescription(){
return "You are " + description + "\n" + getExitString() + "\n";
}
}
|
package com.mrhan.text.tatl.base;
import com.mrhan.text.tatl.ActionType;
import com.mrhan.text.tatl.IBlockAction;
import com.mrhan.text.tatl.ISingleAction;
import com.mrhan.text.tatl.ITextTemplate;
/**
* 单条语句操作实现类
*/
public class SingleAction implements ISingleAction {
/*
* 字符模板
*/
private ITextTemplate textTemplate;
/* 当前操作的父级操作!null 不存在父级,隶属于根操作*/
private IBlockAction parentAction;
/**
* 构造函数
* @param template 操作所在的模板对象
* @param parentAction
* @param actionStr 单条操作的字符串!操作=》{{&a=1}} 传递字符串=>&a=1
*/
public SingleAction(ITextTemplate template,IBlockAction parentAction,String actionStr){
}
@Override
public ActionType getActionType() {
return ActionType.ACTION__SINGLE;
}
@Override
public String executeAction() {
return null;
}
@Override
public ITextTemplate getTemplate() {
return null;
}
@Override
public IBlockAction getBlockAction() {
return null;
}
}
|
package com.yida.design.Mediator.demo.colleague;
import com.yida.design.Mediator.demo.mediator.AbstractMediator;
/**
*********************
* 抽象同事类
*
* @author yangke
* @version 1.0
* @created 2018年5月11日 下午4:57:55
***********************
*/
public abstract class AbstractColleague {
protected AbstractMediator mediator;
public AbstractColleague(AbstractMediator mediator) {
super();
this.mediator = mediator;
}
}
|
package org.dmonix.util.zip;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.dmonix.io.IOUtil;
/**
* Class for writing/deflating entries to a ZIP file.
* <p>
* Copyright: Copyright (c) 2001
* </p>
* <p>
* Company: dmonix.org
* </p>
*
* @author Peter Nerg
* @since 1.0
*/
public class ZipWriter {
/** The logger instance for this class */
private static final Logger log = Logger.getLogger(ZipWriter.class.getName());
private ZipOutputStream zoStream = null;
private ZipEntry currentEntry = null;
private ZipWriter(String fileName) throws IOException {
this.zoStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(fileName)));
}
/**
* Add a new file entry to the existing zip file. <br>
* The method will add the file to zip file with information on the original files source path relative to the supplied directory path. <br>
* E.g. the directory <i>/etc/foo/</i> and the file <i>/etc/foo/data/file.txt</i> results in an entry called <i>data/file.txt/</i> <br>
* The method will implicitly perform an <code>addZipEntry</code> and a <code>closeZipEntry</code>.
*
* @param file
* A file object
* @param directory
* A parent directory
* @throws IOException
* @see org.dmonix.io.IOUtil.getRelativePath(File, File)
*/
public void addFile(File file, File directory) throws IOException {
addZipEntry(IOUtil.getRelativePath(directory, file));
writeDataToZipEntry(new FileInputStream(file), true);
closeZipEntry();
}
/**
* Add a new file entry to the existing zip file. <br>
* The method will add the file to zip file with no information on the original files source path. <br>
* I.e. the file <i>/etc/foo/data/file.txt</i> will be written to the ZIP file simply as <i>file.txt</i>. <br>
* Note that there is a risk of filename collision this way. <br>
* The method will implicitly perform an <code>addZipEntry</code> and a <code>closeZipEntry</code>.
*
* @param file
* The file
* @throws IOException
*/
public void addFile(File file) throws IOException {
addZipEntry(file.getName());
writeDataToZipEntry(new FileInputStream(file), true);
closeZipEntry();
}
/**
* Add a new file entry to the existing zip file <br>
* The method will add the file to zip file with no information on the original files source path. <br>
* I.e. the file <i>/etc/foo/data/file.txt</i> will be written to the ZIP file simply as <i>file.txt</i>. <br>
* Note that there is a risk of filename collision this way. <br>
* The method will implicitly perform an <code>addZipEntry</code> and a <code>closeZipEntry</code>.
*
* @param fileName
* name/path of the file to add
* @throws IOException
*/
public void addFile(String fileName) throws IOException {
addFile(new File(fileName));
}
/**
* Add a new file entry to the existing zip file. <br>
* The method will add the file to zip file with information on the original files source path relative to the supplied directory path. <br>
* E.g. the directory <i>/etc/foo/</i> and the file <i>/etc/foo/data/file.txt</i> results in an entry called <i>data/file.txt/</i> <br>
* The method will implicitly perform an <code>addZipEntry</code> and a <code>closeZipEntry</code>.
*
* @param file
* A file object
* @param directory
* A parent directory
* @param comment
* The entry comment
* @throws IOException
* @see org.dmonix.io.IOUtil.getRelativePath(File, File)
*/
public void addFile(File file, File directory, String comment) throws IOException {
addZipEntry(IOUtil.getRelativePath(directory, file), comment);
writeDataToZipEntry(new FileInputStream(file), true);
closeZipEntry();
if (log.isLoggable(Level.FINER))
log.log(Level.FINER, "Added zip entry " + file.getAbsolutePath());
}
/**
* Add a new file entry to the existing zip file. <br>
* The method will add the file to zip file with no information on the original files source path. <br>
* I.e. the file <i>/etc/foo/data/file.txt</i> will be written to the ZIP file simply as <i>file.txt</i>. <br>
* Note that there is a risk of filename collision this way. <br>
* The method will implicitly perform an <code>addZipEntry</code> and a <code>closeZipEntry</code>.
*
* @param file
* The file
* @param comment
* The entry comment
* @throws IOException
*/
public void addFile(File file, String comment) throws IOException {
addZipEntry(file.getName(), comment);
writeDataToZipEntry(new FileInputStream(file), true);
closeZipEntry();
if (log.isLoggable(Level.FINER))
log.log(Level.FINER, "Added zip entry " + file.getAbsolutePath());
}
/**
* Add a new file entry to the existing zip file <br>
* The method will implicitly perform an <code>addZipEntry</code> and a <code>closeZipEntry</code>.
*
* @param fileName
* name/path of the file to add
* @param comment
* The entry comment
* @throws IOException
*/
public void addFile(String fileName, String comment) throws IOException {
addFile(new File(fileName), comment);
}
/**
* Add an array of files to the existing zip file. <br>
* This is equal to multiple calls to <code>addFile(File)</code>
*
* @param files
* The files to add
* @throws IOException
* @see addFile(File)
*/
public void addFiles(File[] files) throws IOException {
for (int i = 0; i < files.length; i++) {
this.addFile(files[i]);
}
}
/**
* Creates a new entry in the ZIP file.
*
* @param name
* The name/path of the entry
* @throws IOException
*/
public void addZipEntry(String name) throws IOException {
this.currentEntry = new ZipEntry(name);
zoStream.putNextEntry(this.currentEntry);
}
/**
* Creates a new entry in the ZIP file.
*
* @param name
* The name/path of the entry
* @param comment
* The entry comment
* @throws IOException
*/
public void addZipEntry(String name, String comment) throws IOException {
this.currentEntry = new ZipEntry(name);
this.currentEntry.setComment(comment);
zoStream.putNextEntry(this.currentEntry);
}
/**
* Writes data to the current entry. <br>
* A call to <code>addZipEntry</code> must preceed this operation.
*
* @param data
* The data to write to the entry
* @throws IOException
* @see addZipEntry(String)
* @see addZipEntry(String, String)
*/
public void writeDataToZipEntry(int data) throws IOException {
zoStream.write(data);
}
/**
* Writes data to the current entry. <br>
* A call to <code>addZipEntry</code> must preceed this operation.
*
* @param data
* The data to write to the entry
* @throws IOException
* @see addZipEntry(String)
* @see addZipEntry(String, String)
*/
public void writeDataToZipEntry(byte[] data) throws IOException {
zoStream.write(data);
}
/**
* Writes data to the current entry. <br>
* A call to <code>addZipEntry</code> must preceed this operation.
*
* @param data
* The data to write to the entry
* @param offset
* The offset from where to start read data in the data array
* @param length
* The amount of data to read from the data array
* @throws IOException
* @see addZipEntry(String)
* @see addZipEntry(String, String)
*/
public void writeDataToZipEntry(byte[] data, int offset, int length) throws IOException {
zoStream.write(data, offset, length);
}
/**
* Copies data from the provided stream to the current entry <br>
* A call to <code>addZipEntry</code> must preceed this operation.
*
* @param istream
* The inputstrream from where to copy data
* @param closeInputStream
* If the inputstream is to be closed
* @throws IOException
* @see addZipEntry(String)
* @see addZipEntry(String, String)
*/
public void writeDataToZipEntry(InputStream istream, boolean closeInputStream) throws IOException {
IOUtil.copyStreams(istream, zoStream, closeInputStream, false);
}
/**
* Closes the current zip entry. <br>
* A call to <code>addZipEntry</code> must preceed this operation.
*
* @throws IOException
* @see addZipEntry(String)
* @see addZipEntry(String, String)
*/
public void closeZipEntry() throws IOException {
zoStream.flush();
zoStream.closeEntry();
this.currentEntry = null;
}
/**
* Close the outputstream to the zip file. <br>
* The methods does nothing if the outputstream is already closed.
*
* @throws IOException
*/
public void close() throws IOException {
if (zoStream != null)
zoStream.close();
zoStream = null;
}
/**
* Sets the level of compression.
*
* @param compressionLevel
* The compression level [0-9]
*/
public void setCompressionLevel(int compressionLevel) {
this.zoStream.setLevel(compressionLevel);
}
/**
* Set a comment for the current ZIP file.
*
* @param comment
* The ZIP file comment
*/
public void setZipfileComment(String comment) {
this.zoStream.setComment(comment);
}
/**
* Creates a new ZIP file.
*
* @param file
* The ZIP file
* @return A ZIPWriter instance
* @throws IOException
*/
public static ZipWriter createZipFile(File file) throws IOException {
return new ZipWriter(file.getAbsolutePath());
}
/**
* Creates a new ZIP file.
*
* @param file
* The ZIP file
* @param compressionLevel
* The compression level [0-9]
* @return A ZIPWriter instance
* @throws IOException
*/
public static ZipWriter createZipFile(File file, int compressionLevel) throws IOException {
ZipWriter zr = new ZipWriter(file.getAbsolutePath());
zr.setCompressionLevel(compressionLevel);
return zr;
}
/**
* Creates a new ZIP file.
*
* @param fileName
* Name of the zip file
* @return A ZIPWriter instance
* @throws IOException
*/
public static ZipWriter createZipFile(String fileName) throws IOException {
return new ZipWriter(fileName);
}
/**
* Creates a new ZIP file.
*
* @param fileName
* Name of the zip file
* @param compressionLevel
* The compression level [0-9]
* @return A ZIPWriter instance
* @throws IOException
*/
public static ZipWriter createZipFile(String fileName, int compressionLevel) throws IOException {
ZipWriter zr = new ZipWriter(fileName);
zr.setCompressionLevel(compressionLevel);
return zr;
}
} |
/*
* GNUnetWebUI - A Web User Interface for P2P networks. <https://gitorious.org/gnunet-webui>
* Copyright 2013 Sébastien Moratinos <sebastien.moratinos@gmail.com>
*
*
* This file is part of GNUnetWebUI.
*
* GNUnetWebUI is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GNUnetWebUI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with GNUnetWebUI. If not, see <http://www.gnu.org/licenses/>.
*/
package org.gnunet.integration.internal.persistor;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.validation.constraints.NotNull;
import com.avaje.ebean.Ebean;
/**
* A search for file-sharing system
*
* @author smoratinos
*
*/
@Entity
public class SearchEntity {
@Id
@GeneratedValue
public Long id;
/**
* UserEntity who as ask for the search
*/
@NotNull
public String username;
@NotNull
public Date askDate;
@NotNull
public String keywords;
public Integer anonymity;//-a LEVEL, --anonymity=LEVEL
public Boolean remote;//-n, --no-network
public Integer maxResult;//-N VALUE, --results=VALUE
public Long timeout;
@OneToMany(mappedBy = "search")
public Set<SearchFoundEntity> results = new HashSet<SearchFoundEntity>();
public boolean inProgress;
public String searcherPath;
public String executorPath;
/**
* Don't use this constructor.
* It exist only for class enhancement use by libraries.
* The object is not valid
*/
@Deprecated
public SearchEntity() {
super();
}
public SearchEntity(final String username, final Date askDate, final String keywords) {
super();
this.username = username;
this.askDate = askDate;
this.keywords = keywords;
}
/**
* Retrieve all search.
*/
public static List<SearchEntity> findAll() {
return Ebean.find(SearchEntity.class).findList();//find.all();
}
/**
* Retrieve a SearchEntity from id.
*/
public static SearchEntity findById(final Long id) {
return Ebean.find(SearchEntity.class).fetch("results").where().eq("id", id).findUnique();
//find.fetch("results").where().eq("id", id).findUnique();
}
public Long getId() {
return id;
}
public void setId(final Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(final String username) {
this.username = username;
}
public Date getAskDate() {
return askDate;
}
public void setAskDate(final Date askDate) {
this.askDate = askDate;
}
public String getKeywords() {
return keywords;
}
public void setKeywords(final String keywords) {
this.keywords = keywords;
}
public Integer getAnonymity() {
return anonymity;
}
public void setAnonymity(final Integer anonymity) {
this.anonymity = anonymity;
}
public Boolean getRemote() {
return remote;
}
public void setRemote(final Boolean remote) {
this.remote = remote;
}
public Integer getMaxResult() {
return maxResult;
}
public void setMaxResult(final Integer maxResult) {
this.maxResult = maxResult;
}
public Long getTimeout() {
return timeout;
}
public void setTimeout(final Long timeout) {
this.timeout = timeout;
}
public Set<SearchFoundEntity> getResults() {
return results;
}
public void setResults(final Set<SearchFoundEntity> results) {
this.results = results;
}
public boolean isInProgress() {
return inProgress;
}
public void setInProgress(final boolean inProgress) {
this.inProgress = inProgress;
}
public String getSearcherPath() {
return searcherPath;
}
public void setSearcherPath(final String searcherPath) {
this.searcherPath = searcherPath;
}
public String getExecutorPath() {
return executorPath;
}
public void setExecutorPath(final String executorPath) {
this.executorPath = executorPath;
}
@Override
public String toString() {
return "SearchEntity [id=" + id + ", username=" + username + ", askDate=" + askDate
+ ", keywords="
+ keywords
+ "]";
}
}
|
public abstract class Personagem
{
protected String nome;
protected Inventario inventario;
protected int experiencia;
protected int vida;
protected Status status;
public Personagem(String nome)
{
this.nome = nome;
this.experiencia = 0;
this.inventario = new Inventario();
this.status = Status.VIVO;
this.vida = 100;
}
public String getNome()
{
return this.nome;
}
public Inventario getInventario()
{
return this.inventario;
}
public int getExperiencia()
{
return this.experiencia;
}
public Status getStatus()
{
return this.status;
}
public int getVida()
{
return this.vida;
}
public abstract void tentarSorte();
}
|
package com.tfjybj.integral.model;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
/**
* @author 崔晓鸿
* @since 2019年9月12日17:38:31
*/
@Data
@Accessors(chain = true)
@ToString(callSuper = true)
public class IntegralColDetDayPayModel implements Serializable {
@ApiModelProperty(value = "支出详情(按插件分类)")
private Set<IntegralCollectPluginModel> expendList;
/**
* 支出详情
*/
@ApiModelProperty(value = "支出详情")
private List<IntegralCollectPluginModel> expendDetailList;
}
|
package Pom_class;
import java.util.List;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class Github_home_links {
@FindBy(xpath="//a")
private List<WebElement> links;
public Github_home_links(WebDriver driver)
{
PageFactory.initElements(driver,this);
}
public void countlinks()
{
int count = links.size();
System.out.println(count);
for(int i=0; i<count; i++)
{
WebElement we = links.get(i);
String text = we.getText();
System.out.println(text);
}
}
}
|
public class Staircases {
public static void main(String[] args) {
System.out.println(solution(200));
}
public static int solution(int n) {
return countSteps(n, n + 1);
}
// Recursively checks for and counts all valid staircases.
// Leverages the 1+2+3...+n series to avoid an exhaustive search.
private static int countSteps(int n, int next) {
int counter = 0;
for (int i = n - 1; n <= (i * (i + 1) / 2); i--) {
if (i >= next) {
continue;
}
if (i > n - i) {
counter++;
}
if (n - i > 2) {
counter += countSteps(n - i, i);
}
}
return counter;
}
} |
package sc.helpers;
import sc.protocol.responses.ProtocolMessage;
public interface IAsyncResult {
void operate(ProtocolMessage result);
}
|
package com.sidexia.common;
/**
* Constant values used throughout the application.
*
* @author SAMIR GHAOUTA
*/
public final class Constants {
}
|
package br.com.zup.edu.nossositedeviagens.controller;
import br.com.zup.edu.nossositedeviagens.repository.AeroportReposity;
import br.com.zup.edu.nossositedeviagens.repository.PaisRepository;
import br.com.zup.edu.nossositedeviagens.model.dto.AeroportDto;
import br.com.zup.edu.nossositedeviagens.model.dto.AeroportResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import javax.validation.Valid;
import java.net.URI;
@RestController
@RequestMapping("/aeroporto")
public class AeroportController {
AeroportReposity aeroportReposity;
PaisRepository paisRepository;
public AeroportController(AeroportReposity aeroportReposity, PaisRepository paisRepository) {
this.aeroportReposity = aeroportReposity;
this.paisRepository = paisRepository;
}
@PostMapping
public ResponseEntity<AeroportResponse> cadastra(@RequestBody @Valid AeroportDto aeroportDto, UriComponentsBuilder uriComponentsBuilder) {
var aeroport = aeroportDto.converter(this.paisRepository);
var createdAeroport = aeroportReposity.save(aeroport);
URI uri = uriComponentsBuilder.path("/aeroporto/{id}").buildAndExpand(createdAeroport.getId()).toUri();
return ResponseEntity.created(uri).body(new AeroportResponse(createdAeroport));
}
}
|
package MedianOfTwoSortedArrays;
/**
* /**
* 题目内容
*
* There are two sorted arrays nums1 and nums2 of size m and n respectively.
* Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
* Example 1:
* nums1 = [1, 3]
* nums2 = [2]
* The median is 2.0
* Example 2:
* nums1 = [1, 2]
* nums2 = [3, 4]
* The median is (2 + 3)/2 = 2.5
*
* @author zhangmiao
*
* email:1006299425@qq.com
*
*/
public class Solution {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//测试
int[] nums11 = {1,3};
int[] nums12 = {2};
System.out.println("result 1 : "+findMedianSortedArrays(nums11,nums12));
int[] nums21 = {1,2};
int[] nums22 = {3,4};
System.out.println("result 2 : "+findMedianSortedArrays(nums21,nums22));
int[] nums31 = {1};
int[] nums32 = null;
System.out.println("result 3 : "+findMedianSortedArrays(nums31,nums32));
int[] nums41 = {1};
int[] nums42 = {1};
System.out.println("result 4 : "+findMedianSortedArrays(nums41,nums42));
}
public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
double result = 0;
int[] sort;
if (nums1 == null && nums2 == null) {
return 0;
}else if (nums1 == null) {
sort = nums2;
} else if (nums2 == null) {
sort = nums1;
} else {
int length1 = nums1.length;
int length2 = nums2.length;
//对nums1与nums2进行排序,sort是排序后的结果
sort = new int[length1+length2];
int i = 0,j = 0;
int n =0;
for (; n < sort.length && i < length1 && j < length2; n++ ) {
if (nums1[i] < nums2[j]) {
sort[n] = nums1[i];
i++;
} else {
sort[n] = nums2[j];
j++;
}
}
if (i < length1) {
for(; n < sort.length; n++ ) {
sort[n] = nums1[i];
i++;
}
}
if (j < length2) {
for(; n < sort.length; n++ ) {
sort[n] = nums2[j];
j++;
}
}
}
for (int i = 0; i< sort.length;i++) {
System.out.println("i:"+i+",sort[i]:"+sort[i]);
}
int sLength = sort.length;
if (sLength == 1) {
//只有一个数字
result = sort[0];
} else if (sLength %2 == 0) {
//排序后的结果是偶数
int first = sort[sLength/2-1];
int second = sort[sLength/2];
result = (double)(first+second)/2;
} else {
//排序后的结果是奇数
result = sort[sLength/2];
}
return result;
}
}
|
package cn.edu.hebtu.software.sharemate.Activity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import cn.edu.hebtu.software.sharemate.Fragment.HomeFragment;
import cn.edu.hebtu.software.sharemate.Fragment.MessageFragment;
import cn.edu.hebtu.software.sharemate.Fragment.MyFragment;
import cn.edu.hebtu.software.sharemate.Fragment.ShoppingFragment;
import cn.edu.hebtu.software.sharemate.R;
public class MainActivity extends AppCompatActivity {
private TextView indexView;
private TextView shoppingView;
private TextView messageView;
private TextView myView;
private HomeFragment indexFragment = new HomeFragment();
private ShoppingFragment shoppingFragment = new ShoppingFragment();
private MessageFragment messageFragment = new MessageFragment();
private MyFragment myFragment = new MyFragment();
private FragmentManager manager ;
private Fragment currentFragment = new Fragment();
private List<TextView> views = new ArrayList<>();
private RelativeLayout root = null;
private PopupWindow window = null;
private int userId;
private ArrayList<Integer> type = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
indexView = findViewById(R.id.tv_index);
shoppingView = findViewById(R.id.tv_shopping);
messageView = findViewById(R.id.tv_message);
myView = findViewById(R.id.tv_my);
manager = getSupportFragmentManager();
Log.e("flag",getIntent().getStringExtra("flag"));
userId=getIntent().getIntExtra("userId",0);
type=getIntent().getIntegerArrayListExtra("type");
if ("main".equals(getIntent().getStringExtra("flag"))){
indexView.setTextSize(TypedValue.COMPLEX_UNIT_SP,24);
indexView.setTextColor(getResources().getColor(R.color.inkGray));
showFragment(indexFragment);
}
if("my".equals(getIntent().getStringExtra("flag"))){
showFragment(myFragment);
myView.setTextSize(TypedValue.COMPLEX_UNIT_SP,24);
myView.setTextColor(getResources().getColor(R.color.inkGray));
indexView.setTextSize(TypedValue.COMPLEX_UNIT_SP,22);
indexView.setTextColor(getResources().getColor(R.color.darkGray));
}
views.add(indexView);
views.add(shoppingView);
views.add(messageView);
views.add(myView);
setClickListener();
//实现 popupwindow 功能
root = findViewById(R.id.root);
window = new PopupWindow(root, RelativeLayout.LayoutParams.MATCH_PARENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
Button btnShare = findViewById(R.id.btn_share);
btnShare.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(window.isShowing()){
window.dismiss();
}else{
showPopupWindow(root);
addBackgroundAlpha(0.7f);
}
}
});
}
//为每一个 TextView (模拟的选项) 添加监听器
private void setClickListener(){
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.tv_index:
showFragment(indexFragment);
break;
case R.id.tv_shopping:
showFragment(shoppingFragment);
break;
case R.id.tv_message:
showFragment(messageFragment);
break;
case R.id.tv_my:
showFragment(myFragment);
break;
}
//点击改变效果
for(TextView view : views){
TextView tmp = findViewById(v.getId());
if(tmp == view){
view.setTextColor(getResources().getColor(R.color.inkGray));
view.setTextSize(TypedValue.COMPLEX_UNIT_SP,24);
}else{
view.setTextColor(getResources().getColor(R.color.deepGray));
view.setTextSize(TypedValue.COMPLEX_UNIT_SP,22);
}
}
}
};
indexView.setOnClickListener(listener);
shoppingView.setOnClickListener(listener);
messageView.setOnClickListener(listener);
myView.setOnClickListener(listener);
}
//显示出指定的页面
private void showFragment(Fragment fragment){
//创建 fragment 事务
FragmentTransaction transaction = manager.beginTransaction();
//判断传入的fragment 是否是当前正在显示的fragment
if(fragment != currentFragment)
transaction.hide(currentFragment);
//判断要展示的 fragment 是否被添加过
if(!fragment.isAdded())
transaction.add(R.id.content,fragment);
transaction.show(fragment);
//提交事务
transaction.commit();
currentFragment = fragment;
}
//点击按钮后弹出选项框
private void showPopupWindow(RelativeLayout root){
//设置显示的视图
LayoutInflater inflater =getLayoutInflater();
View view = inflater.inflate(R.layout.share_popupwindow_layout,null);
Button btnCamera = view.findViewById(R.id.btn_camera);
Button btnPhoto = view.findViewById(R.id.btn_photos);
Button btnCancel = view.findViewById(R.id.btn_cancel);
//为弹出框中的每一个按钮
ClickListener listener = new ClickListener();
btnCamera.setOnClickListener(listener);
btnPhoto.setOnClickListener(listener);
btnCancel.setOnClickListener(listener);
//将自定义的视图添加到 popupWindow 中
window.setContentView(view);
//控制 popupwindow 再点击屏幕其他地方时自动消失
window.setFocusable(true);
window.setOutsideTouchable(true);
window.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
//在弹窗消失时调用
addBackgroundAlpha(1f);
}
});
//显示 popupWindow 设置 弹出框的位置
window.showAtLocation(root, Gravity.BOTTOM,0,0);
}
// 弹出选项框时为背景加上透明度
private void addBackgroundAlpha(float alpha){
WindowManager.LayoutParams params = getWindow().getAttributes();
params.alpha = alpha;
getWindow().setAttributes(params);
}
private class ClickListener implements View.OnClickListener{
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_camera:
String state = Environment.getExternalStorageState();// 获取内存卡可用状态
if (state.equals(Environment.MEDIA_MOUNTED)) {
// 内存卡状态可用
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 1);
} else {
// 不可用
Log.e("sd卡","内存不可用");
}
break;
case R.id.btn_photos:
Intent intent1=new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent1, 2);
break;
case R.id.btn_cancel:
window.dismiss();
break;
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
String requestCode1 = String.valueOf(requestCode);
Log.e("requestCode", requestCode1);
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
String sdStatus = Environment.getExternalStorageState();
if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
Log.i("TestFile",
"SD card is not avaiable/writeable right now.");
return;
}
switch (requestCode) {
case 1:
Bundle bundle = data.getExtras();
Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据,并转换为Bitmap图片格式
// 获取 SD 卡根目录 生成图片并
String saveDir = Environment
.getExternalStorageDirectory()
+ "/DCIM/Camera";
// 新建目录
File dir = new File(saveDir);
if (!dir.exists())
dir.mkdir();
// 生成文件名
SimpleDateFormat t = new SimpleDateFormat(
"yyyyMMddssSSS");
String filename = "MT" + (t.format(new Date()))
+ ".jpg";
// 新建文件
File file = new File(saveDir, filename);
Log.e("路径", file.getPath());
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
bos.flush();
bos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Intent intent = new Intent();
intent.setClass(MainActivity.this, FabuActivity.class);
String code = "1";
intent.putExtra("code", code);
intent.putExtra("lujing", file.getPath());///storage/emulated/0/DCIM/Camera/MT2018122121428.jpg
intent.putExtra("userId",userId);
intent.putExtra("type",type);
startActivity(intent);
break;
case 2:
//打开相册并选择照片,这个方式选择单张
// 获取返回的数据,这里是android自定义的Uri地址
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// 获取选择照片的数据视图
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
// 从数据视图中获取已选择图片的路径
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
Log.e("PICFILE", picturePath);
cursor.close();
// 将图片显示到界面上
//加上一个动态获取权限
Intent intent1 = new Intent();
String code1 = "2";
intent1.putExtra("pic1", picturePath);
Log.e("PICFILE", picturePath);
intent1.putExtra("code", code1);
intent1.putExtra("userId",userId);
intent1.putExtra("type",type);
intent1.setClass(MainActivity.this, FabuActivity.class);
startActivity(intent1);
break;
}
}
}
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if (isShouldHideInput(v, ev)) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
return super.dispatchTouchEvent(ev);
}
// 必不可少,否则所有的组件都不会有TouchEvent了
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
public boolean isShouldHideInput(View v, MotionEvent event) {
if (v != null && (v instanceof EditText)) {
int[] leftTop = {0, 0};
//获取输入框当前的location位置
v.getLocationInWindow(leftTop);
int left = leftTop[0];
int top = leftTop[1];
int bottom = top + v.getHeight();
int right = left + v.getWidth();
if (event.getX() > left && event.getX() < right
&& event.getY() > top && event.getY() < bottom) {
// 点击的是输入框区域,保留点击EditText的事件
return false;
} else {
//使EditText触发一次失去焦点事件
v.setFocusable(false);
// v.setFocusable(true); //这里不需要是因为下面一句代码会同时实现这个功能
v.setFocusableInTouchMode(true);
return true;
}
}
return false;
}
}
|
package game.service.cmd;
import game.entity.Cmd;
public interface CmdService {
Cmd convertCmd(String originContent) throws CmdException;
}
|
package com.gokuai.yunku.demo.ent;
import com.gokuai.base.DebugConfig;
import com.gokuai.yunku.demo.Config;
import com.gokuai.yunku.demo.helper.DeserializeHelper;
import com.gokuai.yunku.demo.helper.EntManagerHelper;
/**
* Created by qp on 2017/3/16.
*
* 使用合作方 OutID 进行认证
*/
public class AccessTokenWithThirdPartyOutId {
public static void main(String[] args) {
DebugConfig.PRINT_LOG = true;
// DebugConfig.LOG_PATH="LogPath/";
String returnString = EntManagerHelper.getInstance().accessTokenWithThirdPartyOutId(Config.OUT_ID);
DeserializeHelper.getInstance().deserializeReturn(returnString);
}
}
|
package co.tweetbuy.utils;
import com.google.gson.JsonObject;
import co.tweetbuy.bean.UserBean;
import co.tweetbuy.util.AppUtil;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.HttpsURLConnection;
/**
*
* @author emrah
*/
public class HttpUrlConnectionForTest {
public static <T extends Object> T sendGet(Class<T> classOfT, String url){
T t = null;
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
int responseCode = con.getResponseCode();
System.out.println("Sending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
t = AppUtil.jsonToBean(classOfT, response.toString());
} catch (MalformedURLException ex) {
Logger.getLogger(HttpUrlConnectionForTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(HttpUrlConnectionForTest.class.getName()).log(Level.SEVERE, null, ex);
}
return t;
}
// HTTP POST request
public static <T extends Object> T sendPost(Class<T> classOfT, String url, String params){
T t = null;
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(params);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + params);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
t = AppUtil.jsonToBean(classOfT, response.toString());
return t;
} catch (MalformedURLException ex) {
Logger.getLogger(HttpUrlConnectionForTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (ProtocolException ex) {
Logger.getLogger(HttpUrlConnectionForTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(HttpUrlConnectionForTest.class.getName()).log(Level.SEVERE, null, ex);
}
return t;
}
}
|
package jp.captureAutomationPrj.core;
import java.io.File;
import java.net.URL;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import jp.captureAutomationPrj.constant.CaptureProperties;
import jp.captureAutomationPrj.util.CaptureUtil;
import jp.captureAutomationPrj.util.UrlManager;
/**
* <p>テストキャプチャの簡略化プログラム</br>
* キャプチャ撮るだけなので、Java通常アプリとして作成。</br>
* (普通に機能テストするならユニットテストを作成すること)
* </p>
* @author fujita takashi
*
*/
public class App {
public static void main(String[] args) {
try {
// プロパティ取得
CaptureProperties cp = CaptureProperties.getInstance();
Properties p = cp.getProperties();
// キャプチャユーティリティ
CaptureUtil capUtil = new CaptureUtil();
// exePath設定
// ChromeとIEは設定しないとエラーになる
if (p.getProperty(CaptureProperties.BROESER).equals("ie") || p.getProperty(CaptureProperties.BROESER).equals("chrome")) {
File file = new File("resource/" + p.getProperty(CaptureProperties.EXE_NAME) + ".exe");
System.setProperty("webdriver." + p.getProperty(CaptureProperties.BROESER) + ".driver", file.getAbsolutePath());
}
// 対象ブラウザのドライバーを設定
Class driverClass = Class.forName(p.getProperty(CaptureProperties.DRIVER_NAME));
WebDriver driver = (WebDriver) driverClass.newInstance();
// Wait設定
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// csvファイル
File csvFile = new File(p.getProperty(CaptureProperties.CSV_ADDRESS));
// キャプチャ保存先
File saveAddress = new File(p.getProperty(CaptureProperties.SAVE_ADDRESS));
if (!saveAddress.isDirectory()) {
throw new Exception("保存先が存在しません。\n設定ファイルを再確認してください。");
}
// URLリスト
UrlManager urls = new UrlManager(csvFile);
// https通信時のインターセプター機能対策(初回のみ許可すれば後は通ると仮定する)
//antiHttpsInterceptor(driver, urls.getUrlList().get(0).toString());
for (URL url : urls.getUrlList()) {
// 指定のURLへ接続する
driver.get(url.toString());
// 指定の属性を探す(見つからない場合、wait設定値だけ待つ)
try {
driver.findElement(By.className("footer"));
} catch (Exception e) {
e.printStackTrace();
}
// ファイル名
String[] str = url.getFile().split("/");
String fileName = str[str.length - 2] + ".png";
// キャプチャ
capUtil.driverCapture(driver, new File(saveAddress, "/Dpng/" + fileName));
capUtil.desktopCaptureToPng(new File(saveAddress, "/png/" + fileName));
// capUtil.desktopCaptureToJpeg(new File(saveAddress, "/jpg/" + fileName.replace("png", "jpeg")));
// cookie削除
driver.manage().deleteAllCookies();
}
// 終了
driver.quit();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* <p>https通信& IE& サーバ証明書未設定の場合、別画面へインターセプトされる事への対策</br>
* 単純にインターセプター画面のリンクをクリック
* </p>
* @param driver
* @return
*/
public static boolean antiHttpsInterceptor(WebDriver driver, String url) {
try {
driver.get(url);
driver.findElement(By.id("overridelink")).click();
} catch (Exception e) {
return false;
}
return true;
}
}
|
package webmail.pages;
import org.stringtemplate.v4.ST;
import webmail.misc.VerifyException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by JOKER on 10/28/14.
*/
public class AmailPage extends Page {
public AmailPage(HttpServletRequest request, HttpServletResponse response) {
super(request, response);
}
// -----------------------------sample
@Override
public void handleDefaultArgs() {
// handle default args like page number, etc...
String pageStr = request.getParameter("welcome");
if ( pageStr!=null ) {
pageNum = Integer.valueOf(pageStr); //?
}
}
@Override
public void generate() {
handleDefaultArgs();
try {
verify(); // check args before generation
ST pageST = templates.getInstanceOf("welcome");
//ST bodyST = body();
//pageST.add("body", bodyST);
//pageST.add("title", getTitle());
String page = pageST.render(); //change to String
out.print(page);
}
catch (VerifyException ve) {
// redirect to error page
}
finally {
out.close();
}
}
@Override
public ST body() {
return templates.getInstanceOf("amail");
}
@Override
public ST getTitle() {
return new ST("Amail");
}
} |
package mainDemo;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import entity.Student;
public class Select_using_HQL {
public static void main(String[] args) {
// create session factory
SessionFactory factory = new Configuration().configure().addAnnotatedClass(Student.class).buildSessionFactory();
Session session = factory.getCurrentSession();
try {
//begin transaction
session.beginTransaction();
//query using HQL
List<Student> allStudents = session.createQuery("from Student").getResultList();
//display the result
for(Student s: allStudents)
System.out.println(s);
//commit transaction
session.getTransaction().commit();
} finally {
factory.close();
}
}
}
|
package cn.ouyangnengda.dubbo.DubboSPI;
import java.util.Scanner;
/**
* @Description:
* @Author: 欧阳能达
* @Created: 2019年09月12日 15:44:00
**/
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
/*for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = input.nextInt();
}
}*/
int maxNum = input.nextInt();
int max = 0;
if (maxNum > 0) {
max = maxNum;
}
for (int i = 0; i < (n * n - 1); i++) {
int p = input.nextInt();
if (p > maxNum) {
maxNum = p;
}
if (p > 0) {
max += p;
}
}
if (max == 0) {
System.out.println(maxNum);
} else {
System.out.println(Math.max(max, maxNum));
}
}
}
|
package com.spower.business.examitem.command;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import com.spower.basesystem.common.command.BaseCommandInfo;
/**
* @author huangwq
*2014年11月24日
*/
public class ExamItemEditInfo extends BaseCommandInfo {
/**项目编号*/
private Long itemId;
/**分类ID*/
private Long typeId;
/**项目名称*/
private String itemName;
/**上限值*/
private Double maxValue;
/**下限值*/
private Double minValue;
/**单位*/
private String unit;
/**排序号*/
private String sort;
/**体检项目状态*/
private String status;
public Long getItemId() {
return itemId;
}
public void setItemId(Long itemId) {
this.itemId = itemId;
}
public Long getTypeId() {
return typeId;
}
public void setTypeId(Long typeId) {
this.typeId = typeId;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public Double getMaxValue() {
return maxValue;
}
public void setMaxValue(Double maxValue) {
this.maxValue = maxValue;
}
public Double getMinValue() {
return minValue;
}
public void setMinValue(Double minValue) {
this.minValue = minValue;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public String getSort() {
return sort;
}
public void setSort(String sort) {
this.sort = sort;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
} |
package com.polsl.edziennik.desktopclient.view.common.dialogs;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.ResourceBundle;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import com.jidesoft.swing.JideScrollPane;
import com.polsl.edziennik.desktopclient.controller.utils.FrameToolkit;
import com.polsl.edziennik.desktopclient.controller.utils.LangManager;
import com.polsl.edziennik.desktopclient.model.tables.AttendanceTableModel;
import com.polsl.edziennik.desktopclient.properties.Properties;
import com.polsl.edziennik.desktopclient.view.common.panels.button.SaveExitButtonPanel;
public class AttendancesDialog extends JDialog {
private JTable table;
private JScrollPane scrollPane;
private AttendanceTableModel tableModel;
private FrameToolkit frameToolkit = new FrameToolkit();
protected static ResourceBundle bundle = LangManager.getResource(Properties.Component);
private SaveExitButtonPanel buttonPanel;
public AttendancesDialog(AttendanceTableModel model) {
setTitle(bundle.getString("Attendances"));
Dimension preferredSize = frameToolkit.getSize();
preferredSize.setSize(30 + 140 * 2 + 270 + 40, preferredSize.getHeight());
setSize(preferredSize);
setIconImage(frameToolkit.getTitleIcon("AttendancesIcon"));
setLocationRelativeTo(null);
tableModel = model;
table = new JTable(tableModel);
// table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setRowSelectionAllowed(false);
scrollPane = new JideScrollPane(table);
scrollPane.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder(""),
BorderFactory.createEmptyBorder(0, 6, 6, 6)));
add(scrollPane, BorderLayout.CENTER);
buttonPanel = new SaveExitButtonPanel("saveChangesHint");
add(buttonPanel, BorderLayout.SOUTH);
setColumnWidths();
}
public void setColumnWidths() {
table.getColumnModel().getColumn(0).setPreferredWidth(30);
for (int i = 1; i < 5; i++) {
table.getColumnModel().getColumn(i).setPreferredWidth(130);
}
}
public JButton getSave() {
return buttonPanel.getSaveButton();
}
public JButton getCancelButton() {
return buttonPanel.getExitButton();
}
public void clearSelection() {
table.clearSelection();
}
} |
package com.pointburst.jsmusic.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.pointburst.jsmusic.R;
import com.pointburst.jsmusic.model.Media;
import java.util.ArrayList;
/**
* Created by FARHAN on 12/30/2014.
*/
public class MediaListAdapter extends BaseAdapter{
private ArrayList<Media> mMediaArrayList;
private Context mContext;
private LayoutInflater mLayoutInflater;
public MediaListAdapter(Context context,ArrayList<Media> arrayList) {
mMediaArrayList = arrayList;
mContext = context;
mLayoutInflater = LayoutInflater.from(mContext);
}
@Override
public int getCount() {
return mMediaArrayList==null?0:mMediaArrayList.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
Media media = mMediaArrayList.get(position);
if(convertView==null){
holder = new ViewHolder();
convertView = mLayoutInflater.inflate(R.layout.playlist_item, parent, false);
holder.tvTitle = (TextView)convertView.findViewById(R.id.tv_title);
holder.tvTime = (TextView)convertView.findViewById(R.id.tv_time);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.tvTitle.setText(media.getTitle());
holder.tvTime.setText(media.getDuration());
return convertView;
}
public class ViewHolder{
public TextView tvTitle;
public TextView tvTime;
}
}
|
/*
* 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 br.edul.ifsul.controle;
import br.edu.ifsul.dao.CidadeDAO;
import br.edu.ifsul.dao.PessoaDAO;
import br.edu.ifsul.dao.PosicaoDAO;
import br.edu.ifsul.dao.TimeDAO;
import br.edu.ifsul.dao.UsuarioDAO;
import br.edu.ifsul.modelo.Cidade;
import br.edu.ifsul.modelo.Jogador;
import br.edu.ifsul.modelo.Pessoa;
import br.edu.ifsul.modelo.Posicao;
import br.edu.ifsul.modelo.Time;
import br.edu.ifsul.modelo.Usuario;
import br.edu.ifsul.util.Util;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
/**
*
* @author eliel
*/
@Named(value = "controleTime")
@ViewScoped
public class ControleTime implements Serializable {
@EJB
private TimeDAO<Time> dao;
private Time objeto;
@EJB
private UsuarioDAO<Usuario> daoUsuario;
@EJB
private PessoaDAO<Pessoa> daoPessoa;
@EJB
private PosicaoDAO<Posicao> daoPosicao;
@EJB
private CidadeDAO<Cidade> daoCidade;
private Jogador jogador;
private Boolean novoJogador;
public ControleTime(){
}
public void novoJogador(){
jogador = new Jogador();
novoJogador = true;
}
public void alterarJogador(int index){
jogador = objeto.getJogadores().get(index);
novoJogador = false;
}
public void salvarJogador(){
if(novoJogador) {
objeto.adicionarJogador(jogador);
}
Util.mensagemInformacao("Jogador adicionado ou alterado com sucesso!");
}
public void removerJogador(int index){
objeto.removerJogador(index);
Util.mensagemInformacao("Jogador removido com sucesso!");
}
public String listar(){
return "/privado/time/listar?faces-redirect=true";
}
public void novo(){
objeto = new Time();
}
public void alterar(Object id){
try {
objeto = dao.getObjectByID(id);
} catch (Exception e) {
Util.mensagemInformacao("Erro ao recuperar o objeto: " + Util.getMensagemErro(e));
}
}
public void excluir(Object id){
try {
objeto = dao.getObjectByID(id);
dao.remove(objeto);
Util.mensagemInformacao("Objeto removido com sucesso!");
} catch (Exception e) {
Util.mensagemInformacao("Erro ao remover o objeto: " + Util.getMensagemErro(e));
}
}
public void salvar(){
try {
if(objeto.getId() == null){
dao.persist(objeto);
}else{
dao.merge(objeto);
}
Util.mensagemInformacao("Objeto persistido com sucesso!");
} catch (Exception e) {
Util.mensagemInformacao("Erro ao salvar o objeto: " + Util.getMensagemErro(e));
}
}
public TimeDAO<Time> getDao() {
return dao;
}
public void setDao(TimeDAO<Time> dao) {
this.dao = dao;
}
public Time getObjeto() {
return objeto;
}
public void setObjeto(Time objeto) {
this.objeto = objeto;
}
public UsuarioDAO<Usuario> getDaoUsuario() {
return daoUsuario;
}
public void setDaoUsuario(UsuarioDAO<Usuario> daoUsuario) {
this.daoUsuario = daoUsuario;
}
public PessoaDAO<Pessoa> getDaoPessoa() {
return daoPessoa;
}
public void setDaoPessoa(PessoaDAO<Pessoa> daoPessoa) {
this.daoPessoa = daoPessoa;
}
public PosicaoDAO<Posicao> getDaoPosicao() {
return daoPosicao;
}
public void setDaoPosicao(PosicaoDAO<Posicao> daoPosicao) {
this.daoPosicao = daoPosicao;
}
public CidadeDAO<Cidade> getDaoCidade() {
return daoCidade;
}
public void setDaoCidade(CidadeDAO<Cidade> daoCidade) {
this.daoCidade = daoCidade;
}
public Jogador getJogador() {
return jogador;
}
public void setJogador(Jogador jogador) {
this.jogador = jogador;
}
public Boolean getNovoJogador() {
return novoJogador;
}
public void setNovoJogador(Boolean novoJogador) {
this.novoJogador = novoJogador;
}
}
|
package com.zpjr.cunguan.ui.activity.security;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.zpjr.cunguan.R;
import com.zpjr.cunguan.common.base.BaseActivity;
/**
* Description: 手势密码解锁界面
* Autour: LF
* Date: 2017/7/24 17:01
*/
public class GestureLockActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gesture_lock);
}
}
|
package baekjoon.dp1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test_1904 {
//DP문제 메모리제이션 활용
//N>=2일때만 arr[2]=2 가 되도록 해줌으로써 런타임에러 해결
static final int NUM = 15746;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
long[] arr = new long[N+1];
arr[1] = 1;
if(N>=2) {
arr[2] = 2;
}
for(int i=3; i<=N; i++) {
arr[i] = (arr[i-1] + arr[i-2])%NUM;
}
System.out.println(arr[N]);
}
}
|
package com.demo;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
/**
* @description:
* @author: hezhichao
* @date: 2019-04-24 下午4:50
*/
public class App {
public static void main(String[] args) throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
System.out.println(111);
}
}
|
package gk.netty.com.heartbeat;
import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
/**
* netty心跳机制服务器端实现
* Project Name:NettyDemo
* @author gk
* TODO
* Date:2016年11月11日上午10:34:07
* Copyright (c) 2016, gkaigk@126.com All Rights Reserved.
* @Version 1.0
*/
public class HeartBeatServer {
private int port;//端口号
public HeartBeatServer() {
}
public HeartBeatServer(int port) {
this.port = port;
}
public void start() {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workGroup = new NioEventLoopGroup();
try {
ServerBootstrap sb = new ServerBootstrap();
sb.group(bossGroup, workGroup).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO))
.localAddress(new InetSocketAddress(port)).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch)
throws Exception {
ch.pipeline().addLast(new IdleStateHandler(5, 0, 0, TimeUnit.SECONDS));
ch.pipeline().addLast("decoder", new StringDecoder());
ch.pipeline().addLast("encoder", new StringEncoder());
ch.pipeline().addLast(new HeartBeatServerHandler());
}
}).option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
// 绑定端口,开始接收进来的连接
ChannelFuture future = sb.bind().sync();
System.out.println("Server start listen to port : " + port);
future.channel().closeFuture().sync();
} catch (Exception e) {
}finally {
workGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
public static void main(String[] args) {
new HeartBeatServer(8080).start();
}
}
|
package com.example.hawkeyetest;
import java.io.IOException;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.graphics.ImageFormat;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.Size;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
public class FrameCapture extends Activity implements SurfaceHolder.Callback, PreviewCallback {
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;
LayoutInflater controlInflater = null;
static final String TAG = "Frame Capture Activity";
@Override
protected 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.activity_frame_capture);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
controlInflater = LayoutInflater.from(getBaseContext());
View viewControl = controlInflater.inflate(R.layout.custom, null);
LayoutParams layoutParamsControl = new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
this.addContentView(viewControl, layoutParamsControl);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if(previewing){
camera.stopPreview();
previewing = false;
}
if (camera != null){
try {
camera.setPreviewDisplay(surfaceHolder);
camera.getParameters().setPreviewFormat(ImageFormat.RGB_565);
camera.startPreview();
previewing = true;
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Called when the surface is created. Releases any previously
* opened cameras and creates a single instance of the Camera
* class.
* @param holder the SurfaceHolder object created in the onCreate
* method
*/
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (camera != null) {
camera.release();
camera = null;
}
camera = Camera.open();
camera.getParameters().setPreviewFormat(ImageFormat.RGB_565);
camera.startPreview();
}
/**
* Called when the surface is destroyed (when the activity
* is ended). Stops the camera preview and releases the camera.
* @param holder the SurfaceHolder object created in the onCreate
*/
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
/**
* Inherited from the PreviewCallback interface.
*/
@Override
public void onPreviewFrame(byte[] data, Camera cam) {
Log.i(TAG, "Frame logged");
}
/**
* Called when the Start button is clicked. Begins capturing
* frames at 30 fps in the RGB format and stores the RGB values
* of each frame captured in an array.
*/
public void startCapture(View view) {
Parameters parameters = camera.getParameters();
Size size = parameters.getPreviewSize();
}
/**
* Called when the Stop button is clicked. Stops capturing
* frames and writes the array to a csv file.
*/
public void stopCapture(View view) {
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.frame_capture, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
} |
package com.techlab.dip.test;
import com.techlab.dip.TaxCalculator;
public class TaxCalculatorTest {
public static void main(String[] args) {
TaxCalculator calc = new TaxCalculator(0);
System.out.println(calc.calculateTax(5, 2));
System.out.println(calc.calculateTax(0, 0));
}
}
|
package com.tencent.mm.plugin.luckymoney.a;
import android.text.TextUtils;
import com.tencent.mm.bt.h.d;
import com.tencent.mm.g.a.tm;
import com.tencent.mm.model.ar;
import com.tencent.mm.model.p;
import com.tencent.mm.platformtools.ab;
import com.tencent.mm.plugin.luckymoney.b.aj;
import com.tencent.mm.plugin.luckymoney.b.b;
import com.tencent.mm.plugin.luckymoney.b.c;
import com.tencent.mm.plugin.luckymoney.b.e;
import com.tencent.mm.plugin.luckymoney.b.g;
import com.tencent.mm.plugin.luckymoney.b.o;
import com.tencent.mm.pluginsdk.model.app.ap;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.bl;
import com.tencent.mm.sdk.platformtools.x;
import java.io.File;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
public class a implements ar {
private com.tencent.mm.model.bv.a hTD = new com.tencent.mm.model.bv.a() {
public final void a(com.tencent.mm.ab.d.a aVar) {
Map z = bl.z(ab.a(aVar.dIN.rcl), "sysmsg");
x.i("MicroMsg.SubCoreLuckyMoney", "helios::::mPayMsgListener");
if (z == null) {
x.e("MicroMsg.SubCoreLuckyMoney", "Resolve msg error");
return;
}
if ("14".equals((String) z.get(".sysmsg.paymsg.PayMsgType"))) {
String decode = URLDecoder.decode((String) z.get(".sysmsg.paymsg.appmsgcontent"));
if (TextUtils.isEmpty(decode)) {
x.e("MicroMsg.SubCoreLuckyMoney", "msgxml illegal");
return;
}
Map z2 = bl.z(decode, "msg");
if (z2 == null) {
x.e("MicroMsg.SubCoreLuckyMoney", "Resolve appmsgxml error");
return;
}
String str = (String) z2.get(".msg.appmsg.wcpayinfo.paymsgid");
if (bi.oW(str)) {
x.e("MicroMsg.SubCoreLuckyMoney", "paymsgid is null");
return;
}
String str2 = (String) z.get(".sysmsg.paymsg.tousername");
if (bi.oW(decode) || bi.oW(str2)) {
x.e("MicroMsg.SubCoreLuckyMoney", "onRecieveMsg get a illegal msg,which content or toUserName is null");
} else if (a.this.baw().Gb(str)) {
x.i("MicroMsg.SubCoreLuckyMoney", "insert a local msg for luckymoney");
if (!o.C(decode, str2, 1)) {
a.this.baw().Gc(str);
}
}
}
}
};
private e kKF;
private g kKG;
private c kKH = new c();
private aj kKI;
private com.tencent.mm.sdk.b.c<tm> kKJ = new 2(this);
public static a bat() {
return (a) p.v(a.class);
}
public a() {
File file = new File(bav());
if (!file.exists()) {
file.mkdir();
}
file = new File(com.tencent.mm.compatible.util.e.dgu);
if (!file.exists()) {
file.mkdir();
}
}
public final HashMap<Integer, d> Ci() {
return null;
}
public final void gi(int i) {
}
public final void bo(boolean z) {
}
public final void bn(boolean z) {
ap ccb = ap.ccb();
if (com.tencent.mm.kernel.g.Eg().Dx()) {
com.tencent.mm.plugin.ac.a.bmi().a(4, ccb);
com.tencent.mm.kernel.g.Ek();
com.tencent.mm.kernel.g.Eh().dpP.a(1060, ccb);
}
((com.tencent.mm.plugin.messenger.foundation.a.o) com.tencent.mm.kernel.g.n(com.tencent.mm.plugin.messenger.foundation.a.o.class)).getSysCmdMsgExtension().a("paymsg", this.hTD, true);
boolean z2 = false;
com.tencent.mm.kernel.g.Ek();
if (System.currentTimeMillis() - com.tencent.mm.kernel.g.Ei().DT().Dj(352276) >= 43200000) {
z2 = true;
}
x.i("MicroMsg.SubCoreLuckyMoney", "isTime=" + z2 + ", isUpdate=" + z);
if (z || z2) {
x.i("MicroMsg.SubCoreLuckyMoney", "get service applist");
ap.ccb().eT(ad.getContext());
}
com.tencent.mm.sdk.b.a.sFg.b(this.kKH);
com.tencent.mm.sdk.b.a.sFg.b(this.kKJ);
this.kKI = new aj();
b.init();
}
public final void onAccountRelease() {
ap ccb = ap.ccb();
if (com.tencent.mm.kernel.g.Eg().Dx()) {
com.tencent.mm.plugin.ac.a.bmi().b(4, ccb);
com.tencent.mm.kernel.g.Ek();
com.tencent.mm.kernel.g.Eh().dpP.b(1060, ccb);
ccb.qAT = false;
ccb.qAU = false;
}
((com.tencent.mm.plugin.messenger.foundation.a.o) com.tencent.mm.kernel.g.n(com.tencent.mm.plugin.messenger.foundation.a.o.class)).getSysCmdMsgExtension().b("paymsg", this.hTD, true);
synchronized (this) {
this.kKG = null;
}
com.tencent.mm.sdk.b.a.sFg.c(this.kKH);
com.tencent.mm.sdk.b.a.sFg.c(this.kKJ);
if (this.kKI != null) {
aj ajVar = this.kKI;
com.tencent.mm.sdk.b.a.sFg.c(ajVar.kRJ);
if (ajVar.kRG != null) {
com.tencent.mm.kernel.g.Ek();
com.tencent.mm.kernel.g.Eh().dpP.c(ajVar.kRG);
ajVar.kRG = null;
}
if (ajVar.kRH != null) {
com.tencent.mm.kernel.g.Ek();
com.tencent.mm.kernel.g.Eh().dpP.c(ajVar.kRH);
ajVar.kRH = null;
}
}
b.Wa();
}
public static e bau() {
com.tencent.mm.kernel.g.Eg().Ds();
if (bat().kKF == null) {
bat().kKF = new e();
}
return bat().kKF;
}
public static String bav() {
if (com.tencent.mm.kernel.g.Eg().Dx()) {
return com.tencent.mm.plugin.p.c.Gb() + "luckymoney";
}
return "";
}
public final synchronized g baw() {
if (this.kKG == null) {
this.kKG = new g();
}
return this.kKG;
}
}
|
package cn.edu.zucc.music.service.impl;
import cn.edu.zucc.music.dao.UserMapper;
import cn.edu.zucc.music.model.User;
import cn.edu.zucc.music.service.UserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Resource
UserMapper userMapper;
@Override
public int addUser(User user) {
userMapper.insert(user);
return 1;
}
@Override
public int deleteUser(User user) {
return 0;
}
@Override
public int updateUser(User user) {
return 0;
}
@Override
public User findById(String userId) {
return userMapper.selectByPrimaryKey(userId);
}
@Override
public User findByName(String userName) { return userMapper.selectByUserName(userName);}
@Override
public String findMaxId() {
return userMapper.findMaxId();
}
@Override
public List<User> findAll() {
return null;
}
}
|
package mop.main.java.database.model.queryable;
public class Episode extends Queryable {
private int episodeId, episodeNumber;
private String name, fileLocation;
public int getEpisodeId() {
return episodeId;
}
public int getEpisodeNumber() {
return episodeNumber;
}
public String getName() {
return name;
}
public String getFileLocation() {
return fileLocation;
}
public void setEpisodeId(Integer episodeId) {
this.episodeId = episodeId;
}
public void setEpisodeNumber(Integer episodeNumber) {
this.episodeNumber = episodeNumber;
}
public void setName(String name) {
this.name = name;
}
public void setFileLocation(String fileLocation) {
this.fileLocation = fileLocation;
}
}
|
package com.lbs.index;
import java.io.File;
public interface Searcher {
int search(File indexDir, String q) throws Exception;
}
|
package org.corbin.common.service;
import org.corbin.common.base.service.BaseService;
import org.corbin.common.entity.SongStatisticsDayLog;
import org.corbin.common.repository.CollectInfoRepository;
import org.corbin.common.repository.CommentInfoRepository;
import org.corbin.common.repository.SingerInfoRepository;
import org.corbin.common.repository.SongInfoRepository;
import org.corbin.common.repository.SongStatisticsDayLogRepository;
import org.corbin.common.repository.UserInfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;
@Service
public class SongStatisticsDayLogService extends BaseService<SongStatisticsDayLog,Long> {
@Autowired
private CollectInfoRepository collectInfoRepository;
@Autowired
private CommentInfoRepository commentInfoRepository;
@Autowired
private SingerInfoRepository singerInfoRepository;
@Autowired
private SongInfoRepository songInfoRepository;
@Autowired
private UserInfoRepository userInfoRepository;
@Autowired
private SongStatisticsDayLogRepository songStatisticsDayLogRepository;
public SongStatisticsDayLog updateSongStatisicsDayLog(@NonNull SongStatisticsDayLog songStatisticsDayLog) {
return songStatisticsDayLogRepository.saveAndFlush(songStatisticsDayLog);
}
/**
* 更新点赞次数
* @param songId
* @return
*/
public SongStatisticsDayLog updateStarNum(@NonNull Long songId){
//记录今天的点赞数
SongStatisticsDayLog songStatisticsDayLog= songStatisticsDayLogRepository.findBySongId(songId);
if (songStatisticsDayLog==null){
songStatisticsDayLog=new SongStatisticsDayLog();
songStatisticsDayLog.setSongId(songId);
}
Integer todayStartTimes=songStatisticsDayLog.getStarTimesToday();
todayStartTimes=todayStartTimes==null?0:todayStartTimes;
songStatisticsDayLog.setStarTimesToday(todayStartTimes+1);
songStatisticsDayLogRepository.save(songStatisticsDayLog);
return songStatisticsDayLog;
}
/**
* 更新今日收藏数
* @param songId
* @return
*/
public SongStatisticsDayLog updateCollectNum(@NonNull Long songId){
//记录今天的收藏数
SongStatisticsDayLog songStatisticsDayLog= songStatisticsDayLogRepository.findBySongId(songId);
if (songStatisticsDayLog==null){
songStatisticsDayLog=new SongStatisticsDayLog();
songStatisticsDayLog.setSongId(songId);
}
Integer todayCollectTimes=songStatisticsDayLog.getCollectTimesToday();
todayCollectTimes=todayCollectTimes==null?0:todayCollectTimes;
songStatisticsDayLog.setCollectTimesToday(todayCollectTimes+1);
songStatisticsDayLogRepository.save(songStatisticsDayLog);
return songStatisticsDayLog;
}
/**
* 更新播放次数
* @param songId
* @return
*/
public SongStatisticsDayLog updatePlayNum(@NonNull Long songId){
//记录今天的播放数
SongStatisticsDayLog songStatisticsDayLog= songStatisticsDayLogRepository.findBySongId(songId);
if (songStatisticsDayLog==null){
songStatisticsDayLog=new SongStatisticsDayLog();
songStatisticsDayLog.setSongId(songId);
}
Integer todayPlayTimes=songStatisticsDayLog.getPlayTimesToday();
todayPlayTimes=todayPlayTimes==null?0:todayPlayTimes;
songStatisticsDayLog.setPlayTimesToday(todayPlayTimes+1);
songStatisticsDayLogRepository.save(songStatisticsDayLog);
return songStatisticsDayLog;
}
}
|
package com.hcl.dmu.sowpes.dao;
import java.util.List;
import com.hcl.dmu.clientprocess.vo.CandidateClientProcessVo;
import com.hcl.dmu.sowpes.vo.CandidateSowPesVo;
public interface CandidateSowPesDao {
List<CandidateClientProcessVo> getAllClientSelectedDetails();
public int updateSelectedDetails(CandidateSowPesVo candidateSowPesVo);
int insertSelectedCandidateDetails(List<CandidateSowPesVo> candidateSowPesVoList);
List<CandidateSowPesVo> getCandidateSowPesDetails();
int updateCandidateSowPesDetails(List<CandidateSowPesVo> candidateSowPesVoList);
}
|
package com.example.coronapp;
import com.example.coronapp.entity.Humain;
import com.example.coronapp.enumeration.EtatDeSante;
import com.example.coronapp.service.HumainService;
import com.example.coronapp.utils.HunainUtils;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringRunner.class)
@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "javax.xml.transform.*", "org.xml.*", "javax.management.*", "javax.net.ssl.*", "com.sun.org.apache.xalan.internal.xsltc.trax.*"})
@PrepareForTest(HunainUtils.class)
public class PowerMockTest {
@Autowired
private HumainService humainService;
//Test junit 4 car powermock n'est pas compatible avec Junit 5
@Test
public void changerEtatDeSanteUnePersonneTest() {
Humain humain = Humain.builder().etat(EtatDeSante.MALADE).build();
PowerMockito.mockStatic(HunainUtils.class);
PowerMockito.when(HunainUtils.changeEtatDeSanteHumain(humain, EtatDeSante.SAIN))
.thenReturn(Humain.builder().etat(EtatDeSante.SAIN).build());
Assertions.assertThat(humainService.changerEtatDeSanteUnePersonne(humain, EtatDeSante.SAIN))
.isEqualToComparingFieldByField(humain);
}
}
|
package matth.dungeon.RandomEventTile;
import android.content.Context;
import matth.dungeon.Utility.FileUtility;
import matth.dungeon.Utility.PlayerInfoPassUtility;
public class HealthPotionEvent extends RandomEvent {
public HealthPotionEvent(PlayerInfoPassUtility playerInfoPassUtility, Context con) {
super(playerInfoPassUtility, con);
}
@Override
public String textDescription() {
return "Your health has been restored";
}
@Override
public void immediateEffect() {
setText();
playerInfoPassUtility.setHealth(playerInfoPassUtility.getMaxHealth());
FileUtility.savePlayer(playerInfoPassUtility, con);
displayLeaveButton();
}
}
|
package errors;
@SuppressWarnings("serial")
public class BadReturnValueError extends BaseException {
}
|
package de.jmda.app.cgol.xy.fx.cdi.view.grid.shapetemplate;
import org.junit.Test;
import de.jmda.app.cgol.xy.fx.cdi.view.grid.shapetemplate.CircleTemplatePopulated;
import de.jmda.app.cgol.xy.fx.cdi.view.grid.shapetemplate.CircleTemplateUnpopulated;
import javafx.scene.shape.Circle;
public class JUTShapeTemplatesCreation
{
@Test(expected=IllegalArgumentException.class)
public void canNotCreatePopulatedShapeTemplateWithNullShape()
{
new CircleTemplatePopulated(null);
}
@Test public void canCreatePopulatedShapeTemplateWithNonNullShape()
{
new CircleTemplatePopulated(new Circle());
}
@Test public void canCreateUnpopulatedShapeTemplateWithNullShape()
{
new CircleTemplateUnpopulated(null);
}
} |
package mx.com.azaelmorales.yurtaapp;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONObject;
public class MaterialEditarActivity extends AppCompatActivity implements Response.Listener<JSONObject>,Response.ErrorListener{
Button btnaceptar,btncancelar;
EditText textViewNombre,textViewFN,textViewTel;
String cod="",nomb=" ",tipo=" ",marca=" ";
RequestQueue rq;
JsonRequest jrq;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_material_editar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_editar_material);
setSupportActionBar(toolbar);
toolbar.setTitle("Editar empleado");
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
TextView textViewRFC = (TextView)findViewById(R.id.tVDetEmRFC);
textViewNombre = (EditText) findViewById(R.id.tVDetEmNombre);
textViewFN = (EditText) findViewById(R.id.tVdDetEmFecha);
textViewTel = (EditText) findViewById(R.id.tVdDetEmTel);
btnaceptar=(Button)findViewById(R.id.btn_add_material_aceptar);
btncancelar=(Button)findViewById(R.id.btn_add_material_cancelar);
btncancelar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
btnaceptar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cargardatos();
actualizar();
}
});
Intent intent = getIntent();
Bundle b = intent.getExtras();
if(b!=null){
cod= b.getString("CODIGO");
textViewRFC.setText("codigo:" + b.getString("CODIGO"));
textViewNombre.setText(b.getString("NOMBRE"));
textViewFN.setText(b.getString("MARCA"));
textViewTel.setText(b.getString("TIPO"));
}
rq = Volley.newRequestQueue(this);
}
private void cargardatos(){
nomb=textViewNombre.getText().toString();
marca=textViewFN.getText().toString();
tipo=textViewTel.getText().toString();
}
private void actualizar(){ //se ejecuta la solicitud al web service alojado en el servidor
//http://dissymmetrical-diox.xyz/registrom.php?nombre=ppp&tipo=ttt&marca=mmm&estado_m=1
String url ="http://dissymmetrical-diox.xyz/actualizarm.php?codigoh="+cod+"&nombre="+nomb+"&tipo="+tipo+
"&marca="+marca+"&estado_m=1";
url=url.replace(" ","%");
jrq = new JsonObjectRequest(Request.Method.GET,url,null,this,this);
rq.add(jrq);
}
@Override
public void onErrorResponse(VolleyError error) {
Toast toast1 =
Toast.makeText(this,
"Error al cargar los datos"+ error.getMessage(), Toast.LENGTH_LONG);
toast1.show();
}
@Override
public void onResponse(JSONObject response) {
Toast toast1 =
Toast.makeText(this,
"datos actualizados", Toast.LENGTH_LONG);
toast1.show();
}
}
|
package com.layla.modules;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.*;
import android.view.KeyEvent;
import android.view.View;
import android.widget.*;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.layla.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class Chat extends AppCompatActivity
{
private String secondUser;
private List<ChatMessage> messages = new ArrayList<>();
private MessageAdapter arrayAdapter;
static final int POLL_INTERVAL = 1;
private Timer timer;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getUsername();
retainMessages();
setContentView(R.layout.activity_chat);
setToolbar();
setMessageAdapter();
refreshMessages();
}
@Override
protected void onDestroy() {
super.onDestroy();
timer.cancel();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode == KeyEvent.KEYCODE_BACK) finish();
return super.onKeyDown(keyCode, event);
}
public void refreshMessages()
{
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
retainMessages();
}
}, 1000, 1000);
}
public void retainMessages()
{
ParseQuery<ParseObject> firstQuery = new ParseQuery<>("ChatMessage");
firstQuery.whereEqualTo("sender", ParseUser.getCurrentUser().getUsername());
firstQuery.whereEqualTo("recipient", secondUser);
ParseQuery<ParseObject> secondQuery = new ParseQuery<>("ChatMessage");
secondQuery.whereEqualTo("recipient", ParseUser.getCurrentUser().getUsername());
secondQuery.whereEqualTo("sender", secondUser);
List<ParseQuery<ParseObject>> queries = new ArrayList<>();
queries.add(firstQuery);
queries.add(secondQuery);
ParseQuery<ParseObject> query = ParseQuery.or(queries);
query.orderByAscending("createdAt");
query.findInBackground((objects, e) ->
{
if(e == null)
{
if(objects.size() > 0)
{
messages.clear();
for(ParseObject message : objects)
{
String messageContent = message.getString("message");
if(message.getString("sender").equals(ParseUser.getCurrentUser().getUsername()))
{
ChatMessage m = new ChatMessage(ParseUser.getCurrentUser().getUsername(), messageContent, true);
appendMessage(m);
}
else
{
ChatMessage m = new ChatMessage(secondUser, messageContent, false);
appendMessage(m);
}
}
arrayAdapter.notifyDataSetChanged();
}
}
else
{
Log.e("LAYLA", e.getMessage());
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
public void sendChat(View view)
{
final EditText inputMessage = findViewById(R.id.inputMsg);
final ParseObject message = new ParseObject("ChatMessage");
final String messageContent = inputMessage.getText().toString();
message.put("sender", ParseUser.getCurrentUser().getUsername());
message.put("recipient", secondUser);
message.put("message", messageContent);
inputMessage.setText("");
message.saveInBackground(e ->
{
if(e == null)
{
appendMessage(new ChatMessage(ParseUser.getCurrentUser().getUsername(), messageContent, true));
}
else
{
Log.e("LAYLA", e.getMessage());
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
public void setToolbar()
{
Toolbar myToolbar = findViewById(R.id.my_toolbar);
myToolbar.setTitle(getString(R.string.chat_with)+" "+secondUser);
setSupportActionBar(myToolbar);
myToolbar.setNavigationIcon(ContextCompat.getDrawable(this, R.drawable.ic_arrow_back_white_24dp));
myToolbar.setNavigationOnClickListener(v -> finish());
}
public void getUsername()
{
secondUser = getIntent().getStringExtra("username");
}
public void setMessageAdapter()
{
ListView listViewMessages = findViewById(R.id.list_view_messages);
arrayAdapter = new MessageAdapter(this, messages);
listViewMessages.setAdapter(arrayAdapter);
}
private void appendMessage(final ChatMessage message)
{
runOnUiThread(() ->
{
messages.add(message);
arrayAdapter.notifyDataSetChanged();
});
}
}
|
package vanadis.objectmanagers;
/**
* Common interface for simple status reports, providing some reflection into
* an {@link vanadis.ext.ObjectManager}.
*
* @see ObjectManager#getExposedServices()
* @see ObjectManager#getInjectedServices()
* @see ObjectManager#getConfigureSummaries()
*/
public interface ManagedFeatureSummary extends Iterable<InstanceSummary> {
boolean isActive();
String getName();
String getFeatureClass();
}
|
package co.staruml.test;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class CanvasSWTTest {
public static void main(String [] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
shell.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent event) {
co.staruml.graphics.Canvas canvas = new co.staruml.swt.CanvasSWT(event.gc);
((co.staruml.swt.CanvasSWT) canvas).setGC(event.gc);
canvas.rectangle(10, 10, 200, 200);
}
});
shell.setBounds(10, 10, 500, 500);
shell.open ();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
display.dispose();
}
}
|
package com.cngl.bilet.service.impl;
import java.util.List;
import com.cngl.bilet.dto.EngelliRotaRequestDto;
import com.cngl.bilet.dto.EngelliRotaResponseDto;
import com.cngl.bilet.entity.EngelliRota;
import com.cngl.bilet.repository.EngelliRotaRepository;
import com.cngl.bilet.repository.HavayoluRepository;
import com.cngl.bilet.service.EngelliRotaService;
import org.modelmapper.ModelMapper;
import org.modelmapper.TypeToken;
import org.springframework.stereotype.Service;
@Service
public class EngelliRotaServiceImpl implements EngelliRotaService{
private final EngelliRotaRepository engelliRotaRepository;
private final HavayoluRepository havayoluRepository;
private final ModelMapper modelMapper;
public EngelliRotaServiceImpl(EngelliRotaRepository engelliRotaRepository,
HavayoluRepository havayoluRepository,
ModelMapper modelMapper) {
this.engelliRotaRepository=engelliRotaRepository;
this.havayoluRepository=havayoluRepository;
this.modelMapper = modelMapper;
}
public List<EngelliRotaResponseDto> tumunuGetir(){
return modelMapper.map(engelliRotaRepository.findAll(),
new TypeToken<List<EngelliRotaResponseDto>>() {}.getType());
}
public EngelliRotaResponseDto idYeGoreGetir(Long id) throws Exception {
return modelMapper.
map(engelliRotaRepository.findById(id).orElseThrow(()-> new Exception("ff")), EngelliRotaResponseDto.class);
}
public EngelliRotaResponseDto kaydetVeyaGuncelle(EngelliRotaRequestDto engelliRotaRequestDto){
return modelMapper.map(engelliRotaRepository.
save(modelMapper.map(engelliRotaRequestDto,EngelliRota.class)),EngelliRotaResponseDto.class);
}
public EngelliRotaResponseDto kaydet(EngelliRotaRequestDto engelliRotaRequestDto){
EngelliRota engelliRota=modelMapper.map(engelliRotaRequestDto,EngelliRota.class);
if(!engelliRotaRequestDto.getHavalimaniId().isEmpty())
engelliRota.setHavayollari(havayoluRepository.findAllById(engelliRotaRequestDto.getHavalimaniId()));
return modelMapper.map(engelliRotaRepository.save(engelliRota),EngelliRotaResponseDto.class);
}
public EngelliRotaResponseDto guncelle(EngelliRotaRequestDto engelliRotaRequestDto)throws Exception{
EngelliRota engelliRota=engelliRotaRepository.findById(engelliRotaRequestDto.getId())
.orElseThrow(()->new Exception("Engelli Rota bulanamadı"));
engelliRota.setHavayollari(havayoluRepository.findAllById(engelliRotaRequestDto.getHavalimaniId()));
return modelMapper.map(engelliRotaRepository.
save(modelMapper.map(engelliRotaRequestDto,EngelliRota.class)),EngelliRotaResponseDto.class);
}
public void sil(Long id) throws Exception {
engelliRotaRepository.delete(
engelliRotaRepository.findById(id).orElseThrow(()->new Exception("Engelli Rota bulanamadı"))
);
}
} |
package com.bluemingo.bluemingo.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.bluemingo.bluemingo.domain.AdvVO;
import com.bluemingo.bluemingo.generic.GenericDAO;
import com.bluemingo.bluemingo.generic.GenericServiceImpl;
import com.bluemingo.bluemingo.persistence.AdvDAO;
/** Last Edit 2017-02-11
* AdvVO - AdvDAO - AdvService - AdvController
* 광고 리스트 페이지에서 사용됨
*
*/
@Service("advService")
public class AdvServiceImpl extends GenericServiceImpl<AdvVO, Integer> implements AdvService{
private static final Logger logger = LoggerFactory.getLogger(AdvServiceImpl.class);
@Autowired
private AdvDAO advDao;
public AdvServiceImpl() {
}
@Autowired
public AdvServiceImpl(@Qualifier("advDao") GenericDAO<AdvVO, Integer> genericDao) {
super(genericDao);
this.advDao = (AdvDAO) genericDao;
}
public void setAdvDao(AdvDAO advDao) {
this.advDao = advDao;
}
@Override
public void getData() {
// TODO Auto-generated method stub
}
/* �߰� ��� ��
* Generic���� �����ϴ� �⺻ ��� �ܿ� �ʿ��� ����� ���Ѵ�.
*/
//test
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapred;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.server.jobtracker.JTConfig;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.AccessControlException;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.util.DiskChecker.DiskErrorException;
/**
* Persists and retrieves the Job info of a job into/from DFS.
* <p/>
* If the retain time is zero jobs are not persisted.
* <p/>
* A daemon thread cleans up job info files older than the retain time
* <p/>
* The retain time can be set with the 'persist.jobstatus.hours'
* configuration variable (it is in hours).
*/
class CompletedJobStatusStore implements Runnable {
private boolean active;
private String jobInfoDir;
private long retainTime;
private FileSystem fs;
private static final String JOB_INFO_STORE_DIR = "/jobtracker/jobsInfo";
private ACLsManager aclsManager;
public static final Log LOG =
LogFactory.getLog(CompletedJobStatusStore.class);
private static long HOUR = 1000 * 60 * 60;
private static long SLEEP_TIME = 1 * HOUR;
final static FsPermission JOB_STATUS_STORE_DIR_PERMISSION = FsPermission
.createImmutable((short) 0750); // rwxr-x--
CompletedJobStatusStore(Configuration conf, ACLsManager aclsManager)
throws IOException {
active =
conf.getBoolean(JTConfig.JT_PERSIST_JOBSTATUS, true);
if (active) {
retainTime =
conf.getInt(JTConfig.JT_PERSIST_JOBSTATUS_HOURS, 1) * HOUR;
jobInfoDir =
conf.get(JTConfig.JT_PERSIST_JOBSTATUS_DIR, JOB_INFO_STORE_DIR);
Path path = new Path(jobInfoDir);
// set the fs
this.fs = path.getFileSystem(conf);
if (!fs.exists(path)) {
if (!fs.mkdirs(path, new FsPermission(JOB_STATUS_STORE_DIR_PERMISSION))) {
throw new IOException(
"CompletedJobStatusStore mkdirs failed to create "
+ path.toString());
}
} else {
FileStatus stat = fs.getFileStatus(path);
FsPermission actual = stat.getPermission();
if (!stat.isDir())
throw new DiskErrorException("not a directory: "
+ path.toString());
FsAction user = actual.getUserAction();
if (!user.implies(FsAction.READ))
throw new DiskErrorException("directory is not readable: "
+ path.toString());
if (!user.implies(FsAction.WRITE))
throw new DiskErrorException("directory is not writable: "
+ path.toString());
}
if (retainTime == 0) {
// as retain time is zero, all stored jobstatuses are deleted.
deleteJobStatusDirs();
}
this.aclsManager = aclsManager;
LOG.info("Completed job store activated/configured with retain-time : "
+ retainTime + " , job-info-dir : " + jobInfoDir);
} else {
LOG.info("Completed job store is inactive");
}
}
/**
* Indicates if job status persistency is active or not.
*
* @return TRUE if active, FALSE otherwise.
*/
public boolean isActive() {
return active;
}
public void run() {
if (retainTime > 0) {
while (true) {
deleteJobStatusDirs();
try {
Thread.sleep(SLEEP_TIME);
}
catch (InterruptedException ex) {
break;
}
}
}
}
private void deleteJobStatusDirs() {
try {
long currentTime = JobTracker.getClock().getTime();
//noinspection ForLoopReplaceableByForEach
for (FileStatus jobInfo : fs.listStatus(new Path(jobInfoDir))) {
try {
if ((currentTime - jobInfo.getModificationTime()) > retainTime) {
LOG.info("Retiring job status from the store [" + jobInfo.getPath()
+ "]");
fs.delete(jobInfo.getPath(), true);
}
}
catch (IOException ie) {
LOG.warn("Could not do housekeeping for [ " +
jobInfo.getPath() + "] job info : " + ie.getMessage(), ie);
}
}
}
catch (IOException ie) {
LOG.warn("Could not obtain job info files : " + ie.getMessage(), ie);
}
}
private Path getInfoFilePath(JobID jobId) {
return new Path(jobInfoDir, jobId + ".info");
}
/**
* Persists a job in DFS.
*
* @param job the job about to be 'retired'
*/
public void store(JobInProgress job) {
if (active && retainTime > 0) {
JobID jobId = job.getStatus().getJobID();
Path jobStatusFile = getInfoFilePath(jobId);
try {
FSDataOutputStream dataOut = fs.create(jobStatusFile);
job.getStatus().write(dataOut);
job.getProfile().write(dataOut);
job.getCounters().write(dataOut);
TaskCompletionEvent[] events =
job.getTaskCompletionEvents(0, Integer.MAX_VALUE);
dataOut.writeInt(events.length);
for (TaskCompletionEvent event : events) {
event.write(dataOut);
}
dataOut.close();
} catch (IOException ex) {
LOG.warn("Could not store [" + jobId + "] job info : " +
ex.getMessage(), ex);
try {
fs.delete(jobStatusFile, true);
}
catch (IOException ex1) {
//ignore
}
}
}
}
private FSDataInputStream getJobInfoFile(JobID jobId) throws IOException {
Path jobStatusFile = getInfoFilePath(jobId);
return (fs.exists(jobStatusFile)) ? fs.open(jobStatusFile) : null;
}
private JobStatus readJobStatus(FSDataInputStream dataIn) throws IOException {
JobStatus jobStatus = new JobStatus();
jobStatus.readFields(dataIn);
return jobStatus;
}
private JobProfile readJobProfile(FSDataInputStream dataIn)
throws IOException {
JobProfile jobProfile = new JobProfile();
jobProfile.readFields(dataIn);
return jobProfile;
}
private Counters readCounters(FSDataInputStream dataIn) throws IOException {
Counters counters = new Counters();
counters.readFields(dataIn);
return counters;
}
private TaskCompletionEvent[] readEvents(FSDataInputStream dataIn,
int offset, int len)
throws IOException {
int size = dataIn.readInt();
if (offset > size) {
return TaskCompletionEvent.EMPTY_ARRAY;
}
if (offset + len > size) {
len = size - offset;
}
TaskCompletionEvent[] events = new TaskCompletionEvent[len];
for (int i = 0; i < (offset + len); i++) {
TaskCompletionEvent event = new TaskCompletionEvent();
event.readFields(dataIn);
if (i >= offset) {
events[i - offset] = event;
}
}
return events;
}
/**
* This method retrieves JobStatus information from DFS stored using
* store method.
*
* @param jobId the jobId for which jobStatus is queried
* @return JobStatus object, null if not able to retrieve
*/
public JobStatus readJobStatus(JobID jobId) {
JobStatus jobStatus = null;
if (null == jobId) {
LOG.warn("Could not read job status for null jobId");
return null;
}
if (active) {
try {
FSDataInputStream dataIn = getJobInfoFile(jobId);
if (dataIn != null) {
jobStatus = readJobStatus(dataIn);
dataIn.close();
}
} catch (IOException ex) {
LOG.warn("Could not read [" + jobId + "] job status : " + ex, ex);
}
}
return jobStatus;
}
/**
* This method retrieves JobProfile information from DFS stored using
* store method.
*
* @param jobId the jobId for which jobProfile is queried
* @return JobProfile object, null if not able to retrieve
*/
public JobProfile readJobProfile(JobID jobId) {
JobProfile jobProfile = null;
if (active) {
try {
FSDataInputStream dataIn = getJobInfoFile(jobId);
if (dataIn != null) {
readJobStatus(dataIn);
jobProfile = readJobProfile(dataIn);
dataIn.close();
}
} catch (IOException ex) {
LOG.warn("Could not read [" + jobId + "] job profile : " + ex, ex);
}
}
return jobProfile;
}
/**
* This method retrieves Counters information from file stored using
* store method.
*
* @param jobId the jobId for which Counters is queried
* @return Counters object, null if not able to retrieve
* @throws AccessControlException
*/
public Counters readCounters(JobID jobId) throws AccessControlException {
Counters counters = null;
if (active) {
try {
FSDataInputStream dataIn = getJobInfoFile(jobId);
if (dataIn != null) {
JobStatus jobStatus = readJobStatus(dataIn);
JobProfile profile = readJobProfile(dataIn);
String queue = profile.getQueueName();
// authorize the user for job view access
aclsManager.checkAccess(jobStatus,
UserGroupInformation.getCurrentUser(), queue,
Operation.VIEW_JOB_COUNTERS);
counters = readCounters(dataIn);
dataIn.close();
}
} catch (AccessControlException ace) {
throw ace;
} catch (IOException ex) {
LOG.warn("Could not read [" + jobId + "] job counters : " + ex, ex);
}
}
return counters;
}
/**
* This method retrieves TaskCompletionEvents information from DFS stored
* using store method.
*
* @param jobId the jobId for which TaskCompletionEvents is queried
* @param fromEventId events offset
* @param maxEvents max number of events
* @return TaskCompletionEvent[], empty array if not able to retrieve
*/
public TaskCompletionEvent[] readJobTaskCompletionEvents(JobID jobId,
int fromEventId,
int maxEvents) {
TaskCompletionEvent[] events = TaskCompletionEvent.EMPTY_ARRAY;
if (active) {
try {
FSDataInputStream dataIn = getJobInfoFile(jobId);
if (dataIn != null) {
readJobStatus(dataIn);
readJobProfile(dataIn);
readCounters(dataIn);
events = readEvents(dataIn, fromEventId, maxEvents);
dataIn.close();
}
} catch (IOException ex) {
LOG.warn("Could not read [" + jobId + "] job events : " + ex, ex);
}
}
return events;
}
}
|
package com.duanxr.yith.easy;
/**
* @author Duanran 2019/1/24 0024
*/
public class LicenseKeyFormatting {
/**
* You are given a license key represented as a string S which consists only alphanumeric
* character and dashes. The string is separated into N+1 groups by N dashes.
*
* Given a number K, we would want to reformat the strings such that each group contains exactly K
* characters, except for the first group which could be shorter than K, but still must contain at
* least one character. Furthermore, there must be a dash inserted between two groups and all
* lowercase letters should be converted to uppercase.
*
* Given a non-empty string S and a number K, format the string according to the rules described
* above.
*
* Example 1:
*
* Input: S = "5F3Z-2e-9-w", K = 4
*
* Output: "5F3Z-2E9W"
*
* Explanation: The string S has been split into two parts, each part has 4 characters.
*
* Note that the two extra dashes are not needed and can be removed.
*
* Example 2:
*
* Input: S = "2-5g-3-J", K = 2
*
* Output: "2-5G-3J"
*
* Explanation: The string S has been split into three parts, each part has 2 characters except
* the first part as it could be shorter as mentioned above.
*
* Note:
*
* The length of string S will not exceed 12,000, and K is a positive integer.
*
* String S consists only of alphanumerical characters (a-z and/or A-Z and/or 0-9) and dashes(-).
*
* String S is non-empty.
*
* 给定一个密钥字符串S,只包含字母,数字以及 '-'(破折号)。N 个 '-' 将字符串分成了 N+1 组。给定一个数字 K,重新格式化字符串,除了第一个分组以外,每个分组要包含 K
* 个字符,第一个分组至少要包含 1 个字符。两个分组之间用 '-'(破折号)隔开,并且将所有的小写字母转换为大写字母。
*
* 给定非空字符串 S 和数字 K,按照上面描述的规则进行格式化。
*
* 示例 1:
*
* 输入:S = "5F3Z-2e-9-w", K = 4
*
* 输出:"5F3Z-2E9W"
*
* 解释:字符串 S 被分成了两个部分,每部分 4 个字符;
*
* 注意,两个额外的破折号需要删掉。
*
* 示例 2:
*
* 输入:S = "2-5g-3-J", K = 2
*
* 输出:"2-5G-3J"
*
* 解释:字符串 S 被分成了 3 个部分,按照前面的规则描述,第一部分的字符可以少于给定的数量,其余部分皆为 2 个字符。
*
*
* 提示:
*
* S 的长度不超过 12,000,K 为正整数
*
* S 只包含字母数字(a-z,A-Z,0-9)以及破折号'-'
*
* S 非空
*/
class Solution {
public String licenseKeyFormatting(String S, int K) {
StringBuilder sb = new StringBuilder();
int count = 0;
K++;
for (int i = S.length() - 1; i >= 0; i--) {
char c = S.charAt(i);
if (c != '-') {
count++;
if (count == K) {
sb.append('-');
count = 1;
}
sb.append(Character.toUpperCase(c));
}
}
return sb.reverse().toString();
}
}
}
|
package id.co.ahm.sd.nis.app020.util;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.EmbeddedId;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.apache.commons.beanutils.PropertyUtils;
public class Nis020ObjectUtiliti {
// copy dari a ke b
public final static Object copyObject(Object origin, Object dest) {
try {
PropertyUtils.copyProperties(dest, origin);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return dest;
}
public final static Object copyObjectFromMap(HashMap<String, Object> origin, Object dest) {
Field[] fields = dest.getClass().getDeclaredFields();
for (Field field : fields) {
Object obx = origin.get(field.getName());
try {
if (obx == null) {
obx = origin.get(field.getName().toLowerCase());
}
if (obx == null) {
obx = origin.get(field.getName().toUpperCase());
}
PropertyUtils.setProperty(dest, field.getName(), obx);
} catch (Exception e) {
}
}
return dest;
}
public final static Map<String, Object> getConstraintErr(Object x) {
Map<String, Object> msg = new HashMap<>();
Field[] declaredFields = x.getClass().getDeclaredFields();
for (Field field : declaredFields) {
try {
Object ob = PropertyUtils.getProperty(x, field.getName());
Annotation[] annotations = field.getAnnotations();
for (Annotation ann : annotations) {
if (ann instanceof Size) {
Size s = (Size) ann;
if (ob != null) {
String st = (String) ob;
if (st.length() > s.max()) {
msg.put("err", "Jumlah maksimal karakter " + field.getName() + " harus " + s.max() + " karakter");
}
}
}
if (ann instanceof NotNull) {
if (ob == null) {
msg.put("err", "Kolom " + field.getName() + " wajib diisi");
}
}
if (ann instanceof Id) {
if (ob == null) {
msg.put("err", "Field " + field.getName() + " tidak boleh kosong");
}
}
if (ann instanceof EmbeddedId) {
if (ob == null) {
msg.put("err", "Field " + field.getName() + " tidak boleh kosong");
}
}
}
} catch (Exception e) {
}
}
return msg;
}
}
|
package officehours06_01;
public class Developer {
// name, employeeID, JobTitle, Salary
// hasCodingSkills
//
// Constructor:
// accepts and sets all instance variables
//
// Actions:
// getter/setters, coding(), fixingBug(), toString()
private String name;
private int employeeID;
private String jobTitle;
private double salary;
private static boolean hasCodingSkills = true;
public Developer(String name,int employeeID,String jobTitle,double salary){
this.name = name;
this.employeeID = employeeID;
this.jobTitle = jobTitle;
this.salary = salary;
}
public void coding(){
System.out.println(this.name + " is coding");
}
public void fixingBug(){
System.out.println(this.name + " is fixing a bug");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getEmployee() {
return employeeID;
}
public void setEmployee(int employee) {
this.employeeID = employee;
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public boolean isHasCodingSkills() {
return hasCodingSkills;
}
@Override
public String toString() {
return "Developer{" +
"name='" + name + '\'' +
", employeeID=" + employeeID +
", jobTitle='" + jobTitle + '\'' +
", salary=" + salary +
'}';
}
}
|
/**
* @author baihu868
* INFO202 2019
* Sale
*/
package domain;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import net.sf.oval.constraint.NotBlank;
import net.sf.oval.constraint.NotNull;
public class Sale {
private Integer saleID;
@NotNull(message = "Date must be provided.")
@NotBlank(message = "Date must be provided.")
private LocalDate date;
@NotNull(message = "Status must be provided.")
@NotBlank(message = "Status must be provided.")
private String status;
SaleItem saleItem = new SaleItem();
Customer customer = new Customer();
ArrayList <SaleItem> items = new ArrayList<>();
public Sale(Integer saleID, LocalDate date, String status) {
this.saleID = saleID;
this.date = date;
this.status = status;
}
public Integer getSaleID() {
return saleID;
}
public LocalDate getDate() {
return date;
}
public String getStatus() {
return status;
}
public BigDecimal getTotal() {
return saleItem.getItemTotal();
}
public ArrayList<SaleItem> getItems() {
return items;
}
public SaleItem getSaleItem() {
return saleItem;
}
public Customer getCustomer() {
return customer;
}
public void addItem(SaleItem saleItem){
items.add(saleItem);
}
public void setSaleID(Integer saleID) {
this.saleID = saleID;
}
public void setDate(LocalDate date) {
this.date = date;
}
public void setStatus(String status) {
this.status = status;
}
@Override
public String toString() {
return "Sale{" + "saleID=" + saleID + ", date=" + date + ", status=" + status + '}';
}
}
|
package assemAssist.model.option;
/**
* This enum describes the different types of
* {@link assemAssist.model.operations.task.Task}s, it has a certain name (used
* in toString) and description. These option categories are used in the
* {@link assemAssist.model.factoryline.workStation.WorkStation}s to filter the
* tasks that they can execute.
*
* @author SWOP Group 3
* @version 3.0
*/
public enum VehicleOptionCategory {
BODY("Body", "Assemble vehicle body"), COLOR("Color", "Paint vehicle"), ENGINE("Engine",
"Insert engine"), GEARBOX("Gearbox", "Insert gearbox"), SEATS("Seats", "Install seats"), AIRCO(
"Airco", "Install airco"), WHEELS("Wheels", "Mount wheels"), SPOILER("Spoiler",
"Install spoiler"), STORAGE("Storage", "Install tool storage"), PROTECTION(
"Protection", "Add cargo protection"), CERTIFICATION("Certification",
"Certify maximum cargo load");
/**
* Initialises this option category with the given name and description.
*
* @param name
* The name of this option category
* @param description
* The description of this option category
*/
private VehicleOptionCategory(String name, String description) {
this.name = name;
this.description = description;
}
/**
* Returns the description of this option category.
*/
public String getDescription() {
return this.description;
}
private final String name, description;
/**
* Returns the string representation of this option category.
*/
@Override
public String toString() {
return this.name;
}
}
|
package Pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class MiniStatementPage {
@FindBy(xpath = "html/body/div[2]/div/ul/li[13]/a")
public WebElement MinistatementPageField;
@FindBy(name = "accountno")
public WebElement AccountNumberField;
@FindBy(name = "AccSubmit")
public WebElement AccountsubmitField;
@FindBy(xpath = "html/body/table/tbody/tr[1]/td/p")
public WebElement GetTextField;
@FindBy(xpath = ".//*[@id='ministmt']/tbody/tr[3]/td/a")
public WebElement GoHomePage;
public void MiniStats() {
MinistatementPageField.click();
AccountNumberField.sendKeys("7390");
AccountsubmitField.click();
// GetTextField.getText();
GoHomePage.click();
}
}
|
/**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2015 Paco Avila & Josep Llort
*
* No bytes were intentionally harmed during the development of this application.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.frontend.client.widget.foldertree;
import java.util.Vector;
import com.google.gwt.event.logical.shared.HasSelectionHandlers;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.TreeItem;
import com.openkm.frontend.client.Main;
import com.openkm.frontend.client.widget.Draggable;
import com.openkm.frontend.client.widget.OriginPanel;
/**
* ExtendedTree captures right button and marks a popup flag
*
* @author jllort
*
*/
public class ExtendedTree extends Tree implements HasSelectionHandlers<TreeItem> {
// Drag pixels sensibility
private static final int DRAG_PIXELS_SENSIBILITY = 3;
private boolean flagPopup = false;
public int mouseX = 0;
public int mouseY = 0;
private boolean dragged = false;
private int mouseDownX = 0;
private int mouseDownY = 0;
/**
* ExtendedTree
*/
public ExtendedTree() {
super();
sinkEvents(Event.MOUSEEVENTS | Event.ONCLICK | Event.ONDBLCLICK);
}
/**
* evalDragPixelSensibility
*/
private boolean evalDragPixelSensibility() {
if (mouseDownX - mouseX >= DRAG_PIXELS_SENSIBILITY) {
return true;
} else if (mouseX - mouseDownX >= DRAG_PIXELS_SENSIBILITY) {
return true;
} else if (mouseDownY - mouseY >= DRAG_PIXELS_SENSIBILITY) {
return true;
} else if (mouseY - mouseDownY >= DRAG_PIXELS_SENSIBILITY) {
return true;
} else {
return false;
}
}
/**
* isShowPopUP
*
* @return true or false popup flag
*/
public boolean isShowPopUP() {
return flagPopup;
}
@Override
public void onBrowserEvent(Event event) {
// When de button mouse is released
if (DOM.eventGetType(event) == Event.ONMOUSEDOWN) {
// When de button mouse is released
mouseX = DOM.eventGetClientX(event);
mouseY = DOM.eventGetClientY(event);
// remove dragable item
Main.get().draggable.clear();
switch (DOM.eventGetButton(event)) {
case Event.BUTTON_RIGHT:
DOM.eventPreventDefault(event); // Prevent to fire event to browser
flagPopup = true;
mouseDownX = 0;
mouseDownY = 0;
dragged = false;
Main.get().activeFolderTree.menuPopup.disableAllOptions();
fireSelection(elementClicked(DOM.eventGetTarget(event)));
break;
default:
flagPopup = false;
// dragging is enable only if cursor is inside actual item
dragged = isCursorInsideActualItem(elementClicked(DOM.eventGetTarget(event)));
mouseDownX = event.getScreenX();
mouseDownY = event.getClientY();
}
} else if (DOM.eventGetType(event) == Event.ONMOUSEMOVE) {
mouseX = DOM.eventGetClientX(event);
mouseY = DOM.eventGetClientY(event);
if (Main.get().activeFolderTree.canDrag() && dragged && mouseDownX > 0 && mouseDownY > 0
&& evalDragPixelSensibility()) {
TreeItem actualItem = Main.get().activeFolderTree.getActualItem();
Main.get().draggable.show(actualItem.getHTML(), OriginPanel.TREE_ROOT);
Main.get().activeFolderTree.fileBrowserRefreshDone();
mouseDownX = 0;
mouseDownY = 0;
dragged = false;
}
} else if (DOM.eventGetType(event) == Event.ONMOUSEUP || DOM.eventGetType(event) == Event.ONCLICK
|| DOM.eventGetType(event) == Event.ONDBLCLICK) {
mouseDownX = 0;
mouseDownY = 0;
dragged = false; // Always disabling the popup flag
}
// Prevent folder creation or renaming propagate actions to other tree nodes
int action = Main.get().activeFolderTree.getFolderAction();
if (action != FolderTree.ACTION_CREATE && action != FolderTree.ACTION_RENAME) {
super.onBrowserEvent(event);
}
}
/**
* disableDragged
*/
public void disableDragged() {
dragged = false;
}
/**
* fire a change event
*/
private void fireSelection(TreeItem treeItem) {
// SelectElement nativeEvent = Document.get().createSelectElement();
SelectionEvent.fire(this, treeItem);
// setSelectedItem(treeItem); // Now is not necessary select treeItem here is done by capturing events
}
public HandlerRegistration addSelectionHandler(SelectionHandler<TreeItem> handler) {
return addHandler(handler, SelectionEvent.getType());
}
/**
* elementClicked
*
* Returns the treeItem when and element is clicked, used to capture drag and drop tree Item
*/
public TreeItem elementClicked(Element element) {
Vector<Element> chain = new Vector<Element>();
collectElementChain(chain, this.getElement(), element);
TreeItem item = findItemByChain(chain, 0, null);
return item;
}
/**
* collectElementChain
*/
private void collectElementChain(Vector<Element> chain, Element elementRoot, Element element) {
if ((element == null) || element == elementRoot)
return;
collectElementChain(chain, elementRoot, DOM.getParent(element));
chain.add(element);
}
/**
* findItemByChain
*/
private TreeItem findItemByChain(Vector<Element> chain, int idx, TreeItem root) {
if (idx == chain.size())
return root;
Element hCurElem = (Element) chain.get(idx);
if (root == null) {
for (int i = 0, n = this.getItemCount(); i < n; ++i) {
TreeItem child = this.getItem(i);
if (child.getElement() == hCurElem) {
TreeItem retItem = findItemByChain(chain, idx + 1, child);
if (retItem == null)
return child;
return retItem;
}
}
} else {
for (int i = 0, n = root.getChildCount(); i < n; ++i) {
TreeItem child = root.getChild(i);
if (child.getElement() == hCurElem) {
TreeItem retItem = findItemByChain(chain, idx + 1, root.getChild(i));
if (retItem == null)
return child;
return retItem;
}
}
}
return findItemByChain(chain, idx + 1, root);
}
/**
* Detects whether mouse cursor is inside actual item.
*
* @return returns true if mouse cursor is inside actual item
*/
private boolean isCursorInsideActualItem(TreeItem clickedItem) {
if (clickedItem == null) {
return false;
}
Element selectedElement = Draggable.getSelectedElement(clickedItem.getElement());
if (selectedElement == null) {
return false;
}
return mouseX >= selectedElement.getAbsoluteLeft() && mouseX <= selectedElement.getAbsoluteRight()
&& mouseY >= selectedElement.getAbsoluteTop() && mouseY <= selectedElement.getAbsoluteBottom();
}
} |
import javax.swing.*;
/**
* Klasa tworząca pop-up kończący grę.
*/
class ThreadForJOptionPane implements Runnable {
/**
* Wątek
*/
private Thread thread;
/**
* Wiadomość: 'biały' lub 'czarny'
*/
private String msg;
private JFrame window;
/**
* Tworzenie obiektu oraz ustawienie wiadomościa do wydrukowania
* @param string - komunikat do wydrukowania: biały(klient) lub czarny(serwer)
*/
ThreadForJOptionPane(String string, JFrame window) {
msg = string;
this.window = window;
thread = new Thread(this);
thread.start();
}
/**
* Metoda watku
*/
public void run() {
String a = msg + " won the game !";
String b = "Game over";
JOptionPane.showMessageDialog(null, a, b, JOptionPane.INFORMATION_MESSAGE);
window.dispose();
}
}
|
import java.sql.ResultSet;
import java.sql.SQLException;
import kovaUtils.OpalDialog.kovaDialog.OpalDialogType;
import net.miginfocom.swt.MigLayout;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
public class operPregledNew extends DEF implements FocusListener, KeyListener,
MouseListener {
private static Display display;
private static Shell shell;
static MigLayout layout = new MigLayout();
static MigLayout layout2 = new MigLayout();
private static Group group;
private static int iRed;
private ResultSet rs2;
static Button cmdNovi;
static Button cmdObrisi;
static Button cmdUredi;
private static String SQLquery;
private static ResultSet rs;
private static String val[][];
private Label lblUkIznos;
private Label lbl;
protected int IDbroj;
protected String sTablica = "operateri";
static kovaTable table;
public operPregledNew(Shell parent) {
shell = new Shell(parent, SWT.APPLICATION_MODAL | SWT.DIALOG_TRIM);
display = shell.getDisplay();
Image icona = new Image(display, "library/icons/Boue.ico");
shell.setImage(icona);
CenterScreen(shell, shell.getDisplay());
shell.setText(appName + " " + getLabel("GR4")); //$NON-NLS-2$
shell.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
shell.setSize(350, 500);
shell.setLayout(layout);
createWidgets();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
}
public static void main(String[] args) {
new operPregledNew(shell);
}
private void createWidgets() {
// *****************************TABLICA******************************//
group = new Group(shell, SWT.NONE);
group.setText(getLabel("GR4"));
group.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
group.setForeground(display.getSystemColor(SWT.COLOR_BLUE));
group.setLayoutData("width 220px,wrap");
group.setLayout(layout2);
// ************************************kreiranje
// tablice********************************************//
// RSet.setSystemBase();
// rs2 = RSet.openRS("select id,ime,prezime,korisnik from operateri");
table = fillKovaTable(group);
// tableOper=KTable.createKTable(group,rs2);
// tableOper.addFocusListener(this);
// tableOper.addKeyListener(this);
// tableOper.setData("TBL");
lblUkIznos = new Label(group, SWT.RIGHT);
lblUkIznos.setLayoutData("width 120px,span,gapleft 340");
lblUkIznos.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
lbl = new Label(group, SWT.NONE);
lbl.setText(getLabel("lblFast"));
lbl.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
table.createSearchField(group, SWT.BORDER);
table.contentTable.addMouseListener(this);
table.contentTable.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event e) {
IDbroj = Integer.parseInt(table.getItem(
table.contentTable.getSelectionIndex()).getText());
}
});
final TableColumn IDCol = table.getColumn(0);
IDCol.setData("IDCol");
IDCol.setText(getLabel("IDCol"));
IDCol.setWidth(30);
final TableColumn imeCol = table.getColumn(1);
imeCol.setData("colName");
imeCol.setText(getLabel("colName"));
imeCol.setWidth(100);
TableColumn prezimeCol = table.getColumn(2);
prezimeCol.setText(getLabel("Surname"));
prezimeCol.setWidth(100);
TableColumn userCol = table.getColumn(3);
userCol.setText(getLabel("colUser"));
userCol.setData("COL3");
userCol.setWidth(60);
table.setLayoutData("width 300px,height 345px,span");
table.addColorListener(new Listener() {
@Override
public void handleEvent(final Event event) {
for (TableItem singleItem : table.getItems()) {
applyColors(singleItem);
}
}
});
// initial coloring
for (TableItem singleItem : table.getItems()) {
applyColors(singleItem);
}
cmdNovi = new Button(shell, SWT.PUSH);
cmdNovi.setText(getLabel("NewOper"));
cmdNovi.setLayoutData("width 100px,split 3");
cmdNovi.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event e) {
gBroj = 0;
new operUnos(shell);
freshTable();
}
});
cmdUredi = new Button(shell, SWT.PUSH);
cmdUredi.setText(getLabel("Edit"));
cmdUredi.setLayoutData("width 100px,split 3");
cmdUredi.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event e) {
gBroj = IDbroj;
new operUnos(shell);
freshTable();
gBroj = 0;
}
});
cmdObrisi = new Button(shell, SWT.PUSH);
cmdObrisi.setText(getLabel("Delete"));
cmdObrisi.setLayoutData("width 100px,split 3");
cmdObrisi.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event e) {
// int odg = ALERT.open(shell, "?", "Brisanje operatera?",
// "Želite li obrisati operatera: "+ getColVal(1)+ " " +
// getColVal(2)+"", "Obriši|Odustani",0);
int odg = ALERT
.show(getLabel("mess40"), "?", getLabel("mess40txt") + getColVal(1) + " " + getColVal(2) + "?", OpalDialogType.OK_CANCEL, "", ""); //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
if (odg == 0) {
logger.logg(getLabel("logg11") + " " + sTablica + " (ID="
+ IDbroj + ")");
RSet.deleteRSid(IDbroj, sTablica);
freshTable();
} else {
}
}
});
}
private void freshTable() {
rs2 = RSet.openRS("select id,ime,prezime,korisnik from operateri");
;
table.resetValues(kovaTable.fillVal(rs2));
try {
rs2.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
logger.loggErr("operPregledNew " + e.getMessage());
}
}
static void applyColors(final TableItem target) {
if (iRed == 0) {
target.setBackground(target.getDisplay().getSystemColor(
SWT.COLOR_WIDGET_LIGHT_SHADOW));
iRed = 1;
} else {
target.setBackground(target.getDisplay().getSystemColor(
SWT.COLOR_WHITE));
iRed = 0;
}
}
@Override
public void focusGained(FocusEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void focusLost(FocusEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseDoubleClick(MouseEvent arg0) {
gBroj = IDbroj;
new operUnos(shell);
freshTable();
}
@Override
public void mouseDown(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseUp(MouseEvent arg0) {
// TODO Auto-generated method stub
}
private static String getColVal(int kolona) {
String val = "";
if (table.contentTable.getSelectionCount() > 0) {
val = table.getItem(table.contentTable.getSelectionIndex())
.getText(kolona);
}
return val;
}
private static kovaTable fillKovaTable(final Composite parent) {
// može ovako, a može se i iz metaData-e izčitati
final String[] header = { "ID", "Ime", "Prezime", "Korisnik" };
SQLquery = "select id,ime,prezime,korisnik from operateri";
rs = RSet.openRS(SQLquery);
val = kovaTable.fillVal(rs);
// create the table itself
final kovaTable table = kovaTable.createKovaTable(parent,
SWT.FULL_SELECTION | SWT.MULTI, header, val);
table.setLayoutData("width 470px,height 345px,span");
for (TableColumn singleColumn : table.getColumns()) {
singleColumn.pack();
}
kovaTable.setColumnsMeta(rs, table);
table.setEditable(false, 1, 2, 3);
/*
* highlight first column items
*/
table.addColorListener(new Listener() {
@Override
public void handleEvent(final Event event) {
for (TableItem singleItem : table.getItems()) {
applyColors(singleItem);
}
}
});
// initial coloring
for (TableItem singleItem : table.getItems()) {
applyColors(singleItem);
}
return table;
}
} |
package day49_AbstractionIntro;
public abstract class Abstraction {
public static void main(String[] args) {
}
public abstract void startTheCar();
}
class Toyota extends Abstraction{
@Override
public void startTheCar() {
System.out.println("Brake");
System.out.println("push the start button");
System.out.println("release the brake");
}
public static void main(String[] args) {
// Abstraction obj=new Abstraction();// abstraction class can not create object
Tesla tesla=new Tesla();
tesla.startTheCar();
Toyota toyota=new Toyota();
toyota.startTheCar();
}
}
class Tesla extends Abstraction{
//must implement the abstarct method from the abstract class
public void startTheCar() {//when we give the implementation abstrcat is not abstract anymore
System.out.println("voice control");
System.out.println("drive");
}
}
|
package metodosAgen;
import java.util.ArrayList;
import java.util.Date;
public class Pasaje {
private String origen;
private String destino;
private int precioTotal;
private Date fechaIda;
private Date fechaVuelta;
private String nombreCliente;
private String empresa;
private String tipoTransporte;
private ArrayList<EmpresaPasaje> empresas;
public Pasaje(String origen, String destino, Date fechaIda, Date fechaVuelta, String nombreCliente, String tipoTransporte, String empresa, int precioTotal) {
this.origen = origen;
this.destino = destino;
this.precioTotal = precioTotal;
this.fechaIda = fechaIda;
this.fechaVuelta = fechaVuelta;
this.nombreCliente = nombreCliente;
this.empresa = empresa;
this.tipoTransporte = tipoTransporte;
}
//zona seters
public void setDestino(String destino) {
this.destino = destino;
}
public void setFechaIda(Date fechaIda) {
this.fechaIda = fechaIda;
}
public void setFechaVuelta(Date fechaVuelta) {
this.fechaVuelta = fechaVuelta;
}
public void setNombreCliente(String nombreCliente) {
this.nombreCliente = nombreCliente;
}
public void setOrigen(String origen) {
this.origen = origen;
}
public void setPrecioTotal(int precioTotal) {
this.precioTotal = precioTotal;
}
public void setEmpresas(ArrayList<EmpresaPasaje> empresas) {
this.empresas = empresas;
}
//zona geters
public String getDestino() {
return destino;
}
public Date getFechaIda() {
return fechaIda;
}
public Date getFechaVuelta() {
return fechaVuelta;
}
public String getNombreCliente() {
return nombreCliente;
}
public String getOrigen() {
return origen;
}
public int getPrecioTotal() {
return precioTotal;
}
public String getEmpresa(){
return empresa;
}
public String getTipoTransporte(){
return tipoTransporte;
}
public ArrayList<EmpresaPasaje> getEmpresas() {
return empresas;
}
} |
/*
* 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 uk.ac.dundee.computing.aec.instagrim.servlets;
import com.datastax.driver.core.Cluster;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import uk.ac.dundee.computing.aec.instagrim.lib.CassandraHosts;
import uk.ac.dundee.computing.aec.instagrim.models.Current2;
import uk.ac.dundee.computing.aec.instagrim.lib.Keyspaces;
/**
*
* @author Administrator
*/
@WebServlet(name = "Current1", urlPatterns = {"/Current1"})
public class Current1 extends HttpServlet {
Cluster cluster=null;
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
cluster = CassandraHosts.getCluster();
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String first_name = request.getParameter("firstname");
String last_name = request.getParameter("lastname");
String Oname = request.getParameter("Oname");
String DOB = request.getParameter("DOB");
String address = request.getParameter("address");
String email = request.getParameter("email");
String phone = request.getParameter("phone");
String pan = request.getParameter("pan");
String aadhar = request.getParameter("aadhar");
String Occ= request.getParameter("Occ");
String TOB= request.getParameter("TOB");
String shoplic = request.getParameter("ShopLic");
String Too = request.getParameter("Too");
String Joi= request.getParameter("Joi");
String Accno = request.getParameter("Accno");
String ROI = request.getParameter("ROI");
String DOAO= request.getParameter("DOAO");
Current2 sa=new Current2 ();
sa.setCluster(cluster);
sa.AddCust(first_name,last_name,Oname,DOB,address,email,phone,pan, aadhar,Occ,TOB,shoplic,Too,Joi,Accno,ROI,DOAO);
response.sendRedirect("/Instagrim/Index2.jsp");
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
package ist.meic.ie.createcustomer;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.RequestStreamHandler;
import ist.meic.ie.utils.Constants;
import ist.meic.ie.utils.DatabaseConfig;
import ist.meic.ie.utils.LambdaUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.*;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.MissingFormatArgumentException;
public class CreateCustomer implements RequestStreamHandler {
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
LambdaLogger logger = context.getLogger();
JSONObject newCustomer = LambdaUtils.parseInput(inputStream, logger);
if (verifyArgs(outputStream, newCustomer)) return;
int customerId = ((Long) newCustomer.get("customerId")).intValue();
String firstName = (String) newCustomer.get("firstName");
String lastName = (String) newCustomer.get("lastName");
String street = (String) newCustomer.get("street");
String postalCode = (String) newCustomer.get("postalCode");
String district = (String) newCustomer.get("district");
String council = (String) newCustomer.get("council");
String parish = (String) newCustomer.get("parish");
String email = (String) newCustomer.get("email");
String password = (String) newCustomer.get("password");
int doorNumber = ((Long) newCustomer.get("doorNumber")).intValue();
Date birthDate = null;
try {
birthDate = new SimpleDateFormat("yyyy-MM-dd").parse((String) newCustomer.get("birthDate"));
} catch (ParseException e) {
logger.log(e.toString());
}
Connection conn = new DatabaseConfig(Constants.CUSTOMER_HANDLING_DB, "CustomerHandling", Constants.CUSTOMER_HANDLING_DB_USER, Constants.CUSTOMER_HANDLING_DB_PASSWORD).getConnection();
try {
PreparedStatement insert = conn.prepareStatement ("UPDATE Customer SET firstName = ?, lastName = ?, birthDate = ?," +
"street = ?, postalCode = ?, district = ?, council = ?, parish = ?," +
"email = ?, password = ?, doorNumber = ? WHERE id = ?");
insert.setString(1,firstName);
insert.setString(2,lastName);
insert.setDate(3, new java.sql.Date(birthDate.getTime()));
insert.setString(4, street);
insert.setString(5, postalCode);
insert.setString(6, district);
insert.setString(7, council);
insert.setString(8, parish);
insert.setString(9, email);
insert.setString(10, password);
insert.setInt(11, doorNumber);
insert.setInt(12, customerId);
insert.executeUpdate();
insert.close();
logger.log(newCustomer.toJSONString());
LambdaUtils.buildResponse(outputStream, newCustomer.toJSONString(),200);
} catch (SQLException e) {
logger.log(e.toString());
} finally {
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
private boolean verifyArgs(OutputStream outputStream, JSONObject newCustomer) throws IOException {
if (newCustomer.get("customerId") == null) {
LambdaUtils.buildResponse(outputStream, "No customer Id defined!", 500);
return true;
}
if (newCustomer.get("firstName") == null) {
LambdaUtils.buildResponse(outputStream, "No first name defined!", 500);
return true;
}
if (newCustomer.get("lastName") == null) {
LambdaUtils.buildResponse(outputStream, "No last name defined!", 500);
return true;
}
if (newCustomer.get("birthDate") == null) {
LambdaUtils.buildResponse(outputStream, "No birth date defined!", 500);
return true;
}
if (newCustomer.get("postalCode") == null) {
LambdaUtils.buildResponse(outputStream, "No postal code defined!", 500);
return true;
}
if (newCustomer.get("street") == null) {
LambdaUtils.buildResponse(outputStream, "No street defined!", 500);
return true;
}
if (newCustomer.get("district") == null) {
LambdaUtils.buildResponse(outputStream, "No district defined!", 500);
return true;
}
if (newCustomer.get("council") == null) {
LambdaUtils.buildResponse(outputStream, "No council defined!", 500);
return true;
}
if (newCustomer.get("doorNumber") == null) {
LambdaUtils.buildResponse(outputStream, "No parish defined!", 500);
return true;
}
return false;
}
}
|
package org.tosch.neverrest.data.repositories;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.NoRepositoryBean;
import org.tosch.neverrest.data.models.CoreDataEntity;
import java.io.Serializable;
import java.util.UUID;
@NoRepositoryBean
public interface CoreEntityRepository<D extends CoreDataEntity<ID>, ID extends Serializable>
extends CrudRepository<D, ID> {
ID parseUuid(UUID uuid);
}
|
import java.awt.*;
import java.awt.event.*;
class Buttons extends Frame implements ActionListener
{
Button b1,b2,b3;
Buttons()
{
setLayout(new GridBagLayout());
b1=new Button("Yellow");
b2=new Button("Blue");
b3=new Button("Pink");
b1.setBounds(100,100,70,40);
b2.setBounds(100,160,70,40);
b3.setBounds(100,220,70,40);
this.add(b1);
this.add(b2);
this.add(b3);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
if(str.equals("Yellow"))this.setBackground(Color.yellow);
if(str.equals("Blue"))this.setBackground(Color.blue);
if(str.equals("Pink"))this.setBackground(Color.pink);
}
public static void main(String args[])
{
Buttons mb=new Buttons();
mb.setSize(400,400);
mb.setTitle("Buttons");
mb.setVisible(true);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.