blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
sequence
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
sequence
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
4adfd988b8424bbe693a2433ec125a2763a89f40
23,819,888,641,072
6afd0cbf702f5b7361794d686082cce9e5dfbab5
/src/main/java/by/vladkostevich/dynamodbunit/enums/DynamoDbStructureFileType.java
5d34f1e884b901eacc0043d63ccb3d4dee17320d
[]
no_license
vladkostevich/dynamodb-unit
https://github.com/vladkostevich/dynamodb-unit
e11741bc8d64f53911b510b8f7b24dc954d92db2
798dafd97d8722c05c8d6388775ded3840d1d26c
refs/heads/master
2021-06-24T10:36:00.873000
2019-11-12T16:03:28
2019-11-12T16:03:28
221,050,326
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package by.vladkostevich.dynamodbunit.enums; public enum DynamoDbStructureFileType { AWS_CLOUD_FORMATION_YAML; }
UTF-8
Java
118
java
DynamoDbStructureFileType.java
Java
[]
null
[]
package by.vladkostevich.dynamodbunit.enums; public enum DynamoDbStructureFileType { AWS_CLOUD_FORMATION_YAML; }
118
0.805085
0.805085
5
22.6
18.682611
44
false
false
0
0
0
0
0
0
0.4
false
false
13
9485fd652191954574cc568e7e10168841b9147e
24,455,543,796,173
f975773f56bcf1fb6951872ea0e27dea1eeb7b17
/src/main/java/com/kudi_test/product_service/service/interfaces/BaseService.java
543a5421cd1456eaa4df961c475402868a944140
[]
no_license
GabrielSebastine/product-service
https://github.com/GabrielSebastine/product-service
5e1bbed4014527dce09a4fe7d5387857de4decb6
65f4cf53f69cff7dc2fa1bc7bfa0ecca0dd7a17f
refs/heads/master
2021-02-10T12:14:10.389000
2020-03-02T14:02:10
2020-03-02T14:02:10
244,380,877
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kudi_test.product_service.service.interfaces; import com.kudi_test.product_service.entity.Identifiable; import com.kudi_test.product_service.exception.EntityDoesNotExistException; import org.springframework.data.domain.Example; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.io.Serializable; import java.util.List; import java.util.Optional; public interface BaseService<T extends Identifiable<ID>, ID extends Serializable> { public Optional<T> getById(ID id); public T save(T model); public T update(String uuid, T model) throws EntityDoesNotExistException; public boolean delete(String uuid); public Page<T> getAll(Pageable page); public Optional<T> getByUuid(String uuid); //throws exception if model cannot be found public T findByUuid(String uuid) throws EntityDoesNotExistException; }
UTF-8
Java
887
java
BaseService.java
Java
[]
null
[]
package com.kudi_test.product_service.service.interfaces; import com.kudi_test.product_service.entity.Identifiable; import com.kudi_test.product_service.exception.EntityDoesNotExistException; import org.springframework.data.domain.Example; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.io.Serializable; import java.util.List; import java.util.Optional; public interface BaseService<T extends Identifiable<ID>, ID extends Serializable> { public Optional<T> getById(ID id); public T save(T model); public T update(String uuid, T model) throws EntityDoesNotExistException; public boolean delete(String uuid); public Page<T> getAll(Pageable page); public Optional<T> getByUuid(String uuid); //throws exception if model cannot be found public T findByUuid(String uuid) throws EntityDoesNotExistException; }
887
0.801578
0.801578
30
28.566668
26.7665
83
false
false
0
0
0
0
0
0
1.066667
false
false
13
ec11821c44dffbee33ca981a1c0e1b2eef7e63d7
29,867,202,592,664
6707f9f2b2cfa6c8c436f64e2b4897f41aeab4bd
/eRoute/Tag/1.10.0/Codigo/RouteLite/routeLite/src/main/java/com/amesol/routelite/vistas/CapturaPedido.java
08d20153177aaa9828cca2dcf38600f74cd20356
[]
no_license
cadusousa/Productos
https://github.com/cadusousa/Productos
b36a2ace550b7c61ecae1b28d0f95b7ffc8f91a6
c70bdeff530d699aa9f1c08577c99a0ebaeb0de4
refs/heads/master
2023-03-07T17:44:45.009000
2021-02-26T20:07:23
2021-02-26T20:07:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.amesol.routelite.vistas; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnShowListener; import android.content.Intent; import android.database.Cursor; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.view.View.OnKeyListener; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.SimpleCursorAdapter.ViewBinder; import android.widget.Spinner; import android.widget.TableLayout.LayoutParams; import android.widget.TextView; import com.amesol.routelite.R; import com.amesol.routelite.actividades.Enumeradores.Inventario.TiposValidacionInventario; import com.amesol.routelite.actividades.Inventario; import com.amesol.routelite.actividades.InventarioDobleUnidad; import com.amesol.routelite.actividades.ListaPrecio; import com.amesol.routelite.actividades.Mensajes; import com.amesol.routelite.actividades.Promociones2; import com.amesol.routelite.actividades.Promociones2.onTerminarAplicacionListener; import com.amesol.routelite.actividades.Transacciones; import com.amesol.routelite.actividades.ValoresReferencia; import com.amesol.routelite.controles.CapturaProducto; import com.amesol.routelite.datos.Cliente; import com.amesol.routelite.datos.Dia; import com.amesol.routelite.datos.Producto; import com.amesol.routelite.datos.TPDImpuesto; import com.amesol.routelite.datos.TransProd; import com.amesol.routelite.datos.TransProdDetalle; import com.amesol.routelite.datos.Vendedor; import com.amesol.routelite.datos.basedatos.BDVend; import com.amesol.routelite.datos.basedatos.Consultas; import com.amesol.routelite.datos.generales.ISetDatos; import com.amesol.routelite.datos.utilerias.ArchivoConfiguracion; import com.amesol.routelite.datos.utilerias.CONHist; import com.amesol.routelite.datos.utilerias.ConfigParametro; import com.amesol.routelite.datos.utilerias.ConfiguracionLocal; import com.amesol.routelite.datos.utilerias.MOTConfiguracion; import com.amesol.routelite.datos.utilerias.Sesion; import com.amesol.routelite.datos.utilerias.Sesion.Campo; import com.amesol.routelite.presentadores.Enumeradores; import com.amesol.routelite.presentadores.Enumeradores.Acciones; import com.amesol.routelite.presentadores.Enumeradores.RespuestaMsg; import com.amesol.routelite.presentadores.Enumeradores.Solicitudes; import com.amesol.routelite.presentadores.Enumeradores.TiposFasesDocto; import com.amesol.routelite.presentadores.Enumeradores.TiposMovimientos; import com.amesol.routelite.presentadores.Enumeradores.TiposTransProd; import com.amesol.routelite.presentadores.act.CapturarPedido; import com.amesol.routelite.presentadores.interfaces.IAplicacionPromocion; import com.amesol.routelite.presentadores.interfaces.ICapturaInventario; import com.amesol.routelite.presentadores.interfaces.ICapturaPedido; import com.amesol.routelite.presentadores.interfaces.ICapturaPedidoSugerido; import com.amesol.routelite.presentadores.interfaces.ICapturaTotales; import com.amesol.routelite.presentadores.interfaces.ICapturaTotalesConsignacion; import com.amesol.routelite.presentadores.interfaces.IConsultaUltimaVenta; import com.amesol.routelite.utilerias.Generales; import com.amesol.routelite.vistas.generico.DialogoAlerta; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import java.io.File; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicReference; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; public class CapturaPedido extends Vista implements ICapturaPedido { CapturarPedido mPresenta; CapturaProducto captura; String mAccion; int index; int top; HashMap<String, String> oParametros = null; boolean siguiente = false; boolean salir = false; Object mPausaCiclo; //Runnable hiloFor; //Thread promo; boolean esNuevo = true; boolean soloLectura = false; boolean mostrandoPregunta = false; boolean huboCambios = false; boolean calculando = false; boolean regresandoPromo = false; boolean sugeridoMostrado = false; //private Cursor producto; private Menu mnu; boolean surtir = false; boolean reparto = false; ArrayList<TransProdDetalle> prodSinExistencia = new ArrayList<TransProdDetalle>(); boolean consultar = false; boolean modificando = false; boolean modificandoAutoventa = false; MenuItem modificar; boolean manejoDobleUnidad = false; Iterator<TransProd> docsTransProd; ListView lista; Handler handler; Promociones2 promociones; Producto productoAgregar; int tipoUnidadAgregar; float cantidadAgregar; Float cantidadOriginalAgregar; String transprodIDEliminar; String transprodDetalleIDEliminar; boolean existe; ISetDatos envasesPorRecolectar; String inventarioID; HashMap<Short, InventarioDobleUnidad.DetalleProductoDobleUnidad> hmDetalleDobleUnidadAgregar = null; private static final String FRAGMENT_TAG = "ventaMensualFragment"; private Button btPrecioManualAceptar=null; @SuppressWarnings("unchecked") @Override public void onCreate(Bundle savedInstanceState) { try { super.onCreate(savedInstanceState); mAccion = getIntent().getAction(); setContentView(R.layout.captura_pedido); deshabilitarBarra(true); if(Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.REPARTO) setTitulo(Mensajes.get("XReparto")); else if(Integer.parseInt(Sesion.get(Campo.TipoIndiceModuloMovDetalleClave).toString()) == Enumeradores.TiposModuloMovDetalle.CONSIGNACION) setTitulo(Mensajes.get("XConsignacion")); else setTitulo(Mensajes.get("XVentas")); if(mAccion != null){ if(mAccion.equals(Enumeradores.Acciones.ACCION_CAPTURAR_MOV_SIN_INV_EN_VISITA)){ setTitulo(Consultas.ConsultasModuloMovDetalle.obtenerTitulo()); } } TextView texto = (TextView) findViewById(R.id.lblProducto); texto.setText(Mensajes.get("XProducto")); texto = (TextView) findViewById(R.id.lblUnidad); texto.setText(Mensajes.get("XUnidad")); texto = (TextView) findViewById(R.id.lblTotalPrevio); texto.setText(Mensajes.get("MDBTotalPrevio") + ":"); texto = (TextView) findViewById(R.id.lblVolumen); texto.setText(Mensajes.get("XKgVol") + ":"); texto = (TextView) findViewById(R.id.lblTotalProductos); texto.setText(Mensajes.get("MDBFilas") + ":"); texto = (TextView) findViewById(R.id.lblTotalUnidades); texto.setText(Mensajes.get("XUnidades") + ":"); Button boton = (Button) findViewById(R.id.btnSugerido); boton.setText(Mensajes.get("XSugerido")); boton.setOnClickListener(mPedidoSugerido); boton = (Button) findViewById(R.id.btnContinuar); boton.setText(Mensajes.get("XContinuar")); boton.setOnClickListener(mAplicarPromociones); lista = (ListView) findViewById(R.id.lsTransProdDetalle); lista.setItemsCanFocus(false); //TODO: checar esto!!!! cuando truena el quecolin se brinca todo el codigo que sigue ya que se va al catch!!! -Sergio //le agregue un try-catch para que no se fuera hasta abajo, checar si esta bien asi!!! try{ encenderBluetooth(); }catch(Exception e){ e.printStackTrace(); } if (((MOTConfiguracion) Sesion.get(Campo.MOTConfiguracion)).get("ManejoDobleUnidad").toString().equals("1")) { manejoDobleUnidad = true; } captura = (CapturaProducto) findViewById(R.id.capturaProducto); if(manejoDobleUnidad){ captura.setOnAgregarProdDobleUnidadListener(mAgregarProdDobleUnidadListener); }else { captura.setOnAgregarProductoListener(mAgregarProductoListener); } captura.setOnProductoNoEncontradoListener(new CapturaProducto.onProductoNoEncontradoListener() { @Override public void onProductoNoEncontrado() { captura.setTransProdIds(mPresenta.getTransProdIds()); } }); mPresenta = new CapturarPedido(this, mAccion); if (getIntent().getSerializableExtra("parametros") != null) { oParametros = (HashMap<String, String>) getIntent().getSerializableExtra("parametros"); } if (oParametros != null && (!oParametros.get("TransProdId").trim().equals(""))) { if( (Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.REPARTO || Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.VENTA || Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.PREVENTA) && mAccion != Acciones.ACCION_CAPTURAR_MOV_SIN_INV_EN_VISITA && ((MOTConfiguracion)Sesion.get(Campo.MOTConfiguracion)).get("AgruparTransacciones").toString().equals("1")){ //agrupar transacciones ArrayList<String> transacciones = Consultas.ConsultasTransProd.agruparTransacciones(oParametros.get("TransProdId")); for(String tran : transacciones){ mPresenta.agregarTransaccion(tran); Consultas.ConsultasTRPGrupo.eliminarTransaccionGrupo(tran); //eliminar el registro del grupo setHuboCambios(true); } }else mPresenta.agregarTransaccion(oParametros.get("TransProdId")); } Date seleccion = new Date(); SimpleDateFormat x = new SimpleDateFormat("dd/MM/yyyy"); seleccion = x.parse(((Dia)Sesion.get(Campo.DiaActual)).DiaClave ); if (Generales.getFechaActual().compareTo(seleccion) != 0){ if (((ConfigParametro) Sesion.get(Campo.ConfigParametro)).existeParametro("ValidarActPrecio")) { if (((ConfigParametro) Sesion.get(Campo.ConfigParametro)).get("ValidarActPrecio").equals("1")) { //Se revisa el archivo de actualizaciones, para ver si se actualizaron los precios DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db; Document xmlActualiza; boolean archivosServerEliminados = true; try { ConfiguracionLocal conf = (ConfiguracionLocal) Sesion.get(Campo.ConfiguracionLocal); File archXML = new File(conf.get(ArchivoConfiguracion.CampoConfiguracion.DIRECTORIO_TRABAJO).toString()); archXML = new File(archXML, "bd"); archXML = new File(archXML, BDVend.nombreBaseDatos().replace("db", "xml")); db = dbf.newDocumentBuilder(); xmlActualiza = db.parse(new File(archXML.getAbsolutePath())); NodeList tablasXml = xmlActualiza.getFirstChild().getChildNodes(); String nombreTabla; Date fechaActualizacion = new Date(1900,1,1); for (int i = 0; i <= tablasXml.getLength() - 1; i++) { nombreTabla = tablasXml.item(i).getChildNodes().item(0).getTextContent(); if (nombreTabla.equalsIgnoreCase("Precio") || nombreTabla.equalsIgnoreCase("PrecioProductoVig")) { Date actualizacion = new Date(); SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd"); actualizacion = formatDate.parse( tablasXml.item(i).getChildNodes().item(1).getTextContent()); if (fechaActualizacion.compareTo(actualizacion) >0){ fechaActualizacion =actualizacion; } } } if (Generales.getFechaActual().compareTo(fechaActualizacion) >0){ mostrarError(Mensajes.get("E0954"),0); mPresenta.errorFinalizar = true; return; } }catch (Exception ex){ mostrarError("Error al recuperar el parámetro ValidarActPrecio"); } } } } mPresenta.iniciar(); if (mPresenta.errorFinalizar){ return; } // si se paso como parametro el TransProdId, cargar el detalle del // pedido if (oParametros != null && (!oParametros.get("TransProdId").trim().equals(""))) { //boolean reparto = false; if (oParametros != null && oParametros.get("Reparto") != null && (!oParametros.get("Reparto").trim().equals(""))){ reparto = Boolean.parseBoolean(oParametros.get("Reparto")); } if (oParametros != null && oParametros.get("Consultar") != null && (!oParametros.get("Consultar").trim().equals(""))){ consultar = Boolean.parseBoolean(oParametros.get("Consultar")); } if (oParametros != null && oParametros.get("Surtir") != null && (!oParametros.get("Surtir").trim().equals(""))){ surtir = Boolean.parseBoolean(oParametros.get("Surtir")); } esNuevo = false; //marcar como modificado CAI 3111 modificandoAutoventa = true; refrescarProductos(mPresenta.getTransaccionesIds()); if (mPresenta.getTipoFase() == 0 || mPresenta.getTipoFase() == 3 ||((mPresenta.getTipoFase() == 2 || mPresenta.getTipoFase() == 1) && Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.REPARTO && reparto) ) { // si esta cancelado o surtido mostrar como solo lectura, si viene de reparto tambien soloLectura = true; captura.setVisibility(View.GONE); } } else if (mPresenta.getPedidoSugerido()) { esNuevo = true; refrescarProductos(mPresenta.getTransaccionesIds()); } captura.setTipoValidacionExistencia(mPresenta.getTipoValidacionExistencia()); captura.setCadenaListasPrecios(mPresenta.getListasPrecios()); captura.setTipoMovimiento(mPresenta.getModuloMovDetalle().TipoMovimiento); captura.setTipoTransProd(mPresenta.getModuloMovDetalle().TipoTransProd); captura.setSurtir(surtir); /*Se excluyen de la venta los productos tipo Canje Con la finalidad de que solo se muestren en las promociones*/ captura.setExcluirCanjes(true); if (!soloLectura) { registerForContextMenu(lista); lista.setOnItemLongClickListener(menu); } } catch (Exception ex) { ex.printStackTrace(); // mostrarError(ex.getMessage().equals("") ? ex.getCause().getMessage() : ex.getMessage()); } final EditText txtScaner = (EditText) findViewById(R.id.txtScanner); final EditText txtCantidad = (EditText) findViewById(R.id.txtCantidad); final Spinner spinUnit = (Spinner) findViewById(R.id.cboUnidad); if (!(spinUnit.getCount() > 1)) spinUnit.setEnabled(false); final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); txtCantidad.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { // getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); txtScaner.clearFocus(); imm.showSoftInput(txtCantidad, InputMethodManager.SHOW_FORCED); if (!(spinUnit.getCount() > 1)) spinUnit.setEnabled(false); String mCantidad = mPresenta.consultarUnidadProductoExistente(mPresenta.getTransProdIds(), txtScaner.getText().toString()); if (!mCantidad.equals("0")) { txtCantidad.setText(mCantidad); txtCantidad.requestFocus(); txtCantidad.selectAll(); txtCantidad.setSelectAllOnFocus(true); } } } }); txtScaner.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { // getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); txtCantidad.clearFocus(); } } }); } public void setCapturaCantidad(float cantidad){ captura.setCantidad(cantidad); } //Se usa solo para el manejo normal de unidades private boolean validarVenderApartado(Producto producto, int tipoUnidad, float cantidad){ return validarVenderApartado(producto,tipoUnidad,cantidad, null, null, null); } //Se usa para el manejo normal de unidades private boolean validarVenderApartado(Producto producto, int tipoUnidad, float cantidad, Float cantidadOriginal, String transProdID, String transProdDetalleID ){ if(Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.REPARTO){ if(((CONHist)Sesion.get(Campo.CONHist)).get("VenderApartado").toString().equals("0")){ //mostrarAdvertencia(Mensajes.get("E0714").replace("$0$", productoClave)); captura.setError(Mensajes.get("E0714").replace("$0$", producto.ProductoClave)); return false; }else if(((CONHist)Sesion.get(Campo.CONHist)).get("VenderApartado").toString().equals("1")){ AtomicReference<Float> existencia = new AtomicReference<Float>(); StringBuilder error = new StringBuilder(); if(!Inventario.ValidarExistenciaDifNoDisponible(producto.ProductoClave, tipoUnidad, cantidad, existencia, error)){ //mostrarAdvertencia(Mensajes.get("E0714").replace("$0$", productoClave)); captura.setError(Mensajes.get("E0714").replace("$0$", producto.ProductoClave)); return false; } mostrarPreguntaSiNo(Mensajes.get("P0087"), 10); captura.setError(""); /*guardar todo en las varibles para poder agregar si responde SI*/ tipoUnidadAgregar = tipoUnidad; productoAgregar = producto; cantidadAgregar = cantidad; cantidadOriginalAgregar = cantidadOriginal; transprodIDEliminar = transProdID; transprodDetalleIDEliminar = transProdDetalleID; } } return true; } public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (hasFocus) { if (regresandoPromo) { regresandoPromo = false; try { if (Sesion.get(Campo.ResultadoActividad) != null) { if ((Boolean) Sesion.get(Campo.ResultadoActividad)) { promociones.TerminoPromocionRegalo(); Sesion.remove(Campo.ResultadoActividad); } else { promociones.SiguientePromocion(); Sesion.remove(Campo.ResultadoActividad); } } else { promociones.SiguientePromocion(); } } catch (Exception e) { mostrarError(e.getMessage()); } } } // Toast.makeText(context, text, duration).show(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: VentaMensual fmFragment; if((fmFragment = (VentaMensual) getFragmentManager().findFragmentByTag(FRAGMENT_TAG)) != null){ fmFragment.close(); }else{ salir(); } return true; } return super.onKeyDown(keyCode, event); } public OnItemLongClickListener menu = new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { openContextMenu(lista); return true; } }; @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.context_transaccion_detalle, menu); menu.getItem(0).setTitle(Mensajes.get("XEliminar")); if (((Vendedor) Sesion.get(Campo.VendedorActual)).ModificarPrecios == 1){ menu.getItem(1).setTitle(Mensajes.get("XModificarPrecio")); menu.getItem(1).setVisible(true); } if (((MOTConfiguracion)Sesion.get(Campo.MOTConfiguracion)).get("AsignarManualListas").equals("1")){ menu.getItem(2).setTitle(Mensajes.get("XCambiarListaPrecio")); menu.getItem(2).setVisible(true); } } @Override public boolean onContextItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.eliminar: mostrandoPregunta = true; mostrarPreguntaSiNo(Mensajes.get("P0233"), 2); return true; case R.id.modificarPrecio: try { LayoutInflater inflater = (LayoutInflater) CapturaPedido.this .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View dialogView = inflater.inflate(R.layout.dialog_number_picker, null); AlertDialog.Builder builder = new AlertDialog.Builder(CapturaPedido.this); final EditText np = (EditText) dialogView.findViewById(R.id.numText ); np.setSelectAllOnFocus(true); Cursor producto = (Cursor) (((SimpleCursorAdapter) lista.getAdapter()).getCursor()); final String transProdID= producto.getString(producto.getColumnIndex("TransProdID")); final String transProdDetalleID = producto.getString(producto.getColumnIndex("TransProdDetalleID")); final String subEmpresaId = producto.getString(producto.getColumnIndex("SubEmpresaId")); final String productoClave = producto.getString(producto.getColumnIndex("ProductoClave")); final short tipoUnidad = producto.getShort(producto.getColumnIndex("TipoUnidad")); final float cantidad = producto.getFloat(producto.getColumnIndex("Cantidad")); final float precio = Generales.getRound(producto.getFloat(producto.getColumnIndex("Precio")),Integer.parseInt(((CONHist)Sesion.get(Campo.CONHist)).get("DecimalesImporte").toString())); np.setText(Generales.getFormatoDecimal(producto.getFloat(producto.getColumnIndex("Precio")),Integer.parseInt(((CONHist)Sesion.get(Campo.CONHist)).get("DecimalesImporte").toString()))); np.selectAll(); np.requestFocus(); np.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { String userInput = np.getText().toString(); if (userInput.toString().matches("")) { userInput = "0.00"; } else { float floatValue = Float.parseFloat(userInput); userInput = String.format("%." + Integer.parseInt(((CONHist)Sesion.get(Campo.CONHist)).get("DecimalesImporte").toString()) + "f",floatValue); } np.setText(userInput); np.selectAll(); } } }); builder.setPositiveButton(Mensajes.get("XAceptar"),new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { MOTConfiguracion motConf = (MOTConfiguracion) Sesion.get(Campo.MOTConfiguracion); float precioEspecial = Generales.getRound(Float.parseFloat(np.getText().toString()),Integer.parseInt(((CONHist)Sesion.get(Campo.CONHist)).get("DecimalesImporte").toString())); if(precio != precioEspecial){ if(motConf.get("ValidaRangoPrecio").toString().equals("1")){ try{ Float precioMin = ListaPrecio.ObtenerPecioMinimo(mPresenta.getListasPrecios(), productoClave, tipoUnidad); if(precioEspecial >= precioMin){ mPresenta.eliminarDetalle(transProdID, transProdDetalleID, subEmpresaId, productoClave, tipoUnidad, cantidad, false ); mPresenta.agregarProductoUnidad(productoClave, subEmpresaId, tipoUnidad, cantidad, precioEspecial); dialog.dismiss(); }else{ mostrarError(Mensajes.get("I0278")); return; } } catch (Exception e){ mostrarError(e.getMessage()); } }else{ if (Float.parseFloat(np.getText().toString()) < 0f){ mostrarError(Mensajes.get("E0007")); return; } if(precio != precioEspecial){ mPresenta.eliminarDetalle(transProdID, transProdDetalleID, subEmpresaId, productoClave, tipoUnidad, cantidad, false ); mPresenta.agregarProductoUnidad(productoClave, subEmpresaId, tipoUnidad, cantidad, precioEspecial); dialog.dismiss(); } } }else{ dialog.dismiss(); } } }); builder.setNegativeButton(Mensajes.get("XCancelar"),new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setView(dialogView); final Dialog dialog = builder.create(); dialog.setOnShowListener(new OnShowListener() { @Override public void onShow(DialogInterface dialog) { final Button btPrecioAceptar; btPrecioAceptar = ((AlertDialog) dialog) .getButton(AlertDialog.BUTTON_POSITIVE); np.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_UP) { // check if the right key was pressed if (keyCode == KeyEvent.KEYCODE_ENTER) { btPrecioAceptar.performClick(); return true; } } return false; } }); } }); dialog.show(); } catch (Exception ex) { mostrarError(ex.getMessage()); } return true; case R.id.modificarListaPrecio: try { //obtenerTotales(TransProdId); //SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.elemento_captura_producto, cProductos, new String[] // { "TipoUnidad", "ProductoClave", "Descripcion", "Precio", "Cantidad", "Total", "Existencia", "CantidadOriginal" }, new int[] // { R.id.lblUnidadProductoClave, R.id.lblUnidadProductoClave, R.id.lblDescripcion, R.id.lblPU, R.id.lblCantidad, R.id.lblTotal, R.id.lblExistencia, R.id.lblCantidadOriginal }); //adapter.setViewBinder(new vista()); //lista.setAdapter(adapter); Cursor producto = (Cursor) (((SimpleCursorAdapter) lista.getAdapter()).getCursor()); final String productoClave = producto.getString(producto.getColumnIndex("ProductoClave")); final short tipoUnidad = producto.getShort(producto.getColumnIndex("TipoUnidad")); LayoutInflater inflater = (LayoutInflater) CapturaPedido.this .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View dialogViewModificarListaPrecio = inflater.inflate(R.layout.dialog_listas_precios, null); AlertDialog.Builder builder = new AlertDialog.Builder(CapturaPedido.this); ListView lista_precios = (ListView) dialogViewModificarListaPrecio.findViewById(R.id.lstAgenda); String sClienteClave = ((Cliente)Sesion.get(Campo.ClienteActual)).ClienteClave; ISetDatos MinMaxJerarquia = Consultas.ConsultasPrecio.obtenerJerarquiaMinMaxCliente(sClienteClave); MinMaxJerarquia.moveToFirst(); String sListaPrecios = mPresenta.getListasPreciosPedido(); ISetDatos precios = Consultas.ConsultasPrecio.obtenerPreciosProducto(productoClave, tipoUnidad, sClienteClave, sListaPrecios, MinMaxJerarquia.getShort("JerarquiaMinima"), MinMaxJerarquia.getShort("JerarquiaMaxima")); if (precios.getCount() == 0){ mostrarError(Mensajes.get("I0306")); return true; } Cursor cPrecios = (Cursor) precios.getOriginal(); startManagingCursor(cPrecios); //ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.lista_simple2_hor, cPrecios, new String[] { "Descripcion", "Precio" }, new int[] { R.id.txtCol1, R.id.txtCol2 }); SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.lista_simple2_hor, cPrecios, new String[] { "Descripcion", "Precio" }, new int[] { R.id.txtCol1, R.id.txtCol2 }); adapter.setViewBinder(new vistaListasPrecios()); lista_precios.setAdapter(adapter); lista_precios.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String sPrecioManual; Cursor listasprecios = (Cursor) parent.getItemAtPosition(position); listasprecios.moveToPosition(position); sPrecioManual = listasprecios.getString(2); Cursor producto = (Cursor) (((SimpleCursorAdapter) lista.getAdapter()).getCursor()); final String transProdID= producto.getString(producto.getColumnIndex("TransProdID")); final String transProdDetalleID = producto.getString(producto.getColumnIndex("TransProdDetalleID")); final String subEmpresaId = producto.getString(producto.getColumnIndex("SubEmpresaId")); final String productoClave = producto.getString(producto.getColumnIndex("ProductoClave")); final short tipoUnidad = producto.getShort(producto.getColumnIndex("TipoUnidad")); final float cantidad = producto.getFloat(producto.getColumnIndex("Cantidad")); float precioEspecial = Generales.getRound(Float.parseFloat(sPrecioManual),Integer.parseInt(((CONHist)Sesion.get(Campo.CONHist)).get("DecimalesImporte").toString())); Sesion.set(Campo.CambioLPTpdExtra,true); Sesion.set(Campo.LPTpdExtra,listasprecios.getString(0)); mPresenta.eliminarDetalle(transProdID, transProdDetalleID, subEmpresaId, productoClave, tipoUnidad, cantidad, false ); mPresenta.agregarProductoUnidad(productoClave, subEmpresaId, tipoUnidad, cantidad, precioEspecial); Sesion.set(Campo.LPTpdExtra,""); Sesion.set(Campo.CambioLPTpdExtra,false); btPrecioManualAceptar.performClick(); } }); builder.setNegativeButton(Mensajes.get("XCancelar"),new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setView(dialogViewModificarListaPrecio); final Dialog dialog = builder.create(); dialog.setOnShowListener(new OnShowListener() { @Override public void onShow(DialogInterface dialog) { btPrecioManualAceptar = ((AlertDialog) dialog) .getButton(AlertDialog.BUTTON_NEGATIVE); } }); dialog.show(); } catch (Exception ex) { mostrarError(ex.getMessage()); } return true; default: return super.onOptionsItemSelected(item); } } @Override public void iniciar() { } public void mostrarPromocionProducto(String promocionClave, String promocionReglaID, int CantidadGrupoApp, String SubEmpresaId, int cantidad, String productoDisparador, String cadenaListasPrecios) { HashMap<String, Object> oParametros = new HashMap<String, Object>(); oParametros.put("PromocionClave", promocionClave); oParametros.put("PromocionReglaID", promocionReglaID); oParametros.put("CantidadGrupo", CantidadGrupoApp); oParametros.put("SubEmpresaID", SubEmpresaId); oParametros.put("CantidadMax", cantidad); oParametros.put("TipoValidarExistencia", mPresenta.getTipoValidacionExistencia()); oParametros.put("ProductoDisparador", productoDisparador); oParametros.put("CadenaListasPrecio", cadenaListasPrecios); iniciarActividadConResultado(IAplicacionPromocion.class, Solicitudes.SOLICITUD_MOSTRAR_PROMOCIONES_APLICADAS, Acciones.ACCION_APLICAR_PROMOCIONES, oParametros); } @SuppressWarnings("deprecation") public void mostrarObligatorio(String mensaje, final int tipoMensaje, String...titulo) { DialogoAlerta dialogo = new DialogoAlerta(this); dialogo.setMessage(mensaje); dialogo.setCancelable(false); String msgSi = "Si"; String msgNo = "No"; if (Mensajes.existe()) { msgSi = Mensajes.get("XSi"); msgNo = Mensajes.get("XNo"); } dialogo.setButton(msgSi, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { respuestaMensaje(RespuestaMsg.Si, tipoMensaje); dialog.dismiss(); } }); dialogo.setButton2(msgNo, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { respuestaMensaje(RespuestaMsg.No, tipoMensaje); dialog.cancel(); } }); dialogo.show(); } @SuppressWarnings("unchecked") @Override public void resultadoActividad(int requestCode, int resultCode, Intent data) { Button boton = (Button) findViewById(R.id.btnContinuar); boton.setEnabled(true); if (requestCode == Enumeradores.Solicitudes.SOLICITUD_BUSQUEDA_PRODUCTOS) { // si esta regresándo de la busqueda de productos if (resultCode == Enumeradores.Resultados.RESULTADO_BIEN) { // si selecciono Agregar en la busqueda de productos, obtener la // seleccion y agregarlos al pedido // DatosProductos productosSeleccionados; // productosSeleccionados = (DatosProductos) // data.getExtras().getParcelable("Objeto"); if (Sesion.get(Campo.ResultadoActividad) != null) { insertarSeleccion((HashMap<String, TransProdDetalle>) Sesion.get(Campo.ResultadoActividad)); Sesion.remove(Campo.ResultadoActividad); captura.setFinBusqueda(); }else{ captura.setFinBusqueda(); if(data != null) { txtScanner.setTexto(data.getStringExtra("mensajeIniciar")); captura.IngresaProductoBusquedaSimple(data.getStringExtra("mensajeIniciar")); } } } else if (resultCode == Enumeradores.Resultados.RESULTADO_MAL) { if (data != null) { String mensajeError = (String) data.getExtras().getString("mensajeIniciar"); if (!mensajeError.equals("")) { // cuando se presiona back se manda el mensaje vacio mostrarError(mensajeError); } } captura.setFinBusqueda(); } //captura.setFinBusqueda(); } else if (requestCode == Enumeradores.Solicitudes.SOLICITUD_MOSTRAR_PROMOCIONES_APLICADAS) { if (resultCode == Enumeradores.Resultados.RESULTADO_BIEN) { regresandoPromo = true; }else { if (data != null) { String mensajeError = (String) data.getExtras().getString("mensajeIniciar"); if (mensajeError.contains("SinPrecio")) { mostrarError(Mensajes.get("E0958", mensajeError.replace("SinPrecio", "")), 60); } } } } else if (requestCode == Enumeradores.Solicitudes.SOLICITUD_MOSTRAR_TOTALES) { // regreso de la pantalla de totales if (resultCode == Enumeradores.Resultados.RESULTADO_BIEN) { // si selecciono terminar, finalizar la captura del pedido setResult(Enumeradores.Resultados.RESULTADO_BIEN); finalizar(); } else if (resultCode == Enumeradores.Resultados.RESULTADO_MAL) { String mensajeError = (String) data.getExtras().getString("mensajeIniciar"); if (!mensajeError.equals("")) { // cuando se presiona back se manda el mensaje vacio this.setResultado(Enumeradores.Resultados.RESULTADO_MAL, mensajeError); finalizar(); } else { // si el mensaje esta vacio, presiono back mPresenta.eliminarPromos(); } } } else if (requestCode == Enumeradores.Solicitudes.SOLICITUD_MOSTRAR_PEDIDO_SUGERIDO) { // si esta regresándo de la busqueda de productos if (resultCode == Enumeradores.Resultados.RESULTADO_BIEN) { // si selecciono Agregar en la busqueda de productos, obtener la // seleccion y agregarlos al pedido // DatosProductos productosSeleccionados; // productosSeleccionados = (DatosProductos) // data.getExtras().getParcelable("Objeto"); if (Sesion.get(Campo.ResultadoActividad) != null) { insertarSeleccionSugerido((HashMap<String, HashMap<Short, TransProdDetalle>>) Sesion.get(Campo.ResultadoActividad)); Sesion.remove(Campo.ResultadoActividad); } } else if (resultCode == Enumeradores.Resultados.RESULTADO_MAL) { if (data != null) { String mensajeError = (String) data.getExtras().getString("mensajeIniciar"); if (!mensajeError.equals("")) { // cuando se presiona back se manda el mensaje vacio mostrarError(mensajeError); } } } }else if ((requestCode == Enumeradores.Solicitudes.SOLICITUD_SERVIDOR_COMUNICACIONES_ENVIO_PARCIAL) && (resultCode == Enumeradores.Resultados.RESULTADO_BIEN)) //si el envio parcial fue correcto, sincronizar el inventario mPresenta.obtenerInventarioEnLinea(); else if ((requestCode == Enumeradores.Solicitudes.SOLICITUD_SERVIDOR_COMUNICACIONES_ENVIO_PARCIAL || requestCode == Enumeradores.Solicitudes.SOLICITUD_SERVIDOR_COMUNICACIONES) && (resultCode == Enumeradores.Resultados.RESULTADO_MAL)) { if (data != null) { String mensajeError = (String) data.getExtras().getString("mensajeIniciar"); if (mensajeError != null) { iniciarActividad(ICapturaPedido.class, mensajeError); return; } } iniciarActividad(ICapturaPedido.class); } else if (requestCode == Enumeradores.Solicitudes.SOLICITUD_MOSTRAR_TOTALES_CONSIGNACION) { // regreso de la pantalla de totales if (resultCode == Enumeradores.Resultados.RESULTADO_BIEN) { // si selecciono terminar, finalizar la captura del pedido setResultado(Enumeradores.Resultados.RESULTADO_MAL); finalizar(); } else if (resultCode == Enumeradores.Resultados.RESULTADO_MAL) { if (!esNuevo) { // cuando se presiona back se manda el mensaje vacio if(mAccion.equals(Enumeradores.Acciones.ACCION_CAPTURAR_CONSIGNACIONES)) { salir(); }else{ this.setResultado(Enumeradores.Resultados.RESULTADO_BIEN); finalizar(); } } else { // si el mensaje esta vacio, presiono back mPresenta.eliminarPromos(); } } } else if (requestCode == Solicitudes.SOLICITUD_TOMAR_INVENTARIO_PEDIDO) { if (resultCode == Enumeradores.Resultados.RESULTADO_BIEN) { if (Sesion.get(Campo.ResultadoActividad) != null) { insertarSeleccion((HashMap<String, TransProdDetalle>) Sesion.get(Campo.ResultadoActividad)); Sesion.remove(Campo.ResultadoActividad); if (data != null) { String res = (String) data.getExtras().getString("mensajeIniciar"); if (!res.equals("")) { inventarioID = res; } } } }else if (resultCode == Enumeradores.Resultados.RESULTADO_MAL) { if (data != null) { String mensajeError = (String) data.getExtras().getString("mensajeIniciar"); if (!mensajeError.equals("")) { // cuando se presiona back se manda el mensaje vacio mostrarError(mensajeError); } } } } } @Override public void onDestroy() { super.onDestroy(); if (lista.getAdapter() != null){ stopManagingCursor(((Cursor) (((SimpleCursorAdapter) lista.getAdapter()).getCursor()))); ((Cursor) (((SimpleCursorAdapter) lista.getAdapter()).getCursor())).close(); } if (captura.getSpinnerUnidad() != null && captura.getSpinnerUnidad().getAdapter() != null){ stopManagingCursor(((Cursor) (((SimpleCursorAdapter) captura.getSpinnerUnidad().getAdapter()).getCursor()))); ((Cursor) (((SimpleCursorAdapter) captura.getSpinnerUnidad().getAdapter()).getCursor())).close(); } } @Override public void respuestaMensaje(RespuestaMsg respuesta, int tipoMensaje) { if (tipoMensaje == 2) { if (respuesta == RespuestaMsg.Si) { if (manejoDobleUnidad){ Cursor producto = (Cursor) (((SimpleCursorAdapter) lista.getAdapter()).getCursor()); HashMap<Short,InventarioDobleUnidad.DetalleProductoDobleUnidad> hmUnidades = new HashMap<Short,InventarioDobleUnidad.DetalleProductoDobleUnidad>(); hmUnidades.put(producto.getShort(producto.getColumnIndex("TipoUnidad")), new InventarioDobleUnidad.DetalleProductoDobleUnidad(producto.getShort(producto.getColumnIndex("TipoUnidad")), null, producto.getFloat(producto.getColumnIndex("Cantidad")),null, null, producto.getShort(producto.getColumnIndex("DecimalProd1")),null)); if(producto.getShort(producto.getColumnIndex("UnidadAlterna"))>0 ){ hmUnidades.put(producto.getShort(producto.getColumnIndex("UnidadAlterna")), new InventarioDobleUnidad.DetalleProductoDobleUnidad(producto.getShort(producto.getColumnIndex("UnidadAlterna")), null, producto.getFloat(producto.getColumnIndex("CantidadAlterna")),null, null, producto.getShort(producto.getColumnIndex("DecimalProd2")),null)); } mPresenta.eliminarDetalleDobleUnidad(producto.getString(producto.getColumnIndex("TransProdID")), producto.getString(producto.getColumnIndex("TransProdDetalleID")),producto.getString(producto.getColumnIndex("SubEmpresaId")), producto.getString(producto.getColumnIndex("ProductoClave")), hmUnidades,true); captura.limpiarProducto(); }else { Cursor producto = (Cursor) (((SimpleCursorAdapter) lista.getAdapter()).getCursor()); mPresenta.eliminarDetalle(producto.getString(producto.getColumnIndex("TransProdID")), producto.getString(producto.getColumnIndex("TransProdDetalleID")), producto.getString(producto.getColumnIndex("SubEmpresaId")), producto.getString(producto.getColumnIndex("ProductoClave")), producto.getShort(producto.getColumnIndex("TipoUnidad")), producto.getFloat(producto.getColumnIndex("Cantidad"))); captura.limpiarProducto(); } } mostrandoPregunta = false; } else if (tipoMensaje == 3) { if (respuesta == RespuestaMsg.Si) { regresar(); } } else if (tipoMensaje == 99) { // pregunta aplicar promocion /* * synchronized(mPausaCiclo){ siguiente = true; * mPausaCiclo.notifyAll(); } */ try { if (respuesta.equals(RespuestaMsg.Si)) { if (promociones.promocionActual.Tipo == com.amesol.routelite.actividades.Enumeradores.Promocion.Tipo.ProductoAcumulado) { if (promociones.reglaAcumActual != null) { promociones.reglaAcumActual.Aplicar(); promociones.promocionActual.SeAcepto = true; } } else { if (promociones.reglaActual != null) { promociones.reglaActual.Aplicar(); } } } promociones.SiguientePromocion(); } catch (Exception ex) { mostrarError(ex.getMessage()); } }else if(tipoMensaje == 50){ try { if (respuesta == RespuestaMsg.Si){ //ajustar inventario for(TransProdDetalle oTpd : prodSinExistencia){ if(oTpd.Promocion == 2){//Solo los regalados se ajustan, para los canjes hay que modificar el pedido porque hay recalculo implicado Inventario.ActualizarInventario(oTpd.ProductoClave, oTpd.TipoUnidad, oTpd.Cantidad, TiposTransProd.PEDIDO, TiposMovimientos.NO_DEFINIDO, ((Vendedor) Sesion.get(Campo.VendedorActual)).AlmacenID, true); oTpd.CantidadOriginal = oTpd.Cantidad; oTpd.Cantidad = 0; BDVend.guardarInsertar(oTpd); } } cuadreEnvases(); }else{ regresar(); } } catch (Exception e) { e.printStackTrace(); } }else if(tipoMensaje == 20){ if(respuesta == RespuestaMsg.Si){ //modificar pedido modificarPedidoReparto(); /*captura.setVisibility(View.VISIBLE); modificando = true; modificar.setEnabled(false); mPresenta.modificarPedido();*/ } }else if(tipoMensaje == 10){ if(respuesta == RespuestaMsg.Si){ //mostrarAdvertencia("Agregar Producto"); if (manejoDobleUnidad){ if (transprodIDEliminar == null) mPresenta.agregarProductoDobleUnidad(hmDetalleDobleUnidadAgregar, productoAgregar.ProductoClave, productoAgregar.SubEmpresaId, null); else { mPresenta.eliminarDetalleDobleUnidad(transprodIDEliminar, transprodDetalleIDEliminar, productoAgregar.SubEmpresaId, productoAgregar.ProductoClave, hmDetalleDobleUnidadAgregar, false); mPresenta.agregarProductoDobleUnidad(hmDetalleDobleUnidadAgregar, productoAgregar.ProductoClave, productoAgregar.SubEmpresaId, transprodDetalleIDEliminar); } }else { if (cantidadOriginalAgregar == null) mPresenta.agregarProductoUnidad(productoAgregar.ProductoClave, productoAgregar.SubEmpresaId, Short.parseShort(String.valueOf(tipoUnidadAgregar)), cantidadAgregar, Float.parseFloat("-1")); else { mPresenta.eliminarDetalle(transprodIDEliminar, transprodDetalleIDEliminar, productoAgregar.SubEmpresaId, productoAgregar.ProductoClave, Short.parseShort(String.valueOf(tipoUnidadAgregar)), cantidadOriginalAgregar, false); mPresenta.agregarProductoUnidad(productoAgregar.ProductoClave, productoAgregar.SubEmpresaId, tipoUnidadAgregar, cantidadAgregar, Float.parseFloat("-1"), cantidadOriginalAgregar); } } }else{ //mostrarAdvertencia("NO Agregar Producto"); } }else if(tipoMensaje == 30){ //cantidad maxima de producto if(respuesta == RespuestaMsg.Si){ if(existe){ mPresenta.eliminarDetalle(transprodIDEliminar, transprodDetalleIDEliminar, productoAgregar.SubEmpresaId, productoAgregar.ProductoClave, tipoUnidadAgregar, cantidadOriginalAgregar, false); if((Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.REPARTO)) mPresenta.agregarProductoUnidad(productoAgregar.ProductoClave, productoAgregar.SubEmpresaId, tipoUnidadAgregar, cantidadAgregar, Float.parseFloat("-1"),cantidadOriginalAgregar, transprodDetalleIDEliminar); else mPresenta.agregarProductoUnidad(productoAgregar.ProductoClave, productoAgregar.SubEmpresaId, tipoUnidadAgregar, cantidadAgregar, Float.parseFloat("-1"), cantidadOriginalAgregar); }else{ mPresenta.agregarProductoUnidad(productoAgregar.ProductoClave, productoAgregar.SubEmpresaId, tipoUnidadAgregar, cantidadAgregar, Float.parseFloat("-1")); } } }else if(tipoMensaje == 40){ if(respuesta == RespuestaMsg.Si){ //TODO: sperez CUROLMOV_18 1.4.1.1 try { TransProd oTrp = null; docsTransProd = mPresenta.getHashMapTransacciones().values().iterator(); if(docsTransProd.hasNext()){ oTrp = docsTransProd.next(); Transacciones.recolectarEnvasesAutomaticamente(oTrp, envasesPorRecolectar); } //envasesPorRecolectar.close(); //iniciarCapturaTotales(); } catch (Exception e) { e.printStackTrace(); } } envasesPorRecolectar.close(); iniciarCapturaTotales(); }else if(tipoMensaje ==0){ if(mPresenta.errorFinalizar){ finalizar(); } }else if (tipoMensaje == 60){ regresandoPromo = true; } } private void modificarPedidoReparto(){ //registerForContextMenu(lista); //lista.setOnItemLongClickListener(menu); captura.setVisibility(View.VISIBLE); modificando = true; modificar.setEnabled(false); Button boton = (Button) findViewById(R.id.btnContinuar); boton.setEnabled(true); if (manejoDobleUnidad){ mPresenta.modificarPedidoDobleUnidad(); }else { mPresenta.modificarPedido(); } } private void salir() { if (!esNuevo) { if (!soloLectura) mostrarPreguntaSiNo(Mensajes.get("BP0002"), 3); else { try{ //Se agrega este rollback porque al surtir pedido entra como solo lectura y estaba cambiando el //TipoPedido al entrar a los totales, lo que provocaba que el pedido desapareciera del listado BDVend.rollback(); }catch (Exception ex){ if (ex != null && ex.getMessage() != null){ mostrarError(ex.getMessage()); } } setResultado(Enumeradores.Resultados.RESULTADO_BIEN); finalizar(); } } else { if (hayProductos()) { if (!soloLectura) mostrarPreguntaSiNo(Mensajes.get("BP0002"), 3); else { setResultado(Enumeradores.Resultados.RESULTADO_BIEN); finalizar(); } } else { // no hay productos regresar(); } } } private void regresar() { try { if (esNuevo) { BDVend.rollback(); } else { if (huboCambios) BDVend.rollback(); } setResultado(Enumeradores.Resultados.RESULTADO_BIEN); finalizar(); } catch (Exception ex) { mostrarError(ex.getMessage()); } } @SuppressWarnings("rawtypes") public void insertarSeleccion(HashMap<String, TransProdDetalle> transProdDetalles) { try { Iterator<Entry<String, TransProdDetalle>> it = transProdDetalles.entrySet().iterator(); boolean bHuboInserciones = false; while (it.hasNext()) { // recorrer los productos Map.Entry producto = (Map.Entry) it.next(); String productoClave = producto.getKey().toString(); // int tipoUnidad =((TransProdDetalle) // producto.getValue()).TipoUnidad ; // Ya no es necesario buscar si existe porque se filtran los // productos que ya fueron capturados // Object aTransProdDetalle[] = // Consultas.ConsultasTransProdDetalle.obtenerDetallePorProductoClaveUnidad(productoClave, // String.valueOf(tipoUnidad), mPresenta.getTransaccionesIds()); boolean validar = false; Producto oProducto = Consultas.ConsultasProducto.obtenerProducto(productoClave); try { validar = mPresenta.validarProductoContenido(oProducto); } catch (Exception ex) { mostrarError(ex.getMessage().equals("") ? ex.getCause().getMessage() : ex.getMessage()); } if (/* aTransProdDetalle== null && */validar) { // agregarlo solo si no existe try { bHuboInserciones = true; //mPresenta.agregarProductoUnidad(oProducto.SubEmpresaId, ((TransProdDetalle) producto.getValue()), false); mPresenta.agregarProductoUnidad(oProducto, ((TransProdDetalle) producto.getValue()), false); } catch (Exception ex) { mostrarError(ex.getMessage().equals("") ? ex.getCause().getMessage() : ex.getMessage()); } } } if (bHuboInserciones) { refrescarProductos(mPresenta.getTransaccionesIds()); } } catch (Exception ex) { mostrarError(ex.getMessage()); } } @SuppressWarnings( { "rawtypes", "unchecked" }) public void insertarSeleccionSugerido(HashMap<String, HashMap<Short, TransProdDetalle>> transProdDetalles) { try { boolean bHuboInserciones = false; Iterator<Entry<String, HashMap<Short, TransProdDetalle>>> itProd = transProdDetalles.entrySet().iterator(); while (itProd.hasNext()) { Map.Entry producto = (Map.Entry) itProd.next(); boolean validar = false; Producto oProducto = Consultas.ConsultasProducto.obtenerProducto(producto.getKey().toString()); try { validar = mPresenta.validarProductoContenido(oProducto); } catch (Exception ex) { mostrarError(ex.getMessage().equals("") ? ex.getCause().getMessage() : ex.getMessage()); } Iterator<Entry<Short, TransProdDetalle>> it = ((HashMap<Short, TransProdDetalle>) producto.getValue()).entrySet().iterator(); while (it.hasNext()) { // recorrer los productos Map.Entry productoUnidad = (Map.Entry) it.next(); // Los productos que ya estan capturados no se permite editar //por lo que no es necesario verificar la existencia, ademas, ya se valido el inventario en caso de ser necesario. if (validar) { // agregarlo solo si no existe try { bHuboInserciones = true; //mPresenta.agregarProductoUnidad(oProducto.SubEmpresaId, ((TransProdDetalle) productoUnidad.getValue()), false); mPresenta.agregarProductoUnidad(oProducto, ((TransProdDetalle) productoUnidad.getValue()), false); } catch (Exception ex) { mostrarError(ex.getMessage().equals("") ? ex.getCause().getMessage() : ex.getMessage()); } } } } if (bHuboInserciones) { refrescarProductos(mPresenta.getTransaccionesIds()); } } catch (Exception ex) { mostrarError(ex.getMessage()); } } public void setProductoActual(Producto producto) { txtScanner.setTexto(producto.ProductoClave); txtScanner.setTag(producto.SubEmpresaId); } public void setListaPrecios(String valor) { TextView texto = (TextView) findViewById(R.id.lblListaPrecios); texto.setText(valor); } public void setHuboCambios(boolean cambio) { huboCambios = cambio; } public boolean getSurtir() { return surtir; } public boolean getModificandoPedidoReparto() { return modificando; } public boolean getModificandoPedidoNoReparto() { return modificandoAutoventa; } public boolean getReparto() { return reparto; } private OnClickListener mPedidoSugerido = new OnClickListener() { @Override public void onClick(View v) { final HashMap<String, Object> parametros = new HashMap<String, Object>(); parametros.put("ListaPrecios", mPresenta.getListasPrecios()); parametros.put("TransProd", mPresenta.getTransProdIds()); parametros.put("tipoValidacionExistencia", mPresenta.getTipoValidacionExistencia()); parametros.put("ModuloMovDetalle", mPresenta.getModuloMovDetalle()); parametros.put("mostrarValIniciales", !sugeridoMostrado); sugeridoMostrado = true; iniciarActividadConResultado(ICapturaPedidoSugerido.class, Enumeradores.Solicitudes.SOLICITUD_MOSTRAR_PEDIDO_SUGERIDO, Enumeradores.Acciones.ACCION_CAPTURAR_SUGERIDO, parametros); } }; /** * Para el caso del modulo de consignaciones que reutiliza esta actividad, se deberá * de validar la bandera CancConsigLiqui para calcular o no promociones. */ private OnClickListener mAplicarPromociones = new OnClickListener() { @Override public void onClick(View v) { Button boton = (Button) findViewById(R.id.btnContinuar); boton.setEnabled(false); if (!hayProductos()) { mostrarError(Mensajes.get("MDBAsignarProducto")); boton.setEnabled(true); } else { boolean cancConsigLiqui = "0".equals(((CONHist)Sesion.get(Campo.CONHist)).get("CancConsigLiqui")); if(consultar || (mPresenta.getModuloMovDetalle().TipoTransProd == TiposTransProd.VENTA_CONSIGNACION && cancConsigLiqui) || (mAccion != null && mAccion.equals(Enumeradores.Acciones.ACCION_ELIMINAR_CONSIGNACIONES))){ Sesion.set(Campo.ArrayTransProd, mPresenta.getHashMapTransacciones()); iniciarCapturaTotales(); boton.setEnabled(true); }else{ Sesion.set(Campo.ArrayTransProd, mPresenta.getHashMapTransacciones()); mPausaCiclo = new Object(); docsTransProd = mPresenta.getHashMapTransacciones().values().iterator(); if (docsTransProd.hasNext()) { calcularPromociones(docsTransProd.next()); } } } } }; private boolean hayProductos() { TextView totalProductos = (TextView) findViewById(R.id.txtTotalProductos); if (totalProductos.getText().toString().trim().equals("") || Float.parseFloat(totalProductos.getText().toString().replace(",", ".")) == 0) return false; else return true; } private void calcularPromociones(TransProd transProd) { // for(final Object transProd : // mPresenta.getHashMapTransacciones().values().toArray()){ //recorrer // todas las transacciones generadas y aplicar las promociones // correspondientes try { siguiente = false; try { BDVend.recuperar((TransProd) transProd, TransProdDetalle.class); for (TransProdDetalle oTpd : ((TransProd) transProd).TransProdDetalle) { BDVend.recuperar(oTpd, TPDImpuesto.class); } } catch (Exception e) { e.printStackTrace(); } promociones = new Promociones2((TransProd) transProd, (Vista) this, modificando); promociones.setOnTerminarAplicacionListener(new onTerminarAplicacionListener() { @Override public void onTerminarAplicacion() { if (docsTransProd.hasNext()) { calcularPromociones(docsTransProd.next()); } else { //validar reparto aqui? *********** no validar inv para msiev if(Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.REPARTO && mPresenta.getTipoTransProd() != 21 && surtir && reparto ){ //validar inventario despues de calcular las promociones, se validan tambien los productos promocionales try { if (manejoDobleUnidad) { prodSinExistencia = mPresenta.validarInventarioASurtirDobleUnidad(); }else{ prodSinExistencia = mPresenta.validarInventarioASurtir(); } }catch(Exception ex){ mostrarError("Error al validar inventario"); return; } if(prodSinExistencia.size() != 0){ boolean soloPromo = true; String productosNoPromo = ""; String productosPromo = ""; String productosCanje = ""; for(TransProdDetalle oTpd : prodSinExistencia){ //Los productos tipo Canje no se ajustan, solo modificando el pedido, ya que hay recalculo if(oTpd.Promocion != 2 && oTpd.Promocion != 3){ productosNoPromo += oTpd.ProductoClave + ", "; soloPromo = false; }else if(oTpd.Promocion == 2){ productosPromo += oTpd.ProductoClave + ", "; }else if(oTpd.Promocion == 3) { productosCanje += oTpd.ProductoClave + ", "; } } if(productosNoPromo != ""){ productosNoPromo = productosNoPromo.substring(0, productosNoPromo.length() - 2); } if(productosPromo != "" && soloPromo){ productosPromo = productosPromo.substring(0, productosPromo.length() - 2); } if(productosCanje != "" && soloPromo){ productosCanje = productosCanje.substring(0, productosCanje.length() - 2); } if(productosNoPromo != ""){ mostrarAdvertencia(Mensajes.get("E0714").replace("$0$", productosNoPromo)); return; }else if(productosCanje!=""){ mostrarAdvertencia(Mensajes.get("E0714").replace("$0$", " tipo Canje " + productosCanje )); return; }else if(productosPromo != ""){ mostrarPreguntaSiNo(Mensajes.get("P0209", productosPromo), 50); return; } } } //Lo que estaba del cuadre de envase se manda a un método separado //para poder llamarlo en la respuesta afirmativa del mensaje P0209 cuadreEnvases(); } } }); if (Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.REPARTO && mPresenta.getTipoTransProd() != 21 && surtir && !modificando){ //Se recorre hasta el final para que no se aplique ninguna promocion while (docsTransProd.hasNext()){ docsTransProd.next(); } promociones.TerminarAplicacionSinCalculos(); return; } if (promociones.Preparar()) { try { BDVend.recuperar((TransProd) transProd); BDVend.recuperar((TransProd) transProd, TransProdDetalle.class); // obtener todos los impuestos para que se recalculen // correctamente for (TransProdDetalle oTpd : ((TransProd) transProd).TransProdDetalle) { BDVend.recuperar(oTpd, TPDImpuesto.class); } } catch (Exception e) { e.printStackTrace(); } } promociones.Aplicar(); } catch (Exception e) { mostrarError(e.getMessage()); } } @SuppressWarnings("rawtypes") private void iniciarCapturaTotales(){ HashMap<String, Object> oParametros = new HashMap<String, Object>(); ArrayList<String> nuevo = new ArrayList<String>(); nuevo.add(String.valueOf(esNuevo)); ArrayList<String> transprod = new ArrayList<String>(); Iterator it = mPresenta.getHashMapTransacciones().entrySet().iterator(); while (it.hasNext()) { // recorrer todas las transacciones generadas para // calcular totales, impuestos, descuentos, etc ... Map.Entry e = (Map.Entry) it.next(); transprod.add(((TransProd) e.getValue()).TransProdID); } oParametros.put("TransProdId", transprod); oParametros.put("esNuevo", nuevo); oParametros.put("ModuloMovDetalle", mPresenta.getModuloMovDetalle()); oParametros.put("TotalInicial", mPresenta.getTotalInicial()); oParametros.put("Surtir", Boolean.toString(surtir)); oParametros.put("Modificando", Boolean.toString(modificando)); oParametros.put("ModificandoAutoventa", Boolean.toString(modificandoAutoventa)); if(mPresenta.getModuloMovDetalle().TipoTransProd == TiposTransProd.VENTA_CONSIGNACION) { iniciarActividadConResultado(ICapturaTotalesConsignacion.class, Enumeradores.Solicitudes.SOLICITUD_MOSTRAR_TOTALES_CONSIGNACION, mAccion, oParametros); }else { iniciarActividadConResultado(ICapturaTotales.class, Enumeradores.Solicitudes.SOLICITUD_MOSTRAR_TOTALES, Enumeradores.Acciones.ACCION_APLICAR_TOTALES, oParametros); } } public Handler getHandler() { return handler; } public Object getPausaCiclo() { return mPausaCiclo; } /* * public boolean getSiguiente(){ return siguiente; } */ public void setSiguiente(boolean bsiguiente) { siguiente = bsiguiente; } @SuppressWarnings("deprecation") public void refrescarProductos(String TransProdId) { try { // limpiarProducto(); // ocultarTeclado(); if (manejoDobleUnidad){ refrescarProductosDobleUnidad(TransProdId); return; } boolean existe = false; if (lista.getAdapter() != null){ stopManagingCursor(((Cursor) (((SimpleCursorAdapter) lista.getAdapter()).getCursor()))); ((Cursor) (((SimpleCursorAdapter) lista.getAdapter()).getCursor())).close(); existe = true; } ISetDatos stTransProdDetalle = Consultas.ConsultasTransProdDetalle.obtenerDetalle(TransProdId); Cursor cProductos = (Cursor) stTransProdDetalle.getOriginal(); startManagingCursor(cProductos); try { obtenerTotales(TransProdId); SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.elemento_captura_producto, cProductos, new String[] { "TipoUnidad", "ProductoClave", "Descripcion", "Precio", "Cantidad", "Total", "Existencia", "CantidadOriginal" }, new int[] { R.id.lblUnidadProductoClave, R.id.lblUnidadProductoClave, R.id.lblDescripcion, R.id.lblPU, R.id.lblCantidad, R.id.lblTotal, R.id.lblExistencia, R.id.lblCantidadOriginal }); adapter.setViewBinder(new vista()); lista.setAdapter(adapter); lista.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View v, int pos, long arg3) { captura.setEnableCantidadAgregar(true); if (oParametros != null && (!oParametros.get("TransProdId").trim().equals("")) && (mPresenta.getTipoFase() == 0 || mPresenta.getTipoFase() == 2) && calculando) { // si recibio el transprodid como parametro y esta // cancelado o surtido, mostrar cantidad de solo // lectura return; } // calculando = true; Cursor producto = (Cursor) (((SimpleCursorAdapter) lista.getAdapter()).getCursor()); Log.d("CapturaPedido", "Producto Seleccionado: " + producto.getString(producto.getColumnIndex("ProductoClave"))); // final String TransProdId = producto.getString(producto.getColumnIndex("TransProdID")); // final String TransProdDetalleId = producto.getString(producto.getColumnIndex("TransProdDetalleID")); lista.requestFocusFromTouch(); lista.setSelection(pos); // Se crea el objeto producto con lo que se trae en la // consulta para eficientar tiempos. Producto oProducto = new Producto(); oProducto.ProductoClave = producto.getString(producto.getColumnIndex("ProductoClave")); oProducto.Nombre = producto.getString(producto.getColumnIndex("Descripcion")); oProducto.SubEmpresaId = producto.getString(producto.getColumnIndex("SubEmpresaId")); oProducto.Venta = ((producto.getShort(producto.getColumnIndex("Venta")) == 1) ? true : false); oProducto.Contenido = ((producto.getShort(producto.getColumnIndex("Contenido")) == 1) ? true : false); captura.llenarProductoUnidad(oProducto, producto.getInt(producto.getColumnIndex("TipoUnidad")), producto.getFloat(producto.getColumnIndex("Cantidad"))); } } ); stopManagingCursor(cProductos); } catch (Exception e) { mostrarError(e.getMessage()); } txtScanner.requestFocus(); calculando = false; } catch (Exception ex) { mostrarError(ex.getMessage()); } } @SuppressWarnings("deprecation") public void refrescarProductosDobleUnidad(String TransProdIds) { try { // limpiarProducto(); // ocultarTeclado(); boolean existe = false; if (lista.getAdapter() != null){ stopManagingCursor(((Cursor) (((SimpleCursorAdapter) lista.getAdapter()).getCursor()))); ((Cursor) (((SimpleCursorAdapter) lista.getAdapter()).getCursor())).close(); existe = true; } ISetDatos stTransProdDetalle = Consultas.ConsultasTransProdDetalle.obtenerDetalleDobleUnidad(TransProdIds); Cursor cProductos = (Cursor) stTransProdDetalle.getOriginal(); startManagingCursor(cProductos); try { obtenerTotales(TransProdIds); SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.elemento_captura_prod_doble_unidad, cProductos, new String[] { "TipoUnidad", "Cantidad","UnidadAlterna","CantidadAlterna","ProductoClave", "Precio", "Total"}, new int[] { R.id.lblUnidad1, R.id.lblCantidad1, R.id.lblUnidad2, R.id.lblCantidad2, R.id.lblProducto,R.id.lblPU, R.id.lblTotal}); adapter.setViewBinder(new vistaDobleUnidad()); lista.setAdapter(adapter); lista.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View v, int pos, long arg3) { captura.setEnableCantidadAgregar(true); if (oParametros != null && (!oParametros.get("TransProdId").trim().equals("")) && (mPresenta.getTipoFase() == 0 || mPresenta.getTipoFase() == 2) && calculando) { // si recibio el transprodid como parametro y esta // cancelado o surtido, mostrar cantidad de solo // lectura return; } // calculando = true; Cursor producto = (Cursor) (((SimpleCursorAdapter) lista.getAdapter()).getCursor()); Log.d("CapturaPedido", "Producto Seleccionado: " + producto.getString(producto.getColumnIndex("ProductoClave"))); // final String TransProdId = producto.getString(producto.getColumnIndex("TransProdID")); // final String TransProdDetalleId = producto.getString(producto.getColumnIndex("TransProdDetalleID")); lista.requestFocusFromTouch(); lista.setSelection(pos); // Se crea el objeto producto con lo que se trae en la // consulta para eficientar tiempos. Producto oProducto = new Producto(); oProducto.ProductoClave = producto.getString(producto.getColumnIndex("ProductoClave")); oProducto.Nombre = producto.getString(producto.getColumnIndex("Descripcion")); oProducto.SubEmpresaId = producto.getString(producto.getColumnIndex("SubEmpresaId")); oProducto.Venta = ((producto.getShort(producto.getColumnIndex("Venta")) == 1) ? true : false); oProducto.Contenido = ((producto.getShort(producto.getColumnIndex("Contenido")) == 1) ? true : false); HashMap<Short,Float> hmUnidades = new HashMap<Short,Float>(); hmUnidades.put(producto.getShort(producto.getColumnIndex("TipoUnidad")), producto.getFloat(producto.getColumnIndex("Cantidad"))); if(producto.getShort(producto.getColumnIndex("UnidadAlterna"))>0 ){ hmUnidades.put(producto.getShort(producto.getColumnIndex("UnidadAlterna")), producto.getFloat(producto.getColumnIndex("CantidadAlterna"))); } captura.llenarProductoDobleUnidad(oProducto,hmUnidades); } } ); stopManagingCursor(cProductos); } catch (Exception e) { mostrarError(e.getMessage()); } txtScanner.requestFocus(); calculando = false; } catch (Exception ex) { mostrarError(ex.getMessage()); } } private void obtenerTotales(String TransProdID) { try { ISetDatos setDatos = Consultas.ConsultasTransProdDetalle.obtenerTotales(TransProdID); if (setDatos.moveToNext()) { TextView texto = (TextView) findViewById(R.id.txtTotalPrevio); Float totalCanjes = Consultas.ConsultasTransProdDetalle.obtenerTotalesCanjes(TransProdID); texto.setText(Generales.getFormatoDecimal(setDatos.getFloat(1) - (totalCanjes == null ? 0 : totalCanjes), "$ #,##0.00")); texto = (TextView) findViewById(R.id.txtTotalProductos); texto.setText(String.format("%.0f", setDatos.getFloat(0))); texto = (TextView) findViewById(R.id.txtTotalUnidades); texto.setText(String.format("%.0f", setDatos.getFloat("Unidades"))); String peso$volumen = String.format("%.2f", setDatos.getFloat("Peso")) + " / "; peso$volumen += String.format("%.2f", setDatos.getFloat("Volumen")); texto = (TextView) findViewById(R.id.txtVolumen); texto.setText(peso$volumen); } setDatos.close(); if(mnu != null){ if(hayProductos()){ mnu.getItem(1).setEnabled(false); }else{ mnu.getItem(1).setEnabled(true); } } } catch (Exception e) { mostrarError(e.getMessage()); //mostrarError(e); } } public void ocultarPedidoSugerido() { Button boton = (Button) findViewById(R.id.btnSugerido); boton.setVisibility(View.GONE); boton = (Button) findViewById(R.id.btnContinuar); android.widget.LinearLayout.LayoutParams param = new LinearLayout.LayoutParams( 0, LayoutParams.WRAP_CONTENT, 0.9f); boton.setLayoutParams(param); } @Override public boolean onCreateOptionsMenu(Menu menu) { if (mPresenta.errorFinalizar) return false; MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_captura_pedido, menu); menu.getItem(0).setTitle(Mensajes.get("XPromociones")); menu.getItem(1).setTitle(Mensajes.get("XActualizar") + " " + Mensajes.get("XInventario")); menu.getItem(2).setTitle(Mensajes.get("XModificar")); menu.getItem(3).setTitle(Mensajes.get("MCNMostrarUltimaVenta")); menu.getItem(4).setTitle(Mensajes.get("XAcMenVen")); menu.getItem(5).setTitle(Mensajes.get("XSaldoEnvases")); menu.getItem(6).setTitle(Mensajes.get("XTomaInventario")); //if(!(((Ruta) Sesion.get(Campo.RutaActual)).Inventario && Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.PREVENTA)){ menu.getItem(1).setVisible(false); //} menu.getItem(2).setVisible(false); menu.getItem(5).setVisible(false); menu.getItem(6).setVisible(false); if(Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.REPARTO && mPresenta.getTipoFase() == TiposFasesDocto.CAPTURA && mPresenta.getTipoTransProd() == TiposTransProd.PEDIDO && reparto && surtir){// || (Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.REPARTO && surtir)){ menu.getItem(2).setVisible(true); } MOTConfiguracion motConf = (MOTConfiguracion) Sesion.get(Campo.MOTConfiguracion); if(motConf.get("MostrarUltVta").equals("0")){ menu.getItem(3).setVisible(false); } if(!Consultas.ConsultasClienteVentaMensual.existeInformacion( ((Cliente)Sesion.get(Campo.ClienteActual)).ClienteClave)){ menu.getItem(4).setVisible(false); } if ( (Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.VENTA || Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.REPARTO) && mPresenta.getTipoTransProd() == TiposTransProd.PEDIDO && ((Cliente)Sesion.get(Campo.ClienteActual)).Prestamo ) { menu.getItem(5).setVisible(true); } try { if (((ConfigParametro) Sesion.get(Campo.ConfigParametro)).existeParametro("TomaInventario") && ((ConfigParametro) Sesion.get(Campo.ConfigParametro)).get("TomaInventario").equals("1")) { menu.getItem(6).setVisible(true); } }catch(Exception ex){ mostrarError("Error al recuperar"); } mnu = menu; return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.promociones: mPresenta.consultarPromociones(); return true; case R.id.actualizar: mPresenta.obtenerInventarioEnLinea(); return true; case R.id.modificar: //modificar pedido de reparto modificar = item; if(mPresenta.getTipoFase() != TiposFasesDocto.CAPTURA_ESCRITORIO) mostrarPreguntaSiNo(Mensajes.get("P0232"), 20); else{ modificarPedidoReparto(); /*captura.setVisibility(View.VISIBLE); modificando = true; modificar.setEnabled(false); mPresenta.modificarPedido();*/ } return true; case R.id.ultimavta: iniciarActividad(IConsultaUltimaVenta.class,null,null,false); return true; case R.id.ventaMensual: mostrarVentaMensual(); return true; case R.id.saldoEnvase: mostrarSaldoEnvase(); return true; case R.id.tomaInventario: if (hayProductos()){ mostrarError(Mensajes.get("I0297")); }else { HashMap<String, Object> oParametros = new HashMap<String, Object>(); oParametros.put("ListasPrecio", mPresenta.getListasPrecios()); oParametros.put("TipoValidarExistencia", mPresenta.getTipoValidacionExistencia()); if (inventarioID!= null && !inventarioID.equals("")) { oParametros.put("InventarioID", inventarioID); } iniciarActividadConResultado(ICapturaInventario.class, Solicitudes.SOLICITUD_TOMAR_INVENTARIO_PEDIDO, Acciones.ACCION_TOMAR_INVENTARIO_PEDIDO, oParametros); } return true; default: return super.onOptionsItemSelected(item); } } public void setSurtir(boolean surtir){ this.surtir = surtir; } public void setSoloLectura(boolean soloLectura){ this.soloLectura = soloLectura; } public void setEsNuevo(boolean esNuevo){ this.esNuevo = esNuevo; } public void setCapturaEnabled(boolean enabled){ captura.setEnabled(enabled); } // viewbinder para la lista de productos private class vista implements ViewBinder { @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { int viewId = view.getId(); switch (viewId) { case android.R.id.text1: // para llenar el combo TextView combo = (TextView) view; combo.setText(ValoresReferencia.getDescripcion("UNIDADV", cursor.getString(cursor.getColumnIndex("PRUTipoUnidad")))); break; case R.id.lblUnidadProductoClave: TextView unidadproducto = (TextView) view; if (columnIndex == 6) { // tipo unidad unidadproducto.setText(ValoresReferencia.getDescripcion("UNIDADV", cursor.getString(cursor.getColumnIndex("TipoUnidad")))); } else if (columnIndex == 3) { // producto clave unidadproducto.setText(unidadproducto.getText() + " - " + cursor.getString(columnIndex)); } break; case R.id.lblPU: case R.id.lblTotal: TextView total = (TextView) view; total.setText(Generales.getFormatoDecimal(cursor.getFloat(columnIndex), "$ #,##0.00")); break; case R.id.lblExistencia: // mostrar la existencia con los decimales configurados TextView existencia = (TextView) view; if (mPresenta.getTipoValidacionExistencia() == TiposValidacionInventario.NoValidar) { existencia.setVisibility(View.GONE); } else { existencia.setText(Generales.getFormatoDecimal(cursor.getFloat(columnIndex), cursor.getInt(cursor.getColumnIndex("DecimalProducto")))); } break; case R.id.lblCantidad: TextView cantidad = (TextView) view; cantidad.setText(Generales.getFormatoDecimal(cursor.getFloat(columnIndex), cursor.getInt(cursor.getColumnIndex("DecimalProducto")))); break; case R.id.lblDescripcion: TextView lblDescripcion = (TextView) view; lblDescripcion.setText(cursor.getString(columnIndex)); break; default: TextView texto = (TextView) view; texto.setText(cursor.getString(columnIndex)); break; } return true; } } private class vistaDobleUnidad implements ViewBinder { @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { int viewId = view.getId(); switch (viewId) { /*case android.R.id.text1: // para llenar el combo TextView combo = (TextView) view; combo.setText(ValoresReferencia.getDescripcion("UNIDADV", cursor.getString(cursor.getColumnIndex("PRUTipoUnidad")))); break;*/ case R.id.lblUnidad1: TextView unidadproducto1 = (TextView) view; unidadproducto1.setText(ValoresReferencia.getDescripcion("UNIDADV", cursor.getString(cursor.getColumnIndex("TipoUnidad")))); break; case R.id.lblUnidad2: TextView unidadproducto2 = (TextView) view; if (cursor.getString(cursor.getColumnIndex("UnidadAlterna")) != null) { unidadproducto2.setText(ValoresReferencia.getDescripcion("UNIDADV", cursor.getString(cursor.getColumnIndex("UnidadAlterna")))); }else{ unidadproducto2.setText(""); } break; case R.id.lblPU: case R.id.lblTotal: TextView total = (TextView) view; total.setText(Generales.getFormatoDecimal(cursor.getFloat(columnIndex), "$ #,##0.00")); break; case R.id.lblCantidad1: TextView cantidad1 = (TextView) view; cantidad1.setText(Generales.getFormatoDecimal(cursor.getFloat(columnIndex), cursor.getInt(cursor.getColumnIndex("DecimalProd1")))); break; case R.id.lblCantidad2: TextView cantidad2 = (TextView) view; if ( cursor.getFloat(columnIndex)>0) { cantidad2.setText(Generales.getFormatoDecimal(cursor.getFloat(columnIndex), cursor.getInt(cursor.getColumnIndex("DecimalProd2")))); }else{ cantidad2.setText(""); } break; case R.id.lblProducto: TextView producto = (TextView) view; producto.setText(cursor.getString(columnIndex) + " - " + cursor.getString(cursor.getColumnIndex("Descripcion"))); break; default: TextView texto = (TextView) view; texto.setText(cursor.getString(columnIndex)); break; } return true; } } private class vistaListasPrecios implements ViewBinder { @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { int viewId = view.getId(); switch (viewId) { case R.id.txtCol2: TextView total = (TextView) view; total.setText(Generales.getFormatoDecimal(cursor.getFloat(columnIndex), "$ #,##0.00")); break; default: TextView texto = (TextView) view; texto.setText(cursor.getString(columnIndex)); break; } return true; } } private void mostrarVentaMensual(){ VentaMensual vm = VentaMensual.newInstance( ((Cliente)Sesion.get(Campo.ClienteActual)).ClienteClave); getFragmentManager().beginTransaction(). setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out). add(R.id.layout_captura_pedido, vm, FRAGMENT_TAG).commit(); } private void mostrarSaldoEnvase() { try{ LayoutInflater inflater = (LayoutInflater) CapturaPedido.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View dialogView = inflater.inflate(R.layout.dialog_saldoenvase, null); AlertDialog.Builder builder = new AlertDialog.Builder(this); TextView lbl = (TextView) dialogView.findViewById(R.id.lblTituloDialogoSaldoEnvase); lbl.setText(Mensajes.get("XSaldoEnvases")); lbl = (TextView) dialogView.findViewById(R.id.lblClave); lbl.setText(Mensajes.get("XClave")); lbl = (TextView) dialogView.findViewById(R.id.lblCargo); lbl.setText(Mensajes.get("XCargo")); lbl = (TextView) dialogView.findViewById(R.id.lblAbono); lbl.setText(Mensajes.get("XAbono")); lbl = (TextView) dialogView.findViewById(R.id.lblVenta); lbl.setText(Mensajes.get("XVenta")); lbl = (TextView) dialogView.findViewById(R.id.lblSaldo); lbl.setText(Mensajes.get("XSaldo")); ListView modeList = (ListView) dialogView.findViewById(R.id.lstSaldoEnvase); modeList.setBackgroundColor(Color.WHITE); Cursor cursor = mPresenta.obtenerSaldoEnvase(); SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,R.layout.lista_simple_hor5,cursor, new String[]{"ProductoClave","Cargo","Abono","Venta","Saldo"}, new int[]{R.id.txtCol1,R.id.txtCol2,R.id.txtCol3,R.id.txtCol4,R.id.txtCol5}); modeList.setAdapter(adapter); builder.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); builder.setView(dialogView); final Dialog dialog = builder.create(); dialog.show(); }catch(Exception e){ mostrarError(e.getMessage()); e.printStackTrace(); } } private void cuadreEnvases(){ Cliente oCliente = (Cliente) Sesion.get(Campo.ClienteActual); boolean iniciarTotales = true; //bandera para iniciar la captura de totales MOTConfiguracion oMC = (MOTConfiguracion) Sesion.get(Campo.MOTConfiguracion); if(( (Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.REPARTO && !surtir && !reparto) || Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.VENTA) //&& mPresenta.getTipoTransProd() == 1 && oCliente.Prestamo && oCliente.LimiteEnvase == 0 ){ && mPresenta.getTipoTransProd() == TiposTransProd.PEDIDO && oMC.get("CuadreDeEnvase").toString().equals("1") && oCliente.Prestamo ){ //TODO sperez CUROLMOV18 Anexo 3 punto 1.1: cuadre de envase try { String transprodIds = mPresenta.getTransProdIds(); envasesPorRecolectar = Consultas.ConsultasTransProd.obtenerDiferenciaEnvase(transprodIds); String sProductos = ""; while(envasesPorRecolectar.moveToNext()){ float dif = envasesPorRecolectar.getFloat("Diferencia"); int decimales = envasesPorRecolectar.getInt("DecimalProducto"); if(dif > 0){ sProductos += envasesPorRecolectar.getString("ProductoDetClave") + " (" + String.format("%."+decimales+"f",dif) + "), "; } } if(sProductos.length() > 0){ sProductos = sProductos.substring(0,sProductos.length()-2); mostrarPreguntaSiNo(Mensajes.get("P0242").replace("$0$", sProductos), 40); iniciarTotales = false; //no iniciar totales para poder mostrar y contestar la pregunta } }catch (Exception e){ e.printStackTrace(); } } if(iniciarTotales){ iniciarCapturaTotales(); } } private CapturaProducto.onAgregarProductoListener mAgregarProductoListener = new CapturaProducto.onAgregarProductoListener() { @Override public void onAgregarProducto (Producto producto,int tipoUnidad, float cantidad) { try { Object aTransProdDetalle[] = Consultas.ConsultasTransProdDetalle.obtenerDetallePorProductoClaveUnidad(producto.ProductoClave, String.valueOf(tipoUnidad), mPresenta.getTransaccionesIds()); MOTConfiguracion motConf = (MOTConfiguracion) Sesion.get(Campo.MOTConfiguracion); //validacion NoAdicionProducto if(modificando == true && (Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.REPARTO) && motConf.get("NoAdicionProducto").toString().equals("1")){ if(aTransProdDetalle == null){ //no existe en el pedido, no se puede agregar mostrarAdvertencia(Mensajes.get("E0908")); return; } //si existe, validar cantidades float valorOriginal = Float.parseFloat(aTransProdDetalle[2].toString()); float valorActual = cantidad; if(valorOriginal < valorActual){ captura.setEnableCantidadAgregar(false); mostrarAdvertencia(Mensajes.get("E0908")); return; } } if (aTransProdDetalle != null) { // si ya existe, seleccionarlo de la lista E0714 if (Float.parseFloat(aTransProdDetalle[2].toString()) != cantidad) { AtomicReference<Float> existencia = new AtomicReference<Float>(); StringBuilder error = new StringBuilder(); if (mPresenta.getTipoValidacionExistencia() != TiposValidacionInventario.NoValidar) { if (!Inventario.ValidarExistencia(producto.ProductoClave, tipoUnidad, cantidad, Float.parseFloat(aTransProdDetalle[2].toString()), mPresenta.getModuloMovDetalle(), false, existencia, error)) { captura.setError(error.toString()); if (mPresenta.getTipoValidacionExistencia() == TiposValidacionInventario.ValidacionRestrictiva) { if(!validarVenderApartado(producto, Short.parseShort(String.valueOf(tipoUnidad)) , cantidad, Float.parseFloat(aTransProdDetalle[2].toString()),aTransProdDetalle[0].toString(),aTransProdDetalle[1].toString())) return; if (existencia.get() != null && existencia.get() > 0) { captura.setCantidad(Float.parseFloat(aTransProdDetalle[2].toString()) + existencia.get()); } else { captura.setCantidad(cantidad); } return; } } else { captura.setAdvertencia(error.toString()); } } if(!mPresenta.validarCantMax(cantidad)){ //no esta configurada ninguna cantidad, continuar normal mPresenta.eliminarDetalle(aTransProdDetalle[0].toString(), aTransProdDetalle[1].toString(), producto.SubEmpresaId, producto.ProductoClave, tipoUnidad, Float.parseFloat(aTransProdDetalle[2].toString()), false); if((Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.REPARTO)) mPresenta.agregarProductoUnidad(producto.ProductoClave, producto.SubEmpresaId, tipoUnidad, cantidad, Float.parseFloat("-1"),Float.parseFloat(aTransProdDetalle[2].toString()), aTransProdDetalle[1].toString()); else mPresenta.agregarProductoUnidad(producto.ProductoClave, producto.SubEmpresaId, tipoUnidad, cantidad, Float.parseFloat("-1"), aTransProdDetalle[1].toString()); }else{ //guardar la info en las varibles para poder agregar el producto si contesta que si a la pregunta productoAgregar = producto; tipoUnidadAgregar = Short.parseShort(String.valueOf(tipoUnidad)) ; cantidadAgregar = cantidad; cantidadOriginalAgregar = Float.parseFloat(aTransProdDetalle[2].toString()); transprodIDEliminar = aTransProdDetalle[0].toString(); transprodDetalleIDEliminar = aTransProdDetalle[1].toString(); existe = true; } } } else { AtomicReference<Float> existencia = new AtomicReference<Float>(); StringBuilder error = new StringBuilder(); if (mPresenta.getTipoValidacionExistencia() != TiposValidacionInventario.NoValidar) { if (!Inventario.ValidarExistencia(producto.ProductoClave, tipoUnidad, cantidad, mPresenta.getModuloMovDetalle(), existencia, error)) { captura.setError(error.toString()); if (mPresenta.getTipoValidacionExistencia() == TiposValidacionInventario.ValidacionRestrictiva) { if(!validarVenderApartado(producto, tipoUnidad, cantidad)) return; if (existencia.get() != null && existencia.get() > 0) { captura.setCantidad(existencia.get()); } else { captura.setCantidad(Float.valueOf(0)); } return; } } else { captura.setAdvertencia(error.toString()); } } //mPresenta.agregarProductoUnidad(producto.ProductoClave, producto.SubEmpresaId, tipoUnidad, cantidad, Float.parseFloat("-1")); if(!mPresenta.validarCantMax(cantidad)){ //no esta configurada ninguna cantidad, continuar normal mPresenta.agregarProductoUnidad(producto.ProductoClave, producto.SubEmpresaId, tipoUnidad, cantidad, Float.parseFloat("-1")); }else{ //guardar la info en las varibles para poder agregar el producto si contesta que si a la pregunta productoAgregar = producto; tipoUnidadAgregar = tipoUnidad; cantidadAgregar = cantidad; existe = false; } } } catch (Exception e) { mostrarError(e.getMessage()); } } }; private CapturaProducto.onAgregarProdDobleUnidadListener mAgregarProdDobleUnidadListener = new CapturaProducto.onAgregarProdDobleUnidadListener(){ @Override public void onAgregarProdDobleUnidad(Producto producto, HashMap<Short, InventarioDobleUnidad.DetalleProductoDobleUnidad> hmDetalleUnidades) { try { TransProdDetalle oTPD = Consultas.ConsultasTransProdDetalle.obtenerTPDDobleUnidadPorProducto(producto.ProductoClave, mPresenta.getTransaccionesIds()); //Verificar inventario if (oTPD != null) { // si ya existe, seleccionarlo de la lista E0714 HashMap<Short, InventarioDobleUnidad.DetalleProductoDobleUnidad> hmCantidadesOrig = new HashMap<Short,InventarioDobleUnidad.DetalleProductoDobleUnidad>(); hmCantidadesOrig.put(Short.parseShort(String.valueOf(oTPD.TipoUnidad)), new InventarioDobleUnidad.DetalleProductoDobleUnidad(Short.parseShort(String.valueOf(oTPD.TipoUnidad)),null,oTPD.Cantidad,null, null, hmDetalleUnidades.get(Short.parseShort(String.valueOf(oTPD.TipoUnidad))).DecimalProducto , null)); if(oTPD.TPDDatosExtra.size() >0 && oTPD.TPDDatosExtra.get(0).UnidadAlterna != null && oTPD.TPDDatosExtra.get(0).UnidadAlterna>0){ hmCantidadesOrig.put(oTPD.TPDDatosExtra.get(0).UnidadAlterna, new InventarioDobleUnidad.DetalleProductoDobleUnidad(oTPD.TPDDatosExtra.get(0).UnidadAlterna,null,oTPD.TPDDatosExtra.get(0).CantidadAlterna, null,null,hmDetalleUnidades.get(oTPD.TPDDatosExtra.get(0).UnidadAlterna).DecimalProducto,null )); } //Se guarda en el arreglo la cantidad original para tenerla de referencia al guardar el TransProdDetalle, cuando es reparto if (hmDetalleUnidades.containsKey(Short.parseShort(String.valueOf(oTPD.TipoUnidad)))){ hmDetalleUnidades.get(Short.parseShort(String.valueOf(oTPD.TipoUnidad))).CantidadOriginal = ((oTPD.CantidadOriginal != null && oTPD.CantidadOriginal>0 )? oTPD.CantidadOriginal : oTPD.Cantidad); } if (oTPD.TPDDatosExtra != null && oTPD.TPDDatosExtra.size() >0 && oTPD.TPDDatosExtra.get(0).UnidadAlterna != null && hmDetalleUnidades.containsKey(oTPD.TPDDatosExtra.get(0).UnidadAlterna)){ hmDetalleUnidades.get(oTPD.TPDDatosExtra.get(0).UnidadAlterna).CantidadOriginal = ((oTPD.TPDDatosExtra.get(0).CantidadAlternaOriginal != null && oTPD.TPDDatosExtra.get(0).CantidadAlternaOriginal >0 )? oTPD.TPDDatosExtra.get(0).CantidadAlternaOriginal : oTPD.TPDDatosExtra.get(0).CantidadAlterna); } boolean bCambioCantidad = false; boolean bTomarApartado = false; for(Short unidad : hmDetalleUnidades.keySet()){ if (!hmCantidadesOrig.containsKey(unidad)){ throw( new Exception("La unidad " + ValoresReferencia.getDescripcion("UNIDADV",unidad.toString()) + " no existe en el documento original")); } if (hmDetalleUnidades.get(unidad).Cantidad != hmCantidadesOrig.get(unidad).Cantidad){ bCambioCantidad = true; AtomicReference<Float> existencia = new AtomicReference<Float>(); StringBuilder error = new StringBuilder(); if (mPresenta.getTipoValidacionExistencia() != TiposValidacionInventario.NoValidar) { if (!InventarioDobleUnidad.ValidarExistencia(producto.ProductoClave, unidad, hmDetalleUnidades.get(unidad).Cantidad, hmCantidadesOrig.get(unidad).Cantidad, mPresenta.getModuloMovDetalle(), false, existencia, error)) { captura.setError(error.toString()); if (mPresenta.getTipoValidacionExistencia() == TiposValidacionInventario.ValidacionRestrictiva) { if(Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.REPARTO){ /*if(((CONHist)Sesion.get(Campo.CONHist)).get("VenderApartado").toString().equals("0")){ captura.setError(Mensajes.get("E0714").replace("$0$", producto.ProductoClave)); return; }else */if(((CONHist)Sesion.get(Campo.CONHist)).get("VenderApartado").toString().equals("1")){ AtomicReference<Float> existenciaApartado = new AtomicReference<Float>(); StringBuilder errorApartado = new StringBuilder(); if(!InventarioDobleUnidad.ValidarExistenciaDifNoDisponible(producto.ProductoClave, unidad, hmDetalleUnidades.get(unidad).Cantidad, existencia, error)){ captura.setError(Mensajes.get("E0714").replace("$0$", producto.ProductoClave)); return; } bTomarApartado=true; captura.setError(""); } } if (existencia.get() != null && existencia.get() > 0) { captura.setCantidad( hmCantidadesOrig.get(unidad).Cantidad + existencia.get(), unidad); } else { //revisar esto en el escenario normal captura.setCantidad(hmDetalleUnidades.get(unidad).Cantidad, unidad); } if(!bTomarApartado) return; } } else { captura.setAdvertencia(error.toString()); } } } } if(bCambioCantidad) { if (bTomarApartado){ mostrarPreguntaSiNo(Mensajes.get("P0087"), 10); hmDetalleDobleUnidadAgregar = hmDetalleUnidades; productoAgregar = producto; transprodIDEliminar = oTPD.TransProdID; transprodDetalleIDEliminar = oTPD.TransProdDetalleID; return; } mPresenta.eliminarDetalleDobleUnidad(oTPD.TransProdID, oTPD.TransProdDetalleID, producto.SubEmpresaId, producto.ProductoClave, hmCantidadesOrig, false); mPresenta.agregarProductoDobleUnidad(hmDetalleUnidades, producto.ProductoClave, producto.SubEmpresaId, oTPD.TransProdDetalleID); } } else { boolean bTomarApartado = false; if (mPresenta.getTipoValidacionExistencia() != TiposValidacionInventario.NoValidar) { captura.setError(""); for(Short unidad : hmDetalleUnidades.keySet()) { AtomicReference<Float> existencia = new AtomicReference<Float>(); StringBuilder error = new StringBuilder(); if (!InventarioDobleUnidad.ValidarExistencia(producto.ProductoClave, unidad, hmDetalleUnidades.get(unidad).Cantidad, mPresenta.getModuloMovDetalle(), existencia, error)) { captura.setError(error.toString()); if (mPresenta.getTipoValidacionExistencia() == TiposValidacionInventario.ValidacionRestrictiva) { if(Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.REPARTO){ if(((CONHist)Sesion.get(Campo.CONHist)).get("VenderApartado").toString().equals("0")){ captura.setError(Mensajes.get("E0714").replace("$0$", producto.ProductoClave)); return; }else if(((CONHist)Sesion.get(Campo.CONHist)).get("VenderApartado").toString().equals("1")){ AtomicReference<Float> existenciaApartado = new AtomicReference<Float>(); StringBuilder errorApartado = new StringBuilder(); if(!InventarioDobleUnidad.ValidarExistenciaDifNoDisponible(producto.ProductoClave, unidad, hmDetalleUnidades.get(unidad).Cantidad, existencia, error)){ captura.setError(Mensajes.get("E0714").replace("$0$", producto.ProductoClave)); return; } bTomarApartado=true; captura.setError(""); } } if (existencia.get() != null && existencia.get() > 0) { captura.setCantidad(existencia.get(), unidad); } else { captura.setCantidad(Float.valueOf(0),unidad); } if(!bTomarApartado) return; }else{ captura.setAdvertencia(error.toString()); } } else { captura.setAdvertencia(error.toString()); } } } if(bTomarApartado){ mostrarPreguntaSiNo(Mensajes.get("P0087"), 10); hmDetalleDobleUnidadAgregar = hmDetalleUnidades; productoAgregar = producto; transprodIDEliminar = null; transprodDetalleIDEliminar = null; return; } mPresenta.agregarProductoDobleUnidad( hmDetalleUnidades, producto.ProductoClave, producto.SubEmpresaId,null); } } catch (Exception e) { mostrarError(e.getMessage()); } } }; }
UTF-8
Java
101,576
java
CapturaPedido.java
Java
[ { "context": "odo el codigo que sigue ya que se va al catch!!! -Sergio\n\t\t\t//le agregue un try-catch para que no se fu", "end": 8003, "score": 0.5953910946846008, "start": 8000, "tag": "NAME", "value": "Ser" }, { "context": " el codigo que sigue ya que se va al catch!!! -Sergio\n\t\t\t//le agregue un try-catch para que no se fuera", "end": 8006, "score": 0.55967116355896, "start": 8003, "tag": "USERNAME", "value": "gio" }, { "context": "uesta == RespuestaMsg.Si){\n //TODO: sperez CUROLMOV_18 1.4.1.1\n try {\n ", "end": 48714, "score": 0.6997344493865967, "start": 48710, "tag": "USERNAME", "value": "sper" }, { "context": "= RespuestaMsg.Si){\n //TODO: sperez CUROLMOV_18 1.4.1.1\n try {\n ", "end": 48728, "score": 0.9982817769050598, "start": 48717, "tag": "USERNAME", "value": "CUROLMOV_18" } ]
null
[]
package com.amesol.routelite.vistas; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnShowListener; import android.content.Intent; import android.database.Cursor; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.view.View.OnKeyListener; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.SimpleCursorAdapter.ViewBinder; import android.widget.Spinner; import android.widget.TableLayout.LayoutParams; import android.widget.TextView; import com.amesol.routelite.R; import com.amesol.routelite.actividades.Enumeradores.Inventario.TiposValidacionInventario; import com.amesol.routelite.actividades.Inventario; import com.amesol.routelite.actividades.InventarioDobleUnidad; import com.amesol.routelite.actividades.ListaPrecio; import com.amesol.routelite.actividades.Mensajes; import com.amesol.routelite.actividades.Promociones2; import com.amesol.routelite.actividades.Promociones2.onTerminarAplicacionListener; import com.amesol.routelite.actividades.Transacciones; import com.amesol.routelite.actividades.ValoresReferencia; import com.amesol.routelite.controles.CapturaProducto; import com.amesol.routelite.datos.Cliente; import com.amesol.routelite.datos.Dia; import com.amesol.routelite.datos.Producto; import com.amesol.routelite.datos.TPDImpuesto; import com.amesol.routelite.datos.TransProd; import com.amesol.routelite.datos.TransProdDetalle; import com.amesol.routelite.datos.Vendedor; import com.amesol.routelite.datos.basedatos.BDVend; import com.amesol.routelite.datos.basedatos.Consultas; import com.amesol.routelite.datos.generales.ISetDatos; import com.amesol.routelite.datos.utilerias.ArchivoConfiguracion; import com.amesol.routelite.datos.utilerias.CONHist; import com.amesol.routelite.datos.utilerias.ConfigParametro; import com.amesol.routelite.datos.utilerias.ConfiguracionLocal; import com.amesol.routelite.datos.utilerias.MOTConfiguracion; import com.amesol.routelite.datos.utilerias.Sesion; import com.amesol.routelite.datos.utilerias.Sesion.Campo; import com.amesol.routelite.presentadores.Enumeradores; import com.amesol.routelite.presentadores.Enumeradores.Acciones; import com.amesol.routelite.presentadores.Enumeradores.RespuestaMsg; import com.amesol.routelite.presentadores.Enumeradores.Solicitudes; import com.amesol.routelite.presentadores.Enumeradores.TiposFasesDocto; import com.amesol.routelite.presentadores.Enumeradores.TiposMovimientos; import com.amesol.routelite.presentadores.Enumeradores.TiposTransProd; import com.amesol.routelite.presentadores.act.CapturarPedido; import com.amesol.routelite.presentadores.interfaces.IAplicacionPromocion; import com.amesol.routelite.presentadores.interfaces.ICapturaInventario; import com.amesol.routelite.presentadores.interfaces.ICapturaPedido; import com.amesol.routelite.presentadores.interfaces.ICapturaPedidoSugerido; import com.amesol.routelite.presentadores.interfaces.ICapturaTotales; import com.amesol.routelite.presentadores.interfaces.ICapturaTotalesConsignacion; import com.amesol.routelite.presentadores.interfaces.IConsultaUltimaVenta; import com.amesol.routelite.utilerias.Generales; import com.amesol.routelite.vistas.generico.DialogoAlerta; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import java.io.File; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicReference; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; public class CapturaPedido extends Vista implements ICapturaPedido { CapturarPedido mPresenta; CapturaProducto captura; String mAccion; int index; int top; HashMap<String, String> oParametros = null; boolean siguiente = false; boolean salir = false; Object mPausaCiclo; //Runnable hiloFor; //Thread promo; boolean esNuevo = true; boolean soloLectura = false; boolean mostrandoPregunta = false; boolean huboCambios = false; boolean calculando = false; boolean regresandoPromo = false; boolean sugeridoMostrado = false; //private Cursor producto; private Menu mnu; boolean surtir = false; boolean reparto = false; ArrayList<TransProdDetalle> prodSinExistencia = new ArrayList<TransProdDetalle>(); boolean consultar = false; boolean modificando = false; boolean modificandoAutoventa = false; MenuItem modificar; boolean manejoDobleUnidad = false; Iterator<TransProd> docsTransProd; ListView lista; Handler handler; Promociones2 promociones; Producto productoAgregar; int tipoUnidadAgregar; float cantidadAgregar; Float cantidadOriginalAgregar; String transprodIDEliminar; String transprodDetalleIDEliminar; boolean existe; ISetDatos envasesPorRecolectar; String inventarioID; HashMap<Short, InventarioDobleUnidad.DetalleProductoDobleUnidad> hmDetalleDobleUnidadAgregar = null; private static final String FRAGMENT_TAG = "ventaMensualFragment"; private Button btPrecioManualAceptar=null; @SuppressWarnings("unchecked") @Override public void onCreate(Bundle savedInstanceState) { try { super.onCreate(savedInstanceState); mAccion = getIntent().getAction(); setContentView(R.layout.captura_pedido); deshabilitarBarra(true); if(Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.REPARTO) setTitulo(Mensajes.get("XReparto")); else if(Integer.parseInt(Sesion.get(Campo.TipoIndiceModuloMovDetalleClave).toString()) == Enumeradores.TiposModuloMovDetalle.CONSIGNACION) setTitulo(Mensajes.get("XConsignacion")); else setTitulo(Mensajes.get("XVentas")); if(mAccion != null){ if(mAccion.equals(Enumeradores.Acciones.ACCION_CAPTURAR_MOV_SIN_INV_EN_VISITA)){ setTitulo(Consultas.ConsultasModuloMovDetalle.obtenerTitulo()); } } TextView texto = (TextView) findViewById(R.id.lblProducto); texto.setText(Mensajes.get("XProducto")); texto = (TextView) findViewById(R.id.lblUnidad); texto.setText(Mensajes.get("XUnidad")); texto = (TextView) findViewById(R.id.lblTotalPrevio); texto.setText(Mensajes.get("MDBTotalPrevio") + ":"); texto = (TextView) findViewById(R.id.lblVolumen); texto.setText(Mensajes.get("XKgVol") + ":"); texto = (TextView) findViewById(R.id.lblTotalProductos); texto.setText(Mensajes.get("MDBFilas") + ":"); texto = (TextView) findViewById(R.id.lblTotalUnidades); texto.setText(Mensajes.get("XUnidades") + ":"); Button boton = (Button) findViewById(R.id.btnSugerido); boton.setText(Mensajes.get("XSugerido")); boton.setOnClickListener(mPedidoSugerido); boton = (Button) findViewById(R.id.btnContinuar); boton.setText(Mensajes.get("XContinuar")); boton.setOnClickListener(mAplicarPromociones); lista = (ListView) findViewById(R.id.lsTransProdDetalle); lista.setItemsCanFocus(false); //TODO: checar esto!!!! cuando truena el quecolin se brinca todo el codigo que sigue ya que se va al catch!!! -Sergio //le agregue un try-catch para que no se fuera hasta abajo, checar si esta bien asi!!! try{ encenderBluetooth(); }catch(Exception e){ e.printStackTrace(); } if (((MOTConfiguracion) Sesion.get(Campo.MOTConfiguracion)).get("ManejoDobleUnidad").toString().equals("1")) { manejoDobleUnidad = true; } captura = (CapturaProducto) findViewById(R.id.capturaProducto); if(manejoDobleUnidad){ captura.setOnAgregarProdDobleUnidadListener(mAgregarProdDobleUnidadListener); }else { captura.setOnAgregarProductoListener(mAgregarProductoListener); } captura.setOnProductoNoEncontradoListener(new CapturaProducto.onProductoNoEncontradoListener() { @Override public void onProductoNoEncontrado() { captura.setTransProdIds(mPresenta.getTransProdIds()); } }); mPresenta = new CapturarPedido(this, mAccion); if (getIntent().getSerializableExtra("parametros") != null) { oParametros = (HashMap<String, String>) getIntent().getSerializableExtra("parametros"); } if (oParametros != null && (!oParametros.get("TransProdId").trim().equals(""))) { if( (Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.REPARTO || Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.VENTA || Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.PREVENTA) && mAccion != Acciones.ACCION_CAPTURAR_MOV_SIN_INV_EN_VISITA && ((MOTConfiguracion)Sesion.get(Campo.MOTConfiguracion)).get("AgruparTransacciones").toString().equals("1")){ //agrupar transacciones ArrayList<String> transacciones = Consultas.ConsultasTransProd.agruparTransacciones(oParametros.get("TransProdId")); for(String tran : transacciones){ mPresenta.agregarTransaccion(tran); Consultas.ConsultasTRPGrupo.eliminarTransaccionGrupo(tran); //eliminar el registro del grupo setHuboCambios(true); } }else mPresenta.agregarTransaccion(oParametros.get("TransProdId")); } Date seleccion = new Date(); SimpleDateFormat x = new SimpleDateFormat("dd/MM/yyyy"); seleccion = x.parse(((Dia)Sesion.get(Campo.DiaActual)).DiaClave ); if (Generales.getFechaActual().compareTo(seleccion) != 0){ if (((ConfigParametro) Sesion.get(Campo.ConfigParametro)).existeParametro("ValidarActPrecio")) { if (((ConfigParametro) Sesion.get(Campo.ConfigParametro)).get("ValidarActPrecio").equals("1")) { //Se revisa el archivo de actualizaciones, para ver si se actualizaron los precios DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db; Document xmlActualiza; boolean archivosServerEliminados = true; try { ConfiguracionLocal conf = (ConfiguracionLocal) Sesion.get(Campo.ConfiguracionLocal); File archXML = new File(conf.get(ArchivoConfiguracion.CampoConfiguracion.DIRECTORIO_TRABAJO).toString()); archXML = new File(archXML, "bd"); archXML = new File(archXML, BDVend.nombreBaseDatos().replace("db", "xml")); db = dbf.newDocumentBuilder(); xmlActualiza = db.parse(new File(archXML.getAbsolutePath())); NodeList tablasXml = xmlActualiza.getFirstChild().getChildNodes(); String nombreTabla; Date fechaActualizacion = new Date(1900,1,1); for (int i = 0; i <= tablasXml.getLength() - 1; i++) { nombreTabla = tablasXml.item(i).getChildNodes().item(0).getTextContent(); if (nombreTabla.equalsIgnoreCase("Precio") || nombreTabla.equalsIgnoreCase("PrecioProductoVig")) { Date actualizacion = new Date(); SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd"); actualizacion = formatDate.parse( tablasXml.item(i).getChildNodes().item(1).getTextContent()); if (fechaActualizacion.compareTo(actualizacion) >0){ fechaActualizacion =actualizacion; } } } if (Generales.getFechaActual().compareTo(fechaActualizacion) >0){ mostrarError(Mensajes.get("E0954"),0); mPresenta.errorFinalizar = true; return; } }catch (Exception ex){ mostrarError("Error al recuperar el parámetro ValidarActPrecio"); } } } } mPresenta.iniciar(); if (mPresenta.errorFinalizar){ return; } // si se paso como parametro el TransProdId, cargar el detalle del // pedido if (oParametros != null && (!oParametros.get("TransProdId").trim().equals(""))) { //boolean reparto = false; if (oParametros != null && oParametros.get("Reparto") != null && (!oParametros.get("Reparto").trim().equals(""))){ reparto = Boolean.parseBoolean(oParametros.get("Reparto")); } if (oParametros != null && oParametros.get("Consultar") != null && (!oParametros.get("Consultar").trim().equals(""))){ consultar = Boolean.parseBoolean(oParametros.get("Consultar")); } if (oParametros != null && oParametros.get("Surtir") != null && (!oParametros.get("Surtir").trim().equals(""))){ surtir = Boolean.parseBoolean(oParametros.get("Surtir")); } esNuevo = false; //marcar como modificado CAI 3111 modificandoAutoventa = true; refrescarProductos(mPresenta.getTransaccionesIds()); if (mPresenta.getTipoFase() == 0 || mPresenta.getTipoFase() == 3 ||((mPresenta.getTipoFase() == 2 || mPresenta.getTipoFase() == 1) && Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.REPARTO && reparto) ) { // si esta cancelado o surtido mostrar como solo lectura, si viene de reparto tambien soloLectura = true; captura.setVisibility(View.GONE); } } else if (mPresenta.getPedidoSugerido()) { esNuevo = true; refrescarProductos(mPresenta.getTransaccionesIds()); } captura.setTipoValidacionExistencia(mPresenta.getTipoValidacionExistencia()); captura.setCadenaListasPrecios(mPresenta.getListasPrecios()); captura.setTipoMovimiento(mPresenta.getModuloMovDetalle().TipoMovimiento); captura.setTipoTransProd(mPresenta.getModuloMovDetalle().TipoTransProd); captura.setSurtir(surtir); /*Se excluyen de la venta los productos tipo Canje Con la finalidad de que solo se muestren en las promociones*/ captura.setExcluirCanjes(true); if (!soloLectura) { registerForContextMenu(lista); lista.setOnItemLongClickListener(menu); } } catch (Exception ex) { ex.printStackTrace(); // mostrarError(ex.getMessage().equals("") ? ex.getCause().getMessage() : ex.getMessage()); } final EditText txtScaner = (EditText) findViewById(R.id.txtScanner); final EditText txtCantidad = (EditText) findViewById(R.id.txtCantidad); final Spinner spinUnit = (Spinner) findViewById(R.id.cboUnidad); if (!(spinUnit.getCount() > 1)) spinUnit.setEnabled(false); final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); txtCantidad.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { // getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); txtScaner.clearFocus(); imm.showSoftInput(txtCantidad, InputMethodManager.SHOW_FORCED); if (!(spinUnit.getCount() > 1)) spinUnit.setEnabled(false); String mCantidad = mPresenta.consultarUnidadProductoExistente(mPresenta.getTransProdIds(), txtScaner.getText().toString()); if (!mCantidad.equals("0")) { txtCantidad.setText(mCantidad); txtCantidad.requestFocus(); txtCantidad.selectAll(); txtCantidad.setSelectAllOnFocus(true); } } } }); txtScaner.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { // getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); txtCantidad.clearFocus(); } } }); } public void setCapturaCantidad(float cantidad){ captura.setCantidad(cantidad); } //Se usa solo para el manejo normal de unidades private boolean validarVenderApartado(Producto producto, int tipoUnidad, float cantidad){ return validarVenderApartado(producto,tipoUnidad,cantidad, null, null, null); } //Se usa para el manejo normal de unidades private boolean validarVenderApartado(Producto producto, int tipoUnidad, float cantidad, Float cantidadOriginal, String transProdID, String transProdDetalleID ){ if(Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.REPARTO){ if(((CONHist)Sesion.get(Campo.CONHist)).get("VenderApartado").toString().equals("0")){ //mostrarAdvertencia(Mensajes.get("E0714").replace("$0$", productoClave)); captura.setError(Mensajes.get("E0714").replace("$0$", producto.ProductoClave)); return false; }else if(((CONHist)Sesion.get(Campo.CONHist)).get("VenderApartado").toString().equals("1")){ AtomicReference<Float> existencia = new AtomicReference<Float>(); StringBuilder error = new StringBuilder(); if(!Inventario.ValidarExistenciaDifNoDisponible(producto.ProductoClave, tipoUnidad, cantidad, existencia, error)){ //mostrarAdvertencia(Mensajes.get("E0714").replace("$0$", productoClave)); captura.setError(Mensajes.get("E0714").replace("$0$", producto.ProductoClave)); return false; } mostrarPreguntaSiNo(Mensajes.get("P0087"), 10); captura.setError(""); /*guardar todo en las varibles para poder agregar si responde SI*/ tipoUnidadAgregar = tipoUnidad; productoAgregar = producto; cantidadAgregar = cantidad; cantidadOriginalAgregar = cantidadOriginal; transprodIDEliminar = transProdID; transprodDetalleIDEliminar = transProdDetalleID; } } return true; } public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (hasFocus) { if (regresandoPromo) { regresandoPromo = false; try { if (Sesion.get(Campo.ResultadoActividad) != null) { if ((Boolean) Sesion.get(Campo.ResultadoActividad)) { promociones.TerminoPromocionRegalo(); Sesion.remove(Campo.ResultadoActividad); } else { promociones.SiguientePromocion(); Sesion.remove(Campo.ResultadoActividad); } } else { promociones.SiguientePromocion(); } } catch (Exception e) { mostrarError(e.getMessage()); } } } // Toast.makeText(context, text, duration).show(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: VentaMensual fmFragment; if((fmFragment = (VentaMensual) getFragmentManager().findFragmentByTag(FRAGMENT_TAG)) != null){ fmFragment.close(); }else{ salir(); } return true; } return super.onKeyDown(keyCode, event); } public OnItemLongClickListener menu = new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { openContextMenu(lista); return true; } }; @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.context_transaccion_detalle, menu); menu.getItem(0).setTitle(Mensajes.get("XEliminar")); if (((Vendedor) Sesion.get(Campo.VendedorActual)).ModificarPrecios == 1){ menu.getItem(1).setTitle(Mensajes.get("XModificarPrecio")); menu.getItem(1).setVisible(true); } if (((MOTConfiguracion)Sesion.get(Campo.MOTConfiguracion)).get("AsignarManualListas").equals("1")){ menu.getItem(2).setTitle(Mensajes.get("XCambiarListaPrecio")); menu.getItem(2).setVisible(true); } } @Override public boolean onContextItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.eliminar: mostrandoPregunta = true; mostrarPreguntaSiNo(Mensajes.get("P0233"), 2); return true; case R.id.modificarPrecio: try { LayoutInflater inflater = (LayoutInflater) CapturaPedido.this .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View dialogView = inflater.inflate(R.layout.dialog_number_picker, null); AlertDialog.Builder builder = new AlertDialog.Builder(CapturaPedido.this); final EditText np = (EditText) dialogView.findViewById(R.id.numText ); np.setSelectAllOnFocus(true); Cursor producto = (Cursor) (((SimpleCursorAdapter) lista.getAdapter()).getCursor()); final String transProdID= producto.getString(producto.getColumnIndex("TransProdID")); final String transProdDetalleID = producto.getString(producto.getColumnIndex("TransProdDetalleID")); final String subEmpresaId = producto.getString(producto.getColumnIndex("SubEmpresaId")); final String productoClave = producto.getString(producto.getColumnIndex("ProductoClave")); final short tipoUnidad = producto.getShort(producto.getColumnIndex("TipoUnidad")); final float cantidad = producto.getFloat(producto.getColumnIndex("Cantidad")); final float precio = Generales.getRound(producto.getFloat(producto.getColumnIndex("Precio")),Integer.parseInt(((CONHist)Sesion.get(Campo.CONHist)).get("DecimalesImporte").toString())); np.setText(Generales.getFormatoDecimal(producto.getFloat(producto.getColumnIndex("Precio")),Integer.parseInt(((CONHist)Sesion.get(Campo.CONHist)).get("DecimalesImporte").toString()))); np.selectAll(); np.requestFocus(); np.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { String userInput = np.getText().toString(); if (userInput.toString().matches("")) { userInput = "0.00"; } else { float floatValue = Float.parseFloat(userInput); userInput = String.format("%." + Integer.parseInt(((CONHist)Sesion.get(Campo.CONHist)).get("DecimalesImporte").toString()) + "f",floatValue); } np.setText(userInput); np.selectAll(); } } }); builder.setPositiveButton(Mensajes.get("XAceptar"),new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { MOTConfiguracion motConf = (MOTConfiguracion) Sesion.get(Campo.MOTConfiguracion); float precioEspecial = Generales.getRound(Float.parseFloat(np.getText().toString()),Integer.parseInt(((CONHist)Sesion.get(Campo.CONHist)).get("DecimalesImporte").toString())); if(precio != precioEspecial){ if(motConf.get("ValidaRangoPrecio").toString().equals("1")){ try{ Float precioMin = ListaPrecio.ObtenerPecioMinimo(mPresenta.getListasPrecios(), productoClave, tipoUnidad); if(precioEspecial >= precioMin){ mPresenta.eliminarDetalle(transProdID, transProdDetalleID, subEmpresaId, productoClave, tipoUnidad, cantidad, false ); mPresenta.agregarProductoUnidad(productoClave, subEmpresaId, tipoUnidad, cantidad, precioEspecial); dialog.dismiss(); }else{ mostrarError(Mensajes.get("I0278")); return; } } catch (Exception e){ mostrarError(e.getMessage()); } }else{ if (Float.parseFloat(np.getText().toString()) < 0f){ mostrarError(Mensajes.get("E0007")); return; } if(precio != precioEspecial){ mPresenta.eliminarDetalle(transProdID, transProdDetalleID, subEmpresaId, productoClave, tipoUnidad, cantidad, false ); mPresenta.agregarProductoUnidad(productoClave, subEmpresaId, tipoUnidad, cantidad, precioEspecial); dialog.dismiss(); } } }else{ dialog.dismiss(); } } }); builder.setNegativeButton(Mensajes.get("XCancelar"),new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setView(dialogView); final Dialog dialog = builder.create(); dialog.setOnShowListener(new OnShowListener() { @Override public void onShow(DialogInterface dialog) { final Button btPrecioAceptar; btPrecioAceptar = ((AlertDialog) dialog) .getButton(AlertDialog.BUTTON_POSITIVE); np.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_UP) { // check if the right key was pressed if (keyCode == KeyEvent.KEYCODE_ENTER) { btPrecioAceptar.performClick(); return true; } } return false; } }); } }); dialog.show(); } catch (Exception ex) { mostrarError(ex.getMessage()); } return true; case R.id.modificarListaPrecio: try { //obtenerTotales(TransProdId); //SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.elemento_captura_producto, cProductos, new String[] // { "TipoUnidad", "ProductoClave", "Descripcion", "Precio", "Cantidad", "Total", "Existencia", "CantidadOriginal" }, new int[] // { R.id.lblUnidadProductoClave, R.id.lblUnidadProductoClave, R.id.lblDescripcion, R.id.lblPU, R.id.lblCantidad, R.id.lblTotal, R.id.lblExistencia, R.id.lblCantidadOriginal }); //adapter.setViewBinder(new vista()); //lista.setAdapter(adapter); Cursor producto = (Cursor) (((SimpleCursorAdapter) lista.getAdapter()).getCursor()); final String productoClave = producto.getString(producto.getColumnIndex("ProductoClave")); final short tipoUnidad = producto.getShort(producto.getColumnIndex("TipoUnidad")); LayoutInflater inflater = (LayoutInflater) CapturaPedido.this .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View dialogViewModificarListaPrecio = inflater.inflate(R.layout.dialog_listas_precios, null); AlertDialog.Builder builder = new AlertDialog.Builder(CapturaPedido.this); ListView lista_precios = (ListView) dialogViewModificarListaPrecio.findViewById(R.id.lstAgenda); String sClienteClave = ((Cliente)Sesion.get(Campo.ClienteActual)).ClienteClave; ISetDatos MinMaxJerarquia = Consultas.ConsultasPrecio.obtenerJerarquiaMinMaxCliente(sClienteClave); MinMaxJerarquia.moveToFirst(); String sListaPrecios = mPresenta.getListasPreciosPedido(); ISetDatos precios = Consultas.ConsultasPrecio.obtenerPreciosProducto(productoClave, tipoUnidad, sClienteClave, sListaPrecios, MinMaxJerarquia.getShort("JerarquiaMinima"), MinMaxJerarquia.getShort("JerarquiaMaxima")); if (precios.getCount() == 0){ mostrarError(Mensajes.get("I0306")); return true; } Cursor cPrecios = (Cursor) precios.getOriginal(); startManagingCursor(cPrecios); //ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.lista_simple2_hor, cPrecios, new String[] { "Descripcion", "Precio" }, new int[] { R.id.txtCol1, R.id.txtCol2 }); SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.lista_simple2_hor, cPrecios, new String[] { "Descripcion", "Precio" }, new int[] { R.id.txtCol1, R.id.txtCol2 }); adapter.setViewBinder(new vistaListasPrecios()); lista_precios.setAdapter(adapter); lista_precios.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String sPrecioManual; Cursor listasprecios = (Cursor) parent.getItemAtPosition(position); listasprecios.moveToPosition(position); sPrecioManual = listasprecios.getString(2); Cursor producto = (Cursor) (((SimpleCursorAdapter) lista.getAdapter()).getCursor()); final String transProdID= producto.getString(producto.getColumnIndex("TransProdID")); final String transProdDetalleID = producto.getString(producto.getColumnIndex("TransProdDetalleID")); final String subEmpresaId = producto.getString(producto.getColumnIndex("SubEmpresaId")); final String productoClave = producto.getString(producto.getColumnIndex("ProductoClave")); final short tipoUnidad = producto.getShort(producto.getColumnIndex("TipoUnidad")); final float cantidad = producto.getFloat(producto.getColumnIndex("Cantidad")); float precioEspecial = Generales.getRound(Float.parseFloat(sPrecioManual),Integer.parseInt(((CONHist)Sesion.get(Campo.CONHist)).get("DecimalesImporte").toString())); Sesion.set(Campo.CambioLPTpdExtra,true); Sesion.set(Campo.LPTpdExtra,listasprecios.getString(0)); mPresenta.eliminarDetalle(transProdID, transProdDetalleID, subEmpresaId, productoClave, tipoUnidad, cantidad, false ); mPresenta.agregarProductoUnidad(productoClave, subEmpresaId, tipoUnidad, cantidad, precioEspecial); Sesion.set(Campo.LPTpdExtra,""); Sesion.set(Campo.CambioLPTpdExtra,false); btPrecioManualAceptar.performClick(); } }); builder.setNegativeButton(Mensajes.get("XCancelar"),new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setView(dialogViewModificarListaPrecio); final Dialog dialog = builder.create(); dialog.setOnShowListener(new OnShowListener() { @Override public void onShow(DialogInterface dialog) { btPrecioManualAceptar = ((AlertDialog) dialog) .getButton(AlertDialog.BUTTON_NEGATIVE); } }); dialog.show(); } catch (Exception ex) { mostrarError(ex.getMessage()); } return true; default: return super.onOptionsItemSelected(item); } } @Override public void iniciar() { } public void mostrarPromocionProducto(String promocionClave, String promocionReglaID, int CantidadGrupoApp, String SubEmpresaId, int cantidad, String productoDisparador, String cadenaListasPrecios) { HashMap<String, Object> oParametros = new HashMap<String, Object>(); oParametros.put("PromocionClave", promocionClave); oParametros.put("PromocionReglaID", promocionReglaID); oParametros.put("CantidadGrupo", CantidadGrupoApp); oParametros.put("SubEmpresaID", SubEmpresaId); oParametros.put("CantidadMax", cantidad); oParametros.put("TipoValidarExistencia", mPresenta.getTipoValidacionExistencia()); oParametros.put("ProductoDisparador", productoDisparador); oParametros.put("CadenaListasPrecio", cadenaListasPrecios); iniciarActividadConResultado(IAplicacionPromocion.class, Solicitudes.SOLICITUD_MOSTRAR_PROMOCIONES_APLICADAS, Acciones.ACCION_APLICAR_PROMOCIONES, oParametros); } @SuppressWarnings("deprecation") public void mostrarObligatorio(String mensaje, final int tipoMensaje, String...titulo) { DialogoAlerta dialogo = new DialogoAlerta(this); dialogo.setMessage(mensaje); dialogo.setCancelable(false); String msgSi = "Si"; String msgNo = "No"; if (Mensajes.existe()) { msgSi = Mensajes.get("XSi"); msgNo = Mensajes.get("XNo"); } dialogo.setButton(msgSi, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { respuestaMensaje(RespuestaMsg.Si, tipoMensaje); dialog.dismiss(); } }); dialogo.setButton2(msgNo, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { respuestaMensaje(RespuestaMsg.No, tipoMensaje); dialog.cancel(); } }); dialogo.show(); } @SuppressWarnings("unchecked") @Override public void resultadoActividad(int requestCode, int resultCode, Intent data) { Button boton = (Button) findViewById(R.id.btnContinuar); boton.setEnabled(true); if (requestCode == Enumeradores.Solicitudes.SOLICITUD_BUSQUEDA_PRODUCTOS) { // si esta regresándo de la busqueda de productos if (resultCode == Enumeradores.Resultados.RESULTADO_BIEN) { // si selecciono Agregar en la busqueda de productos, obtener la // seleccion y agregarlos al pedido // DatosProductos productosSeleccionados; // productosSeleccionados = (DatosProductos) // data.getExtras().getParcelable("Objeto"); if (Sesion.get(Campo.ResultadoActividad) != null) { insertarSeleccion((HashMap<String, TransProdDetalle>) Sesion.get(Campo.ResultadoActividad)); Sesion.remove(Campo.ResultadoActividad); captura.setFinBusqueda(); }else{ captura.setFinBusqueda(); if(data != null) { txtScanner.setTexto(data.getStringExtra("mensajeIniciar")); captura.IngresaProductoBusquedaSimple(data.getStringExtra("mensajeIniciar")); } } } else if (resultCode == Enumeradores.Resultados.RESULTADO_MAL) { if (data != null) { String mensajeError = (String) data.getExtras().getString("mensajeIniciar"); if (!mensajeError.equals("")) { // cuando se presiona back se manda el mensaje vacio mostrarError(mensajeError); } } captura.setFinBusqueda(); } //captura.setFinBusqueda(); } else if (requestCode == Enumeradores.Solicitudes.SOLICITUD_MOSTRAR_PROMOCIONES_APLICADAS) { if (resultCode == Enumeradores.Resultados.RESULTADO_BIEN) { regresandoPromo = true; }else { if (data != null) { String mensajeError = (String) data.getExtras().getString("mensajeIniciar"); if (mensajeError.contains("SinPrecio")) { mostrarError(Mensajes.get("E0958", mensajeError.replace("SinPrecio", "")), 60); } } } } else if (requestCode == Enumeradores.Solicitudes.SOLICITUD_MOSTRAR_TOTALES) { // regreso de la pantalla de totales if (resultCode == Enumeradores.Resultados.RESULTADO_BIEN) { // si selecciono terminar, finalizar la captura del pedido setResult(Enumeradores.Resultados.RESULTADO_BIEN); finalizar(); } else if (resultCode == Enumeradores.Resultados.RESULTADO_MAL) { String mensajeError = (String) data.getExtras().getString("mensajeIniciar"); if (!mensajeError.equals("")) { // cuando se presiona back se manda el mensaje vacio this.setResultado(Enumeradores.Resultados.RESULTADO_MAL, mensajeError); finalizar(); } else { // si el mensaje esta vacio, presiono back mPresenta.eliminarPromos(); } } } else if (requestCode == Enumeradores.Solicitudes.SOLICITUD_MOSTRAR_PEDIDO_SUGERIDO) { // si esta regresándo de la busqueda de productos if (resultCode == Enumeradores.Resultados.RESULTADO_BIEN) { // si selecciono Agregar en la busqueda de productos, obtener la // seleccion y agregarlos al pedido // DatosProductos productosSeleccionados; // productosSeleccionados = (DatosProductos) // data.getExtras().getParcelable("Objeto"); if (Sesion.get(Campo.ResultadoActividad) != null) { insertarSeleccionSugerido((HashMap<String, HashMap<Short, TransProdDetalle>>) Sesion.get(Campo.ResultadoActividad)); Sesion.remove(Campo.ResultadoActividad); } } else if (resultCode == Enumeradores.Resultados.RESULTADO_MAL) { if (data != null) { String mensajeError = (String) data.getExtras().getString("mensajeIniciar"); if (!mensajeError.equals("")) { // cuando se presiona back se manda el mensaje vacio mostrarError(mensajeError); } } } }else if ((requestCode == Enumeradores.Solicitudes.SOLICITUD_SERVIDOR_COMUNICACIONES_ENVIO_PARCIAL) && (resultCode == Enumeradores.Resultados.RESULTADO_BIEN)) //si el envio parcial fue correcto, sincronizar el inventario mPresenta.obtenerInventarioEnLinea(); else if ((requestCode == Enumeradores.Solicitudes.SOLICITUD_SERVIDOR_COMUNICACIONES_ENVIO_PARCIAL || requestCode == Enumeradores.Solicitudes.SOLICITUD_SERVIDOR_COMUNICACIONES) && (resultCode == Enumeradores.Resultados.RESULTADO_MAL)) { if (data != null) { String mensajeError = (String) data.getExtras().getString("mensajeIniciar"); if (mensajeError != null) { iniciarActividad(ICapturaPedido.class, mensajeError); return; } } iniciarActividad(ICapturaPedido.class); } else if (requestCode == Enumeradores.Solicitudes.SOLICITUD_MOSTRAR_TOTALES_CONSIGNACION) { // regreso de la pantalla de totales if (resultCode == Enumeradores.Resultados.RESULTADO_BIEN) { // si selecciono terminar, finalizar la captura del pedido setResultado(Enumeradores.Resultados.RESULTADO_MAL); finalizar(); } else if (resultCode == Enumeradores.Resultados.RESULTADO_MAL) { if (!esNuevo) { // cuando se presiona back se manda el mensaje vacio if(mAccion.equals(Enumeradores.Acciones.ACCION_CAPTURAR_CONSIGNACIONES)) { salir(); }else{ this.setResultado(Enumeradores.Resultados.RESULTADO_BIEN); finalizar(); } } else { // si el mensaje esta vacio, presiono back mPresenta.eliminarPromos(); } } } else if (requestCode == Solicitudes.SOLICITUD_TOMAR_INVENTARIO_PEDIDO) { if (resultCode == Enumeradores.Resultados.RESULTADO_BIEN) { if (Sesion.get(Campo.ResultadoActividad) != null) { insertarSeleccion((HashMap<String, TransProdDetalle>) Sesion.get(Campo.ResultadoActividad)); Sesion.remove(Campo.ResultadoActividad); if (data != null) { String res = (String) data.getExtras().getString("mensajeIniciar"); if (!res.equals("")) { inventarioID = res; } } } }else if (resultCode == Enumeradores.Resultados.RESULTADO_MAL) { if (data != null) { String mensajeError = (String) data.getExtras().getString("mensajeIniciar"); if (!mensajeError.equals("")) { // cuando se presiona back se manda el mensaje vacio mostrarError(mensajeError); } } } } } @Override public void onDestroy() { super.onDestroy(); if (lista.getAdapter() != null){ stopManagingCursor(((Cursor) (((SimpleCursorAdapter) lista.getAdapter()).getCursor()))); ((Cursor) (((SimpleCursorAdapter) lista.getAdapter()).getCursor())).close(); } if (captura.getSpinnerUnidad() != null && captura.getSpinnerUnidad().getAdapter() != null){ stopManagingCursor(((Cursor) (((SimpleCursorAdapter) captura.getSpinnerUnidad().getAdapter()).getCursor()))); ((Cursor) (((SimpleCursorAdapter) captura.getSpinnerUnidad().getAdapter()).getCursor())).close(); } } @Override public void respuestaMensaje(RespuestaMsg respuesta, int tipoMensaje) { if (tipoMensaje == 2) { if (respuesta == RespuestaMsg.Si) { if (manejoDobleUnidad){ Cursor producto = (Cursor) (((SimpleCursorAdapter) lista.getAdapter()).getCursor()); HashMap<Short,InventarioDobleUnidad.DetalleProductoDobleUnidad> hmUnidades = new HashMap<Short,InventarioDobleUnidad.DetalleProductoDobleUnidad>(); hmUnidades.put(producto.getShort(producto.getColumnIndex("TipoUnidad")), new InventarioDobleUnidad.DetalleProductoDobleUnidad(producto.getShort(producto.getColumnIndex("TipoUnidad")), null, producto.getFloat(producto.getColumnIndex("Cantidad")),null, null, producto.getShort(producto.getColumnIndex("DecimalProd1")),null)); if(producto.getShort(producto.getColumnIndex("UnidadAlterna"))>0 ){ hmUnidades.put(producto.getShort(producto.getColumnIndex("UnidadAlterna")), new InventarioDobleUnidad.DetalleProductoDobleUnidad(producto.getShort(producto.getColumnIndex("UnidadAlterna")), null, producto.getFloat(producto.getColumnIndex("CantidadAlterna")),null, null, producto.getShort(producto.getColumnIndex("DecimalProd2")),null)); } mPresenta.eliminarDetalleDobleUnidad(producto.getString(producto.getColumnIndex("TransProdID")), producto.getString(producto.getColumnIndex("TransProdDetalleID")),producto.getString(producto.getColumnIndex("SubEmpresaId")), producto.getString(producto.getColumnIndex("ProductoClave")), hmUnidades,true); captura.limpiarProducto(); }else { Cursor producto = (Cursor) (((SimpleCursorAdapter) lista.getAdapter()).getCursor()); mPresenta.eliminarDetalle(producto.getString(producto.getColumnIndex("TransProdID")), producto.getString(producto.getColumnIndex("TransProdDetalleID")), producto.getString(producto.getColumnIndex("SubEmpresaId")), producto.getString(producto.getColumnIndex("ProductoClave")), producto.getShort(producto.getColumnIndex("TipoUnidad")), producto.getFloat(producto.getColumnIndex("Cantidad"))); captura.limpiarProducto(); } } mostrandoPregunta = false; } else if (tipoMensaje == 3) { if (respuesta == RespuestaMsg.Si) { regresar(); } } else if (tipoMensaje == 99) { // pregunta aplicar promocion /* * synchronized(mPausaCiclo){ siguiente = true; * mPausaCiclo.notifyAll(); } */ try { if (respuesta.equals(RespuestaMsg.Si)) { if (promociones.promocionActual.Tipo == com.amesol.routelite.actividades.Enumeradores.Promocion.Tipo.ProductoAcumulado) { if (promociones.reglaAcumActual != null) { promociones.reglaAcumActual.Aplicar(); promociones.promocionActual.SeAcepto = true; } } else { if (promociones.reglaActual != null) { promociones.reglaActual.Aplicar(); } } } promociones.SiguientePromocion(); } catch (Exception ex) { mostrarError(ex.getMessage()); } }else if(tipoMensaje == 50){ try { if (respuesta == RespuestaMsg.Si){ //ajustar inventario for(TransProdDetalle oTpd : prodSinExistencia){ if(oTpd.Promocion == 2){//Solo los regalados se ajustan, para los canjes hay que modificar el pedido porque hay recalculo implicado Inventario.ActualizarInventario(oTpd.ProductoClave, oTpd.TipoUnidad, oTpd.Cantidad, TiposTransProd.PEDIDO, TiposMovimientos.NO_DEFINIDO, ((Vendedor) Sesion.get(Campo.VendedorActual)).AlmacenID, true); oTpd.CantidadOriginal = oTpd.Cantidad; oTpd.Cantidad = 0; BDVend.guardarInsertar(oTpd); } } cuadreEnvases(); }else{ regresar(); } } catch (Exception e) { e.printStackTrace(); } }else if(tipoMensaje == 20){ if(respuesta == RespuestaMsg.Si){ //modificar pedido modificarPedidoReparto(); /*captura.setVisibility(View.VISIBLE); modificando = true; modificar.setEnabled(false); mPresenta.modificarPedido();*/ } }else if(tipoMensaje == 10){ if(respuesta == RespuestaMsg.Si){ //mostrarAdvertencia("Agregar Producto"); if (manejoDobleUnidad){ if (transprodIDEliminar == null) mPresenta.agregarProductoDobleUnidad(hmDetalleDobleUnidadAgregar, productoAgregar.ProductoClave, productoAgregar.SubEmpresaId, null); else { mPresenta.eliminarDetalleDobleUnidad(transprodIDEliminar, transprodDetalleIDEliminar, productoAgregar.SubEmpresaId, productoAgregar.ProductoClave, hmDetalleDobleUnidadAgregar, false); mPresenta.agregarProductoDobleUnidad(hmDetalleDobleUnidadAgregar, productoAgregar.ProductoClave, productoAgregar.SubEmpresaId, transprodDetalleIDEliminar); } }else { if (cantidadOriginalAgregar == null) mPresenta.agregarProductoUnidad(productoAgregar.ProductoClave, productoAgregar.SubEmpresaId, Short.parseShort(String.valueOf(tipoUnidadAgregar)), cantidadAgregar, Float.parseFloat("-1")); else { mPresenta.eliminarDetalle(transprodIDEliminar, transprodDetalleIDEliminar, productoAgregar.SubEmpresaId, productoAgregar.ProductoClave, Short.parseShort(String.valueOf(tipoUnidadAgregar)), cantidadOriginalAgregar, false); mPresenta.agregarProductoUnidad(productoAgregar.ProductoClave, productoAgregar.SubEmpresaId, tipoUnidadAgregar, cantidadAgregar, Float.parseFloat("-1"), cantidadOriginalAgregar); } } }else{ //mostrarAdvertencia("NO Agregar Producto"); } }else if(tipoMensaje == 30){ //cantidad maxima de producto if(respuesta == RespuestaMsg.Si){ if(existe){ mPresenta.eliminarDetalle(transprodIDEliminar, transprodDetalleIDEliminar, productoAgregar.SubEmpresaId, productoAgregar.ProductoClave, tipoUnidadAgregar, cantidadOriginalAgregar, false); if((Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.REPARTO)) mPresenta.agregarProductoUnidad(productoAgregar.ProductoClave, productoAgregar.SubEmpresaId, tipoUnidadAgregar, cantidadAgregar, Float.parseFloat("-1"),cantidadOriginalAgregar, transprodDetalleIDEliminar); else mPresenta.agregarProductoUnidad(productoAgregar.ProductoClave, productoAgregar.SubEmpresaId, tipoUnidadAgregar, cantidadAgregar, Float.parseFloat("-1"), cantidadOriginalAgregar); }else{ mPresenta.agregarProductoUnidad(productoAgregar.ProductoClave, productoAgregar.SubEmpresaId, tipoUnidadAgregar, cantidadAgregar, Float.parseFloat("-1")); } } }else if(tipoMensaje == 40){ if(respuesta == RespuestaMsg.Si){ //TODO: sperez CUROLMOV_18 1.4.1.1 try { TransProd oTrp = null; docsTransProd = mPresenta.getHashMapTransacciones().values().iterator(); if(docsTransProd.hasNext()){ oTrp = docsTransProd.next(); Transacciones.recolectarEnvasesAutomaticamente(oTrp, envasesPorRecolectar); } //envasesPorRecolectar.close(); //iniciarCapturaTotales(); } catch (Exception e) { e.printStackTrace(); } } envasesPorRecolectar.close(); iniciarCapturaTotales(); }else if(tipoMensaje ==0){ if(mPresenta.errorFinalizar){ finalizar(); } }else if (tipoMensaje == 60){ regresandoPromo = true; } } private void modificarPedidoReparto(){ //registerForContextMenu(lista); //lista.setOnItemLongClickListener(menu); captura.setVisibility(View.VISIBLE); modificando = true; modificar.setEnabled(false); Button boton = (Button) findViewById(R.id.btnContinuar); boton.setEnabled(true); if (manejoDobleUnidad){ mPresenta.modificarPedidoDobleUnidad(); }else { mPresenta.modificarPedido(); } } private void salir() { if (!esNuevo) { if (!soloLectura) mostrarPreguntaSiNo(Mensajes.get("BP0002"), 3); else { try{ //Se agrega este rollback porque al surtir pedido entra como solo lectura y estaba cambiando el //TipoPedido al entrar a los totales, lo que provocaba que el pedido desapareciera del listado BDVend.rollback(); }catch (Exception ex){ if (ex != null && ex.getMessage() != null){ mostrarError(ex.getMessage()); } } setResultado(Enumeradores.Resultados.RESULTADO_BIEN); finalizar(); } } else { if (hayProductos()) { if (!soloLectura) mostrarPreguntaSiNo(Mensajes.get("BP0002"), 3); else { setResultado(Enumeradores.Resultados.RESULTADO_BIEN); finalizar(); } } else { // no hay productos regresar(); } } } private void regresar() { try { if (esNuevo) { BDVend.rollback(); } else { if (huboCambios) BDVend.rollback(); } setResultado(Enumeradores.Resultados.RESULTADO_BIEN); finalizar(); } catch (Exception ex) { mostrarError(ex.getMessage()); } } @SuppressWarnings("rawtypes") public void insertarSeleccion(HashMap<String, TransProdDetalle> transProdDetalles) { try { Iterator<Entry<String, TransProdDetalle>> it = transProdDetalles.entrySet().iterator(); boolean bHuboInserciones = false; while (it.hasNext()) { // recorrer los productos Map.Entry producto = (Map.Entry) it.next(); String productoClave = producto.getKey().toString(); // int tipoUnidad =((TransProdDetalle) // producto.getValue()).TipoUnidad ; // Ya no es necesario buscar si existe porque se filtran los // productos que ya fueron capturados // Object aTransProdDetalle[] = // Consultas.ConsultasTransProdDetalle.obtenerDetallePorProductoClaveUnidad(productoClave, // String.valueOf(tipoUnidad), mPresenta.getTransaccionesIds()); boolean validar = false; Producto oProducto = Consultas.ConsultasProducto.obtenerProducto(productoClave); try { validar = mPresenta.validarProductoContenido(oProducto); } catch (Exception ex) { mostrarError(ex.getMessage().equals("") ? ex.getCause().getMessage() : ex.getMessage()); } if (/* aTransProdDetalle== null && */validar) { // agregarlo solo si no existe try { bHuboInserciones = true; //mPresenta.agregarProductoUnidad(oProducto.SubEmpresaId, ((TransProdDetalle) producto.getValue()), false); mPresenta.agregarProductoUnidad(oProducto, ((TransProdDetalle) producto.getValue()), false); } catch (Exception ex) { mostrarError(ex.getMessage().equals("") ? ex.getCause().getMessage() : ex.getMessage()); } } } if (bHuboInserciones) { refrescarProductos(mPresenta.getTransaccionesIds()); } } catch (Exception ex) { mostrarError(ex.getMessage()); } } @SuppressWarnings( { "rawtypes", "unchecked" }) public void insertarSeleccionSugerido(HashMap<String, HashMap<Short, TransProdDetalle>> transProdDetalles) { try { boolean bHuboInserciones = false; Iterator<Entry<String, HashMap<Short, TransProdDetalle>>> itProd = transProdDetalles.entrySet().iterator(); while (itProd.hasNext()) { Map.Entry producto = (Map.Entry) itProd.next(); boolean validar = false; Producto oProducto = Consultas.ConsultasProducto.obtenerProducto(producto.getKey().toString()); try { validar = mPresenta.validarProductoContenido(oProducto); } catch (Exception ex) { mostrarError(ex.getMessage().equals("") ? ex.getCause().getMessage() : ex.getMessage()); } Iterator<Entry<Short, TransProdDetalle>> it = ((HashMap<Short, TransProdDetalle>) producto.getValue()).entrySet().iterator(); while (it.hasNext()) { // recorrer los productos Map.Entry productoUnidad = (Map.Entry) it.next(); // Los productos que ya estan capturados no se permite editar //por lo que no es necesario verificar la existencia, ademas, ya se valido el inventario en caso de ser necesario. if (validar) { // agregarlo solo si no existe try { bHuboInserciones = true; //mPresenta.agregarProductoUnidad(oProducto.SubEmpresaId, ((TransProdDetalle) productoUnidad.getValue()), false); mPresenta.agregarProductoUnidad(oProducto, ((TransProdDetalle) productoUnidad.getValue()), false); } catch (Exception ex) { mostrarError(ex.getMessage().equals("") ? ex.getCause().getMessage() : ex.getMessage()); } } } } if (bHuboInserciones) { refrescarProductos(mPresenta.getTransaccionesIds()); } } catch (Exception ex) { mostrarError(ex.getMessage()); } } public void setProductoActual(Producto producto) { txtScanner.setTexto(producto.ProductoClave); txtScanner.setTag(producto.SubEmpresaId); } public void setListaPrecios(String valor) { TextView texto = (TextView) findViewById(R.id.lblListaPrecios); texto.setText(valor); } public void setHuboCambios(boolean cambio) { huboCambios = cambio; } public boolean getSurtir() { return surtir; } public boolean getModificandoPedidoReparto() { return modificando; } public boolean getModificandoPedidoNoReparto() { return modificandoAutoventa; } public boolean getReparto() { return reparto; } private OnClickListener mPedidoSugerido = new OnClickListener() { @Override public void onClick(View v) { final HashMap<String, Object> parametros = new HashMap<String, Object>(); parametros.put("ListaPrecios", mPresenta.getListasPrecios()); parametros.put("TransProd", mPresenta.getTransProdIds()); parametros.put("tipoValidacionExistencia", mPresenta.getTipoValidacionExistencia()); parametros.put("ModuloMovDetalle", mPresenta.getModuloMovDetalle()); parametros.put("mostrarValIniciales", !sugeridoMostrado); sugeridoMostrado = true; iniciarActividadConResultado(ICapturaPedidoSugerido.class, Enumeradores.Solicitudes.SOLICITUD_MOSTRAR_PEDIDO_SUGERIDO, Enumeradores.Acciones.ACCION_CAPTURAR_SUGERIDO, parametros); } }; /** * Para el caso del modulo de consignaciones que reutiliza esta actividad, se deberá * de validar la bandera CancConsigLiqui para calcular o no promociones. */ private OnClickListener mAplicarPromociones = new OnClickListener() { @Override public void onClick(View v) { Button boton = (Button) findViewById(R.id.btnContinuar); boton.setEnabled(false); if (!hayProductos()) { mostrarError(Mensajes.get("MDBAsignarProducto")); boton.setEnabled(true); } else { boolean cancConsigLiqui = "0".equals(((CONHist)Sesion.get(Campo.CONHist)).get("CancConsigLiqui")); if(consultar || (mPresenta.getModuloMovDetalle().TipoTransProd == TiposTransProd.VENTA_CONSIGNACION && cancConsigLiqui) || (mAccion != null && mAccion.equals(Enumeradores.Acciones.ACCION_ELIMINAR_CONSIGNACIONES))){ Sesion.set(Campo.ArrayTransProd, mPresenta.getHashMapTransacciones()); iniciarCapturaTotales(); boton.setEnabled(true); }else{ Sesion.set(Campo.ArrayTransProd, mPresenta.getHashMapTransacciones()); mPausaCiclo = new Object(); docsTransProd = mPresenta.getHashMapTransacciones().values().iterator(); if (docsTransProd.hasNext()) { calcularPromociones(docsTransProd.next()); } } } } }; private boolean hayProductos() { TextView totalProductos = (TextView) findViewById(R.id.txtTotalProductos); if (totalProductos.getText().toString().trim().equals("") || Float.parseFloat(totalProductos.getText().toString().replace(",", ".")) == 0) return false; else return true; } private void calcularPromociones(TransProd transProd) { // for(final Object transProd : // mPresenta.getHashMapTransacciones().values().toArray()){ //recorrer // todas las transacciones generadas y aplicar las promociones // correspondientes try { siguiente = false; try { BDVend.recuperar((TransProd) transProd, TransProdDetalle.class); for (TransProdDetalle oTpd : ((TransProd) transProd).TransProdDetalle) { BDVend.recuperar(oTpd, TPDImpuesto.class); } } catch (Exception e) { e.printStackTrace(); } promociones = new Promociones2((TransProd) transProd, (Vista) this, modificando); promociones.setOnTerminarAplicacionListener(new onTerminarAplicacionListener() { @Override public void onTerminarAplicacion() { if (docsTransProd.hasNext()) { calcularPromociones(docsTransProd.next()); } else { //validar reparto aqui? *********** no validar inv para msiev if(Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.REPARTO && mPresenta.getTipoTransProd() != 21 && surtir && reparto ){ //validar inventario despues de calcular las promociones, se validan tambien los productos promocionales try { if (manejoDobleUnidad) { prodSinExistencia = mPresenta.validarInventarioASurtirDobleUnidad(); }else{ prodSinExistencia = mPresenta.validarInventarioASurtir(); } }catch(Exception ex){ mostrarError("Error al validar inventario"); return; } if(prodSinExistencia.size() != 0){ boolean soloPromo = true; String productosNoPromo = ""; String productosPromo = ""; String productosCanje = ""; for(TransProdDetalle oTpd : prodSinExistencia){ //Los productos tipo Canje no se ajustan, solo modificando el pedido, ya que hay recalculo if(oTpd.Promocion != 2 && oTpd.Promocion != 3){ productosNoPromo += oTpd.ProductoClave + ", "; soloPromo = false; }else if(oTpd.Promocion == 2){ productosPromo += oTpd.ProductoClave + ", "; }else if(oTpd.Promocion == 3) { productosCanje += oTpd.ProductoClave + ", "; } } if(productosNoPromo != ""){ productosNoPromo = productosNoPromo.substring(0, productosNoPromo.length() - 2); } if(productosPromo != "" && soloPromo){ productosPromo = productosPromo.substring(0, productosPromo.length() - 2); } if(productosCanje != "" && soloPromo){ productosCanje = productosCanje.substring(0, productosCanje.length() - 2); } if(productosNoPromo != ""){ mostrarAdvertencia(Mensajes.get("E0714").replace("$0$", productosNoPromo)); return; }else if(productosCanje!=""){ mostrarAdvertencia(Mensajes.get("E0714").replace("$0$", " tipo Canje " + productosCanje )); return; }else if(productosPromo != ""){ mostrarPreguntaSiNo(Mensajes.get("P0209", productosPromo), 50); return; } } } //Lo que estaba del cuadre de envase se manda a un método separado //para poder llamarlo en la respuesta afirmativa del mensaje P0209 cuadreEnvases(); } } }); if (Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.REPARTO && mPresenta.getTipoTransProd() != 21 && surtir && !modificando){ //Se recorre hasta el final para que no se aplique ninguna promocion while (docsTransProd.hasNext()){ docsTransProd.next(); } promociones.TerminarAplicacionSinCalculos(); return; } if (promociones.Preparar()) { try { BDVend.recuperar((TransProd) transProd); BDVend.recuperar((TransProd) transProd, TransProdDetalle.class); // obtener todos los impuestos para que se recalculen // correctamente for (TransProdDetalle oTpd : ((TransProd) transProd).TransProdDetalle) { BDVend.recuperar(oTpd, TPDImpuesto.class); } } catch (Exception e) { e.printStackTrace(); } } promociones.Aplicar(); } catch (Exception e) { mostrarError(e.getMessage()); } } @SuppressWarnings("rawtypes") private void iniciarCapturaTotales(){ HashMap<String, Object> oParametros = new HashMap<String, Object>(); ArrayList<String> nuevo = new ArrayList<String>(); nuevo.add(String.valueOf(esNuevo)); ArrayList<String> transprod = new ArrayList<String>(); Iterator it = mPresenta.getHashMapTransacciones().entrySet().iterator(); while (it.hasNext()) { // recorrer todas las transacciones generadas para // calcular totales, impuestos, descuentos, etc ... Map.Entry e = (Map.Entry) it.next(); transprod.add(((TransProd) e.getValue()).TransProdID); } oParametros.put("TransProdId", transprod); oParametros.put("esNuevo", nuevo); oParametros.put("ModuloMovDetalle", mPresenta.getModuloMovDetalle()); oParametros.put("TotalInicial", mPresenta.getTotalInicial()); oParametros.put("Surtir", Boolean.toString(surtir)); oParametros.put("Modificando", Boolean.toString(modificando)); oParametros.put("ModificandoAutoventa", Boolean.toString(modificandoAutoventa)); if(mPresenta.getModuloMovDetalle().TipoTransProd == TiposTransProd.VENTA_CONSIGNACION) { iniciarActividadConResultado(ICapturaTotalesConsignacion.class, Enumeradores.Solicitudes.SOLICITUD_MOSTRAR_TOTALES_CONSIGNACION, mAccion, oParametros); }else { iniciarActividadConResultado(ICapturaTotales.class, Enumeradores.Solicitudes.SOLICITUD_MOSTRAR_TOTALES, Enumeradores.Acciones.ACCION_APLICAR_TOTALES, oParametros); } } public Handler getHandler() { return handler; } public Object getPausaCiclo() { return mPausaCiclo; } /* * public boolean getSiguiente(){ return siguiente; } */ public void setSiguiente(boolean bsiguiente) { siguiente = bsiguiente; } @SuppressWarnings("deprecation") public void refrescarProductos(String TransProdId) { try { // limpiarProducto(); // ocultarTeclado(); if (manejoDobleUnidad){ refrescarProductosDobleUnidad(TransProdId); return; } boolean existe = false; if (lista.getAdapter() != null){ stopManagingCursor(((Cursor) (((SimpleCursorAdapter) lista.getAdapter()).getCursor()))); ((Cursor) (((SimpleCursorAdapter) lista.getAdapter()).getCursor())).close(); existe = true; } ISetDatos stTransProdDetalle = Consultas.ConsultasTransProdDetalle.obtenerDetalle(TransProdId); Cursor cProductos = (Cursor) stTransProdDetalle.getOriginal(); startManagingCursor(cProductos); try { obtenerTotales(TransProdId); SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.elemento_captura_producto, cProductos, new String[] { "TipoUnidad", "ProductoClave", "Descripcion", "Precio", "Cantidad", "Total", "Existencia", "CantidadOriginal" }, new int[] { R.id.lblUnidadProductoClave, R.id.lblUnidadProductoClave, R.id.lblDescripcion, R.id.lblPU, R.id.lblCantidad, R.id.lblTotal, R.id.lblExistencia, R.id.lblCantidadOriginal }); adapter.setViewBinder(new vista()); lista.setAdapter(adapter); lista.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View v, int pos, long arg3) { captura.setEnableCantidadAgregar(true); if (oParametros != null && (!oParametros.get("TransProdId").trim().equals("")) && (mPresenta.getTipoFase() == 0 || mPresenta.getTipoFase() == 2) && calculando) { // si recibio el transprodid como parametro y esta // cancelado o surtido, mostrar cantidad de solo // lectura return; } // calculando = true; Cursor producto = (Cursor) (((SimpleCursorAdapter) lista.getAdapter()).getCursor()); Log.d("CapturaPedido", "Producto Seleccionado: " + producto.getString(producto.getColumnIndex("ProductoClave"))); // final String TransProdId = producto.getString(producto.getColumnIndex("TransProdID")); // final String TransProdDetalleId = producto.getString(producto.getColumnIndex("TransProdDetalleID")); lista.requestFocusFromTouch(); lista.setSelection(pos); // Se crea el objeto producto con lo que se trae en la // consulta para eficientar tiempos. Producto oProducto = new Producto(); oProducto.ProductoClave = producto.getString(producto.getColumnIndex("ProductoClave")); oProducto.Nombre = producto.getString(producto.getColumnIndex("Descripcion")); oProducto.SubEmpresaId = producto.getString(producto.getColumnIndex("SubEmpresaId")); oProducto.Venta = ((producto.getShort(producto.getColumnIndex("Venta")) == 1) ? true : false); oProducto.Contenido = ((producto.getShort(producto.getColumnIndex("Contenido")) == 1) ? true : false); captura.llenarProductoUnidad(oProducto, producto.getInt(producto.getColumnIndex("TipoUnidad")), producto.getFloat(producto.getColumnIndex("Cantidad"))); } } ); stopManagingCursor(cProductos); } catch (Exception e) { mostrarError(e.getMessage()); } txtScanner.requestFocus(); calculando = false; } catch (Exception ex) { mostrarError(ex.getMessage()); } } @SuppressWarnings("deprecation") public void refrescarProductosDobleUnidad(String TransProdIds) { try { // limpiarProducto(); // ocultarTeclado(); boolean existe = false; if (lista.getAdapter() != null){ stopManagingCursor(((Cursor) (((SimpleCursorAdapter) lista.getAdapter()).getCursor()))); ((Cursor) (((SimpleCursorAdapter) lista.getAdapter()).getCursor())).close(); existe = true; } ISetDatos stTransProdDetalle = Consultas.ConsultasTransProdDetalle.obtenerDetalleDobleUnidad(TransProdIds); Cursor cProductos = (Cursor) stTransProdDetalle.getOriginal(); startManagingCursor(cProductos); try { obtenerTotales(TransProdIds); SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.elemento_captura_prod_doble_unidad, cProductos, new String[] { "TipoUnidad", "Cantidad","UnidadAlterna","CantidadAlterna","ProductoClave", "Precio", "Total"}, new int[] { R.id.lblUnidad1, R.id.lblCantidad1, R.id.lblUnidad2, R.id.lblCantidad2, R.id.lblProducto,R.id.lblPU, R.id.lblTotal}); adapter.setViewBinder(new vistaDobleUnidad()); lista.setAdapter(adapter); lista.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View v, int pos, long arg3) { captura.setEnableCantidadAgregar(true); if (oParametros != null && (!oParametros.get("TransProdId").trim().equals("")) && (mPresenta.getTipoFase() == 0 || mPresenta.getTipoFase() == 2) && calculando) { // si recibio el transprodid como parametro y esta // cancelado o surtido, mostrar cantidad de solo // lectura return; } // calculando = true; Cursor producto = (Cursor) (((SimpleCursorAdapter) lista.getAdapter()).getCursor()); Log.d("CapturaPedido", "Producto Seleccionado: " + producto.getString(producto.getColumnIndex("ProductoClave"))); // final String TransProdId = producto.getString(producto.getColumnIndex("TransProdID")); // final String TransProdDetalleId = producto.getString(producto.getColumnIndex("TransProdDetalleID")); lista.requestFocusFromTouch(); lista.setSelection(pos); // Se crea el objeto producto con lo que se trae en la // consulta para eficientar tiempos. Producto oProducto = new Producto(); oProducto.ProductoClave = producto.getString(producto.getColumnIndex("ProductoClave")); oProducto.Nombre = producto.getString(producto.getColumnIndex("Descripcion")); oProducto.SubEmpresaId = producto.getString(producto.getColumnIndex("SubEmpresaId")); oProducto.Venta = ((producto.getShort(producto.getColumnIndex("Venta")) == 1) ? true : false); oProducto.Contenido = ((producto.getShort(producto.getColumnIndex("Contenido")) == 1) ? true : false); HashMap<Short,Float> hmUnidades = new HashMap<Short,Float>(); hmUnidades.put(producto.getShort(producto.getColumnIndex("TipoUnidad")), producto.getFloat(producto.getColumnIndex("Cantidad"))); if(producto.getShort(producto.getColumnIndex("UnidadAlterna"))>0 ){ hmUnidades.put(producto.getShort(producto.getColumnIndex("UnidadAlterna")), producto.getFloat(producto.getColumnIndex("CantidadAlterna"))); } captura.llenarProductoDobleUnidad(oProducto,hmUnidades); } } ); stopManagingCursor(cProductos); } catch (Exception e) { mostrarError(e.getMessage()); } txtScanner.requestFocus(); calculando = false; } catch (Exception ex) { mostrarError(ex.getMessage()); } } private void obtenerTotales(String TransProdID) { try { ISetDatos setDatos = Consultas.ConsultasTransProdDetalle.obtenerTotales(TransProdID); if (setDatos.moveToNext()) { TextView texto = (TextView) findViewById(R.id.txtTotalPrevio); Float totalCanjes = Consultas.ConsultasTransProdDetalle.obtenerTotalesCanjes(TransProdID); texto.setText(Generales.getFormatoDecimal(setDatos.getFloat(1) - (totalCanjes == null ? 0 : totalCanjes), "$ #,##0.00")); texto = (TextView) findViewById(R.id.txtTotalProductos); texto.setText(String.format("%.0f", setDatos.getFloat(0))); texto = (TextView) findViewById(R.id.txtTotalUnidades); texto.setText(String.format("%.0f", setDatos.getFloat("Unidades"))); String peso$volumen = String.format("%.2f", setDatos.getFloat("Peso")) + " / "; peso$volumen += String.format("%.2f", setDatos.getFloat("Volumen")); texto = (TextView) findViewById(R.id.txtVolumen); texto.setText(peso$volumen); } setDatos.close(); if(mnu != null){ if(hayProductos()){ mnu.getItem(1).setEnabled(false); }else{ mnu.getItem(1).setEnabled(true); } } } catch (Exception e) { mostrarError(e.getMessage()); //mostrarError(e); } } public void ocultarPedidoSugerido() { Button boton = (Button) findViewById(R.id.btnSugerido); boton.setVisibility(View.GONE); boton = (Button) findViewById(R.id.btnContinuar); android.widget.LinearLayout.LayoutParams param = new LinearLayout.LayoutParams( 0, LayoutParams.WRAP_CONTENT, 0.9f); boton.setLayoutParams(param); } @Override public boolean onCreateOptionsMenu(Menu menu) { if (mPresenta.errorFinalizar) return false; MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_captura_pedido, menu); menu.getItem(0).setTitle(Mensajes.get("XPromociones")); menu.getItem(1).setTitle(Mensajes.get("XActualizar") + " " + Mensajes.get("XInventario")); menu.getItem(2).setTitle(Mensajes.get("XModificar")); menu.getItem(3).setTitle(Mensajes.get("MCNMostrarUltimaVenta")); menu.getItem(4).setTitle(Mensajes.get("XAcMenVen")); menu.getItem(5).setTitle(Mensajes.get("XSaldoEnvases")); menu.getItem(6).setTitle(Mensajes.get("XTomaInventario")); //if(!(((Ruta) Sesion.get(Campo.RutaActual)).Inventario && Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.PREVENTA)){ menu.getItem(1).setVisible(false); //} menu.getItem(2).setVisible(false); menu.getItem(5).setVisible(false); menu.getItem(6).setVisible(false); if(Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.REPARTO && mPresenta.getTipoFase() == TiposFasesDocto.CAPTURA && mPresenta.getTipoTransProd() == TiposTransProd.PEDIDO && reparto && surtir){// || (Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.REPARTO && surtir)){ menu.getItem(2).setVisible(true); } MOTConfiguracion motConf = (MOTConfiguracion) Sesion.get(Campo.MOTConfiguracion); if(motConf.get("MostrarUltVta").equals("0")){ menu.getItem(3).setVisible(false); } if(!Consultas.ConsultasClienteVentaMensual.existeInformacion( ((Cliente)Sesion.get(Campo.ClienteActual)).ClienteClave)){ menu.getItem(4).setVisible(false); } if ( (Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.VENTA || Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.REPARTO) && mPresenta.getTipoTransProd() == TiposTransProd.PEDIDO && ((Cliente)Sesion.get(Campo.ClienteActual)).Prestamo ) { menu.getItem(5).setVisible(true); } try { if (((ConfigParametro) Sesion.get(Campo.ConfigParametro)).existeParametro("TomaInventario") && ((ConfigParametro) Sesion.get(Campo.ConfigParametro)).get("TomaInventario").equals("1")) { menu.getItem(6).setVisible(true); } }catch(Exception ex){ mostrarError("Error al recuperar"); } mnu = menu; return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.promociones: mPresenta.consultarPromociones(); return true; case R.id.actualizar: mPresenta.obtenerInventarioEnLinea(); return true; case R.id.modificar: //modificar pedido de reparto modificar = item; if(mPresenta.getTipoFase() != TiposFasesDocto.CAPTURA_ESCRITORIO) mostrarPreguntaSiNo(Mensajes.get("P0232"), 20); else{ modificarPedidoReparto(); /*captura.setVisibility(View.VISIBLE); modificando = true; modificar.setEnabled(false); mPresenta.modificarPedido();*/ } return true; case R.id.ultimavta: iniciarActividad(IConsultaUltimaVenta.class,null,null,false); return true; case R.id.ventaMensual: mostrarVentaMensual(); return true; case R.id.saldoEnvase: mostrarSaldoEnvase(); return true; case R.id.tomaInventario: if (hayProductos()){ mostrarError(Mensajes.get("I0297")); }else { HashMap<String, Object> oParametros = new HashMap<String, Object>(); oParametros.put("ListasPrecio", mPresenta.getListasPrecios()); oParametros.put("TipoValidarExistencia", mPresenta.getTipoValidacionExistencia()); if (inventarioID!= null && !inventarioID.equals("")) { oParametros.put("InventarioID", inventarioID); } iniciarActividadConResultado(ICapturaInventario.class, Solicitudes.SOLICITUD_TOMAR_INVENTARIO_PEDIDO, Acciones.ACCION_TOMAR_INVENTARIO_PEDIDO, oParametros); } return true; default: return super.onOptionsItemSelected(item); } } public void setSurtir(boolean surtir){ this.surtir = surtir; } public void setSoloLectura(boolean soloLectura){ this.soloLectura = soloLectura; } public void setEsNuevo(boolean esNuevo){ this.esNuevo = esNuevo; } public void setCapturaEnabled(boolean enabled){ captura.setEnabled(enabled); } // viewbinder para la lista de productos private class vista implements ViewBinder { @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { int viewId = view.getId(); switch (viewId) { case android.R.id.text1: // para llenar el combo TextView combo = (TextView) view; combo.setText(ValoresReferencia.getDescripcion("UNIDADV", cursor.getString(cursor.getColumnIndex("PRUTipoUnidad")))); break; case R.id.lblUnidadProductoClave: TextView unidadproducto = (TextView) view; if (columnIndex == 6) { // tipo unidad unidadproducto.setText(ValoresReferencia.getDescripcion("UNIDADV", cursor.getString(cursor.getColumnIndex("TipoUnidad")))); } else if (columnIndex == 3) { // producto clave unidadproducto.setText(unidadproducto.getText() + " - " + cursor.getString(columnIndex)); } break; case R.id.lblPU: case R.id.lblTotal: TextView total = (TextView) view; total.setText(Generales.getFormatoDecimal(cursor.getFloat(columnIndex), "$ #,##0.00")); break; case R.id.lblExistencia: // mostrar la existencia con los decimales configurados TextView existencia = (TextView) view; if (mPresenta.getTipoValidacionExistencia() == TiposValidacionInventario.NoValidar) { existencia.setVisibility(View.GONE); } else { existencia.setText(Generales.getFormatoDecimal(cursor.getFloat(columnIndex), cursor.getInt(cursor.getColumnIndex("DecimalProducto")))); } break; case R.id.lblCantidad: TextView cantidad = (TextView) view; cantidad.setText(Generales.getFormatoDecimal(cursor.getFloat(columnIndex), cursor.getInt(cursor.getColumnIndex("DecimalProducto")))); break; case R.id.lblDescripcion: TextView lblDescripcion = (TextView) view; lblDescripcion.setText(cursor.getString(columnIndex)); break; default: TextView texto = (TextView) view; texto.setText(cursor.getString(columnIndex)); break; } return true; } } private class vistaDobleUnidad implements ViewBinder { @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { int viewId = view.getId(); switch (viewId) { /*case android.R.id.text1: // para llenar el combo TextView combo = (TextView) view; combo.setText(ValoresReferencia.getDescripcion("UNIDADV", cursor.getString(cursor.getColumnIndex("PRUTipoUnidad")))); break;*/ case R.id.lblUnidad1: TextView unidadproducto1 = (TextView) view; unidadproducto1.setText(ValoresReferencia.getDescripcion("UNIDADV", cursor.getString(cursor.getColumnIndex("TipoUnidad")))); break; case R.id.lblUnidad2: TextView unidadproducto2 = (TextView) view; if (cursor.getString(cursor.getColumnIndex("UnidadAlterna")) != null) { unidadproducto2.setText(ValoresReferencia.getDescripcion("UNIDADV", cursor.getString(cursor.getColumnIndex("UnidadAlterna")))); }else{ unidadproducto2.setText(""); } break; case R.id.lblPU: case R.id.lblTotal: TextView total = (TextView) view; total.setText(Generales.getFormatoDecimal(cursor.getFloat(columnIndex), "$ #,##0.00")); break; case R.id.lblCantidad1: TextView cantidad1 = (TextView) view; cantidad1.setText(Generales.getFormatoDecimal(cursor.getFloat(columnIndex), cursor.getInt(cursor.getColumnIndex("DecimalProd1")))); break; case R.id.lblCantidad2: TextView cantidad2 = (TextView) view; if ( cursor.getFloat(columnIndex)>0) { cantidad2.setText(Generales.getFormatoDecimal(cursor.getFloat(columnIndex), cursor.getInt(cursor.getColumnIndex("DecimalProd2")))); }else{ cantidad2.setText(""); } break; case R.id.lblProducto: TextView producto = (TextView) view; producto.setText(cursor.getString(columnIndex) + " - " + cursor.getString(cursor.getColumnIndex("Descripcion"))); break; default: TextView texto = (TextView) view; texto.setText(cursor.getString(columnIndex)); break; } return true; } } private class vistaListasPrecios implements ViewBinder { @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { int viewId = view.getId(); switch (viewId) { case R.id.txtCol2: TextView total = (TextView) view; total.setText(Generales.getFormatoDecimal(cursor.getFloat(columnIndex), "$ #,##0.00")); break; default: TextView texto = (TextView) view; texto.setText(cursor.getString(columnIndex)); break; } return true; } } private void mostrarVentaMensual(){ VentaMensual vm = VentaMensual.newInstance( ((Cliente)Sesion.get(Campo.ClienteActual)).ClienteClave); getFragmentManager().beginTransaction(). setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out). add(R.id.layout_captura_pedido, vm, FRAGMENT_TAG).commit(); } private void mostrarSaldoEnvase() { try{ LayoutInflater inflater = (LayoutInflater) CapturaPedido.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View dialogView = inflater.inflate(R.layout.dialog_saldoenvase, null); AlertDialog.Builder builder = new AlertDialog.Builder(this); TextView lbl = (TextView) dialogView.findViewById(R.id.lblTituloDialogoSaldoEnvase); lbl.setText(Mensajes.get("XSaldoEnvases")); lbl = (TextView) dialogView.findViewById(R.id.lblClave); lbl.setText(Mensajes.get("XClave")); lbl = (TextView) dialogView.findViewById(R.id.lblCargo); lbl.setText(Mensajes.get("XCargo")); lbl = (TextView) dialogView.findViewById(R.id.lblAbono); lbl.setText(Mensajes.get("XAbono")); lbl = (TextView) dialogView.findViewById(R.id.lblVenta); lbl.setText(Mensajes.get("XVenta")); lbl = (TextView) dialogView.findViewById(R.id.lblSaldo); lbl.setText(Mensajes.get("XSaldo")); ListView modeList = (ListView) dialogView.findViewById(R.id.lstSaldoEnvase); modeList.setBackgroundColor(Color.WHITE); Cursor cursor = mPresenta.obtenerSaldoEnvase(); SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,R.layout.lista_simple_hor5,cursor, new String[]{"ProductoClave","Cargo","Abono","Venta","Saldo"}, new int[]{R.id.txtCol1,R.id.txtCol2,R.id.txtCol3,R.id.txtCol4,R.id.txtCol5}); modeList.setAdapter(adapter); builder.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); builder.setView(dialogView); final Dialog dialog = builder.create(); dialog.show(); }catch(Exception e){ mostrarError(e.getMessage()); e.printStackTrace(); } } private void cuadreEnvases(){ Cliente oCliente = (Cliente) Sesion.get(Campo.ClienteActual); boolean iniciarTotales = true; //bandera para iniciar la captura de totales MOTConfiguracion oMC = (MOTConfiguracion) Sesion.get(Campo.MOTConfiguracion); if(( (Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.REPARTO && !surtir && !reparto) || Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.VENTA) //&& mPresenta.getTipoTransProd() == 1 && oCliente.Prestamo && oCliente.LimiteEnvase == 0 ){ && mPresenta.getTipoTransProd() == TiposTransProd.PEDIDO && oMC.get("CuadreDeEnvase").toString().equals("1") && oCliente.Prestamo ){ //TODO sperez CUROLMOV18 Anexo 3 punto 1.1: cuadre de envase try { String transprodIds = mPresenta.getTransProdIds(); envasesPorRecolectar = Consultas.ConsultasTransProd.obtenerDiferenciaEnvase(transprodIds); String sProductos = ""; while(envasesPorRecolectar.moveToNext()){ float dif = envasesPorRecolectar.getFloat("Diferencia"); int decimales = envasesPorRecolectar.getInt("DecimalProducto"); if(dif > 0){ sProductos += envasesPorRecolectar.getString("ProductoDetClave") + " (" + String.format("%."+decimales+"f",dif) + "), "; } } if(sProductos.length() > 0){ sProductos = sProductos.substring(0,sProductos.length()-2); mostrarPreguntaSiNo(Mensajes.get("P0242").replace("$0$", sProductos), 40); iniciarTotales = false; //no iniciar totales para poder mostrar y contestar la pregunta } }catch (Exception e){ e.printStackTrace(); } } if(iniciarTotales){ iniciarCapturaTotales(); } } private CapturaProducto.onAgregarProductoListener mAgregarProductoListener = new CapturaProducto.onAgregarProductoListener() { @Override public void onAgregarProducto (Producto producto,int tipoUnidad, float cantidad) { try { Object aTransProdDetalle[] = Consultas.ConsultasTransProdDetalle.obtenerDetallePorProductoClaveUnidad(producto.ProductoClave, String.valueOf(tipoUnidad), mPresenta.getTransaccionesIds()); MOTConfiguracion motConf = (MOTConfiguracion) Sesion.get(Campo.MOTConfiguracion); //validacion NoAdicionProducto if(modificando == true && (Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.REPARTO) && motConf.get("NoAdicionProducto").toString().equals("1")){ if(aTransProdDetalle == null){ //no existe en el pedido, no se puede agregar mostrarAdvertencia(Mensajes.get("E0908")); return; } //si existe, validar cantidades float valorOriginal = Float.parseFloat(aTransProdDetalle[2].toString()); float valorActual = cantidad; if(valorOriginal < valorActual){ captura.setEnableCantidadAgregar(false); mostrarAdvertencia(Mensajes.get("E0908")); return; } } if (aTransProdDetalle != null) { // si ya existe, seleccionarlo de la lista E0714 if (Float.parseFloat(aTransProdDetalle[2].toString()) != cantidad) { AtomicReference<Float> existencia = new AtomicReference<Float>(); StringBuilder error = new StringBuilder(); if (mPresenta.getTipoValidacionExistencia() != TiposValidacionInventario.NoValidar) { if (!Inventario.ValidarExistencia(producto.ProductoClave, tipoUnidad, cantidad, Float.parseFloat(aTransProdDetalle[2].toString()), mPresenta.getModuloMovDetalle(), false, existencia, error)) { captura.setError(error.toString()); if (mPresenta.getTipoValidacionExistencia() == TiposValidacionInventario.ValidacionRestrictiva) { if(!validarVenderApartado(producto, Short.parseShort(String.valueOf(tipoUnidad)) , cantidad, Float.parseFloat(aTransProdDetalle[2].toString()),aTransProdDetalle[0].toString(),aTransProdDetalle[1].toString())) return; if (existencia.get() != null && existencia.get() > 0) { captura.setCantidad(Float.parseFloat(aTransProdDetalle[2].toString()) + existencia.get()); } else { captura.setCantidad(cantidad); } return; } } else { captura.setAdvertencia(error.toString()); } } if(!mPresenta.validarCantMax(cantidad)){ //no esta configurada ninguna cantidad, continuar normal mPresenta.eliminarDetalle(aTransProdDetalle[0].toString(), aTransProdDetalle[1].toString(), producto.SubEmpresaId, producto.ProductoClave, tipoUnidad, Float.parseFloat(aTransProdDetalle[2].toString()), false); if((Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.REPARTO)) mPresenta.agregarProductoUnidad(producto.ProductoClave, producto.SubEmpresaId, tipoUnidad, cantidad, Float.parseFloat("-1"),Float.parseFloat(aTransProdDetalle[2].toString()), aTransProdDetalle[1].toString()); else mPresenta.agregarProductoUnidad(producto.ProductoClave, producto.SubEmpresaId, tipoUnidad, cantidad, Float.parseFloat("-1"), aTransProdDetalle[1].toString()); }else{ //guardar la info en las varibles para poder agregar el producto si contesta que si a la pregunta productoAgregar = producto; tipoUnidadAgregar = Short.parseShort(String.valueOf(tipoUnidad)) ; cantidadAgregar = cantidad; cantidadOriginalAgregar = Float.parseFloat(aTransProdDetalle[2].toString()); transprodIDEliminar = aTransProdDetalle[0].toString(); transprodDetalleIDEliminar = aTransProdDetalle[1].toString(); existe = true; } } } else { AtomicReference<Float> existencia = new AtomicReference<Float>(); StringBuilder error = new StringBuilder(); if (mPresenta.getTipoValidacionExistencia() != TiposValidacionInventario.NoValidar) { if (!Inventario.ValidarExistencia(producto.ProductoClave, tipoUnidad, cantidad, mPresenta.getModuloMovDetalle(), existencia, error)) { captura.setError(error.toString()); if (mPresenta.getTipoValidacionExistencia() == TiposValidacionInventario.ValidacionRestrictiva) { if(!validarVenderApartado(producto, tipoUnidad, cantidad)) return; if (existencia.get() != null && existencia.get() > 0) { captura.setCantidad(existencia.get()); } else { captura.setCantidad(Float.valueOf(0)); } return; } } else { captura.setAdvertencia(error.toString()); } } //mPresenta.agregarProductoUnidad(producto.ProductoClave, producto.SubEmpresaId, tipoUnidad, cantidad, Float.parseFloat("-1")); if(!mPresenta.validarCantMax(cantidad)){ //no esta configurada ninguna cantidad, continuar normal mPresenta.agregarProductoUnidad(producto.ProductoClave, producto.SubEmpresaId, tipoUnidad, cantidad, Float.parseFloat("-1")); }else{ //guardar la info en las varibles para poder agregar el producto si contesta que si a la pregunta productoAgregar = producto; tipoUnidadAgregar = tipoUnidad; cantidadAgregar = cantidad; existe = false; } } } catch (Exception e) { mostrarError(e.getMessage()); } } }; private CapturaProducto.onAgregarProdDobleUnidadListener mAgregarProdDobleUnidadListener = new CapturaProducto.onAgregarProdDobleUnidadListener(){ @Override public void onAgregarProdDobleUnidad(Producto producto, HashMap<Short, InventarioDobleUnidad.DetalleProductoDobleUnidad> hmDetalleUnidades) { try { TransProdDetalle oTPD = Consultas.ConsultasTransProdDetalle.obtenerTPDDobleUnidadPorProducto(producto.ProductoClave, mPresenta.getTransaccionesIds()); //Verificar inventario if (oTPD != null) { // si ya existe, seleccionarlo de la lista E0714 HashMap<Short, InventarioDobleUnidad.DetalleProductoDobleUnidad> hmCantidadesOrig = new HashMap<Short,InventarioDobleUnidad.DetalleProductoDobleUnidad>(); hmCantidadesOrig.put(Short.parseShort(String.valueOf(oTPD.TipoUnidad)), new InventarioDobleUnidad.DetalleProductoDobleUnidad(Short.parseShort(String.valueOf(oTPD.TipoUnidad)),null,oTPD.Cantidad,null, null, hmDetalleUnidades.get(Short.parseShort(String.valueOf(oTPD.TipoUnidad))).DecimalProducto , null)); if(oTPD.TPDDatosExtra.size() >0 && oTPD.TPDDatosExtra.get(0).UnidadAlterna != null && oTPD.TPDDatosExtra.get(0).UnidadAlterna>0){ hmCantidadesOrig.put(oTPD.TPDDatosExtra.get(0).UnidadAlterna, new InventarioDobleUnidad.DetalleProductoDobleUnidad(oTPD.TPDDatosExtra.get(0).UnidadAlterna,null,oTPD.TPDDatosExtra.get(0).CantidadAlterna, null,null,hmDetalleUnidades.get(oTPD.TPDDatosExtra.get(0).UnidadAlterna).DecimalProducto,null )); } //Se guarda en el arreglo la cantidad original para tenerla de referencia al guardar el TransProdDetalle, cuando es reparto if (hmDetalleUnidades.containsKey(Short.parseShort(String.valueOf(oTPD.TipoUnidad)))){ hmDetalleUnidades.get(Short.parseShort(String.valueOf(oTPD.TipoUnidad))).CantidadOriginal = ((oTPD.CantidadOriginal != null && oTPD.CantidadOriginal>0 )? oTPD.CantidadOriginal : oTPD.Cantidad); } if (oTPD.TPDDatosExtra != null && oTPD.TPDDatosExtra.size() >0 && oTPD.TPDDatosExtra.get(0).UnidadAlterna != null && hmDetalleUnidades.containsKey(oTPD.TPDDatosExtra.get(0).UnidadAlterna)){ hmDetalleUnidades.get(oTPD.TPDDatosExtra.get(0).UnidadAlterna).CantidadOriginal = ((oTPD.TPDDatosExtra.get(0).CantidadAlternaOriginal != null && oTPD.TPDDatosExtra.get(0).CantidadAlternaOriginal >0 )? oTPD.TPDDatosExtra.get(0).CantidadAlternaOriginal : oTPD.TPDDatosExtra.get(0).CantidadAlterna); } boolean bCambioCantidad = false; boolean bTomarApartado = false; for(Short unidad : hmDetalleUnidades.keySet()){ if (!hmCantidadesOrig.containsKey(unidad)){ throw( new Exception("La unidad " + ValoresReferencia.getDescripcion("UNIDADV",unidad.toString()) + " no existe en el documento original")); } if (hmDetalleUnidades.get(unidad).Cantidad != hmCantidadesOrig.get(unidad).Cantidad){ bCambioCantidad = true; AtomicReference<Float> existencia = new AtomicReference<Float>(); StringBuilder error = new StringBuilder(); if (mPresenta.getTipoValidacionExistencia() != TiposValidacionInventario.NoValidar) { if (!InventarioDobleUnidad.ValidarExistencia(producto.ProductoClave, unidad, hmDetalleUnidades.get(unidad).Cantidad, hmCantidadesOrig.get(unidad).Cantidad, mPresenta.getModuloMovDetalle(), false, existencia, error)) { captura.setError(error.toString()); if (mPresenta.getTipoValidacionExistencia() == TiposValidacionInventario.ValidacionRestrictiva) { if(Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.REPARTO){ /*if(((CONHist)Sesion.get(Campo.CONHist)).get("VenderApartado").toString().equals("0")){ captura.setError(Mensajes.get("E0714").replace("$0$", producto.ProductoClave)); return; }else */if(((CONHist)Sesion.get(Campo.CONHist)).get("VenderApartado").toString().equals("1")){ AtomicReference<Float> existenciaApartado = new AtomicReference<Float>(); StringBuilder errorApartado = new StringBuilder(); if(!InventarioDobleUnidad.ValidarExistenciaDifNoDisponible(producto.ProductoClave, unidad, hmDetalleUnidades.get(unidad).Cantidad, existencia, error)){ captura.setError(Mensajes.get("E0714").replace("$0$", producto.ProductoClave)); return; } bTomarApartado=true; captura.setError(""); } } if (existencia.get() != null && existencia.get() > 0) { captura.setCantidad( hmCantidadesOrig.get(unidad).Cantidad + existencia.get(), unidad); } else { //revisar esto en el escenario normal captura.setCantidad(hmDetalleUnidades.get(unidad).Cantidad, unidad); } if(!bTomarApartado) return; } } else { captura.setAdvertencia(error.toString()); } } } } if(bCambioCantidad) { if (bTomarApartado){ mostrarPreguntaSiNo(Mensajes.get("P0087"), 10); hmDetalleDobleUnidadAgregar = hmDetalleUnidades; productoAgregar = producto; transprodIDEliminar = oTPD.TransProdID; transprodDetalleIDEliminar = oTPD.TransProdDetalleID; return; } mPresenta.eliminarDetalleDobleUnidad(oTPD.TransProdID, oTPD.TransProdDetalleID, producto.SubEmpresaId, producto.ProductoClave, hmCantidadesOrig, false); mPresenta.agregarProductoDobleUnidad(hmDetalleUnidades, producto.ProductoClave, producto.SubEmpresaId, oTPD.TransProdDetalleID); } } else { boolean bTomarApartado = false; if (mPresenta.getTipoValidacionExistencia() != TiposValidacionInventario.NoValidar) { captura.setError(""); for(Short unidad : hmDetalleUnidades.keySet()) { AtomicReference<Float> existencia = new AtomicReference<Float>(); StringBuilder error = new StringBuilder(); if (!InventarioDobleUnidad.ValidarExistencia(producto.ProductoClave, unidad, hmDetalleUnidades.get(unidad).Cantidad, mPresenta.getModuloMovDetalle(), existencia, error)) { captura.setError(error.toString()); if (mPresenta.getTipoValidacionExistencia() == TiposValidacionInventario.ValidacionRestrictiva) { if(Integer.parseInt(Sesion.get(Campo.TipoModulo).toString()) == Enumeradores.TiposModulos.REPARTO){ if(((CONHist)Sesion.get(Campo.CONHist)).get("VenderApartado").toString().equals("0")){ captura.setError(Mensajes.get("E0714").replace("$0$", producto.ProductoClave)); return; }else if(((CONHist)Sesion.get(Campo.CONHist)).get("VenderApartado").toString().equals("1")){ AtomicReference<Float> existenciaApartado = new AtomicReference<Float>(); StringBuilder errorApartado = new StringBuilder(); if(!InventarioDobleUnidad.ValidarExistenciaDifNoDisponible(producto.ProductoClave, unidad, hmDetalleUnidades.get(unidad).Cantidad, existencia, error)){ captura.setError(Mensajes.get("E0714").replace("$0$", producto.ProductoClave)); return; } bTomarApartado=true; captura.setError(""); } } if (existencia.get() != null && existencia.get() > 0) { captura.setCantidad(existencia.get(), unidad); } else { captura.setCantidad(Float.valueOf(0),unidad); } if(!bTomarApartado) return; }else{ captura.setAdvertencia(error.toString()); } } else { captura.setAdvertencia(error.toString()); } } } if(bTomarApartado){ mostrarPreguntaSiNo(Mensajes.get("P0087"), 10); hmDetalleDobleUnidadAgregar = hmDetalleUnidades; productoAgregar = producto; transprodIDEliminar = null; transprodDetalleIDEliminar = null; return; } mPresenta.agregarProductoDobleUnidad( hmDetalleUnidades, producto.ProductoClave, producto.SubEmpresaId,null); } } catch (Exception e) { mostrarError(e.getMessage()); } } }; }
101,576
0.66328
0.659263
2,527
39.194302
43.761871
395
false
false
0
0
0
0
0
0
3.709141
false
false
13
ad0f4136b5652451a61cae8317cb348e896afa9e
2,637,109,932,941
d7d7d9dd3d2d2eeba036bc41d01fa5adbd5e6a40
/app/src/main/java/com/sourav/weatherfore/MainActivity.java
3d8d0c55362d0f6f632a16a2be5db65daf83ad82
[]
no_license
Sourav992v/WeatherFore
https://github.com/Sourav992v/WeatherFore
c619f2c01499fcfa917cf069370d4122136ea6a1
e433af187b66e197169637cea38858402ca68b8d
refs/heads/master
2021-05-06T17:10:23.843000
2018-07-09T13:22:18
2018-07-09T13:22:18
107,972,337
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sourav.weatherfore; import android.Manifest; import android.annotation.SuppressLint; import android.app.PendingIntent; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.CollapsingToolbarLayout; import android.support.design.widget.Snackbar; import android.support.v4.app.ActivityCompat; import android.support.v4.app.ActivityOptionsCompat; import android.support.v4.util.Pair; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.TextView; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.sourav.weatherfore.db.WeatherContract; import com.sourav.weatherfore.db.WeatherPreferences; import com.sourav.weatherfore.sync.SyncUtils; import com.sourav.weatherfore.utilities.WeatherUtils; public class MainActivity extends AppCompatActivity implements ForecastFragment.Callback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,SharedPreferences.OnSharedPreferenceChangeListener{ private static final String DETAIL_FRAGMENT_TAG = "DFTAG"; private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 34; private static final long UPDATE_INTERVAL = 10 * 1000; private static final long FASTEST_UPDATE_INTERVAL = UPDATE_INTERVAL / 2; private static final long MAX_WAIT_TIME = UPDATE_INTERVAL * 3; private GoogleApiClient mGoogleApiClient; private LocationRequest mLocationRequest; private boolean mTwoPane; private String mLocation; private TextView mLocationName; @SuppressLint("RestrictedApi") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mLocation = WeatherPreferences.getPreferredWeatherLocation(this); Uri contentUri = getIntent() != null ? getIntent().getData() : null; // Check if the user revoked runtime permissions. if (!checkPermissions()) { requestPermissions(); } buildGoogleApiClient(); ((CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar)).setTitleEnabled(true); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); mLocationName = findViewById(R.id.location_text); if (findViewById(R.id.weather_detail_container) != null) { // The detail container view will be present only in the large-screen layouts // (res/layout-sw600dp). If this view is present, then the activity should be // in two-pane mode. mTwoPane = true; // In two-pane mode, show the detail view in this activity by // adding or replacing the detail fragment using a // fragment transaction. DetailFragment fragment = new DetailFragment(); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .replace(R.id.weather_detail_container, fragment, DETAIL_FRAGMENT_TAG) .commit(); } } else { mTwoPane = false; ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setElevation(0f); } } ForecastFragment forecastFragment = ((ForecastFragment) getSupportFragmentManager() .findFragmentById(R.id.fragment_forecast)); forecastFragment.setUseTodayLayout(!mTwoPane); if (contentUri != null) { forecastFragment.setInitialSelectedDate( WeatherContract.WeatherEntry.getDateFromUri(contentUri)); } SyncUtils.initialize(this); } @Override protected void onResume() { super.onResume(); String location = WeatherPreferences.getPreferredWeatherLocation(this); // update the location in our second pane using the fragment manager if (location != null && !location.equals(mLocation)) { ForecastFragment ff = (ForecastFragment) getSupportFragmentManager() .findFragmentById(R.id.fragment_forecast); if (null != ff) { ff.onLocationChanged(); } DetailFragment df = (DetailFragment) getSupportFragmentManager().findFragmentByTag(DETAIL_FRAGMENT_TAG); if (null != df) { df.onLocationChanged(location); } mLocation = location; } mLocationName.setText(location); } @Override protected void onStart() { super.onStart(); } @Override public void onStop() { super.onStop(); if (mGoogleApiClient.isConnected()) { removeLocationUpdates(); mGoogleApiClient.disconnect(); } } @SuppressWarnings("unchecked") @Override public void onItemSelected(Uri contentUri, ForecastAdapter.ForecastViewHolder vh) { if (mTwoPane) { // In two-pane mode, show the detail view in this activity by // adding or replacing the detail fragment using a // fragment transaction. Bundle args = new Bundle(); args.putParcelable(DetailFragment.DETAIL_URI, contentUri); DetailFragment fragment = new DetailFragment(); fragment.setArguments(args); getSupportFragmentManager().beginTransaction() .replace(R.id.weather_detail_container, fragment, DETAIL_FRAGMENT_TAG) .commit(); } else { Intent intent = new Intent(this, DetailActivity.class) .setData(contentUri); ActivityOptionsCompat activityOptions = ActivityOptionsCompat.makeSceneTransitionAnimation(this, new Pair<View, String>(vh.mIconView, getString(R.string.detail_icon_transition_name))); ActivityCompat.startActivity(this, intent, activityOptions.toBundle()); } } @SuppressLint("MissingPermission") @Override public void onConnected(@Nullable Bundle bundle) { requestLocationUpdates(); WeatherUtils.resetLocationStatus(this); WeatherPreferences.resetLocationCoordinates(this); SyncUtils.startImmediateSync(this); } @Override public void onConnectionSuspended(int i) { removeLocationUpdates(); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } /** * Sets up the location request. Android has two location request settings: * {@code ACCESS_COARSE_LOCATION} and {@code ACCESS_FINE_LOCATION}. These settings control * the accuracy of the current location. This sample uses ACCESS_FINE_LOCATION, as defined in * the AndroidManifest.xml. * <p/> * When the ACCESS_FINE_LOCATION setting is specified, combined with a fast update * interval (5 seconds), the Fused Location Provider API returns location updates that are * accurate to within a few feet. * <p/> * These settings are appropriate for mapping applications that show real-time location * updates. */ @SuppressLint("RestrictedApi") private void createLocationRequest() { mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(UPDATE_INTERVAL); // Sets the fastest rate for active location updates. This interval is exact, and your // application will never receive updates faster than this value. mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); // Sets the maximum time when batched location updates are delivered. Updates may be // delivered sooner than this interval. mLocationRequest.setMaxWaitTime(MAX_WAIT_TIME); SyncUtils.syncImmediately(this); } /** * Builds {@link GoogleApiClient}, enabling automatic lifecycle management using * {@link GoogleApiClient.Builder#enableAutoManage(android.support.v4.app.FragmentActivity, * int, GoogleApiClient.OnConnectionFailedListener)}. I.e., GoogleApiClient connects in * {@link AppCompatActivity#onStart}, or if onStart() has already happened, it connects * immediately, and disconnects automatically in {@link AppCompatActivity#onStop}. */ private void buildGoogleApiClient() { if (mGoogleApiClient != null) { return; } mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .enableAutoManage(this, this) .addApi(LocationServices.API) .build(); createLocationRequest(); } /** * Return the current state of the permissions needed. */ private boolean checkPermissions() { int permissionState = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION); return permissionState == PackageManager.PERMISSION_GRANTED; } private void requestPermissions() { boolean shouldProvideRationale = ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION); // Provide an additional rationale to the user. This would happen if the user denied the // request previously, but didn't check the "Don't ask again" checkbox. if (shouldProvideRationale) { Snackbar.make( findViewById(R.id.fragment_forecast), R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE) .setAction(R.string.ok, new View.OnClickListener() { @Override public void onClick(View view) { // Request permission ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_PERMISSIONS_REQUEST_CODE); } }) .show(); } else { // Request permission. It's possible this can be auto answered if device policy // sets the permission in a given state or the user denied the permission // previously and checked "Never ask again". ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_PERMISSIONS_REQUEST_CODE); } } /** * Callback received when a permissions request has been completed. */ @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == REQUEST_PERMISSIONS_REQUEST_CODE) { if (grantResults.length <= 0) { // If user interaction was interrupted, the permission request is cancelled and you // receive empty arrays. } else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission was granted. Kick off the process of building and connecting // GoogleApiClient. buildGoogleApiClient(); } else { // Permission denied. // Notify the user via a SnackBar that they have rejected a core permission for the // app, which makes the Activity useless. In a real app, core permissions would // typically be best requested during a welcome-screen flow. // Additionally, it is important to remember that a permission might have been // rejected without asking the user for permission (device policy or "Never ask // again" prompts). Therefore, a user interface affordance is typically implemented // when permissions are denied. Otherwise, your app could appear unresponsive to // touches or interactions which have required permissions. Snackbar.make( findViewById(R.id.fragment_forecast), R.string.permission_denied_explanation, Snackbar.LENGTH_INDEFINITE) .setAction(R.string.settings, new View.OnClickListener() { @Override public void onClick(View view) { // Build intent that displays the App settings screen. Intent intent = new Intent(); intent.setAction( Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts("package", BuildConfig.APPLICATION_ID, null); intent.setData(uri); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } }) .show(); } } } private PendingIntent getPendingIntent() { Intent intent = new Intent(this, LocationUpdatesBroadcastReceiver.class); intent.setAction(LocationUpdatesBroadcastReceiver.ACTION_PROCESS_UPDATES); return PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } /** * Handles the Request Updates button and requests start of location updates. */ public void requestLocationUpdates() { try { LocationServices.getFusedLocationProviderClient(this).requestLocationUpdates(mLocationRequest, getPendingIntent()); mGoogleApiClient.connect(); } catch (SecurityException e) { LocationRequestHelper.setRequesting(this, false); } } /** * Handles the Remove Updates button, and requests removal of location updates. */ public void removeLocationUpdates() { LocationRequestHelper.setRequesting(this, false); LocationServices.getFusedLocationProviderClient(this).removeLocationUpdates( getPendingIntent()); mGoogleApiClient.disconnect(); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(getString(R.string.pref_location_key))){ SyncUtils.startImmediateSync(this); } } }
UTF-8
Java
15,332
java
MainActivity.java
Java
[]
null
[]
package com.sourav.weatherfore; import android.Manifest; import android.annotation.SuppressLint; import android.app.PendingIntent; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.CollapsingToolbarLayout; import android.support.design.widget.Snackbar; import android.support.v4.app.ActivityCompat; import android.support.v4.app.ActivityOptionsCompat; import android.support.v4.util.Pair; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.TextView; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.sourav.weatherfore.db.WeatherContract; import com.sourav.weatherfore.db.WeatherPreferences; import com.sourav.weatherfore.sync.SyncUtils; import com.sourav.weatherfore.utilities.WeatherUtils; public class MainActivity extends AppCompatActivity implements ForecastFragment.Callback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,SharedPreferences.OnSharedPreferenceChangeListener{ private static final String DETAIL_FRAGMENT_TAG = "DFTAG"; private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 34; private static final long UPDATE_INTERVAL = 10 * 1000; private static final long FASTEST_UPDATE_INTERVAL = UPDATE_INTERVAL / 2; private static final long MAX_WAIT_TIME = UPDATE_INTERVAL * 3; private GoogleApiClient mGoogleApiClient; private LocationRequest mLocationRequest; private boolean mTwoPane; private String mLocation; private TextView mLocationName; @SuppressLint("RestrictedApi") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mLocation = WeatherPreferences.getPreferredWeatherLocation(this); Uri contentUri = getIntent() != null ? getIntent().getData() : null; // Check if the user revoked runtime permissions. if (!checkPermissions()) { requestPermissions(); } buildGoogleApiClient(); ((CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar)).setTitleEnabled(true); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); mLocationName = findViewById(R.id.location_text); if (findViewById(R.id.weather_detail_container) != null) { // The detail container view will be present only in the large-screen layouts // (res/layout-sw600dp). If this view is present, then the activity should be // in two-pane mode. mTwoPane = true; // In two-pane mode, show the detail view in this activity by // adding or replacing the detail fragment using a // fragment transaction. DetailFragment fragment = new DetailFragment(); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .replace(R.id.weather_detail_container, fragment, DETAIL_FRAGMENT_TAG) .commit(); } } else { mTwoPane = false; ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setElevation(0f); } } ForecastFragment forecastFragment = ((ForecastFragment) getSupportFragmentManager() .findFragmentById(R.id.fragment_forecast)); forecastFragment.setUseTodayLayout(!mTwoPane); if (contentUri != null) { forecastFragment.setInitialSelectedDate( WeatherContract.WeatherEntry.getDateFromUri(contentUri)); } SyncUtils.initialize(this); } @Override protected void onResume() { super.onResume(); String location = WeatherPreferences.getPreferredWeatherLocation(this); // update the location in our second pane using the fragment manager if (location != null && !location.equals(mLocation)) { ForecastFragment ff = (ForecastFragment) getSupportFragmentManager() .findFragmentById(R.id.fragment_forecast); if (null != ff) { ff.onLocationChanged(); } DetailFragment df = (DetailFragment) getSupportFragmentManager().findFragmentByTag(DETAIL_FRAGMENT_TAG); if (null != df) { df.onLocationChanged(location); } mLocation = location; } mLocationName.setText(location); } @Override protected void onStart() { super.onStart(); } @Override public void onStop() { super.onStop(); if (mGoogleApiClient.isConnected()) { removeLocationUpdates(); mGoogleApiClient.disconnect(); } } @SuppressWarnings("unchecked") @Override public void onItemSelected(Uri contentUri, ForecastAdapter.ForecastViewHolder vh) { if (mTwoPane) { // In two-pane mode, show the detail view in this activity by // adding or replacing the detail fragment using a // fragment transaction. Bundle args = new Bundle(); args.putParcelable(DetailFragment.DETAIL_URI, contentUri); DetailFragment fragment = new DetailFragment(); fragment.setArguments(args); getSupportFragmentManager().beginTransaction() .replace(R.id.weather_detail_container, fragment, DETAIL_FRAGMENT_TAG) .commit(); } else { Intent intent = new Intent(this, DetailActivity.class) .setData(contentUri); ActivityOptionsCompat activityOptions = ActivityOptionsCompat.makeSceneTransitionAnimation(this, new Pair<View, String>(vh.mIconView, getString(R.string.detail_icon_transition_name))); ActivityCompat.startActivity(this, intent, activityOptions.toBundle()); } } @SuppressLint("MissingPermission") @Override public void onConnected(@Nullable Bundle bundle) { requestLocationUpdates(); WeatherUtils.resetLocationStatus(this); WeatherPreferences.resetLocationCoordinates(this); SyncUtils.startImmediateSync(this); } @Override public void onConnectionSuspended(int i) { removeLocationUpdates(); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } /** * Sets up the location request. Android has two location request settings: * {@code ACCESS_COARSE_LOCATION} and {@code ACCESS_FINE_LOCATION}. These settings control * the accuracy of the current location. This sample uses ACCESS_FINE_LOCATION, as defined in * the AndroidManifest.xml. * <p/> * When the ACCESS_FINE_LOCATION setting is specified, combined with a fast update * interval (5 seconds), the Fused Location Provider API returns location updates that are * accurate to within a few feet. * <p/> * These settings are appropriate for mapping applications that show real-time location * updates. */ @SuppressLint("RestrictedApi") private void createLocationRequest() { mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(UPDATE_INTERVAL); // Sets the fastest rate for active location updates. This interval is exact, and your // application will never receive updates faster than this value. mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); // Sets the maximum time when batched location updates are delivered. Updates may be // delivered sooner than this interval. mLocationRequest.setMaxWaitTime(MAX_WAIT_TIME); SyncUtils.syncImmediately(this); } /** * Builds {@link GoogleApiClient}, enabling automatic lifecycle management using * {@link GoogleApiClient.Builder#enableAutoManage(android.support.v4.app.FragmentActivity, * int, GoogleApiClient.OnConnectionFailedListener)}. I.e., GoogleApiClient connects in * {@link AppCompatActivity#onStart}, or if onStart() has already happened, it connects * immediately, and disconnects automatically in {@link AppCompatActivity#onStop}. */ private void buildGoogleApiClient() { if (mGoogleApiClient != null) { return; } mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .enableAutoManage(this, this) .addApi(LocationServices.API) .build(); createLocationRequest(); } /** * Return the current state of the permissions needed. */ private boolean checkPermissions() { int permissionState = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION); return permissionState == PackageManager.PERMISSION_GRANTED; } private void requestPermissions() { boolean shouldProvideRationale = ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION); // Provide an additional rationale to the user. This would happen if the user denied the // request previously, but didn't check the "Don't ask again" checkbox. if (shouldProvideRationale) { Snackbar.make( findViewById(R.id.fragment_forecast), R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE) .setAction(R.string.ok, new View.OnClickListener() { @Override public void onClick(View view) { // Request permission ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_PERMISSIONS_REQUEST_CODE); } }) .show(); } else { // Request permission. It's possible this can be auto answered if device policy // sets the permission in a given state or the user denied the permission // previously and checked "Never ask again". ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_PERMISSIONS_REQUEST_CODE); } } /** * Callback received when a permissions request has been completed. */ @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == REQUEST_PERMISSIONS_REQUEST_CODE) { if (grantResults.length <= 0) { // If user interaction was interrupted, the permission request is cancelled and you // receive empty arrays. } else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission was granted. Kick off the process of building and connecting // GoogleApiClient. buildGoogleApiClient(); } else { // Permission denied. // Notify the user via a SnackBar that they have rejected a core permission for the // app, which makes the Activity useless. In a real app, core permissions would // typically be best requested during a welcome-screen flow. // Additionally, it is important to remember that a permission might have been // rejected without asking the user for permission (device policy or "Never ask // again" prompts). Therefore, a user interface affordance is typically implemented // when permissions are denied. Otherwise, your app could appear unresponsive to // touches or interactions which have required permissions. Snackbar.make( findViewById(R.id.fragment_forecast), R.string.permission_denied_explanation, Snackbar.LENGTH_INDEFINITE) .setAction(R.string.settings, new View.OnClickListener() { @Override public void onClick(View view) { // Build intent that displays the App settings screen. Intent intent = new Intent(); intent.setAction( Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts("package", BuildConfig.APPLICATION_ID, null); intent.setData(uri); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } }) .show(); } } } private PendingIntent getPendingIntent() { Intent intent = new Intent(this, LocationUpdatesBroadcastReceiver.class); intent.setAction(LocationUpdatesBroadcastReceiver.ACTION_PROCESS_UPDATES); return PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } /** * Handles the Request Updates button and requests start of location updates. */ public void requestLocationUpdates() { try { LocationServices.getFusedLocationProviderClient(this).requestLocationUpdates(mLocationRequest, getPendingIntent()); mGoogleApiClient.connect(); } catch (SecurityException e) { LocationRequestHelper.setRequesting(this, false); } } /** * Handles the Remove Updates button, and requests removal of location updates. */ public void removeLocationUpdates() { LocationRequestHelper.setRequesting(this, false); LocationServices.getFusedLocationProviderClient(this).removeLocationUpdates( getPendingIntent()); mGoogleApiClient.disconnect(); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(getString(R.string.pref_location_key))){ SyncUtils.startImmediateSync(this); } } }
15,332
0.635664
0.634033
368
40.663044
30.489494
127
false
false
0
0
0
0
0
0
0.48913
false
false
13
4945f35b3771176db3fbb5840b2899f9e2ab03cf
13,795,434,998,356
e7ad53a7dcf6bad745b858f2c94a92ae7cede4b4
/android/contentproviders/m.java
7ce111e31a8bed4f491a75e70be6900b6b10d89a
[ "Apache-2.0" ]
permissive
mhBahrami/testets-v2
https://github.com/mhBahrami/testets-v2
21d973050eb8dc4ac8bd757743bf72647ab1975d
f21427871688fdaec69795ad226a1378c1b33585
refs/heads/master
2016-09-15T20:24:51.262000
2015-03-05T12:08:11
2015-03-05T12:08:11
31,711,805
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.etsy.android.contentproviders; import com.etsy.android.lib.core.o; import com.etsy.android.lib.models.SearchSuggestion; import com.etsy.android.lib.requests.EtsyRequest; import com.etsy.android.lib.requests.SearchSuggestRequest; class m extends o<Void, SearchSuggestion> { private String b; private m(l paraml, String paramString) { this.b = paramString; } protected EtsyRequest<SearchSuggestion> a(Void... paramVarArgs) { return SearchSuggestRequest.search(this.b); } } /* Location: C:\Users\Mohammad\jarToJava\classes.jar * Qualified Name: com.etsy.android.contentproviders.m * JD-Core Version: 0.7.0.1 */
UTF-8
Java
704
java
m.java
Java
[]
null
[]
package com.etsy.android.contentproviders; import com.etsy.android.lib.core.o; import com.etsy.android.lib.models.SearchSuggestion; import com.etsy.android.lib.requests.EtsyRequest; import com.etsy.android.lib.requests.SearchSuggestRequest; class m extends o<Void, SearchSuggestion> { private String b; private m(l paraml, String paramString) { this.b = paramString; } protected EtsyRequest<SearchSuggestion> a(Void... paramVarArgs) { return SearchSuggestRequest.search(this.b); } } /* Location: C:\Users\Mohammad\jarToJava\classes.jar * Qualified Name: com.etsy.android.contentproviders.m * JD-Core Version: 0.7.0.1 */
704
0.697443
0.691761
32
20.1875
23.01825
65
false
false
0
0
0
0
0
0
0.3125
false
false
13
9fc539b56fafdef735bf1c3e8a3feeed1c757e43
28,836,410,488,438
1585b858acb51f138f983fd749b29cd5eb61b435
/app/src/main/java/com/example/hector/proyectodamdaw/Fragments/InviteUserFragment.java
3ab1b6ac1f8d670ccc78b21bac893c3426e2f1e2
[]
no_license
hectorromeroroda/Proyecto-Dam-Daw-App
https://github.com/hectorromeroroda/Proyecto-Dam-Daw-App
12faf3b18193b4dde0c0e1d39d7079e302b72b4e
1abd4d969e2f4f1ec80b37445698c96858a3a1d4
refs/heads/master
2020-03-06T18:58:43.744000
2018-05-27T15:51:18
2018-05-27T15:51:18
127,018,102
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.hector.proyectodamdaw.Fragments; import android.app.ProgressDialog; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.RadioButton; import android.widget.TextView; import android.widget.Toast; import com.example.hector.proyectodamdaw.Activitys.CommunitiesActivity; import com.example.hector.proyectodamdaw.Activitys.SingleCommunitieActivity; import com.example.hector.proyectodamdaw.DataBase.AppDataSources; import com.example.hector.proyectodamdaw.Otros.GlobalVariables; import com.example.hector.proyectodamdaw.R; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import cz.msebera.android.httpclient.Header; import cz.msebera.android.httpclient.entity.StringEntity; import cz.msebera.android.httpclient.message.BasicHeader; import cz.msebera.android.httpclient.protocol.HTTP; /** * Created by Hector on 25/05/2018. */ public class InviteUserFragment extends Fragment { EditText nombreusuarioinvitado; Button btnInvitarusuario; String nombreUsuarioInvitado; String userToken; String idComunidadActual; String jsUserId; String jsUserInvite; String rolUsuario= "user"; private AppDataSources bd; ProgressDialog Dialog; RadioButton rdbEditor; RadioButton rdbAdmin; RadioButton rdbUser; int idUserSqlite; public InviteUserFragment() { // Required empty public constructor } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.invite_user_fragment, container, false); nombreusuarioinvitado = (EditText)view.findViewById(R.id.edtUserNameInvited); btnInvitarusuario = (Button) view.findViewById(R.id.btnInviteUserComunity); rdbEditor=(RadioButton)view.findViewById(R.id.rdbEditor); rdbAdmin=(RadioButton)view.findViewById(R.id.rdbAdmin); rdbUser=(RadioButton)view.findViewById(R.id.rdbUser); rdbUser.setChecked(true); bd = new AppDataSources(getContext()); Dialog = new ProgressDialog(getContext()); Dialog.setCancelable(false); GlobalVariables globales = GlobalVariables.getInstance().getInstance(); idUserSqlite=globales.getIdUserSqlite(); idComunidadActual=globales.getCommunityId(); return view; } public void onActivityCreated(Bundle state) { super.onActivityCreated(state); btnInvitarusuario.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { nombreUsuarioInvitado=nombreusuarioinvitado.getText().toString(); if ( (nombreUsuarioInvitado == null) || (nombreUsuarioInvitado.equals(""))){ //MENSAJE CAMPO DEVE ESTAR LLENO }else{ if (rdbAdmin.isChecked()==true){ rolUsuario="admin"; }else{ if (rdbEditor.isChecked()==true){ rolUsuario="editor"; } } InviteUser(nombreUsuarioInvitado); } } }); } private void InviteUser(String textoABuscar) { AsyncHttpClient client = new AsyncHttpClient(); client.setMaxRetriesAndTimeout(0, 10000); String Url = "http://192.168.43.219:3000/profile/" + textoABuscar; Cursor cursorUserToken = bd.searchUserToken(idUserSqlite); if (cursorUserToken.moveToFirst() != false){ userToken = cursorUserToken.getString(0); } client.addHeader("Authorization", "Bearer " + userToken); client.get(getContext(), Url, new AsyncHttpResponseHandler() { @Override public void onStart() { // called before request is started Dialog.setMessage("Cargando datos..."); Dialog.show(); } @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { String strResponse = new String(responseBody); JSONArray jsResponse = new JSONArray(); try { jsResponse= new JSONArray(strResponse); for (int index = 0; index < jsResponse.length(); index++) { JSONObject jsobjUsuario = jsResponse.getJSONObject(index); jsUserId = jsobjUsuario.getString("_id"); } } catch (JSONException e) { e.printStackTrace(); } if ( (jsUserId == null) || (jsUserId.equals(""))){ Toast toastAlerta = Toast.makeText(getContext(), "No existe ningun usuario con ese nombre", Toast.LENGTH_LONG); toastAlerta.show(); }else{ jsUserInvite=createJsonUserInvite(jsUserId,rolUsuario); try { inviteUserPost(jsUserInvite); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } Dialog.dismiss(); } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { // called when response HTTP status is "4XX" (eg. 401, 403, 404) String mensajeError = new String(error.getMessage().toString()); String mensaje = "No se ha podido enviar los datos al servidor. " + mensajeError; Toast toastAlerta = Toast.makeText(getContext(), mensaje, Toast.LENGTH_LONG); toastAlerta.show(); Dialog.dismiss(); } @Override public void onRetry(int retryNo) { // called when request is retried } }); } private String createJsonUserInvite(String idUsuario, String role) { String strJsonLogin; strJsonLogin= ("{\"invited\": \"" + idUsuario + "\", \"role\": \"" + role +"\"}"); return strJsonLogin; } private void inviteUserPost(String datos) throws UnsupportedEncodingException { AsyncHttpClient client = new AsyncHttpClient(); client.setMaxRetriesAndTimeout(0, 10000); StringEntity entity = new StringEntity(datos); entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); String Url = "http://192.168.43.219:3000/community/" + idComunidadActual + "/invite"; final Cursor cursorUserToken = bd.searchUserToken(idUserSqlite); if (cursorUserToken.moveToFirst() != false){ userToken = cursorUserToken.getString(0); } client.addHeader("Authorization", "Bearer " + userToken); client.post(getContext(), Url, entity , "application/json",new AsyncHttpResponseHandler() { @Override public void onStart() { // called before request is started Dialog.setMessage("Verificando datos..."); Dialog.show(); } @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { //Envia a SingleCommunityActivity al invitar al usuario Intent intent = new Intent(getContext(), SingleCommunitieActivity.class ); startActivity(intent); Dialog.dismiss(); } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { // called when response HTTP status is "4XX" (eg. 401, 403, 404) String mensajeError = new String(error.getMessage().toString()); String badResponse = "No se ha podido recuperar los datos desde el servidor. " + mensajeError; Toast toastAlerta = Toast.makeText(getContext(), badResponse, Toast.LENGTH_LONG); toastAlerta.show(); Dialog.dismiss(); } @Override public void onRetry(int retryNo) { // called when request is retried } }); } }
UTF-8
Java
8,852
java
InviteUserFragment.java
Java
[ { "context": "droid.httpclient.protocol.HTTP;\n\n/**\n * Created by Hector on 25/05/2018.\n */\n\npublic class InviteUserFragme", "end": 1315, "score": 0.9145567417144775, "start": 1309, "tag": "NAME", "value": "Hector" }, { "context": "dTimeout(0, 10000);\n\n String Url = \"http://192.168.43.219:3000/profile/\" + textoABuscar;\n\n Cursor cu", "end": 3930, "score": 0.9994248151779175, "start": 3916, "tag": "IP_ADDRESS", "value": "192.168.43.219" }, { "context": "pplication/json\"));\n\n String Url = \"http://192.168.43.219:3000/community/\" + idComunidadActual + \"/invite\"", "end": 7117, "score": 0.8685742616653442, "start": 7104, "tag": "IP_ADDRESS", "value": "192.168.43.21" } ]
null
[]
package com.example.hector.proyectodamdaw.Fragments; import android.app.ProgressDialog; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.RadioButton; import android.widget.TextView; import android.widget.Toast; import com.example.hector.proyectodamdaw.Activitys.CommunitiesActivity; import com.example.hector.proyectodamdaw.Activitys.SingleCommunitieActivity; import com.example.hector.proyectodamdaw.DataBase.AppDataSources; import com.example.hector.proyectodamdaw.Otros.GlobalVariables; import com.example.hector.proyectodamdaw.R; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import cz.msebera.android.httpclient.Header; import cz.msebera.android.httpclient.entity.StringEntity; import cz.msebera.android.httpclient.message.BasicHeader; import cz.msebera.android.httpclient.protocol.HTTP; /** * Created by Hector on 25/05/2018. */ public class InviteUserFragment extends Fragment { EditText nombreusuarioinvitado; Button btnInvitarusuario; String nombreUsuarioInvitado; String userToken; String idComunidadActual; String jsUserId; String jsUserInvite; String rolUsuario= "user"; private AppDataSources bd; ProgressDialog Dialog; RadioButton rdbEditor; RadioButton rdbAdmin; RadioButton rdbUser; int idUserSqlite; public InviteUserFragment() { // Required empty public constructor } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.invite_user_fragment, container, false); nombreusuarioinvitado = (EditText)view.findViewById(R.id.edtUserNameInvited); btnInvitarusuario = (Button) view.findViewById(R.id.btnInviteUserComunity); rdbEditor=(RadioButton)view.findViewById(R.id.rdbEditor); rdbAdmin=(RadioButton)view.findViewById(R.id.rdbAdmin); rdbUser=(RadioButton)view.findViewById(R.id.rdbUser); rdbUser.setChecked(true); bd = new AppDataSources(getContext()); Dialog = new ProgressDialog(getContext()); Dialog.setCancelable(false); GlobalVariables globales = GlobalVariables.getInstance().getInstance(); idUserSqlite=globales.getIdUserSqlite(); idComunidadActual=globales.getCommunityId(); return view; } public void onActivityCreated(Bundle state) { super.onActivityCreated(state); btnInvitarusuario.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { nombreUsuarioInvitado=nombreusuarioinvitado.getText().toString(); if ( (nombreUsuarioInvitado == null) || (nombreUsuarioInvitado.equals(""))){ //MENSAJE CAMPO DEVE ESTAR LLENO }else{ if (rdbAdmin.isChecked()==true){ rolUsuario="admin"; }else{ if (rdbEditor.isChecked()==true){ rolUsuario="editor"; } } InviteUser(nombreUsuarioInvitado); } } }); } private void InviteUser(String textoABuscar) { AsyncHttpClient client = new AsyncHttpClient(); client.setMaxRetriesAndTimeout(0, 10000); String Url = "http://192.168.43.219:3000/profile/" + textoABuscar; Cursor cursorUserToken = bd.searchUserToken(idUserSqlite); if (cursorUserToken.moveToFirst() != false){ userToken = cursorUserToken.getString(0); } client.addHeader("Authorization", "Bearer " + userToken); client.get(getContext(), Url, new AsyncHttpResponseHandler() { @Override public void onStart() { // called before request is started Dialog.setMessage("Cargando datos..."); Dialog.show(); } @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { String strResponse = new String(responseBody); JSONArray jsResponse = new JSONArray(); try { jsResponse= new JSONArray(strResponse); for (int index = 0; index < jsResponse.length(); index++) { JSONObject jsobjUsuario = jsResponse.getJSONObject(index); jsUserId = jsobjUsuario.getString("_id"); } } catch (JSONException e) { e.printStackTrace(); } if ( (jsUserId == null) || (jsUserId.equals(""))){ Toast toastAlerta = Toast.makeText(getContext(), "No existe ningun usuario con ese nombre", Toast.LENGTH_LONG); toastAlerta.show(); }else{ jsUserInvite=createJsonUserInvite(jsUserId,rolUsuario); try { inviteUserPost(jsUserInvite); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } Dialog.dismiss(); } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { // called when response HTTP status is "4XX" (eg. 401, 403, 404) String mensajeError = new String(error.getMessage().toString()); String mensaje = "No se ha podido enviar los datos al servidor. " + mensajeError; Toast toastAlerta = Toast.makeText(getContext(), mensaje, Toast.LENGTH_LONG); toastAlerta.show(); Dialog.dismiss(); } @Override public void onRetry(int retryNo) { // called when request is retried } }); } private String createJsonUserInvite(String idUsuario, String role) { String strJsonLogin; strJsonLogin= ("{\"invited\": \"" + idUsuario + "\", \"role\": \"" + role +"\"}"); return strJsonLogin; } private void inviteUserPost(String datos) throws UnsupportedEncodingException { AsyncHttpClient client = new AsyncHttpClient(); client.setMaxRetriesAndTimeout(0, 10000); StringEntity entity = new StringEntity(datos); entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); String Url = "http://192.168.43.219:3000/community/" + idComunidadActual + "/invite"; final Cursor cursorUserToken = bd.searchUserToken(idUserSqlite); if (cursorUserToken.moveToFirst() != false){ userToken = cursorUserToken.getString(0); } client.addHeader("Authorization", "Bearer " + userToken); client.post(getContext(), Url, entity , "application/json",new AsyncHttpResponseHandler() { @Override public void onStart() { // called before request is started Dialog.setMessage("Verificando datos..."); Dialog.show(); } @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { //Envia a SingleCommunityActivity al invitar al usuario Intent intent = new Intent(getContext(), SingleCommunitieActivity.class ); startActivity(intent); Dialog.dismiss(); } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { // called when response HTTP status is "4XX" (eg. 401, 403, 404) String mensajeError = new String(error.getMessage().toString()); String badResponse = "No se ha podido recuperar los datos desde el servidor. " + mensajeError; Toast toastAlerta = Toast.makeText(getContext(), badResponse, Toast.LENGTH_LONG); toastAlerta.show(); Dialog.dismiss(); } @Override public void onRetry(int retryNo) { // called when request is retried } }); } }
8,852
0.614211
0.605739
249
34.550201
29.513023
131
false
false
0
0
0
0
0
0
0.630522
false
false
13
94bd01b0406ca3be10dbc4cf623f57a0db504f3d
24,885,040,547,408
9483f1116c76790de4f568d292825d04b8b2e1a7
/src/main/java/co/zero/health/model/Event.java
484a4b095399084065de8efbf618be9dc6017c1e
[]
no_license
htenjo/health-core
https://github.com/htenjo/health-core
5201c527ceeda7c52f5cc76fc956af8dd12d631d
9ecd2a6b6700b7ef0a84da90cc8f75eace7d7a43
refs/heads/master
2021-08-23T00:01:21.882000
2017-12-01T20:18:52
2017-12-01T20:18:52
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package co.zero.health.model; import co.zero.health.common.Constant; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import lombok.Getter; import lombok.Setter; import lombok.ToString; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import java.time.LocalDate; import java.util.List; /** * Created by hernan on 6/30/17. */ @Getter @Setter @ToString @Entity public class Event extends AbstractEntity { @JsonFormat(pattern = Constant.ENTITY_GENERIC_DATE_PATTERN) @JsonSerialize(using = LocalDateSerializer.class) @JsonDeserialize(using = LocalDateDeserializer.class) private LocalDate createdDate; @ManyToOne private Specialty specialty; @ManyToOne @JsonIgnore private Patient patient; private String name; private String loadedId; }
UTF-8
Java
1,207
java
Event.java
Java
[ { "context": "calDate;\nimport java.util.List;\n\n/**\n * Created by hernan on 6/30/17.\n */\n@Getter\n@Setter\n@ToString\n@E", "end": 731, "score": 0.5146072506904602, "start": 730, "tag": "USERNAME", "value": "h" }, { "context": "lDate;\nimport java.util.List;\n\n/**\n * Created by hernan on 6/30/17.\n */\n@Getter\n@Setter\n@ToString\n@Entity", "end": 736, "score": 0.7568891048431396, "start": 731, "tag": "NAME", "value": "ernan" } ]
null
[]
package co.zero.health.model; import co.zero.health.common.Constant; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import lombok.Getter; import lombok.Setter; import lombok.ToString; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import java.time.LocalDate; import java.util.List; /** * Created by hernan on 6/30/17. */ @Getter @Setter @ToString @Entity public class Event extends AbstractEntity { @JsonFormat(pattern = Constant.ENTITY_GENERIC_DATE_PATTERN) @JsonSerialize(using = LocalDateSerializer.class) @JsonDeserialize(using = LocalDateDeserializer.class) private LocalDate createdDate; @ManyToOne private Specialty specialty; @ManyToOne @JsonIgnore private Patient patient; private String name; private String loadedId; }
1,207
0.80116
0.792046
40
29.174999
20.848127
73
false
false
0
0
0
0
0
0
0.55
false
false
13
a4d96cd38edc281e1d1d973a4979a563b7a828bd
8,229,157,374,191
d59f01e0708e7b6808babde1177b1207a838e7a9
/src/test/java/ch/mobi/ueliloetscher/learning/employeemanagement/control/SkillServiceTest.java
a4bc7b93dc5842bfea4c67ef8a2a292427beab54
[]
no_license
loet/employeemanagement
https://github.com/loet/employeemanagement
99cb494b6abdd77ce1da7bff172a483faf0d4dcf
eb25776a007f181d3fbb04c3b04cebcc66c281ec
refs/heads/master
2023-03-28T14:20:16.812000
2021-03-29T10:17:10
2021-03-29T10:17:10
344,487,959
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ch.mobi.ueliloetscher.learning.employeemanagement.control; import ch.mobi.ueliloetscher.learning.employeemanagement.entity.Skill; import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.Test; import javax.inject.Inject; import javax.transaction.Transactional; import static org.junit.jupiter.api.Assertions.*; @QuarkusTest public class SkillServiceTest { @Inject SkillService skillService; @Test @Transactional public void testAddSkill() { Skill created = skillService.addSkill(new Skill("foo")); assertEquals("foo", created.getSkill()); assertNotNull(created.getId()); } }
UTF-8
Java
651
java
SkillServiceTest.java
Java
[]
null
[]
package ch.mobi.ueliloetscher.learning.employeemanagement.control; import ch.mobi.ueliloetscher.learning.employeemanagement.entity.Skill; import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.Test; import javax.inject.Inject; import javax.transaction.Transactional; import static org.junit.jupiter.api.Assertions.*; @QuarkusTest public class SkillServiceTest { @Inject SkillService skillService; @Test @Transactional public void testAddSkill() { Skill created = skillService.addSkill(new Skill("foo")); assertEquals("foo", created.getSkill()); assertNotNull(created.getId()); } }
651
0.74808
0.74808
25
25.040001
22.424059
70
false
false
0
0
0
0
0
0
0.48
false
false
13
83b4604a1300d2456ff54999da6cccf4debdd370
30,288,109,430,186
d54db0cc9f48bef84daeec395a4653d815007d2e
/SelfCrossing.java
65fd08d385a034c21708bb96bc51d8d0c024f7d8
[]
no_license
isax/Leetcode2
https://github.com/isax/Leetcode2
82ff198179f62b6ce7197ded9d1c884e98d6232f
5629475158c8297239a8626981dee2e0668afba1
refs/heads/master
2021-01-10T10:23:48.438000
2016-04-29T00:27:39
2016-04-29T00:27:39
37,003,555
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Solution { // https://leetcode.com/discuss/88054/java-oms-with-explanation public boolean isSelfCrossing(int[] x) { int len = x.length; if(x.length<=3) return false; for(int i = 3; i<len; i++){ // case 1: i cross i-3 (4th cross first) if(x[i]>=x[i-2] && x[i-1]<=x[i-3]) return true; // case 2: i overlaps i-4 (5th meets first) if(i>=4 && x[i-1]==x[i-3] && x[i] + x[i-4] >= x[i-2]) return true; // case 6: i cross i-5 (6th cross first) if(i>=5 && x[i-1]<=x[i-3] && x[i-2]>x[i-4] && x[i-1] + x[i-5]>=x[i-3] && x[i] + x[i-4]>=x[i-2]) return true; } return false; } }
UTF-8
Java
711
java
SelfCrossing.java
Java
[]
null
[]
public class Solution { // https://leetcode.com/discuss/88054/java-oms-with-explanation public boolean isSelfCrossing(int[] x) { int len = x.length; if(x.length<=3) return false; for(int i = 3; i<len; i++){ // case 1: i cross i-3 (4th cross first) if(x[i]>=x[i-2] && x[i-1]<=x[i-3]) return true; // case 2: i overlaps i-4 (5th meets first) if(i>=4 && x[i-1]==x[i-3] && x[i] + x[i-4] >= x[i-2]) return true; // case 6: i cross i-5 (6th cross first) if(i>=5 && x[i-1]<=x[i-3] && x[i-2]>x[i-4] && x[i-1] + x[i-5]>=x[i-3] && x[i] + x[i-4]>=x[i-2]) return true; } return false; } }
711
0.468354
0.420534
18
38.5
30.374058
120
false
false
0
0
0
0
0
0
0.444444
false
false
13
03d1f570c14ab96f4a4d006c08e3b658a74b978f
37,048,387,921,415
b0f512376fc7cf3daa3b1fca0029d70d21aca2cd
/Array2.java
942241dd80586b4e46b19c19578e2e12c09f6394
[]
no_license
Musheer-Ahamed-R/Work
https://github.com/Musheer-Ahamed-R/Work
25afd7a1d799f91e6fd0e973e9e522d7cd967091
020bac93056ba00794c90068983795fc60d33880
refs/heads/master
2016-09-12T01:28:00.909000
2016-09-07T07:53:46
2016-09-07T07:53:46
65,805,441
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; public class Array2 { public static void main(String[] args) { int[] a = { 2, -3, -4, 5, 9, 7, 8}; Stack<Integer> stack = new Stack<>(); stack.push(a[0]); for(int i=1;i<a.length;i++) { if(stack.peek() < a[i]) { stack.push(a[i]); } } System.out.println(stack); } }
UTF-8
Java
363
java
Array2.java
Java
[]
null
[]
import java.util.*; public class Array2 { public static void main(String[] args) { int[] a = { 2, -3, -4, 5, 9, 7, 8}; Stack<Integer> stack = new Stack<>(); stack.push(a[0]); for(int i=1;i<a.length;i++) { if(stack.peek() < a[i]) { stack.push(a[i]); } } System.out.println(stack); } }
363
0.46832
0.440771
21
16.285715
16.260214
43
false
false
0
0
0
0
0
0
0.666667
false
false
13
43da8fd360aff413d3c67637f85952298c898083
38,044,820,334,695
77be5287c1254b456aa7afe7b2db9710716b88d1
/src/main/java/projektOgloszenia/models/Image.java
d7f5fb32b1d8e4a61cd7edc770effe6b257143c6
[]
no_license
jozinzbazin12/ogloszenia
https://github.com/jozinzbazin12/ogloszenia
cac0ab3669ef07c8e1d4134f5ebb28723f4772fd
6b80bb9e869f191f6cb0706b403d9ccb3319c2e2
refs/heads/master
2021-01-10T09:23:20.549000
2015-06-10T18:17:48
2015-06-10T18:17:48
36,760,084
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package projektOgloszenia.models; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Image implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.TABLE) private Integer id; @Column(columnDefinition="longblob") private byte[] img; private String opis; private String typ; public Image() { } public Image(byte[] img, Ogloszenie ogloszenie, String opis, String typ) { this.img = img; this.opis = opis; this.typ = typ; } public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public byte[] getImg() { return this.img; } public void setImg(byte[] img) { this.img = img; } public String getOpis() { return this.opis; } public void setOpis(String opis) { this.opis = opis; } public String getTyp() { return this.typ; } public void setTyp(String typ) { this.typ = typ; } }
UTF-8
Java
1,174
java
Image.java
Java
[]
null
[]
package projektOgloszenia.models; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Image implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.TABLE) private Integer id; @Column(columnDefinition="longblob") private byte[] img; private String opis; private String typ; public Image() { } public Image(byte[] img, Ogloszenie ogloszenie, String opis, String typ) { this.img = img; this.opis = opis; this.typ = typ; } public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public byte[] getImg() { return this.img; } public void setImg(byte[] img) { this.img = img; } public String getOpis() { return this.opis; } public void setOpis(String opis) { this.opis = opis; } public String getTyp() { return this.typ; } public void setTyp(String typ) { this.typ = typ; } }
1,174
0.67121
0.670358
65
16.061539
16.306561
75
false
false
0
0
0
0
0
0
1.169231
false
false
13
06ee65e048b0a1af2285057aae1f4b6ec19a0f72
37,855,841,767,556
deb43d6cc2cc0991e2c4b1f97aa381ed010004ed
/July 11, 2016 - September 4, 2016/Programming Assignments/Programming Assignment 3/src/Question2.java
e36fb4c760c5ebb581c2ea4157bf4a5d9a72806e
[]
no_license
FedorovIgor/Algorithms-Design-and-Analysis-Part-II-Stanford-Coursera
https://github.com/FedorovIgor/Algorithms-Design-and-Analysis-Part-II-Stanford-Coursera
d9b3f1ac0ad63e7a57865ae99492775841183632
428dca8f8255d05b6e1ac9cd66f5ab030b9cc0a4
refs/heads/master
2016-09-13T19:08:10.860000
2016-08-15T11:07:03
2016-08-15T11:07:03
65,726,165
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/****************************************************************************** * Programming Assignment #3.2 - Week 3, August 2016. * * This problem also asks you to solve a knapsack instance, but a much bigger one. * * Download the text file below. * knapsack_big.txt * * This file describes a knapsack instance, and it has the following format: * * [knapsack_size][number_of_items] * * [value_1] [weight_1] * * [value_2] [weight_2] * * ... * * For example, the third line of the file is "50074 834558", indicating that the * second item has value 50074 and size 834558, respectively. As before, you * should assume that item weights and the knapsack capacity are integers. * * This instance is so big that the straightforward iterative implementation uses * an infeasible amount of time and space. So you will have to be creative to * compute an optimal solution. One idea is to go back to a recursive * implementation, solving subproblems --- and, of course, caching the results to * avoid redundant work --- only on an "as needed" basis. Also, be sure to think * about appropriate data structures for storing and looking up solutions to * subproblems. * * In the box below, type in the value of the optimal solution. * * ADVICE: If you're not getting the correct answer, try debugging your algorithm * using some small test cases. And then post them to the discussion forum! * *****************************************************************************/ import java.io.File; import java.io.FileNotFoundException; import java.util.Arrays; import java.util.Scanner; /** * Course_name: Algorithms Design and Analysis, Part II * Section: Coursera @ Stanford * * @author Fedorov Igor * Date: August 13, 2016 * Programming Assignment #3: Question 2 (Ans: 4243395) */ /** * Course_name: Algorithms Design and Analysis, Part II * Section: Coursera @ Stanford * * Compilation: javac Question2.java * Execution: java -Xmx60G Question2 * (In eclipse, Open the Run Configuration for your application, * Run/Run Configurations..., then look for the applications entry in * 'Java application'. * The arguments tab has a text box Vm arguments, enter -Xmx60G. * * % java -Xmx60G Question2 * * @author Fedorov Igor * Date: August 13, 2016 * Programming Assignment #3: Question 2 (Ans: 4243395) * Execution time: ~2min. * Environment: AMD Phenom(tm) 9950 Quad-Core (2.61GHz), 8GB RAM, Windows 10. */ public class Question2 { static int W, N; static int[][] data; static int[][] A; static int[][] readFromFile(String filename) throws FileNotFoundException { Scanner in = new Scanner(new File(filename)); W = Integer.parseInt(in.next()); N = Integer.parseInt(in.next()); data = new int[N+1][2]; for(int i = 1; in.hasNext() && i <= N; i++) { data[i][0] = Integer.parseInt(in.next()); data[i][1] = Integer.parseInt(in.next()); } in.close(); return data; } static int max(int a, int b) { return (a > b)? a : b; } static int knapSackMem(int w, int n) { if (n == 0) { return A[N][W]; } if (A[n][w] != 0) { return A[n][w]; } int val = 0; if (w - data[n][1] < 0) { val = knapSackMem(w, n - 1); } else { val = max(knapSackMem(w, n - 1), knapSackMem(w - data[n][1], n - 1) + data[n][0]); } A[n][w] = val; return val; } public static void main(String[] args) throws FileNotFoundException { int[][] data = readFromFile("knapsack_big.txt"); /*for(int i = 0; i < data.length; i++) { for(int j = 0; j < 2; j++) { System.out.print(data[i][j] + " "); } System.out.println(); }*/ A = new int[N+1][W+1]; long start, end; start = System.currentTimeMillis(); System.out.println(knapSackMem(W, N)); end = System.currentTimeMillis(); System.out.print("It took " + (end - start) + " milliseconds to find the solution."); } }
UTF-8
Java
4,166
java
Question2.java
Java
[ { "context": " II\n * Section: Coursera @ Stanford\n * \n * @author Fedorov Igor\n * Date: August 13, 2016\n * Programming Assignmen", "end": 1734, "score": 0.9997465014457703, "start": 1722, "tag": "NAME", "value": "Fedorov Igor" }, { "context": "0G.\n * \n * % java -Xmx60G Question2\n * \n * @author Fedorov Igor\n * Date: August 13, 2016\n * Programming Assignmen", "end": 2276, "score": 0.9998415112495422, "start": 2264, "tag": "NAME", "value": "Fedorov Igor" } ]
null
[]
/****************************************************************************** * Programming Assignment #3.2 - Week 3, August 2016. * * This problem also asks you to solve a knapsack instance, but a much bigger one. * * Download the text file below. * knapsack_big.txt * * This file describes a knapsack instance, and it has the following format: * * [knapsack_size][number_of_items] * * [value_1] [weight_1] * * [value_2] [weight_2] * * ... * * For example, the third line of the file is "50074 834558", indicating that the * second item has value 50074 and size 834558, respectively. As before, you * should assume that item weights and the knapsack capacity are integers. * * This instance is so big that the straightforward iterative implementation uses * an infeasible amount of time and space. So you will have to be creative to * compute an optimal solution. One idea is to go back to a recursive * implementation, solving subproblems --- and, of course, caching the results to * avoid redundant work --- only on an "as needed" basis. Also, be sure to think * about appropriate data structures for storing and looking up solutions to * subproblems. * * In the box below, type in the value of the optimal solution. * * ADVICE: If you're not getting the correct answer, try debugging your algorithm * using some small test cases. And then post them to the discussion forum! * *****************************************************************************/ import java.io.File; import java.io.FileNotFoundException; import java.util.Arrays; import java.util.Scanner; /** * Course_name: Algorithms Design and Analysis, Part II * Section: Coursera @ Stanford * * @author <NAME> * Date: August 13, 2016 * Programming Assignment #3: Question 2 (Ans: 4243395) */ /** * Course_name: Algorithms Design and Analysis, Part II * Section: Coursera @ Stanford * * Compilation: javac Question2.java * Execution: java -Xmx60G Question2 * (In eclipse, Open the Run Configuration for your application, * Run/Run Configurations..., then look for the applications entry in * 'Java application'. * The arguments tab has a text box Vm arguments, enter -Xmx60G. * * % java -Xmx60G Question2 * * @author <NAME> * Date: August 13, 2016 * Programming Assignment #3: Question 2 (Ans: 4243395) * Execution time: ~2min. * Environment: AMD Phenom(tm) 9950 Quad-Core (2.61GHz), 8GB RAM, Windows 10. */ public class Question2 { static int W, N; static int[][] data; static int[][] A; static int[][] readFromFile(String filename) throws FileNotFoundException { Scanner in = new Scanner(new File(filename)); W = Integer.parseInt(in.next()); N = Integer.parseInt(in.next()); data = new int[N+1][2]; for(int i = 1; in.hasNext() && i <= N; i++) { data[i][0] = Integer.parseInt(in.next()); data[i][1] = Integer.parseInt(in.next()); } in.close(); return data; } static int max(int a, int b) { return (a > b)? a : b; } static int knapSackMem(int w, int n) { if (n == 0) { return A[N][W]; } if (A[n][w] != 0) { return A[n][w]; } int val = 0; if (w - data[n][1] < 0) { val = knapSackMem(w, n - 1); } else { val = max(knapSackMem(w, n - 1), knapSackMem(w - data[n][1], n - 1) + data[n][0]); } A[n][w] = val; return val; } public static void main(String[] args) throws FileNotFoundException { int[][] data = readFromFile("knapsack_big.txt"); /*for(int i = 0; i < data.length; i++) { for(int j = 0; j < 2; j++) { System.out.print(data[i][j] + " "); } System.out.println(); }*/ A = new int[N+1][W+1]; long start, end; start = System.currentTimeMillis(); System.out.println(knapSackMem(W, N)); end = System.currentTimeMillis(); System.out.print("It took " + (end - start) + " milliseconds to find the solution."); } }
4,154
0.590014
0.56505
125
32.327999
26.883087
82
false
false
0
0
0
0
0
0
0.56
false
false
13
a13507f3288d49198077d20484ce335befae6773
37,495,064,525,109
647eef4da03aaaac9872c8b210e4fc24485e49dc
/TestMemory/wandoujia/src/main/java/com/wandoujia/p4/netcheck/fragment/d.java
319a4a4ca236f925e502d93359bb0f636927db27
[]
no_license
AlbertSnow/git_workspace
https://github.com/AlbertSnow/git_workspace
f2d3c68a7b6e62f41c1edcd7744f110e2bf7f021
a0b2cd83cfa6576182f440a44d957a9b9a6bda2e
refs/heads/master
2021-01-22T17:57:16.169000
2016-12-05T15:59:46
2016-12-05T15:59:46
28,154,580
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wandoujia.p4.netcheck.fragment; import android.os.AsyncTask; import android.widget.ProgressBar; import android.widget.TextView; final class d extends AsyncTask<String, Void, Boolean> { private d(NetCheckCheckingFragment paramNetCheckCheckingFragment) { } protected final void onPreExecute() { if (this.a.getActivity() != null) { NetCheckCheckingFragment.c(this.a).setProgress(0); NetCheckCheckingFragment.d(this.a).setText(this.a.getString(2131625165)); } } } /* Location: C:\WorkSpace\WandDouJiaNotificationBar\WanDou1.jar * Qualified Name: com.wandoujia.p4.netcheck.fragment.d * JD-Core Version: 0.6.0 */
UTF-8
Java
678
java
d.java
Java
[]
null
[]
package com.wandoujia.p4.netcheck.fragment; import android.os.AsyncTask; import android.widget.ProgressBar; import android.widget.TextView; final class d extends AsyncTask<String, Void, Boolean> { private d(NetCheckCheckingFragment paramNetCheckCheckingFragment) { } protected final void onPreExecute() { if (this.a.getActivity() != null) { NetCheckCheckingFragment.c(this.a).setProgress(0); NetCheckCheckingFragment.d(this.a).setText(this.a.getString(2131625165)); } } } /* Location: C:\WorkSpace\WandDouJiaNotificationBar\WanDou1.jar * Qualified Name: com.wandoujia.p4.netcheck.fragment.d * JD-Core Version: 0.6.0 */
678
0.724189
0.699115
26
25.115385
25.988647
79
false
false
0
0
0
0
0
0
0.307692
false
false
13
53ef2aec5e7ab65a2b2ba9e0c6addcc0f6630540
18,339,510,392,410
4a53dc4705339f29aae551c780f81cc8d79a13e9
/PaymentSystem/src/main/java/me/admin/PayingSystemController.java
f1c36d906a9d7b3c4d5e5bbb75c8116e6bf4826d
[]
no_license
qwake1378/Solanteq-practice
https://github.com/qwake1378/Solanteq-practice
19d2e21d568b8290c0ca9d36873b36a9fc49a725
537ba917d61b4da8a68760fdeb952dcc27d6825f
refs/heads/master
2021-01-13T23:36:09.400000
2020-05-13T19:21:22
2020-05-13T19:21:22
244,348,040
0
3
null
false
2020-10-13T20:21:50
2020-03-02T10:56:11
2020-05-13T19:22:35
2020-10-13T20:21:48
176
0
1
1
Java
false
false
package me.admin; import org.json.JSONObject; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; //TODO: Add tests @Controller public class PayingSystemController { private final int binLength = 6; private final IssuerBankRepository issuerBankRepository; public PayingSystemController(IssuerBankRepository issuerBankRepository) { this.issuerBankRepository = issuerBankRepository; } @PostMapping("/redirect") public ResponseEntity<?> redirectTransactionToIssuer(@RequestBody Map<String, String> body) { String cardNum = body.get("num"); String bin = Utils.getBinFromCardNum(cardNum); IssuerBank issuerBank = issuerBankRepository.findByBin(bin); if (issuerBank != null) { try { return sendTransactionToIssuerBan(issuerBank.getUrlString(), new JSONObject(body)); } catch (IOException e) { return new ResponseEntity<>(e.getMessage(), HttpStatus.FORBIDDEN); } } return new ResponseEntity<>("Unknown Bin", HttpStatus.BAD_REQUEST); } //TODO: Add status output in html @PostMapping("/add") public ResponseEntity<String> addIssuerBank(@RequestBody Map<String, String> body) { HttpHeaders headers = new HttpHeaders(); headers.add("response:", "edit-result"); String newBin = body.get("newBin"); String newUrl = body.get("newUrl"); if (newBin == null || newUrl == null) { return new ResponseEntity<>("Incorrect json", headers, HttpStatus.OK); } if (newBin.length() != binLength) { return new ResponseEntity<>("Incorrect data", headers, HttpStatus.BAD_REQUEST); } try { Integer.parseInt(newBin); } catch (NumberFormatException e) { return new ResponseEntity<>("Incorrect data", headers, HttpStatus.BAD_REQUEST); } if (issuerBankRepository.findByBin(newBin) != null) { return new ResponseEntity<>("Bin already exists", headers, HttpStatus.BAD_REQUEST); } IssuerBank newBank = new IssuerBank(newBin, newUrl); issuerBankRepository.save(newBank); return new ResponseEntity<>("Done", headers, HttpStatus.OK); } //TODO: Add status output in html @PostMapping("/edit") public ResponseEntity<String> editIssuerBank(@RequestBody Map<String, String> body) { HttpHeaders headers = new HttpHeaders(); headers.add("response:", "edit-result"); String deleteBin = body.get("delBin"); String newBin = body.get("newBin"); String newUrl = body.get("newUrl"); if (deleteBin == null || newBin == null || newUrl == null) { return new ResponseEntity<>("Incorrect json", headers, HttpStatus.OK); } if (deleteBin.length() != binLength || newBin.length() != binLength) { return new ResponseEntity<>("Incorrect data", headers, HttpStatus.BAD_REQUEST); } try { if (Integer.parseInt(deleteBin) < 0 || Integer.parseInt(newBin) < 0) { return new ResponseEntity<>("Incorrect data", headers, HttpStatus.BAD_REQUEST); } } catch (NumberFormatException e) { return new ResponseEntity<>("Incorrect data", headers, HttpStatus.BAD_REQUEST); } IssuerBank bankToDelete; try { bankToDelete = issuerBankRepository.findByBin(deleteBin); } catch (Exception e) { e.printStackTrace(); return new ResponseEntity<>("Incorrect database state", headers, HttpStatus.NOT_FOUND); } if (bankToDelete == null) { return new ResponseEntity<>("Not found", headers, HttpStatus.NOT_FOUND); } try { issuerBankRepository.delete(bankToDelete); if (issuerBankRepository.findByBin(newBin) != null) { issuerBankRepository.save(bankToDelete); return new ResponseEntity<>("Bin already exists", headers, HttpStatus.BAD_REQUEST); } issuerBankRepository.save(new IssuerBank(newBin, newUrl)); } catch (Exception e) { return new ResponseEntity<>("Error", headers, HttpStatus.NOT_FOUND); } return new ResponseEntity<>("Done", headers, HttpStatus.OK); } private List<String> getAllBanksToString() { return getAllBanks() .stream() .map(IssuerBank::toCompactString) .collect(Collectors.toCollection(ArrayList::new)); } public List<IssuerBank> getAllBanks() { return issuerBankRepository.findAll(); } //TODO: Beatify with css @GetMapping("/add") public String openDBAddPage(Model model) { model.addAttribute("bank", new IssuerBank()); return "add"; } //TODO: Beatify with css //TODO: Fix incorrect behaving @GetMapping("/edit") public String openDBEditPage(Model model) { List<IssuerBank> allBanks = issuerBankRepository.findAll(); model.addAttribute("allBanks", allBanks); model.addAttribute("bankToDel", new IssuerBank()); model.addAttribute("bankToAdd", new IssuerBank()); return "edit"; } @PostMapping("/rem") public void deleteAll() { for (IssuerBank ib : issuerBankRepository.findAll()) { issuerBankRepository.delete(ib); } } private ResponseEntity<?> sendTransactionToIssuerBan(String urlString, JSONObject body) throws IOException { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json; utf-8"); connection.setRequestProperty("Accept", "application/json"); connection.setDoOutput(true); try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) { wr.write(body.toString().getBytes(StandardCharsets.UTF_8)); wr.flush(); } StringBuilder response = new StringBuilder(); try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) { String responseLine; while ((responseLine = br.readLine()) != null) { response.append(responseLine.trim()); } } return ResponseEntity.status(HttpStatus.OK).body(response.toString()); } }
UTF-8
Java
7,112
java
PayingSystemController.java
Java
[]
null
[]
package me.admin; import org.json.JSONObject; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; //TODO: Add tests @Controller public class PayingSystemController { private final int binLength = 6; private final IssuerBankRepository issuerBankRepository; public PayingSystemController(IssuerBankRepository issuerBankRepository) { this.issuerBankRepository = issuerBankRepository; } @PostMapping("/redirect") public ResponseEntity<?> redirectTransactionToIssuer(@RequestBody Map<String, String> body) { String cardNum = body.get("num"); String bin = Utils.getBinFromCardNum(cardNum); IssuerBank issuerBank = issuerBankRepository.findByBin(bin); if (issuerBank != null) { try { return sendTransactionToIssuerBan(issuerBank.getUrlString(), new JSONObject(body)); } catch (IOException e) { return new ResponseEntity<>(e.getMessage(), HttpStatus.FORBIDDEN); } } return new ResponseEntity<>("Unknown Bin", HttpStatus.BAD_REQUEST); } //TODO: Add status output in html @PostMapping("/add") public ResponseEntity<String> addIssuerBank(@RequestBody Map<String, String> body) { HttpHeaders headers = new HttpHeaders(); headers.add("response:", "edit-result"); String newBin = body.get("newBin"); String newUrl = body.get("newUrl"); if (newBin == null || newUrl == null) { return new ResponseEntity<>("Incorrect json", headers, HttpStatus.OK); } if (newBin.length() != binLength) { return new ResponseEntity<>("Incorrect data", headers, HttpStatus.BAD_REQUEST); } try { Integer.parseInt(newBin); } catch (NumberFormatException e) { return new ResponseEntity<>("Incorrect data", headers, HttpStatus.BAD_REQUEST); } if (issuerBankRepository.findByBin(newBin) != null) { return new ResponseEntity<>("Bin already exists", headers, HttpStatus.BAD_REQUEST); } IssuerBank newBank = new IssuerBank(newBin, newUrl); issuerBankRepository.save(newBank); return new ResponseEntity<>("Done", headers, HttpStatus.OK); } //TODO: Add status output in html @PostMapping("/edit") public ResponseEntity<String> editIssuerBank(@RequestBody Map<String, String> body) { HttpHeaders headers = new HttpHeaders(); headers.add("response:", "edit-result"); String deleteBin = body.get("delBin"); String newBin = body.get("newBin"); String newUrl = body.get("newUrl"); if (deleteBin == null || newBin == null || newUrl == null) { return new ResponseEntity<>("Incorrect json", headers, HttpStatus.OK); } if (deleteBin.length() != binLength || newBin.length() != binLength) { return new ResponseEntity<>("Incorrect data", headers, HttpStatus.BAD_REQUEST); } try { if (Integer.parseInt(deleteBin) < 0 || Integer.parseInt(newBin) < 0) { return new ResponseEntity<>("Incorrect data", headers, HttpStatus.BAD_REQUEST); } } catch (NumberFormatException e) { return new ResponseEntity<>("Incorrect data", headers, HttpStatus.BAD_REQUEST); } IssuerBank bankToDelete; try { bankToDelete = issuerBankRepository.findByBin(deleteBin); } catch (Exception e) { e.printStackTrace(); return new ResponseEntity<>("Incorrect database state", headers, HttpStatus.NOT_FOUND); } if (bankToDelete == null) { return new ResponseEntity<>("Not found", headers, HttpStatus.NOT_FOUND); } try { issuerBankRepository.delete(bankToDelete); if (issuerBankRepository.findByBin(newBin) != null) { issuerBankRepository.save(bankToDelete); return new ResponseEntity<>("Bin already exists", headers, HttpStatus.BAD_REQUEST); } issuerBankRepository.save(new IssuerBank(newBin, newUrl)); } catch (Exception e) { return new ResponseEntity<>("Error", headers, HttpStatus.NOT_FOUND); } return new ResponseEntity<>("Done", headers, HttpStatus.OK); } private List<String> getAllBanksToString() { return getAllBanks() .stream() .map(IssuerBank::toCompactString) .collect(Collectors.toCollection(ArrayList::new)); } public List<IssuerBank> getAllBanks() { return issuerBankRepository.findAll(); } //TODO: Beatify with css @GetMapping("/add") public String openDBAddPage(Model model) { model.addAttribute("bank", new IssuerBank()); return "add"; } //TODO: Beatify with css //TODO: Fix incorrect behaving @GetMapping("/edit") public String openDBEditPage(Model model) { List<IssuerBank> allBanks = issuerBankRepository.findAll(); model.addAttribute("allBanks", allBanks); model.addAttribute("bankToDel", new IssuerBank()); model.addAttribute("bankToAdd", new IssuerBank()); return "edit"; } @PostMapping("/rem") public void deleteAll() { for (IssuerBank ib : issuerBankRepository.findAll()) { issuerBankRepository.delete(ib); } } private ResponseEntity<?> sendTransactionToIssuerBan(String urlString, JSONObject body) throws IOException { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json; utf-8"); connection.setRequestProperty("Accept", "application/json"); connection.setDoOutput(true); try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) { wr.write(body.toString().getBytes(StandardCharsets.UTF_8)); wr.flush(); } StringBuilder response = new StringBuilder(); try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) { String responseLine; while ((responseLine = br.readLine()) != null) { response.append(responseLine.trim()); } } return ResponseEntity.status(HttpStatus.OK).body(response.toString()); } }
7,112
0.644123
0.643279
194
35.659794
29.947338
130
false
false
0
0
0
0
0
0
0.716495
false
false
13
755d452708eb648c9a4a68911f9d81c3a65451b9
18,279,380,877,005
8640591f5521a9f4f0757c590ddc1ccfb346763e
/app/src/main/java/com/example/zhexuanliu/androidnsdservicedemo/connection/NSDUDPServer.java
ce083a820839a338fefa16adf1c4c8b9cb05c8e1
[]
no_license
oozliuoo/AndroidNSDDemo
https://github.com/oozliuoo/AndroidNSDDemo
c4be6fed43d8f267a3fefde6e6b570a669318ba7
986a13d6da05cfb9207d288d19e05306237b3341
refs/heads/master
2021-09-01T18:49:13.261000
2017-12-28T09:32:12
2017-12-28T09:32:12
115,440,534
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.zhexuanliu.androidnsdservicedemo.connection; import android.os.Handler; import android.util.Log; import com.example.zhexuanliu.androidnsdservicedemo.commons.Constants; import com.example.zhexuanliu.androidnsdservicedemo.utils.Utils; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import static android.content.ContentValues.TAG; /** * Created by zhexuanliu on 12/28/17. */ public class NSDUDPServer { /** * Datagram socket of the UDP server */ private DatagramSocket mDatagramSocket = null; /** * Main thread of the UDP server */ private Thread mThread = null; /** * Stores port information of the datagram socket */ private int mPort = -1; /** * The main thread handler to interact with main thread */ private Handler mMainThreadHandler; /** * Store the client's address */ private InetAddress mClientAddress; /** * Stores port of the client */ private int mClientPort; /** * Track the instance context */ private NSDUDPServer mNSDUDPServerContext; /** * Name of service this udp server serves */ private String mServiceName; /** * Constructor */ public NSDUDPServer(String serviceName, Handler mainThreadHandler){ this.mNSDUDPServerContext = this; this.mMainThreadHandler = mainThreadHandler; this.mServiceName = serviceName; this.mThread = new Thread( new UdpServerThread()); this.mThread.start(); } /** * Quit the server */ public void tearDown() { mThread.interrupt(); mDatagramSocket.close(); } class UdpServerThread implements Runnable{ @Override public void run() { try { // grab an available prot and advertise it via Nsd. mDatagramSocket = new DatagramSocket(); mPort = mDatagramSocket.getLocalPort(); mMainThreadHandler.obtainMessage(Constants.MSG_SERVER_CREATED, mNSDUDPServerContext).sendToTarget(); while (!Thread.currentThread().isInterrupted()) { // TODO: need proper size and handling here byte[] buf = new byte[Constants.DATA_BUFFER_SIZE]; DatagramPacket dp = new DatagramPacket( buf, buf.length); // listen to the port and wait for message mDatagramSocket.receive(dp); mClientAddress = dp.getAddress(); mClientPort = dp.getPort(); mMainThreadHandler.obtainMessage(Constants.MSG_CLIENT_RECEIVE, "Message from service `" + mServiceName + "`: " + Utils.convertBytesToString(dp.getData())).sendToTarget(); } } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } /** * Sends data over the socket * @param data - data to be sent */ public void sendData(byte[] data){ try { if (mDatagramSocket == null){ Log.d(Constants.LOG_TAG, "datagram socket not initialized yet"); return; } if (mDatagramSocket.isClosed()) { Log.d(Constants.LOG_TAG, "datagram socket closed"); return; } DatagramPacket datagramPacket = new DatagramPacket(data, data.length, mClientAddress, mPort); mDatagramSocket.send(datagramPacket); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } /** * Returns the server socket port * @return - server socket port */ public int getLocalPort() { return this.mPort; } /** * Gets the service name * @return - service name */ public String getServiceName() { return this.mServiceName; } }
UTF-8
Java
4,206
java
NSDUDPServer.java
Java
[ { "context": "roid.content.ContentValues.TAG;\n\n/**\n * Created by zhexuanliu on 12/28/17.\n */\n\npublic class NSDUDPServer\n{\n ", "end": 489, "score": 0.9996674656867981, "start": 479, "tag": "USERNAME", "value": "zhexuanliu" } ]
null
[]
package com.example.zhexuanliu.androidnsdservicedemo.connection; import android.os.Handler; import android.util.Log; import com.example.zhexuanliu.androidnsdservicedemo.commons.Constants; import com.example.zhexuanliu.androidnsdservicedemo.utils.Utils; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import static android.content.ContentValues.TAG; /** * Created by zhexuanliu on 12/28/17. */ public class NSDUDPServer { /** * Datagram socket of the UDP server */ private DatagramSocket mDatagramSocket = null; /** * Main thread of the UDP server */ private Thread mThread = null; /** * Stores port information of the datagram socket */ private int mPort = -1; /** * The main thread handler to interact with main thread */ private Handler mMainThreadHandler; /** * Store the client's address */ private InetAddress mClientAddress; /** * Stores port of the client */ private int mClientPort; /** * Track the instance context */ private NSDUDPServer mNSDUDPServerContext; /** * Name of service this udp server serves */ private String mServiceName; /** * Constructor */ public NSDUDPServer(String serviceName, Handler mainThreadHandler){ this.mNSDUDPServerContext = this; this.mMainThreadHandler = mainThreadHandler; this.mServiceName = serviceName; this.mThread = new Thread( new UdpServerThread()); this.mThread.start(); } /** * Quit the server */ public void tearDown() { mThread.interrupt(); mDatagramSocket.close(); } class UdpServerThread implements Runnable{ @Override public void run() { try { // grab an available prot and advertise it via Nsd. mDatagramSocket = new DatagramSocket(); mPort = mDatagramSocket.getLocalPort(); mMainThreadHandler.obtainMessage(Constants.MSG_SERVER_CREATED, mNSDUDPServerContext).sendToTarget(); while (!Thread.currentThread().isInterrupted()) { // TODO: need proper size and handling here byte[] buf = new byte[Constants.DATA_BUFFER_SIZE]; DatagramPacket dp = new DatagramPacket( buf, buf.length); // listen to the port and wait for message mDatagramSocket.receive(dp); mClientAddress = dp.getAddress(); mClientPort = dp.getPort(); mMainThreadHandler.obtainMessage(Constants.MSG_CLIENT_RECEIVE, "Message from service `" + mServiceName + "`: " + Utils.convertBytesToString(dp.getData())).sendToTarget(); } } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } /** * Sends data over the socket * @param data - data to be sent */ public void sendData(byte[] data){ try { if (mDatagramSocket == null){ Log.d(Constants.LOG_TAG, "datagram socket not initialized yet"); return; } if (mDatagramSocket.isClosed()) { Log.d(Constants.LOG_TAG, "datagram socket closed"); return; } DatagramPacket datagramPacket = new DatagramPacket(data, data.length, mClientAddress, mPort); mDatagramSocket.send(datagramPacket); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } /** * Returns the server socket port * @return - server socket port */ public int getLocalPort() { return this.mPort; } /** * Gets the service name * @return - service name */ public String getServiceName() { return this.mServiceName; } }
4,206
0.584641
0.582977
160
25.2875
26.472483
190
false
false
0
0
0
0
0
0
0.35
false
false
13
6d9c3f0a565ff2b93a99b348eb68bd6e14042711
23,244,363,065,045
df4539abf5d521be6fddd25734ccd7d7ac461428
/01-JavaSE/day_28/src/cn/liuawen/exception/MyThread.java
339e5772952c6255c91797cd71e3c19970958a6c
[]
no_license
muzierixao/Learning-Java
https://github.com/muzierixao/Learning-Java
c9bf6d1d020fd5b6e55d99c50172c465ea06fec0
893d9a730d6429626d1df5613fa7f81aca5bdd84
refs/heads/master
2023-04-18T06:48:46.280000
2020-12-27T05:32:02
2020-12-27T05:32:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.liuawen.exception; /** * @author : Liu Awen Email:willowawen@gmail.com * @create : 2020-05-29 */ public class MyThread extends Thread { /** * 重写run方法,完成该线程执行的逻辑 */ @Override public void run() { for (int i = 1; i <= 100; i++) { if (i % 2 == 0) { System.out.println("子线程打印输出偶数:" + i); } } } }
UTF-8
Java
442
java
MyThread.java
Java
[ { "context": "package cn.liuawen.exception;\n\n/**\n * @author : Liu Awen Email:willowawen@gmail.com\n * @create : 2020-05-", "end": 56, "score": 0.9998509287834167, "start": 48, "tag": "NAME", "value": "Liu Awen" }, { "context": "uawen.exception;\n\n/**\n * @author : Liu Awen Email:willowawen@gmail.com\n * @create : 2020-05-29\n */\npublic class MyThrea", "end": 83, "score": 0.9999269843101501, "start": 63, "tag": "EMAIL", "value": "willowawen@gmail.com" } ]
null
[]
package cn.liuawen.exception; /** * @author : <NAME> Email:<EMAIL> * @create : 2020-05-29 */ public class MyThread extends Thread { /** * 重写run方法,完成该线程执行的逻辑 */ @Override public void run() { for (int i = 1; i <= 100; i++) { if (i % 2 == 0) { System.out.println("子线程打印输出偶数:" + i); } } } }
427
0.482143
0.446429
22
16.818182
16.386349
53
false
false
0
0
0
0
0
0
0.181818
false
false
13
5cc7e7bb77f2f50681d93cdb6679134f9658b519
9,225,589,790,447
3ca92846a6b8eaab7a445d9cdbda5f127cd3cf11
/src/test/java/StepsDefinition/HistManutencaoStepsDefinition.java
69a3d6478fe0fcf86f1ad3049d57ac66dc14c4af
[]
no_license
RodrigoSodre17/Convivencia
https://github.com/RodrigoSodre17/Convivencia
e7084715919efef1878b5779de9f95fbea49f234
9cbc1ff446272bb9c9381142c9014e2b4c6603dc
refs/heads/master
2018-10-22T22:35:17.059000
2018-08-28T14:16:36
2018-08-28T14:16:36
144,298,493
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package StepsDefinition; import Compartilhado.BaseDriverStepBusiness; import StepsBusiness.HistManutencaoStepsBusiness; import cucumber.api.java.pt.Quando; public class HistManutencaoStepsDefinition { HistManutencaoStepsBusiness step; @Quando("^clicar na tela Histórico de Manutenção no link (.*)$") public void clicar_na_tela_Historico_de_Manutencao_no_link(String arg) { step = new HistManutencaoStepsBusiness(BaseDriverStepBusiness.getDriver()); step.vLinkListaTopico(arg); } @Quando("^clicar na tela Histórico de Manutenção no Sub-link (.*)$") public void clicar_na_tela_Historico_de_Manutencao_no_sub_link(String arg) { step = new HistManutencaoStepsBusiness(BaseDriverStepBusiness.getDriver()); step.vLinkListaSubTopico(arg); } @Quando("^selecionar na tela Lista de Tópicos o valor (.*)$") public void selecionar_na_tela_Lista_de_Topicos_o_valor(String arg) { step = new HistManutencaoStepsBusiness(BaseDriverStepBusiness.getDriver()); step.vListaTopico(arg); } @Quando("^selecionar na tela Lista de Sub-Tópicos o valor (.*)$") public void selecionar_na_tela_Lista_de_Sub_Topicos_o_valor(String arg) { step = new HistManutencaoStepsBusiness(BaseDriverStepBusiness.getDriver()); step.vListaSubTopico(arg); } @Quando("^clicar na tela Histórico de Manutenção no botao '(.*)'$") public void clicar_na_tela_Historico_de_Manutencao_no_botao(String arg) { step = new HistManutencaoStepsBusiness(BaseDriverStepBusiness.getDriver()); step.vBotao(arg); } }
UTF-8
Java
1,552
java
HistManutencaoStepsDefinition.java
Java
[]
null
[]
package StepsDefinition; import Compartilhado.BaseDriverStepBusiness; import StepsBusiness.HistManutencaoStepsBusiness; import cucumber.api.java.pt.Quando; public class HistManutencaoStepsDefinition { HistManutencaoStepsBusiness step; @Quando("^clicar na tela Histórico de Manutenção no link (.*)$") public void clicar_na_tela_Historico_de_Manutencao_no_link(String arg) { step = new HistManutencaoStepsBusiness(BaseDriverStepBusiness.getDriver()); step.vLinkListaTopico(arg); } @Quando("^clicar na tela Histórico de Manutenção no Sub-link (.*)$") public void clicar_na_tela_Historico_de_Manutencao_no_sub_link(String arg) { step = new HistManutencaoStepsBusiness(BaseDriverStepBusiness.getDriver()); step.vLinkListaSubTopico(arg); } @Quando("^selecionar na tela Lista de Tópicos o valor (.*)$") public void selecionar_na_tela_Lista_de_Topicos_o_valor(String arg) { step = new HistManutencaoStepsBusiness(BaseDriverStepBusiness.getDriver()); step.vListaTopico(arg); } @Quando("^selecionar na tela Lista de Sub-Tópicos o valor (.*)$") public void selecionar_na_tela_Lista_de_Sub_Topicos_o_valor(String arg) { step = new HistManutencaoStepsBusiness(BaseDriverStepBusiness.getDriver()); step.vListaSubTopico(arg); } @Quando("^clicar na tela Histórico de Manutenção no botao '(.*)'$") public void clicar_na_tela_Historico_de_Manutencao_no_botao(String arg) { step = new HistManutencaoStepsBusiness(BaseDriverStepBusiness.getDriver()); step.vBotao(arg); } }
1,552
0.748864
0.748864
40
36.575001
30.800882
77
false
false
0
0
0
0
0
0
1.425
false
false
13
4cf5db5275f2153a3f64d51b4584c3e86675add7
21,492,016,386,713
e7aea08cf17539b39fa313a468d46265934cd86b
/arithmetic/src/main/java/cn/plusman/arithmetic/leetcode/top/top102/Top102Solution.java
ba6cd381d4652864b9e01291fe45c12e37aae086
[ "Apache-2.0" ]
permissive
plusmancn/learn-arithmetic
https://github.com/plusmancn/learn-arithmetic
d37ac84377d509bc36103efb8206ea479a3a95eb
44f02fc6c2454cfae495ab29c193fa88fd10cd83
refs/heads/master
2023-08-07T13:42:44.760000
2021-10-31T15:36:35
2021-10-31T15:36:35
217,059,165
0
1
Apache-2.0
false
2023-07-22T19:35:04
2019-10-23T13:04:35
2021-10-31T15:36:44
2023-07-22T19:35:04
378
0
1
6
Java
false
false
package cn.plusman.arithmetic.leetcode.top.top102; import cn.plusman.arithmetic.leetcode.top.TreeNode; import java.util.List; /** * @author plusman * @since 2021/7/20 9:54 PM */ public interface Top102Solution { List<List<Integer>> levelOrder(TreeNode root); }
UTF-8
Java
271
java
Top102Solution.java
Java
[ { "context": ".TreeNode;\n\nimport java.util.List;\n\n/**\n * @author plusman\n * @since 2021/7/20 9:54 PM\n */\npublic interface ", "end": 151, "score": 0.9995384216308594, "start": 144, "tag": "USERNAME", "value": "plusman" } ]
null
[]
package cn.plusman.arithmetic.leetcode.top.top102; import cn.plusman.arithmetic.leetcode.top.TreeNode; import java.util.List; /** * @author plusman * @since 2021/7/20 9:54 PM */ public interface Top102Solution { List<List<Integer>> levelOrder(TreeNode root); }
271
0.741697
0.682657
13
19.846153
19.856586
51
false
false
0
0
0
0
0
0
0.307692
false
false
13
1f9a54514cdd99e219cded22c15742c561b9835a
26,585,847,574,599
b0ccc6f5e6d38018c36df2b8f536bbd9f45237f2
/src/test/java/recommendator/services/BehaviorServiceTest.java
5764a5e0f955722f5139451dbc118bf3cad48eae
[]
no_license
Elvinasl/recommendation-system
https://github.com/Elvinasl/recommendation-system
9baa3878c714e9ff6044c4f528f8f73a3bf6ada5
013a6a0b0d2f901313d3fd5983bf1152f9daeedc
refs/heads/master
2022-12-23T17:26:50.243000
2020-02-02T15:48:45
2020-02-02T15:48:45
226,535,149
0
0
null
false
2022-12-15T23:30:47
2019-12-07T15:28:38
2020-02-02T15:48:49
2022-12-15T23:30:47
944
0
0
8
Java
false
false
package recommendator.services; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentMatchers; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import recommendator.dto.BehaviorDTO; import recommendator.exceptions.responses.Response; import recommendator.models.entities.Behavior; import recommendator.models.entities.Project; import recommendator.models.entities.Row; import recommendator.models.entities.User; import recommendator.repositories.BehaviorRepository; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.verify; import static org.mockito.internal.verification.VerificationModeFactory.times; @ExtendWith(MockitoExtension.class) class BehaviorServiceTest { @Mock ProjectService projectService; @Mock RowService rowService; @Mock UserService userService; @Mock UserPreferenceService userPreferenceService; @Mock BehaviorRepository behaviorRepository; @InjectMocks BehaviorService behaviorService; @Test void add() { Mockito.when(projectService.getByApiKey(anyString())).thenReturn(new Project()); Mockito.when(rowService.getRowByCellDTOAndProject(anyList(), any(Project.class))).thenReturn(new Row()); // if we are creating behavior with existing user, we need user, // if we are creating with new (external) user we want to create new (external) user Mockito.when(userService.findByExternalIdAndProjectOrNull(anyString(), any(Project.class))).thenReturn(new User()).thenReturn(null); Response response = behaviorService.add("test", new BehaviorDTO(new ArrayList<>(), false, "userId")); assertThat("Behavior recorded").isEqualTo(response.getMessage()); verify(behaviorRepository, times(1)).add(any(Behavior.class)); // Checking if the user is null response = behaviorService.add("test", new BehaviorDTO(new ArrayList<>(), false, "userId")); assertThat("Behavior recorded").isEqualTo(response.getMessage()); // if it is a new user, this method should be called verify(userService, times(1)).add(any(User.class)); } @Test void getBehaviorsByUserAndTypeAndProject() { // get liked behaviors Mockito.when(behaviorRepository.getBehaviorsByUserAndTypeAndProject(any(User.class), ArgumentMatchers.eq(true), any(Project.class))) .thenReturn(Collections.singletonList(new Behavior(1L, true, null, null))); // get disliked behaviors Mockito.when(behaviorRepository.getBehaviorsByUserAndTypeAndProject(any(User.class), ArgumentMatchers.eq(false), any(Project.class))) .thenReturn(Collections.singletonList(new Behavior(1L, false, null, null))); List<Behavior> likedResponse = behaviorService.getBehaviorsByUserAndTypeAndProject(new User(), true, new Project()); List<Behavior> dislikedResponse = behaviorService.getBehaviorsByUserAndTypeAndProject(new User(), false, new Project()); assertThat(likedResponse.get(0).isLiked()).isTrue(); assertThat(likedResponse.size()).isEqualTo(1); assertThat(dislikedResponse.get(0).isLiked()).isFalse(); assertThat(dislikedResponse.size()).isEqualTo(1); } @Test void getBehaviorsByUser() { User u = new User(); u.setId(10L); Mockito.when(behaviorRepository.getBehaviorsByUser(u)) .thenReturn(Collections.singletonList(new Behavior(1L, false, null, u))); List<Behavior> response = behaviorService.getBehaviorsByUser(u); assertThat(response.get(0).getUser()).isEqualTo(u); assertThat(response.size()).isEqualTo(1); } }
UTF-8
Java
3,949
java
BehaviorServiceTest.java
Java
[]
null
[]
package recommendator.services; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentMatchers; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import recommendator.dto.BehaviorDTO; import recommendator.exceptions.responses.Response; import recommendator.models.entities.Behavior; import recommendator.models.entities.Project; import recommendator.models.entities.Row; import recommendator.models.entities.User; import recommendator.repositories.BehaviorRepository; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.verify; import static org.mockito.internal.verification.VerificationModeFactory.times; @ExtendWith(MockitoExtension.class) class BehaviorServiceTest { @Mock ProjectService projectService; @Mock RowService rowService; @Mock UserService userService; @Mock UserPreferenceService userPreferenceService; @Mock BehaviorRepository behaviorRepository; @InjectMocks BehaviorService behaviorService; @Test void add() { Mockito.when(projectService.getByApiKey(anyString())).thenReturn(new Project()); Mockito.when(rowService.getRowByCellDTOAndProject(anyList(), any(Project.class))).thenReturn(new Row()); // if we are creating behavior with existing user, we need user, // if we are creating with new (external) user we want to create new (external) user Mockito.when(userService.findByExternalIdAndProjectOrNull(anyString(), any(Project.class))).thenReturn(new User()).thenReturn(null); Response response = behaviorService.add("test", new BehaviorDTO(new ArrayList<>(), false, "userId")); assertThat("Behavior recorded").isEqualTo(response.getMessage()); verify(behaviorRepository, times(1)).add(any(Behavior.class)); // Checking if the user is null response = behaviorService.add("test", new BehaviorDTO(new ArrayList<>(), false, "userId")); assertThat("Behavior recorded").isEqualTo(response.getMessage()); // if it is a new user, this method should be called verify(userService, times(1)).add(any(User.class)); } @Test void getBehaviorsByUserAndTypeAndProject() { // get liked behaviors Mockito.when(behaviorRepository.getBehaviorsByUserAndTypeAndProject(any(User.class), ArgumentMatchers.eq(true), any(Project.class))) .thenReturn(Collections.singletonList(new Behavior(1L, true, null, null))); // get disliked behaviors Mockito.when(behaviorRepository.getBehaviorsByUserAndTypeAndProject(any(User.class), ArgumentMatchers.eq(false), any(Project.class))) .thenReturn(Collections.singletonList(new Behavior(1L, false, null, null))); List<Behavior> likedResponse = behaviorService.getBehaviorsByUserAndTypeAndProject(new User(), true, new Project()); List<Behavior> dislikedResponse = behaviorService.getBehaviorsByUserAndTypeAndProject(new User(), false, new Project()); assertThat(likedResponse.get(0).isLiked()).isTrue(); assertThat(likedResponse.size()).isEqualTo(1); assertThat(dislikedResponse.get(0).isLiked()).isFalse(); assertThat(dislikedResponse.size()).isEqualTo(1); } @Test void getBehaviorsByUser() { User u = new User(); u.setId(10L); Mockito.when(behaviorRepository.getBehaviorsByUser(u)) .thenReturn(Collections.singletonList(new Behavior(1L, false, null, u))); List<Behavior> response = behaviorService.getBehaviorsByUser(u); assertThat(response.get(0).getUser()).isEqualTo(u); assertThat(response.size()).isEqualTo(1); } }
3,949
0.730818
0.727526
96
40.135418
36.429047
141
false
false
0
0
0
0
0
0
0.84375
false
false
13
a5f9266f7e411bdd374e33b4fa79c333e8b02d86
5,806,795,833,841
31ae910c8be6d90e8086e2bcc3c1bdb736ef98bc
/gui-events Students and Courses/src/com/java/pamak/Student.java
178d3d501b31c792d46ae6dce15d0d7f4f102eef
[]
no_license
dimitkos/Java
https://github.com/dimitkos/Java
ad4aeb797899803f110a0904614af6f5562ee35b
cfca36ad79c7b0c5dad8c0648503d035a370dc4f
refs/heads/master
2020-03-22T15:32:51.668000
2018-09-07T16:30:25
2018-09-07T16:30:25
140,260,881
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.java.pamak; public class Student { private String name; private Course course; public Student(String name) { this.name= name; } public void setCourse(Course acourse) { course=acourse; } public void printInfo() { System.out.println("Student Name: "+name); System.out.println("Selected Course: "+course.getName()); System.out.println("----------------------------------"); } }
UTF-8
Java
505
java
Student.java
Java
[]
null
[]
package com.java.pamak; public class Student { private String name; private Course course; public Student(String name) { this.name= name; } public void setCourse(Course acourse) { course=acourse; } public void printInfo() { System.out.println("Student Name: "+name); System.out.println("Selected Course: "+course.getName()); System.out.println("----------------------------------"); } }
505
0.518812
0.518812
26
17.423077
19.613914
65
false
false
0
0
0
0
0
0
0.307692
false
false
13
435e97a70efa32b36d1dd5b068bbbde0ce4bc4cf
37,924,561,254,248
f5ebc7294f1917f9b767ec6b1f38d6f99efb70e0
/Oluttietokanta-refaktorointiin/src/main/java/olutopas/tietokanta/Datamapper.java
5b60a96815a64edf871ec2c0861940737fb37d66
[]
no_license
pslaakso/ohtu-viikko6
https://github.com/pslaakso/ohtu-viikko6
a94039f95662fec6dff7c6839e9146e98584b530
2df888b1d04f4a90954e4a983c43fa850d00134f
refs/heads/master
2016-09-06T19:23:06.733000
2013-04-28T10:41:04
2013-04-28T10:41:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package olutopas.tietokanta; import com.avaje.ebean.EbeanServer; import java.util.List; import olutopas.model.Beer; import olutopas.model.Brewery; import olutopas.model.Rating; import olutopas.model.User; public interface Datamapper { public Brewery brewerywithName(String n); public Beer beerWithName(String name); // public void saveRating(Rating rating); public void addBeer(Beer beer); // public void saveBrewery(Brewery brewery); public void save(Object o); public List<Beer> listBeers(); public List<User> listUsers(); public Brewery findBrewery(String name); public void saveBrewery(Brewery brewery); User getCurrentUser(); void setCurrentUser(User user); public EbeanServer getServer(); }
UTF-8
Java
725
java
Datamapper.java
Java
[]
null
[]
package olutopas.tietokanta; import com.avaje.ebean.EbeanServer; import java.util.List; import olutopas.model.Beer; import olutopas.model.Brewery; import olutopas.model.Rating; import olutopas.model.User; public interface Datamapper { public Brewery brewerywithName(String n); public Beer beerWithName(String name); // public void saveRating(Rating rating); public void addBeer(Beer beer); // public void saveBrewery(Brewery brewery); public void save(Object o); public List<Beer> listBeers(); public List<User> listUsers(); public Brewery findBrewery(String name); public void saveBrewery(Brewery brewery); User getCurrentUser(); void setCurrentUser(User user); public EbeanServer getServer(); }
725
0.772414
0.772414
36
19.138889
16.83441
44
false
false
0
0
0
0
0
0
0.888889
false
false
13
e141d7d7ef6a60d4f372005be8b831308d43307f
506,806,203,286
867353edec9fb1ff8a3a75b0d6622a512b26fda6
/app/src/main/java/com/jeevitnadi/riversofpune/ui/riverhistory/RiverHistoryFragment.java
8ba2f493e27de14bf2f88f4c2b224127efacd58d
[]
no_license
ashwinkolhatkar/RiversofPune
https://github.com/ashwinkolhatkar/RiversofPune
76a4288b905312a0c00a548e3b9522178d8e057d
718935cebca03e57fa817d224ce0c6a65319bea8
refs/heads/master
2020-07-26T00:01:42.043000
2020-06-01T03:32:57
2020-06-01T03:32:57
208,463,367
1
4
null
false
2019-10-13T09:19:17
2019-09-14T15:51:32
2019-10-13T09:19:12
2019-10-13T09:19:17
1,304
0
3
4
Java
false
false
package com.jeevitnadi.riversofpune.ui.riverhistory; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProviders; import com.jeevitnadi.riversofpune.R; public class RiverHistoryFragment extends Fragment { private RiverHistoryViewModel riverHistoryViewModel; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { riverHistoryViewModel = ViewModelProviders.of(this).get(RiverHistoryViewModel.class); View root = inflater.inflate(R.layout.fragment_history, container, false); WebView webView = root.findViewById(R.id.history_webview); String aid = "history_of_the_river"; webView.loadUrl("file:///android_asset/" + aid + "/" + aid + ".html"); return root; } }
UTF-8
Java
1,033
java
RiverHistoryFragment.java
Java
[]
null
[]
package com.jeevitnadi.riversofpune.ui.riverhistory; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProviders; import com.jeevitnadi.riversofpune.R; public class RiverHistoryFragment extends Fragment { private RiverHistoryViewModel riverHistoryViewModel; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { riverHistoryViewModel = ViewModelProviders.of(this).get(RiverHistoryViewModel.class); View root = inflater.inflate(R.layout.fragment_history, container, false); WebView webView = root.findViewById(R.id.history_webview); String aid = "history_of_the_river"; webView.loadUrl("file:///android_asset/" + aid + "/" + aid + ".html"); return root; } }
1,033
0.727977
0.727977
30
33.466667
26.848629
82
false
false
0
0
0
0
0
0
0.7
false
false
13
1ed531f6219b2e9ad212dc1425b3341faed4cbac
20,203,526,211,830
256f162593ae7e8eaceab947e6fce6eabee1421a
/src/se/sthlm/jfw/toyrobot/data/Command.java
2f1bd3f6273174921c49ac350ce9629e6413ecce
[]
no_license
jfwsthlm/Toy-Robot-Simulator
https://github.com/jfwsthlm/Toy-Robot-Simulator
70202b27286497b7405e229a07581a35d506ca16
11cafef0bf3782a4819eeae3b6d9af5d028061ca
refs/heads/main
2023-03-23T19:00:25.585000
2021-03-12T22:41:09
2021-03-12T22:41:09
344,937,792
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package se.sthlm.jfw.toyrobot.data; public enum Command { PLACE("PLACE"), MOVE("MOVE"), LEFT("LEFT"), RIGHT("RIGHT"), REPORT("REPORT"), INVALID_COMMAND("INVALID_COMMAND"); public final String commandString; private Command(String commandString) { this.commandString = commandString; } public static Command getCommand(String commandString) { for (Command commandElement : values()) { if (commandElement.commandString.equals(commandString)) { return commandElement; } } return INVALID_COMMAND; } }
UTF-8
Java
559
java
Command.java
Java
[]
null
[]
package se.sthlm.jfw.toyrobot.data; public enum Command { PLACE("PLACE"), MOVE("MOVE"), LEFT("LEFT"), RIGHT("RIGHT"), REPORT("REPORT"), INVALID_COMMAND("INVALID_COMMAND"); public final String commandString; private Command(String commandString) { this.commandString = commandString; } public static Command getCommand(String commandString) { for (Command commandElement : values()) { if (commandElement.commandString.equals(commandString)) { return commandElement; } } return INVALID_COMMAND; } }
559
0.681574
0.681574
25
21.360001
18.542664
63
false
false
0
0
0
0
0
0
0.44
false
false
13
6883dcfde6c0bb340aacff8fc0f38891983e5a51
12,489,764,907,773
12d1b2c3073b2ebb6fb20d15554cfe8bcc4bcc4c
/src/main/java/ru/job4j/collection/LexSort.java
ff072c3f58e11772e43010bbfcd0d816dfa435f3
[]
no_license
KirillReal/job4j_tracker
https://github.com/KirillReal/job4j_tracker
4cf297dd822c56a8d7d8610f0cdffbfc51b3f14f
bb93a12e2988ff9f63671d6ae1a382b612d5eff2
refs/heads/master
2023-05-08T18:27:22.203000
2022-07-01T21:14:08
2022-07-01T21:14:08
299,130,177
0
0
null
true
2020-09-27T22:24:46
2020-09-27T22:24:45
2020-09-19T16:51:23
2020-06-17T05:19:58
6
0
0
0
null
false
false
package ru.job4j.collection; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; public class LexSort implements Comparator<String> { @Override public int compare(String left, String right) { int sort = 0; List<String> list1 = Arrays.asList(left.split("\\ ")); List<String> list2 = Arrays.asList(right.split("\\ ")); int listOne = Integer.parseInt(list1.get(0).substring(0, list1.get(0).length() - 1)); int listTwo = Integer.parseInt(list2.get(0).substring(0, list2.get(0).length() - 1)); sort = Integer.compare(listOne, listTwo); return sort; } }
UTF-8
Java
684
java
LexSort.java
Java
[]
null
[]
package ru.job4j.collection; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; public class LexSort implements Comparator<String> { @Override public int compare(String left, String right) { int sort = 0; List<String> list1 = Arrays.asList(left.split("\\ ")); List<String> list2 = Arrays.asList(right.split("\\ ")); int listOne = Integer.parseInt(list1.get(0).substring(0, list1.get(0).length() - 1)); int listTwo = Integer.parseInt(list2.get(0).substring(0, list2.get(0).length() - 1)); sort = Integer.compare(listOne, listTwo); return sort; } }
684
0.644737
0.621345
20
33.200001
29.234568
97
false
false
0
0
0
0
0
0
0.8
false
false
13
6a21ca871e3645b0d7bb17fbd33ea15990b8f75b
19,215,683,703,405
0e70c8932d3bf08f6d9e01099b0d680c5798c96f
/app/src/main/java/felipesoares/justjava/MainActivity.java
9991cabacc2dc1f3498ab91bc97482ed86e805f4
[]
no_license
felipesoares6/JustJava
https://github.com/felipesoares6/JustJava
5c1bd6495a334bb51db220a413aa1dc517cc9d3f
8d88ddefa973c9d690b33ad04e863a47420765d9
refs/heads/master
2021-01-20T18:45:24.413000
2016-07-23T02:30:27
2016-07-23T02:30:27
63,993,683
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package felipesoares.justjava; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { Toast toast; Context context; int contCoffee = 0; float valueCoffee = 5; float contValue = 0; Toast toastOrder; Context contextOrder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); context = getApplicationContext(); toast = Toast.makeText(context, "Devagar e sempre", Toast.LENGTH_LONG); toast.setGravity(Gravity.BOTTOM, 0, 65); contextOrder = getApplicationContext(); toastOrder = Toast.makeText(contextOrder, "Pedido enviado", Toast.LENGTH_LONG); toastOrder.setGravity(Gravity.BOTTOM, 0, 65); } @Override public boolean onCreateOptionsMenu(Menu menu){ getMenuInflater().inflate(R.menu.menujustjava, menu); return true; } public void displayCoffe(){ TextView txtView= (TextView) findViewById(R.id.txtViewQuantity); txtView.setText("" + contCoffee); } public void displayValue(){ TextView txtView = (TextView) findViewById(R.id.txtViewValue); txtView.setText(String.format("R$%4.2f", contValue)); } public void viewDec(View view) { if(contCoffee == 0){ toast.show(); }else { contCoffee--; contValue-=valueCoffee; displayCoffe(); displayValue(); } } public void viewEnc(View view) { if(contCoffee == 99){ toast.show(); }else { contCoffee++; contValue+=valueCoffee; displayCoffe(); displayValue(); } } public void submitOrder(View view){ contCoffee = 0; contValue = 0; displayCoffe(); displayValue(); toastOrder.show(); } public void viewAbout(MenuItem item){ Intent newAbout = new Intent(MainActivity.this, About.class); startActivity(newAbout); } }
UTF-8
Java
2,389
java
MainActivity.java
Java
[ { "context": "package felipesoares.justjava;\n\nimport android.content.Context;\nimport", "end": 20, "score": 0.8041588664054871, "start": 8, "tag": "USERNAME", "value": "felipesoares" } ]
null
[]
package felipesoares.justjava; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { Toast toast; Context context; int contCoffee = 0; float valueCoffee = 5; float contValue = 0; Toast toastOrder; Context contextOrder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); context = getApplicationContext(); toast = Toast.makeText(context, "Devagar e sempre", Toast.LENGTH_LONG); toast.setGravity(Gravity.BOTTOM, 0, 65); contextOrder = getApplicationContext(); toastOrder = Toast.makeText(contextOrder, "Pedido enviado", Toast.LENGTH_LONG); toastOrder.setGravity(Gravity.BOTTOM, 0, 65); } @Override public boolean onCreateOptionsMenu(Menu menu){ getMenuInflater().inflate(R.menu.menujustjava, menu); return true; } public void displayCoffe(){ TextView txtView= (TextView) findViewById(R.id.txtViewQuantity); txtView.setText("" + contCoffee); } public void displayValue(){ TextView txtView = (TextView) findViewById(R.id.txtViewValue); txtView.setText(String.format("R$%4.2f", contValue)); } public void viewDec(View view) { if(contCoffee == 0){ toast.show(); }else { contCoffee--; contValue-=valueCoffee; displayCoffe(); displayValue(); } } public void viewEnc(View view) { if(contCoffee == 99){ toast.show(); }else { contCoffee++; contValue+=valueCoffee; displayCoffe(); displayValue(); } } public void submitOrder(View view){ contCoffee = 0; contValue = 0; displayCoffe(); displayValue(); toastOrder.show(); } public void viewAbout(MenuItem item){ Intent newAbout = new Intent(MainActivity.this, About.class); startActivity(newAbout); } }
2,389
0.631645
0.624529
92
24.967392
20.419222
87
false
false
0
0
0
0
0
0
0.652174
false
false
13
69b3df8667edfe272339686b5e20af7292989aa3
13,950,053,817,440
0c09e7de895aacba05048f4e349e81a2d1c0a729
/src/main/java/net/musicrecommend/www/vo/DetailChartVO.java
e4a665b8fa7d17b7b28b2d4910b6db63d8dfe4d7
[]
no_license
rpzen/ListenOn
https://github.com/rpzen/ListenOn
c750737e94d9f7395d6ccd61fd97cdf64a332b38
e3a7003743ac2b5344b24e1ba2bb184a22f97ad5
refs/heads/master
2021-01-20T19:29:51.612000
2016-06-20T07:28:34
2016-06-20T07:28:34
61,277,111
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.musicrecommend.www.vo; import java.io.Serializable; public class DetailChartVO implements Serializable{ private double avg_star_point; private double star_point; private long cnt; public double getAvg_star_point() { return avg_star_point; } public void setAvg_star_point(double avg_star_point) { this.avg_star_point = avg_star_point; } public double getStar_point() { return star_point; } public void setStar_point(double star_point) { this.star_point = star_point; } public long getCnt() { return cnt; } public void setCnt(long cnt) { this.cnt = cnt; } }
UTF-8
Java
639
java
DetailChartVO.java
Java
[]
null
[]
package net.musicrecommend.www.vo; import java.io.Serializable; public class DetailChartVO implements Serializable{ private double avg_star_point; private double star_point; private long cnt; public double getAvg_star_point() { return avg_star_point; } public void setAvg_star_point(double avg_star_point) { this.avg_star_point = avg_star_point; } public double getStar_point() { return star_point; } public void setStar_point(double star_point) { this.star_point = star_point; } public long getCnt() { return cnt; } public void setCnt(long cnt) { this.cnt = cnt; } }
639
0.676056
0.676056
32
17.96875
16.967772
55
false
false
0
0
0
0
0
0
1.34375
false
false
13
a4e237cff2042e6b28bf51a9838b3901650afc3d
29,446,295,813,534
2f385d9c08d9309e57cc6610f2f5513a87a188f9
/xdf4-provider-conference-8001/src/main/java/com/aaa/springcloud/mapper/PurchaseMapper.java
37e9c6de7ddf128b74dcdf756e3ac3e4c22a0403
[]
no_license
96561226/xdf4
https://github.com/96561226/xdf4
ebdc8771eb7c38aa2964422f0106b652911fc929
15e3e7031328caf79da98078f781ce76150e89a2
refs/heads/main
2023-03-03T06:39:38.498000
2021-02-15T13:16:46
2021-02-15T13:16:46
339,073,303
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.aaa.springcloud.mapper; import com.aaa.pojo.conference.PurchaseVo; import com.aaa.pojo.conference.TbPurchase; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Component; import javax.xml.crypto.Data; import java.util.List; @Mapper @Component public interface PurchaseMapper { //动态查询物品采购表 List<PurchaseVo> selPurchaseDT(PurchaseVo purchaseVo); //修改 物品采购表 只能通过id修改状态 int updPurchase(@Param("state") Integer state, @Param("purchaseBuytime") String purchaseBuytime, @Param("purchaseId") Long purchaseId); //添加 物品采购 int addPurchase(TbPurchase tbPurchase); }
UTF-8
Java
730
java
PurchaseMapper.java
Java
[]
null
[]
package com.aaa.springcloud.mapper; import com.aaa.pojo.conference.PurchaseVo; import com.aaa.pojo.conference.TbPurchase; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Component; import javax.xml.crypto.Data; import java.util.List; @Mapper @Component public interface PurchaseMapper { //动态查询物品采购表 List<PurchaseVo> selPurchaseDT(PurchaseVo purchaseVo); //修改 物品采购表 只能通过id修改状态 int updPurchase(@Param("state") Integer state, @Param("purchaseBuytime") String purchaseBuytime, @Param("purchaseId") Long purchaseId); //添加 物品采购 int addPurchase(TbPurchase tbPurchase); }
730
0.783582
0.783582
21
30.904762
30.001436
139
false
false
0
0
0
0
0
0
0.619048
false
false
13
3094ef0861a3fe62bf964bc784736dfb74008b53
21,706,764,728,925
55d41085074daaac1ac797f7770b45b26686ca26
/src/main/java/pl/kopka/summary/service/EmailService.java
74342286f655fcddafcc4989494e6febb94f2fb2
[]
no_license
JakubKopka/Summary-Backend
https://github.com/JakubKopka/Summary-Backend
fcfa3e4ecf2d79e6fd61bb0b3f2c28fb1fc3e68c
cbb19a7a59a473ec2a8cc46d2c216b3d5512cc18
refs/heads/master
2023-07-16T20:24:08.992000
2021-08-31T19:27:31
2021-08-31T19:27:31
332,577,147
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pl.kopka.summary.service; import com.sun.mail.smtp.SMTPTransport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import pl.kopka.summary.constant.EmailConst; import pl.kopka.summary.domain.model.User; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Date; import java.util.Properties; import static javax.mail.Message.RecipientType.CC; import static javax.mail.Message.RecipientType.TO; @Service public class EmailService { private Logger LOGGER = LoggerFactory.getLogger(getClass()); public void sendWelcomingEmail(User user) { String textMessage = "Hello " + user.getFirstName() + ", \n \n Your new account is created!" + "" + "\n \n The Support Team"; sendEmail(user.getEmail(), EmailConst.EMAIL_WELCOMING__SUBJECT, textMessage); LOGGER.info(textMessage); } public void sendNewPasswordEmail(User user, String password) { String textMessage = "Hello " + user.getFirstName() + ", \n \n Your new password: " + password + "\n \n The Support Team"; sendEmail(user.getEmail(), EmailConst.EMAIL_NEW_PASSWORD_SUBJECT, textMessage); LOGGER.info(textMessage); } public void sendEmail(String email, String subject, String textMessage) { try { Message message = createEmail(email, subject, textMessage); SMTPTransport smtpTransport = (SMTPTransport) getEmailSession().getTransport(EmailConst.SIMPLE_MAIL_TRANSFER_PROTOCOL); smtpTransport.connect(EmailConst.GMAIL_SMTP_SERVER, EmailConst.USERNAME, EmailConst.PASSWORD); smtpTransport.sendMessage(message, message.getAllRecipients()); smtpTransport.close(); } catch (MessagingException e) { LOGGER.error(e.getMessage()); } } private Message createEmail(String email, String subject, String messageText) throws MessagingException { Message message = new MimeMessage(getEmailSession()); message.setFrom(new InternetAddress(EmailConst.FROM_EMAIL)); message.setRecipients(TO, InternetAddress.parse(email, false)); message.setRecipients(CC, InternetAddress.parse(EmailConst.CC_EMAIL, false)); message.setSubject(subject); message.setText(messageText); message.setSentDate(new Date()); message.saveChanges(); return message; } private Session getEmailSession() { Properties properties = System.getProperties(); properties.put(EmailConst.SMTP_HOST, EmailConst.GMAIL_SMTP_SERVER); properties.put(EmailConst.SMTP_AUTH, true); properties.put(EmailConst.SMTP_PORT, EmailConst.DEFAULT_PORT); properties.put(EmailConst.SMTP_STARTTLS_ENABLE, true); properties.put(EmailConst.SMTP_STARTTLS_REQUIRED, true); return Session.getInstance(properties, null); } }
UTF-8
Java
3,015
java
EmailService.java
Java
[]
null
[]
package pl.kopka.summary.service; import com.sun.mail.smtp.SMTPTransport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import pl.kopka.summary.constant.EmailConst; import pl.kopka.summary.domain.model.User; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Date; import java.util.Properties; import static javax.mail.Message.RecipientType.CC; import static javax.mail.Message.RecipientType.TO; @Service public class EmailService { private Logger LOGGER = LoggerFactory.getLogger(getClass()); public void sendWelcomingEmail(User user) { String textMessage = "Hello " + user.getFirstName() + ", \n \n Your new account is created!" + "" + "\n \n The Support Team"; sendEmail(user.getEmail(), EmailConst.EMAIL_WELCOMING__SUBJECT, textMessage); LOGGER.info(textMessage); } public void sendNewPasswordEmail(User user, String password) { String textMessage = "Hello " + user.getFirstName() + ", \n \n Your new password: " + password + "\n \n The Support Team"; sendEmail(user.getEmail(), EmailConst.EMAIL_NEW_PASSWORD_SUBJECT, textMessage); LOGGER.info(textMessage); } public void sendEmail(String email, String subject, String textMessage) { try { Message message = createEmail(email, subject, textMessage); SMTPTransport smtpTransport = (SMTPTransport) getEmailSession().getTransport(EmailConst.SIMPLE_MAIL_TRANSFER_PROTOCOL); smtpTransport.connect(EmailConst.GMAIL_SMTP_SERVER, EmailConst.USERNAME, EmailConst.PASSWORD); smtpTransport.sendMessage(message, message.getAllRecipients()); smtpTransport.close(); } catch (MessagingException e) { LOGGER.error(e.getMessage()); } } private Message createEmail(String email, String subject, String messageText) throws MessagingException { Message message = new MimeMessage(getEmailSession()); message.setFrom(new InternetAddress(EmailConst.FROM_EMAIL)); message.setRecipients(TO, InternetAddress.parse(email, false)); message.setRecipients(CC, InternetAddress.parse(EmailConst.CC_EMAIL, false)); message.setSubject(subject); message.setText(messageText); message.setSentDate(new Date()); message.saveChanges(); return message; } private Session getEmailSession() { Properties properties = System.getProperties(); properties.put(EmailConst.SMTP_HOST, EmailConst.GMAIL_SMTP_SERVER); properties.put(EmailConst.SMTP_AUTH, true); properties.put(EmailConst.SMTP_PORT, EmailConst.DEFAULT_PORT); properties.put(EmailConst.SMTP_STARTTLS_ENABLE, true); properties.put(EmailConst.SMTP_STARTTLS_REQUIRED, true); return Session.getInstance(properties, null); } }
3,015
0.713764
0.713101
70
42.07143
33.348515
133
false
false
0
0
0
0
0
0
1.014286
false
false
13
82c7c4460a4b04e231c4bab06bbbd38e6885022e
19,971,597,942,905
21ba91b16304eb38c41055bf5ba2ad0b9aa4f20e
/eggwars-api/src/main/java/net/seniorteam/eggwars/kit/Kit.java
b92b043220815994491f9eac4b91ca159edaf41c
[]
no_license
sophia-laura/SeniorEggwars
https://github.com/sophia-laura/SeniorEggwars
7b26ddc1f9c1effdde9c92042d90f8683127303c
d6e37724b6ccd049a403d140b8591b2449db22a9
refs/heads/master
2022-11-29T06:15:16.061000
2020-08-11T17:23:58
2020-08-11T17:23:58
286,805,317
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.seniorteam.eggwars.kit; public interface Kit { String getName(); String getPermission(); int getPrice(); KitIcon getIcon(); int getIconSlot(); boolean hasSpecialAbility(); boolean isActivate(); }
UTF-8
Java
245
java
Kit.java
Java
[]
null
[]
package net.seniorteam.eggwars.kit; public interface Kit { String getName(); String getPermission(); int getPrice(); KitIcon getIcon(); int getIconSlot(); boolean hasSpecialAbility(); boolean isActivate(); }
245
0.653061
0.653061
19
11.894737
12.916308
35
false
false
0
0
0
0
0
0
0.421053
false
false
13
b934fc77a1d8612718e10c556ac2f58028ce7899
29,197,187,700,531
a1bd12f6140879d2a4f272733c380b518d249b1d
/app/src/main/java/o1/mobile/softhanjolup/SplashActivity.java
23dfee8465791d10ded450fd443668ccc704202f
[]
no_license
2019mobileprogramming/SoftHanJolUp
https://github.com/2019mobileprogramming/SoftHanJolUp
7d0e24e8618996d785745e7364e40176157f7546
6eaed478632cb49fcebfe86e22c6796b2e97b992
refs/heads/master
2020-05-27T19:03:37.202000
2019-06-05T13:19:23
2019-06-05T13:19:23
188,754,363
2
0
null
false
2019-06-05T13:21:43
2019-05-27T01:59:48
2019-06-05T13:19:25
2019-06-05T13:19:24
9,316
2
0
1
HTML
false
false
package o1.mobile.softhanjolup; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import o1.mobile.softhanjolup.Init.InitialActivity; public class SplashActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.splash_x); SharedPreferences pref = getSharedPreferences("initFlag", Context.MODE_PRIVATE); boolean first = pref.getBoolean("isFirst",false); if(first == false){ SharedPreferences.Editor editor = pref.edit(); editor.putBoolean("isFirst", true); editor.commit(); new Handler().postDelayed(new Runnable() { @Override public void run() { Intent intent = new Intent(SplashActivity.this, InitialActivity.class); Bundle bundle = new Bundle(); bundle.putInt("isFirst", 0); intent.putExtras(bundle); startActivity(intent); finish(); } }, 2000); } else{ new Handler().postDelayed(new Runnable() { @Override public void run() { Intent intent = new Intent(SplashActivity.this, MainActivity.class); startActivity(intent); finish(); } }, 2000); } } }
UTF-8
Java
1,651
java
SplashActivity.java
Java
[]
null
[]
package o1.mobile.softhanjolup; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import o1.mobile.softhanjolup.Init.InitialActivity; public class SplashActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.splash_x); SharedPreferences pref = getSharedPreferences("initFlag", Context.MODE_PRIVATE); boolean first = pref.getBoolean("isFirst",false); if(first == false){ SharedPreferences.Editor editor = pref.edit(); editor.putBoolean("isFirst", true); editor.commit(); new Handler().postDelayed(new Runnable() { @Override public void run() { Intent intent = new Intent(SplashActivity.this, InitialActivity.class); Bundle bundle = new Bundle(); bundle.putInt("isFirst", 0); intent.putExtras(bundle); startActivity(intent); finish(); } }, 2000); } else{ new Handler().postDelayed(new Runnable() { @Override public void run() { Intent intent = new Intent(SplashActivity.this, MainActivity.class); startActivity(intent); finish(); } }, 2000); } } }
1,651
0.572986
0.565718
51
31.372549
23.321253
91
false
false
0
0
0
0
0
0
0.666667
false
false
13
58cffae483afe72976ac1e9852fece8a7d74c237
33,225,867,022,490
ce34e090bd857e0f59cd0f0e4fc2bbbd381163fa
/src/main/java/com/example/todobook/model/Task.java
e0c3ea029ad6926c0127726456b17c2c1972a436
[ "Unlicense" ]
permissive
JarekDziuraDev/ToDoBook
https://github.com/JarekDziuraDev/ToDoBook
c8201fa645cffc960a6d864ffa2a38b1ca02d823
994f2ec00324c4dc305da866f27d2bf7f80df42a
refs/heads/main
2023-08-13T10:33:13.566000
2021-09-27T19:49:55
2021-09-27T19:49:55
410,596,874
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.todobook.model; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.*; import javax.validation.constraints.NotBlank; import java.time.LocalDateTime; @Getter @Setter @Entity @NoArgsConstructor public class Task { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @NotBlank(message = "Task description must be not empty.") private String description; private boolean done; @Embedded private Audit audit = new Audit(); private LocalDateTime deadline; @ManyToOne @JoinColumn(name = "task_groups_id") private TaskGroup group; public Task(String description, LocalDateTime deadline) { this.deadline = deadline; this.description = description; } public void updateFrom(final Task source) { this.description = source.description; this.done = source.done; this.deadline = source.deadline; this.group = source.group; } }
UTF-8
Java
1,024
java
Task.java
Java
[]
null
[]
package com.example.todobook.model; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.*; import javax.validation.constraints.NotBlank; import java.time.LocalDateTime; @Getter @Setter @Entity @NoArgsConstructor public class Task { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @NotBlank(message = "Task description must be not empty.") private String description; private boolean done; @Embedded private Audit audit = new Audit(); private LocalDateTime deadline; @ManyToOne @JoinColumn(name = "task_groups_id") private TaskGroup group; public Task(String description, LocalDateTime deadline) { this.deadline = deadline; this.description = description; } public void updateFrom(final Task source) { this.description = source.description; this.done = source.done; this.deadline = source.deadline; this.group = source.group; } }
1,024
0.703125
0.703125
44
22.272728
18.228804
62
false
false
0
0
0
0
0
0
0.454545
false
false
13
9abef0dcad69defe2b7454449c55f07dc3e9efcb
21,002,390,103,779
560bc101286928ffb442d6a82683bddb856c24bd
/CeeMe/CeeMeWeb/src/main/java/com/appspot/cee_me/endpoints/model/Message.java
845bce8ee0f5bf80d44c93ded077075a6a116cd6
[ "Apache-2.0" ]
permissive
Preston-Landers/planders-apt2013
https://github.com/Preston-Landers/planders-apt2013
6e3acd7e3eaf75c7955dca831f8e793aff94a0f1
b52f1158843cf07caa580869d78d865606d1c4cd
refs/heads/master
2023-06-23T07:00:12.589000
2014-09-18T14:00:40
2014-09-18T14:00:40
33,744,515
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.appspot.cee_me.endpoints.model; import org.joda.time.DateTime; import java.io.Serializable; /** * Represents a Message in the endpoint API. */ public class Message implements Serializable { private String messageKey; private Device fromDevice; private Device toDevice; private User fromUser; private User toUser; private Media media; private String urlData; private String text; private DateTime creationDate; private DateTime lastRetrievalDate; private boolean accepted; private String openWithApp; private String openWithAppName; public Message() { } public Message(String messageKey) { this.messageKey = messageKey; } public Message(com.appspot.cee_me.model.Message message) { if (message != null) { setMessageKey(message.getKey().getString()); com.appspot.cee_me.model.Device fromDevice = message.getFromDevice(); setFromDevice(fromDevice == null ? null : new Device(fromDevice)); setToDevice(new Device(message.getToDevice())); setToUser(new User(message.getToUser())); setFromUser(new User(message.getFromUser())); com.appspot.cee_me.model.Media media = message.getMedia(); setMedia(media == null ? null : new Media(media)); setUrlData(message.getUrlData()); setText(message.getText()); setCreationDate(message.getCreationDate()); setLastRetrievalDate(message.getLastRetrievalDate()); setAccepted(message.getAccepted()); setOpenWithApp(message.getOpenWithApp()); setOpenWithAppName(message.getOpenWithAppName()); } } public String getMessageKey() { return messageKey; } public void setMessageKey(String messageKey) { this.messageKey = messageKey; } public Device getFromDevice() { return fromDevice; } public void setFromDevice(Device fromDevice) { this.fromDevice = fromDevice; } public Device getToDevice() { return toDevice; } public void setToDevice(Device toDevice) { this.toDevice = toDevice; } public User getFromUser() { return fromUser; } public void setFromUser(User fromUser) { this.fromUser = fromUser; } public User getToUser() { return toUser; } public void setToUser(User toUser) { this.toUser = toUser; } public Media getMedia() { return media; } public void setMedia(Media media) { this.media = media; } public String getUrlData() { return urlData; } public void setUrlData(String urlData) { this.urlData = urlData; } public String getText() { return text; } public void setText(String text) { this.text = text; } public DateTime getCreationDate() { return creationDate; } public void setCreationDate(DateTime creationDate) { this.creationDate = creationDate; } public DateTime getLastRetrievalDate() { return lastRetrievalDate; } public void setLastRetrievalDate(DateTime lastRetrievalDate) { this.lastRetrievalDate = lastRetrievalDate; } public boolean isAccepted() { return accepted; } public void setAccepted(boolean accepted) { this.accepted = accepted; } public String getOpenWithApp() { return openWithApp; } public void setOpenWithApp(String openWithApp) { this.openWithApp = openWithApp; } public String getOpenWithAppName() { return openWithAppName; } public void setOpenWithAppName(String openWithAppName) { this.openWithAppName = openWithAppName; } }
UTF-8
Java
3,834
java
Message.java
Java
[]
null
[]
package com.appspot.cee_me.endpoints.model; import org.joda.time.DateTime; import java.io.Serializable; /** * Represents a Message in the endpoint API. */ public class Message implements Serializable { private String messageKey; private Device fromDevice; private Device toDevice; private User fromUser; private User toUser; private Media media; private String urlData; private String text; private DateTime creationDate; private DateTime lastRetrievalDate; private boolean accepted; private String openWithApp; private String openWithAppName; public Message() { } public Message(String messageKey) { this.messageKey = messageKey; } public Message(com.appspot.cee_me.model.Message message) { if (message != null) { setMessageKey(message.getKey().getString()); com.appspot.cee_me.model.Device fromDevice = message.getFromDevice(); setFromDevice(fromDevice == null ? null : new Device(fromDevice)); setToDevice(new Device(message.getToDevice())); setToUser(new User(message.getToUser())); setFromUser(new User(message.getFromUser())); com.appspot.cee_me.model.Media media = message.getMedia(); setMedia(media == null ? null : new Media(media)); setUrlData(message.getUrlData()); setText(message.getText()); setCreationDate(message.getCreationDate()); setLastRetrievalDate(message.getLastRetrievalDate()); setAccepted(message.getAccepted()); setOpenWithApp(message.getOpenWithApp()); setOpenWithAppName(message.getOpenWithAppName()); } } public String getMessageKey() { return messageKey; } public void setMessageKey(String messageKey) { this.messageKey = messageKey; } public Device getFromDevice() { return fromDevice; } public void setFromDevice(Device fromDevice) { this.fromDevice = fromDevice; } public Device getToDevice() { return toDevice; } public void setToDevice(Device toDevice) { this.toDevice = toDevice; } public User getFromUser() { return fromUser; } public void setFromUser(User fromUser) { this.fromUser = fromUser; } public User getToUser() { return toUser; } public void setToUser(User toUser) { this.toUser = toUser; } public Media getMedia() { return media; } public void setMedia(Media media) { this.media = media; } public String getUrlData() { return urlData; } public void setUrlData(String urlData) { this.urlData = urlData; } public String getText() { return text; } public void setText(String text) { this.text = text; } public DateTime getCreationDate() { return creationDate; } public void setCreationDate(DateTime creationDate) { this.creationDate = creationDate; } public DateTime getLastRetrievalDate() { return lastRetrievalDate; } public void setLastRetrievalDate(DateTime lastRetrievalDate) { this.lastRetrievalDate = lastRetrievalDate; } public boolean isAccepted() { return accepted; } public void setAccepted(boolean accepted) { this.accepted = accepted; } public String getOpenWithApp() { return openWithApp; } public void setOpenWithApp(String openWithApp) { this.openWithApp = openWithApp; } public String getOpenWithAppName() { return openWithAppName; } public void setOpenWithAppName(String openWithAppName) { this.openWithAppName = openWithAppName; } }
3,834
0.635629
0.635629
161
22.813665
20.921387
81
false
false
0
0
0
0
0
0
0.360248
false
false
13
a817011a48496b1354b2cf4af620f51df5ff5754
13,116,830,153,304
52a454f63b27ec3236d405ffa35dc8558f52a873
/src/test/java/com/usul/training/javaslang/TuplesTest.java
279f47a17f2becde150ba2c13061ec342b988010
[ "MIT" ]
permissive
niushaokai/javaslang-tutorials
https://github.com/niushaokai/javaslang-tutorials
39e3a3515a18bb34db6ec9e1ac23af7bc9b45332
01cd308e47f3d88444cc4885210c7ed4cacd9532
refs/heads/master
2021-07-15T06:38:36.539000
2017-10-17T06:56:22
2017-10-17T06:56:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.usul.training.javaslang; import javaslang.Tuple; import javaslang.Tuple2; import javaslang.collection.List; import javaslang.collection.Map; import javaslang.control.Option; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; /** * TuplesTest * * @author bigkahuna * @since 12/11/2016 */ public class TuplesTest { @Test public void groupBy() { Map<Integer, List<Integer>> mapOfTuples = List.of(1, 2, 3, 4).groupBy(i -> i % 2); assertThat(mapOfTuples.get(0)).isEqualTo(Option.of(List.of(2,4))); assertThat(mapOfTuples.get(1)).isEqualTo(Option.of(List.of(1,3))); } @Test public void zip() { List<Tuple2<Character, Long>> tuple2List = List.of('a', 'b', 'c').zipWithIndex(); assertThat(tuple2List.get(0)).isEqualTo(Tuple.of('a', 0L)); assertThat(tuple2List.get(1)).isEqualTo(Tuple.of('b', 1L)); assertThat(tuple2List.get(2)).isEqualTo(Tuple.of('c', 2L)); } @Test public void mapByComponent() { Tuple2<Integer, Integer> tuple2 = Tuple.of(1, 2); Tuple2<Integer, Integer> mapped = tuple2.map(i -> i + 1, j -> j + 1); assertThat(mapped._1).isEqualTo(2); assertThat(mapped._2).isEqualTo(3); } @Test public void mapWithBiFunction() { Tuple2<Integer, Integer> tuple2 = Tuple.of(1, 2); Tuple2<Integer, Integer> mapped = tuple2.map((i,j) -> Tuple.of(i + 1, j + 1)); assertThat(mapped._1).isEqualTo(2); assertThat(mapped._2).isEqualTo(3); } @Test public void transform() { Tuple2<Integer, Integer> tuple2 = Tuple.of(1, 2); String transform = tuple2.transform((i, j) -> i + " -> " + j); assertThat(transform).isEqualTo("1 -> 2"); } }
UTF-8
Java
1,817
java
TuplesTest.java
Java
[ { "context": "tions.assertThat;\n\n/**\n * TuplesTest\n *\n * @author bigkahuna\n * @since 12/11/2016\n */\npublic class TuplesTest ", "end": 323, "score": 0.9994825720787048, "start": 314, "tag": "USERNAME", "value": "bigkahuna" } ]
null
[]
package com.usul.training.javaslang; import javaslang.Tuple; import javaslang.Tuple2; import javaslang.collection.List; import javaslang.collection.Map; import javaslang.control.Option; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; /** * TuplesTest * * @author bigkahuna * @since 12/11/2016 */ public class TuplesTest { @Test public void groupBy() { Map<Integer, List<Integer>> mapOfTuples = List.of(1, 2, 3, 4).groupBy(i -> i % 2); assertThat(mapOfTuples.get(0)).isEqualTo(Option.of(List.of(2,4))); assertThat(mapOfTuples.get(1)).isEqualTo(Option.of(List.of(1,3))); } @Test public void zip() { List<Tuple2<Character, Long>> tuple2List = List.of('a', 'b', 'c').zipWithIndex(); assertThat(tuple2List.get(0)).isEqualTo(Tuple.of('a', 0L)); assertThat(tuple2List.get(1)).isEqualTo(Tuple.of('b', 1L)); assertThat(tuple2List.get(2)).isEqualTo(Tuple.of('c', 2L)); } @Test public void mapByComponent() { Tuple2<Integer, Integer> tuple2 = Tuple.of(1, 2); Tuple2<Integer, Integer> mapped = tuple2.map(i -> i + 1, j -> j + 1); assertThat(mapped._1).isEqualTo(2); assertThat(mapped._2).isEqualTo(3); } @Test public void mapWithBiFunction() { Tuple2<Integer, Integer> tuple2 = Tuple.of(1, 2); Tuple2<Integer, Integer> mapped = tuple2.map((i,j) -> Tuple.of(i + 1, j + 1)); assertThat(mapped._1).isEqualTo(2); assertThat(mapped._2).isEqualTo(3); } @Test public void transform() { Tuple2<Integer, Integer> tuple2 = Tuple.of(1, 2); String transform = tuple2.transform((i, j) -> i + " -> " + j); assertThat(transform).isEqualTo("1 -> 2"); } }
1,817
0.613099
0.578976
69
25.333334
27.041925
90
false
false
0
0
0
0
0
0
0.724638
false
false
13
86557aa0c90cf4fb25c8442a2d65a78634e6dea6
23,304,492,573,948
1eba35ed5d8a06b9a315f65b3c00b3aa65793fb2
/Day21.java
42333aacc5c047321d8382e24279503fc8e9d4e9
[]
no_license
shreyxskar/may-leetcoding-challenge
https://github.com/shreyxskar/may-leetcoding-challenge
a49682b8bd1b31d2d05dc45eb7c2079742e6cf09
e14167c3deef34d06aac0955df7da4cc57688420
refs/heads/master
2022-09-19T17:45:54.854000
2020-05-31T09:35:26
2020-05-31T09:35:26
260,644,918
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class Solution { public int countSquares(int[][] matrix) { int count = 0; int i, j; for(i = 0; i < matrix.length; i++) if(matrix[i][0] == 1) count += 1; for(j = 1; j < matrix[0].length; j++) if(matrix[0][j] == 1) count += 1; for(i = 1; i < matrix.length; i++){ for(j = 1; j < matrix[i].length; j++){ if(matrix[i][j] != 0){ int min = Math.min(Math.min(matrix[i-1][j-1], matrix[i-1][j]), matrix[i][j-1]) + 1; count += min; matrix[i][j] = min; } } } return count; } }
UTF-8
Java
701
java
Day21.java
Java
[]
null
[]
class Solution { public int countSquares(int[][] matrix) { int count = 0; int i, j; for(i = 0; i < matrix.length; i++) if(matrix[i][0] == 1) count += 1; for(j = 1; j < matrix[0].length; j++) if(matrix[0][j] == 1) count += 1; for(i = 1; i < matrix.length; i++){ for(j = 1; j < matrix[i].length; j++){ if(matrix[i][j] != 0){ int min = Math.min(Math.min(matrix[i-1][j-1], matrix[i-1][j]), matrix[i][j-1]) + 1; count += min; matrix[i][j] = min; } } } return count; } }
701
0.369472
0.343795
22
30.863636
20.824583
103
false
false
0
0
0
0
0
0
0.863636
false
false
13
bdb65e29a1272c8130ca159804d68616a4966615
25,640,954,782,175
9a6bd50fe96dbb9c91a4d98dea52b2dbb5086869
/LocationTracking/src/main/java/com/trnkarthik/locationtracking/locationtracking/db/LocationDataManager.java
6460e6c25b533c053a97df8adc196f033cb9a1b3
[]
no_license
trnkarthik/LocationTracking
https://github.com/trnkarthik/LocationTracking
cf29abfe3674da598c3fa21b80e06a3cb3185ef2
b4a99b9a2142a55cfa0216a5cf15453eef042758
refs/heads/master
2016-09-10T01:39:04.766000
2014-06-13T07:42:17
2014-06-13T07:42:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.trnkarthik.locationtracking.locationtracking.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import java.util.List; /** * Created by karthiktangirala on 6/11/14. */ public class LocationDataManager { Context mContext; LocationDBHelper dbOpenHelper; SQLiteDatabase db; LocationDAO locationDAO; public LocationDataManager(Context mContext){ this.mContext = mContext; dbOpenHelper = new LocationDBHelper(mContext); db = dbOpenHelper.getWritableDatabase(); locationDAO = new LocationDAO(db); } public void close(){ db.close(); } public long saveLocationObject(LocationObject locationObject){ return locationDAO.save(locationObject); } public boolean updateLocationObject(LocationObject locationObject){ return locationDAO.update(locationObject); } public boolean deleteLocationObject(LocationObject locationObject){ return locationDAO.delete(locationObject); } public LocationObject getLocationObject(long id){ return locationDAO.get(id); } public List<LocationObject> getAllLocationObjects(){ return locationDAO.getAll(); } }
UTF-8
Java
1,233
java
LocationDataManager.java
Java
[ { "context": "tabase;\n\nimport java.util.List;\n\n/**\n * Created by karthiktangirala on 6/11/14.\n */\npublic class LocationDataManager ", "end": 200, "score": 0.99930340051651, "start": 184, "tag": "USERNAME", "value": "karthiktangirala" } ]
null
[]
package com.trnkarthik.locationtracking.locationtracking.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import java.util.List; /** * Created by karthiktangirala on 6/11/14. */ public class LocationDataManager { Context mContext; LocationDBHelper dbOpenHelper; SQLiteDatabase db; LocationDAO locationDAO; public LocationDataManager(Context mContext){ this.mContext = mContext; dbOpenHelper = new LocationDBHelper(mContext); db = dbOpenHelper.getWritableDatabase(); locationDAO = new LocationDAO(db); } public void close(){ db.close(); } public long saveLocationObject(LocationObject locationObject){ return locationDAO.save(locationObject); } public boolean updateLocationObject(LocationObject locationObject){ return locationDAO.update(locationObject); } public boolean deleteLocationObject(LocationObject locationObject){ return locationDAO.delete(locationObject); } public LocationObject getLocationObject(long id){ return locationDAO.get(id); } public List<LocationObject> getAllLocationObjects(){ return locationDAO.getAll(); } }
1,233
0.716951
0.712895
47
25.25532
22.962011
71
false
false
0
0
0
0
0
0
0.382979
false
false
13
6e63b593d869b3d26c50a30e67bea9effe079a1e
11,295,764,042,657
6e21191e1cc6ebe22257f1452b01615230044adf
/src/main/java/cot/colabare/calendar/controller/CalendarController.java
508a3521d2e13a2a5e26cb3a74144ac41a47140f
[]
no_license
hyh528/colabareV2
https://github.com/hyh528/colabareV2
0820597d4438d36ac76eea43a9b5a45ac3b666e8
8516863990697e182daddd32c2dd48619e6164ab
refs/heads/master
2022-12-21T15:22:27.696000
2020-01-02T07:28:16
2020-01-02T07:28:16
228,282,418
0
3
null
false
2022-12-16T01:01:00
2019-12-16T01:58:15
2020-01-02T07:28:30
2022-12-16T01:00:57
14,525
0
3
10
HTML
false
false
package cot.colabare.calendar.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import lombok.AllArgsConstructor; import lombok.extern.log4j.Log4j; @Controller @Log4j @RequestMapping("/calendar/*") @AllArgsConstructor public class CalendarController { @GetMapping("/calendarform") public void calendarList(){ } @GetMapping("/calendarform2") public void calendarList2(){ } }
UTF-8
Java
527
java
CalendarController.java
Java
[]
null
[]
package cot.colabare.calendar.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import lombok.AllArgsConstructor; import lombok.extern.log4j.Log4j; @Controller @Log4j @RequestMapping("/calendar/*") @AllArgsConstructor public class CalendarController { @GetMapping("/calendarform") public void calendarList(){ } @GetMapping("/calendarform2") public void calendarList2(){ } }
527
0.793169
0.783681
26
19.26923
19.320292
62
false
false
0
0
0
0
0
0
0.653846
false
false
13
57628b61813182c53eb7a6655dee0607b5cb1b13
25,503,515,809,161
76bf35fff53cde4f2b33c1c849f3e4be9a27c34a
/src/main/java/com/duckspot/diar/GoogleAuthCallbackServlet.java
687932b26d3a7de701eb3b2ab6c539d2297592a0
[]
no_license
duckspot/ducks-in-a-row
https://github.com/duckspot/ducks-in-a-row
a9f225fd474147520c18ae82345c87fae2c5fb06
d742d418f5230b9f1a9890b9e1f07ac13722b67e
refs/heads/master
2020-12-24T15:49:18.013000
2013-10-25T04:24:14
2013-10-25T04:24:14
12,601,238
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* dair/src/com/duckspot/dair/GoogleAuthCallbackServlet.java * * History: * 4/ 6/13 PD * 4/ 9/13 PD add call to googleAuth.setRedirectURI() * 4/12/13 PD updated nextURL code to use OAUTH2 scope as nextURL * 4/12/13 PD better error handling */ package com.duckspot.diar; import com.duckspot.diar.model.GoogleAuth; import com.duckspot.diar.model.Settings; import com.duckspot.diar.model.SettingsDAO; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Receives authorization to access Google account information. * */ public class GoogleAuthCallbackServlet extends AbstractServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { checkSecurity(request); Settings settings = (Settings)request.getAttribute("settings"); SettingsDAO settingsDAO = (SettingsDAO)request.getAttribute("settingsDAO"); // errors forward to backURL // success redirects to nextURL String[] s = request.getParameter("state").split("::"); String backURL = s[0]; String nextURL = s[1]; // error messages collected in this map Map<String,String> errors = new HashMap<String,String>(); // deal with error from OAUTH2 String error = request.getParameter("error"); if (error != null) { // send errors attribute to backURL errors.put("top","Google Authorization Error: "+error); request.setAttribute("errors",errors); if (backURL != null) { request.getRequestDispatcher(backURL) .forward(request, response); } throw new Error(errors.get("top")); } // get authorization from Google GoogleAuth googleAuth = settings.getGoogleAuth(); googleAuth.setRedirectURI(getServerURL(request) + "/oauth2callback"); error = googleAuth.requestAuthTokens(request.getParameter("code")); if (error != null) { // send errors attribute to backURL errors.put("top","Google Authorization Token Request Error: "+error); request.setAttribute("errors",errors); if (backURL != null) { request.getRequestDispatcher(backURL) .forward(request, response); } throw new Error(errors.get("top")); } // write settings (they have a copy of approved GoogleAuthScope) settingsDAO.put(settings); response.sendRedirect(nextURL); } }
UTF-8
Java
2,882
java
GoogleAuthCallbackServlet.java
Java
[]
null
[]
/* dair/src/com/duckspot/dair/GoogleAuthCallbackServlet.java * * History: * 4/ 6/13 PD * 4/ 9/13 PD add call to googleAuth.setRedirectURI() * 4/12/13 PD updated nextURL code to use OAUTH2 scope as nextURL * 4/12/13 PD better error handling */ package com.duckspot.diar; import com.duckspot.diar.model.GoogleAuth; import com.duckspot.diar.model.Settings; import com.duckspot.diar.model.SettingsDAO; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Receives authorization to access Google account information. * */ public class GoogleAuthCallbackServlet extends AbstractServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { checkSecurity(request); Settings settings = (Settings)request.getAttribute("settings"); SettingsDAO settingsDAO = (SettingsDAO)request.getAttribute("settingsDAO"); // errors forward to backURL // success redirects to nextURL String[] s = request.getParameter("state").split("::"); String backURL = s[0]; String nextURL = s[1]; // error messages collected in this map Map<String,String> errors = new HashMap<String,String>(); // deal with error from OAUTH2 String error = request.getParameter("error"); if (error != null) { // send errors attribute to backURL errors.put("top","Google Authorization Error: "+error); request.setAttribute("errors",errors); if (backURL != null) { request.getRequestDispatcher(backURL) .forward(request, response); } throw new Error(errors.get("top")); } // get authorization from Google GoogleAuth googleAuth = settings.getGoogleAuth(); googleAuth.setRedirectURI(getServerURL(request) + "/oauth2callback"); error = googleAuth.requestAuthTokens(request.getParameter("code")); if (error != null) { // send errors attribute to backURL errors.put("top","Google Authorization Token Request Error: "+error); request.setAttribute("errors",errors); if (backURL != null) { request.getRequestDispatcher(backURL) .forward(request, response); } throw new Error(errors.get("top")); } // write settings (they have a copy of approved GoogleAuthScope) settingsDAO.put(settings); response.sendRedirect(nextURL); } }
2,882
0.619709
0.611728
81
34.580246
23.122253
81
false
false
0
0
0
0
0
0
0.506173
false
false
13
7106951fdced24c75f5a39acf94333d42b71f448
24,464,133,771,810
8bae441ba11ea6b0347a847e9423648c6a2362e5
/LibraryManagementSystem2/src/main/java/org/lms/service/ReservationServiceImpl.java
8544785b644fb734d463114950dba8b6aaf3d900
[]
no_license
fotionkonomi/LibraryInternship
https://github.com/fotionkonomi/LibraryInternship
e50a9e9fc5a1ad127aa21656bcb5f29411582997
4eef26454573716fd8faf1596d8f2cf443db2c65
refs/heads/master
2020-04-18T12:56:57.791000
2019-02-20T16:11:52
2019-02-20T16:11:52
167,549,051
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.lms.service; import java.util.ArrayList; import java.util.List; import org.lms.dao.ReservationDAO; import org.lms.dto.BookDTO; import org.lms.dto.UserDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class ReservationServiceImpl implements ReservationService { @Autowired private ReservationDAO reservationDAO; @Autowired private BookService bookService; @Override public void bookReservation(BookDTO bookDTO, UserDTO userDTO) { this.reservationDAO.bookReservation(bookDTO, userDTO); } @Override public void bookDelivering(BookDTO bookDTO) { this.reservationDAO.bookDelivering(bookDTO); } @Override public void bookFree(BookDTO bookDTO) { this.reservationDAO.bookFree(bookDTO); } @Override public UserDTO getUserThatHasBookedTheBook(BookDTO bookDTO) { return reservationDAO.getUserThatHasBookedTheBook(bookDTO); } @Override public UserDTO getUserThatTheBookIsDelivered(BookDTO bookDTO) { return reservationDAO.getUserThatTheBookIsDelivered(bookDTO); } public ReservationDAO getReservationDAO() { return reservationDAO; } public void setReservationDAO(ReservationDAO reservationDAO) { this.reservationDAO = reservationDAO; } @Override public List<BookDTO> booksReservation(List<BookDTO> booksDTO, UserDTO userDTO) { List<BookDTO> allBooksFree = bookService.getBookFree(); List<BookDTO> booksNotReserved = new ArrayList<>(); for (BookDTO bookSelected : booksDTO) { if (!allBooksFree.contains(bookSelected)) { booksNotReserved.add(bookSelected); } else { bookReservation(bookSelected, userDTO); } } return booksNotReserved; } public BookService getBookService() { return bookService; } public void setBookService(BookService bookService) { this.bookService = bookService; } @Override public boolean isBookFree(BookDTO bookDTO) { return reservationDAO.isBookFree(bookDTO); } }
UTF-8
Java
2,128
java
ReservationServiceImpl.java
Java
[]
null
[]
package org.lms.service; import java.util.ArrayList; import java.util.List; import org.lms.dao.ReservationDAO; import org.lms.dto.BookDTO; import org.lms.dto.UserDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class ReservationServiceImpl implements ReservationService { @Autowired private ReservationDAO reservationDAO; @Autowired private BookService bookService; @Override public void bookReservation(BookDTO bookDTO, UserDTO userDTO) { this.reservationDAO.bookReservation(bookDTO, userDTO); } @Override public void bookDelivering(BookDTO bookDTO) { this.reservationDAO.bookDelivering(bookDTO); } @Override public void bookFree(BookDTO bookDTO) { this.reservationDAO.bookFree(bookDTO); } @Override public UserDTO getUserThatHasBookedTheBook(BookDTO bookDTO) { return reservationDAO.getUserThatHasBookedTheBook(bookDTO); } @Override public UserDTO getUserThatTheBookIsDelivered(BookDTO bookDTO) { return reservationDAO.getUserThatTheBookIsDelivered(bookDTO); } public ReservationDAO getReservationDAO() { return reservationDAO; } public void setReservationDAO(ReservationDAO reservationDAO) { this.reservationDAO = reservationDAO; } @Override public List<BookDTO> booksReservation(List<BookDTO> booksDTO, UserDTO userDTO) { List<BookDTO> allBooksFree = bookService.getBookFree(); List<BookDTO> booksNotReserved = new ArrayList<>(); for (BookDTO bookSelected : booksDTO) { if (!allBooksFree.contains(bookSelected)) { booksNotReserved.add(bookSelected); } else { bookReservation(bookSelected, userDTO); } } return booksNotReserved; } public BookService getBookService() { return bookService; } public void setBookService(BookService bookService) { this.bookService = bookService; } @Override public boolean isBookFree(BookDTO bookDTO) { return reservationDAO.isBookFree(bookDTO); } }
2,128
0.757519
0.757519
84
23.333334
23.35713
81
false
false
0
0
0
0
0
0
1.309524
false
false
13
946e152224dae04330385dcbea79edeca3ac7b46
10,153,302,690,295
e2050137a3e5128c9a759da7b88d88e79c654f97
/plugin/org/vcssl/connect/ArrayDataContainerInterface1.java
7b7ee0dd5520ec2fb854a7b04e74c6ef506fa9a3
[ "CC0-1.0" ]
permissive
RINEARN/vnano-plugin
https://github.com/RINEARN/vnano-plugin
81f2e3508ece4ccb652596108ed25b83782a26ef
3783cf837143c244410b22eafd73c3054cb988d0
refs/heads/master
2020-07-09T22:12:55.668000
2020-07-05T16:42:55
2020-07-05T16:42:55
204,094,838
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * ================================================== * Array Data Container Interface 1 (ADCI 1) * ( for VCSSL / Vnano Plug-in Development ) * -------------------------------------------------- * This file is released under CC0. * Written in 2017-2020 by RINEARN (Fumihiro Matsui) * ================================================== */ package org.vcssl.connect; /** * <p> * ADCI 1 (Array Data Container Interface 1) 形式のデータコンテナ・インターフェースです。 * </p> * * <p> * <span style="font-weight: bold;"> * ※ このインターフェースは未確定であり、 * このインターフェースをサポートする処理系が正式にリリースされるまでの間、 * 一部仕様が変更される可能性があります。 * </span> * </p> * * <p> * ここでのデータコンテナとは、処理系内部や内外でデータをやり取りする単位として、 * データを格納する事を目的としたオブジェクトの事を指します。 * このデータコンテナ・インターフェースは、言語処理系と、処理系外部のプラグインとの間で、 * 多次元配列データを直接的に(変換などを行わずに)やり取りしたい場合などに使用します。 * </p> * * <p> * 外部変数や外部関数のプラグインはホスト言語で実装されるため、 * ホスト言語とスクリプト言語との間におけるデータ型の違いや、 * 処理系内部でのデータの扱いの違いなどを、どこかで吸収する必要があります。 * 通常、プラグイン側はホスト言語のデータ型のみを用いて開発され、 * そのようなデータ変換などは処理系側において自動的に行われます。 * </p> * * <p> * しかし、オーバーヘッドを避けるためなどの理由で、 * 自動のデータ変換を利用しない場合(プラグイン開発の際に任意に選択できます)、 * プラグイン側は、処理系側の内部で使用されるデータコンテナの形式で、 * データを受け渡しする必要があります。 * その形式は処理系に依存しますが、このインターフェースは、 * 主にベクトル演算ベースの処理系の内部で使用されるデータコンテナの仕様を、 * プラグインの再利用性を確保するために抽象化して定義したものです。 * </p> * * <p> * 現時点では、このインターフェースは * Vnano (VCSSL nano) 処理系の内部でのデータコンテナ形式において使用されています。 * Vnano 処理系は仮想プロセッサ(いわゆるVM)がベクトル演算主体の設計であり、 * レジスタや仮想メモリーのデータ単位が全て配列であるため、 * スカラも含めたあらゆるデータにおいて、このインターフェースを実装したデータコンテナが使用されます。 * 従って、Vnano用のプラグイン開発において、自動のデータ変換を利用しない場合、 * このインターフェースを実装したデータコンテナによって、 * 引数や戻り値などのデータをやり取りします。 * </p> * * <p> * データの格納のされ方などの詳細については、具体的な実装を交えた説明の方が適しているため、 * Vnano のスクリプトエンジン実装における org.vcssl.nano.vm.memory.DataContainer * クラスの説明などを参照してください。 * </p> * * @param <T> 保持するデータの型 * @author RINEARN (Fumihiro Matsui) */ public interface ArrayDataContainerInterface1<T> { /** 動的ロード時などに処理系側から参照される、インターフェースの形式名(値は"ADCI")です。*/ public static String INTERFACE_TYPE = "ADCI"; /** 動的ロード時などに処理系側から参照される、インターフェースの世代名(値は"1")です。*/ public static String INTERFACE_GENERATION = "1"; /** * このデータコンテナが格納するデータをスカラ値と見なしたい場合において、 * そのスカラ値を中に含んでいる配列データと、 * その中でスカラ値が保持されているオフセット値を指定します。 * * オフセット値とは、データコンテナが内部で保持している配列データ内において、 * スカラ値が格納されている要素のインデックスを意味します。 * * このデータコンテナの仕様は、 * 内部でデータを1次元配列として保持する事を前提としているため、 * 引数 data には常に1次元配列を渡す必要があります。 * * データコンテナが保持する設定値の組み合わせが、瞬間的にでも不整合な状態になる事を防ぐため、 * オフセット値(引数offset)のみを設定するメソッドは提供されません。 * * @param data 格納するデータ(1次元配列) * @param offset オフセット値(データ内でスカラ値が存在する配列インデックス) */ public abstract void setData(T data, int offset); /** * 格納するデータを、次元ごとの長さ情報と共に設定します。 * * このデータコンテナの仕様は、 * 内部でデータを1次元配列として保持する事を前提としているため、 * 引数 data には常に1次元配列を渡す必要があります。 * * 多次元配列は、右端次元の要素が連続的に並ぶように1次元化した配列を * 引数 data に渡してください。 * スカラは、要素数1の配列とするか、より大きな配列のどこかに格納した上で、 * このメソッドの代わりに * {@link ArrayDataContainerInterface1#setData(Object, int) setData(T, int)} * メソッドでそのインデックスを指定してください。 * * 引数 lengths には、次元ごとの長さを格納する配列を指定してください。 * 要素の順序については、スクリプト言語内での多次元配列との対応において、 * 左端次元の要素数を[0]番要素、その一つ右隣りにある次元の要素数を[1]番要素 ... * という順で格納してください。 * また、このデータコンテナの保持データをスカラ値として扱わせたい場合は、 * 引数 lengths には要素数0の配列を指定してください(つまりスカラは0次元の配列と見なします)。 * * データコンテナが保持する設定値の組み合わせが、瞬間的にでも不整合な状態になる事を防ぐため、 * 次元ごとの長さ情報(引数 lengths)のみを設定するメソッドは提供されません。 * * @param data 格納するデータ(1次元配列) * @param lengths 次元ごとの長さを格納する配列 */ public abstract void setData(T data, int[] lengths); /** * 格納されているデータを取得します。 * * このデータコンテナの仕様は、 * 内部でデータを1次元配列として保持する事を前提としているため、 * 戻り値は1次元配列として返されます。 * * 多次元配列は、右端次元の要素が連続的に並ぶように1次元化されます。 * スカラは、要素数1の配列として返されるか、 * またはより大きな配列のどこかに格納した上で返され、後者の場合は * {@link ArrayDataContainerInterface1#getOffset getOffset} * メソッドでそのインデックスを取得できます。 * * @return 格納されているデータ(1次元配列) */ public abstract T getData(); /** * 格納されているデータをスカラ値と見なす場合における、オフセット値を取得します。 * * オフセット値とは、データコンテナが内部で保持している配列データ内において、 * スカラ値が格納されている要素のインデックスを意味します。 * この仕様は、ベクトル演算ベースの処理系において、 * 配列ベースのデータコンテナでスカラデータを効率的に扱うためのものです。 * * なお、データコンテナが保持する設定値の組み合わせが、瞬間的にでも不整合な状態になる事を防ぐため、 * オフセット値のみを設定するメソッドは提供されません。 * 設定したい場合は {@link ArrayDataContainerInterface1#setData(Object, int) setData(T, int) } * メソッドを使用して、データと共に設定してください。 * * @return スカラデータの配列内位置を示すオフセット値 */ public abstract int getOffset(); /** * 多次元配列の次元ごとの長さを取得します。 * * なお、データコンテナが保持する設定値の組み合わせが、瞬間的にでも不整合な状態になる事を防ぐため、 * 次元ごとの長さのみを設定するメソッドは提供されません。 * 設定したい場合は {@link ArrayDataContainerInterface1#setData(Object, int[]) setData(T, int[]) } * メソッドを使用して、データと共に設定してください。 * * @return 次元ごとの長さを格納する配列 */ public abstract int[] getLengths(); /** * サイズを取得します。 * * ここでのサイズとは、多次元配列における総要素数の事です。 * 具体的には、データがスカラではない場合には、サイズは * {@link ArrayDataContainerInterface1#getLengths getLengths} * メソッドで取得できる次元長配列の、全要素の積に一致します。 * * データがスカラである場合には、サイズは常に 1 となります。 * 仮に {@link ArrayDataContainerInterface1#getData getData} * メソッドで取得したデータの配列の要素数が 1 よりも大きく * その配列内に要素として(オフセット値で指定される位置に) * スカラ値が格納されている場合でも、 * このメソッドで返されるサイズは 1 になります。 * * サイズとデータの要素数を独立に設定する事はできないため、 * サイズの setter はありません。 * 設定したい場合は {@link ArrayDataContainerInterface1#setData(Object, int[]) setData(T, int[]) } * メソッドなどを使用して、データおよび次元ごとの長さ情報と共に設定してください。 * * @return サイズ */ public abstract int getSize(); /** * 多次元配列の次元数(次元の総数)を取得します。 * * 具体的には、{@link ArrayDataContainerInterface1#getLengths getLengths} * メソッドで取得できる次元長配列の、要素数に一致します。 * * 次元数と、次元ごとの長さを独立に設定する事はできないため、 * 次元数の setter はありません。 * 設定したい場合は {@link ArrayDataContainerInterface1#setData(Object, int[]) setData(T, int[]) } * メソッドなどを使用して、データおよび次元ごとの長さ情報と共に設定してください。 * * @return 次元数 */ public abstract int getRank(); }
UTF-8
Java
11,708
java
ArrayDataContainerInterface1.java
Java
[ { "context": "is released under CC0.\r\n * Written in 2017-2020 by RINEARN (Fumihiro Matsui)\r\n * ===========================", "end": 277, "score": 0.9571084976196289, "start": 270, "tag": "USERNAME", "value": "RINEARN" }, { "context": "d under CC0.\r\n * Written in 2017-2020 by RINEARN (Fumihiro Matsui)\r\n * ============================================", "end": 294, "score": 0.9998809695243835, "start": 279, "tag": "NAME", "value": "Fumihiro Matsui" }, { "context": "\r\n * </p>\r\n *\r\n * @param <T> 保持するデータの型\r\n * @author RINEARN (Fumihiro Matsui)\r\n */\r\npublic interface ArrayDat", "end": 1842, "score": 0.9928607940673828, "start": 1835, "tag": "NAME", "value": "RINEARN" }, { "context": "\n *\r\n * @param <T> 保持するデータの型\r\n * @author RINEARN (Fumihiro Matsui)\r\n */\r\npublic interface ArrayDataContainer", "end": 1852, "score": 0.996845006942749, "start": 1844, "tag": "NAME", "value": "Fumihiro" } ]
null
[]
/* * ================================================== * Array Data Container Interface 1 (ADCI 1) * ( for VCSSL / Vnano Plug-in Development ) * -------------------------------------------------- * This file is released under CC0. * Written in 2017-2020 by RINEARN (<NAME>) * ================================================== */ package org.vcssl.connect; /** * <p> * ADCI 1 (Array Data Container Interface 1) 形式のデータコンテナ・インターフェースです。 * </p> * * <p> * <span style="font-weight: bold;"> * ※ このインターフェースは未確定であり、 * このインターフェースをサポートする処理系が正式にリリースされるまでの間、 * 一部仕様が変更される可能性があります。 * </span> * </p> * * <p> * ここでのデータコンテナとは、処理系内部や内外でデータをやり取りする単位として、 * データを格納する事を目的としたオブジェクトの事を指します。 * このデータコンテナ・インターフェースは、言語処理系と、処理系外部のプラグインとの間で、 * 多次元配列データを直接的に(変換などを行わずに)やり取りしたい場合などに使用します。 * </p> * * <p> * 外部変数や外部関数のプラグインはホスト言語で実装されるため、 * ホスト言語とスクリプト言語との間におけるデータ型の違いや、 * 処理系内部でのデータの扱いの違いなどを、どこかで吸収する必要があります。 * 通常、プラグイン側はホスト言語のデータ型のみを用いて開発され、 * そのようなデータ変換などは処理系側において自動的に行われます。 * </p> * * <p> * しかし、オーバーヘッドを避けるためなどの理由で、 * 自動のデータ変換を利用しない場合(プラグイン開発の際に任意に選択できます)、 * プラグイン側は、処理系側の内部で使用されるデータコンテナの形式で、 * データを受け渡しする必要があります。 * その形式は処理系に依存しますが、このインターフェースは、 * 主にベクトル演算ベースの処理系の内部で使用されるデータコンテナの仕様を、 * プラグインの再利用性を確保するために抽象化して定義したものです。 * </p> * * <p> * 現時点では、このインターフェースは * Vnano (VCSSL nano) 処理系の内部でのデータコンテナ形式において使用されています。 * Vnano 処理系は仮想プロセッサ(いわゆるVM)がベクトル演算主体の設計であり、 * レジスタや仮想メモリーのデータ単位が全て配列であるため、 * スカラも含めたあらゆるデータにおいて、このインターフェースを実装したデータコンテナが使用されます。 * 従って、Vnano用のプラグイン開発において、自動のデータ変換を利用しない場合、 * このインターフェースを実装したデータコンテナによって、 * 引数や戻り値などのデータをやり取りします。 * </p> * * <p> * データの格納のされ方などの詳細については、具体的な実装を交えた説明の方が適しているため、 * Vnano のスクリプトエンジン実装における org.vcssl.nano.vm.memory.DataContainer * クラスの説明などを参照してください。 * </p> * * @param <T> 保持するデータの型 * @author RINEARN (Fumihiro Matsui) */ public interface ArrayDataContainerInterface1<T> { /** 動的ロード時などに処理系側から参照される、インターフェースの形式名(値は"ADCI")です。*/ public static String INTERFACE_TYPE = "ADCI"; /** 動的ロード時などに処理系側から参照される、インターフェースの世代名(値は"1")です。*/ public static String INTERFACE_GENERATION = "1"; /** * このデータコンテナが格納するデータをスカラ値と見なしたい場合において、 * そのスカラ値を中に含んでいる配列データと、 * その中でスカラ値が保持されているオフセット値を指定します。 * * オフセット値とは、データコンテナが内部で保持している配列データ内において、 * スカラ値が格納されている要素のインデックスを意味します。 * * このデータコンテナの仕様は、 * 内部でデータを1次元配列として保持する事を前提としているため、 * 引数 data には常に1次元配列を渡す必要があります。 * * データコンテナが保持する設定値の組み合わせが、瞬間的にでも不整合な状態になる事を防ぐため、 * オフセット値(引数offset)のみを設定するメソッドは提供されません。 * * @param data 格納するデータ(1次元配列) * @param offset オフセット値(データ内でスカラ値が存在する配列インデックス) */ public abstract void setData(T data, int offset); /** * 格納するデータを、次元ごとの長さ情報と共に設定します。 * * このデータコンテナの仕様は、 * 内部でデータを1次元配列として保持する事を前提としているため、 * 引数 data には常に1次元配列を渡す必要があります。 * * 多次元配列は、右端次元の要素が連続的に並ぶように1次元化した配列を * 引数 data に渡してください。 * スカラは、要素数1の配列とするか、より大きな配列のどこかに格納した上で、 * このメソッドの代わりに * {@link ArrayDataContainerInterface1#setData(Object, int) setData(T, int)} * メソッドでそのインデックスを指定してください。 * * 引数 lengths には、次元ごとの長さを格納する配列を指定してください。 * 要素の順序については、スクリプト言語内での多次元配列との対応において、 * 左端次元の要素数を[0]番要素、その一つ右隣りにある次元の要素数を[1]番要素 ... * という順で格納してください。 * また、このデータコンテナの保持データをスカラ値として扱わせたい場合は、 * 引数 lengths には要素数0の配列を指定してください(つまりスカラは0次元の配列と見なします)。 * * データコンテナが保持する設定値の組み合わせが、瞬間的にでも不整合な状態になる事を防ぐため、 * 次元ごとの長さ情報(引数 lengths)のみを設定するメソッドは提供されません。 * * @param data 格納するデータ(1次元配列) * @param lengths 次元ごとの長さを格納する配列 */ public abstract void setData(T data, int[] lengths); /** * 格納されているデータを取得します。 * * このデータコンテナの仕様は、 * 内部でデータを1次元配列として保持する事を前提としているため、 * 戻り値は1次元配列として返されます。 * * 多次元配列は、右端次元の要素が連続的に並ぶように1次元化されます。 * スカラは、要素数1の配列として返されるか、 * またはより大きな配列のどこかに格納した上で返され、後者の場合は * {@link ArrayDataContainerInterface1#getOffset getOffset} * メソッドでそのインデックスを取得できます。 * * @return 格納されているデータ(1次元配列) */ public abstract T getData(); /** * 格納されているデータをスカラ値と見なす場合における、オフセット値を取得します。 * * オフセット値とは、データコンテナが内部で保持している配列データ内において、 * スカラ値が格納されている要素のインデックスを意味します。 * この仕様は、ベクトル演算ベースの処理系において、 * 配列ベースのデータコンテナでスカラデータを効率的に扱うためのものです。 * * なお、データコンテナが保持する設定値の組み合わせが、瞬間的にでも不整合な状態になる事を防ぐため、 * オフセット値のみを設定するメソッドは提供されません。 * 設定したい場合は {@link ArrayDataContainerInterface1#setData(Object, int) setData(T, int) } * メソッドを使用して、データと共に設定してください。 * * @return スカラデータの配列内位置を示すオフセット値 */ public abstract int getOffset(); /** * 多次元配列の次元ごとの長さを取得します。 * * なお、データコンテナが保持する設定値の組み合わせが、瞬間的にでも不整合な状態になる事を防ぐため、 * 次元ごとの長さのみを設定するメソッドは提供されません。 * 設定したい場合は {@link ArrayDataContainerInterface1#setData(Object, int[]) setData(T, int[]) } * メソッドを使用して、データと共に設定してください。 * * @return 次元ごとの長さを格納する配列 */ public abstract int[] getLengths(); /** * サイズを取得します。 * * ここでのサイズとは、多次元配列における総要素数の事です。 * 具体的には、データがスカラではない場合には、サイズは * {@link ArrayDataContainerInterface1#getLengths getLengths} * メソッドで取得できる次元長配列の、全要素の積に一致します。 * * データがスカラである場合には、サイズは常に 1 となります。 * 仮に {@link ArrayDataContainerInterface1#getData getData} * メソッドで取得したデータの配列の要素数が 1 よりも大きく * その配列内に要素として(オフセット値で指定される位置に) * スカラ値が格納されている場合でも、 * このメソッドで返されるサイズは 1 になります。 * * サイズとデータの要素数を独立に設定する事はできないため、 * サイズの setter はありません。 * 設定したい場合は {@link ArrayDataContainerInterface1#setData(Object, int[]) setData(T, int[]) } * メソッドなどを使用して、データおよび次元ごとの長さ情報と共に設定してください。 * * @return サイズ */ public abstract int getSize(); /** * 多次元配列の次元数(次元の総数)を取得します。 * * 具体的には、{@link ArrayDataContainerInterface1#getLengths getLengths} * メソッドで取得できる次元長配列の、要素数に一致します。 * * 次元数と、次元ごとの長さを独立に設定する事はできないため、 * 次元数の setter はありません。 * 設定したい場合は {@link ArrayDataContainerInterface1#setData(Object, int[]) setData(T, int[]) } * メソッドなどを使用して、データおよび次元ごとの長さ情報と共に設定してください。 * * @return 次元数 */ public abstract int getRank(); }
11,699
0.69186
0.684166
221
24.461538
20.689356
91
false
false
0
0
0
0
0
0
0.696833
false
false
13
75ce11c7234986440977208672bdd8c282025f2c
12,575,664,306,570
afdd0c6ae5a02be441d29087548027283d67e7cb
/src/game/GameSettings/Loading.java
e0a32a5d4c5584d5846fe850bab82837e8774019
[]
no_license
georgecity/Ninja-Game
https://github.com/georgecity/Ninja-Game
cc72f782dde0d663a2ea52444292a71333aae2ca
0ad6e7767795658d6e364cee267d4499ae0d7485
refs/heads/master
2021-01-03T14:06:21.487000
2020-02-13T14:31:10
2020-02-13T14:31:10
240,096,596
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package game.GameSettings; import game.GAMEPANEL.Game; import org.jbox2d.common.Vec2; import java.io.*; /** * Handles Loading and Demonstrates how player data can be read from a text * file and printed to the terminal. */ public class Loading { private String fileName; private Game game; /** * Initialise a new Loading reader * @param fileName the name of the Loading file */ public Loading(String fileName, Game game) { this.fileName = fileName; this.game = game; } /** * Read the player data from the Saving file and print it to * the terminal window. */ public void readScores() throws Exceptions { // FileReader fr = null; // BufferedReader reader = null; try { FileReader fr = new FileReader(fileName); BufferedReader br = new BufferedReader(fr); String line = br.readLine(); if (line == null) { throw new Exceptions("no data in the file"); } else { String[] split = line.split(","); if (split.length != 6) { throw new Exceptions("line needs 3 items"); } else { String playerName = split[0]; int score = 0; float posX = 0; float posY = 0; String level = split[5]; int HP = 0; try { score = Integer.parseInt(split[1]); } catch (NumberFormatException e) { throw new Exceptions("third item needs to be a number"); } try { posX = Float.parseFloat(split[2]); } catch (NumberFormatException e) { throw new Exceptions("third item needs to be a number"); } try { posY = Float.parseFloat(split[3]); } catch (NumberFormatException e) { throw new Exceptions("third item needs to be a number"); } try { HP = Integer.parseInt(split[4]); } catch (NumberFormatException e) { throw new Exceptions("third item needs to be a number"); } game.lvlNumber(Integer.parseInt(level)); game.getNinjaPlayer().setPosition(new Vec2(posX, posY)); game.getNinjaPlayer().setHealth(HP); System.out.println(game.getNinjaPlayer().getHealth()); } } }catch (FileNotFoundException e){ throw new Exceptions("file does not exists"); }catch (IOException e){ e.printStackTrace(); } } } // try { // System.out.println("Reading " + fileName + " ..."); // fr = new FileReader(fileName); // reader = new BufferedReader(fr); // String line = reader.readLine(); // // if (line == null){ // } // while (line != null) { // // file is assumed to contain one name, score pair per line // String[] tokens = line.split(","); // String name = tokens[0]; // int score = Integer.parseInt(tokens[1]); // System.out.println("Name: " + name + ", Score: " + score); // line = reader.readLine(); // } // System.out.println("...done."); // } finally { // if (reader != null) { // reader.close(); // } // if (fr != null) { // fr.close(); // } // }
UTF-8
Java
3,845
java
Loading.java
Java
[]
null
[]
package game.GameSettings; import game.GAMEPANEL.Game; import org.jbox2d.common.Vec2; import java.io.*; /** * Handles Loading and Demonstrates how player data can be read from a text * file and printed to the terminal. */ public class Loading { private String fileName; private Game game; /** * Initialise a new Loading reader * @param fileName the name of the Loading file */ public Loading(String fileName, Game game) { this.fileName = fileName; this.game = game; } /** * Read the player data from the Saving file and print it to * the terminal window. */ public void readScores() throws Exceptions { // FileReader fr = null; // BufferedReader reader = null; try { FileReader fr = new FileReader(fileName); BufferedReader br = new BufferedReader(fr); String line = br.readLine(); if (line == null) { throw new Exceptions("no data in the file"); } else { String[] split = line.split(","); if (split.length != 6) { throw new Exceptions("line needs 3 items"); } else { String playerName = split[0]; int score = 0; float posX = 0; float posY = 0; String level = split[5]; int HP = 0; try { score = Integer.parseInt(split[1]); } catch (NumberFormatException e) { throw new Exceptions("third item needs to be a number"); } try { posX = Float.parseFloat(split[2]); } catch (NumberFormatException e) { throw new Exceptions("third item needs to be a number"); } try { posY = Float.parseFloat(split[3]); } catch (NumberFormatException e) { throw new Exceptions("third item needs to be a number"); } try { HP = Integer.parseInt(split[4]); } catch (NumberFormatException e) { throw new Exceptions("third item needs to be a number"); } game.lvlNumber(Integer.parseInt(level)); game.getNinjaPlayer().setPosition(new Vec2(posX, posY)); game.getNinjaPlayer().setHealth(HP); System.out.println(game.getNinjaPlayer().getHealth()); } } }catch (FileNotFoundException e){ throw new Exceptions("file does not exists"); }catch (IOException e){ e.printStackTrace(); } } } // try { // System.out.println("Reading " + fileName + " ..."); // fr = new FileReader(fileName); // reader = new BufferedReader(fr); // String line = reader.readLine(); // // if (line == null){ // } // while (line != null) { // // file is assumed to contain one name, score pair per line // String[] tokens = line.split(","); // String name = tokens[0]; // int score = Integer.parseInt(tokens[1]); // System.out.println("Name: " + name + ", Score: " + score); // line = reader.readLine(); // } // System.out.println("...done."); // } finally { // if (reader != null) { // reader.close(); // } // if (fr != null) { // fr.close(); // } // }
3,845
0.460338
0.455917
118
31.59322
23.311172
80
false
false
0
0
0
0
0
0
0.457627
false
false
13
9964f34125db12eec9eafa4951791e7bf341695b
12,575,664,307,286
b963502f99b2bdf059be8f3b50a62dfe8e40dbd9
/wookie/src/test/java/org/apache/wookie/w3c/test/EntityTest.java
c4c3e2984eb5942837d822dce5746cf4aad2da71
[ "Apache-2.0" ]
permissive
obigo-dev6/wookie-parser-for-android
https://github.com/obigo-dev6/wookie-parser-for-android
bfe2a20183e5f6845d63fb275854b88bb64e8b1d
9b6c915f68c3216ad2ad99ba1de0a5ad2c822604
refs/heads/master
2020-04-22T14:00:45.045000
2019-02-13T07:12:05
2019-02-13T07:12:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.wookie.w3c.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.wookie.w3c.IParam; import org.apache.wookie.w3c.IW3CXMLConfiguration; import org.apache.wookie.w3c.exceptions.BadManifestException; import org.apache.wookie.w3c.impl.AuthorEntity; import org.apache.wookie.w3c.impl.ContentEntity; import org.apache.wookie.w3c.impl.DescriptionEntity; import org.apache.wookie.w3c.impl.FeatureEntity; import org.apache.wookie.w3c.impl.IconEntity; import org.apache.wookie.w3c.impl.LicenseEntity; import org.apache.wookie.w3c.impl.NameEntity; import org.apache.wookie.w3c.impl.ParamEntity; import org.apache.wookie.w3c.impl.PreferenceEntity; import org.apache.wookie.w3c.impl.WidgetManifestModel; import org.apache.wookie.w3c.util.FormattingUtils; import org.apache.wookie.w3c.util.LocalizationUtils; import org.apache.wookie.w3c.util.UnicodeUtils; import org.apache.wookie.w3c.util.WidgetPackageUtils; import org.jdom.JDOMException; import org.junit.Test; /** * Tests generic functionality in the w3c.impl package classes, including constructors, getters and setters etc */ public class EntityTest { @Test public void author() { AuthorEntity author = new AuthorEntity("test", "http://test", "test@test.net"); assertEquals("test", author.getAuthorName()); assertEquals("test@test.net", author.getEmail()); assertEquals("http://test", author.getHref()); author.setAuthorName("test2"); author.setEmail("test2@test.net"); author.setHref("http://test2"); assertEquals("test2", author.getAuthorName()); assertEquals("test2@test.net", author.getEmail()); assertEquals("http://test2", author.getHref()); } @Test public void content() { ContentEntity content = new ContentEntity("http://test", "UTF-8", "text/html"); assertEquals("http://test", content.getSrc()); assertEquals("UTF-8", content.getCharSet()); assertEquals("text/html", content.getType()); } @Test public void description() { DescriptionEntity desc = new DescriptionEntity("test", "en"); assertEquals("test", desc.getDescription()); assertEquals("en", desc.getLang()); desc.setDescription("test2"); assertEquals("test2", desc.getDescription()); } @Test public void feature() { FeatureEntity feature = new FeatureEntity("http://test", true); assertEquals("http://test", feature.getName()); assertTrue(feature.isRequired()); assertFalse(feature.hasParams()); ParamEntity param = new ParamEntity("name", "value"); List<IParam> params = new ArrayList<>(); params.add(param); feature = new FeatureEntity("http://test", true, params); assertTrue(feature.hasParams()); feature.setRequired(false); assertFalse(feature.isRequired()); feature.setName("http://test2"); assertEquals("http://test2", feature.getName()); ParamEntity param2 = new ParamEntity(); param2.setName("name2"); param2.setValue("value2"); params.add(param2); assertEquals("name2", param2.getName()); assertEquals("value2", param2.getValue()); feature.setParameters(params); assertEquals(2, feature.getParameters().size()); } @Test public void icon() { IconEntity icon = new IconEntity("test.png", 320, 200); assertEquals(320, icon.getHeight().intValue()); assertEquals(200, icon.getWidth().intValue()); icon.setHeight(800); assertEquals(800, icon.getHeight().intValue()); icon.setWidth(400); assertEquals(400, icon.getWidth().intValue()); icon.setHeight(null); assertNull(icon.getHeight()); } @Test public void license() { LicenseEntity license = new LicenseEntity("test", "http://test", "en", "ltr"); assertEquals("test", license.getLicenseText()); assertEquals("http://test", license.getHref()); assertEquals("en", license.getLang()); assertEquals("ltr", license.getDir()); license.setLicenseText("test2"); assertEquals("test2", license.getLicenseText()); license.setHref("http://test2"); assertEquals("http://test2", license.getHref()); } @Test public void name() { NameEntity name = new NameEntity("test", "tst", "en"); assertEquals("test", name.getName()); assertEquals("tst", name.getShort()); assertEquals("en", name.getLang()); name.setName("test2"); assertEquals("test2", name.getName()); name.setShort("t2"); assertEquals("t2", name.getShort()); } @Test public void preference() { PreferenceEntity pref = new PreferenceEntity(); pref.setReadOnly(true); assertTrue(pref.isReadOnly()); pref.setReadOnly(false); assertFalse(pref.isReadOnly()); } @Test public void widget() throws JDOMException, IOException, BadManifestException { WidgetManifestModel widget = new WidgetManifestModel("<widget xmlns=\"" + IW3CXMLConfiguration.MANIFEST_NAMESPACE + "\"><name>test</name></widget>", null, null, null, null, null); assertNull(widget.getAuthor()); assertEquals("test", widget.getLocalName("en")); assertEquals("floating", widget.getViewModes()); widget = new WidgetManifestModel("<widget xmlns=\"" + IW3CXMLConfiguration.MANIFEST_NAMESPACE + "\" viewmodes=\"fullscreen\"></widget>", null, null, null, null, null); assertNull(widget.getAuthor()); assertEquals(IW3CXMLConfiguration.UNKNOWN, widget.getLocalName("en")); assertEquals("fullscreen", widget.getViewModes()); } @Test public void utils() { UnicodeUtils utils = new UnicodeUtils(); LocalizationUtils lutils = new LocalizationUtils(); FormattingUtils futils = new FormattingUtils(); WidgetPackageUtils wputils = new WidgetPackageUtils(); assertNotNull(utils); assertNotNull(futils); assertNotNull(lutils); assertNotNull(wputils); } }
UTF-8
Java
6,996
java
EntityTest.java
Java
[ { "context": "author = new AuthorEntity(\"test\", \"http://test\", \"test@test.net\");\n assertEquals(\"test\", author.getAuthorN", "end": 2082, "score": 0.9999264478683472, "start": 2069, "tag": "EMAIL", "value": "test@test.net" }, { "context": "\", author.getAuthorName());\n assertEquals(\"test@test.net\", author.getEmail());\n assertEquals(\"http:", "end": 2175, "score": 0.9999263882637024, "start": 2162, "tag": "EMAIL", "value": "test@test.net" }, { "context": " author.getHref());\n author.setAuthorName(\"test2\");\n author.setEmail(\"test2@test.net\");\n ", "end": 2288, "score": 0.9967304468154907, "start": 2283, "tag": "USERNAME", "value": "test2" }, { "context": ".setAuthorName(\"test2\");\n author.setEmail(\"test2@test.net\");\n author.setHref(\"http://test2\");\n ", "end": 2331, "score": 0.999928891658783, "start": 2317, "tag": "EMAIL", "value": "test2@test.net" }, { "context": "\", author.getAuthorName());\n assertEquals(\"test2@test.net\", author.getEmail());\n assertEquals(\"http:", "end": 2466, "score": 0.9999291300773621, "start": 2452, "tag": "EMAIL", "value": "test2@test.net" }, { "context": "uals(\"en\", name.getLang());\n name.setName(\"test2\");\n assertEquals(\"test2\", name.getName());", "end": 5422, "score": 0.9970653057098389, "start": 5417, "tag": "USERNAME", "value": "test2" } ]
null
[]
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.wookie.w3c.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.wookie.w3c.IParam; import org.apache.wookie.w3c.IW3CXMLConfiguration; import org.apache.wookie.w3c.exceptions.BadManifestException; import org.apache.wookie.w3c.impl.AuthorEntity; import org.apache.wookie.w3c.impl.ContentEntity; import org.apache.wookie.w3c.impl.DescriptionEntity; import org.apache.wookie.w3c.impl.FeatureEntity; import org.apache.wookie.w3c.impl.IconEntity; import org.apache.wookie.w3c.impl.LicenseEntity; import org.apache.wookie.w3c.impl.NameEntity; import org.apache.wookie.w3c.impl.ParamEntity; import org.apache.wookie.w3c.impl.PreferenceEntity; import org.apache.wookie.w3c.impl.WidgetManifestModel; import org.apache.wookie.w3c.util.FormattingUtils; import org.apache.wookie.w3c.util.LocalizationUtils; import org.apache.wookie.w3c.util.UnicodeUtils; import org.apache.wookie.w3c.util.WidgetPackageUtils; import org.jdom.JDOMException; import org.junit.Test; /** * Tests generic functionality in the w3c.impl package classes, including constructors, getters and setters etc */ public class EntityTest { @Test public void author() { AuthorEntity author = new AuthorEntity("test", "http://test", "<EMAIL>"); assertEquals("test", author.getAuthorName()); assertEquals("<EMAIL>", author.getEmail()); assertEquals("http://test", author.getHref()); author.setAuthorName("test2"); author.setEmail("<EMAIL>"); author.setHref("http://test2"); assertEquals("test2", author.getAuthorName()); assertEquals("<EMAIL>", author.getEmail()); assertEquals("http://test2", author.getHref()); } @Test public void content() { ContentEntity content = new ContentEntity("http://test", "UTF-8", "text/html"); assertEquals("http://test", content.getSrc()); assertEquals("UTF-8", content.getCharSet()); assertEquals("text/html", content.getType()); } @Test public void description() { DescriptionEntity desc = new DescriptionEntity("test", "en"); assertEquals("test", desc.getDescription()); assertEquals("en", desc.getLang()); desc.setDescription("test2"); assertEquals("test2", desc.getDescription()); } @Test public void feature() { FeatureEntity feature = new FeatureEntity("http://test", true); assertEquals("http://test", feature.getName()); assertTrue(feature.isRequired()); assertFalse(feature.hasParams()); ParamEntity param = new ParamEntity("name", "value"); List<IParam> params = new ArrayList<>(); params.add(param); feature = new FeatureEntity("http://test", true, params); assertTrue(feature.hasParams()); feature.setRequired(false); assertFalse(feature.isRequired()); feature.setName("http://test2"); assertEquals("http://test2", feature.getName()); ParamEntity param2 = new ParamEntity(); param2.setName("name2"); param2.setValue("value2"); params.add(param2); assertEquals("name2", param2.getName()); assertEquals("value2", param2.getValue()); feature.setParameters(params); assertEquals(2, feature.getParameters().size()); } @Test public void icon() { IconEntity icon = new IconEntity("test.png", 320, 200); assertEquals(320, icon.getHeight().intValue()); assertEquals(200, icon.getWidth().intValue()); icon.setHeight(800); assertEquals(800, icon.getHeight().intValue()); icon.setWidth(400); assertEquals(400, icon.getWidth().intValue()); icon.setHeight(null); assertNull(icon.getHeight()); } @Test public void license() { LicenseEntity license = new LicenseEntity("test", "http://test", "en", "ltr"); assertEquals("test", license.getLicenseText()); assertEquals("http://test", license.getHref()); assertEquals("en", license.getLang()); assertEquals("ltr", license.getDir()); license.setLicenseText("test2"); assertEquals("test2", license.getLicenseText()); license.setHref("http://test2"); assertEquals("http://test2", license.getHref()); } @Test public void name() { NameEntity name = new NameEntity("test", "tst", "en"); assertEquals("test", name.getName()); assertEquals("tst", name.getShort()); assertEquals("en", name.getLang()); name.setName("test2"); assertEquals("test2", name.getName()); name.setShort("t2"); assertEquals("t2", name.getShort()); } @Test public void preference() { PreferenceEntity pref = new PreferenceEntity(); pref.setReadOnly(true); assertTrue(pref.isReadOnly()); pref.setReadOnly(false); assertFalse(pref.isReadOnly()); } @Test public void widget() throws JDOMException, IOException, BadManifestException { WidgetManifestModel widget = new WidgetManifestModel("<widget xmlns=\"" + IW3CXMLConfiguration.MANIFEST_NAMESPACE + "\"><name>test</name></widget>", null, null, null, null, null); assertNull(widget.getAuthor()); assertEquals("test", widget.getLocalName("en")); assertEquals("floating", widget.getViewModes()); widget = new WidgetManifestModel("<widget xmlns=\"" + IW3CXMLConfiguration.MANIFEST_NAMESPACE + "\" viewmodes=\"fullscreen\"></widget>", null, null, null, null, null); assertNull(widget.getAuthor()); assertEquals(IW3CXMLConfiguration.UNKNOWN, widget.getLocalName("en")); assertEquals("fullscreen", widget.getViewModes()); } @Test public void utils() { UnicodeUtils utils = new UnicodeUtils(); LocalizationUtils lutils = new LocalizationUtils(); FormattingUtils futils = new FormattingUtils(); WidgetPackageUtils wputils = new WidgetPackageUtils(); assertNotNull(utils); assertNotNull(futils); assertNotNull(lutils); assertNotNull(wputils); } }
6,970
0.66924
0.657519
179
38.083797
27.46229
187
false
false
0
0
0
0
0
0
1.039106
false
false
13
9db21df20bf62cac102a8be7ec19470ba38dcfe6
14,817,637,230,607
bf7b4c21300a8ccebb380e0e0a031982466ccd83
/middlewareConcepts2014-master/Assignment3/lib/jacorb-3.4/src/generated/org/omg/DynamicAny/NameDynAnyPair.java
aa42517a39e6a151655adf8a3e263e97281a3516
[]
no_license
Puriakshat/Tuberlin
https://github.com/Puriakshat/Tuberlin
3fe36b970aabad30ed95e8a07c2f875e4912a3db
28dcf7f7edfe7320c740c306b1c0593a6c1b3115
refs/heads/master
2021-01-19T07:30:16.857000
2014-11-06T18:49:16
2014-11-06T18:49:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.omg.DynamicAny; /** * Generated from IDL struct "NameDynAnyPair". * * @author JacORB IDL compiler V @project.version@ * @version generated at 27-May-2014 20:14:30 */ public final class NameDynAnyPair implements org.omg.CORBA.portable.IDLEntity { /** Serial version UID. */ private static final long serialVersionUID = 1L; public NameDynAnyPair(){} public java.lang.String id = ""; public org.omg.DynamicAny.DynAny value; public NameDynAnyPair(java.lang.String id, org.omg.DynamicAny.DynAny value) { this.id = id; this.value = value; } }
UTF-8
Java
569
java
NameDynAnyPair.java
Java
[]
null
[]
package org.omg.DynamicAny; /** * Generated from IDL struct "NameDynAnyPair". * * @author JacORB IDL compiler V @project.version@ * @version generated at 27-May-2014 20:14:30 */ public final class NameDynAnyPair implements org.omg.CORBA.portable.IDLEntity { /** Serial version UID. */ private static final long serialVersionUID = 1L; public NameDynAnyPair(){} public java.lang.String id = ""; public org.omg.DynamicAny.DynAny value; public NameDynAnyPair(java.lang.String id, org.omg.DynamicAny.DynAny value) { this.id = id; this.value = value; } }
569
0.727592
0.704745
23
23.73913
21.26687
76
false
false
0
0
0
0
0
0
0.869565
false
false
13
4e01dc9c3a7dda6f5350203f11f0a1ce3f22f379
10,050,223,526,185
ed5159d056e98d6715357d0d14a9b3f20b764f89
/src/irvine/oeis/a041/A041689.java
92a8de0f8885137ecc6d61addfa9e8800a344b2d
[]
no_license
flywind2/joeis
https://github.com/flywind2/joeis
c5753169cf562939b04dd246f8a2958e97f74558
e5efd6971a0062ac99f4fae21a7c78c9f9e74fea
refs/heads/master
2020-09-13T18:34:35.080000
2019-11-19T05:40:55
2019-11-19T05:40:55
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package irvine.oeis.a041; // Generated by gen_seq4.pl cfsqden 364 at 2019-07-04 10:59 // DO NOT EDIT here! import irvine.math.z.Z; import irvine.oeis.ContinuedFractionOfSqrtSequence; /** * A041689 Denominators of continued fraction convergents to <code>sqrt(364)</code>. * @author Georg Fischer */ public class A041689 extends ContinuedFractionOfSqrtSequence { /** Construct the sequence. */ public A041689() { super(0, 364); } @Override public Z next() { final Z result = getDenominator(); iterate(); iterateConvergents(); return result; } }
UTF-8
Java
585
java
A041689.java
Java
[ { "context": " convergents to <code>sqrt(364)</code>.\n * @author Georg Fischer\n */\npublic class A041689 extends ContinuedFractio", "end": 298, "score": 0.999862015247345, "start": 285, "tag": "NAME", "value": "Georg Fischer" } ]
null
[]
package irvine.oeis.a041; // Generated by gen_seq4.pl cfsqden 364 at 2019-07-04 10:59 // DO NOT EDIT here! import irvine.math.z.Z; import irvine.oeis.ContinuedFractionOfSqrtSequence; /** * A041689 Denominators of continued fraction convergents to <code>sqrt(364)</code>. * @author <NAME> */ public class A041689 extends ContinuedFractionOfSqrtSequence { /** Construct the sequence. */ public A041689() { super(0, 364); } @Override public Z next() { final Z result = getDenominator(); iterate(); iterateConvergents(); return result; } }
578
0.695727
0.620513
26
21.5
21.510731
84
false
false
0
0
0
0
0
0
0.346154
false
false
13
89403cc8cd528c971bffe2685cd438e4a429fb13
24,120,536,393,359
b09b2456d10172767aebbf191e37492fc3cc29df
/src/nineteen/lesson/LessonNineteen.java
4b3d4c9c078c72d29098f773dc4c01de99427dc1
[]
no_license
GrafMKristo/DerekBanasJavaTutorial
https://github.com/GrafMKristo/DerekBanasJavaTutorial
674387791e5a503db00065bd96106600535a85ce
c274b7c8cb0538f182ac19138ce08b029528b8b5
refs/heads/master
2021-02-09T17:09:23.923000
2020-03-12T05:18:59
2020-03-12T05:18:59
244,305,549
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package nineteen.lesson; import java.util.regex.Matcher; import java.util.regex.Pattern; public class LessonNineteen { public static void main(String[] args) { String longString = " Derek Banas CA 12345 PA AL (412)555-1212 CTjohnsmith@hotmail.comAZ 412-555-1234 412 555-1234"; String strangeString = "17 AAA **** *** {{{ {{ { "; System.out.println("----------- WORD 2 TO 20 CHARS"); // [A-Za-z]{2,20} or \\w{2,20} //regexChecker("\\s[A-Za-z]{2,20}\\s", longString); System.out.println("----------- ZIP code 5 digits long"); //regexChecker("\\s\\d{5}\\s", longString); System.out.println("----------- States starting with A or C"); //regexChecker("A[KLRZ]|C[AOT]", longString); // {5,} - only minimum bounds // + - one or more time // .^*+?{}[]\|() - symbols to be backslashed // stars, brackets //regexChecker("\\{{2,}", strangeString); // zero or more times //regexChecker("[A-Za-z0-9._%-]+@[A-Za-z0-9._-]+\\.[A-Za-z]{2,4}", longString); //different phones //regexChecker("([0-9]( |-)?)?(\\(?[0-9]{3}\\)?|[0-9]{3})( |-)?([0-9]{3}( |-)?)([0-9]{4}|[a-zA-Z0-9]{7})", longString); regexReplace(longString); } public static void regexChecker(String theRegex, String str2chk) { Pattern checkRegex = Pattern.compile(theRegex); Matcher regexMatcher = checkRegex.matcher(str2chk); while (regexMatcher.find()) { if (regexMatcher.group().length() != 0) { System.out.println(regexMatcher.group().trim()); } System.out.println("start index: " + regexMatcher.start()); System.out.println("End index: " + regexMatcher.end()); } } public static void regexReplace(String str2Replace) { Pattern replace = Pattern.compile("\\s+"); Matcher regexMatcher = replace.matcher(str2Replace.trim()); System.out.println(regexMatcher.replaceAll(", ")); } }
UTF-8
Java
2,046
java
LessonNineteen.java
Java
[ { "context": "tring = \" Derek Banas CA 12345 PA AL (412)555-1212 CTjohnsmith@hotmail.comAZ 412-555-1234 412 555-1234\";\n String stra", "end": 261, "score": 0.9996059536933899, "start": 238, "tag": "EMAIL", "value": "CTjohnsmith@hotmail.com" } ]
null
[]
package nineteen.lesson; import java.util.regex.Matcher; import java.util.regex.Pattern; public class LessonNineteen { public static void main(String[] args) { String longString = " Derek Banas CA 12345 PA AL (412)555-1212 <EMAIL>AZ 412-555-1234 412 555-1234"; String strangeString = "17 AAA **** *** {{{ {{ { "; System.out.println("----------- WORD 2 TO 20 CHARS"); // [A-Za-z]{2,20} or \\w{2,20} //regexChecker("\\s[A-Za-z]{2,20}\\s", longString); System.out.println("----------- ZIP code 5 digits long"); //regexChecker("\\s\\d{5}\\s", longString); System.out.println("----------- States starting with A or C"); //regexChecker("A[KLRZ]|C[AOT]", longString); // {5,} - only minimum bounds // + - one or more time // .^*+?{}[]\|() - symbols to be backslashed // stars, brackets //regexChecker("\\{{2,}", strangeString); // zero or more times //regexChecker("[A-Za-z0-9._%-]+@[A-Za-z0-9._-]+\\.[A-Za-z]{2,4}", longString); //different phones //regexChecker("([0-9]( |-)?)?(\\(?[0-9]{3}\\)?|[0-9]{3})( |-)?([0-9]{3}( |-)?)([0-9]{4}|[a-zA-Z0-9]{7})", longString); regexReplace(longString); } public static void regexChecker(String theRegex, String str2chk) { Pattern checkRegex = Pattern.compile(theRegex); Matcher regexMatcher = checkRegex.matcher(str2chk); while (regexMatcher.find()) { if (regexMatcher.group().length() != 0) { System.out.println(regexMatcher.group().trim()); } System.out.println("start index: " + regexMatcher.start()); System.out.println("End index: " + regexMatcher.end()); } } public static void regexReplace(String str2Replace) { Pattern replace = Pattern.compile("\\s+"); Matcher regexMatcher = replace.matcher(str2Replace.trim()); System.out.println(regexMatcher.replaceAll(", ")); } }
2,030
0.554741
0.515152
61
32.540985
31.495289
127
false
false
0
0
0
0
0
0
0.737705
false
false
13
caadcfe22658615486f982f3adbce44071358ee5
10,419,590,673,497
a6930dc7feeaf7b503497dfb3041f4aa1ab9eba9
/base-learning/src/main/java/com/open/baselearning/designpattern/proxy/dynamicproxy/Client.java
1919ee00f0a3ccd23e8612f2a63d084b9f4f515e
[ "Apache-2.0" ]
permissive
zmlgirl/MyCode
https://github.com/zmlgirl/MyCode
f521252760cbbfc30006b712d36cca0bd762a91f
eeb67ee3b6e93aa5ad12715574cf65aca4d63c4a
refs/heads/master
2021-04-26T15:03:14.813000
2020-06-01T15:22:50
2020-06-01T15:22:50
121,221,185
0
0
NOASSERTION
false
2021-06-04T02:04:49
2018-02-12T08:39:19
2021-05-17T15:47:42
2021-06-04T02:04:48
4,299
0
0
1
Java
false
false
package com.open.baselearning.designpattern.proxy.dynamicproxy; import java.lang.reflect.InvocationHandler; /** * 测试动态代理 */ public class Client { public static void main(String[] args) { // 被代理对象 final RealSubject realSubject = new RealSubject(); // 代理类 final InvocationHandler handler = new Proxy(realSubject); final Subject newProxyInstance = (Subject) java.lang.reflect.Proxy.newProxyInstance(handler.getClass().getClassLoader(), realSubject.getClass().getInterfaces(), handler); // newProxyInstance.request("123"); newProxyInstance.response("123"); // final Hello hello = new Hello(); // final InvocationHandler helloHandler = new Proxy(hello); // final HelloInterface helloInstance = (HelloInterface) java.lang.reflect.Proxy.newProxyInstance(helloHandler.getClass().getClassLoader(), // hello.getClass().getInterfaces(), helloHandler); // helloInstance.sayHello(); } }
UTF-8
Java
1,028
java
Client.java
Java
[]
null
[]
package com.open.baselearning.designpattern.proxy.dynamicproxy; import java.lang.reflect.InvocationHandler; /** * 测试动态代理 */ public class Client { public static void main(String[] args) { // 被代理对象 final RealSubject realSubject = new RealSubject(); // 代理类 final InvocationHandler handler = new Proxy(realSubject); final Subject newProxyInstance = (Subject) java.lang.reflect.Proxy.newProxyInstance(handler.getClass().getClassLoader(), realSubject.getClass().getInterfaces(), handler); // newProxyInstance.request("123"); newProxyInstance.response("123"); // final Hello hello = new Hello(); // final InvocationHandler helloHandler = new Proxy(hello); // final HelloInterface helloInstance = (HelloInterface) java.lang.reflect.Proxy.newProxyInstance(helloHandler.getClass().getClassLoader(), // hello.getClass().getInterfaces(), helloHandler); // helloInstance.sayHello(); } }
1,028
0.681
0.675
24
40.666668
37.495186
146
false
false
0
0
0
0
0
0
0.625
false
false
13
df8d0c86d278a32d3afbc6024b6a3e3e2ec0a5bf
24,266,565,230,241
02a8d7cd19003db0f900b2c1454dd1bf821a169d
/SENG201ProjectExploringVoyager/src/exceptions/TakenDamageException.java
adcb12455766e54fb00f4e7ac4e4b4dd959411c2
[]
no_license
connor-hitchcock/Exploring-Voyager-Project-Java-Game
https://github.com/connor-hitchcock/Exploring-Voyager-Project-Java-Game
3bbf8d0260702d5b83970f43ca14b7c5ff3112c7
3ceed9afab9c48ece35e293ba3554e7c4b11e9de
refs/heads/main
2023-03-31T14:10:05.311000
2021-04-07T08:21:45
2021-04-07T08:21:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package exceptions; public class TakenDamageException extends IllegalArgumentException{ public TakenDamageException(String message) { super(message); } }
UTF-8
Java
161
java
TakenDamageException.java
Java
[]
null
[]
package exceptions; public class TakenDamageException extends IllegalArgumentException{ public TakenDamageException(String message) { super(message); } }
161
0.807453
0.807453
8
19.125
23.277874
67
false
false
0
0
0
0
0
0
0.875
false
false
13
8afc2acd69f61f7abd15ed01fa2814031d9174ab
14,147,622,285,835
5bc3a791c543ad6371b4fdce6fbf7901faa3a208
/src/main/java/com/quantitycontroller/QuantityRepository.java
a35960c7c570e0204785b77394b4c4af2df12376
[]
no_license
niraj28/BookProject
https://github.com/niraj28/BookProject
2e8785ca09788b18c1008da429486c9042d02712
9ecd877c8fff892782b22c62944793c8d02df8ad
refs/heads/main
2021-07-14T22:54:24.963000
2020-10-04T07:04:45
2020-10-04T07:04:45
240,917,919
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.quantitycontroller; import org.springframework.data.repository.CrudRepository; public interface QuantityRepository extends CrudRepository<Quantity, String> { }
UTF-8
Java
182
java
QuantityRepository.java
Java
[]
null
[]
package com.quantitycontroller; import org.springframework.data.repository.CrudRepository; public interface QuantityRepository extends CrudRepository<Quantity, String> { }
182
0.813187
0.813187
7
24
30.185143
78
false
false
0
0
0
0
0
0
0.428571
false
false
13
5d67497643a34963c3f7d85e81a460a228587f90
33,552,284,542,816
7191b1cb4ff11847b3729e61513cd855689f4f0b
/core/src/main/java/uk/co/revsys/objectology/dao/CachingDaoFactory.java
99c7bbd62078a03880281e04747555182909756b
[]
no_license
revolutionarysystems/objectology
https://github.com/revolutionarysystems/objectology
f4ef0dee00dc8247106f82f9ec321e96872256dd
97628779b1b9261c6dc02753bc282cf7c1f069c4
refs/heads/master
2021-01-02T09:09:21.922000
2015-09-11T12:38:56
2015-09-11T12:38:56
19,858,574
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package uk.co.revsys.objectology.dao; import java.util.HashMap; import java.util.Map; public abstract class CachingDaoFactory<D extends AbstractDao> implements DaoFactory<D>{ private Map<String, D> daoMap = new HashMap<String, D>(); @Override public D getDao(String objectType) { D dao = daoMap.get(objectType); if(dao == null){ dao = createDao(objectType); daoMap.put(objectType, dao); } return dao; } public abstract D createDao(String objectType); }
UTF-8
Java
480
java
CachingDaoFactory.java
Java
[]
null
[]
package uk.co.revsys.objectology.dao; import java.util.HashMap; import java.util.Map; public abstract class CachingDaoFactory<D extends AbstractDao> implements DaoFactory<D>{ private Map<String, D> daoMap = new HashMap<String, D>(); @Override public D getDao(String objectType) { D dao = daoMap.get(objectType); if(dao == null){ dao = createDao(objectType); daoMap.put(objectType, dao); } return dao; } public abstract D createDao(String objectType); }
480
0.722917
0.722917
22
20.818182
22.664824
88
false
false
0
0
0
0
0
0
1.5
false
false
13
1f0ba9b342abfeb2b8f8ccd5450575ac188b5ff7
7,937,099,617,288
5f2b485d55e9f963a36dc91f8f4323bbf0a50712
/src/test/java/test/SimpleGetTest.java
ddf5574a34b8db92f3e85f35de0b1476f6d0aae5
[]
no_license
AnuragRKGautam/_10
https://github.com/AnuragRKGautam/_10
e30806d912b314e8005147ee800cf1e6f9476d2c
20be8cd203ed7ae1bf8000d1e89ba86012fa632a
refs/heads/master
2023-04-29T23:32:32.262000
2019-10-17T01:03:08
2019-10-17T01:03:08
215,213,078
0
0
null
false
2023-04-14T17:43:05
2019-10-15T05:21:12
2019-10-18T00:22:02
2023-04-14T17:43:05
5,062
0
0
2
Java
false
false
package test; import configuration.constants; import io.restassured.path.json.JsonPath; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.testng.annotations.Test; import io.restassured.RestAssured; import io.restassured.http.Method; import io.restassured.response.Response; import utils.RestAssuredUtils; import utils.fileUtils; import static utils.RestAssuredUtils.getResponse; //https://openweathermap.org/api public class SimpleGetTest{ constants cons = constants.getInstance(); @Test public void test(){ Response response = getResponse(cons.OWM_WEATHER_2_5+"?q=London"+ cons.WEATHER_API_APP_KEY); // System.out.println(response.path("coord")); // System.out.println(response.path("coord")); if(response.getBody()!=null) { System.out.println(response.getStatusCode()); System.out.println(response.prettyPrint()); JsonPath jsonPath = new JsonPath(response.asString()); System.out.println(jsonPath.prettyPrint()); System.out.println(jsonPath.get("main.temp").toString()); } } //@Test public void readingFromFixedJson() { // JSONObject jsonObject = fileUtils.readJson(); // JSONObject jsonObject= fileUtils.readJson("/Users/harry/git/DemoChrome/src/test/resources/test.json"); // JSONObject jsonObject= fileUtils.returnJsonObject("./src/test/resources/data/history.city.list.min.json"); JSONArray jsonArray = fileUtils.returnJsonArray("./src/test/resources/data/history.city.list.min.json"); // for (int i =0 ;i<jsonArray.size();i++) // { // System.out.println("This is execution Number: "+ i +" "+((JSONObject) jsonArray.get(i)).get("city")); // } JsonPath jsonPath = new JsonPath(jsonArray.toJSONString()); System.out.println(jsonPath.get("country").toString()); } }
UTF-8
Java
1,827
java
SimpleGetTest.java
Java
[]
null
[]
package test; import configuration.constants; import io.restassured.path.json.JsonPath; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.testng.annotations.Test; import io.restassured.RestAssured; import io.restassured.http.Method; import io.restassured.response.Response; import utils.RestAssuredUtils; import utils.fileUtils; import static utils.RestAssuredUtils.getResponse; //https://openweathermap.org/api public class SimpleGetTest{ constants cons = constants.getInstance(); @Test public void test(){ Response response = getResponse(cons.OWM_WEATHER_2_5+"?q=London"+ cons.WEATHER_API_APP_KEY); // System.out.println(response.path("coord")); // System.out.println(response.path("coord")); if(response.getBody()!=null) { System.out.println(response.getStatusCode()); System.out.println(response.prettyPrint()); JsonPath jsonPath = new JsonPath(response.asString()); System.out.println(jsonPath.prettyPrint()); System.out.println(jsonPath.get("main.temp").toString()); } } //@Test public void readingFromFixedJson() { // JSONObject jsonObject = fileUtils.readJson(); // JSONObject jsonObject= fileUtils.readJson("/Users/harry/git/DemoChrome/src/test/resources/test.json"); // JSONObject jsonObject= fileUtils.returnJsonObject("./src/test/resources/data/history.city.list.min.json"); JSONArray jsonArray = fileUtils.returnJsonArray("./src/test/resources/data/history.city.list.min.json"); // for (int i =0 ;i<jsonArray.size();i++) // { // System.out.println("This is execution Number: "+ i +" "+((JSONObject) jsonArray.get(i)).get("city")); // } JsonPath jsonPath = new JsonPath(jsonArray.toJSONString()); System.out.println(jsonPath.get("country").toString()); } }
1,827
0.713191
0.711549
54
32.851852
32.099041
116
false
false
0
0
0
0
0
0
0.555556
false
false
13
c8575c5fbb60ae013480327fcc025d5ab68fb9cc
33,097,017,989,492
5e553e5b039fbbd4afb1d33c710fd36058fbb895
/src/main/java/de/dkt/eservices/databackend/collectionexploration/stats/StatisticsService.java
22166474be52c5efdaaac0049165f9aeda650d06
[]
no_license
dkt-projekt/Data-Backend
https://github.com/dkt-projekt/Data-Backend
dfe460f6419cda49a6d1f9e71b99ff38fbf41eeb
240c446052c49ad651ad8f4aa0d02abd9a76e7b9
refs/heads/master
2021-01-12T12:52:43.842000
2017-11-13T13:21:51
2017-11-13T13:21:51
69,473,579
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.dkt.eservices.databackend.collectionexploration.stats; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.hp.hpl.jena.query.Query; import com.hp.hpl.jena.query.QueryExecution; import com.hp.hpl.jena.query.QueryFactory; import com.hp.hpl.jena.query.QuerySolution; import com.hp.hpl.jena.query.ResultSet; import de.dkt.eservices.databackend.common.SparqlService; @Service public class StatisticsService { @Autowired SparqlService sparqlService; public enum Types{ Organization, TemporalExpression, Location, Person; public static String getUri(Types t){ switch(t){ case Organization: return "http://dbpedia.org/ontology/Organisation"; case TemporalExpression: return "http://www.w3.org/2006/time#TemporalEntity"; case Location: return "http://dbpedia.org/ontology/Location"; case Person: return "http://dbpedia.org/ontology/Person"; default: throw new RuntimeException("Unknown type"); } } } public JSONArray countEntities(String type){ QueryExecution qe = null; try{ qe = sparqlService.createQueryExecution("count-entities.sparql", type); ResultSet res = qe.execSelect(); ArrayList<JSONObject> list = new ArrayList<>(); while( res.hasNext() ){ QuerySolution qs = res.next(); JSONObject json = new JSONObject(); json.put("anchorOf", qs.getLiteral("text").getString()); json.put("count", qs.getLiteral("count").getInt()); list.add(json); } return new JSONArray(list); } finally{ if( qe != null){ qe.close(); } } } public JSONObject getEntityStats(String collectionName){ sparqlService.setCollectionName(collectionName); JSONObject json = new JSONObject(); for( Types type : Types.values() ){ String uri = Types.getUri(type); json.put(uri, countEntities(uri)); } return json; } public Integer getNumberOfContexts(){ Query query = QueryFactory.create("SELECT (COUNT(*) as ?count) WHERE { ?s a <http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#Context> . }"); QueryExecution qexec = null; try{ qexec = sparqlService.createQueryExecution(query); ResultSet res = qexec.execSelect(); if( !res.hasNext() ){ return null; } else{ return res.next().getLiteral("count").getInt(); } } finally{ if( qexec != null){ qexec.close(); } } } public Integer getNumberOfTriples(){ Query query = QueryFactory.create("SELECT (COUNT(*) as ?count) WHERE { ?s ?p ?o . }"); QueryExecution qexec = null; try{ qexec = sparqlService.createQueryExecution(query); ResultSet res = qexec.execSelect(); if( !res.hasNext() ){ return null; } else{ return res.next().getLiteral("count").getInt(); } } finally{ if( qexec != null){ qexec.close(); } } } public JSONObject getGeneralStats(String collectionName){ sparqlService.setCollectionName(collectionName); JSONObject json = new JSONObject(); json.put("numberOfContexts", getNumberOfContexts()); json.put("numberOfTriples", getNumberOfTriples()); return json; } }
UTF-8
Java
3,328
java
StatisticsService.java
Java
[]
null
[]
package de.dkt.eservices.databackend.collectionexploration.stats; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.hp.hpl.jena.query.Query; import com.hp.hpl.jena.query.QueryExecution; import com.hp.hpl.jena.query.QueryFactory; import com.hp.hpl.jena.query.QuerySolution; import com.hp.hpl.jena.query.ResultSet; import de.dkt.eservices.databackend.common.SparqlService; @Service public class StatisticsService { @Autowired SparqlService sparqlService; public enum Types{ Organization, TemporalExpression, Location, Person; public static String getUri(Types t){ switch(t){ case Organization: return "http://dbpedia.org/ontology/Organisation"; case TemporalExpression: return "http://www.w3.org/2006/time#TemporalEntity"; case Location: return "http://dbpedia.org/ontology/Location"; case Person: return "http://dbpedia.org/ontology/Person"; default: throw new RuntimeException("Unknown type"); } } } public JSONArray countEntities(String type){ QueryExecution qe = null; try{ qe = sparqlService.createQueryExecution("count-entities.sparql", type); ResultSet res = qe.execSelect(); ArrayList<JSONObject> list = new ArrayList<>(); while( res.hasNext() ){ QuerySolution qs = res.next(); JSONObject json = new JSONObject(); json.put("anchorOf", qs.getLiteral("text").getString()); json.put("count", qs.getLiteral("count").getInt()); list.add(json); } return new JSONArray(list); } finally{ if( qe != null){ qe.close(); } } } public JSONObject getEntityStats(String collectionName){ sparqlService.setCollectionName(collectionName); JSONObject json = new JSONObject(); for( Types type : Types.values() ){ String uri = Types.getUri(type); json.put(uri, countEntities(uri)); } return json; } public Integer getNumberOfContexts(){ Query query = QueryFactory.create("SELECT (COUNT(*) as ?count) WHERE { ?s a <http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#Context> . }"); QueryExecution qexec = null; try{ qexec = sparqlService.createQueryExecution(query); ResultSet res = qexec.execSelect(); if( !res.hasNext() ){ return null; } else{ return res.next().getLiteral("count").getInt(); } } finally{ if( qexec != null){ qexec.close(); } } } public Integer getNumberOfTriples(){ Query query = QueryFactory.create("SELECT (COUNT(*) as ?count) WHERE { ?s ?p ?o . }"); QueryExecution qexec = null; try{ qexec = sparqlService.createQueryExecution(query); ResultSet res = qexec.execSelect(); if( !res.hasNext() ){ return null; } else{ return res.next().getLiteral("count").getInt(); } } finally{ if( qexec != null){ qexec.close(); } } } public JSONObject getGeneralStats(String collectionName){ sparqlService.setCollectionName(collectionName); JSONObject json = new JSONObject(); json.put("numberOfContexts", getNumberOfContexts()); json.put("numberOfTriples", getNumberOfTriples()); return json; } }
3,328
0.674579
0.672776
120
25.733334
23.676899
157
false
false
0
0
0
0
0
0
2.55
false
false
13
c230177f7b7404c36593643c6378ba9d41a8f35b
12,567,074,357,007
072c0c56145cd18381e2a48e64ca021f9575a88d
/core/src/main/java/com/prueba/core/base/viewmodel/BasicViewModelType.java
8613278f038ae7227cb2a98c60a2ba828c7fe9fa
[]
no_license
Yercko/asv_android
https://github.com/Yercko/asv_android
2bdc6c88d28233eb53254ab1267278bb850f3f19
c0722ecd3987fd07394d11796d840e3bbdda023e
refs/heads/master
2020-06-04T01:53:26.458000
2019-06-13T19:58:41
2019-06-13T19:58:41
191,821,998
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.prueba.core.base.viewmodel; import android.support.annotation.NonNull; import com.prueba.core.base.model.ModelType; import com.prueba.core.base.view.ViewType; /** * Created by prueba on 8/3/18. */ public interface BasicViewModelType <M extends ModelType, V extends ViewType> extends BaseViewModelType<V> { /** * Actualiza el modelo y notifica el cambio a la vista * @param model Modelo a actualizar */ void updateModel(@NonNull M model); }
UTF-8
Java
483
java
BasicViewModelType.java
Java
[ { "context": "prueba.core.base.view.ViewType;\n\n/**\n * Created by prueba on 8/3/18.\n */\n\npublic interface BasicViewModelTy", "end": 198, "score": 0.9995428323745728, "start": 192, "tag": "USERNAME", "value": "prueba" } ]
null
[]
package com.prueba.core.base.viewmodel; import android.support.annotation.NonNull; import com.prueba.core.base.model.ModelType; import com.prueba.core.base.view.ViewType; /** * Created by prueba on 8/3/18. */ public interface BasicViewModelType <M extends ModelType, V extends ViewType> extends BaseViewModelType<V> { /** * Actualiza el modelo y notifica el cambio a la vista * @param model Modelo a actualizar */ void updateModel(@NonNull M model); }
483
0.726708
0.718427
20
23.15
27.76198
108
false
false
0
0
0
0
0
0
0.3
false
false
13
4bc9b4dc57dc02188d0365deecc25c3762d751f6
20,718,922,290,978
d90160ee4e5bc3f98bd193c630ce326865b4751f
/1FoodUnifier/src/main/java/com/xmith/services/UserServices.java
15578d5cfb55f84bff2ca9966272cccdcc281a20
[]
no_license
smithlfc/foodAppCentral
https://github.com/smithlfc/foodAppCentral
eb16ac799e525b8c8da39f98094959e0a727aa6e
e7801962487212b479295baa5af3db7fa86ab668
refs/heads/master
2022-12-22T04:56:49.745000
2020-06-24T04:23:09
2020-06-24T04:23:09
141,039,053
0
0
null
false
2022-12-16T09:43:16
2018-07-15T15:42:02
2020-06-24T04:39:13
2022-12-16T09:43:15
1,865
0
0
25
Java
false
false
package com.xmith.services; import java.util.List; import com.xmith.models.UserAccount; import com.xmith.models.UserDetails; import com.xmith.models.Users; public interface UserServices { public String getUserId(String username); public boolean updateTokenService(String username,String token); public Users getuserService(String userid); public String[] authenticateUser(String username); public boolean updateAttemptsService(String userid,String attempts); public boolean insertUserRegDetails(UserDetails userDetails); public List<UserAccount> getAccounts(String UserId); }
UTF-8
Java
608
java
UserServices.java
Java
[]
null
[]
package com.xmith.services; import java.util.List; import com.xmith.models.UserAccount; import com.xmith.models.UserDetails; import com.xmith.models.Users; public interface UserServices { public String getUserId(String username); public boolean updateTokenService(String username,String token); public Users getuserService(String userid); public String[] authenticateUser(String username); public boolean updateAttemptsService(String userid,String attempts); public boolean insertUserRegDetails(UserDetails userDetails); public List<UserAccount> getAccounts(String UserId); }
608
0.796053
0.796053
19
30
23.517071
69
false
false
0
0
0
0
0
0
1.157895
false
false
13
0098aff3c7fb785452324ecbb0d1c7085e00a1de
30,288,109,399,479
7dc45d29d7ae8c8ded4d550a5973ca9737c7275c
/app/src/main/java/francis/loupgarou2/GameActivities/DeadActivity.java
55662dc4cc5e20809771b4304d1efeb42d8e1821
[]
no_license
francisbr/LoupGarouV2
https://github.com/francisbr/LoupGarouV2
2156b9d8cd863aca3fb2fa4d1727694752402c82
d727e89d6567d401d031369649107415d71a3742
refs/heads/master
2019-06-16T08:43:26.025000
2018-01-03T22:21:47
2018-01-03T22:21:47
98,832,227
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package francis.loupgarou2.GameActivities; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import francis.loupgarou2.LibrairiesAdaptations.MyActivity; import francis.loupgarou2.R; public class DeadActivity extends MyActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dead); } @Override public void onBackPressed() {} }
UTF-8
Java
479
java
DeadActivity.java
Java
[]
null
[]
package francis.loupgarou2.GameActivities; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import francis.loupgarou2.LibrairiesAdaptations.MyActivity; import francis.loupgarou2.R; public class DeadActivity extends MyActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dead); } @Override public void onBackPressed() {} }
479
0.76618
0.757829
19
24.210526
21.338326
59
false
false
0
0
0
0
0
0
0.368421
false
false
13
d6c449162a456481ee0665649c626a5e113de762
30,288,109,403,577
98a5e23ebdb447e2746a06c0d1abf2c8040b13ef
/src/main/java/com/sxkl/project/cloudnote/etl/mapper/remote/RemoteWaitingTaskMapper.java
4bae8e178f7227cc170a0e1758f545046a9ddc79
[]
no_license
wangyao88/cloudnote-service
https://github.com/wangyao88/cloudnote-service
a4a3f8a4919e020b5d5ed6287eefb0f565c1b99c
0faa927d2f0b2c8c1883f4ed8e83606cd8de8906
refs/heads/master
2022-09-11T07:58:07.415000
2019-08-27T01:57:58
2019-08-27T01:57:58
181,862,760
0
0
null
false
2022-09-01T23:05:32
2019-04-17T09:46:50
2019-08-27T01:58:37
2022-09-01T23:05:30
6,762
0
0
5
JavaScript
false
false
package com.sxkl.project.cloudnote.etl.mapper.remote; import com.sxkl.project.cloudnote.etl.entity.WaitingTask; import com.sxkl.project.cloudnote.etl.mapper.BaseExtractMapper; import com.sxkl.project.cloudnote.etl.mapper.MyBatisSQL; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.SelectProvider; import org.apache.ibatis.type.JdbcType; import java.util.List; @Mapper public interface RemoteWaitingTaskMapper extends BaseExtractMapper { @Override @SelectProvider(type = WaitingTaskMapperProvider.class, method = "findAll") @Results(id = "WaitingTaskResult", value = { @Result(column = "id", property = "id", jdbcType = JdbcType.VARCHAR, id = true), @Result(column = "name", property = "name", jdbcType = JdbcType.VARCHAR), @Result(column = "createDate", property = "createDate", jdbcType = JdbcType.TIMESTAMP), @Result(column = "expireDate", property = "expireDate", jdbcType = JdbcType.TIMESTAMP), @Result(column = "taskType", property = "taskType", jdbcType = JdbcType.VARCHAR), @Result(column = "uId", property = "uId", jdbcType = JdbcType.VARCHAR), @Result(column = "process", property = "process", jdbcType = JdbcType.VARCHAR), @Result(column = "content", property = "content", jdbcType = JdbcType.VARCHAR), @Result(column = "beginDate", property = "beginDate", jdbcType = JdbcType.TIMESTAMP) }) List<WaitingTask> findAll(); class WaitingTaskMapperProvider { public String findAll() { return MyBatisSQL.builder() .SELECT("id, name, createDate, expireDate, taskType, uId, process, content, beginDate ") .FROM("cn_waitingtask") .build(); } } }
UTF-8
Java
1,931
java
RemoteWaitingTaskMapper.java
Java
[]
null
[]
package com.sxkl.project.cloudnote.etl.mapper.remote; import com.sxkl.project.cloudnote.etl.entity.WaitingTask; import com.sxkl.project.cloudnote.etl.mapper.BaseExtractMapper; import com.sxkl.project.cloudnote.etl.mapper.MyBatisSQL; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.SelectProvider; import org.apache.ibatis.type.JdbcType; import java.util.List; @Mapper public interface RemoteWaitingTaskMapper extends BaseExtractMapper { @Override @SelectProvider(type = WaitingTaskMapperProvider.class, method = "findAll") @Results(id = "WaitingTaskResult", value = { @Result(column = "id", property = "id", jdbcType = JdbcType.VARCHAR, id = true), @Result(column = "name", property = "name", jdbcType = JdbcType.VARCHAR), @Result(column = "createDate", property = "createDate", jdbcType = JdbcType.TIMESTAMP), @Result(column = "expireDate", property = "expireDate", jdbcType = JdbcType.TIMESTAMP), @Result(column = "taskType", property = "taskType", jdbcType = JdbcType.VARCHAR), @Result(column = "uId", property = "uId", jdbcType = JdbcType.VARCHAR), @Result(column = "process", property = "process", jdbcType = JdbcType.VARCHAR), @Result(column = "content", property = "content", jdbcType = JdbcType.VARCHAR), @Result(column = "beginDate", property = "beginDate", jdbcType = JdbcType.TIMESTAMP) }) List<WaitingTask> findAll(); class WaitingTaskMapperProvider { public String findAll() { return MyBatisSQL.builder() .SELECT("id, name, createDate, expireDate, taskType, uId, process, content, beginDate ") .FROM("cn_waitingtask") .build(); } } }
1,931
0.661833
0.661833
43
43.906979
35.388092
117
false
false
0
0
0
0
0
0
1.139535
false
false
13
0059922a5a640b6e4c3d8d79faf1ede734f99e0a
18,571,438,653,390
0650786904f81021320b1d1f5bd50e993af613d8
/src/test/sorters/SortersTestRunner.java
8c5f4bcb6923cc02ab671212ae592cfb2edbc62e
[]
no_license
andriy-shulepa/ShulepaLab01
https://github.com/andriy-shulepa/ShulepaLab01
0242d85479988819991f6bb52623ae2e6a0d3d54
0db709709e9cccebe9aa2149de0f957110ba42b8
refs/heads/master
2023-01-10T14:14:18.053000
2018-03-18T21:20:02
2018-03-18T21:20:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package test.sorters; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class SortersTestRunner { public static void main(String... args) { Result result = JUnitCore.runClasses( FromEndBubbleSortTest.class, FromStartBubbleSortTest.class, SelectionSortTest.class, MergeSortTest.class, QuickSortTest.class, ArraysSortTest.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } }
UTF-8
Java
688
java
SortersTestRunner.java
Java
[]
null
[]
package test.sorters; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class SortersTestRunner { public static void main(String... args) { Result result = JUnitCore.runClasses( FromEndBubbleSortTest.class, FromStartBubbleSortTest.class, SelectionSortTest.class, MergeSortTest.class, QuickSortTest.class, ArraysSortTest.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } }
688
0.627907
0.627907
24
27.666666
19.578192
54
false
false
0
0
0
0
0
0
0.5
false
false
13
114c27113e998a8e4b92291116c988aea4f7860c
27,298,812,181,851
1961ae487504d7f73afc731398a7fd2c2ad1c097
/button/src/main/java/io/button/dagger/annotation/Button.java
79e5dc454cab24ed3cd10eb86db7c3201cf6f474
[]
no_license
davidsnyder/button-android-experimental
https://github.com/davidsnyder/button-android-experimental
961cdba47c3a0589328408ec177e4837c071b8d9
5526ad04d047fa800c54405de26133547e5594b7
refs/heads/master
2020-03-25T09:25:09.927000
2014-03-09T06:00:28
2014-03-09T06:00:28
143,668,462
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package io.button.dagger.annotation; import javax.inject.Qualifier; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) @Qualifier public @interface Button { }
UTF-8
Java
230
java
Button.java
Java
[]
null
[]
package io.button.dagger.annotation; import javax.inject.Qualifier; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) @Qualifier public @interface Button { }
230
0.826087
0.826087
10
22
16.546904
44
false
false
0
0
0
0
0
0
0.4
false
false
13
26be5e8f8ef5993554db1b39889c166353d79def
14,637,248,549,570
f0a019197eb781b157f90bd79f3c63be4258f082
/src/zad25/SearchTable.java
ea394ca0476c4e881dab6a931dea1ac9144717de
[]
no_license
roztropny/concurrency_learning
https://github.com/roztropny/concurrency_learning
b4090d466b3bbb804ce2422299608c4a11babf61
3e47fc00c6a552ab4a9a20083f159845728fd507
refs/heads/master
2020-03-07T02:28:20.897000
2018-09-20T00:14:46
2018-09-20T00:14:46
127,209,577
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package zad25; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicBoolean; public class SearchTable { private static final int ARRAY_SIZE = 1000; private static final int CHUNK_SIZE = 100; private static final int VALUE = 73; private static final int THREADS = ARRAY_SIZE / CHUNK_SIZE; private static final int MIN = 1; private static final int MAX = 1000; private static int[] generateTable(int[] array, int min, int max){ for(int i = 0; i < array.length; i++){ array[i] = ThreadLocalRandom.current().nextInt(min, max + 1); } return array; } public static void main(String[] args) throws InterruptedException { AtomicBoolean foundFlag = new AtomicBoolean(false); CountDownLatch latch = new CountDownLatch(THREADS); int[] array = new int[ARRAY_SIZE]; array = generateTable(array, MIN, MAX); System.out.println("Wygenerowano"); for(int i = 0; i < ARRAY_SIZE; i += CHUNK_SIZE){ new Searcher(array, i, i + CHUNK_SIZE, VALUE, foundFlag, latch); } System.out.println("Wyszukiwanie rozpoczete"); latch.await(); System.out.println("Czy znaleziono: "+ foundFlag); } }
UTF-8
Java
1,314
java
SearchTable.java
Java
[]
null
[]
package zad25; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicBoolean; public class SearchTable { private static final int ARRAY_SIZE = 1000; private static final int CHUNK_SIZE = 100; private static final int VALUE = 73; private static final int THREADS = ARRAY_SIZE / CHUNK_SIZE; private static final int MIN = 1; private static final int MAX = 1000; private static int[] generateTable(int[] array, int min, int max){ for(int i = 0; i < array.length; i++){ array[i] = ThreadLocalRandom.current().nextInt(min, max + 1); } return array; } public static void main(String[] args) throws InterruptedException { AtomicBoolean foundFlag = new AtomicBoolean(false); CountDownLatch latch = new CountDownLatch(THREADS); int[] array = new int[ARRAY_SIZE]; array = generateTable(array, MIN, MAX); System.out.println("Wygenerowano"); for(int i = 0; i < ARRAY_SIZE; i += CHUNK_SIZE){ new Searcher(array, i, i + CHUNK_SIZE, VALUE, foundFlag, latch); } System.out.println("Wyszukiwanie rozpoczete"); latch.await(); System.out.println("Czy znaleziono: "+ foundFlag); } }
1,314
0.652207
0.637747
36
35.5
24.366985
76
false
false
0
0
0
0
0
0
0.972222
false
false
13
fc04730a405ba66f9e441da2fd71ad7e882d2ea7
33,243,046,879,711
a5a66f8068df2a6ff3f0993d49a32eb82deba4af
/Basic Apps/src/mathQuiz.java
06e3b56c64cae7947850884f32f2ca7fbdb33478
[]
no_license
KevinHorning/Basic-Programming-Apps
https://github.com/KevinHorning/Basic-Programming-Apps
d50df575cfe59db339ada20ff4443dac3cb87a20
e69ba4402038d17aba56a0f14101df601d97fc91
refs/heads/master
2020-08-17T20:23:03.670000
2020-04-21T22:40:45
2020-04-21T22:40:45
215,707,930
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// try me!!! import javax.swing.JOptionPane; public class mathQuiz { public static void main(String[] args) { JOptionPane.showMessageDialog(null, "Welcome to the Arithmetic Quiz"); JOptionPane.showMessageDialog(null, "5 questions! First 4 you choose and we choose the last one"); for (int i = 1; i < 6; i++){ String Question1Choice = JOptionPane.showInputDialog("What operation for question" + i + " ? (1 for addition 2 for subtraction, 3 for multipley, 4 for division)"); if (Question1Choice.equals("1")){ int number1 = RandomNumber(); int number2 = RandomNumber(); String answer1 = JOptionPane.showInputDialog(null, "What is answer to " + number1 + " + " + number2, "Answer here"); if(number1 + number2 == Integer.parseInt(answer1)){ JOptionPane.showConfirmDialog(null, "CORRREECCTTT", "Result", JOptionPane.YES_NO_OPTION); } else{ JOptionPane.showMessageDialog(null, "WRONG", "Result", JOptionPane.YES_NO_OPTION); } } if (Question1Choice.equals("2")){ int number1 = RandomNumber(); int number2 = RandomNumber(); String answer1 = JOptionPane.showInputDialog(null, "What is answer to " + number1 + " - " + number2, "Answer here"); if(number1 - number2 == Integer.parseInt(answer1)){ JOptionPane.showConfirmDialog(null, "CORRREECCTTT", "Result", JOptionPane.YES_NO_OPTION); } else{ JOptionPane.showMessageDialog(null, "WRONG", "Result", JOptionPane.YES_NO_OPTION); } } if (Question1Choice.equals("3")){ int number1 = RandomNumber(); int number2 = RandomNumber(); String answer1 = JOptionPane.showInputDialog(null, "What is answer to " + number1 + " * " + number2, "Answer here"); if(number1 * number2 == Integer.parseInt(answer1)){ JOptionPane.showConfirmDialog(null, "CORRREECCTTT", "Result", JOptionPane.YES_NO_OPTION); } else{ JOptionPane.showMessageDialog(null, "WRONG", "Result", JOptionPane.YES_NO_OPTION); } } if (Question1Choice.equals("4")){ int number1 = RandomNumber(); int number2 = RandomNumber(); String answer1 = JOptionPane.showInputDialog(null, "What is answer to " + number1 + " / " + number2 + "enter only integers", "Answer here"); if(number1 / number2 == Integer.parseInt(answer1)){ JOptionPane.showConfirmDialog(null, "CORRREECCTTT", "Result", JOptionPane.YES_NO_OPTION); } else{ JOptionPane.showMessageDialog(null, "WRONG", "Result", JOptionPane.YES_NO_OPTION); } } } } public static int RandomNumber(){ return (int) (Math.random() * 10); } } /* Pseudo-Code * Create package and import JavaOptionPane; * Create class and public static main method * Use JOptionPane Message Dialog to Welcome user and give instuctions for the quiz * Use for loop to run all 5 questions * We use */
UTF-8
Java
2,888
java
mathQuiz.java
Java
[]
null
[]
// try me!!! import javax.swing.JOptionPane; public class mathQuiz { public static void main(String[] args) { JOptionPane.showMessageDialog(null, "Welcome to the Arithmetic Quiz"); JOptionPane.showMessageDialog(null, "5 questions! First 4 you choose and we choose the last one"); for (int i = 1; i < 6; i++){ String Question1Choice = JOptionPane.showInputDialog("What operation for question" + i + " ? (1 for addition 2 for subtraction, 3 for multipley, 4 for division)"); if (Question1Choice.equals("1")){ int number1 = RandomNumber(); int number2 = RandomNumber(); String answer1 = JOptionPane.showInputDialog(null, "What is answer to " + number1 + " + " + number2, "Answer here"); if(number1 + number2 == Integer.parseInt(answer1)){ JOptionPane.showConfirmDialog(null, "CORRREECCTTT", "Result", JOptionPane.YES_NO_OPTION); } else{ JOptionPane.showMessageDialog(null, "WRONG", "Result", JOptionPane.YES_NO_OPTION); } } if (Question1Choice.equals("2")){ int number1 = RandomNumber(); int number2 = RandomNumber(); String answer1 = JOptionPane.showInputDialog(null, "What is answer to " + number1 + " - " + number2, "Answer here"); if(number1 - number2 == Integer.parseInt(answer1)){ JOptionPane.showConfirmDialog(null, "CORRREECCTTT", "Result", JOptionPane.YES_NO_OPTION); } else{ JOptionPane.showMessageDialog(null, "WRONG", "Result", JOptionPane.YES_NO_OPTION); } } if (Question1Choice.equals("3")){ int number1 = RandomNumber(); int number2 = RandomNumber(); String answer1 = JOptionPane.showInputDialog(null, "What is answer to " + number1 + " * " + number2, "Answer here"); if(number1 * number2 == Integer.parseInt(answer1)){ JOptionPane.showConfirmDialog(null, "CORRREECCTTT", "Result", JOptionPane.YES_NO_OPTION); } else{ JOptionPane.showMessageDialog(null, "WRONG", "Result", JOptionPane.YES_NO_OPTION); } } if (Question1Choice.equals("4")){ int number1 = RandomNumber(); int number2 = RandomNumber(); String answer1 = JOptionPane.showInputDialog(null, "What is answer to " + number1 + " / " + number2 + "enter only integers", "Answer here"); if(number1 / number2 == Integer.parseInt(answer1)){ JOptionPane.showConfirmDialog(null, "CORRREECCTTT", "Result", JOptionPane.YES_NO_OPTION); } else{ JOptionPane.showMessageDialog(null, "WRONG", "Result", JOptionPane.YES_NO_OPTION); } } } } public static int RandomNumber(){ return (int) (Math.random() * 10); } } /* Pseudo-Code * Create package and import JavaOptionPane; * Create class and public static main method * Use JOptionPane Message Dialog to Welcome user and give instuctions for the quiz * Use for loop to run all 5 questions * We use */
2,888
0.66205
0.644044
69
39.84058
39.75819
166
false
false
0
0
0
0
0
0
3.724638
false
false
13
8a16f279e2510fbd5d13f8c2f0c228d6b8d66a9e
16,252,156,248,121
89139ec39ae60d0fea7f96ba316ae39d7ac04576
/src/hw/hw01.java
3fbb836eb3a19f9b59fe9f11882fcb57588157da
[ "MIT" ]
permissive
bblkk355/week09-20161128-wei112177
https://github.com/bblkk355/week09-20161128-wei112177
ab0f74c1db511b7c9bab5546f88f46adf5a0f365
a27da8a9b3b16e1ce078134375167fa5f0a60b2c
refs/heads/master
2021-06-05T16:32:31.031000
2016-11-28T09:14:07
2016-11-28T09:14:07
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package hw; /* * Topic: 霈蝙��撓�銝�甇���嚗��撘���銝���蝥�����府�����甇支�甇���嚗��迤��銝虫�����蝥�嚗�銝������o��� 靘��: 15 =1+2+3+4+5 =4+5+6=7+8 * Date: 2016/11/28 * Author: 103021009 吳庭瑋 */ public class hw01 { public static void main(String[] args) { // TODO Auto-generated method stub } }
UTF-8
Java
592
java
hw01.java
Java
[ { "context": "2+3+4+5 =4+5+6=7+8\n * Date: 2016/11/28\n * Author: 103021009 吳庭瑋\n */\npublic class hw01 {\n\n\tpublic static void ", "end": 220, "score": 0.9966729283332825, "start": 211, "tag": "USERNAME", "value": "103021009" }, { "context": "+5+6=7+8\n * Date: 2016/11/28\n * Author: 103021009 吳庭瑋\n */\npublic class hw01 {\n\n\tpublic static void main", "end": 224, "score": 0.9991633296012878, "start": 221, "tag": "NAME", "value": "吳庭瑋" } ]
null
[]
package hw; /* * Topic: 霈蝙��撓�銝�甇���嚗��撘���銝���蝥�����府�����甇支�甇���嚗��迤��銝虫�����蝥�嚗�銝������o��� 靘��: 15 =1+2+3+4+5 =4+5+6=7+8 * Date: 2016/11/28 * Author: 103021009 吳庭瑋 */ public class hw01 { public static void main(String[] args) { // TODO Auto-generated method stub } }
592
0.446429
0.354167
15
21.4
32.587933
132
false
false
0
0
0
0
0
0
0.333333
false
false
13
6e62f00335066ffc1593eebff5a4def85156cb6a
18,511,309,049,102
0c3bbcdf952c7fa2e504a06c67735c9b27b9525b
/Pgo-task9/src/Task1/Car.java
471cb3e4d86907d8b70020a6ea78b33ff3bb8456
[]
no_license
s21190/pgo-tutorials-task
https://github.com/s21190/pgo-tutorials-task
88a00b06f84609b540589fa411793dd28536c242
3ca8da69730470854606c5c7fb2e08b1feecf779
refs/heads/master
2021-04-03T12:54:51.074000
2020-05-20T09:01:19
2020-05-20T09:01:19
248,355,692
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Task1; public class Car extends Vehicle { private int numberOfSeats; public Car(int numberOfSeats) { this.numberOfSeats = numberOfSeats; } public int getNumberOfSeats() { return numberOfSeats; } @Override public void start(){ System.out.println("car has started task2\n"); } @Override public void stop(){ System.out.println("car has stoped task2 \n"); } }
UTF-8
Java
441
java
Car.java
Java
[]
null
[]
package Task1; public class Car extends Vehicle { private int numberOfSeats; public Car(int numberOfSeats) { this.numberOfSeats = numberOfSeats; } public int getNumberOfSeats() { return numberOfSeats; } @Override public void start(){ System.out.println("car has started task2\n"); } @Override public void stop(){ System.out.println("car has stoped task2 \n"); } }
441
0.62585
0.619048
27
15.333333
17.448336
54
false
false
0
0
0
0
0
0
0.222222
false
false
13
53572cf344abce2a4dfa5c78951abd6b4c3cfbd7
4,844,723,149,402
39bf9203e801176f53f5b00b2736cf0f67dc7304
/android-project/FarmaceuticaTAES/app/src/main/java/farmaceutica/taes/farmaceutica/presentacion/controlador/util/AdaptadorListaMateriales.java
4e56a024bb250142bbd68fcbec86fc0a7f0420bd
[]
no_license
felixem/FarmaceuticaTAES
https://github.com/felixem/FarmaceuticaTAES
00c96d41fe7334145f93a1beb333baa369ecc4a1
81f8a226baca40f521e473d1548f5022cc234dc9
refs/heads/master
2021-01-10T20:39:04.288000
2016-02-07T19:43:11
2016-02-07T19:43:11
32,096,110
0
0
null
false
2016-02-07T19:43:11
2015-03-12T19:00:23
2015-03-12T19:00:23
2016-02-07T19:43:11
1,504
0
0
0
null
null
null
package farmaceutica.taes.farmaceutica.presentacion.controlador.util; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.List; import farmaceutica.taes.domainmodel.Model.MaterialPromocional; import farmaceutica.taes.domainmodel.Model.Producto; import farmaceutica.taes.farmaceutica.R; /** * Created by John on 08/04/2015. * * Este clase será modoficada en función de los valores que se quieran mostrar * a través de la consulta a la base de datos remota */ public class AdaptadorListaMateriales extends BaseAdapter { private List<MaterialPromocional> materiales; private Context context; public int getMaterialesCantidad(){return materiales.size();} public MaterialPromocional getMaterial(int posicionArray){return materiales.get(posicionArray);} @Override public int getCount() { return materiales.size(); } @Override public Object getItem(int position) { return materiales.get(position); } @Override public long getItemId(int position) { return position; } //Elemento utilizado para reutilización de instancias static class ViewHolder { TextView nombre; } public AdaptadorListaMateriales(Context context, List<MaterialPromocional> datos){ this.context=context; this.materiales =datos; } //Inflamos el elemento de la lista con los datos que queremos @Override public View getView(int position, View convertView, ViewGroup parent) { //Optimizamos la creación del layout realizándola solo una primera vez. View item= convertView; ViewHolder holder; if(item==null) { LayoutInflater inflater = LayoutInflater.from(context); holder= new ViewHolder(); item = inflater.inflate(R.layout.material_promocional, null); holder.nombre=(TextView)item.findViewById(R.id.textView_nombre); //Almacenamos el elemento en como un tag de la View item.setTag(holder); }else{ //Si el item ya ha sido instanciado con anterioridad lo recuperamos del convertView holder= (ViewHolder)item.getTag(); } holder.nombre.setText(materiales.get(position).getNombre()); return item; } }
UTF-8
Java
2,441
java
AdaptadorListaMateriales.java
Java
[ { "context": "maceutica.taes.farmaceutica.R;\n\n\n/**\n * Created by John on 08/04/2015.\n *\n * Este clase será modoficada e", "end": 470, "score": 0.8442875146865845, "start": 466, "tag": "NAME", "value": "John" } ]
null
[]
package farmaceutica.taes.farmaceutica.presentacion.controlador.util; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.List; import farmaceutica.taes.domainmodel.Model.MaterialPromocional; import farmaceutica.taes.domainmodel.Model.Producto; import farmaceutica.taes.farmaceutica.R; /** * Created by John on 08/04/2015. * * Este clase será modoficada en función de los valores que se quieran mostrar * a través de la consulta a la base de datos remota */ public class AdaptadorListaMateriales extends BaseAdapter { private List<MaterialPromocional> materiales; private Context context; public int getMaterialesCantidad(){return materiales.size();} public MaterialPromocional getMaterial(int posicionArray){return materiales.get(posicionArray);} @Override public int getCount() { return materiales.size(); } @Override public Object getItem(int position) { return materiales.get(position); } @Override public long getItemId(int position) { return position; } //Elemento utilizado para reutilización de instancias static class ViewHolder { TextView nombre; } public AdaptadorListaMateriales(Context context, List<MaterialPromocional> datos){ this.context=context; this.materiales =datos; } //Inflamos el elemento de la lista con los datos que queremos @Override public View getView(int position, View convertView, ViewGroup parent) { //Optimizamos la creación del layout realizándola solo una primera vez. View item= convertView; ViewHolder holder; if(item==null) { LayoutInflater inflater = LayoutInflater.from(context); holder= new ViewHolder(); item = inflater.inflate(R.layout.material_promocional, null); holder.nombre=(TextView)item.findViewById(R.id.textView_nombre); //Almacenamos el elemento en como un tag de la View item.setTag(holder); }else{ //Si el item ya ha sido instanciado con anterioridad lo recuperamos del convertView holder= (ViewHolder)item.getTag(); } holder.nombre.setText(materiales.get(position).getNombre()); return item; } }
2,441
0.700616
0.697331
83
28.337349
27.353235
100
false
false
0
0
0
0
0
0
0.421687
false
false
13
256e730e5a7c20c9e12f89ae8c80cf2c82e8da40
39,109,972,217,646
e57083ea584d69bc9fb1b32f5ec86bdd4fca61c0
/sample-project-5400/src/main/java/com/example/project/sample5400/other/sample8/Other8_75.java
bf63aabc4ea33f9c1b2b38c3ca326e6fd3d0d4ed
[]
no_license
snicoll-scratches/test-spring-components-index
https://github.com/snicoll-scratches/test-spring-components-index
77e0ad58c8646c7eb1d1563bf31f51aa42a0636e
aa48681414a11bb704bdbc8acabe45fa5ef2fd2d
refs/heads/main
2021-06-13T08:46:58.532000
2019-12-09T15:11:10
2019-12-09T15:11:10
65,806,297
5
3
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.project.sample5400.other.sample8; public class Other8_75 { }
UTF-8
Java
83
java
Other8_75.java
Java
[]
null
[]
package com.example.project.sample5400.other.sample8; public class Other8_75 { }
83
0.783133
0.686747
5
15.6
20.828827
53
false
false
0
0
0
0
0
0
0.2
false
false
13
eede5fc78edc7891c9b88586dbd5eaf4ab045d1f
36,318,243,493,473
2bc10c43e95e3606abb309215a9193d2db0a74fd
/Java Prog/Pro29.java
1421f8cc433bd5e27eafb1fef4c25b6c88660b70
[]
no_license
aman177/java-programs
https://github.com/aman177/java-programs
9c30e6f1890364462d227fadac9e15608f8b36ef
b84719583fbfcb999f282de0a1aaeac667eeccf8
refs/heads/master
2020-04-16T23:28:05.974000
2019-01-16T09:40:53
2019-01-16T09:40:53
166,012,663
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* Write a program to initialize an array and print them in a sorted fashion */ import java.util.*; public class Pro29{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n=sc.nextInt(); int arr[]=new int[n]; int l=arr.length; for(int i=0;i<n;i++) { arr[i]=sc.nextInt(); } int temp; int i,j; for(i=0;i<n;i++) { for( j =i+1;j<n;j++) { if(arr[i]>arr[j]) { temp=arr[j]; arr[j]=arr[i]; arr[i]=temp; } } } for( i=0;i<n;i++) { System.out.print(arr[i]); } } }
UTF-8
Java
570
java
Pro29.java
Java
[]
null
[]
/* Write a program to initialize an array and print them in a sorted fashion */ import java.util.*; public class Pro29{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n=sc.nextInt(); int arr[]=new int[n]; int l=arr.length; for(int i=0;i<n;i++) { arr[i]=sc.nextInt(); } int temp; int i,j; for(i=0;i<n;i++) { for( j =i+1;j<n;j++) { if(arr[i]>arr[j]) { temp=arr[j]; arr[j]=arr[i]; arr[i]=temp; } } } for( i=0;i<n;i++) { System.out.print(arr[i]); } } }
570
0.524561
0.514035
38
13.052631
15.389585
79
false
false
0
0
0
0
0
0
0.552632
false
false
13
de09c6d3fbdaa6de9b761e656b883404109f764b
36,352,603,228,552
a84fe9c8fd2640b9e19cd016c3a49bde0ce251db
/JavaApplication15/src/com/app/ffilters/EarJarFileFilter.java
a6a13fe134169b4bf0b6747ea6dc97d4814dea7b
[]
no_license
dariofl24/darioNBS
https://github.com/dariofl24/darioNBS
e5701db5522d5f7b71f3d06616e1d93911642c79
2f719de4ed22dfc9083ccbfad10486502aec13f9
refs/heads/master
2021-08-31T15:07:51.168000
2017-12-21T20:31:02
2017-12-21T20:31:02
115,043,526
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.app.ffilters; import java.io.File; /** * * @author Dario */ public class EarJarFileFilter extends javax.swing.filechooser.FileFilter { @Override public boolean accept(File file) { return (file != null && ( file.getName().endsWith(".jar") || file.getName().endsWith(".ear") ) ); } @Override public String getDescription() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }//class
UTF-8
Java
626
java
EarJarFileFilter.java
Java
[ { "context": "ffilters;\n\nimport java.io.File;\n\n/**\n *\n * @author Dario\n */\npublic class EarJarFileFilter extends javax.s", "end": 172, "score": 0.9960873126983643, "start": 167, "tag": "NAME", "value": "Dario" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.app.ffilters; import java.io.File; /** * * @author Dario */ public class EarJarFileFilter extends javax.swing.filechooser.FileFilter { @Override public boolean accept(File file) { return (file != null && ( file.getName().endsWith(".jar") || file.getName().endsWith(".ear") ) ); } @Override public String getDescription() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }//class
626
0.664537
0.664537
25
24.040001
34.0746
135
false
false
0
0
0
0
0
0
0.4
false
false
13
9e29654ba4cd468a3d348824f615fd0615353ef4
36,936,718,776,547
e66fa84feff4f5a8251f75e1adc7a64871449f3c
/app/src/main/java/com/weimu/chewu/origin/view/BaseActivity.java
006b82242b2e2f13365ab2aca95da834e3cb589b
[]
no_license
PursueMxy/chewu
https://github.com/PursueMxy/chewu
a26bbe8ebaba5a22f634920ff0cfb9c4d63d0446
2ecb08531aa52cdb1a22956dbc5063e39623e828
refs/heads/master
2020-09-28T01:27:02.493000
2019-12-08T13:34:23
2019-12-08T13:34:23
226,655,468
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.weimu.chewu.origin.view; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.support.annotation.LayoutRes; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.ViewGroup; import com.umeng.analytics.MobclickAgent; import com.weimu.chewu.AppData; import com.weimu.chewu.R; import com.weimu.chewu.origin.mvp.BaseView; import com.weimu.chewu.widget.WMProgressBar; import com.weimu.chewu.widget.WMToast; import butterknife.ButterKnife; import butterknife.Unbinder; /** * Author:你需要一台永动机 * Date:2018/3/7 17:24 * Description:Activity的基类 */ public abstract class BaseActivity extends AppCompatActivity implements BaseView { private Unbinder mUnbinder; @LayoutRes protected abstract int getLayoutResID(); @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); init(savedInstanceState); } protected void init(@Nullable Bundle savedInstanceState) { //PushAgent.getInstance(this).onAppStart();//统计 beforeViewAttach(savedInstanceState); setContentView(getLayoutResID()); mUnbinder = ButterKnife.bind(this); afterViewAttach(savedInstanceState); } protected void beforeViewAttach(Bundle savedInstanceState) { } protected void afterViewAttach(Bundle savedInstanceState) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//请求为竖直屏幕 } public ViewGroup getContentView() { return getWindow().getDecorView().findViewById(android.R.id.content); } @Override public void startActivityForResult(Intent intent, int requestCode) { super.startActivityForResult(intent, requestCode); overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out); } @Override public void finish() { super.finish(); overridePendingTransition(R.anim.slide_left_in, R.anim.slide_right_out); } public void finishByDefault() { super.finish(); } @Override public Context getContext() { return this; } @Override public Context getApplicationContext() { return AppData.getContext(); } @Override public AppCompatActivity getCurrentActivity() { return this; } @Override public void showToast(String message) { WMToast.show(message); } @Override public void backPreviewPage() { onBackPressed(); } @Override public void showProgressBar() { WMProgressBar.showProgressDialog(this); } @Override public void showProgressBar(String message) { WMProgressBar.showProgressDialog(this, message); } @Override public void hideProgressBar() { WMProgressBar.hideProgressDialog(); } @Override protected void onDestroy() { super.onDestroy(); mUnbinder.unbind(); } @Override protected void onResume() { super.onResume(); MobclickAgent.onResume(this); } @Override protected void onPause() { super.onPause(); MobclickAgent.onPause(this); } }
UTF-8
Java
3,338
java
BaseActivity.java
Java
[]
null
[]
package com.weimu.chewu.origin.view; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.support.annotation.LayoutRes; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.ViewGroup; import com.umeng.analytics.MobclickAgent; import com.weimu.chewu.AppData; import com.weimu.chewu.R; import com.weimu.chewu.origin.mvp.BaseView; import com.weimu.chewu.widget.WMProgressBar; import com.weimu.chewu.widget.WMToast; import butterknife.ButterKnife; import butterknife.Unbinder; /** * Author:你需要一台永动机 * Date:2018/3/7 17:24 * Description:Activity的基类 */ public abstract class BaseActivity extends AppCompatActivity implements BaseView { private Unbinder mUnbinder; @LayoutRes protected abstract int getLayoutResID(); @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); init(savedInstanceState); } protected void init(@Nullable Bundle savedInstanceState) { //PushAgent.getInstance(this).onAppStart();//统计 beforeViewAttach(savedInstanceState); setContentView(getLayoutResID()); mUnbinder = ButterKnife.bind(this); afterViewAttach(savedInstanceState); } protected void beforeViewAttach(Bundle savedInstanceState) { } protected void afterViewAttach(Bundle savedInstanceState) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//请求为竖直屏幕 } public ViewGroup getContentView() { return getWindow().getDecorView().findViewById(android.R.id.content); } @Override public void startActivityForResult(Intent intent, int requestCode) { super.startActivityForResult(intent, requestCode); overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out); } @Override public void finish() { super.finish(); overridePendingTransition(R.anim.slide_left_in, R.anim.slide_right_out); } public void finishByDefault() { super.finish(); } @Override public Context getContext() { return this; } @Override public Context getApplicationContext() { return AppData.getContext(); } @Override public AppCompatActivity getCurrentActivity() { return this; } @Override public void showToast(String message) { WMToast.show(message); } @Override public void backPreviewPage() { onBackPressed(); } @Override public void showProgressBar() { WMProgressBar.showProgressDialog(this); } @Override public void showProgressBar(String message) { WMProgressBar.showProgressDialog(this, message); } @Override public void hideProgressBar() { WMProgressBar.hideProgressDialog(); } @Override protected void onDestroy() { super.onDestroy(); mUnbinder.unbind(); } @Override protected void onResume() { super.onResume(); MobclickAgent.onResume(this); } @Override protected void onPause() { super.onPause(); MobclickAgent.onPause(this); } }
3,338
0.688599
0.685264
146
21.589041
21.815437
83
false
false
0
0
0
0
0
0
0.356164
false
false
13
b5c5a7bff5c2c213f33b5743c4aa616193f565d8
36,936,718,776,986
248689de5aaf024d75ea16e550b25ed96f43b288
/app/src/main/java/com/samourai/wallet/paynym/addPaynym/AddPaynymActivity.java
362f1a0432815a6085f49c7a62f0aa3f1f3e3494
[ "Unlicense" ]
permissive
Samourai-Wallet/samourai-wallet-android
https://github.com/Samourai-Wallet/samourai-wallet-android
42d68072613e8951744686d878dd3ab024e88bb9
c71f21a631bbc69db2bd411f2905c7f141d1523f
refs/heads/develop
2023-08-30T00:20:15.602000
2020-06-17T13:41:22
2020-06-17T13:41:22
55,045,712
706
267
Unlicense
false
2021-12-05T20:07:12
2016-03-30T08:24:06
2021-11-10T12:53:03
2021-10-18T11:41:00
39,505
550
213
94
Java
false
false
package com.samourai.wallet.paynym.addPaynym; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Intent; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.appcompat.widget.SearchView; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import android.widget.ViewSwitcher; import com.google.common.base.Splitter; import com.samourai.wallet.R; import com.samourai.wallet.bip47.BIP47Meta; import com.samourai.wallet.bip47.BIP47Util; import com.samourai.wallet.fragments.CameraFragmentBottomSheet; import com.samourai.wallet.paynym.paynymDetails.PayNymDetailsActivity; import com.samourai.wallet.util.FormatsUtil; import org.bitcoinj.core.AddressFormatException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.HashMap; import java.util.Map; import static com.samourai.wallet.bip47.BIP47Meta.strSamouraiDonationPCode; public class AddPaynymActivity extends AppCompatActivity { private SearchView mSearchView; private ViewSwitcher viewSwitcher; private RecyclerView searchPaynymList; private static final String TAG = "AddPaynymActivity"; private String pcode; private static final int EDIT_PCODE = 2000; private static final int SCAN_PCODE = 2077; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_paynym); setSupportActionBar(findViewById(R.id.toolbar_addpaynym)); viewSwitcher = findViewById(R.id.viewswitcher_addpaynym); searchPaynymList = findViewById(R.id.search_list_addpaynym); searchPaynymList.setLayoutManager(new LinearLayoutManager(this)); searchPaynymList.setAdapter(new SearchAdapter()); getSupportActionBar().setDisplayHomeAsUpEnabled(true); findViewById(R.id.add_paynym_scan_qr).setOnClickListener(view -> { CameraFragmentBottomSheet cameraFragmentBottomSheet = new CameraFragmentBottomSheet(); cameraFragmentBottomSheet.show(getSupportFragmentManager(),cameraFragmentBottomSheet.getTag()); cameraFragmentBottomSheet.setQrCodeScanLisenter(code -> { cameraFragmentBottomSheet.dismissAllowingStateLoss(); processScan(code); }); }); findViewById(R.id.add_paynym_paste).setOnClickListener(view -> { pastePcode(); }); findViewById(R.id.dev_fund_button).setOnClickListener(view -> { Intent intent = new Intent(this, PayNymDetailsActivity.class); intent.putExtra("pcode", strSamouraiDonationPCode); intent.putExtra("label", BIP47Meta.getInstance().getDisplayLabel(strSamouraiDonationPCode)); startActivityForResult(intent, EDIT_PCODE); }); } private void pastePcode() { try { ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0); processScan(item.getText().toString()); } catch (Exception ex) { Toast.makeText(this, "Unable to access Clipboard", Toast.LENGTH_SHORT).show(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.add_paynym_menu, menu); mSearchView = (SearchView) menu.findItem(R.id.action_search_addpaynym).getActionView(); menu.findItem(R.id.action_search_addpaynym).setOnActionExpandListener(new MenuItem.OnActionExpandListener() { @Override public boolean onMenuItemActionExpand(MenuItem menuItem) { viewSwitcher.showNext(); return true; } @Override public boolean onMenuItemActionCollapse(MenuItem menuItem) { viewSwitcher.showNext(); return true; } }); setUpSearch(); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { finish(); } return super.onOptionsItemSelected(item); } private void setUpSearch() { mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { return false; } }); } private void processScan(String data) { if (data.startsWith("bitcoin://") && data.length() > 10) { data = data.substring(10); } if (data.startsWith("bitcoin:") && data.length() > 8) { data = data.substring(8); } if (FormatsUtil.getInstance().isValidPaymentCode(data)) { try { if (data.equals(BIP47Util.getInstance(this).getPaymentCode().toString())) { Toast.makeText(this, R.string.bip47_cannot_scan_own_pcode, Toast.LENGTH_SHORT).show(); return; } } catch (AddressFormatException afe) { ; } Intent intent = new Intent(this, PayNymDetailsActivity.class); intent.putExtra("pcode", data); startActivityForResult(intent, EDIT_PCODE); } else if (data.contains("?") && (data.length() >= data.indexOf("?"))) { String meta = data.substring(data.indexOf("?") + 1); String _meta = null; try { Map<String, String> map = new HashMap<String, String>(); if (meta != null && meta.length() > 0) { _meta = URLDecoder.decode(meta, "UTF-8"); map = Splitter.on('&').trimResults().withKeyValueSeparator("=").split(_meta); } Intent intent = new Intent(this, PayNymDetailsActivity.class); intent.putExtra("pcode", data.substring(0, data.indexOf("?"))); intent.putExtra("label", map.containsKey("title") ? map.get("title").trim() : ""); startActivityForResult(intent, EDIT_PCODE); } catch (UnsupportedEncodingException uee) { ; } catch (Exception e) { ; } } else { Toast.makeText(this, R.string.scan_error, Toast.LENGTH_SHORT).show(); } } class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.ViewHolder> { @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new ViewHolder(LayoutInflater.from(parent.getContext()) .inflate(R.layout.paynym_list_item, parent, false)); } @Override public void onBindViewHolder(ViewHolder holder, int position) { } @Override public int getItemCount() { return 0; } class ViewHolder extends RecyclerView.ViewHolder { public ViewHolder(View itemView) { super(itemView); } } } }
UTF-8
Java
7,568
java
AddPaynymActivity.java
Java
[]
null
[]
package com.samourai.wallet.paynym.addPaynym; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Intent; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.appcompat.widget.SearchView; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import android.widget.ViewSwitcher; import com.google.common.base.Splitter; import com.samourai.wallet.R; import com.samourai.wallet.bip47.BIP47Meta; import com.samourai.wallet.bip47.BIP47Util; import com.samourai.wallet.fragments.CameraFragmentBottomSheet; import com.samourai.wallet.paynym.paynymDetails.PayNymDetailsActivity; import com.samourai.wallet.util.FormatsUtil; import org.bitcoinj.core.AddressFormatException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.HashMap; import java.util.Map; import static com.samourai.wallet.bip47.BIP47Meta.strSamouraiDonationPCode; public class AddPaynymActivity extends AppCompatActivity { private SearchView mSearchView; private ViewSwitcher viewSwitcher; private RecyclerView searchPaynymList; private static final String TAG = "AddPaynymActivity"; private String pcode; private static final int EDIT_PCODE = 2000; private static final int SCAN_PCODE = 2077; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_paynym); setSupportActionBar(findViewById(R.id.toolbar_addpaynym)); viewSwitcher = findViewById(R.id.viewswitcher_addpaynym); searchPaynymList = findViewById(R.id.search_list_addpaynym); searchPaynymList.setLayoutManager(new LinearLayoutManager(this)); searchPaynymList.setAdapter(new SearchAdapter()); getSupportActionBar().setDisplayHomeAsUpEnabled(true); findViewById(R.id.add_paynym_scan_qr).setOnClickListener(view -> { CameraFragmentBottomSheet cameraFragmentBottomSheet = new CameraFragmentBottomSheet(); cameraFragmentBottomSheet.show(getSupportFragmentManager(),cameraFragmentBottomSheet.getTag()); cameraFragmentBottomSheet.setQrCodeScanLisenter(code -> { cameraFragmentBottomSheet.dismissAllowingStateLoss(); processScan(code); }); }); findViewById(R.id.add_paynym_paste).setOnClickListener(view -> { pastePcode(); }); findViewById(R.id.dev_fund_button).setOnClickListener(view -> { Intent intent = new Intent(this, PayNymDetailsActivity.class); intent.putExtra("pcode", strSamouraiDonationPCode); intent.putExtra("label", BIP47Meta.getInstance().getDisplayLabel(strSamouraiDonationPCode)); startActivityForResult(intent, EDIT_PCODE); }); } private void pastePcode() { try { ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0); processScan(item.getText().toString()); } catch (Exception ex) { Toast.makeText(this, "Unable to access Clipboard", Toast.LENGTH_SHORT).show(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.add_paynym_menu, menu); mSearchView = (SearchView) menu.findItem(R.id.action_search_addpaynym).getActionView(); menu.findItem(R.id.action_search_addpaynym).setOnActionExpandListener(new MenuItem.OnActionExpandListener() { @Override public boolean onMenuItemActionExpand(MenuItem menuItem) { viewSwitcher.showNext(); return true; } @Override public boolean onMenuItemActionCollapse(MenuItem menuItem) { viewSwitcher.showNext(); return true; } }); setUpSearch(); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { finish(); } return super.onOptionsItemSelected(item); } private void setUpSearch() { mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { return false; } }); } private void processScan(String data) { if (data.startsWith("bitcoin://") && data.length() > 10) { data = data.substring(10); } if (data.startsWith("bitcoin:") && data.length() > 8) { data = data.substring(8); } if (FormatsUtil.getInstance().isValidPaymentCode(data)) { try { if (data.equals(BIP47Util.getInstance(this).getPaymentCode().toString())) { Toast.makeText(this, R.string.bip47_cannot_scan_own_pcode, Toast.LENGTH_SHORT).show(); return; } } catch (AddressFormatException afe) { ; } Intent intent = new Intent(this, PayNymDetailsActivity.class); intent.putExtra("pcode", data); startActivityForResult(intent, EDIT_PCODE); } else if (data.contains("?") && (data.length() >= data.indexOf("?"))) { String meta = data.substring(data.indexOf("?") + 1); String _meta = null; try { Map<String, String> map = new HashMap<String, String>(); if (meta != null && meta.length() > 0) { _meta = URLDecoder.decode(meta, "UTF-8"); map = Splitter.on('&').trimResults().withKeyValueSeparator("=").split(_meta); } Intent intent = new Intent(this, PayNymDetailsActivity.class); intent.putExtra("pcode", data.substring(0, data.indexOf("?"))); intent.putExtra("label", map.containsKey("title") ? map.get("title").trim() : ""); startActivityForResult(intent, EDIT_PCODE); } catch (UnsupportedEncodingException uee) { ; } catch (Exception e) { ; } } else { Toast.makeText(this, R.string.scan_error, Toast.LENGTH_SHORT).show(); } } class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.ViewHolder> { @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new ViewHolder(LayoutInflater.from(parent.getContext()) .inflate(R.layout.paynym_list_item, parent, false)); } @Override public void onBindViewHolder(ViewHolder holder, int position) { } @Override public int getItemCount() { return 0; } class ViewHolder extends RecyclerView.ViewHolder { public ViewHolder(View itemView) { super(itemView); } } } }
7,568
0.635703
0.630682
221
33.244343
29.443159
117
false
false
0
0
0
0
0
0
0.565611
false
false
13
7e20b12b0c90578f8c9258f039d68100bedd980d
36,017,595,767,580
99adfc5ee391f5fa62dd5093c242fd69cee3581b
/chapter04/heimaPro/demo03Calendar/Demo01CalendarMethod.java
826d47742c79eb7e0b7e57c9208d5aaf576b2312
[]
no_license
LemonYu997/Study-Java
https://github.com/LemonYu997/Study-Java
36517a9ac66b2ac2b1377fe1890036c7ca0eb514
9c6a4a02a975e4b7d730d1b79847cfe245d8fbfc
refs/heads/master
2022-12-09T03:43:59.198000
2020-09-12T14:40:19
2020-09-12T14:40:19
263,622,128
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package chapter04.heimaPro.demo03Calendar; import java.util.Calendar; import java.util.Date; /* * 常用方法: * 1、public int get(int field):返回给定日历字段的值 * 2、public void set(int field, int value):将给定的日历字段设置为给定值 * 3、public abstract void add(int field, int amount):根据日历的规则,为给定的日历字段添加或减去给定的时间量 * 4、public Date getTime():返回一个表示Calendar时间值(从历元到现在的毫秒偏移量)的Date对象 * 成员方法的参数: * int field:日历类的字段,可以使用Calendar类的静态成员变量获取 * * public static final int YEAR = 1; //年 * public static final int MONTH = 11; //月 * public static final int DATE = 20; //月中的某一天 * public static final int DAY_OF_MONTH = 5; //月中的某一天 * public static final int HOUR = 10; //时 * public static final int MINUTE = 50; //分 * public static final int SECOND = 55; //秒 */ public class Demo01CalendarMethod { public static void main(String[] args) { demo01(); demo02(); demo03(); demo04(); } /* * public int get(int field):返回给定日历字段的值 * 参数:传递指定的日历字段(YEAR,MONTH,...) * 返回值:日历字段代表的具体的值 * */ private static void demo01() { //使用getInstance方法获取Calendar对象 Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); System.out.println(year); //2020 //西方的月份0~11,东方1~12 int month = c.get(Calendar.MONTH); System.out.println(month + 1); //7 //天数 int date = c.get(Calendar.DAY_OF_MONTH); System.out.println(date); //17 System.out.println("---------------------"); } /* * public void set(int field, int value):将给定的日历字段设置为给定值 * 参数: * int field:传递指定的日历字段(YEAR,MONTH,...) * int value:给指定字段设置的值 * */ private static void demo02() { //使用getInstance方法获取Calendar对象 Calendar c = Calendar.getInstance(); //设置年为9999 c.set(Calendar.YEAR, 9999); //设置月为9月(从0计数,所以为8) c.set(Calendar.MONTH, 8); //设置天数为9日 c.set(Calendar.DATE, 9); //同时设置年月日,使用set的重载方法 c.set(8888, 8, 8); int year = c.get(Calendar.YEAR); System.out.println(year); //9999 //西方的月份0~11,东方1~12 int month = c.get(Calendar.MONTH); System.out.println(month + 1); //9 //天数 int date = c.get(Calendar.DAY_OF_MONTH); System.out.println(date); //9 System.out.println("---------------------"); } /* * public abstract void add(int field, int amount): * 根据日历的规则,为给定的日历字段添加或减去给定的时间量 * 参数: * int field:传递指定的日历字段(YEAR,MONTH,...) * int amount:增加减少指定的值 * 正数:增加 * 负数:减少 * */ private static void demo03() { //使用getInstance方法获取Calendar对象 Calendar c = Calendar.getInstance(); //把年增加两年 c.add(Calendar.YEAR, 2); //把月份减少3个月 c.add(Calendar.MONTH, -3); int year = c.get(Calendar.YEAR); System.out.println(year); //2022 //西方的月份0~11,东方1~12 int month = c.get(Calendar.MONTH); System.out.println(month + 1); //4 //天数 int date = c.get(Calendar.DAY_OF_MONTH); System.out.println(date); //17 System.out.println("---------------------"); } /* * public Date getTime():返回一个表示Calendar时间值(从历元到现在的毫秒偏移量)的Date对象 * 把日历对象转换为日期对象 * */ private static void demo04() { //使用getInstance方法获取Calendar对象 Calendar c = Calendar.getInstance(); Date date = c.getTime(); System.out.println(date); //Fri Jul 17 23:06:21 CST 2020 } }
UTF-8
Java
4,688
java
Demo01CalendarMethod.java
Java
[]
null
[]
package chapter04.heimaPro.demo03Calendar; import java.util.Calendar; import java.util.Date; /* * 常用方法: * 1、public int get(int field):返回给定日历字段的值 * 2、public void set(int field, int value):将给定的日历字段设置为给定值 * 3、public abstract void add(int field, int amount):根据日历的规则,为给定的日历字段添加或减去给定的时间量 * 4、public Date getTime():返回一个表示Calendar时间值(从历元到现在的毫秒偏移量)的Date对象 * 成员方法的参数: * int field:日历类的字段,可以使用Calendar类的静态成员变量获取 * * public static final int YEAR = 1; //年 * public static final int MONTH = 11; //月 * public static final int DATE = 20; //月中的某一天 * public static final int DAY_OF_MONTH = 5; //月中的某一天 * public static final int HOUR = 10; //时 * public static final int MINUTE = 50; //分 * public static final int SECOND = 55; //秒 */ public class Demo01CalendarMethod { public static void main(String[] args) { demo01(); demo02(); demo03(); demo04(); } /* * public int get(int field):返回给定日历字段的值 * 参数:传递指定的日历字段(YEAR,MONTH,...) * 返回值:日历字段代表的具体的值 * */ private static void demo01() { //使用getInstance方法获取Calendar对象 Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); System.out.println(year); //2020 //西方的月份0~11,东方1~12 int month = c.get(Calendar.MONTH); System.out.println(month + 1); //7 //天数 int date = c.get(Calendar.DAY_OF_MONTH); System.out.println(date); //17 System.out.println("---------------------"); } /* * public void set(int field, int value):将给定的日历字段设置为给定值 * 参数: * int field:传递指定的日历字段(YEAR,MONTH,...) * int value:给指定字段设置的值 * */ private static void demo02() { //使用getInstance方法获取Calendar对象 Calendar c = Calendar.getInstance(); //设置年为9999 c.set(Calendar.YEAR, 9999); //设置月为9月(从0计数,所以为8) c.set(Calendar.MONTH, 8); //设置天数为9日 c.set(Calendar.DATE, 9); //同时设置年月日,使用set的重载方法 c.set(8888, 8, 8); int year = c.get(Calendar.YEAR); System.out.println(year); //9999 //西方的月份0~11,东方1~12 int month = c.get(Calendar.MONTH); System.out.println(month + 1); //9 //天数 int date = c.get(Calendar.DAY_OF_MONTH); System.out.println(date); //9 System.out.println("---------------------"); } /* * public abstract void add(int field, int amount): * 根据日历的规则,为给定的日历字段添加或减去给定的时间量 * 参数: * int field:传递指定的日历字段(YEAR,MONTH,...) * int amount:增加减少指定的值 * 正数:增加 * 负数:减少 * */ private static void demo03() { //使用getInstance方法获取Calendar对象 Calendar c = Calendar.getInstance(); //把年增加两年 c.add(Calendar.YEAR, 2); //把月份减少3个月 c.add(Calendar.MONTH, -3); int year = c.get(Calendar.YEAR); System.out.println(year); //2022 //西方的月份0~11,东方1~12 int month = c.get(Calendar.MONTH); System.out.println(month + 1); //4 //天数 int date = c.get(Calendar.DAY_OF_MONTH); System.out.println(date); //17 System.out.println("---------------------"); } /* * public Date getTime():返回一个表示Calendar时间值(从历元到现在的毫秒偏移量)的Date对象 * 把日历对象转换为日期对象 * */ private static void demo04() { //使用getInstance方法获取Calendar对象 Calendar c = Calendar.getInstance(); Date date = c.getTime(); System.out.println(date); //Fri Jul 17 23:06:21 CST 2020 } }
4,688
0.52105
0.491424
130
28.6
22.285421
85
false
false
0
0
0
0
0
0
0.492308
false
false
13
ecd97c4f28584f28d903556fea6ebb01fecf8ce4
26,027,501,872,306
1707a95aa1ab7af7ca1c279770556477c7188cde
/src/main/java/neu/lab/autoexec/sensor/AutoSemanticsRisk.java
b0aa184bebe3210da4d985fd2a47e2b2b3ac4164
[]
no_license
wangcwangc/AutoExecSensor
https://github.com/wangcwangc/AutoExecSensor
a571f026db237736434c92ed74fe8de625ddeef8
10f6898ef4f569339679dd8edce91c2fcb3c4ffa
refs/heads/master
2022-07-08T08:19:50.985000
2021-08-16T15:30:47
2021-08-16T15:30:47
227,359,439
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package neu.lab.autoexec.sensor; public class AutoSemanticsRisk extends AutoSensor { public AutoSemanticsRisk(String projectDir) { super(projectDir, "risk",2); } public String getCommand() { return "mvn -f=pom.xml -DuseAllJar=false -DresultPath=/home/wwww/wangSensor/out/sensor/ -DignoreTestScope=true -Dmaven.test.skip=true neu.lab:X:1.0:semanticsRisk -e"; } }
UTF-8
Java
396
java
AutoSemanticsRisk.java
Java
[]
null
[]
package neu.lab.autoexec.sensor; public class AutoSemanticsRisk extends AutoSensor { public AutoSemanticsRisk(String projectDir) { super(projectDir, "risk",2); } public String getCommand() { return "mvn -f=pom.xml -DuseAllJar=false -DresultPath=/home/wwww/wangSensor/out/sensor/ -DignoreTestScope=true -Dmaven.test.skip=true neu.lab:X:1.0:semanticsRisk -e"; } }
396
0.714646
0.707071
11
35
47.861542
174
false
false
0
0
0
0
0
0
0.454545
false
false
13
9db1bd838cdf6935c7df29e760794de3a096538d
1,932,735,332,741
38cbabc6e5d4f91d8288256093bcd26e4734035b
/demo-service-feign/src/main/java/com/example/demoservicefeign/service/SchedualServiceHi.java
6942cda625abf1c86cb3988a489845e3c4780dcd
[]
no_license
929359291/cloud-config
https://github.com/929359291/cloud-config
10cd8e7bc36217680cf76baf55827a34420f33eb
c9b9199b15dbafa8067ccbba3c565e97efb6923d
refs/heads/master
2020-04-07T17:37:14.085000
2018-06-01T05:42:58
2018-06-01T05:42:58
124,225,581
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.demoservicefeign.service; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; /** * @desc: * @author: zengxc * @date: 2018/2/28 */ @FeignClient(value = "service-hi", fallback = SchedualServiceHiHystric.class) public interface SchedualServiceHi { @GetMapping(value = "/hi") String sayHiFromClientOne(@RequestParam("name") String name); }
UTF-8
Java
544
java
SchedualServiceHi.java
Java
[ { "context": "nnotation.RequestParam;\n\n/**\n * @desc:\n * @author: zengxc\n * @date: 2018/2/28\n */\n@FeignClient(value = \"ser", "end": 303, "score": 0.9996210932731628, "start": 297, "tag": "USERNAME", "value": "zengxc" } ]
null
[]
package com.example.demoservicefeign.service; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; /** * @desc: * @author: zengxc * @date: 2018/2/28 */ @FeignClient(value = "service-hi", fallback = SchedualServiceHiHystric.class) public interface SchedualServiceHi { @GetMapping(value = "/hi") String sayHiFromClientOne(@RequestParam("name") String name); }
544
0.775735
0.762868
19
27.631578
25.913237
77
false
false
0
0
0
0
0
0
0.368421
false
false
13
4ea40339714ad797bbc7d95e89d4e424dab77bb2
34,196,529,634,985
35b73f8d584ddef1f4854d795e0030829d226166
/works/works-masters/src/main/java/org/egov/works/masters/domain/validator/EstimateTemplateValidator.java
ac611e644fa8925059a428b90b4089827c63335e
[]
no_license
kiranmai-tarento/test
https://github.com/kiranmai-tarento/test
d8920e0c4e218d2b1747915bac50e331ec6736c6
0b54413e44fdd873ce0bc07efad24b6dcec25628
refs/heads/master
2021-09-04T08:18:31.937000
2018-01-17T07:25:44
2018-01-17T07:25:44
110,786,458
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.egov.works.masters.domain.validator; import net.minidev.json.JSONArray; import org.egov.tracer.model.CustomException; import org.egov.works.commons.utils.CommonConstants; import org.egov.works.masters.domain.service.EstimateTemplateService; import org.egov.works.masters.domain.service.ScheduleOfRateService; import org.egov.works.masters.utils.Constants; import org.egov.works.masters.web.contract.EstimateTemplate; import org.egov.works.masters.web.contract.EstimateTemplateActivities; import org.egov.works.masters.web.contract.EstimateTemplateRequest; import org.egov.works.masters.web.repository.MdmsRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; /** * Created by ramki on 3/11/17. */ @Service public class EstimateTemplateValidator { @Autowired private MdmsRepository mdmsRepository; @Autowired private ScheduleOfRateService scheduleOfRateService; @Autowired private EstimateTemplateService estimateTemplateService; public void validate(EstimateTemplateRequest estimateTemplateRequest) { JSONArray mdmsResponse = null; Map<String, String> validationMessages = new HashMap<>(); Boolean isDataValid = Boolean.FALSE; for (final EstimateTemplate estimateTemplate : estimateTemplateRequest.getEstimateTemplates()) { if ((estimateTemplate.getTypeOfWork() != null && !estimateTemplate.getTypeOfWork().isEmpty()) && (estimateTemplate.getSubTypeOfWork() != null && !estimateTemplate.getSubTypeOfWork().isEmpty())) { validationMessages.put(Constants.KEY_TYPEOFWORK_SUBTYPEOFWORK_EITHER_ONE_MANDATORY, Constants.MESSAGE_TYPEOFWORK_SUBTYPEOFWORK_EITHER_ONE_MANDATORY + estimateTemplate.getTypeOfWork() + ", " + estimateTemplate.getSubTypeOfWork()); isDataValid=Boolean.TRUE; } if (estimateTemplate.getTypeOfWork() != null && !estimateTemplate.getTypeOfWork().isEmpty()) { mdmsResponse = mdmsRepository.getByCriteria(estimateTemplate.getTenantId(), CommonConstants.MODULENAME_WORKS, CommonConstants.MASTERNAME_TYPEOFWORK, "code", estimateTemplate.getTypeOfWork(), estimateTemplateRequest.getRequestInfo()); if (mdmsResponse == null || mdmsResponse.size() == 0) { validationMessages.put(Constants.KEY_TYPEOFWORK_CODE_INVALID, Constants.MESSAGE_TYPEOFWORK_CODE_INVALID + estimateTemplate.getTypeOfWork()); isDataValid=Boolean.TRUE; } } if (estimateTemplate.getSubTypeOfWork() != null && !estimateTemplate.getSubTypeOfWork().isEmpty()) { mdmsResponse = mdmsRepository.getByCriteria(estimateTemplate.getTenantId(), CommonConstants.MODULENAME_WORKS, CommonConstants.MASTERNAME_TYPEOFWORK, "code", estimateTemplate.getSubTypeOfWork(), estimateTemplateRequest.getRequestInfo()); if (mdmsResponse == null || mdmsResponse.size() == 0) { validationMessages.put(Constants.KEY_SUBTYPEOFWORK_CODE_INVALID, Constants.MESSAGE_SUBTYPEOFWORK_CODE_INVALID + estimateTemplate.getSubTypeOfWork()); isDataValid=Boolean.TRUE; } } for(EstimateTemplateActivities estimateTemplateActivities : estimateTemplate.getEstimateTemplateActivities()) { if (estimateTemplateActivities.getScheduleOfRate() != null && !estimateTemplateActivities.getScheduleOfRate().isEmpty()) { if (scheduleOfRateService.getById(estimateTemplateActivities.getScheduleOfRate(), estimateTemplateActivities.getTenantId()) == null) { validationMessages.put(Constants.KEY_SCHEDULEOFRATE_ID_INVALID, Constants.MESSAGE_SCHEDULEOFRATE_ID_INVALID + estimateTemplateActivities.getScheduleOfRate()); isDataValid = Boolean.TRUE; } } if (estimateTemplateActivities.getUom() != null && !estimateTemplateActivities.getUom().isEmpty()) { mdmsResponse = mdmsRepository.getByCriteria(estimateTemplate.getTenantId(), CommonConstants.MODULENAME_COMMON, CommonConstants.MASTERNAME_UOM, "code", estimateTemplateActivities.getUom(), estimateTemplateRequest.getRequestInfo()); if (mdmsResponse == null || mdmsResponse.size() == 0) { validationMessages.put(Constants.KEY_UOM_CODE_INVALID, Constants.MESSAGE_UOM_CODE_INVALID + estimateTemplateActivities.getUom()); isDataValid = Boolean.TRUE; } } if (estimateTemplateActivities.getNonSOR() != null && !estimateTemplateActivities.getNonSOR().getUom().isEmpty()) { mdmsResponse = mdmsRepository.getByCriteria(estimateTemplate.getTenantId(), CommonConstants.MODULENAME_COMMON, CommonConstants.MASTERNAME_UOM, "code", estimateTemplateActivities.getNonSOR().getUom(), estimateTemplateRequest.getRequestInfo()); if (mdmsResponse == null || mdmsResponse.size() == 0) { validationMessages.put(Constants.KEY_UOM_CODE_INVALID, Constants.MESSAGE_UOM_CODE_INVALID + estimateTemplateActivities.getNonSOR().getUom()); isDataValid = Boolean.TRUE; } } } } if(isDataValid) throw new CustomException(validationMessages); } public void validateForExistance(EstimateTemplateRequest estimateTemplateRequest) { Map<String, String> validationMessages = new HashMap<>(); Boolean isDataValid = Boolean.FALSE; for (final EstimateTemplate estimateTemplate : estimateTemplateRequest.getEstimateTemplates()) { if (estimateTemplate.getCode() != null) { if (estimateTemplateService.getByCode(estimateTemplate.getCode(), estimateTemplate.getTenantId()) != null) { validationMessages.put(Constants.KEY_ESTIMATETEMPLATE_CODE_EXISTS, Constants.MESSAGE_ESTIMATETEMPLATE_CODE_EXISTS + estimateTemplate.getCode()); isDataValid = Boolean.TRUE; } } } if(isDataValid) throw new CustomException(validationMessages); } }
UTF-8
Java
6,607
java
EstimateTemplateValidator.java
Java
[ { "context": ".HashMap;\nimport java.util.Map;\n\n/**\n * Created by ramki on 3/11/17.\n */\n@Service\npublic class EstimateTem", "end": 813, "score": 0.999542236328125, "start": 808, "tag": "USERNAME", "value": "ramki" } ]
null
[]
package org.egov.works.masters.domain.validator; import net.minidev.json.JSONArray; import org.egov.tracer.model.CustomException; import org.egov.works.commons.utils.CommonConstants; import org.egov.works.masters.domain.service.EstimateTemplateService; import org.egov.works.masters.domain.service.ScheduleOfRateService; import org.egov.works.masters.utils.Constants; import org.egov.works.masters.web.contract.EstimateTemplate; import org.egov.works.masters.web.contract.EstimateTemplateActivities; import org.egov.works.masters.web.contract.EstimateTemplateRequest; import org.egov.works.masters.web.repository.MdmsRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; /** * Created by ramki on 3/11/17. */ @Service public class EstimateTemplateValidator { @Autowired private MdmsRepository mdmsRepository; @Autowired private ScheduleOfRateService scheduleOfRateService; @Autowired private EstimateTemplateService estimateTemplateService; public void validate(EstimateTemplateRequest estimateTemplateRequest) { JSONArray mdmsResponse = null; Map<String, String> validationMessages = new HashMap<>(); Boolean isDataValid = Boolean.FALSE; for (final EstimateTemplate estimateTemplate : estimateTemplateRequest.getEstimateTemplates()) { if ((estimateTemplate.getTypeOfWork() != null && !estimateTemplate.getTypeOfWork().isEmpty()) && (estimateTemplate.getSubTypeOfWork() != null && !estimateTemplate.getSubTypeOfWork().isEmpty())) { validationMessages.put(Constants.KEY_TYPEOFWORK_SUBTYPEOFWORK_EITHER_ONE_MANDATORY, Constants.MESSAGE_TYPEOFWORK_SUBTYPEOFWORK_EITHER_ONE_MANDATORY + estimateTemplate.getTypeOfWork() + ", " + estimateTemplate.getSubTypeOfWork()); isDataValid=Boolean.TRUE; } if (estimateTemplate.getTypeOfWork() != null && !estimateTemplate.getTypeOfWork().isEmpty()) { mdmsResponse = mdmsRepository.getByCriteria(estimateTemplate.getTenantId(), CommonConstants.MODULENAME_WORKS, CommonConstants.MASTERNAME_TYPEOFWORK, "code", estimateTemplate.getTypeOfWork(), estimateTemplateRequest.getRequestInfo()); if (mdmsResponse == null || mdmsResponse.size() == 0) { validationMessages.put(Constants.KEY_TYPEOFWORK_CODE_INVALID, Constants.MESSAGE_TYPEOFWORK_CODE_INVALID + estimateTemplate.getTypeOfWork()); isDataValid=Boolean.TRUE; } } if (estimateTemplate.getSubTypeOfWork() != null && !estimateTemplate.getSubTypeOfWork().isEmpty()) { mdmsResponse = mdmsRepository.getByCriteria(estimateTemplate.getTenantId(), CommonConstants.MODULENAME_WORKS, CommonConstants.MASTERNAME_TYPEOFWORK, "code", estimateTemplate.getSubTypeOfWork(), estimateTemplateRequest.getRequestInfo()); if (mdmsResponse == null || mdmsResponse.size() == 0) { validationMessages.put(Constants.KEY_SUBTYPEOFWORK_CODE_INVALID, Constants.MESSAGE_SUBTYPEOFWORK_CODE_INVALID + estimateTemplate.getSubTypeOfWork()); isDataValid=Boolean.TRUE; } } for(EstimateTemplateActivities estimateTemplateActivities : estimateTemplate.getEstimateTemplateActivities()) { if (estimateTemplateActivities.getScheduleOfRate() != null && !estimateTemplateActivities.getScheduleOfRate().isEmpty()) { if (scheduleOfRateService.getById(estimateTemplateActivities.getScheduleOfRate(), estimateTemplateActivities.getTenantId()) == null) { validationMessages.put(Constants.KEY_SCHEDULEOFRATE_ID_INVALID, Constants.MESSAGE_SCHEDULEOFRATE_ID_INVALID + estimateTemplateActivities.getScheduleOfRate()); isDataValid = Boolean.TRUE; } } if (estimateTemplateActivities.getUom() != null && !estimateTemplateActivities.getUom().isEmpty()) { mdmsResponse = mdmsRepository.getByCriteria(estimateTemplate.getTenantId(), CommonConstants.MODULENAME_COMMON, CommonConstants.MASTERNAME_UOM, "code", estimateTemplateActivities.getUom(), estimateTemplateRequest.getRequestInfo()); if (mdmsResponse == null || mdmsResponse.size() == 0) { validationMessages.put(Constants.KEY_UOM_CODE_INVALID, Constants.MESSAGE_UOM_CODE_INVALID + estimateTemplateActivities.getUom()); isDataValid = Boolean.TRUE; } } if (estimateTemplateActivities.getNonSOR() != null && !estimateTemplateActivities.getNonSOR().getUom().isEmpty()) { mdmsResponse = mdmsRepository.getByCriteria(estimateTemplate.getTenantId(), CommonConstants.MODULENAME_COMMON, CommonConstants.MASTERNAME_UOM, "code", estimateTemplateActivities.getNonSOR().getUom(), estimateTemplateRequest.getRequestInfo()); if (mdmsResponse == null || mdmsResponse.size() == 0) { validationMessages.put(Constants.KEY_UOM_CODE_INVALID, Constants.MESSAGE_UOM_CODE_INVALID + estimateTemplateActivities.getNonSOR().getUom()); isDataValid = Boolean.TRUE; } } } } if(isDataValid) throw new CustomException(validationMessages); } public void validateForExistance(EstimateTemplateRequest estimateTemplateRequest) { Map<String, String> validationMessages = new HashMap<>(); Boolean isDataValid = Boolean.FALSE; for (final EstimateTemplate estimateTemplate : estimateTemplateRequest.getEstimateTemplates()) { if (estimateTemplate.getCode() != null) { if (estimateTemplateService.getByCode(estimateTemplate.getCode(), estimateTemplate.getTenantId()) != null) { validationMessages.put(Constants.KEY_ESTIMATETEMPLATE_CODE_EXISTS, Constants.MESSAGE_ESTIMATETEMPLATE_CODE_EXISTS + estimateTemplate.getCode()); isDataValid = Boolean.TRUE; } } } if(isDataValid) throw new CustomException(validationMessages); } }
6,607
0.667323
0.66596
114
56.956139
48.348766
182
false
false
0
0
0
0
0
0
0.72807
false
false
13
549af8b0baeef207eba8352b131e062a64508c1f
37,898,791,433,269
0aa6b0cff0eb092f98209f3ffe726efb027d8758
/shop-backend-web/src/main/java/com/xiaofei/shop/controller/ProductController.java
c5b78402265ab5b207808caf77d99ee3b64867f2
[]
no_license
madlax5821/online-shop
https://github.com/madlax5821/online-shop
46be9baac985a593e7caa140deedd92696b6b9ba
1e29798426129d63ecd64ea982ad6b0711cfd294
refs/heads/main
2023-08-23T14:44:33.367000
2021-10-14T03:09:56
2021-10-14T03:09:56
416,974,539
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xiaofei.shop.controller; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.xiaofei.shop.constant.PaginationConstant; import com.xiaofei.shop.constant.ResponseStatusConstant; import com.xiaofei.shop.dto.ProductDTO; import com.xiaofei.shop.pojo.Product; import com.xiaofei.shop.pojo.ProductType; import com.xiaofei.shop.service.ProductService; import com.xiaofei.shop.service.ProductTypeService; import com.xiaofei.shop.util.ResponseResult; import com.xiaofei.shop.vo.ProductVo; import org.apache.commons.beanutils.PropertyUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.util.ObjectUtils; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpSession; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Map; /** * Author: madlax * Date: 9/9/2021, 6:03 PM * Description: */ @Controller @RequestMapping("/backend/product") public class ProductController { @Autowired private ProductTypeService service; @Autowired private ProductService productService; @ModelAttribute("productTypes") public List<ProductType> loadProductTypes(){ List<ProductType> types = service.findAllTypes(); return types; } @RequestMapping("/getAllProducts") public String getAllProducts(Integer pageNum,Map map){ if (ObjectUtils.isEmpty(pageNum)){ pageNum= PaginationConstant.PAGE_NUM; } //configure pageHelper PageHelper.startPage(pageNum,PaginationConstant.PAGE_SIZE); List<Product> products = productService.findAllProducts(); PageInfo<Product> pageInfo = new PageInfo<>(products); map.put("pageInfo",pageInfo); return "productManager"; } @RequestMapping("/addProduct") public String add(ProductVo vo, HttpSession session, Map map){ //transfer vo to DTO String uploadPath = session.getServletContext().getRealPath("/WEB-INF/upload"); ProductDTO productDTO = new ProductDTO(); try { PropertyUtils.copyProperties(productDTO,vo); productDTO.setInputStream(vo.getFile().getInputStream()); productDTO.setFileName(vo.getFile().getOriginalFilename()); productDTO.setUploadPath(uploadPath); productService.addProduct(productDTO); map.put("successMsg","添加商品成功"); } catch (Exception e) { //e.printStackTrace(); map.put("errorMsg",e.getMessage()); } return "forward:getAllProducts"; } @RequestMapping("/modifyProduct") public String modifyProduct(ProductVo vo, Map map, HttpSession session, Integer pageNum){ String path = session.getServletContext().getRealPath("/WEB-INF/upload"); ProductDTO dto = new ProductDTO(); try { PropertyUtils.copyProperties(dto,vo); dto.setInputStream(vo.getFile().getInputStream()); dto.setFileName(vo.getFile().getOriginalFilename()); dto.setUploadPath(path); map.put("successMsg","修改成功"); System.out.println(dto); productService.modifyProduct(dto); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException | IOException e) { map.put("errorMsg",e.getMessage()); } return "forward:getAllProducts?pageNum="+pageNum; } @RequestMapping("/removeProduct") @ResponseBody public ResponseResult removeProduct(long id){ productService.removeProductById(id); ResponseResult result = new ResponseResult(); result.setStatus(ResponseStatusConstant.RESPONSE_STATUS_SUCCESS); result.setMessage("删除成功"); return result; } @RequestMapping("/getProduct") @ResponseBody public ResponseResult getProductById(long id){ Product product = productService.findProductById(id); return ResponseResult.success(product); } @RequestMapping("/getImage") public void getImage(String path, OutputStream outputStream, HttpSession session){ int slash = path.lastIndexOf("/"); path = path.substring(slash); path = session.getServletContext().getRealPath("WEB-INF/upload"+path); System.out.println(path); productService.getImage(path,outputStream); } }
UTF-8
Java
4,715
java
ProductController.java
Java
[ { "context": "a.util.List;\nimport java.util.Map;\n\n/**\n * Author: madlax\n * Date: 9/9/2021, 6:03 PM\n * Description:\n */\n@C", "end": 1175, "score": 0.9994039535522461, "start": 1169, "tag": "USERNAME", "value": "madlax" } ]
null
[]
package com.xiaofei.shop.controller; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.xiaofei.shop.constant.PaginationConstant; import com.xiaofei.shop.constant.ResponseStatusConstant; import com.xiaofei.shop.dto.ProductDTO; import com.xiaofei.shop.pojo.Product; import com.xiaofei.shop.pojo.ProductType; import com.xiaofei.shop.service.ProductService; import com.xiaofei.shop.service.ProductTypeService; import com.xiaofei.shop.util.ResponseResult; import com.xiaofei.shop.vo.ProductVo; import org.apache.commons.beanutils.PropertyUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.util.ObjectUtils; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpSession; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Map; /** * Author: madlax * Date: 9/9/2021, 6:03 PM * Description: */ @Controller @RequestMapping("/backend/product") public class ProductController { @Autowired private ProductTypeService service; @Autowired private ProductService productService; @ModelAttribute("productTypes") public List<ProductType> loadProductTypes(){ List<ProductType> types = service.findAllTypes(); return types; } @RequestMapping("/getAllProducts") public String getAllProducts(Integer pageNum,Map map){ if (ObjectUtils.isEmpty(pageNum)){ pageNum= PaginationConstant.PAGE_NUM; } //configure pageHelper PageHelper.startPage(pageNum,PaginationConstant.PAGE_SIZE); List<Product> products = productService.findAllProducts(); PageInfo<Product> pageInfo = new PageInfo<>(products); map.put("pageInfo",pageInfo); return "productManager"; } @RequestMapping("/addProduct") public String add(ProductVo vo, HttpSession session, Map map){ //transfer vo to DTO String uploadPath = session.getServletContext().getRealPath("/WEB-INF/upload"); ProductDTO productDTO = new ProductDTO(); try { PropertyUtils.copyProperties(productDTO,vo); productDTO.setInputStream(vo.getFile().getInputStream()); productDTO.setFileName(vo.getFile().getOriginalFilename()); productDTO.setUploadPath(uploadPath); productService.addProduct(productDTO); map.put("successMsg","添加商品成功"); } catch (Exception e) { //e.printStackTrace(); map.put("errorMsg",e.getMessage()); } return "forward:getAllProducts"; } @RequestMapping("/modifyProduct") public String modifyProduct(ProductVo vo, Map map, HttpSession session, Integer pageNum){ String path = session.getServletContext().getRealPath("/WEB-INF/upload"); ProductDTO dto = new ProductDTO(); try { PropertyUtils.copyProperties(dto,vo); dto.setInputStream(vo.getFile().getInputStream()); dto.setFileName(vo.getFile().getOriginalFilename()); dto.setUploadPath(path); map.put("successMsg","修改成功"); System.out.println(dto); productService.modifyProduct(dto); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException | IOException e) { map.put("errorMsg",e.getMessage()); } return "forward:getAllProducts?pageNum="+pageNum; } @RequestMapping("/removeProduct") @ResponseBody public ResponseResult removeProduct(long id){ productService.removeProductById(id); ResponseResult result = new ResponseResult(); result.setStatus(ResponseStatusConstant.RESPONSE_STATUS_SUCCESS); result.setMessage("删除成功"); return result; } @RequestMapping("/getProduct") @ResponseBody public ResponseResult getProductById(long id){ Product product = productService.findProductById(id); return ResponseResult.success(product); } @RequestMapping("/getImage") public void getImage(String path, OutputStream outputStream, HttpSession session){ int slash = path.lastIndexOf("/"); path = path.substring(slash); path = session.getServletContext().getRealPath("WEB-INF/upload"+path); System.out.println(path); productService.getImage(path,outputStream); } }
4,715
0.704075
0.702155
126
36.198414
23.401608
110
false
false
0
0
0
0
0
0
0.722222
false
false
13
fbf5b8014af2173dd10a6e064098811fe648b63e
35,029,753,298,767
547616f63e596334ca8243e337a528075e62528e
/stock_02_api/src/main/java/com/mj/model/system/RoleResource.java
54e10c3f58a0b26de1cfabfc68772005a6953819
[]
no_license
yingziAz/test
https://github.com/yingziAz/test
f15495dee72c3ba87524d50646bdf13413f13ae6
7abdca5648e5d7261b9053bb70f6ff4c63e830c3
refs/heads/main
2023-08-11T15:35:00.830000
2021-09-21T06:47:50
2021-09-21T06:47:50
408,698,267
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mj.model.system; import com.mj.bean.system.BaseRoleResource; /** * Generated by JFinal. */ @SuppressWarnings("serial") public class RoleResource extends BaseRoleResource<RoleResource> { public static final RoleResource dao = new RoleResource(); }
UTF-8
Java
264
java
RoleResource.java
Java
[]
null
[]
package com.mj.model.system; import com.mj.bean.system.BaseRoleResource; /** * Generated by JFinal. */ @SuppressWarnings("serial") public class RoleResource extends BaseRoleResource<RoleResource> { public static final RoleResource dao = new RoleResource(); }
264
0.772727
0.772727
11
23
23.214417
66
false
false
0
0
0
0
0
0
0.363636
false
false
13
9b515ce337862f506510fa6ed8ecc6e552891bc0
36,180,804,524,999
d833c786ea6963f42722d23b80e05445989e8d05
/src/main/java/com/virustracker/services/AlertMailService.java
ba7dfbb8e497810867acb042e5954b9667de8cf6
[]
no_license
SJCET2021-Project-Team2/spring-boot-mysql-restAPI
https://github.com/SJCET2021-Project-Team2/spring-boot-mysql-restAPI
6e4723617680d8eec716dd612cdf8b6983fbaeb0
18564e78fcfd25b20b3efee640db4e20354e7265
refs/heads/main
2023-06-08T22:32:24.361000
2021-07-04T04:03:50
2021-07-04T04:03:50
350,431,083
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.virustracker.services; import java.util.Properties; import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.stereotype.Service; import com.virustracker.entity.AlertMail; @Service public class AlertMailService { @Value("${spring.mail.properties.mail.smtp.starttls.enable}") private boolean starttls; @Value("${spring.mail.host}") private String host; @Value("${spring.mail.username}") private String username; @Value("${spring.mail.password}") private String password; @Value("${spring.mail.port}") private int port; public JavaMailSender getJavaMailSender() { JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost(this.host); mailSender.setPort(this.port); mailSender.setUsername(this.username); mailSender.setPassword(this.password); Properties props = mailSender.getJavaMailProperties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.debug", "true"); return mailSender; } public void sendAlertMail(AlertMail alertMail) { SimpleMailMessage msg = new SimpleMailMessage(); msg.setFrom(username); msg.setTo(alertMail.getUserMailId()); msg.setSubject("Virus Tracker Alert"); msg.setText(alertMail.getAlertMsg()); JavaMailSender javaMailSender = this.getJavaMailSender(); javaMailSender.send(msg); System.out.println("Email sent successfully to " + alertMail.getUserMailId()); } }
UTF-8
Java
1,675
java
AlertMailService.java
Java
[ { "context": "setPort(this.port);\n\t\tmailSender.setUsername(this.username);\n\t\tmailSender.setPassword(this.password);\n\t\tProp", "end": 954, "score": 0.6660282611846924, "start": 946, "tag": "USERNAME", "value": "username" }, { "context": "name(this.username);\n\t\tmailSender.setPassword(this.password);\n\t\tProperties props = mailSender.getJavaMailProp", "end": 995, "score": 0.6789070963859558, "start": 987, "tag": "PASSWORD", "value": "password" } ]
null
[]
package com.virustracker.services; import java.util.Properties; import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.stereotype.Service; import com.virustracker.entity.AlertMail; @Service public class AlertMailService { @Value("${spring.mail.properties.mail.smtp.starttls.enable}") private boolean starttls; @Value("${spring.mail.host}") private String host; @Value("${spring.mail.username}") private String username; @Value("${spring.mail.password}") private String password; @Value("${spring.mail.port}") private int port; public JavaMailSender getJavaMailSender() { JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost(this.host); mailSender.setPort(this.port); mailSender.setUsername(this.username); mailSender.setPassword(this.<PASSWORD>); Properties props = mailSender.getJavaMailProperties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.debug", "true"); return mailSender; } public void sendAlertMail(AlertMail alertMail) { SimpleMailMessage msg = new SimpleMailMessage(); msg.setFrom(username); msg.setTo(alertMail.getUserMailId()); msg.setSubject("Virus Tracker Alert"); msg.setText(alertMail.getAlertMsg()); JavaMailSender javaMailSender = this.getJavaMailSender(); javaMailSender.send(msg); System.out.println("Email sent successfully to " + alertMail.getUserMailId()); } }
1,677
0.768358
0.768358
54
30.018518
20.860641
80
false
false
0
0
0
0
0
0
1.648148
false
false
13
7d00064e2d672c5924fb99a5b0df4c48bd322e62
13,288,628,816,058
adebd1893add1e619c370d12f6ad1d68f8f2e2d0
/app/src/main/java/com/example/testlocation/MainActivity.java
dc465f0d2655e010d1e9eafd0e5e679bda414435
[]
no_license
mrbqxu/TestLocation
https://github.com/mrbqxu/TestLocation
6ad70fc4b4918fd8079d7196cb311b6f3fabb42e
0ade4575d0266133c4701a908a94d5136af6e5ad
refs/heads/master
2020-12-02T20:17:02.469000
2016-09-11T17:28:22
2016-09-11T17:28:22
67,944,037
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.testlocation; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.util.List; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private static final String TAG = "MainActivity"; private static final int MY_PERMISSION_LOCATION = 100; private Button startLocationUpdate, stopLocationUpdate; private TextView positionTextView; private LocationManager locationManager; private String provider; LocationListener locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { showLocation(location); } @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { } }; @Override public void onClick(View view) { switch (view.getId()){ case R.id.start_location_update: checkAndRequestPermission(); Location location = locationManager.getLastKnownLocation(provider); if(location!=null){ showLocation(location); } locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10 * 1000, //10 sec 10, //10 meter locationListener); break; case R.id.stop_location_update: stopLocationListener(); break; default: break; } } private void stopLocationListener(){ if(locationManager!=null){ try { locationManager.removeUpdates(locationListener); }catch (SecurityException ex){ ex.printStackTrace(); } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "onCreate()"); setContentView(R.layout.activity_main); startLocationUpdate = (Button)findViewById(R.id.start_location_update); stopLocationUpdate = (Button)findViewById(R.id.stop_location_update); positionTextView = (TextView)findViewById(R.id.position_text_view); startLocationUpdate.setOnClickListener(this); stopLocationUpdate.setOnClickListener(this); locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); checkAndRequestPermission(); List<String> providerList = locationManager.getProviders(true); if(providerList.contains(LocationManager.GPS_PROVIDER)){ provider = LocationManager.GPS_PROVIDER; } else if (providerList.contains(LocationManager.NETWORK_PROVIDER)){ provider = LocationManager.NETWORK_PROVIDER; } else { Toast.makeText(this, "No location provider to use", Toast.LENGTH_LONG).show(); return; } } @Override protected void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy()"); stopLocationListener(); } private void showLocation(Location location){ String currentPosition = location.getLatitude() + ", " + location.getLongitude(); positionTextView.setText(currentPosition); } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode) { case MY_PERMISSION_LOCATION: if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission Granted Toast.makeText(this, "permission is granted successfully", Toast.LENGTH_SHORT).show(); } else { // Permission Denied Toast.makeText(this, "permission is denied", Toast.LENGTH_SHORT).show(); } break; default: super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } private void checkAndRequestPermission() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, "Please grant this App the permission to get LOCATION service at this device", Toast.LENGTH_LONG).show(); ActivityCompat.requestPermissions( this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION }, MY_PERMISSION_LOCATION ); } } }
UTF-8
Java
5,256
java
MainActivity.java
Java
[]
null
[]
package com.example.testlocation; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.util.List; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private static final String TAG = "MainActivity"; private static final int MY_PERMISSION_LOCATION = 100; private Button startLocationUpdate, stopLocationUpdate; private TextView positionTextView; private LocationManager locationManager; private String provider; LocationListener locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { showLocation(location); } @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { } }; @Override public void onClick(View view) { switch (view.getId()){ case R.id.start_location_update: checkAndRequestPermission(); Location location = locationManager.getLastKnownLocation(provider); if(location!=null){ showLocation(location); } locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10 * 1000, //10 sec 10, //10 meter locationListener); break; case R.id.stop_location_update: stopLocationListener(); break; default: break; } } private void stopLocationListener(){ if(locationManager!=null){ try { locationManager.removeUpdates(locationListener); }catch (SecurityException ex){ ex.printStackTrace(); } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "onCreate()"); setContentView(R.layout.activity_main); startLocationUpdate = (Button)findViewById(R.id.start_location_update); stopLocationUpdate = (Button)findViewById(R.id.stop_location_update); positionTextView = (TextView)findViewById(R.id.position_text_view); startLocationUpdate.setOnClickListener(this); stopLocationUpdate.setOnClickListener(this); locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); checkAndRequestPermission(); List<String> providerList = locationManager.getProviders(true); if(providerList.contains(LocationManager.GPS_PROVIDER)){ provider = LocationManager.GPS_PROVIDER; } else if (providerList.contains(LocationManager.NETWORK_PROVIDER)){ provider = LocationManager.NETWORK_PROVIDER; } else { Toast.makeText(this, "No location provider to use", Toast.LENGTH_LONG).show(); return; } } @Override protected void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy()"); stopLocationListener(); } private void showLocation(Location location){ String currentPosition = location.getLatitude() + ", " + location.getLongitude(); positionTextView.setText(currentPosition); } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode) { case MY_PERMISSION_LOCATION: if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission Granted Toast.makeText(this, "permission is granted successfully", Toast.LENGTH_SHORT).show(); } else { // Permission Denied Toast.makeText(this, "permission is denied", Toast.LENGTH_SHORT).show(); } break; default: super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } private void checkAndRequestPermission() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, "Please grant this App the permission to get LOCATION service at this device", Toast.LENGTH_LONG).show(); ActivityCompat.requestPermissions( this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION }, MY_PERMISSION_LOCATION ); } } }
5,256
0.635084
0.631469
154
33.129871
29.477859
138
false
false
0
0
0
0
0
0
0.558442
false
false
13
f2154774196cc595d8c53437324d6b34b5751cb5
34,179,349,780,258
79aceab8f48dae078ab344334af125eed062891c
/src/main/java/kawac/common/lib/computer/Computer.java
355a22ec605e105a1d35548bf3b2b4d3359685d7
[]
no_license
s0cks/KawaComputers
https://github.com/s0cks/KawaComputers
b03f3aa9da5d32e6960f9626d0d4796119444763
aca1af44bb0b9a4d2232e3dac8fcfc0fb727c41c
refs/heads/master
2021-01-13T02:19:20.168000
2015-03-17T02:28:05
2015-03-17T02:28:05
32,277,053
3
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package kawac.common.lib.computer; import com.google.common.jimfs.Configuration; import com.google.common.jimfs.Jimfs; import java.nio.file.FileSystem; public final class Computer{ public final FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix()); public Computer(){ } private void initFileSystem(){ } }
UTF-8
Java
343
java
Computer.java
Java
[]
null
[]
package kawac.common.lib.computer; import com.google.common.jimfs.Configuration; import com.google.common.jimfs.Jimfs; import java.nio.file.FileSystem; public final class Computer{ public final FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix()); public Computer(){ } private void initFileSystem(){ } }
343
0.74344
0.74344
18
18.111111
22.402601
83
false
false
0
0
0
0
0
0
0.277778
false
false
13
856ddeeb14bfb727305c9eeacbc941eebd3d73d2
35,407,710,415,528
a58c747d7f63cd3b408e8db13c6c95936d6291ef
/Lab5/Lab5q10.java
08df212280c812bd17de2fe4a25f0b2aca325f0c
[]
no_license
Trev2689/SecondYearWork
https://github.com/Trev2689/SecondYearWork
1a6742b4b3e1cf70f98e25564da439332798808b
4372fadbbf919a927c4f74e1fbaf2b54f6d1cc73
refs/heads/master
2020-03-18T18:06:07.906000
2019-01-31T12:43:28
2019-01-31T12:43:28
135,071,540
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ie.ITCarlow.OOSD.Lab5; import java.util.Scanner; public class Lab5q10 { public static void main(String[] args) { int num; int largest=0; int smallest=Integer.MAX_VALUE; int count=0; Scanner input = new Scanner(System.in); System.out.println("Please enter a non zero integer to begin"); num=input.nextInt(); while(num!=0) { System.out.println("Please enter an integer "); num=input.nextInt(); count++; if(num>largest) { largest=num; } if(num<smallest&&num!=0) { smallest=num; } } System.out.println("The amount of numbers you entered was " +count); System.out.println("The largest number you entered was " +largest); System.out.println("The smallest number not including zero you entered was " +smallest); } }
UTF-8
Java
836
java
Lab5q10.java
Java
[]
null
[]
package ie.ITCarlow.OOSD.Lab5; import java.util.Scanner; public class Lab5q10 { public static void main(String[] args) { int num; int largest=0; int smallest=Integer.MAX_VALUE; int count=0; Scanner input = new Scanner(System.in); System.out.println("Please enter a non zero integer to begin"); num=input.nextInt(); while(num!=0) { System.out.println("Please enter an integer "); num=input.nextInt(); count++; if(num>largest) { largest=num; } if(num<smallest&&num!=0) { smallest=num; } } System.out.println("The amount of numbers you entered was " +count); System.out.println("The largest number you entered was " +largest); System.out.println("The smallest number not including zero you entered was " +smallest); } }
836
0.632775
0.623206
36
21.194445
22.644375
90
false
false
0
0
0
0
0
0
2.305556
false
false
13
46ec4baa8553c9a1bc24a46ceddcebf22244cca9
34,291,018,913,670
5f3a637ef933be4d126b820d28184a84acb11dc9
/src/main/java/com/james/purchaselist/controller/CrudController.java
e27320308dbd39ad91efbaaa0c7d172fb5591241
[]
no_license
YoungJunSohn/purchaselist
https://github.com/YoungJunSohn/purchaselist
2e52ce1257f52e4ec71c6a0398af5ca2da3db8e5
9f717cb6deb072bc775d2d37f444de0a2ea19dc1
refs/heads/master
2023-03-31T09:25:41.117000
2021-04-09T08:57:36
2021-04-09T08:57:36
353,985,325
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.james.purchaselist.controller; import com.james.purchaselist.domain.model.network.CrudInterface; import com.james.purchaselist.domain.model.network.Header; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.*; @Slf4j public abstract class CrudController<Req, Resp> implements CrudInterface<Req, Resp> { //상속받는 클래스에서만 접근이 가능하며, Req와 Resp를 가지고 있는 baseService 선언 protected CrudInterface<Req, Resp> baseService; @Override @PostMapping("") public Header<Resp> create(@RequestBody Header<Req> request) { log.info("CrudController [create]: ", request); return baseService.create(request); } @Override @GetMapping("/{id}") public Header<Resp> read(@PathVariable Long id) { log.info("CrudController [read]: ", id); return baseService.read(id); } @Override @PutMapping("") public Header<Resp> update(@RequestBody Header<Req> request) { log.info("CrudController [update]: ", request); return baseService.update(request); } @Override @DeleteMapping("/{id}") public Header<Resp> delete(@PathVariable Long id) { log.info("CrudController [delete]: ", id); return baseService.delete(id); } }
UTF-8
Java
1,314
java
CrudController.java
Java
[]
null
[]
package com.james.purchaselist.controller; import com.james.purchaselist.domain.model.network.CrudInterface; import com.james.purchaselist.domain.model.network.Header; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.*; @Slf4j public abstract class CrudController<Req, Resp> implements CrudInterface<Req, Resp> { //상속받는 클래스에서만 접근이 가능하며, Req와 Resp를 가지고 있는 baseService 선언 protected CrudInterface<Req, Resp> baseService; @Override @PostMapping("") public Header<Resp> create(@RequestBody Header<Req> request) { log.info("CrudController [create]: ", request); return baseService.create(request); } @Override @GetMapping("/{id}") public Header<Resp> read(@PathVariable Long id) { log.info("CrudController [read]: ", id); return baseService.read(id); } @Override @PutMapping("") public Header<Resp> update(@RequestBody Header<Req> request) { log.info("CrudController [update]: ", request); return baseService.update(request); } @Override @DeleteMapping("/{id}") public Header<Resp> delete(@PathVariable Long id) { log.info("CrudController [delete]: ", id); return baseService.delete(id); } }
1,314
0.681458
0.679081
42
29.047619
24.663403
85
false
false
0
0
0
0
0
0
0.52381
false
false
13
540dd4cf6ad374acf5bc89dd563bd0f7013319fc
25,220,048,007,571
7d3870658c188c0bd5e4f381901f8cee431825d6
/JAVA/src/main/java/Lab1/Question.java
4d47f07ef7159799655c1580cf2e462ecaec9107
[]
no_license
zrmzack/SheffieldLife
https://github.com/zrmzack/SheffieldLife
267a61b2f848f3fa64d69430b2f14e44b57ee3e2
7c5b34ddc3bb54b11e8116190cd840643c59a4e7
refs/heads/master
2022-12-22T21:02:48.371000
2020-04-20T22:03:10
2020-04-20T22:03:10
220,312,220
1
1
null
false
2022-12-16T01:25:08
2019-11-07T19:21:22
2020-04-20T22:03:32
2022-12-16T01:25:05
9,551
1
1
15
Jupyter Notebook
false
false
package Lab1; import java.util.Random; import java.util.Scanner; /** * @author zack * @create 2019-11-11-4:22 */ public class Question { private int answer; private int x; private int y; //record the mark people get private int mark = 0; //judge '+' || '-' private char judge() { int x = new Random().nextInt(2); if (x == 0) { return '-'; } else { return '+'; } } //generate question private void generate() { Random random = new Random(); x = random.nextInt(20); y = random.nextInt(20); if (judge() == '-') { if (x >= y) { System.out.println(x + "-" + y); //set answers this.setAnswer(x - y); } else { System.out.println(y + "-" + x); this.setAnswer(y - x); } } else { System.out.println(y + "+" + x); this.setAnswer(y + x); } } //judge the answers right or wrong private boolean judgeanswer(int userInput) { if (this.getAnswer() == userInput) { System.out.println("Correct, well done"); return true; } else { System.out.println("The correct answer is " + this.getAnswer()); return false; } } public int getAnswer() { return answer; } public void setAnswer(int answer) { this.answer = answer; } //get all those questions public int getallquestions() { for (int x = 0; x < 10; x++) { System.out.print("Question " + (x + 1) + ": "); generate(); System.out.print("Answer?"); int userinput = new Scanner(System.in).nextInt(); if (judgeanswer(userinput)) { this.mark += 1; } } return mark; } }
UTF-8
Java
1,929
java
Question.java
Java
[ { "context": ".Random;\nimport java.util.Scanner;\n\n/**\n * @author zack\n * @create 2019-11-11-4:22\n */\npublic class Qu", "end": 83, "score": 0.854606032371521, "start": 82, "tag": "NAME", "value": "z" }, { "context": "andom;\nimport java.util.Scanner;\n\n/**\n * @author zack\n * @create 2019-11-11-4:22\n */\npublic class Quest", "end": 86, "score": 0.5644124150276184, "start": 83, "tag": "USERNAME", "value": "ack" } ]
null
[]
package Lab1; import java.util.Random; import java.util.Scanner; /** * @author zack * @create 2019-11-11-4:22 */ public class Question { private int answer; private int x; private int y; //record the mark people get private int mark = 0; //judge '+' || '-' private char judge() { int x = new Random().nextInt(2); if (x == 0) { return '-'; } else { return '+'; } } //generate question private void generate() { Random random = new Random(); x = random.nextInt(20); y = random.nextInt(20); if (judge() == '-') { if (x >= y) { System.out.println(x + "-" + y); //set answers this.setAnswer(x - y); } else { System.out.println(y + "-" + x); this.setAnswer(y - x); } } else { System.out.println(y + "+" + x); this.setAnswer(y + x); } } //judge the answers right or wrong private boolean judgeanswer(int userInput) { if (this.getAnswer() == userInput) { System.out.println("Correct, well done"); return true; } else { System.out.println("The correct answer is " + this.getAnswer()); return false; } } public int getAnswer() { return answer; } public void setAnswer(int answer) { this.answer = answer; } //get all those questions public int getallquestions() { for (int x = 0; x < 10; x++) { System.out.print("Question " + (x + 1) + ": "); generate(); System.out.print("Answer?"); int userinput = new Scanner(System.in).nextInt(); if (judgeanswer(userinput)) { this.mark += 1; } } return mark; } }
1,929
0.4676
0.455158
80
23.125
16.421309
76
false
false
0
0
0
0
0
0
0.45
false
false
13
e0bbadf7940cfe17fed8db9b04be246692980288
34,926,674,091,327
4a39d14a3be914fac9125c7a40004e2472d3bb1b
/Examples/src/com/home/string/SolutionStreet.java
cf868bc243b1c61034646479cec22917089bb098
[]
no_license
manasvij2ee/Git-Workspace
https://github.com/manasvij2ee/Git-Workspace
9d927b98da596ee48b90e82ae4be82452679a60a
8ecaa42d529c42f95cea481ba594f8e54fa8f2dc
refs/heads/master
2021-04-15T09:41:27.960000
2018-04-27T18:08:33
2018-04-27T18:08:33
126,626,027
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.home.string; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Scanner; public class SolutionStreet { //Write a function that accepts a single string input and returns the first non-repeated character. //"AABBCDD" //"AABBCCDEEFF" public static void main(String[] args) { //String inputString = "AABBCCDEEFF"; System.out.println("Enter input String: "); Scanner sc = new Scanner(System.in); String inputString = sc.nextLine(); sc.close(); String output = getFirstNonRepeatedCharacter(inputString); System.out.println(output); } private static String getFirstNonRepeatedCharacter(String inputString) { Map<String, Integer> charMap = new LinkedHashMap<>(); for(int i = 0; i < inputString.length(); i++) { String key = String.valueOf(inputString.charAt(i)); Integer count = charMap.get(key); if(count != null) { count = count + 1; charMap.put(key, count); } else { charMap.put(key, 1); } } for(Entry<String, Integer> entry : charMap.entrySet()) { if(entry.getValue() == 1) { return entry.getKey(); } } return null; } }
UTF-8
Java
1,209
java
SolutionStreet.java
Java
[ { "context": "st non-repeated character.\r\n\t//\"AABBCDD\"\r\n\t//\"AABBCCDEEFF\" \r\n\tpublic static void main(String[] args) {\r\n", "end": 303, "score": 0.5288554430007935, "start": 299, "tag": "KEY", "value": "CCDE" }, { "context": "n(String[] args) {\r\n\t\t//String inputString = \"AABBCCDEEFF\";\r\n\t\tSystem.out.println(\"Enter input String: \"", "end": 387, "score": 0.608515739440918, "start": 383, "tag": "KEY", "value": "CCDE" } ]
null
[]
package com.home.string; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Scanner; public class SolutionStreet { //Write a function that accepts a single string input and returns the first non-repeated character. //"AABBCDD" //"AABBCCDEEFF" public static void main(String[] args) { //String inputString = "AABBCCDEEFF"; System.out.println("Enter input String: "); Scanner sc = new Scanner(System.in); String inputString = sc.nextLine(); sc.close(); String output = getFirstNonRepeatedCharacter(inputString); System.out.println(output); } private static String getFirstNonRepeatedCharacter(String inputString) { Map<String, Integer> charMap = new LinkedHashMap<>(); for(int i = 0; i < inputString.length(); i++) { String key = String.valueOf(inputString.charAt(i)); Integer count = charMap.get(key); if(count != null) { count = count + 1; charMap.put(key, count); } else { charMap.put(key, 1); } } for(Entry<String, Integer> entry : charMap.entrySet()) { if(entry.getValue() == 1) { return entry.getKey(); } } return null; } }
1,209
0.655087
0.651778
43
26.11628
22.261877
100
false
false
0
0
0
0
0
0
2.55814
false
false
13
25732fa7870bb6afc8c5806d3f355248f4572559
15,195,594,347,054
7ced6c0ed03f2f9345bbc06a09dbbcf5c8687619
/catering-basic-server/catering-merchant/catering-merchant-server/src/main/java/com/meiyuan/catering/merchant/dao/CateringShopEmployeeMapper.java
44f6743b65a224c582e4ddb3aad220f6c928267d
[]
no_license
haorq/food-word
https://github.com/haorq/food-word
c14d5752c6492aed4a6a1410f9e0352479460da0
18a71259d77b4d96261dab8ed51ca1f109ab5c2f
refs/heads/master
2023-01-01T12:19:48.967000
2020-10-26T07:32:25
2020-10-26T07:32:25
307,292,398
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.meiyuan.catering.merchant.dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.meiyuan.catering.merchant.dto.shop.ShopEmployeeDTO; import com.meiyuan.catering.merchant.dto.shop.config.EmployeeQueryPageDTO; import com.meiyuan.catering.merchant.entity.CateringShopEmployeeEntity; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import java.util.List; /** * @author fql */ @Mapper public interface CateringShopEmployeeMapper extends BaseMapper<CateringShopEmployeeEntity> { /** * 方法描述 : 员工列表 * @param dto 查询条件 * @param page 分页 * @return 员工列表 */ IPage<ShopEmployeeDTO> queryPageShopEmployee(@Param("page") Page page, @Param("dto") EmployeeQueryPageDTO dto); /** * describe: 查询所有有效电话号码 * @author: fql * @date: 2020/9/30 18:05 * @return: {@link List<String>} * @version 1.5.0 **/ @Select("select phone from catering_shop_employee where is_del = 0") List<String> selectAll(); CateringShopEmployeeEntity selectByPhone(@Param("phone") String phone); }
UTF-8
Java
1,327
java
CateringShopEmployeeMapper.java
Java
[ { "context": "s.Select;\n\nimport java.util.List;\n\n\n/**\n * @author fql\n */\n@Mapper\npublic interface CateringShopEmployee", "end": 608, "score": 0.9996411800384521, "start": 605, "tag": "USERNAME", "value": "fql" }, { "context": " /**\n * describe: 查询所有有效电话号码\n * @author: fql\n * @date: 2020/9/30 18:05\n * @return: {@l", "end": 987, "score": 0.9996299743652344, "start": 984, "tag": "USERNAME", "value": "fql" } ]
null
[]
package com.meiyuan.catering.merchant.dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.meiyuan.catering.merchant.dto.shop.ShopEmployeeDTO; import com.meiyuan.catering.merchant.dto.shop.config.EmployeeQueryPageDTO; import com.meiyuan.catering.merchant.entity.CateringShopEmployeeEntity; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import java.util.List; /** * @author fql */ @Mapper public interface CateringShopEmployeeMapper extends BaseMapper<CateringShopEmployeeEntity> { /** * 方法描述 : 员工列表 * @param dto 查询条件 * @param page 分页 * @return 员工列表 */ IPage<ShopEmployeeDTO> queryPageShopEmployee(@Param("page") Page page, @Param("dto") EmployeeQueryPageDTO dto); /** * describe: 查询所有有效电话号码 * @author: fql * @date: 2020/9/30 18:05 * @return: {@link List<String>} * @version 1.5.0 **/ @Select("select phone from catering_shop_employee where is_del = 0") List<String> selectAll(); CateringShopEmployeeEntity selectByPhone(@Param("phone") String phone); }
1,327
0.735225
0.723404
42
29.214285
29.138859
115
false
false
0
0
0
0
0
0
0.357143
false
false
13
b510074a989106ce15e6e1c76dd3f6454d6eeda3
9,740,985,883,147
691c996821d12db6c3972e604789a6d2581427cb
/app/src/main/java/com/ufc/phdestination/ph_guide/View/Adapters/TopDestinationsHorizontalAdapter.java
4ec050f317d58b3f8102710c2744fcbe9c6a10f1
[]
no_license
Leehongo/PH-guide
https://github.com/Leehongo/PH-guide
bfccbfe7385ef1689b2e9991bb23a7fc33576f23
ff958cc04c11c45d7289a5ed52f10e4c96e2335e
refs/heads/master
2021-01-21T09:42:24.986000
2017-09-20T07:21:52
2017-09-20T07:21:52
83,879,532
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ufc.phdestination.ph_guide.View.Adapters; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.support.v4.app.ActivityOptionsCompat; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.ufc.phdestination.ph_guide.Controller.tools.Utilities; import com.ufc.phdestination.ph_guide.Model.Destination; import com.ufc.phdestination.ph_guide.R; import com.ufc.phdestination.ph_guide.View.Activities.DestinationDetailActivity; import java.util.ArrayList; import java.util.List; public class TopDestinationsHorizontalAdapter extends RecyclerView.Adapter<TopDestinationsHorizontalAdapter.MyViewHolder> { private static final String TAG = "TopDestinationsAdapter"; List<Destination> topDestinationList = new ArrayList<Destination>(); private Context mContext; View itemView; public class MyViewHolder extends RecyclerView.ViewHolder{ public TextView name; public ImageView image; public ProgressBar progressBar; public MyViewHolder(View view) { super(view); name = (TextView) view.findViewById(R.id.destination_name); image = (ImageView) view.findViewById(R.id.destination_image); progressBar = (ProgressBar) view.findViewById(R.id.progress_bar); } } public TopDestinationsHorizontalAdapter(Context mContext, List<Destination> topDestinationList){ this.mContext = mContext; Log.d(TAG,"size: " + topDestinationList.size()); this.topDestinationList = topDestinationList; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.topdestination_horizontal_list_item, parent, false); return new MyViewHolder(itemView); } @Override public void onBindViewHolder(final MyViewHolder viewHolder, final int position) { final Destination destination = topDestinationList.get(position); viewHolder.name.setText(destination.getDestinationName()); Utilities.loadImageFromURL(this.mContext, viewHolder.progressBar, viewHolder.image, destination.getImage()); viewHolder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { switch (view.getId()){ case R.id.destination_card_view: Intent intent = new Intent(view.getContext(), DestinationDetailActivity.class); intent.putExtra("destination", destination); ActivityOptionsCompat options = ActivityOptionsCompat. makeSceneTransitionAnimation((Activity)view.getContext(), view.findViewById(R.id.destination_card_view), mContext.getString(R.string.destination_image_trans)); view.getContext().startActivity(intent, options.toBundle()); break; } } }); } @Override public int getItemCount() { return topDestinationList.size(); } }
UTF-8
Java
3,386
java
TopDestinationsHorizontalAdapter.java
Java
[]
null
[]
package com.ufc.phdestination.ph_guide.View.Adapters; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.support.v4.app.ActivityOptionsCompat; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.ufc.phdestination.ph_guide.Controller.tools.Utilities; import com.ufc.phdestination.ph_guide.Model.Destination; import com.ufc.phdestination.ph_guide.R; import com.ufc.phdestination.ph_guide.View.Activities.DestinationDetailActivity; import java.util.ArrayList; import java.util.List; public class TopDestinationsHorizontalAdapter extends RecyclerView.Adapter<TopDestinationsHorizontalAdapter.MyViewHolder> { private static final String TAG = "TopDestinationsAdapter"; List<Destination> topDestinationList = new ArrayList<Destination>(); private Context mContext; View itemView; public class MyViewHolder extends RecyclerView.ViewHolder{ public TextView name; public ImageView image; public ProgressBar progressBar; public MyViewHolder(View view) { super(view); name = (TextView) view.findViewById(R.id.destination_name); image = (ImageView) view.findViewById(R.id.destination_image); progressBar = (ProgressBar) view.findViewById(R.id.progress_bar); } } public TopDestinationsHorizontalAdapter(Context mContext, List<Destination> topDestinationList){ this.mContext = mContext; Log.d(TAG,"size: " + topDestinationList.size()); this.topDestinationList = topDestinationList; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.topdestination_horizontal_list_item, parent, false); return new MyViewHolder(itemView); } @Override public void onBindViewHolder(final MyViewHolder viewHolder, final int position) { final Destination destination = topDestinationList.get(position); viewHolder.name.setText(destination.getDestinationName()); Utilities.loadImageFromURL(this.mContext, viewHolder.progressBar, viewHolder.image, destination.getImage()); viewHolder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { switch (view.getId()){ case R.id.destination_card_view: Intent intent = new Intent(view.getContext(), DestinationDetailActivity.class); intent.putExtra("destination", destination); ActivityOptionsCompat options = ActivityOptionsCompat. makeSceneTransitionAnimation((Activity)view.getContext(), view.findViewById(R.id.destination_card_view), mContext.getString(R.string.destination_image_trans)); view.getContext().startActivity(intent, options.toBundle()); break; } } }); } @Override public int getItemCount() { return topDestinationList.size(); } }
3,386
0.699646
0.699055
93
35.408604
36.125599
191
false
false
0
0
0
0
0
0
0.634409
false
false
13
f582ba24ac1c4a2643e4d2a20a9b2040a7f22a5b
37,383,395,351,505
addbc404a75281f8ad0d42889ffe507b72a2471e
/Day20190618/src/kr/co/bit/For_Test1.java
bfe3eb78ab52583d6ef83f3075e711f1fd33efcd
[]
no_license
yongje93/bitcamp
https://github.com/yongje93/bitcamp
81df3b0d954e57752243ecc339ccb92447d71561
16f105c4cd6baa5b876291b2504338b6acfb2938
refs/heads/master
2020-06-07T17:57:26.427000
2019-10-05T12:27:31
2019-10-05T12:27:31
193,066,923
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package kr.co.bit; public class For_Test1 { public static void main(String[] args) { int number1 = 0; int sum = 0; for (int i = 0; i < 10; i++) { number1++; // number1 = number1 + 1; sum += number1; // sum = sum + number1; } System.out.println("Áõ°¡=" + number1 + " ÇÕ°è=" + sum); } }
WINDOWS-1252
Java
329
java
For_Test1.java
Java
[]
null
[]
package kr.co.bit; public class For_Test1 { public static void main(String[] args) { int number1 = 0; int sum = 0; for (int i = 0; i < 10; i++) { number1++; // number1 = number1 + 1; sum += number1; // sum = sum + number1; } System.out.println("Áõ°¡=" + number1 + " ÇÕ°è=" + sum); } }
329
0.52648
0.482866
15
19.4
18.307739
57
false
false
0
0
0
0
0
0
1.866667
false
false
13
f929dcbec00433dab7b13e8eecea7606bf130390
37,589,553,793,874
5b89827b523112e6b6e7b0688ad5fbacbd8d08a7
/regression/src/Test07.java
2bb200b94c6a42a44849644ba7dfdec498b7cdce
[ "MIT" ]
permissive
TheVinhLuong102/lego-rcx-lejos
https://github.com/TheVinhLuong102/lego-rcx-lejos
b69228c560d0ba450f2287a4a957415186b4fd39
c4772a12a51fe7f63a4dede1c2b95a1bdf2a4309
refs/heads/master
2022-08-07T12:38:10.912000
2020-05-31T11:57:20
2020-05-31T11:57:20
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// Test for virtual methods import josx.platform.rcx.*; public class Test07 { public Test07() { Motor.controlMotor('A', 1, 1); for (int i = 0; i < 10000; i++) { } Motor.controlMotor('A', 3, 1); } public void virtualMethod(int i) { LCD.showNumber(i); } public void virtualMethod2() { LCD.showNumber(4490); } public static interface TestInterface { public void callback(); } public static class Inner extends Test07 implements TestInterface { public Inner() { this(30); } public void callback() { Motor.controlMotor('C', 1, 1); for (int i = 0; i < 10000; i++) { } Motor.controlMotor('C', 3, 1); } public Inner(int k) { super(); Sound.playTone((short) (k * 20), (short) 50); } public void virtualMethod(int i) { super.virtualMethod(i + 2); Sound.playTone((short) i, (short) 200); } } public static void main(String[] aArg) { Test07 p = new Inner(); Inner q = (Inner) p; if (p == null) throw new NullPointerException(); TestInterface t = (TestInterface) p; if (t == null) throw new RuntimeException(); p.virtualMethod(1800); for (int i = 0; i < 50000; i++) ; q.virtualMethod2(); t.callback(); for (int i = 0; i < 50000; i++) ; } }
UTF-8
Java
1,532
java
Test07.java
Java
[]
null
[]
// Test for virtual methods import josx.platform.rcx.*; public class Test07 { public Test07() { Motor.controlMotor('A', 1, 1); for (int i = 0; i < 10000; i++) { } Motor.controlMotor('A', 3, 1); } public void virtualMethod(int i) { LCD.showNumber(i); } public void virtualMethod2() { LCD.showNumber(4490); } public static interface TestInterface { public void callback(); } public static class Inner extends Test07 implements TestInterface { public Inner() { this(30); } public void callback() { Motor.controlMotor('C', 1, 1); for (int i = 0; i < 10000; i++) { } Motor.controlMotor('C', 3, 1); } public Inner(int k) { super(); Sound.playTone((short) (k * 20), (short) 50); } public void virtualMethod(int i) { super.virtualMethod(i + 2); Sound.playTone((short) i, (short) 200); } } public static void main(String[] aArg) { Test07 p = new Inner(); Inner q = (Inner) p; if (p == null) throw new NullPointerException(); TestInterface t = (TestInterface) p; if (t == null) throw new RuntimeException(); p.virtualMethod(1800); for (int i = 0; i < 50000; i++) ; q.virtualMethod2(); t.callback(); for (int i = 0; i < 50000; i++) ; } }
1,532
0.491514
0.45235
63
23.269842
16.676384
57
false
false
0
0
0
0
0
0
0.650794
false
false
13
cff2cf2c2e7bc9f6d8b36a1c0d793f56dc4d2314
36,309,653,545,405
66fc94806263152ce1d12e9e94ea6d17c1b363af
/src/main/java/com/liujinjin/momo20221024/JodaDateUtil.java
d4717f37729eb6660c2045afa5eeb140240a9653
[]
no_license
liujinjin777/liujinjintest
https://github.com/liujinjin777/liujinjintest
acfd7a9c6d4db67d7270c0ca74c2b6e749d66632
4d766d476bd034fb1ccf9591e55e19ad82003880
refs/heads/master
2023-04-09T07:14:58.873000
2023-03-03T05:10:11
2023-03-03T05:10:11
79,523,052
0
0
null
false
2023-09-05T22:04:15
2017-01-20T03:49:42
2022-10-21T04:00:09
2023-09-05T22:04:15
183
0
0
5
Java
false
false
package com.liujinjin.momo20221024; import lombok.extern.slf4j.Slf4j; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; /** * Created by liuxin on 2021/6/30. */ @Slf4j public class JodaDateUtil { public static final DateTimeFormatter yyyyMMddHHmmss = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); public static final DateTimeFormatter YYYYMMDD = DateTimeFormat.forPattern("yyyyMMdd"); public static final DateTimeFormatter YYYYMM = DateTimeFormat.forPattern("yyyyMM"); public static final DateTimeFormatter MMDD = DateTimeFormat.forPattern("MMdd"); public static final DateTimeFormatter DD = DateTimeFormat.forPattern("dd"); public static final DateTimeFormatter MMDD_V2 = DateTimeFormat.forPattern("MM.dd"); public static String format(long time, DateTimeFormatter formatter){ return formatter.print(time); } public static int getTimeYYMMDD(long time) { return Integer.parseInt(YYYYMMDD.print(time)); } }
UTF-8
Java
999
java
JodaDateUtil.java
Java
[ { "context": ".time.format.DateTimeFormatter;\n\n/**\n * Created by liuxin on 2021/6/30.\n */\n@Slf4j\npublic class JodaDateUti", "end": 188, "score": 0.9992665648460388, "start": 182, "tag": "USERNAME", "value": "liuxin" } ]
null
[]
package com.liujinjin.momo20221024; import lombok.extern.slf4j.Slf4j; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; /** * Created by liuxin on 2021/6/30. */ @Slf4j public class JodaDateUtil { public static final DateTimeFormatter yyyyMMddHHmmss = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); public static final DateTimeFormatter YYYYMMDD = DateTimeFormat.forPattern("yyyyMMdd"); public static final DateTimeFormatter YYYYMM = DateTimeFormat.forPattern("yyyyMM"); public static final DateTimeFormatter MMDD = DateTimeFormat.forPattern("MMdd"); public static final DateTimeFormatter DD = DateTimeFormat.forPattern("dd"); public static final DateTimeFormatter MMDD_V2 = DateTimeFormat.forPattern("MM.dd"); public static String format(long time, DateTimeFormatter formatter){ return formatter.print(time); } public static int getTimeYYMMDD(long time) { return Integer.parseInt(YYYYMMDD.print(time)); } }
999
0.770771
0.751752
30
32.299999
31.307241
90
false
false
0
0
0
0
0
0
0.433333
false
false
13
6bb00058ec416ec1a44bc87adb3de62b0e29a104
35,304,631,213,755
a7af376642f2a766f36cf8f7ac3081eda9964c41
/src/com/example/dreamfly/MainActivity.java
b7369483c6c47c0ef5c14f0c507f99487fdf320a
[]
no_license
pzdfly/DreamFlyV1.0
https://github.com/pzdfly/DreamFlyV1.0
35a29ffb5bf917eebdf131ac372ae6f589029dad
55ed1e6afe888d3ffcbf44d6d894e15871d91158
refs/heads/master
2021-04-09T17:21:29.492000
2013-11-08T02:03:14
2013-11-08T02:03:14
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.dreamfly; import java.io.FileOutputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import com.example.dreamfly.PullToRefreshListView.OnRefreshListener; import com.umeng.analytics.MobclickAgent; import pz.rg.domain.NewsHead; import pz.rg.domain.NewsPictures; import pz.rg.domain.Notice; import pz.rg.downloadimage.DownLoadImage_top; import pz.rg.exit.ExitApplication; import pz.rg.http.HttpTools; import pz.rg.json.tool.JsonTools; import pz.rg.menu.BottomMenu; import pz.rg.menu.LeftMenu; import pz.rg.mydialog.MyDialog; import pz.rg.sliding.BuileGestureExt; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Parcelable; import android.annotation.SuppressLint; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.graphics.Color; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.GestureDetector; import android.view.Gravity; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.Button; import android.widget.ImageView; import android.widget.PopupWindow; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; import android.widget.ImageView.ScaleType; @SuppressLint("HandlerLeak") public class MainActivity extends Activity { private static boolean setstate=false; private PopupWindow dialogPopupWindow; private Button homepage_refreshButton; private Button homepage_set_netButton; private ProgressBar homepage_loading_progressBar; private ProgressBar loadmoreprogressBar; private TextView loadmoretextView; private ListviewAdapter adapter; private static int page=2; private Button loadmoreButton; private static List<Map<String, Object>> list; private View loadMoreView; private View listview_headview; private PullToRefreshListView listView; private ViewPager viewPager; // android-support-v4中的滑动组件 private static List<ImageView> imageViews; // 滑动的图片集合 private static String[] titles; // 图片标题 private List<View> dots; // 图片标题正文的那些点 private TextView tv_title; private int currentItem = 0; // 当前图片的索引号 // An ExecutorService that can schedule commands to run after a given delay, // or to execute periodically. private ScheduledExecutorService scheduledExecutorService; // 切换当前显示的图片 private Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { viewPager.setCurrentItem(currentItem);// 切换当前显示的图片 }; }; @Override protected void onStop() { // 当Activity不可见的时候停止切换 if(setstate==false) scheduledExecutorService.shutdown(); setstate=false; super.onStop(); } @Override protected void onRestart() { // 当Activity重新可见时的时候停止切换 scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); // 每两秒钟切换一次图片显示 scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), 1, 4, TimeUnit.SECONDS); setstate=false; super.onRestart(); } public static MainActivity mainActivity=null; private PopupWindow left_menu;//菜单控件 private PopupWindow bottom_menu; private GestureDetector gestureDetector;//滑动控件 private int screenWidth; private int screenHeight; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mainActivity=this; ExitApplication.getInstance().addActivity(this); homepage_loading_progressBar=(ProgressBar)findViewById(R.id.homepage_loading_progress); homepage_refreshButton=(Button)findViewById(R.id.homepage_refresh); homepage_set_netButton=(Button)findViewById(R.id.homepage_set_net); homepage_refreshButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub HomeListviewRefresh pageRefresh=new HomeListviewRefresh(); pageRefresh.execute(); PicturesList picturesRefresh=new PicturesList(); picturesRefresh.execute(); } }); homepage_set_netButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub setstate=true; Intent homepageintent=null; //判断手机系统的版本 即API大于10 就是3.0或以上版本 if(android.os.Build.VERSION.SDK_INT>10){ homepageintent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS); }else{ homepageintent = new Intent(); ComponentName component = new ComponentName("com.android.settings","com.android.settings.WirelessSettings"); homepageintent.setComponent(component); homepageintent.setAction("android.intent.action.VIEW"); } startActivity(homepageintent); } }); //列表 PicturesList pictures=new PicturesList(); pictures.execute(); listView=(PullToRefreshListView)findViewById(R.id.newslist); listView.setCacheColorHint(Color.TRANSPARENT); listView.setBackgroundResource(R.drawable.listviewbackground); listview_headview = getLayoutInflater().inflate(R.layout.listview_headview, null); listView.addHeaderView(listview_headview); list=new ArrayList<Map<String,Object>>(); HomeListviewRefresh listviewdefault=new HomeListviewRefresh(); listviewdefault.execute(); adapter=new ListviewAdapter(MainActivity.this, list); listView.setAdapter(adapter); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { String newsid=list.get(position-2).get("newsid").toString(); String databaseid=list.get(position-2).get("databaseid").toString(); Intent intent=new Intent(MainActivity.this,NewsContent.class); intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); intent.putExtra("newsid", newsid); intent.putExtra("databaseid", databaseid); startActivity(intent); } }); listView.setonRefreshListener(new OnRefreshListener() { @Override public void onRefresh() { list.clear(); page=2; HomeListviewRefresh homelistviewRefresh=new HomeListviewRefresh(); homelistviewRefresh.execute(); } }); loadMoreView = getLayoutInflater().inflate(R.layout.loadmoreview, null); listView.addFooterView(loadMoreView); loadmoreprogressBar=(ProgressBar)findViewById(R.id.loadmoreprogress); loadmoretextView=(TextView)findViewById(R.id.loadmoretextview); loadmoreButton=(Button)findViewById(R.id.loadmorebutton); loadmoreButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { loadmoreButton.setVisibility(View.INVISIBLE); loadmoreprogressBar.setVisibility(View.VISIBLE); loadmoretextView.setVisibility(View.VISIBLE); HomeLoadMoreData homeLoadMoreData=new HomeLoadMoreData(); homeLoadMoreData.execute(Integer.toString(page)); page++; } }); //向右滑动弹出菜单栏 gestureDetector = new BuileGestureExt(this,new BuileGestureExt.OnGestureResult() { @Override public void onGestureResult(int direction) { if (direction==3) { screenWidth = MainActivity.this.getWindowManager().getDefaultDisplay().getWidth(); screenHeight = MainActivity.this.getWindowManager().getDefaultDisplay().getHeight(); View left_menu_view = getLayoutInflater().inflate(R.layout.leftmenu, null,false); left_menu = new PopupWindow(left_menu_view, screenWidth, screenHeight, true); LeftMenu.initPopuptWindow(left_menu, left_menu_view,MainActivity.this); left_menu.showAsDropDown(findViewById(R.id.toptitle), 0, screenHeight/6); } } } ).Buile(); //开启获取通知的线程 getNotice tNotice = new getNotice(); tNotice.execute(); } public class getNotice extends AsyncTask<Void, Void, List<Notice>>{ @Override protected List<Notice> doInBackground(Void... params) { String url = new String("http://www.peizheng.cn/mobile/index.php?interfaceid=0213&topnum=3&cname=dfly&cpwd=123456"); String jsonString = HttpTools.getJsonString(url); List<Notice> noticeList = JsonTools.getNotice(jsonString); //序列化PC通知,写到文件中 try { FileOutputStream tFileStream = MainActivity.this.openFileOutput("Notices", MODE_PRIVATE); ObjectOutputStream tObjectStream = new ObjectOutputStream(tFileStream); tObjectStream.writeObject(noticeList); tObjectStream.close(); tFileStream.close(); } catch (Exception e) { e.printStackTrace(); } return noticeList; } } private class ScrollTask implements Runnable { public void run() { synchronized (viewPager) { System.out.println("currentItem: " + currentItem); currentItem = (currentItem + 1) % imageViews.size(); handler.obtainMessage().sendToTarget(); // 通过Handler切换图片 } } } /** * 当ViewPager中页面的状态发生改变时调用 * * @author Administrator * */ private class MyPageChangeListener implements OnPageChangeListener { private int oldPosition = 0; /** * This method will be invoked when a new page becomes selected. * position: Position index of the new selected page. */ public void onPageSelected(int position) { currentItem = position; tv_title.setText(titles[position]); dots.get(oldPosition).setBackgroundResource(R.drawable.dot_normal); dots.get(position).setBackgroundResource(R.drawable.dot_focused); oldPosition = position; } public void onPageScrollStateChanged(int arg0) { } public void onPageScrolled(int arg0, float arg1, int arg2) { } } /** * 填充ViewPager页面的适配器 * * @author Administrator * */ private class MyAdapter extends PagerAdapter { @Override public int getCount() { return 5; } @Override public Object instantiateItem(View arg0, int arg1) { ((ViewPager) arg0).addView(imageViews.get(arg1)); return imageViews.get(arg1); } @Override public void destroyItem(View arg0, int arg1, Object arg2) { ((ViewPager) arg0).removeView((View) arg2); } @Override public boolean isViewFromObject(View arg0, Object arg1) { return arg0 == arg1; } @Override public void restoreState(Parcelable arg0, ClassLoader arg1) { } @Override public Parcelable saveState() { return null; } @Override public void startUpdate(View arg0) { } @Override public void finishUpdate(View arg0) { } } //listview刷新 public class HomeListviewRefresh extends AsyncTask<Void, Void, List<NewsHead>> { private String jsonString; public HomeListviewRefresh() { // TODO Auto-generated constructor stub } @Override protected void onPreExecute() { homepage_loading_progressBar.setVisibility(View.VISIBLE); homepage_refreshButton.setVisibility(View.INVISIBLE); homepage_set_netButton.setVisibility(View.INVISIBLE); listView.setVisibility(View.INVISIBLE); super.onPreExecute(); } @Override protected List<NewsHead> doInBackground(Void... parm) { StringBuffer pathBuffer=new StringBuffer("http://www.peizheng.cn/mobile/index.php?interfaceid=0101&page=1&limit=10"+"&cname=dfly&cpwd=123456"); jsonString = HttpTools.getJsonString(pathBuffer.toString()); List<NewsHead> newsHeads=new ArrayList<NewsHead>(); newsHeads=JsonTools.getNewsHeads(jsonString); return newsHeads; } @Override protected void onPostExecute(List<NewsHead> result) { homepage_loading_progressBar.setVisibility(View.INVISIBLE); if (result.toString().equals("[]")) { homepage_refreshButton.setVisibility(View.VISIBLE); homepage_set_netButton.setVisibility(View.VISIBLE); } else { listView.setVisibility(View.VISIBLE); } list.addAll(newsListview.getData(result,adapter)); adapter.notifyDataSetChanged(); listView.onRefreshComplete(); super.onPostExecute(result); } } public class HomeLoadMoreData extends AsyncTask<String, Void, List<NewsHead>> { private String jsonString; public HomeLoadMoreData() { // TODO Auto-generated constructor stub } @Override protected List<NewsHead> doInBackground(String... parm) { // TODO Auto-generated method stub String page = parm[0]; StringBuffer pathBuffer=new StringBuffer("http://www.peizheng.cn/mobile/index.php?interfaceid=0101&page="+page+"&limit=10"+"&cname=dfly&cpwd=123456"); jsonString = HttpTools.getJsonString(pathBuffer.toString()); List<NewsHead> newsHeads=new ArrayList<NewsHead>(); newsHeads=JsonTools.getNewsHeads(jsonString); return newsHeads; } @Override protected void onPostExecute(List<NewsHead> result) { // TODO Auto-generated method stub if (result.toString().equals("[]")) { Toast.makeText(MainActivity.this, "网络不给力,请重试!",Toast.LENGTH_SHORT).show(); } list.addAll(newsListview.getData(result,adapter)); adapter.notifyDataSetChanged(); loadmoreButton.setVisibility(View.VISIBLE); loadmoreprogressBar.setVisibility(View.INVISIBLE); loadmoretextView.setVisibility(View.INVISIBLE); super.onPostExecute(result); } } public class PicturesList extends AsyncTask<Void, Void, List<NewsPictures>> { private String jsonString; public PicturesList() { // TODO Auto-generated constructor stub } @Override protected List<NewsPictures> doInBackground(Void... parm) { StringBuffer pathBuffer=new StringBuffer("http://www.peizheng.cn/mobile/index.php?interfaceid=0102&page=1&limit=10&catid=252&cname=dfly&cpwd=123456"); jsonString = HttpTools.getJsonString(pathBuffer.toString()); List<NewsPictures> newsPictures=new ArrayList<NewsPictures>(); newsPictures=JsonTools.getPictures(jsonString); return newsPictures; } @Override public void onPostExecute(List<NewsPictures> result) { // TODO Auto-generated method stub try { titles = new String[5]; for (int i = 0; i < 5; i++) { titles[i] = result.get(i).getTitle(); } imageViews = new ArrayList<ImageView>(); // 初始化图片资源 for (int i = 0; i < 5; i++) { ImageView imageView = new ImageView(MainActivity.this); DownLoadImage_top downLoadImage_top=new DownLoadImage_top(imageView); downLoadImage_top.execute(result.get(i).getImgUrl()); imageView.setScaleType(ScaleType.CENTER_INSIDE); imageViews.add(imageView); } dots = new ArrayList<View>(); dots.add(findViewById(R.id.v_dot0)); dots.add(findViewById(R.id.v_dot1)); dots.add(findViewById(R.id.v_dot2)); dots.add(findViewById(R.id.v_dot3)); dots.add(findViewById(R.id.v_dot4)); tv_title = (TextView)findViewById(R.id.tv_title); tv_title.setText(titles[0]); viewPager = (ViewPager)findViewById(R.id.vp); viewPager.setAdapter(new MyAdapter());// 设置填充ViewPager页面的适配器 // 设置一个监听器,当ViewPager中的页面改变时调用 viewPager.setOnPageChangeListener(new MyPageChangeListener()); scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); // 每两秒钟切换一次图片显示 scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), 0, 4, TimeUnit.SECONDS); } catch (Exception e) { // TODO: handle exception System.out.println("图片读取不到"); } super.onPostExecute(result); } } //滑动时用的触摸事件 @Override public boolean onTouchEvent(MotionEvent event) { return gestureDetector.onTouchEvent(event); } //防止滑动事件被listview的item事件覆盖 @Override public boolean dispatchTouchEvent(MotionEvent ev) { // TODO Auto-generated method stub this.gestureDetector.onTouchEvent(ev); return super.dispatchTouchEvent(ev); } //菜单 @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_MENU) { //监控/拦截菜单键 //获取屏幕高宽 screenWidth = MainActivity.this.getWindowManager().getDefaultDisplay().getWidth(); screenHeight = MainActivity.this.getWindowManager().getDefaultDisplay().getHeight(); View bottom_menu_view = getLayoutInflater().inflate(R.layout.bottommenu, null,false); bottom_menu = new PopupWindow(bottom_menu_view, screenWidth, screenHeight, true); BottomMenu.initPopuptWindow(bottom_menu, bottom_menu_view,MainActivity.this); bottom_menu.showAtLocation(findViewById(R.id.mainactivity), Gravity.BOTTOM, 0, 0); } if (keyCode==KeyEvent.KEYCODE_BACK ) { screenWidth = MainActivity.this.getWindowManager().getDefaultDisplay().getWidth(); screenHeight = MainActivity.this.getWindowManager().getDefaultDisplay().getHeight(); View dialog_view = getLayoutInflater().inflate(R.layout.mydialog, null,false); dialogPopupWindow= new PopupWindow(dialog_view, screenWidth, screenHeight/2, true); MyDialog.initPopuptWindow(dialogPopupWindow, dialog_view,MainActivity.this); dialogPopupWindow.showAtLocation(findViewById(R.id.mainactivity), Gravity.CENTER, 0, screenHeight/20); } return super.onKeyDown(keyCode, event); } @Override protected void onPause() { super.onPause(); MobclickAgent.onPause(this); } @Override protected void onResume() { super.onResume(); MobclickAgent.onResume(this); } }
GB18030
Java
18,307
java
MainActivity.java
Java
[ { "context": "\n\t/**\n\t * 当ViewPager中页面的状态发生改变时调用\n\t * \n\t * @author Administrator\n\t * \n\t */\n\tprivate class MyPageChangeListener imp", "end": 9545, "score": 0.9371069073677063, "start": 9532, "tag": "NAME", "value": "Administrator" }, { "context": "\t}\n\t}\n\n\t/**\n\t * 填充ViewPager页面的适配器\n\t * \n\t * @author Administrator\n\t * \n\t */\n\tprivate class MyAdapter extends PagerA", "end": 10266, "score": 0.9594925045967102, "start": 10253, "tag": "NAME", "value": "Administrator" } ]
null
[]
package com.example.dreamfly; import java.io.FileOutputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import com.example.dreamfly.PullToRefreshListView.OnRefreshListener; import com.umeng.analytics.MobclickAgent; import pz.rg.domain.NewsHead; import pz.rg.domain.NewsPictures; import pz.rg.domain.Notice; import pz.rg.downloadimage.DownLoadImage_top; import pz.rg.exit.ExitApplication; import pz.rg.http.HttpTools; import pz.rg.json.tool.JsonTools; import pz.rg.menu.BottomMenu; import pz.rg.menu.LeftMenu; import pz.rg.mydialog.MyDialog; import pz.rg.sliding.BuileGestureExt; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Parcelable; import android.annotation.SuppressLint; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.graphics.Color; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.GestureDetector; import android.view.Gravity; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.Button; import android.widget.ImageView; import android.widget.PopupWindow; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; import android.widget.ImageView.ScaleType; @SuppressLint("HandlerLeak") public class MainActivity extends Activity { private static boolean setstate=false; private PopupWindow dialogPopupWindow; private Button homepage_refreshButton; private Button homepage_set_netButton; private ProgressBar homepage_loading_progressBar; private ProgressBar loadmoreprogressBar; private TextView loadmoretextView; private ListviewAdapter adapter; private static int page=2; private Button loadmoreButton; private static List<Map<String, Object>> list; private View loadMoreView; private View listview_headview; private PullToRefreshListView listView; private ViewPager viewPager; // android-support-v4中的滑动组件 private static List<ImageView> imageViews; // 滑动的图片集合 private static String[] titles; // 图片标题 private List<View> dots; // 图片标题正文的那些点 private TextView tv_title; private int currentItem = 0; // 当前图片的索引号 // An ExecutorService that can schedule commands to run after a given delay, // or to execute periodically. private ScheduledExecutorService scheduledExecutorService; // 切换当前显示的图片 private Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { viewPager.setCurrentItem(currentItem);// 切换当前显示的图片 }; }; @Override protected void onStop() { // 当Activity不可见的时候停止切换 if(setstate==false) scheduledExecutorService.shutdown(); setstate=false; super.onStop(); } @Override protected void onRestart() { // 当Activity重新可见时的时候停止切换 scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); // 每两秒钟切换一次图片显示 scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), 1, 4, TimeUnit.SECONDS); setstate=false; super.onRestart(); } public static MainActivity mainActivity=null; private PopupWindow left_menu;//菜单控件 private PopupWindow bottom_menu; private GestureDetector gestureDetector;//滑动控件 private int screenWidth; private int screenHeight; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mainActivity=this; ExitApplication.getInstance().addActivity(this); homepage_loading_progressBar=(ProgressBar)findViewById(R.id.homepage_loading_progress); homepage_refreshButton=(Button)findViewById(R.id.homepage_refresh); homepage_set_netButton=(Button)findViewById(R.id.homepage_set_net); homepage_refreshButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub HomeListviewRefresh pageRefresh=new HomeListviewRefresh(); pageRefresh.execute(); PicturesList picturesRefresh=new PicturesList(); picturesRefresh.execute(); } }); homepage_set_netButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub setstate=true; Intent homepageintent=null; //判断手机系统的版本 即API大于10 就是3.0或以上版本 if(android.os.Build.VERSION.SDK_INT>10){ homepageintent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS); }else{ homepageintent = new Intent(); ComponentName component = new ComponentName("com.android.settings","com.android.settings.WirelessSettings"); homepageintent.setComponent(component); homepageintent.setAction("android.intent.action.VIEW"); } startActivity(homepageintent); } }); //列表 PicturesList pictures=new PicturesList(); pictures.execute(); listView=(PullToRefreshListView)findViewById(R.id.newslist); listView.setCacheColorHint(Color.TRANSPARENT); listView.setBackgroundResource(R.drawable.listviewbackground); listview_headview = getLayoutInflater().inflate(R.layout.listview_headview, null); listView.addHeaderView(listview_headview); list=new ArrayList<Map<String,Object>>(); HomeListviewRefresh listviewdefault=new HomeListviewRefresh(); listviewdefault.execute(); adapter=new ListviewAdapter(MainActivity.this, list); listView.setAdapter(adapter); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { String newsid=list.get(position-2).get("newsid").toString(); String databaseid=list.get(position-2).get("databaseid").toString(); Intent intent=new Intent(MainActivity.this,NewsContent.class); intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); intent.putExtra("newsid", newsid); intent.putExtra("databaseid", databaseid); startActivity(intent); } }); listView.setonRefreshListener(new OnRefreshListener() { @Override public void onRefresh() { list.clear(); page=2; HomeListviewRefresh homelistviewRefresh=new HomeListviewRefresh(); homelistviewRefresh.execute(); } }); loadMoreView = getLayoutInflater().inflate(R.layout.loadmoreview, null); listView.addFooterView(loadMoreView); loadmoreprogressBar=(ProgressBar)findViewById(R.id.loadmoreprogress); loadmoretextView=(TextView)findViewById(R.id.loadmoretextview); loadmoreButton=(Button)findViewById(R.id.loadmorebutton); loadmoreButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { loadmoreButton.setVisibility(View.INVISIBLE); loadmoreprogressBar.setVisibility(View.VISIBLE); loadmoretextView.setVisibility(View.VISIBLE); HomeLoadMoreData homeLoadMoreData=new HomeLoadMoreData(); homeLoadMoreData.execute(Integer.toString(page)); page++; } }); //向右滑动弹出菜单栏 gestureDetector = new BuileGestureExt(this,new BuileGestureExt.OnGestureResult() { @Override public void onGestureResult(int direction) { if (direction==3) { screenWidth = MainActivity.this.getWindowManager().getDefaultDisplay().getWidth(); screenHeight = MainActivity.this.getWindowManager().getDefaultDisplay().getHeight(); View left_menu_view = getLayoutInflater().inflate(R.layout.leftmenu, null,false); left_menu = new PopupWindow(left_menu_view, screenWidth, screenHeight, true); LeftMenu.initPopuptWindow(left_menu, left_menu_view,MainActivity.this); left_menu.showAsDropDown(findViewById(R.id.toptitle), 0, screenHeight/6); } } } ).Buile(); //开启获取通知的线程 getNotice tNotice = new getNotice(); tNotice.execute(); } public class getNotice extends AsyncTask<Void, Void, List<Notice>>{ @Override protected List<Notice> doInBackground(Void... params) { String url = new String("http://www.peizheng.cn/mobile/index.php?interfaceid=0213&topnum=3&cname=dfly&cpwd=123456"); String jsonString = HttpTools.getJsonString(url); List<Notice> noticeList = JsonTools.getNotice(jsonString); //序列化PC通知,写到文件中 try { FileOutputStream tFileStream = MainActivity.this.openFileOutput("Notices", MODE_PRIVATE); ObjectOutputStream tObjectStream = new ObjectOutputStream(tFileStream); tObjectStream.writeObject(noticeList); tObjectStream.close(); tFileStream.close(); } catch (Exception e) { e.printStackTrace(); } return noticeList; } } private class ScrollTask implements Runnable { public void run() { synchronized (viewPager) { System.out.println("currentItem: " + currentItem); currentItem = (currentItem + 1) % imageViews.size(); handler.obtainMessage().sendToTarget(); // 通过Handler切换图片 } } } /** * 当ViewPager中页面的状态发生改变时调用 * * @author Administrator * */ private class MyPageChangeListener implements OnPageChangeListener { private int oldPosition = 0; /** * This method will be invoked when a new page becomes selected. * position: Position index of the new selected page. */ public void onPageSelected(int position) { currentItem = position; tv_title.setText(titles[position]); dots.get(oldPosition).setBackgroundResource(R.drawable.dot_normal); dots.get(position).setBackgroundResource(R.drawable.dot_focused); oldPosition = position; } public void onPageScrollStateChanged(int arg0) { } public void onPageScrolled(int arg0, float arg1, int arg2) { } } /** * 填充ViewPager页面的适配器 * * @author Administrator * */ private class MyAdapter extends PagerAdapter { @Override public int getCount() { return 5; } @Override public Object instantiateItem(View arg0, int arg1) { ((ViewPager) arg0).addView(imageViews.get(arg1)); return imageViews.get(arg1); } @Override public void destroyItem(View arg0, int arg1, Object arg2) { ((ViewPager) arg0).removeView((View) arg2); } @Override public boolean isViewFromObject(View arg0, Object arg1) { return arg0 == arg1; } @Override public void restoreState(Parcelable arg0, ClassLoader arg1) { } @Override public Parcelable saveState() { return null; } @Override public void startUpdate(View arg0) { } @Override public void finishUpdate(View arg0) { } } //listview刷新 public class HomeListviewRefresh extends AsyncTask<Void, Void, List<NewsHead>> { private String jsonString; public HomeListviewRefresh() { // TODO Auto-generated constructor stub } @Override protected void onPreExecute() { homepage_loading_progressBar.setVisibility(View.VISIBLE); homepage_refreshButton.setVisibility(View.INVISIBLE); homepage_set_netButton.setVisibility(View.INVISIBLE); listView.setVisibility(View.INVISIBLE); super.onPreExecute(); } @Override protected List<NewsHead> doInBackground(Void... parm) { StringBuffer pathBuffer=new StringBuffer("http://www.peizheng.cn/mobile/index.php?interfaceid=0101&page=1&limit=10"+"&cname=dfly&cpwd=123456"); jsonString = HttpTools.getJsonString(pathBuffer.toString()); List<NewsHead> newsHeads=new ArrayList<NewsHead>(); newsHeads=JsonTools.getNewsHeads(jsonString); return newsHeads; } @Override protected void onPostExecute(List<NewsHead> result) { homepage_loading_progressBar.setVisibility(View.INVISIBLE); if (result.toString().equals("[]")) { homepage_refreshButton.setVisibility(View.VISIBLE); homepage_set_netButton.setVisibility(View.VISIBLE); } else { listView.setVisibility(View.VISIBLE); } list.addAll(newsListview.getData(result,adapter)); adapter.notifyDataSetChanged(); listView.onRefreshComplete(); super.onPostExecute(result); } } public class HomeLoadMoreData extends AsyncTask<String, Void, List<NewsHead>> { private String jsonString; public HomeLoadMoreData() { // TODO Auto-generated constructor stub } @Override protected List<NewsHead> doInBackground(String... parm) { // TODO Auto-generated method stub String page = parm[0]; StringBuffer pathBuffer=new StringBuffer("http://www.peizheng.cn/mobile/index.php?interfaceid=0101&page="+page+"&limit=10"+"&cname=dfly&cpwd=123456"); jsonString = HttpTools.getJsonString(pathBuffer.toString()); List<NewsHead> newsHeads=new ArrayList<NewsHead>(); newsHeads=JsonTools.getNewsHeads(jsonString); return newsHeads; } @Override protected void onPostExecute(List<NewsHead> result) { // TODO Auto-generated method stub if (result.toString().equals("[]")) { Toast.makeText(MainActivity.this, "网络不给力,请重试!",Toast.LENGTH_SHORT).show(); } list.addAll(newsListview.getData(result,adapter)); adapter.notifyDataSetChanged(); loadmoreButton.setVisibility(View.VISIBLE); loadmoreprogressBar.setVisibility(View.INVISIBLE); loadmoretextView.setVisibility(View.INVISIBLE); super.onPostExecute(result); } } public class PicturesList extends AsyncTask<Void, Void, List<NewsPictures>> { private String jsonString; public PicturesList() { // TODO Auto-generated constructor stub } @Override protected List<NewsPictures> doInBackground(Void... parm) { StringBuffer pathBuffer=new StringBuffer("http://www.peizheng.cn/mobile/index.php?interfaceid=0102&page=1&limit=10&catid=252&cname=dfly&cpwd=123456"); jsonString = HttpTools.getJsonString(pathBuffer.toString()); List<NewsPictures> newsPictures=new ArrayList<NewsPictures>(); newsPictures=JsonTools.getPictures(jsonString); return newsPictures; } @Override public void onPostExecute(List<NewsPictures> result) { // TODO Auto-generated method stub try { titles = new String[5]; for (int i = 0; i < 5; i++) { titles[i] = result.get(i).getTitle(); } imageViews = new ArrayList<ImageView>(); // 初始化图片资源 for (int i = 0; i < 5; i++) { ImageView imageView = new ImageView(MainActivity.this); DownLoadImage_top downLoadImage_top=new DownLoadImage_top(imageView); downLoadImage_top.execute(result.get(i).getImgUrl()); imageView.setScaleType(ScaleType.CENTER_INSIDE); imageViews.add(imageView); } dots = new ArrayList<View>(); dots.add(findViewById(R.id.v_dot0)); dots.add(findViewById(R.id.v_dot1)); dots.add(findViewById(R.id.v_dot2)); dots.add(findViewById(R.id.v_dot3)); dots.add(findViewById(R.id.v_dot4)); tv_title = (TextView)findViewById(R.id.tv_title); tv_title.setText(titles[0]); viewPager = (ViewPager)findViewById(R.id.vp); viewPager.setAdapter(new MyAdapter());// 设置填充ViewPager页面的适配器 // 设置一个监听器,当ViewPager中的页面改变时调用 viewPager.setOnPageChangeListener(new MyPageChangeListener()); scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); // 每两秒钟切换一次图片显示 scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), 0, 4, TimeUnit.SECONDS); } catch (Exception e) { // TODO: handle exception System.out.println("图片读取不到"); } super.onPostExecute(result); } } //滑动时用的触摸事件 @Override public boolean onTouchEvent(MotionEvent event) { return gestureDetector.onTouchEvent(event); } //防止滑动事件被listview的item事件覆盖 @Override public boolean dispatchTouchEvent(MotionEvent ev) { // TODO Auto-generated method stub this.gestureDetector.onTouchEvent(ev); return super.dispatchTouchEvent(ev); } //菜单 @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_MENU) { //监控/拦截菜单键 //获取屏幕高宽 screenWidth = MainActivity.this.getWindowManager().getDefaultDisplay().getWidth(); screenHeight = MainActivity.this.getWindowManager().getDefaultDisplay().getHeight(); View bottom_menu_view = getLayoutInflater().inflate(R.layout.bottommenu, null,false); bottom_menu = new PopupWindow(bottom_menu_view, screenWidth, screenHeight, true); BottomMenu.initPopuptWindow(bottom_menu, bottom_menu_view,MainActivity.this); bottom_menu.showAtLocation(findViewById(R.id.mainactivity), Gravity.BOTTOM, 0, 0); } if (keyCode==KeyEvent.KEYCODE_BACK ) { screenWidth = MainActivity.this.getWindowManager().getDefaultDisplay().getWidth(); screenHeight = MainActivity.this.getWindowManager().getDefaultDisplay().getHeight(); View dialog_view = getLayoutInflater().inflate(R.layout.mydialog, null,false); dialogPopupWindow= new PopupWindow(dialog_view, screenWidth, screenHeight/2, true); MyDialog.initPopuptWindow(dialogPopupWindow, dialog_view,MainActivity.this); dialogPopupWindow.showAtLocation(findViewById(R.id.mainactivity), Gravity.CENTER, 0, screenHeight/20); } return super.onKeyDown(keyCode, event); } @Override protected void onPause() { super.onPause(); MobclickAgent.onPause(this); } @Override protected void onResume() { super.onResume(); MobclickAgent.onResume(this); } }
18,307
0.724247
0.717488
584
29.400684
27.582697
155
false
false
0
0
0
0
0
0
2.421233
false
false
13
ae78eca064b3c7768cc778037a0b000843ba3e63
34,007,551,092,087
763c24bebe61a40f4f064aaf5cec2d3ad1f664ba
/app/src/main/java/com/anyemi/housi/MobileLoginActivity.java
cbe953b29379a8c363acca58a8d2566f27965a14
[]
no_license
anyemiuser/Login
https://github.com/anyemiuser/Login
fc459bb75a29563dc777ba6a60403b516be49de1
ff88d5dec3976daa5174b50c57ac95979c41e154
refs/heads/master
2021-05-26T00:47:44.180000
2020-06-11T13:58:59
2020-06-11T13:58:59
253,983,016
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.anyemi.housi; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import com.anyemi.housi.connection.ApiServices; import com.anyemi.housi.connection.bgtask.BackgroundTask; import com.anyemi.housi.connection.bgtask.BackgroundThread; import com.anyemi.housi.utils.Globals; import com.anyemi.housi.utils.SharedPreferenceUtil; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.InstanceIdResult; import com.google.firebase.messaging.FirebaseMessaging; import com.google.gson.Gson; import org.json.JSONException; import org.json.JSONObject; public class MobileLoginActivity extends AppCompatActivity { private TextView tv_Resendotp; private EditText et_mobile,et_otp_no; private Button btn_Next,btn_verify_otp; String token; // EditText et_mobile2 = new EditText(CreateRoomActivity.this); // Button btn_Next2 = new Button(CreateRoomActivity.this); protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getSupportActionBar().hide(); setContentView(R.layout.activity_mobile_login); FirebaseInstanceId.getInstance().getInstanceId() .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() { @Override public void onComplete(@NonNull Task<InstanceIdResult> task) { if (!task.isSuccessful()) { Log.w("getInstanceId", "getInstanceId failed", task.getException()); return; } // Get new Instance ID token token = task.getResult().getToken(); // Log and toast // String msg = getString(R.string.msg_token_fmt, token); Log.e("token", token); // Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show(); } }); // String reg_code = SharedPreferenceUtil.getRegCode(getApplicationContext()); et_mobile = findViewById(R.id.et_mobile_no); et_otp_no = findViewById(R.id.et_otp); tv_Resendotp = findViewById(R.id.tv_resend_otp); btn_Next = findViewById(R.id.btn_next); btn_verify_otp = findViewById(R.id.btn_verify); et_otp_no.setVisibility(View.INVISIBLE); btn_verify_otp.setVisibility(View.INVISIBLE); tv_Resendotp.setVisibility(View.INVISIBLE); /* btn_Next.setOnClickListener(new View.OnClickListener() {*/ btn_Next.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { if(isvalidphonenumber()) { et_mobile.setVisibility(View.INVISIBLE); btn_Next.setVisibility(View.INVISIBLE); et_otp_no.setVisibility(View.VISIBLE); btn_verify_otp.setVisibility(View.VISIBLE); tv_Resendotp.setVisibility(View.VISIBLE); postMobileNumber(); } } }); tv_Resendotp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { postResendOtp(); } }); btn_verify_otp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(isvalidotpnumber()) { postVerifyOtpNumber(); /*Intent i=new Intent( getApplicationContext(), HomeActivity.class); startActivity(i);*/ } } }); } private void postMobileNumber() { new BackgroundTask(MobileLoginActivity.this, new BackgroundThread() { @Override public Object runTask() { return ApiServices.login(MobileLoginActivity.this, mobileloginRequestModel()); } public void taskCompleted(Object data) { SharedPreferenceUtil.setMobile_number(getApplicationContext(), et_mobile.getText().toString()); Globals.showToast(getApplicationContext(), data.toString()); /* Intent mediaActivity = new Intent(getApplicationContext(), MediaActivity.class); startActivity(mediaActivity);*/ } }, getString(R.string.loading_txt)).execute(); } private String mobileloginRequestModel() { String mobile_no, version_id; mobile_no = et_mobile.getText().toString(); // version_id = BuildConfig.VERSION_NAME; JSONObject requestObject = new JSONObject(); try { requestObject.put("mobile_number", mobile_no); requestObject.put("device_id", token); /// requestObject.put("AppVersion", version_id); System.out.println(requestObject.toString()); } catch (JSONException e) { e.printStackTrace(); } return requestObject.toString(); } private void postVerifyOtpNumber() { new BackgroundTask(MobileLoginActivity.this, new BackgroundThread() { @Override public Object runTask() { return ApiServices.verifyotp(MobileLoginActivity.this, otpverifyRequestModel()); } public void taskCompleted(Object data) { VerifyOtp verifyOtp =new VerifyOtp(); verifyOtp= new Gson().fromJson(data.toString(),VerifyOtp.class); SharedPreferenceUtil.setMobile_number(getApplicationContext(), et_mobile.getText().toString()); SharedPreferenceUtil.setId(getApplicationContext(), verifyOtp.getId()); Globals.showToast(getApplicationContext(), data.toString()); Intent i = new Intent(getApplicationContext(), HomeActivity.class); startActivity(i); } }, getString(R.string.loading_txt)).execute(); } //uma private String otpverifyRequestModel() { String otp_no,mobile_no, version_id; mobile_no = et_mobile.getText().toString(); otp_no = et_otp_no.getText().toString(); //version_id = BuildConfig.VERSION_NAME; JSONObject requestObject = new JSONObject(); try { requestObject.put("mobile_number", mobile_no); requestObject.put("otp", otp_no); //requestObject.put("AppVersion", version_id); System.out.println(requestObject.toString()); } catch (JSONException e) { e.printStackTrace(); } return requestObject.toString(); } private void postResendOtp() { new BackgroundTask(MobileLoginActivity.this, new BackgroundThread() { @Override public Object runTask() { return ApiServices.resendotp(MobileLoginActivity.this, resendotpRequestModel()); } public void taskCompleted(Object data) { SharedPreferenceUtil.setMobile_number(getApplicationContext(), et_mobile.getText().toString()); Globals.showToast(getApplicationContext(), data.toString()); /* Intent mediaActivity = new Intent(getApplicationContext(), MediaActivity.class); startActivity(mediaActivity);*/ } }, getString(R.string.loading_txt)).execute(); } private String resendotpRequestModel() { String mobile_no, version_id; mobile_no = et_mobile.getText().toString(); // version_id = BuildConfig.VERSION_NAME; JSONObject requestObject = new JSONObject(); try { requestObject.put("mobile_number", mobile_no); requestObject.put("device_id", token); /// requestObject.put("AppVersion", version_id); System.out.println(requestObject.toString()); } catch (JSONException e) { e.printStackTrace(); } return requestObject.toString(); } private boolean isvalidphonenumber() { boolean isValid = false; if (et_mobile.getText().toString().equals("")) { et_mobile.setError("Please enter phone number"); et_mobile.requestFocus();} /*else if(Double.parseDouble(et_mobile.getText().toString())!=10){ et_mobile.setError("please enter valid Phone Number"); et_mobile.requestFocus();}*/ else { isValid = true; } return isValid; } private boolean isvalidotpnumber() { boolean isValid = false; if (et_otp_no.getText().toString().equals("")) { et_otp_no.setError("Please enter OTP "); et_otp_no.requestFocus();} else { isValid = true; } return isValid; } }
UTF-8
Java
9,246
java
MobileLoginActivity.java
Java
[]
null
[]
package com.anyemi.housi; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import com.anyemi.housi.connection.ApiServices; import com.anyemi.housi.connection.bgtask.BackgroundTask; import com.anyemi.housi.connection.bgtask.BackgroundThread; import com.anyemi.housi.utils.Globals; import com.anyemi.housi.utils.SharedPreferenceUtil; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.InstanceIdResult; import com.google.firebase.messaging.FirebaseMessaging; import com.google.gson.Gson; import org.json.JSONException; import org.json.JSONObject; public class MobileLoginActivity extends AppCompatActivity { private TextView tv_Resendotp; private EditText et_mobile,et_otp_no; private Button btn_Next,btn_verify_otp; String token; // EditText et_mobile2 = new EditText(CreateRoomActivity.this); // Button btn_Next2 = new Button(CreateRoomActivity.this); protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getSupportActionBar().hide(); setContentView(R.layout.activity_mobile_login); FirebaseInstanceId.getInstance().getInstanceId() .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() { @Override public void onComplete(@NonNull Task<InstanceIdResult> task) { if (!task.isSuccessful()) { Log.w("getInstanceId", "getInstanceId failed", task.getException()); return; } // Get new Instance ID token token = task.getResult().getToken(); // Log and toast // String msg = getString(R.string.msg_token_fmt, token); Log.e("token", token); // Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show(); } }); // String reg_code = SharedPreferenceUtil.getRegCode(getApplicationContext()); et_mobile = findViewById(R.id.et_mobile_no); et_otp_no = findViewById(R.id.et_otp); tv_Resendotp = findViewById(R.id.tv_resend_otp); btn_Next = findViewById(R.id.btn_next); btn_verify_otp = findViewById(R.id.btn_verify); et_otp_no.setVisibility(View.INVISIBLE); btn_verify_otp.setVisibility(View.INVISIBLE); tv_Resendotp.setVisibility(View.INVISIBLE); /* btn_Next.setOnClickListener(new View.OnClickListener() {*/ btn_Next.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { if(isvalidphonenumber()) { et_mobile.setVisibility(View.INVISIBLE); btn_Next.setVisibility(View.INVISIBLE); et_otp_no.setVisibility(View.VISIBLE); btn_verify_otp.setVisibility(View.VISIBLE); tv_Resendotp.setVisibility(View.VISIBLE); postMobileNumber(); } } }); tv_Resendotp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { postResendOtp(); } }); btn_verify_otp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(isvalidotpnumber()) { postVerifyOtpNumber(); /*Intent i=new Intent( getApplicationContext(), HomeActivity.class); startActivity(i);*/ } } }); } private void postMobileNumber() { new BackgroundTask(MobileLoginActivity.this, new BackgroundThread() { @Override public Object runTask() { return ApiServices.login(MobileLoginActivity.this, mobileloginRequestModel()); } public void taskCompleted(Object data) { SharedPreferenceUtil.setMobile_number(getApplicationContext(), et_mobile.getText().toString()); Globals.showToast(getApplicationContext(), data.toString()); /* Intent mediaActivity = new Intent(getApplicationContext(), MediaActivity.class); startActivity(mediaActivity);*/ } }, getString(R.string.loading_txt)).execute(); } private String mobileloginRequestModel() { String mobile_no, version_id; mobile_no = et_mobile.getText().toString(); // version_id = BuildConfig.VERSION_NAME; JSONObject requestObject = new JSONObject(); try { requestObject.put("mobile_number", mobile_no); requestObject.put("device_id", token); /// requestObject.put("AppVersion", version_id); System.out.println(requestObject.toString()); } catch (JSONException e) { e.printStackTrace(); } return requestObject.toString(); } private void postVerifyOtpNumber() { new BackgroundTask(MobileLoginActivity.this, new BackgroundThread() { @Override public Object runTask() { return ApiServices.verifyotp(MobileLoginActivity.this, otpverifyRequestModel()); } public void taskCompleted(Object data) { VerifyOtp verifyOtp =new VerifyOtp(); verifyOtp= new Gson().fromJson(data.toString(),VerifyOtp.class); SharedPreferenceUtil.setMobile_number(getApplicationContext(), et_mobile.getText().toString()); SharedPreferenceUtil.setId(getApplicationContext(), verifyOtp.getId()); Globals.showToast(getApplicationContext(), data.toString()); Intent i = new Intent(getApplicationContext(), HomeActivity.class); startActivity(i); } }, getString(R.string.loading_txt)).execute(); } //uma private String otpverifyRequestModel() { String otp_no,mobile_no, version_id; mobile_no = et_mobile.getText().toString(); otp_no = et_otp_no.getText().toString(); //version_id = BuildConfig.VERSION_NAME; JSONObject requestObject = new JSONObject(); try { requestObject.put("mobile_number", mobile_no); requestObject.put("otp", otp_no); //requestObject.put("AppVersion", version_id); System.out.println(requestObject.toString()); } catch (JSONException e) { e.printStackTrace(); } return requestObject.toString(); } private void postResendOtp() { new BackgroundTask(MobileLoginActivity.this, new BackgroundThread() { @Override public Object runTask() { return ApiServices.resendotp(MobileLoginActivity.this, resendotpRequestModel()); } public void taskCompleted(Object data) { SharedPreferenceUtil.setMobile_number(getApplicationContext(), et_mobile.getText().toString()); Globals.showToast(getApplicationContext(), data.toString()); /* Intent mediaActivity = new Intent(getApplicationContext(), MediaActivity.class); startActivity(mediaActivity);*/ } }, getString(R.string.loading_txt)).execute(); } private String resendotpRequestModel() { String mobile_no, version_id; mobile_no = et_mobile.getText().toString(); // version_id = BuildConfig.VERSION_NAME; JSONObject requestObject = new JSONObject(); try { requestObject.put("mobile_number", mobile_no); requestObject.put("device_id", token); /// requestObject.put("AppVersion", version_id); System.out.println(requestObject.toString()); } catch (JSONException e) { e.printStackTrace(); } return requestObject.toString(); } private boolean isvalidphonenumber() { boolean isValid = false; if (et_mobile.getText().toString().equals("")) { et_mobile.setError("Please enter phone number"); et_mobile.requestFocus();} /*else if(Double.parseDouble(et_mobile.getText().toString())!=10){ et_mobile.setError("please enter valid Phone Number"); et_mobile.requestFocus();}*/ else { isValid = true; } return isValid; } private boolean isvalidotpnumber() { boolean isValid = false; if (et_otp_no.getText().toString().equals("")) { et_otp_no.setError("Please enter OTP "); et_otp_no.requestFocus();} else { isValid = true; } return isValid; } }
9,246
0.601557
0.601125
287
31.188154
28.048355
111
false
false
0
0
0
0
0
0
0.581882
false
false
13
4b30355fb4794785ccdabc75552f5bcfdadb0d4e
5,720,896,507,095
0d3d4d93533a239880a8dd47a6ae27ab9628ffa9
/java/com/turing/card/service/impl/BukaServiceImpl.java
2e68758cc1b402e278e4170b4fcfe6153fcfbe62
[]
no_license
maerkaixin/myProject
https://github.com/maerkaixin/myProject
35bada9c6fcd9ab9ba58d7ff6b35a75881eb4d2b
e923765f066ab71ad7ec77fc89a58b51c4793f64
refs/heads/master
2021-07-10T11:53:09.979000
2017-10-10T14:00:33
2017-10-10T14:00:33
104,576,466
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.turing.card.service.impl; import java.util.Date; import java.util.List; import java.util.UUID; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.turing.card.entity.CardBuka; import com.turing.card.entity.CardHuiyuanbanka; import com.turing.card.mapper.CardBukaMapper; import com.turing.card.mapper.CardHuiyuanbankaMapper; import com.turing.card.page.BukaPage; import com.turing.card.service.IBukaService; @Service public class BukaServiceImpl implements IBukaService { @Autowired private CardBukaMapper mapper; @Autowired private CardHuiyuanbankaMapper hybkMapper; @Override public List<CardBuka> queryAll(BukaPage page) { return mapper.queryAll(page); } @Override public void save(CardBuka bk) { if (StringUtils.isNotBlank(bk.getBkId())) {//修改保存 //将旧卡的卡号还原 CardBuka oldbk = mapper.selectById(bk.getBkId()); CardHuiyuanbanka oldhybk = hybkMapper.selectOne(oldbk.getHcId()); oldhybk.setHcNo(oldbk.getBkOldNo()); hybkMapper.updateByPrimaryKey(oldhybk); //修改新卡的卡号 CardHuiyuanbanka newhybk = hybkMapper.selectOne(bk.getHcId()); newhybk.setHcNo(bk.getBkNo()); hybkMapper.updateByPrimaryKey(newhybk); //修改补卡记录 bk.setBkTime(new Date()); mapper.updateByPrimaryKeySelective(bk); }else{ //更新会员办卡表字段 CardHuiyuanbanka hybk = hybkMapper.selectOne(bk.getHcId()); hybk.setHcNo(bk.getBkNo()); hybkMapper.updateByPrimaryKeySelective(hybk); //新增保存 bk.setBkId(UUID.randomUUID().toString()); bk.setBkTime(new Date()); mapper.insertSelective(bk); } } @Override public void delete(String[] ids) { for (String id : ids) { CardBuka bk = mapper.selectByPrimaryKey(id); CardHuiyuanbanka hybk = hybkMapper.selectOne(bk.getHcId()); hybk.setHcNo(bk.getBkOldNo()); hybkMapper.updateByPrimaryKeySelective(hybk); mapper.deleteByPrimaryKey(id); } } @Override public CardBuka selectById(String id) { return mapper.selectById(id); } }
UTF-8
Java
2,219
java
BukaServiceImpl.java
Java
[]
null
[]
package com.turing.card.service.impl; import java.util.Date; import java.util.List; import java.util.UUID; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.turing.card.entity.CardBuka; import com.turing.card.entity.CardHuiyuanbanka; import com.turing.card.mapper.CardBukaMapper; import com.turing.card.mapper.CardHuiyuanbankaMapper; import com.turing.card.page.BukaPage; import com.turing.card.service.IBukaService; @Service public class BukaServiceImpl implements IBukaService { @Autowired private CardBukaMapper mapper; @Autowired private CardHuiyuanbankaMapper hybkMapper; @Override public List<CardBuka> queryAll(BukaPage page) { return mapper.queryAll(page); } @Override public void save(CardBuka bk) { if (StringUtils.isNotBlank(bk.getBkId())) {//修改保存 //将旧卡的卡号还原 CardBuka oldbk = mapper.selectById(bk.getBkId()); CardHuiyuanbanka oldhybk = hybkMapper.selectOne(oldbk.getHcId()); oldhybk.setHcNo(oldbk.getBkOldNo()); hybkMapper.updateByPrimaryKey(oldhybk); //修改新卡的卡号 CardHuiyuanbanka newhybk = hybkMapper.selectOne(bk.getHcId()); newhybk.setHcNo(bk.getBkNo()); hybkMapper.updateByPrimaryKey(newhybk); //修改补卡记录 bk.setBkTime(new Date()); mapper.updateByPrimaryKeySelective(bk); }else{ //更新会员办卡表字段 CardHuiyuanbanka hybk = hybkMapper.selectOne(bk.getHcId()); hybk.setHcNo(bk.getBkNo()); hybkMapper.updateByPrimaryKeySelective(hybk); //新增保存 bk.setBkId(UUID.randomUUID().toString()); bk.setBkTime(new Date()); mapper.insertSelective(bk); } } @Override public void delete(String[] ids) { for (String id : ids) { CardBuka bk = mapper.selectByPrimaryKey(id); CardHuiyuanbanka hybk = hybkMapper.selectOne(bk.getHcId()); hybk.setHcNo(bk.getBkOldNo()); hybkMapper.updateByPrimaryKeySelective(hybk); mapper.deleteByPrimaryKey(id); } } @Override public CardBuka selectById(String id) { return mapper.selectById(id); } }
2,219
0.721419
0.721419
77
25.831169
20.134226
68
false
false
0
0
0
0
0
0
2.103896
false
false
13
5b9507862875111389dc474b801a3519b6e61f5c
19,439,022,051,202
dc165278d4e617f330468cf5e987881ce25394d4
/src/main/java/dev/onyxstudios/bff/blocks/BlockFunctionalFlower.java
3835d9af2bafdf8692c2cde4211e63e9827d5dd1
[]
no_license
OnyxStudios/Botanical-Functioning-Flora
https://github.com/OnyxStudios/Botanical-Functioning-Flora
a08051faf3d6acd6c7801730c0a7793a3816bd69
17bb5cb2549623559c153e61e3f445af355099de
refs/heads/main
2023-02-05T23:46:38.598000
2021-01-02T10:51:12
2021-01-02T10:51:12
325,907,860
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dev.onyxstudios.bff.blocks; import net.minecraft.potion.Effect; import vazkii.botania.api.subtile.TileEntitySpecialFlower; import vazkii.botania.common.block.BlockSpecialFlower; import java.util.function.Supplier; public class BlockFunctionalFlower extends BlockSpecialFlower { public BlockFunctionalFlower(Effect stewEffect, int stewDuration, Properties props, Supplier<? extends TileEntitySpecialFlower> teProvider) { super(stewEffect, stewDuration, props, teProvider); } }
UTF-8
Java
504
java
BlockFunctionalFlower.java
Java
[]
null
[]
package dev.onyxstudios.bff.blocks; import net.minecraft.potion.Effect; import vazkii.botania.api.subtile.TileEntitySpecialFlower; import vazkii.botania.common.block.BlockSpecialFlower; import java.util.function.Supplier; public class BlockFunctionalFlower extends BlockSpecialFlower { public BlockFunctionalFlower(Effect stewEffect, int stewDuration, Properties props, Supplier<? extends TileEntitySpecialFlower> teProvider) { super(stewEffect, stewDuration, props, teProvider); } }
504
0.813492
0.813492
14
35
39.010986
145
false
false
0
0
0
0
0
0
0.857143
false
false
13
a7633a29e7e3fb31bd2896d0aadd43f9a9a2ede8
38,371,237,833,195
ab64547749394f03eb75703f297dc2ca9ad3a8ff
/src/DAO/Filetype.java
b842b1687129c85e4d1e070b78c1ad538c1abde8
[]
no_license
dream9/editol-javaee
https://github.com/dream9/editol-javaee
4a32b9df50f6f0913d6a021a15480e7e403a90de
da105282c05fd88d50cc4b2c08bc860859ef1711
HEAD
2019-04-23T14:03:13.294000
2017-06-09T08:28:59
2017-06-09T08:28:59
93,577,325
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package DAO; import java.util.List; import org.hibernate.Session; import org.hibernate.Transaction; import DAO.HibernateUtil; import bean.filetypebean; public class Filetype { public void add(filetypebean tb_ft){ Session session= HibernateUtil.getSessionFactory().getCurrentSession(); Transaction tx=session.beginTransaction(); session.save(tb_ft); tx.commit(); System.out.println("saved"); } public void delete(String id){ Session session= HibernateUtil.getSessionFactory().getCurrentSession(); Transaction tx=session.beginTransaction(); filetypebean tb_ft =(filetypebean)session.get(filetypebean.class,id); if(tb_ft!=null) session.delete(tb_ft); tx.commit(); System.out.println("deleted"); } public void modify(filetypebean tb_ft){ Session session= HibernateUtil.getSessionFactory().getCurrentSession(); Transaction tx=session.beginTransaction(); session.update(tb_ft); tx.commit(); System.out.println("updated"); } public filetypebean selectByID(String id){ Session session= HibernateUtil.getSessionFactory().getCurrentSession(); Transaction tx=session.beginTransaction(); filetypebean tb_ft =(filetypebean)session.get(filetypebean.class,id); tx.commit(); return tb_ft; } public List<filetypebean> selectAll(){ Session session= HibernateUtil.getSessionFactory().getCurrentSession(); Transaction tx=session.beginTransaction(); org.hibernate.Query qry = session.createQuery("from filetypebean"); java.util.List list = qry.list(); tx.commit(); return list; } public List<filetypebean> select (String key1,String key2){ Session session= HibernateUtil.getSessionFactory().getCurrentSession(); Transaction tx=session.beginTransaction(); org.hibernate.Query qry = session.createQuery("from filetypebean where "+key1+" = '"+key2+"'"); java.util.List list = qry.list(); tx.commit(); return list; } }
UTF-8
Java
1,899
java
Filetype.java
Java
[]
null
[]
package DAO; import java.util.List; import org.hibernate.Session; import org.hibernate.Transaction; import DAO.HibernateUtil; import bean.filetypebean; public class Filetype { public void add(filetypebean tb_ft){ Session session= HibernateUtil.getSessionFactory().getCurrentSession(); Transaction tx=session.beginTransaction(); session.save(tb_ft); tx.commit(); System.out.println("saved"); } public void delete(String id){ Session session= HibernateUtil.getSessionFactory().getCurrentSession(); Transaction tx=session.beginTransaction(); filetypebean tb_ft =(filetypebean)session.get(filetypebean.class,id); if(tb_ft!=null) session.delete(tb_ft); tx.commit(); System.out.println("deleted"); } public void modify(filetypebean tb_ft){ Session session= HibernateUtil.getSessionFactory().getCurrentSession(); Transaction tx=session.beginTransaction(); session.update(tb_ft); tx.commit(); System.out.println("updated"); } public filetypebean selectByID(String id){ Session session= HibernateUtil.getSessionFactory().getCurrentSession(); Transaction tx=session.beginTransaction(); filetypebean tb_ft =(filetypebean)session.get(filetypebean.class,id); tx.commit(); return tb_ft; } public List<filetypebean> selectAll(){ Session session= HibernateUtil.getSessionFactory().getCurrentSession(); Transaction tx=session.beginTransaction(); org.hibernate.Query qry = session.createQuery("from filetypebean"); java.util.List list = qry.list(); tx.commit(); return list; } public List<filetypebean> select (String key1,String key2){ Session session= HibernateUtil.getSessionFactory().getCurrentSession(); Transaction tx=session.beginTransaction(); org.hibernate.Query qry = session.createQuery("from filetypebean where "+key1+" = '"+key2+"'"); java.util.List list = qry.list(); tx.commit(); return list; } }
1,899
0.743549
0.741443
63
29.142857
24.976725
97
false
false
0
0
0
0
0
0
1.984127
false
false
13
cfc7b247590fdc8f0a32ac69264ceb491c88b400
9,199,820,012,537
865067eb3577cdfc3615efcb8edb91de91ed8ad1
/FeignServer/src/main/java/com/alimaomao/service/MessageServerClient.java
df995c5e07fcada4169edf3cf2d851e234550c1c
[]
no_license
lihuacheng/spring-cloud
https://github.com/lihuacheng/spring-cloud
01b86936efc0190804b0c55e9fa90ee25f01f1fc
b94662bda0dff4d20da659ae6cc738dbdfaea880
refs/heads/master
2021-01-20T15:06:58.087000
2017-05-23T10:19:18
2017-05-23T10:19:18
90,720,684
15
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.alimaomao.service; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; import com.alimaomao.hystrix.MessageServerClientHystrix; @FeignClient(value="ribbon-server",fallback=MessageServerClientHystrix.class) public interface MessageServerClient { @RequestMapping("/Ribbon/message-server") public String test(); }
UTF-8
Java
401
java
MessageServerClient.java
Java
[]
null
[]
package com.alimaomao.service; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; import com.alimaomao.hystrix.MessageServerClientHystrix; @FeignClient(value="ribbon-server",fallback=MessageServerClientHystrix.class) public interface MessageServerClient { @RequestMapping("/Ribbon/message-server") public String test(); }
401
0.832918
0.832918
13
29.846153
26.89537
77
false
false
0
0
0
0
0
0
0.692308
false
false
13
1d27ee26c06cfcf7284b29c45622f44d476a689a
9,199,820,009,330
472a1fee2291cff0e632730fe0b96a49cdda0a6a
/CoupPeli/src/main/java/fi/aleksisv/kayttoliittyma/PelausIkkuna.java
aa71b805e08f2f83ffe7f82ce151362a3f713efe
[]
no_license
aleksisv/Coup-Peli
https://github.com/aleksisv/Coup-Peli
268bfd9e0d921fdef8f1cee39d5f3203a2692b75
8493786568cc330368c84a0271bd6537f193e07c
refs/heads/master
2020-04-17T13:00:32.367000
2016-10-21T09:19:25
2016-10-21T09:19:25
67,588,516
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fi.aleksisv.kayttoliittyma; import fi.aleksisv.logiikka.Vastustaja; import java.awt.*; import java.util.Enumeration; import javax.swing.*; /** * Luokka kuvaa ikkunaa, jossa siirron tapahtuvat. */ public class PelausIkkuna extends JFrame { /** * Tarvittavat nappularyhmät. */ ButtonGroup siirtonappularyhma; ButtonGroup kohdenappularyhma; /** * Peliä pyörittävä taho. */ PeliOhjaus peliOhjaus; /** * Graafinen käyttöliittymä. */ GraafinenKayttoliittyma gkl; /** * Erityishuomioista ilmoittava tekstialue.. */ JTextArea huomiotekstit; /** * Luokan konstruktori. * * @param peliOhjaus Peliä pyörittävä taho. * @param gkl Graafinen käyttöliittymä. * @throws HeadlessException */ public PelausIkkuna(PeliOhjaus peliOhjaus, GraafinenKayttoliittyma gkl) throws HeadlessException { super("Pelausikkuna"); this.peliOhjaus = peliOhjaus; this.gkl = gkl; this.huomiotekstit = new JTextArea(); this.setLocation(500, 500); this.setVisible(true); this.setSize(1000, 700); } /** * Metodi luo pelausvaihtoehdot ikkunaan. * * @param sailio Container-olio. * * @throws HeadlessException */ public void luoPelausVaihtoehdot(Container sailio) { JPanel kokonaisuus = new JPanel(new BorderLayout()); JPanel tekstiPaneeli = new JPanel(new BorderLayout()); this.huomiotekstit.setText("Valitse siirto ja mahdollinen kohde."); this.huomiotekstit.setPreferredSize(new Dimension(1000, 100)); this.huomiotekstit.setBorder(BorderFactory.createEtchedBorder(Color.lightGray, Color.black)); tekstiPaneeli.add(this.huomiotekstit, BorderLayout.CENTER); tekstiPaneeli.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); kokonaisuus.add(tekstiPaneeli, BorderLayout.PAGE_START); JPanel napit = new JPanel(new GridLayout(2, 1)); JPanel siirtonapit = new JPanel(); JPanel kohdenapit = new JPanel(); String[][] siirtoVaihtoehdot = {{"Perustulo:", "Ota 1 kolikko pankista."}, {"Ulkomaanapu:", "Ota 2 kolikkoa pankista. Torjuu: Herttua"}, {"Vallankumous:", "Maksa 7 kolikkoa ja hyökkää yhtä osanottajaa vastaan."}, {"Verotus:", "Ota 3 kolikkoa pankista. Tarvitset: Herttua."}, {"Assassinoi:", "Maksa 3 kolikkoa ja hyökkää yhtä osanottajaa kohtaan. Tarvitset: Salamurhaaja. Torjuu: Kreivitär."}, {"Varasta:", "Ota vastustajalta 2 kolikkoa. Tarvitset: Kapteeni. Torjuu: Kapteeni."}}; napit.add(lisaaSiirtonapit(siirtoVaihtoehdot, siirtonapit)); napit.add(lisaaKohdenapit(kohdenapit)); kokonaisuus.add(napit, BorderLayout.CENTER); JButton teeSiirto = new JButton("Tee siirto!"); JPanel teeNappiPaneeli = new JPanel(new BorderLayout()); teeNappiPaneeli.setBorder(BorderFactory.createEmptyBorder(15, 560, 15, 560)); teeNappiPaneeli.add(teeSiirto, BorderLayout.CENTER); teeSiirto.addActionListener(new PeliSiirtoKuuntelija(peliOhjaus, this, gkl, this.siirtonappularyhma, this.kohdenappularyhma)); kokonaisuus.add(teeNappiPaneeli, BorderLayout.PAGE_END); kokonaisuus.validate(); sailio.add(kokonaisuus); this.pack(); } private JPanel lisaaSiirtonapit(String[][] siirtoVaihtoehdot, JPanel siirtonapit) { JPanel seliteJaNappi = new JPanel(new GridLayout(6, 1)); seliteJaNappi.setBorder(BorderFactory.createEtchedBorder(Color.lightGray, Color.black)); this.siirtonappularyhma = new ButtonGroup(); for (int i = 0; i < siirtoVaihtoehdot.length; i++) { JRadioButton nappi = new JRadioButton(siirtoVaihtoehdot[i][0]); nappi.setActionCommand(Integer.toString(i + 1)); seliteJaNappi.add(nappi, BorderLayout.PAGE_START); seliteJaNappi.add(new JLabel(siirtoVaihtoehdot[i][1])); siirtonappularyhma.add(nappi); if (i == 0) { nappi.setSelected(true); } } siirtonapit.setBorder(BorderFactory.createEmptyBorder(10, 15, 10, 15)); siirtonapit.add(seliteJaNappi); return siirtonapit; } private JPanel lisaaKohdenapit(JPanel kohdenapit) { int osanottajiaMukana = this.peliOhjaus.getPeli().getOsanottajajoukko().size(); JPanel seliteJaNappi = new JPanel(new GridLayout(osanottajiaMukana, 1)); seliteJaNappi.setBorder(BorderFactory.createEtchedBorder(Color.lightGray, Color.black)); this.kohdenappularyhma = new ButtonGroup(); for (int i = 1; i < this.peliOhjaus.getPeli().getOsanottajajoukko().size(); i++) { JRadioButton nappi = new JRadioButton(Integer.toString(i)); nappi.setActionCommand(Integer.toString(i)); seliteJaNappi.add(nappi); seliteJaNappi.add(new JLabel("osanottaja " + this.peliOhjaus.getPeli().getOsanottajajoukko().get(i).getNimi() + " ")); kohdenappularyhma.add(nappi); if (i == 1) { nappi.setSelected(true); } } kohdenapit.setBorder(BorderFactory.createEmptyBorder(50, 0, 50, 0)); kohdenapit.add(seliteJaNappi); return kohdenapit; } /** * Metodi luo vastustajan vuoroon tarvittavat komponentit ja kuuntelijat. * * @param vastustaja Vastustaja, jonka vuoro luodaan. * @param sailio Container-olio. */ public void luoVastustajanVuoro(Vastustaja vastustaja, Container sailio) { sailio.removeAll(); JPanel paneeli = new JPanel(new GridLayout(2, 1)); paneeli.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); JLabel otsikko = new JLabel("Vastustajan vuoro."); otsikko.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); paneeli.add(otsikko); JButton vastustajanSiirto = new JButton("Anna vastustajan tehdä siirto!"); vastustajanSiirto.addActionListener(new VastustajanSiirtoKuuntelija(this.peliOhjaus, this.gkl, this, vastustaja)); paneeli.add(vastustajanSiirto); sailio.add(paneeli); } /** * Metodi palauttaa huomiotekstit-tekstialueen. * * @return Huomiotekstit. */ public JTextArea getHuomiotekstit() { return huomiotekstit; } }
UTF-8
Java
6,636
java
PelausIkkuna.java
Java
[]
null
[]
package fi.aleksisv.kayttoliittyma; import fi.aleksisv.logiikka.Vastustaja; import java.awt.*; import java.util.Enumeration; import javax.swing.*; /** * Luokka kuvaa ikkunaa, jossa siirron tapahtuvat. */ public class PelausIkkuna extends JFrame { /** * Tarvittavat nappularyhmät. */ ButtonGroup siirtonappularyhma; ButtonGroup kohdenappularyhma; /** * Peliä pyörittävä taho. */ PeliOhjaus peliOhjaus; /** * Graafinen käyttöliittymä. */ GraafinenKayttoliittyma gkl; /** * Erityishuomioista ilmoittava tekstialue.. */ JTextArea huomiotekstit; /** * Luokan konstruktori. * * @param peliOhjaus Peliä pyörittävä taho. * @param gkl Graafinen käyttöliittymä. * @throws HeadlessException */ public PelausIkkuna(PeliOhjaus peliOhjaus, GraafinenKayttoliittyma gkl) throws HeadlessException { super("Pelausikkuna"); this.peliOhjaus = peliOhjaus; this.gkl = gkl; this.huomiotekstit = new JTextArea(); this.setLocation(500, 500); this.setVisible(true); this.setSize(1000, 700); } /** * Metodi luo pelausvaihtoehdot ikkunaan. * * @param sailio Container-olio. * * @throws HeadlessException */ public void luoPelausVaihtoehdot(Container sailio) { JPanel kokonaisuus = new JPanel(new BorderLayout()); JPanel tekstiPaneeli = new JPanel(new BorderLayout()); this.huomiotekstit.setText("Valitse siirto ja mahdollinen kohde."); this.huomiotekstit.setPreferredSize(new Dimension(1000, 100)); this.huomiotekstit.setBorder(BorderFactory.createEtchedBorder(Color.lightGray, Color.black)); tekstiPaneeli.add(this.huomiotekstit, BorderLayout.CENTER); tekstiPaneeli.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); kokonaisuus.add(tekstiPaneeli, BorderLayout.PAGE_START); JPanel napit = new JPanel(new GridLayout(2, 1)); JPanel siirtonapit = new JPanel(); JPanel kohdenapit = new JPanel(); String[][] siirtoVaihtoehdot = {{"Perustulo:", "Ota 1 kolikko pankista."}, {"Ulkomaanapu:", "Ota 2 kolikkoa pankista. Torjuu: Herttua"}, {"Vallankumous:", "Maksa 7 kolikkoa ja hyökkää yhtä osanottajaa vastaan."}, {"Verotus:", "Ota 3 kolikkoa pankista. Tarvitset: Herttua."}, {"Assassinoi:", "Maksa 3 kolikkoa ja hyökkää yhtä osanottajaa kohtaan. Tarvitset: Salamurhaaja. Torjuu: Kreivitär."}, {"Varasta:", "Ota vastustajalta 2 kolikkoa. Tarvitset: Kapteeni. Torjuu: Kapteeni."}}; napit.add(lisaaSiirtonapit(siirtoVaihtoehdot, siirtonapit)); napit.add(lisaaKohdenapit(kohdenapit)); kokonaisuus.add(napit, BorderLayout.CENTER); JButton teeSiirto = new JButton("Tee siirto!"); JPanel teeNappiPaneeli = new JPanel(new BorderLayout()); teeNappiPaneeli.setBorder(BorderFactory.createEmptyBorder(15, 560, 15, 560)); teeNappiPaneeli.add(teeSiirto, BorderLayout.CENTER); teeSiirto.addActionListener(new PeliSiirtoKuuntelija(peliOhjaus, this, gkl, this.siirtonappularyhma, this.kohdenappularyhma)); kokonaisuus.add(teeNappiPaneeli, BorderLayout.PAGE_END); kokonaisuus.validate(); sailio.add(kokonaisuus); this.pack(); } private JPanel lisaaSiirtonapit(String[][] siirtoVaihtoehdot, JPanel siirtonapit) { JPanel seliteJaNappi = new JPanel(new GridLayout(6, 1)); seliteJaNappi.setBorder(BorderFactory.createEtchedBorder(Color.lightGray, Color.black)); this.siirtonappularyhma = new ButtonGroup(); for (int i = 0; i < siirtoVaihtoehdot.length; i++) { JRadioButton nappi = new JRadioButton(siirtoVaihtoehdot[i][0]); nappi.setActionCommand(Integer.toString(i + 1)); seliteJaNappi.add(nappi, BorderLayout.PAGE_START); seliteJaNappi.add(new JLabel(siirtoVaihtoehdot[i][1])); siirtonappularyhma.add(nappi); if (i == 0) { nappi.setSelected(true); } } siirtonapit.setBorder(BorderFactory.createEmptyBorder(10, 15, 10, 15)); siirtonapit.add(seliteJaNappi); return siirtonapit; } private JPanel lisaaKohdenapit(JPanel kohdenapit) { int osanottajiaMukana = this.peliOhjaus.getPeli().getOsanottajajoukko().size(); JPanel seliteJaNappi = new JPanel(new GridLayout(osanottajiaMukana, 1)); seliteJaNappi.setBorder(BorderFactory.createEtchedBorder(Color.lightGray, Color.black)); this.kohdenappularyhma = new ButtonGroup(); for (int i = 1; i < this.peliOhjaus.getPeli().getOsanottajajoukko().size(); i++) { JRadioButton nappi = new JRadioButton(Integer.toString(i)); nappi.setActionCommand(Integer.toString(i)); seliteJaNappi.add(nappi); seliteJaNappi.add(new JLabel("osanottaja " + this.peliOhjaus.getPeli().getOsanottajajoukko().get(i).getNimi() + " ")); kohdenappularyhma.add(nappi); if (i == 1) { nappi.setSelected(true); } } kohdenapit.setBorder(BorderFactory.createEmptyBorder(50, 0, 50, 0)); kohdenapit.add(seliteJaNappi); return kohdenapit; } /** * Metodi luo vastustajan vuoroon tarvittavat komponentit ja kuuntelijat. * * @param vastustaja Vastustaja, jonka vuoro luodaan. * @param sailio Container-olio. */ public void luoVastustajanVuoro(Vastustaja vastustaja, Container sailio) { sailio.removeAll(); JPanel paneeli = new JPanel(new GridLayout(2, 1)); paneeli.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); JLabel otsikko = new JLabel("Vastustajan vuoro."); otsikko.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); paneeli.add(otsikko); JButton vastustajanSiirto = new JButton("Anna vastustajan tehdä siirto!"); vastustajanSiirto.addActionListener(new VastustajanSiirtoKuuntelija(this.peliOhjaus, this.gkl, this, vastustaja)); paneeli.add(vastustajanSiirto); sailio.add(paneeli); } /** * Metodi palauttaa huomiotekstit-tekstialueen. * * @return Huomiotekstit. */ public JTextArea getHuomiotekstit() { return huomiotekstit; } }
6,636
0.640448
0.627137
186
34.543011
31.402876
134
false
false
0
0
0
0
0
0
0.747312
false
false
13
35aed38ed035e911e6d2748e1f0b1c8f61af9b6c
33,002,528,765,038
f897e902626f07d8020a258fc74762bd53775e8d
/src/dao/AllUseBoardDAO2.java
5e74b17c5c6cda5c9288b6130a5d4d24ad901a37
[]
no_license
kjs1m1/tproject
https://github.com/kjs1m1/tproject
70f62d3b606b3b552977c90255891e74113d3377
3426bd7125bc82cec59d87071d99b7fcf5fea138
refs/heads/master
2020-12-22T07:31:54.139000
2020-01-28T10:46:51
2020-01-28T10:46:51
236,705,865
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dao; import service.OracleUtil; import vo.AllUseBoard; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.util.ArrayList; import java.util.HashMap; public class AllUseBoardDAO2 { private Connection conn = null; private PreparedStatement pstmt = null; private ResultSet rs = null; OracleUtil oracle = new OracleUtil(); private ArrayList<HashMap<String, Object>> lists = null; // 게시판 목록을 보여주기위한 메소드 (공통으로 사용가능) public ArrayList<HashMap<String, Object>> getBoardList(String listSQL) { try { conn = oracle.getConn(); pstmt = conn.prepareStatement(listSQL); rs = pstmt.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); String columnName = ""; lists = new ArrayList<>(); HashMap<String, Object> result = null; while (rs.next()) { result = new HashMap<>(); for (int i = 1; i <= columnCount; i++) { columnName = rsmd.getColumnName(i).toLowerCase(); switch (rsmd.getColumnTypeName(i)) { case "VARCHAR" : case "VARCHAR2": case "DATE": case "CLOB": case "CHAR" : result.put(columnName, rs.getString(i)); break; case "INTEGER": case "NUMBER": case "NUMERIC": result.put(columnName, rs.getInt(i)); break; } // switch end } // for end lists.add(result); } } catch (Exception e) { e.printStackTrace(); System.out.println("getBoardList 확인 요망"); } finally { oracle.closeConn(rs, pstmt, conn); } return lists; } // 게시물 수를 반환하는 메소드 (공통으로 사용가능) public int countBoard(String countSQL) { int bdcnt = 0; try { conn = oracle.getConn(); pstmt = conn.prepareStatement(countSQL); rs = pstmt.executeQuery(); while (rs.next()) { bdcnt = rs.getInt(1); } } catch (Exception e) { e.printStackTrace(); } finally { oracle.closeConn(rs, pstmt, conn); } return bdcnt; } // 글쓰기 기능을 하는 메소드(수정필요) public int writeBoard(HashMap<String, String> writer, String writeSQL) { int check = 0; try { conn = oracle.getConn(); pstmt = conn.prepareStatement(writeSQL); pstmt.setString(1, writer.get("title")); pstmt.setString(2, writer.get("userid")); pstmt.setString(3, writer.get("contents")); check = pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { oracle.closeConn(pstmt, conn); } return check; } // 글 내용을 보여주는 메소드 (공통으로 사용가능) public ArrayList<HashMap<String, Object>> viewContents(int bdno, String viewSQL) { try { conn = oracle.getConn(); pstmt = conn.prepareStatement(viewSQL); pstmt.setInt(1, bdno); rs = pstmt.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); String columnName = ""; lists = new ArrayList<>(); HashMap<String, Object> result = null; while (rs.next()) { result = new HashMap<>(); for (int i = 1; i <= columnCount; i++) { columnName = rsmd.getColumnName(i).toLowerCase(); switch (rsmd.getColumnTypeName(i)) { case "VARCHAR" : case "VARCHAR2": case "DATE": case "CLOB": case "CHAR" : result.put(columnName, rs.getString(i)); break; case "INTEGER": case "NUMBER": case "NUMERIC": result.put(columnName, rs.getInt(i)); break; } // switch end } // for end lists.add(result); } } catch (Exception e) { e.printStackTrace(); } finally { oracle.closeConn(rs, pstmt, conn); } return lists; } // 글 내용 수정하는 메소드 (수정필요) public int modifyContents(AllUseBoard modifybd, int mbdno, String modifySQL) { int check = 0; try { conn = oracle.getConn(); pstmt = conn.prepareStatement(modifySQL); pstmt.setString(1, modifybd.getTitle()); pstmt.setString(2, modifybd.getContents()); pstmt.setInt(3, mbdno); check = pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); System.out.println("modifyContents 메소드 확인 요망"); } finally { oracle.closeConn(rs, pstmt, conn); } return check; } // 글 내용 삭제하는 메소드 (공통으로 사용가능) public int deleteList(int bdno, String deleteSQL) { int check = 0; try { conn = oracle.getConn(); pstmt = conn.prepareStatement(deleteSQL); pstmt.setInt(1, bdno); check = pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); System.out.println("deleteList 메소드 확인 요망"); } finally { oracle.closeConn(pstmt, conn); } return check; } }
UTF-8
Java
5,976
java
AllUseBoardDAO2.java
Java
[]
null
[]
package dao; import service.OracleUtil; import vo.AllUseBoard; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.util.ArrayList; import java.util.HashMap; public class AllUseBoardDAO2 { private Connection conn = null; private PreparedStatement pstmt = null; private ResultSet rs = null; OracleUtil oracle = new OracleUtil(); private ArrayList<HashMap<String, Object>> lists = null; // 게시판 목록을 보여주기위한 메소드 (공통으로 사용가능) public ArrayList<HashMap<String, Object>> getBoardList(String listSQL) { try { conn = oracle.getConn(); pstmt = conn.prepareStatement(listSQL); rs = pstmt.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); String columnName = ""; lists = new ArrayList<>(); HashMap<String, Object> result = null; while (rs.next()) { result = new HashMap<>(); for (int i = 1; i <= columnCount; i++) { columnName = rsmd.getColumnName(i).toLowerCase(); switch (rsmd.getColumnTypeName(i)) { case "VARCHAR" : case "VARCHAR2": case "DATE": case "CLOB": case "CHAR" : result.put(columnName, rs.getString(i)); break; case "INTEGER": case "NUMBER": case "NUMERIC": result.put(columnName, rs.getInt(i)); break; } // switch end } // for end lists.add(result); } } catch (Exception e) { e.printStackTrace(); System.out.println("getBoardList 확인 요망"); } finally { oracle.closeConn(rs, pstmt, conn); } return lists; } // 게시물 수를 반환하는 메소드 (공통으로 사용가능) public int countBoard(String countSQL) { int bdcnt = 0; try { conn = oracle.getConn(); pstmt = conn.prepareStatement(countSQL); rs = pstmt.executeQuery(); while (rs.next()) { bdcnt = rs.getInt(1); } } catch (Exception e) { e.printStackTrace(); } finally { oracle.closeConn(rs, pstmt, conn); } return bdcnt; } // 글쓰기 기능을 하는 메소드(수정필요) public int writeBoard(HashMap<String, String> writer, String writeSQL) { int check = 0; try { conn = oracle.getConn(); pstmt = conn.prepareStatement(writeSQL); pstmt.setString(1, writer.get("title")); pstmt.setString(2, writer.get("userid")); pstmt.setString(3, writer.get("contents")); check = pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { oracle.closeConn(pstmt, conn); } return check; } // 글 내용을 보여주는 메소드 (공통으로 사용가능) public ArrayList<HashMap<String, Object>> viewContents(int bdno, String viewSQL) { try { conn = oracle.getConn(); pstmt = conn.prepareStatement(viewSQL); pstmt.setInt(1, bdno); rs = pstmt.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); String columnName = ""; lists = new ArrayList<>(); HashMap<String, Object> result = null; while (rs.next()) { result = new HashMap<>(); for (int i = 1; i <= columnCount; i++) { columnName = rsmd.getColumnName(i).toLowerCase(); switch (rsmd.getColumnTypeName(i)) { case "VARCHAR" : case "VARCHAR2": case "DATE": case "CLOB": case "CHAR" : result.put(columnName, rs.getString(i)); break; case "INTEGER": case "NUMBER": case "NUMERIC": result.put(columnName, rs.getInt(i)); break; } // switch end } // for end lists.add(result); } } catch (Exception e) { e.printStackTrace(); } finally { oracle.closeConn(rs, pstmt, conn); } return lists; } // 글 내용 수정하는 메소드 (수정필요) public int modifyContents(AllUseBoard modifybd, int mbdno, String modifySQL) { int check = 0; try { conn = oracle.getConn(); pstmt = conn.prepareStatement(modifySQL); pstmt.setString(1, modifybd.getTitle()); pstmt.setString(2, modifybd.getContents()); pstmt.setInt(3, mbdno); check = pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); System.out.println("modifyContents 메소드 확인 요망"); } finally { oracle.closeConn(rs, pstmt, conn); } return check; } // 글 내용 삭제하는 메소드 (공통으로 사용가능) public int deleteList(int bdno, String deleteSQL) { int check = 0; try { conn = oracle.getConn(); pstmt = conn.prepareStatement(deleteSQL); pstmt.setInt(1, bdno); check = pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); System.out.println("deleteList 메소드 확인 요망"); } finally { oracle.closeConn(pstmt, conn); } return check; } }
5,976
0.508389
0.505243
195
28.338461
22.516964
97
false
false
0
0
0
0
0
0
0.651282
false
false
13
0ad53ea3606906fd0cd87bc3015f12d14bdd1b62
4,698,694,281,747
1f53b9ab9d6dccc492e648fcc25ab6456d92bce8
/domain/src/main/java/br/com/milenio/vendingmachine/domain/AbstractRepositoryBean.java
8f0bd2b7590392273da586e022ca29e0413b4554
[]
no_license
otavioprado/vendingmachine
https://github.com/otavioprado/vendingmachine
456ee46fdcbf045fe5c69ba0c6cb3534b2f3990b
1ca7e03103b7801e5e0861816ba81aaf0f9bab9f
refs/heads/master
2020-04-11T13:55:21.708000
2015-11-10T23:28:14
2015-11-10T23:28:14
30,721,138
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.milenio.vendingmachine.domain; import java.io.Serializable; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Query; /** * Implementação abstrata de um Repository. * <p/> * Esta classe não deve ser estendida diretamente por classes concretas se o * aplicativo sendo desenvolvido utiliza várias unidades de persistência. * Idealmente, deve haver uma classe abstrata intermediária que é injetada com a * unidade de persistência desejada e que implementa o método * {@link #getEntityManager()}, de modo que o repositório atual estenderia esta * classe intermediária. * * @author Otávio Prado * @param <T> * Interface implemented by the entity * @param <ID> * Class of the primary key attribute */ public abstract class AbstractRepositoryBean<T extends Serializable, I extends Serializable> implements Repository<T, I> { protected final Class<? extends T> entityConcreteClass; /** * Cria uma nova instância do repositório. * * @param entityConcreteClass * Classe concreta da entidade. Observe que esta classe está * escondida atrás da interface {@link Repository} */ protected AbstractRepositoryBean(Class<? extends T> entityConcreteClass) { this.entityConcreteClass = entityConcreteClass; } /** * Obtém o entity manager atual. * <p/> * Sub-classes devem implementar este método de acordo com suas * necessidades. Isto é especialmente útil quando forem usadas várias * unidades de persistência. * * @return EntityManager */ protected abstract EntityManager getEntityManager(); public void persist(T v) { getEntityManager().persist(v); } public T merge(T v) { return getEntityManager().merge(v); } public T findById(I id) { return (T) getEntityManager().find(entityConcreteClass, id); } public void remove(T c) { getEntityManager().remove(c); } @SuppressWarnings("unchecked") public List<T> getAll() { Query query = getEntityManager().createQuery( "SELECT e FROM " + entityConcreteClass.getName() + " e"); return (List<T>) query.getResultList(); } /** * Cria uma nova instância da entidade. */ public T newInstance() { try { return entityConcreteClass.newInstance(); } catch (InstantiationException e) { throw new RuntimeException("Error creating entity instance", e); } catch (IllegalAccessException e) { throw new RuntimeException("Error creating entity instance", e); } } }
ISO-8859-1
Java
2,509
java
AbstractRepositoryBean.java
Java
[ { "context": "nderia esta\n * classe intermediária.\n *\n * @author Otávio Prado\n * @param <T>\n * Interface implemented", "end": 654, "score": 0.9998802542686462, "start": 642, "tag": "NAME", "value": "Otávio Prado" } ]
null
[]
package br.com.milenio.vendingmachine.domain; import java.io.Serializable; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Query; /** * Implementação abstrata de um Repository. * <p/> * Esta classe não deve ser estendida diretamente por classes concretas se o * aplicativo sendo desenvolvido utiliza várias unidades de persistência. * Idealmente, deve haver uma classe abstrata intermediária que é injetada com a * unidade de persistência desejada e que implementa o método * {@link #getEntityManager()}, de modo que o repositório atual estenderia esta * classe intermediária. * * @author <NAME> * @param <T> * Interface implemented by the entity * @param <ID> * Class of the primary key attribute */ public abstract class AbstractRepositoryBean<T extends Serializable, I extends Serializable> implements Repository<T, I> { protected final Class<? extends T> entityConcreteClass; /** * Cria uma nova instância do repositório. * * @param entityConcreteClass * Classe concreta da entidade. Observe que esta classe está * escondida atrás da interface {@link Repository} */ protected AbstractRepositoryBean(Class<? extends T> entityConcreteClass) { this.entityConcreteClass = entityConcreteClass; } /** * Obtém o entity manager atual. * <p/> * Sub-classes devem implementar este método de acordo com suas * necessidades. Isto é especialmente útil quando forem usadas várias * unidades de persistência. * * @return EntityManager */ protected abstract EntityManager getEntityManager(); public void persist(T v) { getEntityManager().persist(v); } public T merge(T v) { return getEntityManager().merge(v); } public T findById(I id) { return (T) getEntityManager().find(entityConcreteClass, id); } public void remove(T c) { getEntityManager().remove(c); } @SuppressWarnings("unchecked") public List<T> getAll() { Query query = getEntityManager().createQuery( "SELECT e FROM " + entityConcreteClass.getName() + " e"); return (List<T>) query.getResultList(); } /** * Cria uma nova instância da entidade. */ public T newInstance() { try { return entityConcreteClass.newInstance(); } catch (InstantiationException e) { throw new RuntimeException("Error creating entity instance", e); } catch (IllegalAccessException e) { throw new RuntimeException("Error creating entity instance", e); } } }
2,502
0.720032
0.720032
88
27.25
25.675531
92
false
false
0
0
0
0
0
0
1.113636
false
false
13
c1f4318de44aafc54e0d34f5893f499d73717873
39,651,138,089,878
2b36691a8c13c08026a6be7ebc8ed78bd3532af4
/app/src/main/java/com/liansu/boduowms/ui/adapter/inHouseStock/InStockHouseReplenishmentItemAdapter.java
ad52472058e2899386452f536e38452bd995234a
[]
no_license
xuxin511/BoduoAndroid
https://github.com/xuxin511/BoduoAndroid
26bc5bc86c018ce55b4c8329562ef315806b2c21
9bc3c1004c16fc761aee8582e8cb8c9ff8ec8ff7
refs/heads/master
2023-04-13T05:24:40.152000
2021-04-22T05:50:49
2021-04-22T05:50:49
285,480,762
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.liansu.boduowms.ui.adapter.inHouseStock; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.liansu.boduowms.R; import com.liansu.boduowms.base.BaseApplication; import com.liansu.boduowms.bean.stock.StockInfo; import com.liansu.boduowms.ui.dialog.MessageBox; import java.util.ArrayList; import java.util.List; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; /** * @desc: 补货适配器 * @param: * @return: * @author: Nietzsche * @time 2020/9/25 15:49 */ public class InStockHouseReplenishmentItemAdapter extends RecyclerView.Adapter<InStockHouseReplenishmentItemAdapter.ViewHolder> implements View.OnClickListener { private Context context; // 运行上下文 private List<StockInfo> mStockList; // 信息集合 private LayoutInflater listContainer; // 视图容器 private RecyclerView mRecyclerView; private List<Boolean> selectedList;//用布尔型的list记录每一行的选中状态 public interface OnItemClickListener {//也可以不在这个activity或者是fragment中来声明接口,可以在项目中单独创建一个interface,就改成static就OK //参数(父组件,当前单击的View,单击的View的位置,数据) void onItemClick(RecyclerView parent, View view, int position, StockInfo data); } public void setRecyclerView(RecyclerView recyclerView) { mRecyclerView = recyclerView; } private OnItemClickListener mOnItemClickListener;//声明一下这个接口 //提供setter方法 public void setOnItemClickListener(OnItemClickListener onItemClickListener) { this.mOnItemClickListener = onItemClickListener; } public InStockHouseReplenishmentItemAdapter(Context context, List<StockInfo> list) { this.context = context; listContainer = LayoutInflater.from(context); // 创建视图容器并设置上下文 notifySelectedList(list); } /** * @desc: 初始化选中集合 * @param: * @return: * @author: Nietzsche * @time 2020/9/27 10:33 */ public void notifySelectedList(List<StockInfo> list) { this.mStockList = list; if (list != null) { int count = list.size(); this.selectedList = new ArrayList<Boolean>(count); for (int i = 0; i < count; i++) { selectedList.add(false);//初始为false,长度和listview一样 } } } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_stock_roll_stock, parent, false); view.setOnClickListener(this);//设置监听器 ViewHolder holder = new ViewHolder(view); return holder; } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { StockInfo info = mStockList.get(position); holder.txt_barcode.setText("条码:" + info.getBarcode()); holder.txt_material_no.setText("料号:" + info.getMaterialno()); holder.txt_batch_no.setText("批次:" + info.getBatchno()); holder.txt_qty.setText("库存数量:" + info.getQty()); holder.txt_material_desc.setText("品名:" + info.getMaterialdesc()); holder.txt_task_qty.setText("库位:" + info.getAreano()); } @Override public long getItemId(int position) { return position; } @Override public int getItemCount() { return mStockList == null ? 0 : mStockList.size(); } @Override public void onClick(View v) { //程序执行到此,会去执行具体实现的onItemClick()方法 if (mOnItemClickListener != null && mRecyclerView != null) { //根据RecyclerView获得当前View的位置 int position = mRecyclerView.getChildAdapterPosition(v); mOnItemClickListener.onItemClick(mRecyclerView, v, position, mStockList.get(position)); } } public class ViewHolder extends RecyclerView.ViewHolder { public TextView txt_barcode; public TextView txt_material_no; public TextView txt_batch_no; public TextView txt_qty; public TextView txt_area_no; public TextView txt_material_desc; public TextView txt_task_qty; public View rootView; public ViewHolder(View itemView) { super(itemView); txt_barcode = (TextView) itemView.findViewById(R.id.txt_barcode); txt_material_no = (TextView) itemView.findViewById(R.id.txt_material_no); txt_batch_no = (TextView) itemView.findViewById(R.id.txt_batch_no); txt_qty = (TextView) itemView.findViewById(R.id.txt_qty); txt_area_no = (TextView) itemView.findViewById(R.id.txt_area_no); txt_material_desc = (TextView) itemView.findViewById(R.id.txt_material_desc); txt_task_qty = (TextView) itemView.findViewById(R.id.txt_task_qty); rootView = itemView; } } @Override public void onAttachedToRecyclerView(RecyclerView recyclerView) { super.onAttachedToRecyclerView(recyclerView); this.mRecyclerView = recyclerView; } @Override public void onDetachedFromRecyclerView(RecyclerView recyclerView) { super.onDetachedFromRecyclerView(recyclerView); this.mRecyclerView = null; } /** * @desc: 只能用于一次性加载的数据,多次更新数据需要用别的方法实现 * @param: * @return: * @author: Nietzsche * @time 2020/9/27 10:40 */ public void setCheckedStatus(View view, int position) { try { if (selectedList.get(position) == false) { selectedList.set(position, true);//如果相应position的记录是未被选中则设置为选中(true) if (view != null) { view.setBackgroundResource(R.color.springgreen); } notifyDataSetChanged(); } else { selectedList.set(position, false);//否则相应position的记录是被选中则设置为未选中(false) if (view != null) { view.setBackgroundResource(R.color.trans); } notifyDataSetChanged(); } } catch (Exception e) { MessageBox.Show(BaseApplication.context, "点击列表出现预期之外的异常:" + e.getMessage()); } } /** * @desc: 单选 只能用于一次性加载的数据,多次更新数据需要用别的方法实现 * @param: * @return: * @author: Nietzsche * @time 2020/9/27 10:40 */ public void setSingleCheckedStatus(View view, int position) { try { notifySelectedList(mStockList); resetItemsBackground(); // for (int i = 0; i < selectedList.size(); i++) { // if (selectedList.get(i) == true) { // selectedList.set(position, false);//将状态全部还原为初始状态(false) // if (view != null) { // view.setBackgroundResource(R.color.trans); // } // } // } selectedList.set(position, true);//将当前item设置为选中(true) if (view != null) { view.setBackgroundResource(R.color.springgreen); } notifyDataSetChanged(); } catch (Exception e) { MessageBox.Show(BaseApplication.context, "点击列表出现预期之外的异常:" + e.getMessage()); } } /** * @desc: 将item重置为无色 * @param: * @return: * @author: Nietzsche * @time 2020/10/12 12:23 */ public void resetItemsBackground() { if (mRecyclerView != null) { for (int i = 0; i < getItemCount(); i++) { InStockHouseReplenishmentItemAdapter.ViewHolder item = (ViewHolder) mRecyclerView.findViewHolderForAdapterPosition(i); if (item!=null){ item.rootView.setBackgroundResource(R.color.trans); } } } } /** * @desc: 获取选中数据 * @param: * @return: * @author: Nietzsche * @time 2020/9/26 16:31 */ public List<StockInfo> getSelectedData() { List<StockInfo> list = new ArrayList<>(); for (int i = 0; i < selectedList.size(); i++) { if (selectedList.get(i) == true) { list.add(mStockList.get(i)); } } return list; } }
UTF-8
Java
8,862
java
InStockHouseReplenishmentItemAdapter.java
Java
[ { "context": " * @desc: 补货适配器\n * @param:\n * @return:\n * @author: Nietzsche\n * @time 2020/9/25 15:49\n */\npublic class InStock", "end": 594, "score": 0.9733213782310486, "start": 585, "tag": "USERNAME", "value": "Nietzsche" }, { "context": "中集合\n * @param:\n * @return:\n * @author: Nietzsche\n * @time 2020/9/27 10:33\n */\n public v", "end": 1942, "score": 0.757235050201416, "start": 1933, "tag": "NAME", "value": "Nietzsche" }, { "context": "法实现\n * @param:\n * @return:\n * @author: Nietzsche\n * @time 2020/9/27 10:40\n */\n public v", "end": 5352, "score": 0.8580442070960999, "start": 5343, "tag": "USERNAME", "value": "Nietzsche" }, { "context": "法实现\n * @param:\n * @return:\n * @author: Nietzsche\n * @time 2020/9/27 10:40\n */\n public v", "end": 6296, "score": 0.9988031387329102, "start": 6287, "tag": "USERNAME", "value": "Nietzsche" }, { "context": "\n * @param:\n * @return:\n * @author: Nietzsche\n * @time 2020/10/12 12:23\n */\n publi", "end": 7306, "score": 0.9988096952438354, "start": 7297, "tag": "USERNAME", "value": "Nietzsche" }, { "context": "中数据\n * @param:\n * @return:\n * @author: Nietzsche\n * @time 2020/9/26 16:31\n */\n public L", "end": 7854, "score": 0.9997531175613403, "start": 7845, "tag": "NAME", "value": "Nietzsche" } ]
null
[]
package com.liansu.boduowms.ui.adapter.inHouseStock; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.liansu.boduowms.R; import com.liansu.boduowms.base.BaseApplication; import com.liansu.boduowms.bean.stock.StockInfo; import com.liansu.boduowms.ui.dialog.MessageBox; import java.util.ArrayList; import java.util.List; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; /** * @desc: 补货适配器 * @param: * @return: * @author: Nietzsche * @time 2020/9/25 15:49 */ public class InStockHouseReplenishmentItemAdapter extends RecyclerView.Adapter<InStockHouseReplenishmentItemAdapter.ViewHolder> implements View.OnClickListener { private Context context; // 运行上下文 private List<StockInfo> mStockList; // 信息集合 private LayoutInflater listContainer; // 视图容器 private RecyclerView mRecyclerView; private List<Boolean> selectedList;//用布尔型的list记录每一行的选中状态 public interface OnItemClickListener {//也可以不在这个activity或者是fragment中来声明接口,可以在项目中单独创建一个interface,就改成static就OK //参数(父组件,当前单击的View,单击的View的位置,数据) void onItemClick(RecyclerView parent, View view, int position, StockInfo data); } public void setRecyclerView(RecyclerView recyclerView) { mRecyclerView = recyclerView; } private OnItemClickListener mOnItemClickListener;//声明一下这个接口 //提供setter方法 public void setOnItemClickListener(OnItemClickListener onItemClickListener) { this.mOnItemClickListener = onItemClickListener; } public InStockHouseReplenishmentItemAdapter(Context context, List<StockInfo> list) { this.context = context; listContainer = LayoutInflater.from(context); // 创建视图容器并设置上下文 notifySelectedList(list); } /** * @desc: 初始化选中集合 * @param: * @return: * @author: Nietzsche * @time 2020/9/27 10:33 */ public void notifySelectedList(List<StockInfo> list) { this.mStockList = list; if (list != null) { int count = list.size(); this.selectedList = new ArrayList<Boolean>(count); for (int i = 0; i < count; i++) { selectedList.add(false);//初始为false,长度和listview一样 } } } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_stock_roll_stock, parent, false); view.setOnClickListener(this);//设置监听器 ViewHolder holder = new ViewHolder(view); return holder; } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { StockInfo info = mStockList.get(position); holder.txt_barcode.setText("条码:" + info.getBarcode()); holder.txt_material_no.setText("料号:" + info.getMaterialno()); holder.txt_batch_no.setText("批次:" + info.getBatchno()); holder.txt_qty.setText("库存数量:" + info.getQty()); holder.txt_material_desc.setText("品名:" + info.getMaterialdesc()); holder.txt_task_qty.setText("库位:" + info.getAreano()); } @Override public long getItemId(int position) { return position; } @Override public int getItemCount() { return mStockList == null ? 0 : mStockList.size(); } @Override public void onClick(View v) { //程序执行到此,会去执行具体实现的onItemClick()方法 if (mOnItemClickListener != null && mRecyclerView != null) { //根据RecyclerView获得当前View的位置 int position = mRecyclerView.getChildAdapterPosition(v); mOnItemClickListener.onItemClick(mRecyclerView, v, position, mStockList.get(position)); } } public class ViewHolder extends RecyclerView.ViewHolder { public TextView txt_barcode; public TextView txt_material_no; public TextView txt_batch_no; public TextView txt_qty; public TextView txt_area_no; public TextView txt_material_desc; public TextView txt_task_qty; public View rootView; public ViewHolder(View itemView) { super(itemView); txt_barcode = (TextView) itemView.findViewById(R.id.txt_barcode); txt_material_no = (TextView) itemView.findViewById(R.id.txt_material_no); txt_batch_no = (TextView) itemView.findViewById(R.id.txt_batch_no); txt_qty = (TextView) itemView.findViewById(R.id.txt_qty); txt_area_no = (TextView) itemView.findViewById(R.id.txt_area_no); txt_material_desc = (TextView) itemView.findViewById(R.id.txt_material_desc); txt_task_qty = (TextView) itemView.findViewById(R.id.txt_task_qty); rootView = itemView; } } @Override public void onAttachedToRecyclerView(RecyclerView recyclerView) { super.onAttachedToRecyclerView(recyclerView); this.mRecyclerView = recyclerView; } @Override public void onDetachedFromRecyclerView(RecyclerView recyclerView) { super.onDetachedFromRecyclerView(recyclerView); this.mRecyclerView = null; } /** * @desc: 只能用于一次性加载的数据,多次更新数据需要用别的方法实现 * @param: * @return: * @author: Nietzsche * @time 2020/9/27 10:40 */ public void setCheckedStatus(View view, int position) { try { if (selectedList.get(position) == false) { selectedList.set(position, true);//如果相应position的记录是未被选中则设置为选中(true) if (view != null) { view.setBackgroundResource(R.color.springgreen); } notifyDataSetChanged(); } else { selectedList.set(position, false);//否则相应position的记录是被选中则设置为未选中(false) if (view != null) { view.setBackgroundResource(R.color.trans); } notifyDataSetChanged(); } } catch (Exception e) { MessageBox.Show(BaseApplication.context, "点击列表出现预期之外的异常:" + e.getMessage()); } } /** * @desc: 单选 只能用于一次性加载的数据,多次更新数据需要用别的方法实现 * @param: * @return: * @author: Nietzsche * @time 2020/9/27 10:40 */ public void setSingleCheckedStatus(View view, int position) { try { notifySelectedList(mStockList); resetItemsBackground(); // for (int i = 0; i < selectedList.size(); i++) { // if (selectedList.get(i) == true) { // selectedList.set(position, false);//将状态全部还原为初始状态(false) // if (view != null) { // view.setBackgroundResource(R.color.trans); // } // } // } selectedList.set(position, true);//将当前item设置为选中(true) if (view != null) { view.setBackgroundResource(R.color.springgreen); } notifyDataSetChanged(); } catch (Exception e) { MessageBox.Show(BaseApplication.context, "点击列表出现预期之外的异常:" + e.getMessage()); } } /** * @desc: 将item重置为无色 * @param: * @return: * @author: Nietzsche * @time 2020/10/12 12:23 */ public void resetItemsBackground() { if (mRecyclerView != null) { for (int i = 0; i < getItemCount(); i++) { InStockHouseReplenishmentItemAdapter.ViewHolder item = (ViewHolder) mRecyclerView.findViewHolderForAdapterPosition(i); if (item!=null){ item.rootView.setBackgroundResource(R.color.trans); } } } } /** * @desc: 获取选中数据 * @param: * @return: * @author: Nietzsche * @time 2020/9/26 16:31 */ public List<StockInfo> getSelectedData() { List<StockInfo> list = new ArrayList<>(); for (int i = 0; i < selectedList.size(); i++) { if (selectedList.get(i) == true) { list.add(mStockList.get(i)); } } return list; } }
8,862
0.611084
0.602295
255
31.12549
28.328188
161
false
false
0
0
0
0
0
0
0.447059
false
false
13
14b14410d026f6d6f8c1a7229b487bedba30ad3b
37,409,165,175,980
be59c0ca127a4f7041758b2709e1327bc71b6e12
/qipai/guajiLogin/src/main/java/com/sy/sanguo/common/util/XmlUtil.java
49cd11c27176533b50c051fab33da81f7a034c41
[]
no_license
Yiwei-TEST/xxqp-server
https://github.com/Yiwei-TEST/xxqp-server
2389dd6b12614b0a9557d59b473f88a3a59620cf
c2c683ce8060c0cbaee86c3ee550e0195e1bb7e4
refs/heads/main
2023-08-14T08:49:37.586000
2021-09-15T03:21:13
2021-09-15T03:21:13
401,583,086
1
4
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sy.sanguo.common.util; import java.io.StringReader; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.dom4j.Element; import org.dom4j.dom.DOMElement; import org.dom4j.io.SAXReader; /** * 依赖包dom4j XML工具类 * * @author wqc * @date 2012-7-23 * @version v1.0 */ public class XmlUtil { private static String ROOT = "request"; private static String LIST = "list"; private XmlUtil() { } public static String fromMap(Map<String, Object> map) { return fromMap(map, null); } /** * Map-XML * * @param map * @return String xml */ public static String fromMap(Map<String, Object> map, String rootName) { Element root = null; if (!StringUtils.isBlank(rootName)) { root = new DOMElement(rootName); } else { root = new DOMElement(ROOT); } for (String k : map.keySet()) { addElement(root, k, map.get(k)); } return root.asXML(); } /** * XML-Map * * @param xml * @return Map<String,Object> */ @SuppressWarnings("unchecked") public static Map<String, Object> toMap(String xml) { Element root; try { root = new SAXReader().read(new StringReader(xml)).getDocument().getRootElement(); } catch (Throwable e) { e.printStackTrace(); return null; } Map<String, Object> map = new HashMap<String, Object>(); Iterator<Element> it = root.elementIterator(); while (it.hasNext()) { Element e = it.next(); addObject(map, e); } return map; } @SuppressWarnings("unchecked") private static void addObject(Map<String, Object> map, Element e) { if (e.getName().trim().equals(LIST)) { addList(map, e.elements()); return; } if (e.elements().size() > 0) { addMap(map, e); return; } String k = e.getName(); String v = e.getTextTrim(); if (k == null) k = "null"; if (v == null) v = ""; map.put(k, v); } @SuppressWarnings("unchecked") private static void addMap(Map<String, Object> map, Element e) { Map<String, Object> m = new HashMap<String, Object>(); Iterator<Element> it = e.elements().iterator(); while (it.hasNext()) { Element element = it.next(); addObject(m, element); } map.put(e.getName(), m); } private static void addList(Map<String, Object> map, Collection<Element> c) { List<Object> list = new ArrayList<Object>(); for (Element element : c) { Map<String, Object> e = new HashMap<String, Object>(); addObject(e, element); list.add(e); } map.put(LIST, list); } @SuppressWarnings("unchecked") private static void addElement(Element root, String key, Object o) { if (o instanceof Map) { try { Map map = (Map) o; addMap(root, key, map); } catch (Throwable e) { e.printStackTrace(); } return; } if (o instanceof List) { try { List list = (List) o; addList(root, key, list); } catch (Throwable e) { e.printStackTrace(); } return; } if (key == null) key = "null"; String v = ""; if (o != null) v = o.toString(); Element ele = new DOMElement(key); ele.addCDATA(v); root.add(ele); } @SuppressWarnings("unchecked") private static void addMap(Element root, String key, Map map) { if (key == null) key = "null"; Element ele = new DOMElement(key); for (Object o : map.keySet()) { addElement(ele, o.toString(), map.get(o)); } root.add(ele); } @SuppressWarnings("unchecked") private static void addList(Element root, String key, List list) { if (key == null) key = "null"; Element ele = new DOMElement(key); for (Object o : list) { addElement(ele, LIST, o); } root.add(ele); } }
UTF-8
Java
3,720
java
XmlUtil.java
Java
[ { "context": "o.SAXReader;\n\n/**\n * 依赖包dom4j XML工具类\n *\n * @author wqc\n * @date 2012-7-23\n * @version v1.0\n */\npublic cl", "end": 397, "score": 0.9995840787887573, "start": 394, "tag": "USERNAME", "value": "wqc" } ]
null
[]
package com.sy.sanguo.common.util; import java.io.StringReader; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.dom4j.Element; import org.dom4j.dom.DOMElement; import org.dom4j.io.SAXReader; /** * 依赖包dom4j XML工具类 * * @author wqc * @date 2012-7-23 * @version v1.0 */ public class XmlUtil { private static String ROOT = "request"; private static String LIST = "list"; private XmlUtil() { } public static String fromMap(Map<String, Object> map) { return fromMap(map, null); } /** * Map-XML * * @param map * @return String xml */ public static String fromMap(Map<String, Object> map, String rootName) { Element root = null; if (!StringUtils.isBlank(rootName)) { root = new DOMElement(rootName); } else { root = new DOMElement(ROOT); } for (String k : map.keySet()) { addElement(root, k, map.get(k)); } return root.asXML(); } /** * XML-Map * * @param xml * @return Map<String,Object> */ @SuppressWarnings("unchecked") public static Map<String, Object> toMap(String xml) { Element root; try { root = new SAXReader().read(new StringReader(xml)).getDocument().getRootElement(); } catch (Throwable e) { e.printStackTrace(); return null; } Map<String, Object> map = new HashMap<String, Object>(); Iterator<Element> it = root.elementIterator(); while (it.hasNext()) { Element e = it.next(); addObject(map, e); } return map; } @SuppressWarnings("unchecked") private static void addObject(Map<String, Object> map, Element e) { if (e.getName().trim().equals(LIST)) { addList(map, e.elements()); return; } if (e.elements().size() > 0) { addMap(map, e); return; } String k = e.getName(); String v = e.getTextTrim(); if (k == null) k = "null"; if (v == null) v = ""; map.put(k, v); } @SuppressWarnings("unchecked") private static void addMap(Map<String, Object> map, Element e) { Map<String, Object> m = new HashMap<String, Object>(); Iterator<Element> it = e.elements().iterator(); while (it.hasNext()) { Element element = it.next(); addObject(m, element); } map.put(e.getName(), m); } private static void addList(Map<String, Object> map, Collection<Element> c) { List<Object> list = new ArrayList<Object>(); for (Element element : c) { Map<String, Object> e = new HashMap<String, Object>(); addObject(e, element); list.add(e); } map.put(LIST, list); } @SuppressWarnings("unchecked") private static void addElement(Element root, String key, Object o) { if (o instanceof Map) { try { Map map = (Map) o; addMap(root, key, map); } catch (Throwable e) { e.printStackTrace(); } return; } if (o instanceof List) { try { List list = (List) o; addList(root, key, list); } catch (Throwable e) { e.printStackTrace(); } return; } if (key == null) key = "null"; String v = ""; if (o != null) v = o.toString(); Element ele = new DOMElement(key); ele.addCDATA(v); root.add(ele); } @SuppressWarnings("unchecked") private static void addMap(Element root, String key, Map map) { if (key == null) key = "null"; Element ele = new DOMElement(key); for (Object o : map.keySet()) { addElement(ele, o.toString(), map.get(o)); } root.add(ele); } @SuppressWarnings("unchecked") private static void addList(Element root, String key, List list) { if (key == null) key = "null"; Element ele = new DOMElement(key); for (Object o : list) { addElement(ele, LIST, o); } root.add(ele); } }
3,720
0.635113
0.631068
170
20.811764
17.971214
85
false
false
0
0
0
0
0
0
2.264706
false
false
13
adac4925b8e7f54faed7996322537a0e0a0964fa
34,557,306,921,143
ca94731101da03c9d577e664aec85884e1c85ef8
/app/src/main/java/com/example/touche/apptest/ActorsFragment/ActorAdapter.java
035ccd3fa810168e9b1e63e9f507428b164d190b
[]
no_license
Niellai/AppTest
https://github.com/Niellai/AppTest
83ad90c43e2d89e183f1a308947de3513f47a7d9
515513d5fe09571fd9b05584ea75f119c5770634
refs/heads/master
2017-12-01T23:43:30.303000
2016-05-29T07:10:46
2016-05-29T07:10:46
59,929,531
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.touche.apptest.ActorsFragment; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.example.touche.apptest.ActorsFragment.Event.SearchResultEvent; import com.example.touche.apptest.Model.ActorModel; import com.example.touche.apptest.R; import com.example.touche.apptest.TopNagviFragment.Event.RemoveFilterEvent; import com.example.touche.apptest.Utilities.FontUtil; import org.greenrobot.eventbus.EventBus; import java.text.DecimalFormat; import java.util.List; import jp.wasabeef.glide.transformations.CropCircleTransformation; /** * Created by himur on 5/22/2016. */ public class ActorAdapter extends ArrayAdapter<ActorModel> { public ActorAdapter(Context context, int resource, List<ActorModel> objects) { super(context, resource, objects); this.context = context; } @Override public View getView(final int position, View convertView, ViewGroup parent) { if (convertView == null) { if (position % 2 == 0) { convertView = inflateDarkView(); } else { convertView = inflateLightView(); } } updateView(convertView, position); convertView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EventBus.getDefault().post(new SearchResultEvent(getItem(position))); } }); FontUtil.applyFontRecursively(context, (ViewGroup) convertView); return convertView; } private View inflateLightView() { View view = LayoutInflater.from(context).inflate(R.layout.actor_item_light, null, false); ImageView actorIV = (ImageView) view.findViewById(R.id.actorIV); TextView firstNameTV = (TextView) view.findViewById(R.id.firstNameTV); TextView lastNameTV = (TextView) view.findViewById(R.id.lastNameTV); TextView actorLocationTV = (TextView) view.findViewById(R.id.actorLocationTV); TextView descriptionTV = (TextView) view.findViewById(R.id.descriptionTV); TextView ratingTV = (TextView) view.findViewById(R.id.popularityTV); ViewHolder viewHolder = new ViewHolder(); viewHolder.setActorIV(actorIV); viewHolder.setFirstNameTV(firstNameTV); viewHolder.setLastNameTV(lastNameTV); viewHolder.setActorLocationTV(actorLocationTV); viewHolder.setDescriptionTV(descriptionTV); viewHolder.setRatingTV(ratingTV); view.setTag(viewHolder); return view; } private View inflateDarkView() { View view = LayoutInflater.from(context).inflate(R.layout.actor_item_dark, null, false); ImageView actorIV = (ImageView) view.findViewById(R.id.actorIV); TextView firstNameTV = (TextView) view.findViewById(R.id.firstNameTV); TextView lastNameTV = (TextView) view.findViewById(R.id.lastNameTV); TextView actorLocationTV = (TextView) view.findViewById(R.id.actorLocationTV); TextView contentTV = (TextView) view.findViewById(R.id.descriptionTV); TextView ratingTV = (TextView) view.findViewById(R.id.popularityTV); ViewHolder viewHolder = new ViewHolder(); viewHolder.setActorIV(actorIV); viewHolder.setFirstNameTV(firstNameTV); viewHolder.setLastNameTV(lastNameTV); viewHolder.setActorLocationTV(actorLocationTV); viewHolder.setDescriptionTV(contentTV); viewHolder.setRatingTV(ratingTV); view.setTag(viewHolder); return view; } private void updateView(View convertView, int position) { ActorModel model = getItem(position); ViewHolder viewHolder = (ViewHolder) convertView.getTag(); convertView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EventBus.getDefault().post(new RemoveFilterEvent()); } }); Glide.with(context) .load(model.getProfile_path()) .bitmapTransform(new CropCircleTransformation(context)) .placeholder(R.drawable.actor_iv_bg) .crossFade() .into(viewHolder.getActorIV()); String[] actorNameArr = model.getName().split(" "); viewHolder.getFirstNameTV().setText(actorNameArr[0]); viewHolder.getLastNameTV().setText(actorNameArr[1]); viewHolder.getActorLocationTV().setText(model.getLocation()); viewHolder.getDescriptionTV().setText(model.getDescription()); DecimalFormat df = new DecimalFormat("#.00"); String popularityStr = df.format(model.getPopularity()); popularityStr = popularityStr.replace(".", ","); viewHolder.getRatingTV().setText(popularityStr); } private Context context; private class ViewHolder { public ImageView getActorIV() { return actorIV; } public void setActorIV(ImageView actorIV) { this.actorIV = actorIV; } public TextView getFirstNameTV() { return firstNameTV; } public void setFirstNameTV(TextView firstNameTV) { this.firstNameTV = firstNameTV; } public TextView getLastNameTV() { return lastNameTV; } public void setLastNameTV(TextView lastNameTV) { this.lastNameTV = lastNameTV; } public TextView getActorLocationTV() { return actorLocationTV; } public void setActorLocationTV(TextView actorLocationTV) { this.actorLocationTV = actorLocationTV; } public TextView getDescriptionTV() { return descriptionTV; } public void setDescriptionTV(TextView descriptionTV) { this.descriptionTV = descriptionTV; } public TextView getRatingTV() { return ratingTV; } public void setRatingTV(TextView ratingTV) { this.ratingTV = ratingTV; } private ImageView actorIV; private TextView firstNameTV; private TextView lastNameTV; private TextView actorLocationTV; private TextView descriptionTV; private TextView ratingTV; } }
UTF-8
Java
6,486
java
ActorAdapter.java
Java
[ { "context": "tions.CropCircleTransformation;\n\n/**\n * Created by himur on 5/22/2016.\n */\npublic class ActorAdapter exten", "end": 795, "score": 0.998940110206604, "start": 790, "tag": "USERNAME", "value": "himur" }, { "context": "torIV(actorIV);\n viewHolder.setFirstNameTV(firstNameTV);\n viewHolder.setLastNameTV(lastNameTV);\n ", "end": 2495, "score": 0.8951267004013062, "start": 2484, "tag": "NAME", "value": "firstNameTV" }, { "context": "TV(firstNameTV);\n viewHolder.setLastNameTV(lastNameTV);\n viewHolder.setActorLocationTV(actorLoca", "end": 2541, "score": 0.8053848743438721, "start": 2531, "tag": "NAME", "value": "lastNameTV" }, { "context": "torIV(actorIV);\n viewHolder.setFirstNameTV(firstNameTV);\n viewHolder.setLastNameTV(lastNameTV);\n ", "end": 3497, "score": 0.8034176826477051, "start": 3486, "tag": "NAME", "value": "firstNameTV" }, { "context": "TV(firstNameTV);\n viewHolder.setLastNameTV(lastNameTV);\n viewHolder.setActorLocationTV(actorLoca", "end": 3543, "score": 0.9308881759643555, "start": 3533, "tag": "NAME", "value": "lastNameTV" } ]
null
[]
package com.example.touche.apptest.ActorsFragment; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.example.touche.apptest.ActorsFragment.Event.SearchResultEvent; import com.example.touche.apptest.Model.ActorModel; import com.example.touche.apptest.R; import com.example.touche.apptest.TopNagviFragment.Event.RemoveFilterEvent; import com.example.touche.apptest.Utilities.FontUtil; import org.greenrobot.eventbus.EventBus; import java.text.DecimalFormat; import java.util.List; import jp.wasabeef.glide.transformations.CropCircleTransformation; /** * Created by himur on 5/22/2016. */ public class ActorAdapter extends ArrayAdapter<ActorModel> { public ActorAdapter(Context context, int resource, List<ActorModel> objects) { super(context, resource, objects); this.context = context; } @Override public View getView(final int position, View convertView, ViewGroup parent) { if (convertView == null) { if (position % 2 == 0) { convertView = inflateDarkView(); } else { convertView = inflateLightView(); } } updateView(convertView, position); convertView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EventBus.getDefault().post(new SearchResultEvent(getItem(position))); } }); FontUtil.applyFontRecursively(context, (ViewGroup) convertView); return convertView; } private View inflateLightView() { View view = LayoutInflater.from(context).inflate(R.layout.actor_item_light, null, false); ImageView actorIV = (ImageView) view.findViewById(R.id.actorIV); TextView firstNameTV = (TextView) view.findViewById(R.id.firstNameTV); TextView lastNameTV = (TextView) view.findViewById(R.id.lastNameTV); TextView actorLocationTV = (TextView) view.findViewById(R.id.actorLocationTV); TextView descriptionTV = (TextView) view.findViewById(R.id.descriptionTV); TextView ratingTV = (TextView) view.findViewById(R.id.popularityTV); ViewHolder viewHolder = new ViewHolder(); viewHolder.setActorIV(actorIV); viewHolder.setFirstNameTV(firstNameTV); viewHolder.setLastNameTV(lastNameTV); viewHolder.setActorLocationTV(actorLocationTV); viewHolder.setDescriptionTV(descriptionTV); viewHolder.setRatingTV(ratingTV); view.setTag(viewHolder); return view; } private View inflateDarkView() { View view = LayoutInflater.from(context).inflate(R.layout.actor_item_dark, null, false); ImageView actorIV = (ImageView) view.findViewById(R.id.actorIV); TextView firstNameTV = (TextView) view.findViewById(R.id.firstNameTV); TextView lastNameTV = (TextView) view.findViewById(R.id.lastNameTV); TextView actorLocationTV = (TextView) view.findViewById(R.id.actorLocationTV); TextView contentTV = (TextView) view.findViewById(R.id.descriptionTV); TextView ratingTV = (TextView) view.findViewById(R.id.popularityTV); ViewHolder viewHolder = new ViewHolder(); viewHolder.setActorIV(actorIV); viewHolder.setFirstNameTV(firstNameTV); viewHolder.setLastNameTV(lastNameTV); viewHolder.setActorLocationTV(actorLocationTV); viewHolder.setDescriptionTV(contentTV); viewHolder.setRatingTV(ratingTV); view.setTag(viewHolder); return view; } private void updateView(View convertView, int position) { ActorModel model = getItem(position); ViewHolder viewHolder = (ViewHolder) convertView.getTag(); convertView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EventBus.getDefault().post(new RemoveFilterEvent()); } }); Glide.with(context) .load(model.getProfile_path()) .bitmapTransform(new CropCircleTransformation(context)) .placeholder(R.drawable.actor_iv_bg) .crossFade() .into(viewHolder.getActorIV()); String[] actorNameArr = model.getName().split(" "); viewHolder.getFirstNameTV().setText(actorNameArr[0]); viewHolder.getLastNameTV().setText(actorNameArr[1]); viewHolder.getActorLocationTV().setText(model.getLocation()); viewHolder.getDescriptionTV().setText(model.getDescription()); DecimalFormat df = new DecimalFormat("#.00"); String popularityStr = df.format(model.getPopularity()); popularityStr = popularityStr.replace(".", ","); viewHolder.getRatingTV().setText(popularityStr); } private Context context; private class ViewHolder { public ImageView getActorIV() { return actorIV; } public void setActorIV(ImageView actorIV) { this.actorIV = actorIV; } public TextView getFirstNameTV() { return firstNameTV; } public void setFirstNameTV(TextView firstNameTV) { this.firstNameTV = firstNameTV; } public TextView getLastNameTV() { return lastNameTV; } public void setLastNameTV(TextView lastNameTV) { this.lastNameTV = lastNameTV; } public TextView getActorLocationTV() { return actorLocationTV; } public void setActorLocationTV(TextView actorLocationTV) { this.actorLocationTV = actorLocationTV; } public TextView getDescriptionTV() { return descriptionTV; } public void setDescriptionTV(TextView descriptionTV) { this.descriptionTV = descriptionTV; } public TextView getRatingTV() { return ratingTV; } public void setRatingTV(TextView ratingTV) { this.ratingTV = ratingTV; } private ImageView actorIV; private TextView firstNameTV; private TextView lastNameTV; private TextView actorLocationTV; private TextView descriptionTV; private TextView ratingTV; } }
6,486
0.661425
0.65942
182
34.637363
25.950298
97
false
false
0
0
0
0
0
0
0.587912
false
false
13
5af75b473e2162486d1a9d1c2565b24447a6cbc8
34,016,141,047,389
c6a638a3341867d134ea6b41ba869684f2569f14
/ReparacionEquipos/src/Entidades/Empleado.java
b78fe082754f0a3bd98ca6c2bffae6cd880acf5e
[]
no_license
icastilloc01/ReparacionEquipos
https://github.com/icastilloc01/ReparacionEquipos
f3cabd5f8ae6d840913ad46e95dcfefe57176188
2d0de4d909af2d4d01b412a23f1ec4a6bfc7c92b
refs/heads/main
2023-05-06T08:30:18.309000
2021-05-28T19:18:00
2021-05-28T19:18:00
314,032,065
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 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 Entidades; import Exception.EmpleadoException; import Main.ReparacionEquipos; import java.io.BufferedReader; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PrintWriter; import java.io.Serializable; import java.util.ArrayList; import java.util.InputMismatchException; import java.util.Scanner; /** * * @author icasc */ public class Empleado implements Serializable { protected long id; //no puede ser menor de 0 protected String nombre; protected String telefono; //debe ser una sucesión de 9 números protected String nif; //debe ser una sucesión de 8 números y 1 letra protected String apellido; protected String direccion; static final long serialVersionUID = 1L; public Empleado() { } public Empleado(long id, String nombre, String teléfono, String nif, String apellido, String direccion) { this.id = id; this.nombre = nombre; this.telefono = teléfono; this.nif = nif; this.apellido = apellido; this.direccion = direccion; } public Empleado(Empleado e) { this.id = e.id; this.nombre = e.nombre; this.telefono = e.telefono; this.nif = e.nif; this.apellido = e.apellido; this.direccion = e.direccion; } public long getId() { return id; } public String getNombre() { return nombre; } public String getTelefono() { return telefono; } public String getNif() { return nif; } public String getApellido() { return apellido; } public String getDireccion() { return direccion; } public void setId(long id) throws EmpleadoException{ if (id <= 0) { this.id = id; } else { throw new EmpleadoException("El id introducido es menor que 1"); } } public void setNombre(String nombre) /*throws EmpleadoException*/{ //if (nombre.length() < 3 && nombre.length() > 25 && Utilidades.isNumeric(nombre)) { this.nombre = nombre; //} else { //throw new EmpleadoException("El nombre introducido contiene números, es menor de 3 o mayor de 25 caracteres"); //} } public void setTelefono(String telefono) { this.telefono = telefono; } public void setNif(String nif) { this.nif = nif; } public void setApellido(String apellido) { this.apellido = apellido; } public void setDireccion(String direccion) { this.direccion = direccion; } public static long nextIdEmpleado() { long ret = 0; for (Empleado e : Utilidades.EMPLEADOS) { if (e.getId() > ret) { ret = e.getId(); } } for (Repartidor r : Utilidades.REPARTIDORES) { if (r.getId() > ret) { ret = r.getId(); } } for (Sustituto s : Utilidades.SUSTITUTOS) { if (s.getId() > ret) { ret = s.getId(); } } for (Detaller s : Utilidades.DETALLERES) { if (s.getId() > ret) { ret = s.getId(); } } return ret + 1; } public static Empleado nuevoEmpleado() { Empleado nuevoEmpleado = new Empleado(); Scanner in = new Scanner(System.in); nuevoEmpleado.id = nextIdEmpleado(); do { System.out.print("Introduzca el nombre del nuevo empleado: "); nuevoEmpleado.nombre = in.nextLine(); if (nuevoEmpleado.nombre.length() < 3 || nuevoEmpleado.nombre.length() > 25 || Utilidades.isNumeric(nuevoEmpleado.nombre)) { System.out.println("El nombre introducido contiene números, es menos de 3 o mayor de 25 caracteres"); } } while (nuevoEmpleado.nombre.length() < 3 || nuevoEmpleado.nombre.length() > 25 || Utilidades.isNumeric(nuevoEmpleado.nombre)); do { System.out.print("Introduzca el teléfono del nuevo empleado: "); nuevoEmpleado.telefono = in.nextLine(); if (nuevoEmpleado.telefono.length() != 9 || !Utilidades.isNumeric(nuevoEmpleado.telefono)) { System.out.println("La cadena introducida para teléfono contiene algún caracter que no es un número o no tiene una longitud de 9 carácteres"); } } while (nuevoEmpleado.telefono.length() != 9 || !Utilidades.isNumeric(nuevoEmpleado.telefono)); do { System.out.print("Introduzca el nif del nuevo empleado: "); nuevoEmpleado.nif = in.nextLine(); if (!Utilidades.validarNIF(nuevoEmpleado.nif)) { System.out.println("La cadena introducida no corresponde con el formato de un nif"); } } while (!Utilidades.validarNIF(nuevoEmpleado.nif)); do { System.out.print("Introduzca el apellido del nuevo empleado: "); nuevoEmpleado.apellido = in.nextLine(); if (nuevoEmpleado.nombre.length() < 3 || nuevoEmpleado.nombre.length() > 25 || Utilidades.isNumeric(nuevoEmpleado.nombre)) { System.out.println("El apellido introducido contiene números, es menos de 3 o mayor de 25 caracteres"); } } while (nuevoEmpleado.apellido.length() < 3 || nuevoEmpleado.apellido.length() > 25 || Utilidades.isNumeric(nuevoEmpleado.apellido)); //do { //System.out.print("Introduzca la direccion del nuevo empleado: "); nuevoEmpleado.direccion = in.nextLine(); //if (nuevoEmpleado.direccion.startsWith("C\\") == false) { //System.out.println("El formato de dirección que ha introducido no es valido,introduzca una dirección que empiece por C\\"); //} //} while (nuevoEmpleado.direccion.startsWith("C\\") == false); return nuevoEmpleado; } public static void verEmpleado(ArrayList<Empleado> empleados) { System.out.println("En el sistema estan registrados los siguientes empleados:"); for (Empleado e : empleados) { System.out.println(e.getId() + ". " + e.getNombre() + ". " + e.getApellido() + ". " + e.getTelefono() + ". " + e.getNif() + ". " + e.getDireccion() + ". (" + e.getClass().getSimpleName() + ")"); } } public static void buscarEmpleado(ArrayList<Empleado> empleados) { ArrayList<Empleado> valores; Scanner in = new Scanner(System.in); valores = new ArrayList<Empleado>(); System.out.println("Pulse 1 para buscar un empleado por el id"); System.out.println("Pulse 2 para buscar un empleado por el nombre"); System.out.println("Pulse 3 para buscar un empleado por el telefono"); System.out.println("Pulse 4 para buscar un empleado por el nif"); System.out.println("Pulse 5 para buscar un empleado por el apellido"); System.out.println("Pulse 6 para buscar un empleado por la direccion"); System.out.println("Pulse 0 para volver"); in.reset(); int opcion = in.nextInt(); try { do { switch (opcion) { case 1: buscarEmpleadoPorId(empleados); ReparacionEquipos.mostrarGestionEmpleados(empleados); break; case 2: System.out.println("Introduzca el nombre del empleado que desea buscar:"); String nombreEmp = in.nextLine(); //linea para que no se salte el nextLine() nombreEmp = in.nextLine(); valores = buscarEmpleadoPorNombre(nombreEmp, empleados); if (valores.size() > 0) { System.out.println("Se han encontrado datos: "); for (Empleado e : valores) { System.out.println(e.getId() + ". " + e.getNombre() + ". " + e.getApellido() + ". " + e.getTelefono() + ". " + e.getNif() + ". " + e.getDireccion() + ". (" + e.getClass().getSimpleName() + ")"); } } else { System.out.println("El empleado con nombre " + nombreEmp + " no se ha encontrado en el sistema."); } System.out.println(""); ReparacionEquipos.mostrarGestionEmpleados(empleados); break; case 3: System.out.println("Introduzca el telefono del empleado que desea buscar:"); String telefonoEmp = in.nextLine(); //linea para que no se salte el nextLine() telefonoEmp = in.nextLine(); valores = buscarEmpleadoPorTelefono(telefonoEmp, empleados); if (valores.size() > 0) { System.out.println("Se han encontrado datos: "); for (Empleado e : valores) { System.out.println(e.getId() + ". " + e.getNombre() + ". " + e.getApellido() + ". " + e.getTelefono() + ". " + e.getNif() + ". " + e.getDireccion() + ". (" + e.getClass().getSimpleName() + ")"); } } else { System.out.println("El empleado con telefono " + telefonoEmp + " no se ha encontrado en el sistema."); } System.out.println(""); ReparacionEquipos.mostrarGestionEmpleados(empleados); break; case 4: System.out.println("Introduzca el NIF del empleado que desea buscar:"); String nifEmp = in.nextLine(); //linea para que no se salte el nextLine() nifEmp = in.nextLine(); valores = buscarEmpleadoPorNif(nifEmp, empleados); if (valores.size() > 0) { System.out.println("Se han encontrado datos: "); for (Empleado e : valores) { System.out.println(e.getId() + ". " + e.getNombre() + ". " + e.getApellido() + ". " + e.getTelefono() + ". " + e.getNif() + ". " + e.getDireccion() + ". (" + e.getClass().getSimpleName() + ")"); } } else { System.out.println("El empleado con NIF " + nifEmp + " no se ha encontrado en el sistema."); } System.out.println(""); ReparacionEquipos.mostrarGestionEmpleados(empleados); break; case 5: System.out.println("Introduzca el apellido del empleado que desea buscar:"); String apellidoEmp = in.nextLine(); //linea para que no se salte el nextLine() apellidoEmp = in.nextLine(); valores = buscarEmpleadoPorApellido(apellidoEmp, empleados); if (valores.size() > 0) { System.out.println("Se han encontrado datos: "); for (Empleado e : valores) { System.out.println(e.getId() + ". " + e.getNombre() + ". " + e.getApellido() + ". " + e.getTelefono() + ". " + e.getNif() + ". " + e.getDireccion() + ". (" + e.getClass().getSimpleName() + ")"); } } else { System.out.println("El empleado con apellido " + apellidoEmp + " no se ha encontrado en el sistema."); } System.out.println(""); ReparacionEquipos.mostrarGestionEmpleados(empleados); break; case 6: System.out.println("Introduzca el direccion del empleado que desea buscar:"); String direccionEmp = in.nextLine(); //linea para que no se salte el nextLine() direccionEmp = in.nextLine(); valores = buscarEmpleadoPorDireccion(direccionEmp, empleados); if (valores.size() > 0) { System.out.println("Se han encontrado datos: "); for (Empleado e : valores) { System.out.println(e.getId() + ". " + e.getNombre() + ". " + e.getApellido() + ". " + e.getTelefono() + ". " + e.getNif() + ". " + e.getDireccion() + ". (" + e.getClass().getSimpleName() + ")"); } } else { System.out.println("El empleado con direccion " + direccionEmp + " no se ha encontrado en el sistema."); } System.out.println(""); ReparacionEquipos.mostrarGestionEmpleados(empleados); break; case 0: ReparacionEquipos.mostrarGestionEmpleados(empleados); break; default: System.out.println("El valor que ha introducido no es un número del 0 al 6"); System.out.println(""); } } while (opcion > 6 || opcion < 0); } catch (InputMismatchException ex) { System.out.println("El caracter introducido no es un número"); System.out.println(""); buscarEmpleado(empleados); } } public static void buscarEmpleadoPorId(ArrayList<Empleado> empleados) { Scanner in = new Scanner(System.in); try { System.out.println("Introduzca el id del empleado que quiere buscar"); in.reset(); int idEmpleado = in.nextInt(); Empleado ret = null; for (Empleado e : empleados) { if (e.getId() == idEmpleado) { ret = e; break; } } if (ret != null) { System.out.println("Se ha encontrado a un empleado"); System.out.print("El empleado encontrado tiene los siguientes datos: "); System.out.println(ret.getId() + ". " + ret.getNombre() + ". " + ret.getApellido() + ". " + ret.getTelefono() + ". " + ret.getNif() + ". " + ret.getDireccion() + ". (" + ret.getClass().getSimpleName() + ")"); } else { System.out.println("Empleado con id " + idEmpleado + " no se ha encontrado en el sistema."); } System.out.println(""); } catch (InputMismatchException ex) { System.out.println("El carácter introducido no es un número, porfavor introduzca un número"); } } public static ArrayList<Empleado> buscarEmpleadoPorNombre(String nombreEmp, ArrayList<Empleado> empleados) { ArrayList<Empleado> ret = new ArrayList<Empleado>(); for (Empleado e : empleados) { if (Utilidades.removeDiacriticalMarks(e.getNombre().toLowerCase()).contains(Utilidades.removeDiacriticalMarks(nombreEmp.toLowerCase()))) { ret.add(e); } if (e.getNombre().toLowerCase().contains(nombreEmp.toLowerCase())) { if (!ret.contains(e)) { ret.add(e); } } } return ret; } public static ArrayList<Empleado> buscarEmpleadoPorTelefono(String telefonoEmp, ArrayList<Empleado> empleados) { ArrayList<Empleado> ret = new ArrayList<Empleado>(); for (Empleado e : empleados) { if (Utilidades.removeDiacriticalMarks(e.getTelefono().toLowerCase()).contains(Utilidades.removeDiacriticalMarks(telefonoEmp.toLowerCase()))) { ret.add(e); } if (e.getTelefono().toLowerCase().contains(telefonoEmp.toLowerCase())) { if (!ret.contains(e)) { ret.add(e); } } } return ret; } public static ArrayList<Empleado> buscarEmpleadoPorNif(String nifEmp, ArrayList<Empleado> empleados) { ArrayList<Empleado> ret = new ArrayList<Empleado>(); for (Empleado e : empleados) { if (Utilidades.removeDiacriticalMarks(e.getNif().toLowerCase()).contains(Utilidades.removeDiacriticalMarks(nifEmp.toLowerCase()))) { ret.add(e); } if (e.getNif().toLowerCase().contains(nifEmp.toLowerCase())) { if (!ret.contains(e)) { ret.add(e); } } } return ret; } public static ArrayList<Empleado> buscarEmpleadoPorApellido(String apellidoEmp, ArrayList<Empleado> empleados) { ArrayList<Empleado> ret = new ArrayList<Empleado>(); for (Empleado e : empleados) { if (Utilidades.removeDiacriticalMarks(e.getApellido().toLowerCase()).contains(Utilidades.removeDiacriticalMarks(apellidoEmp.toLowerCase()))) { ret.add(e); } if (e.getApellido().toLowerCase().contains(apellidoEmp.toLowerCase())) { if (!ret.contains(e)) { ret.add(e); } } } return ret; } public static ArrayList<Empleado> buscarEmpleadoPorDireccion(String direccionEmp, ArrayList<Empleado> empleados) { ArrayList<Empleado> ret = new ArrayList<Empleado>(); for (Empleado e : empleados) { if (Utilidades.removeDiacriticalMarks(e.getDireccion().toLowerCase()).contains(Utilidades.removeDiacriticalMarks(direccionEmp.toLowerCase()))) { ret.add(e); } if (e.getDireccion().toLowerCase().contains(direccionEmp.toLowerCase())) { if (!ret.contains(e)) { ret.add(e); } } } return ret; } /** * Este metodo exporta todos los datos de un objeto de tipo empleado a un * fichero de texto pasado anteriormente mediante un String llamado path * * @param path */ public void exportarObjetoEmpleadoTexto(String path) { File fichero = new File(path); FileWriter escritor = null; PrintWriter buffer = null; try { try { escritor = new FileWriter(fichero, true); buffer = new PrintWriter(escritor); buffer.print(this.data() + "\r\n"); } finally { if (buffer != null) { buffer.close(); } if (escritor != null) { escritor.close(); } } } catch (FileNotFoundException e) { System.out.println("No se ha encontrado el fichero"); } catch (IOException e) { System.out.println("Se ha producido un error en la inserción de los datos"); } catch (Exception e) { System.out.println("Se ha producido un error inesperado intentelo de nuevo"); } } /** * Este metodo exporta todos los datos de una coleccion de objetos de la * clase empleado empleado a un fichero de texto pasado anteriormente * mediante un String llamado path * * @param path */ public static void exportarColeccionDeObjetosEmpleadoTexto(String path) { ArrayList<Empleado> coleccion; coleccion = Empleado.convertir(Utilidades.EMPLEADOS); File fichero = new File(path); FileWriter escritor = null; PrintWriter buffer = null; try { try { escritor = new FileWriter(fichero, true); buffer = new PrintWriter(escritor); for (Empleado e : coleccion) { buffer.print(e.data() + "\n"); } } finally { if (buffer != null) { buffer.close(); } if (escritor != null) { escritor.close(); } } } catch (FileNotFoundException e) { System.out.println("No se ha encontrado el fichero"); } catch (IOException e) { System.out.println("Se ha producido un error en la inserción de los datos"); } catch (Exception e) { System.out.println("Se ha producido un error inesperado intentelo de nuevo"); } } /** * Este metodo exporta todos los datos de un objeto de tipo empleado a un * fichero de bytes pasado anteriormente mediante un String llamado path * * @param path */ public void exportarEmpleadoaArchivoBinario(String path) { try { FileOutputStream fichero = new FileOutputStream(path, true); ObjectOutputStream empleado = new ObjectOutputStream(fichero); empleado.writeObject(this); empleado.flush(); empleado.close(); } catch (FileNotFoundException e) { System.out.println("No se ha encontrado el fichero"); } catch (IOException e) { System.out.println("Se ha producido un error en la inserción de los datos"); } catch (Exception e) { System.out.println("Se ha producido un error inesperado intentelo de nuevo"); } } /** * Este metodo exporta una coleccion de objetos de tipo empleado a un * fichero binario * * @param path */ public static void exportarColeccionEmpleadosaArchivoBinario(String path) { ArrayList<Empleado> coleccion; coleccion = Empleado.convertir(Utilidades.EMPLEADOS); try { FileOutputStream fichero = new FileOutputStream(path, true); ObjectOutputStream escritor = new ObjectOutputStream(fichero); escritor.writeObject(coleccion); escritor.flush(); escritor.close(); } catch (FileNotFoundException e) { System.out.println("No se ha encontrado el fichero"); } catch (IOException e) { System.out.println("Se ha producido un error en la inserción de los datos"); } catch (Exception e) { System.out.println("Se ha producido un error inesperado intentelo de nuevo"); } } /** * Este metodo importa una coleccion de obejtos de tipo empleado desde un * fichero de datos binario * * @param path * @return */ public static ArrayList<Empleado> importarEmpleadoDesdeFicheroBinario(String path) { ArrayList<Empleado> ret = new ArrayList<Empleado>(); FileInputStream lector = null; ObjectInputStream lectorObjeto = null; try { try { lector = new FileInputStream(path); lectorObjeto = new ObjectInputStream(lector); Empleado e; while ((e = (Empleado) lectorObjeto.readObject()) != null) { ret.add(e); lector.skip(4); } } finally { if (lectorObjeto != null) { lectorObjeto.close(); } if (lector != null) { lector.close(); } } } catch (FileNotFoundException e) { System.out.println("No se ha encontrado el fichero"); } catch (EOFException e) { System.out.println("Final de fichero"); } catch (IOException e) { System.out.println("Se ha producido un error en la inserción de los datos"); } catch (ClassNotFoundException e) { System.out.println("No se ha encontrado la clase a la cual haces referencia"); } catch (Exception e) { System.out.println("Se ha producido un error inesperado intentelo de nuevo"); } return ret; } /** * Este metodo importa una coleccion de objetos de tipo empleado desde un * fichero de tecto * * @param path * @return */ public static ArrayList<Empleado> importarEmpleadoDesdeFicheroTexto(String path) { ArrayList<Empleado> ret = new ArrayList<Empleado>(); FileReader inputStream = null; BufferedReader lector = null; try { try { inputStream = new FileReader(path); lector = new BufferedReader(inputStream); Empleado e; while (lector.ready()) { String cadena = lector.readLine(); if (cadena.isEmpty() == false) { String[] parametros = cadena.split("\\|"); e = new Empleado(Integer.valueOf(parametros[0]), parametros[1], parametros[2], parametros[3], parametros[4], parametros[5]); ret.add(e); } } } finally { if (lector != null) { lector.close(); } } } catch (FileNotFoundException e) { System.out.println("No se ha encontrado el fichero"); } catch (EOFException e) { System.out.println("Final de fichero"); } catch (IOException e) { System.out.println("Se ha producido un error en la inserción de los datos"); } catch (Exception e) { System.out.println("Se ha producido un error inesperado intentelo de nuevo"); } return ret; } /** * Este metodo busca un objeto de la coleccion de objetos de un fichero de * texto mediante el id del objeto * * @param path * @return */ public static ArrayList<Empleado> buscarPorIDEnFicheroDeTexto(String path) { ArrayList<Empleado> ret = new ArrayList<Empleado>(); FileReader inputStream = null; BufferedReader lector = null; try { try { inputStream = new FileReader(path); lector = new BufferedReader(inputStream); Empleado e; while (lector.ready()) { String cadena = lector.readLine(); if (cadena.isEmpty() == false) { String[] parametros = cadena.split("\\|"); e = new Empleado(Integer.valueOf(parametros[0]), parametros[1], parametros[2], parametros[3], parametros[4], parametros[5]); ret.add(e); } } Scanner in = new Scanner(System.in); int idBuscar = 0; do { System.out.print("Introduce el id que desea buscar dentro del fichero de texto: "); idBuscar = in.nextInt(); if (idBuscar <= 0) { System.out.println("Debe introducir un valor mayor que cero"); } } while (idBuscar <= 0); for (Empleado em : ret) { if (em.getId() == idBuscar) { System.out.println(em.data()); break; } } } finally { if (lector != null) { lector.close(); } } } catch (InputMismatchException e) { System.out.println("El carácter introducido no es un entero"); } catch (FileNotFoundException e) { System.out.println("No se ha encontrado el fichero"); } catch (EOFException e) { System.out.println("Final de fichero"); } catch (IOException e) { System.out.println("Se ha producido un error en la inserción de los datos"); } catch (Exception e) { System.out.println("Se ha producido un error inesperado intentelo de nuevo"); } return ret; } public static ArrayList<Empleado> convertir(Empleado[] array) { ArrayList<Empleado> ret = new ArrayList<Empleado>(); for (Empleado e : array) { ret.add((Empleado) e); } return ret; } public String data() { return id + "|" + nombre + '|' + telefono + '|' + nif + '|' + apellido + '|' + direccion; } @Override public String toString() { return "Empleado{" + "id=" + id + ", nombre=" + nombre + ", telefono=" + telefono + ", nif=" + nif + ", apellido=" + apellido + ", direccion=" + direccion + '}'; } }
UTF-8
Java
29,200
java
Empleado.java
Java
[ { "context": "tion;\nimport java.util.Scanner;\n\n/**\n *\n * @author icasc\n */\npublic class Empleado implements Serializable", "end": 783, "score": 0.9991026520729065, "start": 778, "tag": "USERNAME", "value": "icasc" } ]
null
[]
/* * 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 Entidades; import Exception.EmpleadoException; import Main.ReparacionEquipos; import java.io.BufferedReader; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PrintWriter; import java.io.Serializable; import java.util.ArrayList; import java.util.InputMismatchException; import java.util.Scanner; /** * * @author icasc */ public class Empleado implements Serializable { protected long id; //no puede ser menor de 0 protected String nombre; protected String telefono; //debe ser una sucesión de 9 números protected String nif; //debe ser una sucesión de 8 números y 1 letra protected String apellido; protected String direccion; static final long serialVersionUID = 1L; public Empleado() { } public Empleado(long id, String nombre, String teléfono, String nif, String apellido, String direccion) { this.id = id; this.nombre = nombre; this.telefono = teléfono; this.nif = nif; this.apellido = apellido; this.direccion = direccion; } public Empleado(Empleado e) { this.id = e.id; this.nombre = e.nombre; this.telefono = e.telefono; this.nif = e.nif; this.apellido = e.apellido; this.direccion = e.direccion; } public long getId() { return id; } public String getNombre() { return nombre; } public String getTelefono() { return telefono; } public String getNif() { return nif; } public String getApellido() { return apellido; } public String getDireccion() { return direccion; } public void setId(long id) throws EmpleadoException{ if (id <= 0) { this.id = id; } else { throw new EmpleadoException("El id introducido es menor que 1"); } } public void setNombre(String nombre) /*throws EmpleadoException*/{ //if (nombre.length() < 3 && nombre.length() > 25 && Utilidades.isNumeric(nombre)) { this.nombre = nombre; //} else { //throw new EmpleadoException("El nombre introducido contiene números, es menor de 3 o mayor de 25 caracteres"); //} } public void setTelefono(String telefono) { this.telefono = telefono; } public void setNif(String nif) { this.nif = nif; } public void setApellido(String apellido) { this.apellido = apellido; } public void setDireccion(String direccion) { this.direccion = direccion; } public static long nextIdEmpleado() { long ret = 0; for (Empleado e : Utilidades.EMPLEADOS) { if (e.getId() > ret) { ret = e.getId(); } } for (Repartidor r : Utilidades.REPARTIDORES) { if (r.getId() > ret) { ret = r.getId(); } } for (Sustituto s : Utilidades.SUSTITUTOS) { if (s.getId() > ret) { ret = s.getId(); } } for (Detaller s : Utilidades.DETALLERES) { if (s.getId() > ret) { ret = s.getId(); } } return ret + 1; } public static Empleado nuevoEmpleado() { Empleado nuevoEmpleado = new Empleado(); Scanner in = new Scanner(System.in); nuevoEmpleado.id = nextIdEmpleado(); do { System.out.print("Introduzca el nombre del nuevo empleado: "); nuevoEmpleado.nombre = in.nextLine(); if (nuevoEmpleado.nombre.length() < 3 || nuevoEmpleado.nombre.length() > 25 || Utilidades.isNumeric(nuevoEmpleado.nombre)) { System.out.println("El nombre introducido contiene números, es menos de 3 o mayor de 25 caracteres"); } } while (nuevoEmpleado.nombre.length() < 3 || nuevoEmpleado.nombre.length() > 25 || Utilidades.isNumeric(nuevoEmpleado.nombre)); do { System.out.print("Introduzca el teléfono del nuevo empleado: "); nuevoEmpleado.telefono = in.nextLine(); if (nuevoEmpleado.telefono.length() != 9 || !Utilidades.isNumeric(nuevoEmpleado.telefono)) { System.out.println("La cadena introducida para teléfono contiene algún caracter que no es un número o no tiene una longitud de 9 carácteres"); } } while (nuevoEmpleado.telefono.length() != 9 || !Utilidades.isNumeric(nuevoEmpleado.telefono)); do { System.out.print("Introduzca el nif del nuevo empleado: "); nuevoEmpleado.nif = in.nextLine(); if (!Utilidades.validarNIF(nuevoEmpleado.nif)) { System.out.println("La cadena introducida no corresponde con el formato de un nif"); } } while (!Utilidades.validarNIF(nuevoEmpleado.nif)); do { System.out.print("Introduzca el apellido del nuevo empleado: "); nuevoEmpleado.apellido = in.nextLine(); if (nuevoEmpleado.nombre.length() < 3 || nuevoEmpleado.nombre.length() > 25 || Utilidades.isNumeric(nuevoEmpleado.nombre)) { System.out.println("El apellido introducido contiene números, es menos de 3 o mayor de 25 caracteres"); } } while (nuevoEmpleado.apellido.length() < 3 || nuevoEmpleado.apellido.length() > 25 || Utilidades.isNumeric(nuevoEmpleado.apellido)); //do { //System.out.print("Introduzca la direccion del nuevo empleado: "); nuevoEmpleado.direccion = in.nextLine(); //if (nuevoEmpleado.direccion.startsWith("C\\") == false) { //System.out.println("El formato de dirección que ha introducido no es valido,introduzca una dirección que empiece por C\\"); //} //} while (nuevoEmpleado.direccion.startsWith("C\\") == false); return nuevoEmpleado; } public static void verEmpleado(ArrayList<Empleado> empleados) { System.out.println("En el sistema estan registrados los siguientes empleados:"); for (Empleado e : empleados) { System.out.println(e.getId() + ". " + e.getNombre() + ". " + e.getApellido() + ". " + e.getTelefono() + ". " + e.getNif() + ". " + e.getDireccion() + ". (" + e.getClass().getSimpleName() + ")"); } } public static void buscarEmpleado(ArrayList<Empleado> empleados) { ArrayList<Empleado> valores; Scanner in = new Scanner(System.in); valores = new ArrayList<Empleado>(); System.out.println("Pulse 1 para buscar un empleado por el id"); System.out.println("Pulse 2 para buscar un empleado por el nombre"); System.out.println("Pulse 3 para buscar un empleado por el telefono"); System.out.println("Pulse 4 para buscar un empleado por el nif"); System.out.println("Pulse 5 para buscar un empleado por el apellido"); System.out.println("Pulse 6 para buscar un empleado por la direccion"); System.out.println("Pulse 0 para volver"); in.reset(); int opcion = in.nextInt(); try { do { switch (opcion) { case 1: buscarEmpleadoPorId(empleados); ReparacionEquipos.mostrarGestionEmpleados(empleados); break; case 2: System.out.println("Introduzca el nombre del empleado que desea buscar:"); String nombreEmp = in.nextLine(); //linea para que no se salte el nextLine() nombreEmp = in.nextLine(); valores = buscarEmpleadoPorNombre(nombreEmp, empleados); if (valores.size() > 0) { System.out.println("Se han encontrado datos: "); for (Empleado e : valores) { System.out.println(e.getId() + ". " + e.getNombre() + ". " + e.getApellido() + ". " + e.getTelefono() + ". " + e.getNif() + ". " + e.getDireccion() + ". (" + e.getClass().getSimpleName() + ")"); } } else { System.out.println("El empleado con nombre " + nombreEmp + " no se ha encontrado en el sistema."); } System.out.println(""); ReparacionEquipos.mostrarGestionEmpleados(empleados); break; case 3: System.out.println("Introduzca el telefono del empleado que desea buscar:"); String telefonoEmp = in.nextLine(); //linea para que no se salte el nextLine() telefonoEmp = in.nextLine(); valores = buscarEmpleadoPorTelefono(telefonoEmp, empleados); if (valores.size() > 0) { System.out.println("Se han encontrado datos: "); for (Empleado e : valores) { System.out.println(e.getId() + ". " + e.getNombre() + ". " + e.getApellido() + ". " + e.getTelefono() + ". " + e.getNif() + ". " + e.getDireccion() + ". (" + e.getClass().getSimpleName() + ")"); } } else { System.out.println("El empleado con telefono " + telefonoEmp + " no se ha encontrado en el sistema."); } System.out.println(""); ReparacionEquipos.mostrarGestionEmpleados(empleados); break; case 4: System.out.println("Introduzca el NIF del empleado que desea buscar:"); String nifEmp = in.nextLine(); //linea para que no se salte el nextLine() nifEmp = in.nextLine(); valores = buscarEmpleadoPorNif(nifEmp, empleados); if (valores.size() > 0) { System.out.println("Se han encontrado datos: "); for (Empleado e : valores) { System.out.println(e.getId() + ". " + e.getNombre() + ". " + e.getApellido() + ". " + e.getTelefono() + ". " + e.getNif() + ". " + e.getDireccion() + ". (" + e.getClass().getSimpleName() + ")"); } } else { System.out.println("El empleado con NIF " + nifEmp + " no se ha encontrado en el sistema."); } System.out.println(""); ReparacionEquipos.mostrarGestionEmpleados(empleados); break; case 5: System.out.println("Introduzca el apellido del empleado que desea buscar:"); String apellidoEmp = in.nextLine(); //linea para que no se salte el nextLine() apellidoEmp = in.nextLine(); valores = buscarEmpleadoPorApellido(apellidoEmp, empleados); if (valores.size() > 0) { System.out.println("Se han encontrado datos: "); for (Empleado e : valores) { System.out.println(e.getId() + ". " + e.getNombre() + ". " + e.getApellido() + ". " + e.getTelefono() + ". " + e.getNif() + ". " + e.getDireccion() + ". (" + e.getClass().getSimpleName() + ")"); } } else { System.out.println("El empleado con apellido " + apellidoEmp + " no se ha encontrado en el sistema."); } System.out.println(""); ReparacionEquipos.mostrarGestionEmpleados(empleados); break; case 6: System.out.println("Introduzca el direccion del empleado que desea buscar:"); String direccionEmp = in.nextLine(); //linea para que no se salte el nextLine() direccionEmp = in.nextLine(); valores = buscarEmpleadoPorDireccion(direccionEmp, empleados); if (valores.size() > 0) { System.out.println("Se han encontrado datos: "); for (Empleado e : valores) { System.out.println(e.getId() + ". " + e.getNombre() + ". " + e.getApellido() + ". " + e.getTelefono() + ". " + e.getNif() + ". " + e.getDireccion() + ". (" + e.getClass().getSimpleName() + ")"); } } else { System.out.println("El empleado con direccion " + direccionEmp + " no se ha encontrado en el sistema."); } System.out.println(""); ReparacionEquipos.mostrarGestionEmpleados(empleados); break; case 0: ReparacionEquipos.mostrarGestionEmpleados(empleados); break; default: System.out.println("El valor que ha introducido no es un número del 0 al 6"); System.out.println(""); } } while (opcion > 6 || opcion < 0); } catch (InputMismatchException ex) { System.out.println("El caracter introducido no es un número"); System.out.println(""); buscarEmpleado(empleados); } } public static void buscarEmpleadoPorId(ArrayList<Empleado> empleados) { Scanner in = new Scanner(System.in); try { System.out.println("Introduzca el id del empleado que quiere buscar"); in.reset(); int idEmpleado = in.nextInt(); Empleado ret = null; for (Empleado e : empleados) { if (e.getId() == idEmpleado) { ret = e; break; } } if (ret != null) { System.out.println("Se ha encontrado a un empleado"); System.out.print("El empleado encontrado tiene los siguientes datos: "); System.out.println(ret.getId() + ". " + ret.getNombre() + ". " + ret.getApellido() + ". " + ret.getTelefono() + ". " + ret.getNif() + ". " + ret.getDireccion() + ". (" + ret.getClass().getSimpleName() + ")"); } else { System.out.println("Empleado con id " + idEmpleado + " no se ha encontrado en el sistema."); } System.out.println(""); } catch (InputMismatchException ex) { System.out.println("El carácter introducido no es un número, porfavor introduzca un número"); } } public static ArrayList<Empleado> buscarEmpleadoPorNombre(String nombreEmp, ArrayList<Empleado> empleados) { ArrayList<Empleado> ret = new ArrayList<Empleado>(); for (Empleado e : empleados) { if (Utilidades.removeDiacriticalMarks(e.getNombre().toLowerCase()).contains(Utilidades.removeDiacriticalMarks(nombreEmp.toLowerCase()))) { ret.add(e); } if (e.getNombre().toLowerCase().contains(nombreEmp.toLowerCase())) { if (!ret.contains(e)) { ret.add(e); } } } return ret; } public static ArrayList<Empleado> buscarEmpleadoPorTelefono(String telefonoEmp, ArrayList<Empleado> empleados) { ArrayList<Empleado> ret = new ArrayList<Empleado>(); for (Empleado e : empleados) { if (Utilidades.removeDiacriticalMarks(e.getTelefono().toLowerCase()).contains(Utilidades.removeDiacriticalMarks(telefonoEmp.toLowerCase()))) { ret.add(e); } if (e.getTelefono().toLowerCase().contains(telefonoEmp.toLowerCase())) { if (!ret.contains(e)) { ret.add(e); } } } return ret; } public static ArrayList<Empleado> buscarEmpleadoPorNif(String nifEmp, ArrayList<Empleado> empleados) { ArrayList<Empleado> ret = new ArrayList<Empleado>(); for (Empleado e : empleados) { if (Utilidades.removeDiacriticalMarks(e.getNif().toLowerCase()).contains(Utilidades.removeDiacriticalMarks(nifEmp.toLowerCase()))) { ret.add(e); } if (e.getNif().toLowerCase().contains(nifEmp.toLowerCase())) { if (!ret.contains(e)) { ret.add(e); } } } return ret; } public static ArrayList<Empleado> buscarEmpleadoPorApellido(String apellidoEmp, ArrayList<Empleado> empleados) { ArrayList<Empleado> ret = new ArrayList<Empleado>(); for (Empleado e : empleados) { if (Utilidades.removeDiacriticalMarks(e.getApellido().toLowerCase()).contains(Utilidades.removeDiacriticalMarks(apellidoEmp.toLowerCase()))) { ret.add(e); } if (e.getApellido().toLowerCase().contains(apellidoEmp.toLowerCase())) { if (!ret.contains(e)) { ret.add(e); } } } return ret; } public static ArrayList<Empleado> buscarEmpleadoPorDireccion(String direccionEmp, ArrayList<Empleado> empleados) { ArrayList<Empleado> ret = new ArrayList<Empleado>(); for (Empleado e : empleados) { if (Utilidades.removeDiacriticalMarks(e.getDireccion().toLowerCase()).contains(Utilidades.removeDiacriticalMarks(direccionEmp.toLowerCase()))) { ret.add(e); } if (e.getDireccion().toLowerCase().contains(direccionEmp.toLowerCase())) { if (!ret.contains(e)) { ret.add(e); } } } return ret; } /** * Este metodo exporta todos los datos de un objeto de tipo empleado a un * fichero de texto pasado anteriormente mediante un String llamado path * * @param path */ public void exportarObjetoEmpleadoTexto(String path) { File fichero = new File(path); FileWriter escritor = null; PrintWriter buffer = null; try { try { escritor = new FileWriter(fichero, true); buffer = new PrintWriter(escritor); buffer.print(this.data() + "\r\n"); } finally { if (buffer != null) { buffer.close(); } if (escritor != null) { escritor.close(); } } } catch (FileNotFoundException e) { System.out.println("No se ha encontrado el fichero"); } catch (IOException e) { System.out.println("Se ha producido un error en la inserción de los datos"); } catch (Exception e) { System.out.println("Se ha producido un error inesperado intentelo de nuevo"); } } /** * Este metodo exporta todos los datos de una coleccion de objetos de la * clase empleado empleado a un fichero de texto pasado anteriormente * mediante un String llamado path * * @param path */ public static void exportarColeccionDeObjetosEmpleadoTexto(String path) { ArrayList<Empleado> coleccion; coleccion = Empleado.convertir(Utilidades.EMPLEADOS); File fichero = new File(path); FileWriter escritor = null; PrintWriter buffer = null; try { try { escritor = new FileWriter(fichero, true); buffer = new PrintWriter(escritor); for (Empleado e : coleccion) { buffer.print(e.data() + "\n"); } } finally { if (buffer != null) { buffer.close(); } if (escritor != null) { escritor.close(); } } } catch (FileNotFoundException e) { System.out.println("No se ha encontrado el fichero"); } catch (IOException e) { System.out.println("Se ha producido un error en la inserción de los datos"); } catch (Exception e) { System.out.println("Se ha producido un error inesperado intentelo de nuevo"); } } /** * Este metodo exporta todos los datos de un objeto de tipo empleado a un * fichero de bytes pasado anteriormente mediante un String llamado path * * @param path */ public void exportarEmpleadoaArchivoBinario(String path) { try { FileOutputStream fichero = new FileOutputStream(path, true); ObjectOutputStream empleado = new ObjectOutputStream(fichero); empleado.writeObject(this); empleado.flush(); empleado.close(); } catch (FileNotFoundException e) { System.out.println("No se ha encontrado el fichero"); } catch (IOException e) { System.out.println("Se ha producido un error en la inserción de los datos"); } catch (Exception e) { System.out.println("Se ha producido un error inesperado intentelo de nuevo"); } } /** * Este metodo exporta una coleccion de objetos de tipo empleado a un * fichero binario * * @param path */ public static void exportarColeccionEmpleadosaArchivoBinario(String path) { ArrayList<Empleado> coleccion; coleccion = Empleado.convertir(Utilidades.EMPLEADOS); try { FileOutputStream fichero = new FileOutputStream(path, true); ObjectOutputStream escritor = new ObjectOutputStream(fichero); escritor.writeObject(coleccion); escritor.flush(); escritor.close(); } catch (FileNotFoundException e) { System.out.println("No se ha encontrado el fichero"); } catch (IOException e) { System.out.println("Se ha producido un error en la inserción de los datos"); } catch (Exception e) { System.out.println("Se ha producido un error inesperado intentelo de nuevo"); } } /** * Este metodo importa una coleccion de obejtos de tipo empleado desde un * fichero de datos binario * * @param path * @return */ public static ArrayList<Empleado> importarEmpleadoDesdeFicheroBinario(String path) { ArrayList<Empleado> ret = new ArrayList<Empleado>(); FileInputStream lector = null; ObjectInputStream lectorObjeto = null; try { try { lector = new FileInputStream(path); lectorObjeto = new ObjectInputStream(lector); Empleado e; while ((e = (Empleado) lectorObjeto.readObject()) != null) { ret.add(e); lector.skip(4); } } finally { if (lectorObjeto != null) { lectorObjeto.close(); } if (lector != null) { lector.close(); } } } catch (FileNotFoundException e) { System.out.println("No se ha encontrado el fichero"); } catch (EOFException e) { System.out.println("Final de fichero"); } catch (IOException e) { System.out.println("Se ha producido un error en la inserción de los datos"); } catch (ClassNotFoundException e) { System.out.println("No se ha encontrado la clase a la cual haces referencia"); } catch (Exception e) { System.out.println("Se ha producido un error inesperado intentelo de nuevo"); } return ret; } /** * Este metodo importa una coleccion de objetos de tipo empleado desde un * fichero de tecto * * @param path * @return */ public static ArrayList<Empleado> importarEmpleadoDesdeFicheroTexto(String path) { ArrayList<Empleado> ret = new ArrayList<Empleado>(); FileReader inputStream = null; BufferedReader lector = null; try { try { inputStream = new FileReader(path); lector = new BufferedReader(inputStream); Empleado e; while (lector.ready()) { String cadena = lector.readLine(); if (cadena.isEmpty() == false) { String[] parametros = cadena.split("\\|"); e = new Empleado(Integer.valueOf(parametros[0]), parametros[1], parametros[2], parametros[3], parametros[4], parametros[5]); ret.add(e); } } } finally { if (lector != null) { lector.close(); } } } catch (FileNotFoundException e) { System.out.println("No se ha encontrado el fichero"); } catch (EOFException e) { System.out.println("Final de fichero"); } catch (IOException e) { System.out.println("Se ha producido un error en la inserción de los datos"); } catch (Exception e) { System.out.println("Se ha producido un error inesperado intentelo de nuevo"); } return ret; } /** * Este metodo busca un objeto de la coleccion de objetos de un fichero de * texto mediante el id del objeto * * @param path * @return */ public static ArrayList<Empleado> buscarPorIDEnFicheroDeTexto(String path) { ArrayList<Empleado> ret = new ArrayList<Empleado>(); FileReader inputStream = null; BufferedReader lector = null; try { try { inputStream = new FileReader(path); lector = new BufferedReader(inputStream); Empleado e; while (lector.ready()) { String cadena = lector.readLine(); if (cadena.isEmpty() == false) { String[] parametros = cadena.split("\\|"); e = new Empleado(Integer.valueOf(parametros[0]), parametros[1], parametros[2], parametros[3], parametros[4], parametros[5]); ret.add(e); } } Scanner in = new Scanner(System.in); int idBuscar = 0; do { System.out.print("Introduce el id que desea buscar dentro del fichero de texto: "); idBuscar = in.nextInt(); if (idBuscar <= 0) { System.out.println("Debe introducir un valor mayor que cero"); } } while (idBuscar <= 0); for (Empleado em : ret) { if (em.getId() == idBuscar) { System.out.println(em.data()); break; } } } finally { if (lector != null) { lector.close(); } } } catch (InputMismatchException e) { System.out.println("El carácter introducido no es un entero"); } catch (FileNotFoundException e) { System.out.println("No se ha encontrado el fichero"); } catch (EOFException e) { System.out.println("Final de fichero"); } catch (IOException e) { System.out.println("Se ha producido un error en la inserción de los datos"); } catch (Exception e) { System.out.println("Se ha producido un error inesperado intentelo de nuevo"); } return ret; } public static ArrayList<Empleado> convertir(Empleado[] array) { ArrayList<Empleado> ret = new ArrayList<Empleado>(); for (Empleado e : array) { ret.add((Empleado) e); } return ret; } public String data() { return id + "|" + nombre + '|' + telefono + '|' + nif + '|' + apellido + '|' + direccion; } @Override public String toString() { return "Empleado{" + "id=" + id + ", nombre=" + nombre + ", telefono=" + telefono + ", nif=" + nif + ", apellido=" + apellido + ", direccion=" + direccion + '}'; } }
29,200
0.535086
0.532515
682
41.772728
37.347614
226
false
false
0
0
0
0
0
0
0.535191
false
false
13
49e8a4071820872acf3417c72c681ea919e0488f
39,376,260,207,613
818311c7481aef22bad9e2e571139f4ef06f901f
/src/com/example/twothree/InformActivity.java
52824477b93b8e7e359cdc84629c56b3b76486fd
[]
no_license
naheas/testnn
https://github.com/naheas/testnn
8af479ba0682e0bc9f110e75c9f8cc54f01213c9
e2df13d0b1d3b28125b03dd73a1a1b3cbbd26eed
refs/heads/master
2020-12-24T18:03:25.004000
2013-07-31T07:21:48
2013-07-31T07:21:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.twothree; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.widget.TextView; public class InformActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_inform); Intent myintent = getIntent(); String nameStr = myintent.getExtras().getString("name"); String manStr = myintent.getExtras().getString("man"); String womanStr = myintent.getExtras().getString("woman"); String placeStr = myintent.getExtras().getString("place"); ((TextView)findViewById(R.id.textGrName)).setText(nameStr); ((TextView)findViewById(R.id.textMan)).setText(manStr); ((TextView)findViewById(R.id.textWoman)).setText(womanStr); ((TextView)findViewById(R.id.textPlace)).setText(placeStr); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.inform, menu); return true; } }
UTF-8
Java
1,103
java
InformActivity.java
Java
[]
null
[]
package com.example.twothree; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.widget.TextView; public class InformActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_inform); Intent myintent = getIntent(); String nameStr = myintent.getExtras().getString("name"); String manStr = myintent.getExtras().getString("man"); String womanStr = myintent.getExtras().getString("woman"); String placeStr = myintent.getExtras().getString("place"); ((TextView)findViewById(R.id.textGrName)).setText(nameStr); ((TextView)findViewById(R.id.textMan)).setText(manStr); ((TextView)findViewById(R.id.textWoman)).setText(womanStr); ((TextView)findViewById(R.id.textPlace)).setText(placeStr); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.inform, menu); return true; } }
1,103
0.755213
0.755213
36
29.638889
24.143269
74
false
false
0
0
0
0
0
0
1.638889
false
false
13
79c95e5e54ebcce8f68a70a473704fefb0b81655
37,134,287,278,395
5099edffd3fea2bcb310c5de94d05f4bd5780975
/src/com/job/ic/nlp/services/Stemmer.java
722528adaf3e7b55629bb3c3f0e7e47504a74e0f
[]
no_license
b4lmung/AFSCrawler
https://github.com/b4lmung/AFSCrawler
1d6e6f553210fc614d05ce6d4414ae59db746ff7
5935e8423c93a97b0ae027667ee5edaa66019c2d
refs/heads/master
2021-09-09T15:26:50.835000
2018-03-17T12:56:53
2018-03-17T12:58:32
111,373,784
4
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.job.ic.nlp.services; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.util.Version; import com.job.ic.crawlers.models.CrawlerConfig; import com.job.ic.utils.FileUtils; public class Stemmer { private static HashSet<String> stopword = new HashSet<>(); static { InputStream is = Stemmer.class.getResourceAsStream("/resources/classifiers/stopword.txt"); String[] lines = FileUtils.readStream(is); for (String s : lines) { stopword.add(s); } } public static String stem(String text) { if (!CrawlerConfig.getConfig().getTargetLang().equals("en")) return text; text = text.toLowerCase(); StringBuffer result = new StringBuffer(); if (text != null && text.trim().length() > 0) { StringReader tReader = new StringReader(text); Analyzer analyzer; analyzer = new StandardAnalyzer(Version.LUCENE_35, stopword); TokenStream tStream = analyzer.tokenStream("contents", tReader); CharTermAttribute term = tStream.addAttribute(CharTermAttribute.class); try { while (tStream.incrementToken()) { result.append(term.toString()); result.append(" "); } } catch (IOException ioe) { System.out.println("Error: " + ioe.getMessage()); } } // If, for some reason, the stemming did not happen, return the original // text if (result.length() == 0) result.append(text); return result.toString().trim(); } public static void main(String[] args) { String[] s = new String[5]; s[0] = "Banking on banks to raise the interest rate"; s[1] = "Jogging along the river bank to look at the sailboats"; s[2] = "Jogging to the bank to look at the interest rate"; s[3] = "BuzzerBeating shot banked in!"; s[4] = "Scenic outlooks on the bank of the PotomacRiver"; HashSet<String> set = new HashSet<>(); String[] tmp; for (String str : s) { System.out.println(Stemmer.stem(str)); tmp = Stemmer.stem(str).split(" "); set.addAll(Arrays.asList(tmp)); } ArrayList<String> output = new ArrayList<>(); for (String str : set) output.add(str); Collections.sort(output, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } }); for (String str : output) System.out.println(str); // String target = "D:/current-research/page-classifier/sampling/"; // non // String[] tmp; // BufferedWriter bw; // for (File i : new File(target + "non").listFiles()) { // // tmp = FileUtils.readFile(i.getAbsolutePath()); // try { // bw = FileUtils.getBufferedFileWriter(i.getAbsolutePath()); // // for (String s : tmp) { // bw.write(s.concat("\n")); // } // bw.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // String s = Stemmer.stem("walking"); // System.out.println(s); } }
UTF-8
Java
3,392
java
Stemmer.java
Java
[]
null
[]
package com.job.ic.nlp.services; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.util.Version; import com.job.ic.crawlers.models.CrawlerConfig; import com.job.ic.utils.FileUtils; public class Stemmer { private static HashSet<String> stopword = new HashSet<>(); static { InputStream is = Stemmer.class.getResourceAsStream("/resources/classifiers/stopword.txt"); String[] lines = FileUtils.readStream(is); for (String s : lines) { stopword.add(s); } } public static String stem(String text) { if (!CrawlerConfig.getConfig().getTargetLang().equals("en")) return text; text = text.toLowerCase(); StringBuffer result = new StringBuffer(); if (text != null && text.trim().length() > 0) { StringReader tReader = new StringReader(text); Analyzer analyzer; analyzer = new StandardAnalyzer(Version.LUCENE_35, stopword); TokenStream tStream = analyzer.tokenStream("contents", tReader); CharTermAttribute term = tStream.addAttribute(CharTermAttribute.class); try { while (tStream.incrementToken()) { result.append(term.toString()); result.append(" "); } } catch (IOException ioe) { System.out.println("Error: " + ioe.getMessage()); } } // If, for some reason, the stemming did not happen, return the original // text if (result.length() == 0) result.append(text); return result.toString().trim(); } public static void main(String[] args) { String[] s = new String[5]; s[0] = "Banking on banks to raise the interest rate"; s[1] = "Jogging along the river bank to look at the sailboats"; s[2] = "Jogging to the bank to look at the interest rate"; s[3] = "BuzzerBeating shot banked in!"; s[4] = "Scenic outlooks on the bank of the PotomacRiver"; HashSet<String> set = new HashSet<>(); String[] tmp; for (String str : s) { System.out.println(Stemmer.stem(str)); tmp = Stemmer.stem(str).split(" "); set.addAll(Arrays.asList(tmp)); } ArrayList<String> output = new ArrayList<>(); for (String str : set) output.add(str); Collections.sort(output, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } }); for (String str : output) System.out.println(str); // String target = "D:/current-research/page-classifier/sampling/"; // non // String[] tmp; // BufferedWriter bw; // for (File i : new File(target + "non").listFiles()) { // // tmp = FileUtils.readFile(i.getAbsolutePath()); // try { // bw = FileUtils.getBufferedFileWriter(i.getAbsolutePath()); // // for (String s : tmp) { // bw.write(s.concat("\n")); // } // bw.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // String s = Stemmer.stem("walking"); // System.out.println(s); } }
3,392
0.655366
0.651238
120
26.283333
22.12208
92
false
false
0
0
0
0
0
0
2.133333
false
false
13
96075b08978c34decb463cc526010078f019e1f7
33,895,881,953,276
e8e4984bbc1cd34b184ca32376d7a705ef1f3126
/oreilly-spring-security-rest-apis/src/test/java/io/jzheaux/springsecurity/goals/Module3_Tests.java
f77e38aba1a17dd408bce519d57419aef1a7a4e7
[ "Apache-2.0" ]
permissive
dattadiptayandev/current-courses
https://github.com/dattadiptayandev/current-courses
0ee750e0ab1c2d81f054a4ecc4ba8612151501ba
b5b4061c6b843f233649373d5c3337ebaefc903b
refs/heads/master
2021-06-15T12:52:23.950000
2021-03-20T14:33:03
2021-03-20T14:33:03
174,764,710
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package io.jzheaux.springsecurity.goals; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrint; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.oauth2.jwt.BadJwtException; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.JwtDecoder; import org.springframework.security.oauth2.jwt.NimbusJwtDecoder; import org.springframework.security.oauth2.server.resource.introspection.NimbusOpaqueTokenIntrospector; import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector; import org.springframework.security.web.FilterChainProxy; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.filter.CorsFilter; import javax.servlet.Filter; import java.util.List; import java.util.UUID; import static io.jzheaux.springsecurity.goals.ReflectionSupport.annotation; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options; @RunWith(SpringRunner.class) @AutoConfigureMockMvc(print= MockMvcPrint.NONE) @SpringBootTest public class Module3_Tests { @Autowired MockMvc mvc; @Autowired(required = false) FilterChainProxy springSecurityFilterChain; @Autowired(required = false) CorsConfigurationSource cors; @Autowired(required = false) Jwt jwt; @Autowired(required = false) OpaqueTokenIntrospector introspector; @Before public void setup() { assertNotNull( "Module 1: Could not find the Spring Security Filter Chain in the application context;" + "make sure that you complete the earlier modules before starting this one", this.springSecurityFilterChain); } @TestConfiguration static class TestConfig { @ConditionalOnProperty("spring.security.oauth2.resourceserver.jwt.issuer-uri") @Bean JwtDecoder jwtDecoder() { return NimbusJwtDecoder .withJwkSetUri("https://idp.example.org/jwks") .build(); } @ConditionalOnProperty("spring.security.oauth2.resourceserver.opaquetoken.introspection-uri") @Bean JwtDecoder interrim() { return token -> { throw new BadJwtException("bad jwt"); }; } @ConditionalOnProperty("spring.security.oauth2.resourceserver.opaquetoken.introspection-uri") @ConditionalOnMissingBean @Bean OpaqueTokenIntrospector introspector(OAuth2ResourceServerProperties properties) { return new NimbusOpaqueTokenIntrospector( properties.getOpaquetoken().getIntrospectionUri(), properties.getOpaquetoken().getClientId(), properties.getOpaquetoken().getClientSecret()); } } @Test public void task_1() throws Exception { // cors() CorsFilter filter = getFilter(CorsFilter.class); assertNotNull( "Task 2: It doesn't appear that `cors()` is being called on the `HttpSecurity` object. If it is, make " + "sure that `GoalsApplication` is extending `WebSecurityConfigurerAdapter` and is overriding `configure(HttpSecurity http)`", filter); CorsConfiguration configuration = this.cors.getCorsConfiguration (new MockHttpServletRequest("GET", "/" + UUID.randomUUID())); if (this.jwt == null && this.introspector == null) { // Compatibility with Module 6, which shuts this field off MockHttpServletRequest request = new MockHttpServletRequest("GET", "/goals"); assertTrue("Task 1: So that HTTP Basic works in the browser for this request, set the `allowCredentials` property to `\"true\"`", configuration.getAllowCredentials()); } assertNotNull( "Task 1: Make sure that you've added a mapping for all endpoints by calling `addMapping(\"/**\")`'", configuration); assertEquals( "Task 1: Make sure that globally you are only allowing the `http://localhost:8081` origin", 1, configuration.getAllowedOrigins().size()); assertEquals( "Task 1: Make sure that globally you are only allowing the `http://localhost:8081` origin", "http://localhost:8081", configuration.getAllowedOrigins().get(0)); MvcResult result = this.mvc.perform(options("/goals") .header("Access-Control-Request-Method", "GET") .header("Access-Control-Allow-Credentials", "true") .header("Origin", "http://localhost:8081")) .andReturn(); if (this.jwt == null && this.introspector == null) { // Compatibility with Module 6, which shuts this field off assertEquals( "Task 1: Tried to do an `OPTIONS` pre-flight request from `http://localhost:8081` for `GET /goals` failed.", "true", result.getResponse().getHeader("Access-Control-Allow-Credentials")); } } @Test public void task_2() throws Exception { task_1(); // csrf CorsConfiguration configuration = this.cors.getCorsConfiguration (new MockHttpServletRequest("GET", "/" + UUID.randomUUID())); assertTrue( "Task 2: Make sure that you are both allowing and exposing the X-CSRF-TOKEN header", configuration.getAllowedHeaders().contains("X-CSRF-TOKEN")); assertTrue( "Task 2: Make sure that you are both allowing and exposing the X-CSRF-TOKEN header", configuration.getExposedHeaders().contains("X-CSRF-TOKEN")); } private <T extends Filter> T getFilter(Class<T> filterClass) { List<Filter> filters = this.springSecurityFilterChain.getFilters("/goals"); for (Filter filter : filters) { if (filter.getClass() == filterClass) { return (T) filter; } } return null; } }
UTF-8
Java
7,278
java
Module3_Tests.java
Java
[]
null
[]
package io.jzheaux.springsecurity.goals; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrint; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.oauth2.jwt.BadJwtException; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.JwtDecoder; import org.springframework.security.oauth2.jwt.NimbusJwtDecoder; import org.springframework.security.oauth2.server.resource.introspection.NimbusOpaqueTokenIntrospector; import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector; import org.springframework.security.web.FilterChainProxy; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.filter.CorsFilter; import javax.servlet.Filter; import java.util.List; import java.util.UUID; import static io.jzheaux.springsecurity.goals.ReflectionSupport.annotation; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options; @RunWith(SpringRunner.class) @AutoConfigureMockMvc(print= MockMvcPrint.NONE) @SpringBootTest public class Module3_Tests { @Autowired MockMvc mvc; @Autowired(required = false) FilterChainProxy springSecurityFilterChain; @Autowired(required = false) CorsConfigurationSource cors; @Autowired(required = false) Jwt jwt; @Autowired(required = false) OpaqueTokenIntrospector introspector; @Before public void setup() { assertNotNull( "Module 1: Could not find the Spring Security Filter Chain in the application context;" + "make sure that you complete the earlier modules before starting this one", this.springSecurityFilterChain); } @TestConfiguration static class TestConfig { @ConditionalOnProperty("spring.security.oauth2.resourceserver.jwt.issuer-uri") @Bean JwtDecoder jwtDecoder() { return NimbusJwtDecoder .withJwkSetUri("https://idp.example.org/jwks") .build(); } @ConditionalOnProperty("spring.security.oauth2.resourceserver.opaquetoken.introspection-uri") @Bean JwtDecoder interrim() { return token -> { throw new BadJwtException("bad jwt"); }; } @ConditionalOnProperty("spring.security.oauth2.resourceserver.opaquetoken.introspection-uri") @ConditionalOnMissingBean @Bean OpaqueTokenIntrospector introspector(OAuth2ResourceServerProperties properties) { return new NimbusOpaqueTokenIntrospector( properties.getOpaquetoken().getIntrospectionUri(), properties.getOpaquetoken().getClientId(), properties.getOpaquetoken().getClientSecret()); } } @Test public void task_1() throws Exception { // cors() CorsFilter filter = getFilter(CorsFilter.class); assertNotNull( "Task 2: It doesn't appear that `cors()` is being called on the `HttpSecurity` object. If it is, make " + "sure that `GoalsApplication` is extending `WebSecurityConfigurerAdapter` and is overriding `configure(HttpSecurity http)`", filter); CorsConfiguration configuration = this.cors.getCorsConfiguration (new MockHttpServletRequest("GET", "/" + UUID.randomUUID())); if (this.jwt == null && this.introspector == null) { // Compatibility with Module 6, which shuts this field off MockHttpServletRequest request = new MockHttpServletRequest("GET", "/goals"); assertTrue("Task 1: So that HTTP Basic works in the browser for this request, set the `allowCredentials` property to `\"true\"`", configuration.getAllowCredentials()); } assertNotNull( "Task 1: Make sure that you've added a mapping for all endpoints by calling `addMapping(\"/**\")`'", configuration); assertEquals( "Task 1: Make sure that globally you are only allowing the `http://localhost:8081` origin", 1, configuration.getAllowedOrigins().size()); assertEquals( "Task 1: Make sure that globally you are only allowing the `http://localhost:8081` origin", "http://localhost:8081", configuration.getAllowedOrigins().get(0)); MvcResult result = this.mvc.perform(options("/goals") .header("Access-Control-Request-Method", "GET") .header("Access-Control-Allow-Credentials", "true") .header("Origin", "http://localhost:8081")) .andReturn(); if (this.jwt == null && this.introspector == null) { // Compatibility with Module 6, which shuts this field off assertEquals( "Task 1: Tried to do an `OPTIONS` pre-flight request from `http://localhost:8081` for `GET /goals` failed.", "true", result.getResponse().getHeader("Access-Control-Allow-Credentials")); } } @Test public void task_2() throws Exception { task_1(); // csrf CorsConfiguration configuration = this.cors.getCorsConfiguration (new MockHttpServletRequest("GET", "/" + UUID.randomUUID())); assertTrue( "Task 2: Make sure that you are both allowing and exposing the X-CSRF-TOKEN header", configuration.getAllowedHeaders().contains("X-CSRF-TOKEN")); assertTrue( "Task 2: Make sure that you are both allowing and exposing the X-CSRF-TOKEN header", configuration.getExposedHeaders().contains("X-CSRF-TOKEN")); } private <T extends Filter> T getFilter(Class<T> filterClass) { List<Filter> filters = this.springSecurityFilterChain.getFilters("/goals"); for (Filter filter : filters) { if (filter.getClass() == filterClass) { return (T) filter; } } return null; } }
7,278
0.688239
0.681369
167
42.580837
35.513737
148
false
false
0
0
0
0
0
0
0.532934
false
false
13