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
list
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
list
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
e8cda01fd56c4e9b3db659997d1c4d45e5088025
33,397,665,764,170
610820db3b38101ccecfb809812621b25c164ff9
/SEM-V-Java/Extras/InterfacePackageTest.java
5d480eb0c174c7a338f08148663b017c8a5b50fe
[ "MIT" ]
permissive
AnkitApurv/BCA
https://github.com/AnkitApurv/BCA
5d0532dcd3abf8f5ea3f2a0c097e99ca67a47b6b
9a7715e098de7029813fd06d3ee7e40a0d31f6c4
refs/heads/master
2021-01-13T00:53:19.783000
2020-03-23T17:43:49
2020-03-23T17:43:49
44,240,585
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import pac1.*; public class InterfacePackageTest implements Pack1 { public int display(int num) { return num * a1 + a2; } public static void main(String[] args) { int n = 100; InterfacePackageTest obj1 = new InterfacePackageTest(); int res = obj1.display(n); System.out.println("The result is " + res); } }
UTF-8
Java
323
java
InterfacePackageTest.java
Java
[]
null
[]
import pac1.*; public class InterfacePackageTest implements Pack1 { public int display(int num) { return num * a1 + a2; } public static void main(String[] args) { int n = 100; InterfacePackageTest obj1 = new InterfacePackageTest(); int res = obj1.display(n); System.out.println("The result is " + res); } }
323
0.690402
0.662539
15
20.533333
19.109741
57
false
false
0
0
0
0
0
0
1.466667
false
false
13
c58fd3ca8aef3bf9e61696aa23a336491e03af26
10,359,461,174,542
98e126336213273044ee2a451135b999a6d70f4b
/core/src/main/java/com/exactprosystems/jf/actions/app/ApplicationStart.java
c58c8387eda9fa45773d0f8f618a151844908c62
[ "Apache-2.0" ]
permissive
bellmit/jackfish
https://github.com/bellmit/jackfish
b14a0ad3a4b0beb2dcc252d60ca6cf64bed329ee
efeedcce7a8100f6f06b61d2641339f4ee3db559
refs/heads/master
2022-04-07T08:09:28.804000
2019-06-20T16:11:35
2019-06-20T16:11:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/******************************************************************************* * Copyright 2009-2018 Exactpro (Exactpro Systems Limited) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.exactprosystems.jf.actions.app; import com.exactprosystems.jf.actions.*; import com.exactprosystems.jf.actions.gui.*; import com.exactprosystems.jf.api.app.AppConnection; import com.exactprosystems.jf.api.app.IApplicationPool; import com.exactprosystems.jf.api.common.ParametersKind; import com.exactprosystems.jf.api.common.Str; import com.exactprosystems.jf.api.common.i18n.R; import com.exactprosystems.jf.api.error.ErrorKind; import com.exactprosystems.jf.common.evaluator.AbstractEvaluator; import com.exactprosystems.jf.common.report.ReportBuilder; import com.exactprosystems.jf.documents.config.Context; import com.exactprosystems.jf.documents.matrix.parser.Parameter; import com.exactprosystems.jf.documents.matrix.parser.Parameters; import com.exactprosystems.jf.documents.matrix.parser.items.TypeMandatory; import com.exactprosystems.jf.functions.HelpKind; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @ActionAttribute( group = ActionGroups.App, suffix = "APPSTR", additionFieldsAllowed = true, outputType = AppConnection.class, constantGeneralDescription = R.APP_START_GENERAL_DESC, constantAdditionalDescription = R.APP_START_ADDITIONAL_DESC, constantOutputDescription = R.APP_START_OUTPUT_DESC, constantExamples = R.APP_START_EXAMPLE, seeAlsoClass = {ApplicationStop.class, ApplicationConnectTo.class, ApplicationGetProperties.class, ApplicationNewInstance.class, ApplicationRefresh.class, ApplicationResize.class, ApplicationSwitchTo.class, DialogAlert.class, DialogCheckLayout.class, DialogClose.class, DialogFill.class, DialogSwitchToWindow.class} ) public class ApplicationStart extends AbstractAction { public static final String idName = "AppId"; @ActionFieldAttribute(name = idName, mandatory = true, constantDescription = R.APPLICATION_START_APP_ID) protected String id; @Override protected void helpToAddParametersDerived(List<ReadableValue> list, Context context, Parameters parameters) throws Exception { Helper.helpToAddParameters(list, ParametersKind.START, this.owner.getMatrix(), context, parameters, idName, null); } @Override protected HelpKind howHelpWithParameterDerived(Context context, Parameters parameters, String fieldName) throws Exception { boolean res; switch (fieldName) { case idName: res = true; break; default: res = Helper.canFillParameter(this.owner.getMatrix(), context, parameters, idName, null, fieldName); break; } return res ? HelpKind.ChooseFromList : null; } @Override protected void listToFillParameterDerived(List<ReadableValue> list, Context context, String parameterToFill, Parameters parameters) throws Exception { switch (parameterToFill) { case idName: Helper.applicationsNames(list, context); break; default: Helper.fillListForParameter(list, this.owner.getMatrix(), context, parameters, idName, null, parameterToFill); break; } } @Override public void doRealAction(Context context, ReportBuilder report, Parameters parameters, AbstractEvaluator evaluator) throws Exception { IApplicationPool pool = context.getConfiguration().getApplicationPool(); Map<String, String> args = parameters.select(TypeMandatory.Extra) .stream() .collect(Collectors.toMap(Parameter::getName, par -> Str.asString(par.getValue()))); AppConnection connection = pool.startApplication(this.id, args); if (connection.isGood()) { super.setResult(connection); } else { super.setError("Application is not started.", ErrorKind.APPLICATION_ERROR); } } }
UTF-8
Java
4,418
java
ApplicationStart.java
Java
[]
null
[]
/******************************************************************************* * Copyright 2009-2018 Exactpro (Exactpro Systems Limited) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.exactprosystems.jf.actions.app; import com.exactprosystems.jf.actions.*; import com.exactprosystems.jf.actions.gui.*; import com.exactprosystems.jf.api.app.AppConnection; import com.exactprosystems.jf.api.app.IApplicationPool; import com.exactprosystems.jf.api.common.ParametersKind; import com.exactprosystems.jf.api.common.Str; import com.exactprosystems.jf.api.common.i18n.R; import com.exactprosystems.jf.api.error.ErrorKind; import com.exactprosystems.jf.common.evaluator.AbstractEvaluator; import com.exactprosystems.jf.common.report.ReportBuilder; import com.exactprosystems.jf.documents.config.Context; import com.exactprosystems.jf.documents.matrix.parser.Parameter; import com.exactprosystems.jf.documents.matrix.parser.Parameters; import com.exactprosystems.jf.documents.matrix.parser.items.TypeMandatory; import com.exactprosystems.jf.functions.HelpKind; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @ActionAttribute( group = ActionGroups.App, suffix = "APPSTR", additionFieldsAllowed = true, outputType = AppConnection.class, constantGeneralDescription = R.APP_START_GENERAL_DESC, constantAdditionalDescription = R.APP_START_ADDITIONAL_DESC, constantOutputDescription = R.APP_START_OUTPUT_DESC, constantExamples = R.APP_START_EXAMPLE, seeAlsoClass = {ApplicationStop.class, ApplicationConnectTo.class, ApplicationGetProperties.class, ApplicationNewInstance.class, ApplicationRefresh.class, ApplicationResize.class, ApplicationSwitchTo.class, DialogAlert.class, DialogCheckLayout.class, DialogClose.class, DialogFill.class, DialogSwitchToWindow.class} ) public class ApplicationStart extends AbstractAction { public static final String idName = "AppId"; @ActionFieldAttribute(name = idName, mandatory = true, constantDescription = R.APPLICATION_START_APP_ID) protected String id; @Override protected void helpToAddParametersDerived(List<ReadableValue> list, Context context, Parameters parameters) throws Exception { Helper.helpToAddParameters(list, ParametersKind.START, this.owner.getMatrix(), context, parameters, idName, null); } @Override protected HelpKind howHelpWithParameterDerived(Context context, Parameters parameters, String fieldName) throws Exception { boolean res; switch (fieldName) { case idName: res = true; break; default: res = Helper.canFillParameter(this.owner.getMatrix(), context, parameters, idName, null, fieldName); break; } return res ? HelpKind.ChooseFromList : null; } @Override protected void listToFillParameterDerived(List<ReadableValue> list, Context context, String parameterToFill, Parameters parameters) throws Exception { switch (parameterToFill) { case idName: Helper.applicationsNames(list, context); break; default: Helper.fillListForParameter(list, this.owner.getMatrix(), context, parameters, idName, null, parameterToFill); break; } } @Override public void doRealAction(Context context, ReportBuilder report, Parameters parameters, AbstractEvaluator evaluator) throws Exception { IApplicationPool pool = context.getConfiguration().getApplicationPool(); Map<String, String> args = parameters.select(TypeMandatory.Extra) .stream() .collect(Collectors.toMap(Parameter::getName, par -> Str.asString(par.getValue()))); AppConnection connection = pool.startApplication(this.id, args); if (connection.isGood()) { super.setResult(connection); } else { super.setError("Application is not started.", ErrorKind.APPLICATION_ERROR); } } }
4,418
0.743323
0.740154
117
36.760685
36.695477
149
false
false
0
0
0
0
0
0
2.316239
false
false
13
fe43602a0a05e0d29427a25abfbe4023d21bb3a4
33,320,356,339,318
35b70146d307cf3212f302b90506f3a06bc45f00
/build/classes/Interfas/Publicacion.java
10eced7e49dc6daf6a9fa81d46b7e5144c1f4920
[]
no_license
iutll/javaDBConection
https://github.com/iutll/javaDBConection
57d368466a16515b7e94d5c051feef83c5a5995c
969fb1c79e81a06a097b71c20a14d7d76ad0dca1
refs/heads/master
2020-09-10T16:33:29.356000
2019-11-28T05:49:39
2019-11-28T05:49:39
221,760,977
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Interfas; import static Interfas.Pagina.PASSWORD; import static Interfas.Pagina.URL; import static Interfas.Pagina.USERNAME; import java.sql.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * * @author jose-dasilva */ public class Publicacion extends JPanel implements ActionListener { //--------Atributos Globales---------- private JButton BB,BID,BAnadir,BGuardar,BModificar,BLimpiar,BEliminar; private JTextField txtBp,txtID,txtUsu,txtTitle,txtFecha; private JTextArea ACont; private JComboBox Red=new JComboBox(); private PreparedStatement ps; private ResultSet rs; //------------------------------------ public Connection getConnection(){ Connection con = null; try { Class.forName("java.sql.Driver"); con=(Connection) DriverManager.getConnection(URL,USERNAME,PASSWORD); JOptionPane.showMessageDialog(this,"Conectado a la base de datos..."); } catch (Exception e) { JOptionPane.showMessageDialog(this,"Error:" + e); } return con; } public Publicacion(){ setLayout(null); //Desactivamos el diseño por Defecto del panel setBackground(Color.CYAN);//Agregamos Color Al Panel initComponents(); } private void initComponents(){ //----------->>>>>>>>>Etiquetas<<<<<<<<<<<------------ JLabel title=new JLabel("¡¡Registro de Publicaciónes!!", SwingConstants.CENTER); title.setForeground(Color.DARK_GRAY); title.setBounds(170, 5, 250, 50); title.setFont(new Font("Dyuthi",Font.ITALIC, 20)); add(title); JLabel BP=new JLabel("Ingrese Cedula", SwingConstants.CENTER); BP.setForeground(Color.BLACK); BP.setBounds(440, 30, 150, 40); BP.setFont(new Font("Dyuthi",Font.ITALIC, 16)); add(BP); JLabel ID=new JLabel("Ingrese ID", SwingConstants.CENTER); ID.setForeground(Color.BLACK); ID.setBounds(440, 210, 150, 40); ID.setFont(new Font("Dyuthi",Font.ITALIC, 16)); add(ID); JLabel Usuario=new JLabel("Usuario:", SwingConstants.CENTER); Usuario.setForeground(Color.BLACK); Usuario.setBounds(5, 45, 100, 40); Usuario.setFont(new Font("Dyuthi",Font.ITALIC, 17)); add(Usuario); JLabel Title=new JLabel("Titulo:", SwingConstants.CENTER); Title.setForeground(Color.BLACK); Title.setBounds(5, 75, 100, 40); Title.setFont(new Font("Dyuthi",Font.ITALIC, 17)); add(Title); JLabel Cont=new JLabel("Contenido:", SwingConstants.CENTER); Cont.setForeground(Color.BLACK); Cont.setBounds(5, 115, 100, 40); Cont.setFont(new Font("Dyuthi",Font.ITALIC, 17)); add(Cont); JLabel Publi=new JLabel("Publicar en:", SwingConstants.CENTER); Publi.setForeground(Color.BLACK); Publi.setBounds(5, 250, 100, 40); Publi.setFont(new Font("Dyuthi",Font.ITALIC, 17)); add(Publi); JLabel Fecha=new JLabel("Fecha:", SwingConstants.CENTER); Fecha.setForeground(Color.BLACK); Fecha.setBounds(5, 360, 100, 40); Fecha.setFont(new Font("Dyuthi",Font.ITALIC, 17)); add(Fecha); //----------->>>>>>>>>Cajas de Texto<<<<<<<<<<<------------ txtBp = new JTextField(); txtBp.setBounds(450, 60, 130, 20); add(txtBp); txtID = new JTextField(); txtID.setBounds(450, 250, 130, 20); add(txtID); txtUsu = new JTextField(); txtUsu.setBounds(90, 55, 315, 20); txtUsu.setEditable(false); add(txtUsu); txtTitle = new JTextField(); txtTitle.setBounds(90, 85, 315, 20); txtTitle.setEditable(false); add(txtTitle); txtFecha = new JTextField(); txtFecha.setBounds(90, 370, 315, 20); txtFecha.setEditable(false); add(txtFecha); //----------->>>>>>>>>Area de Texto<<<<<<<<<<<------------ ACont=new JTextArea(); ACont.setBounds(100, 110, 300, 100); ACont.setBackground(Color.WHITE); ACont.setForeground(Color.BLACK); ACont.setEditable(false); add(ACont); //----------->>>>>>>>>Lista Desplegable<<<<<<<<<<<------------ String[] Redes= {"Seleccione","Facebook","Instagram","Twitter"}; Red=new JComboBox(Redes); Red.setBounds(120, 260, 140, 30); Red.setSelectedItem("Seleccione"); //Selecciona el Primer Obj Mostrado add(Red); //----------->>>>>>>>>Botones<<<<<<<<<<<------------ BB = new JButton("Buscar"); BB.setBounds(470, 90, 100, 25); BB.setEnabled(true); BB.addActionListener(this); add(BB); BID = new JButton("Buscar"); BID.setBounds(470, 280, 100, 25); BID.setEnabled(true); BID.addActionListener(this); add(BID); BAnadir = new JButton("Nueva"); BAnadir.setBounds(10, 410, 100, 30); BAnadir.setEnabled(true); BAnadir.addActionListener(this); add(BAnadir); BGuardar = new JButton("Publicar"); BGuardar.setBounds(130, 410, 100, 30); BGuardar.setEnabled(true); BGuardar.addActionListener(this); add(BGuardar); BModificar = new JButton("Modificar"); BModificar.setBounds(250, 410, 100, 30); BModificar.setEnabled(true); BModificar.addActionListener(this); add(BModificar); BLimpiar = new JButton("Limpiar"); BLimpiar.setBounds(370, 410, 100, 30); BLimpiar.setEnabled(true); BLimpiar.addActionListener(this); add(BLimpiar); BEliminar = new JButton("Eliminar"); BEliminar.setBounds(480, 410, 100, 30); BEliminar.setEnabled(true); BEliminar.addActionListener(this); add(BEliminar); } @Override public void actionPerformed(ActionEvent ae) { if (ae.getSource()==BB){ JOptionPane.showMessageDialog(this,"Encontrando Resultados de CI... "+txtBp.getText()); txtBp.setText(""); buscarPorCedula(); } if (ae.getSource()==BID){ JOptionPane.showMessageDialog(this,"Encontrando Resultados de ID... "+txtBp.getText()); txtID.setText(""); //buscarPorId(txtID.getText()); } if (ae.getSource()==BAnadir){ JOptionPane.showMessageDialog(this,"Agrega Tus Datos... "); ACont.setEditable(true); txtTitle.setEditable(true); txtFecha.setEditable(true); } if (ae.getSource()==BGuardar){ JOptionPane.showMessageDialog(this,"Guardando... "); ACont.setEditable(false); txtTitle.setEditable(false); txtFecha.setEditable(false); } if (ae.getSource()==BModificar){ JOptionPane.showMessageDialog(this,"Modifica la Publicación... "); ACont.setEditable(true); txtTitle.setEditable(true); txtFecha.setEditable(true); } if (ae.getSource()==BLimpiar){ JOptionPane.showMessageDialog(this,"Limpiando... "); txtUsu.setText(" "); txtTitle.setText(" "); ACont.setText(" "); txtFecha.setText(" "); ACont.setEditable(false); txtTitle.setEditable(false); txtFecha.setEditable(false); } if (ae.getSource()==BEliminar){ JOptionPane.showMessageDialog(this,"Eliminando... "); ACont.setEditable(false); txtTitle.setEditable(false); txtFecha.setEditable(false); } } // *********************** acciones crud **************************** private void buscarPorCedula(){ java.sql.Connection con = null; try{ con = (java.sql.Connection) getConnection(); ps = con.prepareStatement("SELECT * FROM pu WHERE cedula = ?"); ps.setString(1,txtBp.getText() ); rs = ps.executeQuery(); if(rs.first()){ do{ String[] valores = { rs.getString("Nombre_red"), rs.getString("Url"), }; }while(rs.next()); // mostrar usuario //mostrarUsuario(txtUsu, txtBr.getText(), false); hacerEditable(true); }else{ JOptionPane.showMessageDialog(null,"No existen redes asociadas a esa cedula \n puedes agregarlas"); // mostrar usuario //mostrarUsuario(txtUsu, txtBr.getText(), false); // hacer editable para agregar redes a usuario hacerEditable(true); } }catch(Exception e){ System.out.println("error " + e); } } // hacer campos editables private boolean hacerEditable(boolean visible){ return true; } }
UTF-8
Java
9,063
java
Publicacion.java
Java
[ { "context": ".event.*;\nimport javax.swing.*;\n\n/**\n *\n * @author jose-dasilva\n */\npublic class Publicacion extends JPanel imple", "end": 251, "score": 0.9976928234100342, "start": 239, "tag": "USERNAME", "value": "jose-dasilva" } ]
null
[]
package Interfas; import static Interfas.Pagina.PASSWORD; import static Interfas.Pagina.URL; import static Interfas.Pagina.USERNAME; import java.sql.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * * @author jose-dasilva */ public class Publicacion extends JPanel implements ActionListener { //--------Atributos Globales---------- private JButton BB,BID,BAnadir,BGuardar,BModificar,BLimpiar,BEliminar; private JTextField txtBp,txtID,txtUsu,txtTitle,txtFecha; private JTextArea ACont; private JComboBox Red=new JComboBox(); private PreparedStatement ps; private ResultSet rs; //------------------------------------ public Connection getConnection(){ Connection con = null; try { Class.forName("java.sql.Driver"); con=(Connection) DriverManager.getConnection(URL,USERNAME,PASSWORD); JOptionPane.showMessageDialog(this,"Conectado a la base de datos..."); } catch (Exception e) { JOptionPane.showMessageDialog(this,"Error:" + e); } return con; } public Publicacion(){ setLayout(null); //Desactivamos el diseño por Defecto del panel setBackground(Color.CYAN);//Agregamos Color Al Panel initComponents(); } private void initComponents(){ //----------->>>>>>>>>Etiquetas<<<<<<<<<<<------------ JLabel title=new JLabel("¡¡Registro de Publicaciónes!!", SwingConstants.CENTER); title.setForeground(Color.DARK_GRAY); title.setBounds(170, 5, 250, 50); title.setFont(new Font("Dyuthi",Font.ITALIC, 20)); add(title); JLabel BP=new JLabel("Ingrese Cedula", SwingConstants.CENTER); BP.setForeground(Color.BLACK); BP.setBounds(440, 30, 150, 40); BP.setFont(new Font("Dyuthi",Font.ITALIC, 16)); add(BP); JLabel ID=new JLabel("Ingrese ID", SwingConstants.CENTER); ID.setForeground(Color.BLACK); ID.setBounds(440, 210, 150, 40); ID.setFont(new Font("Dyuthi",Font.ITALIC, 16)); add(ID); JLabel Usuario=new JLabel("Usuario:", SwingConstants.CENTER); Usuario.setForeground(Color.BLACK); Usuario.setBounds(5, 45, 100, 40); Usuario.setFont(new Font("Dyuthi",Font.ITALIC, 17)); add(Usuario); JLabel Title=new JLabel("Titulo:", SwingConstants.CENTER); Title.setForeground(Color.BLACK); Title.setBounds(5, 75, 100, 40); Title.setFont(new Font("Dyuthi",Font.ITALIC, 17)); add(Title); JLabel Cont=new JLabel("Contenido:", SwingConstants.CENTER); Cont.setForeground(Color.BLACK); Cont.setBounds(5, 115, 100, 40); Cont.setFont(new Font("Dyuthi",Font.ITALIC, 17)); add(Cont); JLabel Publi=new JLabel("Publicar en:", SwingConstants.CENTER); Publi.setForeground(Color.BLACK); Publi.setBounds(5, 250, 100, 40); Publi.setFont(new Font("Dyuthi",Font.ITALIC, 17)); add(Publi); JLabel Fecha=new JLabel("Fecha:", SwingConstants.CENTER); Fecha.setForeground(Color.BLACK); Fecha.setBounds(5, 360, 100, 40); Fecha.setFont(new Font("Dyuthi",Font.ITALIC, 17)); add(Fecha); //----------->>>>>>>>>Cajas de Texto<<<<<<<<<<<------------ txtBp = new JTextField(); txtBp.setBounds(450, 60, 130, 20); add(txtBp); txtID = new JTextField(); txtID.setBounds(450, 250, 130, 20); add(txtID); txtUsu = new JTextField(); txtUsu.setBounds(90, 55, 315, 20); txtUsu.setEditable(false); add(txtUsu); txtTitle = new JTextField(); txtTitle.setBounds(90, 85, 315, 20); txtTitle.setEditable(false); add(txtTitle); txtFecha = new JTextField(); txtFecha.setBounds(90, 370, 315, 20); txtFecha.setEditable(false); add(txtFecha); //----------->>>>>>>>>Area de Texto<<<<<<<<<<<------------ ACont=new JTextArea(); ACont.setBounds(100, 110, 300, 100); ACont.setBackground(Color.WHITE); ACont.setForeground(Color.BLACK); ACont.setEditable(false); add(ACont); //----------->>>>>>>>>Lista Desplegable<<<<<<<<<<<------------ String[] Redes= {"Seleccione","Facebook","Instagram","Twitter"}; Red=new JComboBox(Redes); Red.setBounds(120, 260, 140, 30); Red.setSelectedItem("Seleccione"); //Selecciona el Primer Obj Mostrado add(Red); //----------->>>>>>>>>Botones<<<<<<<<<<<------------ BB = new JButton("Buscar"); BB.setBounds(470, 90, 100, 25); BB.setEnabled(true); BB.addActionListener(this); add(BB); BID = new JButton("Buscar"); BID.setBounds(470, 280, 100, 25); BID.setEnabled(true); BID.addActionListener(this); add(BID); BAnadir = new JButton("Nueva"); BAnadir.setBounds(10, 410, 100, 30); BAnadir.setEnabled(true); BAnadir.addActionListener(this); add(BAnadir); BGuardar = new JButton("Publicar"); BGuardar.setBounds(130, 410, 100, 30); BGuardar.setEnabled(true); BGuardar.addActionListener(this); add(BGuardar); BModificar = new JButton("Modificar"); BModificar.setBounds(250, 410, 100, 30); BModificar.setEnabled(true); BModificar.addActionListener(this); add(BModificar); BLimpiar = new JButton("Limpiar"); BLimpiar.setBounds(370, 410, 100, 30); BLimpiar.setEnabled(true); BLimpiar.addActionListener(this); add(BLimpiar); BEliminar = new JButton("Eliminar"); BEliminar.setBounds(480, 410, 100, 30); BEliminar.setEnabled(true); BEliminar.addActionListener(this); add(BEliminar); } @Override public void actionPerformed(ActionEvent ae) { if (ae.getSource()==BB){ JOptionPane.showMessageDialog(this,"Encontrando Resultados de CI... "+txtBp.getText()); txtBp.setText(""); buscarPorCedula(); } if (ae.getSource()==BID){ JOptionPane.showMessageDialog(this,"Encontrando Resultados de ID... "+txtBp.getText()); txtID.setText(""); //buscarPorId(txtID.getText()); } if (ae.getSource()==BAnadir){ JOptionPane.showMessageDialog(this,"Agrega Tus Datos... "); ACont.setEditable(true); txtTitle.setEditable(true); txtFecha.setEditable(true); } if (ae.getSource()==BGuardar){ JOptionPane.showMessageDialog(this,"Guardando... "); ACont.setEditable(false); txtTitle.setEditable(false); txtFecha.setEditable(false); } if (ae.getSource()==BModificar){ JOptionPane.showMessageDialog(this,"Modifica la Publicación... "); ACont.setEditable(true); txtTitle.setEditable(true); txtFecha.setEditable(true); } if (ae.getSource()==BLimpiar){ JOptionPane.showMessageDialog(this,"Limpiando... "); txtUsu.setText(" "); txtTitle.setText(" "); ACont.setText(" "); txtFecha.setText(" "); ACont.setEditable(false); txtTitle.setEditable(false); txtFecha.setEditable(false); } if (ae.getSource()==BEliminar){ JOptionPane.showMessageDialog(this,"Eliminando... "); ACont.setEditable(false); txtTitle.setEditable(false); txtFecha.setEditable(false); } } // *********************** acciones crud **************************** private void buscarPorCedula(){ java.sql.Connection con = null; try{ con = (java.sql.Connection) getConnection(); ps = con.prepareStatement("SELECT * FROM pu WHERE cedula = ?"); ps.setString(1,txtBp.getText() ); rs = ps.executeQuery(); if(rs.first()){ do{ String[] valores = { rs.getString("Nombre_red"), rs.getString("Url"), }; }while(rs.next()); // mostrar usuario //mostrarUsuario(txtUsu, txtBr.getText(), false); hacerEditable(true); }else{ JOptionPane.showMessageDialog(null,"No existen redes asociadas a esa cedula \n puedes agregarlas"); // mostrar usuario //mostrarUsuario(txtUsu, txtBr.getText(), false); // hacer editable para agregar redes a usuario hacerEditable(true); } }catch(Exception e){ System.out.println("error " + e); } } // hacer campos editables private boolean hacerEditable(boolean visible){ return true; } }
9,063
0.559726
0.533561
286
30.667831
21.192215
107
false
false
0
0
0
0
0
0
1.024476
false
false
13
06ce063bad01feef241f9205bf0b2264774a9107
19,396,072,324,132
4a698321e6b1ab1337cfe52ab3ea38a1134f8894
/mall-back/src/main/java/com/cplatform/mall/back/sys/dao/SysFeeDao.java
98df3ba2b9ebedeea05aa662b8f24ec47db8ab4d
[]
no_license
bellmit/ws
https://github.com/bellmit/ws
c823419a6a335c424a19bfcdcc00f052f20ec65c
6d3cd146ab82e06097a4eb94c4c3061ce000328c
refs/heads/master
2022-03-22T22:47:10.514000
2015-10-10T10:39:54
2015-10-10T10:39:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cplatform.mall.back.sys.dao; import java.util.List; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; import com.cplatform.mall.back.sys.entity.SysFee; /** * 分类费率管理jpa数据访问接口. <br> * 类详细说明. * <p> * Copyright: Copyright (c) 2013-5-24 上午11:10:07 * <p> * Company: 北京宽连十方数字技术有限公司 * <p> * * @author zhaowei@c-platform.com * @version 1.0.0 */ public interface SysFeeDao extends PagingAndSortingRepository<SysFee, Long> { /** * 获得所有有效的费率分类 * * @return */ @Query("select f from SysFee f where f.valid = 1 and f.syncGyFlag = 1") List<SysFee> getAllFee(); @Query("select f from SysFee f where f.valid = 1 and f.syncGyFlag = 1") List<SysFee> getFeeList(); }
UTF-8
Java
854
java
SysFeeDao.java
Java
[ { "context": ">\n * Company: 北京宽连十方数字技术有限公司\n * <p>\n * \n * @author zhaowei@c-platform.com\n * @version 1.0.0\n */\npublic interface SysFeeDao ", "end": 416, "score": 0.9999311566352844, "start": 394, "tag": "EMAIL", "value": "zhaowei@c-platform.com" } ]
null
[]
package com.cplatform.mall.back.sys.dao; import java.util.List; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; import com.cplatform.mall.back.sys.entity.SysFee; /** * 分类费率管理jpa数据访问接口. <br> * 类详细说明. * <p> * Copyright: Copyright (c) 2013-5-24 上午11:10:07 * <p> * Company: 北京宽连十方数字技术有限公司 * <p> * * @author <EMAIL> * @version 1.0.0 */ public interface SysFeeDao extends PagingAndSortingRepository<SysFee, Long> { /** * 获得所有有效的费率分类 * * @return */ @Query("select f from SysFee f where f.valid = 1 and f.syncGyFlag = 1") List<SysFee> getAllFee(); @Query("select f from SysFee f where f.valid = 1 and f.syncGyFlag = 1") List<SysFee> getFeeList(); }
839
0.704961
0.678851
34
21.529411
24.060261
77
false
false
0
0
0
0
0
0
0.529412
false
false
13
4a290ef1f15956213518ea19aacd88db67bab030
3,856,880,671,651
c4a0e678332a85b06ece49d2587d943a938702ba
/src/main/java/com/demo/zookeeper/分布式屏障/DistributedBarrierDemo.java
9cdebb3707fc59dd59d5b1cd2d94e20938d1dd13
[]
no_license
jayBin106/zookeeper
https://github.com/jayBin106/zookeeper
c50dc46f44ee773095a87122e176f6606205e0d2
cc682838918d03ed0f4e1b62894c3449263a0095
refs/heads/master
2020-05-03T14:14:35.595000
2019-04-11T06:10:57
2019-04-11T06:10:57
178,672,004
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.demo.zookeeper.分布式屏障; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.barriers.DistributedBarrier; import org.apache.curator.retry.ExponentialBackoffRetry; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static com.demo.zookeeper.zookeeper基本操作.ZookeeperDemo.zookeeperAddress; /** * 分布式屏障—Barrier * 分布式Barrier是这样一个类: 它会阻塞所有节点上的等待进程,直到某一个被满足, 然后所有的节点继续进行。 * <p> * 比如赛马比赛中, 等赛马陆续来到起跑线前。 一声令下,所有的赛马都飞奔而出。 * <p> * DistributedBarrier */ public class DistributedBarrierDemo { private static final int QTY = 5; private static final String PATH = "/examples/barrier"; public static void main(String[] args) throws Exception { //初始话客户端 CuratorFramework client = CuratorFrameworkFactory.newClient(zookeeperAddress, new ExponentialBackoffRetry(1000, 3)); client.start(); //设置多个线程 ExecutorService service = Executors.newFixedThreadPool(QTY); //DistributedBarrier类实现了栅栏的功能。 DistributedBarrier controlBarrier = new DistributedBarrier(client, PATH); //首先你需要设置栅栏,它将阻塞在它上面等待的线程: controlBarrier.setBarrier(); for (int i = 0; i < QTY; ++i) { final DistributedBarrier barrier = new DistributedBarrier(client, PATH); final int index = i; service.submit(new Runnable() { @Override public void run() { try { Thread.sleep((long) (3 * Math.random())); System.out.println("Client #" + index + " 在前栅栏等待"); //需要阻塞的线程调用方法等待放行条件: barrier.waitOnBarrier(); System.out.println("Client #" + index + "开始运行"); } catch (Exception e) { e.printStackTrace(); } } }); } Thread.sleep(5000); System.out.println("所有Barrier实例都应该等待这个条件"); //移除栅栏,所有等待的线程将继续执行 System.out.println("移除栅栏。。。"); controlBarrier.removeBarrier(); service.shutdown(); service.awaitTermination(10, TimeUnit.MINUTES); Thread.sleep(20000); } }
UTF-8
Java
2,764
java
DistributedBarrierDemo.java
Java
[]
null
[]
package com.demo.zookeeper.分布式屏障; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.barriers.DistributedBarrier; import org.apache.curator.retry.ExponentialBackoffRetry; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static com.demo.zookeeper.zookeeper基本操作.ZookeeperDemo.zookeeperAddress; /** * 分布式屏障—Barrier * 分布式Barrier是这样一个类: 它会阻塞所有节点上的等待进程,直到某一个被满足, 然后所有的节点继续进行。 * <p> * 比如赛马比赛中, 等赛马陆续来到起跑线前。 一声令下,所有的赛马都飞奔而出。 * <p> * DistributedBarrier */ public class DistributedBarrierDemo { private static final int QTY = 5; private static final String PATH = "/examples/barrier"; public static void main(String[] args) throws Exception { //初始话客户端 CuratorFramework client = CuratorFrameworkFactory.newClient(zookeeperAddress, new ExponentialBackoffRetry(1000, 3)); client.start(); //设置多个线程 ExecutorService service = Executors.newFixedThreadPool(QTY); //DistributedBarrier类实现了栅栏的功能。 DistributedBarrier controlBarrier = new DistributedBarrier(client, PATH); //首先你需要设置栅栏,它将阻塞在它上面等待的线程: controlBarrier.setBarrier(); for (int i = 0; i < QTY; ++i) { final DistributedBarrier barrier = new DistributedBarrier(client, PATH); final int index = i; service.submit(new Runnable() { @Override public void run() { try { Thread.sleep((long) (3 * Math.random())); System.out.println("Client #" + index + " 在前栅栏等待"); //需要阻塞的线程调用方法等待放行条件: barrier.waitOnBarrier(); System.out.println("Client #" + index + "开始运行"); } catch (Exception e) { e.printStackTrace(); } } }); } Thread.sleep(5000); System.out.println("所有Barrier实例都应该等待这个条件"); //移除栅栏,所有等待的线程将继续执行 System.out.println("移除栅栏。。。"); controlBarrier.removeBarrier(); service.shutdown(); service.awaitTermination(10, TimeUnit.MINUTES); Thread.sleep(20000); } }
2,764
0.623724
0.615646
64
35.765625
25.513931
124
false
false
0
0
0
0
0
0
0.59375
false
false
13
9397cf06098ad347422e0dec9f58870daea6dd2e
6,811,818,180,956
66f780a9c2cf235b1941fe959e419112d20626a2
/rxactivity/src/test/java/com/rubyhuntersky/rxactivity/ScopedObservableTest.java
9b375a1c895b7e8d1ac55fe8a55d27f67c67dca1
[]
no_license
wehjin/rxactivity
https://github.com/wehjin/rxactivity
409543c38750cab44c095a6a260b910591a7fe15
12e90715b8d9e8bd5332bbe77e1c8089317fa4fd
refs/heads/master
2021-01-01T20:22:57.245000
2015-08-08T18:35:45
2015-08-08T18:45:29
40,552,395
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rubyhuntersky.rxactivity; import org.junit.Before; import org.junit.Test; import rx.functions.Func1; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.fail; /** * @author wehjin * @since 8/8/15. * <p/> * TODO: flatMap, subscribe(Action2,Action2, Action1) */ public class ScopedObservableTest { public static final String SCOPE1 = "Hello"; public static final String VALUE1 = "Jeff"; public static final String VALUE2 = "Emily"; private ScopedObservable<String, String> just1; private AssertingObserver observer1; @Before public void setUp() throws Exception { just1 = ScopedObservable.just(SCOPE1, VALUE1); observer1 = new AssertingObserver(SCOPE1, VALUE1); } @Test public void testMap() throws Exception { final ScopedObservable<String, String> map = just1.map(new Func1<String, String>() { @Override public String call(String s) { return VALUE2; } }); map.subscribe(observer1.withExpectedValue(VALUE2)); } @Test public void testJust() throws Exception { just1.subscribe(observer1); } private static class AssertingObserver implements ScopedObserver<String, String> { private final String expectedScope; private final String expectedValue; public AssertingObserver(String expectedScope, String expectedValue) { this.expectedScope = expectedScope; this.expectedValue = expectedValue; } @Override public void onNext(String scope, String value) { assertEquals(expectedScope, scope); assertEquals(expectedValue, value); } @Override public void onCompleted(String scope) { assertEquals(expectedScope, scope); } @Override public void onError(String scope, Throwable throwable) { fail(throwable.getMessage()); } public AssertingObserver withExpectedValue(String expectedValue) { return new AssertingObserver(expectedScope, expectedValue); } } }
UTF-8
Java
2,176
java
ScopedObservableTest.java
Java
[ { "context": "tatic junit.framework.Assert.fail;\n\n/**\n * @author wehjin\n * @since 8/8/15.\n * <p/>\n * TODO: flatMap, subsc", "end": 232, "score": 0.9996888041496277, "start": 226, "tag": "USERNAME", "value": "wehjin" }, { "context": "\"Hello\";\n public static final String VA...
null
[]
package com.rubyhuntersky.rxactivity; import org.junit.Before; import org.junit.Test; import rx.functions.Func1; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.fail; /** * @author wehjin * @since 8/8/15. * <p/> * TODO: flatMap, subscribe(Action2,Action2, Action1) */ public class ScopedObservableTest { public static final String SCOPE1 = "Hello"; public static final String VALUE1 = "Jeff"; public static final String VALUE2 = "Emily"; private ScopedObservable<String, String> just1; private AssertingObserver observer1; @Before public void setUp() throws Exception { just1 = ScopedObservable.just(SCOPE1, VALUE1); observer1 = new AssertingObserver(SCOPE1, VALUE1); } @Test public void testMap() throws Exception { final ScopedObservable<String, String> map = just1.map(new Func1<String, String>() { @Override public String call(String s) { return VALUE2; } }); map.subscribe(observer1.withExpectedValue(VALUE2)); } @Test public void testJust() throws Exception { just1.subscribe(observer1); } private static class AssertingObserver implements ScopedObserver<String, String> { private final String expectedScope; private final String expectedValue; public AssertingObserver(String expectedScope, String expectedValue) { this.expectedScope = expectedScope; this.expectedValue = expectedValue; } @Override public void onNext(String scope, String value) { assertEquals(expectedScope, scope); assertEquals(expectedValue, value); } @Override public void onCompleted(String scope) { assertEquals(expectedScope, scope); } @Override public void onError(String scope, Throwable throwable) { fail(throwable.getMessage()); } public AssertingObserver withExpectedValue(String expectedValue) { return new AssertingObserver(expectedScope, expectedValue); } } }
2,176
0.652574
0.640625
77
27.272728
24.410257
92
false
false
0
0
0
0
0
0
0.545455
false
false
13
c6593ee63e9ab0d7981188236baf4962be2de278
6,975,026,944,770
3243bb38bd8445ac5d6484f91227dec2784047d3
/modules/voucher/voucher-api/src/main/java/com/bjike/goddess/voucher/vo/PartOptionVO.java
3f1cc3feb5db54a8e701c5ce10fb337059b55e2a
[]
no_license
moutainhigh/goddess-java
https://github.com/moutainhigh/goddess-java
4809935c3c34cd8139e176e08537967ab0504ced
a59cfa5326f01f09e43a69f90161cdc81f7d9fb4
refs/heads/master
2023-03-16T23:52:43.384000
2018-05-18T08:03:42
2018-05-18T08:03:42
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bjike.goddess.voucher.vo; import com.bjike.goddess.common.api.bo.BaseBO; /** * 提供给资金核对的部分数据 * * @Author: [ tanghaixiang ] * @Date: [ 2017-04-17 05:35 ] * @Description: [ 提供给资金核对的部分数据 ] * @Version: [ v1.0.0 ] * @Copy: [ com.bjike ] */ public class PartOptionVO extends BaseBO { /** * 一级科目名称 */ private String firstName; /** * 二级科目名称 */ private String secondName; /** * 三级科目名称 */ private String thirdName; /** * 贷方金额 */ private Double loanMoney; /** * 借方金额 */ private Double borrowMoney; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getSecondName() { return secondName; } public void setSecondName(String secondName) { this.secondName = secondName; } public String getThirdName() { return thirdName; } public void setThirdName(String thirdName) { this.thirdName = thirdName; } public Double getLoanMoney() { return loanMoney; } public void setLoanMoney(Double loanMoney) { this.loanMoney = loanMoney; } public Double getBorrowMoney() { return borrowMoney; } public void setBorrowMoney(Double borrowMoney) { this.borrowMoney = borrowMoney; } }
UTF-8
Java
1,519
java
PartOptionVO.java
Java
[ { "context": "i.bo.BaseBO;\n\n/**\n * 提供给资金核对的部分数据\n *\n * @Author: [ tanghaixiang ]\n * @Date: [ 2017-04-17 05:35 ]\n * @Description:", "end": 136, "score": 0.9990694522857666, "start": 124, "tag": "USERNAME", "value": "tanghaixiang" } ]
null
[]
package com.bjike.goddess.voucher.vo; import com.bjike.goddess.common.api.bo.BaseBO; /** * 提供给资金核对的部分数据 * * @Author: [ tanghaixiang ] * @Date: [ 2017-04-17 05:35 ] * @Description: [ 提供给资金核对的部分数据 ] * @Version: [ v1.0.0 ] * @Copy: [ com.bjike ] */ public class PartOptionVO extends BaseBO { /** * 一级科目名称 */ private String firstName; /** * 二级科目名称 */ private String secondName; /** * 三级科目名称 */ private String thirdName; /** * 贷方金额 */ private Double loanMoney; /** * 借方金额 */ private Double borrowMoney; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getSecondName() { return secondName; } public void setSecondName(String secondName) { this.secondName = secondName; } public String getThirdName() { return thirdName; } public void setThirdName(String thirdName) { this.thirdName = thirdName; } public Double getLoanMoney() { return loanMoney; } public void setLoanMoney(Double loanMoney) { this.loanMoney = loanMoney; } public Double getBorrowMoney() { return borrowMoney; } public void setBorrowMoney(Double borrowMoney) { this.borrowMoney = borrowMoney; } }
1,519
0.594785
0.584214
77
17.441559
16.006081
52
false
false
0
0
0
0
0
0
0.220779
false
false
13
98f003214f90ffd6af4374b319058bb094ceab55
19,138,374,334,572
f92e190d47dc9d28f09401e75015173be60b1972
/Source/dataLayer/Packet.java
cdd207b1ded6704bbd4eca0874db8b7350481bce
[]
no_license
bobor16/NordicSrc
https://github.com/bobor16/NordicSrc
110b923c2488d36cfc59f2472dab6b654fa0ee59
039b6868be96869cd28e548050384489fd209d37
refs/heads/master
2020-04-02T09:36:16.783000
2018-12-18T20:56:26
2018-12-18T20:56:26
154,300,630
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dataLayer; public class Packet implements java.io.Serializable { private int id; private Object object; //Packet class that carries objects. public Packet(){ } public Packet(int id, Object object) { this.id = id; this.object = object; } public int getId() { return this.id; } public Object getObject() { return this.object; } public void setId(int id) { this.id = id; } public void setObject(Object object) { this.object = object; } }
UTF-8
Java
560
java
Packet.java
Java
[]
null
[]
package dataLayer; public class Packet implements java.io.Serializable { private int id; private Object object; //Packet class that carries objects. public Packet(){ } public Packet(int id, Object object) { this.id = id; this.object = object; } public int getId() { return this.id; } public Object getObject() { return this.object; } public void setId(int id) { this.id = id; } public void setObject(Object object) { this.object = object; } }
560
0.578571
0.578571
32
16.5
15.348045
53
false
false
0
0
0
0
0
0
0.3125
false
false
13
290354da07ff36e10de1637f50bc45e563731f92
25,262,997,686,301
4db048132ade6f26a079f47900a4f655faf6ef04
/JiraPlugins/atlassian-jira-4.4.3-source/jira-project/jira-components/jira-core/src/main/java/com/atlassian/jira/security/roles/ProjectRoleActorsImpl.java
91bbdbb18fad3e3ed687f255dc089b2e6f420a07
[]
no_license
JCVI-VIRIFX/SampleTracking
https://github.com/JCVI-VIRIFX/SampleTracking
045f3a690161cd6735dda6cf53964a89910c2d32
8f68cf385a083dcef055605dc040a224576a16fe
refs/heads/master
2018-01-07T23:30:42.211000
2015-12-11T04:23:38
2015-12-11T04:23:38
47,804,829
1
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.atlassian.jira.security.roles; import java.util.Collection; import java.util.HashSet; import java.util.Set; /** * @see ProjectRoleActors */ public class ProjectRoleActorsImpl extends DefaultRoleActorsImpl implements ProjectRoleActors { private final Long projectId; public ProjectRoleActorsImpl(Long projectId, Long projectRoleId, Set roleActors) { super(projectRoleId, roleActors); this.projectId = projectId; } public ProjectRoleActorsImpl(Long projectId, Long projectRoleId, RoleActor roleActor) { super(projectRoleId, roleActor); this.projectId = projectId; } public Long getProjectId() { return projectId; } public DefaultRoleActors addRoleActor(RoleActor roleActor) { Set set = new HashSet(getRoleActors()); set.add(roleActor); return new ProjectRoleActorsImpl(this.projectId, getProjectRoleId(), set); } public DefaultRoleActors addRoleActors(Collection roleActors) { Set set = new HashSet(getRoleActors()); set.addAll(roleActors); return new ProjectRoleActorsImpl(this.projectId, getProjectRoleId(), set); } public DefaultRoleActors removeRoleActor(RoleActor roleActor) { Set roleActors = getRoleActors(); if (!roleActors.contains(roleActor)) { return this; } Set set = new HashSet(roleActors); set.remove(roleActor); return new ProjectRoleActorsImpl(this.projectId, getProjectRoleId(), set); } public DefaultRoleActors removeRoleActors(Collection roleActors) { Set set = new HashSet(getRoleActors()); set.removeAll(roleActors); return new ProjectRoleActorsImpl(this.projectId, getProjectRoleId(), set); } }
UTF-8
Java
1,807
java
ProjectRoleActorsImpl.java
Java
[]
null
[]
package com.atlassian.jira.security.roles; import java.util.Collection; import java.util.HashSet; import java.util.Set; /** * @see ProjectRoleActors */ public class ProjectRoleActorsImpl extends DefaultRoleActorsImpl implements ProjectRoleActors { private final Long projectId; public ProjectRoleActorsImpl(Long projectId, Long projectRoleId, Set roleActors) { super(projectRoleId, roleActors); this.projectId = projectId; } public ProjectRoleActorsImpl(Long projectId, Long projectRoleId, RoleActor roleActor) { super(projectRoleId, roleActor); this.projectId = projectId; } public Long getProjectId() { return projectId; } public DefaultRoleActors addRoleActor(RoleActor roleActor) { Set set = new HashSet(getRoleActors()); set.add(roleActor); return new ProjectRoleActorsImpl(this.projectId, getProjectRoleId(), set); } public DefaultRoleActors addRoleActors(Collection roleActors) { Set set = new HashSet(getRoleActors()); set.addAll(roleActors); return new ProjectRoleActorsImpl(this.projectId, getProjectRoleId(), set); } public DefaultRoleActors removeRoleActor(RoleActor roleActor) { Set roleActors = getRoleActors(); if (!roleActors.contains(roleActor)) { return this; } Set set = new HashSet(roleActors); set.remove(roleActor); return new ProjectRoleActorsImpl(this.projectId, getProjectRoleId(), set); } public DefaultRoleActors removeRoleActors(Collection roleActors) { Set set = new HashSet(getRoleActors()); set.removeAll(roleActors); return new ProjectRoleActorsImpl(this.projectId, getProjectRoleId(), set); } }
1,807
0.683453
0.683453
64
27.25
27.771952
93
false
false
0
0
0
0
0
0
0.59375
false
false
13
a04084f33383fa52f18834fdba9edcf153fdd988
21,741,124,516,770
d38e92d12289e9adabf9ef329a842d33f9a3b0bd
/src/proyectosa/ProyectoSA.java
f281f8cbfc29f599da227b9fc62b6323d5333ce7
[]
no_license
Luishvdiaz/Sell_Asist
https://github.com/Luishvdiaz/Sell_Asist
3cfa7c56d3e6240500185d9f58e3203f4698b7cc
c226779bf0da785679142c385fdf6fa98147eb3a
refs/heads/master
2022-07-29T15:42:54.723000
2020-05-18T04:39:38
2020-05-18T04:39:38
264,824,183
0
0
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 proyectosa; /** * * @author Luis Diaz */ public class ProyectoSA { public static int ene1=0, ene2=0, feb1=0, feb2=0, mar1=0, mar2=0, abr1=0, abr2=0, may1=0, may2=0, jun1=0, jun2=0, jul1=0, jul2=0, ago1=0, ago2=0, sep1=0, sep2=0, oct1=0, oct2=0, nov1=0, nov2=0, dic1=2, dic2=0; public static int usuario_sesion =0; /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here login n = new login(); n.setResizable(false); n.setVisible(true); n.setLocationRelativeTo(null); } }
UTF-8
Java
813
java
ProyectoSA.java
Java
[ { "context": "editor.\n */\npackage proyectosa;\n\n/**\n *\n * @author Luis Diaz\n */\npublic class ProyectoSA {\n\n public static ", "end": 233, "score": 0.9998477101325989, "start": 224, "tag": "NAME", "value": "Luis Diaz" } ]
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 proyectosa; /** * * @author <NAME> */ public class ProyectoSA { public static int ene1=0, ene2=0, feb1=0, feb2=0, mar1=0, mar2=0, abr1=0, abr2=0, may1=0, may2=0, jun1=0, jun2=0, jul1=0, jul2=0, ago1=0, ago2=0, sep1=0, sep2=0, oct1=0, oct2=0, nov1=0, nov2=0, dic1=2, dic2=0; public static int usuario_sesion =0; /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here login n = new login(); n.setResizable(false); n.setVisible(true); n.setLocationRelativeTo(null); } }
810
0.634686
0.574416
27
29.111111
41.474075
213
false
false
0
0
0
0
0
0
1.222222
false
false
13
540d884e53667456aee2642df9c4a4e935c9e71a
25,778,393,762,577
369d4f883a707b456d5c303fa820d6cd39572cb0
/src/main/java/uk/ac/leeds/ccg/projects/dw/visualisation/charts/DW_LineGraph.java
20da9483685e57dde2d8874efc7a728a6dcd3677
[]
no_license
agdturner/digital-welfare
https://github.com/agdturner/digital-welfare
530f655bc26f56b8b42963bf13708adef1c51834
0b87583670944f831a37ffbce1d01dbaa39597e2
refs/heads/master
2020-05-21T23:04:28.113000
2020-02-11T14:57:33
2020-02-11T14:57:33
27,935,369
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package uk.ac.leeds.ccg.projects.dw.visualisation.charts; import java.io.IOException; import java.math.BigDecimal; //import java.math.MathContext; import java.math.RoundingMode; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Set; //import java.util.Set; import java.util.TreeMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import uk.ac.leeds.ccg.chart.examples.Chart_Line; import uk.ac.leeds.ccg.data.ukp.util.UKP_YM3; import uk.ac.leeds.ccg.data.shbe.data.id.SHBE_ClaimID; import uk.ac.leeds.ccg.data.shbe.core.SHBE_Strings; //import uk.ac.leeds.ccg.generic.io.Generic_StaticIO; import uk.ac.leeds.ccg.generic.execution.Generic_Execution; import uk.ac.leeds.ccg.generic.util.Generic_Time; import uk.ac.leeds.ccg.generic.visualisation.Generic_Visualisation; import uk.ac.leeds.ccg.projects.dw.core.DW_Environment; import uk.ac.leeds.ccg.projects.dw.core.DW_Strings; import uk.ac.leeds.ccg.projects.dw.data.generated.DW_Table; import uk.ac.leeds.ccg.data.shbe.data.SHBE_Data; import uk.ac.leeds.ccg.data.shbe.data.SHBE_TenancyType; import uk.ac.leeds.ccg.projects.dw.data.uo.DW_UO_Data; import uk.ac.leeds.ccg.projects.dw.data.uo.DW_UO_Handler; import uk.ac.leeds.ccg.projects.dw.io.DW_Files; /** * @author Andy Turner * @version 1.0.0 */ public class DW_LineGraph extends Chart_Line { protected final transient DW_Environment env; protected final transient DW_Files files; protected final transient SHBE_Data shbeData; protected final transient DW_UO_Handler uoHandler; protected final transient DW_UO_Data uoData; /** * Area Codes */ HashMap<String, HashSet<String>> ac; public DW_LineGraph(DW_Environment de) throws IOException, Exception { super(de.ge); this.env = de; this.files = de.files; this.shbeData = de.getShbeData(); this.uoData = de.getUoData(); this.uoHandler = de.getUoHandler(); } public DW_LineGraph(DW_Environment de, ExecutorService es, Path file, String format, String title, int dataWidth, int dataHeight, String xAxisLabel, String yAxisLabel, BigDecimal yMax, ArrayList<BigDecimal> yPin, BigDecimal yIncrement, int numberOfYAxisTicks, int decimalPlacePrecisionForCalculations, int decimalPlacePrecisionForDisplay, RoundingMode rm) throws IOException, Exception { super(de.ge, es, file, format, title, dataWidth, dataHeight, xAxisLabel, yAxisLabel, yMax, yPin, yIncrement, numberOfYAxisTicks, true, decimalPlacePrecisionForCalculations, decimalPlacePrecisionForDisplay, rm); this.env = de; this.files = de.files; this.shbeData = de.getShbeData(); this.uoData = de.getUoData(); this.uoHandler = de.getUoHandler(); } HashSet<Future> futures; ArrayList<Boolean> b; String[] SHBEFilenames; TreeMap<String, ArrayList<Integer>> includes; ArrayList<String> PTs; /** * * @param doGraphTenancyTypeTransitions * @param doGraphAggregateData */ public void run( boolean doGraphTenancyTypeTransitions, boolean doGraphAggregateData) throws IOException, Exception { env.ge.log("<run>"); vis.getHeadlessEnvironment(); dataWidth = 1300; dataHeight = 500; xAxisLabel = "Time Periods"; // setyPin(BigDecimal.ZERO); // yMax = new BigDecimal(700); // yIncrement = BigDecimal.TEN; // yIncrement = BigDecimal.ONE; //int yAxisStartOfEndInterval = 60; decimalPlacePrecisionForCalculations = 20; decimalPlacePrecisionForDisplay = 3; roundingMode = RoundingMode.HALF_UP; // mc = new MathContext(decimalPlacePrecisionForCalculations, roundingMode); numberOfYAxisTicks = 10; executorService = Executors.newSingleThreadExecutor(); SHBEFilenames = shbeData.getFilenames(); // ArrayList<String> claimantTypes; // claimantTypes = DW_Strings.getHB_CTB(); includes = shbeData.getIncludes(); includes.remove(SHBE_Strings.s_IncludeAll); includes.remove(SHBE_Strings.s_IncludeYearly); includes.remove(SHBE_Strings.s_Include6Monthly); includes.remove(SHBE_Strings.s_Include3Monthly); includes.remove(SHBE_Strings.s_IncludeMonthly); // includes.remove(DW_SHBE_Strings.s_IncludeMonthlySinceApril2013); includes.remove(SHBE_Strings.s_Include2MonthlySinceApril2013Offset0); includes.remove(SHBE_Strings.s_Include2MonthlySinceApril2013Offset1); includes.remove(SHBE_Strings.s_IncludeStartEndSinceApril2013); includes.remove(SHBE_Strings.s_IncludeApril2013May2013); futures = new HashSet<>(); format = "PNG"; // ArrayList<String> types; // types = new ArrayList<String>(); // types.add(DW_Files.sPostcodeChanged); // types.add(sPostcodeChangedNo); // types.add("Multiple"); // types.add(""); PTs = SHBE_Strings.getPaymentTypes(); // PTs.remove(shbeData.sPaymentTypeAll); PTs.remove(SHBE_Strings.s_PaymentTypeIn); PTs.remove(SHBE_Strings.s_PaymentTypeSuspended); PTs.remove(SHBE_Strings.s_PaymentTypeOther); b = new ArrayList<>(); b.add(true); b.add(false); // if (doGraphTenancyTypeTransitions) { // graphTenancyTypeTransitions(); // } if (doGraphAggregateData) { graphAggregateData(); } } protected void graphAggregateData() throws IOException, Exception { DW_Table table = new DW_Table(env); ArrayList<String> AZs; // AggregatedZones AZs = new ArrayList<>(); // AZs.add(DW_Strings.sParliamentaryConstituency); AZs.add(DW_Strings.sStatisticalWard); // AZs.add(DW_Strings.sLSOA); // AZs.add(DW_Strings.sMSOA); Iterator<String> ptIte = PTs.iterator(); while (ptIte.hasNext()) { String pt = ptIte.next(); Path dirIn = Paths.get(files.getOutputSHBETablesDir().toString(), DW_Strings.sHBGeneralAggregateStatistics, pt); Path dirOut = Paths.get(files.getOutputSHBEPlotsDir().toString(), DW_Strings.sHBGeneralAggregateStatistics, pt); Iterator<String> iIte = includes.keySet().iterator(); while (iIte.hasNext()) { String includeName = iIte.next(); ArrayList<Integer> include = includes.get(includeName); Iterator<String> AZsIte = AZs.iterator(); while (AZsIte.hasNext()) { String AZ = AZsIte.next(); Path dirIn1 = Paths.get(dirIn.toString(), AZ); Path dirOut1; dirOut1 = Paths.get(dirOut.toString(), AZ); dirOut1 = Paths.get(dirOut1.toString(), includeName); //dirOut1.mkdirs(); Path fout; for (int stat = 1; stat <= 8; stat++) { String filename; switch (stat) { case 1: filename = "NumberOfHBClaims.PNG"; yAxisLabel = "Number Of Housing Benefit Claims"; title = yAxisLabel + " Over Time"; break; case 2: filename = "NumberOfChildDependentsInHBClaimingHouseholds.PNG"; yAxisLabel = "Number Of Child Dependents In HB Claiming Households"; title = yAxisLabel + " Over Time"; break; case 3: filename = "TotalPopulationInHBClaimingHouseholds.PNG"; yAxisLabel = "Total Population In HB Claiming Households"; title = yAxisLabel + " Over Time"; break; case 4: filename = "NumberOfUOHouseholdsRequiring1Room.PNG"; yAxisLabel = "Number Of UO Households Requiring 1 Room"; title = yAxisLabel + " Over Time"; break; case 5: filename = "NumberOfUOHouseholdsRequiring2Rooms.PNG"; yAxisLabel = "Number Of UO Households Requiring 2 Rooms"; title = yAxisLabel + " Over Time"; break; case 6: filename = "NumberOfUOHouseholdsRequiring3Rooms.PNG"; yAxisLabel = "Number Of UO Households Requiring 3 Rooms"; title = yAxisLabel + " Over Time"; break; case 7: filename = "NumberOfUOHouseholdsRequiring4Rooms.PNG"; yAxisLabel = "Number Of UO Households Requiring 4 Rooms"; title = yAxisLabel + " Over Time"; break; default: filename = "NumberOfUOHouseholdsRequiring5OrMoreRooms.PNG"; yAxisLabel = "Number Of UO Households Requiring 5 Or More Rooms"; title = yAxisLabel + " Over Time"; break; } fout = Paths.get(dirOut1.toString(), filename); TreeMap<String, TreeMap<UKP_YM3, BigDecimal>> data0 = new TreeMap<>(); Iterator<Integer> includeIte = include.iterator(); while (includeIte.hasNext()) { int i = includeIte.next(); UKP_YM3 YM3; YM3 = shbeData.getYM3(SHBEFilenames[i]); Path f = Paths.get(dirIn1.toString(), YM3 + ".csv"); // readCSV ArrayList<String> lines = table.readCSV(f); Iterator<String> ite = lines.iterator(); String line; String[] fields; String header = ite.next(); String[] headerFields = header.split(DW_Strings.special_commaSpace); /* * AreaCode, NumberOfHBClaims, * NumberOfChildDependentsInHBClaimingHouseholds, * TotalPopulationInHBClaimingHouseholds, * NumberOfUOHouseholdsRequiring1Room, * NumberOfUOHouseholdsRequiring2Rooms, * NumberOfUOHouseholdsRequiring3Rooms, * NumberOfUOHouseholdsRequiring4Rooms, * NumberOfUOHouseholdsRequiring5OrMoreRooms */ while (ite.hasNext()) { line = ite.next(); //System.out.println(line); fields = line.split(DW_Strings.special_commaSpace); TreeMap<UKP_YM3, BigDecimal> dateValue; dateValue = data0.get(fields[0]); if (dateValue == null) { dateValue = new TreeMap<>(); data0.put(fields[0], dateValue); } dateValue.put(YM3, new BigDecimal(fields[stat])); } } DW_LineGraph chart = new DW_LineGraph(env, executorService, fout, format, title, getDataWidth(), getDataHeight(), xAxisLabel, yAxisLabel, yMax, yPin, yIncrement, numberOfYAxisTicks, decimalPlacePrecisionForCalculations, decimalPlacePrecisionForDisplay, getRoundingMode()); // Object[] TreeMapDateLabelSHBEFilename; TreeMapDateLabelSHBEFilename = shbeData.getTreeMapDateLabelSHBEFilenamesSingle( SHBEFilenames, include); TreeMap<BigDecimal, UKP_YM3> xAxisLabels; xAxisLabels = (TreeMap<BigDecimal, UKP_YM3>) TreeMapDateLabelSHBEFilename[0]; TreeMap<UKP_YM3, BigDecimal> fileLabelValue; fileLabelValue = (TreeMap<UKP_YM3, BigDecimal>) TreeMapDateLabelSHBEFilename[1]; Object[] data; data = getData(data0, xAxisLabels, fileLabelValue); // HashSet<String> selection = allSelections.get(selections); // data = getData(bigMatrix,selection,xAxisLabels); if (data != null) { chart.setData(data); chart.run(); future = chart.future; futures.add(future); } else { futures.add(chart.future); } } } } } } protected void graphTenancyTypeTransitions() throws IOException, Exception { ArrayList<String> month3Letters; month3Letters = Generic_Time.getMonths3Letters(); // Init allSelections of different types of tenancy type transitions to graph. HashMap<Boolean, HashMap<Boolean, HashMap<Boolean, TreeMap<String, HashSet<String>>>>> allSelections; allSelections = new HashMap<>(); // Init allSelections of different types of tenancy type transitions to graph. HashMap<Boolean, HashMap<Boolean, HashMap<Boolean, TreeMap<String, HashSet<String>>>>> allSelectionsGrouped; allSelectionsGrouped = new HashMap<>(); Iterator<Boolean> iteB; iteB = b.iterator(); while (iteB.hasNext()) { boolean do999; do999 = iteB.next(); HashMap<Boolean, HashMap<Boolean, TreeMap<String, HashSet<String>>>> asss; asss = new HashMap<>(); HashMap<Boolean, HashMap<Boolean, TreeMap<String, HashSet<String>>>> asssg; asssg = new HashMap<>(); Iterator<Boolean> iteB2; iteB2 = b.iterator(); while (iteB2.hasNext()) { boolean doUnderOccupancy; doUnderOccupancy = iteB2.next(); HashMap<Boolean, TreeMap<String, HashSet<String>>> ass; ass = new HashMap<>(); HashMap<Boolean, TreeMap<String, HashSet<String>>> assg; assg = new HashMap<>(); TreeMap<String, HashSet<String>> as; TreeMap<String, HashSet<String>> asg; Iterator<Boolean> iteB3; iteB3 = b.iterator(); while (iteB3.hasNext()) { boolean doSameTenancy; doSameTenancy = iteB3.next(); as = getAllSelections( doUnderOccupancy, do999, doSameTenancy); ass.put(doSameTenancy, as); asg = getAllSelectionsGrouped( doUnderOccupancy, do999, doSameTenancy); assg.put(doSameTenancy, asg); } asss.put(doUnderOccupancy, ass); asssg.put(doUnderOccupancy, assg); } allSelections.put(do999, asss); allSelectionsGrouped.put(do999, asssg); } Set<SHBE_ClaimID> UOApril2013ClaimIDs; UOApril2013ClaimIDs = uoHandler.getUOStartApril2013ClaimIDs(uoData); boolean CheckPreviousTenancyType; //// checkPreviousTenure = false; // checkPreviousTenure = false; iteB = b.iterator(); while (iteB.hasNext()) { CheckPreviousTenancyType = iteB.next(); env.ge.log("CheckPreviousTenancyType " + CheckPreviousTenancyType); Path dirIn; dirIn = files.getOutputSHBETablesTenancyTypeTransitionDir( //DW_DW_Strings.sPaymentTypeAll, CheckPreviousTenancyType); Path dirOut; dirOut = files.getOutputSHBEPlotsTenancyTypeTransitionDir( //DW_DW_Strings.sAll, CheckPreviousTenancyType); boolean tenancyOnly; // tenancyOnly = false; // Switch for testing. Iterator<Boolean> iteB1; iteB1 = b.iterator(); while (iteB1.hasNext()) { tenancyOnly = iteB1.next(); if (tenancyOnly) { Path dirIn2 = Paths.get( dirIn.toString(), DW_Strings.sWithOrWithoutPostcodeChange); Path dirOut2 = Paths.get( dirOut.toString(), DW_Strings.sWithOrWithoutPostcodeChange); Iterator<Boolean> iteB2; iteB2 = b.iterator(); boolean doUnderOccupancyData; // doUnderOccupancyData = false; // Switch for testing. Iterator<String> includesIte = includes.keySet().iterator(); while (includesIte.hasNext()) { String includeKey = includesIte.next(); ArrayList<Integer> include = includes.get(includeKey); Path dirIn3 = Paths.get(dirIn2.toString(), includeKey); Path dirOut3 = Paths.get(dirOut2.toString(), includeKey); /** * It is thought this should be a choice between doing * All or doing only those that were UO in April 2013. * This needs checking! */ dirIn3 = Paths.get(dirIn2.toString(), DW_Strings.sAll); dirOut3 = Paths.get(dirOut2.toString(), DW_Strings.sAll); while (iteB2.hasNext()) { doUnderOccupancyData = iteB2.next(); if (doUnderOccupancyData) { // boolean DoUOOnlyOnThoseOriginallyUO; // env.logO("<DoUOOnlyOnThoseOriginallyUO " + DoUOOnlyOnThoseOriginallyUO + ">", true); // Set<SHBE_ClaimID> UOApril2013ClaimIDsDummy; // if (DoUOOnlyOnThoseOriginallyUO) { // UOApril2013ClaimIDsDummy = UOApril2013ClaimIDs; // } else { // UOApril2013ClaimIDsDummy = null; // } Path dirIn4 = Paths.get(dirIn3.toString(), DW_Strings.sU); Path dirOut4 = Paths.get(dirOut3.toString(), DW_Strings.sU); Path dirIn5; Path dirOut5; boolean doAll = true; if (doAll) { dirIn5 = Paths.get(dirIn4.toString(), DW_Strings.s_B); dirOut5 = Paths.get(dirOut4.toString(), DW_Strings.s_B); Iterator<Boolean> iteB4; iteB4 = b.iterator(); while (iteB4.hasNext()) { boolean do999 = iteB4.next(); Path dirOut6; if (do999) { dirOut6 = Paths.get(dirOut5.toString(), DW_Strings.sInclude999); Iterator<Boolean> iteB5; iteB5 = b.iterator(); while (iteB5.hasNext()) { boolean doSameTenancy; doSameTenancy = iteB5.next(); Path dirOut7; if (doSameTenancy) { dirOut7 = Paths.get(dirOut6.toString(), SHBE_Strings.s_IncludeSameTenancy); } else { dirOut7 = Paths.get(dirOut6.toString(), SHBE_Strings.s_NotIncludeSameTenancy); } Iterator<Boolean> iteB6; iteB6 = b.iterator(); while (iteB6.hasNext()) { boolean grouped; grouped = iteB6.next(); if (grouped) { doSumat(dirIn5, dirOut7, include, includeKey, allSelectionsGrouped.get(doSameTenancy).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } else { doSumat(dirIn5, dirOut7, include, includeKey, allSelections.get(doSameTenancy).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } } } } else { dirOut6 = Paths.get(dirOut5.toString(), DW_Strings.sExclude999); Iterator<Boolean> iteB5; iteB5 = b.iterator(); while (iteB5.hasNext()) { boolean doSameTenancy; doSameTenancy = iteB5.next(); Path dirOut7; if (doSameTenancy) { dirOut7 = Paths.get(dirOut6.toString(), SHBE_Strings.s_IncludeSameTenancy); } else { dirOut7 = Paths.get(dirOut6.toString(), SHBE_Strings.s_NotIncludeSameTenancy); } Iterator<Boolean> iteB6; iteB6 = b.iterator(); while (iteB6.hasNext()) { boolean grouped; grouped = iteB6.next(); if (grouped) { doSumat(dirIn5, dirOut7, include, includeKey, allSelectionsGrouped.get(doSameTenancy).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } else { doSumat(dirIn5, dirOut7, include, includeKey, allSelections.get(doSameTenancy).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } } } } } } boolean doCouncilRSL = false; if (doCouncilRSL) { Iterator<Boolean> iteB3; iteB3 = b.iterator(); while (iteB3.hasNext()) { boolean doCouncil; doCouncil = iteB3.next(); if (doCouncil) { dirIn5 = Paths.get(dirIn4.toString(), DW_Strings.sCouncil); dirOut5 = Paths.get(dirOut4.toString(), DW_Strings.sCouncil); } else { dirIn5 = Paths.get(dirIn4.toString(), DW_Strings.sRSL); dirOut5 = Paths.get(dirOut4.toString(), DW_Strings.sRSL); } Iterator<Boolean> iteB4; iteB4 = b.iterator(); while (iteB4.hasNext()) { boolean do999 = iteB4.next(); Path dirOut6; if (do999) { dirOut6 = Paths.get(dirOut5.toString(), DW_Strings.sInclude999); Iterator<Boolean> iteB5 = b.iterator(); while (iteB5.hasNext()) { boolean doSameTenancy; doSameTenancy = iteB5.next(); Path dirOut7; if (doSameTenancy) { dirOut7 = Paths.get(dirOut6.toString(), SHBE_Strings.s_IncludeSameTenancy); } else { dirOut7 = Paths.get(dirOut6.toString(), SHBE_Strings.s_NotIncludeSameTenancy); } Iterator<Boolean> iteB6; iteB6 = b.iterator(); while (iteB6.hasNext()) { boolean grouped; grouped = iteB6.next(); if (grouped) { doSumat(dirIn5, dirOut7, include, includeKey, allSelectionsGrouped.get(doSameTenancy).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } else { doSumat( dirIn5, dirOut7, include, includeKey, allSelections.get(doSameTenancy).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } } } } else { dirOut6 = Paths.get(dirOut5.toString(), DW_Strings.sExclude999); Iterator<Boolean> iteB5; iteB5 = b.iterator(); while (iteB5.hasNext()) { boolean doSameTenancy; doSameTenancy = iteB5.next(); Path dirOut7; if (doSameTenancy) { dirOut7 = Paths.get(dirOut6.toString(), SHBE_Strings.s_IncludeSameTenancy); } else { dirOut7 = Paths.get(dirOut6.toString(), SHBE_Strings.s_NotIncludeSameTenancy); } Iterator<Boolean> iteB6; iteB6 = b.iterator(); while (iteB6.hasNext()) { boolean grouped; grouped = iteB6.next(); if (grouped) { doSumat(dirIn5, dirOut7, include, includeKey, allSelectionsGrouped.get(doSameTenancy).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } else { doSumat( dirIn5, dirOut7, include, includeKey, allSelections.get(doSameTenancy).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } } } } } } } } else { Path dirIn4 = Paths.get(dirIn3.toString(), DW_Strings.sU); Path dirOut4 = Paths.get(dirOut3.toString(), DW_Strings.sU); boolean doBoth = true; if (doBoth) { Path dirIn5 = Paths.get(dirIn4.toString(), DW_Strings.s_B); Path dirOut5 = Paths.get(dirOut4.toString(), DW_Strings.s_B); Iterator<Boolean> iteB3; iteB3 = b.iterator(); while (iteB3.hasNext()) { boolean do999 = iteB3.next(); Path dirOut6; if (do999) { dirOut6 = Paths.get(dirOut5.toString(), DW_Strings.sInclude999); Iterator<Boolean> iteB4; iteB4 = b.iterator(); while (iteB4.hasNext()) { boolean grouped; grouped = iteB4.next(); if (grouped) { doSumat(dirIn5, dirOut6, include, includeKey, allSelectionsGrouped.get(false).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } else { doSumat(dirIn5, dirOut4, include, includeKey, allSelections.get(false).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } } } else { dirOut6 = Paths.get(dirOut5.toString(), DW_Strings.sExclude999); Iterator<Boolean> iteB4; iteB4 = b.iterator(); while (iteB4.hasNext()) { boolean grouped; grouped = iteB4.next(); if (grouped) { doSumat(dirIn5, dirOut6, include, includeKey, allSelectionsGrouped.get(false).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } else { doSumat(dirIn5, dirOut6, include, includeKey, allSelections.get(false).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } } } } } } } } } else { Path dirIn2 = Paths.get(dirIn.toString(), DW_Strings.sTenancyAndPostcodeChanges); Path dirOut2 = Paths.get(dirOut.toString(), DW_Strings.sTenancyAndPostcodeChanges); Iterator<String> includesIte = includes.keySet().iterator(); while (includesIte.hasNext()) { String includeKey = includesIte.next(); ArrayList<Integer> include = includes.get(includeKey); Path dirIn3; Path dirOut3; dirIn3 = Paths.get(dirIn2.toString(), includeKey); dirOut3 = Paths.get(dirOut2.toString(), includeKey); /** * It is thought this should be a choice between doing * All or doing only those that were UO in April 2013. * This needs checking! */ dirIn3 = Paths.get(dirIn2.toString(), DW_Strings.sAll); dirOut3 = Paths.get(dirOut2.toString(), DW_Strings.sAll); boolean doUnderOccupancyData; // doUnderOccupancyData = false; Iterator<Boolean> iteB2; iteB2 = b.iterator(); while (iteB2.hasNext()) { doUnderOccupancyData = iteB2.next(); if (doUnderOccupancyData) { Path dirIn4; Path dirOut4; dirIn4 = Paths.get(dirIn3.toString(), DW_Strings.sU); dirOut4 = Paths.get(dirOut3.toString(), DW_Strings.sU); boolean doBoth; doBoth = true; if (doBoth) { Path dirIn5; Path dirOut5; dirIn5 = Paths.get(dirIn4.toString(), DW_Strings.s_B); dirOut5 = Paths.get(dirOut4.toString(), DW_Strings.s_B); // Iterator<String> includesIte; // includesIte = includes.keySet().iterator(); // while (includesIte.hasNext()) { // String include; // include = includesIte.next(); // Path dirIn5; // Path dirOut5; // dirIn5 = Paths.get(dirIn4, include); // dirOut5 = Paths.get(dirOut4, include); // } Iterator<Boolean> iteB4 = b.iterator(); while (iteB4.hasNext()) { boolean grouped = iteB4.next(); Iterator<Boolean> iteB5 = b.iterator(); while (iteB5.hasNext()) { boolean postcodeChanged = iteB5.next(); Path dirIn6; Path dirOut6; if (postcodeChanged) { dirIn6 = Paths.get(dirIn5.toString(), DW_Strings.sPostcodeChanged); dirOut6 = Paths.get(dirOut5.toString(), DW_Strings.sPostcodeChanged); } else { dirIn6 = Paths.get(dirIn5.toString(), DW_Strings.sPostcodeChangedNo); dirOut6 = Paths.get(dirOut5.toString(), DW_Strings.sPostcodeChangedNo); } Iterator<Boolean> iteB6; iteB6 = b.iterator(); while (iteB6.hasNext()) { boolean do999 = iteB6.next(); Path dirOut7; if (do999) { dirOut7 = Paths.get(dirOut6.toString(), DW_Strings.sInclude999); Iterator<Boolean> iteB7; iteB7 = b.iterator(); while (iteB7.hasNext()) { boolean doSameTenancy; doSameTenancy = iteB7.next(); Path dirOut8; if (doSameTenancy) { dirOut8 = Paths.get(dirOut7.toString(), SHBE_Strings.s_IncludeSameTenancy); } else { dirOut8 = Paths.get(dirOut7.toString(), SHBE_Strings.s_NotIncludeSameTenancy); } if (grouped) { doSumat(dirIn6, dirOut8, include, includeKey, allSelectionsGrouped.get(doSameTenancy).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } else { doSumat(dirIn6, dirOut8, include, includeKey, allSelections.get(doSameTenancy).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } } } else { dirOut7 = Paths.get(dirOut6.toString(), DW_Strings.sExclude999); Iterator<Boolean> iteB7; iteB7 = b.iterator(); while (iteB7.hasNext()) { boolean doSameTenancy; doSameTenancy = iteB7.next(); Path dirOut8; if (doSameTenancy) { dirOut8 = Paths.get(dirOut7.toString(), SHBE_Strings.s_IncludeSameTenancy); } else { dirOut8 = Paths.get(dirOut7.toString(), SHBE_Strings.s_NotIncludeSameTenancy); } if (grouped) { doSumat(dirIn6, dirOut8, include, includeKey, allSelectionsGrouped.get(doSameTenancy).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } else { doSumat(dirIn6, dirOut8, include, includeKey, allSelections.get(doSameTenancy).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } } } } } } } Iterator<Boolean> iteB3; iteB3 = b.iterator(); while (iteB3.hasNext()) { boolean doCouncil; doCouncil = iteB3.next(); if (doCouncil) { dirIn4 = Paths.get(dirIn3.toString(), DW_Strings.sCouncil); dirOut4 = Paths.get(dirOut3.toString(), DW_Strings.sCouncil); } else { dirIn4 = Paths.get(dirIn3.toString(), DW_Strings.sRSL); dirOut4 = Paths.get(dirOut3.toString(), DW_Strings.sRSL); } Iterator<Boolean> iteB4; iteB4 = b.iterator(); while (iteB4.hasNext()) { boolean grouped; grouped = iteB4.next(); Path dirIn5; Path dirOut5; if (grouped) { dirIn5 = Paths.get(dirIn4.toString(), DW_Strings.sGrouped); dirOut5 = Paths.get(dirOut4.toString(), DW_Strings.sGrouped); } else { dirIn5 = Paths.get(dirIn4.toString(), DW_Strings.sGroupedNo); dirOut5 = Paths.get(dirOut4.toString(), DW_Strings.sGroupedNo); } Iterator<Boolean> iteB5 = b.iterator(); while (iteB5.hasNext()) { boolean postcodeChanged = iteB5.next(); Path dirIn6; Path dirOut6; if (postcodeChanged) { dirIn6 = Paths.get(dirIn5.toString(), DW_Strings.sPostcodeChanged); dirOut6 = Paths.get(dirOut5.toString(), DW_Strings.sPostcodeChanged); } else { dirIn6 = Paths.get(dirIn5.toString(), DW_Strings.sPostcodeChangedNo); dirOut6 = Paths.get(dirOut5.toString(), DW_Strings.sPostcodeChangedNo); } Iterator<Boolean> iteB6; iteB6 = b.iterator(); while (iteB6.hasNext()) { boolean do999 = iteB6.next(); Path dirOut7; if (do999) { dirOut7 = Paths.get(dirOut6.toString(), DW_Strings.sInclude999); Iterator<Boolean> iteB7; iteB7 = b.iterator(); while (iteB7.hasNext()) { boolean doSameTenancy; doSameTenancy = iteB7.next(); Path dirOut8; if (doSameTenancy) { dirOut8 = Paths.get(dirOut7.toString(), SHBE_Strings.s_IncludeSameTenancy); } else { dirOut8 = Paths.get(dirOut7.toString(), SHBE_Strings.s_NotIncludeSameTenancy); } if (grouped) { doSumat(dirIn6, dirOut8, include, includeKey, allSelectionsGrouped.get(doSameTenancy).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } else { doSumat(dirIn6, dirOut8, include, includeKey, allSelections.get(doSameTenancy).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } } } else { dirOut7 = Paths.get(dirOut6.toString(), DW_Strings.sExclude999); Iterator<Boolean> iteB7; iteB7 = b.iterator(); while (iteB7.hasNext()) { boolean doSameTenancy; doSameTenancy = iteB7.next(); Path dirOut8; if (doSameTenancy) { dirOut8 = Paths.get(dirOut7.toString(), SHBE_Strings.s_IncludeSameTenancy); } else { dirOut8 = Paths.get(dirOut7.toString(), SHBE_Strings.s_NotIncludeSameTenancy); } if (grouped) { doSumat(dirIn6, dirOut8, include, includeKey, allSelectionsGrouped.get(doSameTenancy).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } else { doSumat(dirIn6, dirOut8, include, includeKey, allSelections.get(doSameTenancy).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } } } } } } } } else { Path dirIn4; Path dirOut4; dirIn4 = Paths.get(dirIn3.toString(), DW_Strings.sAll); dirOut4 = Paths.get(dirOut3.toString(), DW_Strings.sAll); Iterator<Boolean> iteB3; iteB3 = b.iterator(); while (iteB3.hasNext()) { boolean grouped = iteB3.next(); Iterator<Boolean> iteB4 = b.iterator(); while (iteB4.hasNext()) { boolean postcodeChanged = iteB4.next(); Path dirIn5; Path dirOut5; if (postcodeChanged) { dirIn5 = Paths.get(dirIn4.toString(), DW_Strings.sPostcodeChanged); dirOut5 = Paths.get(dirOut4.toString(), DW_Strings.sPostcodeChanged); } else { dirIn5 = Paths.get(dirIn4.toString(), DW_Strings.sPostcodeChangedNo); dirOut5 = Paths.get(dirOut4.toString(), DW_Strings.sPostcodeChangedNo); } Iterator<Boolean> iteB5; iteB5 = b.iterator(); while (iteB5.hasNext()) { boolean do999 = iteB5.next(); Path dirOut6; if (do999) { dirOut6 = Paths.get(dirOut5.toString(), DW_Strings.sInclude999); if (grouped) { doSumat(dirIn5, dirOut6, include, includeKey, allSelectionsGrouped.get(false).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } else { doSumat(dirIn5, dirOut6, include, includeKey, allSelections.get(false).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } } else { dirOut6 = Paths.get(dirOut5.toString(), DW_Strings.sExclude999); if (grouped) { doSumat(dirIn5, dirOut6, include, includeKey, allSelectionsGrouped.get(false).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } else { doSumat(dirIn5, dirOut6, include, includeKey, allSelections.get(false).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } } } } } } } } } } } exec.shutdownExecutorService(executorService, futures, this); env.ge.log("</run>"); } private void doSumat(Path dirIn, Path dirOut, ArrayList<Integer> include, String includeKey, TreeMap<String, HashSet<String>> allSelections, HashSet<Future> futures, String format, String[] SHBEFilenames, boolean grouped, ArrayList<String> month3Letters) throws IOException, Exception { // Iterator<String> includesIte; // includesIte = includes.keySet().iterator(); // while (includesIte.hasNext()) { // String includeKey; // includeKey = includesIte.next(); // Path dirIn2; // dirIn2 = Paths.get( dirIn, includeKey); //// doneFirsts.put(includeKey, false); // ArrayList<Integer> include; // include = includes.get(includeKey); Object[] treeMapDateLabelSHBEFilename; treeMapDateLabelSHBEFilename = shbeData.getTreeMapDateLabelSHBEFilenames( SHBEFilenames, include); TreeMap<BigDecimal, String> xAxisLabels; xAxisLabels = (TreeMap<BigDecimal, String>) treeMapDateLabelSHBEFilename[0]; TreeMap<String, BigDecimal> fileLabelValue; fileLabelValue = (TreeMap<String, BigDecimal>) treeMapDateLabelSHBEFilename[1]; TreeMap<BigDecimal, TreeMap<String, TreeMap<String, BigDecimal>>> bigMatrix; bigMatrix = new TreeMap<>(); // int size = Integer.MIN_VALUE; // Double min = Double.MAX_VALUE; // Double max = Double.MIN_VALUE; boolean doneFirst; doneFirst = false; UKP_YM3 YM30 = null; String yM30 = ""; Iterator<Integer> includeIte; includeIte = include.iterator(); while (includeIte.hasNext()) { int i = includeIte.next(); if (!doneFirst) { if (include.contains(i - 1) && (i - 1) >= 0) { String aSHBEFilename0; aSHBEFilename0 = SHBEFilenames[i - 1]; YM30 = shbeData.getYM3(aSHBEFilename0); yM30 = YM30.toString(); doneFirst = true; } } if (doneFirst) { String aSHBEFilename1; aSHBEFilename1 = SHBEFilenames[i]; UKP_YM3 YM31; YM31 = shbeData.getYM3(aSHBEFilename1); String yM31; yM31 = YM31.toString(); String filename; filename = DW_Strings.sTenancyTypeTransition + "_Start_" + YM30 + "_End_" + YM31 + ".csv"; if (include.contains(i)) { Path dirIn3; double timeDiff; timeDiff = Generic_Time.getMonthDiff(YM30.getYear(), YM31.getYear(), YM30.getMonth(), YM31.getMonth()); String label; label = getLabel(yM30, yM31); BigDecimal key; key = fileLabelValue.get(label); if (grouped) { // dirIn3 = Paths.get(dirIn, DW_DW_Strings.sAll); dirIn3 = Paths.get(dirIn.toString(), DW_Strings.sGrouped); Path f = Paths.get(dirIn3.toString(), filename); if (Files.exists(f)) { System.out.println("Using file " + f); TreeMap<String, TreeMap<String, BigDecimal>> tttmg; tttmg = getTenancyTypeTransitionMapGrouped( f, timeDiff); if (key != null) { bigMatrix.put(key, tttmg); } else { System.out.println("No value for label " + label); } } else { System.out.println(f + " does not exist"); } } else { // dirIn3 = Paths.get(dirIn, DW_DW_Strings.sAll); dirIn3 = Paths.get(dirIn.toString(), DW_Strings.sGroupedNo); Path f = Paths.get(dirIn3.toString(), filename); if (Files.exists(f)) { System.out.println("Using file " + f); // TenancyTypeBefore, TenancyTypeNow Counts. TreeMap<String, TreeMap<String, BigDecimal>> tenancyTypeTransitionMap; tenancyTypeTransitionMap = getTenancyTypeTransitionMap( f, timeDiff); // Object[] tenancyTypeTransitionMatrixMinMaxSize; // tenancyTypeTransitionMatrixMinMaxSize = getTenancyTypeTransitionMap( // f, // timeDiff); // tenancyTypeTransitionMap = (TreeMap<Integer, TreeMap<Integer, BigDecimal>>) tenancyTypeTransitionMatrixMinMaxSize[0]; // Double tenancyTypeTransitionMatrixMin; // tenancyTypeTransitionMatrixMin = (Double) tenancyTypeTransitionMatrixMinMaxSize[1]; // min = Math.min(tenancyTypeTransitionMatrixMin, min); // Double tenancyTypeTransitionMatrixMax; // tenancyTypeTransitionMatrixMax = (Double) tenancyTypeTransitionMatrixMinMaxSize[2]; // max = Math.max(tenancyTypeTransitionMatrixMax, max); // size = Math.max(size, (Integer) tenancyTypeTransitionMatrixMinMaxSize[3]); //System.out.println("fileLabel " + fileLabel); //System.out.println("key " + key); if (key != null) { bigMatrix.put(key, tenancyTypeTransitionMap); // System.out.println("max " + max); // System.out.println("min " + min); // System.out.println("size " + size); } else { System.out.println("No value for label " + label); } } else { System.out.println(f + " does not exist"); } } YM30 = YM31; yM30 = YM30.toString(); } else { System.out.println("Omitted file " + filename); } } } if (!bigMatrix.isEmpty()) { Path dirOut2 = Paths.get(dirOut.toString(), includeKey); if (grouped) { dirOut2 = Paths.get(dirOut2.toString(), DW_Strings.sGrouped); } else { dirOut2 = Paths.get(dirOut2.toString(), DW_Strings.sGroupedNo); } Iterator<String> allSelectionsIte = allSelections.keySet().iterator(); while (allSelectionsIte.hasNext()) { String selections = allSelectionsIte.next(); //dirOut2.mkdirs(); // only make if there is result. Path fout; fout = Paths.get(dirOut2.toString(), DW_Strings.sTenancyTypeTransitionLineGraph + selections + ".PNG"); yAxisLabel = "Tenancy Changes Per Month"; title = "Tenancy Transition Line Graph"; DW_LineGraph chart = new DW_LineGraph(env, executorService, fout, format, title, getDataWidth(), getDataHeight(), xAxisLabel, yAxisLabel, yMax, yPin, yIncrement, numberOfYAxisTicks, decimalPlacePrecisionForCalculations, decimalPlacePrecisionForDisplay, getRoundingMode()); HashSet<String> selection = allSelections.get(selections); data = getData(bigMatrix, selection, xAxisLabels); if (data != null) { BigDecimal newMinY; newMinY = (BigDecimal) data[1]; BigDecimal newMaxY; newMaxY = (BigDecimal) data[2]; if (newMaxY.compareTo(new BigDecimal(Double.MIN_VALUE)) != 1) { if (newMinY.compareTo(newMaxY) == 1) { env.ge.log("newMinY.compareTo(newMaxY) == 1 so no graph is produced."); } else { Files.createDirectories(dirOut2); chart.setData(data); //chart.run(); future = chart.future; futures.add(future); } } else { env.ge.log("No values, so no graph is produced."); } } else { //futures.add(chart.future); } } } //} } /** * @param doUnderOccupancy * @param do999 * @param sameTenancyType * @return */ protected TreeMap<String, HashSet<String>> getAllSelections( boolean doUnderOccupancy, boolean do999, boolean sameTenancyType) { TreeMap<String, HashSet<String>> result; result = new TreeMap<>(); String selectionName; selectionName = DW_Strings.sCouncil; HashSet<String> CouncilSelection; CouncilSelection = new HashSet<>(); if (doUnderOccupancy) { if (sameTenancyType) { CouncilSelection.add("1UO - 1"); CouncilSelection.add("1 - 1UO"); CouncilSelection.add("1UO - 1UO"); } CouncilSelection.add("1UO - 2"); CouncilSelection.add("1 - 2UO"); CouncilSelection.add("1UO - 2UO"); CouncilSelection.add("1UO - 3"); CouncilSelection.add("1 - 3UO"); CouncilSelection.add("1UO - 3UO"); CouncilSelection.add("1UO - 4"); CouncilSelection.add("1 - 4UO"); CouncilSelection.add("1UO - 4UO"); CouncilSelection.add("1UO - 5"); CouncilSelection.add("1 - 5UO"); CouncilSelection.add("1UO - 5UO"); CouncilSelection.add("1UO - 6"); CouncilSelection.add("1 - 6UO"); CouncilSelection.add("1UO - 6UO"); CouncilSelection.add("1UO - 7"); CouncilSelection.add("1 - 7UO"); CouncilSelection.add("1UO - 7UO"); CouncilSelection.add("1UO - 8"); CouncilSelection.add("1 - 8UO"); CouncilSelection.add("1UO - 8UO"); CouncilSelection.add("1UO - 9"); CouncilSelection.add("1 - 9UO"); CouncilSelection.add("1UO - 9UO"); if (do999) { CouncilSelection.add("1UO - -999"); CouncilSelection.add("-999 - 1UO"); CouncilSelection.add("1 - -999UO"); CouncilSelection.add("-999UO - 1"); CouncilSelection.add("1UO - -999UO"); CouncilSelection.add("-999UO - 1UO"); } } else { if (sameTenancyType) { CouncilSelection.add("1 - 1"); } CouncilSelection.add("1 - 2"); CouncilSelection.add("1 - 3"); CouncilSelection.add("1 - 4"); CouncilSelection.add("1 - 5"); CouncilSelection.add("1 - 6"); CouncilSelection.add("1 - 7"); CouncilSelection.add("1 - 8"); CouncilSelection.add("1 - 9"); if (do999) { CouncilSelection.add("1 - -999"); CouncilSelection.add("-999 - 1"); } } result.put(selectionName, CouncilSelection); selectionName = "PrivateRegulated"; HashSet<String> PrivateRegulatedSelection; PrivateRegulatedSelection = new HashSet<>(); if (doUnderOccupancy) { if (sameTenancyType) { PrivateRegulatedSelection.add("2UO - 2"); PrivateRegulatedSelection.add("2 - 2UO"); PrivateRegulatedSelection.add("2UO - 2UO"); } PrivateRegulatedSelection.add("2UO - 1"); PrivateRegulatedSelection.add("2 - 1UO"); PrivateRegulatedSelection.add("2UO - 1UO"); PrivateRegulatedSelection.add("2UO - 3"); PrivateRegulatedSelection.add("2 - 3UO"); PrivateRegulatedSelection.add("2UO - 3UO"); PrivateRegulatedSelection.add("2UO - 4"); PrivateRegulatedSelection.add("2 - 4UO"); PrivateRegulatedSelection.add("2UO - 4UO"); PrivateRegulatedSelection.add("2UO - 5"); PrivateRegulatedSelection.add("2 - 5UO"); PrivateRegulatedSelection.add("2UO - 5UO"); PrivateRegulatedSelection.add("2UO - 6"); PrivateRegulatedSelection.add("2 - 6UO"); PrivateRegulatedSelection.add("2UO - 6UO"); PrivateRegulatedSelection.add("2UO - 7"); PrivateRegulatedSelection.add("2 - 7UO"); PrivateRegulatedSelection.add("2UO - 7UO"); PrivateRegulatedSelection.add("2UO - 8"); PrivateRegulatedSelection.add("2 - 8UO"); PrivateRegulatedSelection.add("2UO - 8UO"); PrivateRegulatedSelection.add("2UO - 9"); PrivateRegulatedSelection.add("2 - 9UO"); PrivateRegulatedSelection.add("2UO - 9UO"); if (do999) { PrivateRegulatedSelection.add("2UO - -999"); PrivateRegulatedSelection.add("-999 - 2UO"); PrivateRegulatedSelection.add("2 - -999UO"); PrivateRegulatedSelection.add("-999UO - 2UO"); PrivateRegulatedSelection.add("2UO - -999UO"); PrivateRegulatedSelection.add("-999UO - 2UO"); } } else { if (sameTenancyType) { PrivateRegulatedSelection.add("2 - 2"); } PrivateRegulatedSelection.add("2 - 1"); PrivateRegulatedSelection.add("2 - 3"); PrivateRegulatedSelection.add("2 - 4"); PrivateRegulatedSelection.add("2 - 5"); PrivateRegulatedSelection.add("2 - 6"); PrivateRegulatedSelection.add("2 - 7"); PrivateRegulatedSelection.add("2 - 8"); PrivateRegulatedSelection.add("2 - 9"); if (do999) { PrivateRegulatedSelection.add("2 - -999"); PrivateRegulatedSelection.add("-999 - 2"); } } result.put(selectionName, PrivateRegulatedSelection); HashSet<String> PrivateDeregulatedSelection; PrivateDeregulatedSelection = new HashSet<>(); selectionName = "PrivateDeregulated"; if (doUnderOccupancy) { if (sameTenancyType) { PrivateDeregulatedSelection.add("3UO - 3"); PrivateDeregulatedSelection.add("3 - 3UO"); PrivateDeregulatedSelection.add("3UO - 3UO"); } PrivateDeregulatedSelection.add("3UO - 1"); PrivateDeregulatedSelection.add("3 - 1UO"); PrivateDeregulatedSelection.add("3UO - 1UO"); PrivateDeregulatedSelection.add("3UO - 2"); PrivateDeregulatedSelection.add("3 - 2UO"); PrivateDeregulatedSelection.add("3UO - 2UO"); PrivateDeregulatedSelection.add("3UO - 2UO"); PrivateDeregulatedSelection.add("3UO - 4"); PrivateDeregulatedSelection.add("3 - 4UO"); PrivateDeregulatedSelection.add("3UO - 4UO"); PrivateDeregulatedSelection.add("3UO - 5"); PrivateDeregulatedSelection.add("3 - 5UO"); PrivateDeregulatedSelection.add("3UO - 5UO"); PrivateDeregulatedSelection.add("3UO - 6"); PrivateDeregulatedSelection.add("3 - 6UO"); PrivateDeregulatedSelection.add("3UO - 6UO"); PrivateDeregulatedSelection.add("3UO - 7"); PrivateDeregulatedSelection.add("3 - 7UO"); PrivateDeregulatedSelection.add("3UO - 7UO"); PrivateDeregulatedSelection.add("3UO - 8"); PrivateDeregulatedSelection.add("3 - 8UO"); PrivateDeregulatedSelection.add("3UO - 8UO"); PrivateDeregulatedSelection.add("3UO - 9"); PrivateDeregulatedSelection.add("3 - 9UO"); PrivateDeregulatedSelection.add("3UO - 9UO"); if (do999) { PrivateDeregulatedSelection.add("3UO - -999"); PrivateDeregulatedSelection.add("-999 - 3UO"); PrivateDeregulatedSelection.add("3 - -999UO"); PrivateDeregulatedSelection.add("-999UO - 3"); PrivateDeregulatedSelection.add("3UO - -999UO"); PrivateDeregulatedSelection.add("-999UO - 3UO"); } } else { if (sameTenancyType) { PrivateDeregulatedSelection.add("3 - 3"); } PrivateDeregulatedSelection.add("3 - 1"); PrivateDeregulatedSelection.add("3 - 2"); PrivateDeregulatedSelection.add("3 - 4"); PrivateDeregulatedSelection.add("3 - 5"); PrivateDeregulatedSelection.add("3 - 6"); PrivateDeregulatedSelection.add("3 - 7"); PrivateDeregulatedSelection.add("3 - 8"); PrivateDeregulatedSelection.add("3 - 9"); if (do999) { PrivateDeregulatedSelection.add("3 - -999"); PrivateDeregulatedSelection.add("-999 - 3"); } } result.put(selectionName, PrivateDeregulatedSelection); HashSet<String> PrivateHousingAssociationSelection; PrivateHousingAssociationSelection = new HashSet<>(); selectionName = "PrivateHousingAssociation"; if (doUnderOccupancy) { if (sameTenancyType) { PrivateHousingAssociationSelection.add("4UO - 4"); PrivateHousingAssociationSelection.add("4 - 4UO"); PrivateHousingAssociationSelection.add("4UO - 4UO"); } PrivateHousingAssociationSelection.add("4UO - 4"); PrivateHousingAssociationSelection.add("4 - 4UO"); PrivateHousingAssociationSelection.add("4UO - 1"); PrivateHousingAssociationSelection.add("4 - 1UO"); PrivateHousingAssociationSelection.add("4UO - 1UO"); PrivateHousingAssociationSelection.add("4UO - 2"); PrivateHousingAssociationSelection.add("4 - 2UO"); PrivateHousingAssociationSelection.add("4UO - 2UO"); PrivateHousingAssociationSelection.add("4UO - 3"); PrivateHousingAssociationSelection.add("4 - 3UO"); PrivateHousingAssociationSelection.add("4UO - 3UO"); PrivateHousingAssociationSelection.add("4UO - 5"); PrivateHousingAssociationSelection.add("4 - 5UO"); PrivateHousingAssociationSelection.add("4UO - 5UO"); PrivateHousingAssociationSelection.add("4UO - 6"); PrivateHousingAssociationSelection.add("4 - 6UO"); PrivateHousingAssociationSelection.add("4UO - 6UO"); PrivateHousingAssociationSelection.add("4UO - 7"); PrivateHousingAssociationSelection.add("4 - 7UO"); PrivateHousingAssociationSelection.add("4UO - 7UO"); PrivateHousingAssociationSelection.add("4UO - 8"); PrivateHousingAssociationSelection.add("4 - 8UO"); PrivateHousingAssociationSelection.add("4UO - 8UO"); PrivateHousingAssociationSelection.add("4UO - 9"); PrivateHousingAssociationSelection.add("4 - 9UO"); PrivateHousingAssociationSelection.add("4UO - 9UO"); if (do999) { PrivateHousingAssociationSelection.add("4UO - -999"); PrivateHousingAssociationSelection.add("-999 - 4UO"); PrivateHousingAssociationSelection.add("4 - -999UO"); PrivateHousingAssociationSelection.add("-999UO - 4"); PrivateHousingAssociationSelection.add("4UO - -999UO"); PrivateHousingAssociationSelection.add("-999UO - 4UO"); } } else { if (sameTenancyType) { PrivateHousingAssociationSelection.add("4 - 4"); } PrivateHousingAssociationSelection.add("4 - 1"); PrivateHousingAssociationSelection.add("4 - 2"); PrivateHousingAssociationSelection.add("4 - 3"); PrivateHousingAssociationSelection.add("4 - 5"); PrivateHousingAssociationSelection.add("4 - 6"); PrivateHousingAssociationSelection.add("4 - 7"); PrivateHousingAssociationSelection.add("4 - 8"); PrivateHousingAssociationSelection.add("4 - 9"); if (do999) { PrivateHousingAssociationSelection.add("4 - -999"); PrivateHousingAssociationSelection.add("-999 - 4"); } } result.put(selectionName, PrivateHousingAssociationSelection); HashSet<String> PrivateOtherSelection; PrivateOtherSelection = new HashSet<>(); selectionName = "PrivateOther"; if (doUnderOccupancy) { if (sameTenancyType) { PrivateOtherSelection.add("6UO - 6"); PrivateOtherSelection.add("6 - 6UO"); PrivateOtherSelection.add("6UO - 6UO"); } PrivateOtherSelection.add("6UO - 1"); PrivateOtherSelection.add("6 - 1UO"); PrivateOtherSelection.add("6UO - 1UO"); PrivateOtherSelection.add("6UO - 2"); PrivateOtherSelection.add("6 - 2UO"); PrivateOtherSelection.add("6UO - 2UO"); PrivateOtherSelection.add("6UO - 3"); PrivateOtherSelection.add("6 - 3UO"); PrivateOtherSelection.add("6UO - 3UO"); PrivateOtherSelection.add("6UO - 4"); PrivateOtherSelection.add("6 - 4UO"); PrivateOtherSelection.add("6UO - 4UO"); PrivateOtherSelection.add("6UO - 5"); PrivateOtherSelection.add("6 - 5UO"); PrivateOtherSelection.add("6UO - 5UO"); PrivateOtherSelection.add("6UO - 7"); PrivateOtherSelection.add("6 - 7UO"); PrivateOtherSelection.add("6UO - 7UO"); PrivateOtherSelection.add("6UO - 8"); PrivateOtherSelection.add("6 - 8UO"); PrivateOtherSelection.add("6UO - 8UO"); PrivateOtherSelection.add("6UO - 9"); PrivateOtherSelection.add("6 - 9UO"); PrivateOtherSelection.add("6UO - 9UO"); if (do999) { PrivateOtherSelection.add("6UO - -999"); PrivateOtherSelection.add("-999 - 6UO"); PrivateOtherSelection.add("6 - -999UO"); PrivateOtherSelection.add("-999UO - 6"); PrivateOtherSelection.add("6UO - -999UO"); PrivateOtherSelection.add("-999UO - 6UO"); } } else { if (sameTenancyType) { PrivateOtherSelection.add("6 - 6"); } PrivateOtherSelection.add("6 - 1"); PrivateOtherSelection.add("6 - 2"); PrivateOtherSelection.add("6 - 3"); PrivateOtherSelection.add("6 - 4"); PrivateOtherSelection.add("6 - 5"); PrivateOtherSelection.add("6 - 7"); PrivateOtherSelection.add("6 - 8"); PrivateOtherSelection.add("6 - 9"); if (do999) { PrivateOtherSelection.add("6 - -999"); PrivateOtherSelection.add("-999 - 6"); } } result.put(selectionName, PrivateOtherSelection); HashSet<String> CTBOnlySelection; CTBOnlySelection = new HashSet<>(); selectionName = "CTBOnly"; if (doUnderOccupancy) { if (sameTenancyType) { CTBOnlySelection.add("5 - 5UO"); CTBOnlySelection.add("5UO - 5"); CTBOnlySelection.add("5UO - 5UO"); CTBOnlySelection.add("7 - 7UO"); CTBOnlySelection.add("7UO - 7"); CTBOnlySelection.add("7UO - 7UO"); } // 5 CTBOnlySelection.add("5UO - 1"); CTBOnlySelection.add("5 - 1UO"); CTBOnlySelection.add("5UO - 1UO"); CTBOnlySelection.add("5UO - 2"); CTBOnlySelection.add("5 - 2UO"); CTBOnlySelection.add("5UO - 2UO"); CTBOnlySelection.add("5UO - 3"); CTBOnlySelection.add("5 - 3UO"); CTBOnlySelection.add("5UO - 3UO"); CTBOnlySelection.add("5UO - 4"); CTBOnlySelection.add("5 - 4UO"); CTBOnlySelection.add("5UO - 4UO"); CTBOnlySelection.add("5UO - 6"); CTBOnlySelection.add("5 - 6UO"); CTBOnlySelection.add("5UO - 6UO"); CTBOnlySelection.add("5UO - 7"); CTBOnlySelection.add("5 - 7UO"); CTBOnlySelection.add("5UO - 7UO"); CTBOnlySelection.add("5UO - 8"); CTBOnlySelection.add("5 - 8UO"); CTBOnlySelection.add("5UO - 8UO"); CTBOnlySelection.add("5UO - 9"); CTBOnlySelection.add("5 - 9UO"); CTBOnlySelection.add("5UO - 9UO"); // 7 CTBOnlySelection.add("7UO - 1"); CTBOnlySelection.add("7 - 1UO"); CTBOnlySelection.add("7UO - 1UO"); CTBOnlySelection.add("7UO - 2"); CTBOnlySelection.add("7 - 2UO"); CTBOnlySelection.add("7UO - 2UO"); CTBOnlySelection.add("7UO - 3"); CTBOnlySelection.add("7 - 3UO"); CTBOnlySelection.add("7UO - 3UO"); CTBOnlySelection.add("7UO - 4"); CTBOnlySelection.add("7 - 4UO"); CTBOnlySelection.add("7UO - 4UO"); CTBOnlySelection.add("7UO - 5"); CTBOnlySelection.add("7 - 5UO"); CTBOnlySelection.add("7UO - 5UO"); CTBOnlySelection.add("7UO - 6"); CTBOnlySelection.add("7 - 6UO"); CTBOnlySelection.add("7UO - 6UO"); CTBOnlySelection.add("7UO - 8"); CTBOnlySelection.add("7 - 8UO"); CTBOnlySelection.add("7UO - 8UO"); CTBOnlySelection.add("7UO - 9"); CTBOnlySelection.add("7 - 9UO"); CTBOnlySelection.add("7UO - 9UO"); if (do999) { CTBOnlySelection.add("5UO - -999"); CTBOnlySelection.add("-999 - 5UO"); CTBOnlySelection.add("5 - -999UO"); CTBOnlySelection.add("-999UO - 5"); CTBOnlySelection.add("5UO - -999UO"); CTBOnlySelection.add("-999UO - 5UO"); CTBOnlySelection.add("7UO - -999"); CTBOnlySelection.add("-999 - 7UO"); CTBOnlySelection.add("7 - -999UO"); CTBOnlySelection.add("-999UO - 7"); CTBOnlySelection.add("7UO - -999UO"); CTBOnlySelection.add("-999UO - 7UO"); } } else { if (sameTenancyType) { CTBOnlySelection.add("5 - 5"); CTBOnlySelection.add("7 - 7"); } // 5 CTBOnlySelection.add("7 - 1"); CTBOnlySelection.add("7 - 2"); CTBOnlySelection.add("7 - 3"); CTBOnlySelection.add("7 - 4"); CTBOnlySelection.add("7 - 5"); CTBOnlySelection.add("7 - 6"); CTBOnlySelection.add("7 - 8"); CTBOnlySelection.add("7 - 9"); // 7 CTBOnlySelection.add("7 - 1"); CTBOnlySelection.add("7 - 2"); CTBOnlySelection.add("7 - 3"); CTBOnlySelection.add("7 - 4"); CTBOnlySelection.add("7 - 5"); CTBOnlySelection.add("7 - 6"); CTBOnlySelection.add("7 - 8"); CTBOnlySelection.add("7 - 9"); if (do999) { CTBOnlySelection.add("7 - -999"); CTBOnlySelection.add("-999 - 7"); } } result.put(selectionName, CTBOnlySelection); HashSet<String> CouncilNonHRAOnlySelection; CouncilNonHRAOnlySelection = new HashSet<>(); selectionName = "CouncilNonHRA"; if (doUnderOccupancy) { if (sameTenancyType) { CouncilNonHRAOnlySelection.add("8 - 8UO"); CouncilNonHRAOnlySelection.add("8UO - 8"); CouncilNonHRAOnlySelection.add("8UO - 8UO"); } CouncilNonHRAOnlySelection.add("8UO - 1"); CouncilNonHRAOnlySelection.add("8 - 1UO"); CouncilNonHRAOnlySelection.add("8UO - 1UO"); CouncilNonHRAOnlySelection.add("8UO - 2"); CouncilNonHRAOnlySelection.add("8 - 2UO"); CouncilNonHRAOnlySelection.add("8UO - 2UO"); CouncilNonHRAOnlySelection.add("8UO - 3"); CouncilNonHRAOnlySelection.add("8 - 3UO"); CouncilNonHRAOnlySelection.add("8UO - 3UO"); CouncilNonHRAOnlySelection.add("8UO - 4"); CouncilNonHRAOnlySelection.add("8 - 4UO"); CouncilNonHRAOnlySelection.add("8UO - 4UO"); CouncilNonHRAOnlySelection.add("8UO - 5"); CouncilNonHRAOnlySelection.add("8 - 5UO"); CouncilNonHRAOnlySelection.add("8UO - 5UO"); CouncilNonHRAOnlySelection.add("8UO - 6"); CouncilNonHRAOnlySelection.add("8 - 6UO"); CouncilNonHRAOnlySelection.add("8UO - 6UO"); CouncilNonHRAOnlySelection.add("8UO - 7"); CouncilNonHRAOnlySelection.add("8 - 7UO"); CouncilNonHRAOnlySelection.add("8UO - 7UO"); CouncilNonHRAOnlySelection.add("8UO - 9"); CouncilNonHRAOnlySelection.add("8 - 9UO"); CouncilNonHRAOnlySelection.add("8UO - 9UO"); if (do999) { CouncilNonHRAOnlySelection.add("8UO - -999"); CouncilNonHRAOnlySelection.add("-999 - 8UO"); CouncilNonHRAOnlySelection.add("8 - -999UO"); CouncilNonHRAOnlySelection.add("-999UO - 8"); CouncilNonHRAOnlySelection.add("8UO - -999UO"); CouncilNonHRAOnlySelection.add("-999UO - 8UO"); } } else { if (sameTenancyType) { CouncilNonHRAOnlySelection.add("8 - 8"); } CouncilNonHRAOnlySelection.add("8 - 1"); CouncilNonHRAOnlySelection.add("8 - 2"); CouncilNonHRAOnlySelection.add("8 - 3"); CouncilNonHRAOnlySelection.add("8 - 4"); CouncilNonHRAOnlySelection.add("8 - 5"); CouncilNonHRAOnlySelection.add("8 - 6"); CouncilNonHRAOnlySelection.add("8 - 7"); CouncilNonHRAOnlySelection.add("8 - 9"); if (do999) { CouncilNonHRAOnlySelection.add("8 - -999"); CouncilNonHRAOnlySelection.add("-999 - 8"); } } result.put(selectionName, CouncilNonHRAOnlySelection); HashSet<String> PrivateMealDeductionSelection; PrivateMealDeductionSelection = new HashSet<>(); selectionName = "PrivateMealDeduction"; if (doUnderOccupancy) { if (sameTenancyType) { PrivateMealDeductionSelection.add("9 - 9UO"); PrivateMealDeductionSelection.add("9UO - 9"); PrivateMealDeductionSelection.add("9UO - 9UO"); } PrivateMealDeductionSelection.add("9UO - 1"); PrivateMealDeductionSelection.add("9 - 1UO"); PrivateMealDeductionSelection.add("9UO - 1UO"); PrivateMealDeductionSelection.add("9UO - 2"); PrivateMealDeductionSelection.add("9 - 2UO"); PrivateMealDeductionSelection.add("9UO - 2UO"); PrivateMealDeductionSelection.add("9UO - 3"); PrivateMealDeductionSelection.add("9 - 3UO"); PrivateMealDeductionSelection.add("9UO - 3UO"); PrivateMealDeductionSelection.add("9UO - 4"); PrivateMealDeductionSelection.add("9 - 4UO"); PrivateMealDeductionSelection.add("9UO - 4UO"); PrivateMealDeductionSelection.add("9UO - 5"); PrivateMealDeductionSelection.add("9 - 5UO"); PrivateMealDeductionSelection.add("9UO - 5UO"); PrivateMealDeductionSelection.add("9UO - 6"); PrivateMealDeductionSelection.add("9 - 6UO"); PrivateMealDeductionSelection.add("9UO - 6UO"); PrivateMealDeductionSelection.add("9UO - 7"); PrivateMealDeductionSelection.add("9 - 7UO"); PrivateMealDeductionSelection.add("9UO - 7UO"); PrivateMealDeductionSelection.add("9UO - 8"); PrivateMealDeductionSelection.add("9 - 8UO"); PrivateMealDeductionSelection.add("9UO - 8UO"); if (do999) { PrivateMealDeductionSelection.add("9UO - -999"); PrivateMealDeductionSelection.add("-999 - 9UO"); PrivateMealDeductionSelection.add("9 - -999UO"); PrivateMealDeductionSelection.add("-999UO - 9"); PrivateMealDeductionSelection.add("9UO - -999UO"); PrivateMealDeductionSelection.add("-999UO - 9UO"); } } else { if (sameTenancyType) { PrivateMealDeductionSelection.add("9 - 9"); } PrivateMealDeductionSelection.add("9 - 1"); PrivateMealDeductionSelection.add("9 - 2"); PrivateMealDeductionSelection.add("9 - 3"); PrivateMealDeductionSelection.add("9 - 4"); PrivateMealDeductionSelection.add("9 - 5"); PrivateMealDeductionSelection.add("9 - 6"); PrivateMealDeductionSelection.add("9 - 7"); PrivateMealDeductionSelection.add("9 - 9"); if (do999) { PrivateMealDeductionSelection.add("9 - -999"); PrivateMealDeductionSelection.add("-999 - 9"); } } result.put(selectionName, PrivateMealDeductionSelection); HashSet<String> allSelection; allSelection = new HashSet<>(); selectionName = DW_Strings.sAll; allSelection.addAll(CouncilSelection); allSelection.addAll(PrivateHousingAssociationSelection); allSelection.addAll(PrivateRegulatedSelection); allSelection.addAll(PrivateDeregulatedSelection); allSelection.addAll(PrivateOtherSelection); result.put(selectionName, allSelection); selectionName = "ReportSelection"; HashSet<String> selection; selection = new HashSet<>(); if (doUnderOccupancy) { if (sameTenancyType) { selection.add("1 - 1UO"); selection.add("1UO - 1"); selection.add("1UO - 1UO"); // selection.add("2 - 2UO"); // selection.add("2UO - 2"); // selection.add("2UO - 2UO"); selection.add("3 - 3UO"); selection.add("3UO - 3"); selection.add("3UO - 3UO"); selection.add("4 - 4UO"); selection.add("4UO - 4"); selection.add("4UO - 4UO"); } selection.add("1 - 3UO"); selection.add("1UO - 3"); selection.add("1UO - 3UO"); selection.add("1 - 4UO"); selection.add("1UO - 4"); selection.add("1UO - 4UO"); selection.add("3 - 1UO"); selection.add("3UO - 1"); selection.add("3UO - 1UO"); selection.add("3 - 4UO"); selection.add("3UO - 4"); selection.add("3UO - 4UO"); selection.add("4 - 1UO"); selection.add("4UO - 1"); selection.add("4UO - 1UO"); selection.add("4 - 3UO"); selection.add("4UO - 3"); selection.add("4UO - 3UO"); if (do999) { selection.add("1UO - -999"); selection.add("-999 - 1UO"); selection.add("3UO - -999"); selection.add("-999 - 3UO"); selection.add("4UO - -999"); selection.add("-999 - 4UO"); } } else { if (sameTenancyType) { selection.add("1 - 1"); selection.add("3 - 3"); selection.add("4 - 4"); } selection.add("1 - 3"); selection.add("1 - 4"); selection.add("3 - 1"); selection.add("3 - 4"); selection.add("4 - 1"); selection.add("4 - 3"); if (do999) { selection.add("1 - -999"); selection.add("-999 - 1"); selection.add("3 - -999"); selection.add("-999 - 3"); selection.add("4 - -999"); selection.add("-999 - 4"); } } result.put(selectionName, selection); return result; } /** * @param doUnderOccupancy * @param do999 * @param sameTenancyType * @return */ protected TreeMap<String, HashSet<String>> getAllSelectionsGrouped( boolean doUnderOccupancy, boolean do999, boolean sameTenancyType) { TreeMap<String, HashSet<String>> result; result = new TreeMap<>(); String selectionName; selectionName = "Regulated"; HashSet<String> regulatedSelection; regulatedSelection = new HashSet<>(); if (doUnderOccupancy) { if (sameTenancyType) { regulatedSelection.add("RegulatedUO - Regulated"); regulatedSelection.add("Regulated - RegulatedUO"); regulatedSelection.add("RegulatedUO - RegulatedUO"); } regulatedSelection.add("RegulatedUO - Unregulated"); regulatedSelection.add("Regulated - UnregulatedUO"); regulatedSelection.add("RegulatedUO - UnregulatedUO"); regulatedSelection.add("Regulated - UngroupedUO"); regulatedSelection.add("RegulatedUO - Ungrouped"); regulatedSelection.add("RegulatedUO - UngroupedUO"); if (do999) { regulatedSelection.add("RegulatedUO - -999"); regulatedSelection.add("-999 - RegulatedUO"); regulatedSelection.add("Regulated - -999UO"); regulatedSelection.add("-999UO - Regulated"); regulatedSelection.add("RegulatedUO - -999UO"); regulatedSelection.add("-999UO - RegulatedUO"); } } else { if (sameTenancyType) { regulatedSelection.add("Regulated - Regulated"); } regulatedSelection.add("Regulated - Unregulated"); regulatedSelection.add("Regulated - Ungrouped"); if (do999) { regulatedSelection.add("Regulated - -999"); regulatedSelection.add("-999 - Regulated"); } } result.put(selectionName, regulatedSelection); HashSet<String> unregulatedSelection; unregulatedSelection = new HashSet<>(); selectionName = "Unregulated"; if (doUnderOccupancy) { if (sameTenancyType) { unregulatedSelection.add("UnregulatedUO - Unregulated"); unregulatedSelection.add("Unregulated - UnregulatedUO"); unregulatedSelection.add("UnregulatedUO - UnregulatedUO"); } unregulatedSelection.add("UnregulatedUO - Regulated"); unregulatedSelection.add("Unregulated - RegulatedUO"); unregulatedSelection.add("UnregulatedUO - RegulatedUO"); unregulatedSelection.add("UnregulatedUO - UngroupedUO"); unregulatedSelection.add("UnregulatedUO - Ungrouped"); unregulatedSelection.add("Unregulated - UngroupedUO"); if (do999) { unregulatedSelection.add("UnregulatedUO - -999"); unregulatedSelection.add("-999 - UnregulatedUO"); unregulatedSelection.add("Unregulated - -999UO"); unregulatedSelection.add("-999UO - Unregulated"); unregulatedSelection.add("UnregulatedUO - -999UO"); unregulatedSelection.add("-999UO - UnregulatedUO"); } } else { if (sameTenancyType) { unregulatedSelection.add("Unregulated - Unregulated"); } unregulatedSelection.add("Unregulated - Regulated"); unregulatedSelection.add("Unregulated - Ungrouped"); if (do999) { unregulatedSelection.add("Unregulated - -999"); unregulatedSelection.add("-999 - Unregulated"); } } result.put(selectionName, unregulatedSelection); HashSet<String> ungroupedSelection; ungroupedSelection = new HashSet<>(); selectionName = DW_Strings.sGroupedNo; if (doUnderOccupancy) { if (sameTenancyType) { ungroupedSelection.add("UngroupedUO - Ungrouped"); ungroupedSelection.add("Ungrouped - UngroupedUO"); ungroupedSelection.add("UngroupedUO - UngroupedUO"); } ungroupedSelection.add("UngroupedUO - Regulated"); ungroupedSelection.add("Ungrouped - RegulatedUO"); ungroupedSelection.add("UngroupedUO - RegulatedUO"); ungroupedSelection.add("UngroupedUO - Unregulated"); ungroupedSelection.add("Ungrouped - UnregulatedUO"); ungroupedSelection.add("UngroupedUO - UnregulatedUO"); if (do999) { ungroupedSelection.add("UngroupedUO - -999"); ungroupedSelection.add("-999 - UngroupedUO"); ungroupedSelection.add("Ungrouped - -999UO"); ungroupedSelection.add("-999UO - Ungrouped"); ungroupedSelection.add("UngroupedUO - -999UO"); ungroupedSelection.add("-999UO - UngroupedUO"); } } else { if (sameTenancyType) { ungroupedSelection.add("Ungrouped - Ungrouped"); } ungroupedSelection.add("Ungrouped - Regulated"); ungroupedSelection.add("Ungrouped - Unregulated"); if (do999) { ungroupedSelection.add("Ungrouped - -999"); ungroupedSelection.add("-999 - Ungrouped"); } } result.put(selectionName, ungroupedSelection); HashSet<String> allSelection; allSelection = new HashSet<>(); selectionName = DW_Strings.sAll; allSelection.addAll(regulatedSelection); allSelection.addAll(unregulatedSelection); allSelection.addAll(ungroupedSelection); result.put(selectionName, allSelection); return result; } // public static String getLabel( // String year0, // String month0, // String year, // String month) { // String result; // result = year0 + " " + month0 + "_" + year + " " + month; // // System.out.println(result); // return result; // } public static String getLabel( String yM30, String yM31) { String result; result = yM30 + "-" + yM31; //result = yM30 + "_TO_" + yM31; // System.out.println(result); return result; } /** * {@code * Object[] result; * result = new Object[3]; * TreeMap<Integer, TreeMap<Integer, BigDecimal>> map; * map = new TreeMap<Integer, TreeMap<Integer, BigDecimal>>(); * result[0] = map; * Double min = null; * result[1] = min; * Double max = null; * result[2] = max; * result[3] = size; * } * * @param f * @param timeDiff Normaliser for counts. * @return TenureBefore, TenureNow Counts. */ public TreeMap<String, TreeMap<String, BigDecimal>> getTenancyTypeTransitionMap( Path f, double timeDiff) { DW_Table table = new DW_Table(env); // Object[] result; // result = new Object[4]; TreeMap<String, TreeMap<String, BigDecimal>> map; map = new TreeMap<>(); // result[0] = map; // Double min = Double.MAX_VALUE; // Double max = Double.MIN_VALUE; // int size = 0; ArrayList<String> lines = table.readCSV(f); ArrayList<String> tenancyTypes; tenancyTypes = new ArrayList<>(); boolean mapContainsNonZeroValues = false; boolean first = true; Iterator<String> ite = lines.iterator(); while (ite.hasNext()) { // Skip the first line String line; line = ite.next(); String[] split; split = line.split(","); if (first) { for (int i = 1; i < split.length; i++) { String tenancyBefore; tenancyBefore = split[i]; TreeMap<String, BigDecimal> transitions; transitions = new TreeMap<>(); map.put(tenancyBefore, transitions); tenancyTypes.add(tenancyBefore); } first = false; } else { String tenancyNow; tenancyNow = split[0]; for (int i = 1; i < split.length; i++) { String tenancyTypeBefore; // This is tenancyStart!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! tenancyTypeBefore = tenancyTypes.get(i - 1); Integer count; count = Integer.valueOf(split[i]); if (count != 0) { mapContainsNonZeroValues = true; } Double rate; rate = count / timeDiff; TreeMap<String, BigDecimal> tenancyTransition; tenancyTransition = map.get(tenancyTypeBefore); tenancyTransition.put(tenancyNow, BigDecimal.valueOf(rate)); // if (tenancyTypeBefore.compareTo(tenancyEnd) != 0) { // min = Math.min(min, rate); // max = Math.max(max, rate); // size++; // } } } } if (!mapContainsNonZeroValues) { return null; } // System.out.println("max " + max); // System.out.println("min " + min); // System.out.println("size " + size); // result[1] = min; // This has to be here because of unboxing!? // result[2] = max; // result[3] = size; // return result; return map; } /** * {@code * Object[] result; * result = new Object[3]; * TreeMap<Integer, TreeMap<Integer, BigDecimal>> map; * map = new TreeMap<Integer, TreeMap<Integer, BigDecimal>>(); * result[0] = map; * Double min = null; * result[1] = min; * Double max = null; * result[2] = max; * result[3] = size; * } * * @param f * @param timeDiff Normaliser for counts. * @return TenancyTypeBefore, TenancyTypeNow Counts. */ public TreeMap<String, TreeMap<String, BigDecimal>> getTenancyTypeTransitionMapGrouped( Path f, double timeDiff) { DW_Table table = new DW_Table(env); // Object[] result; // result = new Object[4]; TreeMap<String, TreeMap<String, BigDecimal>> map; map = new TreeMap<>(); // result[0] = map; // Double min = Double.MAX_VALUE; // Double max = Double.MIN_VALUE; // int size = 0; ArrayList<String> lines = table.readCSV(f); ArrayList<String> tenancyTypes; tenancyTypes = new ArrayList<>(); boolean mapContainsNonZeroValues = false; boolean first = true; Iterator<String> ite = lines.iterator(); while (ite.hasNext()) { // Skip the first line String line; line = ite.next(); String[] split; split = line.split(","); if (first) { for (int i = 1; i < split.length; i++) { String tenancyStart; tenancyStart = split[i]; TreeMap<String, BigDecimal> transitions; transitions = new TreeMap<>(); map.put(tenancyStart, transitions); tenancyTypes.add(tenancyStart); } first = false; } else { String tenancyEnd; tenancyEnd = split[0]; for (int i = 1; i < split.length; i++) { String tenancyTypeBefore; if (split.length > 9) { int debug = 1; } tenancyTypeBefore = tenancyTypes.get(i - 1); Integer count; count = Integer.valueOf(split[i]); if (count != 0) { mapContainsNonZeroValues = true; } Double rate; rate = count / timeDiff; TreeMap<String, BigDecimal> tenancyTransition; tenancyTransition = map.get(tenancyTypeBefore); tenancyTransition.put(tenancyEnd, BigDecimal.valueOf(rate)); // if (tenancyTypeBefore.compareTo(tenancyEnd) != 0) { // min = Math.min(min, rate); // max = Math.max(max, rate); // size++; // } } } } if (!mapContainsNonZeroValues) { return null; } // System.out.println("max " + max); // System.out.println("min " + min); // System.out.println("size " + size); // result[1] = min; // This has to be here because of unboxing!? // result[2] = max; // result[3] = size; // return result; return map; } /** * Object[] result; result = new Object[7]; result[0] = maps; * TreeMap<String, TreeMap<BigDecimal, BigDecimal>> // label, x, y maps * result[1] = newMinY; // BigDecimal minimum y value in selection. * result[2] = newMaxY; // BigDecimal maximum y value in selection. * result[3] = newMinX; // BigDecimal minimum x value in selection. * result[4] = newMaxX; // BigDecimal maximum x value in selection. * result[5] = labels; // collection of strings: row index " - " column * index result[6] = xAxisLabels; result[7] = TreeMap<String, Boolean> // * label, non-zero values result[7] = TreeMap<String, Boolean> // labels, * non-zero values */ private Object[] getData( TreeMap<String, TreeMap<UKP_YM3, BigDecimal>> data, TreeMap<BigDecimal, UKP_YM3> xAxisLabels, TreeMap<UKP_YM3, BigDecimal> fileLabelValue) { Object[] result; result = new Object[9]; TreeMap<String, TreeMap<BigDecimal, BigDecimal>> maps; maps = new TreeMap<>(); BigDecimal newMinX; newMinX = BigDecimal.valueOf(Double.MAX_VALUE); BigDecimal newMaxX; newMaxX = BigDecimal.valueOf(Double.MIN_VALUE); BigDecimal newMinY; newMinY = BigDecimal.valueOf(Double.MAX_VALUE); BigDecimal newMaxY; newMaxY = BigDecimal.valueOf(Double.MIN_VALUE); TreeMap<String, Boolean> nonZero; nonZero = new TreeMap<>(); // Initialise data, newMinX, newMaxX, newMinY, newMaxY Iterator<String> iteS; Iterator<UKP_YM3> iteS2; iteS = data.keySet().iterator(); String key; TreeMap<UKP_YM3, BigDecimal> dataYX; while (iteS.hasNext()) { key = iteS.next(); // key is aggregate area code TreeMap<BigDecimal, BigDecimal> map; map = maps.get(key); if (map == null) { map = new TreeMap<>(); maps.put(key, map); } dataYX = data.get(key); // init Boolean bo; bo = nonZero.get(key); if (bo == null) { nonZero.put(key, false); } iteS2 = dataYX.keySet().iterator(); while (iteS2.hasNext()) { UKP_YM3 YM3; YM3 = iteS2.next(); // System.out.println("YM3 " + YM3); BigDecimal x = fileLabelValue.get(YM3); if (x == null) { nonZero.put(key, true); } else { if (x.compareTo(BigDecimal.ZERO) != 0) { nonZero.put(key, true); } BigDecimal y; y = dataYX.get(YM3); // System.out.println("x " + x); // System.out.println("y " + y); // set min and max newMinY = y.min(newMinY); newMaxY = y.max(newMaxY); newMinX = x.min(newMinX); newMaxX = x.max(newMaxX); // Add to map map.put(x, y); } } } TreeMap<String, Boolean> nonZero2; nonZero2 = new TreeMap<>(); // Initialise labels. ArrayList<String> labels; labels = new ArrayList<>(); iteS = maps.keySet().iterator(); while (iteS.hasNext()) { String label; label = iteS.next(); labels.add(label); nonZero2.put(label, nonZero.get(label)); } result[0] = maps; result[1] = newMinY; result[2] = newMaxY; result[3] = newMinX; result[4] = newMaxX; result[5] = labels; result[6] = xAxisLabels; result[7] = nonZero; result[8] = nonZero2; return result; } /** * @param bigMatrix The bigMatrix to repack and select from. Keys are x * values to be plot, the final values are y values, the Integer keys * between are row and column indexes. TenancyTypeBefore, TenancyTypeNow * Counts. * @param selection A collection of strings for selecting what data to get. * @param xAxisLabels Passed in for packaging. * @return { * @code * Object[] result; * result = new Object[7]; * result[0] = maps; TreeMap<String, TreeMap<BigDecimal, BigDecimal>> // label, x, y maps * result[1] = newMinY; // BigDecimal minimum y value in selection. * result[2] = newMaxY; // BigDecimal maximum y value in selection. * result[3] = newMinX; // BigDecimal minimum x value in selection. * result[4] = newMaxX; // BigDecimal maximum x value in selection. * result[5] = labels; // collection of strings: row index " - " column index * result[6] = xAxisLabels; * result[7] = TreeMap<String, Boolean> // label, non-zero values * result[8] = TreeMap<String, Boolean> // labels, non-zero values */ private Object[] getData( TreeMap<BigDecimal, TreeMap<String, TreeMap<String, BigDecimal>>> bigMatrix, HashSet<String> selection, TreeMap<BigDecimal, String> xAxisLabels) { Object[] result; result = new Object[9]; TreeMap<String, TreeMap<BigDecimal, BigDecimal>> maps; maps = new TreeMap<>(); BigDecimal newMinX; newMinX = BigDecimal.valueOf(Double.MAX_VALUE); BigDecimal newMaxX; newMaxX = BigDecimal.valueOf(Double.MIN_VALUE); BigDecimal newMinY; newMinY = BigDecimal.valueOf(Double.MAX_VALUE); BigDecimal newMaxY; newMaxY = BigDecimal.valueOf(Double.MIN_VALUE); // Declare nonZero TreeMap<String, Boolean> nonZero; nonZero = new TreeMap<>(); Iterator<BigDecimal> ite; ite = bigMatrix.keySet().iterator(); while (ite.hasNext()) { BigDecimal x = ite.next(); TreeMap<String, TreeMap<String, BigDecimal>> iomatrix; iomatrix = bigMatrix.get(x); Iterator<String> ite2; ite2 = iomatrix.keySet().iterator(); while (ite2.hasNext()) { String tenancyTypeBefore = ite2.next(); // This is Before!!!!!!!!!!!! TreeMap<String, BigDecimal> omatrix; omatrix = iomatrix.get(tenancyTypeBefore); Iterator<String> ite3; ite3 = omatrix.keySet().iterator(); while (ite3.hasNext()) { String tenancyTypeNow = ite3.next(); // This is now!!!!!!!!!1 if (!tenancyTypeNow.equalsIgnoreCase(tenancyTypeBefore)) { String key; key = "" + tenancyTypeBefore + " - " + tenancyTypeNow; // init Boolean b; b = nonZero.get(key); if (b == null) { nonZero.put(key, false); } if (selection.contains(key)) { TreeMap<BigDecimal, BigDecimal> map; map = maps.get(key); if (map == null) { map = new TreeMap<>(); maps.put(key, map); } BigDecimal y; y = omatrix.get(tenancyTypeNow); // set non-zero if (y.compareTo(BigDecimal.ZERO) != 0) { nonZero.put(key, true); } // set min and max newMinY = y.min(newMinY); newMaxY = y.max(newMaxY); newMinX = x.min(newMinX); newMaxX = x.max(newMaxX); // Add to map map.put(x, y); } } } } } // BigDecimal minX = bigMatrix.firstKey(); // BigDecimal maxX = bigMatrix.lastKey(); // BigDecimal minX = maps.firstKey(); // BigDecimal maxX = maps.lastKey(); result[0] = maps; result[1] = newMinY; result[2] = newMaxY; result[3] = newMinX; result[4] = newMaxX; ArrayList<String> labels; labels = new ArrayList<>(); // labels.addAll(maps.keySet()); // This does not work as maps is gc resulting in labels becoming null for some reason. // Declare nonZero2 SHBE_TenancyType shbeTT = env.getShbeTenancyType(); TreeMap<String, Boolean> nonZero2 = new TreeMap<>(); Iterator<String> iteS = maps.keySet().iterator(); while (iteS.hasNext()) { String label = iteS.next(); String[] tenancyTypes = label.split(" - "); String newLabel = shbeTT.getTenancyTypeName(tenancyTypes[0]); newLabel += " TO "; newLabel += shbeTT.getTenancyTypeName(tenancyTypes[1]); labels.add(newLabel); nonZero2.put(newLabel, nonZero.get(label)); } result[5] = labels; result[6] = xAxisLabels; result[7] = nonZero; result[8] = nonZero2; return result; } // private Object[] getDataGrouped( // TreeMap<BigDecimal, TreeMap<String, TreeMap<String, BigDecimal>>> bigMatrixGrouped, // HashSet<String> selection, // TreeMap<BigDecimal, String> xAxisLabels) { // Object[] result; // result = new Object[9]; // TreeMap<String, TreeMap<BigDecimal, BigDecimal>> maps; // maps = new TreeMap<String, TreeMap<BigDecimal, BigDecimal>>(); // BigDecimal newMinX; // newMinX = BigDecimal.valueOf(Double.MAX_VALUE); // BigDecimal newMaxX; // newMaxX = BigDecimal.valueOf(Double.MIN_VALUE); // BigDecimal newMinY; // newMinY = BigDecimal.valueOf(Double.MAX_VALUE); // BigDecimal newMaxY; // newMaxY = BigDecimal.valueOf(Double.MIN_VALUE); // // Declare nonZero // TreeMap<String, Boolean> nonZero; // nonZero = new TreeMap<String, Boolean>(); // Iterator<BigDecimal> ite; // ite = bigMatrixGrouped.keySet().iterator(); // while (ite.hasNext()) { // BigDecimal x = ite.next(); // TreeMap<String, TreeMap<String, BigDecimal>> iomatrix; // iomatrix = bigMatrixGrouped.get(x); // Iterator<String> ite2; // ite2 = iomatrix.keySet().iterator(); // while (ite2.hasNext()) { // String tenancyTypeBefore = ite2.next(); // TreeMap<String, BigDecimal> omatrix; // omatrix = iomatrix.get(tenancyTypeBefore); // Iterator<String> ite3; // ite3 = omatrix.keySet().iterator(); // while (ite3.hasNext()) { // String tenancyTypeNow = ite3.next(); // if (!tenancyTypeNow.equalsIgnoreCase(tenancyTypeBefore)) { // String key; // key = "" + tenancyTypeBefore + " - " + tenancyTypeNow; // // init // Boolean b; // b = nonZero.get(key); // if (b == null) { // nonZero.put(key, false); // } // if (selection.contains(key)) { // TreeMap<BigDecimal, BigDecimal> map; // map = maps.get(key); // if (map == null) { // map = new TreeMap<BigDecimal, BigDecimal>(); // maps.put(key, map); // } // BigDecimal y; // y = omatrix.get(tenancyTypeNow); // // set non-zero // if (y.compareTo(BigDecimal.ZERO) != 0) { // nonZero.put(key, true); // } // // set min and max // newMinY = y.min(newMinY); // newMaxY = y.max(newMaxY); // newMinX = x.min(newMinX); // newMaxX = x.max(newMaxX); // // add to map // map.put(x, y); // } // } // } // } // } //// BigDecimal minX = bigMatrix.firstKey(); //// BigDecimal maxX = bigMatrix.lastKey(); //// BigDecimal minX = maps.firstKey(); //// BigDecimal maxX = maps.lastKey(); // result[0] = maps; // result[1] = newMinY; // result[2] = newMaxY; // result[3] = newMinX; // result[4] = newMaxX; // // Declare nonZero2 // TreeMap<String, Boolean> nonZero2; // nonZero2 = new TreeMap<String, Boolean>(); // ArrayList<String> labels; // labels = new ArrayList<String>(); //// labels.addAll(maps.keySet()); // This does not work as maps is gc resulting in labels becoming null for some reason. // Iterator<String> iteS; // iteS = maps.keySet().iterator(); // while (iteS.hasNext()) { // String label; // label = iteS.next(); // String[] tenancyTypes; // //tenancyTypes = label.split(" - "); // tenancyTypes = label.split(" - "); // String newLabel; // newLabel = shbeData.getTenancyTypeName(Integer.valueOf(tenancyTypes[0])); // newLabel += " TO "; // newLabel += shbeData.getTenancyTypeName(Integer.valueOf(tenancyTypes[1])); // labels.add(newLabel); // nonZero2.put(newLabel, nonZero.get(label)); // } // result[5] = labels; // result[6] = xAxisLabels; // result[7] = nonZero; // result[8] = nonZero2; // return result; // } }
UTF-8
Java
122,381
java
DW_LineGraph.java
Java
[ { "context": "leeds.ccg.projects.dw.io.DW_Files;\n\n/**\n * @author Andy Turner\n * @version 1.0.0\n */\npublic class DW_LineGraph e", "end": 1457, "score": 0.9997553825378418, "start": 1446, "tag": "NAME", "value": "Andy Turner" } ]
null
[]
package uk.ac.leeds.ccg.projects.dw.visualisation.charts; import java.io.IOException; import java.math.BigDecimal; //import java.math.MathContext; import java.math.RoundingMode; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Set; //import java.util.Set; import java.util.TreeMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import uk.ac.leeds.ccg.chart.examples.Chart_Line; import uk.ac.leeds.ccg.data.ukp.util.UKP_YM3; import uk.ac.leeds.ccg.data.shbe.data.id.SHBE_ClaimID; import uk.ac.leeds.ccg.data.shbe.core.SHBE_Strings; //import uk.ac.leeds.ccg.generic.io.Generic_StaticIO; import uk.ac.leeds.ccg.generic.execution.Generic_Execution; import uk.ac.leeds.ccg.generic.util.Generic_Time; import uk.ac.leeds.ccg.generic.visualisation.Generic_Visualisation; import uk.ac.leeds.ccg.projects.dw.core.DW_Environment; import uk.ac.leeds.ccg.projects.dw.core.DW_Strings; import uk.ac.leeds.ccg.projects.dw.data.generated.DW_Table; import uk.ac.leeds.ccg.data.shbe.data.SHBE_Data; import uk.ac.leeds.ccg.data.shbe.data.SHBE_TenancyType; import uk.ac.leeds.ccg.projects.dw.data.uo.DW_UO_Data; import uk.ac.leeds.ccg.projects.dw.data.uo.DW_UO_Handler; import uk.ac.leeds.ccg.projects.dw.io.DW_Files; /** * @author <NAME> * @version 1.0.0 */ public class DW_LineGraph extends Chart_Line { protected final transient DW_Environment env; protected final transient DW_Files files; protected final transient SHBE_Data shbeData; protected final transient DW_UO_Handler uoHandler; protected final transient DW_UO_Data uoData; /** * Area Codes */ HashMap<String, HashSet<String>> ac; public DW_LineGraph(DW_Environment de) throws IOException, Exception { super(de.ge); this.env = de; this.files = de.files; this.shbeData = de.getShbeData(); this.uoData = de.getUoData(); this.uoHandler = de.getUoHandler(); } public DW_LineGraph(DW_Environment de, ExecutorService es, Path file, String format, String title, int dataWidth, int dataHeight, String xAxisLabel, String yAxisLabel, BigDecimal yMax, ArrayList<BigDecimal> yPin, BigDecimal yIncrement, int numberOfYAxisTicks, int decimalPlacePrecisionForCalculations, int decimalPlacePrecisionForDisplay, RoundingMode rm) throws IOException, Exception { super(de.ge, es, file, format, title, dataWidth, dataHeight, xAxisLabel, yAxisLabel, yMax, yPin, yIncrement, numberOfYAxisTicks, true, decimalPlacePrecisionForCalculations, decimalPlacePrecisionForDisplay, rm); this.env = de; this.files = de.files; this.shbeData = de.getShbeData(); this.uoData = de.getUoData(); this.uoHandler = de.getUoHandler(); } HashSet<Future> futures; ArrayList<Boolean> b; String[] SHBEFilenames; TreeMap<String, ArrayList<Integer>> includes; ArrayList<String> PTs; /** * * @param doGraphTenancyTypeTransitions * @param doGraphAggregateData */ public void run( boolean doGraphTenancyTypeTransitions, boolean doGraphAggregateData) throws IOException, Exception { env.ge.log("<run>"); vis.getHeadlessEnvironment(); dataWidth = 1300; dataHeight = 500; xAxisLabel = "Time Periods"; // setyPin(BigDecimal.ZERO); // yMax = new BigDecimal(700); // yIncrement = BigDecimal.TEN; // yIncrement = BigDecimal.ONE; //int yAxisStartOfEndInterval = 60; decimalPlacePrecisionForCalculations = 20; decimalPlacePrecisionForDisplay = 3; roundingMode = RoundingMode.HALF_UP; // mc = new MathContext(decimalPlacePrecisionForCalculations, roundingMode); numberOfYAxisTicks = 10; executorService = Executors.newSingleThreadExecutor(); SHBEFilenames = shbeData.getFilenames(); // ArrayList<String> claimantTypes; // claimantTypes = DW_Strings.getHB_CTB(); includes = shbeData.getIncludes(); includes.remove(SHBE_Strings.s_IncludeAll); includes.remove(SHBE_Strings.s_IncludeYearly); includes.remove(SHBE_Strings.s_Include6Monthly); includes.remove(SHBE_Strings.s_Include3Monthly); includes.remove(SHBE_Strings.s_IncludeMonthly); // includes.remove(DW_SHBE_Strings.s_IncludeMonthlySinceApril2013); includes.remove(SHBE_Strings.s_Include2MonthlySinceApril2013Offset0); includes.remove(SHBE_Strings.s_Include2MonthlySinceApril2013Offset1); includes.remove(SHBE_Strings.s_IncludeStartEndSinceApril2013); includes.remove(SHBE_Strings.s_IncludeApril2013May2013); futures = new HashSet<>(); format = "PNG"; // ArrayList<String> types; // types = new ArrayList<String>(); // types.add(DW_Files.sPostcodeChanged); // types.add(sPostcodeChangedNo); // types.add("Multiple"); // types.add(""); PTs = SHBE_Strings.getPaymentTypes(); // PTs.remove(shbeData.sPaymentTypeAll); PTs.remove(SHBE_Strings.s_PaymentTypeIn); PTs.remove(SHBE_Strings.s_PaymentTypeSuspended); PTs.remove(SHBE_Strings.s_PaymentTypeOther); b = new ArrayList<>(); b.add(true); b.add(false); // if (doGraphTenancyTypeTransitions) { // graphTenancyTypeTransitions(); // } if (doGraphAggregateData) { graphAggregateData(); } } protected void graphAggregateData() throws IOException, Exception { DW_Table table = new DW_Table(env); ArrayList<String> AZs; // AggregatedZones AZs = new ArrayList<>(); // AZs.add(DW_Strings.sParliamentaryConstituency); AZs.add(DW_Strings.sStatisticalWard); // AZs.add(DW_Strings.sLSOA); // AZs.add(DW_Strings.sMSOA); Iterator<String> ptIte = PTs.iterator(); while (ptIte.hasNext()) { String pt = ptIte.next(); Path dirIn = Paths.get(files.getOutputSHBETablesDir().toString(), DW_Strings.sHBGeneralAggregateStatistics, pt); Path dirOut = Paths.get(files.getOutputSHBEPlotsDir().toString(), DW_Strings.sHBGeneralAggregateStatistics, pt); Iterator<String> iIte = includes.keySet().iterator(); while (iIte.hasNext()) { String includeName = iIte.next(); ArrayList<Integer> include = includes.get(includeName); Iterator<String> AZsIte = AZs.iterator(); while (AZsIte.hasNext()) { String AZ = AZsIte.next(); Path dirIn1 = Paths.get(dirIn.toString(), AZ); Path dirOut1; dirOut1 = Paths.get(dirOut.toString(), AZ); dirOut1 = Paths.get(dirOut1.toString(), includeName); //dirOut1.mkdirs(); Path fout; for (int stat = 1; stat <= 8; stat++) { String filename; switch (stat) { case 1: filename = "NumberOfHBClaims.PNG"; yAxisLabel = "Number Of Housing Benefit Claims"; title = yAxisLabel + " Over Time"; break; case 2: filename = "NumberOfChildDependentsInHBClaimingHouseholds.PNG"; yAxisLabel = "Number Of Child Dependents In HB Claiming Households"; title = yAxisLabel + " Over Time"; break; case 3: filename = "TotalPopulationInHBClaimingHouseholds.PNG"; yAxisLabel = "Total Population In HB Claiming Households"; title = yAxisLabel + " Over Time"; break; case 4: filename = "NumberOfUOHouseholdsRequiring1Room.PNG"; yAxisLabel = "Number Of UO Households Requiring 1 Room"; title = yAxisLabel + " Over Time"; break; case 5: filename = "NumberOfUOHouseholdsRequiring2Rooms.PNG"; yAxisLabel = "Number Of UO Households Requiring 2 Rooms"; title = yAxisLabel + " Over Time"; break; case 6: filename = "NumberOfUOHouseholdsRequiring3Rooms.PNG"; yAxisLabel = "Number Of UO Households Requiring 3 Rooms"; title = yAxisLabel + " Over Time"; break; case 7: filename = "NumberOfUOHouseholdsRequiring4Rooms.PNG"; yAxisLabel = "Number Of UO Households Requiring 4 Rooms"; title = yAxisLabel + " Over Time"; break; default: filename = "NumberOfUOHouseholdsRequiring5OrMoreRooms.PNG"; yAxisLabel = "Number Of UO Households Requiring 5 Or More Rooms"; title = yAxisLabel + " Over Time"; break; } fout = Paths.get(dirOut1.toString(), filename); TreeMap<String, TreeMap<UKP_YM3, BigDecimal>> data0 = new TreeMap<>(); Iterator<Integer> includeIte = include.iterator(); while (includeIte.hasNext()) { int i = includeIte.next(); UKP_YM3 YM3; YM3 = shbeData.getYM3(SHBEFilenames[i]); Path f = Paths.get(dirIn1.toString(), YM3 + ".csv"); // readCSV ArrayList<String> lines = table.readCSV(f); Iterator<String> ite = lines.iterator(); String line; String[] fields; String header = ite.next(); String[] headerFields = header.split(DW_Strings.special_commaSpace); /* * AreaCode, NumberOfHBClaims, * NumberOfChildDependentsInHBClaimingHouseholds, * TotalPopulationInHBClaimingHouseholds, * NumberOfUOHouseholdsRequiring1Room, * NumberOfUOHouseholdsRequiring2Rooms, * NumberOfUOHouseholdsRequiring3Rooms, * NumberOfUOHouseholdsRequiring4Rooms, * NumberOfUOHouseholdsRequiring5OrMoreRooms */ while (ite.hasNext()) { line = ite.next(); //System.out.println(line); fields = line.split(DW_Strings.special_commaSpace); TreeMap<UKP_YM3, BigDecimal> dateValue; dateValue = data0.get(fields[0]); if (dateValue == null) { dateValue = new TreeMap<>(); data0.put(fields[0], dateValue); } dateValue.put(YM3, new BigDecimal(fields[stat])); } } DW_LineGraph chart = new DW_LineGraph(env, executorService, fout, format, title, getDataWidth(), getDataHeight(), xAxisLabel, yAxisLabel, yMax, yPin, yIncrement, numberOfYAxisTicks, decimalPlacePrecisionForCalculations, decimalPlacePrecisionForDisplay, getRoundingMode()); // Object[] TreeMapDateLabelSHBEFilename; TreeMapDateLabelSHBEFilename = shbeData.getTreeMapDateLabelSHBEFilenamesSingle( SHBEFilenames, include); TreeMap<BigDecimal, UKP_YM3> xAxisLabels; xAxisLabels = (TreeMap<BigDecimal, UKP_YM3>) TreeMapDateLabelSHBEFilename[0]; TreeMap<UKP_YM3, BigDecimal> fileLabelValue; fileLabelValue = (TreeMap<UKP_YM3, BigDecimal>) TreeMapDateLabelSHBEFilename[1]; Object[] data; data = getData(data0, xAxisLabels, fileLabelValue); // HashSet<String> selection = allSelections.get(selections); // data = getData(bigMatrix,selection,xAxisLabels); if (data != null) { chart.setData(data); chart.run(); future = chart.future; futures.add(future); } else { futures.add(chart.future); } } } } } } protected void graphTenancyTypeTransitions() throws IOException, Exception { ArrayList<String> month3Letters; month3Letters = Generic_Time.getMonths3Letters(); // Init allSelections of different types of tenancy type transitions to graph. HashMap<Boolean, HashMap<Boolean, HashMap<Boolean, TreeMap<String, HashSet<String>>>>> allSelections; allSelections = new HashMap<>(); // Init allSelections of different types of tenancy type transitions to graph. HashMap<Boolean, HashMap<Boolean, HashMap<Boolean, TreeMap<String, HashSet<String>>>>> allSelectionsGrouped; allSelectionsGrouped = new HashMap<>(); Iterator<Boolean> iteB; iteB = b.iterator(); while (iteB.hasNext()) { boolean do999; do999 = iteB.next(); HashMap<Boolean, HashMap<Boolean, TreeMap<String, HashSet<String>>>> asss; asss = new HashMap<>(); HashMap<Boolean, HashMap<Boolean, TreeMap<String, HashSet<String>>>> asssg; asssg = new HashMap<>(); Iterator<Boolean> iteB2; iteB2 = b.iterator(); while (iteB2.hasNext()) { boolean doUnderOccupancy; doUnderOccupancy = iteB2.next(); HashMap<Boolean, TreeMap<String, HashSet<String>>> ass; ass = new HashMap<>(); HashMap<Boolean, TreeMap<String, HashSet<String>>> assg; assg = new HashMap<>(); TreeMap<String, HashSet<String>> as; TreeMap<String, HashSet<String>> asg; Iterator<Boolean> iteB3; iteB3 = b.iterator(); while (iteB3.hasNext()) { boolean doSameTenancy; doSameTenancy = iteB3.next(); as = getAllSelections( doUnderOccupancy, do999, doSameTenancy); ass.put(doSameTenancy, as); asg = getAllSelectionsGrouped( doUnderOccupancy, do999, doSameTenancy); assg.put(doSameTenancy, asg); } asss.put(doUnderOccupancy, ass); asssg.put(doUnderOccupancy, assg); } allSelections.put(do999, asss); allSelectionsGrouped.put(do999, asssg); } Set<SHBE_ClaimID> UOApril2013ClaimIDs; UOApril2013ClaimIDs = uoHandler.getUOStartApril2013ClaimIDs(uoData); boolean CheckPreviousTenancyType; //// checkPreviousTenure = false; // checkPreviousTenure = false; iteB = b.iterator(); while (iteB.hasNext()) { CheckPreviousTenancyType = iteB.next(); env.ge.log("CheckPreviousTenancyType " + CheckPreviousTenancyType); Path dirIn; dirIn = files.getOutputSHBETablesTenancyTypeTransitionDir( //DW_DW_Strings.sPaymentTypeAll, CheckPreviousTenancyType); Path dirOut; dirOut = files.getOutputSHBEPlotsTenancyTypeTransitionDir( //DW_DW_Strings.sAll, CheckPreviousTenancyType); boolean tenancyOnly; // tenancyOnly = false; // Switch for testing. Iterator<Boolean> iteB1; iteB1 = b.iterator(); while (iteB1.hasNext()) { tenancyOnly = iteB1.next(); if (tenancyOnly) { Path dirIn2 = Paths.get( dirIn.toString(), DW_Strings.sWithOrWithoutPostcodeChange); Path dirOut2 = Paths.get( dirOut.toString(), DW_Strings.sWithOrWithoutPostcodeChange); Iterator<Boolean> iteB2; iteB2 = b.iterator(); boolean doUnderOccupancyData; // doUnderOccupancyData = false; // Switch for testing. Iterator<String> includesIte = includes.keySet().iterator(); while (includesIte.hasNext()) { String includeKey = includesIte.next(); ArrayList<Integer> include = includes.get(includeKey); Path dirIn3 = Paths.get(dirIn2.toString(), includeKey); Path dirOut3 = Paths.get(dirOut2.toString(), includeKey); /** * It is thought this should be a choice between doing * All or doing only those that were UO in April 2013. * This needs checking! */ dirIn3 = Paths.get(dirIn2.toString(), DW_Strings.sAll); dirOut3 = Paths.get(dirOut2.toString(), DW_Strings.sAll); while (iteB2.hasNext()) { doUnderOccupancyData = iteB2.next(); if (doUnderOccupancyData) { // boolean DoUOOnlyOnThoseOriginallyUO; // env.logO("<DoUOOnlyOnThoseOriginallyUO " + DoUOOnlyOnThoseOriginallyUO + ">", true); // Set<SHBE_ClaimID> UOApril2013ClaimIDsDummy; // if (DoUOOnlyOnThoseOriginallyUO) { // UOApril2013ClaimIDsDummy = UOApril2013ClaimIDs; // } else { // UOApril2013ClaimIDsDummy = null; // } Path dirIn4 = Paths.get(dirIn3.toString(), DW_Strings.sU); Path dirOut4 = Paths.get(dirOut3.toString(), DW_Strings.sU); Path dirIn5; Path dirOut5; boolean doAll = true; if (doAll) { dirIn5 = Paths.get(dirIn4.toString(), DW_Strings.s_B); dirOut5 = Paths.get(dirOut4.toString(), DW_Strings.s_B); Iterator<Boolean> iteB4; iteB4 = b.iterator(); while (iteB4.hasNext()) { boolean do999 = iteB4.next(); Path dirOut6; if (do999) { dirOut6 = Paths.get(dirOut5.toString(), DW_Strings.sInclude999); Iterator<Boolean> iteB5; iteB5 = b.iterator(); while (iteB5.hasNext()) { boolean doSameTenancy; doSameTenancy = iteB5.next(); Path dirOut7; if (doSameTenancy) { dirOut7 = Paths.get(dirOut6.toString(), SHBE_Strings.s_IncludeSameTenancy); } else { dirOut7 = Paths.get(dirOut6.toString(), SHBE_Strings.s_NotIncludeSameTenancy); } Iterator<Boolean> iteB6; iteB6 = b.iterator(); while (iteB6.hasNext()) { boolean grouped; grouped = iteB6.next(); if (grouped) { doSumat(dirIn5, dirOut7, include, includeKey, allSelectionsGrouped.get(doSameTenancy).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } else { doSumat(dirIn5, dirOut7, include, includeKey, allSelections.get(doSameTenancy).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } } } } else { dirOut6 = Paths.get(dirOut5.toString(), DW_Strings.sExclude999); Iterator<Boolean> iteB5; iteB5 = b.iterator(); while (iteB5.hasNext()) { boolean doSameTenancy; doSameTenancy = iteB5.next(); Path dirOut7; if (doSameTenancy) { dirOut7 = Paths.get(dirOut6.toString(), SHBE_Strings.s_IncludeSameTenancy); } else { dirOut7 = Paths.get(dirOut6.toString(), SHBE_Strings.s_NotIncludeSameTenancy); } Iterator<Boolean> iteB6; iteB6 = b.iterator(); while (iteB6.hasNext()) { boolean grouped; grouped = iteB6.next(); if (grouped) { doSumat(dirIn5, dirOut7, include, includeKey, allSelectionsGrouped.get(doSameTenancy).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } else { doSumat(dirIn5, dirOut7, include, includeKey, allSelections.get(doSameTenancy).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } } } } } } boolean doCouncilRSL = false; if (doCouncilRSL) { Iterator<Boolean> iteB3; iteB3 = b.iterator(); while (iteB3.hasNext()) { boolean doCouncil; doCouncil = iteB3.next(); if (doCouncil) { dirIn5 = Paths.get(dirIn4.toString(), DW_Strings.sCouncil); dirOut5 = Paths.get(dirOut4.toString(), DW_Strings.sCouncil); } else { dirIn5 = Paths.get(dirIn4.toString(), DW_Strings.sRSL); dirOut5 = Paths.get(dirOut4.toString(), DW_Strings.sRSL); } Iterator<Boolean> iteB4; iteB4 = b.iterator(); while (iteB4.hasNext()) { boolean do999 = iteB4.next(); Path dirOut6; if (do999) { dirOut6 = Paths.get(dirOut5.toString(), DW_Strings.sInclude999); Iterator<Boolean> iteB5 = b.iterator(); while (iteB5.hasNext()) { boolean doSameTenancy; doSameTenancy = iteB5.next(); Path dirOut7; if (doSameTenancy) { dirOut7 = Paths.get(dirOut6.toString(), SHBE_Strings.s_IncludeSameTenancy); } else { dirOut7 = Paths.get(dirOut6.toString(), SHBE_Strings.s_NotIncludeSameTenancy); } Iterator<Boolean> iteB6; iteB6 = b.iterator(); while (iteB6.hasNext()) { boolean grouped; grouped = iteB6.next(); if (grouped) { doSumat(dirIn5, dirOut7, include, includeKey, allSelectionsGrouped.get(doSameTenancy).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } else { doSumat( dirIn5, dirOut7, include, includeKey, allSelections.get(doSameTenancy).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } } } } else { dirOut6 = Paths.get(dirOut5.toString(), DW_Strings.sExclude999); Iterator<Boolean> iteB5; iteB5 = b.iterator(); while (iteB5.hasNext()) { boolean doSameTenancy; doSameTenancy = iteB5.next(); Path dirOut7; if (doSameTenancy) { dirOut7 = Paths.get(dirOut6.toString(), SHBE_Strings.s_IncludeSameTenancy); } else { dirOut7 = Paths.get(dirOut6.toString(), SHBE_Strings.s_NotIncludeSameTenancy); } Iterator<Boolean> iteB6; iteB6 = b.iterator(); while (iteB6.hasNext()) { boolean grouped; grouped = iteB6.next(); if (grouped) { doSumat(dirIn5, dirOut7, include, includeKey, allSelectionsGrouped.get(doSameTenancy).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } else { doSumat( dirIn5, dirOut7, include, includeKey, allSelections.get(doSameTenancy).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } } } } } } } } else { Path dirIn4 = Paths.get(dirIn3.toString(), DW_Strings.sU); Path dirOut4 = Paths.get(dirOut3.toString(), DW_Strings.sU); boolean doBoth = true; if (doBoth) { Path dirIn5 = Paths.get(dirIn4.toString(), DW_Strings.s_B); Path dirOut5 = Paths.get(dirOut4.toString(), DW_Strings.s_B); Iterator<Boolean> iteB3; iteB3 = b.iterator(); while (iteB3.hasNext()) { boolean do999 = iteB3.next(); Path dirOut6; if (do999) { dirOut6 = Paths.get(dirOut5.toString(), DW_Strings.sInclude999); Iterator<Boolean> iteB4; iteB4 = b.iterator(); while (iteB4.hasNext()) { boolean grouped; grouped = iteB4.next(); if (grouped) { doSumat(dirIn5, dirOut6, include, includeKey, allSelectionsGrouped.get(false).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } else { doSumat(dirIn5, dirOut4, include, includeKey, allSelections.get(false).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } } } else { dirOut6 = Paths.get(dirOut5.toString(), DW_Strings.sExclude999); Iterator<Boolean> iteB4; iteB4 = b.iterator(); while (iteB4.hasNext()) { boolean grouped; grouped = iteB4.next(); if (grouped) { doSumat(dirIn5, dirOut6, include, includeKey, allSelectionsGrouped.get(false).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } else { doSumat(dirIn5, dirOut6, include, includeKey, allSelections.get(false).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } } } } } } } } } else { Path dirIn2 = Paths.get(dirIn.toString(), DW_Strings.sTenancyAndPostcodeChanges); Path dirOut2 = Paths.get(dirOut.toString(), DW_Strings.sTenancyAndPostcodeChanges); Iterator<String> includesIte = includes.keySet().iterator(); while (includesIte.hasNext()) { String includeKey = includesIte.next(); ArrayList<Integer> include = includes.get(includeKey); Path dirIn3; Path dirOut3; dirIn3 = Paths.get(dirIn2.toString(), includeKey); dirOut3 = Paths.get(dirOut2.toString(), includeKey); /** * It is thought this should be a choice between doing * All or doing only those that were UO in April 2013. * This needs checking! */ dirIn3 = Paths.get(dirIn2.toString(), DW_Strings.sAll); dirOut3 = Paths.get(dirOut2.toString(), DW_Strings.sAll); boolean doUnderOccupancyData; // doUnderOccupancyData = false; Iterator<Boolean> iteB2; iteB2 = b.iterator(); while (iteB2.hasNext()) { doUnderOccupancyData = iteB2.next(); if (doUnderOccupancyData) { Path dirIn4; Path dirOut4; dirIn4 = Paths.get(dirIn3.toString(), DW_Strings.sU); dirOut4 = Paths.get(dirOut3.toString(), DW_Strings.sU); boolean doBoth; doBoth = true; if (doBoth) { Path dirIn5; Path dirOut5; dirIn5 = Paths.get(dirIn4.toString(), DW_Strings.s_B); dirOut5 = Paths.get(dirOut4.toString(), DW_Strings.s_B); // Iterator<String> includesIte; // includesIte = includes.keySet().iterator(); // while (includesIte.hasNext()) { // String include; // include = includesIte.next(); // Path dirIn5; // Path dirOut5; // dirIn5 = Paths.get(dirIn4, include); // dirOut5 = Paths.get(dirOut4, include); // } Iterator<Boolean> iteB4 = b.iterator(); while (iteB4.hasNext()) { boolean grouped = iteB4.next(); Iterator<Boolean> iteB5 = b.iterator(); while (iteB5.hasNext()) { boolean postcodeChanged = iteB5.next(); Path dirIn6; Path dirOut6; if (postcodeChanged) { dirIn6 = Paths.get(dirIn5.toString(), DW_Strings.sPostcodeChanged); dirOut6 = Paths.get(dirOut5.toString(), DW_Strings.sPostcodeChanged); } else { dirIn6 = Paths.get(dirIn5.toString(), DW_Strings.sPostcodeChangedNo); dirOut6 = Paths.get(dirOut5.toString(), DW_Strings.sPostcodeChangedNo); } Iterator<Boolean> iteB6; iteB6 = b.iterator(); while (iteB6.hasNext()) { boolean do999 = iteB6.next(); Path dirOut7; if (do999) { dirOut7 = Paths.get(dirOut6.toString(), DW_Strings.sInclude999); Iterator<Boolean> iteB7; iteB7 = b.iterator(); while (iteB7.hasNext()) { boolean doSameTenancy; doSameTenancy = iteB7.next(); Path dirOut8; if (doSameTenancy) { dirOut8 = Paths.get(dirOut7.toString(), SHBE_Strings.s_IncludeSameTenancy); } else { dirOut8 = Paths.get(dirOut7.toString(), SHBE_Strings.s_NotIncludeSameTenancy); } if (grouped) { doSumat(dirIn6, dirOut8, include, includeKey, allSelectionsGrouped.get(doSameTenancy).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } else { doSumat(dirIn6, dirOut8, include, includeKey, allSelections.get(doSameTenancy).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } } } else { dirOut7 = Paths.get(dirOut6.toString(), DW_Strings.sExclude999); Iterator<Boolean> iteB7; iteB7 = b.iterator(); while (iteB7.hasNext()) { boolean doSameTenancy; doSameTenancy = iteB7.next(); Path dirOut8; if (doSameTenancy) { dirOut8 = Paths.get(dirOut7.toString(), SHBE_Strings.s_IncludeSameTenancy); } else { dirOut8 = Paths.get(dirOut7.toString(), SHBE_Strings.s_NotIncludeSameTenancy); } if (grouped) { doSumat(dirIn6, dirOut8, include, includeKey, allSelectionsGrouped.get(doSameTenancy).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } else { doSumat(dirIn6, dirOut8, include, includeKey, allSelections.get(doSameTenancy).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } } } } } } } Iterator<Boolean> iteB3; iteB3 = b.iterator(); while (iteB3.hasNext()) { boolean doCouncil; doCouncil = iteB3.next(); if (doCouncil) { dirIn4 = Paths.get(dirIn3.toString(), DW_Strings.sCouncil); dirOut4 = Paths.get(dirOut3.toString(), DW_Strings.sCouncil); } else { dirIn4 = Paths.get(dirIn3.toString(), DW_Strings.sRSL); dirOut4 = Paths.get(dirOut3.toString(), DW_Strings.sRSL); } Iterator<Boolean> iteB4; iteB4 = b.iterator(); while (iteB4.hasNext()) { boolean grouped; grouped = iteB4.next(); Path dirIn5; Path dirOut5; if (grouped) { dirIn5 = Paths.get(dirIn4.toString(), DW_Strings.sGrouped); dirOut5 = Paths.get(dirOut4.toString(), DW_Strings.sGrouped); } else { dirIn5 = Paths.get(dirIn4.toString(), DW_Strings.sGroupedNo); dirOut5 = Paths.get(dirOut4.toString(), DW_Strings.sGroupedNo); } Iterator<Boolean> iteB5 = b.iterator(); while (iteB5.hasNext()) { boolean postcodeChanged = iteB5.next(); Path dirIn6; Path dirOut6; if (postcodeChanged) { dirIn6 = Paths.get(dirIn5.toString(), DW_Strings.sPostcodeChanged); dirOut6 = Paths.get(dirOut5.toString(), DW_Strings.sPostcodeChanged); } else { dirIn6 = Paths.get(dirIn5.toString(), DW_Strings.sPostcodeChangedNo); dirOut6 = Paths.get(dirOut5.toString(), DW_Strings.sPostcodeChangedNo); } Iterator<Boolean> iteB6; iteB6 = b.iterator(); while (iteB6.hasNext()) { boolean do999 = iteB6.next(); Path dirOut7; if (do999) { dirOut7 = Paths.get(dirOut6.toString(), DW_Strings.sInclude999); Iterator<Boolean> iteB7; iteB7 = b.iterator(); while (iteB7.hasNext()) { boolean doSameTenancy; doSameTenancy = iteB7.next(); Path dirOut8; if (doSameTenancy) { dirOut8 = Paths.get(dirOut7.toString(), SHBE_Strings.s_IncludeSameTenancy); } else { dirOut8 = Paths.get(dirOut7.toString(), SHBE_Strings.s_NotIncludeSameTenancy); } if (grouped) { doSumat(dirIn6, dirOut8, include, includeKey, allSelectionsGrouped.get(doSameTenancy).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } else { doSumat(dirIn6, dirOut8, include, includeKey, allSelections.get(doSameTenancy).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } } } else { dirOut7 = Paths.get(dirOut6.toString(), DW_Strings.sExclude999); Iterator<Boolean> iteB7; iteB7 = b.iterator(); while (iteB7.hasNext()) { boolean doSameTenancy; doSameTenancy = iteB7.next(); Path dirOut8; if (doSameTenancy) { dirOut8 = Paths.get(dirOut7.toString(), SHBE_Strings.s_IncludeSameTenancy); } else { dirOut8 = Paths.get(dirOut7.toString(), SHBE_Strings.s_NotIncludeSameTenancy); } if (grouped) { doSumat(dirIn6, dirOut8, include, includeKey, allSelectionsGrouped.get(doSameTenancy).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } else { doSumat(dirIn6, dirOut8, include, includeKey, allSelections.get(doSameTenancy).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } } } } } } } } else { Path dirIn4; Path dirOut4; dirIn4 = Paths.get(dirIn3.toString(), DW_Strings.sAll); dirOut4 = Paths.get(dirOut3.toString(), DW_Strings.sAll); Iterator<Boolean> iteB3; iteB3 = b.iterator(); while (iteB3.hasNext()) { boolean grouped = iteB3.next(); Iterator<Boolean> iteB4 = b.iterator(); while (iteB4.hasNext()) { boolean postcodeChanged = iteB4.next(); Path dirIn5; Path dirOut5; if (postcodeChanged) { dirIn5 = Paths.get(dirIn4.toString(), DW_Strings.sPostcodeChanged); dirOut5 = Paths.get(dirOut4.toString(), DW_Strings.sPostcodeChanged); } else { dirIn5 = Paths.get(dirIn4.toString(), DW_Strings.sPostcodeChangedNo); dirOut5 = Paths.get(dirOut4.toString(), DW_Strings.sPostcodeChangedNo); } Iterator<Boolean> iteB5; iteB5 = b.iterator(); while (iteB5.hasNext()) { boolean do999 = iteB5.next(); Path dirOut6; if (do999) { dirOut6 = Paths.get(dirOut5.toString(), DW_Strings.sInclude999); if (grouped) { doSumat(dirIn5, dirOut6, include, includeKey, allSelectionsGrouped.get(false).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } else { doSumat(dirIn5, dirOut6, include, includeKey, allSelections.get(false).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } } else { dirOut6 = Paths.get(dirOut5.toString(), DW_Strings.sExclude999); if (grouped) { doSumat(dirIn5, dirOut6, include, includeKey, allSelectionsGrouped.get(false).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } else { doSumat(dirIn5, dirOut6, include, includeKey, allSelections.get(false).get(do999).get(doUnderOccupancyData), futures, format, SHBEFilenames, grouped, month3Letters); } } } } } } } } } } } exec.shutdownExecutorService(executorService, futures, this); env.ge.log("</run>"); } private void doSumat(Path dirIn, Path dirOut, ArrayList<Integer> include, String includeKey, TreeMap<String, HashSet<String>> allSelections, HashSet<Future> futures, String format, String[] SHBEFilenames, boolean grouped, ArrayList<String> month3Letters) throws IOException, Exception { // Iterator<String> includesIte; // includesIte = includes.keySet().iterator(); // while (includesIte.hasNext()) { // String includeKey; // includeKey = includesIte.next(); // Path dirIn2; // dirIn2 = Paths.get( dirIn, includeKey); //// doneFirsts.put(includeKey, false); // ArrayList<Integer> include; // include = includes.get(includeKey); Object[] treeMapDateLabelSHBEFilename; treeMapDateLabelSHBEFilename = shbeData.getTreeMapDateLabelSHBEFilenames( SHBEFilenames, include); TreeMap<BigDecimal, String> xAxisLabels; xAxisLabels = (TreeMap<BigDecimal, String>) treeMapDateLabelSHBEFilename[0]; TreeMap<String, BigDecimal> fileLabelValue; fileLabelValue = (TreeMap<String, BigDecimal>) treeMapDateLabelSHBEFilename[1]; TreeMap<BigDecimal, TreeMap<String, TreeMap<String, BigDecimal>>> bigMatrix; bigMatrix = new TreeMap<>(); // int size = Integer.MIN_VALUE; // Double min = Double.MAX_VALUE; // Double max = Double.MIN_VALUE; boolean doneFirst; doneFirst = false; UKP_YM3 YM30 = null; String yM30 = ""; Iterator<Integer> includeIte; includeIte = include.iterator(); while (includeIte.hasNext()) { int i = includeIte.next(); if (!doneFirst) { if (include.contains(i - 1) && (i - 1) >= 0) { String aSHBEFilename0; aSHBEFilename0 = SHBEFilenames[i - 1]; YM30 = shbeData.getYM3(aSHBEFilename0); yM30 = YM30.toString(); doneFirst = true; } } if (doneFirst) { String aSHBEFilename1; aSHBEFilename1 = SHBEFilenames[i]; UKP_YM3 YM31; YM31 = shbeData.getYM3(aSHBEFilename1); String yM31; yM31 = YM31.toString(); String filename; filename = DW_Strings.sTenancyTypeTransition + "_Start_" + YM30 + "_End_" + YM31 + ".csv"; if (include.contains(i)) { Path dirIn3; double timeDiff; timeDiff = Generic_Time.getMonthDiff(YM30.getYear(), YM31.getYear(), YM30.getMonth(), YM31.getMonth()); String label; label = getLabel(yM30, yM31); BigDecimal key; key = fileLabelValue.get(label); if (grouped) { // dirIn3 = Paths.get(dirIn, DW_DW_Strings.sAll); dirIn3 = Paths.get(dirIn.toString(), DW_Strings.sGrouped); Path f = Paths.get(dirIn3.toString(), filename); if (Files.exists(f)) { System.out.println("Using file " + f); TreeMap<String, TreeMap<String, BigDecimal>> tttmg; tttmg = getTenancyTypeTransitionMapGrouped( f, timeDiff); if (key != null) { bigMatrix.put(key, tttmg); } else { System.out.println("No value for label " + label); } } else { System.out.println(f + " does not exist"); } } else { // dirIn3 = Paths.get(dirIn, DW_DW_Strings.sAll); dirIn3 = Paths.get(dirIn.toString(), DW_Strings.sGroupedNo); Path f = Paths.get(dirIn3.toString(), filename); if (Files.exists(f)) { System.out.println("Using file " + f); // TenancyTypeBefore, TenancyTypeNow Counts. TreeMap<String, TreeMap<String, BigDecimal>> tenancyTypeTransitionMap; tenancyTypeTransitionMap = getTenancyTypeTransitionMap( f, timeDiff); // Object[] tenancyTypeTransitionMatrixMinMaxSize; // tenancyTypeTransitionMatrixMinMaxSize = getTenancyTypeTransitionMap( // f, // timeDiff); // tenancyTypeTransitionMap = (TreeMap<Integer, TreeMap<Integer, BigDecimal>>) tenancyTypeTransitionMatrixMinMaxSize[0]; // Double tenancyTypeTransitionMatrixMin; // tenancyTypeTransitionMatrixMin = (Double) tenancyTypeTransitionMatrixMinMaxSize[1]; // min = Math.min(tenancyTypeTransitionMatrixMin, min); // Double tenancyTypeTransitionMatrixMax; // tenancyTypeTransitionMatrixMax = (Double) tenancyTypeTransitionMatrixMinMaxSize[2]; // max = Math.max(tenancyTypeTransitionMatrixMax, max); // size = Math.max(size, (Integer) tenancyTypeTransitionMatrixMinMaxSize[3]); //System.out.println("fileLabel " + fileLabel); //System.out.println("key " + key); if (key != null) { bigMatrix.put(key, tenancyTypeTransitionMap); // System.out.println("max " + max); // System.out.println("min " + min); // System.out.println("size " + size); } else { System.out.println("No value for label " + label); } } else { System.out.println(f + " does not exist"); } } YM30 = YM31; yM30 = YM30.toString(); } else { System.out.println("Omitted file " + filename); } } } if (!bigMatrix.isEmpty()) { Path dirOut2 = Paths.get(dirOut.toString(), includeKey); if (grouped) { dirOut2 = Paths.get(dirOut2.toString(), DW_Strings.sGrouped); } else { dirOut2 = Paths.get(dirOut2.toString(), DW_Strings.sGroupedNo); } Iterator<String> allSelectionsIte = allSelections.keySet().iterator(); while (allSelectionsIte.hasNext()) { String selections = allSelectionsIte.next(); //dirOut2.mkdirs(); // only make if there is result. Path fout; fout = Paths.get(dirOut2.toString(), DW_Strings.sTenancyTypeTransitionLineGraph + selections + ".PNG"); yAxisLabel = "Tenancy Changes Per Month"; title = "Tenancy Transition Line Graph"; DW_LineGraph chart = new DW_LineGraph(env, executorService, fout, format, title, getDataWidth(), getDataHeight(), xAxisLabel, yAxisLabel, yMax, yPin, yIncrement, numberOfYAxisTicks, decimalPlacePrecisionForCalculations, decimalPlacePrecisionForDisplay, getRoundingMode()); HashSet<String> selection = allSelections.get(selections); data = getData(bigMatrix, selection, xAxisLabels); if (data != null) { BigDecimal newMinY; newMinY = (BigDecimal) data[1]; BigDecimal newMaxY; newMaxY = (BigDecimal) data[2]; if (newMaxY.compareTo(new BigDecimal(Double.MIN_VALUE)) != 1) { if (newMinY.compareTo(newMaxY) == 1) { env.ge.log("newMinY.compareTo(newMaxY) == 1 so no graph is produced."); } else { Files.createDirectories(dirOut2); chart.setData(data); //chart.run(); future = chart.future; futures.add(future); } } else { env.ge.log("No values, so no graph is produced."); } } else { //futures.add(chart.future); } } } //} } /** * @param doUnderOccupancy * @param do999 * @param sameTenancyType * @return */ protected TreeMap<String, HashSet<String>> getAllSelections( boolean doUnderOccupancy, boolean do999, boolean sameTenancyType) { TreeMap<String, HashSet<String>> result; result = new TreeMap<>(); String selectionName; selectionName = DW_Strings.sCouncil; HashSet<String> CouncilSelection; CouncilSelection = new HashSet<>(); if (doUnderOccupancy) { if (sameTenancyType) { CouncilSelection.add("1UO - 1"); CouncilSelection.add("1 - 1UO"); CouncilSelection.add("1UO - 1UO"); } CouncilSelection.add("1UO - 2"); CouncilSelection.add("1 - 2UO"); CouncilSelection.add("1UO - 2UO"); CouncilSelection.add("1UO - 3"); CouncilSelection.add("1 - 3UO"); CouncilSelection.add("1UO - 3UO"); CouncilSelection.add("1UO - 4"); CouncilSelection.add("1 - 4UO"); CouncilSelection.add("1UO - 4UO"); CouncilSelection.add("1UO - 5"); CouncilSelection.add("1 - 5UO"); CouncilSelection.add("1UO - 5UO"); CouncilSelection.add("1UO - 6"); CouncilSelection.add("1 - 6UO"); CouncilSelection.add("1UO - 6UO"); CouncilSelection.add("1UO - 7"); CouncilSelection.add("1 - 7UO"); CouncilSelection.add("1UO - 7UO"); CouncilSelection.add("1UO - 8"); CouncilSelection.add("1 - 8UO"); CouncilSelection.add("1UO - 8UO"); CouncilSelection.add("1UO - 9"); CouncilSelection.add("1 - 9UO"); CouncilSelection.add("1UO - 9UO"); if (do999) { CouncilSelection.add("1UO - -999"); CouncilSelection.add("-999 - 1UO"); CouncilSelection.add("1 - -999UO"); CouncilSelection.add("-999UO - 1"); CouncilSelection.add("1UO - -999UO"); CouncilSelection.add("-999UO - 1UO"); } } else { if (sameTenancyType) { CouncilSelection.add("1 - 1"); } CouncilSelection.add("1 - 2"); CouncilSelection.add("1 - 3"); CouncilSelection.add("1 - 4"); CouncilSelection.add("1 - 5"); CouncilSelection.add("1 - 6"); CouncilSelection.add("1 - 7"); CouncilSelection.add("1 - 8"); CouncilSelection.add("1 - 9"); if (do999) { CouncilSelection.add("1 - -999"); CouncilSelection.add("-999 - 1"); } } result.put(selectionName, CouncilSelection); selectionName = "PrivateRegulated"; HashSet<String> PrivateRegulatedSelection; PrivateRegulatedSelection = new HashSet<>(); if (doUnderOccupancy) { if (sameTenancyType) { PrivateRegulatedSelection.add("2UO - 2"); PrivateRegulatedSelection.add("2 - 2UO"); PrivateRegulatedSelection.add("2UO - 2UO"); } PrivateRegulatedSelection.add("2UO - 1"); PrivateRegulatedSelection.add("2 - 1UO"); PrivateRegulatedSelection.add("2UO - 1UO"); PrivateRegulatedSelection.add("2UO - 3"); PrivateRegulatedSelection.add("2 - 3UO"); PrivateRegulatedSelection.add("2UO - 3UO"); PrivateRegulatedSelection.add("2UO - 4"); PrivateRegulatedSelection.add("2 - 4UO"); PrivateRegulatedSelection.add("2UO - 4UO"); PrivateRegulatedSelection.add("2UO - 5"); PrivateRegulatedSelection.add("2 - 5UO"); PrivateRegulatedSelection.add("2UO - 5UO"); PrivateRegulatedSelection.add("2UO - 6"); PrivateRegulatedSelection.add("2 - 6UO"); PrivateRegulatedSelection.add("2UO - 6UO"); PrivateRegulatedSelection.add("2UO - 7"); PrivateRegulatedSelection.add("2 - 7UO"); PrivateRegulatedSelection.add("2UO - 7UO"); PrivateRegulatedSelection.add("2UO - 8"); PrivateRegulatedSelection.add("2 - 8UO"); PrivateRegulatedSelection.add("2UO - 8UO"); PrivateRegulatedSelection.add("2UO - 9"); PrivateRegulatedSelection.add("2 - 9UO"); PrivateRegulatedSelection.add("2UO - 9UO"); if (do999) { PrivateRegulatedSelection.add("2UO - -999"); PrivateRegulatedSelection.add("-999 - 2UO"); PrivateRegulatedSelection.add("2 - -999UO"); PrivateRegulatedSelection.add("-999UO - 2UO"); PrivateRegulatedSelection.add("2UO - -999UO"); PrivateRegulatedSelection.add("-999UO - 2UO"); } } else { if (sameTenancyType) { PrivateRegulatedSelection.add("2 - 2"); } PrivateRegulatedSelection.add("2 - 1"); PrivateRegulatedSelection.add("2 - 3"); PrivateRegulatedSelection.add("2 - 4"); PrivateRegulatedSelection.add("2 - 5"); PrivateRegulatedSelection.add("2 - 6"); PrivateRegulatedSelection.add("2 - 7"); PrivateRegulatedSelection.add("2 - 8"); PrivateRegulatedSelection.add("2 - 9"); if (do999) { PrivateRegulatedSelection.add("2 - -999"); PrivateRegulatedSelection.add("-999 - 2"); } } result.put(selectionName, PrivateRegulatedSelection); HashSet<String> PrivateDeregulatedSelection; PrivateDeregulatedSelection = new HashSet<>(); selectionName = "PrivateDeregulated"; if (doUnderOccupancy) { if (sameTenancyType) { PrivateDeregulatedSelection.add("3UO - 3"); PrivateDeregulatedSelection.add("3 - 3UO"); PrivateDeregulatedSelection.add("3UO - 3UO"); } PrivateDeregulatedSelection.add("3UO - 1"); PrivateDeregulatedSelection.add("3 - 1UO"); PrivateDeregulatedSelection.add("3UO - 1UO"); PrivateDeregulatedSelection.add("3UO - 2"); PrivateDeregulatedSelection.add("3 - 2UO"); PrivateDeregulatedSelection.add("3UO - 2UO"); PrivateDeregulatedSelection.add("3UO - 2UO"); PrivateDeregulatedSelection.add("3UO - 4"); PrivateDeregulatedSelection.add("3 - 4UO"); PrivateDeregulatedSelection.add("3UO - 4UO"); PrivateDeregulatedSelection.add("3UO - 5"); PrivateDeregulatedSelection.add("3 - 5UO"); PrivateDeregulatedSelection.add("3UO - 5UO"); PrivateDeregulatedSelection.add("3UO - 6"); PrivateDeregulatedSelection.add("3 - 6UO"); PrivateDeregulatedSelection.add("3UO - 6UO"); PrivateDeregulatedSelection.add("3UO - 7"); PrivateDeregulatedSelection.add("3 - 7UO"); PrivateDeregulatedSelection.add("3UO - 7UO"); PrivateDeregulatedSelection.add("3UO - 8"); PrivateDeregulatedSelection.add("3 - 8UO"); PrivateDeregulatedSelection.add("3UO - 8UO"); PrivateDeregulatedSelection.add("3UO - 9"); PrivateDeregulatedSelection.add("3 - 9UO"); PrivateDeregulatedSelection.add("3UO - 9UO"); if (do999) { PrivateDeregulatedSelection.add("3UO - -999"); PrivateDeregulatedSelection.add("-999 - 3UO"); PrivateDeregulatedSelection.add("3 - -999UO"); PrivateDeregulatedSelection.add("-999UO - 3"); PrivateDeregulatedSelection.add("3UO - -999UO"); PrivateDeregulatedSelection.add("-999UO - 3UO"); } } else { if (sameTenancyType) { PrivateDeregulatedSelection.add("3 - 3"); } PrivateDeregulatedSelection.add("3 - 1"); PrivateDeregulatedSelection.add("3 - 2"); PrivateDeregulatedSelection.add("3 - 4"); PrivateDeregulatedSelection.add("3 - 5"); PrivateDeregulatedSelection.add("3 - 6"); PrivateDeregulatedSelection.add("3 - 7"); PrivateDeregulatedSelection.add("3 - 8"); PrivateDeregulatedSelection.add("3 - 9"); if (do999) { PrivateDeregulatedSelection.add("3 - -999"); PrivateDeregulatedSelection.add("-999 - 3"); } } result.put(selectionName, PrivateDeregulatedSelection); HashSet<String> PrivateHousingAssociationSelection; PrivateHousingAssociationSelection = new HashSet<>(); selectionName = "PrivateHousingAssociation"; if (doUnderOccupancy) { if (sameTenancyType) { PrivateHousingAssociationSelection.add("4UO - 4"); PrivateHousingAssociationSelection.add("4 - 4UO"); PrivateHousingAssociationSelection.add("4UO - 4UO"); } PrivateHousingAssociationSelection.add("4UO - 4"); PrivateHousingAssociationSelection.add("4 - 4UO"); PrivateHousingAssociationSelection.add("4UO - 1"); PrivateHousingAssociationSelection.add("4 - 1UO"); PrivateHousingAssociationSelection.add("4UO - 1UO"); PrivateHousingAssociationSelection.add("4UO - 2"); PrivateHousingAssociationSelection.add("4 - 2UO"); PrivateHousingAssociationSelection.add("4UO - 2UO"); PrivateHousingAssociationSelection.add("4UO - 3"); PrivateHousingAssociationSelection.add("4 - 3UO"); PrivateHousingAssociationSelection.add("4UO - 3UO"); PrivateHousingAssociationSelection.add("4UO - 5"); PrivateHousingAssociationSelection.add("4 - 5UO"); PrivateHousingAssociationSelection.add("4UO - 5UO"); PrivateHousingAssociationSelection.add("4UO - 6"); PrivateHousingAssociationSelection.add("4 - 6UO"); PrivateHousingAssociationSelection.add("4UO - 6UO"); PrivateHousingAssociationSelection.add("4UO - 7"); PrivateHousingAssociationSelection.add("4 - 7UO"); PrivateHousingAssociationSelection.add("4UO - 7UO"); PrivateHousingAssociationSelection.add("4UO - 8"); PrivateHousingAssociationSelection.add("4 - 8UO"); PrivateHousingAssociationSelection.add("4UO - 8UO"); PrivateHousingAssociationSelection.add("4UO - 9"); PrivateHousingAssociationSelection.add("4 - 9UO"); PrivateHousingAssociationSelection.add("4UO - 9UO"); if (do999) { PrivateHousingAssociationSelection.add("4UO - -999"); PrivateHousingAssociationSelection.add("-999 - 4UO"); PrivateHousingAssociationSelection.add("4 - -999UO"); PrivateHousingAssociationSelection.add("-999UO - 4"); PrivateHousingAssociationSelection.add("4UO - -999UO"); PrivateHousingAssociationSelection.add("-999UO - 4UO"); } } else { if (sameTenancyType) { PrivateHousingAssociationSelection.add("4 - 4"); } PrivateHousingAssociationSelection.add("4 - 1"); PrivateHousingAssociationSelection.add("4 - 2"); PrivateHousingAssociationSelection.add("4 - 3"); PrivateHousingAssociationSelection.add("4 - 5"); PrivateHousingAssociationSelection.add("4 - 6"); PrivateHousingAssociationSelection.add("4 - 7"); PrivateHousingAssociationSelection.add("4 - 8"); PrivateHousingAssociationSelection.add("4 - 9"); if (do999) { PrivateHousingAssociationSelection.add("4 - -999"); PrivateHousingAssociationSelection.add("-999 - 4"); } } result.put(selectionName, PrivateHousingAssociationSelection); HashSet<String> PrivateOtherSelection; PrivateOtherSelection = new HashSet<>(); selectionName = "PrivateOther"; if (doUnderOccupancy) { if (sameTenancyType) { PrivateOtherSelection.add("6UO - 6"); PrivateOtherSelection.add("6 - 6UO"); PrivateOtherSelection.add("6UO - 6UO"); } PrivateOtherSelection.add("6UO - 1"); PrivateOtherSelection.add("6 - 1UO"); PrivateOtherSelection.add("6UO - 1UO"); PrivateOtherSelection.add("6UO - 2"); PrivateOtherSelection.add("6 - 2UO"); PrivateOtherSelection.add("6UO - 2UO"); PrivateOtherSelection.add("6UO - 3"); PrivateOtherSelection.add("6 - 3UO"); PrivateOtherSelection.add("6UO - 3UO"); PrivateOtherSelection.add("6UO - 4"); PrivateOtherSelection.add("6 - 4UO"); PrivateOtherSelection.add("6UO - 4UO"); PrivateOtherSelection.add("6UO - 5"); PrivateOtherSelection.add("6 - 5UO"); PrivateOtherSelection.add("6UO - 5UO"); PrivateOtherSelection.add("6UO - 7"); PrivateOtherSelection.add("6 - 7UO"); PrivateOtherSelection.add("6UO - 7UO"); PrivateOtherSelection.add("6UO - 8"); PrivateOtherSelection.add("6 - 8UO"); PrivateOtherSelection.add("6UO - 8UO"); PrivateOtherSelection.add("6UO - 9"); PrivateOtherSelection.add("6 - 9UO"); PrivateOtherSelection.add("6UO - 9UO"); if (do999) { PrivateOtherSelection.add("6UO - -999"); PrivateOtherSelection.add("-999 - 6UO"); PrivateOtherSelection.add("6 - -999UO"); PrivateOtherSelection.add("-999UO - 6"); PrivateOtherSelection.add("6UO - -999UO"); PrivateOtherSelection.add("-999UO - 6UO"); } } else { if (sameTenancyType) { PrivateOtherSelection.add("6 - 6"); } PrivateOtherSelection.add("6 - 1"); PrivateOtherSelection.add("6 - 2"); PrivateOtherSelection.add("6 - 3"); PrivateOtherSelection.add("6 - 4"); PrivateOtherSelection.add("6 - 5"); PrivateOtherSelection.add("6 - 7"); PrivateOtherSelection.add("6 - 8"); PrivateOtherSelection.add("6 - 9"); if (do999) { PrivateOtherSelection.add("6 - -999"); PrivateOtherSelection.add("-999 - 6"); } } result.put(selectionName, PrivateOtherSelection); HashSet<String> CTBOnlySelection; CTBOnlySelection = new HashSet<>(); selectionName = "CTBOnly"; if (doUnderOccupancy) { if (sameTenancyType) { CTBOnlySelection.add("5 - 5UO"); CTBOnlySelection.add("5UO - 5"); CTBOnlySelection.add("5UO - 5UO"); CTBOnlySelection.add("7 - 7UO"); CTBOnlySelection.add("7UO - 7"); CTBOnlySelection.add("7UO - 7UO"); } // 5 CTBOnlySelection.add("5UO - 1"); CTBOnlySelection.add("5 - 1UO"); CTBOnlySelection.add("5UO - 1UO"); CTBOnlySelection.add("5UO - 2"); CTBOnlySelection.add("5 - 2UO"); CTBOnlySelection.add("5UO - 2UO"); CTBOnlySelection.add("5UO - 3"); CTBOnlySelection.add("5 - 3UO"); CTBOnlySelection.add("5UO - 3UO"); CTBOnlySelection.add("5UO - 4"); CTBOnlySelection.add("5 - 4UO"); CTBOnlySelection.add("5UO - 4UO"); CTBOnlySelection.add("5UO - 6"); CTBOnlySelection.add("5 - 6UO"); CTBOnlySelection.add("5UO - 6UO"); CTBOnlySelection.add("5UO - 7"); CTBOnlySelection.add("5 - 7UO"); CTBOnlySelection.add("5UO - 7UO"); CTBOnlySelection.add("5UO - 8"); CTBOnlySelection.add("5 - 8UO"); CTBOnlySelection.add("5UO - 8UO"); CTBOnlySelection.add("5UO - 9"); CTBOnlySelection.add("5 - 9UO"); CTBOnlySelection.add("5UO - 9UO"); // 7 CTBOnlySelection.add("7UO - 1"); CTBOnlySelection.add("7 - 1UO"); CTBOnlySelection.add("7UO - 1UO"); CTBOnlySelection.add("7UO - 2"); CTBOnlySelection.add("7 - 2UO"); CTBOnlySelection.add("7UO - 2UO"); CTBOnlySelection.add("7UO - 3"); CTBOnlySelection.add("7 - 3UO"); CTBOnlySelection.add("7UO - 3UO"); CTBOnlySelection.add("7UO - 4"); CTBOnlySelection.add("7 - 4UO"); CTBOnlySelection.add("7UO - 4UO"); CTBOnlySelection.add("7UO - 5"); CTBOnlySelection.add("7 - 5UO"); CTBOnlySelection.add("7UO - 5UO"); CTBOnlySelection.add("7UO - 6"); CTBOnlySelection.add("7 - 6UO"); CTBOnlySelection.add("7UO - 6UO"); CTBOnlySelection.add("7UO - 8"); CTBOnlySelection.add("7 - 8UO"); CTBOnlySelection.add("7UO - 8UO"); CTBOnlySelection.add("7UO - 9"); CTBOnlySelection.add("7 - 9UO"); CTBOnlySelection.add("7UO - 9UO"); if (do999) { CTBOnlySelection.add("5UO - -999"); CTBOnlySelection.add("-999 - 5UO"); CTBOnlySelection.add("5 - -999UO"); CTBOnlySelection.add("-999UO - 5"); CTBOnlySelection.add("5UO - -999UO"); CTBOnlySelection.add("-999UO - 5UO"); CTBOnlySelection.add("7UO - -999"); CTBOnlySelection.add("-999 - 7UO"); CTBOnlySelection.add("7 - -999UO"); CTBOnlySelection.add("-999UO - 7"); CTBOnlySelection.add("7UO - -999UO"); CTBOnlySelection.add("-999UO - 7UO"); } } else { if (sameTenancyType) { CTBOnlySelection.add("5 - 5"); CTBOnlySelection.add("7 - 7"); } // 5 CTBOnlySelection.add("7 - 1"); CTBOnlySelection.add("7 - 2"); CTBOnlySelection.add("7 - 3"); CTBOnlySelection.add("7 - 4"); CTBOnlySelection.add("7 - 5"); CTBOnlySelection.add("7 - 6"); CTBOnlySelection.add("7 - 8"); CTBOnlySelection.add("7 - 9"); // 7 CTBOnlySelection.add("7 - 1"); CTBOnlySelection.add("7 - 2"); CTBOnlySelection.add("7 - 3"); CTBOnlySelection.add("7 - 4"); CTBOnlySelection.add("7 - 5"); CTBOnlySelection.add("7 - 6"); CTBOnlySelection.add("7 - 8"); CTBOnlySelection.add("7 - 9"); if (do999) { CTBOnlySelection.add("7 - -999"); CTBOnlySelection.add("-999 - 7"); } } result.put(selectionName, CTBOnlySelection); HashSet<String> CouncilNonHRAOnlySelection; CouncilNonHRAOnlySelection = new HashSet<>(); selectionName = "CouncilNonHRA"; if (doUnderOccupancy) { if (sameTenancyType) { CouncilNonHRAOnlySelection.add("8 - 8UO"); CouncilNonHRAOnlySelection.add("8UO - 8"); CouncilNonHRAOnlySelection.add("8UO - 8UO"); } CouncilNonHRAOnlySelection.add("8UO - 1"); CouncilNonHRAOnlySelection.add("8 - 1UO"); CouncilNonHRAOnlySelection.add("8UO - 1UO"); CouncilNonHRAOnlySelection.add("8UO - 2"); CouncilNonHRAOnlySelection.add("8 - 2UO"); CouncilNonHRAOnlySelection.add("8UO - 2UO"); CouncilNonHRAOnlySelection.add("8UO - 3"); CouncilNonHRAOnlySelection.add("8 - 3UO"); CouncilNonHRAOnlySelection.add("8UO - 3UO"); CouncilNonHRAOnlySelection.add("8UO - 4"); CouncilNonHRAOnlySelection.add("8 - 4UO"); CouncilNonHRAOnlySelection.add("8UO - 4UO"); CouncilNonHRAOnlySelection.add("8UO - 5"); CouncilNonHRAOnlySelection.add("8 - 5UO"); CouncilNonHRAOnlySelection.add("8UO - 5UO"); CouncilNonHRAOnlySelection.add("8UO - 6"); CouncilNonHRAOnlySelection.add("8 - 6UO"); CouncilNonHRAOnlySelection.add("8UO - 6UO"); CouncilNonHRAOnlySelection.add("8UO - 7"); CouncilNonHRAOnlySelection.add("8 - 7UO"); CouncilNonHRAOnlySelection.add("8UO - 7UO"); CouncilNonHRAOnlySelection.add("8UO - 9"); CouncilNonHRAOnlySelection.add("8 - 9UO"); CouncilNonHRAOnlySelection.add("8UO - 9UO"); if (do999) { CouncilNonHRAOnlySelection.add("8UO - -999"); CouncilNonHRAOnlySelection.add("-999 - 8UO"); CouncilNonHRAOnlySelection.add("8 - -999UO"); CouncilNonHRAOnlySelection.add("-999UO - 8"); CouncilNonHRAOnlySelection.add("8UO - -999UO"); CouncilNonHRAOnlySelection.add("-999UO - 8UO"); } } else { if (sameTenancyType) { CouncilNonHRAOnlySelection.add("8 - 8"); } CouncilNonHRAOnlySelection.add("8 - 1"); CouncilNonHRAOnlySelection.add("8 - 2"); CouncilNonHRAOnlySelection.add("8 - 3"); CouncilNonHRAOnlySelection.add("8 - 4"); CouncilNonHRAOnlySelection.add("8 - 5"); CouncilNonHRAOnlySelection.add("8 - 6"); CouncilNonHRAOnlySelection.add("8 - 7"); CouncilNonHRAOnlySelection.add("8 - 9"); if (do999) { CouncilNonHRAOnlySelection.add("8 - -999"); CouncilNonHRAOnlySelection.add("-999 - 8"); } } result.put(selectionName, CouncilNonHRAOnlySelection); HashSet<String> PrivateMealDeductionSelection; PrivateMealDeductionSelection = new HashSet<>(); selectionName = "PrivateMealDeduction"; if (doUnderOccupancy) { if (sameTenancyType) { PrivateMealDeductionSelection.add("9 - 9UO"); PrivateMealDeductionSelection.add("9UO - 9"); PrivateMealDeductionSelection.add("9UO - 9UO"); } PrivateMealDeductionSelection.add("9UO - 1"); PrivateMealDeductionSelection.add("9 - 1UO"); PrivateMealDeductionSelection.add("9UO - 1UO"); PrivateMealDeductionSelection.add("9UO - 2"); PrivateMealDeductionSelection.add("9 - 2UO"); PrivateMealDeductionSelection.add("9UO - 2UO"); PrivateMealDeductionSelection.add("9UO - 3"); PrivateMealDeductionSelection.add("9 - 3UO"); PrivateMealDeductionSelection.add("9UO - 3UO"); PrivateMealDeductionSelection.add("9UO - 4"); PrivateMealDeductionSelection.add("9 - 4UO"); PrivateMealDeductionSelection.add("9UO - 4UO"); PrivateMealDeductionSelection.add("9UO - 5"); PrivateMealDeductionSelection.add("9 - 5UO"); PrivateMealDeductionSelection.add("9UO - 5UO"); PrivateMealDeductionSelection.add("9UO - 6"); PrivateMealDeductionSelection.add("9 - 6UO"); PrivateMealDeductionSelection.add("9UO - 6UO"); PrivateMealDeductionSelection.add("9UO - 7"); PrivateMealDeductionSelection.add("9 - 7UO"); PrivateMealDeductionSelection.add("9UO - 7UO"); PrivateMealDeductionSelection.add("9UO - 8"); PrivateMealDeductionSelection.add("9 - 8UO"); PrivateMealDeductionSelection.add("9UO - 8UO"); if (do999) { PrivateMealDeductionSelection.add("9UO - -999"); PrivateMealDeductionSelection.add("-999 - 9UO"); PrivateMealDeductionSelection.add("9 - -999UO"); PrivateMealDeductionSelection.add("-999UO - 9"); PrivateMealDeductionSelection.add("9UO - -999UO"); PrivateMealDeductionSelection.add("-999UO - 9UO"); } } else { if (sameTenancyType) { PrivateMealDeductionSelection.add("9 - 9"); } PrivateMealDeductionSelection.add("9 - 1"); PrivateMealDeductionSelection.add("9 - 2"); PrivateMealDeductionSelection.add("9 - 3"); PrivateMealDeductionSelection.add("9 - 4"); PrivateMealDeductionSelection.add("9 - 5"); PrivateMealDeductionSelection.add("9 - 6"); PrivateMealDeductionSelection.add("9 - 7"); PrivateMealDeductionSelection.add("9 - 9"); if (do999) { PrivateMealDeductionSelection.add("9 - -999"); PrivateMealDeductionSelection.add("-999 - 9"); } } result.put(selectionName, PrivateMealDeductionSelection); HashSet<String> allSelection; allSelection = new HashSet<>(); selectionName = DW_Strings.sAll; allSelection.addAll(CouncilSelection); allSelection.addAll(PrivateHousingAssociationSelection); allSelection.addAll(PrivateRegulatedSelection); allSelection.addAll(PrivateDeregulatedSelection); allSelection.addAll(PrivateOtherSelection); result.put(selectionName, allSelection); selectionName = "ReportSelection"; HashSet<String> selection; selection = new HashSet<>(); if (doUnderOccupancy) { if (sameTenancyType) { selection.add("1 - 1UO"); selection.add("1UO - 1"); selection.add("1UO - 1UO"); // selection.add("2 - 2UO"); // selection.add("2UO - 2"); // selection.add("2UO - 2UO"); selection.add("3 - 3UO"); selection.add("3UO - 3"); selection.add("3UO - 3UO"); selection.add("4 - 4UO"); selection.add("4UO - 4"); selection.add("4UO - 4UO"); } selection.add("1 - 3UO"); selection.add("1UO - 3"); selection.add("1UO - 3UO"); selection.add("1 - 4UO"); selection.add("1UO - 4"); selection.add("1UO - 4UO"); selection.add("3 - 1UO"); selection.add("3UO - 1"); selection.add("3UO - 1UO"); selection.add("3 - 4UO"); selection.add("3UO - 4"); selection.add("3UO - 4UO"); selection.add("4 - 1UO"); selection.add("4UO - 1"); selection.add("4UO - 1UO"); selection.add("4 - 3UO"); selection.add("4UO - 3"); selection.add("4UO - 3UO"); if (do999) { selection.add("1UO - -999"); selection.add("-999 - 1UO"); selection.add("3UO - -999"); selection.add("-999 - 3UO"); selection.add("4UO - -999"); selection.add("-999 - 4UO"); } } else { if (sameTenancyType) { selection.add("1 - 1"); selection.add("3 - 3"); selection.add("4 - 4"); } selection.add("1 - 3"); selection.add("1 - 4"); selection.add("3 - 1"); selection.add("3 - 4"); selection.add("4 - 1"); selection.add("4 - 3"); if (do999) { selection.add("1 - -999"); selection.add("-999 - 1"); selection.add("3 - -999"); selection.add("-999 - 3"); selection.add("4 - -999"); selection.add("-999 - 4"); } } result.put(selectionName, selection); return result; } /** * @param doUnderOccupancy * @param do999 * @param sameTenancyType * @return */ protected TreeMap<String, HashSet<String>> getAllSelectionsGrouped( boolean doUnderOccupancy, boolean do999, boolean sameTenancyType) { TreeMap<String, HashSet<String>> result; result = new TreeMap<>(); String selectionName; selectionName = "Regulated"; HashSet<String> regulatedSelection; regulatedSelection = new HashSet<>(); if (doUnderOccupancy) { if (sameTenancyType) { regulatedSelection.add("RegulatedUO - Regulated"); regulatedSelection.add("Regulated - RegulatedUO"); regulatedSelection.add("RegulatedUO - RegulatedUO"); } regulatedSelection.add("RegulatedUO - Unregulated"); regulatedSelection.add("Regulated - UnregulatedUO"); regulatedSelection.add("RegulatedUO - UnregulatedUO"); regulatedSelection.add("Regulated - UngroupedUO"); regulatedSelection.add("RegulatedUO - Ungrouped"); regulatedSelection.add("RegulatedUO - UngroupedUO"); if (do999) { regulatedSelection.add("RegulatedUO - -999"); regulatedSelection.add("-999 - RegulatedUO"); regulatedSelection.add("Regulated - -999UO"); regulatedSelection.add("-999UO - Regulated"); regulatedSelection.add("RegulatedUO - -999UO"); regulatedSelection.add("-999UO - RegulatedUO"); } } else { if (sameTenancyType) { regulatedSelection.add("Regulated - Regulated"); } regulatedSelection.add("Regulated - Unregulated"); regulatedSelection.add("Regulated - Ungrouped"); if (do999) { regulatedSelection.add("Regulated - -999"); regulatedSelection.add("-999 - Regulated"); } } result.put(selectionName, regulatedSelection); HashSet<String> unregulatedSelection; unregulatedSelection = new HashSet<>(); selectionName = "Unregulated"; if (doUnderOccupancy) { if (sameTenancyType) { unregulatedSelection.add("UnregulatedUO - Unregulated"); unregulatedSelection.add("Unregulated - UnregulatedUO"); unregulatedSelection.add("UnregulatedUO - UnregulatedUO"); } unregulatedSelection.add("UnregulatedUO - Regulated"); unregulatedSelection.add("Unregulated - RegulatedUO"); unregulatedSelection.add("UnregulatedUO - RegulatedUO"); unregulatedSelection.add("UnregulatedUO - UngroupedUO"); unregulatedSelection.add("UnregulatedUO - Ungrouped"); unregulatedSelection.add("Unregulated - UngroupedUO"); if (do999) { unregulatedSelection.add("UnregulatedUO - -999"); unregulatedSelection.add("-999 - UnregulatedUO"); unregulatedSelection.add("Unregulated - -999UO"); unregulatedSelection.add("-999UO - Unregulated"); unregulatedSelection.add("UnregulatedUO - -999UO"); unregulatedSelection.add("-999UO - UnregulatedUO"); } } else { if (sameTenancyType) { unregulatedSelection.add("Unregulated - Unregulated"); } unregulatedSelection.add("Unregulated - Regulated"); unregulatedSelection.add("Unregulated - Ungrouped"); if (do999) { unregulatedSelection.add("Unregulated - -999"); unregulatedSelection.add("-999 - Unregulated"); } } result.put(selectionName, unregulatedSelection); HashSet<String> ungroupedSelection; ungroupedSelection = new HashSet<>(); selectionName = DW_Strings.sGroupedNo; if (doUnderOccupancy) { if (sameTenancyType) { ungroupedSelection.add("UngroupedUO - Ungrouped"); ungroupedSelection.add("Ungrouped - UngroupedUO"); ungroupedSelection.add("UngroupedUO - UngroupedUO"); } ungroupedSelection.add("UngroupedUO - Regulated"); ungroupedSelection.add("Ungrouped - RegulatedUO"); ungroupedSelection.add("UngroupedUO - RegulatedUO"); ungroupedSelection.add("UngroupedUO - Unregulated"); ungroupedSelection.add("Ungrouped - UnregulatedUO"); ungroupedSelection.add("UngroupedUO - UnregulatedUO"); if (do999) { ungroupedSelection.add("UngroupedUO - -999"); ungroupedSelection.add("-999 - UngroupedUO"); ungroupedSelection.add("Ungrouped - -999UO"); ungroupedSelection.add("-999UO - Ungrouped"); ungroupedSelection.add("UngroupedUO - -999UO"); ungroupedSelection.add("-999UO - UngroupedUO"); } } else { if (sameTenancyType) { ungroupedSelection.add("Ungrouped - Ungrouped"); } ungroupedSelection.add("Ungrouped - Regulated"); ungroupedSelection.add("Ungrouped - Unregulated"); if (do999) { ungroupedSelection.add("Ungrouped - -999"); ungroupedSelection.add("-999 - Ungrouped"); } } result.put(selectionName, ungroupedSelection); HashSet<String> allSelection; allSelection = new HashSet<>(); selectionName = DW_Strings.sAll; allSelection.addAll(regulatedSelection); allSelection.addAll(unregulatedSelection); allSelection.addAll(ungroupedSelection); result.put(selectionName, allSelection); return result; } // public static String getLabel( // String year0, // String month0, // String year, // String month) { // String result; // result = year0 + " " + month0 + "_" + year + " " + month; // // System.out.println(result); // return result; // } public static String getLabel( String yM30, String yM31) { String result; result = yM30 + "-" + yM31; //result = yM30 + "_TO_" + yM31; // System.out.println(result); return result; } /** * {@code * Object[] result; * result = new Object[3]; * TreeMap<Integer, TreeMap<Integer, BigDecimal>> map; * map = new TreeMap<Integer, TreeMap<Integer, BigDecimal>>(); * result[0] = map; * Double min = null; * result[1] = min; * Double max = null; * result[2] = max; * result[3] = size; * } * * @param f * @param timeDiff Normaliser for counts. * @return TenureBefore, TenureNow Counts. */ public TreeMap<String, TreeMap<String, BigDecimal>> getTenancyTypeTransitionMap( Path f, double timeDiff) { DW_Table table = new DW_Table(env); // Object[] result; // result = new Object[4]; TreeMap<String, TreeMap<String, BigDecimal>> map; map = new TreeMap<>(); // result[0] = map; // Double min = Double.MAX_VALUE; // Double max = Double.MIN_VALUE; // int size = 0; ArrayList<String> lines = table.readCSV(f); ArrayList<String> tenancyTypes; tenancyTypes = new ArrayList<>(); boolean mapContainsNonZeroValues = false; boolean first = true; Iterator<String> ite = lines.iterator(); while (ite.hasNext()) { // Skip the first line String line; line = ite.next(); String[] split; split = line.split(","); if (first) { for (int i = 1; i < split.length; i++) { String tenancyBefore; tenancyBefore = split[i]; TreeMap<String, BigDecimal> transitions; transitions = new TreeMap<>(); map.put(tenancyBefore, transitions); tenancyTypes.add(tenancyBefore); } first = false; } else { String tenancyNow; tenancyNow = split[0]; for (int i = 1; i < split.length; i++) { String tenancyTypeBefore; // This is tenancyStart!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! tenancyTypeBefore = tenancyTypes.get(i - 1); Integer count; count = Integer.valueOf(split[i]); if (count != 0) { mapContainsNonZeroValues = true; } Double rate; rate = count / timeDiff; TreeMap<String, BigDecimal> tenancyTransition; tenancyTransition = map.get(tenancyTypeBefore); tenancyTransition.put(tenancyNow, BigDecimal.valueOf(rate)); // if (tenancyTypeBefore.compareTo(tenancyEnd) != 0) { // min = Math.min(min, rate); // max = Math.max(max, rate); // size++; // } } } } if (!mapContainsNonZeroValues) { return null; } // System.out.println("max " + max); // System.out.println("min " + min); // System.out.println("size " + size); // result[1] = min; // This has to be here because of unboxing!? // result[2] = max; // result[3] = size; // return result; return map; } /** * {@code * Object[] result; * result = new Object[3]; * TreeMap<Integer, TreeMap<Integer, BigDecimal>> map; * map = new TreeMap<Integer, TreeMap<Integer, BigDecimal>>(); * result[0] = map; * Double min = null; * result[1] = min; * Double max = null; * result[2] = max; * result[3] = size; * } * * @param f * @param timeDiff Normaliser for counts. * @return TenancyTypeBefore, TenancyTypeNow Counts. */ public TreeMap<String, TreeMap<String, BigDecimal>> getTenancyTypeTransitionMapGrouped( Path f, double timeDiff) { DW_Table table = new DW_Table(env); // Object[] result; // result = new Object[4]; TreeMap<String, TreeMap<String, BigDecimal>> map; map = new TreeMap<>(); // result[0] = map; // Double min = Double.MAX_VALUE; // Double max = Double.MIN_VALUE; // int size = 0; ArrayList<String> lines = table.readCSV(f); ArrayList<String> tenancyTypes; tenancyTypes = new ArrayList<>(); boolean mapContainsNonZeroValues = false; boolean first = true; Iterator<String> ite = lines.iterator(); while (ite.hasNext()) { // Skip the first line String line; line = ite.next(); String[] split; split = line.split(","); if (first) { for (int i = 1; i < split.length; i++) { String tenancyStart; tenancyStart = split[i]; TreeMap<String, BigDecimal> transitions; transitions = new TreeMap<>(); map.put(tenancyStart, transitions); tenancyTypes.add(tenancyStart); } first = false; } else { String tenancyEnd; tenancyEnd = split[0]; for (int i = 1; i < split.length; i++) { String tenancyTypeBefore; if (split.length > 9) { int debug = 1; } tenancyTypeBefore = tenancyTypes.get(i - 1); Integer count; count = Integer.valueOf(split[i]); if (count != 0) { mapContainsNonZeroValues = true; } Double rate; rate = count / timeDiff; TreeMap<String, BigDecimal> tenancyTransition; tenancyTransition = map.get(tenancyTypeBefore); tenancyTransition.put(tenancyEnd, BigDecimal.valueOf(rate)); // if (tenancyTypeBefore.compareTo(tenancyEnd) != 0) { // min = Math.min(min, rate); // max = Math.max(max, rate); // size++; // } } } } if (!mapContainsNonZeroValues) { return null; } // System.out.println("max " + max); // System.out.println("min " + min); // System.out.println("size " + size); // result[1] = min; // This has to be here because of unboxing!? // result[2] = max; // result[3] = size; // return result; return map; } /** * Object[] result; result = new Object[7]; result[0] = maps; * TreeMap<String, TreeMap<BigDecimal, BigDecimal>> // label, x, y maps * result[1] = newMinY; // BigDecimal minimum y value in selection. * result[2] = newMaxY; // BigDecimal maximum y value in selection. * result[3] = newMinX; // BigDecimal minimum x value in selection. * result[4] = newMaxX; // BigDecimal maximum x value in selection. * result[5] = labels; // collection of strings: row index " - " column * index result[6] = xAxisLabels; result[7] = TreeMap<String, Boolean> // * label, non-zero values result[7] = TreeMap<String, Boolean> // labels, * non-zero values */ private Object[] getData( TreeMap<String, TreeMap<UKP_YM3, BigDecimal>> data, TreeMap<BigDecimal, UKP_YM3> xAxisLabels, TreeMap<UKP_YM3, BigDecimal> fileLabelValue) { Object[] result; result = new Object[9]; TreeMap<String, TreeMap<BigDecimal, BigDecimal>> maps; maps = new TreeMap<>(); BigDecimal newMinX; newMinX = BigDecimal.valueOf(Double.MAX_VALUE); BigDecimal newMaxX; newMaxX = BigDecimal.valueOf(Double.MIN_VALUE); BigDecimal newMinY; newMinY = BigDecimal.valueOf(Double.MAX_VALUE); BigDecimal newMaxY; newMaxY = BigDecimal.valueOf(Double.MIN_VALUE); TreeMap<String, Boolean> nonZero; nonZero = new TreeMap<>(); // Initialise data, newMinX, newMaxX, newMinY, newMaxY Iterator<String> iteS; Iterator<UKP_YM3> iteS2; iteS = data.keySet().iterator(); String key; TreeMap<UKP_YM3, BigDecimal> dataYX; while (iteS.hasNext()) { key = iteS.next(); // key is aggregate area code TreeMap<BigDecimal, BigDecimal> map; map = maps.get(key); if (map == null) { map = new TreeMap<>(); maps.put(key, map); } dataYX = data.get(key); // init Boolean bo; bo = nonZero.get(key); if (bo == null) { nonZero.put(key, false); } iteS2 = dataYX.keySet().iterator(); while (iteS2.hasNext()) { UKP_YM3 YM3; YM3 = iteS2.next(); // System.out.println("YM3 " + YM3); BigDecimal x = fileLabelValue.get(YM3); if (x == null) { nonZero.put(key, true); } else { if (x.compareTo(BigDecimal.ZERO) != 0) { nonZero.put(key, true); } BigDecimal y; y = dataYX.get(YM3); // System.out.println("x " + x); // System.out.println("y " + y); // set min and max newMinY = y.min(newMinY); newMaxY = y.max(newMaxY); newMinX = x.min(newMinX); newMaxX = x.max(newMaxX); // Add to map map.put(x, y); } } } TreeMap<String, Boolean> nonZero2; nonZero2 = new TreeMap<>(); // Initialise labels. ArrayList<String> labels; labels = new ArrayList<>(); iteS = maps.keySet().iterator(); while (iteS.hasNext()) { String label; label = iteS.next(); labels.add(label); nonZero2.put(label, nonZero.get(label)); } result[0] = maps; result[1] = newMinY; result[2] = newMaxY; result[3] = newMinX; result[4] = newMaxX; result[5] = labels; result[6] = xAxisLabels; result[7] = nonZero; result[8] = nonZero2; return result; } /** * @param bigMatrix The bigMatrix to repack and select from. Keys are x * values to be plot, the final values are y values, the Integer keys * between are row and column indexes. TenancyTypeBefore, TenancyTypeNow * Counts. * @param selection A collection of strings for selecting what data to get. * @param xAxisLabels Passed in for packaging. * @return { * @code * Object[] result; * result = new Object[7]; * result[0] = maps; TreeMap<String, TreeMap<BigDecimal, BigDecimal>> // label, x, y maps * result[1] = newMinY; // BigDecimal minimum y value in selection. * result[2] = newMaxY; // BigDecimal maximum y value in selection. * result[3] = newMinX; // BigDecimal minimum x value in selection. * result[4] = newMaxX; // BigDecimal maximum x value in selection. * result[5] = labels; // collection of strings: row index " - " column index * result[6] = xAxisLabels; * result[7] = TreeMap<String, Boolean> // label, non-zero values * result[8] = TreeMap<String, Boolean> // labels, non-zero values */ private Object[] getData( TreeMap<BigDecimal, TreeMap<String, TreeMap<String, BigDecimal>>> bigMatrix, HashSet<String> selection, TreeMap<BigDecimal, String> xAxisLabels) { Object[] result; result = new Object[9]; TreeMap<String, TreeMap<BigDecimal, BigDecimal>> maps; maps = new TreeMap<>(); BigDecimal newMinX; newMinX = BigDecimal.valueOf(Double.MAX_VALUE); BigDecimal newMaxX; newMaxX = BigDecimal.valueOf(Double.MIN_VALUE); BigDecimal newMinY; newMinY = BigDecimal.valueOf(Double.MAX_VALUE); BigDecimal newMaxY; newMaxY = BigDecimal.valueOf(Double.MIN_VALUE); // Declare nonZero TreeMap<String, Boolean> nonZero; nonZero = new TreeMap<>(); Iterator<BigDecimal> ite; ite = bigMatrix.keySet().iterator(); while (ite.hasNext()) { BigDecimal x = ite.next(); TreeMap<String, TreeMap<String, BigDecimal>> iomatrix; iomatrix = bigMatrix.get(x); Iterator<String> ite2; ite2 = iomatrix.keySet().iterator(); while (ite2.hasNext()) { String tenancyTypeBefore = ite2.next(); // This is Before!!!!!!!!!!!! TreeMap<String, BigDecimal> omatrix; omatrix = iomatrix.get(tenancyTypeBefore); Iterator<String> ite3; ite3 = omatrix.keySet().iterator(); while (ite3.hasNext()) { String tenancyTypeNow = ite3.next(); // This is now!!!!!!!!!1 if (!tenancyTypeNow.equalsIgnoreCase(tenancyTypeBefore)) { String key; key = "" + tenancyTypeBefore + " - " + tenancyTypeNow; // init Boolean b; b = nonZero.get(key); if (b == null) { nonZero.put(key, false); } if (selection.contains(key)) { TreeMap<BigDecimal, BigDecimal> map; map = maps.get(key); if (map == null) { map = new TreeMap<>(); maps.put(key, map); } BigDecimal y; y = omatrix.get(tenancyTypeNow); // set non-zero if (y.compareTo(BigDecimal.ZERO) != 0) { nonZero.put(key, true); } // set min and max newMinY = y.min(newMinY); newMaxY = y.max(newMaxY); newMinX = x.min(newMinX); newMaxX = x.max(newMaxX); // Add to map map.put(x, y); } } } } } // BigDecimal minX = bigMatrix.firstKey(); // BigDecimal maxX = bigMatrix.lastKey(); // BigDecimal minX = maps.firstKey(); // BigDecimal maxX = maps.lastKey(); result[0] = maps; result[1] = newMinY; result[2] = newMaxY; result[3] = newMinX; result[4] = newMaxX; ArrayList<String> labels; labels = new ArrayList<>(); // labels.addAll(maps.keySet()); // This does not work as maps is gc resulting in labels becoming null for some reason. // Declare nonZero2 SHBE_TenancyType shbeTT = env.getShbeTenancyType(); TreeMap<String, Boolean> nonZero2 = new TreeMap<>(); Iterator<String> iteS = maps.keySet().iterator(); while (iteS.hasNext()) { String label = iteS.next(); String[] tenancyTypes = label.split(" - "); String newLabel = shbeTT.getTenancyTypeName(tenancyTypes[0]); newLabel += " TO "; newLabel += shbeTT.getTenancyTypeName(tenancyTypes[1]); labels.add(newLabel); nonZero2.put(newLabel, nonZero.get(label)); } result[5] = labels; result[6] = xAxisLabels; result[7] = nonZero; result[8] = nonZero2; return result; } // private Object[] getDataGrouped( // TreeMap<BigDecimal, TreeMap<String, TreeMap<String, BigDecimal>>> bigMatrixGrouped, // HashSet<String> selection, // TreeMap<BigDecimal, String> xAxisLabels) { // Object[] result; // result = new Object[9]; // TreeMap<String, TreeMap<BigDecimal, BigDecimal>> maps; // maps = new TreeMap<String, TreeMap<BigDecimal, BigDecimal>>(); // BigDecimal newMinX; // newMinX = BigDecimal.valueOf(Double.MAX_VALUE); // BigDecimal newMaxX; // newMaxX = BigDecimal.valueOf(Double.MIN_VALUE); // BigDecimal newMinY; // newMinY = BigDecimal.valueOf(Double.MAX_VALUE); // BigDecimal newMaxY; // newMaxY = BigDecimal.valueOf(Double.MIN_VALUE); // // Declare nonZero // TreeMap<String, Boolean> nonZero; // nonZero = new TreeMap<String, Boolean>(); // Iterator<BigDecimal> ite; // ite = bigMatrixGrouped.keySet().iterator(); // while (ite.hasNext()) { // BigDecimal x = ite.next(); // TreeMap<String, TreeMap<String, BigDecimal>> iomatrix; // iomatrix = bigMatrixGrouped.get(x); // Iterator<String> ite2; // ite2 = iomatrix.keySet().iterator(); // while (ite2.hasNext()) { // String tenancyTypeBefore = ite2.next(); // TreeMap<String, BigDecimal> omatrix; // omatrix = iomatrix.get(tenancyTypeBefore); // Iterator<String> ite3; // ite3 = omatrix.keySet().iterator(); // while (ite3.hasNext()) { // String tenancyTypeNow = ite3.next(); // if (!tenancyTypeNow.equalsIgnoreCase(tenancyTypeBefore)) { // String key; // key = "" + tenancyTypeBefore + " - " + tenancyTypeNow; // // init // Boolean b; // b = nonZero.get(key); // if (b == null) { // nonZero.put(key, false); // } // if (selection.contains(key)) { // TreeMap<BigDecimal, BigDecimal> map; // map = maps.get(key); // if (map == null) { // map = new TreeMap<BigDecimal, BigDecimal>(); // maps.put(key, map); // } // BigDecimal y; // y = omatrix.get(tenancyTypeNow); // // set non-zero // if (y.compareTo(BigDecimal.ZERO) != 0) { // nonZero.put(key, true); // } // // set min and max // newMinY = y.min(newMinY); // newMaxY = y.max(newMaxY); // newMinX = x.min(newMinX); // newMaxX = x.max(newMaxX); // // add to map // map.put(x, y); // } // } // } // } // } //// BigDecimal minX = bigMatrix.firstKey(); //// BigDecimal maxX = bigMatrix.lastKey(); //// BigDecimal minX = maps.firstKey(); //// BigDecimal maxX = maps.lastKey(); // result[0] = maps; // result[1] = newMinY; // result[2] = newMaxY; // result[3] = newMinX; // result[4] = newMaxX; // // Declare nonZero2 // TreeMap<String, Boolean> nonZero2; // nonZero2 = new TreeMap<String, Boolean>(); // ArrayList<String> labels; // labels = new ArrayList<String>(); //// labels.addAll(maps.keySet()); // This does not work as maps is gc resulting in labels becoming null for some reason. // Iterator<String> iteS; // iteS = maps.keySet().iterator(); // while (iteS.hasNext()) { // String label; // label = iteS.next(); // String[] tenancyTypes; // //tenancyTypes = label.split(" - "); // tenancyTypes = label.split(" - "); // String newLabel; // newLabel = shbeData.getTenancyTypeName(Integer.valueOf(tenancyTypes[0])); // newLabel += " TO "; // newLabel += shbeData.getTenancyTypeName(Integer.valueOf(tenancyTypes[1])); // labels.add(newLabel); // nonZero2.put(newLabel, nonZero.get(label)); // } // result[5] = labels; // result[6] = xAxisLabels; // result[7] = nonZero; // result[8] = nonZero2; // return result; // } }
122,376
0.451197
0.433589
2,372
50.594013
25.622437
145
false
false
0
0
0
0
0
0
0.927909
false
false
13
03cbc03812daa3d96080fc8b162ea33c8ad89910
22,720,377,052,598
3fce48a5d0c705a51a0a1471ab8ae29c72d31369
/app/src/main/java/iste/not/com/Main/MainActivity.java
3039342880870b754d4f54c2126a812898918125
[]
no_license
mhsnabz/notiste
https://github.com/mhsnabz/notiste
b9fe8273a49a9cbeee09d41d895c53088d788e2f
43936fbf1b0d7075bce35311910cafd404675a1d
refs/heads/master
2020-05-15T12:33:47.964000
2019-04-19T13:33:32
2019-04-19T13:33:32
182,269,403
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package iste.not.com.Main; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Build; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.InstanceIdResult; import com.squareup.picasso.Picasso; import java.util.Calendar; import java.util.HashMap; import java.util.Random; import de.hdodenhof.circleimageview.CircleImageView; import iste.not.com.Helper.MainViewPager; import iste.not.com.NotificationService.FirebaseInstanceService; import iste.not.com.POST.ImageLoaderActivity; import iste.not.com.Profile.ProfileActivity; import iste.not.com.R; public class MainActivity extends AppCompatActivity { private static final int izin = 1; private FirebaseAuth auth; String currentUser; DatabaseReference databaseReference,reference; private FirebaseAuth firebaseAuth; FirebaseAuth.AuthStateListener mAuthListener; FirebaseUser firebaseUser =FirebaseAuth.getInstance().getCurrentUser(); LinearLayout messegesLin,notificationLin ; CircleImageView profile; TextView askNote,askQuestions,Notice; ViewPager MainViewPager; FirebaseInstanceService firebaseInstanceService; private iste.not.com.Helper.MainViewPager pagerViewAdapeter; String major; TextView notificationCount,messageCount; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); checkPermisson(); messegesLin=(LinearLayout)findViewById(R.id.messaheNotLayout) ; notificationLin=(LinearLayout)findViewById(R.id.notificationLayout) ; notificationCount=(TextView)findViewById(R.id.notificationCount); messageCount=(TextView)findViewById(R.id.messageCount); major=getIntent().getStringExtra("major"); currentUser=firebaseUser.getUid(); profile =(CircleImageView) findViewById(R.id.profile); profile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent ProfileIntent = new Intent(MainActivity.this,ProfileActivity.class); ProfileIntent.putExtra("major",major); startActivity(ProfileIntent); finish(); } }); askNote=(TextView)findViewById(R.id.askNote); askQuestions=(TextView)findViewById(R.id.askQuestions); Notice=(TextView)findViewById(R.id.notice); MainViewPager = (ViewPager)findViewById(R.id.mainViewPager); pagerViewAdapeter= new iste.not.com.Helper.MainViewPager(getSupportFragmentManager()); MainViewPager.setAdapter(pagerViewAdapeter); loadImage(currentUser); setMessageNotificationCount(currentUser,messageCount,messegesLin); setNotificationCount(major,currentUser,notificationCount,notificationLin); MainViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int i, float v, int i1) { } @Override public void onPageSelected(int i) { changeTabs(i); } @Override public void onPageScrollStateChanged(int i) { } }); askNote.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MainViewPager.setCurrentItem(0); } }); askQuestions.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MainViewPager.setCurrentItem(1); } }); Notice.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MainViewPager.setCurrentItem(2); } }); } private void changeTabs(int i) { String TAG ="changeTabsFunc"; if(i==0) { askNote.setTextColor(getColor(R.color.colorPrimary)); askNote.setTextSize(22); askQuestions.setTextColor(getColor(R.color.Ligth)); askQuestions.setTextSize(16); Notice.setTextColor(getColor(R.color.Ligth)); Notice.setTextSize(16); } if(i==1) { askNote.setTextColor(getColor(R.color.Ligth)); askNote.setTextSize(16); askQuestions.setTextColor(getColor(R.color.colorPrimary)); askQuestions.setTextSize(22); Notice.setTextColor(getColor(R.color.Ligth)); Notice.setTextSize(16); } if(i==2) { askNote.setTextColor(getColor(R.color.Ligth)); askNote.setTextSize(16); askQuestions.setTextColor(getColor(R.color.Ligth)); askQuestions.setTextSize(16); Notice.setTextColor(getColor(R.color.colorPrimary)); Notice.setTextSize(22); } Log.d(TAG, "changeTabs: "); } private void online(final String status) { auth=FirebaseAuth.getInstance(); currentUser=auth.getCurrentUser().getUid(); databaseReference = FirebaseDatabase.getInstance().getReference().child("IsOnline").child(currentUser); reference = FirebaseDatabase.getInstance().getReference().child("Students").child(currentUser); FirebaseAuth.getInstance().addAuthStateListener(new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if(user!=null) { reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot!=null) { // databaseReference.child("online").onDisconnect().setValue(_false); databaseReference.child("online").setValue(status); databaseReference.child("lastOnline").setValue(-1*Calendar.getInstance().getTimeInMillis()); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } } }); } @Override protected void onStart() { super.onStart(); } @Override protected void onStop() { super.onStop(); } private void loadImage(final String keyX) { final DatabaseReference UserInfo = FirebaseDatabase.getInstance().getReference().child("Students").child(keyX); UserInfo.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { String TAG ="image"; String image =dataSnapshot.child("image").getValue().toString(); Log.d(TAG, "onDataChange: "+image); Picasso.get().load(image).resize(256,256).placeholder(R.drawable.placeholder_image).centerCrop().into(profile); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private void checkPermisson() { Log.d("permission", "checkPermisson: "+"asking users"); String[] permissisons = { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.INTERNET, Manifest.permission.CAMERA }; if (ContextCompat.checkSelfPermission(MainActivity.this,permissisons[0])==PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(MainActivity.this,permissisons[1])==PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(MainActivity.this,permissisons[2])==PackageManager.PERMISSION_GRANTED &&ContextCompat.checkSelfPermission(MainActivity.this,permissisons[3])==PackageManager.PERMISSION_GRANTED) { } else { ActivityCompat.requestPermissions(MainActivity.this,permissisons,izin); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { checkPermisson(); } private void setMessageNotificationCount(String _currentUser, final TextView _text, final LinearLayout _linLayNotifCount) { DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("DatabaseMessagesNotifcation") .child(_currentUser) ; reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.getChildrenCount()>0) { if (dataSnapshot.getChildrenCount()<=9) { _text.setText("+"+Long.toString(dataSnapshot.getChildrenCount())); _linLayNotifCount.setVisibility(View.VISIBLE); } else _text.setText(Long.toString(dataSnapshot.getChildrenCount())); _text.setVisibility(View.VISIBLE); _linLayNotifCount.setVisibility(View.VISIBLE); } else { _text.setVisibility(View.INVISIBLE); _linLayNotifCount.setVisibility(View.INVISIBLE); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private void setNotificationCount(String _major, String _currentUser, final TextView _text, final LinearLayout _linLayNotifCount) { DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child(_major) .child("databaseNotifications") .child(_currentUser) .child("NotificationCount"); reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.getChildrenCount()>0) { if (dataSnapshot.getChildrenCount()<=9) { _text.setText("+"+Long.toString(dataSnapshot.getChildrenCount())); _linLayNotifCount.setVisibility(View.VISIBLE); } else _text.setText(Long.toString(dataSnapshot.getChildrenCount())); _linLayNotifCount.setVisibility(View.VISIBLE); _text.setVisibility(View.VISIBLE); } else { _text.setVisibility(View.INVISIBLE); _linLayNotifCount.setVisibility(View.INVISIBLE); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK)) { finish(); return true; } return super.onKeyDown(keyCode, event); } }
UTF-8
Java
12,979
java
MainActivity.java
Java
[]
null
[]
package iste.not.com.Main; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Build; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.InstanceIdResult; import com.squareup.picasso.Picasso; import java.util.Calendar; import java.util.HashMap; import java.util.Random; import de.hdodenhof.circleimageview.CircleImageView; import iste.not.com.Helper.MainViewPager; import iste.not.com.NotificationService.FirebaseInstanceService; import iste.not.com.POST.ImageLoaderActivity; import iste.not.com.Profile.ProfileActivity; import iste.not.com.R; public class MainActivity extends AppCompatActivity { private static final int izin = 1; private FirebaseAuth auth; String currentUser; DatabaseReference databaseReference,reference; private FirebaseAuth firebaseAuth; FirebaseAuth.AuthStateListener mAuthListener; FirebaseUser firebaseUser =FirebaseAuth.getInstance().getCurrentUser(); LinearLayout messegesLin,notificationLin ; CircleImageView profile; TextView askNote,askQuestions,Notice; ViewPager MainViewPager; FirebaseInstanceService firebaseInstanceService; private iste.not.com.Helper.MainViewPager pagerViewAdapeter; String major; TextView notificationCount,messageCount; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); checkPermisson(); messegesLin=(LinearLayout)findViewById(R.id.messaheNotLayout) ; notificationLin=(LinearLayout)findViewById(R.id.notificationLayout) ; notificationCount=(TextView)findViewById(R.id.notificationCount); messageCount=(TextView)findViewById(R.id.messageCount); major=getIntent().getStringExtra("major"); currentUser=firebaseUser.getUid(); profile =(CircleImageView) findViewById(R.id.profile); profile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent ProfileIntent = new Intent(MainActivity.this,ProfileActivity.class); ProfileIntent.putExtra("major",major); startActivity(ProfileIntent); finish(); } }); askNote=(TextView)findViewById(R.id.askNote); askQuestions=(TextView)findViewById(R.id.askQuestions); Notice=(TextView)findViewById(R.id.notice); MainViewPager = (ViewPager)findViewById(R.id.mainViewPager); pagerViewAdapeter= new iste.not.com.Helper.MainViewPager(getSupportFragmentManager()); MainViewPager.setAdapter(pagerViewAdapeter); loadImage(currentUser); setMessageNotificationCount(currentUser,messageCount,messegesLin); setNotificationCount(major,currentUser,notificationCount,notificationLin); MainViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int i, float v, int i1) { } @Override public void onPageSelected(int i) { changeTabs(i); } @Override public void onPageScrollStateChanged(int i) { } }); askNote.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MainViewPager.setCurrentItem(0); } }); askQuestions.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MainViewPager.setCurrentItem(1); } }); Notice.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MainViewPager.setCurrentItem(2); } }); } private void changeTabs(int i) { String TAG ="changeTabsFunc"; if(i==0) { askNote.setTextColor(getColor(R.color.colorPrimary)); askNote.setTextSize(22); askQuestions.setTextColor(getColor(R.color.Ligth)); askQuestions.setTextSize(16); Notice.setTextColor(getColor(R.color.Ligth)); Notice.setTextSize(16); } if(i==1) { askNote.setTextColor(getColor(R.color.Ligth)); askNote.setTextSize(16); askQuestions.setTextColor(getColor(R.color.colorPrimary)); askQuestions.setTextSize(22); Notice.setTextColor(getColor(R.color.Ligth)); Notice.setTextSize(16); } if(i==2) { askNote.setTextColor(getColor(R.color.Ligth)); askNote.setTextSize(16); askQuestions.setTextColor(getColor(R.color.Ligth)); askQuestions.setTextSize(16); Notice.setTextColor(getColor(R.color.colorPrimary)); Notice.setTextSize(22); } Log.d(TAG, "changeTabs: "); } private void online(final String status) { auth=FirebaseAuth.getInstance(); currentUser=auth.getCurrentUser().getUid(); databaseReference = FirebaseDatabase.getInstance().getReference().child("IsOnline").child(currentUser); reference = FirebaseDatabase.getInstance().getReference().child("Students").child(currentUser); FirebaseAuth.getInstance().addAuthStateListener(new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if(user!=null) { reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot!=null) { // databaseReference.child("online").onDisconnect().setValue(_false); databaseReference.child("online").setValue(status); databaseReference.child("lastOnline").setValue(-1*Calendar.getInstance().getTimeInMillis()); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } } }); } @Override protected void onStart() { super.onStart(); } @Override protected void onStop() { super.onStop(); } private void loadImage(final String keyX) { final DatabaseReference UserInfo = FirebaseDatabase.getInstance().getReference().child("Students").child(keyX); UserInfo.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { String TAG ="image"; String image =dataSnapshot.child("image").getValue().toString(); Log.d(TAG, "onDataChange: "+image); Picasso.get().load(image).resize(256,256).placeholder(R.drawable.placeholder_image).centerCrop().into(profile); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private void checkPermisson() { Log.d("permission", "checkPermisson: "+"asking users"); String[] permissisons = { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.INTERNET, Manifest.permission.CAMERA }; if (ContextCompat.checkSelfPermission(MainActivity.this,permissisons[0])==PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(MainActivity.this,permissisons[1])==PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(MainActivity.this,permissisons[2])==PackageManager.PERMISSION_GRANTED &&ContextCompat.checkSelfPermission(MainActivity.this,permissisons[3])==PackageManager.PERMISSION_GRANTED) { } else { ActivityCompat.requestPermissions(MainActivity.this,permissisons,izin); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { checkPermisson(); } private void setMessageNotificationCount(String _currentUser, final TextView _text, final LinearLayout _linLayNotifCount) { DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("DatabaseMessagesNotifcation") .child(_currentUser) ; reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.getChildrenCount()>0) { if (dataSnapshot.getChildrenCount()<=9) { _text.setText("+"+Long.toString(dataSnapshot.getChildrenCount())); _linLayNotifCount.setVisibility(View.VISIBLE); } else _text.setText(Long.toString(dataSnapshot.getChildrenCount())); _text.setVisibility(View.VISIBLE); _linLayNotifCount.setVisibility(View.VISIBLE); } else { _text.setVisibility(View.INVISIBLE); _linLayNotifCount.setVisibility(View.INVISIBLE); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private void setNotificationCount(String _major, String _currentUser, final TextView _text, final LinearLayout _linLayNotifCount) { DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child(_major) .child("databaseNotifications") .child(_currentUser) .child("NotificationCount"); reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.getChildrenCount()>0) { if (dataSnapshot.getChildrenCount()<=9) { _text.setText("+"+Long.toString(dataSnapshot.getChildrenCount())); _linLayNotifCount.setVisibility(View.VISIBLE); } else _text.setText(Long.toString(dataSnapshot.getChildrenCount())); _linLayNotifCount.setVisibility(View.VISIBLE); _text.setVisibility(View.VISIBLE); } else { _text.setVisibility(View.INVISIBLE); _linLayNotifCount.setVisibility(View.INVISIBLE); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK)) { finish(); return true; } return super.onKeyDown(keyCode, event); } }
12,979
0.614069
0.610525
366
34.46175
30.079811
133
false
false
0
0
0
0
0
0
0.505464
false
false
13
caaf8fe6c0b30815fb09f911783f7cb83d993480
22,720,377,056,334
54169e88191fe3df63e2049750df1d722be2c403
/src/main/java/movement/SelfPropelled.java
12adcec7d440046a206f4c3f60e955d1b980e08c
[]
no_license
Turpan/AmyGraphics
https://github.com/Turpan/AmyGraphics
442856b971130f6d57a0ebbe50ac707d82e95566
e326ea669ef91a451d007453af3973e19b88695f
refs/heads/master
2020-03-23T10:21:10.678000
2019-12-05T07:03:48
2019-12-05T07:03:48
141,438,500
0
0
null
false
2019-05-06T13:05:40
2018-07-18T13:27:22
2019-05-06T12:40:17
2019-05-06T13:05:40
5,712
0
0
0
Java
false
false
package movement; import movement.mathDS.Vector; public abstract class SelfPropelled extends Movable { //SelfPropelleds can move themselves. They can generate a force in a direction, if they so //please. They require a baseMoveForce. //Examples of SelfPropelleds that don't inherit this classes children include: //simple creatures that move in complex ways, but aren't fully fleshed characters. Say, //a wisp that follows you. private double baseMoveForce; public SelfPropelled() { } protected SelfPropelled(SelfPropelled selfPropelled) { super(selfPropelled); setBaseMoveForce(selfPropelled.getBaseMoveForce()); } public double getBaseMoveForce() { return baseMoveForce; } public void setBaseMoveForce(double baseMoveForce) { if (baseMoveForce < 0) { baseMoveForce = 0; } this.baseMoveForce = baseMoveForce; } public void locomote(double[] direction) { applyForce(new Vector(baseMoveForce, direction)); } @Override public abstract SelfPropelled clone(); }
UTF-8
Java
1,001
java
SelfPropelled.java
Java
[]
null
[]
package movement; import movement.mathDS.Vector; public abstract class SelfPropelled extends Movable { //SelfPropelleds can move themselves. They can generate a force in a direction, if they so //please. They require a baseMoveForce. //Examples of SelfPropelleds that don't inherit this classes children include: //simple creatures that move in complex ways, but aren't fully fleshed characters. Say, //a wisp that follows you. private double baseMoveForce; public SelfPropelled() { } protected SelfPropelled(SelfPropelled selfPropelled) { super(selfPropelled); setBaseMoveForce(selfPropelled.getBaseMoveForce()); } public double getBaseMoveForce() { return baseMoveForce; } public void setBaseMoveForce(double baseMoveForce) { if (baseMoveForce < 0) { baseMoveForce = 0; } this.baseMoveForce = baseMoveForce; } public void locomote(double[] direction) { applyForce(new Vector(baseMoveForce, direction)); } @Override public abstract SelfPropelled clone(); }
1,001
0.764236
0.762238
35
27.628571
25.689447
91
false
false
0
0
0
0
0
0
1.485714
false
false
13
ebba62aa49e683911ac04fe3e7967345632ecedd
6,786,048,369,768
951d191b18b4adb95073adf0720a94e82e47eb55
/src/main/java/com/model/UserPosts.java
972dbe449d2e47e08a20fba89c9b9b6347113b7e
[]
no_license
O-OF-N/CompletableFuture
https://github.com/O-OF-N/CompletableFuture
9b0fa7b1415b695bb3aba2fad9e7786e9a92c22b
dd09c9f7c2d9c7b1b529d78a6fae85f3c45b8428
refs/heads/master
2020-03-27T13:09:58.930000
2018-08-29T13:32:33
2018-08-29T13:32:33
146,593,732
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.model; import java.util.List; /** * Created by vm033450 on 8/20/18. */ public class UserPosts { private final User user; private final List<Post> posts; public UserPosts(User user, List<Post> posts) { this.user = user; this.posts = posts; } @Override public String toString() { return "user = " + this.user + " \n" + "post = " + posts + " \n \n"; } }
UTF-8
Java
422
java
UserPosts.java
Java
[ { "context": ".model;\n\nimport java.util.List;\n\n/**\n * Created by vm033450 on 8/20/18.\n */\npublic class UserPosts {\n\n pri", "end": 70, "score": 0.999453067779541, "start": 62, "tag": "USERNAME", "value": "vm033450" } ]
null
[]
package com.model; import java.util.List; /** * Created by vm033450 on 8/20/18. */ public class UserPosts { private final User user; private final List<Post> posts; public UserPosts(User user, List<Post> posts) { this.user = user; this.posts = posts; } @Override public String toString() { return "user = " + this.user + " \n" + "post = " + posts + " \n \n"; } }
422
0.57346
0.547393
22
18.181818
19.241613
76
false
false
0
0
0
0
0
0
0.363636
false
false
13
b3f2aea4118cc790a54af1d016bf190481e7ba70
1,194,000,931,053
113da6bb5de2f958650fe361360816fbfa345365
/main/java/java设计模式/模式3单例模式/destroySingleton.java
50def9673a0ac2e34497b33dce1d49f1624f2868
[]
no_license
xuzaiya/javaCodeForInterview
https://github.com/xuzaiya/javaCodeForInterview
b10eaca646fe020a369d657aa61146d94ab27224
d4f5033b5e4dd052e298568f40b29bfcfef98067
refs/heads/master
2022-12-01T22:07:01.643000
2020-08-09T10:38:56
2020-08-09T10:38:56
286,671,080
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package java设计模式.模式3单例模式; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Constructor; /* * 破坏单例的三种方式 * * * */ public class destroySingleton { public static void main(String[] args) throws Exception { System.out.println("-----------序列化----------------------"); Singleton originSingleton = Singleton.getInstance(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(Singleton.getInstance()); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bis); Singleton serializeSingleton = (Singleton) ois.readObject(); System.out.println(originSingleton == serializeSingleton);//false System.out.println("-----------反射----------------------"); //通过反射获取 Constructor<Singleton> cons = Singleton.class.getDeclaredConstructor(); cons.setAccessible(true); Singleton reflextSingleton = cons.newInstance(); System.out.println(reflextSingleton == originSingleton);//false System.out.println("---------------------------克隆----------------------"); //Singleton cloneSingleton = (Singleton) originSingleton.clone(); //System.out.println(cloneSingleton == originSingleton);//false } }
UTF-8
Java
1,550
java
destroySingleton.java
Java
[]
null
[]
package java设计模式.模式3单例模式; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Constructor; /* * 破坏单例的三种方式 * * * */ public class destroySingleton { public static void main(String[] args) throws Exception { System.out.println("-----------序列化----------------------"); Singleton originSingleton = Singleton.getInstance(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(Singleton.getInstance()); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bis); Singleton serializeSingleton = (Singleton) ois.readObject(); System.out.println(originSingleton == serializeSingleton);//false System.out.println("-----------反射----------------------"); //通过反射获取 Constructor<Singleton> cons = Singleton.class.getDeclaredConstructor(); cons.setAccessible(true); Singleton reflextSingleton = cons.newInstance(); System.out.println(reflextSingleton == originSingleton);//false System.out.println("---------------------------克隆----------------------"); //Singleton cloneSingleton = (Singleton) originSingleton.clone(); //System.out.println(cloneSingleton == originSingleton);//false } }
1,550
0.654105
0.653432
40
36.150002
29.443632
82
false
false
0
0
0
0
0
0
0.575
false
false
12
965efce6c142daf7beaacd29192ae8f4f227bf16
8,358,006,427,233
0de7e8b71cba0316b83a96aded4b834c75ed463c
/src/main/java/com/pqqqqq/escript/lang/phrase/phrases/condition/DissimilarPhrase.java
057dfaeb9b1d3493e9126a3d7816f39ac56c711d
[]
no_license
pqqqqq/EScript
https://github.com/pqqqqq/EScript
96b0bbde0e7cd494935344bd13e73c4f0c426c1f
cb7ced071a56d239f304fd10cbcbfbc003a6ddcd
refs/heads/master
2020-07-03T16:00:56.790000
2017-01-03T01:08:23
2017-01-03T01:08:23
67,911,098
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pqqqqq.escript.lang.phrase.phrases.condition; import com.pqqqqq.escript.lang.data.Literal; import com.pqqqqq.escript.lang.line.Context; import com.pqqqqq.escript.lang.phrase.Result; import com.pqqqqq.escript.lang.phrase.analysis.syntax.Syntax; /** * Created by Kevin on 2016-09-02. * <p> * <pre> * The dissimilar phrase, which checks if two literals are NOT similar to each other * * Some examples: * <code>1 is not similar to 1 * $var dissimilar "hello"</code> * </pre> */ public class DissimilarPhrase implements ConditionalPhrase { private static final DissimilarPhrase INSTANCE = new DissimilarPhrase(); private static final Syntax[] SYNTAXES = { Syntax.compile("$Literal1 is? not similar to? $Literal2"), Syntax.compile("$Literal1 is? dissimilar to? $Literal2") }; /** * Gets the main instance * * @return the instance */ public static DissimilarPhrase instance() { return INSTANCE; } private DissimilarPhrase() { } @Override public Syntax[] getSyntaxes() { return SYNTAXES; } @Override public Result execute(Context ctx) { Literal literal1 = ctx.getLiteral("Literal1"); Literal literal2 = ctx.getLiteral("Literal2"); return Result.success(!literal1.asString().equalsIgnoreCase(literal2.asString())); } }
UTF-8
Java
1,389
java
DissimilarPhrase.java
Java
[ { "context": ".phrase.analysis.syntax.Syntax;\n\n/**\n * Created by Kevin on 2016-09-02.\n * <p>\n * <pre>\n * The dissimilar ", "end": 281, "score": 0.9632765650749207, "start": 276, "tag": "NAME", "value": "Kevin" } ]
null
[]
package com.pqqqqq.escript.lang.phrase.phrases.condition; import com.pqqqqq.escript.lang.data.Literal; import com.pqqqqq.escript.lang.line.Context; import com.pqqqqq.escript.lang.phrase.Result; import com.pqqqqq.escript.lang.phrase.analysis.syntax.Syntax; /** * Created by Kevin on 2016-09-02. * <p> * <pre> * The dissimilar phrase, which checks if two literals are NOT similar to each other * * Some examples: * <code>1 is not similar to 1 * $var dissimilar "hello"</code> * </pre> */ public class DissimilarPhrase implements ConditionalPhrase { private static final DissimilarPhrase INSTANCE = new DissimilarPhrase(); private static final Syntax[] SYNTAXES = { Syntax.compile("$Literal1 is? not similar to? $Literal2"), Syntax.compile("$Literal1 is? dissimilar to? $Literal2") }; /** * Gets the main instance * * @return the instance */ public static DissimilarPhrase instance() { return INSTANCE; } private DissimilarPhrase() { } @Override public Syntax[] getSyntaxes() { return SYNTAXES; } @Override public Result execute(Context ctx) { Literal literal1 = ctx.getLiteral("Literal1"); Literal literal2 = ctx.getLiteral("Literal2"); return Result.success(!literal1.asString().equalsIgnoreCase(literal2.asString())); } }
1,389
0.668107
0.653708
50
26.780001
25.580688
90
false
false
0
0
0
0
0
0
0.28
false
false
12
4f668c1527ea780ed98e1d397c2166a4890d8154
2,070,174,305,560
29e857378f1b4501d048bc1b7d60d9f606629253
/Zookeeper/src/com/tang/zk/ZKConnectionManager.java
fd3ce86db1783fa139e7876f98de2696ce3954b3
[]
no_license
kingtang/zkclient
https://github.com/kingtang/zkclient
89d9f07ca9c99131be6780b1b6f0f5c22162bd80
654c3d71995c24c9b81ec716653a6a476cc4c9c6
refs/heads/master
2020-05-30T07:12:08.681000
2017-06-14T14:34:03
2017-06-14T14:34:03
69,365,329
6
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tang.zk; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.ACLBackgroundPathAndBytesable; import org.apache.curator.framework.recipes.cache.TreeCache; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.RetryNTimes; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.data.Stat; import org.eclipse.jface.viewers.TreeViewer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.tang.zk.data.ServerNode; import com.tang.zk.listener.DefaultConnectionStateListener; import com.tang.zk.listener.TreeListener; /** * 管理ZK连接 * * @author Administrator * */ public final class ZKConnectionManager{ private static Logger debugLog = LoggerFactory.getLogger("debug"); private static final ZKConnectionManager INSTANCE = new ZKConnectionManager(); private Map<String, CuratorFramework> zkClients = new HashMap<String, CuratorFramework>(); private List<TreeListener> treeListeners = new ArrayList<TreeListener>(); private List<TreeCache> treeCaches = new ArrayList<TreeCache>(); private Map<String/**connectionString.*/,ConnectionState> states = new ConcurrentHashMap<String, ConnectionState>(); public void initClient(ServerNode serverNode,TreeViewer treeViewer) { String connectString = serverNode.getIp() + ":" + serverNode.getPort(); CuratorFramework zkClient = CuratorFrameworkFactory.builder() .connectString(connectString).connectionTimeoutMs(1000).sessionTimeoutMs(1000) .retryPolicy(new RetryNTimes(Integer.MAX_VALUE, 3000)) .build(); // 启动zk连接 zkClient.start(); zkClients.put(serverNode.getName(), zkClient); debugLog.info(serverNode.getName() + " zk client has started."); TreeListener listener = new TreeListener(serverNode.getName()); TreeCache treeCache = new TreeCache(zkClient, "/"); treeCache.getListenable().addListener(listener); // 启动监听 try { treeCache.start(); } catch (Exception e) { debugLog.error("start tree cache failed.", e); } treeListeners.add(listener); ConnectionStateListener stateListener = new DefaultConnectionStateListener(treeViewer,treeCache); treeCaches.add(treeCache); zkClient.getConnectionStateListenable().addListener(stateListener,Executors.newFixedThreadPool(1)); } public static ZKConnectionManager getInstance() { return INSTANCE; } /** * 返回子路径 * * @param parentPath * @return */ public List<String> getChildrenPath(String parentPath, String serverName) { if (null == zkClients.get(serverName).getZookeeperClient()) { return null; } if (zkClients.get(serverName).getZookeeperClient().isConnected()) { try { return zkClients.get(serverName).getChildren() .forPath(parentPath); } catch (Exception e) { debugLog.error("get children path error.", e); } } return null; } public boolean isConnected(String serverName) { String connectionString = zkClients.get(serverName).getZookeeperClient().getCurrentConnectionString(); ConnectionState currentState = states.get(connectionString); if(ConnectionState.CONNECTED == currentState || ConnectionState.RECONNECTED == currentState) { return true; } return false; } public void setState(String connectString,ConnectionState state) { states.put(connectString, state); } public ConnectionState getState(String connectString) { return states.get(connectString); } public ConnectionState getStateByServerName(String serverName) { return states.get(this.getZkClient(serverName).getZookeeperClient().getCurrentConnectionString()); } //public boolean public Object getZKData(String path, String serverName) { try { byte[] bytes = zkClients.get(serverName).getData().forPath(path); if(null != bytes) { return new String(bytes, Charset.forName("UTF-8")); } } catch (Exception e) { debugLog.error("get zk data error.", e); } return null; } public void updateZKData(String path, String serverName, String data) { if (null != path && null != data) { try { zkClients.get(serverName).setData() .forPath(path, data.getBytes(Charset.forName("UTF-8"))); } catch (Exception e) { debugLog.error("update zk data error", e); } } } public void deleteZKData(String path, String serverName) { if (null != path && null != serverName) { try { zkClients.get(serverName).delete().forPath(path); } catch (Exception e) { debugLog.error("delete zk data error.", e); } } } public void deleteZKDataAndChild(String path, String serverName) { if (null != path && null != serverName) { try { zkClients.get(serverName).delete().deletingChildrenIfNeeded().forPath(path); } catch (Exception e) { debugLog.error("delete zk data and child error.", e); } } } public void addZKData(String path,String data,String serverName,boolean isEphemeral,boolean isSequential) { if (null != path && null != serverName) { try { ACLBackgroundPathAndBytesable<String> builder = getAdjustedBuilder(serverName, isEphemeral, isSequential); if(null == data) { builder.forPath(path); } else { builder.forPath(path, data.getBytes(Charset.forName("UTF-8"))); } } catch (Exception e) { debugLog.error("add zk node error.", e); } } } private ACLBackgroundPathAndBytesable<String> getAdjustedBuilder( String serverName,boolean isEphemeral,boolean isSequential) { //临时节点 if(isEphemeral) { //序列 if(isSequential) { return zkClients.get(serverName).create().withMode(CreateMode.EPHEMERAL_SEQUENTIAL); } else { return zkClients.get(serverName).create().withMode(CreateMode.EPHEMERAL); } } else { if(isSequential) { return zkClients.get(serverName).create().withMode(CreateMode.PERSISTENT_SEQUENTIAL); } else { return zkClients.get(serverName).create().withMode(CreateMode.PERSISTENT); } } } public Stat getZKMetaData(String path, String serverName) { // zkClients.get(serverName).getZookeeperClient().getZooKeeper(). try { Stat stat = zkClients.get(serverName).checkExists().forPath(path); return stat; } catch (Exception e) { debugLog.error("get zk meta data error.", e); } return null; } public CuratorFramework getZkClient(String serverName) { return zkClients.get(serverName); } public void addZkClient(String serverName,CuratorFramework curator) { zkClients.put(serverName,curator); } public void registerTreeViewer(TreeViewer treeViewer) { for (TreeListener treeListener : treeListeners) { treeListener.setTreeViewer(treeViewer); } } public void close() { try { for (TreeCache treeCache : treeCaches) { treeCache.close(); } Iterator<Entry<String, CuratorFramework>> iterator = zkClients.entrySet().iterator(); while(iterator.hasNext()) { CuratorFramework client = iterator.next().getValue(); try { client.close(); } catch (Exception e) { } } } finally { System.exit(0); } } }
UTF-8
Java
7,764
java
ZKConnectionManager.java
Java
[ { "context": "r.TreeListener;\r\n\r\n/**\r\n * 管理ZK连接\r\n * \r\n * @author Administrator\r\n * \r\n */\r\npublic final class ZKConnectionManager", "end": 1109, "score": 0.9876213669776917, "start": 1096, "tag": "NAME", "value": "Administrator" } ]
null
[]
package com.tang.zk; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.ACLBackgroundPathAndBytesable; import org.apache.curator.framework.recipes.cache.TreeCache; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.RetryNTimes; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.data.Stat; import org.eclipse.jface.viewers.TreeViewer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.tang.zk.data.ServerNode; import com.tang.zk.listener.DefaultConnectionStateListener; import com.tang.zk.listener.TreeListener; /** * 管理ZK连接 * * @author Administrator * */ public final class ZKConnectionManager{ private static Logger debugLog = LoggerFactory.getLogger("debug"); private static final ZKConnectionManager INSTANCE = new ZKConnectionManager(); private Map<String, CuratorFramework> zkClients = new HashMap<String, CuratorFramework>(); private List<TreeListener> treeListeners = new ArrayList<TreeListener>(); private List<TreeCache> treeCaches = new ArrayList<TreeCache>(); private Map<String/**connectionString.*/,ConnectionState> states = new ConcurrentHashMap<String, ConnectionState>(); public void initClient(ServerNode serverNode,TreeViewer treeViewer) { String connectString = serverNode.getIp() + ":" + serverNode.getPort(); CuratorFramework zkClient = CuratorFrameworkFactory.builder() .connectString(connectString).connectionTimeoutMs(1000).sessionTimeoutMs(1000) .retryPolicy(new RetryNTimes(Integer.MAX_VALUE, 3000)) .build(); // 启动zk连接 zkClient.start(); zkClients.put(serverNode.getName(), zkClient); debugLog.info(serverNode.getName() + " zk client has started."); TreeListener listener = new TreeListener(serverNode.getName()); TreeCache treeCache = new TreeCache(zkClient, "/"); treeCache.getListenable().addListener(listener); // 启动监听 try { treeCache.start(); } catch (Exception e) { debugLog.error("start tree cache failed.", e); } treeListeners.add(listener); ConnectionStateListener stateListener = new DefaultConnectionStateListener(treeViewer,treeCache); treeCaches.add(treeCache); zkClient.getConnectionStateListenable().addListener(stateListener,Executors.newFixedThreadPool(1)); } public static ZKConnectionManager getInstance() { return INSTANCE; } /** * 返回子路径 * * @param parentPath * @return */ public List<String> getChildrenPath(String parentPath, String serverName) { if (null == zkClients.get(serverName).getZookeeperClient()) { return null; } if (zkClients.get(serverName).getZookeeperClient().isConnected()) { try { return zkClients.get(serverName).getChildren() .forPath(parentPath); } catch (Exception e) { debugLog.error("get children path error.", e); } } return null; } public boolean isConnected(String serverName) { String connectionString = zkClients.get(serverName).getZookeeperClient().getCurrentConnectionString(); ConnectionState currentState = states.get(connectionString); if(ConnectionState.CONNECTED == currentState || ConnectionState.RECONNECTED == currentState) { return true; } return false; } public void setState(String connectString,ConnectionState state) { states.put(connectString, state); } public ConnectionState getState(String connectString) { return states.get(connectString); } public ConnectionState getStateByServerName(String serverName) { return states.get(this.getZkClient(serverName).getZookeeperClient().getCurrentConnectionString()); } //public boolean public Object getZKData(String path, String serverName) { try { byte[] bytes = zkClients.get(serverName).getData().forPath(path); if(null != bytes) { return new String(bytes, Charset.forName("UTF-8")); } } catch (Exception e) { debugLog.error("get zk data error.", e); } return null; } public void updateZKData(String path, String serverName, String data) { if (null != path && null != data) { try { zkClients.get(serverName).setData() .forPath(path, data.getBytes(Charset.forName("UTF-8"))); } catch (Exception e) { debugLog.error("update zk data error", e); } } } public void deleteZKData(String path, String serverName) { if (null != path && null != serverName) { try { zkClients.get(serverName).delete().forPath(path); } catch (Exception e) { debugLog.error("delete zk data error.", e); } } } public void deleteZKDataAndChild(String path, String serverName) { if (null != path && null != serverName) { try { zkClients.get(serverName).delete().deletingChildrenIfNeeded().forPath(path); } catch (Exception e) { debugLog.error("delete zk data and child error.", e); } } } public void addZKData(String path,String data,String serverName,boolean isEphemeral,boolean isSequential) { if (null != path && null != serverName) { try { ACLBackgroundPathAndBytesable<String> builder = getAdjustedBuilder(serverName, isEphemeral, isSequential); if(null == data) { builder.forPath(path); } else { builder.forPath(path, data.getBytes(Charset.forName("UTF-8"))); } } catch (Exception e) { debugLog.error("add zk node error.", e); } } } private ACLBackgroundPathAndBytesable<String> getAdjustedBuilder( String serverName,boolean isEphemeral,boolean isSequential) { //临时节点 if(isEphemeral) { //序列 if(isSequential) { return zkClients.get(serverName).create().withMode(CreateMode.EPHEMERAL_SEQUENTIAL); } else { return zkClients.get(serverName).create().withMode(CreateMode.EPHEMERAL); } } else { if(isSequential) { return zkClients.get(serverName).create().withMode(CreateMode.PERSISTENT_SEQUENTIAL); } else { return zkClients.get(serverName).create().withMode(CreateMode.PERSISTENT); } } } public Stat getZKMetaData(String path, String serverName) { // zkClients.get(serverName).getZookeeperClient().getZooKeeper(). try { Stat stat = zkClients.get(serverName).checkExists().forPath(path); return stat; } catch (Exception e) { debugLog.error("get zk meta data error.", e); } return null; } public CuratorFramework getZkClient(String serverName) { return zkClients.get(serverName); } public void addZkClient(String serverName,CuratorFramework curator) { zkClients.put(serverName,curator); } public void registerTreeViewer(TreeViewer treeViewer) { for (TreeListener treeListener : treeListeners) { treeListener.setTreeViewer(treeViewer); } } public void close() { try { for (TreeCache treeCache : treeCaches) { treeCache.close(); } Iterator<Entry<String, CuratorFramework>> iterator = zkClients.entrySet().iterator(); while(iterator.hasNext()) { CuratorFramework client = iterator.next().getValue(); try { client.close(); } catch (Exception e) { } } } finally { System.exit(0); } } }
7,764
0.69759
0.695128
269
26.69145
28.419939
117
false
false
0
0
0
0
0
0
2.319703
false
false
12
765484d0d090ea20613b6eae91946d7c67d85b4c
27,547,920,284,081
edf022677fb4b482bef75133000214aca0fbae54
/src/main/java/com/jos/sbt/service/FrankfurterConvertService.java
1bbdf7a2dafedcd7a6bc6019f2cf0d36b4e74090
[ "Apache-2.0" ]
permissive
tblasCode/spring-boot-testing-v2
https://github.com/tblasCode/spring-boot-testing-v2
3b855087ca5abc01fda5f19b3c4049931431b359
146d2b62cbaf36cd494030d3c6adec6632ced846
refs/heads/main
2023-01-18T16:25:15.993000
2020-12-02T23:22:13
2020-12-02T23:22:13
302,637,335
0
0
Apache-2.0
true
2020-10-09T12:39:29
2020-10-09T12:39:28
2020-10-09T10:58:40
2020-10-09T10:58:38
6
0
0
0
null
false
false
package com.jos.sbt.service; import java.math.BigDecimal; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import org.springframework.stereotype.Service; import com.jos.sbt.model.RateResponse; import lombok.extern.slf4j.Slf4j; /** * Service. * */ @Service @Slf4j public class FrankfurterConvertService implements ConvertService { /** * Timeout. */ private static final int TIMEOUT = 60; /** * Url endpoint. */ private final String url; /** * RestClientService. */ private final RestClientService restClientService; /** * MoneyConvertService. * @param aRestClientService - restClientService */ public FrankfurterConvertService( final RestClientService aRestClientService) { this.restClientService = aRestClientService; this.url = "https://api.frankfurter.app/latest"; } /** * findRate. * @param target target * @return RateResponse */ public CompletableFuture<BigDecimal> findRate(final String target) { log.info("find rate FrankfurterConvertService."); return CompletableFuture .supplyAsync(() -> restClientService.execute(url, RateResponse.class) .getRates().get(target)) .orTimeout(TIMEOUT, TimeUnit.SECONDS) .handle((response, ex) -> { if (!Objects.isNull(ex)) { log.error(ex.getLocalizedMessage(), ex); } log.info("response FrankfurterConvertService"); return response; }); } }
UTF-8
Java
1,751
java
FrankfurterConvertService.java
Java
[]
null
[]
package com.jos.sbt.service; import java.math.BigDecimal; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import org.springframework.stereotype.Service; import com.jos.sbt.model.RateResponse; import lombok.extern.slf4j.Slf4j; /** * Service. * */ @Service @Slf4j public class FrankfurterConvertService implements ConvertService { /** * Timeout. */ private static final int TIMEOUT = 60; /** * Url endpoint. */ private final String url; /** * RestClientService. */ private final RestClientService restClientService; /** * MoneyConvertService. * @param aRestClientService - restClientService */ public FrankfurterConvertService( final RestClientService aRestClientService) { this.restClientService = aRestClientService; this.url = "https://api.frankfurter.app/latest"; } /** * findRate. * @param target target * @return RateResponse */ public CompletableFuture<BigDecimal> findRate(final String target) { log.info("find rate FrankfurterConvertService."); return CompletableFuture .supplyAsync(() -> restClientService.execute(url, RateResponse.class) .getRates().get(target)) .orTimeout(TIMEOUT, TimeUnit.SECONDS) .handle((response, ex) -> { if (!Objects.isNull(ex)) { log.error(ex.getLocalizedMessage(), ex); } log.info("response FrankfurterConvertService"); return response; }); } }
1,751
0.595089
0.592233
65
25.938461
21.596209
77
false
false
0
0
0
0
0
0
0.338462
false
false
12
669ee8709b94b8b47a38b3f573ecf9d7d220e68a
31,052,613,551,665
dc611023d09bf305f3273e407afd010438cbe867
/src/week7/EchoServer.java
f5d805da387c91d9ade61e501009b964fb6ff672
[]
no_license
kandarp1691/Week7_EchoServer
https://github.com/kandarp1691/Week7_EchoServer
e8b3d9641d1433026eb4c0c809f3539ca8fb52c9
92e84cffafb4171016da43d0cae6fe95bafe43d3
refs/heads/master
2016-09-06T12:12:57.065000
2015-03-06T05:36:48
2015-03-06T05:36:48
31,638,954
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package week7; import java.io.*; import java.net.*; public class EchoServer { public static void main(String[] args) { try { ServerSocket echoserver = new ServerSocket(8888); Socket client = echoserver.accept(); BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream())); PrintWriter writer = new PrintWriter(client.getOutputStream(), true); writer.println("Connected to the EchoServer at port and please Type 'QUIT' to close."); String line = null; while (line != "QUIT") { line = reader.readLine(); writer.println("Got: " + line); System.out.println("The client says :" + line); if (line.equals("QUIT")) { System.out.println("Connection closed and quiting the application"); break; } } client.close(); } catch (Exception e) { System.out.println("Exception occured " + e); } } }
UTF-8
Java
890
java
EchoServer.java
Java
[]
null
[]
package week7; import java.io.*; import java.net.*; public class EchoServer { public static void main(String[] args) { try { ServerSocket echoserver = new ServerSocket(8888); Socket client = echoserver.accept(); BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream())); PrintWriter writer = new PrintWriter(client.getOutputStream(), true); writer.println("Connected to the EchoServer at port and please Type 'QUIT' to close."); String line = null; while (line != "QUIT") { line = reader.readLine(); writer.println("Got: " + line); System.out.println("The client says :" + line); if (line.equals("QUIT")) { System.out.println("Connection closed and quiting the application"); break; } } client.close(); } catch (Exception e) { System.out.println("Exception occured " + e); } } }
890
0.667416
0.661798
37
23.054054
26.191545
94
false
false
0
0
0
0
0
0
2.297297
false
false
12
46125032f8dbebcb61017478ca939f9aa1261984
31,052,613,551,069
ff31a02180223660f757ec3f93fd8467e468e570
/src/main/java/com/gluxen/service/QuestionService.java
0851365f5d70986747b779b5875878d476e46a11
[]
no_license
ILUO/inquirysystem
https://github.com/ILUO/inquirysystem
ac4dc63443f771f6be295881a3d47fe1cd453ad9
3e50b81cfcf46a09298e11bcd9f7f4ef0dfca9ed
refs/heads/master
2021-09-11T16:56:12.976000
2018-04-10T03:03:48
2018-04-10T03:03:48
116,641,643
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gluxen.service; import com.alibaba.fastjson.JSONObject; /** * Created by Yang Xing Luo on 2018/1/21. */ public interface QuestionService { /** * 增加/更新病人填空题历史 * @param jsonObject * @return */ JSONObject addHistory(JSONObject jsonObject); /** * 获得病人最近一次填空题历史 * @param patientId * @return */ JSONObject getCompletionHistory(Long patientId); /** * 获取病人最近一次选择题历史 * @param patientId * @return */ JSONObject getChoiceHistory(Long patientId); /** * 获取某次问诊的选择题历史 * @param inquiryId * @return */ JSONObject getInquiryChoice(int inquiryId); /** * 获取某次问诊的填空题历史 * @param inquiryId * @return */ JSONObject getInquiryCompletion(int inquiryId); /** * 获取最近的问诊答案 * @param inquiryId * @return */ JSONObject getAnswer(int inquiryId); }
UTF-8
Java
1,045
java
QuestionService.java
Java
[ { "context": "om.alibaba.fastjson.JSONObject;\n\n/**\n * Created by Yang Xing Luo on 2018/1/21.\n */\npublic interface QuestionServic", "end": 101, "score": 0.999815821647644, "start": 88, "tag": "NAME", "value": "Yang Xing Luo" } ]
null
[]
package com.gluxen.service; import com.alibaba.fastjson.JSONObject; /** * Created by <NAME> on 2018/1/21. */ public interface QuestionService { /** * 增加/更新病人填空题历史 * @param jsonObject * @return */ JSONObject addHistory(JSONObject jsonObject); /** * 获得病人最近一次填空题历史 * @param patientId * @return */ JSONObject getCompletionHistory(Long patientId); /** * 获取病人最近一次选择题历史 * @param patientId * @return */ JSONObject getChoiceHistory(Long patientId); /** * 获取某次问诊的选择题历史 * @param inquiryId * @return */ JSONObject getInquiryChoice(int inquiryId); /** * 获取某次问诊的填空题历史 * @param inquiryId * @return */ JSONObject getInquiryCompletion(int inquiryId); /** * 获取最近的问诊答案 * @param inquiryId * @return */ JSONObject getAnswer(int inquiryId); }
1,038
0.596685
0.58895
50
17.1
15.118531
52
false
false
0
0
0
0
0
0
0.16
false
false
12
f6b88421390255c8dfa8c815e569fd2eb5552b28
19,370,302,546,273
399da824da3d95b7589bba6e413babfbbb0347cf
/Java框架学习/Spring Boot/springbootmybatis/src/main/java/top/musuixin/mybatis/service/impl/PostServiceImpl.java
84d070f0bae0a8062859363144d79c3c433eeefa
[ "MIT" ]
permissive
musuixin/Java-Study
https://github.com/musuixin/Java-Study
06e5c164d253950d6ea68765839b102992fc9241
1d06ca1b0dc7fd81e727e499c996163e5a2b1c88
refs/heads/main
2023-06-17T10:03:49.929000
2021-07-19T09:01:51
2021-07-19T09:01:51
355,395,890
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package top.musuixin.mybatis.service.impl; import top.musuixin.mybatis.entity.Post; import top.musuixin.mybatis.mapper.PostMapper; import top.musuixin.mybatis.service.IPostService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * 服务实现类 * </p> * * @author jobob * @since 2020-02-10 */ @Service public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements IPostService { }
UTF-8
Java
486
java
PostServiceImpl.java
Java
[ { "context": "ervice;\n\n/**\n * <p>\n * 服务实现类\n * </p>\n *\n * @author jobob\n * @since 2020-02-10\n */\n@Service\npublic class Po", "end": 345, "score": 0.9996166825294495, "start": 340, "tag": "USERNAME", "value": "jobob" } ]
null
[]
package top.musuixin.mybatis.service.impl; import top.musuixin.mybatis.entity.Post; import top.musuixin.mybatis.mapper.PostMapper; import top.musuixin.mybatis.service.IPostService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * 服务实现类 * </p> * * @author jobob * @since 2020-02-10 */ @Service public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements IPostService { }
486
0.779412
0.762605
20
22.799999
25.927977
92
false
false
0
0
0
0
0
0
0.35
false
false
12
11fc705007fb5d86665532dd07f9440d3fa4a7ff
20,194,936,297,658
f20a0889ba159d9b7f21c0236e0203e0cb400392
/health/health_common/src/main/java/com/itheima/utils/CookieUtil.java
11e654ae7bcf1a906b54079cee6081801b46c4d4
[]
no_license
Banay6/health
https://github.com/Banay6/health
34b3859a82e99a153aa651b750755ebb136255b1
821409656a36bc9836d1d3e55000e897f2fa12d1
refs/heads/master
2022-12-21T13:36:12.849000
2019-10-13T03:16:43
2019-10-13T03:16:43
214,751,387
0
0
null
false
2022-12-16T04:25:26
2019-10-13T02:55:49
2019-10-13T03:22:12
2022-12-16T04:25:26
15,812
0
0
15
JavaScript
false
false
package com.itheima.utils; import javax.servlet.http.Cookie; public class CookieUtil { /** * 创建并配置Cookie * * @param name cookie的name * @param value cookie的value * @param time 有效期,秒 * @param path 有效范围 * @return */ public static Cookie createCookie(String name, String value, int time, String path) { Cookie cookie = new Cookie(name, value); cookie.setMaxAge(time); cookie.setPath(path); return cookie; } public static String getCookieValue(Cookie[] cookies, String cookieName) { String value = ""; if (cookies != null && cookies.length > 0) { for (Cookie cookie : cookies) { if (cookieName.equals(cookie.getName())) { value = cookie.getValue(); } } } return value; } }
UTF-8
Java
906
java
CookieUtil.java
Java
[]
null
[]
package com.itheima.utils; import javax.servlet.http.Cookie; public class CookieUtil { /** * 创建并配置Cookie * * @param name cookie的name * @param value cookie的value * @param time 有效期,秒 * @param path 有效范围 * @return */ public static Cookie createCookie(String name, String value, int time, String path) { Cookie cookie = new Cookie(name, value); cookie.setMaxAge(time); cookie.setPath(path); return cookie; } public static String getCookieValue(Cookie[] cookies, String cookieName) { String value = ""; if (cookies != null && cookies.length > 0) { for (Cookie cookie : cookies) { if (cookieName.equals(cookie.getName())) { value = cookie.getValue(); } } } return value; } }
906
0.553776
0.552632
33
25.484848
21.413845
89
false
false
0
0
0
0
0
0
0.424242
false
false
12
35c423b27411445ab71f497a58d7517a449936eb
4,140,348,473,924
8477bbf871f622e9e8ee8dc67b4d4cac0f3ea6b9
/Ch6 ReviewAdvOOP/KinderGartenAndUniversityStudent/Student.java
92c1dd566ed21b040c13d8ada82f91b687f08e61
[]
no_license
abhinav0121/JavaLabExercise
https://github.com/abhinav0121/JavaLabExercise
08aedd0005af0c1b4c780a8d137d38845446822f
d4d9d922d8c05e60fff3edc52af7a3f43ac01f1e
refs/heads/master
2023-08-18T20:55:20.164000
2021-10-05T17:05:24
2021-10-05T17:05:24
413,907,691
0
0
null
true
2021-10-05T17:05:25
2021-10-05T17:03:04
2021-10-05T17:03:05
2021-10-05T17:05:24
8,474
0
0
0
null
false
false
package warmupkustudent; public abstract class Student { protected long studentId; protected String studentName; protected double tuition; public Student(long studentId, String studentName, double tuition) { this.studentId = studentId; this.studentName = studentName; this.tuition = tuition; } public abstract double expensePerSemester(); @Override public String toString() { return "studentId=" + studentId + ", studentName=" + studentName + ", tuition=" + tuition + ", "; } }
UTF-8
Java
584
java
Student.java
Java
[ { "context": "studentId = studentId;\r\n this.studentName = studentName;\r\n this.tuition = tuition;\r\n }\r\n\r\n p", "end": 307, "score": 0.9371075630187988, "start": 296, "tag": "NAME", "value": "studentName" } ]
null
[]
package warmupkustudent; public abstract class Student { protected long studentId; protected String studentName; protected double tuition; public Student(long studentId, String studentName, double tuition) { this.studentId = studentId; this.studentName = studentName; this.tuition = tuition; } public abstract double expensePerSemester(); @Override public String toString() { return "studentId=" + studentId + ", studentName=" + studentName + ", tuition=" + tuition + ", "; } }
584
0.626712
0.626712
21
25.809525
25.548496
105
false
false
0
0
0
0
0
0
0.666667
false
false
12
be5b4aa4b44fcb2ab131e2950ed94a262dd02146
26,499,948,225,524
26b2aecd88f9721caa6e107536e3b6d2af773ff5
/app/src/main/java/com/po/pwr/mountainmaps/Utils/Helpers/AdapterUtils.java
cb8ef5a57a29328986a512f2ff9cb245bb6976ff
[]
no_license
eipc16/po-android
https://github.com/eipc16/po-android
98d77af02c7781346193dfe41cfc898fe5eb7e1f
35b2173b302763e88b26ff9f89e8511e793f527d
refs/heads/master
2020-04-17T11:42:28.063000
2019-01-27T13:53:33
2019-01-27T13:53:33
166,551,922
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.po.pwr.mountainmaps.Utils.Helpers; import android.content.Context; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import com.po.pwr.mountainmaps.Models.PointModel; import com.po.pwr.mountainmaps.R; import com.po.pwr.mountainmaps.Utils.Adapters.PointListAdapter; import java.util.List; public final class AdapterUtils { private AdapterUtils() { /* empty constructor */ } /** Metoda aktualizująca adapter obsługujący listę odcinków trasy * @param view Obecny widok * @param context Obecny kontekst * @param newPointList Nowa lista punktów */ public static void updateRecyclerViewPointList(View view, Context context, List<PointModel> newPointList) { RecyclerView mRecyclerView; RecyclerView.LayoutManager mLayoutManager; mRecyclerView = view.findViewById(R.id.hikingTrailPointsList); mRecyclerView.setHasFixedSize(true); mLayoutManager = new LinearLayoutManager(context); mRecyclerView.setLayoutManager(mLayoutManager); PointListAdapter mRecyclerAdapter = new PointListAdapter(newPointList); mRecyclerView.setAdapter(mRecyclerAdapter); } }
UTF-8
Java
1,245
java
AdapterUtils.java
Java
[]
null
[]
package com.po.pwr.mountainmaps.Utils.Helpers; import android.content.Context; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import com.po.pwr.mountainmaps.Models.PointModel; import com.po.pwr.mountainmaps.R; import com.po.pwr.mountainmaps.Utils.Adapters.PointListAdapter; import java.util.List; public final class AdapterUtils { private AdapterUtils() { /* empty constructor */ } /** Metoda aktualizująca adapter obsługujący listę odcinków trasy * @param view Obecny widok * @param context Obecny kontekst * @param newPointList Nowa lista punktów */ public static void updateRecyclerViewPointList(View view, Context context, List<PointModel> newPointList) { RecyclerView mRecyclerView; RecyclerView.LayoutManager mLayoutManager; mRecyclerView = view.findViewById(R.id.hikingTrailPointsList); mRecyclerView.setHasFixedSize(true); mLayoutManager = new LinearLayoutManager(context); mRecyclerView.setLayoutManager(mLayoutManager); PointListAdapter mRecyclerAdapter = new PointListAdapter(newPointList); mRecyclerView.setAdapter(mRecyclerAdapter); } }
1,245
0.759483
0.757869
36
33.416668
27.72822
111
false
false
0
0
0
0
0
0
0.527778
false
false
12
245437259f2afca4e64144347227dada9970aa12
26,499,948,222,706
02028cd3cfec1ed67e1c16b127893e32e87cbdf0
/about-Hystrix/src/main/java/aboutHystrix/AboutHystrixApplication.java
aa51a048a73dde76f8f5cb8a9833d44bbb43bf5b
[]
no_license
SaiCharan1103/presentation
https://github.com/SaiCharan1103/presentation
2273ef746aeed9e5306023e013410b5ed815bd23
77bf201353ea570d236bbe590f3bff4dc2d60e84
refs/heads/master
2023-09-04T16:10:20.221000
2021-11-25T11:22:51
2021-11-25T11:22:51
428,897,238
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package aboutHystrix; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; @SuppressWarnings("deprecation") @SpringBootApplication @EnableEurekaClient @EnableCircuitBreaker public class AboutHystrixApplication { public static void main(String[] args) { SpringApplication.run(AboutHystrixApplication.class, args); } }
UTF-8
Java
537
java
AboutHystrixApplication.java
Java
[]
null
[]
package aboutHystrix; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; @SuppressWarnings("deprecation") @SpringBootApplication @EnableEurekaClient @EnableCircuitBreaker public class AboutHystrixApplication { public static void main(String[] args) { SpringApplication.run(AboutHystrixApplication.class, args); } }
537
0.851024
0.851024
18
28.833334
25.848383
76
false
false
0
0
0
0
0
0
0.611111
false
false
12
71d05e7b4beed8b2e9c2784ee811d3307ba4c624
12,807,592,498,104
ac02dc5040c19b52af0ed1ce9120d1472f612005
/src/main/java/com/mo/guard/exception/NotFoundUserException.java
6238e3dcd28392bd9822f671fde1be60239ee398
[]
no_license
sdm-project-organization/sdm-web-guard
https://github.com/sdm-project-organization/sdm-web-guard
62e63af34fe30db3c22b09e7cc12f2e041bd37c5
c84382d6bc085b0763c34fc5849f3f1893da3164
refs/heads/master
2020-05-18T22:36:18.161000
2019-09-17T04:20:33
2019-09-17T04:20:33
184,694,633
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mo.guard.exception; public class NotFoundUserException extends RuntimeException{ }
UTF-8
Java
100
java
NotFoundUserException.java
Java
[]
null
[]
package com.mo.guard.exception; public class NotFoundUserException extends RuntimeException{ }
100
0.81
0.81
4
23
24.728525
60
false
false
0
0
0
0
0
0
0.25
false
false
12
40436e879567b53bedf0efb8c7d5514156e6cfee
23,759,759,096,858
7d7e98761fd238dfecd889358333cf8ed637e9d1
/src/test/java/core/game/KingPawnGame.java
c70720181371f159c78152a44bd42c0521f5473a
[]
no_license
hzding621/ChessGame
https://github.com/hzding621/ChessGame
2e8d9b627512dd1da9a00a2a1f67ca36e210f67d
a9ac467b58fb7982e7d0aed5adfbd699a03becad
refs/heads/master
2020-07-03T18:45:06.829000
2016-09-26T03:55:35
2016-09-26T03:55:35
67,578,891
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package core.game; import core.board.Square; import core.piece.KingPawn; import core.piece.Piece; import core.piece.PieceImpl; import core.player.Player; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import java.util.Collection; import java.util.Map; /** * A 4x4 toy piece set that is used for testing purposes */ public final class KingPawnGame implements GameSetting<Square, KingPawn> { private final Square.Builder builder; private final Piece<KingPawn> whitePawn = new PieceImpl<>(KingPawn.PAWN, Player.WHITE, 0); private final Piece<KingPawn> blackPawn = new PieceImpl<>(KingPawn.PAWN, Player.BLACK, 0); private final Piece<KingPawn> whiteKing = new PieceImpl<>(KingPawn.KING, Player.WHITE, 0); private final Piece<KingPawn> blackKing = new PieceImpl<>(KingPawn.KING, Player.BLACK, 0); public KingPawnGame(Square.Builder builder) { this.builder = builder; } @Override public Map<Square, Piece<KingPawn>> constructPiecesByStartingPosition() { return ImmutableMap.<Square, Piece<KingPawn>>builder() .put(builder.at(1, 0), whitePawn) .put(builder.at(2, 0), whiteKing) .put(builder.at(1, 3), blackPawn) .put(builder.at(2, 3), blackKing) .build(); } @Override public Map<Player, Square> getKingStartingPositions() { ImmutableMap.Builder<Player, Square> map = ImmutableMap.builder(); map.put(Player.WHITE, builder.at(2, 0)).put(Player.BLACK, builder.at(2, 3)); return map.build(); } @Override public Collection<Player> getPlayers() { return ImmutableList.of(Player.WHITE, Player.BLACK); } @Override public Player getStarter() { return Player.WHITE; } }
UTF-8
Java
1,824
java
KingPawnGame.java
Java
[]
null
[]
package core.game; import core.board.Square; import core.piece.KingPawn; import core.piece.Piece; import core.piece.PieceImpl; import core.player.Player; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import java.util.Collection; import java.util.Map; /** * A 4x4 toy piece set that is used for testing purposes */ public final class KingPawnGame implements GameSetting<Square, KingPawn> { private final Square.Builder builder; private final Piece<KingPawn> whitePawn = new PieceImpl<>(KingPawn.PAWN, Player.WHITE, 0); private final Piece<KingPawn> blackPawn = new PieceImpl<>(KingPawn.PAWN, Player.BLACK, 0); private final Piece<KingPawn> whiteKing = new PieceImpl<>(KingPawn.KING, Player.WHITE, 0); private final Piece<KingPawn> blackKing = new PieceImpl<>(KingPawn.KING, Player.BLACK, 0); public KingPawnGame(Square.Builder builder) { this.builder = builder; } @Override public Map<Square, Piece<KingPawn>> constructPiecesByStartingPosition() { return ImmutableMap.<Square, Piece<KingPawn>>builder() .put(builder.at(1, 0), whitePawn) .put(builder.at(2, 0), whiteKing) .put(builder.at(1, 3), blackPawn) .put(builder.at(2, 3), blackKing) .build(); } @Override public Map<Player, Square> getKingStartingPositions() { ImmutableMap.Builder<Player, Square> map = ImmutableMap.builder(); map.put(Player.WHITE, builder.at(2, 0)).put(Player.BLACK, builder.at(2, 3)); return map.build(); } @Override public Collection<Player> getPlayers() { return ImmutableList.of(Player.WHITE, Player.BLACK); } @Override public Player getStarter() { return Player.WHITE; } }
1,824
0.676535
0.666667
55
32.163635
29.005808
94
false
false
0
0
0
0
0
0
0.872727
false
false
12
dde902da1edafb0cb8713f9fde1b1e0a83e17b2f
25,099,788,881,868
3767880230113b858e4b9b7f1a698e4de299dd4a
/java/src/main/java/com/logics/t4/_5_Tst.java
dd31f77bb90e2eb344cfe4b12843abf66d14e018
[]
no_license
loki-tailor/tutorials
https://github.com/loki-tailor/tutorials
153ab50c81adeecf9edd2c127e022320b4610d6f
9dc7e53308571926ca4591c02fd3ec7bad11b217
refs/heads/main
2023-03-08T21:04:29.599000
2022-10-23T06:54:43
2022-10-23T06:54:43
154,438,897
0
0
null
false
2023-03-01T06:13:51
2018-10-24T04:27:26
2022-11-10T06:21:27
2023-03-01T06:13:47
189,085
0
0
75
Python
false
false
package com.logics.t4; public class _5_Tst { public static void main(String[] args) { Error e = new Error(); boolean b1 = e instanceof Error; boolean b2 = e instanceof Throwable; boolean b3 = e instanceof Exception; // compile error boolean b4 = e instanceof RuntimeException; // compile error boolean b5 = new StackOverflowError() instanceof Error; } } /*- Explanation class Error extends Throwable, so `obj instanceof Error;` and `obj instanceof Throwable;` return true. But Error class is not related to Exception and RuntimeException classes in multilevel inheritance and that is why Line n1 and Line n2 causes compilation error. */
UTF-8
Java
703
java
_5_Tst.java
Java
[]
null
[]
package com.logics.t4; public class _5_Tst { public static void main(String[] args) { Error e = new Error(); boolean b1 = e instanceof Error; boolean b2 = e instanceof Throwable; boolean b3 = e instanceof Exception; // compile error boolean b4 = e instanceof RuntimeException; // compile error boolean b5 = new StackOverflowError() instanceof Error; } } /*- Explanation class Error extends Throwable, so `obj instanceof Error;` and `obj instanceof Throwable;` return true. But Error class is not related to Exception and RuntimeException classes in multilevel inheritance and that is why Line n1 and Line n2 causes compilation error. */
703
0.698435
0.685633
26
26.038462
38.303928
160
false
false
0
0
0
0
0
0
0.384615
false
false
12
f8f5aa6a5144f16f28c9db30e84f7d2e8b95fa7a
20,547,123,570,077
6eb38a45cc67961190540c0f26b370e226baa5ee
/src/unity2/ABCtrees/Test.java
c247b1be2fa83453ea6137ce3eed7aba1aeae253
[]
no_license
estebanjojoa96/data-structure
https://github.com/estebanjojoa96/data-structure
819483568c994b11240ada026ab650f3d2207a99
195466aa98abfa35a7ded7ac848cf4c576cce206
refs/heads/master
2021-01-21T14:01:59.712000
2016-05-28T04:14:48
2016-05-28T04:14:48
51,145,548
0
0
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 unity2.ABCtrees; /** * * @author AULA1 */ public class Test { public static void main (String args []){ tree t = new tree(); int values[] = {8,4,16,5,6,17,20,1,10,14,13,15}; for (int i=0; i<values.length; i++){ t.add(values[i]); } int v=13; System.out.print("Path to" + v + ":"); t.printpath(v); if(t.isLeaf(v)){ System.out.println(""); }else{ System.out.println(""); } System.out.println("print tree"); t.print(); System.out.print(""); t.Max(); t.Min(); //t.Printleafs(); t.Count(); System.out.println("recuersive print"); t.recursivePrint(); System.out.println("recursive count"); int r = t.recursiveCount(); System.out.println("Total nodes "+r); System.out.println(""); System.out.println("Post Order Print"); t.PostOrderPrint(); System.out.println("Pre Order Print"); t.PreOrderPrint(); System.out.println("In Order Print"); t.inOrderPrint(); System.out.println("Print Leafs"); t.PrintLeafsR(); System.out.println(""); System.out.println("HEIGHT"); System.out.println(""+t.Height()); System.out.println(""); System.out.println("Draw Tree"); t.Draw(); System.out.println(""+ t.isComplete()); System.out.println(""+ t.Exist(4)); System.out.println("PRUEBA DE FALSO"); System.out.println(""); System.out.println(""+ t.Exist(50)); //t.invert(); //t.Prune(); System.out.println("COUNT ODDS"); System.out.println(t.CountOdds()); System.out.println("COMPLETE"); t.Complete(); System.out.println("SON'S ALONE'S"); t.PrintSonAlone(); System.out.println("REVERSE PRINT"); t.reversePrint(); System.out.println("PRINT MISSINGS"); //t.PrintMissings(); t.balance(); t.equilibriumFactor(); t.remove(10); } }
UTF-8
Java
2,443
java
Test.java
Java
[ { "context": "/\r\npackage unity2.ABCtrees;\r\n\r\n/**\r\n *\r\n * @author AULA1\r\n */\r\npublic class Test {\r\n \r\n \r\n public s", "end": 243, "score": 0.9995324611663818, "start": 238, "tag": "USERNAME", "value": "AULA1" } ]
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 unity2.ABCtrees; /** * * @author AULA1 */ public class Test { public static void main (String args []){ tree t = new tree(); int values[] = {8,4,16,5,6,17,20,1,10,14,13,15}; for (int i=0; i<values.length; i++){ t.add(values[i]); } int v=13; System.out.print("Path to" + v + ":"); t.printpath(v); if(t.isLeaf(v)){ System.out.println(""); }else{ System.out.println(""); } System.out.println("print tree"); t.print(); System.out.print(""); t.Max(); t.Min(); //t.Printleafs(); t.Count(); System.out.println("recuersive print"); t.recursivePrint(); System.out.println("recursive count"); int r = t.recursiveCount(); System.out.println("Total nodes "+r); System.out.println(""); System.out.println("Post Order Print"); t.PostOrderPrint(); System.out.println("Pre Order Print"); t.PreOrderPrint(); System.out.println("In Order Print"); t.inOrderPrint(); System.out.println("Print Leafs"); t.PrintLeafsR(); System.out.println(""); System.out.println("HEIGHT"); System.out.println(""+t.Height()); System.out.println(""); System.out.println("Draw Tree"); t.Draw(); System.out.println(""+ t.isComplete()); System.out.println(""+ t.Exist(4)); System.out.println("PRUEBA DE FALSO"); System.out.println(""); System.out.println(""+ t.Exist(50)); //t.invert(); //t.Prune(); System.out.println("COUNT ODDS"); System.out.println(t.CountOdds()); System.out.println("COMPLETE"); t.Complete(); System.out.println("SON'S ALONE'S"); t.PrintSonAlone(); System.out.println("REVERSE PRINT"); t.reversePrint(); System.out.println("PRINT MISSINGS"); //t.PrintMissings(); t.balance(); t.equilibriumFactor(); t.remove(10); } }
2,443
0.502251
0.490381
90
25.055555
16.286573
79
false
false
0
0
0
0
0
0
0.8
false
false
12
251a157b703204b117db1b617d6159d300d9993e
8,512,625,232,979
4c3a03a306d8745ca8084976b9ce011fdeedb68a
/src/main/java/me/dags/actionreplay/NodeUtils.java
e4ff3b421975d72efba6fd9cd600cb282fe17c7a
[]
no_license
dags-/ActionReplay
https://github.com/dags-/ActionReplay
33cdfac578a6909b6af32e4e51fa31f58959e578
bb0005740bc86ffd5e550740333a61b178c9a5b2
refs/heads/master
2020-12-06T05:49:01.497000
2017-02-06T11:34:46
2017-02-06T11:34:46
66,853,219
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package me.dags.actionreplay; import com.flowpowered.math.vector.Vector3i; import me.dags.actionreplay.replay.Meta; import me.dags.data.NodeAdapter; import me.dags.data.node.Node; import me.dags.data.node.NodeObject; import java.nio.file.Files; import java.nio.file.Path; import java.util.Optional; /** * @author dags <dags@dags.me> */ public class NodeUtils { private static final Meta.Adapter META_ADAPTER = new Meta.Adapter(); private static final Config.Adapter CONFIG_ADAPTER = new Config.Adapter(); public static Config loadConfig(Path path) { final Config config; Node node = NodeAdapter.hocon().from(path); if (node.isPresent()) { config = CONFIG_ADAPTER.fromNode(node); } else { config = new Config(); } saveConfig(config, path); return config; } public static void saveConfig(Config config, Path path) { Node node = CONFIG_ADAPTER.toNode(config); NodeAdapter.hocon().to(node, path); } public static Optional<Meta> loadMeta(String name) { Path path = ActionReplay.resolve("recordings").resolve(name).resolve(name + ".conf"); if (Files.exists(path)) { Node node = NodeAdapter.hocon().from(path); Meta meta = META_ADAPTER.fromNode(node); return Optional.of(meta); } return Optional.empty(); } public static void saveMeta(Meta meta) { Path path = ActionReplay.resolve("recordings").resolve(meta.name).resolve(meta.name + ".conf"); Node node = META_ADAPTER.toNode(meta); NodeAdapter.hocon().to(node, path); } public static NodeObject vectorToNode(Vector3i vector3i) { NodeObject vec = new NodeObject(); vec.put("x", vector3i.getX()); vec.put("y", vector3i.getY()); vec.put("z", vector3i.getZ()); return vec; } public static Vector3i vectorFromNode(Node node) { NodeObject vec = node.asNodeObject(); int x = vec.map("x", n -> n.asNumber().intValue(), 0); int y = vec.map("y", n -> n.asNumber().intValue(), 0); int z = vec.map("z", n -> n.asNumber().intValue(), 0); return new Vector3i(x, y, z); } }
UTF-8
Java
2,239
java
NodeUtils.java
Java
[ { "context": "e.Path;\nimport java.util.Optional;\n\n/**\n * @author dags <dags@dags.me>\n */\npublic class NodeUtils {\n\n ", "end": 321, "score": 0.9996263980865479, "start": 317, "tag": "USERNAME", "value": "dags" }, { "context": "\nimport java.util.Optional;\n\n/**\n * @author...
null
[]
package me.dags.actionreplay; import com.flowpowered.math.vector.Vector3i; import me.dags.actionreplay.replay.Meta; import me.dags.data.NodeAdapter; import me.dags.data.node.Node; import me.dags.data.node.NodeObject; import java.nio.file.Files; import java.nio.file.Path; import java.util.Optional; /** * @author dags <<EMAIL>> */ public class NodeUtils { private static final Meta.Adapter META_ADAPTER = new Meta.Adapter(); private static final Config.Adapter CONFIG_ADAPTER = new Config.Adapter(); public static Config loadConfig(Path path) { final Config config; Node node = NodeAdapter.hocon().from(path); if (node.isPresent()) { config = CONFIG_ADAPTER.fromNode(node); } else { config = new Config(); } saveConfig(config, path); return config; } public static void saveConfig(Config config, Path path) { Node node = CONFIG_ADAPTER.toNode(config); NodeAdapter.hocon().to(node, path); } public static Optional<Meta> loadMeta(String name) { Path path = ActionReplay.resolve("recordings").resolve(name).resolve(name + ".conf"); if (Files.exists(path)) { Node node = NodeAdapter.hocon().from(path); Meta meta = META_ADAPTER.fromNode(node); return Optional.of(meta); } return Optional.empty(); } public static void saveMeta(Meta meta) { Path path = ActionReplay.resolve("recordings").resolve(meta.name).resolve(meta.name + ".conf"); Node node = META_ADAPTER.toNode(meta); NodeAdapter.hocon().to(node, path); } public static NodeObject vectorToNode(Vector3i vector3i) { NodeObject vec = new NodeObject(); vec.put("x", vector3i.getX()); vec.put("y", vector3i.getY()); vec.put("z", vector3i.getZ()); return vec; } public static Vector3i vectorFromNode(Node node) { NodeObject vec = node.asNodeObject(); int x = vec.map("x", n -> n.asNumber().intValue(), 0); int y = vec.map("y", n -> n.asNumber().intValue(), 0); int z = vec.map("z", n -> n.asNumber().intValue(), 0); return new Vector3i(x, y, z); } }
2,234
0.620366
0.615453
69
31.449276
24.216139
103
false
false
0
0
0
0
0
0
0.753623
false
false
12
5f67e200a56a969c7ec2750245ea8657f3b0a191
33,595,234,242,906
26c3441cd1e1ee9608256fc0b567f1bc927f84d3
/APIMicroFocusDummy/src/main/java/com/everis/dao/ConnectionFactory.java
c397603a78c7adf5abf520468bbe129d9d746310
[]
no_license
Antony0905/Laboratorio-Estudos
https://github.com/Antony0905/Laboratorio-Estudos
d35bab77183e647ae494105a184f62b069e99767
286b55d39543e9c58c93a643b6bd282bae2cf55a
refs/heads/master
2020-05-31T18:30:51.401000
2019-06-05T17:06:26
2019-06-05T17:06:26
190,435,653
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.everis.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class ConnectionFactory { private String Driver = "org.postgresql.Driver"; public Connection getConnection(String url, String user, String password) throws ClassNotFoundException, SQLException { Class.forName(Driver); return DriverManager.getConnection(url, user, password); } }
UTF-8
Java
416
java
ConnectionFactory.java
Java
[]
null
[]
package com.everis.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class ConnectionFactory { private String Driver = "org.postgresql.Driver"; public Connection getConnection(String url, String user, String password) throws ClassNotFoundException, SQLException { Class.forName(Driver); return DriverManager.getConnection(url, user, password); } }
416
0.783654
0.783654
19
20.894737
22.773241
74
false
false
0
0
0
0
0
0
1.157895
false
false
12
2e2f4e94d8e056ae43b9027913a3d684c0cff01f
14,817,637,219,005
74a089fd11b89b6d531e741840cdfe0f0bdbbfea
/VehicleManagementService/src/main/java/at/htl/vehiclemanagementservice/model/Vehicle.java
ce575e6c5404e525f090d9bec28e2f84d7928fe1
[]
no_license
m-maresch/tracked-vehicle-network
https://github.com/m-maresch/tracked-vehicle-network
29239a332b9ca91780efad72be8e5bc00a4aafd2
4fecd144ecd331272f2b50f690bf712d04fedfb2
refs/heads/master
2021-09-23T12:19:03.147000
2021-09-17T14:51:05
2021-09-17T14:51:05
238,200,216
0
0
null
false
2023-09-05T22:00:25
2020-02-04T12:25:59
2022-06-15T01:17:13
2023-09-05T22:00:25
56
1
0
1
Java
false
false
package at.htl.vehiclemanagementservice.model; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.Setter; import org.apache.ignite.cache.query.annotations.QuerySqlField; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.io.Serializable; @Getter @Setter @AllArgsConstructor @Builder public class Vehicle implements Serializable { @QuerySqlField(index = true) @NotNull private Long id; @QuerySqlField(index = true) @NotBlank private String name; }
UTF-8
Java
570
java
Vehicle.java
Java
[]
null
[]
package at.htl.vehiclemanagementservice.model; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.Setter; import org.apache.ignite.cache.query.annotations.QuerySqlField; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.io.Serializable; @Getter @Setter @AllArgsConstructor @Builder public class Vehicle implements Serializable { @QuerySqlField(index = true) @NotNull private Long id; @QuerySqlField(index = true) @NotBlank private String name; }
570
0.789474
0.789474
26
20.923077
17.408936
63
false
false
0
0
0
0
0
0
0.423077
false
false
12
b92e1fe405837e208009d820706f78d91a991286
2,302,102,531,111
7d3a68e76563862bca3871bc1138e4f239ba92df
/src/main/java/utilities/driver/IEDriverManager.java
c60146609e6367c3c38867e131be84fcd6692ac8
[]
no_license
nhidinh/Gradle-TestNG-Selenium-02
https://github.com/nhidinh/Gradle-TestNG-Selenium-02
5e67dbc34fa4a2ef03e75892da53707196f8e5e8
0eb94f5e1473177c575fadffca27c102048951cd
refs/heads/master
2020-04-08T11:29:30.088000
2018-12-24T10:03:47
2018-12-24T10:03:47
159,308,044
0
0
null
false
2018-12-24T10:03:48
2018-11-27T09:16:41
2018-12-24T09:10:29
2018-12-24T10:03:48
86,902
0
0
0
Java
false
null
package utilities.driver; import io.github.bonigarcia.wdm.WebDriverManager; import org.openqa.selenium.WebDriver; import org.openqa.selenium.ie.InternetExplorerDriver; /** * User: Nhi Dinh * Date: 5/12/2018 */ public class IEDriverManager extends DriverManager { @Override public WebDriver createDriver(){ WebDriverManager.iedriver().setup(); return new InternetExplorerDriver(); } }
UTF-8
Java
418
java
IEDriverManager.java
Java
[ { "context": "package utilities.driver;\n\nimport io.github.bonigarcia.wdm.WebDriverManager;\nimport org.openqa.selenium.", "end": 54, "score": 0.9197102189064026, "start": 44, "tag": "USERNAME", "value": "bonigarcia" }, { "context": ".selenium.ie.InternetExplorerDriver;\n\n/**\n * U...
null
[]
package utilities.driver; import io.github.bonigarcia.wdm.WebDriverManager; import org.openqa.selenium.WebDriver; import org.openqa.selenium.ie.InternetExplorerDriver; /** * User: <NAME> * Date: 5/12/2018 */ public class IEDriverManager extends DriverManager { @Override public WebDriver createDriver(){ WebDriverManager.iedriver().setup(); return new InternetExplorerDriver(); } }
416
0.73445
0.717703
17
23.588236
19.626089
53
false
false
0
0
0
0
0
0
0.352941
false
false
12
20c0a4541c641d460cef9c2e07822110829eaf12
9,629,316,734,764
2089e80014f289e0d632e2cc8ded1b820dc82b61
/odata2-jpa-processor/jpa-core/src/test/java/org/apache/olingo/odata2/jpa/processor/core/mock/data/ODataEntryMockUtil.java
b0a2c316ce6b7b4643ee51d1c4ee71dc028ecfde
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
apache/olingo-odata2
https://github.com/apache/olingo-odata2
a0e489101a6173734934eb9dd1b592f0ca284f49
bed23e77f9735c0094b5784aa0d7e3ee972018be
refs/heads/master
2023-08-25T06:05:34.246000
2022-10-23T06:54:29
2022-11-30T17:01:41
18,830,102
45
96
Apache-2.0
false
2023-09-03T07:44:00
2014-04-16T07:00:07
2022-12-13T10:34:31
2023-09-03T07:43:58
6,956
38
75
9
Java
false
false
/******************************************************************************* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. ******************************************************************************/ package org.apache.olingo.odata2.jpa.processor.core.mock.data; import java.sql.Time; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimeZone; import java.util.UUID; import org.apache.olingo.odata2.api.ep.entry.EntryMetadata; import org.apache.olingo.odata2.api.ep.entry.ODataEntry; import org.apache.olingo.odata2.api.ep.feed.ODataFeed; import org.apache.olingo.odata2.jpa.processor.core.mock.data.JPATypeMock.JPARelatedTypeMock; import org.apache.olingo.odata2.jpa.processor.core.mock.data.JPATypeMock.JPATypeEmbeddableMock; import org.apache.olingo.odata2.jpa.processor.core.mock.data.JPATypeMock.JPATypeEmbeddableMock2; import org.easymock.EasyMock; public class ODataEntryMockUtil { public static final int VALUE_MINT = 20; public static Calendar VALUE_DATE_TIME = null; public static byte[] VALUE_BLOB = null; public static final String VALUE_CLOB = "ABC"; public static final String VALUE_C = "D"; public static final String VALUE_CARRAY = "EFG"; public static final String VALUE_CHAR = "I"; public static final String VALUE_CHARARRAY = "LMN"; public static final String VALUE_MSTRING = "Mock"; public static final String VALUE_XMLADAPTER = "DOES-NOT-MATTER"; public static final long VALUE_MLONG = 1234567890L; public static final double VALUE_MDOUBLE = 20.12; public static final byte VALUE_MBYTE = 0XA; public static final byte[] VALUE_MBYTEARRAY = new byte[] { 0XA, 0XB }; public static final float VALUE_MFLOAT = 2.00F; public static final UUID VALUE_UUID = UUID.fromString("38400000-8cf0-11bd-b23e-10b96e4ef00d"); public static final Short VALUE_SHORT = 2; public static final JPATypeMock.JPATypeMockEnum VALUE_ENUM = JPATypeMock.JPATypeMockEnum.VALUE; public static java.util.Date VALUE_DATE = null; public static java.sql.Date VALUE_DATE1 = null; public static Time VALUE_TIME = null; public static Timestamp VALUE_TIMESTAMP = null; public static ODataEntry mockODataEntry(final String entityName) { ODataEntry oDataEntry = EasyMock.createMock(ODataEntry.class); EasyMock.expect(oDataEntry.getProperties()).andReturn(mockODataEntryProperties(entityName)).anyTimes(); enhanceMockODataEntry(oDataEntry, false, new ArrayList<String>()); EasyMock.replay(oDataEntry); return oDataEntry; } public static ODataEntry mockODataEntryWithNullValue(final String entityName) { ODataEntry oDataEntry = EasyMock.createMock(ODataEntry.class); Map<String, Object> propertiesMap = mockODataEntryProperties(entityName); propertiesMap.put(JPATypeMock.PROPERTY_NAME_MINT, null); propertiesMap.put(JPATypeMock.PROPERTY_NAME_MCHAR, null); propertiesMap.put(JPATypeMock.PROPERTY_NAME_CLOB, null); propertiesMap.put(JPATypeMock.PROPERTY_NAME_ENUM, null); propertiesMap.put(JPATypeMock.PROPERTY_NAME_MBLOB, null); propertiesMap.put(JPATypeMock.PROPERTY_NAME_MCARRAY, null); propertiesMap.put(JPATypeMock.PROPERTY_NAME_MC, null); propertiesMap.put(JPATypeMock.PROPERTY_NAME_MCHARARRAY, null); propertiesMap.put(JPATypeMock.PROPERTY_NAME_MDATETIME, null); propertiesMap.put(JPATypeMock.PROPERTY_NAME_MSTRING, null); EasyMock.expect(oDataEntry.getProperties()).andReturn(propertiesMap).anyTimes(); enhanceMockODataEntry(oDataEntry, false, new ArrayList<String>()); EasyMock.replay(oDataEntry); return oDataEntry; } public static ODataEntry mockODataEntryWithComplexType(final String entityName) { ODataEntry oDataEntry = EasyMock.createMock(ODataEntry.class); EasyMock.expect(oDataEntry.getProperties()).andReturn(mockODataEntryPropertiesWithComplexType(entityName)) .anyTimes(); enhanceMockODataEntry(oDataEntry, false, new ArrayList<String>()); EasyMock.replay(oDataEntry); return oDataEntry; } @SuppressWarnings("unchecked") public static ODataEntry mockODataEntryWithComplexTypeWithNullValue(final String entityName) { ODataEntry oDataEntry = EasyMock.createMock(ODataEntry.class); Map<String, Object> propertiesMap = mockODataEntryPropertiesWithComplexType(entityName); propertiesMap.put(JPATypeMock.PROPERTY_NAME_MCARRAY, null); Map<String, Object> complexPropertiesMap = (Map<String, Object>) propertiesMap.get (JPATypeMock.PROPERTY_NAME_MCOMPLEXTYPE); complexPropertiesMap.put(JPATypeEmbeddableMock.PROPERTY_NAME_MSHORT, null); complexPropertiesMap.put(JPATypeEmbeddableMock.PROPERTY_NAME_MDATE, null); complexPropertiesMap.put(JPATypeEmbeddableMock.PROPERTY_NAME_MDATE1, null); complexPropertiesMap.put(JPATypeEmbeddableMock.PROPERTY_NAME_MTIME, null); complexPropertiesMap.put(JPATypeEmbeddableMock.PROPERTY_NAME_MTIMESTAMP, null); Map<String, Object> embeddableMap = (Map<String, Object>) complexPropertiesMap. get(JPATypeEmbeddableMock.PROPERTY_NAME_MEMBEDDABLE); embeddableMap.put(JPATypeEmbeddableMock2.PROPERTY_NAME_MUUID, null); embeddableMap.put(JPATypeEmbeddableMock2.PROPERTY_NAME_MFLOAT, null); EasyMock.expect(oDataEntry.getProperties()).andReturn(propertiesMap) .anyTimes(); enhanceMockODataEntry(oDataEntry, false, new ArrayList<String>()); EasyMock.replay(oDataEntry); return oDataEntry; } public static Map<String, Object> mockODataEntryProperties(final String entityName) { Map<String, Object> propertyMap = new HashMap<String, Object>(); if (entityName.equals(JPATypeMock.ENTITY_NAME)) { propertyMap.put(JPATypeMock.PROPERTY_NAME_MINT, VALUE_MINT); propertyMap.put(JPATypeMock.PROPERTY_NAME_ENUM, "VALUE"); VALUE_DATE_TIME = Calendar.getInstance(TimeZone.getDefault()); VALUE_DATE_TIME.set(2013, 1, 1, 1, 1, 1); propertyMap.put(JPATypeMock.PROPERTY_NAME_MDATETIME, VALUE_DATE_TIME); VALUE_BLOB = VALUE_MBYTEARRAY; propertyMap.put(JPATypeMock.PROPERTY_NAME_MBLOB, VALUE_BLOB); propertyMap.put(JPATypeMock.PROPERTY_NAME_CLOB, VALUE_CLOB); propertyMap.put(JPATypeMock.PROPERTY_NAME_MC, VALUE_C); propertyMap.put(JPATypeMock.PROPERTY_NAME_MCARRAY, VALUE_CARRAY); propertyMap.put(JPATypeMock.PROPERTY_NAME_MCHAR, VALUE_CHAR); propertyMap.put(JPATypeMock.PROPERTY_NAME_MCHARARRAY, VALUE_CHARARRAY); propertyMap.put(JPATypeMock.PROPERTY_NAME_MSTRING, VALUE_MSTRING); propertyMap.put(JPATypeMock.PROPERTY_NAME_XMLADAPTER, VALUE_XMLADAPTER); } else if (entityName.equals(JPARelatedTypeMock.ENTITY_NAME)) { propertyMap.put(JPARelatedTypeMock.PROPERTY_NAME_MLONG, VALUE_MLONG); propertyMap.put(JPARelatedTypeMock.PROPERTY_NAME_MDOUBLE, VALUE_MDOUBLE); propertyMap.put(JPARelatedTypeMock.PROPERTY_NAME_MBYTE, VALUE_MBYTE); propertyMap.put(JPARelatedTypeMock.PROPERTY_NAME_MBYTEARRAY, VALUE_MBYTEARRAY); } else if (entityName.equals(JPATypeEmbeddableMock.ENTITY_NAME)) { propertyMap.put(JPATypeEmbeddableMock.PROPERTY_NAME_MSHORT, VALUE_SHORT); VALUE_DATE = Calendar.getInstance(TimeZone.getDefault()).getTime(); VALUE_DATE1 = new java.sql.Date(Calendar.getInstance(TimeZone.getDefault()).getTimeInMillis()); VALUE_TIME = new java.sql.Time(Calendar.getInstance(TimeZone.getDefault()).getTimeInMillis()); VALUE_TIMESTAMP = new Timestamp(Calendar.getInstance(TimeZone.getDefault()).getTimeInMillis()); propertyMap.put(JPATypeEmbeddableMock.PROPERTY_NAME_MDATE, Calendar.getInstance(TimeZone.getDefault())); propertyMap.put(JPATypeEmbeddableMock.PROPERTY_NAME_MDATE1, Calendar.getInstance(TimeZone.getDefault())); propertyMap.put(JPATypeEmbeddableMock.PROPERTY_NAME_MTIME, Calendar.getInstance(TimeZone.getDefault())); propertyMap.put(JPATypeEmbeddableMock.PROPERTY_NAME_MTIMESTAMP, Calendar.getInstance(TimeZone.getDefault())); propertyMap.put(JPATypeEmbeddableMock.PROPERTY_NAME_MEMBEDDABLE, mockODataEntryProperties(JPATypeEmbeddableMock2.ENTITY_NAME)); } else if (entityName.equals(JPATypeEmbeddableMock2.ENTITY_NAME)) { propertyMap.put(JPATypeEmbeddableMock2.PROPERTY_NAME_MFLOAT, VALUE_MFLOAT); propertyMap.put(JPATypeEmbeddableMock2.PROPERTY_NAME_MUUID, VALUE_UUID); } return propertyMap; } public static Map<String, Object> mockODataEntryPropertiesWithComplexType(final String entityName) { Map<String, Object> propertyMap = mockODataEntryProperties(entityName); propertyMap .put(JPATypeMock.PROPERTY_NAME_MCOMPLEXTYPE, mockODataEntryProperties(JPATypeEmbeddableMock.ENTITY_NAME)); return propertyMap; } public static Map<String, Object> mockODataEntryPropertiesWithInline(final String entityName) { Map<String, Object> propertyMap = mockODataEntryProperties(entityName); List<ODataEntry> relatedEntries = new ArrayList<ODataEntry>(); relatedEntries.add(mockODataEntry(JPARelatedTypeMock.ENTITY_NAME)); ODataFeed feed = EasyMock.createMock(ODataFeed.class); EasyMock.expect(feed.getEntries()).andReturn(relatedEntries); EasyMock.replay(feed); propertyMap.put(JPATypeMock.NAVIGATION_PROPERTY_X, feed); return propertyMap; } public static ODataEntry mockODataEntryWithInline(final String entityName) { ODataEntry oDataEntry = EasyMock.createMock(ODataEntry.class); EasyMock.expect(oDataEntry.getProperties()).andReturn(mockODataEntryPropertiesWithInline(entityName)).anyTimes(); if (entityName.equals(JPATypeMock.ENTITY_NAME)) { List<String> links = new ArrayList<String>(); links.add(JPATypeMock.ENTITY_NAME + "(" + ODataEntryMockUtil.VALUE_MINT + ")/" + JPATypeMock.NAVIGATION_PROPERTY_X); enhanceMockODataEntry(oDataEntry, true, links); } else { enhanceMockODataEntry(oDataEntry, false, new ArrayList<String>()); } EasyMock.replay(oDataEntry); return oDataEntry; } private static void enhanceMockODataEntry(final ODataEntry oDataEntry, final boolean hasInline, final List<String> associationURIs) { EasyMock.expect(oDataEntry.containsInlineEntry()).andReturn(hasInline).anyTimes(); EntryMetadata entryMetadata = EasyMock.createMock(EntryMetadata.class); if (hasInline) { EasyMock.expect(entryMetadata.getAssociationUris(JPATypeMock.NAVIGATION_PROPERTY_X)).andReturn(associationURIs) .anyTimes(); EasyMock.expect(entryMetadata.getAssociationUris(JPATypeMock.NAVIGATION_PROPERTY_XS)).andReturn( new ArrayList<String>()) .anyTimes(); } else { EasyMock.expect(entryMetadata.getAssociationUris(EasyMock.isA(String.class))).andReturn(associationURIs) .anyTimes(); } EasyMock.replay(entryMetadata); EasyMock.expect(oDataEntry.getMetadata()).andReturn(entryMetadata).anyTimes(); } }
UTF-8
Java
11,697
java
ODataEntryMockUtil.java
Java
[]
null
[]
/******************************************************************************* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. ******************************************************************************/ package org.apache.olingo.odata2.jpa.processor.core.mock.data; import java.sql.Time; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimeZone; import java.util.UUID; import org.apache.olingo.odata2.api.ep.entry.EntryMetadata; import org.apache.olingo.odata2.api.ep.entry.ODataEntry; import org.apache.olingo.odata2.api.ep.feed.ODataFeed; import org.apache.olingo.odata2.jpa.processor.core.mock.data.JPATypeMock.JPARelatedTypeMock; import org.apache.olingo.odata2.jpa.processor.core.mock.data.JPATypeMock.JPATypeEmbeddableMock; import org.apache.olingo.odata2.jpa.processor.core.mock.data.JPATypeMock.JPATypeEmbeddableMock2; import org.easymock.EasyMock; public class ODataEntryMockUtil { public static final int VALUE_MINT = 20; public static Calendar VALUE_DATE_TIME = null; public static byte[] VALUE_BLOB = null; public static final String VALUE_CLOB = "ABC"; public static final String VALUE_C = "D"; public static final String VALUE_CARRAY = "EFG"; public static final String VALUE_CHAR = "I"; public static final String VALUE_CHARARRAY = "LMN"; public static final String VALUE_MSTRING = "Mock"; public static final String VALUE_XMLADAPTER = "DOES-NOT-MATTER"; public static final long VALUE_MLONG = 1234567890L; public static final double VALUE_MDOUBLE = 20.12; public static final byte VALUE_MBYTE = 0XA; public static final byte[] VALUE_MBYTEARRAY = new byte[] { 0XA, 0XB }; public static final float VALUE_MFLOAT = 2.00F; public static final UUID VALUE_UUID = UUID.fromString("38400000-8cf0-11bd-b23e-10b96e4ef00d"); public static final Short VALUE_SHORT = 2; public static final JPATypeMock.JPATypeMockEnum VALUE_ENUM = JPATypeMock.JPATypeMockEnum.VALUE; public static java.util.Date VALUE_DATE = null; public static java.sql.Date VALUE_DATE1 = null; public static Time VALUE_TIME = null; public static Timestamp VALUE_TIMESTAMP = null; public static ODataEntry mockODataEntry(final String entityName) { ODataEntry oDataEntry = EasyMock.createMock(ODataEntry.class); EasyMock.expect(oDataEntry.getProperties()).andReturn(mockODataEntryProperties(entityName)).anyTimes(); enhanceMockODataEntry(oDataEntry, false, new ArrayList<String>()); EasyMock.replay(oDataEntry); return oDataEntry; } public static ODataEntry mockODataEntryWithNullValue(final String entityName) { ODataEntry oDataEntry = EasyMock.createMock(ODataEntry.class); Map<String, Object> propertiesMap = mockODataEntryProperties(entityName); propertiesMap.put(JPATypeMock.PROPERTY_NAME_MINT, null); propertiesMap.put(JPATypeMock.PROPERTY_NAME_MCHAR, null); propertiesMap.put(JPATypeMock.PROPERTY_NAME_CLOB, null); propertiesMap.put(JPATypeMock.PROPERTY_NAME_ENUM, null); propertiesMap.put(JPATypeMock.PROPERTY_NAME_MBLOB, null); propertiesMap.put(JPATypeMock.PROPERTY_NAME_MCARRAY, null); propertiesMap.put(JPATypeMock.PROPERTY_NAME_MC, null); propertiesMap.put(JPATypeMock.PROPERTY_NAME_MCHARARRAY, null); propertiesMap.put(JPATypeMock.PROPERTY_NAME_MDATETIME, null); propertiesMap.put(JPATypeMock.PROPERTY_NAME_MSTRING, null); EasyMock.expect(oDataEntry.getProperties()).andReturn(propertiesMap).anyTimes(); enhanceMockODataEntry(oDataEntry, false, new ArrayList<String>()); EasyMock.replay(oDataEntry); return oDataEntry; } public static ODataEntry mockODataEntryWithComplexType(final String entityName) { ODataEntry oDataEntry = EasyMock.createMock(ODataEntry.class); EasyMock.expect(oDataEntry.getProperties()).andReturn(mockODataEntryPropertiesWithComplexType(entityName)) .anyTimes(); enhanceMockODataEntry(oDataEntry, false, new ArrayList<String>()); EasyMock.replay(oDataEntry); return oDataEntry; } @SuppressWarnings("unchecked") public static ODataEntry mockODataEntryWithComplexTypeWithNullValue(final String entityName) { ODataEntry oDataEntry = EasyMock.createMock(ODataEntry.class); Map<String, Object> propertiesMap = mockODataEntryPropertiesWithComplexType(entityName); propertiesMap.put(JPATypeMock.PROPERTY_NAME_MCARRAY, null); Map<String, Object> complexPropertiesMap = (Map<String, Object>) propertiesMap.get (JPATypeMock.PROPERTY_NAME_MCOMPLEXTYPE); complexPropertiesMap.put(JPATypeEmbeddableMock.PROPERTY_NAME_MSHORT, null); complexPropertiesMap.put(JPATypeEmbeddableMock.PROPERTY_NAME_MDATE, null); complexPropertiesMap.put(JPATypeEmbeddableMock.PROPERTY_NAME_MDATE1, null); complexPropertiesMap.put(JPATypeEmbeddableMock.PROPERTY_NAME_MTIME, null); complexPropertiesMap.put(JPATypeEmbeddableMock.PROPERTY_NAME_MTIMESTAMP, null); Map<String, Object> embeddableMap = (Map<String, Object>) complexPropertiesMap. get(JPATypeEmbeddableMock.PROPERTY_NAME_MEMBEDDABLE); embeddableMap.put(JPATypeEmbeddableMock2.PROPERTY_NAME_MUUID, null); embeddableMap.put(JPATypeEmbeddableMock2.PROPERTY_NAME_MFLOAT, null); EasyMock.expect(oDataEntry.getProperties()).andReturn(propertiesMap) .anyTimes(); enhanceMockODataEntry(oDataEntry, false, new ArrayList<String>()); EasyMock.replay(oDataEntry); return oDataEntry; } public static Map<String, Object> mockODataEntryProperties(final String entityName) { Map<String, Object> propertyMap = new HashMap<String, Object>(); if (entityName.equals(JPATypeMock.ENTITY_NAME)) { propertyMap.put(JPATypeMock.PROPERTY_NAME_MINT, VALUE_MINT); propertyMap.put(JPATypeMock.PROPERTY_NAME_ENUM, "VALUE"); VALUE_DATE_TIME = Calendar.getInstance(TimeZone.getDefault()); VALUE_DATE_TIME.set(2013, 1, 1, 1, 1, 1); propertyMap.put(JPATypeMock.PROPERTY_NAME_MDATETIME, VALUE_DATE_TIME); VALUE_BLOB = VALUE_MBYTEARRAY; propertyMap.put(JPATypeMock.PROPERTY_NAME_MBLOB, VALUE_BLOB); propertyMap.put(JPATypeMock.PROPERTY_NAME_CLOB, VALUE_CLOB); propertyMap.put(JPATypeMock.PROPERTY_NAME_MC, VALUE_C); propertyMap.put(JPATypeMock.PROPERTY_NAME_MCARRAY, VALUE_CARRAY); propertyMap.put(JPATypeMock.PROPERTY_NAME_MCHAR, VALUE_CHAR); propertyMap.put(JPATypeMock.PROPERTY_NAME_MCHARARRAY, VALUE_CHARARRAY); propertyMap.put(JPATypeMock.PROPERTY_NAME_MSTRING, VALUE_MSTRING); propertyMap.put(JPATypeMock.PROPERTY_NAME_XMLADAPTER, VALUE_XMLADAPTER); } else if (entityName.equals(JPARelatedTypeMock.ENTITY_NAME)) { propertyMap.put(JPARelatedTypeMock.PROPERTY_NAME_MLONG, VALUE_MLONG); propertyMap.put(JPARelatedTypeMock.PROPERTY_NAME_MDOUBLE, VALUE_MDOUBLE); propertyMap.put(JPARelatedTypeMock.PROPERTY_NAME_MBYTE, VALUE_MBYTE); propertyMap.put(JPARelatedTypeMock.PROPERTY_NAME_MBYTEARRAY, VALUE_MBYTEARRAY); } else if (entityName.equals(JPATypeEmbeddableMock.ENTITY_NAME)) { propertyMap.put(JPATypeEmbeddableMock.PROPERTY_NAME_MSHORT, VALUE_SHORT); VALUE_DATE = Calendar.getInstance(TimeZone.getDefault()).getTime(); VALUE_DATE1 = new java.sql.Date(Calendar.getInstance(TimeZone.getDefault()).getTimeInMillis()); VALUE_TIME = new java.sql.Time(Calendar.getInstance(TimeZone.getDefault()).getTimeInMillis()); VALUE_TIMESTAMP = new Timestamp(Calendar.getInstance(TimeZone.getDefault()).getTimeInMillis()); propertyMap.put(JPATypeEmbeddableMock.PROPERTY_NAME_MDATE, Calendar.getInstance(TimeZone.getDefault())); propertyMap.put(JPATypeEmbeddableMock.PROPERTY_NAME_MDATE1, Calendar.getInstance(TimeZone.getDefault())); propertyMap.put(JPATypeEmbeddableMock.PROPERTY_NAME_MTIME, Calendar.getInstance(TimeZone.getDefault())); propertyMap.put(JPATypeEmbeddableMock.PROPERTY_NAME_MTIMESTAMP, Calendar.getInstance(TimeZone.getDefault())); propertyMap.put(JPATypeEmbeddableMock.PROPERTY_NAME_MEMBEDDABLE, mockODataEntryProperties(JPATypeEmbeddableMock2.ENTITY_NAME)); } else if (entityName.equals(JPATypeEmbeddableMock2.ENTITY_NAME)) { propertyMap.put(JPATypeEmbeddableMock2.PROPERTY_NAME_MFLOAT, VALUE_MFLOAT); propertyMap.put(JPATypeEmbeddableMock2.PROPERTY_NAME_MUUID, VALUE_UUID); } return propertyMap; } public static Map<String, Object> mockODataEntryPropertiesWithComplexType(final String entityName) { Map<String, Object> propertyMap = mockODataEntryProperties(entityName); propertyMap .put(JPATypeMock.PROPERTY_NAME_MCOMPLEXTYPE, mockODataEntryProperties(JPATypeEmbeddableMock.ENTITY_NAME)); return propertyMap; } public static Map<String, Object> mockODataEntryPropertiesWithInline(final String entityName) { Map<String, Object> propertyMap = mockODataEntryProperties(entityName); List<ODataEntry> relatedEntries = new ArrayList<ODataEntry>(); relatedEntries.add(mockODataEntry(JPARelatedTypeMock.ENTITY_NAME)); ODataFeed feed = EasyMock.createMock(ODataFeed.class); EasyMock.expect(feed.getEntries()).andReturn(relatedEntries); EasyMock.replay(feed); propertyMap.put(JPATypeMock.NAVIGATION_PROPERTY_X, feed); return propertyMap; } public static ODataEntry mockODataEntryWithInline(final String entityName) { ODataEntry oDataEntry = EasyMock.createMock(ODataEntry.class); EasyMock.expect(oDataEntry.getProperties()).andReturn(mockODataEntryPropertiesWithInline(entityName)).anyTimes(); if (entityName.equals(JPATypeMock.ENTITY_NAME)) { List<String> links = new ArrayList<String>(); links.add(JPATypeMock.ENTITY_NAME + "(" + ODataEntryMockUtil.VALUE_MINT + ")/" + JPATypeMock.NAVIGATION_PROPERTY_X); enhanceMockODataEntry(oDataEntry, true, links); } else { enhanceMockODataEntry(oDataEntry, false, new ArrayList<String>()); } EasyMock.replay(oDataEntry); return oDataEntry; } private static void enhanceMockODataEntry(final ODataEntry oDataEntry, final boolean hasInline, final List<String> associationURIs) { EasyMock.expect(oDataEntry.containsInlineEntry()).andReturn(hasInline).anyTimes(); EntryMetadata entryMetadata = EasyMock.createMock(EntryMetadata.class); if (hasInline) { EasyMock.expect(entryMetadata.getAssociationUris(JPATypeMock.NAVIGATION_PROPERTY_X)).andReturn(associationURIs) .anyTimes(); EasyMock.expect(entryMetadata.getAssociationUris(JPATypeMock.NAVIGATION_PROPERTY_XS)).andReturn( new ArrayList<String>()) .anyTimes(); } else { EasyMock.expect(entryMetadata.getAssociationUris(EasyMock.isA(String.class))).andReturn(associationURIs) .anyTimes(); } EasyMock.replay(entryMetadata); EasyMock.expect(oDataEntry.getMetadata()).andReturn(entryMetadata).anyTimes(); } }
11,697
0.755407
0.748995
226
50.756638
32.504841
119
false
false
0
0
0
0
0
0
0.973451
false
false
12
a56c906d72f874d9eb6156c4f04b6c6ae38e4e4e
32,091,995,638,635
edea97a4fb3473539a99cebd85488c03abac5913
/era-backend/era-business/src/main/java/org/dragberry/era/business/CountryService.java
0a54325911cd4be75c0b72cbd1d497ae4d251431
[]
no_license
MaksimDragun/era
https://github.com/MaksimDragun/era
0900b2b7d6c8ea5438adda74b22389b7604df75f
46fb79a7a992df00b808021aebd3dcfd2e0eec3e
refs/heads/master
2021-01-20T01:44:19.457000
2018-02-17T13:00:55
2018-02-17T13:00:55
101,298,773
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.dragberry.era.business; import java.util.Set; public interface CountryService { Set<String> getCountryCodes(); }
UTF-8
Java
129
java
CountryService.java
Java
[]
null
[]
package org.dragberry.era.business; import java.util.Set; public interface CountryService { Set<String> getCountryCodes(); }
129
0.775194
0.775194
8
15.125
15.357714
35
false
false
0
0
0
0
0
0
0.5
false
false
12
b4f11a475a40006569e3338659974e59c4c62396
16,020,228,069,121
29020dd2c48b335e7ca3107bb60726bd20677309
/ZwitscherAppApi/src/edu/hm/cc/zwitscher/api/object/ApiConstants.java
a7ab8c6b4d120037478a791ed5a8dd4439ddb7d3
[]
no_license
st3ffwo3/zwitscher_app
https://github.com/st3ffwo3/zwitscher_app
2040f4a654b7848ace85d709d51a85e43138a623
bb5d549d85e8f0e79abe4c3f1a8f8e07efa2b61c
refs/heads/master
2021-01-01T16:19:25.949000
2012-11-23T19:10:25
2012-11-23T19:10:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package edu.hm.cc.zwitscher.api.object; /** * Klasse enthaelt alle Konstanten der ZwitscherApp API die auch fuer Clients notwendig bzw. sinnvoll sind. * * @author Franz Mathauser, Moritz Munte, Stefan Wörner */ public final class ApiConstants { /** * Privater Konstructor. */ private ApiConstants() { } /** * Konstante mit der Versionsnummer der Server-Anteile. */ public static final String VERSION = "1.000.0"; /** * Datumsformatierungs-String. */ public static final String ZWITSCHER_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; /** * Datumsformatierungs-String (Twitter Response). */ public static final String TWITTER_RESPONSE_DATE_FORMAT = "EEE, dd MMMM yyyy kk:mm:ss +SSSS"; /** * Datumsformatierungs-String (Twitter Request Until-Date). */ public static final String TWITTER_REQUEST_UNTIL_DATE_FORMAT = "yyyy-MM-dd"; }
UTF-8
Java
877
java
ApiConstants.java
Java
[ { "context": "ients notwendig bzw. sinnvoll sind.\n * \n * @author Franz Mathauser, Moritz Munte, Stefan Wörner\n */\npublic final cla", "end": 195, "score": 0.9998675584793091, "start": 180, "tag": "NAME", "value": "Franz Mathauser" }, { "context": "zw. sinnvoll sind.\n * \n * @auth...
null
[]
/** * */ package edu.hm.cc.zwitscher.api.object; /** * Klasse enthaelt alle Konstanten der ZwitscherApp API die auch fuer Clients notwendig bzw. sinnvoll sind. * * @author <NAME>, <NAME>, <NAME> */ public final class ApiConstants { /** * Privater Konstructor. */ private ApiConstants() { } /** * Konstante mit der Versionsnummer der Server-Anteile. */ public static final String VERSION = "1.000.0"; /** * Datumsformatierungs-String. */ public static final String ZWITSCHER_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; /** * Datumsformatierungs-String (Twitter Response). */ public static final String TWITTER_RESPONSE_DATE_FORMAT = "EEE, dd MMMM yyyy kk:mm:ss +SSSS"; /** * Datumsformatierungs-String (Twitter Request Until-Date). */ public static final String TWITTER_REQUEST_UNTIL_DATE_FORMAT = "yyyy-MM-dd"; }
854
0.695205
0.689498
42
19.857143
28.666864
107
false
false
0
0
0
0
0
0
0.714286
false
false
12
df6b38f81bc48c1c07a5a972eb22574fe90b0e9f
309,237,710,826
a591b34f573cff0e60a691ca1d8bd7eb44ea5caf
/src/com/ytripper/thread/YoutubeDownloadThreadPool.java
bf77daf8c5cb01a6d0be481581b2413d351ed0c2
[]
no_license
vijayvani/Youtube-Ripper
https://github.com/vijayvani/Youtube-Ripper
025ae73066d342286a49f8d2cb7f7a67bc94b8d4
4d00b850f34a1d577d9df85825969c8ab421a9c9
refs/heads/master
2020-05-16T08:48:58.296000
2014-04-22T04:00:44
2014-04-22T04:00:44
null
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.ytripper.thread; import com.ytripper.video.YoutubeVideoObject; import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; /** * * @author mmain */ public class YoutubeDownloadThreadPool { protected Integer nWorkers = 3; ArrayList<YoutubeDownloadThread> workers = new ArrayList<YoutubeDownloadThread>(); Queue<YoutubeDownloadJob> jobs = new LinkedList<YoutubeDownloadJob>(); Queue<YoutubeDownloadJob> completed = new LinkedList<YoutubeDownloadJob>(); public YoutubeDownloadThreadPool() { for (int i=0; i < nWorkers; i++) { YoutubeDownloadThread worker = new YoutubeDownloadThread(this); worker.start(); workers.add(worker); } } public YoutubeDownloadThreadPool(int nWorkers) { this.nWorkers = nWorkers; for (int i=0; i < nWorkers; i++) { YoutubeDownloadThread worker = new YoutubeDownloadThread(this); worker.start(); workers.add(worker); } } public void killWorkers() { for (YoutubeDownloadThread worker: workers) { worker.kill(); } } public synchronized String addJob(YoutubeDownloadJob job) { jobs.add(job); return job.getUuid(); } public synchronized String addJob(YoutubeVideoObject youtubeVideo, Integer quality, String codec, String downloadDirectory) { YoutubeDownloadJob job = new YoutubeDownloadJob(youtubeVideo, quality, codec, downloadDirectory); jobs.add(job); return job.getUuid(); } public synchronized YoutubeDownloadJob getJob() { return jobs.poll(); } public synchronized void addCompleted(YoutubeDownloadJob job) { completed.add(job); } public synchronized YoutubeDownloadJob getCompleted() { return completed.poll(); } }
UTF-8
Java
2,012
java
YoutubeDownloadThreadPool.java
Java
[ { "context": "edList;\nimport java.util.Queue;\n\n/**\n *\n * @author mmain\n */\npublic class YoutubeDownloadThreadPool {\n ", "end": 281, "score": 0.9995360970497131, "start": 276, "tag": "USERNAME", "value": "mmain" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.ytripper.thread; import com.ytripper.video.YoutubeVideoObject; import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; /** * * @author mmain */ public class YoutubeDownloadThreadPool { protected Integer nWorkers = 3; ArrayList<YoutubeDownloadThread> workers = new ArrayList<YoutubeDownloadThread>(); Queue<YoutubeDownloadJob> jobs = new LinkedList<YoutubeDownloadJob>(); Queue<YoutubeDownloadJob> completed = new LinkedList<YoutubeDownloadJob>(); public YoutubeDownloadThreadPool() { for (int i=0; i < nWorkers; i++) { YoutubeDownloadThread worker = new YoutubeDownloadThread(this); worker.start(); workers.add(worker); } } public YoutubeDownloadThreadPool(int nWorkers) { this.nWorkers = nWorkers; for (int i=0; i < nWorkers; i++) { YoutubeDownloadThread worker = new YoutubeDownloadThread(this); worker.start(); workers.add(worker); } } public void killWorkers() { for (YoutubeDownloadThread worker: workers) { worker.kill(); } } public synchronized String addJob(YoutubeDownloadJob job) { jobs.add(job); return job.getUuid(); } public synchronized String addJob(YoutubeVideoObject youtubeVideo, Integer quality, String codec, String downloadDirectory) { YoutubeDownloadJob job = new YoutubeDownloadJob(youtubeVideo, quality, codec, downloadDirectory); jobs.add(job); return job.getUuid(); } public synchronized YoutubeDownloadJob getJob() { return jobs.poll(); } public synchronized void addCompleted(YoutubeDownloadJob job) { completed.add(job); } public synchronized YoutubeDownloadJob getCompleted() { return completed.poll(); } }
2,012
0.651093
0.649602
68
28.588236
27.662479
129
false
false
0
0
0
0
0
0
0.544118
false
false
12
25de28e948bb2a23ced710b2338581d789654b85
704,374,638,007
cd6de4640277f701780ee4267d3244b00001aa6c
/app/src/main/java/chinaykc/mobistudi/SeriesContent/SeriesContentAdapter.java
9a171cd562fcef083d3df3d34ecdfe42de27f1c0
[]
no_license
bingweibi/MobistudiForOnLineLearning
https://github.com/bingweibi/MobistudiForOnLineLearning
ff374fd3c58a285cb7e96831d3ece93e6c7d4921
5e34acc316b092689f99595282d978e82137b229
refs/heads/master
2020-03-13T03:19:46.177000
2018-05-02T02:16:37
2018-05-02T02:16:37
130,941,986
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package chinaykc.mobistudi.SeriesContent; import android.content.Context; import android.content.Intent; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; import chinaykc.mobistudi.R; import xyz.kfdykme.mobistudi.activity.CourseDetailActivity; /** * Created by china on 2017/9/26. * @author ykc */ public class SeriesContentAdapter extends RecyclerView.Adapter<SeriesContentAdapter.ViewHolder> { private Context mContext; private List<SeriesContent> mSeriesContentList; static class ViewHolder extends RecyclerView.ViewHolder { CardView cardView; TextView seriesContentTitle; public ViewHolder(View view) { super(view); cardView = (CardView) view.findViewById(R.id.series_content_card_view); seriesContentTitle = (TextView) view.findViewById(R.id.series_content_title); } } public SeriesContentAdapter(List<SeriesContent> seriesContentList) { mSeriesContentList = seriesContentList; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (mContext == null) { mContext = parent.getContext(); } View view = LayoutInflater.from(mContext).inflate(R.layout.series_content_item, parent, false); final ViewHolder holder=new ViewHolder(view); holder.cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int position=holder.getAdapterPosition(); SeriesContent seriesContent=mSeriesContentList.get(position); Intent intent=new Intent(mContext, CourseDetailActivity.class); intent.putExtra("title",seriesContent.getTitle()); mContext.startActivity(intent); } }); return holder; } @Override public void onBindViewHolder(ViewHolder holder, int position) { SeriesContent seriesContent = mSeriesContentList.get(position); holder.seriesContentTitle.setText(seriesContent.getTitle()); } @Override public int getItemCount() { return mSeriesContentList.size(); } }
UTF-8
Java
2,369
java
SeriesContentAdapter.java
Java
[ { "context": ".activity.CourseDetailActivity;\n\n/**\n * Created by china on 2017/9/26.\n * @author ykc\n */\n\npublic class Se", "end": 459, "score": 0.9994416236877441, "start": 454, "tag": "USERNAME", "value": "china" }, { "context": "\n\n/**\n * Created by china on 2017/9/26.\n *...
null
[]
package chinaykc.mobistudi.SeriesContent; import android.content.Context; import android.content.Intent; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; import chinaykc.mobistudi.R; import xyz.kfdykme.mobistudi.activity.CourseDetailActivity; /** * Created by china on 2017/9/26. * @author ykc */ public class SeriesContentAdapter extends RecyclerView.Adapter<SeriesContentAdapter.ViewHolder> { private Context mContext; private List<SeriesContent> mSeriesContentList; static class ViewHolder extends RecyclerView.ViewHolder { CardView cardView; TextView seriesContentTitle; public ViewHolder(View view) { super(view); cardView = (CardView) view.findViewById(R.id.series_content_card_view); seriesContentTitle = (TextView) view.findViewById(R.id.series_content_title); } } public SeriesContentAdapter(List<SeriesContent> seriesContentList) { mSeriesContentList = seriesContentList; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (mContext == null) { mContext = parent.getContext(); } View view = LayoutInflater.from(mContext).inflate(R.layout.series_content_item, parent, false); final ViewHolder holder=new ViewHolder(view); holder.cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int position=holder.getAdapterPosition(); SeriesContent seriesContent=mSeriesContentList.get(position); Intent intent=new Intent(mContext, CourseDetailActivity.class); intent.putExtra("title",seriesContent.getTitle()); mContext.startActivity(intent); } }); return holder; } @Override public void onBindViewHolder(ViewHolder holder, int position) { SeriesContent seriesContent = mSeriesContentList.get(position); holder.seriesContentTitle.setText(seriesContent.getTitle()); } @Override public int getItemCount() { return mSeriesContentList.size(); } }
2,369
0.692275
0.688476
73
31.452055
27.931934
103
false
false
0
0
0
0
0
0
0.534247
false
false
12
510d8705499fb850a51406936ddbd9a058be89d9
16,449,724,802,218
252850c8b6942c022682622defccca57df04416c
/src/com/example/web/Add.java
3c9c60bf984799e6d189ee50ec311f37df603cf4
[]
no_license
rosielickorish/phoneBookV1
https://github.com/rosielickorish/phoneBookV1
8e1106976a8a921c2f0eb7733c35495003747d3e
d2c239a658be56bc23b753b555032162a81885f0
refs/heads/master
2021-01-10T04:26:25.650000
2015-09-29T21:24:11
2015-09-29T21:24:11
43,393,643
0
0
null
false
2015-09-29T21:19:37
2015-09-29T20:48:19
2015-09-29T20:48:19
2015-09-29T21:19:37
0
0
0
0
null
null
null
package com.example.web; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.example.model.Phonebook; import com.example.model.AddressBookPersist; import com.example.model.Contact; public class Add extends PhoneBook{ public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { name= request.getParameter("First Name"); secondname = request.getParameter("Second Name"); phonenumber = request.getParameter("Phone Number"); Contact c = new Contact(name, secondname, phonenumber); ab.addContact(c); addressBookPersist.addAddressBook(ab); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("Phone Book<br>"); out.println("<br>Got contact name " + c + "<br>"); } }
UTF-8
Java
1,026
java
Add.java
Java
[]
null
[]
package com.example.web; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.example.model.Phonebook; import com.example.model.AddressBookPersist; import com.example.model.Contact; public class Add extends PhoneBook{ public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { name= request.getParameter("First Name"); secondname = request.getParameter("Second Name"); phonenumber = request.getParameter("Phone Number"); Contact c = new Contact(name, secondname, phonenumber); ab.addContact(c); addressBookPersist.addAddressBook(ab); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("Phone Book<br>"); out.println("<br>Got contact name " + c + "<br>"); } }
1,026
0.735867
0.735867
43
22.860466
24.406044
116
false
false
0
0
0
0
0
0
2.046512
false
false
12
d6eed6caef697f8aa33de932c5b58ea2d1c780ea
23,046,794,551,934
aee5b5bcc4a7bc075bf3ff9698b2cf00fca9ac63
/src/test/java/br/com/infoq/config/FakeDBTest.java
5dec0ff89a4eba40361a4be7168721d043f778c1
[]
no_license
tiagods/infoq
https://github.com/tiagods/infoq
c3823599ff85400bf578fb03012c570286b5d3fd
6b4b6f0684b995a0491de056f7f272555cfe4521
refs/heads/master
2022-02-02T15:26:38.111000
2021-08-18T20:53:39
2021-08-18T20:53:39
251,351,750
0
0
null
false
2022-01-21T23:40:41
2020-03-30T15:44:21
2021-08-18T20:53:52
2022-01-21T23:40:38
2,019
0
0
1
Java
false
false
package br.com.infoq.config; //@RunWith(SpringRunner.class) //@SpringBootTest(classes = {StartApp.class, H2ConfigTest.class}) public class FakeDBTest { }
UTF-8
Java
156
java
FakeDBTest.java
Java
[]
null
[]
package br.com.infoq.config; //@RunWith(SpringRunner.class) //@SpringBootTest(classes = {StartApp.class, H2ConfigTest.class}) public class FakeDBTest { }
156
0.762821
0.75641
7
21.285715
21.920078
65
false
false
0
0
0
0
0
0
0.285714
false
false
12
7fdd818f642b19f32719e3974dae4eeeb9d6a1d5
22,771,916,653,027
87bd3bc9bf00f874259524ce131d59622806efe2
/web4j/web4j.base/src/main/java/com/web4j/base/common/shiro/WebPermissionAnnotationMethodInterceptor.java
118aa8219be41022b5f8642f833b85071347ec80
[]
no_license
675711828/web4j
https://github.com/675711828/web4j
9c58667ccda248c45f323ff9392c8cd20424fcc9
8057121504afdf6f2f92167c027d8b75e5025c29
refs/heads/master
2018-04-29T01:55:18.279000
2018-04-27T05:47:06
2018-04-27T05:47:06
92,153,488
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.web4j.base.common.shiro; import org.apache.shiro.aop.AnnotationResolver; import org.apache.shiro.aop.MethodInvocation; import org.apache.shiro.authz.AuthorizationException; import org.apache.shiro.authz.aop.AuthorizingAnnotationHandler; import org.apache.shiro.authz.aop.AuthorizingAnnotationMethodInterceptor; import org.apache.shiro.authz.aop.PermissionAnnotationHandler; public class WebPermissionAnnotationMethodInterceptor extends AuthorizingAnnotationMethodInterceptor{ public WebPermissionAnnotationMethodInterceptor() { super(new PermissionAnnotationHandler()); } public WebPermissionAnnotationMethodInterceptor(AnnotationResolver resolver) { super(new WebPermissionAnnotationHandler(), resolver); } @Override public void assertAuthorized(MethodInvocation mi) throws AuthorizationException { try { AuthorizingAnnotationHandler handler = (AuthorizingAnnotationHandler) getHandler(); if(handler instanceof WebPermissionAnnotationHandler) { ((WebPermissionAnnotationHandler) handler).assertAuthorized(mi); } else { handler.assertAuthorized(getAnnotation(mi)); } } catch(AuthorizationException ae) { // Annotation handler doesn't know why it was called, so add the information here if possible. // Don't wrap the exception here since we don't want to mask the specific exception, such as // UnauthenticatedException etc. if (ae.getCause() == null) ae.initCause(new AuthorizationException("Not authorized to invoke method: " + mi.getMethod())); throw ae; } } }
UTF-8
Java
1,720
java
WebPermissionAnnotationMethodInterceptor.java
Java
[]
null
[]
package com.web4j.base.common.shiro; import org.apache.shiro.aop.AnnotationResolver; import org.apache.shiro.aop.MethodInvocation; import org.apache.shiro.authz.AuthorizationException; import org.apache.shiro.authz.aop.AuthorizingAnnotationHandler; import org.apache.shiro.authz.aop.AuthorizingAnnotationMethodInterceptor; import org.apache.shiro.authz.aop.PermissionAnnotationHandler; public class WebPermissionAnnotationMethodInterceptor extends AuthorizingAnnotationMethodInterceptor{ public WebPermissionAnnotationMethodInterceptor() { super(new PermissionAnnotationHandler()); } public WebPermissionAnnotationMethodInterceptor(AnnotationResolver resolver) { super(new WebPermissionAnnotationHandler(), resolver); } @Override public void assertAuthorized(MethodInvocation mi) throws AuthorizationException { try { AuthorizingAnnotationHandler handler = (AuthorizingAnnotationHandler) getHandler(); if(handler instanceof WebPermissionAnnotationHandler) { ((WebPermissionAnnotationHandler) handler).assertAuthorized(mi); } else { handler.assertAuthorized(getAnnotation(mi)); } } catch(AuthorizationException ae) { // Annotation handler doesn't know why it was called, so add the information here if possible. // Don't wrap the exception here since we don't want to mask the specific exception, such as // UnauthenticatedException etc. if (ae.getCause() == null) ae.initCause(new AuthorizationException("Not authorized to invoke method: " + mi.getMethod())); throw ae; } } }
1,720
0.714535
0.713953
38
43.263157
36.689079
134
false
false
0
0
0
0
0
0
0.684211
false
false
12
7c1a8a6dfb3dcb8d5bbc50b2ad04cb0d2c024e6e
20,882,131,028,299
b501a230250173e88a87aa15a00ec5d2657dead2
/src/main/java/pl/infoshare/Lesson3.java
01bd3fee6b7077116a21169128cf3b86c30bc4cd
[]
no_license
Thyion/MyTestRepo
https://github.com/Thyion/MyTestRepo
63bc9fb38f19625b120c5a03aa6ca9a3cb234270
0b714f74f3e5320d82986a1012b5ac59167e48c4
refs/heads/master
2020-03-31T18:02:00.502000
2018-12-05T18:52:31
2018-12-05T18:52:31
152,443,873
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pl.infoshare; import java.util.Random; import java.util.Scanner; public class Lesson3 { public static void main (String[] args) { /* for (short i = 1 ; i <= 1000 ;i++) { System.out.println(i); } int [] [] array2D = new int[10][12]; for (int i = 1; i < array2D.length + 1; i++) { System.out.println("I'm in row no. " + i); for (int j = 1 ; j < array2D[0].length + 1; j++) { // dzieki temu [0] pobieramy dlugosc 2 wymiaru System.out.println("I'm in column no. " + j); } } // ------------------EXERCISES-------------------- System.out.println("------------"); System.out.println("Exercise no 1"); System.out.println("------------"); int[] numbers = {2,5,10,25,75,74,15,12,32,22}; for (int i = 0; i < numbers.length;i++) if (i%2==0){ System.out.println(numbers[i]); } System.out.println("------------"); System.out.println("Exercise no 2"); System.out.println("------------"); char[] [] chars = {{'*','*','*'},{'*','*','*'},{'*','*','*'},{'*','*','*'},{'*','*','*'},{'*','*','*'},{'*','*','*'},{'*','*','*'},{'*','*','*'},{'*','*','*'},}; for (int i = 0; i < chars.length;i++) { if (i % 2 != 0) System.out.println(chars[i]); else System.out.println(" "); } System.out.println("------------"); System.out.println("Exercise no 3"); System.out.println("------------"); Random random = new Random(); int number = random.nextInt(10)+1; System.out.println("Zagrajmy w gre. Pomyslalem jakas liczbe calkowita od 1 do 10...\nZgadniesz jaka to liczba ??"); Scanner in = new Scanner(System.in); while (!in.hasNextInt()) { System.out.println("That's not a number!!!"); in.next(); // this is important! } System.out.print("Podaj liczbe: "); int askNumber; askNumber = in.nextInt(); do { if (askNumber > 10 || askNumber < 1) { do { System.out.println("Liczba miala byc od 1-10 !!! Wybierz jeszcze raz."); in.reset(); askNumber = in.nextInt(); } while (askNumber > 10 || askNumber < 1); } else { do { System.out.println("Niestety nie trafiles !!!"); System.out.println("Myslalem o liczbie: " + number); System.out.println("Pomyliles sie o: " + Math.abs(number-askNumber)); System.out.println("Pomysle nowa liczbe. Sprobuj zgadnac jeszcze raz."); number = random.nextInt(10)+1; in.reset(); askNumber = in.nextInt(); } while (askNumber!=number); } }while(askNumber!=number); System.out.println("Twoja propozycja to: " + askNumber); System.out.println("Liczba o której myslalem, to: " + number); System.out.println("Gratulacje trafiles!!"); */ // ------------------HOMEWORK-------------------- int[] chosenNumbers = new int[6]; int[] randomNumber = new int[6]; randomNumber = randomNumbers(); System.out.println("Wytypuj 6 liczb w zakresie od 1 do 49"); chosenNumbers = typeNumbers(); int score = scores(chosenNumbers, randomNumber); System.out.println("Liczba trafionych numerów : " + score); System.out.println(wygrana(score)); } private static int scores(int[] chosenNumbers, int[] randomNumbers) { int scores = 0; for (int i = 0; i<chosenNumbers.length; i++){ for (int j = 0; j < randomNumbers.length; j++){ if (chosenNumbers[i]==randomNumbers[j]) scores++; } } return scores; } private static int[] typeNumbers() { int[] chosenumbers = new int[6]; for (int i = 0 ; i < chosenumbers.length ; i++) { System.out.println("Wybierz " + (i+1) + " liczbe :"); int number = typeNumber(); if ((areIncluded(number, chosenumbers))==true){ System.out.println("Już taką liczbę wybrałeś. Wybierz jakąś inną."); i--; } else { chosenumbers[i] = number; } } System.out.println("Wybrałeś : " + chosenumbers[0] + " , " + chosenumbers[1] + " , " + chosenumbers[2] + " , " + chosenumbers[3] + " , " + chosenumbers[4] + " , " + chosenumbers[5]); return chosenumbers; } private static boolean areIncluded(int number, int[] chosenNumbers) { for (int i =0 ; i < chosenNumbers.length;i++){ if (chosenNumbers[i]==number) return true; } return false; } private static int typeNumber() { Scanner in = new Scanner(System.in); int choseNumber; do { while (!in.hasNextInt()) { System.out.println("Liczba miala byc od 1-49 !!! Wybierz jeszcze raz."); in.nextInt(); } choseNumber = in.nextInt(); if (choseNumber >49 || choseNumber < 1 ) System.out.println("Liczba miala byc od 1-49 !!! Wybierz jeszcze raz."); }while(choseNumber > 49 || choseNumber < 1); return choseNumber; } private static int[] randomNumbers() { int[] randomNumbers = new int[6]; Random random = new Random(); for (int i = 0 ; i < randomNumbers.length ; i++) { int number = random.nextInt(49)+1; if ((areIncluded(number, randomNumbers))==true){ i--; } else { randomNumbers[i] = number; } } return randomNumbers; } private static String wygrana(int number) { switch (number) { case 0:{ return "Niestety nic nie wygrałeś"; } case 1: { return "Niestety nic nie wygrałeś"; } case 2:{ return "Niestety nic nie wygrałeś"; } case 3:{ return "Wygrałes 20 zł !!!"; } case 4:{ return "Wygrałeś 300 zł !!!"; } case 5:{ return "Wygrałeś 8000 zł !!!"; } case 6:{ return "GRATULACJE !!!! WYGRAŁEŚ 1 000 000 zł !!!!!"; } default: { return "default"; } } } }
UTF-8
Java
6,804
java
Lesson3.java
Java
[]
null
[]
package pl.infoshare; import java.util.Random; import java.util.Scanner; public class Lesson3 { public static void main (String[] args) { /* for (short i = 1 ; i <= 1000 ;i++) { System.out.println(i); } int [] [] array2D = new int[10][12]; for (int i = 1; i < array2D.length + 1; i++) { System.out.println("I'm in row no. " + i); for (int j = 1 ; j < array2D[0].length + 1; j++) { // dzieki temu [0] pobieramy dlugosc 2 wymiaru System.out.println("I'm in column no. " + j); } } // ------------------EXERCISES-------------------- System.out.println("------------"); System.out.println("Exercise no 1"); System.out.println("------------"); int[] numbers = {2,5,10,25,75,74,15,12,32,22}; for (int i = 0; i < numbers.length;i++) if (i%2==0){ System.out.println(numbers[i]); } System.out.println("------------"); System.out.println("Exercise no 2"); System.out.println("------------"); char[] [] chars = {{'*','*','*'},{'*','*','*'},{'*','*','*'},{'*','*','*'},{'*','*','*'},{'*','*','*'},{'*','*','*'},{'*','*','*'},{'*','*','*'},{'*','*','*'},}; for (int i = 0; i < chars.length;i++) { if (i % 2 != 0) System.out.println(chars[i]); else System.out.println(" "); } System.out.println("------------"); System.out.println("Exercise no 3"); System.out.println("------------"); Random random = new Random(); int number = random.nextInt(10)+1; System.out.println("Zagrajmy w gre. Pomyslalem jakas liczbe calkowita od 1 do 10...\nZgadniesz jaka to liczba ??"); Scanner in = new Scanner(System.in); while (!in.hasNextInt()) { System.out.println("That's not a number!!!"); in.next(); // this is important! } System.out.print("Podaj liczbe: "); int askNumber; askNumber = in.nextInt(); do { if (askNumber > 10 || askNumber < 1) { do { System.out.println("Liczba miala byc od 1-10 !!! Wybierz jeszcze raz."); in.reset(); askNumber = in.nextInt(); } while (askNumber > 10 || askNumber < 1); } else { do { System.out.println("Niestety nie trafiles !!!"); System.out.println("Myslalem o liczbie: " + number); System.out.println("Pomyliles sie o: " + Math.abs(number-askNumber)); System.out.println("Pomysle nowa liczbe. Sprobuj zgadnac jeszcze raz."); number = random.nextInt(10)+1; in.reset(); askNumber = in.nextInt(); } while (askNumber!=number); } }while(askNumber!=number); System.out.println("Twoja propozycja to: " + askNumber); System.out.println("Liczba o której myslalem, to: " + number); System.out.println("Gratulacje trafiles!!"); */ // ------------------HOMEWORK-------------------- int[] chosenNumbers = new int[6]; int[] randomNumber = new int[6]; randomNumber = randomNumbers(); System.out.println("Wytypuj 6 liczb w zakresie od 1 do 49"); chosenNumbers = typeNumbers(); int score = scores(chosenNumbers, randomNumber); System.out.println("Liczba trafionych numerów : " + score); System.out.println(wygrana(score)); } private static int scores(int[] chosenNumbers, int[] randomNumbers) { int scores = 0; for (int i = 0; i<chosenNumbers.length; i++){ for (int j = 0; j < randomNumbers.length; j++){ if (chosenNumbers[i]==randomNumbers[j]) scores++; } } return scores; } private static int[] typeNumbers() { int[] chosenumbers = new int[6]; for (int i = 0 ; i < chosenumbers.length ; i++) { System.out.println("Wybierz " + (i+1) + " liczbe :"); int number = typeNumber(); if ((areIncluded(number, chosenumbers))==true){ System.out.println("Już taką liczbę wybrałeś. Wybierz jakąś inną."); i--; } else { chosenumbers[i] = number; } } System.out.println("Wybrałeś : " + chosenumbers[0] + " , " + chosenumbers[1] + " , " + chosenumbers[2] + " , " + chosenumbers[3] + " , " + chosenumbers[4] + " , " + chosenumbers[5]); return chosenumbers; } private static boolean areIncluded(int number, int[] chosenNumbers) { for (int i =0 ; i < chosenNumbers.length;i++){ if (chosenNumbers[i]==number) return true; } return false; } private static int typeNumber() { Scanner in = new Scanner(System.in); int choseNumber; do { while (!in.hasNextInt()) { System.out.println("Liczba miala byc od 1-49 !!! Wybierz jeszcze raz."); in.nextInt(); } choseNumber = in.nextInt(); if (choseNumber >49 || choseNumber < 1 ) System.out.println("Liczba miala byc od 1-49 !!! Wybierz jeszcze raz."); }while(choseNumber > 49 || choseNumber < 1); return choseNumber; } private static int[] randomNumbers() { int[] randomNumbers = new int[6]; Random random = new Random(); for (int i = 0 ; i < randomNumbers.length ; i++) { int number = random.nextInt(49)+1; if ((areIncluded(number, randomNumbers))==true){ i--; } else { randomNumbers[i] = number; } } return randomNumbers; } private static String wygrana(int number) { switch (number) { case 0:{ return "Niestety nic nie wygrałeś"; } case 1: { return "Niestety nic nie wygrałeś"; } case 2:{ return "Niestety nic nie wygrałeś"; } case 3:{ return "Wygrałes 20 zł !!!"; } case 4:{ return "Wygrałeś 300 zł !!!"; } case 5:{ return "Wygrałeś 8000 zł !!!"; } case 6:{ return "GRATULACJE !!!! WYGRAŁEŚ 1 000 000 zł !!!!!"; } default: { return "default"; } } } }
6,804
0.463764
0.445461
224
29.25
28.92555
190
false
false
23
0.003395
0
0
0
0
0.745536
false
false
12
6175936b5bede94843c5af2b487b3b49701f3f59
2,095,944,099,005
6872a63acd6b2d1f1d25059c641538a253cf43ef
/NomTicket/src/VISTAS/AdminProductos.java
15ba83efd986bd0a29ed4dc73974d64db084ab19
[]
no_license
NukeroSempai/NomTicketJava2.0
https://github.com/NukeroSempai/NomTicketJava2.0
9fd34d7fa64b3cd3ac469d185a08b459f44fc8e3
9e7f176667b03e61f73c4df5dce49b102aec2865
refs/heads/main
2023-06-20T09:47:37.913000
2021-07-14T04:20:11
2021-07-14T04:20:11
363,567,226
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package VISTAS; import CONTROLADOR.InformesDAO; import java.awt.Image; import java.awt.Toolkit; import java.util.ArrayList; import java.util.List; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import MODELOS.EVENTOS; import MODELOS.PRODUCTO; import CONTROLADOR.ProductosDAO; import javax.swing.JDialog; /** * * @author Nukero * @version 1.0 */ public class AdminProductos extends javax.swing.JDialog { private ProductosDAO dao = new ProductosDAO(); private InformesDAO infDao = new InformesDAO(); private PRODUCTO p = new PRODUCTO(); private List<String> tipoProd = dao.listarTipo(); private EVENTOS event = new EVENTOS(); private DefaultTableModel modelo = new DefaultTableModel(); private int fila; JDProducto JDProd; public AdminProductos(javax.swing.JDialog parent, boolean modal) { super(parent, modal); initComponents(); inicializar(); } public Image getIconImage() { Image retValue = Toolkit.getDefaultToolkit().getImage(ClassLoader.getSystemResource("IMAGENES/icon2.png")); return retValue; } private void inicializar(){ cargarCombo(); limpiarTabla(); listar(); } private void cargarCombo(){ for (int i = 0; i < tipoProd.size(); i++) { jComboCategoria.addItem(tipoProd.get(i)); } } private void listar(){ List<PRODUCTO> lista = dao.listar(); modelo = (DefaultTableModel) tabla.getModel(); Object[] ob = new Object[5]; for (int i = 0; i < lista.size(); i++) { ob[0] = lista.get(i).getCodigo_producto(); ob[1] = lista.get(i).getNombre(); ob[2] = lista.get(i).getDescripcion(); ob[3] = tipoProd.get(lista.get(i).getFk_tipo_producto()-1); ob[4] = lista.get(i).getPrecio(); modelo.addRow(ob); } tabla.setModel(modelo); } //sobrecarga de metodo private void listar(int categoria){ List<PRODUCTO> lista = dao.listar(categoria); modelo = (DefaultTableModel) tabla.getModel(); Object[] ob = new Object[5]; for (int i = 0; i < lista.size(); i++) { ob[0] = lista.get(i).getCodigo_producto(); ob[1] = lista.get(i).getNombre(); ob[2] = lista.get(i).getDescripcion(); ob[3] = tipoProd.get(lista.get(i).getFk_tipo_producto()-1); ob[4] = lista.get(i).getPrecio(); modelo.addRow(ob); } tabla.setModel(modelo); } private void buscar(){ p=dao.listarCodigo(Integer.parseInt(jTtBuscar.getText())); modelo = (DefaultTableModel) tabla.getModel(); Object[] ob = new Object[5]; ob[0] = p.getCodigo_producto(); ob[1] = p.getNombre(); ob[2] = p.getDescripcion(); ob[3] = tipoProd.get(p.getFk_tipo_producto()-1); ob[4] = p.getPrecio(); modelo.addRow(ob); tabla.setModel(modelo); } private void Eliminar(){ fila = tabla.getSelectedRow(); if (fila == -1) { JOptionPane.showMessageDialog(this, "Debe seleccionar una fila"); } else { String botones[] = {"Sí", "No"}; //int respuesta = JOptionPane.showConfirmDialog(null, "¿Eliminar producto?"); int respuesta = JOptionPane.showOptionDialog(this, "¿Eliminar producto?", "Aviso", 0, 0, null, botones, this); if (respuesta == 0) { if (dao.eliminar(""+p.getCodigo_producto()) > 0) { JOptionPane.showMessageDialog(null, "Producto eliminado exitosamente","Éxito!",JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(null, "Error al eliminar producto", "Error!", JOptionPane.ERROR_MESSAGE); } } } } private void limpiarTabla(){ for (int i = 0; i < modelo.getRowCount(); i++) { modelo.removeRow(i); i = i - 1; } } private void cambiarModulo(JDialog dialogo){ this.setEnabled(false); this.setVisible(false); dialogo.setLocationRelativeTo(this); dialogo.setDefaultCloseOperation(0); dialogo.setVisible(true); this.setEnabled(true); this.setVisible(true); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jButton13 = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jBRegistrar = new javax.swing.JButton(); jBModificar = new javax.swing.JButton(); jBEliminar = new javax.swing.JButton(); jPanel4 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); tabla = new javax.swing.JTable(); GuardarPDF = new javax.swing.JButton(); jPanel12 = new javax.swing.JPanel(); jLabel5 = new javax.swing.JLabel(); jPanel13 = new javax.swing.JPanel(); jBBuscar = new javax.swing.JButton(); jTtBuscar = new javax.swing.JTextField(); jLRut1 = new javax.swing.JLabel(); jPanel15 = new javax.swing.JPanel(); jBFiltrar = new javax.swing.JButton(); jLRut = new javax.swing.JLabel(); jComboCategoria = new javax.swing.JComboBox<>(); jBLimpiar = new javax.swing.JButton(); jPanel5 = new javax.swing.JPanel(); jBVolver = new javax.swing.JButton(); jPanel14 = new javax.swing.JPanel(); jLabel6 = new javax.swing.JLabel(); jButton13.setText("jButton13"); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setIconImage(getIconImage()); setUndecorated(true); addWindowListener(new java.awt.event.WindowAdapter() { public void windowActivated(java.awt.event.WindowEvent evt) { formWindowActivated(evt); } }); jPanel1.setBackground(new java.awt.Color(225, 139, 34)); jPanel3.setBackground(new java.awt.Color(233, 154, 57)); jPanel2.setBackground(new java.awt.Color(204, 204, 204)); jBRegistrar.setText("REGISTRAR"); jBRegistrar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBRegistrarActionPerformed(evt); } }); jBModificar.setText("MODIFICAR"); jBModificar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBModificarActionPerformed(evt); } }); jBEliminar.setText("ELIMINAR"); jBEliminar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBEliminarActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jBRegistrar, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jBModificar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jBEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jBRegistrar) .addComponent(jBModificar) .addComponent(jBEliminar)) .addContainerGap()) ); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel4.setBackground(new java.awt.Color(233, 154, 57)); tabla.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Código", "Nombre", "Descripción", "Tipo", "Precio" } ) { boolean[] canEdit = new boolean [] { false, false, false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); tabla.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tablaMouseClicked(evt); } }); jScrollPane1.setViewportView(tabla); GuardarPDF.setText("Guardar en PDF"); GuardarPDF.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { GuardarPDFActionPerformed(evt); } }); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(GuardarPDF, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(GuardarPDF) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 237, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel12.setBackground(new java.awt.Color(233, 154, 57)); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel5.setForeground(new java.awt.Color(255, 255, 255)); jLabel5.setText("Productos"); jPanel13.setBackground(new java.awt.Color(204, 204, 204)); jBBuscar.setText("BUSCAR"); jBBuscar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBBuscarActionPerformed(evt); } }); jTtBuscar.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { jTtBuscarKeyTyped(evt); } }); jLRut1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLRut1.setText("Buscar"); javax.swing.GroupLayout jPanel13Layout = new javax.swing.GroupLayout(jPanel13); jPanel13.setLayout(jPanel13Layout); jPanel13Layout.setHorizontalGroup( jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel13Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel13Layout.createSequentialGroup() .addComponent(jLRut1) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(jPanel13Layout.createSequentialGroup() .addComponent(jTtBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 35, Short.MAX_VALUE) .addComponent(jBBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); jPanel13Layout.setVerticalGroup( jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel13Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLRut1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTtBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jBBuscar)) .addContainerGap()) ); jPanel15.setBackground(new java.awt.Color(204, 204, 204)); jBFiltrar.setText("FILTRAR"); jBFiltrar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBFiltrarActionPerformed(evt); } }); jLRut.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLRut.setText("Filtrar"); jBLimpiar.setText("LIMPIAR"); jBLimpiar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBLimpiarActionPerformed(evt); } }); javax.swing.GroupLayout jPanel15Layout = new javax.swing.GroupLayout(jPanel15); jPanel15.setLayout(jPanel15Layout); jPanel15Layout.setHorizontalGroup( jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel15Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel15Layout.createSequentialGroup() .addComponent(jLRut) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(jPanel15Layout.createSequentialGroup() .addComponent(jComboCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jBFiltrar, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jBLimpiar, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); jPanel15Layout.setVerticalGroup( jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel15Layout.createSequentialGroup() .addGap(13, 13, 13) .addComponent(jLRut) .addGap(7, 7, 7) .addGroup(jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jComboCategoria) .addGroup(jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jBFiltrar) .addComponent(jBLimpiar))) .addContainerGap()) ); jBVolver.setText("VOLVER"); jBVolver.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBVolverActionPerformed(evt); } }); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addComponent(jBVolver, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addComponent(jBVolver) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout jPanel12Layout = new javax.swing.GroupLayout(jPanel12); jPanel12.setLayout(jPanel12Layout); jPanel12Layout.setHorizontalGroup( jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel12Layout.createSequentialGroup() .addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel12Layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel12Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel15, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel13, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addContainerGap()) ); jPanel12Layout.setVerticalGroup( jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel12Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5) .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel15, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel14.setBackground(new java.awt.Color(225, 139, 34)); jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IMAGENES/logoSmall.png"))); // NOI18N javax.swing.GroupLayout jPanel14Layout = new javax.swing.GroupLayout(jPanel14); jPanel14.setLayout(jPanel14Layout); jPanel14Layout.setHorizontalGroup( jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jPanel14Layout.setVerticalGroup( jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel14Layout.createSequentialGroup() .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addContainerGap()) ); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jPanel14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel12, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel12, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel14, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jBVolverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBVolverActionPerformed this.dispose(); }//GEN-LAST:event_jBVolverActionPerformed private void jBRegistrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBRegistrarActionPerformed JDProd = new JDProducto(new javax.swing.JDialog(), true); JDProd.setModalidad(ProductosDAO.AGREGAR); cambiarModulo(JDProd); limpiarTabla(); listar(); }//GEN-LAST:event_jBRegistrarActionPerformed private void jBModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBModificarActionPerformed fila = tabla.getSelectedRow(); if (fila == -1) { JOptionPane.showMessageDialog(this, "Debe seleccionar una fila"); }else{ JDProd = new JDProducto(new javax.swing.JDialog(), true); JDProd.setModalidad(ProductosDAO.MODIFICAR); JDProd.setProducto(p); cambiarModulo(JDProd); limpiarTabla(); listar(); } }//GEN-LAST:event_jBModificarActionPerformed private void jBEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBEliminarActionPerformed Eliminar(); limpiarTabla(); listar(); }//GEN-LAST:event_jBEliminarActionPerformed private void jBFiltrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBFiltrarActionPerformed limpiarTabla(); listar(jComboCategoria.getSelectedIndex()+1); }//GEN-LAST:event_jBFiltrarActionPerformed private void jBBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBBuscarActionPerformed limpiarTabla(); buscar(); jTtBuscar.setText(""); }//GEN-LAST:event_jBBuscarActionPerformed private void tablaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaMouseClicked fila = tabla.getSelectedRow(); if (fila == -1) { JOptionPane.showMessageDialog(this, "Debe seleccionar una fila"); } else { String codigo = tabla.getValueAt(fila, 0).toString(); String nombre = tabla.getValueAt(fila, 1).toString(); String descripcion = tabla.getValueAt(fila, 2).toString(); String tipoProducto = tabla.getValueAt(fila, 3).toString(); String precio = tabla.getValueAt(fila, 4).toString(); p.setCodigo_producto(Integer.parseInt(codigo)); p.setNombre(nombre); p.setDescripcion(descripcion); p.setFk_tipo_producto(tipoProd.indexOf(tipoProducto)); p.setPrecio(Integer.parseInt(precio)); } }//GEN-LAST:event_tablaMouseClicked private void jBLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBLimpiarActionPerformed jComboCategoria.setSelectedIndex(0); jTtBuscar.setText(""); limpiarTabla(); listar(); }//GEN-LAST:event_jBLimpiarActionPerformed private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated limpiarTabla(); listar(); }//GEN-LAST:event_formWindowActivated private void jTtBuscarKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTtBuscarKeyTyped // TODO add your handling code here: event.numberKeyPress(evt); }//GEN-LAST:event_jTtBuscarKeyTyped private void GuardarPDFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_GuardarPDFActionPerformed if(infDao.GenerarInformeBasicoPDF(tabla, "Lista de Productos")==1){ JOptionPane.showMessageDialog(null, "Informe creado exitosamente","Éxito!",JOptionPane.INFORMATION_MESSAGE); }else{ JOptionPane.showMessageDialog(this, "Error al guardar PDF"); } }//GEN-LAST:event_GuardarPDFActionPerformed public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(AdminProductos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(AdminProductos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(AdminProductos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(AdminProductos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { AdminProductos dialog = new AdminProductos(new javax.swing.JDialog(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton GuardarPDF; private javax.swing.JButton jBBuscar; private javax.swing.JButton jBEliminar; private javax.swing.JButton jBFiltrar; private javax.swing.JButton jBLimpiar; private javax.swing.JButton jBModificar; private javax.swing.JButton jBRegistrar; private javax.swing.JButton jBVolver; private javax.swing.JButton jButton13; private javax.swing.JComboBox<String> jComboCategoria; private javax.swing.JLabel jLRut; private javax.swing.JLabel jLRut1; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel12; private javax.swing.JPanel jPanel13; private javax.swing.JPanel jPanel14; private javax.swing.JPanel jPanel15; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextField jTtBuscar; private javax.swing.JTable tabla; // End of variables declaration//GEN-END:variables }
UTF-8
Java
33,301
java
AdminProductos.java
Java
[ { "context": "AO;\nimport javax.swing.JDialog;\n\n/**\n *\n * @author Nukero\n * @version 1.0\n */\npublic class AdminProductos e", "end": 359, "score": 0.9979521632194519, "start": 353, "tag": "NAME", "value": "Nukero" } ]
null
[]
package VISTAS; import CONTROLADOR.InformesDAO; import java.awt.Image; import java.awt.Toolkit; import java.util.ArrayList; import java.util.List; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import MODELOS.EVENTOS; import MODELOS.PRODUCTO; import CONTROLADOR.ProductosDAO; import javax.swing.JDialog; /** * * @author Nukero * @version 1.0 */ public class AdminProductos extends javax.swing.JDialog { private ProductosDAO dao = new ProductosDAO(); private InformesDAO infDao = new InformesDAO(); private PRODUCTO p = new PRODUCTO(); private List<String> tipoProd = dao.listarTipo(); private EVENTOS event = new EVENTOS(); private DefaultTableModel modelo = new DefaultTableModel(); private int fila; JDProducto JDProd; public AdminProductos(javax.swing.JDialog parent, boolean modal) { super(parent, modal); initComponents(); inicializar(); } public Image getIconImage() { Image retValue = Toolkit.getDefaultToolkit().getImage(ClassLoader.getSystemResource("IMAGENES/icon2.png")); return retValue; } private void inicializar(){ cargarCombo(); limpiarTabla(); listar(); } private void cargarCombo(){ for (int i = 0; i < tipoProd.size(); i++) { jComboCategoria.addItem(tipoProd.get(i)); } } private void listar(){ List<PRODUCTO> lista = dao.listar(); modelo = (DefaultTableModel) tabla.getModel(); Object[] ob = new Object[5]; for (int i = 0; i < lista.size(); i++) { ob[0] = lista.get(i).getCodigo_producto(); ob[1] = lista.get(i).getNombre(); ob[2] = lista.get(i).getDescripcion(); ob[3] = tipoProd.get(lista.get(i).getFk_tipo_producto()-1); ob[4] = lista.get(i).getPrecio(); modelo.addRow(ob); } tabla.setModel(modelo); } //sobrecarga de metodo private void listar(int categoria){ List<PRODUCTO> lista = dao.listar(categoria); modelo = (DefaultTableModel) tabla.getModel(); Object[] ob = new Object[5]; for (int i = 0; i < lista.size(); i++) { ob[0] = lista.get(i).getCodigo_producto(); ob[1] = lista.get(i).getNombre(); ob[2] = lista.get(i).getDescripcion(); ob[3] = tipoProd.get(lista.get(i).getFk_tipo_producto()-1); ob[4] = lista.get(i).getPrecio(); modelo.addRow(ob); } tabla.setModel(modelo); } private void buscar(){ p=dao.listarCodigo(Integer.parseInt(jTtBuscar.getText())); modelo = (DefaultTableModel) tabla.getModel(); Object[] ob = new Object[5]; ob[0] = p.getCodigo_producto(); ob[1] = p.getNombre(); ob[2] = p.getDescripcion(); ob[3] = tipoProd.get(p.getFk_tipo_producto()-1); ob[4] = p.getPrecio(); modelo.addRow(ob); tabla.setModel(modelo); } private void Eliminar(){ fila = tabla.getSelectedRow(); if (fila == -1) { JOptionPane.showMessageDialog(this, "Debe seleccionar una fila"); } else { String botones[] = {"Sí", "No"}; //int respuesta = JOptionPane.showConfirmDialog(null, "¿Eliminar producto?"); int respuesta = JOptionPane.showOptionDialog(this, "¿Eliminar producto?", "Aviso", 0, 0, null, botones, this); if (respuesta == 0) { if (dao.eliminar(""+p.getCodigo_producto()) > 0) { JOptionPane.showMessageDialog(null, "Producto eliminado exitosamente","Éxito!",JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(null, "Error al eliminar producto", "Error!", JOptionPane.ERROR_MESSAGE); } } } } private void limpiarTabla(){ for (int i = 0; i < modelo.getRowCount(); i++) { modelo.removeRow(i); i = i - 1; } } private void cambiarModulo(JDialog dialogo){ this.setEnabled(false); this.setVisible(false); dialogo.setLocationRelativeTo(this); dialogo.setDefaultCloseOperation(0); dialogo.setVisible(true); this.setEnabled(true); this.setVisible(true); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jButton13 = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jBRegistrar = new javax.swing.JButton(); jBModificar = new javax.swing.JButton(); jBEliminar = new javax.swing.JButton(); jPanel4 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); tabla = new javax.swing.JTable(); GuardarPDF = new javax.swing.JButton(); jPanel12 = new javax.swing.JPanel(); jLabel5 = new javax.swing.JLabel(); jPanel13 = new javax.swing.JPanel(); jBBuscar = new javax.swing.JButton(); jTtBuscar = new javax.swing.JTextField(); jLRut1 = new javax.swing.JLabel(); jPanel15 = new javax.swing.JPanel(); jBFiltrar = new javax.swing.JButton(); jLRut = new javax.swing.JLabel(); jComboCategoria = new javax.swing.JComboBox<>(); jBLimpiar = new javax.swing.JButton(); jPanel5 = new javax.swing.JPanel(); jBVolver = new javax.swing.JButton(); jPanel14 = new javax.swing.JPanel(); jLabel6 = new javax.swing.JLabel(); jButton13.setText("jButton13"); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setIconImage(getIconImage()); setUndecorated(true); addWindowListener(new java.awt.event.WindowAdapter() { public void windowActivated(java.awt.event.WindowEvent evt) { formWindowActivated(evt); } }); jPanel1.setBackground(new java.awt.Color(225, 139, 34)); jPanel3.setBackground(new java.awt.Color(233, 154, 57)); jPanel2.setBackground(new java.awt.Color(204, 204, 204)); jBRegistrar.setText("REGISTRAR"); jBRegistrar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBRegistrarActionPerformed(evt); } }); jBModificar.setText("MODIFICAR"); jBModificar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBModificarActionPerformed(evt); } }); jBEliminar.setText("ELIMINAR"); jBEliminar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBEliminarActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jBRegistrar, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jBModificar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jBEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jBRegistrar) .addComponent(jBModificar) .addComponent(jBEliminar)) .addContainerGap()) ); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel4.setBackground(new java.awt.Color(233, 154, 57)); tabla.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Código", "Nombre", "Descripción", "Tipo", "Precio" } ) { boolean[] canEdit = new boolean [] { false, false, false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); tabla.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tablaMouseClicked(evt); } }); jScrollPane1.setViewportView(tabla); GuardarPDF.setText("Guardar en PDF"); GuardarPDF.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { GuardarPDFActionPerformed(evt); } }); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(GuardarPDF, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(GuardarPDF) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 237, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel12.setBackground(new java.awt.Color(233, 154, 57)); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel5.setForeground(new java.awt.Color(255, 255, 255)); jLabel5.setText("Productos"); jPanel13.setBackground(new java.awt.Color(204, 204, 204)); jBBuscar.setText("BUSCAR"); jBBuscar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBBuscarActionPerformed(evt); } }); jTtBuscar.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { jTtBuscarKeyTyped(evt); } }); jLRut1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLRut1.setText("Buscar"); javax.swing.GroupLayout jPanel13Layout = new javax.swing.GroupLayout(jPanel13); jPanel13.setLayout(jPanel13Layout); jPanel13Layout.setHorizontalGroup( jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel13Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel13Layout.createSequentialGroup() .addComponent(jLRut1) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(jPanel13Layout.createSequentialGroup() .addComponent(jTtBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 35, Short.MAX_VALUE) .addComponent(jBBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); jPanel13Layout.setVerticalGroup( jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel13Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLRut1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTtBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jBBuscar)) .addContainerGap()) ); jPanel15.setBackground(new java.awt.Color(204, 204, 204)); jBFiltrar.setText("FILTRAR"); jBFiltrar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBFiltrarActionPerformed(evt); } }); jLRut.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLRut.setText("Filtrar"); jBLimpiar.setText("LIMPIAR"); jBLimpiar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBLimpiarActionPerformed(evt); } }); javax.swing.GroupLayout jPanel15Layout = new javax.swing.GroupLayout(jPanel15); jPanel15.setLayout(jPanel15Layout); jPanel15Layout.setHorizontalGroup( jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel15Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel15Layout.createSequentialGroup() .addComponent(jLRut) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(jPanel15Layout.createSequentialGroup() .addComponent(jComboCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jBFiltrar, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jBLimpiar, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); jPanel15Layout.setVerticalGroup( jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel15Layout.createSequentialGroup() .addGap(13, 13, 13) .addComponent(jLRut) .addGap(7, 7, 7) .addGroup(jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jComboCategoria) .addGroup(jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jBFiltrar) .addComponent(jBLimpiar))) .addContainerGap()) ); jBVolver.setText("VOLVER"); jBVolver.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBVolverActionPerformed(evt); } }); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addComponent(jBVolver, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addComponent(jBVolver) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout jPanel12Layout = new javax.swing.GroupLayout(jPanel12); jPanel12.setLayout(jPanel12Layout); jPanel12Layout.setHorizontalGroup( jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel12Layout.createSequentialGroup() .addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel12Layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel12Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel15, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel13, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addContainerGap()) ); jPanel12Layout.setVerticalGroup( jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel12Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5) .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel15, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel14.setBackground(new java.awt.Color(225, 139, 34)); jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IMAGENES/logoSmall.png"))); // NOI18N javax.swing.GroupLayout jPanel14Layout = new javax.swing.GroupLayout(jPanel14); jPanel14.setLayout(jPanel14Layout); jPanel14Layout.setHorizontalGroup( jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jPanel14Layout.setVerticalGroup( jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel14Layout.createSequentialGroup() .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addContainerGap()) ); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jPanel14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel12, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel12, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel14, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jBVolverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBVolverActionPerformed this.dispose(); }//GEN-LAST:event_jBVolverActionPerformed private void jBRegistrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBRegistrarActionPerformed JDProd = new JDProducto(new javax.swing.JDialog(), true); JDProd.setModalidad(ProductosDAO.AGREGAR); cambiarModulo(JDProd); limpiarTabla(); listar(); }//GEN-LAST:event_jBRegistrarActionPerformed private void jBModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBModificarActionPerformed fila = tabla.getSelectedRow(); if (fila == -1) { JOptionPane.showMessageDialog(this, "Debe seleccionar una fila"); }else{ JDProd = new JDProducto(new javax.swing.JDialog(), true); JDProd.setModalidad(ProductosDAO.MODIFICAR); JDProd.setProducto(p); cambiarModulo(JDProd); limpiarTabla(); listar(); } }//GEN-LAST:event_jBModificarActionPerformed private void jBEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBEliminarActionPerformed Eliminar(); limpiarTabla(); listar(); }//GEN-LAST:event_jBEliminarActionPerformed private void jBFiltrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBFiltrarActionPerformed limpiarTabla(); listar(jComboCategoria.getSelectedIndex()+1); }//GEN-LAST:event_jBFiltrarActionPerformed private void jBBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBBuscarActionPerformed limpiarTabla(); buscar(); jTtBuscar.setText(""); }//GEN-LAST:event_jBBuscarActionPerformed private void tablaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaMouseClicked fila = tabla.getSelectedRow(); if (fila == -1) { JOptionPane.showMessageDialog(this, "Debe seleccionar una fila"); } else { String codigo = tabla.getValueAt(fila, 0).toString(); String nombre = tabla.getValueAt(fila, 1).toString(); String descripcion = tabla.getValueAt(fila, 2).toString(); String tipoProducto = tabla.getValueAt(fila, 3).toString(); String precio = tabla.getValueAt(fila, 4).toString(); p.setCodigo_producto(Integer.parseInt(codigo)); p.setNombre(nombre); p.setDescripcion(descripcion); p.setFk_tipo_producto(tipoProd.indexOf(tipoProducto)); p.setPrecio(Integer.parseInt(precio)); } }//GEN-LAST:event_tablaMouseClicked private void jBLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBLimpiarActionPerformed jComboCategoria.setSelectedIndex(0); jTtBuscar.setText(""); limpiarTabla(); listar(); }//GEN-LAST:event_jBLimpiarActionPerformed private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated limpiarTabla(); listar(); }//GEN-LAST:event_formWindowActivated private void jTtBuscarKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTtBuscarKeyTyped // TODO add your handling code here: event.numberKeyPress(evt); }//GEN-LAST:event_jTtBuscarKeyTyped private void GuardarPDFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_GuardarPDFActionPerformed if(infDao.GenerarInformeBasicoPDF(tabla, "Lista de Productos")==1){ JOptionPane.showMessageDialog(null, "Informe creado exitosamente","Éxito!",JOptionPane.INFORMATION_MESSAGE); }else{ JOptionPane.showMessageDialog(this, "Error al guardar PDF"); } }//GEN-LAST:event_GuardarPDFActionPerformed public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(AdminProductos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(AdminProductos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(AdminProductos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(AdminProductos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { AdminProductos dialog = new AdminProductos(new javax.swing.JDialog(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton GuardarPDF; private javax.swing.JButton jBBuscar; private javax.swing.JButton jBEliminar; private javax.swing.JButton jBFiltrar; private javax.swing.JButton jBLimpiar; private javax.swing.JButton jBModificar; private javax.swing.JButton jBRegistrar; private javax.swing.JButton jBVolver; private javax.swing.JButton jButton13; private javax.swing.JComboBox<String> jComboCategoria; private javax.swing.JLabel jLRut; private javax.swing.JLabel jLRut1; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel12; private javax.swing.JPanel jPanel13; private javax.swing.JPanel jPanel14; private javax.swing.JPanel jPanel15; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextField jTtBuscar; private javax.swing.JTable tabla; // End of variables declaration//GEN-END:variables }
33,301
0.646243
0.632456
680
47.961765
37.032238
188
false
false
0
0
0
0
0
0
0.722059
false
false
12
9602de117b65d141f1c1b6a18bda06c5a04ef7d4
6,597,069,826,373
ef8ac1d78fe41049353c5c4663f815a4adb4b233
/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java
70227e574638384b2cfc2d9cbcb68569d70873e6
[]
no_license
Anandh-Raja/tmf640
https://github.com/Anandh-Raja/tmf640
37e11c9815fa61afa802a767d9011546c48b3f7a
3d485c6e84acd94a7e9676399eab618d82176e7c
refs/heads/main
2023-08-01T16:45:47.620000
2021-09-22T13:41:26
2021-09-22T13:41:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package io.swagger.configuration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.service.ApiInfo; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.models.info.License; @javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2021-08-15T10:06:57.629Z[GMT]") @Configuration public class SwaggerDocumentationConfig { @Bean public Docket customImplementation(){ return new Docket(DocumentationType.OAS_30) .select() .apis(RequestHandlerSelectors.basePackage("io.swagger.api")) .build() .directModelSubstitute(org.threeten.bp.LocalDate.class, java.sql.Date.class) .directModelSubstitute(org.threeten.bp.OffsetDateTime.class, java.util.Date.class) .apiInfo(apiInfo()); } ApiInfo apiInfo() { return new ApiInfoBuilder() .title("API Service Activation and Configuration") .description("## TMF API Reference: TMF640 - Service Activation and Configuration Version 4.0 Service Activation and Configuration API goal is to provide the ability to activate and configure Service. This API features Monitor pattern allowing to manage service configuration/activation asynchronous request (server side will provide monitor as POST/PATCH response) ### TMF640 performs the following Operations on service resource : - Retrieve a service or a collection of services depending on filter criteria - Partial update of an service - Create a service (including default values and creation rules) - Delete a service (for administration purposes) - Manage notification of events ### Monitor Resource Monitor resource is used to track and log activation and/or configuration request ### TMF640 provides following operation on Monitor resource: - Retrieval of a monitor or a collection of monitor Copyright © TM Forum 2019; All Rights Reserved") .license("") .licenseUrl("http://unlicense.org") .termsOfServiceUrl("") .version("4.0.0") .contact(new Contact("","", "")) .build(); } @Bean public OpenAPI openApi() { return new OpenAPI() .info(new Info() .title("API Service Activation and Configuration") .description("## TMF API Reference: TMF640 - Service Activation and Configuration Version 4.0 Service Activation and Configuration API goal is to provide the ability to activate and configure Service. This API features Monitor pattern allowing to manage service configuration/activation asynchronous request (server side will provide monitor as POST/PATCH response) ### TMF640 performs the following Operations on service resource : - Retrieve a service or a collection of services depending on filter criteria - Partial update of an service - Create a service (including default values and creation rules) - Delete a service (for administration purposes) - Manage notification of events ### Monitor Resource Monitor resource is used to track and log activation and/or configuration request ### TMF640 provides following operation on Monitor resource: - Retrieval of a monitor or a collection of monitor Copyright © TM Forum 2019; All Rights Reserved") .termsOfService("") .version("4.0.0") .license(new License() .name("") .url("http://unlicense.org")) .contact(new io.swagger.v3.oas.models.info.Contact() .email(""))); } }
UTF-8
Java
4,034
java
SwaggerDocumentationConfig.java
Java
[]
null
[]
package io.swagger.configuration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.service.ApiInfo; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.models.info.License; @javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2021-08-15T10:06:57.629Z[GMT]") @Configuration public class SwaggerDocumentationConfig { @Bean public Docket customImplementation(){ return new Docket(DocumentationType.OAS_30) .select() .apis(RequestHandlerSelectors.basePackage("io.swagger.api")) .build() .directModelSubstitute(org.threeten.bp.LocalDate.class, java.sql.Date.class) .directModelSubstitute(org.threeten.bp.OffsetDateTime.class, java.util.Date.class) .apiInfo(apiInfo()); } ApiInfo apiInfo() { return new ApiInfoBuilder() .title("API Service Activation and Configuration") .description("## TMF API Reference: TMF640 - Service Activation and Configuration Version 4.0 Service Activation and Configuration API goal is to provide the ability to activate and configure Service. This API features Monitor pattern allowing to manage service configuration/activation asynchronous request (server side will provide monitor as POST/PATCH response) ### TMF640 performs the following Operations on service resource : - Retrieve a service or a collection of services depending on filter criteria - Partial update of an service - Create a service (including default values and creation rules) - Delete a service (for administration purposes) - Manage notification of events ### Monitor Resource Monitor resource is used to track and log activation and/or configuration request ### TMF640 provides following operation on Monitor resource: - Retrieval of a monitor or a collection of monitor Copyright © TM Forum 2019; All Rights Reserved") .license("") .licenseUrl("http://unlicense.org") .termsOfServiceUrl("") .version("4.0.0") .contact(new Contact("","", "")) .build(); } @Bean public OpenAPI openApi() { return new OpenAPI() .info(new Info() .title("API Service Activation and Configuration") .description("## TMF API Reference: TMF640 - Service Activation and Configuration Version 4.0 Service Activation and Configuration API goal is to provide the ability to activate and configure Service. This API features Monitor pattern allowing to manage service configuration/activation asynchronous request (server side will provide monitor as POST/PATCH response) ### TMF640 performs the following Operations on service resource : - Retrieve a service or a collection of services depending on filter criteria - Partial update of an service - Create a service (including default values and creation rules) - Delete a service (for administration purposes) - Manage notification of events ### Monitor Resource Monitor resource is used to track and log activation and/or configuration request ### TMF640 provides following operation on Monitor resource: - Retrieval of a monitor or a collection of monitor Copyright © TM Forum 2019; All Rights Reserved") .termsOfService("") .version("4.0.0") .license(new License() .name("") .url("http://unlicense.org")) .contact(new io.swagger.v3.oas.models.info.Contact() .email(""))); } }
4,034
0.710565
0.695685
58
68.517242
173.693069
979
false
false
0
0
0
0
0
0
0.37931
false
false
12
be6bf820e928a8c3c7f738e83718232d3ee7ec74
26,233,660,304,095
24afd71860b32360bed4b56bcef4a6ecac5290d0
/src/main/java/com/miyano/enterprisecloud/util/MD5.java
980ff84289b63d5383f75f6ffcfa83b60e40a6b3
[]
no_license
DOTE-ON/enterprisecloud
https://github.com/DOTE-ON/enterprisecloud
89abecc9084642f716248ba08bfa5978dd38ce58
a3dbc5634e7f172a22c9781529f5e188723f8dd7
refs/heads/master
2023-01-14T02:14:33.213000
2020-11-23T09:00:57
2020-11-23T09:00:57
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.miyano.enterprisecloud.util; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * @author TeacherXue@isoftstone.com * @date 2018/8/13/ 10:39:15 * @file com.issCollege.util MD5.java * @version V1.0 */ public class MD5 { public static String stringMD5 (String pw) { try { // 拿到一个MD5转换器(如果想要SHA1参数换成”SHA1”) MessageDigest messageDigest = MessageDigest.getInstance("MD5"); // 输入的字符串转换成字节数组 byte[] inputByteArray = pw.getBytes(); // inputByteArray是输入字符串转换得到的字节数组 messageDigest.update(inputByteArray); // 转换并返回结果,也是字节数组,包含16个元素 byte[] resultByteArray = messageDigest.digest(); // 字符数组转换成字符串返回 return byteArrayToHex(resultByteArray); } catch (NoSuchAlgorithmException e) { return null; } } public static String byteArrayToHex(byte[] byteArray) { // 首先初始化一个字符数组,用来存放每个16进制字符 char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; // new一个字符数组,这个就是用来组成结果字符串的(解释一下:一个byte是八位二进制,也就是2位十六进制字符(2的8次方等于16的2次方)) char[] resultCharArray = new char[byteArray.length * 2]; // 遍历字节数组,通过位运算(位运算效率高),转换成字符放到字符数组中去 int index = 0; for (byte b : byteArray) { resultCharArray[index++] = hexDigits[b >>> 4 & 0xf]; resultCharArray[index++] = hexDigits[b & 0xf]; } // 字符数组组合成字符串返回 return new String(resultCharArray); } public static void main(String[] args) { String p=stringMD5 ("C4CA4238A0B923820DCC509A6F75849B"); assert p != null; System.out.println(p+"\t"+p.length()); } }
UTF-8
Java
1,945
java
MD5.java
Java
[ { "context": ".security.NoSuchAlgorithmException;\n/**\n * @author TeacherXue@isoftstone.com\n * @date 2018/8/13/ 10:39:15\n * @file com.issColl", "end": 165, "score": 0.9999064207077026, "start": 140, "tag": "EMAIL", "value": "TeacherXue@isoftstone.com" } ]
null
[]
package com.miyano.enterprisecloud.util; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * @author <EMAIL> * @date 2018/8/13/ 10:39:15 * @file com.issCollege.util MD5.java * @version V1.0 */ public class MD5 { public static String stringMD5 (String pw) { try { // 拿到一个MD5转换器(如果想要SHA1参数换成”SHA1”) MessageDigest messageDigest = MessageDigest.getInstance("MD5"); // 输入的字符串转换成字节数组 byte[] inputByteArray = pw.getBytes(); // inputByteArray是输入字符串转换得到的字节数组 messageDigest.update(inputByteArray); // 转换并返回结果,也是字节数组,包含16个元素 byte[] resultByteArray = messageDigest.digest(); // 字符数组转换成字符串返回 return byteArrayToHex(resultByteArray); } catch (NoSuchAlgorithmException e) { return null; } } public static String byteArrayToHex(byte[] byteArray) { // 首先初始化一个字符数组,用来存放每个16进制字符 char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; // new一个字符数组,这个就是用来组成结果字符串的(解释一下:一个byte是八位二进制,也就是2位十六进制字符(2的8次方等于16的2次方)) char[] resultCharArray = new char[byteArray.length * 2]; // 遍历字节数组,通过位运算(位运算效率高),转换成字符放到字符数组中去 int index = 0; for (byte b : byteArray) { resultCharArray[index++] = hexDigits[b >>> 4 & 0xf]; resultCharArray[index++] = hexDigits[b & 0xf]; } // 字符数组组合成字符串返回 return new String(resultCharArray); } public static void main(String[] args) { String p=stringMD5 ("C4CA4238A0B923820DCC509A6F75849B"); assert p != null; System.out.println(p+"\t"+p.length()); } }
1,927
0.68445
0.639558
54
27.481482
21.174532
75
false
false
0
0
0
0
0
0
2.12963
false
false
12
fcea3631f6b829fb30331369606bcd07fe3a6718
5,798,205,896,932
928460a233a299998de8c6a2243dddaaa5e06bca
/rearrangeFourInteger/src/rearrangeFourInteger/solution.java
dc7128665598d124e79df9e6aba70f9e81467e21
[]
no_license
roy3221/java-algorithm
https://github.com/roy3221/java-algorithm
12e74bcfb4540ac6a8495a8fc2393cd5c2a35480
249668e6ab163cab332dfab81f1fa205d97b3f47
refs/heads/master
2021-01-21T13:25:20.706000
2016-05-13T22:42:00
2016-05-13T22:42:00
52,392,853
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package rearrangeFourInteger; import java.util.Arrays; public class solution { public int[] rearrange(int A, int B, int C, int D) { int[] rvalue = new int[4]; rvalue[0] = A; rvalue[1] = B; rvalue[2] = C; rvalue[3] = D; Arrays.sort(rvalue); swap(rvalue, 0, 1); swap(rvalue, 2, 3); swap(rvalue, 0, 3); return rvalue; } private void swap(int[] array, int i, int j) { int tmp=array[i]; array[i]=array[j]; array[j]=tmp; } public static void main(String args[]){ int [] a={4,3,2,1}; solution test= new solution(); for(int i=0;i<a.length;i++){ System.out.println(test.rearrange(4, 3, 2, 1)[i]); } } }
UTF-8
Java
641
java
solution.java
Java
[]
null
[]
package rearrangeFourInteger; import java.util.Arrays; public class solution { public int[] rearrange(int A, int B, int C, int D) { int[] rvalue = new int[4]; rvalue[0] = A; rvalue[1] = B; rvalue[2] = C; rvalue[3] = D; Arrays.sort(rvalue); swap(rvalue, 0, 1); swap(rvalue, 2, 3); swap(rvalue, 0, 3); return rvalue; } private void swap(int[] array, int i, int j) { int tmp=array[i]; array[i]=array[j]; array[j]=tmp; } public static void main(String args[]){ int [] a={4,3,2,1}; solution test= new solution(); for(int i=0;i<a.length;i++){ System.out.println(test.rearrange(4, 3, 2, 1)[i]); } } }
641
0.605304
0.574103
32
19.03125
14.818663
53
false
false
0
0
0
0
0
0
2.5
false
false
12
48a9a4149c985789295ab23411e6d79bdaeea22e
20,624,433,012,872
d76c402c2f3668a5d76db6d6cf3a5c22a04299ae
/src/com/thalesgroup/optet/devenv/ArtifactToActionFilterAdapter.java
5afc231f4d89f247ea508e9a18b77312c29c6f78
[]
no_license
TrustworthyFactory/DevenvFactory
https://github.com/TrustworthyFactory/DevenvFactory
e108fed09308389fbf37cc7a54e457aa9faa4600
01c859bd7b75f6c644a429a6ed3ae42c782abd1d
refs/heads/master
2021-01-23T19:34:43.864000
2015-09-28T14:23:33
2015-09-28T14:23:33
41,912,781
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.thalesgroup.optet.devenv; import org.eclipse.ui.IActionFilter; public class ArtifactToActionFilterAdapter implements IActionFilter { private static final Object MYOBJECT_TYPE = "objectType"; private static ArtifactToActionFilterAdapter INSTANCE = new ArtifactToActionFilterAdapter(); private ArtifactToActionFilterAdapter() {} @Override public boolean testAttribute(Object target, String name, String value) { System.out.println("*******************test attribute " + name + " " + value); // if (target instanceof MyObject) { // MyObject obj = (MyObject) target; // // if(MYOBJECT_TYPE.equals(name)) { // return value.equals(obj.getType()); // } // } return true; //return false; } public static ArtifactToActionFilterAdapter getInstance() { return INSTANCE; } }
UTF-8
Java
814
java
ArtifactToActionFilterAdapter.java
Java
[]
null
[]
package com.thalesgroup.optet.devenv; import org.eclipse.ui.IActionFilter; public class ArtifactToActionFilterAdapter implements IActionFilter { private static final Object MYOBJECT_TYPE = "objectType"; private static ArtifactToActionFilterAdapter INSTANCE = new ArtifactToActionFilterAdapter(); private ArtifactToActionFilterAdapter() {} @Override public boolean testAttribute(Object target, String name, String value) { System.out.println("*******************test attribute " + name + " " + value); // if (target instanceof MyObject) { // MyObject obj = (MyObject) target; // // if(MYOBJECT_TYPE.equals(name)) { // return value.equals(obj.getType()); // } // } return true; //return false; } public static ArtifactToActionFilterAdapter getInstance() { return INSTANCE; } }
814
0.717445
0.717445
32
24.46875
27.717306
93
false
false
0
0
0
0
0
0
1.46875
false
false
12
6198eb88f252510b87bf329ac9b49dbe2904eddf
15,367,393,001,062
56ca505c3515a32a2da76a692f35f8772d5ffc94
/src/br/com/bootcamp/exer1/Main.java
ab0555bc0d6048f394d2d2ebfd73ecf4c9ad1287
[]
no_license
filipewk/bootcamp
https://github.com/filipewk/bootcamp
d4ade4ba93c57ee8441a934e4e65f9567b336c42
75a7bdfedc953c366700c9e1f2867e031bb39fef
refs/heads/master
2023-02-27T07:16:43.557000
2021-02-05T20:56:39
2021-02-05T20:56:39
334,937,445
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.bootcamp.exer1; import br.com.bootcamp.exer1.endereco.Endereco; import br.com.bootcamp.exer1.pessoa.Pessoa; import br.com.bootcamp.exer1.telefone.Telefone; import br.com.bootcamp.exer1.telefone.TipoTelefone; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { Pessoa pessoa = new Pessoa(); // DADOS PESSOAIS. pessoa.setNome("Filipe"); pessoa.setSobrenome("Oliveira"); LocalDate dataNascimento = LocalDate.of(1990, 7, 1); pessoa.setDataDeNascimento(dataNascimento); pessoa.setCpf("12312312"); pessoa.setEmail("filipe@gmail.com"); // LISTA ENDERECO. List<Endereco> enderecoList = new ArrayList<>(); Endereco endereco = new Endereco("R. tupi", 123, "Centro"); enderecoList.add(endereco); pessoa.setEnderecoList(enderecoList); // TELEFONE Telefone telefone = new Telefone(); telefone.setTipoTelefone(TipoTelefone.CELULAR); telefone.setDdd(45); telefone.setNumero(87312312); pessoa.setTelefoneList(new ArrayList<>()); pessoa.getTelefoneList().add(telefone); System.out.println(pessoa.toString()); } }
UTF-8
Java
1,284
java
Main.java
Java
[ { "context": " // DADOS PESSOAIS.\n pessoa.setNome(\"Filipe\");\n pessoa.setSobrenome(\"Oliveira\");\n ", "end": 466, "score": 0.9998540878295898, "start": 460, "tag": "NAME", "value": "Filipe" }, { "context": "a.setNome(\"Filipe\");\n pessoa.setSobreno...
null
[]
package br.com.bootcamp.exer1; import br.com.bootcamp.exer1.endereco.Endereco; import br.com.bootcamp.exer1.pessoa.Pessoa; import br.com.bootcamp.exer1.telefone.Telefone; import br.com.bootcamp.exer1.telefone.TipoTelefone; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { Pessoa pessoa = new Pessoa(); // DADOS PESSOAIS. pessoa.setNome("Filipe"); pessoa.setSobrenome("Oliveira"); LocalDate dataNascimento = LocalDate.of(1990, 7, 1); pessoa.setDataDeNascimento(dataNascimento); pessoa.setCpf("12312312"); pessoa.setEmail("<EMAIL>"); // LISTA ENDERECO. List<Endereco> enderecoList = new ArrayList<>(); Endereco endereco = new Endereco("R. tupi", 123, "Centro"); enderecoList.add(endereco); pessoa.setEnderecoList(enderecoList); // TELEFONE Telefone telefone = new Telefone(); telefone.setTipoTelefone(TipoTelefone.CELULAR); telefone.setDdd(45); telefone.setNumero(87312312); pessoa.setTelefoneList(new ArrayList<>()); pessoa.getTelefoneList().add(telefone); System.out.println(pessoa.toString()); } }
1,275
0.669003
0.644081
42
29.571428
20.175591
67
false
false
0
0
0
0
0
0
0.714286
false
false
12
811afdcd6f37c16a8b0dca0b49e63440236cac9a
21,732,534,538,890
b1ad3802d10f5de03304e79c2d478b5b97ade375
/src/main/java/com/mbms/model/Customer.java
c0d6012ba75d50cc3b956daaceb0c6822305f972
[]
no_license
maytalbarkan/CouponProjectSpring
https://github.com/maytalbarkan/CouponProjectSpring
146a6f94a5b923a551ab1de1c834c6543a51f1c6
24baffb0d5dfeca9c0db5dcf6a76102aba649f93
refs/heads/master
2020-06-18T06:02:11.610000
2019-07-14T09:41:43
2019-07-14T09:41:43
196,188,577
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mbms.model; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.validation.Valid; import lombok.AllArgsConstructor; import lombok.Data; @Entity @Data @AllArgsConstructor public class Customer { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Basic(optional = false) @Column(nullable = false) private String name; @Basic(optional = false) @Column(nullable = false) private String password; @ManyToMany @Valid private List<Coupon> coupons; public Customer() { coupons = new ArrayList<>(); } public Customer(String name, String password, String country, String city, String address) { this.name = name; this.password = password; this.coupons = new ArrayList<>(); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public List<Coupon> getCoupons() { return coupons; } public void setCoupons(List<Coupon> set) { this.coupons = set; } public void addCoupon(Coupon coupon) { this.coupons.add(coupon); } @Override public String toString() { return "Customer: id=" + id + ", name=" + name + ", password=" + password + " coupons: "; } }
UTF-8
Java
1,770
java
Customer.java
Java
[ { "context": "address) {\r\n\t\tthis.name = name;\r\n\t\tthis.password = password;\r\n\t\tthis.coupons = new ArrayList<>();\r\n\t}\r\n\r\n\tpub", "end": 1018, "score": 0.9991455674171448, "start": 1010, "tag": "PASSWORD", "value": "password" }, { "context": "er: id=\" + id + \", name...
null
[]
package com.mbms.model; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.validation.Valid; import lombok.AllArgsConstructor; import lombok.Data; @Entity @Data @AllArgsConstructor public class Customer { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Basic(optional = false) @Column(nullable = false) private String name; @Basic(optional = false) @Column(nullable = false) private String password; @ManyToMany @Valid private List<Coupon> coupons; public Customer() { coupons = new ArrayList<>(); } public Customer(String name, String password, String country, String city, String address) { this.name = name; this.password = <PASSWORD>; this.coupons = new ArrayList<>(); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public List<Coupon> getCoupons() { return coupons; } public void setCoupons(List<Coupon> set) { this.coupons = set; } public void addCoupon(Coupon coupon) { this.coupons.add(coupon); } @Override public String toString() { return "Customer: id=" + id + ", name=" + name + ", password=" + <PASSWORD> + " coupons: "; } }
1,774
0.679661
0.679661
91
17.417582
17.940723
93
false
false
0
0
0
0
0
0
1.131868
false
false
12
65a7a51e1e3d2b7cee2142362843b67953308e19
27,848,567,963,273
b6e425a6c8cd9d6882bbb656cb9b9be8e20ffdcb
/src/preez/codeforces/cfr263/B462.java
9f0a1258cf3d3fc5ec6c9a9f88a8b78f98e239da
[]
no_license
msskzx/solz
https://github.com/msskzx/solz
d388f80d008a1d550518fc52a3c5d6f73ea93d9a
cc75dc45600459779596ede68b00cd0a56554c35
refs/heads/master
2021-06-17T22:14:58.438000
2017-06-13T02:49:52
2017-06-13T02:49:52
64,698,301
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package preez.codeforces.cfr263; import java.util.Scanner; public class B462 { static Scanner sc = new Scanner(System.in); static int n, k, ind; static long ans, cur; static String s; static int[] a; public static void main(String[] args) { n = sc.nextInt(); k = sc.nextInt(); s = sc.next(); a = new int[26]; for (int i = 0; i < s.length(); i++) { a[s.charAt(i) - 'A']++; } for (int i = 0; i < 26 && k > 0; i++) { for (int j = 0; j < 26; j++) { if (a[j] > a[ind]) { ind = j; } } cur = Math.min(a[ind], k); k -= a[ind]; ans += (cur * cur); a[ind] = 0; } System.out.println(ans); } }
UTF-8
Java
649
java
B462.java
Java
[]
null
[]
package preez.codeforces.cfr263; import java.util.Scanner; public class B462 { static Scanner sc = new Scanner(System.in); static int n, k, ind; static long ans, cur; static String s; static int[] a; public static void main(String[] args) { n = sc.nextInt(); k = sc.nextInt(); s = sc.next(); a = new int[26]; for (int i = 0; i < s.length(); i++) { a[s.charAt(i) - 'A']++; } for (int i = 0; i < 26 && k > 0; i++) { for (int j = 0; j < 26; j++) { if (a[j] > a[ind]) { ind = j; } } cur = Math.min(a[ind], k); k -= a[ind]; ans += (cur * cur); a[ind] = 0; } System.out.println(ans); } }
649
0.514638
0.488444
38
16.078947
13.470009
44
false
false
0
0
0
0
0
0
2.289474
false
false
12
c34384a4785f09f1e2ee184cb90509f319d61bb6
10,376,641,009,420
de9ad2f4efa87ed74efad00d9f1bc83bce5febec
/net.sourceforge.tagsea.delicious/src/net/sourceforge/tagsea/delicious/actions/OpenInExternalBrowserActionDelegate.java
1423a0235d2fd83e7d9a85cca0fd04e9a22fcb74
[]
no_license
rteusner/tagsea
https://github.com/rteusner/tagsea
7bdd8fd088a8099739a9ce94d3c151ccb89b96ab
03f15c2456434b0e0d72e0d575eca1d743d6051c
refs/heads/master
2016-08-05T09:37:57.081000
2012-09-28T19:35:26
2012-09-28T19:35:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.sourceforge.tagsea.delicious.actions; import java.io.IOException; import net.sourceforge.tagsea.core.IWaypoint; import net.sourceforge.tagsea.delicious.waypoints.DeliciousWaypointUtil; import org.eclipse.jface.action.IAction; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IObjectActionDelegate; import org.eclipse.ui.IWorkbenchPart; public class OpenInExternalBrowserActionDelegate implements IObjectActionDelegate{ IWorkbenchPart fPart; IStructuredSelection fSelection; IWaypoint fWaypoint; public void setActivePart(IAction action, IWorkbenchPart targetPart) { fPart = targetPart; } public void run(IAction action) { if(fWaypoint!=null) { String urlString = fWaypoint.getStringValue(DeliciousWaypointUtil.URL_ATTR, ""); String[] cmd = new String[5]; String OS = System.getProperty("os.name").toLowerCase(); if ( (OS.indexOf("nt") > -1) || (OS.indexOf("windows 2000") > -1 ) || (OS.indexOf("windows xp") > -1) ) { cmd[0] = "cmd.exe"; cmd[1] = "/C"; cmd[2] = "rundll32"; cmd[3] = "url.dll,FileProtocolHandler"; cmd[4] = urlString; try { Runtime.getRuntime().exec( cmd ); } catch (IOException e) { e.printStackTrace(); } } } } public void selectionChanged(IAction action, ISelection selection) { fSelection = (IStructuredSelection)selection; if(fSelection!=null) fWaypoint = (IWaypoint)fSelection.getFirstElement(); } }
UTF-8
Java
1,530
java
OpenInExternalBrowserActionDelegate.java
Java
[]
null
[]
package net.sourceforge.tagsea.delicious.actions; import java.io.IOException; import net.sourceforge.tagsea.core.IWaypoint; import net.sourceforge.tagsea.delicious.waypoints.DeliciousWaypointUtil; import org.eclipse.jface.action.IAction; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IObjectActionDelegate; import org.eclipse.ui.IWorkbenchPart; public class OpenInExternalBrowserActionDelegate implements IObjectActionDelegate{ IWorkbenchPart fPart; IStructuredSelection fSelection; IWaypoint fWaypoint; public void setActivePart(IAction action, IWorkbenchPart targetPart) { fPart = targetPart; } public void run(IAction action) { if(fWaypoint!=null) { String urlString = fWaypoint.getStringValue(DeliciousWaypointUtil.URL_ATTR, ""); String[] cmd = new String[5]; String OS = System.getProperty("os.name").toLowerCase(); if ( (OS.indexOf("nt") > -1) || (OS.indexOf("windows 2000") > -1 ) || (OS.indexOf("windows xp") > -1) ) { cmd[0] = "cmd.exe"; cmd[1] = "/C"; cmd[2] = "rundll32"; cmd[3] = "url.dll,FileProtocolHandler"; cmd[4] = urlString; try { Runtime.getRuntime().exec( cmd ); } catch (IOException e) { e.printStackTrace(); } } } } public void selectionChanged(IAction action, ISelection selection) { fSelection = (IStructuredSelection)selection; if(fSelection!=null) fWaypoint = (IWaypoint)fSelection.getFirstElement(); } }
1,530
0.710458
0.700654
62
23.693548
23.416006
83
false
false
0
0
0
0
0
0
2.241935
false
false
12
fce67571e55a382d270aa34ba30c86bfa3d7dedd
11,922,829,237,170
2b9b00b12e861e396ea42e88f8504e9d6df59e12
/resource-provider/src/main/java/com/adobe/examples/db/resourceprovider/impl/DBResourceProviderFactory.java
d489104ec1b40ebbff76da4c371e75c727eebcbd
[ "Apache-2.0" ]
permissive
isabella232/db-resource-provider-example
https://github.com/isabella232/db-resource-provider-example
9a06e63354cd06220d515d0e3395c9865495d44b
c32aedf1539ccb78bdf3cec5d03fb957e8ed94b4
refs/heads/master
2021-05-29T06:15:58.247000
2015-08-03T13:52:08
2015-08-03T13:52:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.adobe.examples.db.resourceprovider.impl; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.ConfigurationPolicy; import org.apache.felix.scr.annotations.Deactivate; import org.apache.felix.scr.annotations.Properties; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Service; import org.apache.sling.api.resource.LoginException; import org.apache.sling.api.resource.ResourceProvider; import org.apache.sling.api.resource.ResourceProviderFactory; import org.apache.sling.api.wrappers.ValueMapDecorator; import org.osgi.framework.BundleContext; import org.osgi.framework.Filter; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.util.tracker.ServiceTracker; import org.osgi.util.tracker.ServiceTrackerCustomizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import java.util.Map; @Component( metatype = true, label = "DB Resource Provider Factory", description = "OSGi Configuration for DB Resource Providers", configurationFactory = true, specVersion = "1.1", policy = ConfigurationPolicy.REQUIRE ) @Service @Properties({ @Property(name = "datasource.name"), @Property(name = ResourceProvider.ROOTS), @Property(name = ResourceProvider.OWNS_ROOTS, boolValue = true, propertyPrivate = true) }) public class DBResourceProviderFactory implements ResourceProviderFactory, ServiceTrackerCustomizer<DataSource, DataSource> { private static final Logger LOG = LoggerFactory.getLogger(DBResourceProviderFactory.class); private static final String FILTER_TEMPLATE = "(&(datasource.name=%s)(objectClass=javax.sql.DataSource))"; private String dataSourceName; private DataSource dataSource; private ServiceTracker<DataSource, DataSource> dataSourceTracker; private ServiceReference<DataSource> dataSourceReference; private Connection connection; private String rootPath; private DBResourceDataFactory dataFactory; public ResourceProvider getResourceProvider(Map<String, Object> authenticationInfo) throws LoginException { try { LOG.info("Getting DBResourceProvider for {}", rootPath); return new DBResourceProvider(dataFactory); } catch (SQLException e) { throw new LoginException("Database initialization failed", e); } } public ResourceProvider getAdministrativeResourceProvider(Map<String, Object> authenticationInfo) throws LoginException { return getResourceProvider(authenticationInfo); } @Activate public void activate(BundleContext context, Map<String, Object> properties) throws InvalidSyntaxException { final ValueMapDecorator props = new ValueMapDecorator(properties); dataSourceName = props.get("datasource.name", String.class); rootPath = props.get(ResourceProvider.ROOTS, String.class); if (dataSourceName != null) { LOG.info("Activating DB Resource Provider Factory for DataSource named [{}]", dataSourceName); final String filterExpression = String.format(FILTER_TEMPLATE, dataSourceName); final Filter filter = context.createFilter(filterExpression); dataSourceTracker = new ServiceTracker<DataSource, DataSource>(context, filter, this); dataSourceTracker.open(); } else { throw new IllegalStateException("Configuration is missing datasource.name property"); } LOG.info("DB Resource Provider Factory for DataSource named [{}] activated", dataSourceName); } @Deactivate public void deactivate() { LOG.info("Deactivating DB Resource Provider Factory for DataSource [{}]", dataSourceName); dataSourceTracker.close(); dataSourceTracker = null; } public DataSource addingService(final ServiceReference<DataSource> reference) { if (dataSource == null) { dataSourceReference = reference; final DataSource ds = reference.getBundle().getBundleContext().getService(reference); registerDataSource(ds); return ds; } else { LOG.info("A DataSource named [{}] is already bound. Ignoring new DataSource.", dataSourceName); } return null; } public void modifiedService(final ServiceReference<DataSource> reference, final DataSource ds) { if (dataSourceReference == reference) { LOG.info("Updating DataSource named [{}].", dataSourceName); unregisterDataSource(); registerDataSource(ds); } } public void removedService(final ServiceReference<DataSource> reference, final DataSource service) { if (dataSourceReference == reference) { if (dataSourceTracker != null) { // prevent misleading log message on deactivate (dataSourceTracker.close()) LOG.info("DataSource named [{}] has disappeared. Deactivating service.", dataSourceName); } unregisterDataSource(); dataSourceReference = null; } } private void registerDataSource(final DataSource ds) { try { connection = ds.getConnection(); dataSource = ds; dataFactory = new DBResourceDataFactory(connection, rootPath); LOG.info("Bound datasource named [{}]", dataSourceName); } catch (SQLException e) { LOG.error("Failed to create a DB connection for DataSource named [{}]", dataSourceName, e); } } private void unregisterDataSource() { try { if (connection != null && !connection.isClosed()) { connection.close(); } } catch (SQLException e) { LOG.error("Failed to close DB connection", e); } finally { connection = null; dataSource = null; dataFactory = null; } } }
UTF-8
Java
6,151
java
DBResourceProviderFactory.java
Java
[]
null
[]
package com.adobe.examples.db.resourceprovider.impl; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.ConfigurationPolicy; import org.apache.felix.scr.annotations.Deactivate; import org.apache.felix.scr.annotations.Properties; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Service; import org.apache.sling.api.resource.LoginException; import org.apache.sling.api.resource.ResourceProvider; import org.apache.sling.api.resource.ResourceProviderFactory; import org.apache.sling.api.wrappers.ValueMapDecorator; import org.osgi.framework.BundleContext; import org.osgi.framework.Filter; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.util.tracker.ServiceTracker; import org.osgi.util.tracker.ServiceTrackerCustomizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import java.util.Map; @Component( metatype = true, label = "DB Resource Provider Factory", description = "OSGi Configuration for DB Resource Providers", configurationFactory = true, specVersion = "1.1", policy = ConfigurationPolicy.REQUIRE ) @Service @Properties({ @Property(name = "datasource.name"), @Property(name = ResourceProvider.ROOTS), @Property(name = ResourceProvider.OWNS_ROOTS, boolValue = true, propertyPrivate = true) }) public class DBResourceProviderFactory implements ResourceProviderFactory, ServiceTrackerCustomizer<DataSource, DataSource> { private static final Logger LOG = LoggerFactory.getLogger(DBResourceProviderFactory.class); private static final String FILTER_TEMPLATE = "(&(datasource.name=%s)(objectClass=javax.sql.DataSource))"; private String dataSourceName; private DataSource dataSource; private ServiceTracker<DataSource, DataSource> dataSourceTracker; private ServiceReference<DataSource> dataSourceReference; private Connection connection; private String rootPath; private DBResourceDataFactory dataFactory; public ResourceProvider getResourceProvider(Map<String, Object> authenticationInfo) throws LoginException { try { LOG.info("Getting DBResourceProvider for {}", rootPath); return new DBResourceProvider(dataFactory); } catch (SQLException e) { throw new LoginException("Database initialization failed", e); } } public ResourceProvider getAdministrativeResourceProvider(Map<String, Object> authenticationInfo) throws LoginException { return getResourceProvider(authenticationInfo); } @Activate public void activate(BundleContext context, Map<String, Object> properties) throws InvalidSyntaxException { final ValueMapDecorator props = new ValueMapDecorator(properties); dataSourceName = props.get("datasource.name", String.class); rootPath = props.get(ResourceProvider.ROOTS, String.class); if (dataSourceName != null) { LOG.info("Activating DB Resource Provider Factory for DataSource named [{}]", dataSourceName); final String filterExpression = String.format(FILTER_TEMPLATE, dataSourceName); final Filter filter = context.createFilter(filterExpression); dataSourceTracker = new ServiceTracker<DataSource, DataSource>(context, filter, this); dataSourceTracker.open(); } else { throw new IllegalStateException("Configuration is missing datasource.name property"); } LOG.info("DB Resource Provider Factory for DataSource named [{}] activated", dataSourceName); } @Deactivate public void deactivate() { LOG.info("Deactivating DB Resource Provider Factory for DataSource [{}]", dataSourceName); dataSourceTracker.close(); dataSourceTracker = null; } public DataSource addingService(final ServiceReference<DataSource> reference) { if (dataSource == null) { dataSourceReference = reference; final DataSource ds = reference.getBundle().getBundleContext().getService(reference); registerDataSource(ds); return ds; } else { LOG.info("A DataSource named [{}] is already bound. Ignoring new DataSource.", dataSourceName); } return null; } public void modifiedService(final ServiceReference<DataSource> reference, final DataSource ds) { if (dataSourceReference == reference) { LOG.info("Updating DataSource named [{}].", dataSourceName); unregisterDataSource(); registerDataSource(ds); } } public void removedService(final ServiceReference<DataSource> reference, final DataSource service) { if (dataSourceReference == reference) { if (dataSourceTracker != null) { // prevent misleading log message on deactivate (dataSourceTracker.close()) LOG.info("DataSource named [{}] has disappeared. Deactivating service.", dataSourceName); } unregisterDataSource(); dataSourceReference = null; } } private void registerDataSource(final DataSource ds) { try { connection = ds.getConnection(); dataSource = ds; dataFactory = new DBResourceDataFactory(connection, rootPath); LOG.info("Bound datasource named [{}]", dataSourceName); } catch (SQLException e) { LOG.error("Failed to create a DB connection for DataSource named [{}]", dataSourceName, e); } } private void unregisterDataSource() { try { if (connection != null && !connection.isClosed()) { connection.close(); } } catch (SQLException e) { LOG.error("Failed to close DB connection", e); } finally { connection = null; dataSource = null; dataFactory = null; } } }
6,151
0.692408
0.691757
148
40.56081
33.251343
125
false
false
0
0
0
0
0
0
0.736486
false
false
12
9be2909165bd91f0e3143b07da7f1d23198a4702
1,254,130,476,969
af07e56e87842ba7c05881efeadddf3be4a84982
/src/main/java/neqsim/physicalProperties/physicalPropertyMethods/gasPhysicalProperties/diffusivity/Diffusivity.java
af5ede8565923a311d24f17e9db27a20f392d41a
[ "Apache-2.0" ]
permissive
EvenSol/neqsim
https://github.com/EvenSol/neqsim
2df72c763ed59e14278774a58092b2a74fcbb78e
d81df26b2937d4a6665e3c28626721aa55667a51
refs/heads/master
2023-05-10T21:30:36.989000
2020-05-14T11:38:28
2020-05-14T11:38:28
185,164,800
0
0
Apache-2.0
true
2020-03-17T17:26:47
2019-05-06T09:23:21
2019-06-01T16:22:57
2020-03-17T17:26:46
7,650
0
0
0
Java
false
false
/* * Conductivity.java * * Created on 1. november 2000, 19:00 */ package neqsim.physicalProperties.physicalPropertyMethods.gasPhysicalProperties.diffusivity; import org.apache.logging.log4j.*; /** * * @author Even Solbraa * @version */ public class Diffusivity extends neqsim.physicalProperties.physicalPropertyMethods.gasPhysicalProperties.GasPhysicalPropertyMethod implements neqsim.physicalProperties.physicalPropertyMethods.methodInterface.DiffusivityInterface, Cloneable{ private static final long serialVersionUID = 1000; static Logger logger = LogManager.getLogger(Diffusivity.class); double[][] binaryDiffusionCoeffisients, binaryLennardJonesOmega; double[] effectiveDiffusionCoefficient; /** Creates new Conductivity */ public Diffusivity() { } public Diffusivity(neqsim.physicalProperties.physicalPropertySystem.PhysicalPropertiesInterface gasPhase) { super(gasPhase); binaryDiffusionCoeffisients = new double[gasPhase.getPhase().getNumberOfComponents()][gasPhase.getPhase().getNumberOfComponents()]; binaryLennardJonesOmega = new double[gasPhase.getPhase().getNumberOfComponents()][gasPhase.getPhase().getNumberOfComponents()]; effectiveDiffusionCoefficient = new double[gasPhase.getPhase().getNumberOfComponents()]; } public Object clone(){ Diffusivity properties = null; try{ properties = (Diffusivity) super.clone(); } catch(Exception e) { logger.error("Cloning failed.",e); } properties.binaryDiffusionCoeffisients = this.binaryDiffusionCoeffisients.clone(); for(int i=0;i<gasPhase.getPhase().getNumberOfComponents();i++){ System.arraycopy(this.binaryDiffusionCoeffisients[i], 0, properties.binaryDiffusionCoeffisients[i], 0, gasPhase.getPhase().getNumberOfComponents()); } return properties; } public double calcBinaryDiffusionCoefficient(int i, int j, int method){ // method - estimation method // if(method==? then) double A2= 1.06036, B2= 0.15610, C2=0.19300, D2=0.47635, E2=1.03587, F2=1.52996, G2=1.76474, H2=3.89411; double tempVar2 = gasPhase.getPhase().getTemperature()/binaryEnergyParameter[i][j]; binaryLennardJonesOmega[i][j] = A2/Math.pow(tempVar2,B2)+C2/Math.exp(D2*tempVar2)+E2/Math.exp(F2*tempVar2)+G2/Math.exp(H2*tempVar2); binaryDiffusionCoeffisients[i][j] = 0.00266*Math.pow(gasPhase.getPhase().getTemperature(),1.5)/(gasPhase.getPhase().getPressure()* Math.sqrt(binaryMolecularMass[i][j])*Math.pow(binaryMolecularDiameter[i][j],2)*binaryLennardJonesOmega[i][j]); return binaryDiffusionCoeffisients[i][j] *= 1e-4; } public double[][] calcDiffusionCoeffisients(int binaryDiffusionCoefficientMethod , int multicomponentDiffusionMethod){ for(int i = 0; i < gasPhase.getPhase().getNumberOfComponents(); i++) { for(int j = i; j < gasPhase.getPhase().getNumberOfComponents(); j++) { binaryDiffusionCoeffisients[i][j] = calcBinaryDiffusionCoefficient(i, j, binaryDiffusionCoefficientMethod); binaryDiffusionCoeffisients[j][i] = binaryDiffusionCoeffisients[i][j]; } } if(multicomponentDiffusionMethod==0){ // ok use full matrix } else if(multicomponentDiffusionMethod==0){ //calcEffectiveDiffusionCoeffisients(); } return binaryDiffusionCoeffisients; } public void calcEffectiveDiffusionCoeffisients(){ double sum=0; for(int i = 0; i < gasPhase.getPhase().getNumberOfComponents(); i++) { sum = 0; for(int j = 0; j < gasPhase.getPhase().getNumberOfComponents(); j++) { if(i==j){ } else{ sum += gasPhase.getPhase().getComponents()[j].getx()/binaryDiffusionCoeffisients[i][j]; } } effectiveDiffusionCoefficient[i] = (1.0-gasPhase.getPhase().getComponents()[i].getx())/sum; } } public double getFickBinaryDiffusionCoefficient(int i, int j){ return binaryDiffusionCoeffisients[i][j]; } public double getEffectiveDiffusionCoefficient(int i){ return effectiveDiffusionCoefficient[i]; } public double getMaxwellStefanBinaryDiffusionCoefficient(int i, int j){ /* double temp = (i==j)? 1.0: 0.0; double nonIdealCorrection = temp + gasPhase.getPhase().getComponents()[i].getx() * gasPhase.getPhase().getComponents()[i].getdfugdn(j) * gasPhase.getPhase().getNumberOfMolesInPhase(); if (Double.isNaN(nonIdealCorrection)) nonIdealCorrection=1.0; return binaryDiffusionCoeffisients[i][j]/nonIdealCorrection; // shuld be divided by non ideality factor */ return binaryDiffusionCoeffisients[i][j]; } }
UTF-8
Java
4,982
java
Diffusivity.java
Java
[ { "context": "rt org.apache.logging.log4j.*;\n\n/**\n *\n * @author Even Solbraa\n * @version\n */\npublic class Diffusivity extends ", "end": 231, "score": 0.9998491406440735, "start": 219, "tag": "NAME", "value": "Even Solbraa" } ]
null
[]
/* * Conductivity.java * * Created on 1. november 2000, 19:00 */ package neqsim.physicalProperties.physicalPropertyMethods.gasPhysicalProperties.diffusivity; import org.apache.logging.log4j.*; /** * * @author <NAME> * @version */ public class Diffusivity extends neqsim.physicalProperties.physicalPropertyMethods.gasPhysicalProperties.GasPhysicalPropertyMethod implements neqsim.physicalProperties.physicalPropertyMethods.methodInterface.DiffusivityInterface, Cloneable{ private static final long serialVersionUID = 1000; static Logger logger = LogManager.getLogger(Diffusivity.class); double[][] binaryDiffusionCoeffisients, binaryLennardJonesOmega; double[] effectiveDiffusionCoefficient; /** Creates new Conductivity */ public Diffusivity() { } public Diffusivity(neqsim.physicalProperties.physicalPropertySystem.PhysicalPropertiesInterface gasPhase) { super(gasPhase); binaryDiffusionCoeffisients = new double[gasPhase.getPhase().getNumberOfComponents()][gasPhase.getPhase().getNumberOfComponents()]; binaryLennardJonesOmega = new double[gasPhase.getPhase().getNumberOfComponents()][gasPhase.getPhase().getNumberOfComponents()]; effectiveDiffusionCoefficient = new double[gasPhase.getPhase().getNumberOfComponents()]; } public Object clone(){ Diffusivity properties = null; try{ properties = (Diffusivity) super.clone(); } catch(Exception e) { logger.error("Cloning failed.",e); } properties.binaryDiffusionCoeffisients = this.binaryDiffusionCoeffisients.clone(); for(int i=0;i<gasPhase.getPhase().getNumberOfComponents();i++){ System.arraycopy(this.binaryDiffusionCoeffisients[i], 0, properties.binaryDiffusionCoeffisients[i], 0, gasPhase.getPhase().getNumberOfComponents()); } return properties; } public double calcBinaryDiffusionCoefficient(int i, int j, int method){ // method - estimation method // if(method==? then) double A2= 1.06036, B2= 0.15610, C2=0.19300, D2=0.47635, E2=1.03587, F2=1.52996, G2=1.76474, H2=3.89411; double tempVar2 = gasPhase.getPhase().getTemperature()/binaryEnergyParameter[i][j]; binaryLennardJonesOmega[i][j] = A2/Math.pow(tempVar2,B2)+C2/Math.exp(D2*tempVar2)+E2/Math.exp(F2*tempVar2)+G2/Math.exp(H2*tempVar2); binaryDiffusionCoeffisients[i][j] = 0.00266*Math.pow(gasPhase.getPhase().getTemperature(),1.5)/(gasPhase.getPhase().getPressure()* Math.sqrt(binaryMolecularMass[i][j])*Math.pow(binaryMolecularDiameter[i][j],2)*binaryLennardJonesOmega[i][j]); return binaryDiffusionCoeffisients[i][j] *= 1e-4; } public double[][] calcDiffusionCoeffisients(int binaryDiffusionCoefficientMethod , int multicomponentDiffusionMethod){ for(int i = 0; i < gasPhase.getPhase().getNumberOfComponents(); i++) { for(int j = i; j < gasPhase.getPhase().getNumberOfComponents(); j++) { binaryDiffusionCoeffisients[i][j] = calcBinaryDiffusionCoefficient(i, j, binaryDiffusionCoefficientMethod); binaryDiffusionCoeffisients[j][i] = binaryDiffusionCoeffisients[i][j]; } } if(multicomponentDiffusionMethod==0){ // ok use full matrix } else if(multicomponentDiffusionMethod==0){ //calcEffectiveDiffusionCoeffisients(); } return binaryDiffusionCoeffisients; } public void calcEffectiveDiffusionCoeffisients(){ double sum=0; for(int i = 0; i < gasPhase.getPhase().getNumberOfComponents(); i++) { sum = 0; for(int j = 0; j < gasPhase.getPhase().getNumberOfComponents(); j++) { if(i==j){ } else{ sum += gasPhase.getPhase().getComponents()[j].getx()/binaryDiffusionCoeffisients[i][j]; } } effectiveDiffusionCoefficient[i] = (1.0-gasPhase.getPhase().getComponents()[i].getx())/sum; } } public double getFickBinaryDiffusionCoefficient(int i, int j){ return binaryDiffusionCoeffisients[i][j]; } public double getEffectiveDiffusionCoefficient(int i){ return effectiveDiffusionCoefficient[i]; } public double getMaxwellStefanBinaryDiffusionCoefficient(int i, int j){ /* double temp = (i==j)? 1.0: 0.0; double nonIdealCorrection = temp + gasPhase.getPhase().getComponents()[i].getx() * gasPhase.getPhase().getComponents()[i].getdfugdn(j) * gasPhase.getPhase().getNumberOfMolesInPhase(); if (Double.isNaN(nonIdealCorrection)) nonIdealCorrection=1.0; return binaryDiffusionCoeffisients[i][j]/nonIdealCorrection; // shuld be divided by non ideality factor */ return binaryDiffusionCoeffisients[i][j]; } }
4,976
0.666198
0.643717
116
41.948277
46.550091
240
false
false
0
0
0
0
0
0
0.612069
false
false
12
6b1af191c66c2818f665a35d4f69a03926ea71b7
5,394,478,944,803
7f1dfa6812e10abc1e82335fe121521b61bb0ab0
/src/main/java/com/orb/interview/security/AuthenticationTokenFilter.java
30a1445e477501f443c1ffbf0c91faf7d3d23a65
[]
no_license
DoumanAsh/sample-server
https://github.com/DoumanAsh/sample-server
f43b0174ad39d1216f8e343700dcb503463894a9
9b077b882115e26d16189c6c1d5cb90f7afa3238
refs/heads/master
2020-08-03T09:03:16.687000
2019-09-29T17:02:36
2019-09-29T17:02:36
211,694,241
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.orb.interview.security; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import static com.orb.interview.security.TokenAuthentication.AUTH_TOKEN_HEADER; import java.io.IOException; /** * Request filter that extract an authentication token from the request header and, * if present, set it to the security context. */ @Component public class AuthenticationTokenFilter extends OncePerRequestFilter { private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationTokenFilter.class); @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String token = request.getHeader(AUTH_TOKEN_HEADER); if (token != null && token.length() > 0) { TokenAuthentication authenticationToken = new TokenAuthentication(token); SecurityContextHolder.getContext().setAuthentication(authenticationToken); LOGGER.info("Set the authentication token to the SecurityContext. token:{}", token); } filterChain.doFilter(request, response); } }
UTF-8
Java
1,454
java
AuthenticationTokenFilter.java
Java
[]
null
[]
package com.orb.interview.security; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import static com.orb.interview.security.TokenAuthentication.AUTH_TOKEN_HEADER; import java.io.IOException; /** * Request filter that extract an authentication token from the request header and, * if present, set it to the security context. */ @Component public class AuthenticationTokenFilter extends OncePerRequestFilter { private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationTokenFilter.class); @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String token = request.getHeader(AUTH_TOKEN_HEADER); if (token != null && token.length() > 0) { TokenAuthentication authenticationToken = new TokenAuthentication(token); SecurityContextHolder.getContext().setAuthentication(authenticationToken); LOGGER.info("Set the authentication token to the SecurityContext. token:{}", token); } filterChain.doFilter(request, response); } }
1,454
0.803989
0.801926
38
37.263157
36.156593
155
false
false
0
0
0
0
0
0
0.657895
false
false
12
cf07ea6d1f8c9f33addfd50db50d6595250511f6
18,528,488,942,432
c6bdc86605df7a03bd77a1ea6e3abd49c6b5eeb5
/sources/com/xys/libzxing/zxing/decode/DecodeHandler.java
edd5a6acd54c4e1173a453b3c2f970ab0d6fbc25
[]
no_license
vince-lynch/bozzys-padlock-hackiot
https://github.com/vince-lynch/bozzys-padlock-hackiot
9918481243489a558f7f8075b89409ee80fcc8c7
9e237f0e77045215d23a774b981c4d9915add06e
refs/heads/master
2021-01-01T22:27:00.847000
2020-02-09T20:39:03
2020-02-09T20:39:03
239,369,941
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xys.libzxing.zxing.decode; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.Bitmap.Config; import android.graphics.Rect; import android.hardware.Camera.Size; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import com.google.zxing.BinaryBitmap; import com.google.zxing.DecodeHintType; import com.google.zxing.MultiFormatReader; import com.google.zxing.PlanarYUVLuminanceSource; import com.google.zxing.ReaderException; import com.google.zxing.Result; import com.google.zxing.common.HybridBinarizer; import com.xys.libzxing.R; import com.xys.libzxing.zxing.activity.CaptureActivity; import java.io.ByteArrayOutputStream; import java.util.Map; public class DecodeHandler extends Handler { private final CaptureActivity activity; private final MultiFormatReader multiFormatReader = new MultiFormatReader(); private boolean running = true; public DecodeHandler(CaptureActivity captureActivity, Map<DecodeHintType, Object> map) { this.multiFormatReader.setHints(map); this.activity = captureActivity; } private static void bundleThumbnail(PlanarYUVLuminanceSource planarYUVLuminanceSource, Bundle bundle) { int[] renderThumbnail = planarYUVLuminanceSource.renderThumbnail(); int thumbnailWidth = planarYUVLuminanceSource.getThumbnailWidth(); Bitmap createBitmap = Bitmap.createBitmap(renderThumbnail, 0, thumbnailWidth, thumbnailWidth, planarYUVLuminanceSource.getThumbnailHeight(), Config.ARGB_8888); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); createBitmap.compress(CompressFormat.JPEG, 50, byteArrayOutputStream); bundle.putByteArray(DecodeThread.BARCODE_BITMAP, byteArrayOutputStream.toByteArray()); } public void handleMessage(Message message) { if (this.running) { if (message.what == R.id.decode) { decode((byte[]) message.obj, message.arg1, message.arg2); } else if (message.what == R.id.quit) { this.running = false; Looper.myLooper().quit(); } } } private void decode(byte[] bArr, int i, int i2) { Size previewSize = this.activity.getCameraManager().getPreviewSize(); byte[] bArr2 = new byte[bArr.length]; for (int i3 = 0; i3 < previewSize.height; i3++) { for (int i4 = 0; i4 < previewSize.width; i4++) { bArr2[(((previewSize.height * i4) + previewSize.height) - i3) - 1] = bArr[(previewSize.width * i3) + i4]; } } int i5 = previewSize.width; previewSize.width = previewSize.height; previewSize.height = i5; Object obj = null; PlanarYUVLuminanceSource buildLuminanceSource = buildLuminanceSource(bArr2, previewSize.width, previewSize.height); if (buildLuminanceSource != null) { try { Result decodeWithState = this.multiFormatReader.decodeWithState(new BinaryBitmap(new HybridBinarizer(buildLuminanceSource))); this.multiFormatReader.reset(); obj = decodeWithState; } catch (ReaderException unused) { this.multiFormatReader.reset(); } catch (Throwable th) { this.multiFormatReader.reset(); throw th; } } Handler handler = this.activity.getHandler(); if (obj != null) { if (handler != null) { Message obtain = Message.obtain(handler, R.id.decode_succeeded, obj); Bundle bundle = new Bundle(); bundleThumbnail(buildLuminanceSource, bundle); obtain.setData(bundle); obtain.sendToTarget(); } } else if (handler != null) { Message.obtain(handler, R.id.decode_failed).sendToTarget(); } } public PlanarYUVLuminanceSource buildLuminanceSource(byte[] bArr, int i, int i2) { Rect cropRect = this.activity.getCropRect(); if (cropRect == null) { return null; } PlanarYUVLuminanceSource planarYUVLuminanceSource = new PlanarYUVLuminanceSource(bArr, i, i2, cropRect.left, cropRect.top, cropRect.width(), cropRect.height(), false); return planarYUVLuminanceSource; } }
UTF-8
Java
4,408
java
DecodeHandler.java
Java
[]
null
[]
package com.xys.libzxing.zxing.decode; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.Bitmap.Config; import android.graphics.Rect; import android.hardware.Camera.Size; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import com.google.zxing.BinaryBitmap; import com.google.zxing.DecodeHintType; import com.google.zxing.MultiFormatReader; import com.google.zxing.PlanarYUVLuminanceSource; import com.google.zxing.ReaderException; import com.google.zxing.Result; import com.google.zxing.common.HybridBinarizer; import com.xys.libzxing.R; import com.xys.libzxing.zxing.activity.CaptureActivity; import java.io.ByteArrayOutputStream; import java.util.Map; public class DecodeHandler extends Handler { private final CaptureActivity activity; private final MultiFormatReader multiFormatReader = new MultiFormatReader(); private boolean running = true; public DecodeHandler(CaptureActivity captureActivity, Map<DecodeHintType, Object> map) { this.multiFormatReader.setHints(map); this.activity = captureActivity; } private static void bundleThumbnail(PlanarYUVLuminanceSource planarYUVLuminanceSource, Bundle bundle) { int[] renderThumbnail = planarYUVLuminanceSource.renderThumbnail(); int thumbnailWidth = planarYUVLuminanceSource.getThumbnailWidth(); Bitmap createBitmap = Bitmap.createBitmap(renderThumbnail, 0, thumbnailWidth, thumbnailWidth, planarYUVLuminanceSource.getThumbnailHeight(), Config.ARGB_8888); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); createBitmap.compress(CompressFormat.JPEG, 50, byteArrayOutputStream); bundle.putByteArray(DecodeThread.BARCODE_BITMAP, byteArrayOutputStream.toByteArray()); } public void handleMessage(Message message) { if (this.running) { if (message.what == R.id.decode) { decode((byte[]) message.obj, message.arg1, message.arg2); } else if (message.what == R.id.quit) { this.running = false; Looper.myLooper().quit(); } } } private void decode(byte[] bArr, int i, int i2) { Size previewSize = this.activity.getCameraManager().getPreviewSize(); byte[] bArr2 = new byte[bArr.length]; for (int i3 = 0; i3 < previewSize.height; i3++) { for (int i4 = 0; i4 < previewSize.width; i4++) { bArr2[(((previewSize.height * i4) + previewSize.height) - i3) - 1] = bArr[(previewSize.width * i3) + i4]; } } int i5 = previewSize.width; previewSize.width = previewSize.height; previewSize.height = i5; Object obj = null; PlanarYUVLuminanceSource buildLuminanceSource = buildLuminanceSource(bArr2, previewSize.width, previewSize.height); if (buildLuminanceSource != null) { try { Result decodeWithState = this.multiFormatReader.decodeWithState(new BinaryBitmap(new HybridBinarizer(buildLuminanceSource))); this.multiFormatReader.reset(); obj = decodeWithState; } catch (ReaderException unused) { this.multiFormatReader.reset(); } catch (Throwable th) { this.multiFormatReader.reset(); throw th; } } Handler handler = this.activity.getHandler(); if (obj != null) { if (handler != null) { Message obtain = Message.obtain(handler, R.id.decode_succeeded, obj); Bundle bundle = new Bundle(); bundleThumbnail(buildLuminanceSource, bundle); obtain.setData(bundle); obtain.sendToTarget(); } } else if (handler != null) { Message.obtain(handler, R.id.decode_failed).sendToTarget(); } } public PlanarYUVLuminanceSource buildLuminanceSource(byte[] bArr, int i, int i2) { Rect cropRect = this.activity.getCropRect(); if (cropRect == null) { return null; } PlanarYUVLuminanceSource planarYUVLuminanceSource = new PlanarYUVLuminanceSource(bArr, i, i2, cropRect.left, cropRect.top, cropRect.width(), cropRect.height(), false); return planarYUVLuminanceSource; } }
4,408
0.667423
0.660617
101
42.643566
33.729733
175
false
false
0
0
0
0
0
0
0.930693
false
false
12
5bb59bedaf314ca92894dcd7a2ffbc5a20235096
25,701,084,324,379
0abf5a084f7caa09514207510b7427cd33c0abfc
/Ex14.java
a27059d724847c54fff380c4ae4f0a2bb9ab56cf
[]
no_license
MoraruIgariok/ForJava
https://github.com/MoraruIgariok/ForJava
d13ac18b8c36a642b6d2b5a04e29707a1ea1563e
02a68417075c93e02cf450899544d988dcb8e914
refs/heads/master
2021-01-19T08:14:52.841000
2017-09-14T11:06:40
2017-09-14T11:06:40
100,651,189
1
0
null
false
2017-08-25T13:43:09
2017-08-17T22:48:55
2017-08-25T13:35:20
2017-08-25T13:43:08
0
0
0
0
null
null
null
import java.util.Scanner; public class Ex14 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("introduceti numaarul de 3 cifre ___"); int n = 3; int abc[] = new int[n] ; for(int i =0; i< n; i++) { abc[i] = sc.nextInt(); } System.out.print("Numarul este: "); for(int i =0; i< n; i++) { System.out.print(abc[i]); } System.out.println(); for(int j = n-1; j >=1;j --){ int temp = abc[j]; abc[j] = abc[j-1]; abc[j-1] = temp; } System.out.print("numarul finl este: "); for(int j = 0; j < n;j ++){ System.out.print(abc[j]); } sc.close(); } }
UTF-8
Java
657
java
Ex14.java
Java
[]
null
[]
import java.util.Scanner; public class Ex14 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("introduceti numaarul de 3 cifre ___"); int n = 3; int abc[] = new int[n] ; for(int i =0; i< n; i++) { abc[i] = sc.nextInt(); } System.out.print("Numarul este: "); for(int i =0; i< n; i++) { System.out.print(abc[i]); } System.out.println(); for(int j = n-1; j >=1;j --){ int temp = abc[j]; abc[j] = abc[j-1]; abc[j-1] = temp; } System.out.print("numarul finl este: "); for(int j = 0; j < n;j ++){ System.out.print(abc[j]); } sc.close(); } }
657
0.538813
0.52207
34
18.32353
15.357926
60
false
false
0
0
0
0
0
0
2.617647
false
false
12
31a29ac21b07e6389d45c28f558db6688a96099f
27,659,589,400,225
76eedf4c796beff38cce29811fbaaf4bb39b36b1
/src/br/fatec/pi/guiadm/MenuAdm.java
cf057a3a2c3872a5fffccec45999bfef883662d7
[]
no_license
luclissi/box.show
https://github.com/luclissi/box.show
a5bd1d58d850e8479e165f9de349d5da37fd2943
50afb926db0c8ac163183a64f89a1717a30429d1
refs/heads/master
2021-09-08T06:52:33.051000
2018-03-08T03:31:49
2018-03-08T03:31:49
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.fatec.pi.guiadm; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import com.jfoenix.controls.JFXButton; import br.fatec.pi.gui.GUIMainCtrl; import javafx.animation.FadeTransition; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.util.Duration; public class MenuAdm implements Initializable { @FXML private Label lblTitle; @FXML private ScrollPane spCenter; @FXML private AnchorPane panel; @FXML private AnchorPane bpPane; private FXMLLoader loadBPanel; private String id; private ListaAdmCtrl listaAdm = new ListaAdmCtrl(); @Override public void initialize(URL location, ResourceBundle resources) { try { panel = FXMLLoader.load(getClass().getResource("PainelAdm.fxml")); loadBPanel = new FXMLLoader(getClass().getResource("ListaAdm.fxml")); loadBPanel.setController(listaAdm); bpPane = loadBPanel.load(); AddTransition(panel); AddTransition(bpPane); listaAdm.novo.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { switch (id) { case "btn02"://Aulas aulas(); break; case "btn03"://Administradores administradores(); break; case "btn04"://Questoes questoes(); break; case "btn05"://FAQsvalue break; } } }); spCenter.setContent(panel); } catch (IOException ex) { Logger.getLogger(GUIMainCtrl.class.getName()).log(Level.SEVERE, null, ex); } } @FXML private void changePage(ActionEvent event) { JFXButton btn = (JFXButton) event.getSource(); id = btn.getId(); listaAdm.id = id; listaAdm.busca(); listaAdm.getTxtPesquisa().setText(""); switch (btn.getId()) { case "btn01"://Panel lblTitle.setText("Panel"); spCenter.setContent(panel); break; case "btn02"://Aulas lblTitle.setText("Aulas"); spCenter.setContent(bpPane); break; case "btn03"://Administradores lblTitle.setText("Administradores"); spCenter.setContent(bpPane); break; case "btn04"://Questoes lblTitle.setText("Questões"); spCenter.setContent(bpPane); break; case "btn05"://FAQsvalue lblTitle.setText("FAQs"); spCenter.setContent(bpPane); break; } } @FXML private void exit(ActionEvent event) { System.exit(0); } private void aulas() { try { NovasAulasCtrl nac = new NovasAulasCtrl(); BorderPane bpAulas; FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("NovasAulas.fxml")); fxmlLoader.setController(nac); bpAulas = fxmlLoader.load(); if(listaAdm.aula != null) { nac.aula = listaAdm.aula; nac.showInfo(); listaAdm.aula = null; }else { nac.limpaInfo(); } nac.getBtnVoltar().setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { listaAdm.busca(); lblTitle.setText("Aulas"); spCenter.setContent(bpPane); } });; spCenter.setContent(bpAulas); } catch (IOException e) { Logger.getLogger(GUIMainCtrl.class.getName()).log(Level.SEVERE, null, e); } } private void questoes() { try { NovasQuestoes nq = new NovasQuestoes(); BorderPane bpAulas; FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("NovasQuestoes.fxml")); fxmlLoader.setController(nq); bpAulas = fxmlLoader.load(); if(listaAdm.quest!= null) { nq.quest = listaAdm.quest; nq.showInfo(); listaAdm.quest = null; }else { nq.limpaInfo(); } nq.getBtnVoltar().setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { listaAdm.busca(); lblTitle.setText("Questões"); spCenter.setContent(bpPane); } });; spCenter.setContent(bpAulas); } catch (IOException e) { Logger.getLogger(GUIMainCtrl.class.getName()).log(Level.SEVERE, null, e); } } private void administradores() { try { NovosAdms na = new NovosAdms(); AnchorPane apAdms; FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("NovosAdm.fxml")); fxmlLoader.setController(na); apAdms = fxmlLoader.load(); if(listaAdm.pessoa!= null) { na.pessoa = listaAdm.pessoa; na.showInfo(); listaAdm.pessoa = null; }else { na.limpaInfo(); } na.getBtnVoltar().setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { listaAdm.busca(); lblTitle.setText("Questões"); spCenter.setContent(bpPane); } });; spCenter.setContent(apAdms); } catch (IOException e) { Logger.getLogger(GUIMainCtrl.class.getName()).log(Level.SEVERE, null, e); } } private void AddTransition(AnchorPane panel) { FadeTransition ft = new FadeTransition(Duration.millis(300), panel); ft.setFromValue(0.0); ft.setToValue(1.0); ft.play(); } }
UTF-8
Java
5,273
java
MenuAdm.java
Java
[]
null
[]
package br.fatec.pi.guiadm; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import com.jfoenix.controls.JFXButton; import br.fatec.pi.gui.GUIMainCtrl; import javafx.animation.FadeTransition; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.util.Duration; public class MenuAdm implements Initializable { @FXML private Label lblTitle; @FXML private ScrollPane spCenter; @FXML private AnchorPane panel; @FXML private AnchorPane bpPane; private FXMLLoader loadBPanel; private String id; private ListaAdmCtrl listaAdm = new ListaAdmCtrl(); @Override public void initialize(URL location, ResourceBundle resources) { try { panel = FXMLLoader.load(getClass().getResource("PainelAdm.fxml")); loadBPanel = new FXMLLoader(getClass().getResource("ListaAdm.fxml")); loadBPanel.setController(listaAdm); bpPane = loadBPanel.load(); AddTransition(panel); AddTransition(bpPane); listaAdm.novo.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { switch (id) { case "btn02"://Aulas aulas(); break; case "btn03"://Administradores administradores(); break; case "btn04"://Questoes questoes(); break; case "btn05"://FAQsvalue break; } } }); spCenter.setContent(panel); } catch (IOException ex) { Logger.getLogger(GUIMainCtrl.class.getName()).log(Level.SEVERE, null, ex); } } @FXML private void changePage(ActionEvent event) { JFXButton btn = (JFXButton) event.getSource(); id = btn.getId(); listaAdm.id = id; listaAdm.busca(); listaAdm.getTxtPesquisa().setText(""); switch (btn.getId()) { case "btn01"://Panel lblTitle.setText("Panel"); spCenter.setContent(panel); break; case "btn02"://Aulas lblTitle.setText("Aulas"); spCenter.setContent(bpPane); break; case "btn03"://Administradores lblTitle.setText("Administradores"); spCenter.setContent(bpPane); break; case "btn04"://Questoes lblTitle.setText("Questões"); spCenter.setContent(bpPane); break; case "btn05"://FAQsvalue lblTitle.setText("FAQs"); spCenter.setContent(bpPane); break; } } @FXML private void exit(ActionEvent event) { System.exit(0); } private void aulas() { try { NovasAulasCtrl nac = new NovasAulasCtrl(); BorderPane bpAulas; FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("NovasAulas.fxml")); fxmlLoader.setController(nac); bpAulas = fxmlLoader.load(); if(listaAdm.aula != null) { nac.aula = listaAdm.aula; nac.showInfo(); listaAdm.aula = null; }else { nac.limpaInfo(); } nac.getBtnVoltar().setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { listaAdm.busca(); lblTitle.setText("Aulas"); spCenter.setContent(bpPane); } });; spCenter.setContent(bpAulas); } catch (IOException e) { Logger.getLogger(GUIMainCtrl.class.getName()).log(Level.SEVERE, null, e); } } private void questoes() { try { NovasQuestoes nq = new NovasQuestoes(); BorderPane bpAulas; FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("NovasQuestoes.fxml")); fxmlLoader.setController(nq); bpAulas = fxmlLoader.load(); if(listaAdm.quest!= null) { nq.quest = listaAdm.quest; nq.showInfo(); listaAdm.quest = null; }else { nq.limpaInfo(); } nq.getBtnVoltar().setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { listaAdm.busca(); lblTitle.setText("Questões"); spCenter.setContent(bpPane); } });; spCenter.setContent(bpAulas); } catch (IOException e) { Logger.getLogger(GUIMainCtrl.class.getName()).log(Level.SEVERE, null, e); } } private void administradores() { try { NovosAdms na = new NovosAdms(); AnchorPane apAdms; FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("NovosAdm.fxml")); fxmlLoader.setController(na); apAdms = fxmlLoader.load(); if(listaAdm.pessoa!= null) { na.pessoa = listaAdm.pessoa; na.showInfo(); listaAdm.pessoa = null; }else { na.limpaInfo(); } na.getBtnVoltar().setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { listaAdm.busca(); lblTitle.setText("Questões"); spCenter.setContent(bpPane); } });; spCenter.setContent(apAdms); } catch (IOException e) { Logger.getLogger(GUIMainCtrl.class.getName()).log(Level.SEVERE, null, e); } } private void AddTransition(AnchorPane panel) { FadeTransition ft = new FadeTransition(Duration.millis(300), panel); ft.setFromValue(0.0); ft.setToValue(1.0); ft.play(); } }
5,273
0.671916
0.666983
219
23.063927
19.331181
88
false
false
0
0
0
0
0
0
3.086758
false
false
12
0c33e4b0467918e3b1503b6bf8df26cf439d90f5
962,072,685,254
e96772a23ea3c85a67ad1d428b2ea3b393ba079b
/ext/supervisord4j/src/test/java/com/iogogogo/supervisord4j/Tests.java
ec19eee66f6cc25a2111e540653a96462b216f8f
[ "Apache-2.0" ]
permissive
iogogogo/supervisord-spring-boot
https://github.com/iogogogo/supervisord-spring-boot
8b9cffc32405f5e61859e746f4427c4a02dafd2a
d80d8b77bb8d1a2e0eaed352515aea00ecfddf28
refs/heads/master
2023-06-16T09:39:40.192000
2021-07-12T08:05:08
2021-07-12T08:05:08
379,210,686
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.iogogogo.supervisord4j; import org.junit.jupiter.api.Test; import java.time.LocalTime; /** * Created by tao.zeng on 2021/7/8. */ public class Tests { @Test public void test() { System.out.println(LocalTime.ofSecondOfDay(24120000)); } }
UTF-8
Java
274
java
Tests.java
Java
[ { "context": "t;\n\nimport java.time.LocalTime;\n\n/**\n * Created by tao.zeng on 2021/7/8.\n */\npublic class Tests {\n\n @Test\n", "end": 128, "score": 0.9977977871894836, "start": 120, "tag": "USERNAME", "value": "tao.zeng" } ]
null
[]
package com.iogogogo.supervisord4j; import org.junit.jupiter.api.Test; import java.time.LocalTime; /** * Created by tao.zeng on 2021/7/8. */ public class Tests { @Test public void test() { System.out.println(LocalTime.ofSecondOfDay(24120000)); } }
274
0.678832
0.624088
16
16.125
17.888107
62
false
false
0
0
0
0
0
0
0.25
false
false
12
36c25b6b47d9bcfef39884c737f016c639bbff7d
15,857,019,268,566
3931cea6476dc421f61bcb3e323816b148f178b6
/src/main/java/net/hzfanqun/weixin/baidu/pojo/BaiduPlace.java
ed53f2c123134762b3121eec6d572fbca209c5a3
[ "Apache-2.0" ]
permissive
fanqun/weixin-nutz
https://github.com/fanqun/weixin-nutz
863954f08285484baf9c4b0bab4ce1e7e2927a55
071c3ada43a4d52977df41f596d0de16eab2310e
refs/heads/master
2020-04-16T03:12:58.508000
2016-08-08T22:34:35
2016-08-08T22:34:35
60,218,620
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.hzfanqun.weixin.baidu.pojo; /** * 地址信息 * * @author fanqun * @date 2016-01-26 */ public class BaiduPlace implements Comparable<BaiduPlace> { @Override public String toString() { return "BaiduPlace [name=" + name + ", location=" + location + ", address=" + address + ", telephone=" + telephone + ", detail_info=" + detail_info + "]"; } // 名称 private String name; // 位置 private Location location; // 详细地址 private String address; // 联系电话 private String telephone; // 距离 private DetailInfo detail_info; public String getName() { return name; } public void setName(String name) { this.name = name; } public Location getLocation() { return location; } public void setLocation(Location location) { this.location = location; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public DetailInfo getDetail_info() { return detail_info; } public void setDetail_info(DetailInfo detail_info) { this.detail_info = detail_info; } @Override public int compareTo(BaiduPlace baiduPlace) { return this.detail_info.getDistance() - baiduPlace.getDetail_info().getDistance(); } }
UTF-8
Java
1,383
java
BaiduPlace.java
Java
[ { "context": "qun.weixin.baidu.pojo;\n\n/**\n * 地址信息\n * \n * @author fanqun\n * @date 2016-01-26\n */\npublic class BaiduPlace i", "end": 74, "score": 0.8187273144721985, "start": 68, "tag": "USERNAME", "value": "fanqun" } ]
null
[]
package net.hzfanqun.weixin.baidu.pojo; /** * 地址信息 * * @author fanqun * @date 2016-01-26 */ public class BaiduPlace implements Comparable<BaiduPlace> { @Override public String toString() { return "BaiduPlace [name=" + name + ", location=" + location + ", address=" + address + ", telephone=" + telephone + ", detail_info=" + detail_info + "]"; } // 名称 private String name; // 位置 private Location location; // 详细地址 private String address; // 联系电话 private String telephone; // 距离 private DetailInfo detail_info; public String getName() { return name; } public void setName(String name) { this.name = name; } public Location getLocation() { return location; } public void setLocation(Location location) { this.location = location; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public DetailInfo getDetail_info() { return detail_info; } public void setDetail_info(DetailInfo detail_info) { this.detail_info = detail_info; } @Override public int compareTo(BaiduPlace baiduPlace) { return this.detail_info.getDistance() - baiduPlace.getDetail_info().getDistance(); } }
1,383
0.687454
0.681515
73
17.424658
20.65033
104
false
false
0
0
0
0
0
0
1.191781
false
false
12
c53cee103511a4b8aa30421189d27c0e2d6e7578
28,398,323,769,647
ff4ab79816572ce597d1c523aa6d1f75962bf156
/src/main/java/com/valueplus/domain/service/abstracts/SettingsService.java
1ed82ab87721f8665475889100fc0f89daaf78d5
[]
no_license
johnojetunde/valueplus
https://github.com/johnojetunde/valueplus
206f645ee5b75f91638c43ff2dda46edb955bb63
052217b4bd2a1aee7e451288379ce90a8127ca6e
refs/heads/master
2023-07-21T05:04:06.737000
2021-08-07T12:43:53
2021-08-07T12:43:53
402,294,348
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.valueplus.domain.service.abstracts; import com.valueplus.app.exception.ValuePlusException; import com.valueplus.domain.model.SettingCreateRequest; import com.valueplus.domain.model.SettingLogModel; import com.valueplus.domain.model.SettingModel; import com.valueplus.domain.model.SettingScheduleModel; import com.valueplus.persistence.entity.User; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.util.Optional; public interface SettingsService { String update(SettingCreateRequest setting, User loggedInUser) throws ValuePlusException; Optional<SettingModel> getCurrentSetting(); Page<SettingLogModel> getSettingLogs(Pageable pageable); Page<SettingScheduleModel> getScheduledCommission(Pageable pageable); }
UTF-8
Java
801
java
SettingsService.java
Java
[]
null
[]
package com.valueplus.domain.service.abstracts; import com.valueplus.app.exception.ValuePlusException; import com.valueplus.domain.model.SettingCreateRequest; import com.valueplus.domain.model.SettingLogModel; import com.valueplus.domain.model.SettingModel; import com.valueplus.domain.model.SettingScheduleModel; import com.valueplus.persistence.entity.User; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.util.Optional; public interface SettingsService { String update(SettingCreateRequest setting, User loggedInUser) throws ValuePlusException; Optional<SettingModel> getCurrentSetting(); Page<SettingLogModel> getSettingLogs(Pageable pageable); Page<SettingScheduleModel> getScheduledCommission(Pageable pageable); }
801
0.836454
0.836454
22
35.409092
27.123722
93
false
false
0
0
0
0
0
0
0.681818
false
false
12
a08c954b5bca3c725f78b5e9d509c4a95d5f75d1
27,470,610,856,002
f1eb4744f462fc53f5d3f7ef100e4664401aaaa2
/src/main/java/br/com/apolomcmelo/hackerrank/utils/Input.java
b99516d9d582f4763ef3cf761e33e7f118288fb0
[]
no_license
apolomcmelo/hackerrank
https://github.com/apolomcmelo/hackerrank
e9af4616835b8c417040ce2811cb564c2cf5e7dc
219ee930c527936542ed5688059e2f60bd815b44
refs/heads/master
2021-11-30T22:29:05.309000
2021-11-17T22:43:20
2021-11-17T22:43:20
171,509,497
0
0
null
false
2020-10-13T12:12:47
2019-02-19T16:31:36
2019-09-04T17:09:27
2020-10-13T12:12:45
35
0
0
1
Java
false
false
package br.com.apolomcmelo.hackerrank.utils; import java.util.Scanner; public class Input { private Scanner data; public Input() {} public Input(Scanner data) { this.data = data; } public Scanner getData() { return data; } public void setData(Scanner data) { this.data = data; } }
UTF-8
Java
344
java
Input.java
Java
[]
null
[]
package br.com.apolomcmelo.hackerrank.utils; import java.util.Scanner; public class Input { private Scanner data; public Input() {} public Input(Scanner data) { this.data = data; } public Scanner getData() { return data; } public void setData(Scanner data) { this.data = data; } }
344
0.604651
0.604651
22
14.636364
14.278227
44
false
false
0
0
0
0
0
0
0.272727
false
false
12
571a68959af60e4f8bc6b036f93fef6f80ae1105
30,700,426,262,553
9586c0441e3565b621c5ec21c41f71b68353c2d3
/app/src/main/java/com/nightmare/jli/myviewpager/Adapter/MainPagerAdapter.java
2bbfb0c52bd0bb42cb323e24001bfb95c2cc372c
[]
no_license
ljkljk12333/MyViewPager
https://github.com/ljkljk12333/MyViewPager
aca691ca9eb1910ef1ba6ba2318df52f2af5c6a0
56cbd20afd6499e01621698a53137664e0928c1b
refs/heads/master
2021-01-11T03:20:17.484000
2016-10-16T08:37:53
2016-10-16T08:37:53
71,047,778
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.nightmare.jli.myviewpager.Adapter; import android.content.Context; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.nightmare.jli.myviewpager.CycleCarouselViewPager; import com.nightmare.jli.myviewpager.R; import java.util.ArrayList; import java.util.List; /** * Created by J.Li on 2016/6/10. */ public class MainPagerAdapter extends PagerAdapter { Context mContext; LayoutInflater mInflater; /** * 分页内容View链表 */ private List<View> contents; public CycleCarouselPagerAdapter cycleCarouselPagerAdapter; public CarouselPagerAdapter carouselPagerAdapter; public MainPagerAdapter(Context tempContext){ mContext=tempContext; mInflater=LayoutInflater.from(mContext); contents=setPagerContent(); } @Override public Object instantiateItem(ViewGroup container, int position) { View view = contents.get(position); if (position == 0) { CycleCarouselViewPager cycleCarouselViewPager =(CycleCarouselViewPager)view.findViewById(R.id.viewPager_CycleCarousel); cycleCarouselPagerAdapter =new CycleCarouselPagerAdapter(mContext, cycleCarouselViewPager); cycleCarouselViewPager.setAdapter(cycleCarouselPagerAdapter); cycleCarouselViewPager.setCurrentItem(1); cycleCarouselPagerAdapter.StartCarouselPager(); cycleCarouselPagerAdapter.notifyDataSetChanged(); ViewPager carouselViewPager =(ViewPager)view.findViewById(R.id.viewPager_Carousel); carouselPagerAdapter=new CarouselPagerAdapter(mContext, carouselViewPager); carouselViewPager.setAdapter(carouselPagerAdapter); carouselPagerAdapter.StartCarouselPager(); carouselPagerAdapter.notifyDataSetChanged(); }else if(position==1){ } container.addView(view); return view; } @Override public int getCount() { return contents.size(); } @Override public boolean isViewFromObject(View view, Object object) { return (view == object); } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView(contents.get(position)); } /** * 设置各分页内容 * * @return 设置过布局后的各分页链表 */ private List<View> setPagerContent() { List<View> contents = new ArrayList<>(); View view; view = mInflater.inflate(R.layout.viewpager_main, null); contents.add(view); view = mInflater.inflate(R.layout.viewpager_second, null); contents.add(view); return contents; } }
UTF-8
Java
2,839
java
MainPagerAdapter.java
Java
[ { "context": "rayList;\nimport java.util.List;\n\n/**\n * Created by J.Li on 2016/6/10.\n */\npublic class MainPagerAdapter e", "end": 437, "score": 0.9993155002593994, "start": 433, "tag": "NAME", "value": "J.Li" } ]
null
[]
package com.nightmare.jli.myviewpager.Adapter; import android.content.Context; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.nightmare.jli.myviewpager.CycleCarouselViewPager; import com.nightmare.jli.myviewpager.R; import java.util.ArrayList; import java.util.List; /** * Created by J.Li on 2016/6/10. */ public class MainPagerAdapter extends PagerAdapter { Context mContext; LayoutInflater mInflater; /** * 分页内容View链表 */ private List<View> contents; public CycleCarouselPagerAdapter cycleCarouselPagerAdapter; public CarouselPagerAdapter carouselPagerAdapter; public MainPagerAdapter(Context tempContext){ mContext=tempContext; mInflater=LayoutInflater.from(mContext); contents=setPagerContent(); } @Override public Object instantiateItem(ViewGroup container, int position) { View view = contents.get(position); if (position == 0) { CycleCarouselViewPager cycleCarouselViewPager =(CycleCarouselViewPager)view.findViewById(R.id.viewPager_CycleCarousel); cycleCarouselPagerAdapter =new CycleCarouselPagerAdapter(mContext, cycleCarouselViewPager); cycleCarouselViewPager.setAdapter(cycleCarouselPagerAdapter); cycleCarouselViewPager.setCurrentItem(1); cycleCarouselPagerAdapter.StartCarouselPager(); cycleCarouselPagerAdapter.notifyDataSetChanged(); ViewPager carouselViewPager =(ViewPager)view.findViewById(R.id.viewPager_Carousel); carouselPagerAdapter=new CarouselPagerAdapter(mContext, carouselViewPager); carouselViewPager.setAdapter(carouselPagerAdapter); carouselPagerAdapter.StartCarouselPager(); carouselPagerAdapter.notifyDataSetChanged(); }else if(position==1){ } container.addView(view); return view; } @Override public int getCount() { return contents.size(); } @Override public boolean isViewFromObject(View view, Object object) { return (view == object); } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView(contents.get(position)); } /** * 设置各分页内容 * * @return 设置过布局后的各分页链表 */ private List<View> setPagerContent() { List<View> contents = new ArrayList<>(); View view; view = mInflater.inflate(R.layout.viewpager_main, null); contents.add(view); view = mInflater.inflate(R.layout.viewpager_second, null); contents.add(view); return contents; } }
2,839
0.693797
0.689494
97
27.752577
27.473711
131
false
false
0
0
0
0
0
0
0.525773
false
false
12
fe1b0d771c07ed4f7b83911f1b8dcb2b25f6cd1f
23,854,248,427,700
e5b569aefd1a03edbe3ffd6f35a6bba8f3d4118c
/src/main/java/com/emptytomb/dbmanager/dao/QuestionChoiceDao.java
156a1e1a993e528e6fdcf4d34fff9dec2f2d6ffa
[]
no_license
jimzombek/DbManager
https://github.com/jimzombek/DbManager
6d159800a03b4d50f1c5c63459aaeb9bab21296e
389a659dec451cb4d2e8b89b121597f871c93fa3
refs/heads/master
2022-07-11T19:09:32.098000
2022-06-21T11:09:44
2022-06-21T11:09:44
55,367,564
0
0
null
false
2022-06-21T11:08:39
2016-04-03T20:32:06
2022-05-23T11:22:20
2022-06-21T00:47:47
74
0
0
0
Java
false
false
package com.emptytomb.dbmanager.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.emptytomb.dbmanager.dao.DaoException; import com.emptytomb.dbmanager.domain.QuestionChoice; import com.emptytomb.dbmanager.utility.ConnectionFactory; /** * The QuestionChoiceDao class is a concrete JDBC implementation of the BaseDao interface. * This class implements the JDBC persistence storage layer for the QuestionChoice domain model. * * <p><b>Note:</b> This class is implemented as a Singleton. Only one instance of this class * can exist at a time.</p> * * @author Jim Zombek * @version 1.0 * @since 2016-08-01 */ public class QuestionChoiceDao implements BaseDao<QuestionChoice> { private Logger logger = LoggerFactory.getLogger(QuestionChoiceDao.class); private static QuestionChoiceDao instance = null; private Connection connection = null; private static final String QUESTION_CHOICE_TABLE = "question_choice"; private static final String QUESTION_CHOICE_ID = "id"; private static final String QUESTION_CHOICE_TEXT = "text"; private static final String QUESTION_CHOICE_CORRECT_ANSWER = "correctAnswer"; private QuestionChoiceDao() { connection = ConnectionFactory.getInstance().getConnection(); } /** * This method returns the single instance of the QuestionChoiceDao object. * * @return the QuestionDao object * */ public static QuestionChoiceDao getInstance() { if (instance == null) { synchronized (QuestionChoiceDao.class) { if (instance == null) { instance = new QuestionChoiceDao(); } } } return instance; } /** * This method reads the specified question choice id record from the question_choice * table stored in MySQL and returns a QuestionChoice object. * * @param id the unique id of the question choice to return. * @return the QuestionChoice object * * @throws DaoException if a SQL Exception was encountered during processing */ @Override public QuestionChoice get(int id) throws DaoException { QuestionChoice questionChoice = null; String sql = "SELECT * FROM " + QUESTION_CHOICE_TABLE + " WHERE " + QUESTION_CHOICE_ID + " = ?;"; try (PreparedStatement pstmt = connection.prepareStatement(sql);) { pstmt.setInt(1, id); try (ResultSet resultSet = pstmt.executeQuery();) { while (resultSet.next()) { questionChoice = getQuestionChoiceFromResultSet(resultSet); } } } catch (SQLException e) { String errorMessage = this.getClass().getName() + ": getQuestionChoice() - REASON-> " + e.getMessage(); logger.error(errorMessage); e.printStackTrace(); throw new DaoException(e, errorMessage); } return questionChoice; } /** * This method reads all the question choice records from the question table stored in MySQL and * returns a list of QuestionChoice objects. * * @return List of QuestionChoice objects * * @throws DaoException if a SQL Exception was encountered during processing */ @Override public List<QuestionChoice> list() throws DaoException { ArrayList<QuestionChoice> questionChoices = new ArrayList<QuestionChoice>(); String sql = "SELECT * FROM " + QUESTION_CHOICE_TABLE + ";"; try (PreparedStatement pstmt = connection.prepareStatement(sql); ResultSet resultSet = pstmt.executeQuery();) { while (resultSet.next()) { QuestionChoice questionChoice = getQuestionChoiceFromResultSet(resultSet); questionChoices.add(questionChoice); } } catch (SQLException e) { String errorMessage = this.getClass().getName() + ": getQuestionChoices() - REASON-> " + e.getMessage(); logger.error(errorMessage); e.printStackTrace(); throw new DaoException(e, errorMessage); } return questionChoices; } /** * This method adds the specified QuestionChoice record to the question_choice table stored in MySQL. * * <p><b>Note:</b>Referential integrity foreign key constraints will be checked * prior to adding the specified organization record to the organization table * stored in MySQL. The organization record associated with this personality * must exist in the organization table stored in MySQL.</p> * * @param questionChoice the QuestionChoice object * @return the unique id of the QuestionChoice added * * @throws DaoException if a SQL Exception was encountered during processing */ @Override public int add(QuestionChoice questionChoice) throws DaoException { int autoIncKey = -1; String sql = "INSERT INTO " + QUESTION_CHOICE_TABLE + "(" + QUESTION_CHOICE_TEXT + "," + QUESTION_CHOICE_CORRECT_ANSWER + ") " + "VALUES" + "(?,?)"; try (PreparedStatement pstmt = connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);) { pstmt.setString(1,questionChoice.getText()); pstmt.setBoolean(2,questionChoice.isCorrectAnswer()); pstmt.executeUpdate(); // Get the auto-incremented key ResultSet rs = pstmt.getGeneratedKeys(); if (rs.next()) { autoIncKey = rs.getInt(1); } else { String errorMessage = this.getClass().getName() + ": addQuestionChoice() - REASON-> " + "error obtaining auto incremented key"; logger.error(errorMessage); throw new DaoException(new Exception(), errorMessage); } } catch (SQLException e) { String errorMessage = this.getClass().getName() + ": addQuestionChoice() - REASON-> " + e.getMessage(); logger.error(errorMessage); e.printStackTrace(); throw new DaoException(e, errorMessage); } return autoIncKey; } /** * This method updates the specified QuestionChoice record in the question_choice table stored in MySQL. * * @param questionChoice the QuestionChoice object * * @throws DaoException if a SQL Exception was encountered during processing */ @Override public void update(QuestionChoice questionChoice) throws DaoException { String sql = "UPDATE " + QUESTION_CHOICE_TABLE + " SET " + QUESTION_CHOICE_TEXT + "=?, " + QUESTION_CHOICE_CORRECT_ANSWER + "=? " + "WHERE " + QUESTION_CHOICE_ID + "=?;"; try (PreparedStatement pstmt = connection.prepareStatement(sql);) { pstmt.setString(1,questionChoice.getText()); pstmt.setBoolean(2,questionChoice.isCorrectAnswer()); pstmt.setInt(3,questionChoice.getQuestionChoiceId()); pstmt.executeUpdate(); } catch (SQLException e) { String errorMessage = this.getClass().getName() + ": updateQuestion() - REASON-> " + e.getMessage(); logger.error(errorMessage); e.printStackTrace(); throw new DaoException(e, errorMessage); } } /** * This method deletes the specified question choice id from the question_choice table stored in MySQL. * * <p><b>Note:</b>Referential integrity foreign key constraints will be checked * prior to deleting the specified personality record from the personality table * stored in MySQL. All commentary records in the commentary table stored in MySQL * associated with the specified personality id must have been previously deleted * prior to calling this method.</p> * * @param id the unique id of the question choice to delete. * * @throws DaoException if a SQL Exception was encountered during processing */ @Override public void delete(int id) throws DaoException { String sql = "DELETE FROM " + QUESTION_CHOICE_TABLE + " WHERE " + QUESTION_CHOICE_ID + " = ?;"; try (PreparedStatement pstmt = connection.prepareStatement(sql);) { pstmt.setInt(1, id); pstmt.execute(); } catch (SQLException e) { String errorMessage = this.getClass().getName() + ": deleteQuestionChoice() - REASON-> " + e.getMessage(); logger.error(errorMessage); e.printStackTrace(); throw new DaoException(e, errorMessage); } } private QuestionChoice getQuestionChoiceFromResultSet(ResultSet resultSet) throws SQLException { QuestionChoice questionChoice = new QuestionChoice(); questionChoice.setQuestionChoiceId(resultSet.getInt(QUESTION_CHOICE_ID)); questionChoice.setText(resultSet.getString(QUESTION_CHOICE_TEXT)); questionChoice.setCorrectAnswer(resultSet.getBoolean(QUESTION_CHOICE_CORRECT_ANSWER)); return questionChoice; } }
UTF-8
Java
9,135
java
QuestionChoiceDao.java
Java
[ { "context": " class\n * can exist at a time.</p>\n * \n * @author Jim Zombek\n * @version 1.0\n * @since 2016-08-01\n */\npublic", "end": 773, "score": 0.9997970461845398, "start": 763, "tag": "NAME", "value": "Jim Zombek" } ]
null
[]
package com.emptytomb.dbmanager.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.emptytomb.dbmanager.dao.DaoException; import com.emptytomb.dbmanager.domain.QuestionChoice; import com.emptytomb.dbmanager.utility.ConnectionFactory; /** * The QuestionChoiceDao class is a concrete JDBC implementation of the BaseDao interface. * This class implements the JDBC persistence storage layer for the QuestionChoice domain model. * * <p><b>Note:</b> This class is implemented as a Singleton. Only one instance of this class * can exist at a time.</p> * * @author <NAME> * @version 1.0 * @since 2016-08-01 */ public class QuestionChoiceDao implements BaseDao<QuestionChoice> { private Logger logger = LoggerFactory.getLogger(QuestionChoiceDao.class); private static QuestionChoiceDao instance = null; private Connection connection = null; private static final String QUESTION_CHOICE_TABLE = "question_choice"; private static final String QUESTION_CHOICE_ID = "id"; private static final String QUESTION_CHOICE_TEXT = "text"; private static final String QUESTION_CHOICE_CORRECT_ANSWER = "correctAnswer"; private QuestionChoiceDao() { connection = ConnectionFactory.getInstance().getConnection(); } /** * This method returns the single instance of the QuestionChoiceDao object. * * @return the QuestionDao object * */ public static QuestionChoiceDao getInstance() { if (instance == null) { synchronized (QuestionChoiceDao.class) { if (instance == null) { instance = new QuestionChoiceDao(); } } } return instance; } /** * This method reads the specified question choice id record from the question_choice * table stored in MySQL and returns a QuestionChoice object. * * @param id the unique id of the question choice to return. * @return the QuestionChoice object * * @throws DaoException if a SQL Exception was encountered during processing */ @Override public QuestionChoice get(int id) throws DaoException { QuestionChoice questionChoice = null; String sql = "SELECT * FROM " + QUESTION_CHOICE_TABLE + " WHERE " + QUESTION_CHOICE_ID + " = ?;"; try (PreparedStatement pstmt = connection.prepareStatement(sql);) { pstmt.setInt(1, id); try (ResultSet resultSet = pstmt.executeQuery();) { while (resultSet.next()) { questionChoice = getQuestionChoiceFromResultSet(resultSet); } } } catch (SQLException e) { String errorMessage = this.getClass().getName() + ": getQuestionChoice() - REASON-> " + e.getMessage(); logger.error(errorMessage); e.printStackTrace(); throw new DaoException(e, errorMessage); } return questionChoice; } /** * This method reads all the question choice records from the question table stored in MySQL and * returns a list of QuestionChoice objects. * * @return List of QuestionChoice objects * * @throws DaoException if a SQL Exception was encountered during processing */ @Override public List<QuestionChoice> list() throws DaoException { ArrayList<QuestionChoice> questionChoices = new ArrayList<QuestionChoice>(); String sql = "SELECT * FROM " + QUESTION_CHOICE_TABLE + ";"; try (PreparedStatement pstmt = connection.prepareStatement(sql); ResultSet resultSet = pstmt.executeQuery();) { while (resultSet.next()) { QuestionChoice questionChoice = getQuestionChoiceFromResultSet(resultSet); questionChoices.add(questionChoice); } } catch (SQLException e) { String errorMessage = this.getClass().getName() + ": getQuestionChoices() - REASON-> " + e.getMessage(); logger.error(errorMessage); e.printStackTrace(); throw new DaoException(e, errorMessage); } return questionChoices; } /** * This method adds the specified QuestionChoice record to the question_choice table stored in MySQL. * * <p><b>Note:</b>Referential integrity foreign key constraints will be checked * prior to adding the specified organization record to the organization table * stored in MySQL. The organization record associated with this personality * must exist in the organization table stored in MySQL.</p> * * @param questionChoice the QuestionChoice object * @return the unique id of the QuestionChoice added * * @throws DaoException if a SQL Exception was encountered during processing */ @Override public int add(QuestionChoice questionChoice) throws DaoException { int autoIncKey = -1; String sql = "INSERT INTO " + QUESTION_CHOICE_TABLE + "(" + QUESTION_CHOICE_TEXT + "," + QUESTION_CHOICE_CORRECT_ANSWER + ") " + "VALUES" + "(?,?)"; try (PreparedStatement pstmt = connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);) { pstmt.setString(1,questionChoice.getText()); pstmt.setBoolean(2,questionChoice.isCorrectAnswer()); pstmt.executeUpdate(); // Get the auto-incremented key ResultSet rs = pstmt.getGeneratedKeys(); if (rs.next()) { autoIncKey = rs.getInt(1); } else { String errorMessage = this.getClass().getName() + ": addQuestionChoice() - REASON-> " + "error obtaining auto incremented key"; logger.error(errorMessage); throw new DaoException(new Exception(), errorMessage); } } catch (SQLException e) { String errorMessage = this.getClass().getName() + ": addQuestionChoice() - REASON-> " + e.getMessage(); logger.error(errorMessage); e.printStackTrace(); throw new DaoException(e, errorMessage); } return autoIncKey; } /** * This method updates the specified QuestionChoice record in the question_choice table stored in MySQL. * * @param questionChoice the QuestionChoice object * * @throws DaoException if a SQL Exception was encountered during processing */ @Override public void update(QuestionChoice questionChoice) throws DaoException { String sql = "UPDATE " + QUESTION_CHOICE_TABLE + " SET " + QUESTION_CHOICE_TEXT + "=?, " + QUESTION_CHOICE_CORRECT_ANSWER + "=? " + "WHERE " + QUESTION_CHOICE_ID + "=?;"; try (PreparedStatement pstmt = connection.prepareStatement(sql);) { pstmt.setString(1,questionChoice.getText()); pstmt.setBoolean(2,questionChoice.isCorrectAnswer()); pstmt.setInt(3,questionChoice.getQuestionChoiceId()); pstmt.executeUpdate(); } catch (SQLException e) { String errorMessage = this.getClass().getName() + ": updateQuestion() - REASON-> " + e.getMessage(); logger.error(errorMessage); e.printStackTrace(); throw new DaoException(e, errorMessage); } } /** * This method deletes the specified question choice id from the question_choice table stored in MySQL. * * <p><b>Note:</b>Referential integrity foreign key constraints will be checked * prior to deleting the specified personality record from the personality table * stored in MySQL. All commentary records in the commentary table stored in MySQL * associated with the specified personality id must have been previously deleted * prior to calling this method.</p> * * @param id the unique id of the question choice to delete. * * @throws DaoException if a SQL Exception was encountered during processing */ @Override public void delete(int id) throws DaoException { String sql = "DELETE FROM " + QUESTION_CHOICE_TABLE + " WHERE " + QUESTION_CHOICE_ID + " = ?;"; try (PreparedStatement pstmt = connection.prepareStatement(sql);) { pstmt.setInt(1, id); pstmt.execute(); } catch (SQLException e) { String errorMessage = this.getClass().getName() + ": deleteQuestionChoice() - REASON-> " + e.getMessage(); logger.error(errorMessage); e.printStackTrace(); throw new DaoException(e, errorMessage); } } private QuestionChoice getQuestionChoiceFromResultSet(ResultSet resultSet) throws SQLException { QuestionChoice questionChoice = new QuestionChoice(); questionChoice.setQuestionChoiceId(resultSet.getInt(QUESTION_CHOICE_ID)); questionChoice.setText(resultSet.getString(QUESTION_CHOICE_TEXT)); questionChoice.setCorrectAnswer(resultSet.getBoolean(QUESTION_CHOICE_CORRECT_ANSWER)); return questionChoice; } }
9,131
0.656814
0.654516
223
39.968609
31.856657
116
false
false
0
0
0
0
0
0
0.591928
false
false
12
07c450dcf7a5153b706ca3479b5d6da74a38c2b2
9,448,928,081,175
75f43675a623abff91ab5370c818fb90def997d3
/jpa-services/src/main/java/com/wci/umls/server/jpa/services/handlers/UmlsGraphResolutionHandler.java
0b515b2a26839437668fe96249f248c82a710034
[ "Apache-2.0" ]
permissive
WestCoastInformatics/UMLS-Terminology-Server
https://github.com/WestCoastInformatics/UMLS-Terminology-Server
3739f73be10e730237ea06d264466d4c7cccaafa
708f088babd3e5d16016ab9016af9fee01f2921b
refs/heads/master
2023-08-24T03:43:19.637000
2023-05-24T21:15:42
2023-05-24T21:15:42
32,935,903
18
8
Apache-2.0
false
2023-06-15T20:04:07
2015-03-26T15:33:38
2023-05-24T21:18:10
2023-06-14T23:00:18
166,149
14
8
1
Java
false
false
/** * Copyright 2016 West Coast Informatics, LLC */ package com.wci.umls.server.jpa.services.handlers; import java.util.ArrayList; import com.wci.umls.server.model.content.Atom; import com.wci.umls.server.model.content.AtomSubsetMember; import com.wci.umls.server.model.content.Concept; import com.wci.umls.server.model.content.ConceptSubsetMember; import com.wci.umls.server.model.content.Definition; import com.wci.umls.server.model.content.SemanticTypeComponent; import com.wci.umls.server.services.handlers.GraphResolutionHandler; /** * Default implementation of {@link GraphResolutionHandler}. This connects * graphs at the level at which CascadeType.ALL is used in the data model. */ public class UmlsGraphResolutionHandler extends DefaultGraphResolutionHandler { @Override public void resolve(Concept concept) throws Exception { if (concept != null) { boolean nullId = concept.getId() == null; concept.setMembers(new ArrayList<ConceptSubsetMember>(0)); // Attributes resolveAttributes(concept, nullId); // Definitions for (final Definition def : concept.getDefinitions()) { resolveDefinition(def, nullId); } // Semantic type components for (final SemanticTypeComponent sty : concept.getSemanticTypes()) { if (nullId) { sty.setId(null); } sty.getSemanticType(); resolve(sty); } // Atoms for (final Atom atom : concept.getAtoms()) { // if the concept is "new", then the atom must be too if (nullId) { atom.setId(null); } resolve(atom); } // Relationships // Default behavior -- do not return relationships, require paging calls concept.setRelationships(new ArrayList<>(0)); concept.setTreePositions(new ArrayList<>(0)); // lazy initialization of user annotations concept.getNotes().size(); concept.getLabels(); // lazy initialization of component history concept.getComponentHistory().size(); } else if (concept == null) { throw new Exception("Cannot resolve a null concept."); } } @Override public void resolve(Atom atom) throws Exception { if (atom != null) { boolean nullId = atom.getId() == null; atom.setMembers(new ArrayList<AtomSubsetMember>(0)); atom.getName(); atom.getConceptTerminologyIds().keySet(); atom.getAlternateTerminologyIds().keySet(); atom.getNotes().size(); // Attributes resolveAttributes(atom, nullId); // Definitions for (final Definition def : atom.getDefinitions()) { resolveDefinition(def, nullId); } // for UMLS view dont read atom subset members atom.setMembers(new ArrayList<>(0)); // for UMLS view don't read relationship as // these are terminology-specific rels // they can show when browsing that terminology atom.setRelationships(new ArrayList<>(0)); atom.setTreePositions(new ArrayList<>(0)); // resolve component history resolveComponentHistory(atom, nullId); } else if (atom == null) { throw new Exception("Cannot resolve a null atom."); } } }
UTF-8
Java
3,214
java
UmlsGraphResolutionHandler.java
Java
[]
null
[]
/** * Copyright 2016 West Coast Informatics, LLC */ package com.wci.umls.server.jpa.services.handlers; import java.util.ArrayList; import com.wci.umls.server.model.content.Atom; import com.wci.umls.server.model.content.AtomSubsetMember; import com.wci.umls.server.model.content.Concept; import com.wci.umls.server.model.content.ConceptSubsetMember; import com.wci.umls.server.model.content.Definition; import com.wci.umls.server.model.content.SemanticTypeComponent; import com.wci.umls.server.services.handlers.GraphResolutionHandler; /** * Default implementation of {@link GraphResolutionHandler}. This connects * graphs at the level at which CascadeType.ALL is used in the data model. */ public class UmlsGraphResolutionHandler extends DefaultGraphResolutionHandler { @Override public void resolve(Concept concept) throws Exception { if (concept != null) { boolean nullId = concept.getId() == null; concept.setMembers(new ArrayList<ConceptSubsetMember>(0)); // Attributes resolveAttributes(concept, nullId); // Definitions for (final Definition def : concept.getDefinitions()) { resolveDefinition(def, nullId); } // Semantic type components for (final SemanticTypeComponent sty : concept.getSemanticTypes()) { if (nullId) { sty.setId(null); } sty.getSemanticType(); resolve(sty); } // Atoms for (final Atom atom : concept.getAtoms()) { // if the concept is "new", then the atom must be too if (nullId) { atom.setId(null); } resolve(atom); } // Relationships // Default behavior -- do not return relationships, require paging calls concept.setRelationships(new ArrayList<>(0)); concept.setTreePositions(new ArrayList<>(0)); // lazy initialization of user annotations concept.getNotes().size(); concept.getLabels(); // lazy initialization of component history concept.getComponentHistory().size(); } else if (concept == null) { throw new Exception("Cannot resolve a null concept."); } } @Override public void resolve(Atom atom) throws Exception { if (atom != null) { boolean nullId = atom.getId() == null; atom.setMembers(new ArrayList<AtomSubsetMember>(0)); atom.getName(); atom.getConceptTerminologyIds().keySet(); atom.getAlternateTerminologyIds().keySet(); atom.getNotes().size(); // Attributes resolveAttributes(atom, nullId); // Definitions for (final Definition def : atom.getDefinitions()) { resolveDefinition(def, nullId); } // for UMLS view dont read atom subset members atom.setMembers(new ArrayList<>(0)); // for UMLS view don't read relationship as // these are terminology-specific rels // they can show when browsing that terminology atom.setRelationships(new ArrayList<>(0)); atom.setTreePositions(new ArrayList<>(0)); // resolve component history resolveComponentHistory(atom, nullId); } else if (atom == null) { throw new Exception("Cannot resolve a null atom."); } } }
3,214
0.666148
0.662726
107
29.037384
23.764391
79
false
false
0
0
0
0
0
0
0.420561
false
false
12
5d318a0e2f385899f062c1a575aff0920c1f3763
26,362,509,325,898
9d144fff1dc5b0edd8ed2d8f25164aa0a8a28004
/src/homeWork/stringManoipulation.java
96454187d51279227485a16f41ebe9698ad088fb
[]
no_license
mirshodtairov/JavaProgrammingSpring2019
https://github.com/mirshodtairov/JavaProgrammingSpring2019
d64a7cef13dc58703d87d5ffec30f896f3a280b8
dcf99c5b0d58c6a81ef8775af2bd960c4062e630
refs/heads/master
2020-05-18T10:33:44.869000
2019-07-16T18:36:16
2019-07-16T18:36:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package homeWork; import java.util.Scanner; public class stringManoipulation { public static void main(String[] args) { Scanner scan=new Scanner(System.in); System.out.println("enter the name:"); String n=scan.next(); while (n.charAt(0)!=(n.charAt(1))){ System.out.println("first and second letters != enter another name"); n=scan.next(); } System.out.println("it matches"); } }
UTF-8
Java
416
java
stringManoipulation.java
Java
[]
null
[]
package homeWork; import java.util.Scanner; public class stringManoipulation { public static void main(String[] args) { Scanner scan=new Scanner(System.in); System.out.println("enter the name:"); String n=scan.next(); while (n.charAt(0)!=(n.charAt(1))){ System.out.println("first and second letters != enter another name"); n=scan.next(); } System.out.println("it matches"); } }
416
0.663462
0.658654
22
17.954546
19.634102
73
false
false
0
0
0
0
0
0
1.681818
false
false
12
1fe40d778264eb9736d29ae1920d1bc5461bc89b
6,365,141,540,633
3731d769b4ffbdef0beab4638392115828d268f6
/src/service/Produto.java
81cd167e79ffb17b5f6927365ed1b9cf4ee07002
[]
no_license
AquilesOliveira/ClientJee
https://github.com/AquilesOliveira/ClientJee
88679ebdfb7c6894a12f7e9f6f11b94384ecff67
236a7401ed7184e1fc3cc61f858a478f4d69e56f
refs/heads/master
2020-05-18T16:10:14.963000
2014-05-09T01:01:37
2014-05-09T01:01:37
null
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 service; /** * * @author azizsault */ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import swing.annotation.GridHeader; import swing.model.DefaultModel; import swing.ui.ModelField; import api.wadl.annotation.XMLCast; import client.crud.Service; import client.exception.ValidationException; import client.request.ApacheRequest; import client.response.JSONResponse; import com.google.gson.reflect.TypeToken; /** * * @author azizsault */ @XMLCast(thisClassFrom = "models.Produto") public class Produto implements DefaultModel<Produto> { @GridHeader(name = "ID", size = 10) public Long id; @GridHeader(name = "Nome", size = 50) public String nome; @GridHeader(name = "descricao", size = 200) public String descricao; @GridHeader(name = "valor", size = 12) public double valor; @GridHeader(name = "Qtd", size = 12) public int quantidade; public static Service<Produto> service = new Service<Produto>(new ApacheRequest("http://localhost:8080/restee/api/produtos"), Produto.class, new TypeToken<List<Produto>>() { }.getType()); @Override public String toString() { return this.nome; } @Override public List<Produto> findStart() { return service.findAll(); } @Override public List<Produto> filterGrid(final String filter) { if ("".equals(filter) || filter.equals("*")) { final List<Produto> lista = service.findAll(); return lista; } final ApacheRequest apacheRequest = new ApacheRequest("http://localhost:8080/restee/api/produtos"); final String json = apacheRequest.get("/findName/" + filter); final JSONResponse<Produto> jsonResult = new JSONResponse<Produto>(json); try { final List<Produto> lista = jsonResult.getCollectionContent(new TypeToken<List<Produto>>() { }.getType()); return lista; } catch (final Exception e) { return new ArrayList<Produto>(); } } @Override public Produto findById(final Long id) { return service.findById(id); } @Override public Produto save(final Long id, final HashMap<String, Object> map) throws ValidationException { final HashMap<String, String> vo = new HashMap<String, String>(); vo.put("produto.nome", map.get("Nome").toString()); vo.put("produto.descricao", map.get("Descricao").toString()); vo.put("produto.quantidade", map.get("Quantidade").toString()); vo.put("produto.valor", map.get("Valor").toString()); return service.save(id, vo); } @Override public boolean delete(final Long id) { return service.delete(id); } @Override public ModelField getGridFields() { final ModelField gf = new ModelField(); gf.addField(this.id); gf.addField(this.nome); gf.addField(this.descricao); gf.addField(this.quantidade); gf.addField(this.valor); return gf; } @Override public ModelField getViewFields() { final ModelField ff = new ModelField(); ff.addField("Nome", this.nome); ff.addField("Descricao", this.descricao); ff.addField("Quantidade", this.quantidade); ff.addField("Valor", this.valor); return ff; } @Override public Long getId() { return this.id; } @Override public List<? extends DefaultModel> getObj(final String campo) { return null; } }
UTF-8
Java
3,272
java
Produto.java
Java
[ { "context": "he editor.\n */\npackage service;\n\n/**\n *\n * @author azizsault\n */\nimport java.util.ArrayList;\nimport java.util.", "end": 145, "score": 0.9989106059074402, "start": 136, "tag": "USERNAME", "value": "azizsault" }, { "context": ".google.gson.reflect.TypeToken;\n\n/...
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package service; /** * * @author azizsault */ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import swing.annotation.GridHeader; import swing.model.DefaultModel; import swing.ui.ModelField; import api.wadl.annotation.XMLCast; import client.crud.Service; import client.exception.ValidationException; import client.request.ApacheRequest; import client.response.JSONResponse; import com.google.gson.reflect.TypeToken; /** * * @author azizsault */ @XMLCast(thisClassFrom = "models.Produto") public class Produto implements DefaultModel<Produto> { @GridHeader(name = "ID", size = 10) public Long id; @GridHeader(name = "Nome", size = 50) public String nome; @GridHeader(name = "descricao", size = 200) public String descricao; @GridHeader(name = "valor", size = 12) public double valor; @GridHeader(name = "Qtd", size = 12) public int quantidade; public static Service<Produto> service = new Service<Produto>(new ApacheRequest("http://localhost:8080/restee/api/produtos"), Produto.class, new TypeToken<List<Produto>>() { }.getType()); @Override public String toString() { return this.nome; } @Override public List<Produto> findStart() { return service.findAll(); } @Override public List<Produto> filterGrid(final String filter) { if ("".equals(filter) || filter.equals("*")) { final List<Produto> lista = service.findAll(); return lista; } final ApacheRequest apacheRequest = new ApacheRequest("http://localhost:8080/restee/api/produtos"); final String json = apacheRequest.get("/findName/" + filter); final JSONResponse<Produto> jsonResult = new JSONResponse<Produto>(json); try { final List<Produto> lista = jsonResult.getCollectionContent(new TypeToken<List<Produto>>() { }.getType()); return lista; } catch (final Exception e) { return new ArrayList<Produto>(); } } @Override public Produto findById(final Long id) { return service.findById(id); } @Override public Produto save(final Long id, final HashMap<String, Object> map) throws ValidationException { final HashMap<String, String> vo = new HashMap<String, String>(); vo.put("produto.nome", map.get("Nome").toString()); vo.put("produto.descricao", map.get("Descricao").toString()); vo.put("produto.quantidade", map.get("Quantidade").toString()); vo.put("produto.valor", map.get("Valor").toString()); return service.save(id, vo); } @Override public boolean delete(final Long id) { return service.delete(id); } @Override public ModelField getGridFields() { final ModelField gf = new ModelField(); gf.addField(this.id); gf.addField(this.nome); gf.addField(this.descricao); gf.addField(this.quantidade); gf.addField(this.valor); return gf; } @Override public ModelField getViewFields() { final ModelField ff = new ModelField(); ff.addField("Nome", this.nome); ff.addField("Descricao", this.descricao); ff.addField("Quantidade", this.quantidade); ff.addField("Valor", this.valor); return ff; } @Override public Long getId() { return this.id; } @Override public List<? extends DefaultModel> getObj(final String campo) { return null; } }
3,272
0.712408
0.706601
132
23.787878
24.402878
141
false
false
0
0
0
0
0
0
1.55303
false
false
12
a53a0eaa7ae61f7880054460e29181d1d5d878a0
24,455,543,839,075
fd557a85c31bc4f47b4425fd3bac550173379805
/homework5/Company.java
7f3ac2fbdb2ef4101f56e330fe01ce43b4622f9d
[]
no_license
Blinky82/java-course
https://github.com/Blinky82/java-course
34cb3053e0d31fcebeb86210244c590b83248082
92d42757cf302c8873407673ee0e841607cb9084
refs/heads/master
2021-01-01T18:18:08.766000
2015-02-23T13:33:59
2015-02-23T13:33:59
27,298,381
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Random; import java.util.ArrayList; /** * Created by blinky on 14.01.15. */ public class Company { private String name; private String address; private int employee; private String web; public Company() { } public Company(String name, String address, int employee, String web) { this.name = name; this.address = address; this.employee = employee; this.web = web; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getEmployees() { return employee; } public void setEmployees(int employees) { this.employee = employees; } public String getWeb() { return web; } public void setWeb(String web) { this.web = web; } public static void main(String[] args) { ArrayList<Company> companies = new ArrayList<Company>(); companies.add(new Company("Coca Cola", "Sofia", 100, "www.cocacola.bg")); companies .add(new Company("Fanta", "Sofia", 200, "www.cocacola.bg")); companies.add(new Company("Sprite", "Sofia", 150, "www.cocacola.bg")); int maxIdx = -1; int maxEmployees=-1; for (int i = 0; i < companies.size(); i++) { if (maxEmployees < companies.get(i).getEmployee()) { maxEmployees=companies.get(i).getEmployee(); maxIdx = i; } } System.out.println("Company to remove: " + companies.get(maxIdx).getName() + " " + maxIdx); companies.remove(maxIdx); companies.add(new Company("Mercedes", "Sofia", 250, "www.cocacola.bg")); companies.add(new Company("BMW", "Sofia", 300, "www.cocacola.bg")); for (int i = 0; i < companies.size(); i++) { System.out.println("Company "+i+" " + companies.get(i).getName()); } int currMaxNameLen=-1; int maxLenNameIdx=-1; for (int i = 0; i < companies.size(); i++) { if (currMaxNameLen < companies.get(i).getName().length()) { currMaxNameLen=companies.get(i).getName().length(); maxLenNameIdx = i; } } System.out.println("Company with longest name: " + companies.get(maxLenNameIdx).getName() + " " + maxLenNameIdx); companies.set(maxLenNameIdx, new Company("Honda","Dobrich",20,"honda.bg")); for (int i = 0; i < companies.size(); i++) { System.out.println("Final companies "+i+" " + companies.get(i).getName()); } } }
UTF-8
Java
2,887
java
Company.java
Java
[ { "context": "m;\n\nimport java.util.ArrayList;\n\n/**\n * Created by blinky on 14.01.15.\n */\npublic class Company {\n\n priv", "end": 70, "score": 0.9995759725570679, "start": 64, "tag": "USERNAME", "value": "blinky" }, { "context": "\"));\n companies.add(new Company(\"B...
null
[]
package Random; import java.util.ArrayList; /** * Created by blinky on 14.01.15. */ public class Company { private String name; private String address; private int employee; private String web; public Company() { } public Company(String name, String address, int employee, String web) { this.name = name; this.address = address; this.employee = employee; this.web = web; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getEmployees() { return employee; } public void setEmployees(int employees) { this.employee = employees; } public String getWeb() { return web; } public void setWeb(String web) { this.web = web; } public static void main(String[] args) { ArrayList<Company> companies = new ArrayList<Company>(); companies.add(new Company("Coca Cola", "Sofia", 100, "www.cocacola.bg")); companies .add(new Company("Fanta", "Sofia", 200, "www.cocacola.bg")); companies.add(new Company("Sprite", "Sofia", 150, "www.cocacola.bg")); int maxIdx = -1; int maxEmployees=-1; for (int i = 0; i < companies.size(); i++) { if (maxEmployees < companies.get(i).getEmployee()) { maxEmployees=companies.get(i).getEmployee(); maxIdx = i; } } System.out.println("Company to remove: " + companies.get(maxIdx).getName() + " " + maxIdx); companies.remove(maxIdx); companies.add(new Company("Mercedes", "Sofia", 250, "www.cocacola.bg")); companies.add(new Company("BMW", "Sofia", 300, "www.cocacola.bg")); for (int i = 0; i < companies.size(); i++) { System.out.println("Company "+i+" " + companies.get(i).getName()); } int currMaxNameLen=-1; int maxLenNameIdx=-1; for (int i = 0; i < companies.size(); i++) { if (currMaxNameLen < companies.get(i).getName().length()) { currMaxNameLen=companies.get(i).getName().length(); maxLenNameIdx = i; } } System.out.println("Company with longest name: " + companies.get(maxLenNameIdx).getName() + " " + maxLenNameIdx); companies.set(maxLenNameIdx, new Company("Honda","Dobrich",20,"honda.bg")); for (int i = 0; i < companies.size(); i++) { System.out.println("Final companies "+i+" " + companies.get(i).getName()); } } }
2,887
0.536543
0.525805
105
26.485714
23.18091
83
false
false
0
0
0
0
0
0
0.647619
false
false
12
c9806f4260ef2e0431b95bb96b4eeba5f969a55d
395,137,056,643
11e9197bc4df7b5572f98a846075723c24a17caf
/src/test/java/com/avalontm/leetcode/_198HouseRobber/SolutionTest.java
5cbc0990ff0d5897e31df14cda00fa09e09bfe7c
[ "MIT" ]
permissive
SemiHum/leetCode
https://github.com/SemiHum/leetCode
5b9945fabdb72e3076ddc7a912b011e7781b1af9
966289981ba1f52fcca4d70f1e88e5bfc3e8d327
refs/heads/master
2021-01-22T09:47:28.526000
2015-07-17T06:25:50
2015-07-17T06:25:50
38,348,062
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.avalontm.leetcode._198HouseRobber; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * 198. House Robber * You are a professional robber planning to rob houses along a street. * Each house has a certain amount of money stashed, the only constraint stopping you from robbing * each of them is that adjacent houses have security system connected and it will automatically * contact the police if two adjacent houses were broken into on the same night. * <p/> * Given a list of non-negative integers representing the amount of money of each house, determine * the maximum amount of money you can rob tonight without alerting the police. * Created by jiang_s on 2015/7/2. */ public class SolutionTest { Solution solution; @Before public void setUp() throws Exception { solution = new Solution(); } @Test public void test1House() throws Exception { // Assert.assertEquals(12, solution.rob(new int[]{12})); // Assert.assertEquals(3, solution.rob(new int[]{1, 3, 1})); // Assert.assertEquals(4, solution.rob(new int[]{2, 3, 2})); // Assert.assertEquals(3, solution.rob(new int[]{3, 1})); // Assert.assertEquals(0, solution.rob(new int[]{0, 0, 0})); Assert.assertEquals(0, solution.rob(new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})); } }
UTF-8
Java
1,626
java
SolutionTest.java
Java
[ { "context": "tonight without alerting the police.\n * Created by jiang_s on 2015/7/2.\n */\npublic class SolutionTest {\n ", "end": 704, "score": 0.9997166395187378, "start": 697, "tag": "USERNAME", "value": "jiang_s" } ]
null
[]
package com.avalontm.leetcode._198HouseRobber; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * 198. House Robber * You are a professional robber planning to rob houses along a street. * Each house has a certain amount of money stashed, the only constraint stopping you from robbing * each of them is that adjacent houses have security system connected and it will automatically * contact the police if two adjacent houses were broken into on the same night. * <p/> * Given a list of non-negative integers representing the amount of money of each house, determine * the maximum amount of money you can rob tonight without alerting the police. * Created by jiang_s on 2015/7/2. */ public class SolutionTest { Solution solution; @Before public void setUp() throws Exception { solution = new Solution(); } @Test public void test1House() throws Exception { // Assert.assertEquals(12, solution.rob(new int[]{12})); // Assert.assertEquals(3, solution.rob(new int[]{1, 3, 1})); // Assert.assertEquals(4, solution.rob(new int[]{2, 3, 2})); // Assert.assertEquals(3, solution.rob(new int[]{3, 1})); // Assert.assertEquals(0, solution.rob(new int[]{0, 0, 0})); Assert.assertEquals(0, solution.rob(new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})); } }
1,626
0.626076
0.54428
35
45.485714
61.859459
356
false
false
0
0
0
0
0
0
3.6
false
false
12
f77e03fc92241d76bdb6184d4da45dfb96e6678e
26,190,710,639,301
4b38f85c97d478625488539df602e6530f1e1357
/finance/service/src/main/java/cn/geekhalo/webtech/dao/UserRoleMapper.java
f96f5a4d82ca0a137abc9c9ffba6c0e7071876a6
[ "Apache-2.0" ]
permissive
SmartGim/geekhalofinance
https://github.com/SmartGim/geekhalofinance
6efb1a7663705c06c9796f3855e56c85381f0bed
8542b6e109c0e58b78253eec523ab34cb1eeca7d
refs/heads/master
2019-08-20T03:19:00.222000
2017-02-22T14:43:52
2017-02-22T14:43:52
67,605,595
5
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.geekhalo.webtech.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.geekhalo.webtech.pojo.UserRole; public interface UserRoleMapper { int deleteByPrimaryKey(String id); int insert(UserRole record); int insertSelective(UserRole record); UserRole selectByPrimaryKey(String id); int updateByPrimaryKeySelective(UserRole record); int updateByPrimaryKey(UserRole record); List<UserRole> getAllRoles(); List<String> getRolesByUserId(String id); void grantUserRoles(@Param(value="id") String id,@Param(value="list")List<UserRole> roles); }
UTF-8
Java
639
java
UserRoleMapper.java
Java
[]
null
[]
package cn.geekhalo.webtech.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.geekhalo.webtech.pojo.UserRole; public interface UserRoleMapper { int deleteByPrimaryKey(String id); int insert(UserRole record); int insertSelective(UserRole record); UserRole selectByPrimaryKey(String id); int updateByPrimaryKeySelective(UserRole record); int updateByPrimaryKey(UserRole record); List<UserRole> getAllRoles(); List<String> getRolesByUserId(String id); void grantUserRoles(@Param(value="id") String id,@Param(value="list")List<UserRole> roles); }
639
0.733959
0.733959
27
21.74074
23.755846
92
false
false
0
0
0
0
0
0
0.62963
false
false
12
41e0499147611446df98e1b64e655a4d4b217a5e
9,156,870,334,753
366bc1e3848f2291ffcb270c36d71b44df1fcec1
/app/src/main/java/smartassist/appreciate/be/smartassist/model/ChatConversation.java
f14b6e6b085baefc11e4daed70ded6fb764d2ab9
[]
no_license
henridev/City-Assistant
https://github.com/henridev/City-Assistant
0e208cacd9e1180500b60bdf3bc4a629ac906bfb
841804fed77f6d2f33ef5fe81f178eff97eb1fe5
refs/heads/master
2021-06-10T13:12:13.057000
2016-11-08T09:45:32
2016-11-08T09:45:32
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package smartassist.appreciate.be.smartassist.model; import android.database.Cursor; import java.util.ArrayList; import java.util.List; import smartassist.appreciate.be.smartassist.database.ChatConversationTable; import smartassist.appreciate.be.smartassist.database.ChatMessageTable; /** * Created by Inneke De Clippel on 8/09/2016. */ public class ChatConversation { private int conversationId; private String lastMessage; private long lastMessageSentAt; private boolean lastMessageRead; private List<ChatSender> senders; public int getConversationId() { return conversationId; } public String getLastMessage() { return lastMessage; } public long getLastMessageSentAt() { return lastMessageSentAt; } public boolean isLastMessageRead() { return lastMessageRead; } public List<ChatSender> getSenders() { return senders; } public String getParticipantNames(int ownContactId) { StringBuilder sb = new StringBuilder(); if(this.senders != null) { for(ChatSender sender : this.senders) { if(sender.getContactId() != ownContactId) { if(sb.length() > 0) { sb.append(", "); } sb.append(sender.getName()); } } } //TODO show a default value 'You are the only one left' when sb.length() == 0 return sb.toString(); } public boolean isGroupChat() { return this.senders != null && this.senders.size() > 2; } public String getSenderPhoto(int ownContactId) { if(this.senders != null) { for(ChatSender sender : this.senders) { if(sender.getContactId() != ownContactId) { return sender.getPhoto(); } } } return null; } public void addSender(ChatSender sender) { if(this.senders == null) { this.senders = new ArrayList<>(); } this.senders.add(sender); } public void clearSenders() { if(this.senders != null) { this.senders.clear(); } } public static List<ChatConversation> constructListFromCursor(Cursor cursor) { List<ChatConversation> conversations = new ArrayList<>(); if(cursor != null && cursor.moveToFirst()) { do { conversations.add(ChatConversation.constructFromCursor(cursor)); } while (cursor.moveToNext()); } return conversations; } public static ChatConversation constructFromCursor(Cursor cursor) { ChatConversation conversation = new ChatConversation(); conversation.conversationId = cursor.getInt(cursor.getColumnIndex(ChatConversationTable.COLUMN_CONVERSATION_ID_FULL)); conversation.lastMessage = cursor.getString(cursor.getColumnIndex(ChatMessageTable.COLUMN_MESSAGE_FULL)); conversation.lastMessageSentAt = cursor.getLong(cursor.getColumnIndex(ChatMessageTable.COLUMN_SENT_AT_FULL)); conversation.lastMessageRead = cursor.getInt(cursor.getColumnIndex(ChatMessageTable.COLUMN_READ_FULL)) == 1; return conversation; } }
UTF-8
Java
3,461
java
ChatConversation.java
Java
[ { "context": "sist.database.ChatMessageTable;\n\n/**\n * Created by Inneke De Clippel on 8/09/2016.\n */\npublic class ChatConversation\n{", "end": 324, "score": 0.9998899698257446, "start": 307, "tag": "NAME", "value": "Inneke De Clippel" } ]
null
[]
package smartassist.appreciate.be.smartassist.model; import android.database.Cursor; import java.util.ArrayList; import java.util.List; import smartassist.appreciate.be.smartassist.database.ChatConversationTable; import smartassist.appreciate.be.smartassist.database.ChatMessageTable; /** * Created by <NAME> on 8/09/2016. */ public class ChatConversation { private int conversationId; private String lastMessage; private long lastMessageSentAt; private boolean lastMessageRead; private List<ChatSender> senders; public int getConversationId() { return conversationId; } public String getLastMessage() { return lastMessage; } public long getLastMessageSentAt() { return lastMessageSentAt; } public boolean isLastMessageRead() { return lastMessageRead; } public List<ChatSender> getSenders() { return senders; } public String getParticipantNames(int ownContactId) { StringBuilder sb = new StringBuilder(); if(this.senders != null) { for(ChatSender sender : this.senders) { if(sender.getContactId() != ownContactId) { if(sb.length() > 0) { sb.append(", "); } sb.append(sender.getName()); } } } //TODO show a default value 'You are the only one left' when sb.length() == 0 return sb.toString(); } public boolean isGroupChat() { return this.senders != null && this.senders.size() > 2; } public String getSenderPhoto(int ownContactId) { if(this.senders != null) { for(ChatSender sender : this.senders) { if(sender.getContactId() != ownContactId) { return sender.getPhoto(); } } } return null; } public void addSender(ChatSender sender) { if(this.senders == null) { this.senders = new ArrayList<>(); } this.senders.add(sender); } public void clearSenders() { if(this.senders != null) { this.senders.clear(); } } public static List<ChatConversation> constructListFromCursor(Cursor cursor) { List<ChatConversation> conversations = new ArrayList<>(); if(cursor != null && cursor.moveToFirst()) { do { conversations.add(ChatConversation.constructFromCursor(cursor)); } while (cursor.moveToNext()); } return conversations; } public static ChatConversation constructFromCursor(Cursor cursor) { ChatConversation conversation = new ChatConversation(); conversation.conversationId = cursor.getInt(cursor.getColumnIndex(ChatConversationTable.COLUMN_CONVERSATION_ID_FULL)); conversation.lastMessage = cursor.getString(cursor.getColumnIndex(ChatMessageTable.COLUMN_MESSAGE_FULL)); conversation.lastMessageSentAt = cursor.getLong(cursor.getColumnIndex(ChatMessageTable.COLUMN_SENT_AT_FULL)); conversation.lastMessageRead = cursor.getInt(cursor.getColumnIndex(ChatMessageTable.COLUMN_READ_FULL)) == 1; return conversation; } }
3,450
0.59087
0.587691
137
24.262774
26.690786
126
false
false
0
0
0
0
0
0
0.270073
false
false
12
8f78499b19e07b2b81c87bbc92b116499856fa14
8,151,847,978,753
4cb863a1bfd30598db156050bd8fc1f92c4564be
/src/com/goffity/demo/test/sendobjectbwtact/MainActivity.java
3ea6459900ee088ce621553f770809bec162d4a7
[]
no_license
goffity/TestSendObjectBetweenActivity
https://github.com/goffity/TestSendObjectBetweenActivity
da503d9cb5700cc3461e2e01153e234d5addd518
7ce909d0aceedc9f3fb3b1a283feb21fe5a1348d
refs/heads/master
2021-01-02T09:33:41.971000
2013-08-01T14:57:44
2013-08-01T14:57:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.goffity.demo.test.sendobjectbwtact; import com.goffity.demo.test.sendobjectbwtact.object.ParcelableObject; import com.goffity.demo.test.sendobjectbwtact.object.SerializableObject; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = (Button) findViewById(R.id.button1); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { SerializableObject object = new SerializableObject(); object.setName("Name from Serail obj."); object.setLastname("lastname from Serail obj."); Bundle bundle = new Bundle(); Intent intent = new Intent(); bundle.putSerializable("name", object); intent.putExtras(bundle); intent.setClass(MainActivity.this, ReceiveActivity.class); startActivity(intent); } }); Button button2 = (Button) findViewById(R.id.button2); button2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ParcelableObject object = new ParcelableObject(); object.setName("First Name"); object.setLastname("lastName"); Intent intent = new Intent(MainActivity.this, ReceiveActivity.class); intent.putExtra("parcel", object); startActivity(intent); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
UTF-8
Java
1,806
java
MainActivity.java
Java
[ { "context": "ect = new ParcelableObject();\n\t\t\t\tobject.setName(\"First Name\");\n\n\t\t\t\tobject.setLastname(\"lastName\");\n\n\t\t\t\tInte", "end": 1397, "score": 0.8535394668579102, "start": 1387, "tag": "NAME", "value": "First Name" }, { "context": "t.setName(\"First Name\")...
null
[]
package com.goffity.demo.test.sendobjectbwtact; import com.goffity.demo.test.sendobjectbwtact.object.ParcelableObject; import com.goffity.demo.test.sendobjectbwtact.object.SerializableObject; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = (Button) findViewById(R.id.button1); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { SerializableObject object = new SerializableObject(); object.setName("Name from Serail obj."); object.setLastname("lastname from Serail obj."); Bundle bundle = new Bundle(); Intent intent = new Intent(); bundle.putSerializable("name", object); intent.putExtras(bundle); intent.setClass(MainActivity.this, ReceiveActivity.class); startActivity(intent); } }); Button button2 = (Button) findViewById(R.id.button2); button2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ParcelableObject object = new ParcelableObject(); object.setName("<NAME>"); object.setLastname("lastName"); Intent intent = new Intent(MainActivity.this, ReceiveActivity.class); intent.putExtra("parcel", object); startActivity(intent); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
1,802
0.739203
0.736988
71
24.436619
22.389467
74
false
false
0
0
0
0
0
0
2.12676
false
false
12
0ec2cb656e471cb978393667f9e337da2ae971d1
8,151,847,976,344
2165fd290492da9ade8d28e0b7a49634022e9c49
/SIAP/src/main/java/com/ryuseicode/siap/repository/admin/intf/IUserDataAdministrativeUnitRepository.java
7d9b1bad79507112d18b9983ac21fee4ecd0950d
[]
no_license
RicardoSanchezRyuseiCode/SIAP
https://github.com/RicardoSanchezRyuseiCode/SIAP
d4fd35f303ee9a86b5c62142bf0c6892b87fd867
47ceadd6318df67071479747d9d592f6f4583d79
refs/heads/master
2021-06-26T15:46:13.768000
2019-12-26T17:05:37
2019-12-26T17:05:37
227,230,920
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ryuseicode.siap.repository.admin.intf; import java.util.List; import com.ryuseicode.siap.entity.admin.UserDataAdministrativeUnit; /** * @name IUserDataAdministrativeUnitRepository * {@summary Interface to define the behavior of IUserDataAdminitrativeUnitRepository } * @author Ricardo Sanchez Romero (ricardo.sanchez@ryuseicode.com) * @since Nov 27, 2019 */ public interface IUserDataAdministrativeUnitRepository { /** * @name GetByIds * {@summary Method to get UserData AdministrativeUnit relation by ids} * @param userDataId * @param administrativeUnitId * @return UserDataAdministrativeUnit */ UserDataAdministrativeUnit GetByIds(int userDataId, int administrativeUnitId); /** * @name GetByAdministrativeUnitId * @param administrativeUnitId * @return Collection of UserAdministrativeUnit */ List<UserDataAdministrativeUnit> GetByAdministrativeUnitId(int administrativeUnitId); /** * @name Save * {@summary Method to save UserDataAdministrativeUnit} * @param userDataRole */ int Save(UserDataAdministrativeUnit userDataAdministrativeUnit); /** * @name Delete * {@summary Method to delete administrativeUnit of user} * @param userDataId * @return */ int Delete(int userDataId); /** * @name Delete * {@summary Method to delete UserDataAdministrativeUnit} * @param userDataId * @param administrativeUnitId */ int Delete(int userDataId, int administrativeUnitId); }
UTF-8
Java
1,491
java
IUserDataAdministrativeUnitRepository.java
Java
[ { "context": "IUserDataAdminitrativeUnitRepository }\r\n * @author Ricardo Sanchez Romero (ricardo.sanchez@ryuseicode.com)\r\n * @since Nov 2", "end": 326, "score": 0.9998839497566223, "start": 304, "tag": "NAME", "value": "Ricardo Sanchez Romero" }, { "context": "tRepository }\r\n *...
null
[]
package com.ryuseicode.siap.repository.admin.intf; import java.util.List; import com.ryuseicode.siap.entity.admin.UserDataAdministrativeUnit; /** * @name IUserDataAdministrativeUnitRepository * {@summary Interface to define the behavior of IUserDataAdminitrativeUnitRepository } * @author <NAME> (<EMAIL>) * @since Nov 27, 2019 */ public interface IUserDataAdministrativeUnitRepository { /** * @name GetByIds * {@summary Method to get UserData AdministrativeUnit relation by ids} * @param userDataId * @param administrativeUnitId * @return UserDataAdministrativeUnit */ UserDataAdministrativeUnit GetByIds(int userDataId, int administrativeUnitId); /** * @name GetByAdministrativeUnitId * @param administrativeUnitId * @return Collection of UserAdministrativeUnit */ List<UserDataAdministrativeUnit> GetByAdministrativeUnitId(int administrativeUnitId); /** * @name Save * {@summary Method to save UserDataAdministrativeUnit} * @param userDataRole */ int Save(UserDataAdministrativeUnit userDataAdministrativeUnit); /** * @name Delete * {@summary Method to delete administrativeUnit of user} * @param userDataId * @return */ int Delete(int userDataId); /** * @name Delete * {@summary Method to delete UserDataAdministrativeUnit} * @param userDataId * @param administrativeUnitId */ int Delete(int userDataId, int administrativeUnitId); }
1,452
0.741784
0.73776
48
29.0625
25.964243
87
false
false
0
0
0
0
0
0
0.9375
false
false
12
1e3d481feb60a709a237c95b842650d6eff59121
9,655,086,505,541
de71b3ff9ed63075e67e93e2f8e34098cb0ddd11
/doradus-server/src/main/java/com/dell/doradus/search/iterator/AllIterable.java
58955d8ff1d389a1bb4e8d624a96a88862d66398
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
gaurav46/Doradus
https://github.com/gaurav46/Doradus
c88adce502f109ad615f895a6915fe8e6a67315b
a2646c47e2c7b7a167dc3a1123e53e3e8775a047
refs/heads/master
2022-12-21T22:16:03.971000
2015-08-15T05:22:28
2015-08-15T05:22:28
40,792,129
1
0
Apache-2.0
true
2022-12-14T20:26:11
2015-08-15T23:44:10
2017-08-18T19:18:58
2022-12-14T20:26:08
176,740
0
0
2
Java
false
false
/* * Copyright (C) 2014 Dell, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dell.doradus.search.iterator; import java.util.Iterator; import java.util.List; import com.dell.doradus.common.TableDefinition; import com.dell.doradus.core.ObjectID; import com.dell.doradus.fieldanalyzer.FieldAnalyzer; public class AllIterable implements Iterable<ObjectID> { private TableDefinition m_table; private List<Integer> m_shards; private ObjectID m_continuation; private boolean m_inclusive; public AllIterable(TableDefinition table, List<Integer> shards, ObjectID continuation, boolean inclusive) { m_table = table; m_shards = shards; m_continuation = continuation; m_inclusive = inclusive; } @Override public Iterator<ObjectID> iterator() { TermsIterable te = new TermsIterable(m_table, m_shards, m_continuation, m_inclusive); te.add(FieldAnalyzer.makeAllKey()); return te.iterator(); } }
UTF-8
Java
1,510
java
AllIterable.java
Java
[]
null
[]
/* * Copyright (C) 2014 Dell, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dell.doradus.search.iterator; import java.util.Iterator; import java.util.List; import com.dell.doradus.common.TableDefinition; import com.dell.doradus.core.ObjectID; import com.dell.doradus.fieldanalyzer.FieldAnalyzer; public class AllIterable implements Iterable<ObjectID> { private TableDefinition m_table; private List<Integer> m_shards; private ObjectID m_continuation; private boolean m_inclusive; public AllIterable(TableDefinition table, List<Integer> shards, ObjectID continuation, boolean inclusive) { m_table = table; m_shards = shards; m_continuation = continuation; m_inclusive = inclusive; } @Override public Iterator<ObjectID> iterator() { TermsIterable te = new TermsIterable(m_table, m_shards, m_continuation, m_inclusive); te.add(FieldAnalyzer.makeAllKey()); return te.iterator(); } }
1,510
0.722517
0.717219
44
32.31818
27.346075
111
false
false
0
0
0
0
0
0
1.022727
false
false
12
51badbbb65f7f6d61c149f2fd3e7ff84f44e7584
28,183,575,407,240
a1923b24426e2de5b27926d7f41abea691330566
/app/src/main/java/com/sanron/sunweather/activities/MainActivity.java
74a13488dfd337239e6f6cb827250bc8fb683ce5
[]
no_license
gzxg1234/SunWeather
https://github.com/gzxg1234/SunWeather
726f0ce7788fb597bdaff59a26d7db7d731c87ad
95ff421b22c39fdc29963dea505f8f1bb98159bf
refs/heads/master
2020-12-10T07:51:29.352000
2016-08-13T11:31:17
2016-08-13T11:31:17
53,301,864
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sanron.sunweather.activities; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentManager.OnBackStackChangedListener; import android.support.v4.app.FragmentTransaction; import android.view.Gravity; import android.view.View; import android.widget.Toast; import com.sanron.sunweather.R; import com.sanron.sunweather.activities.fragment.AboveFrag; import com.sanron.sunweather.activities.fragment.BaseFragment; import com.sanron.sunweather.activities.fragment.ExtrasFrag; import com.sanron.sunweather.activities.fragment.LifeIndexFrag; import com.sanron.sunweather.activities.fragment.MenuFrag; import com.sanron.sunweather.common.CityProvider; import com.sanron.sunweather.engine.AppConfig; import com.sanron.sunweather.engine.CacheManager; import com.sanron.sunweather.engine.LocationProvider; import com.sanron.sunweather.engine.LocationProvider.OnLocationListener; import com.sanron.sunweather.engine.WeatherProvider; import com.sanron.sunweather.engine.WeatherProvider.OnGetWeatherListener; import com.sanron.sunweather.entity.City; import com.sanron.sunweather.entity.Weather; import com.sanron.sunweather.entity.WeatherData; import com.sanron.sunweather.event.AboveEvent; import com.sanron.sunweather.event.CityEvent; import com.sanron.sunweather.utils.DateUtils; import com.sanron.sunweather.utils.NetUtils; import com.sanron.sunweather.view.RotateView; import com.sanron.sunweather.view.v4.DrawerLayout; import com.sanron.sunweather.view.v4.DrawerLayout.DrawerListener; import com.umeng.update.UmengUpdateAgent; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Map; import de.greenrobot.event.EventBus; public class MainActivity extends FragmentActivity { private AppConfig config; private DrawerLayout drawerLayout; private View contentView; private View menuView; private FragmentManager fm; private AboveFrag aboveFrag; private MenuFrag menuFrag; private EventBus eventBus; public static final String TAG_ABOVE = "above"; public static final String TAG_MENU = "menu"; public static final String TAG_EXTRAS = "extras"; public static final String TAG_LIFE_INDEX = "lifeindex"; private Map<String, WeatherData> weatherDatas; private int currentCityPosition = 0; //当前显示城市的位置 public static final int REQUEST_ADD_CITY = 0x110; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); UmengUpdateAgent.update(getApplicationContext()); eventBus = EventBus.getDefault(); eventBus.register(this); initView(); //设置view initData(); //读取配置和缓存 initFragment(); //设置fragment initConfig(); // } private void initView() { contentView = findViewById(R.id.content); menuView = findViewById(R.id.menu_container); drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); drawerLayout.setDrawerListener(new DrawerListener() { @Override public void onDrawerStateChanged(int newState) { } @Override public void onDrawerOpened(View drawerView) { fm.beginTransaction() .add(R.id.menu_container, menuFrag, TAG_MENU) .commit(); } @Override public void onDrawerClosed(View drawerView) { fm.beginTransaction() .remove(menuFrag) .commit(); } @Override public void onDrawerSlide(View drawerView, float slideOffset) { //滑动菜单时滚动主内容 int x = (int) (slideOffset * menuView.getMeasuredWidth()); contentView.scrollTo(x, 0); } }); } private void initData() { CityProvider.init(this); config = AppConfig.getInstance(this); weatherDatas = CacheManager.getWeatherDatas(this, config.getCities()); } private void initFragment() { fm = getSupportFragmentManager(); aboveFrag = (AboveFrag) fm.findFragmentByTag(TAG_ABOVE); if(aboveFrag==null) { aboveFrag = new AboveFrag(); fm.beginTransaction(). add(R.id.fragment_container_above, aboveFrag, TAG_ABOVE) .commit(); } menuFrag = new MenuFrag(); menuFrag.setWeatherDatas(weatherDatas); menuFrag.setCities(config.getCities()); if (config.getCities().size() != 0) { WeatherData curWeatherData = weatherDatas.get(config.getCity(currentCityPosition)); aboveFrag.setWeatherData(curWeatherData); } fm.addOnBackStackChangedListener(new OnBackStackChangedListener() { @Override public void onBackStackChanged() { //fragment回退栈空时 if (fm.getBackStackEntryCount() == 0) { aboveFrag.setCenterVisiable(true); aboveFrag.setTopVisiable(true); aboveFrag.setRotateViewState(RotateView.STATE_UP); } } }); } private void initConfig() { boolean netWorkEnable = NetUtils.checkNetwork(this); if (config.isLocation()) { if (!netWorkEnable) { aboveFrag.setStateText("无可用网络"); } else { //有网络 locationWeather(); } } if (netWorkEnable) { final List<String> cities = config.getCities(); switch (config.getUpdatePolicy()) { case AppConfig.UPDATE_ALWAYS: { for (int i = 0; i < cities.size(); i++) { if (config.isLocationPrimaryCity() && i == 0) { continue; } WeatherProvider.getInstance().getWeahterData(CityProvider.findByName(cities.get(i)), getWeatherListener); } } break; case AppConfig.UPDATE_AUTO: { for (int i = 0; i < cities.size(); i++) { if (config.isLocationPrimaryCity() && i == 0) { continue; } WeatherData data = weatherDatas.get(cities.get(i)); if (data == null || (int) ((System.currentTimeMillis() - data.getInstantWeather().getTime().getTime()) / 1000 / 60) > 10) { //数据是半小时前的 就更新 WeatherProvider.getInstance().getWeahterData(CityProvider.findByName(config.getCity(i)), getWeatherListener); } } } break; } } } //定位 private void locationWeather() { aboveFrag.setStateText("获取位置 "); LocationProvider.getInstance(this).requestLocation(new OnLocationListener() { @Override public void onLocationSuccess(final City city) { aboveFrag.setStateText("定位到 " + city.getName()); config.setPrimaryCity(city.getName()); config.setLocationPrimaryCity(true); WeatherProvider.getInstance().getWeahterData(city, getWeatherListener); } @Override public void onLocationFailed() { aboveFrag.setStateText("定位失败"); } }); } public void onEventMainThread(AboveEvent event) { switch (event.getType()) { case AboveEvent.TYPE_TOP_MENU_CLICK: { //显示/隐藏侧滑菜单 if (drawerLayout.isDrawerOpen(Gravity.RIGHT)) { drawerLayout.closeDrawer(Gravity.RIGHT); } else { drawerLayout.openDrawer(Gravity.RIGHT); } } break; case AboveEvent.TYPE_BOTTOM_STATE_CHANGE: { int state = (Integer) event.getObj(); if (state == RotateView.STATE_UP) { clearFragmentBackStack(); } else if (state == RotateView.STATE_DOWN) { switchFragment(TAG_LIFE_INDEX); } } break; case AboveEvent.TYPE_CENTER_CLICK: { //显示空气环境等额外信息 switchFragment(TAG_EXTRAS); } break; } } public void onEventMainThread(CityEvent event) { int position = event.getPosition(); switch (event.getType()) { case CityEvent.TYPE_SELECT: { if (currentCityPosition == position) return; currentCityPosition = position; refreshFragments(); } break; case CityEvent.TYPE_DEL: { String city = config.getCity(position); config.delCity(city); weatherDatas.remove(city); if (position <= currentCityPosition) { currentCityPosition--; } refreshFragments(); } break; case CityEvent.TYPE_REFRESH: { if (config.isLocationPrimaryCity() && position == 0) { locationWeather(); return; } String cityName = config.getCity(position); City city = CityProvider.findByName(cityName); WeatherProvider.getInstance().getWeahterData(city, getWeatherListener); } break; case CityEvent.TYPE_PRIMARY: { if (config.isLocation() && config.isLocationPrimaryCity()) { //当前主城市为定位的,不能更改主城市 Toast.makeText(this, "当前开启了自动定位,应用将自动把您的位置设为主城市", Toast.LENGTH_SHORT).show(); return; } config.setPrimaryCity(config.getCity(position)); refreshFragments(); } break; case CityEvent.TYPE_ADD: { Intent intent = new Intent(this, AddCityActivity.class); startActivityForResult(intent, REQUEST_ADD_CITY); } break; } } /** * 清空fragment回退栈 */ private void clearFragmentBackStack() { while (fm.getBackStackEntryCount() > 0) { fm.popBackStackImmediate(); } } /** * 切换fragment */ public void switchFragment(String tag) { FragmentTransaction transaction = fm.beginTransaction(); BaseFragment baseFragment = null; transaction.setCustomAnimations( R.anim.slide_up_in, R.anim.slide_down_out, R.anim.slide_up_in, R.anim.slide_down_out); if (TAG_EXTRAS.equals(tag)) { baseFragment = new ExtrasFrag(); aboveFrag.setRotateViewState(RotateView.STATE_HIDE); } else if (TAG_LIFE_INDEX.equals(tag)) { baseFragment = new LifeIndexFrag(); aboveFrag.setTopVisiable(false); aboveFrag.setRotateViewState(RotateView.STATE_DOWN); } aboveFrag.setCenterVisiable(false); baseFragment.setWeatherData(weatherDatas.get(config.getCity(currentCityPosition))); transaction.add(R.id.fragment_container_behind, baseFragment, tag); transaction.addToBackStack(null); transaction.commitAllowingStateLoss(); } /** * 所有fragment刷新视图 */ private void refreshFragments() { List<Fragment> fragments = fm.getFragments(); String cityName = config.getCity(currentCityPosition); WeatherData weatherData = weatherDatas.get(cityName); for (Fragment frag : fragments) { if (frag == null) continue; ((BaseFragment) frag).setWeatherData(weatherData); ((BaseFragment) frag).refreshViews(); } } private OnGetWeatherListener getWeatherListener = new OnGetWeatherListener() { @Override public void onSuccess(WeatherData weatherData) { //缓存数据 Collections.sort(weatherData.getWeathers(), new Comparator<Weather>() { @Override public int compare(Weather lhs, Weather rhs) { return lhs.getDate().compareTo(rhs.getDate()); } }); WeatherData data = weatherDatas.get(weatherData.getCity()); if (data != null) { //把前一天的天气数据保存起来 Weather yestadayWeather = data.getWeatherByDay( DateUtils.addDate(new Date(), -1)); if (yestadayWeather != null) { weatherData.getWeathers().add(0, yestadayWeather); } } CacheManager.saveWeatherData(MainActivity.this, weatherData); weatherDatas.put(weatherData.getCity(), weatherData); refreshFragments(); } @Override public void onError(City city, String error) { if (city.getName().equals(config.getCity(currentCityPosition))) { aboveFrag.setStateText(error); } } @Override public void onStart(City city) { if (city.getName().equals(config.getCity(currentCityPosition))) { aboveFrag.setStateText("请求数据"); } } }; @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case MenuFrag.REQUEST_ADD_CITY: { if (resultCode == Activity.RESULT_OK) { //添加城市 City newCity = (City) data.getSerializableExtra("newCity"); config.addCity(newCity.getName()); WeatherProvider.getInstance().getWeahterData(newCity, getWeatherListener); refreshFragments(); } } break; } } @Override protected void onDestroy() { eventBus.unregister(this); super.onDestroy(); } @Override public void onBackPressed() { if (drawerLayout.isDrawerOpen(Gravity.RIGHT)) { drawerLayout.closeDrawer(Gravity.RIGHT); return; } super.onBackPressed(); } }
UTF-8
Java
15,172
java
MainActivity.java
Java
[]
null
[]
package com.sanron.sunweather.activities; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentManager.OnBackStackChangedListener; import android.support.v4.app.FragmentTransaction; import android.view.Gravity; import android.view.View; import android.widget.Toast; import com.sanron.sunweather.R; import com.sanron.sunweather.activities.fragment.AboveFrag; import com.sanron.sunweather.activities.fragment.BaseFragment; import com.sanron.sunweather.activities.fragment.ExtrasFrag; import com.sanron.sunweather.activities.fragment.LifeIndexFrag; import com.sanron.sunweather.activities.fragment.MenuFrag; import com.sanron.sunweather.common.CityProvider; import com.sanron.sunweather.engine.AppConfig; import com.sanron.sunweather.engine.CacheManager; import com.sanron.sunweather.engine.LocationProvider; import com.sanron.sunweather.engine.LocationProvider.OnLocationListener; import com.sanron.sunweather.engine.WeatherProvider; import com.sanron.sunweather.engine.WeatherProvider.OnGetWeatherListener; import com.sanron.sunweather.entity.City; import com.sanron.sunweather.entity.Weather; import com.sanron.sunweather.entity.WeatherData; import com.sanron.sunweather.event.AboveEvent; import com.sanron.sunweather.event.CityEvent; import com.sanron.sunweather.utils.DateUtils; import com.sanron.sunweather.utils.NetUtils; import com.sanron.sunweather.view.RotateView; import com.sanron.sunweather.view.v4.DrawerLayout; import com.sanron.sunweather.view.v4.DrawerLayout.DrawerListener; import com.umeng.update.UmengUpdateAgent; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Map; import de.greenrobot.event.EventBus; public class MainActivity extends FragmentActivity { private AppConfig config; private DrawerLayout drawerLayout; private View contentView; private View menuView; private FragmentManager fm; private AboveFrag aboveFrag; private MenuFrag menuFrag; private EventBus eventBus; public static final String TAG_ABOVE = "above"; public static final String TAG_MENU = "menu"; public static final String TAG_EXTRAS = "extras"; public static final String TAG_LIFE_INDEX = "lifeindex"; private Map<String, WeatherData> weatherDatas; private int currentCityPosition = 0; //当前显示城市的位置 public static final int REQUEST_ADD_CITY = 0x110; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); UmengUpdateAgent.update(getApplicationContext()); eventBus = EventBus.getDefault(); eventBus.register(this); initView(); //设置view initData(); //读取配置和缓存 initFragment(); //设置fragment initConfig(); // } private void initView() { contentView = findViewById(R.id.content); menuView = findViewById(R.id.menu_container); drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); drawerLayout.setDrawerListener(new DrawerListener() { @Override public void onDrawerStateChanged(int newState) { } @Override public void onDrawerOpened(View drawerView) { fm.beginTransaction() .add(R.id.menu_container, menuFrag, TAG_MENU) .commit(); } @Override public void onDrawerClosed(View drawerView) { fm.beginTransaction() .remove(menuFrag) .commit(); } @Override public void onDrawerSlide(View drawerView, float slideOffset) { //滑动菜单时滚动主内容 int x = (int) (slideOffset * menuView.getMeasuredWidth()); contentView.scrollTo(x, 0); } }); } private void initData() { CityProvider.init(this); config = AppConfig.getInstance(this); weatherDatas = CacheManager.getWeatherDatas(this, config.getCities()); } private void initFragment() { fm = getSupportFragmentManager(); aboveFrag = (AboveFrag) fm.findFragmentByTag(TAG_ABOVE); if(aboveFrag==null) { aboveFrag = new AboveFrag(); fm.beginTransaction(). add(R.id.fragment_container_above, aboveFrag, TAG_ABOVE) .commit(); } menuFrag = new MenuFrag(); menuFrag.setWeatherDatas(weatherDatas); menuFrag.setCities(config.getCities()); if (config.getCities().size() != 0) { WeatherData curWeatherData = weatherDatas.get(config.getCity(currentCityPosition)); aboveFrag.setWeatherData(curWeatherData); } fm.addOnBackStackChangedListener(new OnBackStackChangedListener() { @Override public void onBackStackChanged() { //fragment回退栈空时 if (fm.getBackStackEntryCount() == 0) { aboveFrag.setCenterVisiable(true); aboveFrag.setTopVisiable(true); aboveFrag.setRotateViewState(RotateView.STATE_UP); } } }); } private void initConfig() { boolean netWorkEnable = NetUtils.checkNetwork(this); if (config.isLocation()) { if (!netWorkEnable) { aboveFrag.setStateText("无可用网络"); } else { //有网络 locationWeather(); } } if (netWorkEnable) { final List<String> cities = config.getCities(); switch (config.getUpdatePolicy()) { case AppConfig.UPDATE_ALWAYS: { for (int i = 0; i < cities.size(); i++) { if (config.isLocationPrimaryCity() && i == 0) { continue; } WeatherProvider.getInstance().getWeahterData(CityProvider.findByName(cities.get(i)), getWeatherListener); } } break; case AppConfig.UPDATE_AUTO: { for (int i = 0; i < cities.size(); i++) { if (config.isLocationPrimaryCity() && i == 0) { continue; } WeatherData data = weatherDatas.get(cities.get(i)); if (data == null || (int) ((System.currentTimeMillis() - data.getInstantWeather().getTime().getTime()) / 1000 / 60) > 10) { //数据是半小时前的 就更新 WeatherProvider.getInstance().getWeahterData(CityProvider.findByName(config.getCity(i)), getWeatherListener); } } } break; } } } //定位 private void locationWeather() { aboveFrag.setStateText("获取位置 "); LocationProvider.getInstance(this).requestLocation(new OnLocationListener() { @Override public void onLocationSuccess(final City city) { aboveFrag.setStateText("定位到 " + city.getName()); config.setPrimaryCity(city.getName()); config.setLocationPrimaryCity(true); WeatherProvider.getInstance().getWeahterData(city, getWeatherListener); } @Override public void onLocationFailed() { aboveFrag.setStateText("定位失败"); } }); } public void onEventMainThread(AboveEvent event) { switch (event.getType()) { case AboveEvent.TYPE_TOP_MENU_CLICK: { //显示/隐藏侧滑菜单 if (drawerLayout.isDrawerOpen(Gravity.RIGHT)) { drawerLayout.closeDrawer(Gravity.RIGHT); } else { drawerLayout.openDrawer(Gravity.RIGHT); } } break; case AboveEvent.TYPE_BOTTOM_STATE_CHANGE: { int state = (Integer) event.getObj(); if (state == RotateView.STATE_UP) { clearFragmentBackStack(); } else if (state == RotateView.STATE_DOWN) { switchFragment(TAG_LIFE_INDEX); } } break; case AboveEvent.TYPE_CENTER_CLICK: { //显示空气环境等额外信息 switchFragment(TAG_EXTRAS); } break; } } public void onEventMainThread(CityEvent event) { int position = event.getPosition(); switch (event.getType()) { case CityEvent.TYPE_SELECT: { if (currentCityPosition == position) return; currentCityPosition = position; refreshFragments(); } break; case CityEvent.TYPE_DEL: { String city = config.getCity(position); config.delCity(city); weatherDatas.remove(city); if (position <= currentCityPosition) { currentCityPosition--; } refreshFragments(); } break; case CityEvent.TYPE_REFRESH: { if (config.isLocationPrimaryCity() && position == 0) { locationWeather(); return; } String cityName = config.getCity(position); City city = CityProvider.findByName(cityName); WeatherProvider.getInstance().getWeahterData(city, getWeatherListener); } break; case CityEvent.TYPE_PRIMARY: { if (config.isLocation() && config.isLocationPrimaryCity()) { //当前主城市为定位的,不能更改主城市 Toast.makeText(this, "当前开启了自动定位,应用将自动把您的位置设为主城市", Toast.LENGTH_SHORT).show(); return; } config.setPrimaryCity(config.getCity(position)); refreshFragments(); } break; case CityEvent.TYPE_ADD: { Intent intent = new Intent(this, AddCityActivity.class); startActivityForResult(intent, REQUEST_ADD_CITY); } break; } } /** * 清空fragment回退栈 */ private void clearFragmentBackStack() { while (fm.getBackStackEntryCount() > 0) { fm.popBackStackImmediate(); } } /** * 切换fragment */ public void switchFragment(String tag) { FragmentTransaction transaction = fm.beginTransaction(); BaseFragment baseFragment = null; transaction.setCustomAnimations( R.anim.slide_up_in, R.anim.slide_down_out, R.anim.slide_up_in, R.anim.slide_down_out); if (TAG_EXTRAS.equals(tag)) { baseFragment = new ExtrasFrag(); aboveFrag.setRotateViewState(RotateView.STATE_HIDE); } else if (TAG_LIFE_INDEX.equals(tag)) { baseFragment = new LifeIndexFrag(); aboveFrag.setTopVisiable(false); aboveFrag.setRotateViewState(RotateView.STATE_DOWN); } aboveFrag.setCenterVisiable(false); baseFragment.setWeatherData(weatherDatas.get(config.getCity(currentCityPosition))); transaction.add(R.id.fragment_container_behind, baseFragment, tag); transaction.addToBackStack(null); transaction.commitAllowingStateLoss(); } /** * 所有fragment刷新视图 */ private void refreshFragments() { List<Fragment> fragments = fm.getFragments(); String cityName = config.getCity(currentCityPosition); WeatherData weatherData = weatherDatas.get(cityName); for (Fragment frag : fragments) { if (frag == null) continue; ((BaseFragment) frag).setWeatherData(weatherData); ((BaseFragment) frag).refreshViews(); } } private OnGetWeatherListener getWeatherListener = new OnGetWeatherListener() { @Override public void onSuccess(WeatherData weatherData) { //缓存数据 Collections.sort(weatherData.getWeathers(), new Comparator<Weather>() { @Override public int compare(Weather lhs, Weather rhs) { return lhs.getDate().compareTo(rhs.getDate()); } }); WeatherData data = weatherDatas.get(weatherData.getCity()); if (data != null) { //把前一天的天气数据保存起来 Weather yestadayWeather = data.getWeatherByDay( DateUtils.addDate(new Date(), -1)); if (yestadayWeather != null) { weatherData.getWeathers().add(0, yestadayWeather); } } CacheManager.saveWeatherData(MainActivity.this, weatherData); weatherDatas.put(weatherData.getCity(), weatherData); refreshFragments(); } @Override public void onError(City city, String error) { if (city.getName().equals(config.getCity(currentCityPosition))) { aboveFrag.setStateText(error); } } @Override public void onStart(City city) { if (city.getName().equals(config.getCity(currentCityPosition))) { aboveFrag.setStateText("请求数据"); } } }; @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case MenuFrag.REQUEST_ADD_CITY: { if (resultCode == Activity.RESULT_OK) { //添加城市 City newCity = (City) data.getSerializableExtra("newCity"); config.addCity(newCity.getName()); WeatherProvider.getInstance().getWeahterData(newCity, getWeatherListener); refreshFragments(); } } break; } } @Override protected void onDestroy() { eventBus.unregister(this); super.onDestroy(); } @Override public void onBackPressed() { if (drawerLayout.isDrawerOpen(Gravity.RIGHT)) { drawerLayout.closeDrawer(Gravity.RIGHT); return; } super.onBackPressed(); } }
15,172
0.573585
0.571496
436
33.036697
25.079754
137
false
false
0
0
0
0
0
0
0.504587
false
false
12
6cc06e57d388a9dff3bfdca6674713f83a483dd9
7,593,502,195,499
9f9167a49aef1740b1bca567a9c24ad0a829f067
/src/main/java/pe/farmaciasperuanas/concentrador/controller/ProspectoController.java
11ec2e6acbad70a8ded89eaa3c214f46e952babe
[ "Apache-2.0" ]
permissive
joedayz/ConcentradorJakartaEE
https://github.com/joedayz/ConcentradorJakartaEE
45d7452f6c97bf615fc4eca0a0da701b3859ca03
33c07f845cf2715a210879db89f3facc19681eee
refs/heads/main
2023-07-03T07:08:31.658000
2021-08-20T05:33:59
2021-08-20T05:33:59
398,165,734
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pe.farmaciasperuanas.concentrador.controller; import java.util.List; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; import pe.farmaciasperuanas.concentrador.dto.request.ProspectoRequest; import pe.farmaciasperuanas.concentrador.model.Prospecto; import pe.farmaciasperuanas.concentrador.service.ProspectoService; @RequestScoped @Path("/prospecto") @Produces("application/json") @Consumes("application/json") public class ProspectoController { @Inject ProspectoService prospectoService; @POST @Path("/listar/pagina/{page}") public List<Prospecto> fidAll(ProspectoRequest request, @PathParam("page") Integer page){ return prospectoService.listar(request, page); } @POST public Response guardar(Prospecto obj) { prospectoService.saveOrUpdate(obj); return Response.created(UriBuilder.fromResource(ProspectoController.class).path(String.valueOf(obj.getIdProspecto())).build()) .build(); } }
UTF-8
Java
1,159
java
ProspectoController.java
Java
[]
null
[]
package pe.farmaciasperuanas.concentrador.controller; import java.util.List; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; import pe.farmaciasperuanas.concentrador.dto.request.ProspectoRequest; import pe.farmaciasperuanas.concentrador.model.Prospecto; import pe.farmaciasperuanas.concentrador.service.ProspectoService; @RequestScoped @Path("/prospecto") @Produces("application/json") @Consumes("application/json") public class ProspectoController { @Inject ProspectoService prospectoService; @POST @Path("/listar/pagina/{page}") public List<Prospecto> fidAll(ProspectoRequest request, @PathParam("page") Integer page){ return prospectoService.listar(request, page); } @POST public Response guardar(Prospecto obj) { prospectoService.saveOrUpdate(obj); return Response.created(UriBuilder.fromResource(ProspectoController.class).path(String.valueOf(obj.getIdProspecto())).build()) .build(); } }
1,159
0.795513
0.795513
41
27.268293
26.945314
128
false
false
0
0
0
0
0
0
1.02439
false
false
12
cb0cd303bf77fd228dd897ed37961e3c9f2a5006
7,593,502,197,211
f83db66c1a655ee0c68fa734599e58a8252e7367
/src/WebPortal/stable/src/main/java/de/decidr/ui/controller/UploadAction.java
8e5798c28d4e1f186ebed028d1a41f5e0e0c4aa7
[]
no_license
matthiasmeyer/decidrplus
https://github.com/matthiasmeyer/decidrplus
3c5e7a474084cdbfae3d2e7d677256dfa00c6f2a
2bd36a35e936eeabbf8269d9677b3dfd308362a3
refs/heads/master
2020-03-26T17:12:12.772000
2011-06-03T09:52:18
2011-06-03T09:52:18
32,228,646
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * The DecidR Development Team licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package de.decidr.ui.controller; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import com.vaadin.ui.Upload.Receiver; import de.decidr.model.annotations.Reviewed; import de.decidr.model.annotations.Reviewed.State; import de.decidr.ui.main.DecidrUI; import de.decidr.ui.view.windows.InformationDialogComponent; /** * This class handles the actions when the upload for a human task is started, * finished and received. * * @author AT */ @Reviewed(reviewers = "RR", lastRevision = "0", currentReviewState = State.NeedsReview) public class UploadAction implements Receiver { private static final long serialVersionUID = 1L; private File file = null; /** * Returns the file * * @return file */ public File getFile() { return file; } /* * (non-Javadoc) * * @see com.vaadin.ui.Upload.Receiver#receiveUpload(java.lang.String, * java.lang.String) */ @Override public OutputStream receiveUpload(String filename, String MIMEType) { FileOutputStream fos = null; try { file = File.createTempFile("decidr", "tmp"); fos = new FileOutputStream(file); } catch (IOException e) { DecidrUI.getCurrent().getMainWindow().addWindow( new InformationDialogComponent( "An error occured wihle uploading your file:<br/>" + e.getMessage(), "Upload Failure")); } return fos; } }
UTF-8
Java
2,191
java
UploadAction.java
Java
[ { "context": " started,\n * finished and received.\n * \n * @author AT\n */\n@Reviewed(reviewers = \"RR\", lastRevision = \"0", "end": 1114, "score": 0.5564282536506653, "start": 1112, "tag": "USERNAME", "value": "AT" } ]
null
[]
/* * The DecidR Development Team licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package de.decidr.ui.controller; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import com.vaadin.ui.Upload.Receiver; import de.decidr.model.annotations.Reviewed; import de.decidr.model.annotations.Reviewed.State; import de.decidr.ui.main.DecidrUI; import de.decidr.ui.view.windows.InformationDialogComponent; /** * This class handles the actions when the upload for a human task is started, * finished and received. * * @author AT */ @Reviewed(reviewers = "RR", lastRevision = "0", currentReviewState = State.NeedsReview) public class UploadAction implements Receiver { private static final long serialVersionUID = 1L; private File file = null; /** * Returns the file * * @return file */ public File getFile() { return file; } /* * (non-Javadoc) * * @see com.vaadin.ui.Upload.Receiver#receiveUpload(java.lang.String, * java.lang.String) */ @Override public OutputStream receiveUpload(String filename, String MIMEType) { FileOutputStream fos = null; try { file = File.createTempFile("decidr", "tmp"); fos = new FileOutputStream(file); } catch (IOException e) { DecidrUI.getCurrent().getMainWindow().addWindow( new InformationDialogComponent( "An error occured wihle uploading your file:<br/>" + e.getMessage(), "Upload Failure")); } return fos; } }
2,191
0.66408
0.661342
76
27.828947
25.270321
87
false
false
0
0
0
0
0
0
0.394737
false
false
12
aa3ee986de9a84a56a02b50ddd560ff426bc44b3
22,539,988,386,633
5ecef6eaed3169540c2792c5aa693bc2988ef58d
/app/src/main/java/com/holenzhou/happytestdemo/ui/base/TitleActivity.java
beab24f73273a2982d7a6ae5bfb344e6ffc926db
[]
no_license
HolenZhou/HappyTestDemo
https://github.com/HolenZhou/HappyTestDemo
12bb22c0daf6efb94df51151ccd8922621b8ffa0
f426ba970b1a09afaf6353bfebb504c88b220a1f
refs/heads/master
2017-11-03T11:36:42.245000
2017-07-09T15:43:50
2017-07-09T15:43:50
96,620,869
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.holenzhou.happytestdemo.ui.base; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.view.View; import android.widget.ImageButton; import android.widget.TextView; import com.holenzhou.happytestdemo.R; import com.holenzhou.happytestdemo.utils.ClickFliter; public abstract class TitleActivity extends BaseActivity { private ImageButton mLeftBtn; private TextView mLeftCloseView; private TextView mTitleView; private ImageButton mRightBtn; private TextView mRightText; private TextView mLeftText; private ImageButton mRightBtnTwo; private ImageButton mRigthBtnThree; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); View rootView = getRootView(); if (rootView != null) { mLeftBtn = (ImageButton) findViewById(R.id.titleBar_left_btn); mLeftCloseView = (TextView) findViewById(R.id.titleBar_left_close_btn); mTitleView = (TextView) findViewById(R.id.titleBar_title); mRightBtn = (ImageButton) findViewById(R.id.titleBar_right_btn); mRightText = (TextView) findViewById(R.id.titleBar_right_text); mLeftText = (TextView) findViewById(R.id.titleBar_left_text); mRightBtnTwo = (ImageButton) findViewById(R.id.titleBar_right_btn_two); mRigthBtnThree = (ImageButton) findViewById(R.id.titleBar_right_btn_three); mLeftBtn.setOnClickListener(clickListener); mLeftCloseView.setOnClickListener(clickListener); mTitleView.setOnClickListener(clickListener); mRightBtn.setOnClickListener(clickListener); mRightText.setOnClickListener(clickListener); mLeftText.setOnClickListener(clickListener); mRightBtnTwo.setOnClickListener(clickListener); mRigthBtnThree.setOnClickListener(clickListener); mLeftBtn.setClickable(false); mTitleView.setClickable(false); mRightBtn.setClickable(false); mRightText.setClickable(false); mLeftText.setClickable(false); mRightBtnTwo.setClickable(false); mRigthBtnThree.setClickable(false); onInitTitle(); } } @Override public void onInitView() { } @Override public void onInitData(Bundle savedInstanceState) { } @Override public boolean hasTitle() { return true; } public abstract void onInitTitle(); public void setTitleID(int title) { if (mTitleView != null) mTitleView.setText(title); } public void setTitleText(String title) { if (mTitleView != null) mTitleView.setText(title); } /** * 该方法用于设置中间标题栏的drawableRight属性 */ public void enableTitleBtn() { if (mTitleView != null) { Drawable titleBtn = getResources().getDrawable(R.drawable.ic_grey_expandable_arrow_down); if (titleBtn != null) { titleBtn.setBounds(0, 0, titleBtn.getMinimumWidth(), titleBtn.getMinimumHeight()); } mTitleView.setCompoundDrawables(null, null, titleBtn, null); mTitleView.setBackgroundColor(getResources().getColor(R.color.transparent)); mTitleView.setClickable(true); } } public void setLeftBtn(int btnId) { if (mLeftBtn != null) { mLeftBtn.setImageResource(btnId); mLeftBtn.setVisibility(View.VISIBLE); mLeftBtn.setClickable(true); if (mLeftText != null) { mLeftText.setVisibility(View.GONE); mLeftText.setClickable(false); } } } public void setRightBtnTwoRes(int btnId) { if (mRightBtnTwo != null) { mRightBtnTwo.setImageResource(btnId); mRightBtnTwo.setVisibility(View.VISIBLE); mRightBtnTwo.setClickable(true); } } public void setRigthBtnThree(int btnId) { if(mRigthBtnThree != null) { mRigthBtnThree.setImageResource(btnId); mRigthBtnThree.setVisibility(View.VISIBLE); mRigthBtnThree.setClickable(true); } } protected void clickableRightText(boolean enable) { if (mRightText != null){ mRightText.setClickable(enable); mRightText.setTextColor(enable ? getResources().getColor(R.color.primary) : getResources().getColor(R.color .text_grey)); } } protected void clickableTitleText(boolean enable) { if (mTitleView != null) { mTitleView.setClickable(enable); } } protected void clickableTitleCenter() { if (mTitleView != null) { mTitleView.setClickable(true); mTitleView.setBackgroundColor(getResources().getColor(R.color.transparent)); } } // public void setRightBtnRedot(boolean isShow) { // int[] location = new int[2]; // mRightBtn.getLocationOnScreen(location); // BadgeView badge = (BadgeView) mRightBtn.getTag(); // if (null == badge) { // badge = new BadgeView(this, mRightBtn); // badge.setBadgeMargin(location[0] + mRightBtn.getWidth() + 20, DisplayUtils.dip2px(10)); // mRightBtn.setTag(badge); // } // if (isShow) { // badge.show(); // } else { // badge.hide(); // } // } public void setBackBtn() { setLeftBtn(R.drawable.ic_titlebar_back); } public void setLeftCloseBtn(boolean show) { mLeftCloseView.setVisibility(show ? View.VISIBLE : View.GONE); } public void setRightBtn(int btnId) { if (mRightBtn != null) { mRightBtn.setImageResource(btnId); mRightBtn.setVisibility(View.VISIBLE); mRightBtn.setClickable(true); if (mRightText != null) { mRightText.setVisibility(View.GONE); mRightText.setClickable(false); } } } public void setRightText(int btnId) { setRightText(getResources().getText(btnId).toString()); } public void setLeftText(int btnId) { setLeftText(getResources().getText(btnId).toString()); } public void setRightBtnTwo(boolean isShow){ mRightBtnTwo.setVisibility(isShow ? View.VISIBLE : View.GONE); } public void setRigthBtnThree(boolean isShow) { mRigthBtnThree.setVisibility(isShow ? View.VISIBLE : View.GONE); } public void setRightBtn(boolean isShow){ mRightBtn.setVisibility(isShow ? View.VISIBLE : View.GONE); mRightBtn.setClickable(isShow); } public void setRightText(String text) { if (mRightText != null) { mRightText.setText(text); mRightText.setVisibility(View.VISIBLE); mRightText.setClickable(true); if (mRightBtn != null) { mRightBtn.setVisibility(View.GONE); mRightBtn.setClickable(false); } } } public void setLeftText(String text) { if (mLeftText != null) { mLeftText.setText(text); mLeftText.setVisibility(View.VISIBLE); mLeftText.setClickable(true); if (mLeftBtn != null) { mLeftBtn.setVisibility(View.GONE); mLeftBtn.setClickable(false); } } } public void setRightTextColor(int color) { mRightText.setTextColor(color); } public void setLeftTextColor(int color) { mLeftText.setTextColor(color); } public void setTitleTextColor(int color) { mTitleView.setTextColor(color); } public void onLeftClick(View view) { finish(); } @Override public void onBackPressed() { super.onBackPressed(); } public void onLeftCloseClick(View view) { finish(); } public void onRightClick(View view) { } public void onTitleClick(View view) { } public void onRightBtnTwoClick(View view){ } public void onRightBtnThreeClick(View view) { } private View.OnClickListener clickListener = new View.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.titleBar_left_btn: case R.id.titleBar_left_text: onLeftClick(v); break; case R.id.titleBar_left_close_btn: onLeftCloseClick(v); break; case R.id.titleBar_right_btn: case R.id.titleBar_right_text: if(ClickFliter.canClick()) { onRightClick(v); } break; case R.id.titleBar_title: onTitleClick(v); break; case R.id.titleBar_right_btn_two: onRightBtnTwoClick(v); break; case R.id.titleBar_right_btn_three: onRightBtnThreeClick(v); break; } } }; }
UTF-8
Java
9,293
java
TitleActivity.java
Java
[]
null
[]
package com.holenzhou.happytestdemo.ui.base; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.view.View; import android.widget.ImageButton; import android.widget.TextView; import com.holenzhou.happytestdemo.R; import com.holenzhou.happytestdemo.utils.ClickFliter; public abstract class TitleActivity extends BaseActivity { private ImageButton mLeftBtn; private TextView mLeftCloseView; private TextView mTitleView; private ImageButton mRightBtn; private TextView mRightText; private TextView mLeftText; private ImageButton mRightBtnTwo; private ImageButton mRigthBtnThree; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); View rootView = getRootView(); if (rootView != null) { mLeftBtn = (ImageButton) findViewById(R.id.titleBar_left_btn); mLeftCloseView = (TextView) findViewById(R.id.titleBar_left_close_btn); mTitleView = (TextView) findViewById(R.id.titleBar_title); mRightBtn = (ImageButton) findViewById(R.id.titleBar_right_btn); mRightText = (TextView) findViewById(R.id.titleBar_right_text); mLeftText = (TextView) findViewById(R.id.titleBar_left_text); mRightBtnTwo = (ImageButton) findViewById(R.id.titleBar_right_btn_two); mRigthBtnThree = (ImageButton) findViewById(R.id.titleBar_right_btn_three); mLeftBtn.setOnClickListener(clickListener); mLeftCloseView.setOnClickListener(clickListener); mTitleView.setOnClickListener(clickListener); mRightBtn.setOnClickListener(clickListener); mRightText.setOnClickListener(clickListener); mLeftText.setOnClickListener(clickListener); mRightBtnTwo.setOnClickListener(clickListener); mRigthBtnThree.setOnClickListener(clickListener); mLeftBtn.setClickable(false); mTitleView.setClickable(false); mRightBtn.setClickable(false); mRightText.setClickable(false); mLeftText.setClickable(false); mRightBtnTwo.setClickable(false); mRigthBtnThree.setClickable(false); onInitTitle(); } } @Override public void onInitView() { } @Override public void onInitData(Bundle savedInstanceState) { } @Override public boolean hasTitle() { return true; } public abstract void onInitTitle(); public void setTitleID(int title) { if (mTitleView != null) mTitleView.setText(title); } public void setTitleText(String title) { if (mTitleView != null) mTitleView.setText(title); } /** * 该方法用于设置中间标题栏的drawableRight属性 */ public void enableTitleBtn() { if (mTitleView != null) { Drawable titleBtn = getResources().getDrawable(R.drawable.ic_grey_expandable_arrow_down); if (titleBtn != null) { titleBtn.setBounds(0, 0, titleBtn.getMinimumWidth(), titleBtn.getMinimumHeight()); } mTitleView.setCompoundDrawables(null, null, titleBtn, null); mTitleView.setBackgroundColor(getResources().getColor(R.color.transparent)); mTitleView.setClickable(true); } } public void setLeftBtn(int btnId) { if (mLeftBtn != null) { mLeftBtn.setImageResource(btnId); mLeftBtn.setVisibility(View.VISIBLE); mLeftBtn.setClickable(true); if (mLeftText != null) { mLeftText.setVisibility(View.GONE); mLeftText.setClickable(false); } } } public void setRightBtnTwoRes(int btnId) { if (mRightBtnTwo != null) { mRightBtnTwo.setImageResource(btnId); mRightBtnTwo.setVisibility(View.VISIBLE); mRightBtnTwo.setClickable(true); } } public void setRigthBtnThree(int btnId) { if(mRigthBtnThree != null) { mRigthBtnThree.setImageResource(btnId); mRigthBtnThree.setVisibility(View.VISIBLE); mRigthBtnThree.setClickable(true); } } protected void clickableRightText(boolean enable) { if (mRightText != null){ mRightText.setClickable(enable); mRightText.setTextColor(enable ? getResources().getColor(R.color.primary) : getResources().getColor(R.color .text_grey)); } } protected void clickableTitleText(boolean enable) { if (mTitleView != null) { mTitleView.setClickable(enable); } } protected void clickableTitleCenter() { if (mTitleView != null) { mTitleView.setClickable(true); mTitleView.setBackgroundColor(getResources().getColor(R.color.transparent)); } } // public void setRightBtnRedot(boolean isShow) { // int[] location = new int[2]; // mRightBtn.getLocationOnScreen(location); // BadgeView badge = (BadgeView) mRightBtn.getTag(); // if (null == badge) { // badge = new BadgeView(this, mRightBtn); // badge.setBadgeMargin(location[0] + mRightBtn.getWidth() + 20, DisplayUtils.dip2px(10)); // mRightBtn.setTag(badge); // } // if (isShow) { // badge.show(); // } else { // badge.hide(); // } // } public void setBackBtn() { setLeftBtn(R.drawable.ic_titlebar_back); } public void setLeftCloseBtn(boolean show) { mLeftCloseView.setVisibility(show ? View.VISIBLE : View.GONE); } public void setRightBtn(int btnId) { if (mRightBtn != null) { mRightBtn.setImageResource(btnId); mRightBtn.setVisibility(View.VISIBLE); mRightBtn.setClickable(true); if (mRightText != null) { mRightText.setVisibility(View.GONE); mRightText.setClickable(false); } } } public void setRightText(int btnId) { setRightText(getResources().getText(btnId).toString()); } public void setLeftText(int btnId) { setLeftText(getResources().getText(btnId).toString()); } public void setRightBtnTwo(boolean isShow){ mRightBtnTwo.setVisibility(isShow ? View.VISIBLE : View.GONE); } public void setRigthBtnThree(boolean isShow) { mRigthBtnThree.setVisibility(isShow ? View.VISIBLE : View.GONE); } public void setRightBtn(boolean isShow){ mRightBtn.setVisibility(isShow ? View.VISIBLE : View.GONE); mRightBtn.setClickable(isShow); } public void setRightText(String text) { if (mRightText != null) { mRightText.setText(text); mRightText.setVisibility(View.VISIBLE); mRightText.setClickable(true); if (mRightBtn != null) { mRightBtn.setVisibility(View.GONE); mRightBtn.setClickable(false); } } } public void setLeftText(String text) { if (mLeftText != null) { mLeftText.setText(text); mLeftText.setVisibility(View.VISIBLE); mLeftText.setClickable(true); if (mLeftBtn != null) { mLeftBtn.setVisibility(View.GONE); mLeftBtn.setClickable(false); } } } public void setRightTextColor(int color) { mRightText.setTextColor(color); } public void setLeftTextColor(int color) { mLeftText.setTextColor(color); } public void setTitleTextColor(int color) { mTitleView.setTextColor(color); } public void onLeftClick(View view) { finish(); } @Override public void onBackPressed() { super.onBackPressed(); } public void onLeftCloseClick(View view) { finish(); } public void onRightClick(View view) { } public void onTitleClick(View view) { } public void onRightBtnTwoClick(View view){ } public void onRightBtnThreeClick(View view) { } private View.OnClickListener clickListener = new View.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.titleBar_left_btn: case R.id.titleBar_left_text: onLeftClick(v); break; case R.id.titleBar_left_close_btn: onLeftCloseClick(v); break; case R.id.titleBar_right_btn: case R.id.titleBar_right_text: if(ClickFliter.canClick()) { onRightClick(v); } break; case R.id.titleBar_title: onTitleClick(v); break; case R.id.titleBar_right_btn_two: onRightBtnTwoClick(v); break; case R.id.titleBar_right_btn_three: onRightBtnThreeClick(v); break; } } }; }
9,293
0.59376
0.592789
298
30.083893
23.682953
119
false
false
0
0
0
0
0
0
0.426174
false
false
12
e0c2efc8b34ad71e92638acdf4d8ebdf6b1ff533
21,646,635,190,127
b03a44324dc8976c507a28037094c04a564a80ad
/src/ast/FunCallNode.java
bc98e2afce8fa43ce0f017d113ebaae8d0df2958
[]
no_license
DarthVi/FOOL18
https://github.com/DarthVi/FOOL18
236939274dad54bdc0ad647005274d595e037dd4
0abac38774076c9eb5068cbee76c80e24ca57d5c
refs/heads/master
2020-03-25T07:10:18.936000
2018-11-14T17:00:14
2018-11-14T17:00:14
143,545,700
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package ast; import exception.MissingMethodException; import exception.TypeException; import exception.UndefinedFunctionException; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.Token; import parser.FOOLParser; import type.BoolType; import type.FunctionType; import type.IType; import type.IntType; import util.Environment; import util.STentry; import util.SemanticError; import java.util.ArrayList; public class FunCallNode implements INode { private Token token; private String id; protected ActualParamsNode actualArgs; private STentry entry; private int nestingLevel; protected ParserRuleContext ctx; int extra; // extra = 1 id preceded by '-', extra = 2 id preceded by 'not', extra = 0 there aren't both public FunCallNode(Token token, ActualParamsNode actualArgs, ParserRuleContext ctx) { this.token = token; this.id = token.getText(); this.actualArgs = actualArgs; this.entry = null; this.ctx = ctx; if (ctx.getChild(0).toString().equalsIgnoreCase( "-")) extra = 1; else if ((ctx.getChild(0).toString().equalsIgnoreCase( "not"))) extra = 2; else extra = 0; } @Override public IType typeCheck() throws TypeException { FunctionType funType; //we must check that we are actually calling a function if(!(entry.getType() instanceof FunctionType)) { throw new TypeException("The object called is not a function.", ctx); } else { funType = (FunctionType) entry.getType(); actualArgs.typeCheck(); if(actualArgs.size() != funType.getArgumentListSize()) throw new TypeException("Wrong number of arguments.", ctx); //we must check that the actual arguments are of the right type //(the one that follows the function declaration) for(int i = 0; i < actualArgs.size(); i++) { INode arg = actualArgs.get(i); if(!arg.typeCheck().isSubtypeOf(funType.getArgumentType(i))) throw new TypeException("Argument " + (i + 1) + " has an incorrect type.",ctx); } } if (extra == 1 &&!(((FunctionType) entry.getType()).getReturnType().isSubtypeOf(new IntType()))) { throw new TypeException("- operator allowed only for int value", ctx); } if (extra == 2 &&!(((FunctionType) entry.getType()).getReturnType().isSubtypeOf(new BoolType()))) { throw new TypeException("not operator allowed only for bool value", ctx); } return funType.getReturnType(); } @Override public String codeGeneration() { StringBuilder parCode = new StringBuilder(); for (int i = actualArgs.size() - 1; i >= 0; i--) parCode.append(actualArgs.get(i).codeGeneration()); StringBuilder getAR = new StringBuilder(); for (int i = 0; i < nestingLevel - entry.getNestingLevel()-1; i++) getAR.append("lw\n"); String s = "lfp\n" + //CL parCode + "lfp\n" + getAR + //setto AL risalendo la catena statica // ora recupero l'indirizzo a cui saltare e lo metto sullo stack "push " + entry.getOffset() + "\n" + //metto offset sullo stack "lfp\n" + getAR + //risalgo la catena statica "add\n" + "lw\n" + //carico sullo stack il valore all'indirizzo ottenuto "js\n"; if(extra==1) s="push 0\n" + s +"sub\n"; else if(extra==2) s="push 1\n" + s +"sub\n"; return s; } @Override public ArrayList<SemanticError> checkSemantics(Environment env) { ArrayList<SemanticError> errors = new ArrayList<>(); boolean isInsideMethod = false; ParserRuleContext ctxIterator = ctx; // if ctx contains RULE_fun or RULE_classdec we are inside function or method while (!isInsideMethod && ctxIterator != null) { if(FOOLParser.ruleNames[ctxIterator.getRuleIndex()]. equals(FOOLParser.ruleNames[FOOLParser.RULE_classdec]) ) isInsideMethod = true; else ctxIterator = ctxIterator.getParent(); } if(isInsideMethod) errors.add(new SemanticError(new MissingMethodException(id).getMessage())); try { entry = env.getFunEntry(token); } catch (UndefinedFunctionException e) { errors.add(new SemanticError(e.getMessage())); } nestingLevel = env.getNestingLevel(); errors.addAll(actualArgs.checkSemantics(env)); return errors; } @Override public String toString() { return "Called " + entry.getType().toString() + "\n"; } }
UTF-8
Java
4,898
java
FunCallNode.java
Java
[]
null
[]
package ast; import exception.MissingMethodException; import exception.TypeException; import exception.UndefinedFunctionException; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.Token; import parser.FOOLParser; import type.BoolType; import type.FunctionType; import type.IType; import type.IntType; import util.Environment; import util.STentry; import util.SemanticError; import java.util.ArrayList; public class FunCallNode implements INode { private Token token; private String id; protected ActualParamsNode actualArgs; private STentry entry; private int nestingLevel; protected ParserRuleContext ctx; int extra; // extra = 1 id preceded by '-', extra = 2 id preceded by 'not', extra = 0 there aren't both public FunCallNode(Token token, ActualParamsNode actualArgs, ParserRuleContext ctx) { this.token = token; this.id = token.getText(); this.actualArgs = actualArgs; this.entry = null; this.ctx = ctx; if (ctx.getChild(0).toString().equalsIgnoreCase( "-")) extra = 1; else if ((ctx.getChild(0).toString().equalsIgnoreCase( "not"))) extra = 2; else extra = 0; } @Override public IType typeCheck() throws TypeException { FunctionType funType; //we must check that we are actually calling a function if(!(entry.getType() instanceof FunctionType)) { throw new TypeException("The object called is not a function.", ctx); } else { funType = (FunctionType) entry.getType(); actualArgs.typeCheck(); if(actualArgs.size() != funType.getArgumentListSize()) throw new TypeException("Wrong number of arguments.", ctx); //we must check that the actual arguments are of the right type //(the one that follows the function declaration) for(int i = 0; i < actualArgs.size(); i++) { INode arg = actualArgs.get(i); if(!arg.typeCheck().isSubtypeOf(funType.getArgumentType(i))) throw new TypeException("Argument " + (i + 1) + " has an incorrect type.",ctx); } } if (extra == 1 &&!(((FunctionType) entry.getType()).getReturnType().isSubtypeOf(new IntType()))) { throw new TypeException("- operator allowed only for int value", ctx); } if (extra == 2 &&!(((FunctionType) entry.getType()).getReturnType().isSubtypeOf(new BoolType()))) { throw new TypeException("not operator allowed only for bool value", ctx); } return funType.getReturnType(); } @Override public String codeGeneration() { StringBuilder parCode = new StringBuilder(); for (int i = actualArgs.size() - 1; i >= 0; i--) parCode.append(actualArgs.get(i).codeGeneration()); StringBuilder getAR = new StringBuilder(); for (int i = 0; i < nestingLevel - entry.getNestingLevel()-1; i++) getAR.append("lw\n"); String s = "lfp\n" + //CL parCode + "lfp\n" + getAR + //setto AL risalendo la catena statica // ora recupero l'indirizzo a cui saltare e lo metto sullo stack "push " + entry.getOffset() + "\n" + //metto offset sullo stack "lfp\n" + getAR + //risalgo la catena statica "add\n" + "lw\n" + //carico sullo stack il valore all'indirizzo ottenuto "js\n"; if(extra==1) s="push 0\n" + s +"sub\n"; else if(extra==2) s="push 1\n" + s +"sub\n"; return s; } @Override public ArrayList<SemanticError> checkSemantics(Environment env) { ArrayList<SemanticError> errors = new ArrayList<>(); boolean isInsideMethod = false; ParserRuleContext ctxIterator = ctx; // if ctx contains RULE_fun or RULE_classdec we are inside function or method while (!isInsideMethod && ctxIterator != null) { if(FOOLParser.ruleNames[ctxIterator.getRuleIndex()]. equals(FOOLParser.ruleNames[FOOLParser.RULE_classdec]) ) isInsideMethod = true; else ctxIterator = ctxIterator.getParent(); } if(isInsideMethod) errors.add(new SemanticError(new MissingMethodException(id).getMessage())); try { entry = env.getFunEntry(token); } catch (UndefinedFunctionException e) { errors.add(new SemanticError(e.getMessage())); } nestingLevel = env.getNestingLevel(); errors.addAll(actualArgs.checkSemantics(env)); return errors; } @Override public String toString() { return "Called " + entry.getType().toString() + "\n"; } }
4,898
0.599224
0.594733
146
32.547947
29.14867
128
false
false
0
0
0
0
0
0
0.513699
false
false
12
3bf06f0cd87d54742f4445f84f13fb3219f45d40
16,973,710,773,834
65ee0e97447342f56ebbd93a8f6be6085f663b0c
/src/cn/designpattern/singleton/SingletonDemo05.java
c75aa3cd1a23d75d628991088aff5239533a9159
[]
no_license
baqimeilaoban/idea_test
https://github.com/baqimeilaoban/idea_test
18206e87c93f9b6354f229d9ac3c87ebbe27ca2f
a266578607fdb20ab1c98f73276f4486b26c1e43
refs/heads/master
2021-02-18T15:06:23.341000
2020-05-23T17:21:06
2020-05-23T17:21:06
245,208,169
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.designpattern.singleton; /** * 测试枚举式实现单例模式(没有延时加载) * @author hjb */ public enum SingletonDemo05 { /** * 这个枚举元素,本身就是单例对象 */ INSTANCE; /** * 添加自己需要的操作 */ public void SingletonOperation(){ } }
GB18030
Java
333
java
SingletonDemo05.java
Java
[ { "context": ".singleton;\n\n/**\n * 测试枚举式实现单例模式(没有延时加载)\n * @author hjb\n */\npublic enum SingletonDemo05 {\n /**\n * ", "end": 78, "score": 0.9996606111526489, "start": 75, "tag": "USERNAME", "value": "hjb" } ]
null
[]
package cn.designpattern.singleton; /** * 测试枚举式实现单例模式(没有延时加载) * @author hjb */ public enum SingletonDemo05 { /** * 这个枚举元素,本身就是单例对象 */ INSTANCE; /** * 添加自己需要的操作 */ public void SingletonOperation(){ } }
333
0.57085
0.562753
19
12
11.534844
37
false
false
0
0
0
0
0
0
0.105263
false
false
12
9a160c5345e902504580ca9ea935779924ac023c
25,615,184,974,812
62697db7643aebc17f96b89ea43ee7d671149be0
/Calculator/src/main/java/com/android2/calculator3/CalculatorPageAdapter.java
3a212381dc710447d65b0516e47121a6b3c35272
[ "Apache-2.0" ]
permissive
manniru/android_packages_apps_Calculator
https://github.com/manniru/android_packages_apps_Calculator
80d10ce2dfa616df0a4b23220017b14c5e40b6cd
c6823c916d22885f9e0dc2a93a3a0ab96c8496a6
refs/heads/ics
2020-12-25T19:50:30.903000
2015-04-04T12:12:37
2015-04-04T12:12:37
33,404,274
0
0
null
true
2015-04-04T12:10:21
2015-04-04T12:10:20
2015-03-16T21:08:19
2015-03-28T13:41:53
112,645
0
0
0
null
null
null
package com.android2.calculator3; import android.os.Parcelable; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; import com.android2.calculator3.BaseModule.Mode; import java.util.List; public abstract class CalculatorPageAdapter extends PagerAdapter { @Override public void startUpdate(View container) { } @Override public Object instantiateItem(View container, int position) { View v = getViewAt(position); ((ViewGroup) container).addView(v); return v; } public abstract View getViewAt(int position); @Override public void destroyItem(View container, int position, Object object) { ((ViewGroup) container).removeView((View) object); } @Override public void finishUpdate(View container) { } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public Parcelable saveState() { return null; } @Override public void restoreState(Parcelable state, ClassLoader loader) { } protected void applyBannedResourcesByPage(Logic logic, View page, Mode baseMode) { // Enable for(Mode key : logic.getBaseModule().mBannedResources.keySet()) { if(baseMode.compareTo(key) != 0) { List<Integer> resources = logic.getBaseModule().mBannedResources.get(key); for(Integer resource : resources) { final int resId = resource.intValue(); View v = page.findViewById(resId); if(v != null) v.setEnabled(true); } } } // Disable List<Integer> resources = logic.getBaseModule().mBannedResources.get(baseMode); for(Integer resource : resources) { final int resId = resource.intValue(); View v = page.findViewById(resId); if(v != null) v.setEnabled(false); } } public abstract Iterable<View> getViewIterator(); public abstract List<Page> getPages(); }
UTF-8
Java
2,114
java
CalculatorPageAdapter.java
Java
[]
null
[]
package com.android2.calculator3; import android.os.Parcelable; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; import com.android2.calculator3.BaseModule.Mode; import java.util.List; public abstract class CalculatorPageAdapter extends PagerAdapter { @Override public void startUpdate(View container) { } @Override public Object instantiateItem(View container, int position) { View v = getViewAt(position); ((ViewGroup) container).addView(v); return v; } public abstract View getViewAt(int position); @Override public void destroyItem(View container, int position, Object object) { ((ViewGroup) container).removeView((View) object); } @Override public void finishUpdate(View container) { } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public Parcelable saveState() { return null; } @Override public void restoreState(Parcelable state, ClassLoader loader) { } protected void applyBannedResourcesByPage(Logic logic, View page, Mode baseMode) { // Enable for(Mode key : logic.getBaseModule().mBannedResources.keySet()) { if(baseMode.compareTo(key) != 0) { List<Integer> resources = logic.getBaseModule().mBannedResources.get(key); for(Integer resource : resources) { final int resId = resource.intValue(); View v = page.findViewById(resId); if(v != null) v.setEnabled(true); } } } // Disable List<Integer> resources = logic.getBaseModule().mBannedResources.get(baseMode); for(Integer resource : resources) { final int resId = resource.intValue(); View v = page.findViewById(resId); if(v != null) v.setEnabled(false); } } public abstract Iterable<View> getViewIterator(); public abstract List<Page> getPages(); }
2,114
0.631977
0.629139
74
27.567568
25.600929
90
false
false
0
0
0
0
0
0
0.418919
false
false
12
53285daad1971f45d4e38b1988deae7c8282f782
25,580,825,235,223
991702954402a4be028c3fb50136ff2baaee81de
/src/com/sood/vaibhav/webcrawler/App.java
56005ca3a35c72a012faf24c0ff903881c35c593
[]
no_license
Backstabber1090/AdvancedAlgos
https://github.com/Backstabber1090/AdvancedAlgos
a3d6d180c70960431bbfd37152b8b0410c2ae6d5
1bfc13c233f26d1d76f54b19c7aaada7fd85b82e
refs/heads/master
2020-03-18T13:22:54.506000
2018-05-25T19:34:25
2018-05-25T19:34:25
134,779,527
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sood.vaibhav.webcrawler; import java.util.List; import java.util.Queue; public class App { public static void main(String[] args){ WebCrawler wc= new WebCrawler(); String url = "https://www.google.com"; wc.dicoveredWebisiteList(url); } }
UTF-8
Java
275
java
App.java
Java
[]
null
[]
package com.sood.vaibhav.webcrawler; import java.util.List; import java.util.Queue; public class App { public static void main(String[] args){ WebCrawler wc= new WebCrawler(); String url = "https://www.google.com"; wc.dicoveredWebisiteList(url); } }
275
0.687273
0.687273
15
16.333334
15.763531
39
false
false
0
0
0
0
0
0
0.733333
false
false
12
49650d7a64d8ceaae53b9fefbf8adc71c9be5675
31,628,139,188,159
57438dc74f470d68b6f2a2778f526383307a09f2
/Java Classes/com/layer/sdk/internal/lsdkc/lsdka/c.java
78fb25a46bffaf3cf68022470d6cbab416489157
[]
no_license
itsnotqwerty/vent-source
https://github.com/itsnotqwerty/vent-source
464b065f81ff809e7e2de4d2d7ea47718962f993
60f9373dd9957b2d2262553c7d75d918e23076d5
refs/heads/master
2020-03-20T19:16:54.248000
2018-06-17T05:05:42
2018-06-17T05:05:42
137,630,376
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.layer.sdk.internal.lsdkc.lsdka; import com.layer.a.c.e; import com.layer.b.d.k.26; import com.layer.b.d.k.f; import com.layer.sdk.exceptions.LayerException; import com.layer.sdk.exceptions.LayerException.Type; import com.layer.sdk.exceptions.LayerObjectException; import com.layer.sdk.internal.lsdkd.f; import com.layer.sdk.internal.lsdkd.h; import com.layer.sdk.internal.lsdkd.i; import com.layer.sdk.internal.lsdkd.l; import com.layer.sdk.internal.lsdkd.l.a; import com.layer.sdk.internal.lsdkd.lsdka.j; import java.util.UUID; public class c extends a<a, b> { private static final com.layer.sdk.internal.lsdkk.k.a a = com.layer.sdk.internal.lsdkk.k.a(c.class); public c(com.layer.a.a.a parama, a.a parama1, a parama2, j paramj) { super(parama, parama1, parama2, paramj); } protected b a(a parama) throws Exception { Object localObject1 = null; b localb = new b(); final j localj = a(); final a.a locala = b(); label493: for (;;) { try { if (com.layer.sdk.internal.lsdkk.k.a(2)) { com.layer.sdk.internal.lsdkk.k.a(a, "PostContentTask : Executing for MessagePart : " + localj); } final Object localObject2 = localj.n(); long l1; if (localObject2 == null) { localObject2 = parama.c(); if (localObject2 == null) { a(new e(this, parama, "No stream ID", new LayerException(LayerException.Type.INVALID_CONTENT, "MessagePart not associated with a Stream"))); return null; } final Object localObject3 = parama.a(); String str = localj.getMimeType(); l1 = localj.getSize(); localObject2 = (String)new k.f((com.layer.b.d.k)localObject3).a(new Integer[] { Integer.valueOf(200) }).a(new k.26((com.layer.b.d.k)localObject3, str, l1, (UUID)localObject2)); localObject3 = parama.d(); if (localObject3 == null) { if ((!l.a((f)localObject1, localj.getId(), com.layer.sdk.internal.lsdkd.k.a.e, new l.a() { public final void a(com.layer.sdk.internal.lsdkd.d paramAnonymousd, Throwable paramAnonymousThrowable) { if (com.layer.sdk.internal.lsdkk.k.a(6)) { com.layer.sdk.internal.lsdkk.k.d(c.wu(), "Exception in PostContentTask : Updating url for MessagePart : " + localj, paramAnonymousThrowable); } localObject3.n().a(new LayerObjectException(LayerException.Type.FAILED_CONTENT_OPERATION, paramAnonymousd, paramAnonymousThrowable.getMessage(), paramAnonymousThrowable)); } public final boolean a(com.layer.sdk.internal.lsdkd.d paramAnonymousd) { ((j)paramAnonymousd).b(localObject2); return true; } })) && (com.layer.sdk.internal.lsdkk.k.a(6))) { com.layer.sdk.internal.lsdkk.k.e(a, "Failed to transact transactedCacheUpdate while updating messagePart url: " + localj); } localj.a((String)localObject2); l1 = 0L; if (com.layer.sdk.internal.lsdkk.k.a(2)) { com.layer.sdk.internal.lsdkk.k.a(a, "MessagePart " + localj.getId() + " uploading " + localj.getSize() + " bytes. MessagePart : " + localj); break label493; parama.b().a((String)localObject1, localj.f(), localj.getMimeType(), l1, new com.layer.sdk.internal.lsdki.lsdkc.a.a() { public final void a(long paramAnonymousLong1, long paramAnonymousLong2, long paramAnonymousLong3) { locala.a(c.this, localj, paramAnonymousLong1, paramAnonymousLong2); } }); return localb; } } else { localObject1 = ((h)localObject3).m(); continue; } } else { long l2 = parama.b().a((String)localObject2, localj.getSize()); localObject1 = localObject2; l1 = l2; if (!com.layer.sdk.internal.lsdkk.k.a(2)) { continue; } com.layer.sdk.internal.lsdkk.k.a(a, "MessagePart " + localj.getId() + " resuming upload from " + l2 + " of " + localj.getSize() + " bytes. MessagePart : " + localj); localObject1 = localObject2; l1 = l2; continue; } localObject1 = localObject2; } catch (Exception parama) { if (com.layer.sdk.internal.lsdkk.k.a(6)) { com.layer.sdk.internal.lsdkk.k.d(a, "Exception in PostContentTask for MessagePart : " + localj, parama); } throw parama; } } } public static final class a { private final com.layer.b.d.k a; private final com.layer.sdk.internal.lsdkc.d b; private final h c; private final UUID d; public a(h paramh, com.layer.b.d.k paramk, com.layer.sdk.internal.lsdkc.d paramd, UUID paramUUID) { this.a = paramk; this.b = paramd; this.c = paramh; this.d = paramUUID; } public final com.layer.b.d.k a() { return this.a; } public final com.layer.sdk.internal.lsdkc.d b() { return this.b; } public final UUID c() { return this.d; } public final h d() { return this.c; } } public static class b {} } /* Location: /home/qerwtr546/Documents/Vent Source/dex2jar-2.0/classes-dex2jar.jar!/com/layer/sdk/internal/lsdkc/lsdka/c.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
UTF-8
Java
5,716
java
c.java
Java
[ { "context": "ic class b {}\n}\n\n\n/* Location: /home/qerwtr546/Documents/Vent Source/dex2jar-2.0/classes-dex2jar", "end": 5547, "score": 0.9955306053161621, "start": 5538, "tag": "USERNAME", "value": "qerwtr546" } ]
null
[]
package com.layer.sdk.internal.lsdkc.lsdka; import com.layer.a.c.e; import com.layer.b.d.k.26; import com.layer.b.d.k.f; import com.layer.sdk.exceptions.LayerException; import com.layer.sdk.exceptions.LayerException.Type; import com.layer.sdk.exceptions.LayerObjectException; import com.layer.sdk.internal.lsdkd.f; import com.layer.sdk.internal.lsdkd.h; import com.layer.sdk.internal.lsdkd.i; import com.layer.sdk.internal.lsdkd.l; import com.layer.sdk.internal.lsdkd.l.a; import com.layer.sdk.internal.lsdkd.lsdka.j; import java.util.UUID; public class c extends a<a, b> { private static final com.layer.sdk.internal.lsdkk.k.a a = com.layer.sdk.internal.lsdkk.k.a(c.class); public c(com.layer.a.a.a parama, a.a parama1, a parama2, j paramj) { super(parama, parama1, parama2, paramj); } protected b a(a parama) throws Exception { Object localObject1 = null; b localb = new b(); final j localj = a(); final a.a locala = b(); label493: for (;;) { try { if (com.layer.sdk.internal.lsdkk.k.a(2)) { com.layer.sdk.internal.lsdkk.k.a(a, "PostContentTask : Executing for MessagePart : " + localj); } final Object localObject2 = localj.n(); long l1; if (localObject2 == null) { localObject2 = parama.c(); if (localObject2 == null) { a(new e(this, parama, "No stream ID", new LayerException(LayerException.Type.INVALID_CONTENT, "MessagePart not associated with a Stream"))); return null; } final Object localObject3 = parama.a(); String str = localj.getMimeType(); l1 = localj.getSize(); localObject2 = (String)new k.f((com.layer.b.d.k)localObject3).a(new Integer[] { Integer.valueOf(200) }).a(new k.26((com.layer.b.d.k)localObject3, str, l1, (UUID)localObject2)); localObject3 = parama.d(); if (localObject3 == null) { if ((!l.a((f)localObject1, localj.getId(), com.layer.sdk.internal.lsdkd.k.a.e, new l.a() { public final void a(com.layer.sdk.internal.lsdkd.d paramAnonymousd, Throwable paramAnonymousThrowable) { if (com.layer.sdk.internal.lsdkk.k.a(6)) { com.layer.sdk.internal.lsdkk.k.d(c.wu(), "Exception in PostContentTask : Updating url for MessagePart : " + localj, paramAnonymousThrowable); } localObject3.n().a(new LayerObjectException(LayerException.Type.FAILED_CONTENT_OPERATION, paramAnonymousd, paramAnonymousThrowable.getMessage(), paramAnonymousThrowable)); } public final boolean a(com.layer.sdk.internal.lsdkd.d paramAnonymousd) { ((j)paramAnonymousd).b(localObject2); return true; } })) && (com.layer.sdk.internal.lsdkk.k.a(6))) { com.layer.sdk.internal.lsdkk.k.e(a, "Failed to transact transactedCacheUpdate while updating messagePart url: " + localj); } localj.a((String)localObject2); l1 = 0L; if (com.layer.sdk.internal.lsdkk.k.a(2)) { com.layer.sdk.internal.lsdkk.k.a(a, "MessagePart " + localj.getId() + " uploading " + localj.getSize() + " bytes. MessagePart : " + localj); break label493; parama.b().a((String)localObject1, localj.f(), localj.getMimeType(), l1, new com.layer.sdk.internal.lsdki.lsdkc.a.a() { public final void a(long paramAnonymousLong1, long paramAnonymousLong2, long paramAnonymousLong3) { locala.a(c.this, localj, paramAnonymousLong1, paramAnonymousLong2); } }); return localb; } } else { localObject1 = ((h)localObject3).m(); continue; } } else { long l2 = parama.b().a((String)localObject2, localj.getSize()); localObject1 = localObject2; l1 = l2; if (!com.layer.sdk.internal.lsdkk.k.a(2)) { continue; } com.layer.sdk.internal.lsdkk.k.a(a, "MessagePart " + localj.getId() + " resuming upload from " + l2 + " of " + localj.getSize() + " bytes. MessagePart : " + localj); localObject1 = localObject2; l1 = l2; continue; } localObject1 = localObject2; } catch (Exception parama) { if (com.layer.sdk.internal.lsdkk.k.a(6)) { com.layer.sdk.internal.lsdkk.k.d(a, "Exception in PostContentTask for MessagePart : " + localj, parama); } throw parama; } } } public static final class a { private final com.layer.b.d.k a; private final com.layer.sdk.internal.lsdkc.d b; private final h c; private final UUID d; public a(h paramh, com.layer.b.d.k paramk, com.layer.sdk.internal.lsdkc.d paramd, UUID paramUUID) { this.a = paramk; this.b = paramd; this.c = paramh; this.d = paramUUID; } public final com.layer.b.d.k a() { return this.a; } public final com.layer.sdk.internal.lsdkc.d b() { return this.b; } public final UUID c() { return this.d; } public final h d() { return this.c; } } public static class b {} } /* Location: /home/qerwtr546/Documents/Vent Source/dex2jar-2.0/classes-dex2jar.jar!/com/layer/sdk/internal/lsdkc/lsdka/c.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
5,716
0.578376
0.564381
167
33.233532
38.518204
187
false
false
0
0
0
0
0
0
0.670659
false
false
12
a616fadce0eb191edae3d52fc91d168fddc4dddc
7,902,739,874,327
ec8b019045ea9c7b9d2b026b8ae402a9f7ed658f
/src/main/java/com/nianien/core/function/Consumer.java
2768fad62a67ab1763e32501493d442b660b8b16
[]
no_license
stanvl/nianien
https://github.com/stanvl/nianien
da5a32e83175e83ecd085df60a7667848071730c
a44d5a9bc7cdabdf9ae199b55a694782e82e7adb
refs/heads/master
2021-07-16T02:49:50.794000
2017-10-19T08:24:38
2017-10-19T08:24:38
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.nianien.core.function; /** * 函数式,输入{@link T} * * @author skyfalling */ public interface Consumer<T> { void apply(T t); }
UTF-8
Java
152
java
Consumer.java
Java
[ { "context": "re.function;\n\n/**\n * 函数式,输入{@link T}\n *\n * @author skyfalling\n */\npublic interface Consumer<T> {\n void apply", "end": 83, "score": 0.9995242953300476, "start": 73, "tag": "USERNAME", "value": "skyfalling" } ]
null
[]
package com.nianien.core.function; /** * 函数式,输入{@link T} * * @author skyfalling */ public interface Consumer<T> { void apply(T t); }
152
0.633803
0.633803
10
13.2
12.253979
34
false
false
0
0
0
0
0
0
0.3
false
false
12
73e562902a40f76e5a244f4befe3416cd7f639eb
1,073,741,886,315
9b2ac2ea95faf584dee007dc6fff6dee9daddd05
/src/test/serviceImpl/TeacherService.java
f56f3cfdf7dc3730a6392cb374f5336e8143b5d7
[]
no_license
zhiruchen/JettyTest
https://github.com/zhiruchen/JettyTest
0adf32aa9a0a8a5752d6fede46eb60ff7a1fe0d7
86db8886f35992806928e08f5ecf075648b9191b
refs/heads/master
2015-08-23T01:48:34.461000
2015-06-13T11:33:45
2015-06-13T11:33:45
33,577,210
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package test.serviceImpl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.slf4j.*; import test.beans.Teacher; import test.service.UserService; import test.utils.Dbutils; public class TeacherService implements UserService { private static Logger log = LoggerFactory.getLogger(TeacherService.class); private static final String TABLE_NAME = "t_teacher"; private static final Connection con = Dbutils.getConn(); private static PreparedStatement pst = null; private static ResultSet rs = null; /* */ public TeacherService() { } // 获取院系名称 public String getDept(int deptId) { String sql = "SELECT dept_name FROM t_dept WHERE dept_id=?"; try { pst = con.prepareStatement(sql); pst.setInt(1, deptId); rs = pst.executeQuery(); if (rs.next()) { return rs.getString("dept_name"); } } catch (SQLException e) { e.printStackTrace(); } return null; } public int getDeptId(String deptName) { String sql = "SELECT dept_id FROM t_dept WHERE dept_name=?"; try { pst = con.prepareStatement(sql); pst.setString(1, deptName); rs = pst.executeQuery(); if (rs.next()) { return rs.getInt("dept_id"); } } catch (SQLException e) { e.printStackTrace(); } return -1; } public String getInfo(String uname) { String sql = "select dept_id,t_name,contact from " + TABLE_NAME + " where t_num=?"; PreparedStatement mypst; ResultSet myrs; MyTeacher t = null; try { mypst = con.prepareStatement(sql); mypst.setString(1, uname); myrs = mypst.executeQuery(); // 因为在getDept方法中将类属性pst和rs改变了,所以出现Column 't_name' not found. if (myrs.next()) { t = new MyTeacher(getDept(myrs.getInt("dept_id")), uname, myrs.getString("t_name"), myrs.getString("contact")); } return JSONObject.fromObject(t).toString();// 将MyTeacher对象转变为json字符串 } catch (SQLException e) { e.printStackTrace(); log.info("数据库连接错误"); } return null; } // 获取所有老师信息 public List<MyTeacher> getTeacher() { String sql = "select t_num,dept_id,t_name,contact from " + TABLE_NAME; List<MyTeacher> list = new ArrayList<MyTeacher>(); PreparedStatement mypst; ResultSet myrs; try { mypst = con.prepareStatement(sql); myrs = mypst.executeQuery(); while (myrs.next()) { list.add(new MyTeacher(getDept(myrs.getInt("dept_id")), myrs .getString("t_num"), myrs.getString("t_name"), myrs .getString("contact"))); } return list; } catch (SQLException e) { e.printStackTrace(); } return null; } // 获取json数组字符串 public String getJsonArrayStr() { return JSONArray.fromObject(getTeacher()).toString(); } public class MyTeacher { private String dept;// 院系 private String num;// 编号 private String name;// 姓名 private String contact;// 联系方式 public MyTeacher() { } public MyTeacher(String d, String num, String name, String c) { this.setDept(d); this.setNum(num); this.setName(name); this.setContact(c); } public String getDept() { return dept; } public void setDept(String dept) { this.dept = dept; } public String getNum() { return num; } public void setNum(String num) { this.num = num; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } } public boolean modifyPwd(String num, String newPwd) { String sql = "UPDATE t_teacher SET t_pwd=? WHERE t_num=?"; Connection conn = Dbutils.getConn();// ��������ݿ�����ӡ� PreparedStatement pst = null; try { pst = conn.prepareStatement(sql); pst.setString(1, newPwd); pst.setString(2, num); if (pst.executeUpdate() > 0) return true; else return false; } catch (SQLException e) { e.printStackTrace(); } return false; } public String getNameByNum(String num) { Map<String, String> map = new DbServiceImpl().getSingleField( TABLE_NAME, "t_name", "t_num", num); return map.get("t_name"); } @Override public boolean isUserExist(String num, String pwd) { // TODO Auto-generated method stub String sql = "SELECT tea_id FROM " + TABLE_NAME + " WHERE t_num=? AND t_pwd=?"; try { pst = con.prepareStatement(sql); pst.setString(1, num); pst.setString(2, pwd); rs = pst.executeQuery(); if (rs.next()) return true; else return false; } catch (SQLException e) { e.printStackTrace(); } return false; } public boolean isUserExist(String num) { String sql = "SELECT tea_id FROM " + TABLE_NAME + " WHERE t_num=?"; try { pst = con.prepareStatement(sql); pst.setString(1, num); rs = pst.executeQuery(); if (rs.next()) return true; else return false; } catch (SQLException e) { e.printStackTrace(); } return false; } public int getTeacherId(String tNum) { String sql = "SELECT tea_id FROM " + TABLE_NAME + " WHERE t_num=?"; try { pst = con.prepareStatement(sql); pst.setString(1, tNum); rs = pst.executeQuery(); if (rs.next()) return rs.getInt("tea_id"); } catch (SQLException e) { e.printStackTrace(); } return -1; } public boolean insertTeacher(Teacher t) { String sql = "INSERT INTO " + TABLE_NAME + " (t_num,t_name,t_pwd,dept_id,contact) VALUES(?,?,?,?,?)"; try { pst = con.prepareStatement(sql); pst.setString(1, t.getNum()); pst.setString(2, t.getName()); pst.setString(3, t.getPwd()); pst.setInt(4, t.getDept()); pst.setString(5, t.getContact()); pst.execute(); return true; } catch (SQLException e) { e.printStackTrace(); } return false; } // 出题 public boolean makeQuestion(int paperId, int clsId) { String sql = "INSERT INTO t_makeoutquestion(paper_id,cls_id) VALUES(?,?)"; try { pst = con.prepareStatement(sql); pst.setInt(1, paperId); pst.setInt(2, clsId); if (pst.executeUpdate() > 0) return true; } catch (SQLException e) { e.printStackTrace(); } return false; } // 是否已经出题了 public boolean isPaperBeenMadeout(int paperId, int clsId) { String sql = "SELECT _id FROM t_makeoutquestion WHERE paper_id=? AND cls_id=?"; try { pst = con.prepareStatement(sql); pst.setInt(1, paperId); pst.setInt(2, clsId); rs = pst.executeQuery(); if (rs.next()) return true; } catch (SQLException e) { e.printStackTrace(); } return false; } /* * 更新老师 */ public String updateTeacher(String tNum, String tName, String contact) { String sql = "UPDATE t_teacher SET t_name=?,contact=? WHERE t_num=?"; PreparedStatement p = null; String s = ""; try { p = con.prepareStatement(sql); p.setString(1, tName); p.setString(2, contact); p.setString(3, tNum); p.executeUpdate(); s = "修改成功"; } catch (SQLException e) { e.printStackTrace(); s = "修改失败"; } finally { try { p.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return s; } }
UTF-8
Java
7,410
java
TeacherService.java
Java
[ { "context": "private String num;// 编号\n\t\tprivate String name;// 姓名\n\t\tprivate String contact;// 联系方式\n\n\t\tpublic MyTeac", "end": 2933, "score": 0.9876192808151245, "start": 2931, "tag": "NAME", "value": "姓名" }, { "context": ".setDept(d);\n\t\t\tthis.setNum(num);\n\t\t\tthis.se...
null
[]
package test.serviceImpl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.slf4j.*; import test.beans.Teacher; import test.service.UserService; import test.utils.Dbutils; public class TeacherService implements UserService { private static Logger log = LoggerFactory.getLogger(TeacherService.class); private static final String TABLE_NAME = "t_teacher"; private static final Connection con = Dbutils.getConn(); private static PreparedStatement pst = null; private static ResultSet rs = null; /* */ public TeacherService() { } // 获取院系名称 public String getDept(int deptId) { String sql = "SELECT dept_name FROM t_dept WHERE dept_id=?"; try { pst = con.prepareStatement(sql); pst.setInt(1, deptId); rs = pst.executeQuery(); if (rs.next()) { return rs.getString("dept_name"); } } catch (SQLException e) { e.printStackTrace(); } return null; } public int getDeptId(String deptName) { String sql = "SELECT dept_id FROM t_dept WHERE dept_name=?"; try { pst = con.prepareStatement(sql); pst.setString(1, deptName); rs = pst.executeQuery(); if (rs.next()) { return rs.getInt("dept_id"); } } catch (SQLException e) { e.printStackTrace(); } return -1; } public String getInfo(String uname) { String sql = "select dept_id,t_name,contact from " + TABLE_NAME + " where t_num=?"; PreparedStatement mypst; ResultSet myrs; MyTeacher t = null; try { mypst = con.prepareStatement(sql); mypst.setString(1, uname); myrs = mypst.executeQuery(); // 因为在getDept方法中将类属性pst和rs改变了,所以出现Column 't_name' not found. if (myrs.next()) { t = new MyTeacher(getDept(myrs.getInt("dept_id")), uname, myrs.getString("t_name"), myrs.getString("contact")); } return JSONObject.fromObject(t).toString();// 将MyTeacher对象转变为json字符串 } catch (SQLException e) { e.printStackTrace(); log.info("数据库连接错误"); } return null; } // 获取所有老师信息 public List<MyTeacher> getTeacher() { String sql = "select t_num,dept_id,t_name,contact from " + TABLE_NAME; List<MyTeacher> list = new ArrayList<MyTeacher>(); PreparedStatement mypst; ResultSet myrs; try { mypst = con.prepareStatement(sql); myrs = mypst.executeQuery(); while (myrs.next()) { list.add(new MyTeacher(getDept(myrs.getInt("dept_id")), myrs .getString("t_num"), myrs.getString("t_name"), myrs .getString("contact"))); } return list; } catch (SQLException e) { e.printStackTrace(); } return null; } // 获取json数组字符串 public String getJsonArrayStr() { return JSONArray.fromObject(getTeacher()).toString(); } public class MyTeacher { private String dept;// 院系 private String num;// 编号 private String name;// 姓名 private String contact;// 联系方式 public MyTeacher() { } public MyTeacher(String d, String num, String name, String c) { this.setDept(d); this.setNum(num); this.setName(name); this.setContact(c); } public String getDept() { return dept; } public void setDept(String dept) { this.dept = dept; } public String getNum() { return num; } public void setNum(String num) { this.num = num; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } } public boolean modifyPwd(String num, String newPwd) { String sql = "UPDATE t_teacher SET t_pwd=? WHERE t_num=?"; Connection conn = Dbutils.getConn();// ��������ݿ�����ӡ� PreparedStatement pst = null; try { pst = conn.prepareStatement(sql); pst.setString(1, newPwd); pst.setString(2, num); if (pst.executeUpdate() > 0) return true; else return false; } catch (SQLException e) { e.printStackTrace(); } return false; } public String getNameByNum(String num) { Map<String, String> map = new DbServiceImpl().getSingleField( TABLE_NAME, "t_name", "t_num", num); return map.get("t_name"); } @Override public boolean isUserExist(String num, String pwd) { // TODO Auto-generated method stub String sql = "SELECT tea_id FROM " + TABLE_NAME + " WHERE t_num=? AND t_pwd=?"; try { pst = con.prepareStatement(sql); pst.setString(1, num); pst.setString(2, pwd); rs = pst.executeQuery(); if (rs.next()) return true; else return false; } catch (SQLException e) { e.printStackTrace(); } return false; } public boolean isUserExist(String num) { String sql = "SELECT tea_id FROM " + TABLE_NAME + " WHERE t_num=?"; try { pst = con.prepareStatement(sql); pst.setString(1, num); rs = pst.executeQuery(); if (rs.next()) return true; else return false; } catch (SQLException e) { e.printStackTrace(); } return false; } public int getTeacherId(String tNum) { String sql = "SELECT tea_id FROM " + TABLE_NAME + " WHERE t_num=?"; try { pst = con.prepareStatement(sql); pst.setString(1, tNum); rs = pst.executeQuery(); if (rs.next()) return rs.getInt("tea_id"); } catch (SQLException e) { e.printStackTrace(); } return -1; } public boolean insertTeacher(Teacher t) { String sql = "INSERT INTO " + TABLE_NAME + " (t_num,t_name,t_pwd,dept_id,contact) VALUES(?,?,?,?,?)"; try { pst = con.prepareStatement(sql); pst.setString(1, t.getNum()); pst.setString(2, t.getName()); pst.setString(3, t.getPwd()); pst.setInt(4, t.getDept()); pst.setString(5, t.getContact()); pst.execute(); return true; } catch (SQLException e) { e.printStackTrace(); } return false; } // 出题 public boolean makeQuestion(int paperId, int clsId) { String sql = "INSERT INTO t_makeoutquestion(paper_id,cls_id) VALUES(?,?)"; try { pst = con.prepareStatement(sql); pst.setInt(1, paperId); pst.setInt(2, clsId); if (pst.executeUpdate() > 0) return true; } catch (SQLException e) { e.printStackTrace(); } return false; } // 是否已经出题了 public boolean isPaperBeenMadeout(int paperId, int clsId) { String sql = "SELECT _id FROM t_makeoutquestion WHERE paper_id=? AND cls_id=?"; try { pst = con.prepareStatement(sql); pst.setInt(1, paperId); pst.setInt(2, clsId); rs = pst.executeQuery(); if (rs.next()) return true; } catch (SQLException e) { e.printStackTrace(); } return false; } /* * 更新老师 */ public String updateTeacher(String tNum, String tName, String contact) { String sql = "UPDATE t_teacher SET t_name=?,contact=? WHERE t_num=?"; PreparedStatement p = null; String s = ""; try { p = con.prepareStatement(sql); p.setString(1, tName); p.setString(2, contact); p.setString(3, tNum); p.executeUpdate(); s = "修改成功"; } catch (SQLException e) { e.printStackTrace(); s = "修改失败"; } finally { try { p.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return s; } }
7,410
0.648487
0.644879
314
21.949045
18.38921
81
false
false
0
0
0
0
0
0
2.643312
false
false
12
db0d8f9f6524f5f6a0f981811c0ce9fd257318de
34,402,688,055,761
79595075622ded0bf43023f716389f61d8e96e94
/app/src/main/java/android/filterpacks/imageproc/StraightenFilter.java
e57d1f1282bf82e35eaf61bf933644eb728c9737
[]
no_license
dstmath/OppoR15
https://github.com/dstmath/OppoR15
96f1f7bb4d9cfad47609316debc55095edcd6b56
b9a4da845af251213d7b4c1b35db3e2415290c96
refs/heads/master
2020-03-24T16:52:14.198000
2019-05-27T02:24:53
2019-05-27T02:24:53
142,840,716
7
4
null
null
null
null
null
null
null
null
null
null
null
null
null
package android.filterpacks.imageproc; import android.filterfw.core.Filter; import android.filterfw.core.FilterContext; import android.filterfw.core.Frame; import android.filterfw.core.FrameFormat; import android.filterfw.core.GenerateFieldPort; import android.filterfw.core.Program; import android.filterfw.core.ShaderProgram; import android.filterfw.format.ImageFormat; import android.filterfw.geometry.Point; import android.filterfw.geometry.Quad; public class StraightenFilter extends Filter { private static final float DEGREE_TO_RADIAN = 0.017453292f; @GenerateFieldPort(hasDefault = true, name = "angle") private float mAngle = 0.0f; private int mHeight = 0; @GenerateFieldPort(hasDefault = true, name = "maxAngle") private float mMaxAngle = 45.0f; private Program mProgram; private int mTarget = 0; @GenerateFieldPort(hasDefault = true, name = "tile_size") private int mTileSize = 640; private int mWidth = 0; public StraightenFilter(String name) { super(name); } public void setupPorts() { addMaskedInputPort("image", ImageFormat.create(3)); addOutputBasedOnInput("image", "image"); } public void initProgram(FilterContext context, int target) { switch (target) { case 3: ShaderProgram shaderProgram = ShaderProgram.createIdentity(context); shaderProgram.setMaximumTileSize(this.mTileSize); this.mProgram = shaderProgram; this.mTarget = target; return; default: throw new RuntimeException("Filter Sharpen does not support frames of target " + target + "!"); } } public void fieldPortValueUpdated(String name, FilterContext context) { if (this.mProgram != null) { updateParameters(); } } public void process(FilterContext context) { Frame input = pullInput("image"); FrameFormat inputFormat = input.getFormat(); if (this.mProgram == null || inputFormat.getTarget() != this.mTarget) { initProgram(context, inputFormat.getTarget()); } if (!(inputFormat.getWidth() == this.mWidth && inputFormat.getHeight() == this.mHeight)) { this.mWidth = inputFormat.getWidth(); this.mHeight = inputFormat.getHeight(); updateParameters(); } Frame output = context.getFrameManager().newFrame(inputFormat); this.mProgram.process(input, output); pushOutput("image", output); output.release(); } private void updateParameters() { float cosTheta = (float) Math.cos((double) (this.mAngle * DEGREE_TO_RADIAN)); float sinTheta = (float) Math.sin((double) (this.mAngle * DEGREE_TO_RADIAN)); if (this.mMaxAngle <= 0.0f) { throw new RuntimeException("Max angle is out of range (0-180)."); } this.mMaxAngle = this.mMaxAngle > 90.0f ? 90.0f : this.mMaxAngle; Point p0 = new Point(((-cosTheta) * ((float) this.mWidth)) + (((float) this.mHeight) * sinTheta), ((-sinTheta) * ((float) this.mWidth)) - (((float) this.mHeight) * cosTheta)); Point p1 = new Point((((float) this.mWidth) * cosTheta) + (((float) this.mHeight) * sinTheta), (((float) this.mWidth) * sinTheta) - (((float) this.mHeight) * cosTheta)); Point p2 = new Point(((-cosTheta) * ((float) this.mWidth)) - (((float) this.mHeight) * sinTheta), ((-sinTheta) * ((float) this.mWidth)) + (((float) this.mHeight) * cosTheta)); Point p3 = new Point((((float) this.mWidth) * cosTheta) - (((float) this.mHeight) * sinTheta), (((float) this.mWidth) * sinTheta) + (((float) this.mHeight) * cosTheta)); float scale = 0.5f * Math.min(((float) this.mWidth) / Math.max(Math.abs(p0.x), Math.abs(p1.x)), ((float) this.mHeight) / Math.max(Math.abs(p0.y), Math.abs(p1.y))); p0.set(((p0.x * scale) / ((float) this.mWidth)) + 0.5f, ((p0.y * scale) / ((float) this.mHeight)) + 0.5f); p1.set(((p1.x * scale) / ((float) this.mWidth)) + 0.5f, ((p1.y * scale) / ((float) this.mHeight)) + 0.5f); p2.set(((p2.x * scale) / ((float) this.mWidth)) + 0.5f, ((p2.y * scale) / ((float) this.mHeight)) + 0.5f); p3.set(((p3.x * scale) / ((float) this.mWidth)) + 0.5f, ((p3.y * scale) / ((float) this.mHeight)) + 0.5f); ((ShaderProgram) this.mProgram).setSourceRegion(new Quad(p0, p1, p2, p3)); } }
UTF-8
Java
4,448
java
StraightenFilter.java
Java
[]
null
[]
package android.filterpacks.imageproc; import android.filterfw.core.Filter; import android.filterfw.core.FilterContext; import android.filterfw.core.Frame; import android.filterfw.core.FrameFormat; import android.filterfw.core.GenerateFieldPort; import android.filterfw.core.Program; import android.filterfw.core.ShaderProgram; import android.filterfw.format.ImageFormat; import android.filterfw.geometry.Point; import android.filterfw.geometry.Quad; public class StraightenFilter extends Filter { private static final float DEGREE_TO_RADIAN = 0.017453292f; @GenerateFieldPort(hasDefault = true, name = "angle") private float mAngle = 0.0f; private int mHeight = 0; @GenerateFieldPort(hasDefault = true, name = "maxAngle") private float mMaxAngle = 45.0f; private Program mProgram; private int mTarget = 0; @GenerateFieldPort(hasDefault = true, name = "tile_size") private int mTileSize = 640; private int mWidth = 0; public StraightenFilter(String name) { super(name); } public void setupPorts() { addMaskedInputPort("image", ImageFormat.create(3)); addOutputBasedOnInput("image", "image"); } public void initProgram(FilterContext context, int target) { switch (target) { case 3: ShaderProgram shaderProgram = ShaderProgram.createIdentity(context); shaderProgram.setMaximumTileSize(this.mTileSize); this.mProgram = shaderProgram; this.mTarget = target; return; default: throw new RuntimeException("Filter Sharpen does not support frames of target " + target + "!"); } } public void fieldPortValueUpdated(String name, FilterContext context) { if (this.mProgram != null) { updateParameters(); } } public void process(FilterContext context) { Frame input = pullInput("image"); FrameFormat inputFormat = input.getFormat(); if (this.mProgram == null || inputFormat.getTarget() != this.mTarget) { initProgram(context, inputFormat.getTarget()); } if (!(inputFormat.getWidth() == this.mWidth && inputFormat.getHeight() == this.mHeight)) { this.mWidth = inputFormat.getWidth(); this.mHeight = inputFormat.getHeight(); updateParameters(); } Frame output = context.getFrameManager().newFrame(inputFormat); this.mProgram.process(input, output); pushOutput("image", output); output.release(); } private void updateParameters() { float cosTheta = (float) Math.cos((double) (this.mAngle * DEGREE_TO_RADIAN)); float sinTheta = (float) Math.sin((double) (this.mAngle * DEGREE_TO_RADIAN)); if (this.mMaxAngle <= 0.0f) { throw new RuntimeException("Max angle is out of range (0-180)."); } this.mMaxAngle = this.mMaxAngle > 90.0f ? 90.0f : this.mMaxAngle; Point p0 = new Point(((-cosTheta) * ((float) this.mWidth)) + (((float) this.mHeight) * sinTheta), ((-sinTheta) * ((float) this.mWidth)) - (((float) this.mHeight) * cosTheta)); Point p1 = new Point((((float) this.mWidth) * cosTheta) + (((float) this.mHeight) * sinTheta), (((float) this.mWidth) * sinTheta) - (((float) this.mHeight) * cosTheta)); Point p2 = new Point(((-cosTheta) * ((float) this.mWidth)) - (((float) this.mHeight) * sinTheta), ((-sinTheta) * ((float) this.mWidth)) + (((float) this.mHeight) * cosTheta)); Point p3 = new Point((((float) this.mWidth) * cosTheta) - (((float) this.mHeight) * sinTheta), (((float) this.mWidth) * sinTheta) + (((float) this.mHeight) * cosTheta)); float scale = 0.5f * Math.min(((float) this.mWidth) / Math.max(Math.abs(p0.x), Math.abs(p1.x)), ((float) this.mHeight) / Math.max(Math.abs(p0.y), Math.abs(p1.y))); p0.set(((p0.x * scale) / ((float) this.mWidth)) + 0.5f, ((p0.y * scale) / ((float) this.mHeight)) + 0.5f); p1.set(((p1.x * scale) / ((float) this.mWidth)) + 0.5f, ((p1.y * scale) / ((float) this.mHeight)) + 0.5f); p2.set(((p2.x * scale) / ((float) this.mWidth)) + 0.5f, ((p2.y * scale) / ((float) this.mHeight)) + 0.5f); p3.set(((p3.x * scale) / ((float) this.mWidth)) + 0.5f, ((p3.y * scale) / ((float) this.mHeight)) + 0.5f); ((ShaderProgram) this.mProgram).setSourceRegion(new Quad(p0, p1, p2, p3)); } }
4,448
0.625899
0.608588
90
48.422222
43.100395
183
false
false
0
0
0
0
0
0
0.877778
false
false
12
22e5829b1b54856a4eaf9d58fd70060d6a3eb572
11,854,109,757,558
cf16c7d6338fbaba40481104e14596fe040ff222
/src/main/java/org/flink/example/usercase/streaming/apollo/ConfigurationCenterManagerProxy.java
092cd1f4e8a3f721375ef0f9d106744da155c942
[]
no_license
phenixmzy/flinkcase-java
https://github.com/phenixmzy/flinkcase-java
91b3d727fb08ae4d5ec980bcd78cb6abbdd843f7
6449b05a4a50d0601236d0e9ce6467379d526170
refs/heads/master
2022-06-24T13:00:26.273000
2021-12-06T03:41:55
2021-12-06T03:41:55
215,257,517
0
0
null
false
2022-06-21T04:22:00
2019-10-15T09:19:39
2021-12-06T03:42:00
2022-06-21T04:22:00
221
0
0
4
Java
false
false
package org.flink.example.usercase.streaming.apollo; //import com.ctrip.framework.apollo.Config; //import com.ctrip.framework.apollo.ConfigChangeListener; //import com.ctrip.framework.apollo.ConfigService; //import com.ctrip.framework.apollo.model.ConfigChange; //import com.ctrip.framework.apollo.model.ConfigChangeEvent; import org.flink.example.usercase.streaming.application.ad.ConfigurationChange; public class ConfigurationCenterManagerProxy { /* private String configNameSpace; private String DEFAULT_VALUE = "undefined"; private Config config; private ConfigurationChange configurationChange; public ConfigurationCenterManagerProxy(String configNameSpace) { this.configNameSpace = configNameSpace; init(); } public void register(ConfigurationChange configurationChange) { this.configurationChange = configurationChange; } public void init() { config = ConfigService.getConfig(configNameSpace); config.addChangeListener(new ConfigChangeListener() { @Override public void onChange(ConfigChangeEvent configChangeEvent) { for (String key : configChangeEvent.changedKeys()) { ConfigChange change = configChangeEvent.getChange(key); configurationChange.update(key, change.getNewValue()); } } }); } public String getValue(String key) { return config.getProperty(key, DEFAULT_VALUE); }*/ }
UTF-8
Java
1,508
java
ConfigurationCenterManagerProxy.java
Java
[]
null
[]
package org.flink.example.usercase.streaming.apollo; //import com.ctrip.framework.apollo.Config; //import com.ctrip.framework.apollo.ConfigChangeListener; //import com.ctrip.framework.apollo.ConfigService; //import com.ctrip.framework.apollo.model.ConfigChange; //import com.ctrip.framework.apollo.model.ConfigChangeEvent; import org.flink.example.usercase.streaming.application.ad.ConfigurationChange; public class ConfigurationCenterManagerProxy { /* private String configNameSpace; private String DEFAULT_VALUE = "undefined"; private Config config; private ConfigurationChange configurationChange; public ConfigurationCenterManagerProxy(String configNameSpace) { this.configNameSpace = configNameSpace; init(); } public void register(ConfigurationChange configurationChange) { this.configurationChange = configurationChange; } public void init() { config = ConfigService.getConfig(configNameSpace); config.addChangeListener(new ConfigChangeListener() { @Override public void onChange(ConfigChangeEvent configChangeEvent) { for (String key : configChangeEvent.changedKeys()) { ConfigChange change = configChangeEvent.getChange(key); configurationChange.update(key, change.getNewValue()); } } }); } public String getValue(String key) { return config.getProperty(key, DEFAULT_VALUE); }*/ }
1,508
0.704244
0.704244
42
34.904762
26.60631
79
false
false
0
0
0
0
0
0
0.5
false
false
12
87c34eba6c3d91511fbaef1a00fc8aecbb0238ed
27,668,179,347,494
70f4193f299500585190526f61ed8274888da720
/app/src/main/java/com/jgkj/bxxc/tools/MapBase.java
3a4c0dcfb80a768b41b1f5ee33ddf6bde5c92b16
[]
no_license
EmptyPages0430/bxxc
https://github.com/EmptyPages0430/bxxc
b942f10f9c5fc82fe85f8151fe613121e698ac3e
05ef16765eaef0507ad4c982b931ba49fc181a3a
refs/heads/master
2021-01-23T07:25:49.430000
2017-03-28T08:36:07
2017-03-28T08:36:07
86,421,908
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jgkj.bxxc.tools; import android.content.Context; import android.view.View; import android.widget.Button; import android.widget.RadioGroup.OnCheckedChangeListener; import com.baidu.location.BDLocation; import com.baidu.location.BDLocationListener; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; import com.baidu.mapapi.map.BaiduMap; import com.baidu.mapapi.map.BitmapDescriptor; import com.baidu.mapapi.map.MapStatus; import com.baidu.mapapi.map.MapStatusUpdateFactory; import com.baidu.mapapi.map.MapView; import com.baidu.mapapi.map.MyLocationConfiguration; import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode; import com.baidu.mapapi.map.MyLocationData; import com.baidu.mapapi.model.LatLng; /** * 初始化BaiduMap */ public class MapBase{ // 定位相关 public LocationClient mLocClient; public MyLocationListenner myListener = new MyLocationListenner(); public LocationMode mCurrentMode; public BitmapDescriptor mCurrentMarker; public static final int accuracyCircleFillColor = 0xAAFFFF88; public static final int accuracyCircleStrokeColor = 0xAA00FF00; public MapView mMapView; public BaiduMap mBaiduMap; public Button btn; // UI相关 public OnCheckedChangeListener radioButtonListener; public Button requestLocButton,button2; boolean isFirstLoc = true; // 是否首次定位 public void mapView(Context context, View view) { // 地图初始化 mMapView = (MapView) view; mBaiduMap = mMapView.getMap(); // 开启定位图层 mBaiduMap.setMyLocationEnabled(true); // 定位初始化 mLocClient = new LocationClient(context); mLocClient.registerLocationListener(myListener); LocationClientOption option = new LocationClientOption(); option.setOpenGps(true);// 打开gps option.setCoorType("bd09ll"); // 设置坐标类型 option.setScanSpan(1000); mLocClient.setLocOption(option); mCurrentMode = LocationMode.FOLLOWING; mBaiduMap .setMyLocationConfigeration(new MyLocationConfiguration( mCurrentMode, true, mCurrentMarker)); mLocClient.start(); } /** * 定位SDK监听函数 */ public class MyLocationListenner implements BDLocationListener { @Override public void onReceiveLocation(BDLocation location) { // map view 销毁后不在处理新接收的位置 if (location == null || mMapView == null) { return; } MyLocationData locData = new MyLocationData.Builder() .accuracy(location.getRadius()) // 此处设置开发者获取到的方向信息,顺时针0-360 .direction(100).latitude(location.getLatitude()) .longitude(location.getLongitude()).build(); mBaiduMap.setMyLocationData(locData); if (isFirstLoc) { isFirstLoc = false; LatLng ll = new LatLng(location.getLatitude(), location.getLongitude()); MapStatus.Builder builder = new MapStatus.Builder(); builder.target(ll).zoom(18.0f); mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build())); } } public void onReceivePoi(BDLocation poiLocation) { } } }
UTF-8
Java
3,383
java
MapBase.java
Java
[]
null
[]
package com.jgkj.bxxc.tools; import android.content.Context; import android.view.View; import android.widget.Button; import android.widget.RadioGroup.OnCheckedChangeListener; import com.baidu.location.BDLocation; import com.baidu.location.BDLocationListener; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; import com.baidu.mapapi.map.BaiduMap; import com.baidu.mapapi.map.BitmapDescriptor; import com.baidu.mapapi.map.MapStatus; import com.baidu.mapapi.map.MapStatusUpdateFactory; import com.baidu.mapapi.map.MapView; import com.baidu.mapapi.map.MyLocationConfiguration; import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode; import com.baidu.mapapi.map.MyLocationData; import com.baidu.mapapi.model.LatLng; /** * 初始化BaiduMap */ public class MapBase{ // 定位相关 public LocationClient mLocClient; public MyLocationListenner myListener = new MyLocationListenner(); public LocationMode mCurrentMode; public BitmapDescriptor mCurrentMarker; public static final int accuracyCircleFillColor = 0xAAFFFF88; public static final int accuracyCircleStrokeColor = 0xAA00FF00; public MapView mMapView; public BaiduMap mBaiduMap; public Button btn; // UI相关 public OnCheckedChangeListener radioButtonListener; public Button requestLocButton,button2; boolean isFirstLoc = true; // 是否首次定位 public void mapView(Context context, View view) { // 地图初始化 mMapView = (MapView) view; mBaiduMap = mMapView.getMap(); // 开启定位图层 mBaiduMap.setMyLocationEnabled(true); // 定位初始化 mLocClient = new LocationClient(context); mLocClient.registerLocationListener(myListener); LocationClientOption option = new LocationClientOption(); option.setOpenGps(true);// 打开gps option.setCoorType("bd09ll"); // 设置坐标类型 option.setScanSpan(1000); mLocClient.setLocOption(option); mCurrentMode = LocationMode.FOLLOWING; mBaiduMap .setMyLocationConfigeration(new MyLocationConfiguration( mCurrentMode, true, mCurrentMarker)); mLocClient.start(); } /** * 定位SDK监听函数 */ public class MyLocationListenner implements BDLocationListener { @Override public void onReceiveLocation(BDLocation location) { // map view 销毁后不在处理新接收的位置 if (location == null || mMapView == null) { return; } MyLocationData locData = new MyLocationData.Builder() .accuracy(location.getRadius()) // 此处设置开发者获取到的方向信息,顺时针0-360 .direction(100).latitude(location.getLatitude()) .longitude(location.getLongitude()).build(); mBaiduMap.setMyLocationData(locData); if (isFirstLoc) { isFirstLoc = false; LatLng ll = new LatLng(location.getLatitude(), location.getLongitude()); MapStatus.Builder builder = new MapStatus.Builder(); builder.target(ll).zoom(18.0f); mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build())); } } public void onReceivePoi(BDLocation poiLocation) { } } }
3,383
0.695262
0.687519
100
31.290001
22.907333
93
false
false
0
0
0
0
0
0
0.69
false
false
12
19758f2e25d02c743eb9f1f441bd86264edd17f7
5,222,680,259,903
6c3a98ab39e673f1a0d84f6ab52d79f68ea1588a
/src/main/java/com/sherlochao/dao/FavoritesDao.java
033965834546b82097f228975c1c33a33dad7ba0
[]
no_license
jaycekon/photosharing
https://github.com/jaycekon/photosharing
7e2cf2f4db63b59a53babc8fdb4e75f45580ae29
6595088dcf92abcb1f965df0e23cb4b979750bd9
refs/heads/master
2021-01-18T10:31:01.108000
2017-03-08T16:46:43
2017-03-08T16:46:43
84,320,157
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sherlochao.dao; import java.util.List; import com.sherlochao.model.FavoriteMember; import com.sherlochao.model.FavoriteShared; import com.sherlochao.model.Favorites; import com.sherlochao.model.Member; public interface FavoritesDao { List<Favorites> queryFavById(Favorites favorites); void saveFav(Favorites favorites); void deleteAllFav(Favorites favorites); Integer saveFavMember(FavoriteMember favoriteMember); Integer saveFavShared(FavoriteShared favoriteShared); List<FavoriteMember> listFavMemberByMemberId(Integer memberId, Integer colMemberIdState); List<FavoriteShared> listFavSharedByMemberId(Integer memberId, Integer colSharedIdState); FavoriteMember findFavMemberById(Integer memberId, Integer colMemberId); FavoriteShared findFavSharedById(Integer memberId, Integer colSharedId); Integer updateFavMember(FavoriteMember favoriteMember); Integer updateFavShared(FavoriteShared favoriteShared); }
UTF-8
Java
948
java
FavoritesDao.java
Java
[]
null
[]
package com.sherlochao.dao; import java.util.List; import com.sherlochao.model.FavoriteMember; import com.sherlochao.model.FavoriteShared; import com.sherlochao.model.Favorites; import com.sherlochao.model.Member; public interface FavoritesDao { List<Favorites> queryFavById(Favorites favorites); void saveFav(Favorites favorites); void deleteAllFav(Favorites favorites); Integer saveFavMember(FavoriteMember favoriteMember); Integer saveFavShared(FavoriteShared favoriteShared); List<FavoriteMember> listFavMemberByMemberId(Integer memberId, Integer colMemberIdState); List<FavoriteShared> listFavSharedByMemberId(Integer memberId, Integer colSharedIdState); FavoriteMember findFavMemberById(Integer memberId, Integer colMemberId); FavoriteShared findFavSharedById(Integer memberId, Integer colSharedId); Integer updateFavMember(FavoriteMember favoriteMember); Integer updateFavShared(FavoriteShared favoriteShared); }
948
0.838608
0.838608
33
27.727272
28.900322
90
false
false
0
0
0
0
0
0
1.060606
false
false
12
5a9dcda78774b58f497777fad5474ad918793b5b
7,189,775,315,554
56c826e809110154cdf25197830c6005b93a999f
/src/main/java/com/totalenglish/controller/SubcategoriaController.java
3295cc0a82c9618c0b6233a356d836232d6795a1
[]
no_license
denimar/totalenglishsrv
https://github.com/denimar/totalenglishsrv
8eb460039b92daacbabd35cecaa215857544c76f
f3e4670cc87924c3e8d18ddee9773ef0d0a51d9d
refs/heads/master
2016-08-11T12:15:22.553000
2016-03-11T07:00:32
2016-03-11T07:00:32
52,491,979
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.totalenglish.controller; import java.io.IOException; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.totalenglish.model.T02CAT; import com.totalenglish.model.T03SCT; import com.totalenglish.model.T04PIT; import com.totalenglish.model.T90IMG; import com.totalenglish.service.T02CATService; import com.totalenglish.service.T03SCTService; import com.totalenglish.service.T04PITService; import com.totalenglish.service.T90IMGService; @RestController @RequestMapping("/subcategoria") public class SubcategoriaController { @Autowired private T02CATService t02catService; @Autowired private T03SCTService t03sctService; @Autowired private T04PITService t04pitService; @Autowired private T90IMGService t90imgService; @RequestMapping(value = "/list", produces = MediaType.APPLICATION_JSON_VALUE) public ObjetoRetorno<T03SCT> getCategorias(@RequestParam("cd_categoria") final int cd_categoria) { List<T03SCT> lista = t03sctService.list("t02cat.cd_categoria = " + cd_categoria); return new ObjetoRetorno<T03SCT>(true, lista); } @RequestMapping(value = "/get", produces = MediaType.APPLICATION_JSON_VALUE) public ObjetoRetorno<T03SCT> getSubcategoria(@RequestParam("cd_subcategoria") final int cd_subcategoria) { return new ObjetoRetorno<T03SCT>(true, t03sctService.load(cd_subcategoria)); } @RequestMapping(value = "/add", produces = MediaType.APPLICATION_JSON_VALUE) public ObjetoRetorno<T03SCT> addSubCategorias(@RequestParam("cd_categoria") final int cd_categoria, final String ds_subcategoria, final @RequestBody Map<String, String> bodyParam) throws IOException { T02CAT t02cat = t02catService.load(cd_categoria); //Adiciona a subcategoria T03SCT t03sct = new T03SCT(); t03sct.setT02cat(t02cat); t03sct.setDs_subcategoria(ds_subcategoria); t03sctService.add(t03sct); //Sempre que adicionamos uma subcategoria, uma Pasta "default" para os items deve ser também adicionada T04PIT t04pit = new T04PIT(); t04pit.setT03sct(t03sct); t04pit.setDs_pasta_item("default"); t04pitService.add(t04pit); //Adiciona a imagem da categoria T90IMG t90img = new T90IMG(); t90img.setT03sct(t03sct); byte[] imagem = t90imgService.getBytesFromUriImagem(bodyParam.get("bt_imagem_item")); t90img.setBt_imagem(imagem); t90imgService.add(t90img); return new ObjetoRetorno<T03SCT>(true, t03sct); } @RequestMapping(value = "/del", produces = MediaType.APPLICATION_JSON_VALUE) public ObjetoRetorno<T03SCT> delCategorias(@RequestParam("cd_subcategoria") final int cd_subcategoria) throws IOException { return new ObjetoRetorno<T03SCT>(true, t03sctService.delete(cd_subcategoria)); } @RequestMapping(value = "/upd", produces = MediaType.APPLICATION_JSON_VALUE) public ObjetoRetorno<T03SCT> updCategoria(@RequestParam("cd_subcategoria") final int cd_subcategoria, final String ds_subcategoria, final @RequestBody Map<String, String> bodyParam) throws IOException { //Edita a subcategoria T03SCT t03sct = t03sctService.load(cd_subcategoria); t03sct.setDs_subcategoria(ds_subcategoria); t03sctService.edit(t03sct); //Edita a imagem da subcategoria T90IMG t90img = t90imgService.list("cd_subcategoria = " + cd_subcategoria).get(0); byte[] imagem = t90imgService.getBytesFromUriImagem(bodyParam.get("bt_imagem_item")); t90img.setBt_imagem(imagem); t90imgService.edit(t90img); return new ObjetoRetorno<T03SCT>(true, t03sct); } }
UTF-8
Java
3,803
java
SubcategoriaController.java
Java
[]
null
[]
package com.totalenglish.controller; import java.io.IOException; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.totalenglish.model.T02CAT; import com.totalenglish.model.T03SCT; import com.totalenglish.model.T04PIT; import com.totalenglish.model.T90IMG; import com.totalenglish.service.T02CATService; import com.totalenglish.service.T03SCTService; import com.totalenglish.service.T04PITService; import com.totalenglish.service.T90IMGService; @RestController @RequestMapping("/subcategoria") public class SubcategoriaController { @Autowired private T02CATService t02catService; @Autowired private T03SCTService t03sctService; @Autowired private T04PITService t04pitService; @Autowired private T90IMGService t90imgService; @RequestMapping(value = "/list", produces = MediaType.APPLICATION_JSON_VALUE) public ObjetoRetorno<T03SCT> getCategorias(@RequestParam("cd_categoria") final int cd_categoria) { List<T03SCT> lista = t03sctService.list("t02cat.cd_categoria = " + cd_categoria); return new ObjetoRetorno<T03SCT>(true, lista); } @RequestMapping(value = "/get", produces = MediaType.APPLICATION_JSON_VALUE) public ObjetoRetorno<T03SCT> getSubcategoria(@RequestParam("cd_subcategoria") final int cd_subcategoria) { return new ObjetoRetorno<T03SCT>(true, t03sctService.load(cd_subcategoria)); } @RequestMapping(value = "/add", produces = MediaType.APPLICATION_JSON_VALUE) public ObjetoRetorno<T03SCT> addSubCategorias(@RequestParam("cd_categoria") final int cd_categoria, final String ds_subcategoria, final @RequestBody Map<String, String> bodyParam) throws IOException { T02CAT t02cat = t02catService.load(cd_categoria); //Adiciona a subcategoria T03SCT t03sct = new T03SCT(); t03sct.setT02cat(t02cat); t03sct.setDs_subcategoria(ds_subcategoria); t03sctService.add(t03sct); //Sempre que adicionamos uma subcategoria, uma Pasta "default" para os items deve ser também adicionada T04PIT t04pit = new T04PIT(); t04pit.setT03sct(t03sct); t04pit.setDs_pasta_item("default"); t04pitService.add(t04pit); //Adiciona a imagem da categoria T90IMG t90img = new T90IMG(); t90img.setT03sct(t03sct); byte[] imagem = t90imgService.getBytesFromUriImagem(bodyParam.get("bt_imagem_item")); t90img.setBt_imagem(imagem); t90imgService.add(t90img); return new ObjetoRetorno<T03SCT>(true, t03sct); } @RequestMapping(value = "/del", produces = MediaType.APPLICATION_JSON_VALUE) public ObjetoRetorno<T03SCT> delCategorias(@RequestParam("cd_subcategoria") final int cd_subcategoria) throws IOException { return new ObjetoRetorno<T03SCT>(true, t03sctService.delete(cd_subcategoria)); } @RequestMapping(value = "/upd", produces = MediaType.APPLICATION_JSON_VALUE) public ObjetoRetorno<T03SCT> updCategoria(@RequestParam("cd_subcategoria") final int cd_subcategoria, final String ds_subcategoria, final @RequestBody Map<String, String> bodyParam) throws IOException { //Edita a subcategoria T03SCT t03sct = t03sctService.load(cd_subcategoria); t03sct.setDs_subcategoria(ds_subcategoria); t03sctService.edit(t03sct); //Edita a imagem da subcategoria T90IMG t90img = t90imgService.list("cd_subcategoria = " + cd_subcategoria).get(0); byte[] imagem = t90imgService.getBytesFromUriImagem(bodyParam.get("bt_imagem_item")); t90img.setBt_imagem(imagem); t90imgService.edit(t90img); return new ObjetoRetorno<T03SCT>(true, t03sct); } }
3,803
0.781168
0.7404
95
39.021053
37.957588
204
false
false
0
0
0
0
0
0
1.915789
false
false
12
3fd48202827851d57210ea1446a8368728430e3b
4,466,766,037,025
8061faa075108cadf554b09e63cda488e6ffb787
/springmvc-05-car/src/main/java/com/etoak/controller/UserController.java
762ac7d5bd27440d4fba9919861a922a5429c410
[]
no_license
158402/et1911
https://github.com/158402/et1911
9cbb4ed88578dcc51e29a11f272a2789af5ef232
e12c23764af34523b0c9386e62ee9516b90fd196
refs/heads/master
2022-09-15T16:43:52.101000
2020-05-29T08:56:50
2020-05-29T08:56:50
264,868,191
0
0
null
false
2020-05-20T07:49:21
2020-05-18T07:55:04
2020-05-20T07:48:58
2020-05-20T07:49:20
22
0
0
2
Java
false
false
package com.etoak.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.codec.digest.DigestUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.util.ObjectUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.etoak.bean.User; import com.etoak.exception.Et1911LoginException; import com.etoak.service.UserService; @Controller @RequestMapping("/user") public class UserController { @Autowired UserService userService; @GetMapping("/getById") @ResponseBody public User getById(int id){ return userService.getById(id); } @GetMapping("/logout") public String logout(HttpServletRequest request,HttpServletResponse response){ //销毁session request.getSession().invalidate(); //退出之后重定向到登录页面 return "redirect:/user/toLogin"; } @PostMapping("/login") public String login(@RequestParam String name, //@RequestParam 获取前段页面参数 @RequestParam String password, @RequestParam String code, HttpServletRequest request){ //取出session中的验证码 和请求参数中的验证码进行比对 HttpSession session = request.getSession(); Object sessionCode = session.getAttribute("code"); System.out.println("session===>"+session.getAttribute("code")); if(!code.equals(sessionCode)){ throw new Et1911LoginException("验证码不正确"); } //验证用户 password = DigestUtils.md5Hex(password); User user = userService.getByNameAndPassword(name, password); if(ObjectUtils.isEmpty(user)){ throw new Et1911LoginException("用户名或密码不正确"); } //销毁之前的session session.invalidate(); session = request.getSession(); //将用户密码设置为null 重新获取session user.setPassword(null); session.setAttribute("user", user); System.out.println("session===>"+session.getAttribute("code")+session.getAttribute("user")); //登陆成功 跳到index页面 return "redirect:/"; } }
UTF-8
Java
2,399
java
UserController.java
Java
[ { "context": ";\n\t\t//将用户密码设置为null 重新获取session\n\t\tuser.setPassword(null);\n\t\tsession.setAttribute(\"user\", user);\n\t\tSystem.", "end": 2033, "score": 0.5288360714912415, "start": 2029, "tag": "PASSWORD", "value": "null" } ]
null
[]
package com.etoak.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.codec.digest.DigestUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.util.ObjectUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.etoak.bean.User; import com.etoak.exception.Et1911LoginException; import com.etoak.service.UserService; @Controller @RequestMapping("/user") public class UserController { @Autowired UserService userService; @GetMapping("/getById") @ResponseBody public User getById(int id){ return userService.getById(id); } @GetMapping("/logout") public String logout(HttpServletRequest request,HttpServletResponse response){ //销毁session request.getSession().invalidate(); //退出之后重定向到登录页面 return "redirect:/user/toLogin"; } @PostMapping("/login") public String login(@RequestParam String name, //@RequestParam 获取前段页面参数 @RequestParam String password, @RequestParam String code, HttpServletRequest request){ //取出session中的验证码 和请求参数中的验证码进行比对 HttpSession session = request.getSession(); Object sessionCode = session.getAttribute("code"); System.out.println("session===>"+session.getAttribute("code")); if(!code.equals(sessionCode)){ throw new Et1911LoginException("验证码不正确"); } //验证用户 password = DigestUtils.md5Hex(password); User user = userService.getByNameAndPassword(name, password); if(ObjectUtils.isEmpty(user)){ throw new Et1911LoginException("用户名或密码不正确"); } //销毁之前的session session.invalidate(); session = request.getSession(); //将用户密码设置为null 重新获取session user.setPassword(<PASSWORD>); session.setAttribute("user", user); System.out.println("session===>"+session.getAttribute("code")+session.getAttribute("user")); //登陆成功 跳到index页面 return "redirect:/"; } }
2,405
0.774382
0.768539
74
28.972973
22.357641
94
false
false
0
0
0
0
0
0
1.675676
false
false
12
d49b3a9dc8e2bacd916a39bbb51946c5609df83b
8,684,423,942,551
b8705fdeb3e5b44b9fbe5a6955fa816a2c8c6ee4
/src/main/java/com/ledao/service/impl/OverflowListServiceImpl.java
0b0d85063a16ad13c0aab443ff2ccb6c0a3521fd
[]
no_license
Floafe/JXC
https://github.com/Floafe/JXC
51f9354592e4f1e1376af53fcf4abb3331932628
3b596372eedeef79649096e51dcf696c574765e0
refs/heads/master
2023-05-02T08:08:39.495000
2021-05-30T21:00:27
2021-05-30T21:00:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ledao.service.impl; import com.ledao.entity.OverflowList; import com.ledao.entity.OverflowListGoods; import com.ledao.entity.Goods; import com.ledao.repository.OverflowListGoodsRepository; import com.ledao.repository.OverflowListRepository; import com.ledao.repository.GoodsRepository; import com.ledao.repository.GoodsTypeRepository; import com.ledao.service.OverflowListService; import com.ledao.util.StringUtil; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import java.util.Date; import java.util.List; /** * 商品报溢单Service实现类 * * @author LeDao * @company * @create 2020-01-13 22:44 */ @Service("searchOverflowListService") @Transactional(rollbackFor = Exception.class) public class OverflowListServiceImpl implements OverflowListService { @Resource private OverflowListRepository overflowListRepository; @Resource private GoodsTypeRepository goodsTypeRepository; @Resource private GoodsRepository goodsRepository; @Resource private OverflowListGoodsRepository overflowListGoodsRepository; /** * 获取当天最大商品报溢单号 * * @return */ @Override public String getTodayMaxOverflowNumber() { return overflowListRepository.getTodayMaxOverflowNumber(); } /** * 添加商品报溢单 以及所有商品报溢单商品 以及 修改商品成本价 库存数量 上次进价 * * @param searchOverflowList * @param searchOverflowListGoodsList */ @Override public void save(OverflowList searchOverflowList, List<OverflowListGoods> searchOverflowListGoodsList) { for (OverflowListGoods searchOverflowListGoods : searchOverflowListGoodsList) { //设置类别 searchOverflowListGoods.setType(goodsTypeRepository.findById(searchOverflowListGoods.getTypeId()).get()); //设置商品报溢单 searchOverflowListGoods.setOverflowList(searchOverflowList); overflowListGoodsRepository.save(searchOverflowListGoods); // 修改商品库存 Goods goods = goodsRepository.findById(searchOverflowListGoods.getGoodsId()).get(); goods.setInventoryQuantity(goods.getInventoryQuantity() + searchOverflowListGoods.getNum()); goods.setLastPurchasingPrice(searchOverflowListGoods.getPrice()); goods.setState(2); goodsRepository.save(goods); } searchOverflowList.setOverflowDate(new Date()); overflowListRepository.save(searchOverflowList); } @Override public List<OverflowList> list(OverflowList overflowList) { return overflowListRepository.findAll(new Specification<OverflowList>() { @Override public Predicate toPredicate(Root<OverflowList> root, CriteriaQuery<?> query, CriteriaBuilder cb) { Predicate predicate = cb.conjunction(); if (overflowList != null) { if (StringUtil.isNotEmpty(overflowList.getOverflowNumber())) { predicate.getExpressions().add(cb.like(root.get("overflowNumber"), "%" + overflowList.getOverflowNumber().trim() + "%")); } if (overflowList.getbOverflowDate() != null) { predicate.getExpressions().add(cb.greaterThanOrEqualTo(root.get("overflowDate"), overflowList.getbOverflowDate())); } if (overflowList.geteOverflowDate() != null) { predicate.getExpressions().add(cb.lessThanOrEqualTo(root.get("overflowDate"), overflowList.geteOverflowDate())); } } return predicate; } }); } /** * 根据id查询实体 * * @param overflowId * @return */ @Override public OverflowList findById(Integer overflowId) { return overflowListRepository.findById(overflowId).get(); } /** * 根据id删除商品报溢单信息 包括商品报溢单里的所有商品 * * @param id */ @Override public void delete(Integer id) { overflowListGoodsRepository.deleteByOverflowListId(id); overflowListRepository.deleteById(id); } }
UTF-8
Java
4,605
java
OverflowListServiceImpl.java
Java
[ { "context": "a.util.List;\n\n/**\n * 商品报溢单Service实现类\n *\n * @author LeDao\n * @company\n * @create 2020-01-13 22:44\n */\n@Serv", "end": 907, "score": 0.9842082262039185, "start": 902, "tag": "NAME", "value": "LeDao" } ]
null
[]
package com.ledao.service.impl; import com.ledao.entity.OverflowList; import com.ledao.entity.OverflowListGoods; import com.ledao.entity.Goods; import com.ledao.repository.OverflowListGoodsRepository; import com.ledao.repository.OverflowListRepository; import com.ledao.repository.GoodsRepository; import com.ledao.repository.GoodsTypeRepository; import com.ledao.service.OverflowListService; import com.ledao.util.StringUtil; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import java.util.Date; import java.util.List; /** * 商品报溢单Service实现类 * * @author LeDao * @company * @create 2020-01-13 22:44 */ @Service("searchOverflowListService") @Transactional(rollbackFor = Exception.class) public class OverflowListServiceImpl implements OverflowListService { @Resource private OverflowListRepository overflowListRepository; @Resource private GoodsTypeRepository goodsTypeRepository; @Resource private GoodsRepository goodsRepository; @Resource private OverflowListGoodsRepository overflowListGoodsRepository; /** * 获取当天最大商品报溢单号 * * @return */ @Override public String getTodayMaxOverflowNumber() { return overflowListRepository.getTodayMaxOverflowNumber(); } /** * 添加商品报溢单 以及所有商品报溢单商品 以及 修改商品成本价 库存数量 上次进价 * * @param searchOverflowList * @param searchOverflowListGoodsList */ @Override public void save(OverflowList searchOverflowList, List<OverflowListGoods> searchOverflowListGoodsList) { for (OverflowListGoods searchOverflowListGoods : searchOverflowListGoodsList) { //设置类别 searchOverflowListGoods.setType(goodsTypeRepository.findById(searchOverflowListGoods.getTypeId()).get()); //设置商品报溢单 searchOverflowListGoods.setOverflowList(searchOverflowList); overflowListGoodsRepository.save(searchOverflowListGoods); // 修改商品库存 Goods goods = goodsRepository.findById(searchOverflowListGoods.getGoodsId()).get(); goods.setInventoryQuantity(goods.getInventoryQuantity() + searchOverflowListGoods.getNum()); goods.setLastPurchasingPrice(searchOverflowListGoods.getPrice()); goods.setState(2); goodsRepository.save(goods); } searchOverflowList.setOverflowDate(new Date()); overflowListRepository.save(searchOverflowList); } @Override public List<OverflowList> list(OverflowList overflowList) { return overflowListRepository.findAll(new Specification<OverflowList>() { @Override public Predicate toPredicate(Root<OverflowList> root, CriteriaQuery<?> query, CriteriaBuilder cb) { Predicate predicate = cb.conjunction(); if (overflowList != null) { if (StringUtil.isNotEmpty(overflowList.getOverflowNumber())) { predicate.getExpressions().add(cb.like(root.get("overflowNumber"), "%" + overflowList.getOverflowNumber().trim() + "%")); } if (overflowList.getbOverflowDate() != null) { predicate.getExpressions().add(cb.greaterThanOrEqualTo(root.get("overflowDate"), overflowList.getbOverflowDate())); } if (overflowList.geteOverflowDate() != null) { predicate.getExpressions().add(cb.lessThanOrEqualTo(root.get("overflowDate"), overflowList.geteOverflowDate())); } } return predicate; } }); } /** * 根据id查询实体 * * @param overflowId * @return */ @Override public OverflowList findById(Integer overflowId) { return overflowListRepository.findById(overflowId).get(); } /** * 根据id删除商品报溢单信息 包括商品报溢单里的所有商品 * * @param id */ @Override public void delete(Integer id) { overflowListGoodsRepository.deleteByOverflowListId(id); overflowListRepository.deleteById(id); } }
4,605
0.686435
0.683481
125
34.208
32.14151
145
false
false
0
0
0
0
0
0
0.4
false
false
12
6d7e02a46baeea997961e7498aa45bda59b26acd
8,985,071,599,083
27d8f7de2fd78e6715423848b01d619d6faaf90e
/src/TutorialStage.java
d2211c70ebec27f3f09c00bb356faccfc2d7f2f8
[]
no_license
Cazra/YoBro_ManifestationOfTheCrimsonDemon
https://github.com/Cazra/YoBro_ManifestationOfTheCrimsonDemon
0e61fe9250203ee31d082209c2ae1c9b889a8586
d18773703456a51fe898a9461c3dad8115130410
refs/heads/master
2020-04-29T02:51:15.028000
2014-10-29T02:18:07
2014-10-29T02:18:07
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.awt.*; import java.awt.event.KeyEvent; import java.util.Random; import java.util.ArrayList; import gameEngine.*; public class TutorialStage extends Stage { // essential members // Sprites ABGTutorialSprite background; BossCitrus citrus; SpriteList bossSlaves; StageTextSprite textStageNum; StageTextSprite textStageTitle; // misc vars int spawnerX; int spawnerY; int CITRUS_SPEAK_X = mainLevel.SCREENW - 200; int CITRUS_SPEAK_Y = 100; int CITRUS_LISTEN_X = mainLevel.SCREENW - 180; int CITRUS_LISTEN_Y = 130; int CITRUS_OFF_X = mainLevel.SCREENW + 50; int CITRUS_OFF_Y = 300; int PLAYER_SPEAK_X = 00; int PLAYER_SPEAK_Y = 80; int PLAYER_LISTEN_X = -30; int PLAYER_LISTEN_Y = 110; int PLAYER_OFF_X = -200; int PLAYER_OFF_Y = 300; boolean movedLeft,movedRight,movedUp,movedDown,movedUpLeft,movedUpRight,movedDownLeft,movedDownRight; boolean dodged1; int killCount; /* * Constructor * Preconditions: ml is a reference to the game's main level interface which contains this stage. * Postconditions: This stage is initialized and loads its data. */ public TutorialStage(MainLevel ml, YoBroMainPanel mp) { super(ml, mp); spawnerX = 0; spawnerY = 0; movedLeft = false; movedRight = false; movedUp = false; movedDown = false; movedUpLeft = false; movedUpRight = false; movedDownLeft = false; movedDownRight = false; dodged1 = false; killCount = 0; } public TutorialStage(MainLevel ml, YoBroMainPanel mp, long initTimer) { this(ml,mp); timer = initTimer; } /** * void loadData() * This method should load any additional sprite images or sounds/music/things that this particular stage uses. * It should also initialize any initial sprites or level variables. */ protected void loadData() { // load additional graphics BossCitrus.loadImages(mainLevel.imgLoader); ABGTutorialSprite.loadImages(mainLevel.imgLoader); // load music mainLevel.loopMusic("sound/BombermanHero_-_Monogenic.mid"); // initialize Sprites and SpriteLists. background = new ABGTutorialSprite(mainLevel); // bossBullets = new SpriteList(); bossSlaves = new SpriteList(); citrus = new BossCitrus(-50,0, mainLevel); textStageNum = new StageTextSprite(150, 140, '1',""); textStageNum.setSemiTransparency(1.0); textStageNum.isVisible = false; textStageTitle = new StageTextSprite(200,200,'t',"Tutorial Stage"); textStageTitle.setSemiTransparency(1.0); textStageTitle.isVisible = false; textStageTitle.vars[1] = 5; } /** * void clean() * This method should free any resources that this stage uses. */ protected void clean() { super.clean(); citrus.destroy(); bossSlaves.destroyAll(); BossCitrus.clean(); } /** * void stageTimerLoop() * This method increments the stage's timer and runs the stage's logic based on the timer's current value. * Use the reference to mainLevel to have elements of the stage interact with the player, * player bullets, and the global main level variables. **/ public void stageTimerLoop() { super.stageTimerLoop(); int checkPt; DialogBoxSprite dBox = mainLevel.dBox; checkPt = 0; if(timer >= checkPt && timer < checkPt +60) { // stage title appears textStageTitle.isVisible = true; textStageTitle.setSemiTransparency(textStageTitle.getSemiTransparency()*0.95); textStageTitle.vars[0]+= 18; textStageTitle.vars[1] -= 2.0/30; if(textStageTitle.vars[0] > 360) textStageTitle.vars[0] -= 360; textStageTitle.scale(1.0,textStageTitle.vars[1] * GameMath.cos(textStageTitle.vars[0])); } checkPt = 100; if(timer >= checkPt && timer < checkPt +60) { // stage title disappears textStageTitle.setSemiTransparency(textStageTitle.getSemiTransparency()*1.1); if(textStageTitle.getSemiTransparency() >0.9) { textStageTitle.isVisible = false; } } checkPt += 150; if(timer == checkPt) { // start text runDialogScript(); } checkPt += 200; if(timer == checkPt) { dBox.paragraph++; runDialogScript(); } checkPt += 200; if(timer == checkPt) { dBox.paragraph++; runDialogScript(); } checkPt += 200; if(timer == checkPt) { dBox.paragraph++; runDialogScript(); } checkPt += 200; if(timer == checkPt) // try moving around!! { // start text dBox.paragraph++; runDialogScript(); } if(timer == checkPt+2) // prevent stage from progressing until the player moves in all eight directions. { timer--; if(keyboard.isPressed(config.VK_LEFT)) { movedLeft = true; if(keyboard.isPressed(config.VK_UP)) { movedUpLeft = true; } if(keyboard.isPressed(config.VK_DOWN)) { movedDownLeft = true; } } if(keyboard.isPressed(config.VK_RIGHT)) { movedRight = true; if(keyboard.isPressed(config.VK_UP)) { movedUpRight = true; } if(keyboard.isPressed(config.VK_DOWN)) { movedDownRight = true; } } if(keyboard.isPressed(config.VK_UP)) { movedUp = true; } if(keyboard.isPressed(config.VK_DOWN)) { movedDown = true; } if(movedUp && movedUpRight && movedRight && movedDownRight && movedDown && movedDownLeft && movedLeft && movedUpLeft) timer++; } checkPt += 50; if(timer == checkPt) { // Good! dBox.paragraph++; runDialogScript(); } checkPt += 100; int checkpoint1 = checkPt-1; if(timer == checkPt) { dBox.paragraph = 6; runDialogScript(); } checkPt += 100; if(timer == checkPt) { // spawn in enemy EnemySprite enemy = new EnemySprite(mainLevel.SCREENW/2,-10, 'a', 9999); enemy.aiType = 1; enemy.vars[1] = 150; enemies.add(enemy); dodged1 = true; } if(mainLevel.player.isDead) { dodged1 = false; } checkPt += 500; if(timer == checkPt) { mainLevel.dBox.isVisible = true; if(!dodged1) { int failMessage = mainLevel.rand.nextInt(3); dBox.paragraph = 7 + failMessage; runDialogScript(); } else { dBox.paragraph = 10; runDialogScript(); } } checkPt += 200; if(timer == checkPt) { if(!dodged1) { timer = checkpoint1; } else { dBox.paragraph++; runDialogScript(); } } checkPt += 200; if(timer == checkPt) { dBox.paragraph++; runDialogScript(); } checkPt += 200; int checkpoint2 = checkPt - 1; if(timer == checkPt) { dBox.paragraph = 13; runDialogScript(); } checkPt += 200; if(timer == checkPt) // slow dodging { EnemySprite enemy = new EnemySprite(mainLevel.SCREENW/2,0, 'a', 9999); enemy.aiType = 3; enemy.isVisible = false; enemies.add(enemy); dodged1 = true; } checkPt += 600; if(timer == checkPt) { mainLevel.dBox.isVisible = true; if(!dodged1) { int failMessage = mainLevel.rand.nextInt(3); dBox.paragraph = 14 + failMessage; runDialogScript(); } else { dBox.paragraph = 17; runDialogScript(); } } checkPt += 200; if(timer == checkPt) { if(!dodged1) { timer = checkpoint2; } else { dBox.paragraph++; runDialogScript(); } } checkPt += 200; if(timer == checkPt) { dBox.paragraph++; runDialogScript(); } checkPt += 200; if(timer == checkPt) { dBox.paragraph++; runDialogScript(); } checkPt += 200; if(timer == checkPt) { dBox.paragraph++; runDialogScript(); } checkPt += 200; int checkpoint3 = checkPt+1; if(timer == checkPt) // shooting tutorial { dBox.isVisible = false; killCount = 0; } if(timer >= checkPt && timer <= checkPt + 100 && timer % 30 == 0) { EnemySprite enemy = new EnemySprite(-10,200, 'd', 1); enemy.aiType = 4; enemy.vars[0] = 3; enemy.itemDrops.add(makeItem("ppP")); enemies.add(enemy); } if(timer >= checkPt + 100 && timer <= checkPt + 200 && timer % 30 == 0) { EnemySprite enemy = new EnemySprite(mainLevel.SCREENW+10,150, 'd', 1); enemy.aiType = 4; enemy.vars[0] = -3; enemy.itemDrops.add(makeItem("ppP")); enemies.add(enemy); } if(timer >= checkPt && timer <= checkPt + 200 && killCount >= 20) // success: destroy remaining enemies, magnet all items. { for(Object o : enemies) { EnemySprite enemy = (EnemySprite) o; mainLevel.spawnItems(enemy.itemDrops, enemy.x, enemy.y); FXSprite splosion; splosion = FXSprite.makeBurst1(enemy.x, enemy.y); mainLevel.sfx.add(splosion); for(int i = 0; i < 10; i++) { splosion = FXSprite.makeSimpleOrb2(enemy.x, enemy.y); mainLevel.sfx.add(splosion); } enemy.destroy(); timer = checkPt + 202; } for(Object o: bullets) { BulletSprite bullet = (BulletSprite) o; mainLevel.createBulletPoint(bullet); bullet.destroy(); } for(Object o: mainLevel.powerUps) { ItemSprite item = (ItemSprite) o; item.isMagneted = true; } } if(timer == checkPt + 201) { timer = checkpoint3; } checkPt += 300; int checkpoint4 = checkPt -1; if(timer == checkPt) { dBox.isVisible = true; dBox.paragraph=22; runDialogScript(); } checkPt += 200; if(timer == checkPt) // bomb tutorial (this section is designed to force the player to use a bomb) { dBox.isVisible = false; killCount = 0; dodged1 = true; } if(timer >= checkPt && timer <= checkPt + 100 && timer % 5 == 0) { EnemySprite enemy = new EnemySprite(mainLevel.rand.nextInt(mainLevel.SCREENW),-10, 'a', 1); enemy.aiType = 5; enemy.vars[1] = 2 + mainLevel.rand.nextInt(3)*.75; enemies.add(enemy); } checkPt += 400; if(timer == checkPt) { mainLevel.dBox.isVisible = true; if(!dodged1) { int failMessage = mainLevel.rand.nextInt(3); dBox.paragraph = 23 + failMessage; runDialogScript(); } else { dBox.paragraph = 26; runDialogScript(); } } checkPt += 200; if(timer == checkPt) { if(!dodged1) { timer = checkpoint4; } else { dBox.paragraph++; runDialogScript(); } } checkPt += 200; if(timer == checkPt) { dBox.paragraph++; runDialogScript(); ArrayList<ItemSprite> items = new ArrayList<ItemSprite>(); items.add(new ItemSprite(0,0,'B')); mainLevel.spawnItems(items,mainLevel.SCREENW/2,300); } checkPt += 200; if(timer == checkPt) { dBox.paragraph++; runDialogScript(); } checkPt += 200; if(timer == checkPt) { dBox.paragraph++; runDialogScript(); ArrayList<ItemSprite> items = new ArrayList<ItemSprite>(); items.add(new ItemSprite(0,0,'1')); mainLevel.spawnItems(items,mainLevel.SCREENW/2,300); } checkPt += 200; if(timer == checkPt) { dBox.paragraph++; runDialogScript(); } checkPt += 200; if(timer == checkPt) { dBox.paragraph++; runDialogScript(); ArrayList<ItemSprite> items = new ArrayList<ItemSprite>(); items.add(new ItemSprite(0,0,'F')); mainLevel.spawnItems(items,mainLevel.SCREENW/2,300); } checkPt += 200; if(timer == checkPt) { dBox.paragraph++; runDialogScript(); } checkPt += 200; if(timer == checkPt) { dBox.paragraph++; runDialogScript(); } checkPt += 300; if(timer == checkPt) { endStage = true; } // TEST LOOP AROUND if(timerPaused) timer--; checkPt += 200; if(timer > checkPt) timer = 0; this.runEnemyPatterns(); this.runBulletPatterns(); this.enemy2BulletCollisions(); this.updateSpriteLists(); } private void runEnemyPatterns() { for(Object o : enemies) { EnemySprite enemy = (EnemySprite) o; if(enemy.aiType == 0) { System.out.println("bad ai"); enemy.destroy(); } if(enemy.aiType == 1) { enemy.y += (enemy.vars[1] - enemy.y)/16.0; if(Math.abs(enemy.y - enemy.vars[1]) < 2) { enemy.aiType = 2; enemy.y = enemy.vars[1]; } } if(enemy.aiType == 2) { double angleToPlayer = GameMath.getAngleTo(enemy.x, enemy.y, mainLevel.player.x, mainLevel.player.y); mainLevel.dBox.isVisible = false; enemy.lookingAngle = angleToPlayer; if(enemy.vars[0] % 10 == 0) { BulletSprite bullet; bullet = new BulletSprite(enemy.x, enemy.y,'c',new Color(0x5500FF)); bullet.setVelocity(3.0,angleToPlayer); bullets.add(bullet); bullet = new BulletSprite(enemy.x, enemy.y,'c',new Color(0x5500FF)); bullet.setVelocity(3.0,angleToPlayer+10); bullets.add(bullet); bullet = new BulletSprite(enemy.x, enemy.y,'c',new Color(0x5500FF)); bullet.setVelocity(3.0,angleToPlayer-10); bullets.add(bullet); } if(enemy.vars[0] > 300) { FXSprite splosion; splosion = FXSprite.makeBurst1(enemy.x, enemy.y); mainLevel.sfx.add(splosion); enemy.destroy(); } enemy.vars[0]++; } if(enemy.aiType == 3) { mainLevel.dBox.isVisible = false; BulletSprite bullet; FXSprite splosion; if(enemy.vars[0] % 10 == 0) { enemy.x = mainLevel.rand.nextInt(mainLevel.SCREENW); splosion = FXSprite.makeBurst1(enemy.x, enemy.y); mainLevel.sfx.add(splosion); bullet = new BulletSprite(enemy.x, enemy.y,'c',new Color(0x3300CC)); bullet.scale(1.1,1.0); bullet.setVelocity(2.7,-90); bullets.add(bullet); enemy.x = mainLevel.rand.nextInt(mainLevel.SCREENW); splosion = FXSprite.makeBurst1(enemy.x, enemy.y); mainLevel.sfx.add(splosion); bullet = new BulletSprite(enemy.x, enemy.y,'d',new Color(0x5500FF)); bullet.setVelocity(3.0,-90); bullets.add(bullet); enemy.x = mainLevel.rand.nextInt(mainLevel.SCREENW); splosion = FXSprite.makeBurst1(enemy.x, enemy.y); mainLevel.sfx.add(splosion); bullet = new BulletSprite(enemy.x, enemy.y,'a',new Color(0x330088)); bullet.scale(1.2,1.0); bullet.setVelocity(2.3,-90); bullets.add(bullet); } if(enemy.vars[0] > 400) { enemy.destroy(); } enemy.vars[0]++; } if(enemy.aiType == 4) { enemy.x += enemy.vars[0]; if(enemy.vars[0] < 0) enemy.setDirection('W'); else enemy.setDirection('E'); double angleToPlayer = GameMath.getAngleTo(enemy.x, enemy.y, mainLevel.player.x, mainLevel.player.y); enemy.lookingAngle = angleToPlayer; if(enemy.vars[1] % 60 == 30) { BulletSprite bullet; bullet = new BulletSprite(enemy.x, enemy.y,'c',new Color(0xFF0055)); bullet.setVelocity(3.0,angleToPlayer); bullets.add(bullet); } if(enemy.x < -10 || enemy.x > mainLevel.SCREENW+10) enemy.destroy(); enemy.vars[1]++; } if(enemy.aiType == 5) { enemy.y += enemy.vars[1]; double angleToPlayer = GameMath.getAngleTo(enemy.x, enemy.y, mainLevel.player.x, mainLevel.player.y); if(enemy.vars[0] % 20 == 0) { BulletSprite bullet; bullet = new BulletSprite(enemy.x, enemy.y,'c',new Color(0xFF0055)); bullet.setVelocity(3.0,angleToPlayer); bullets.add(bullet); bullet = new BulletSprite(enemy.x, enemy.y,'c',new Color(0xFF0055)); bullet.setVelocity(3.0,angleToPlayer + 10); bullets.add(bullet); bullet = new BulletSprite(enemy.x, enemy.y,'c',new Color(0xFF0055)); bullet.setVelocity(3.0,angleToPlayer - 10); bullets.add(bullet); bullet = new BulletSprite(enemy.x, enemy.y,'c',new Color(0xFF0055)); bullet.setVelocity(3.0,angleToPlayer + 30); bullets.add(bullet); bullet = new BulletSprite(enemy.x, enemy.y,'c',new Color(0xFF0055)); bullet.setVelocity(3.0,angleToPlayer - 30); bullets.add(bullet); } if(enemy.y > mainLevel.SCREENH+10) enemy.destroy(); enemy.vars[0]++; } quadTree.insert(enemy); } } private void runMidBossLogic() { // dialog portrait positions mainLevel.barBossHealth.caption1 = "Citrus"; if(!mainLevel.reyPortrait.equals("attack")) { mainLevel.reyPortrait.vars[0] = PLAYER_OFF_X; mainLevel.reyPortrait.vars[1] = PLAYER_OFF_Y; } if(!citrus.portrait.emote.equals("attack")) { citrus.portrait.vars[0] = CITRUS_OFF_X; citrus.portrait.vars[1] = CITRUS_OFF_Y; } // AI modes if(citrus.aiMode == 0) // stop for boss dialogue (if any) { runDialogScript(); } quadTree.insert(citrus); } private void runDialogScript() { citrus.isActive = false; // Dialogue happens DialogBoxSprite dBox = mainLevel.dBox; dBox.isVisible = true; int para = 0; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Welcome to the tutorial stage!"; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Here, you'll learn the basics of \n" + "how to play Yo Bro."; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "This awesome bro riding the flying \n" + "skateboard is Rey. Rey Haiku."; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Use the arrow keys to move \n" + "around the screen."; } para++; if(dBox.paragraph == para) // 4 { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Try moving up, down, left,right, and \n" + "in each diagonal direction!"; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Good!"; } para++; if(dBox.paragraph == para) // 6 { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Now try moving around to \n" + "dodge this enemy's bullets!"; } para++; if(dBox.paragraph == para) // { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Yo, Man, that was terrible! Try again!"; } para++; if(dBox.paragraph == para) // { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "That was lame, Bro! Remember to \n" + "dodge this time!"; } para++; if(dBox.paragraph == para) // { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "I've seen shrine maidens\n" + "dodge better than that! AGAIN!!"; } para++; if(dBox.paragraph == para) // 10 { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Cool!"; } para++; if(dBox.paragraph == para) // 11 { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Usually, enemy bullets will be\n" + "closer together than that. "; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Hold the " + KeyEvent.getKeyText(config.VK_SLOW) + " key to \n" + "move in slow mode."; } para++; if(dBox.paragraph == para) // 13 { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Now dodge these bullets \n" + "using slow mode!!!"; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Try using the keyboard with \n" + "your fingers, not your face."; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Bro-tip: Dodge the bullets. \n" + "don't give them hugs!"; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "That was lame! This time, \n" + "try taking it slow, bro."; } para++; if(dBox.paragraph == para) // 17 { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Great!"; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Rey can do more than just dodge. He\n" + "can also return fire with his own attacks!"; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Hold the " + KeyEvent.getKeyText(config.VK_SHOT) + " key to shoot\n" + "using the attack mode you selected."; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Now, go dull out the harshness \n" + "on 20 enemies."; } para++; if(dBox.paragraph == para) // 21 { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Also, collect the red P blocks they drop. \n" + "They will increase your power!"; } para++; if(dBox.paragraph == para) // 22 { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Nice work so far! \n" + "But can you handle THIS?"; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "When things get tough, press " + KeyEvent.getKeyText(config.VK_BOMB) + " \n" + "to use bombs wisely!"; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Too tough? Try pressing "+ KeyEvent.getKeyText(config.VK_BOMB) + " \n" + "to use a powerful bomb attack."; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "That looks like it hurt! \n" + "Bro tip: Press " + KeyEvent.getKeyText(config.VK_BOMB) + " to nuke everything!"; } para++; if(dBox.paragraph == para) // 26 { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Awesome, bro! Remember though, you\n" + "have only a limited number of bombs."; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "You can get more bombs by collecting \n" + "green B-looking items..."; } para++; if(dBox.paragraph == para) // 28 { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "like this!"; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "You can also get more lives by \n" + "scoring enough points, or..."; } para++; if(dBox.paragraph == para) // 30 { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "grabbing purple, starry, 1up-y \n" + "items like this!"; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Also, if you lose all your lives, \n" + "and you choose to continue..."; } para++; if(dBox.paragraph == para) // 32 { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "one of these will spawn from \n" + "where you game-overed."; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "These golden F blocks will \n" + "fill your power up to MAX!"; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "This concludes the tutorial stage."; } para++; } private void runBulletPatterns() { for(Object o : bullets) { BulletSprite bullet = (BulletSprite) o; bullet.move(); if(isOffscreen(bullet) && bullet.screenKillable) bullet.destroy(); quadTree.insert(bullet); } } private boolean isOffscreen(Sprite s) { if(s.x < 0-s.width) { // System.out.println(s + " went offscreen"); return true; } if(s.x > mainLevel.SCREENW + s.width) { // System.out.println(s + " went offscreen"); return true; } if(s.y < 0-s.height) { // System.out.println(s + " went offscreen"); return true; } if(s.y > mainLevel.SCREENH + s.height) { // System.out.println(s + " went offscreen"); return true; } return false; } private double getAngleTo(double origX, double origY, double destX, double destY) { double dx = destX - origX; if(dx == 0) dx = 0.0001; double dy = origY - destY; if(dx > 0) { return Math.atan(dy/dx)/(2.0*Math.PI)*360.0; } else { return 180 + Math.atan(dy/dx)/(2.0*Math.PI)*360.0; } } /** * void enemy2BulletCollisions() * checks for collisions between player bullets and enemies. If a collision occurs, that player bullet is destroyed and that enemy takes damage. * * **/ private void enemy2BulletCollisions() { for(Object o : enemies) { EnemySprite smiley = (EnemySprite) o; ArrayList<Sprite> cList = quadTree.query(smiley); for(Sprite s : cList) { if(s instanceof PlayerBulletSprite) { PlayerBulletSprite pBullet = (PlayerBulletSprite) s; if(!smiley.isSpawner && smiley.collision(pBullet)) { if(smiley.damage(pBullet.damage)) { mainLevel.spawnItems(smiley.itemDrops, smiley.x, smiley.y); FXSprite splosion; splosion = FXSprite.makeBurst1(smiley.x, smiley.y); mainLevel.sfx.add(splosion); for(int i = 0; i < 10; i++) { // splosion = FXSprite.makeSimpleOrb2(smiley.x, smiley.y); splosion = FXSprite.makeSimpleOrb2(smiley.x, smiley.y); mainLevel.sfx.add(splosion); } mainLevel.soundPlayer.play("sound/zap01.wav"); killCount++; smiley.destroy(); } if(!pBullet.permanent) pBullet.destroy(); } } } } // collisions for midboss/boss ArrayList<Sprite> cList = quadTree.query(citrus); for(Sprite s : cList) { if(s instanceof PlayerBulletSprite) { PlayerBulletSprite pBullet = (PlayerBulletSprite) s; if(citrus.collision(pBullet) && citrus.isActive) { if(!pBullet.permanent) pBullet.destroy(); if(citrus.damage(pBullet.damage)) { mainLevel.spawnItems(citrus.itemDrops, citrus.x, citrus.y); citrus.isActive = false; citrus.timer = 0; citrus.hp = 200; mainLevel.numberSCTimer.value = 60; // System.out.println("skipped due to damage"); citrus.attackIndex++; break; } } } } } /** * void updateSpriteLists() * updates the stage's SpriteLists after collisions have been dealed with. * **/ private void updateSpriteLists() { enemies.update(); bullets.update(); } /* * Point getNearestEnemy(double x, double y) * gets the enemy closest to (x,y). Returns null if there are no enemies. * This is used by the Homing Yoyo attack. */ public Sprite getNearestEnemy(double x, double y) { Sprite nearestEnemy = null; double smallestDist = 0; for(Object o : enemies) { EnemySprite enemy = (EnemySprite) o; double dist = getSqrDist(x,y, enemy.x, enemy.y); if(!enemy.isSpawner && (nearestEnemy == null || dist < smallestDist)) { nearestEnemy = enemy; smallestDist = dist; } } if(citrus.isActive) { double dist = getSqrDist(x,y, citrus.x, citrus.y); if(nearestEnemy == null || dist < smallestDist) { nearestEnemy = citrus; smallestDist = dist; } } return nearestEnemy; } private double getSqrDist(double x1, double y1, double x2, double y2) { return (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2); } /////////// RENDERING STUFF /** * void animate(ImageLoader il) * This method should call the animate method for all of its sprites. It should be called in mainLevel's animateAllUnpaused() method. * Preconditions: il is the mainLevel's ImageLoader. **/ public void animate(ImageLoader il) { background.animate(il); enemies.animate(il); bullets.animate(il); // bossBullets.animate(il); bossSlaves.animate(il); citrus.animate(il); citrus.portrait.animate(il); textStageNum.animate(il); textStageTitle.animate(il); } /** * void renderEnemies(Graphics g2D) * This method renders all the stage's enemies. It should be called in mainLevel's render method. **/ public void renderEnemies(Graphics2D g2D) { enemies.render(g2D); bossSlaves.render(g2D); citrus.render(g2D); } /** * void renderBullets(Graphics g2D) * This method renders all the stage's enemy bullets. It should be called in mainLevel's render method. **/ public void renderBullets(Graphics2D g2D) { bullets.render(g2D); // bossBullets.render(g2D); } /** * void renderBackground(Graphics g2D) * This method renders all the stage's background graphics. It should be called in mainLevel's render method. **/ public void renderBackground(Graphics2D g2D) { g2D.setColor(new Color(0xFFAAAAFF, true)); g2D.fillRect(0, 0, mainLevel.SCREENW, mainLevel.SCREENH); background.render(g2D); } /** * void renderForeground(Graphics g2D) * This method renders all the stage's foreground graphics. It should be called in mainLevel's render method. **/ public void renderForeground(Graphics2D g2D) { citrus.portrait.render(g2D); textStageNum.render(g2D); textStageTitle.render(g2D); } }
UTF-8
Java
28,880
java
TutorialStage.java
Java
[ { "context": "ositions\n\t\t\n\t\tmainLevel.barBossHealth.caption1 = \"Citrus\";\n\t\t\n\t\tif(!mainLevel.reyPortrait.equals(\"att", "end": 16128, "score": 0.5070589184761047, "start": 16127, "tag": "NAME", "value": "C" }, { "context": "bro riding the flying \\n\" + \n\t\t\t\t\t\t\t\...
null
[]
import java.awt.*; import java.awt.event.KeyEvent; import java.util.Random; import java.util.ArrayList; import gameEngine.*; public class TutorialStage extends Stage { // essential members // Sprites ABGTutorialSprite background; BossCitrus citrus; SpriteList bossSlaves; StageTextSprite textStageNum; StageTextSprite textStageTitle; // misc vars int spawnerX; int spawnerY; int CITRUS_SPEAK_X = mainLevel.SCREENW - 200; int CITRUS_SPEAK_Y = 100; int CITRUS_LISTEN_X = mainLevel.SCREENW - 180; int CITRUS_LISTEN_Y = 130; int CITRUS_OFF_X = mainLevel.SCREENW + 50; int CITRUS_OFF_Y = 300; int PLAYER_SPEAK_X = 00; int PLAYER_SPEAK_Y = 80; int PLAYER_LISTEN_X = -30; int PLAYER_LISTEN_Y = 110; int PLAYER_OFF_X = -200; int PLAYER_OFF_Y = 300; boolean movedLeft,movedRight,movedUp,movedDown,movedUpLeft,movedUpRight,movedDownLeft,movedDownRight; boolean dodged1; int killCount; /* * Constructor * Preconditions: ml is a reference to the game's main level interface which contains this stage. * Postconditions: This stage is initialized and loads its data. */ public TutorialStage(MainLevel ml, YoBroMainPanel mp) { super(ml, mp); spawnerX = 0; spawnerY = 0; movedLeft = false; movedRight = false; movedUp = false; movedDown = false; movedUpLeft = false; movedUpRight = false; movedDownLeft = false; movedDownRight = false; dodged1 = false; killCount = 0; } public TutorialStage(MainLevel ml, YoBroMainPanel mp, long initTimer) { this(ml,mp); timer = initTimer; } /** * void loadData() * This method should load any additional sprite images or sounds/music/things that this particular stage uses. * It should also initialize any initial sprites or level variables. */ protected void loadData() { // load additional graphics BossCitrus.loadImages(mainLevel.imgLoader); ABGTutorialSprite.loadImages(mainLevel.imgLoader); // load music mainLevel.loopMusic("sound/BombermanHero_-_Monogenic.mid"); // initialize Sprites and SpriteLists. background = new ABGTutorialSprite(mainLevel); // bossBullets = new SpriteList(); bossSlaves = new SpriteList(); citrus = new BossCitrus(-50,0, mainLevel); textStageNum = new StageTextSprite(150, 140, '1',""); textStageNum.setSemiTransparency(1.0); textStageNum.isVisible = false; textStageTitle = new StageTextSprite(200,200,'t',"Tutorial Stage"); textStageTitle.setSemiTransparency(1.0); textStageTitle.isVisible = false; textStageTitle.vars[1] = 5; } /** * void clean() * This method should free any resources that this stage uses. */ protected void clean() { super.clean(); citrus.destroy(); bossSlaves.destroyAll(); BossCitrus.clean(); } /** * void stageTimerLoop() * This method increments the stage's timer and runs the stage's logic based on the timer's current value. * Use the reference to mainLevel to have elements of the stage interact with the player, * player bullets, and the global main level variables. **/ public void stageTimerLoop() { super.stageTimerLoop(); int checkPt; DialogBoxSprite dBox = mainLevel.dBox; checkPt = 0; if(timer >= checkPt && timer < checkPt +60) { // stage title appears textStageTitle.isVisible = true; textStageTitle.setSemiTransparency(textStageTitle.getSemiTransparency()*0.95); textStageTitle.vars[0]+= 18; textStageTitle.vars[1] -= 2.0/30; if(textStageTitle.vars[0] > 360) textStageTitle.vars[0] -= 360; textStageTitle.scale(1.0,textStageTitle.vars[1] * GameMath.cos(textStageTitle.vars[0])); } checkPt = 100; if(timer >= checkPt && timer < checkPt +60) { // stage title disappears textStageTitle.setSemiTransparency(textStageTitle.getSemiTransparency()*1.1); if(textStageTitle.getSemiTransparency() >0.9) { textStageTitle.isVisible = false; } } checkPt += 150; if(timer == checkPt) { // start text runDialogScript(); } checkPt += 200; if(timer == checkPt) { dBox.paragraph++; runDialogScript(); } checkPt += 200; if(timer == checkPt) { dBox.paragraph++; runDialogScript(); } checkPt += 200; if(timer == checkPt) { dBox.paragraph++; runDialogScript(); } checkPt += 200; if(timer == checkPt) // try moving around!! { // start text dBox.paragraph++; runDialogScript(); } if(timer == checkPt+2) // prevent stage from progressing until the player moves in all eight directions. { timer--; if(keyboard.isPressed(config.VK_LEFT)) { movedLeft = true; if(keyboard.isPressed(config.VK_UP)) { movedUpLeft = true; } if(keyboard.isPressed(config.VK_DOWN)) { movedDownLeft = true; } } if(keyboard.isPressed(config.VK_RIGHT)) { movedRight = true; if(keyboard.isPressed(config.VK_UP)) { movedUpRight = true; } if(keyboard.isPressed(config.VK_DOWN)) { movedDownRight = true; } } if(keyboard.isPressed(config.VK_UP)) { movedUp = true; } if(keyboard.isPressed(config.VK_DOWN)) { movedDown = true; } if(movedUp && movedUpRight && movedRight && movedDownRight && movedDown && movedDownLeft && movedLeft && movedUpLeft) timer++; } checkPt += 50; if(timer == checkPt) { // Good! dBox.paragraph++; runDialogScript(); } checkPt += 100; int checkpoint1 = checkPt-1; if(timer == checkPt) { dBox.paragraph = 6; runDialogScript(); } checkPt += 100; if(timer == checkPt) { // spawn in enemy EnemySprite enemy = new EnemySprite(mainLevel.SCREENW/2,-10, 'a', 9999); enemy.aiType = 1; enemy.vars[1] = 150; enemies.add(enemy); dodged1 = true; } if(mainLevel.player.isDead) { dodged1 = false; } checkPt += 500; if(timer == checkPt) { mainLevel.dBox.isVisible = true; if(!dodged1) { int failMessage = mainLevel.rand.nextInt(3); dBox.paragraph = 7 + failMessage; runDialogScript(); } else { dBox.paragraph = 10; runDialogScript(); } } checkPt += 200; if(timer == checkPt) { if(!dodged1) { timer = checkpoint1; } else { dBox.paragraph++; runDialogScript(); } } checkPt += 200; if(timer == checkPt) { dBox.paragraph++; runDialogScript(); } checkPt += 200; int checkpoint2 = checkPt - 1; if(timer == checkPt) { dBox.paragraph = 13; runDialogScript(); } checkPt += 200; if(timer == checkPt) // slow dodging { EnemySprite enemy = new EnemySprite(mainLevel.SCREENW/2,0, 'a', 9999); enemy.aiType = 3; enemy.isVisible = false; enemies.add(enemy); dodged1 = true; } checkPt += 600; if(timer == checkPt) { mainLevel.dBox.isVisible = true; if(!dodged1) { int failMessage = mainLevel.rand.nextInt(3); dBox.paragraph = 14 + failMessage; runDialogScript(); } else { dBox.paragraph = 17; runDialogScript(); } } checkPt += 200; if(timer == checkPt) { if(!dodged1) { timer = checkpoint2; } else { dBox.paragraph++; runDialogScript(); } } checkPt += 200; if(timer == checkPt) { dBox.paragraph++; runDialogScript(); } checkPt += 200; if(timer == checkPt) { dBox.paragraph++; runDialogScript(); } checkPt += 200; if(timer == checkPt) { dBox.paragraph++; runDialogScript(); } checkPt += 200; int checkpoint3 = checkPt+1; if(timer == checkPt) // shooting tutorial { dBox.isVisible = false; killCount = 0; } if(timer >= checkPt && timer <= checkPt + 100 && timer % 30 == 0) { EnemySprite enemy = new EnemySprite(-10,200, 'd', 1); enemy.aiType = 4; enemy.vars[0] = 3; enemy.itemDrops.add(makeItem("ppP")); enemies.add(enemy); } if(timer >= checkPt + 100 && timer <= checkPt + 200 && timer % 30 == 0) { EnemySprite enemy = new EnemySprite(mainLevel.SCREENW+10,150, 'd', 1); enemy.aiType = 4; enemy.vars[0] = -3; enemy.itemDrops.add(makeItem("ppP")); enemies.add(enemy); } if(timer >= checkPt && timer <= checkPt + 200 && killCount >= 20) // success: destroy remaining enemies, magnet all items. { for(Object o : enemies) { EnemySprite enemy = (EnemySprite) o; mainLevel.spawnItems(enemy.itemDrops, enemy.x, enemy.y); FXSprite splosion; splosion = FXSprite.makeBurst1(enemy.x, enemy.y); mainLevel.sfx.add(splosion); for(int i = 0; i < 10; i++) { splosion = FXSprite.makeSimpleOrb2(enemy.x, enemy.y); mainLevel.sfx.add(splosion); } enemy.destroy(); timer = checkPt + 202; } for(Object o: bullets) { BulletSprite bullet = (BulletSprite) o; mainLevel.createBulletPoint(bullet); bullet.destroy(); } for(Object o: mainLevel.powerUps) { ItemSprite item = (ItemSprite) o; item.isMagneted = true; } } if(timer == checkPt + 201) { timer = checkpoint3; } checkPt += 300; int checkpoint4 = checkPt -1; if(timer == checkPt) { dBox.isVisible = true; dBox.paragraph=22; runDialogScript(); } checkPt += 200; if(timer == checkPt) // bomb tutorial (this section is designed to force the player to use a bomb) { dBox.isVisible = false; killCount = 0; dodged1 = true; } if(timer >= checkPt && timer <= checkPt + 100 && timer % 5 == 0) { EnemySprite enemy = new EnemySprite(mainLevel.rand.nextInt(mainLevel.SCREENW),-10, 'a', 1); enemy.aiType = 5; enemy.vars[1] = 2 + mainLevel.rand.nextInt(3)*.75; enemies.add(enemy); } checkPt += 400; if(timer == checkPt) { mainLevel.dBox.isVisible = true; if(!dodged1) { int failMessage = mainLevel.rand.nextInt(3); dBox.paragraph = 23 + failMessage; runDialogScript(); } else { dBox.paragraph = 26; runDialogScript(); } } checkPt += 200; if(timer == checkPt) { if(!dodged1) { timer = checkpoint4; } else { dBox.paragraph++; runDialogScript(); } } checkPt += 200; if(timer == checkPt) { dBox.paragraph++; runDialogScript(); ArrayList<ItemSprite> items = new ArrayList<ItemSprite>(); items.add(new ItemSprite(0,0,'B')); mainLevel.spawnItems(items,mainLevel.SCREENW/2,300); } checkPt += 200; if(timer == checkPt) { dBox.paragraph++; runDialogScript(); } checkPt += 200; if(timer == checkPt) { dBox.paragraph++; runDialogScript(); ArrayList<ItemSprite> items = new ArrayList<ItemSprite>(); items.add(new ItemSprite(0,0,'1')); mainLevel.spawnItems(items,mainLevel.SCREENW/2,300); } checkPt += 200; if(timer == checkPt) { dBox.paragraph++; runDialogScript(); } checkPt += 200; if(timer == checkPt) { dBox.paragraph++; runDialogScript(); ArrayList<ItemSprite> items = new ArrayList<ItemSprite>(); items.add(new ItemSprite(0,0,'F')); mainLevel.spawnItems(items,mainLevel.SCREENW/2,300); } checkPt += 200; if(timer == checkPt) { dBox.paragraph++; runDialogScript(); } checkPt += 200; if(timer == checkPt) { dBox.paragraph++; runDialogScript(); } checkPt += 300; if(timer == checkPt) { endStage = true; } // TEST LOOP AROUND if(timerPaused) timer--; checkPt += 200; if(timer > checkPt) timer = 0; this.runEnemyPatterns(); this.runBulletPatterns(); this.enemy2BulletCollisions(); this.updateSpriteLists(); } private void runEnemyPatterns() { for(Object o : enemies) { EnemySprite enemy = (EnemySprite) o; if(enemy.aiType == 0) { System.out.println("bad ai"); enemy.destroy(); } if(enemy.aiType == 1) { enemy.y += (enemy.vars[1] - enemy.y)/16.0; if(Math.abs(enemy.y - enemy.vars[1]) < 2) { enemy.aiType = 2; enemy.y = enemy.vars[1]; } } if(enemy.aiType == 2) { double angleToPlayer = GameMath.getAngleTo(enemy.x, enemy.y, mainLevel.player.x, mainLevel.player.y); mainLevel.dBox.isVisible = false; enemy.lookingAngle = angleToPlayer; if(enemy.vars[0] % 10 == 0) { BulletSprite bullet; bullet = new BulletSprite(enemy.x, enemy.y,'c',new Color(0x5500FF)); bullet.setVelocity(3.0,angleToPlayer); bullets.add(bullet); bullet = new BulletSprite(enemy.x, enemy.y,'c',new Color(0x5500FF)); bullet.setVelocity(3.0,angleToPlayer+10); bullets.add(bullet); bullet = new BulletSprite(enemy.x, enemy.y,'c',new Color(0x5500FF)); bullet.setVelocity(3.0,angleToPlayer-10); bullets.add(bullet); } if(enemy.vars[0] > 300) { FXSprite splosion; splosion = FXSprite.makeBurst1(enemy.x, enemy.y); mainLevel.sfx.add(splosion); enemy.destroy(); } enemy.vars[0]++; } if(enemy.aiType == 3) { mainLevel.dBox.isVisible = false; BulletSprite bullet; FXSprite splosion; if(enemy.vars[0] % 10 == 0) { enemy.x = mainLevel.rand.nextInt(mainLevel.SCREENW); splosion = FXSprite.makeBurst1(enemy.x, enemy.y); mainLevel.sfx.add(splosion); bullet = new BulletSprite(enemy.x, enemy.y,'c',new Color(0x3300CC)); bullet.scale(1.1,1.0); bullet.setVelocity(2.7,-90); bullets.add(bullet); enemy.x = mainLevel.rand.nextInt(mainLevel.SCREENW); splosion = FXSprite.makeBurst1(enemy.x, enemy.y); mainLevel.sfx.add(splosion); bullet = new BulletSprite(enemy.x, enemy.y,'d',new Color(0x5500FF)); bullet.setVelocity(3.0,-90); bullets.add(bullet); enemy.x = mainLevel.rand.nextInt(mainLevel.SCREENW); splosion = FXSprite.makeBurst1(enemy.x, enemy.y); mainLevel.sfx.add(splosion); bullet = new BulletSprite(enemy.x, enemy.y,'a',new Color(0x330088)); bullet.scale(1.2,1.0); bullet.setVelocity(2.3,-90); bullets.add(bullet); } if(enemy.vars[0] > 400) { enemy.destroy(); } enemy.vars[0]++; } if(enemy.aiType == 4) { enemy.x += enemy.vars[0]; if(enemy.vars[0] < 0) enemy.setDirection('W'); else enemy.setDirection('E'); double angleToPlayer = GameMath.getAngleTo(enemy.x, enemy.y, mainLevel.player.x, mainLevel.player.y); enemy.lookingAngle = angleToPlayer; if(enemy.vars[1] % 60 == 30) { BulletSprite bullet; bullet = new BulletSprite(enemy.x, enemy.y,'c',new Color(0xFF0055)); bullet.setVelocity(3.0,angleToPlayer); bullets.add(bullet); } if(enemy.x < -10 || enemy.x > mainLevel.SCREENW+10) enemy.destroy(); enemy.vars[1]++; } if(enemy.aiType == 5) { enemy.y += enemy.vars[1]; double angleToPlayer = GameMath.getAngleTo(enemy.x, enemy.y, mainLevel.player.x, mainLevel.player.y); if(enemy.vars[0] % 20 == 0) { BulletSprite bullet; bullet = new BulletSprite(enemy.x, enemy.y,'c',new Color(0xFF0055)); bullet.setVelocity(3.0,angleToPlayer); bullets.add(bullet); bullet = new BulletSprite(enemy.x, enemy.y,'c',new Color(0xFF0055)); bullet.setVelocity(3.0,angleToPlayer + 10); bullets.add(bullet); bullet = new BulletSprite(enemy.x, enemy.y,'c',new Color(0xFF0055)); bullet.setVelocity(3.0,angleToPlayer - 10); bullets.add(bullet); bullet = new BulletSprite(enemy.x, enemy.y,'c',new Color(0xFF0055)); bullet.setVelocity(3.0,angleToPlayer + 30); bullets.add(bullet); bullet = new BulletSprite(enemy.x, enemy.y,'c',new Color(0xFF0055)); bullet.setVelocity(3.0,angleToPlayer - 30); bullets.add(bullet); } if(enemy.y > mainLevel.SCREENH+10) enemy.destroy(); enemy.vars[0]++; } quadTree.insert(enemy); } } private void runMidBossLogic() { // dialog portrait positions mainLevel.barBossHealth.caption1 = "Citrus"; if(!mainLevel.reyPortrait.equals("attack")) { mainLevel.reyPortrait.vars[0] = PLAYER_OFF_X; mainLevel.reyPortrait.vars[1] = PLAYER_OFF_Y; } if(!citrus.portrait.emote.equals("attack")) { citrus.portrait.vars[0] = CITRUS_OFF_X; citrus.portrait.vars[1] = CITRUS_OFF_Y; } // AI modes if(citrus.aiMode == 0) // stop for boss dialogue (if any) { runDialogScript(); } quadTree.insert(citrus); } private void runDialogScript() { citrus.isActive = false; // Dialogue happens DialogBoxSprite dBox = mainLevel.dBox; dBox.isVisible = true; int para = 0; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Welcome to the tutorial stage!"; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Here, you'll learn the basics of \n" + "how to play Yo Bro."; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "This awesome bro riding the flying \n" + "skateboard is <NAME>."; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Use the arrow keys to move \n" + "around the screen."; } para++; if(dBox.paragraph == para) // 4 { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Try moving up, down, left,right, and \n" + "in each diagonal direction!"; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Good!"; } para++; if(dBox.paragraph == para) // 6 { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Now try moving around to \n" + "dodge this enemy's bullets!"; } para++; if(dBox.paragraph == para) // { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Yo, Man, that was terrible! Try again!"; } para++; if(dBox.paragraph == para) // { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "That was lame, Bro! Remember to \n" + "dodge this time!"; } para++; if(dBox.paragraph == para) // { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "I've seen shrine maidens\n" + "dodge better than that! AGAIN!!"; } para++; if(dBox.paragraph == para) // 10 { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Cool!"; } para++; if(dBox.paragraph == para) // 11 { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Usually, enemy bullets will be\n" + "closer together than that. "; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Hold the " + KeyEvent.getKeyText(config.VK_SLOW) + " key to \n" + "move in slow mode."; } para++; if(dBox.paragraph == para) // 13 { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Now dodge these bullets \n" + "using slow mode!!!"; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Try using the keyboard with \n" + "your fingers, not your face."; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Bro-tip: Dodge the bullets. \n" + "don't give them hugs!"; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "That was lame! This time, \n" + "try taking it slow, bro."; } para++; if(dBox.paragraph == para) // 17 { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Great!"; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Rey can do more than just dodge. He\n" + "can also return fire with his own attacks!"; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Hold the " + KeyEvent.getKeyText(config.VK_SHOT) + " key to shoot\n" + "using the attack mode you selected."; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Now, go dull out the harshness \n" + "on 20 enemies."; } para++; if(dBox.paragraph == para) // 21 { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Also, collect the red P blocks they drop. \n" + "They will increase your power!"; } para++; if(dBox.paragraph == para) // 22 { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Nice work so far! \n" + "But can you handle THIS?"; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "When things get tough, press " + KeyEvent.getKeyText(config.VK_BOMB) + " \n" + "to use bombs wisely!"; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Too tough? Try pressing "+ KeyEvent.getKeyText(config.VK_BOMB) + " \n" + "to use a powerful bomb attack."; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "That looks like it hurt! \n" + "Bro tip: Press " + KeyEvent.getKeyText(config.VK_BOMB) + " to nuke everything!"; } para++; if(dBox.paragraph == para) // 26 { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Awesome, bro! Remember though, you\n" + "have only a limited number of bombs."; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "You can get more bombs by collecting \n" + "green B-looking items..."; } para++; if(dBox.paragraph == para) // 28 { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "like this!"; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "You can also get more lives by \n" + "scoring enough points, or..."; } para++; if(dBox.paragraph == para) // 30 { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "grabbing purple, starry, 1up-y \n" + "items like this!"; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "Also, if you lose all your lives, \n" + "and you choose to continue..."; } para++; if(dBox.paragraph == para) // 32 { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "one of these will spawn from \n" + "where you game-overed."; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "These golden F blocks will \n" + "fill your power up to MAX!"; } para++; if(dBox.paragraph == para) { dBox.textColor = DialogBoxSprite.BLUE; dBox.text = "This concludes the tutorial stage."; } para++; } private void runBulletPatterns() { for(Object o : bullets) { BulletSprite bullet = (BulletSprite) o; bullet.move(); if(isOffscreen(bullet) && bullet.screenKillable) bullet.destroy(); quadTree.insert(bullet); } } private boolean isOffscreen(Sprite s) { if(s.x < 0-s.width) { // System.out.println(s + " went offscreen"); return true; } if(s.x > mainLevel.SCREENW + s.width) { // System.out.println(s + " went offscreen"); return true; } if(s.y < 0-s.height) { // System.out.println(s + " went offscreen"); return true; } if(s.y > mainLevel.SCREENH + s.height) { // System.out.println(s + " went offscreen"); return true; } return false; } private double getAngleTo(double origX, double origY, double destX, double destY) { double dx = destX - origX; if(dx == 0) dx = 0.0001; double dy = origY - destY; if(dx > 0) { return Math.atan(dy/dx)/(2.0*Math.PI)*360.0; } else { return 180 + Math.atan(dy/dx)/(2.0*Math.PI)*360.0; } } /** * void enemy2BulletCollisions() * checks for collisions between player bullets and enemies. If a collision occurs, that player bullet is destroyed and that enemy takes damage. * * **/ private void enemy2BulletCollisions() { for(Object o : enemies) { EnemySprite smiley = (EnemySprite) o; ArrayList<Sprite> cList = quadTree.query(smiley); for(Sprite s : cList) { if(s instanceof PlayerBulletSprite) { PlayerBulletSprite pBullet = (PlayerBulletSprite) s; if(!smiley.isSpawner && smiley.collision(pBullet)) { if(smiley.damage(pBullet.damage)) { mainLevel.spawnItems(smiley.itemDrops, smiley.x, smiley.y); FXSprite splosion; splosion = FXSprite.makeBurst1(smiley.x, smiley.y); mainLevel.sfx.add(splosion); for(int i = 0; i < 10; i++) { // splosion = FXSprite.makeSimpleOrb2(smiley.x, smiley.y); splosion = FXSprite.makeSimpleOrb2(smiley.x, smiley.y); mainLevel.sfx.add(splosion); } mainLevel.soundPlayer.play("sound/zap01.wav"); killCount++; smiley.destroy(); } if(!pBullet.permanent) pBullet.destroy(); } } } } // collisions for midboss/boss ArrayList<Sprite> cList = quadTree.query(citrus); for(Sprite s : cList) { if(s instanceof PlayerBulletSprite) { PlayerBulletSprite pBullet = (PlayerBulletSprite) s; if(citrus.collision(pBullet) && citrus.isActive) { if(!pBullet.permanent) pBullet.destroy(); if(citrus.damage(pBullet.damage)) { mainLevel.spawnItems(citrus.itemDrops, citrus.x, citrus.y); citrus.isActive = false; citrus.timer = 0; citrus.hp = 200; mainLevel.numberSCTimer.value = 60; // System.out.println("skipped due to damage"); citrus.attackIndex++; break; } } } } } /** * void updateSpriteLists() * updates the stage's SpriteLists after collisions have been dealed with. * **/ private void updateSpriteLists() { enemies.update(); bullets.update(); } /* * Point getNearestEnemy(double x, double y) * gets the enemy closest to (x,y). Returns null if there are no enemies. * This is used by the Homing Yoyo attack. */ public Sprite getNearestEnemy(double x, double y) { Sprite nearestEnemy = null; double smallestDist = 0; for(Object o : enemies) { EnemySprite enemy = (EnemySprite) o; double dist = getSqrDist(x,y, enemy.x, enemy.y); if(!enemy.isSpawner && (nearestEnemy == null || dist < smallestDist)) { nearestEnemy = enemy; smallestDist = dist; } } if(citrus.isActive) { double dist = getSqrDist(x,y, citrus.x, citrus.y); if(nearestEnemy == null || dist < smallestDist) { nearestEnemy = citrus; smallestDist = dist; } } return nearestEnemy; } private double getSqrDist(double x1, double y1, double x2, double y2) { return (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2); } /////////// RENDERING STUFF /** * void animate(ImageLoader il) * This method should call the animate method for all of its sprites. It should be called in mainLevel's animateAllUnpaused() method. * Preconditions: il is the mainLevel's ImageLoader. **/ public void animate(ImageLoader il) { background.animate(il); enemies.animate(il); bullets.animate(il); // bossBullets.animate(il); bossSlaves.animate(il); citrus.animate(il); citrus.portrait.animate(il); textStageNum.animate(il); textStageTitle.animate(il); } /** * void renderEnemies(Graphics g2D) * This method renders all the stage's enemies. It should be called in mainLevel's render method. **/ public void renderEnemies(Graphics2D g2D) { enemies.render(g2D); bossSlaves.render(g2D); citrus.render(g2D); } /** * void renderBullets(Graphics g2D) * This method renders all the stage's enemy bullets. It should be called in mainLevel's render method. **/ public void renderBullets(Graphics2D g2D) { bullets.render(g2D); // bossBullets.render(g2D); } /** * void renderBackground(Graphics g2D) * This method renders all the stage's background graphics. It should be called in mainLevel's render method. **/ public void renderBackground(Graphics2D g2D) { g2D.setColor(new Color(0xFFAAAAFF, true)); g2D.fillRect(0, 0, mainLevel.SCREENW, mainLevel.SCREENH); background.render(g2D); } /** * void renderForeground(Graphics g2D) * This method renders all the stage's foreground graphics. It should be called in mainLevel's render method. **/ public void renderForeground(Graphics2D g2D) { citrus.portrait.render(g2D); textStageNum.render(g2D); textStageTitle.render(g2D); } }
28,872
0.618283
0.596953
1,337
20.599102
21.432875
144
false
false
0
0
0
0
0
0
3.242334
false
false
12
7cdeb4b56f98b639a8f98da0293ed12c0c838d00
7,086,696,058,109
0313857f7f11f1483297af0aab5ff1e3463db005
/com.fzzl.orange/src/net/yasite/service/CommentDaPaiService.java
ece5508fe53fe79b5be0f56cf74954c37a45ab3f
[]
no_license
eesc88/Orange
https://github.com/eesc88/Orange
2603ff4f5c83c333c123e70055cbdd57333caf1a
efffc6ea3f47ec71ec3283baf28615c63fa0e2f7
refs/heads/master
2018-01-09T01:03:40.514000
2016-01-07T14:52:31
2016-01-07T14:53:09
49,210,563
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.yasite.service; import java.util.ArrayList; import java.util.List; import net.yasite.api.BaseAPI; import net.yasite.api.CommentDaPaiAPI; import net.yasite.api.params.CommentDaPaiParams; import net.yasite.entity.CommentDaPaiEntity; import org.apache.http.NameValuePair; import android.content.Context; public class CommentDaPaiService extends BaseService { public CommentDaPaiService(Context context) { super(context); } public CommentDaPaiEntity getCommentDaPai(CommentDaPaiParams params){ List<NameValuePair> value = new ArrayList<NameValuePair>(); value.add(getValue("act", params.getAct())); value.add(getValue("i", params.getI())); value.add(getValue("id", params.getId())); value.add(getValue("uid", params.getUid())); value.add(getValue("content", params.getContent())); BaseAPI api = new CommentDaPaiAPI(context, value); try { if(api.doPost()){ return (CommentDaPaiEntity) api.getHandleResult(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }
UTF-8
Java
1,068
java
CommentDaPaiService.java
Java
[]
null
[]
package net.yasite.service; import java.util.ArrayList; import java.util.List; import net.yasite.api.BaseAPI; import net.yasite.api.CommentDaPaiAPI; import net.yasite.api.params.CommentDaPaiParams; import net.yasite.entity.CommentDaPaiEntity; import org.apache.http.NameValuePair; import android.content.Context; public class CommentDaPaiService extends BaseService { public CommentDaPaiService(Context context) { super(context); } public CommentDaPaiEntity getCommentDaPai(CommentDaPaiParams params){ List<NameValuePair> value = new ArrayList<NameValuePair>(); value.add(getValue("act", params.getAct())); value.add(getValue("i", params.getI())); value.add(getValue("id", params.getId())); value.add(getValue("uid", params.getUid())); value.add(getValue("content", params.getContent())); BaseAPI api = new CommentDaPaiAPI(context, value); try { if(api.doPost()){ return (CommentDaPaiEntity) api.getHandleResult(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }
1,068
0.741573
0.741573
39
26.384615
21.073273
70
false
false
0
0
0
0
0
0
1.794872
false
false
12
f77f6ae1256394e7a7792e5683a735ba3dc17a10
30,674,656,475,238
54bcc49a881aa1d4e6786f4b06764846d973365b
/thunder-biz/src/main/java/club/zhcs/thunder/biz/acl/GameService.java
1a891b8b300f246fa36c2d76deaac3d903a3eacb
[]
no_license
menglinxi/dataManagement
https://github.com/menglinxi/dataManagement
84b43a8a00f98954e41af4a7a814c8894b6253db
b5ec0bf2b8aa94fb8eaac905c321fa9b7c8a5ab8
refs/heads/master
2020-03-06T17:57:40.428000
2018-03-28T03:39:37
2018-03-28T03:39:37
126,997,575
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package club.zhcs.thunder.biz.acl; import club.zhcs.thunder.bean.acl.Game; import org.nutz.dao.Sqls; import org.nutz.dao.sql.Sql; import org.nutz.plugin.spring.boot.service.BaseService; import org.springframework.stereotype.Service; import java.util.List; /** * * @author kerbores@gmail.com * */ @Service public class GameService extends BaseService<Game> { public List<Game> searchObj(String s) { Sql sql = Sqls.create(s); return searchObj(sql); } }
UTF-8
Java
509
java
GameService.java
Java
[ { "context": "\r\n\r\nimport java.util.List;\r\n\r\n/**\r\n * \r\n * @author kerbores@gmail.com\r\n *\r\n */\r\n@Service\r\npublic class GameService exte", "end": 308, "score": 0.9999175667762756, "start": 290, "tag": "EMAIL", "value": "kerbores@gmail.com" } ]
null
[]
package club.zhcs.thunder.biz.acl; import club.zhcs.thunder.bean.acl.Game; import org.nutz.dao.Sqls; import org.nutz.dao.sql.Sql; import org.nutz.plugin.spring.boot.service.BaseService; import org.springframework.stereotype.Service; import java.util.List; /** * * @author <EMAIL> * */ @Service public class GameService extends BaseService<Game> { public List<Game> searchObj(String s) { Sql sql = Sqls.create(s); return searchObj(sql); } }
498
0.679764
0.679764
24
19.208334
18.663643
55
false
false
0
0
0
0
0
0
0.375
false
false
12
ada48d7036790e313de91d5959954cda1d61481b
6,150,393,171,507
767ea25708d4e35a392ff13c9d57d785069a1ba4
/src/vellumcert/GenKeyPair.java
97e6bbf643538a338334a869a69a794251c6d663
[]
no_license
evanx/vellumcert
https://github.com/evanx/vellumcert
015ac32b9d282d99262cfa0dd4f97fe40588e308
0614488ba0816c9449fed671c1ef409d8c764911
refs/heads/master
2021-01-02T08:14:11.557000
2014-01-18T13:25:22
2014-01-18T13:25:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Source https://github.com/evanx by @evanxsummers Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package vellumcert; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.PrivateKey; import java.util.Date; import java.security.cert.X509Certificate; import java.util.concurrent.TimeUnit; import sun.security.x509.CertAndKeyGen; import sun.security.x509.X500Name; /** * * @author evan.summers */ public class GenKeyPair { String keyAlgName = "RSA"; String sigAlgName = "SHA1WithRSA"; int keySize = 2048; String dname; Date notBefore; Date notAfter; CertAndKeyGen gen; X509Certificate cert; public GenKeyPair(String keyAlgName, int keySize, String sigAlgName) { this.keyAlgName = keyAlgName; this.keySize = keySize; this.sigAlgName = sigAlgName; } public void generate(String dname, Date notBefore, long validity, TimeUnit timeUnit) throws GeneralSecurityException, IOException { this.dname = dname; this.notBefore = notBefore; notAfter = new Date(notBefore.getTime() + timeUnit.toMillis(validity)); gen = new CertAndKeyGen(keyAlgName, sigAlgName); gen.generate(keySize); cert = gen.getSelfCertificate(new X500Name(dname), notBefore, timeUnit.toSeconds(validity)); } public CertAndKeyGen getGen() { return gen; } public PrivateKey getPrivateKey() { return gen.getPrivateKey(); } public X509Certificate getCertificate() { return cert; } public CertReq getCertRequest(String dname) throws Exception { return new CertReq(dname, gen.getCertRequest(new X500Name(dname)).getSubjectPublicKeyInfo()); } public void sign(PrivateKey signerKey, X509Certificate signerCert) throws Exception { cert = CertReqs.sign(getCertRequest(dname), signerKey, signerCert, notBefore, notAfter); } }
UTF-8
Java
2,790
java
GenKeyPair.java
Java
[ { "context": "/*\n * Source https://github.com/evanx by @evanxsummers\n\n Licensed to the Apache S", "end": 37, "score": 0.9996170997619629, "start": 32, "tag": "USERNAME", "value": "evanx" }, { "context": "/*\n * Source https://github.com/evanx by @evanxsummers\n\n Licen...
null
[]
/* * Source https://github.com/evanx by @evanxsummers Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package vellumcert; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.PrivateKey; import java.util.Date; import java.security.cert.X509Certificate; import java.util.concurrent.TimeUnit; import sun.security.x509.CertAndKeyGen; import sun.security.x509.X500Name; /** * * @author evan.summers */ public class GenKeyPair { String keyAlgName = "RSA"; String sigAlgName = "SHA1WithRSA"; int keySize = 2048; String dname; Date notBefore; Date notAfter; CertAndKeyGen gen; X509Certificate cert; public GenKeyPair(String keyAlgName, int keySize, String sigAlgName) { this.keyAlgName = keyAlgName; this.keySize = keySize; this.sigAlgName = sigAlgName; } public void generate(String dname, Date notBefore, long validity, TimeUnit timeUnit) throws GeneralSecurityException, IOException { this.dname = dname; this.notBefore = notBefore; notAfter = new Date(notBefore.getTime() + timeUnit.toMillis(validity)); gen = new CertAndKeyGen(keyAlgName, sigAlgName); gen.generate(keySize); cert = gen.getSelfCertificate(new X500Name(dname), notBefore, timeUnit.toSeconds(validity)); } public CertAndKeyGen getGen() { return gen; } public PrivateKey getPrivateKey() { return gen.getPrivateKey(); } public X509Certificate getCertificate() { return cert; } public CertReq getCertRequest(String dname) throws Exception { return new CertReq(dname, gen.getCertRequest(new X500Name(dname)).getSubjectPublicKeyInfo()); } public void sign(PrivateKey signerKey, X509Certificate signerCert) throws Exception { cert = CertReqs.sign(getCertRequest(dname), signerKey, signerCert, notBefore, notAfter); } }
2,790
0.694265
0.681362
82
33.024391
27.032942
101
false
false
0
0
0
0
0
0
0.609756
false
false
12
b1af1b84a9d54dc2517ab3a9517357fed54e645f
16,466,904,650,880
99360b24f0afc022b04635cb6c570eeeacebc00d
/d-ssm-app/src/main/java/com/dssm/domain/product/Image.java
fef0b4cbee6935b9e8e81b92092a5b64dd1f372d
[]
no_license
zhangshixi/d-ssm
https://github.com/zhangshixi/d-ssm
030dd2060b94964655969cc3d710918b97049c3a
be15e3c8ec46f768f3dda27e1ccbbeb7b6c3f239
HEAD
2016-09-06T07:38:46.449000
2013-11-10T14:18:53
2013-11-10T14:18:53
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dssm.domain.product; import java.util.Date; import com.dssm.domain.PrimaryKey; public class Image extends PrimaryKey { private static final long serialVersionUID = 6959661610056390421L; private String path; private Integer sequence; private Date updateTime; private Date updateAdmin; private Product product; /* ---- getter/setter methods ---- */ public String getPath() { return path; } public void setPath(String path) { this.path = path; } public Integer getSequence() { return sequence; } public void setSequence(Integer sequence) { this.sequence = sequence; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public Date getUpdateAdmin() { return updateAdmin; } public void setUpdateAdmin(Date updateAdmin) { this.updateAdmin = updateAdmin; } public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } }
UTF-8
Java
1,070
java
Image.java
Java
[]
null
[]
package com.dssm.domain.product; import java.util.Date; import com.dssm.domain.PrimaryKey; public class Image extends PrimaryKey { private static final long serialVersionUID = 6959661610056390421L; private String path; private Integer sequence; private Date updateTime; private Date updateAdmin; private Product product; /* ---- getter/setter methods ---- */ public String getPath() { return path; } public void setPath(String path) { this.path = path; } public Integer getSequence() { return sequence; } public void setSequence(Integer sequence) { this.sequence = sequence; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public Date getUpdateAdmin() { return updateAdmin; } public void setUpdateAdmin(Date updateAdmin) { this.updateAdmin = updateAdmin; } public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } }
1,070
0.694393
0.676636
51
18.980392
16.478733
67
false
false
0
0
0
0
0
0
1.411765
false
false
12
cad5798d512af96ad72a09153f3dc7b5ac2e9ab3
22,986,665,005,193
c50ec8bea3a8eb9c8c6f591ca0d65f57d245c286
/app/src/main/java/com/example/fredys/routh_huiwitz/componentes/reutilizables/MensajesEnPantalla.java
d50deb8820099c3d523808de24b1aec6fd46e736
[]
no_license
fredy180/Routh-Huiwitz
https://github.com/fredy180/Routh-Huiwitz
b4fb23b3a6ea7fdbc33fb81135ee5c96ce189d0f
5d7dabab1afc273fb298c827ccda997d137ceb23
refs/heads/master
2020-08-30T20:22:00.081000
2016-09-05T04:41:29
2016-09-05T04:41:29
67,388,356
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.fredys.routh_huiwitz.componentes.reutilizables; import android.content.Context; import android.widget.Toast; /** * Created by Fredys on 26/06/2016. */ public class MensajesEnPantalla { public static void mensajeToast(Context context, String texto){ int duration = Toast.LENGTH_LONG; Toast toast = Toast.makeText(context, texto, duration); toast.show(); } }
UTF-8
Java
414
java
MensajesEnPantalla.java
Java
[ { "context": "package com.example.fredys.routh_huiwitz.componentes.reutilizables;\n\nimport ", "end": 26, "score": 0.9888465404510498, "start": 20, "tag": "USERNAME", "value": "fredys" }, { "context": "t;\nimport android.widget.Toast;\n\n/**\n * Created by Fredys on 26/06/2016.\n */\...
null
[]
package com.example.fredys.routh_huiwitz.componentes.reutilizables; import android.content.Context; import android.widget.Toast; /** * Created by Fredys on 26/06/2016. */ public class MensajesEnPantalla { public static void mensajeToast(Context context, String texto){ int duration = Toast.LENGTH_LONG; Toast toast = Toast.makeText(context, texto, duration); toast.show(); } }
414
0.71256
0.693237
16
24.875
24.072481
67
false
false
0
0
0
0
0
0
0.5625
false
false
12
1f799b4f792f8435e15c00175cbdb44cc686ac70
326,417,567,911
89a23e2e38ef8b22672390bcfc9d62202df4cb72
/src/main/java/net/modera/shovel/graph/ResourceTravelerProjection.java
bf9c580d67982c1e7d34707aabb49292b72c7506
[]
no_license
sergeil/DevShovel
https://github.com/sergeil/DevShovel
78f1d0171984d46bf47278843acea68420c5fe51
ab043511ad5c0d4ca8456d48b2d2c3d303522b0b
refs/heads/master
2020-05-20T12:54:55.178000
2011-02-20T11:42:27
2011-02-20T11:42:27
1,382,803
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.modera.shovel.graph; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import net.modera.shovel.model.Connection; import net.modera.shovel.model.Resource; import net.modera.shovel.traveler.ResourceTraveler; import net.modera.shovel.traveler.TravelerEventListener; import org.eclipse.draw2d.ColorConstants; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Region; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.zest.core.widgets.Graph; import org.eclipse.zest.core.widgets.GraphConnection; import org.eclipse.zest.core.widgets.GraphItem; import org.eclipse.zest.core.widgets.GraphNode; import org.eclipse.zest.core.widgets.ZestStyles; import org.eclipse.zest.layouts.LayoutAlgorithm; import org.eclipse.zest.layouts.LayoutStyles; import org.eclipse.zest.layouts.algorithms.HorizontalTreeLayoutAlgorithm; import org.eclipse.zest.layouts.algorithms.RadialLayoutAlgorithm; import org.eclipse.zest.layouts.algorithms.SpringLayoutAlgorithm; import org.eclipse.zest.layouts.algorithms.TreeLayoutAlgorithm; public class ResourceTravelerProjection implements TravelerEventListener { private ResourceTraveler traveler; protected Shell shell; public static final int BACKSPACE = 8; public static final int ENTER = 13; public ResourceTravelerProjection(Shell shell) { this.shell = shell; } public void setTraveler(ResourceTraveler traveler) { this.traveler = traveler; } public ResourceTraveler getTraveler() { return traveler; } public void onReset() { final Map<String,GraphNode> figureListing = new HashMap<String,GraphNode>(); final StringBuffer stringBuffer = new StringBuffer(); FontData fontData = shell.getDisplay().getSystemFont().getFontData()[0]; fontData.height = 42; final Font font = new Font(shell.getDisplay(), fontData); Image image1 = Display.getDefault().getSystemImage(SWT.ICON_INFORMATION); Image image2 = Display.getDefault().getSystemImage(SWT.ICON_WARNING); Image image3 = Display.getDefault().getSystemImage(SWT.ICON_ERROR); final Graph g = new Graph(shell, SWT.NONE); g.setConnectionStyle(ZestStyles.CONNECTIONS_DIRECTED); Resource res = getTraveler().getCurrentResource(); GraphNode currentNode = new GraphNode(g, SWT.NONE, res.getDisplayName(), image1); for (Connection connection : getTraveler().getConnections()) { GraphNode node = new GraphNode(g, SWT.NONE, connection.getTargetResource().getDisplayName(), image2); new GraphConnection(g, SWT.NONE, currentNode, node); } // GraphNode n3 = new GraphNode(g, SWT.NONE, "org.eclipse.Error", image3); // figureListing.put(n1.getText().toLowerCase(), n1); // figureListing.put(n2.getText().toLowerCase(), n2); // figureListing.put(n3.getText().toLowerCase(), n3); // new GraphConnection(g, SWT.NONE, n1, n2); // new GraphConnection(g, SWT.NONE, n2, n3); // n1.setLocation(10, 10); // n2.setLocation(200, 10); // n3.setLocation(200, 200); g.setLayoutAlgorithm(new RadialLayoutAlgorithm(LayoutStyles.NO_LAYOUT_NODE_RESIZING), true); /* g.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { boolean complete = false; if (e.keyCode == BACKSPACE) { if (stringBuffer.length() > 0) { stringBuffer.deleteCharAt(stringBuffer.length() - 1); } } else if (e.keyCode == ENTER) { complete = true; } else if ((e.character >= 'a' && e.character <= 'z') || (e.character >= 'A' && e.character <= 'Z') || (e.character == '.') || (e.character >= '0' && e.character <= '9')) { stringBuffer.append(e.character); } Iterator<String> iterator = figureListing.keySet().iterator(); List<GraphNode> list = new ArrayList<GraphNode>(); if (stringBuffer.length() > 0) { while (iterator.hasNext()) { String string = (String) iterator.next(); if (string.indexOf(stringBuffer.toString().toLowerCase()) >= 0) { list.add(figureListing.get(string)); } } } g.setSelection((GraphItem[]) list.toArray(new GraphItem[list.size()])); if (complete && stringBuffer.length() > 0) { stringBuffer.delete(0, stringBuffer.length()); } g.redraw(); } }); g.addPaintListener(new PaintListener() { public void paintControl(PaintEvent e) { e.gc.setFont(font); e.gc.setClipping((Region) null); e.gc.setForeground(ColorConstants.black); e.gc.drawText(stringBuffer.toString(), 50, 50, true); } }); */ } public void onDispose() { // image1.dispose(); // image2.dispose(); // image3.dispose(); // font.dispose(); } public void onTravelerMoved() { // TODO Auto-generated method stub } }
UTF-8
Java
5,204
java
ResourceTravelerProjection.java
Java
[]
null
[]
package net.modera.shovel.graph; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import net.modera.shovel.model.Connection; import net.modera.shovel.model.Resource; import net.modera.shovel.traveler.ResourceTraveler; import net.modera.shovel.traveler.TravelerEventListener; import org.eclipse.draw2d.ColorConstants; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Region; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.zest.core.widgets.Graph; import org.eclipse.zest.core.widgets.GraphConnection; import org.eclipse.zest.core.widgets.GraphItem; import org.eclipse.zest.core.widgets.GraphNode; import org.eclipse.zest.core.widgets.ZestStyles; import org.eclipse.zest.layouts.LayoutAlgorithm; import org.eclipse.zest.layouts.LayoutStyles; import org.eclipse.zest.layouts.algorithms.HorizontalTreeLayoutAlgorithm; import org.eclipse.zest.layouts.algorithms.RadialLayoutAlgorithm; import org.eclipse.zest.layouts.algorithms.SpringLayoutAlgorithm; import org.eclipse.zest.layouts.algorithms.TreeLayoutAlgorithm; public class ResourceTravelerProjection implements TravelerEventListener { private ResourceTraveler traveler; protected Shell shell; public static final int BACKSPACE = 8; public static final int ENTER = 13; public ResourceTravelerProjection(Shell shell) { this.shell = shell; } public void setTraveler(ResourceTraveler traveler) { this.traveler = traveler; } public ResourceTraveler getTraveler() { return traveler; } public void onReset() { final Map<String,GraphNode> figureListing = new HashMap<String,GraphNode>(); final StringBuffer stringBuffer = new StringBuffer(); FontData fontData = shell.getDisplay().getSystemFont().getFontData()[0]; fontData.height = 42; final Font font = new Font(shell.getDisplay(), fontData); Image image1 = Display.getDefault().getSystemImage(SWT.ICON_INFORMATION); Image image2 = Display.getDefault().getSystemImage(SWT.ICON_WARNING); Image image3 = Display.getDefault().getSystemImage(SWT.ICON_ERROR); final Graph g = new Graph(shell, SWT.NONE); g.setConnectionStyle(ZestStyles.CONNECTIONS_DIRECTED); Resource res = getTraveler().getCurrentResource(); GraphNode currentNode = new GraphNode(g, SWT.NONE, res.getDisplayName(), image1); for (Connection connection : getTraveler().getConnections()) { GraphNode node = new GraphNode(g, SWT.NONE, connection.getTargetResource().getDisplayName(), image2); new GraphConnection(g, SWT.NONE, currentNode, node); } // GraphNode n3 = new GraphNode(g, SWT.NONE, "org.eclipse.Error", image3); // figureListing.put(n1.getText().toLowerCase(), n1); // figureListing.put(n2.getText().toLowerCase(), n2); // figureListing.put(n3.getText().toLowerCase(), n3); // new GraphConnection(g, SWT.NONE, n1, n2); // new GraphConnection(g, SWT.NONE, n2, n3); // n1.setLocation(10, 10); // n2.setLocation(200, 10); // n3.setLocation(200, 200); g.setLayoutAlgorithm(new RadialLayoutAlgorithm(LayoutStyles.NO_LAYOUT_NODE_RESIZING), true); /* g.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { boolean complete = false; if (e.keyCode == BACKSPACE) { if (stringBuffer.length() > 0) { stringBuffer.deleteCharAt(stringBuffer.length() - 1); } } else if (e.keyCode == ENTER) { complete = true; } else if ((e.character >= 'a' && e.character <= 'z') || (e.character >= 'A' && e.character <= 'Z') || (e.character == '.') || (e.character >= '0' && e.character <= '9')) { stringBuffer.append(e.character); } Iterator<String> iterator = figureListing.keySet().iterator(); List<GraphNode> list = new ArrayList<GraphNode>(); if (stringBuffer.length() > 0) { while (iterator.hasNext()) { String string = (String) iterator.next(); if (string.indexOf(stringBuffer.toString().toLowerCase()) >= 0) { list.add(figureListing.get(string)); } } } g.setSelection((GraphItem[]) list.toArray(new GraphItem[list.size()])); if (complete && stringBuffer.length() > 0) { stringBuffer.delete(0, stringBuffer.length()); } g.redraw(); } }); g.addPaintListener(new PaintListener() { public void paintControl(PaintEvent e) { e.gc.setFont(font); e.gc.setClipping((Region) null); e.gc.setForeground(ColorConstants.black); e.gc.drawText(stringBuffer.toString(), 50, 50, true); } }); */ } public void onDispose() { // image1.dispose(); // image2.dispose(); // image3.dispose(); // font.dispose(); } public void onTravelerMoved() { // TODO Auto-generated method stub } }
5,204
0.697348
0.686395
160
30.525
26.872372
176
false
false
0
0
0
0
0
0
2.5
false
false
12
6cedc6eaab6729c7563ec27b2340e958ae9846db
19,499,151,564,162
679ddf779e12803eb07cd6c062ba8b56d1064d36
/src/main/java/com/ssnc/tests/latlong/City.java
a2afe82208a42d637568f391f91ec7f9df4c2526
[]
no_license
trsr99/test_java_master
https://github.com/trsr99/test_java_master
7d44973677d0542dcf87368ce5b6221623309560
4a9b9c966f8811a45f7c519bc001b2e65faaae50
refs/heads/main
2023-03-11T14:31:43.519000
2021-02-28T14:27:28
2021-02-28T14:27:28
343,123,874
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ssnc.tests.latlong; import java.util.HashSet; import java.util.Set; import java.util.stream.Stream; /** * City information with a loader for your convenience. * */ public class City implements Location { private final String name; private final Coordinate coordinates; private final String provinceState; private final String country; public City(String city, Coordinate coordinates, String provinceState, String country) { this.name = city; this.coordinates = coordinates; this.provinceState = provinceState; this.country = country; } public String getName() { return name; } public Coordinate getCoordinates() { return coordinates; } public String getProvinceState() { return provinceState; } public String getCountry() { return country; } public static Set<City> readStreamLines(Stream<String> lines) { Set<City> cityCoordinates = new HashSet<>(); lines.skip(1).forEach( line -> { String[] row = line.split(","); Coordinate coordinates = new Coordinate( Float.parseFloat(row[1]), Float.parseFloat(row[2]) ); cityCoordinates.add( new City(row[0], coordinates, row[3], row[4]) ); }); return cityCoordinates; } @Override public double getLatitude() { return this.coordinates.getLatitude(); } @Override public double getLongitude() { return this.coordinates.getLongitude(); } @Override public Location absoluteDifference(Location otherCoordinate) { return this.coordinates.absoluteDifference(otherCoordinate); } @Override public String toString() { return "City [name=" + name + ", coordinates=" + coordinates + "]"; } }
UTF-8
Java
1,755
java
City.java
Java
[]
null
[]
package com.ssnc.tests.latlong; import java.util.HashSet; import java.util.Set; import java.util.stream.Stream; /** * City information with a loader for your convenience. * */ public class City implements Location { private final String name; private final Coordinate coordinates; private final String provinceState; private final String country; public City(String city, Coordinate coordinates, String provinceState, String country) { this.name = city; this.coordinates = coordinates; this.provinceState = provinceState; this.country = country; } public String getName() { return name; } public Coordinate getCoordinates() { return coordinates; } public String getProvinceState() { return provinceState; } public String getCountry() { return country; } public static Set<City> readStreamLines(Stream<String> lines) { Set<City> cityCoordinates = new HashSet<>(); lines.skip(1).forEach( line -> { String[] row = line.split(","); Coordinate coordinates = new Coordinate( Float.parseFloat(row[1]), Float.parseFloat(row[2]) ); cityCoordinates.add( new City(row[0], coordinates, row[3], row[4]) ); }); return cityCoordinates; } @Override public double getLatitude() { return this.coordinates.getLatitude(); } @Override public double getLongitude() { return this.coordinates.getLongitude(); } @Override public Location absoluteDifference(Location otherCoordinate) { return this.coordinates.absoluteDifference(otherCoordinate); } @Override public String toString() { return "City [name=" + name + ", coordinates=" + coordinates + "]"; } }
1,755
0.667236
0.663818
81
19.666666
20.007406
89
false
false
0
0
0
0
0
0
1.888889
false
false
12
669b89520d49d11466a37e6287e4e4a2e8d41a58
146,028,922,988
c2e50035aa35b819335ab62d871f9557fb663d8a
/src/pl/edu/agh/otanimals/Institution.java
30af30b51b8101f112c894ad8fed55280cb116d9
[]
no_license
Galian5/TO-project
https://github.com/Galian5/TO-project
742d3c2445da332e6c42f0eda17924944357342f
318f328f10f155e8125391f437de0b943ea40e87
refs/heads/master
2020-04-07T21:32:17.046000
2018-11-25T14:44:01
2018-11-25T14:44:01
158,731,055
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pl.edu.agh.otanimals; import java.util.Objects; interface Institution { static Institution newInstitution(String name) { return new InstitutionImpl(name); } default InstitutionType getInstitutionType() { return InstitutionType.NONE; } default void pullNotification(Notification notification) { System.out.println("Received a notification: " + notification); } class InstitutionImpl implements Institution { private final String name; InstitutionImpl(String name) { this.name = name; } @Override public InstitutionType getInstitutionType() { return InstitutionType.FIRST_TYPE; } @Override public String toString() { return "InstitutionImpl{" + "name='" + name + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } InstitutionImpl that = (InstitutionImpl) o; return Objects.equals(name, that.name); } @Override public int hashCode() { return Objects.hash(name); } } }
UTF-8
Java
1,171
java
Institution.java
Java
[]
null
[]
package pl.edu.agh.otanimals; import java.util.Objects; interface Institution { static Institution newInstitution(String name) { return new InstitutionImpl(name); } default InstitutionType getInstitutionType() { return InstitutionType.NONE; } default void pullNotification(Notification notification) { System.out.println("Received a notification: " + notification); } class InstitutionImpl implements Institution { private final String name; InstitutionImpl(String name) { this.name = name; } @Override public InstitutionType getInstitutionType() { return InstitutionType.FIRST_TYPE; } @Override public String toString() { return "InstitutionImpl{" + "name='" + name + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } InstitutionImpl that = (InstitutionImpl) o; return Objects.equals(name, that.name); } @Override public int hashCode() { return Objects.hash(name); } } }
1,171
0.624253
0.624253
57
19.561403
18.83168
67
false
false
0
0
0
0
0
0
0.298246
false
false
12