blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
91b901f9a18eeb61aa56a3df548ae5633070cfa2
Java
ajvillav/ApiEmail
/src/main/java/com/emailapi/EmailApi/repository/EmailUserRepository.java
UTF-8
410
1.929688
2
[]
no_license
package com.emailapi.EmailApi.repository; import com.emailapi.EmailApi.model.EmailUser; import com.emailapi.EmailApi.model.Person; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.UUID; @Repository public interface EmailUserRepository extends JpaRepository<EmailUser, UUID> { EmailUser findAllByPersonId(Person person); }
true
665f9fd075549a45f2e552d93d28ac7163572f8b
Java
Aditya-Zutshi/opensha
/src/main/java/org/opensha/sha/gui/infoTools/IMT_Info_OLD.java
UTF-8
11,884
1.726563
2
[ "Apache-2.0" ]
permissive
/******************************************************************************* * Copyright 2009 OpenSHA.org in partnership with * the Southern California Earthquake Center (SCEC, http://www.scec.org) * at the University of Southern California and the UnitedStates Geological * Survey (USGS; http://www.usgs.gov) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package org.opensha.sha.gui.infoTools; import java.text.DecimalFormat; import org.opensha.commons.data.function.ArbitrarilyDiscretizedFunc; import org.opensha.commons.param.Parameter; import org.opensha.sha.imr.attenRelImpl.ShakeMap_2003_AttenRel; import org.opensha.sha.imr.attenRelImpl.WC94_DisplMagRel; import org.opensha.sha.imr.param.IntensityMeasureParams.MMI_Param; import org.opensha.sha.imr.param.IntensityMeasureParams.PGA_Param; import org.opensha.sha.imr.param.IntensityMeasureParams.PGV_Param; import org.opensha.sha.imr.param.IntensityMeasureParams.SA_Param; /** * <p>Title: IMT_Info</p> * <p>Description: This class provides the default X values for the selected * IMT. The discretization is done in the </p> * @author : Edward (Ned) Field and Nitin Gupta * @created : Nov 24,2003 * @version 1.0 */ public final class IMT_Info_OLD { private String S = "IMT_Info()"; //Default values for the SA and PGA public final static double MIN_SA = .0001; public final static double MAX_SA = 10; public final static double NUM_SA = 51; public final static double DEFAULT_SA = 0.1; //Default values for the PGA public final static double MIN_PGA = .0001; public final static double MAX_PGA = 10; public final static double NUM_PGA = 51; public final static double DEFAULT_PGA = 0.1; //Default values for the PGV public final static double MIN_PGV = .01; public final static double MAX_PGV = 1000; public final static double NUM_PGV = 51; public final static double DEFAULT_PGV = 50; // default values for WC94_DisplMagRel FAULT_DISPL_NAME public final static double MIN_FAULT_DISPL = .001; public final static double MAX_FAULT_DISPL = 100; public final static double NUM_FAULT_DISPL = 51; public final static double DEFAULT_FAULT_DISPL = 1.0; //default values for the ShakeMapAttenRel MMI public final static double MIN_MMI = 1; public final static double MAX_MMI = 10; public final static double NUM_MMI = 51; public final static double DEFAULT_MMI = 7.0; public double discretization_pga; public double discretization_sa; public double discretization_pgv; public double discretization_fault_displ; public double discretization_mmi; private DecimalFormat format = new DecimalFormat("0.00000##"); public IMT_Info_OLD() { discretization_pga = (Math.log(MAX_PGA) - Math.log(MIN_PGA))/(NUM_PGA-1); discretization_sa = (Math.log(MAX_SA) - Math.log(MIN_SA))/(NUM_SA-1); discretization_pgv = (Math.log(MAX_PGV) - Math.log(MIN_PGV))/(NUM_PGV-1); discretization_fault_displ = (Math.log(MAX_FAULT_DISPL) - Math.log(MIN_FAULT_DISPL))/(NUM_FAULT_DISPL-1); discretization_mmi = (Math.log(MAX_MMI) - Math.log(MIN_MMI))/(NUM_MMI-1); format.setMaximumFractionDigits(5); } /** * This function returns the ArbitrarilyDiscretizedFunc X values for the Hazard * Curve in the linear space after discretizing them in the log space. * @param param : Selected IMT Param * @return */ public ArbitrarilyDiscretizedFunc getDefaultHazardCurve(Parameter imtParam){ String paramVal =(String)imtParam.getValue(); return getDefaultHazardCurve(paramVal); } /** * This function returns the ArbitrarilyDiscretizedFunc X values for the Hazard * Curve in the linear space after discretizing them in the log space. * @param imtName : Name of the selected IMT * @return */ public ArbitrarilyDiscretizedFunc getDefaultHazardCurve(String imtName){ ArbitrarilyDiscretizedFunc function = new ArbitrarilyDiscretizedFunc(); if(imtName.equals(SA_Param.NAME)){ for(int i=0; i < NUM_SA ;++i){ double xVal =Double.parseDouble(format.format(Math.exp(Math.log(MIN_SA)+i*discretization_sa))); function.set(xVal,1.0); } return function; } else if(imtName.equals(PGA_Param.NAME)){ for(int i=0; i < NUM_PGA ;++i){ double xVal =Double.parseDouble(format.format(Math.exp(Math.log(MIN_PGA)+i*discretization_pga))); function.set(xVal,1.0); } return function; } else if((imtName.equals(PGV_Param.NAME))){ for(int i=0; i < NUM_PGV ;++i){ double xVal = Double.parseDouble(format.format(Math.exp(Math.log(MIN_PGV)+i*discretization_pgv))); function.set(xVal,1.0); } return function; } else if((imtName.equals(WC94_DisplMagRel.FAULT_DISPL_NAME))){ for(int i=0; i < NUM_FAULT_DISPL ;++i){ double xVal = Double.parseDouble(format.format(Math.exp(Math.log(MIN_FAULT_DISPL)+i*discretization_fault_displ))); function.set(xVal,1.0); } return function; } else if((imtName.equals(MMI_Param.NAME))){ for(int i=0; i < NUM_MMI ;++i){ double xVal = Double.parseDouble(format.format(Math.exp(Math.log(MIN_MMI)+i*discretization_mmi))); function.set(xVal,1.0); } return function; } return null; } /** * Returns the minimum default value for the selectd IMT * @param imt: Selected IMT * @return */ public static double getMinIMT_Val(String imt){ if(imt.equals(SA_Param.NAME)) return MIN_SA; else if(imt.equals(PGA_Param.NAME)) return MIN_PGA; else if(imt.equals(PGV_Param.NAME)) return MIN_PGV; else if(imt.equals(WC94_DisplMagRel.FAULT_DISPL_NAME)) return MIN_FAULT_DISPL; else if(imt.equals(MMI_Param.NAME)) return MIN_MMI; return 0; } /** * Returns the maximum default value for the selectd IMT * @param imt: Selected IMT * @return */ public static double getMaxIMT_Val(String imt){ if(imt.equals(SA_Param.NAME)) return MAX_SA; else if(imt.equals(PGA_Param.NAME)) return MAX_PGA; else if(imt.equals(PGV_Param.NAME)) return MAX_PGV; else if(imt.equals(WC94_DisplMagRel.FAULT_DISPL_NAME)) return MAX_FAULT_DISPL; else if(imt.equals(MMI_Param.NAME)) return MAX_MMI; return 0; } /** * Returns the total number of values for the selectd IMT * @param imt: Selected IMT * @return */ public static double getNumIMT_Val(String imt){ if(imt.equals(SA_Param.NAME)) return NUM_SA; else if(imt.equals(PGA_Param.NAME)) return NUM_PGA; else if(imt.equals(PGV_Param.NAME)) return NUM_PGV; else if(imt.equals(WC94_DisplMagRel.FAULT_DISPL_NAME)) return NUM_FAULT_DISPL; else if(imt.equals(MMI_Param.NAME)) return NUM_MMI; return 0; } /** * Returns the default values for the selectd IMT * @param imt: Selected IMT * @return */ public static double getDefaultIMT_VAL(String imt){ if(imt.equals(SA_Param.NAME)) return DEFAULT_SA; else if(imt.equals(PGA_Param.NAME)) return DEFAULT_PGA; else if(imt.equals(PGV_Param.NAME)) return DEFAULT_PGV; else if(imt.equals(WC94_DisplMagRel.FAULT_DISPL_NAME)) return DEFAULT_FAULT_DISPL; else if(imt.equals(MMI_Param.NAME)) return DEFAULT_MMI; return 0; } /** * * @param imt : Name of the seleceted IMT * @return true if the selected IMT is PGA, PGV or SA * else returns false */ public static boolean isIMT_LogNormalDist(String imt){ if(imt.equalsIgnoreCase(PGA_Param.NAME) || imt.equalsIgnoreCase(PGV_Param.NAME) || imt.equalsIgnoreCase(SA_Param.NAME) || imt.equalsIgnoreCase(MMI_Param.NAME) || imt.equalsIgnoreCase(WC94_DisplMagRel.FAULT_DISPL_NAME)) return true; return false; } /** * initialises the function with the x and y values if the user has chosen the USGS-PGA X Vals * the y values are modified with the values entered by the user */ public static ArbitrarilyDiscretizedFunc getUSGS_PGA_Function(){ ArbitrarilyDiscretizedFunc function= new ArbitrarilyDiscretizedFunc(); function.set(.005,1); function.set(.007,1); function.set(.0098,1); function.set(.0137,1); function.set(.0192,1); function.set(.0269,1); function.set(.0376,1); function.set(.0527,1); function.set(.0738,1); function.set(.103,1); function.set(.145,1); function.set(.203,1); function.set(.284,1); function.set(.397,1); function.set(.556,1); function.set(.778,1); function.set(1.09,1); function.set(1.52,1); function.set(2.13,1); return function; } /** * initialises the function with the x and y values if the user has chosen the USGS-PGA X Vals * the y values are modified with the values entered by the user */ public static ArbitrarilyDiscretizedFunc getUSGS_SA_01_AND_02_Function(){ ArbitrarilyDiscretizedFunc function= new ArbitrarilyDiscretizedFunc(); function.set(.005,1); function.set(.0075,1); function.set(.0113 ,1); function.set(.0169,1); function.set(.0253,1); function.set(.0380,1); function.set(.0570,1); function.set(.0854,1); function.set(.128,1); function.set(.192,1); function.set(.288,1); function.set(.432,1); function.set(.649,1); function.set(.973,1); function.set(1.46,1); function.set(2.19,1); function.set(3.28,1); function.set(4.92,1); function.set(7.38,1); return function; } /** * initialises the function with the x and y values if the user has chosen the USGS SA 0.3,0.4,0.5 and 1.0sec * X Vals ,the y values are modified with the values entered by the user */ public static ArbitrarilyDiscretizedFunc getUSGS_SA_Function(){ ArbitrarilyDiscretizedFunc function= new ArbitrarilyDiscretizedFunc(); function.set(.0025,1); function.set(.00375,1); function.set(.00563 ,1); function.set(.00844,1); function.set(.0127,1); function.set(.0190,1); function.set(.0285,1); function.set(.0427,1); function.set(.0641,1); function.set(.0961,1); function.set(.144,1); function.set(.216,1); function.set(.324,1); function.set(.487,1); function.set(.730,1); function.set(1.09,1); function.set(1.64,1); function.set(2.46,1); function.set(3.69,1); function.set(5.54,1); return function; } /** * * @param imtParam : IMT Parameter * @return true if the selected IMT is PGA, PGV or SA * else returns false */ public static boolean isIMT_LogNormalDist(Parameter imtParam){ String paramVal =(String)imtParam.getValue(); return isIMT_LogNormalDist(paramVal); } //added for debugging purposes public static void main(String args[]){ IMT_Info hazardCurve = new IMT_Info(); ArbitrarilyDiscretizedFunc func = hazardCurve.getDefaultHazardCurve("SA"); System.out.println("For SA and PGA: "); System.out.println("Dis: "+hazardCurve.discretization_pga); System.out.println(func.toString()); func = hazardCurve.getDefaultHazardCurve("PGV"); System.out.println("For PGV: "); System.out.println("Dis: "+hazardCurve.discretization_pgv); System.out.println(func.toString()); } }
true
828d58861e68c339592c36e76e85eebea2b12f0e
Java
WindhoverLabs/ConfigurationRegistry
/src/com/myplugin/rmp/CFSPropertiesPage.java
UTF-8
6,401
2.234375
2
[]
no_license
package com.myplugin.rmp; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.QualifiedName; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IWorkbenchPropertyPage; import org.eclipse.ui.dialogs.PropertyPage; import com.myplugin.rmp.views.PropertyManagerView.TreeObject; import java.io.File; import java.util.ArrayList; import java.util.StringTokenizer; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ProjectScope; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.preferences.IScopeContext; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PathEditor; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.ui.IWorkbenchPropertyPage; import org.eclipse.ui.dialogs.PropertyPage; import org.eclipse.ui.preferences.ScopedPreferenceStore; import org.eclipse.swt.widgets.Button; /** * * GUI Interface for Airliner section in project properties. * * @author vagrant * */ public class CFSPropertiesPage extends PropertyPage implements IWorkbenchPropertyPage { private PathEditor pathChooser; private IProject currentProject; private IPreferenceStore preferenceStore; private IScopeContext context; private Composite pathEditorHolder; public CFSPropertiesPage() { } /** * * Main function executes to create and return the GUI interface of the Airliner property page. * * @param parent * @return Control * */ @Override protected Control createContents(Composite parent) { prepareProperties(); prepareHolder(parent); createPathChooser(); return getControl(); } /** * * Finds the project properties in the preference store and links it to the GUI interfaces on the Airliner property page. * */ private void prepareProperties() { // Retrieve the currently selected project. IAdaptable adaptable = getElement(); currentProject = (IProject) adaptable.getAdapter(IProject.class); context = new ProjectScope(currentProject); // Retrieve the current project's preference store, and associate the property page with it. preferenceStore = new ScopedPreferenceStore(context, "com.windhoverlabs.ide.cfsNature"); setPreferenceStore(preferenceStore); } /** * * Creates the parent composite to hold the path editor composite. * */ private void prepareHolder(Composite parent) { // Create the composite which will hold the path chooser. pathEditorHolder = new Composite(parent, SWT.NONE); GridData gridData = new GridData(); gridData.horizontalAlignment = GridData.FILL; gridData.grabExcessHorizontalSpace = true; pathEditorHolder.setLayoutData(gridData); pathEditorHolder.setLayout(new GridLayout(1, false)); } /** * * Creates the path editor composite and sets the contents. * */ private void createPathChooser() { // Retrieve the current properties from the associated preference store. // Retrieve the preferenceStore string representation of path, and convert it into an array of paths. String defaultPaths = getDefaultPaths(); preferenceStore.setDefault(PropertiesConstants.DEF_CONFIG_PATHS, defaultPaths); String paths = preferenceStore.getString(PropertiesConstants.DEF_CONFIG_PATHS); String[] pathList = parseString(paths); // Create the path chooser, and assign it with the preference variable 'path', set it to the associated preference store. pathChooser = new PathEditor(PropertiesConstants.DEF_CONFIG_PATHS, "Path to YAML file", "Choose", pathEditorHolder); pathChooser.setPreferenceStore(preferenceStore); // Populate the list with current project's path property. If it hasn't been set yet, then set it to the default. pathChooser.getListControl(pathEditorHolder).setItems(pathList); } /** * * Loads the default of the Airliner property page. For the paths editor it is ${project_loc}/apps * */ protected void performDefaults() { pathChooser.loadDefault(); super.performDefaults(); } /** * * Saves the input data. * * @return performedStatus * */ public boolean performOk() { String[] items = pathChooser.getListControl(pathEditorHolder).getItems(); String oneList = createList(items); preferenceStore.setValue(PropertiesConstants.DEF_CONFIG_PATHS, oneList); ContextManager.searchDefinitionConfigurationFiles(currentProject); return true; } /** * * Helper function to convert an array of paths to a single string to store in the preference store. * * @param items * @return paths * */ private String createList(String[] items) { StringBuilder path = new StringBuilder(""); for (String item : items) { path.append(item); path.append(File.pathSeparator); } return path.toString(); } /** * * Helper function to convert a single string of paths to an array of paths to be used as input for the path editor chooser. * * @param stringList * @return pathsAsList * */ private String[] parseString(String stringList) { StringTokenizer st = new StringTokenizer(stringList, File.pathSeparator + "\n\r"); ArrayList<Object> v = new ArrayList<>(); while (st.hasMoreElements()) { v.add(st.nextElement()); } return v.toArray(new String[v.size()]); } /** * * Returns the default path of the configuration file. This could be YAML, XML, SQLite, etc. * * @return defaultPath * */ private String getDefaultPaths() { String defaultPath = "${project_loc}/Resources/definitions.yaml"; return defaultPath; } }
true
a3bb04549f2af65b408e18b4395aa853c35be6d1
Java
Gleb000/parserTest
/src/main/java/by/parserTest/Main2.java
UTF-8
2,464
2.640625
3
[]
no_license
package by.parserTest; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class Main2 { public static void main(String[] args) { String url = "https://www.nasdaq.com/market-activity/stocks/aapl/earnings"; //System.setProperty("webdriver.chrome.driver", "driver\\chromedriver.exe"); WebDriver webDriver = new ChromeDriver(); try { webDriver.get(url); } catch (TimeoutException exception) { System.out.println("Lost Internet Connection"); } Document page = Jsoup.parse(webDriver.getPageSource()); webDriver.close(); Element earningsSurpAmoun = page.select("tbody[class=earnings-surprise__table-body]").first(); Element earningsForecast = page.select("div[class=earnings-forecast__section earnings-forecast__section--quarterly]").first(); Element earningsForecastTable = earningsForecast.select("tbody[class=earnings-forecast__table-body]").first(); for (int i = 0; i < 2; i++) { Element earningsForecastElement = earningsForecastTable.select("tr[class=earnings-forecast__row earnings-forecast__row--body]").get(i); System.out.println("Some " + earningsForecastElement.select("th[class=earnings-forecast__cell]").text()); System.out.println("Some second " + earningsForecastElement.select("td[class=earnings-forecast__cell]").first().text()); System.out.println(); System.out.println(); } for (int i = 0; i < 4; i++) { Element earningsSurpAmounElement = earningsSurpAmoun.select("tr[class=earnings-surprise__row earnings-surprise__row--body]").get(i); System.out.println("Month: " + earningsSurpAmounElement.select("th[class=earnings-surprise__table-cell]").text()); System.out.println("Date: " + earningsSurpAmounElement.select("td[class=earnings-surprise__table-cell]").get(0).text()); System.out.println("First: " + earningsSurpAmounElement.select("td[class=earnings-surprise__table-cell]").get(1).text()); System.out.println("Second: " + earningsSurpAmounElement.select("td[class=earnings-surprise__table-cell]").get(2).text()); System.out.println(); System.out.println(); } } }
true
51c89bc380bdfc441af80c016afa717e00925a79
Java
achowdhury80/leetcode
/src/comp/prep2019/less1000/Prob382.java
UTF-8
676
3.21875
3
[]
no_license
package comp.prep2019.less1000; import java.util.Random; import comp.prep2019.ListNode; public class Prob382 { private ListNode head; private int len; private Random random; public Prob382(ListNode head) { this.head = head; random = new Random(); len = 1; ListNode cur = head; while(cur.next != null) { len++; cur = cur.next; } } /** Returns a random node's value. */ public int getRandom() { int count = 0, idx = random.nextInt(len); ListNode cur = head; while(count < idx) { cur = cur.next; count++; } return cur.val; } }
true
9bff8c9c8ce4299fa01411b142839d181c88332f
Java
google-code/atlantida-market
/Atlantida/Server/Jucatori_online.java
UTF-8
2,348
2.609375
3
[]
no_license
import java.sql.ResultSet; import java.sql.Statement; public class Jucatori_online extends BazaDeDate { public Jucatori_online(String numeBazaDate) { super(numeBazaDate); } public int inserareInregistrare(String numeUtilizator) { Statement decl = null; try { decl = this.conn.createStatement(); String comanda = ""; comanda = "INSERT INTO Jucatori_online (ID, UTILIZATOR, TIP_JUCATOR, NR_PUNCTE) " + "VALUES((SELECT ID FROM Jucatori WHERE UTILIZATOR = '" + numeUtilizator + "')," + "(SELECT UTILIZATOR FROM Jucatori WHERE UTILIZATOR = '" + numeUtilizator + "')," + "(SELECT TIP_JUCATOR FROM Jucatori WHERE UTILIZATOR = '" + numeUtilizator + "')," + "(SELECT NR_PUNCTE FROM Jucatori WHERE UTILIZATOR = '" + numeUtilizator + "'));"; decl.addBatch(comanda); decl.executeBatch(); } catch (Exception e) { e.printStackTrace(); return 1; } return 0; } public String getNumarPuncte(String nume) { Statement decl = null; try { ResultSet rezultatUtilizator; decl = this.conn.createStatement(); rezultatUtilizator = decl.executeQuery("SELECT nr_puncte FROM Jucatori_online WHERE utilizator='" + nume +"';"); rezultatUtilizator.first(); return rezultatUtilizator.getString(1); } catch (Exception e) { e.printStackTrace(); return ""; } } public boolean actualizareCapitalJucator(String numeUtilizator, float valoareElement, String operator) { try { Statement decl = this.conn.createStatement(); String comanda = ""; comanda = "UPDATE Jucatori_online " + "SET nr_puncte= nr_puncte " + operator + valoareElement + " WHERE utilizator='" + numeUtilizator+ "';"; decl.addBatch(comanda); decl.executeBatch(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } public boolean stergereInregistrare(String numeUtilizator) { try { Statement decl = this.conn.createStatement(); String comanda = ""; comanda = "DELETE FROM Jucatori_online WHERE utilizator='" + numeUtilizator + "';"; decl.addBatch(comanda); decl.executeBatch(); } catch (Exception e) { e.printStackTrace(); return false; } return true; } }
true
17833eb65775de5902a742c2f505f6cdbc0cd590
Java
Phalufa/petbook
/Server/src/main/java/com/miko/petbook/repositories/UserRepository.java
UTF-8
420
1.96875
2
[]
no_license
package com.miko.petbook.repositories; import java.util.Optional; import com.miko.petbook.models.User; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository<User, Long> { boolean existsByEmail(String email); boolean existsByUsername(String username); Optional<User> findByUsername(String username); Optional<User> findByEmail(String email); }
true
91a1cf7117b4e4cbaa2f532f04b86cd11106f8de
Java
VicenteqsDam/T2Grupo1
/src/main/java/es/fempa/citas/domain/AmistadPk.java
UTF-8
336
1.632813
2
[]
no_license
package es.fempa.citas.domain; import java.io.Serializable; import javax.persistence.Embeddable; import javax.persistence.ManyToOne; import lombok.Getter; import lombok.Setter; @Getter @Setter @Embeddable public class AmistadPk implements Serializable { @ManyToOne private Usuario usuario; @ManyToOne private Usuario amigo; }
true
005fbf22315d601702bc59bd97be2922188c4eb7
Java
podojuice/algorithm
/javaalgo/src/bj5430.java
UTF-8
1,673
2.8125
3
[]
no_license
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class bj5430 { static char[] def; static int[] list; static boolean R; static boolean err; public static void main(String[] args) throws Exception { StringTokenizer st; // BufferedReader br = new BufferedReader(new FileReader(new File("bj5430"))); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine()); for(int tc=1; tc<=T; tc++) { def = br.readLine().toCharArray(); int N = Integer.parseInt(br.readLine()); String tmp = br.readLine(); int len = tmp.length(); tmp = tmp.substring(1, len-1); st = new StringTokenizer(tmp, ","); list = new int[N]; int front = 0; int rear = N; R = true; err= false; for(int i=0; i<N; i++) { list[i] = Integer.parseInt(st.nextToken()); } for(int i=0; i<def.length; i++) { if(def[i] == 'R') R = !R; else { if(front == rear) { err = true; } if(R) front ++; else rear --; } } if(err) { System.out.println("error"); continue; } if(R) { System.out.print("["); for(int i=front; i<rear; i++) { System.out.print(list[i]); if(i != rear-1) { System.out.print(","); } } System.out.print("]"); System.out.println(); } else { System.out.print("["); for(int i=rear-1; i>=front; i--) { System.out.print(list[i]); if(i != front) { System.out.print(","); } } System.out.print("]"); System.out.println(); } } } }
true
025f108d3bdf02000eceb4908088c352fef923ba
Java
LucasDiasRodrigues/AppJobs
/app/src/main/java/com/teamappjobs/appjobs/fragment/MinhasVitrinesFragment.java
UTF-8
3,512
2.21875
2
[]
no_license
package com.teamappjobs.appjobs.fragment; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import com.teamappjobs.appjobs.R; import com.teamappjobs.appjobs.adapter.RecyclerViewMinhasVitrinesAdapter; import com.teamappjobs.appjobs.asyncTask.ListaVitrinesTask; import com.teamappjobs.appjobs.modelo.Vitrine; import java.util.List; /** * Created by Lucas on 28/04/2016. */ public class MinhasVitrinesFragment extends Fragment{ private RecyclerView listVitrines; private TextView txtSemVitrines; private RecyclerView.LayoutManager mLayoutManager; private SharedPreferences prefs ; private List<Vitrine> vitrines; private ProgressBar progressBar; private SwipeRefreshLayout mSwipeRefreshLayout; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View fragment = inflater.inflate(R.layout.fragment_lista_minhas_vitrines,container,false); listVitrines = (RecyclerView) fragment.findViewById(R.id.recycler_view_vitrines); txtSemVitrines = (TextView) fragment.findViewById(R.id.txtSemVitrines); prefs= getActivity().getSharedPreferences("Configuracoes", Context.MODE_PRIVATE); progressBar = (ProgressBar) fragment.findViewById(R.id.progress); mSwipeRefreshLayout = (SwipeRefreshLayout) fragment.findViewById(R.id.swiperefresh); mSwipeRefreshLayout.setColorSchemeResources(R.color.colorAccent,R.color.colorPrimary,R.color.colorPrimaryDark); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { Log.i("AtualizandoLista", "onRefresh called from SwipeRefreshLayout"); listaVitrines(); } }); return fragment; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); listaVitrines(); } @Override public void onResume() { super.onResume(); listaVitrines(); } public void listaVitrines(){ ListaVitrinesTask task = new ListaVitrinesTask(getActivity(),this,"minhasVitrines",prefs.getString("email", "")); task.execute(); } public void atualizaListaVitrines(List<Vitrine> vitrines){ this.vitrines = vitrines; mSwipeRefreshLayout.setRefreshing(false); progressBar.setVisibility(View.GONE); if(vitrines.size() > 0){ Log.i("atualizaListaVitr",""); txtSemVitrines.setVisibility(View.GONE); RecyclerViewMinhasVitrinesAdapter adapter = new RecyclerViewMinhasVitrinesAdapter(getActivity(),vitrines); mLayoutManager = new LinearLayoutManager(getActivity()); listVitrines.setLayoutManager(mLayoutManager); listVitrines.setAdapter(adapter); } else { txtSemVitrines.setVisibility(View.VISIBLE); } } }
true
d153b0860b2140b8ef111f7bf277c515f5fbd09e
Java
abrahamkang/Coordinatorlayoutdemo
/app/src/main/java/com/example/administrator/coordinatorlayoutdemo/bean/BaseBean.java
UTF-8
1,171
2.171875
2
[]
no_license
/* * File Name:BaseBean.java * Copyright:Copyright 2008-2015 CiWong.Inc. All Rights Reserved. * Description: BaseBean.java * Modify By:bin * Modify Date:2015年4月23日 * Modify Type:Add */ package com.example.administrator.coordinatorlayoutdemo.bean; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; /** * 实体类基类 * */ public class BaseBean implements Serializable { /** * TODO field comment */ private static final long serialVersionUID = -635484015267913538L; protected long _id; public long get_id() { return _id; } public void set_id(long _id) { this._id = _id; } public ParameterizedType getType(final Class raw, final Type... args) { return new ParameterizedType() { public Type getRawType() { return raw; } public Type[] getActualTypeArguments() { return args; } public Type getOwnerType() { return null; } }; } }
true
7a3820d0efda5e7c0026f0e6b4eb7c72d2446448
Java
IvyZh/AgentBible_lj
/AgentBible/app/src/main/java/cn/com/gxdgroup/angentbible/holder/impl/details/HouseIntroHolder.java
UTF-8
1,682
2.203125
2
[]
no_license
package cn.com.gxdgroup.angentbible.holder.impl.details; import android.support.v4.app.FragmentActivity; import android.view.View; import android.widget.ImageButton; import android.widget.TextView; import com.ms.square.android.expandabletextview.ExpandableTextView; import butterknife.BindView; import butterknife.OnClick; import cn.com.gxdgroup.angentbible.R; import cn.com.gxdgroup.angentbible.holder.BaseHolder; import cn.com.gxdgroup.angentbible.utils.UIUtils; /** * Created by Ivy on 2016/10/18. * * @description: 二手房详情里面的Holder */ public class HouseIntroHolder extends BaseHolder { @BindView(R.id.expand_text_view) ExpandableTextView mExpandTextView; public HouseIntroHolder(FragmentActivity activity) { super(activity); } @Override public View setContentView() { return UIUtils.inflate(R.layout.holder_house_intro); } @Override public void setData() { } @Override public void initView() { String str = "实地看房:2房1厅1卫1阳台,客厅朝南带大阳台, 厨卫房朝北,房间朝南,南北通透,全明户型。 地理位置:位于泰和西路/水产西路,宝山顾村核心地段,靠近1号线共富新村站!距离世纪联华大超市五分钟步行,外环高架车程五分钟。 小区配置:高端物业(银顶峰物业)、小区内小桥流水、有公园等多处景观、儿童游乐场,绿化率40%。 商圈配套:紧邻顾村商圈,靠近顾村公园,浦西大的湿地氧吧。对口宝山顾村小学及顾村中学。"; mExpandTextView.setText(str); } }
true
5f6db59b5f1c6cea487c8afb07ce8160f74c81e9
Java
AShynkevich/Exampler
/src/main/java/by/shynkevich/math/example/generator/action/ActionFactory.java
UTF-8
1,544
2.5625
3
[]
no_license
package by.shynkevich.math.example.generator.action; import java.util.Map; import java.util.Objects; import javax.annotation.Resource; import by.shynkevich.math.example.domain.Operator; import by.shynkevich.math.example.exception.NoOperationException; import org.springframework.stereotype.Component; /** * Math action factory. */ @Component public class ActionFactory { private static final String NO_ACTION_FORMAT = "No action for [%s] operator"; @Resource private Map<Operator, Action> actionStrategy; /** * Generates action by operator. * * @param operator the {@link Operator}. * @param minLimit min limit bound * @param maxLimit max limit bound * @return the array of terms */ public int[] generateAction(Operator operator, int minLimit, int maxLimit) { return generateAction(operator, minLimit, maxLimit, null); } /** * Generates action by operator. * * @param operator the {@link Operator}. * @param minLimit min limit bound * @param maxLimit max limit bound * @param forcedResult the forced result * @return the array of terms */ public int[] generateAction(Operator operator, int minLimit, int maxLimit, Integer forcedResult) { Action action = actionStrategy.get(operator); if (Objects.isNull(action)) { throw new NoOperationException(String.format(NO_ACTION_FORMAT, operator.name())); } return action.generate(minLimit, maxLimit, forcedResult); } }
true
e0cae69b4fd969f3e4849ab8804a6668cc787c96
Java
Matsv/java-two-factor-auth
/src/test/java/com/j256/totp/TwoFactorAuthUtilTest.java
UTF-8
3,267
2.859375
3
[ "ISC" ]
permissive
package com.j256.totp; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import java.security.GeneralSecurityException; import java.util.Random; import org.apache.commons.codec.binary.Base32; import org.junit.Test; /** * Little test program to show how to use the TwoFactorAuthUtil utility class. * * See: https://github.com/j256/java-two-factor-auth * * @author graywatson */ public class TwoFactorAuthUtilTest { public static void main(String[] args) throws Exception { TwoFactorAuthUtil twoFactorAuthUtil = new TwoFactorAuthUtil(); // String base32Secret = twoFactorAuthUtil.generateBase32Secret(); String base32Secret = "NY4A5CPJZ46LXZCP"; System.out.println("secret = " + base32Secret); // this is the name of the key which can be displayed by the authenticator program String keyId = "user@foo.com"; System.out.println("Image url = " + twoFactorAuthUtil.qrImageUrl(keyId, base32Secret)); // we can display this image to the user to let them load it into their auth program // we can use the code here and compare it against user input String code = twoFactorAuthUtil.generateCurrentNumber(base32Secret); /* * this little loop is here to show how the number changes over time */ while (true) { long diff = TwoFactorAuthUtil.TIME_STEP_SECONDS - ((System.currentTimeMillis() / 1000) % TwoFactorAuthUtil.TIME_STEP_SECONDS); code = twoFactorAuthUtil.generateCurrentNumber(base32Secret); System.out.println("Secret code = " + code + ", change in " + diff + " seconds"); Thread.sleep(1000); } } @Test public void testZeroPrepend() { TwoFactorAuthUtil tfau = new TwoFactorAuthUtil(); Random random = new Random(); for (int i = 0; i < 10000; i++) { int num = random.nextInt(1000000); /** * NOTE: Did a speed test of these and the zeroPrepend is ~13x faster. */ assertEquals(String.format("%06d", num), tfau.zeroPrepend(num, 6)); } } @Test public void testDecodeBase32() { TwoFactorAuthUtil tfau = new TwoFactorAuthUtil(); Random random = new Random(); random.nextBytes(new byte[100]); Base32 base32 = new Base32(); for (int i = 0; i < 10000; i++) { byte[] bytes = new byte[random.nextInt(10) + 1]; random.nextBytes(bytes); String encoded = base32.encodeAsString(bytes); byte[] expected = base32.decode(encoded); byte[] actual = tfau.decodeBase32(encoded); assertArrayEquals(expected, actual); } } @Test public void testVariusKnownSecretTimeCodes() throws GeneralSecurityException { TwoFactorAuthUtil tfau = new TwoFactorAuthUtil(); String secret = "NY4A5CPJZ46LXZCP"; assertEquals("748810", tfau.generateCurrentNumber(secret, 1000L)); assertEquals("325893", tfau.generateCurrentNumber(secret, 7451000L)); assertEquals("064088", tfau.generateCurrentNumber(secret, 15451000L)); assertEquals("009637", tfau.generateCurrentNumber(secret, 348402049542546145L)); assertEquals("000743", tfau.generateCurrentNumber(secret, 2049455124374752571L)); assertEquals("000092", tfau.generateCurrentNumber(secret, 1359002349304873750L)); assertEquals("000007", tfau.generateCurrentNumber(secret, 6344447817348357059L)); assertEquals("000000", tfau.generateCurrentNumber(secret, 2125701285964551130L)); } }
true
6afd0ef41400020dd61ca21f26f26850227171bf
Java
Megabytte/PongClone
/Pong/src/me/Megabytte/Game/LoadTexture.java
UTF-8
645
2.59375
3
[]
no_license
package me.Megabytte.Game; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import org.newdawn.slick.opengl.Texture; import org.newdawn.slick.opengl.TextureLoader; public class LoadTexture { Texture texture; public LoadTexture() { } public Texture loadImage(String key, Texture texture) { try { texture = TextureLoader.getTexture("PNG", new FileInputStream(new File("res/Images/" + key + ".png"))); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return texture; } }
true
3794c8bc3ce29376c8aa57a25222238680a5d85c
Java
YouwangDeng/Leetcode
/BFS/0854-K-Similar Strings.java
UTF-8
1,054
3.359375
3
[]
no_license
//Solution 1 BFS solution guarantee the min result class Solution { public int kSimilarity(String A, String B) { if (A.equals(B)) return 0; Set<String> vis= new HashSet<>(); Queue<String> q= new LinkedList<>(); q.add(A); vis.add(A); int res=0; while(!q.isEmpty()){ res++; for (int sz=q.size(); sz>0; sz--){ String s= q.poll(); int i=0; while (s.charAt(i)==B.charAt(i)) i++; for (int j=i+1; j<s.length(); j++){ if (s.charAt(j)==B.charAt(j) || s.charAt(i)!=B.charAt(j) ) continue; String temp= swap(s, i, j); if (temp.equals(B)) return res; if (vis.add(temp)) q.add(temp); } } } return res; } public String swap(String s, int i, int j){ char[] ca=s.toCharArray(); char temp=ca[i]; ca[i]=ca[j]; ca[j]=temp; return new String(ca); } }
true
c8f23b013567a1e5fc9665cae277645335f84f16
Java
TihiyTi/HeartLive
/CommunicationSerial/src/test/java/com/tihiy/comm/serial/SignalManager.java
UTF-8
565
2.265625
2
[]
no_license
package com.tihiy.comm.serial; import com.tihiy.comm.serial.protocols.Protocol; import com.tihiy.rclint.control.Controller; import com.tihiy.rclint.models.SignalModel; public class SignalManager extends AbstractSignalManager<Integer> { Controller cn; public SignalManager(Controller cn) { this.cn = cn; } @Override public void createSignal(String flowName){ super.createSignal(flowName); if(getProtocol().equals(Protocol.SimpleEcg)){ cn.createSignalModel(flowName, new SignalModel()); } } }
true
34b1efb86e6cb4fbec0b61354462a7bef2376136
Java
jelinski/kodbot
/src/main/java/pl/jellysoft/kodbot/resolver/evaluator/command/AssignCommand.java
UTF-8
325
2.203125
2
[]
no_license
package pl.jellysoft.kodbot.resolver.evaluator.command; import lombok.Value; @Value public class AssignCommand implements Command { private final String leftOperand; private final String rightOperand; @Override public <R> R accept(CommandVisitor<R> visitor) { return visitor.visit(this); } }
true
12c0b6d9a88ac231eaeb0bc18c32b5641ea60c78
Java
TreyM-WSS/m2x-android
/app/src/main/java/com/att/m2x/android/model/Location.java
UTF-8
3,858
2.6875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package com.att.m2x.android.model; import com.att.m2x.android.utils.DateUtils; import org.json.JSONException; import org.json.JSONObject; import java.text.ParseException; import java.util.Date; /** * Model Object represents a {@see <a href="https://m2x.att.com/developer/documentation/v2/device#Read-Device-Location">Location</a>} */ public class Location implements IModelObject { public Location() { } private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } private Double elevation; public Double getElevation() { return elevation; } public void setElevation(Double elevation) { this.elevation = elevation; } private Double latitude; public Double getLatitude() { return latitude; } public void setLatitude(Double latitude) { this.latitude = latitude; } private Double longitude; public Double getLongitude() { return longitude; } public void setLongitude(Double longitude) { this.longitude = longitude; } private Date timestamp; public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } //////////////////////////////////// // JSON //////////////////////////////////// /** * Converts this Location into a JSONObject * * @return */ public JSONObject toJsonObject() { return Location.toJsonObject(this); } /** * Converts a Location into a JSONObject * * @param location * @return */ public static JSONObject toJsonObject(Location location) { JSONObject result = null; try { if (location != null) { result = new JSONObject(); if (location.getName() != null) result.put("name", location.getName()); if (location.getElevation() != null) result.put("elevation", location.getElevation()); if (location.getLatitude() != null) result.put("latitude", location.getLatitude()); if (location.getLongitude() != null) result.put("longitude", location.getLongitude()); if (location.getTimestamp() != null) result.put("timestamp", DateUtils.dateTimeToString(location.getTimestamp())); } } catch (JSONException je) { je.printStackTrace(); result = null; } return result; } @Override public void fromJson(JSONObject jsonObject) throws JSONException { if (jsonObject != null) { if (jsonObject.has("name")) setName(jsonObject.getString("name")); if (!jsonObject.isNull("timestamp")) try { setTimestamp(DateUtils.stringToDateTime(jsonObject.getString("timestamp"))); } catch (ParseException e) { throw new JSONException(e.getMessage()); } if (!jsonObject.isNull("elevation")) setElevation(jsonObject.getDouble("elevation")); if (!jsonObject.isNull("latitude")) setLatitude(jsonObject.getDouble("latitude")); if (!jsonObject.isNull("longitude")) setLongitude(jsonObject.getDouble("longitude")); } } /** * Converts a JSONObject into a Location * * @param jsonObject * @return */ public static Location fromJsonObject(JSONObject jsonObject) throws JSONException { if (jsonObject == null) return null; Location location = new Location(); location.fromJson(jsonObject); return location; } }
true
c55667c9db6072ee3e48da01cdc4cbb1ed3ac897
Java
N1ghtStalk3r/clothesShop
/src/main/java/clothesShop/model/Order.java
UTF-8
1,856
3.140625
3
[]
no_license
package clothesShop.model; import java.util.Arrays; import java.util.Objects; /** * Класс заказов (покупок) * * @author Ozzy on 12-08-21. */ public class Order { private final int id; private final int customerId; private final int employeeId; private int[] clothes; /** * @param id Идентификатор * @param employeeId Продаваец * @param customerId Покупатель * @param clothes id одежды */ public Order(int id, int employeeId, int customerId, int[] clothes) { this.id = id; this.customerId = customerId; this.employeeId = employeeId; if (clothes.length > 0) this.clothes = clothes; } public int getId() { return id; } public int getCustomerId() { return customerId; } public int getEmployeeId() { return employeeId; } public int[] getClothes() { return clothes; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Order order = (Order) o; return id == order.id && customerId == order.customerId && employeeId == order.employeeId && Arrays.equals(clothes, order.clothes); } @Override public int hashCode() { int result = Objects.hash(id, customerId, employeeId); result = 31 * result + Arrays.hashCode(clothes); return result; } @Override public String toString() { return "Заказ{" + "id=" + id + ", покупатель=" + customerId + ", продавец=" + employeeId + ", одежды=" + Arrays.toString(clothes) + '}'; } }
true
9f3958e77754766f232b6d8e1b6541799054abaa
Java
kojoYeboah53i/expo
/android/versioned-abis/expoview-abi37_0_0/src/main/java/abi37_0_0/expo/modules/barcodescanner/BarCodeScannerModule.java
UTF-8
5,012
1.78125
2
[ "MIT", "BSD-3-Clause", "Apache-2.0" ]
permissive
package abi37_0_0.expo.modules.barcodescanner; import android.Manifest; import android.content.Context; import android.graphics.Bitmap; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.android.gms.vision.barcode.Barcode; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import abi37_0_0.org.unimodules.core.ExportedModule; import abi37_0_0.org.unimodules.core.ModuleRegistry; import abi37_0_0.org.unimodules.core.Promise; import abi37_0_0.org.unimodules.core.interfaces.ExpoMethod; import abi37_0_0.org.unimodules.interfaces.barcodescanner.BarCodeScanner; import abi37_0_0.org.unimodules.interfaces.barcodescanner.BarCodeScannerResult; import abi37_0_0.org.unimodules.interfaces.barcodescanner.BarCodeScannerSettings; import abi37_0_0.org.unimodules.interfaces.imageloader.ImageLoader; import abi37_0_0.org.unimodules.interfaces.permissions.Permissions; import static abi37_0_0.expo.modules.barcodescanner.ExpoBarCodeScanner.CAMERA_TYPE_BACK; import static abi37_0_0.expo.modules.barcodescanner.ExpoBarCodeScanner.CAMERA_TYPE_FRONT; public class BarCodeScannerModule extends ExportedModule { private static final String TAG = "ExpoBarCodeScannerModule"; private static final String ERROR_TAG = "E_BARCODE_SCANNER"; private final BarCodeScannerProvider mBarCodeScannerProvider; private ModuleRegistry mModuleRegistry; private static final Map<String, Object> VALID_BARCODE_TYPES = Collections.unmodifiableMap(new HashMap<String, Object>() { { put("aztec", Barcode.AZTEC); put("ean13", Barcode.EAN_13); put("ean8", Barcode.EAN_8); put("qr", Barcode.QR_CODE); put("pdf417", Barcode.PDF417); put("upc_e", Barcode.UPC_E); put("datamatrix", Barcode.DATA_MATRIX); put("code39", Barcode.CODE_39); put("code93", Barcode.CODE_93); put("itf14", Barcode.ITF); put("codabar", Barcode.CODABAR); put("code128", Barcode.CODE_128); put("upc_a", Barcode.UPC_A); } }); @Override public void onCreate(ModuleRegistry moduleRegistry) { mModuleRegistry = moduleRegistry; } public BarCodeScannerModule(Context context) { super(context); mBarCodeScannerProvider = new BarCodeScannerProvider(); } @Override public String getName() { return TAG; } @Override public Map<String, Object> getConstants() { return Collections.unmodifiableMap(new HashMap<String, Object>() { { put("BarCodeType", getBarCodeConstants()); put("Type", getTypeConstants()); } private Map<String, Object> getBarCodeConstants() { return VALID_BARCODE_TYPES; } private Map<String, Object> getTypeConstants() { return Collections.unmodifiableMap(new HashMap<String, Object>() { { put("front", CAMERA_TYPE_FRONT); put("back", CAMERA_TYPE_BACK); } }); } }); } @ExpoMethod public void requestPermissionsAsync(final Promise promise) { Permissions.askForPermissionsWithPermissionsManager(mModuleRegistry.getModule(Permissions.class), promise, Manifest.permission.CAMERA); } @ExpoMethod public void getPermissionsAsync(final Promise promise) { Permissions.getPermissionsWithPermissionsManager(mModuleRegistry.getModule(Permissions.class), promise, Manifest.permission.CAMERA); } @ExpoMethod public void scanFromURLAsync(final String url, final List<Double> barCodeTypes, final Promise promise) { final List<Integer> types = new ArrayList<>(); if (barCodeTypes != null) { for (int i = 0; i < barCodeTypes.size(); i++) { types.add(barCodeTypes.get(i).intValue()); } } final ImageLoader imageLoader = mModuleRegistry.getModule(ImageLoader.class); imageLoader.loadImageForManipulationFromURL(url, new ImageLoader.ResultListener() { @Override public void onSuccess(@NonNull Bitmap bitmap) { BarCodeScanner scanner = mBarCodeScannerProvider.createBarCodeDetectorWithContext(getContext()); scanner.setSettings(new BarCodeScannerSettings() {{ putTypes(types); }}); List<BarCodeScannerResult> results = scanner.scanMultiple(bitmap); List<Bundle> resultList = new ArrayList<>(); for (BarCodeScannerResult result : results) { if (types.contains(result.getType())) { Bundle bundle = new Bundle(); bundle.putString("data", result.getValue()); bundle.putInt("type", result.getType()); resultList.add(bundle); } } promise.resolve(resultList); } @Override public void onFailure(@Nullable Throwable cause) { promise.reject(ERROR_TAG + "_IMAGE_RETRIEVAL_ERROR", "Could not get the image from given url: '" + url + "'", cause); } }); } }
true
da25d2d32dccfb9a720472a579455d092587117f
Java
joaorodrigues2012/ccp3an_mca_app_previsoes
/src/main/java/br/usjt/previsao_tempo/repository/PeriodosRepository.java
UTF-8
2,035
2.21875
2
[]
no_license
package br.usjt.previsao_tempo.repository; import br.usjt.previsao_tempo.model.Cidade; import br.usjt.previsao_tempo.model.Periodo; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.scheduling.annotation.Async; import java.util.List; import java.util.concurrent.Future; public interface PeriodosRepository extends JpaRepository<Periodo, Long> { //List<Periodo> findAllByCidade_Nome(String nome); //List<Periodo> findAllByCidade_LatitudeAndCidade_Longitude(Double lat, Double lon); // List<Periodo> findAllByCidade_NomeIgnoreCase(String nome); /*-----------------------------------------ASSINCRONA--------------------------------------------------------------*/ // @Async // public Future< List<Periodo>> findAllByCidade_LatitudeAndCidade_Longitude (Double lat, Double lon); // // @Async // public Future< List<Periodo>> findAllByCidade_Nome(String nome); // // @Async // public Future<List<Periodo>> findAllByCidade_NomeIgnoreCase (String nome); /*------------------------------------------------QUERY-----------------------------------------------------------------*/ @Query("select p from Periodo p inner join p.cidade c where c.id = p.id and upper(c.nome) = upper(:nome)") List<Periodo> findAllByCidade_Nome(@Param("nome") String nome); @Query("select p from Periodo p inner join p.cidade c where c.id = p.id and c.latitude = :latitude and c.longitude = :longitude") List<Periodo> findAllByCidade_LatitudeAndCidade_Longitude(@Param("latitude") Double latitude, @Param("longitude") Double longitude); /*--------------------------------------NAMED QUERIES-----------------------------------------------------------------------*/ List<Periodo> BuscaPeloCidadeNome (@Param("nome") String nome); List<Periodo> BuscaPeloLatELon(@Param("latitude") Double latitude,@Param("longitude") Double longitude); }
true
91eb2932e8bbf69a156c61befc36c8d0923461e1
Java
MasannatSandra/CS-3560-Mini-Twitter
/UserGroupVisitor.java
UTF-8
244
1.90625
2
[]
no_license
package twitterdriver; //Inferface for all the 4 children visitor classes in visitor patterns public interface UserGroupVisitor { public void visitUser(UserLeaf user); public void visitGroup(GroupContainer group); }
true
340a8294286d05e5c0e27dd234d44928d3f4b632
Java
miternos/streamsets-signalr-origin
/src/main/java/com/miternos/streamset/stage/util/ResourceCache.java
UTF-8
620
2.359375
2
[]
no_license
package com.miternos.streamset.stage.util; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class ResourceCache { private static ResourceCache instance; private static Map<String,Map<String,Object>> resources; private ResourceCache(){ resources = new ConcurrentHashMap<String,Map<String,Object>>(); } public static synchronized ResourceCache getInstance(){ if ( instance == null ) instance = new ResourceCache(); return instance; } public Map<String,Map<String,Object>> getResources(){ return resources; } }
true
09c9a99d020f82627c2d4c62133df3dd749b8fc4
Java
step-artur87/sinlinChart
/src/main/java/util/UtMap.java
UTF-8
2,876
3.046875
3
[]
no_license
package util; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.OptionalInt; import java.util.stream.IntStream; /** * Created with IntelliJ IDEA. * User: art * Date: 9/13/15 * Time: 2:26 AM * To change this template use File | Settings | File Templates. */ public class UtMap { public static ArrayList<Map<String, Double>> getRowsAL( Map<String, ArrayList<Double>> data) { ArrayList<Map<String, Double>> rows = new ArrayList<>(); ArrayList<ArrayList<Double>> matrix = new ArrayList<>(); ArrayList<ArrayList<Double>> transposed; Map<String, Double> tmpMap; ArrayList<String> keys = getKeys(data); int n = getMapArrayListsSize(data); if (n > 0) { data.forEach((s, a) -> { matrix.add(a); }); transposed = transpose(matrix); for (int i = 0; i < transposed.size(); i++) { tmpMap = new HashMap<>(); for (int j = 0; j < keys.size(); j++) { tmpMap.put(keys.get(j), transposed.get(i).get(j)); } rows.add(tmpMap); } } else { //todo } return rows; } public static int getMapArrayListsSize( Map<String, ArrayList<Double>> map) { IntStream intStream = map.values().stream().mapToInt((a) -> a.size()); OptionalInt max = intStream.max(); //fixme intStream = map.values().stream().mapToInt((a) -> a.size()); OptionalInt min = intStream.min(); if (!max.isPresent() && !min.isPresent()) return 0; if (max.equals(min)) return max.getAsInt(); return -1; } //without checking public static ArrayList<ArrayList<Double>> transpose( ArrayList<ArrayList<Double>> data) { ArrayList<ArrayList<Double>> result = new ArrayList<>(); int w = data.size(); int h = data.get(0).size(); for (int i = 0; i < h; i++) { result.add(new ArrayList<>()); for (int j = 0; j < w; j++) { result.get(i).add(data.get(j).get(i)); } } return result; } public static ArrayList<String> getKeys( Map<String, ?> map) { ArrayList<String> keys = new ArrayList<>(); map.forEach((s, a) -> { keys.add(s); }); return keys; } public static String getString( Map<String, Double> row) { StringBuilder stringBuilder = new StringBuilder(); for (String string : row.keySet()) { stringBuilder.append(string) .append(" = ") .append(row.get(string)) .append(";"); } return stringBuilder.toString(); } }
true
624016dc0e5618cdef85dd47103780c8b083ae60
Java
manugildev/modular-cubes-app
/app/src/main/java/com/manugildev/modularcubes/WifiFragment.java
UTF-8
3,997
2.015625
2
[]
no_license
package com.manugildev.modularcubes; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.NetworkInfo; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.format.Formatter; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.manugildev.modularcubes.network.TCPServerThread; import java.util.List; public class WifiFragment extends Fragment { Context context; String networkSSID = "CUBES_MESH"; BroadcastReceiver receiver; WifiManager wifiManager; private Button button; private String gateway; private TCPServerThread TCPServerThread; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); context = getActivity().getApplicationContext(); startWifi(); } private void startWifi() { wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo info = wifiManager.getConnectionInfo(); if (!info.getSSID().contains(networkSSID)) { WifiConfiguration conf = new WifiConfiguration(); conf.SSID = "\"" + networkSSID + "\""; wifiManager.addNetwork(conf); List<WifiConfiguration> list = wifiManager.getConfiguredNetworks(); for (WifiConfiguration i : list) { if (i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) { wifiManager.disconnect(); wifiManager.enableNetwork(i.networkId, true); wifiManager.reconnect(); break; } } receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) { NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); boolean connected = info.isConnected(); if (connected) { WifiInfo wifiInfo = wifiManager.getConnectionInfo(); String ssid = wifiInfo.getSSID(); Log.d("SSID", ssid + " " + networkSSID); if (ssid.contains(networkSSID)) { gateway = Formatter.formatIpAddress(wifiManager.getDhcpInfo().gateway); startUDP(gateway); } } } } }; getActivity().registerReceiver(receiver, new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION)); } else { gateway = Formatter.formatIpAddress(wifiManager.getDhcpInfo().gateway); startUDP(gateway); } } private void startUDP(String gateway) { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_wifi, container, false); button = (Button) rootView.findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { TCPServerThread.sendMessage("Manuel? Android"); } }); return rootView; } @Override public void onDetach() { super.onDetach(); } @Override public void onDestroy() { // mTcpClient.stopClient(); super.onDestroy(); } }
true
59242e29b38694f7b7b139d640101d09707fac8b
Java
ylsn19821104/hunter
/hunter-core/src/main/java/com/sina/amp/trace/hunter/MixSpanCollector.java
UTF-8
1,159
2.21875
2
[]
no_license
package com.sina.amp.trace.hunter; import com.github.kristofa.brave.LoggingSpanCollector; import com.github.kristofa.brave.SpanCollector; import com.github.kristofa.brave.zipkin.ZipkinSpanCollector; import com.github.kristofa.brave.zipkin.ZipkinSpanCollectorParams; import com.sina.amp.trace.hunter.collector.ZipkinSpanCollectorProxy; import com.twitter.zipkin.gen.Span; public class MixSpanCollector implements SpanCollector{ private SpanCollector loggingCollector; private SpanCollector zipkinConllector; public MixSpanCollector(String host, int port) { try { this.loggingCollector = new LoggingSpanCollector(); this.zipkinConllector = new ZipkinSpanCollector(host, port); }catch(Exception e) { e.printStackTrace(); } } @Override public void collect(Span span) { this.loggingCollector.collect(span); this.zipkinConllector.collect(span); } @Override public void addDefaultAnnotation(String key, String value) { loggingCollector.addDefaultAnnotation(key, value); zipkinConllector.addDefaultAnnotation(key, value); } @Override public void close() { loggingCollector.close(); zipkinConllector.close(); } }
true
679fe0b79f6fa5fb08fc2d9737f62dc3af693798
Java
Pseudonym96/Portfolio
/SpaceInvaders/src/SpaceInvaders/HighScoresScreen.java
UTF-8
6,985
3.25
3
[]
no_license
package SpaceInvaders; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Collections; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.control.Button; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.Text; /** * * @author Alexander */ public class HighScoresScreen { private Pane pane; private Text scoreText = new Text(""); private ArrayList<HighScore> highScores = new ArrayList<HighScore>(); public HighScoresScreen(Pane pane) { this.pane = pane; // populate the score list initializeScores(); } /** * clear and then draw everything to the screen * this is not done in the constructor method because the scores need to be initialized before the screen is drawn * so that the game can check whether or not drawing this screen is necessary */ public void start() { // clear the pane pane.getChildren().clear(); // initialize all text and the button initializeText(); initializeButton(); } private void initializeButton() { Button menuButton = new Button("Main Menu"); // set the button's action to the action defined in the MenuHandler class menuButton.setOnAction(new MenuHandler()); // Set the scale of the button in the x and y to 2 menuButton.setScaleX(2); menuButton.setScaleY(2); // bind the button horizontally to the center of the pane menuButton.layoutXProperty().bind(pane.widthProperty().divide(2).subtract(menuButton.widthProperty().divide(2))); // bind the button vertically to 300 pixels below the center of the pane menuButton.layoutYProperty().bind(pane.heightProperty().divide(2).add(300)); pane.getChildren().add(menuButton); } private void initializeScores() { // if the file by the name of "HighScores.dat" exists... if(new File("HighScores.dat").exists()) { // attempt to create an object input stream based on the input file try(ObjectInputStream input = new ObjectInputStream(new BufferedInputStream(new FileInputStream("HighScores.dat")))) { try { // reads all objects until end of file // Did this instead of reading 10 objects in case I want to recycle this code to create a longer or shorter high score list in the future while(true) { highScores.add((HighScore)input.readObject()); } } // at the end of the file, catch the exception and then do nothing catch(EOFException e) { } } // This should never occur because of the check beforehand, but is necessary to satisfy the compiler catch(FileNotFoundException e) { System.out.println("File opening during file initialization failed because file was not found"); } // catch any issues with the file catch(IOException e) { System.out.println("Problem with file operations during file initialization"); } // catch issues resulting from objects whose class does not match HighScore being scored in the file // this could be cause by a user manually modifying the file catch(ClassNotFoundException e) { System.out.println("Problem with objects in file during file initialization"); } } // if the file does not already exist... else { // populate highScores with a predefined set of high scores highScores.add(new HighScore(10000, "AAA")); highScores.add(new HighScore(9500, "BBB")); highScores.add(new HighScore(9000, "CCC")); highScores.add(new HighScore(8500, "MOM")); highScores.add(new HighScore(8000, "DAD")); highScores.add(new HighScore(7500, "TED")); highScores.add(new HighScore(7000, "KIM")); highScores.add(new HighScore(6500, "JOE")); highScores.add(new HighScore(6000, "BOB")); highScores.add(new HighScore(1000, "TIM")); // try to create an object output stream based on a file of name "HighScores.dat" try(ObjectOutputStream output = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("HighScores.dat")))) { // write every high score in highScores to the file for(HighScore score : highScores) { output.writeObject(score); } } // if their is an issue during the file operations, inform the user catch(IOException e) { System.out.println("Problem initializing file"); } } } // initialize and display all text values private void initializeText() { Text titleText = new Text("High Scores"); updateText(); titleText.setFont(new Font(80)); scoreText.setFont(Font.font(java.awt.Font.MONOSPACED,40)); titleText.setFill(Color.WHITE); scoreText.setFill(Color.WHITE); titleText.xProperty().bind(pane.widthProperty().divide(2).subtract(titleText.getLayoutBounds().getWidth()/2)); titleText.yProperty().bind(pane.heightProperty().divide(2).subtract(250)); scoreText.xProperty().bind(pane.widthProperty().divide(2).subtract(scoreText.getLayoutBounds().getWidth()/2)); scoreText.yProperty().bind(pane.heightProperty().divide(2).subtract(175)); pane.getChildren().add(scoreText); pane.getChildren().add(titleText); } // update the text for the scores to match an updated list private void updateText() { String scores = ""; for(HighScore score : highScores) { scores += score.getInitials() + " " + score.getScore() + "\n"; } scoreText.setText(scores); } // update the file with the new list when a new score is added private void updateFile() { try(ObjectOutputStream output = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("HighScores.dat")))) { for(HighScore score : highScores) { output.writeObject(score); } } catch(IOException e) { System.out.println("Issue with file during score update"); } } /** * * @param score a HighScore object to be tested * @return boolean representation of whether or not the score is high enough to be on the high score list */ public boolean highEnough(HighScore score) { return(highScores.get(9).compareTo(score) > 0); } /** * Adds a score to the high score lis and then sorts it in descending order * @param score The high score to add to the list */ public void addScore(HighScore score) { // add a new score to the list highScores.add(score); // sort the list in descending order Collections.sort(highScores); // remove the score in position 11 highScores.remove(10); // update the high score text updateText(); // update the high scores in the file updateFile(); } class MenuHandler implements EventHandler<ActionEvent> { @Override public void handle(ActionEvent e) { // when the button is clicked, return to the title screen new TitleScreen(pane); } } }
true
8f24546cbf2033c59e2d3e97e451ea150dd7cf74
Java
TheShermanTanker/NMS-1.16.3
/org/bukkit/event/inventory/CraftItemEvent.java
UTF-8
1,616
2.078125
2
[]
no_license
/* */ package org.bukkit.event.inventory; /* */ /* */ import org.bukkit.inventory.CraftingInventory; /* */ import org.bukkit.inventory.Inventory; /* */ import org.bukkit.inventory.InventoryView; /* */ import org.bukkit.inventory.Recipe; /* */ import org.jetbrains.annotations.NotNull; /* */ /* */ /* */ public class CraftItemEvent /* */ extends InventoryClickEvent /* */ { /* */ private Recipe recipe; /* */ /* */ public CraftItemEvent(@NotNull Recipe recipe, @NotNull InventoryView what, @NotNull InventoryType.SlotType type, int slot, @NotNull ClickType click, @NotNull InventoryAction action) { /* 16 */ super(what, type, slot, click, action); /* 17 */ this.recipe = recipe; /* */ } /* */ /* */ public CraftItemEvent(@NotNull Recipe recipe, @NotNull InventoryView what, @NotNull InventoryType.SlotType type, int slot, @NotNull ClickType click, @NotNull InventoryAction action, int key) { /* 21 */ super(what, type, slot, click, action, key); /* 22 */ this.recipe = recipe; /* */ } /* */ /* */ /* */ /* */ /* */ @NotNull /* */ public Recipe getRecipe() { /* 30 */ return this.recipe; /* */ } /* */ /* */ /* */ @NotNull /* */ public CraftingInventory getInventory() { /* 36 */ return (CraftingInventory)super.getInventory(); /* */ } /* */ } /* Location: C:\Users\Josep\Downloads\Decompile Minecraft\tuinity-1.16.3.jar!\org\bukkit\event\inventory\CraftItemEvent.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
true
befd4ce203527b9725bbc8f5c78960e62f54bb2c
Java
biasj/perifarte
/src/main/java/br/senac/sp/tads/pi3/antes/tads/perifarte/modelos/Doacao.java
UTF-8
2,297
2.46875
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package br.senac.sp.tads.pi3.antes.tads.perifarte.modelos; import java.math.BigDecimal; import java.time.Instant; import java.time.LocalDate; /** * * @author marce_000 */ public class Doacao { private int idCompra; // private double totalDoado; //este valor é para o total doado private int idDoador; // somente números 27326531000125 para poder verificar private int idObra; private int idOrganizacao; private LocalDate data_compra; private String status; private BigDecimal valor; // este valor é para o quanto será doado em cada compra individual feita public Doacao(int idDoador, int idObra, int organizacao, BigDecimal valor) { this.idDoador = idDoador; this.idObra = idObra; this.idOrganizacao = organizacao; this.valor = valor; data_compra = LocalDate.now(); status = "pendente"; } public Doacao(int idObra, String status, LocalDate data) { this.data_compra = data; this.idObra = idObra; this.status = status; } public int getIdCompra() { return idCompra; } public void setIdCompra(int id) { this.idCompra = id; } public int getIdDoador() { return idDoador; } public void setIdDoador(int idDoador) { this.idDoador = idDoador; } public int getIdObra() { return idObra; } public void setIdObra(int idObra) { this.idObra = idObra; } public int getIdOrganizacao() { return idOrganizacao; } public void setIdOrganizacao(int idOrganizacao) { this.idOrganizacao = idOrganizacao; } public LocalDate getData_compra() { return data_compra; } public void setData_compra(LocalDate data_compra) { this.data_compra = data_compra; } public void setStatus(String status) { this.status = status; } public String getStatus() { return status; } public BigDecimal getValor() { return valor; } public void setValor(BigDecimal valor) { this.valor = valor; } }
true
069eb67cb3b69534e336966d97a46f4c8622ffb1
Java
mattfrancis888/Airbnb
/app/src/main/java/com/example/toshiba/airbnb/Profile/BecomeAHost/SetTheScene/DescribePlaceFragment.java
UTF-8
7,535
1.929688
2
[]
no_license
package com.example.toshiba.airbnb.Profile.BecomeAHost.SetTheScene; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.example.toshiba.airbnb.DatabaseInterface; import com.example.toshiba.airbnb.Explore.Homes.HomeDescActivity; import com.example.toshiba.airbnb.Profile.ViewListingAndYourBooking.EditListing.DTO.DTODescription; import com.example.toshiba.airbnb.Profile.ViewListingAndYourBooking.EditListing.EditListingFragment; import com.example.toshiba.airbnb.Profile.ViewListingAndYourBooking.ViewListingAndYourBookingAdapter; import com.example.toshiba.airbnb.Util.KeyboardUtil; import com.example.toshiba.airbnb.R; import com.example.toshiba.airbnb.Util.RetrofitUtil; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by Owner on 2017-07-19. */ public class DescribePlaceFragment extends Fragment { public static final String DESCRIBE_SP = "DESCRIBE_SP"; public static final String DESCRIBE_PREVIEW = "DESCRIBE_PREVIEW"; public static final String DESCRIBE_PLACE_KEY = "DESCRIBE_PLACE_KEY"; private SharedPreferences describePlaceSP; Button bPreview; Button bNext; EditText etDescribePlace; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_describe_place, container, false); if (getArguments() == null) { ProgressBar basicProgressBar = (ProgressBar) getActivity().findViewById(R.id.basicProgressBar); basicProgressBar.setProgress(75); } return view; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); etDescribePlace = (EditText) view.findViewById(R.id.etDescribePlace); bPreview = (Button) view.findViewById(R.id.bPreview); bNext = (Button) view.findViewById(R.id.bNext); final TextView tvWordCount = (TextView) view.findViewById(R.id.tvWordCount); //get description stored in internal storage through sharedpreferences describePlaceSP = getActivity().getSharedPreferences(DESCRIBE_SP, Context.MODE_PRIVATE); String savedEtDescribePlace = describePlaceSP.getString(DESCRIBE_PLACE_KEY, ""); etDescribePlace.setText(savedEtDescribePlace); registrationProceed(); TextWatcher textWatcher = new TextWatcher() { public void afterTextChanged(Editable s) { tvWordCount.setText(String.valueOf(500 - etDescribePlace.getText().length())); registrationProceed(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { } }; etDescribePlace.addTextChangedListener(textWatcher); if(getArguments() != null) { if (getArguments().containsKey(EditListingFragment.DESCRIPTION_PLACE_FRAGMENT_INFO_FROM_DATABASE) && getArguments().containsKey(ViewListingAndYourBookingAdapter.LISTING_ID)) { final String descriptionFromDatabase = getArguments().getString(EditListingFragment.DESCRIPTION_PLACE_FRAGMENT_INFO_FROM_DATABASE); etDescribePlace.setText(descriptionFromDatabase); bPreview.setVisibility(View.GONE); bNext.setText(getString(R.string.save)); bNext.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { KeyboardUtil.hideKeyboard(getActivity()); DatabaseInterface retrofit = RetrofitUtil.retrofitBuilderForDatabaseInterface(); final ProgressDialog dialog = new ProgressDialog(getActivity()); dialog.setMessage("Updating data..."); dialog.setCancelable(false); dialog.show(); retrofit.updateDescription(getArguments().getInt(ViewListingAndYourBookingAdapter.LISTING_ID), new DTODescription(etDescribePlace.getText().toString())).enqueue(new Callback<Void>() { @Override public void onResponse(Call<Void> call, Response<Void> response) { dialog.dismiss(); Toast.makeText(getActivity(), "Updated", Toast.LENGTH_LONG).show(); getFragmentManager().popBackStack(); } @Override public void onFailure(Call<Void> call, Throwable t) { dialog.dismiss(); Toast.makeText(getActivity(), getString(R.string.failedToUpdate), Toast.LENGTH_LONG); } }); } }); } }else{ bNext.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { KeyboardUtil.hideKeyboard(getActivity()); getFragmentManager().beginTransaction().replace(R.id.progressFragment, new TitleFragment()).addToBackStack(null).commit(); //Save description SharedPreferences.Editor editor = describePlaceSP.edit(); editor.remove(DESCRIBE_PLACE_KEY); editor.putString(DESCRIBE_PLACE_KEY, etDescribePlace.getText().toString()); editor.apply(); } }); bPreview.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { KeyboardUtil.hideKeyboard(getActivity()); Intent intent = new Intent(getContext(), HomeDescActivity.class); intent.putExtra(DESCRIBE_PREVIEW, etDescribePlace.getText().toString()); Bundle bundle = new Bundle(); intent.putExtras(bundle); startActivity(intent); } }); } } public void registrationProceed() { if (etDescribePlace.getText().length() == 0) { bPreview.setEnabled(false); bNext.setEnabled(false); bPreview.setBackgroundResource(R.drawable.reg_host_proceed_button_fail); bNext.setBackgroundResource(R.drawable.reg_host_proceed_button_fail); } else { bPreview.setEnabled(true); bPreview.setBackgroundResource(R.drawable.reg_host_proceed_button); bNext.setEnabled(true); bNext.setBackgroundResource(R.drawable.reg_host_proceed_button); } } }
true
345b4646a3225ee7f57d5ee21b9ec098681e6cd1
Java
LegacyofAden/emu-ungp
/gameserver/src/main/java/org/l2junity/gameserver/network/packets/s2c/string/CustomMessage.java
UTF-8
3,081
2.421875
2
[]
no_license
package org.l2junity.gameserver.network.packets.s2c.string; import org.l2junity.gameserver.model.Language; import org.l2junity.gameserver.model.actor.instance.Player; import org.l2junity.gameserver.network.packets.s2c.SystemMessage; import java.util.HashMap; import java.util.Map; import java.util.stream.Stream; /** * Created by Hack * Date: 03.04.2017 8:09 * * * * * * * * * * * * * * * * * * * * * * How to use guide * * * * * * * * * * * * * * * * * * * * * * * @see CustomMessage (here) - add the enum name * data/message/custom_messages.xml - add the enum name and phrases for presented langs * call message.send() or player.sendMessage(CustomMessage message) for send a localized message to player * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ public enum CustomMessage { YOU_CANNOT_CHEAT_YOUR_WAY_OUT_OF_HERE_YOU_MUST_WAIT_UNTIL_YOUR_JAIL_TIME_IS_OVER, PRICE_OF_$_HAS_BEEN_CHANGED_TO_$, THE_NEXT_AUCTION_WILL_BEGIN_ON_THE_$, YOU_CAN_NOT_OBSERVE_GAMES_WHILE_REGISTERED_ON_AN_EVENT, YOUR_LIST_OF_BUFFS_IS_EMPTY_PLEASE_ADD_SOME_BUFFS_FIRST, YOUR_TITLE_CANNOT_EXCEED_29_CHARACTERS_IN_LENGTH_PLEASE_TRY_AGAIN, TOO_BIG_PRICE_MAXIMAL_PRICE_IS_$, $_SKIPPING_WAITING_TIME, $_YOU_CANT_SKIP_WAITING_TIME_RIGHT_NOW, $_ANTHARAS_HAS_BEEN_RESPAWNED, $_YOU_CANT_RESPAWN_ANTHARAS_WHILE_ANTHARAS_IS_ALIVE, $_ALL_MINIONS_HAS_BEEN_DELETED, $_YOU_CANT_DESPAWN_MINIONS_RIGHT_NOW, $_FIGHT_HAS_BEEN_ABORTED, $_YOU_CANT_ABORT_FIGHT_RIGHT_NOW, $_YOU_CANT_RESPAWN_BAIUM_WHILE_BAIUM_IS_ALIVE, $_ABORTING_FIGHT, $_ALL_ARCHANGELS_HAS_BEEN_DELETED, $_YOU_CANT_DESPAWN_ARCHANGELS_RIGHT_NOW, $_ISNT_IN_THE_WORLD, YOU_CANNOT_SWITCH_YOUR_CLASS_RIGHT_NOW, YOU_HAVE_LEARNED_$_NEW_SKILLS, CANNOT_SIT_WHILE_CASTING, YOU_CANNOT_MOUNT_A_STEED_WHILE_HOLDING_A_FLAG, SKILL_$_HAS_BEEN_REMOVED, TOO_SMALL_PRICE_MINIMAL_PRICE_IS_$, YOU_ALREADY_REACHED_MAX_COUNT_OF_BUFFS_MAX_BUFFS_IS_$, $_HAS_BEEN_ADDED, $_HAS_NO_ENOUGH_MANA_FOR_$, NOT_ENOUGH_$, NOT_ENOUGH_ITEMS, TELEPORT_SPAWN_PROTECTION_ENDED, ; private Map<Language, String> messages; CustomMessage() { messages = new HashMap<>(5); } public void addMessage(Language lang, String message) { messages.put(lang, message); } public String get(Language lang, String ... args) { String message = messages.get(lang); if (message == null) return "Error: message not found for your language."; if (args.length == 0) return message; for (int i = 0; i < args.length; i++) message = message.replaceFirst("%s%", args[i]); return message; } public void send(Player player, String ... args) { player.sendPacket(SystemMessage.sendString(get(player.getLang(), args))); } public void send(Player player, Object ... args) { if (args.length > 0) { String[] arr = new String[args.length]; for (int i = 0; i < args.length; i++) arr[i] = args[i].toString(); send(player, arr); } send(player); } public static boolean contains(String value) { return Stream.of(values()).anyMatch(e -> e.name().equals(value)); } }
true
8fce8fed548d94c7bb6731430208879f7fc0bba8
Java
siyoon210/spring-framework
/fastcampus/clonekrone/src/main/java/project/shoppingmall/clonekrone/domain/ProductOption.java
UTF-8
395
2.046875
2
[]
no_license
package project.shoppingmall.clonekrone.domain; import lombok.*; import javax.persistence.*; @Entity @Table(name = "product_option") @Data @NoArgsConstructor @AllArgsConstructor public class ProductOption { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(length = 100, nullable = false) private String name; private int extraPrice; }
true
fc932de393ceae5aec62e83e980b0df521a0b951
Java
lT1161558158/shipper-core
/src/main/java/top/trister/shipper/core/implHandler/codec/SimpleCodec.java
UTF-8
1,220
2.640625
3
[]
no_license
package top.trister.shipper.core.implHandler.codec; import lombok.Data; import top.trister.shipper.core.api.handler.codec.Codec; import java.util.HashMap; import java.util.Map; import static top.trister.shipper.core.event.Event.MESSAGE; /** * 添加一个时间filed发编码器 * 使用 format 变量进行时间格式化 * 若使用了错误的格式化则会使用默认的format yyyy-MM-dd HH:mm:ss */ @Data public class SimpleCodec implements Codec<Object, Map> { // private static final String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss"; // private String format = DEFAULT_FORMAT; // // private SimpleDateFormat builderFormat() { // SimpleDateFormat simpleDateFormat = new SimpleDateFormat(); // try { // simpleDateFormat.applyPattern(format); // } catch (Exception ignore) { // simpleDateFormat.applyPattern(DEFAULT_FORMAT); // format = DEFAULT_FORMAT; // } // return simpleDateFormat; // } @Override public Map codec(Object input) { Map<Object, Object> event = new HashMap<>(); // event.put(TIMESTAMP, builderFormat().format(new Date())); event.put(MESSAGE, input); return event; } }
true
e1f4c2cdc3e0921262bdc2f4f314c3e2070dd931
Java
FarhanaPractice/Homework3
/src/Inheritance/Banana.java
UTF-8
142
1.921875
2
[]
no_license
package Inheritance; public class Banana extends WomensDress { public void bullshit() { System.out.println("shut up Rashed bhaia"); } }
true
4d9537fcefeb9b394be967c74b89a12ea23e9687
Java
datree-demo/bcserver_demo
/cosmetic-core/src/main/java/com/cyberlink/cosmetic/hibernate/id/UserIdGenerator.java
UTF-8
1,030
2.265625
2
[ "Apache-2.0" ]
permissive
package com.cyberlink.cosmetic.hibernate.id; import java.io.Serializable; import org.hibernate.HibernateException; import org.hibernate.engine.spi.SessionImplementor; import com.cyberlink.cosmetic.Constants; import com.cyberlink.core.model.AbstractCoreEntity; public class UserIdGenerator extends MillisecValueGenerator { private static final Long SHARD_OTHERS = 1001L; private static Integer SERVER_SHARD_ID = null; public UserIdGenerator() { SERVER_SHARD_ID = Constants.getShardId().intValue() * 10000; } public synchronized Serializable generate(SessionImplementor session, Object object) throws HibernateException { try { @SuppressWarnings("rawtypes") Long shardId = ((AbstractCoreEntity) object).getShardId(); if (shardId == null) shardId = SHARD_OTHERS; initialValues = new Integer[] { SERVER_SHARD_ID + shardId.intValue() }; } catch (Exception e) { initialValues = new Integer[] { SERVER_SHARD_ID + SHARD_OTHERS.intValue() }; } return super.generate(session, object); } }
true
9c96aa262975a58d9b1ac26e1874067d75398ab2
Java
yinon115/finalProject
/src/View/GraphicalUI.java
UTF-8
373
2.328125
2
[]
no_license
package View; import javax.swing.*; import java.util.Scanner; public class GraphicalUI { private transient Scanner s = new Scanner(System.in); public void showMessege (String st){ JOptionPane.showMessageDialog(null,st); } public void showError (String st){ JOptionPane.showMessageDialog(null,st,"Error",JOptionPane.ERROR_MESSAGE); } }
true
d422871b4502b843f2dfad84641b2997b0d7ebae
Java
rholtzjr/eve_j2ee
/EVE_JPA/src/org/holtz/eve/jpa/entity/TRfreportFieldDefaultsId.java
UTF-8
17,605
1.75
2
[]
no_license
package org.holtz.eve.jpa.entity; // Generated Aug 4, 2017 9:16:24 AM by Hibernate Tools 4.0.1.Final import javax.persistence.Column; import javax.persistence.Embeddable; /** * TRfreportFieldDefaultsId generated by hbm2java */ @Embeddable public class TRfreportFieldDefaultsId implements java.io.Serializable { private int rfreportFieldId; private int rfreportLayoutId; private String rffieldTx; private short rffieldTypeId; private int rfreportSectionId; private String rffontNameTx; private float rffontSizeFl; private boolean rffontItalicBl; private boolean rffontBoldBl; private boolean rffontUnderlinedBl; private int rfxin; private int rfyin; private int rfwidthIn; private int rfheightIn; private boolean rfcentredBl; private String rfalignmentTx; private int rfforeColorIn; private boolean rfvisibleBl; private String rffilenameTxN; private String rfformatTxN; private boolean rfcanGrowBl; private boolean rfunavailableBl; private int rflinkedFieldId; private String rfmemoTxN; private Integer rfbackColorIn; private String rfruleTxN; private Integer rfbarcodeTypeIdN; private Integer rfnarrowBarWidthInN; private Integer rfwideBarWidthInN; private boolean rfhumanReadableBl; private int rfmaxCharsIn; public TRfreportFieldDefaultsId() { } public TRfreportFieldDefaultsId(int rfreportFieldId, int rfreportLayoutId, String rffieldTx, short rffieldTypeId, int rfreportSectionId, String rffontNameTx, float rffontSizeFl, boolean rffontItalicBl, boolean rffontBoldBl, boolean rffontUnderlinedBl, int rfxin, int rfyin, int rfwidthIn, int rfheightIn, boolean rfcentredBl, String rfalignmentTx, int rfforeColorIn, boolean rfvisibleBl, boolean rfcanGrowBl, boolean rfunavailableBl, int rflinkedFieldId, boolean rfhumanReadableBl, int rfmaxCharsIn) { this.rfreportFieldId = rfreportFieldId; this.rfreportLayoutId = rfreportLayoutId; this.rffieldTx = rffieldTx; this.rffieldTypeId = rffieldTypeId; this.rfreportSectionId = rfreportSectionId; this.rffontNameTx = rffontNameTx; this.rffontSizeFl = rffontSizeFl; this.rffontItalicBl = rffontItalicBl; this.rffontBoldBl = rffontBoldBl; this.rffontUnderlinedBl = rffontUnderlinedBl; this.rfxin = rfxin; this.rfyin = rfyin; this.rfwidthIn = rfwidthIn; this.rfheightIn = rfheightIn; this.rfcentredBl = rfcentredBl; this.rfalignmentTx = rfalignmentTx; this.rfforeColorIn = rfforeColorIn; this.rfvisibleBl = rfvisibleBl; this.rfcanGrowBl = rfcanGrowBl; this.rfunavailableBl = rfunavailableBl; this.rflinkedFieldId = rflinkedFieldId; this.rfhumanReadableBl = rfhumanReadableBl; this.rfmaxCharsIn = rfmaxCharsIn; } public TRfreportFieldDefaultsId(int rfreportFieldId, int rfreportLayoutId, String rffieldTx, short rffieldTypeId, int rfreportSectionId, String rffontNameTx, float rffontSizeFl, boolean rffontItalicBl, boolean rffontBoldBl, boolean rffontUnderlinedBl, int rfxin, int rfyin, int rfwidthIn, int rfheightIn, boolean rfcentredBl, String rfalignmentTx, int rfforeColorIn, boolean rfvisibleBl, String rffilenameTxN, String rfformatTxN, boolean rfcanGrowBl, boolean rfunavailableBl, int rflinkedFieldId, String rfmemoTxN, Integer rfbackColorIn, String rfruleTxN, Integer rfbarcodeTypeIdN, Integer rfnarrowBarWidthInN, Integer rfwideBarWidthInN, boolean rfhumanReadableBl, int rfmaxCharsIn) { this.rfreportFieldId = rfreportFieldId; this.rfreportLayoutId = rfreportLayoutId; this.rffieldTx = rffieldTx; this.rffieldTypeId = rffieldTypeId; this.rfreportSectionId = rfreportSectionId; this.rffontNameTx = rffontNameTx; this.rffontSizeFl = rffontSizeFl; this.rffontItalicBl = rffontItalicBl; this.rffontBoldBl = rffontBoldBl; this.rffontUnderlinedBl = rffontUnderlinedBl; this.rfxin = rfxin; this.rfyin = rfyin; this.rfwidthIn = rfwidthIn; this.rfheightIn = rfheightIn; this.rfcentredBl = rfcentredBl; this.rfalignmentTx = rfalignmentTx; this.rfforeColorIn = rfforeColorIn; this.rfvisibleBl = rfvisibleBl; this.rffilenameTxN = rffilenameTxN; this.rfformatTxN = rfformatTxN; this.rfcanGrowBl = rfcanGrowBl; this.rfunavailableBl = rfunavailableBl; this.rflinkedFieldId = rflinkedFieldId; this.rfmemoTxN = rfmemoTxN; this.rfbackColorIn = rfbackColorIn; this.rfruleTxN = rfruleTxN; this.rfbarcodeTypeIdN = rfbarcodeTypeIdN; this.rfnarrowBarWidthInN = rfnarrowBarWidthInN; this.rfwideBarWidthInN = rfwideBarWidthInN; this.rfhumanReadableBl = rfhumanReadableBl; this.rfmaxCharsIn = rfmaxCharsIn; } @Column(name = "RFReportFieldID", nullable = false) public int getRfreportFieldId() { return this.rfreportFieldId; } public void setRfreportFieldId(int rfreportFieldId) { this.rfreportFieldId = rfreportFieldId; } @Column(name = "RFReportLayoutID", nullable = false) public int getRfreportLayoutId() { return this.rfreportLayoutId; } public void setRfreportLayoutId(int rfreportLayoutId) { this.rfreportLayoutId = rfreportLayoutId; } @Column(name = "RFFieldTx", nullable = false) public String getRffieldTx() { return this.rffieldTx; } public void setRffieldTx(String rffieldTx) { this.rffieldTx = rffieldTx; } @Column(name = "RFFieldTypeID", nullable = false) public short getRffieldTypeId() { return this.rffieldTypeId; } public void setRffieldTypeId(short rffieldTypeId) { this.rffieldTypeId = rffieldTypeId; } @Column(name = "RFReportSectionID", nullable = false) public int getRfreportSectionId() { return this.rfreportSectionId; } public void setRfreportSectionId(int rfreportSectionId) { this.rfreportSectionId = rfreportSectionId; } @Column(name = "RFFontNameTx", nullable = false) public String getRffontNameTx() { return this.rffontNameTx; } public void setRffontNameTx(String rffontNameTx) { this.rffontNameTx = rffontNameTx; } @Column(name = "RFFontSizeFl", nullable = false, precision = 24, scale = 0) public float getRffontSizeFl() { return this.rffontSizeFl; } public void setRffontSizeFl(float rffontSizeFl) { this.rffontSizeFl = rffontSizeFl; } @Column(name = "RFFontItalicBl", nullable = false) public boolean isRffontItalicBl() { return this.rffontItalicBl; } public void setRffontItalicBl(boolean rffontItalicBl) { this.rffontItalicBl = rffontItalicBl; } @Column(name = "RFFontBoldBl", nullable = false) public boolean isRffontBoldBl() { return this.rffontBoldBl; } public void setRffontBoldBl(boolean rffontBoldBl) { this.rffontBoldBl = rffontBoldBl; } @Column(name = "RFFontUnderlinedBl", nullable = false) public boolean isRffontUnderlinedBl() { return this.rffontUnderlinedBl; } public void setRffontUnderlinedBl(boolean rffontUnderlinedBl) { this.rffontUnderlinedBl = rffontUnderlinedBl; } @Column(name = "RFXIn", nullable = false) public int getRfxin() { return this.rfxin; } public void setRfxin(int rfxin) { this.rfxin = rfxin; } @Column(name = "RFYIn", nullable = false) public int getRfyin() { return this.rfyin; } public void setRfyin(int rfyin) { this.rfyin = rfyin; } @Column(name = "RFWidthIn", nullable = false) public int getRfwidthIn() { return this.rfwidthIn; } public void setRfwidthIn(int rfwidthIn) { this.rfwidthIn = rfwidthIn; } @Column(name = "RFHeightIn", nullable = false) public int getRfheightIn() { return this.rfheightIn; } public void setRfheightIn(int rfheightIn) { this.rfheightIn = rfheightIn; } @Column(name = "RFCentredBl", nullable = false) public boolean isRfcentredBl() { return this.rfcentredBl; } public void setRfcentredBl(boolean rfcentredBl) { this.rfcentredBl = rfcentredBl; } @Column(name = "RFAlignmentTx", nullable = false) public String getRfalignmentTx() { return this.rfalignmentTx; } public void setRfalignmentTx(String rfalignmentTx) { this.rfalignmentTx = rfalignmentTx; } @Column(name = "RFForeColorIn", nullable = false) public int getRfforeColorIn() { return this.rfforeColorIn; } public void setRfforeColorIn(int rfforeColorIn) { this.rfforeColorIn = rfforeColorIn; } @Column(name = "RFVisibleBl", nullable = false) public boolean isRfvisibleBl() { return this.rfvisibleBl; } public void setRfvisibleBl(boolean rfvisibleBl) { this.rfvisibleBl = rfvisibleBl; } @Column(name = "RFFilenameTx_N") public String getRffilenameTxN() { return this.rffilenameTxN; } public void setRffilenameTxN(String rffilenameTxN) { this.rffilenameTxN = rffilenameTxN; } @Column(name = "RFFormatTx_N") public String getRfformatTxN() { return this.rfformatTxN; } public void setRfformatTxN(String rfformatTxN) { this.rfformatTxN = rfformatTxN; } @Column(name = "RFCanGrowBl", nullable = false) public boolean isRfcanGrowBl() { return this.rfcanGrowBl; } public void setRfcanGrowBl(boolean rfcanGrowBl) { this.rfcanGrowBl = rfcanGrowBl; } @Column(name = "RFUnavailableBl", nullable = false) public boolean isRfunavailableBl() { return this.rfunavailableBl; } public void setRfunavailableBl(boolean rfunavailableBl) { this.rfunavailableBl = rfunavailableBl; } @Column(name = "RFLinkedFieldID", nullable = false) public int getRflinkedFieldId() { return this.rflinkedFieldId; } public void setRflinkedFieldId(int rflinkedFieldId) { this.rflinkedFieldId = rflinkedFieldId; } @Column(name = "RFMemoTx_N") public String getRfmemoTxN() { return this.rfmemoTxN; } public void setRfmemoTxN(String rfmemoTxN) { this.rfmemoTxN = rfmemoTxN; } @Column(name = "RFBackColorIn") public Integer getRfbackColorIn() { return this.rfbackColorIn; } public void setRfbackColorIn(Integer rfbackColorIn) { this.rfbackColorIn = rfbackColorIn; } @Column(name = "RFRuleTx_N") public String getRfruleTxN() { return this.rfruleTxN; } public void setRfruleTxN(String rfruleTxN) { this.rfruleTxN = rfruleTxN; } @Column(name = "RFBarcodeTypeID_N") public Integer getRfbarcodeTypeIdN() { return this.rfbarcodeTypeIdN; } public void setRfbarcodeTypeIdN(Integer rfbarcodeTypeIdN) { this.rfbarcodeTypeIdN = rfbarcodeTypeIdN; } @Column(name = "RFNarrowBarWidthIn_N") public Integer getRfnarrowBarWidthInN() { return this.rfnarrowBarWidthInN; } public void setRfnarrowBarWidthInN(Integer rfnarrowBarWidthInN) { this.rfnarrowBarWidthInN = rfnarrowBarWidthInN; } @Column(name = "RFWideBarWidthIn_N") public Integer getRfwideBarWidthInN() { return this.rfwideBarWidthInN; } public void setRfwideBarWidthInN(Integer rfwideBarWidthInN) { this.rfwideBarWidthInN = rfwideBarWidthInN; } @Column(name = "RFHumanReadableBl", nullable = false) public boolean isRfhumanReadableBl() { return this.rfhumanReadableBl; } public void setRfhumanReadableBl(boolean rfhumanReadableBl) { this.rfhumanReadableBl = rfhumanReadableBl; } @Column(name = "RFMaxCharsIn", nullable = false) public int getRfmaxCharsIn() { return this.rfmaxCharsIn; } public void setRfmaxCharsIn(int rfmaxCharsIn) { this.rfmaxCharsIn = rfmaxCharsIn; } public boolean equals(Object other) { if ((this == other)) return true; if ((other == null)) return false; if (!(other instanceof TRfreportFieldDefaultsId)) return false; TRfreportFieldDefaultsId castOther = (TRfreportFieldDefaultsId) other; return (this.getRfreportFieldId() == castOther.getRfreportFieldId()) && (this.getRfreportLayoutId() == castOther.getRfreportLayoutId()) && ((this.getRffieldTx() == castOther.getRffieldTx()) || (this.getRffieldTx() != null && castOther.getRffieldTx() != null && this.getRffieldTx().equals(castOther.getRffieldTx()))) && (this.getRffieldTypeId() == castOther.getRffieldTypeId()) && (this.getRfreportSectionId() == castOther.getRfreportSectionId()) && ((this.getRffontNameTx() == castOther.getRffontNameTx()) || (this.getRffontNameTx() != null && castOther.getRffontNameTx() != null && this.getRffontNameTx().equals(castOther.getRffontNameTx()))) && (this.getRffontSizeFl() == castOther.getRffontSizeFl()) && (this.isRffontItalicBl() == castOther.isRffontItalicBl()) && (this.isRffontBoldBl() == castOther.isRffontBoldBl()) && (this.isRffontUnderlinedBl() == castOther.isRffontUnderlinedBl()) && (this.getRfxin() == castOther.getRfxin()) && (this.getRfyin() == castOther.getRfyin()) && (this.getRfwidthIn() == castOther.getRfwidthIn()) && (this.getRfheightIn() == castOther.getRfheightIn()) && (this.isRfcentredBl() == castOther.isRfcentredBl()) && ((this.getRfalignmentTx() == castOther.getRfalignmentTx()) || (this.getRfalignmentTx() != null && castOther.getRfalignmentTx() != null && this.getRfalignmentTx().equals(castOther.getRfalignmentTx()))) && (this.getRfforeColorIn() == castOther.getRfforeColorIn()) && (this.isRfvisibleBl() == castOther.isRfvisibleBl()) && ((this.getRffilenameTxN() == castOther.getRffilenameTxN()) || (this.getRffilenameTxN() != null && castOther.getRffilenameTxN() != null && this.getRffilenameTxN().equals(castOther.getRffilenameTxN()))) && ((this.getRfformatTxN() == castOther.getRfformatTxN()) || (this.getRfformatTxN() != null && castOther.getRfformatTxN() != null && this.getRfformatTxN().equals(castOther.getRfformatTxN()))) && (this.isRfcanGrowBl() == castOther.isRfcanGrowBl()) && (this.isRfunavailableBl() == castOther.isRfunavailableBl()) && (this.getRflinkedFieldId() == castOther.getRflinkedFieldId()) && ((this.getRfmemoTxN() == castOther.getRfmemoTxN()) || (this.getRfmemoTxN() != null && castOther.getRfmemoTxN() != null && this.getRfmemoTxN().equals(castOther.getRfmemoTxN()))) && ((this.getRfbackColorIn() == castOther.getRfbackColorIn()) || (this.getRfbackColorIn() != null && castOther.getRfbackColorIn() != null && this.getRfbackColorIn().equals(castOther.getRfbackColorIn()))) && ((this.getRfruleTxN() == castOther.getRfruleTxN()) || (this.getRfruleTxN() != null && castOther.getRfruleTxN() != null && this.getRfruleTxN().equals(castOther.getRfruleTxN()))) && ((this.getRfbarcodeTypeIdN() == castOther.getRfbarcodeTypeIdN()) || (this.getRfbarcodeTypeIdN() != null && castOther.getRfbarcodeTypeIdN() != null && this.getRfbarcodeTypeIdN().equals(castOther.getRfbarcodeTypeIdN()))) && ((this.getRfnarrowBarWidthInN() == castOther.getRfnarrowBarWidthInN()) || (this.getRfnarrowBarWidthInN() != null && castOther.getRfnarrowBarWidthInN() != null && this.getRfnarrowBarWidthInN().equals(castOther.getRfnarrowBarWidthInN()))) && ((this.getRfwideBarWidthInN() == castOther.getRfwideBarWidthInN()) || (this.getRfwideBarWidthInN() != null && castOther.getRfwideBarWidthInN() != null && this.getRfwideBarWidthInN().equals(castOther.getRfwideBarWidthInN()))) && (this.isRfhumanReadableBl() == castOther.isRfhumanReadableBl()) && (this.getRfmaxCharsIn() == castOther.getRfmaxCharsIn()); } public int hashCode() { int result = 17; result = 37 * result + this.getRfreportFieldId(); result = 37 * result + this.getRfreportLayoutId(); result = 37 * result + (getRffieldTx() == null ? 0 : this.getRffieldTx().hashCode()); result = 37 * result + this.getRffieldTypeId(); result = 37 * result + this.getRfreportSectionId(); result = 37 * result + (getRffontNameTx() == null ? 0 : this.getRffontNameTx().hashCode()); result = 37 * result + (int) this.getRffontSizeFl(); result = 37 * result + (this.isRffontItalicBl() ? 1 : 0); result = 37 * result + (this.isRffontBoldBl() ? 1 : 0); result = 37 * result + (this.isRffontUnderlinedBl() ? 1 : 0); result = 37 * result + this.getRfxin(); result = 37 * result + this.getRfyin(); result = 37 * result + this.getRfwidthIn(); result = 37 * result + this.getRfheightIn(); result = 37 * result + (this.isRfcentredBl() ? 1 : 0); result = 37 * result + (getRfalignmentTx() == null ? 0 : this.getRfalignmentTx().hashCode()); result = 37 * result + this.getRfforeColorIn(); result = 37 * result + (this.isRfvisibleBl() ? 1 : 0); result = 37 * result + (getRffilenameTxN() == null ? 0 : this.getRffilenameTxN().hashCode()); result = 37 * result + (getRfformatTxN() == null ? 0 : this.getRfformatTxN().hashCode()); result = 37 * result + (this.isRfcanGrowBl() ? 1 : 0); result = 37 * result + (this.isRfunavailableBl() ? 1 : 0); result = 37 * result + this.getRflinkedFieldId(); result = 37 * result + (getRfmemoTxN() == null ? 0 : this.getRfmemoTxN().hashCode()); result = 37 * result + (getRfbackColorIn() == null ? 0 : this.getRfbackColorIn().hashCode()); result = 37 * result + (getRfruleTxN() == null ? 0 : this.getRfruleTxN().hashCode()); result = 37 * result + (getRfbarcodeTypeIdN() == null ? 0 : this.getRfbarcodeTypeIdN().hashCode()); result = 37 * result + (getRfnarrowBarWidthInN() == null ? 0 : this.getRfnarrowBarWidthInN().hashCode()); result = 37 * result + (getRfwideBarWidthInN() == null ? 0 : this.getRfwideBarWidthInN().hashCode()); result = 37 * result + (this.isRfhumanReadableBl() ? 1 : 0); result = 37 * result + this.getRfmaxCharsIn(); return result; } }
true
24bf30bd7f17d7320d7f501ee2708a84da8b1aa6
Java
KaranKanojiya/jbpm
/jbpm-runtime-manager/src/main/java/org/jbpm/runtime/manager/impl/lock/DebugRuntimeManagerLock.java
UTF-8
3,326
2.421875
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2020 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jbpm.runtime.manager.impl.lock; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import org.jbpm.runtime.manager.spi.RuntimeManagerLock; public class DebugRuntimeManagerLock implements RuntimeManagerLock { private ReentrantLock lock = new ReentrantLock(true); private List<StackTraceElement[]> traces; private long currentThreadId; public DebugRuntimeManagerLock() { traces = new ArrayList<>(); currentThreadId = -1; } @Override public void lock() { lock.lock(); addTraces(); } @Override public boolean tryLock(long units, TimeUnit timeUnit) throws InterruptedException { boolean outcome = lock.tryLock(units, timeUnit); if(outcome) { addTraces(); } return outcome; } @Override public void lockInterruptible() throws InterruptedException { lock.lockInterruptibly(); addTraces(); } private void addTraces() { long newThreadId = Thread.currentThread().getId(); if(currentThreadId < 0 || currentThreadId != newThreadId) { currentThreadId = newThreadId; traces.clear(); } // we add all stack traces during reentrant lock traces.add(Thread.currentThread().getStackTrace()); } @Override public void unlock() { // only we clear up when count is 0 if(currentThreadId == Thread.currentThread().getId() && lock.getHoldCount() == 1) { traces.clear(); // clean up } lock.unlock(); } @Override public boolean isHeldByCurrentThread() { return lock.isHeldByCurrentThread(); } @Override public boolean hasQueuedThreads() { return lock.hasQueuedThreads(); } @Override public int getQueueLength() { return lock.getQueueLength(); } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("DebugRuntimeManagerLock ["); builder.append(lock); builder.append("]\n"); builder.append("--------CURRENT REENTRANT STACKTRACE-----------------------\n"); for (int i = 0; i < traces.size(); i++) { builder.append("\tSTACKTRACE " + i + "\n"); StackTraceElement[] trace = traces.get(i); for(int j = 0; j < trace.length; j++) { builder.append("\t\t\t" + trace[j] + "\n"); } } builder.append("--------END CURRENT REENTRANT STACKTRACE-------------------\n"); return builder.toString(); } }
true
8bf5b4a72172fc4e837622d04e9e0af5340b1fd8
Java
meraihan/gemini
/gemini-auth/src/main/java/it/at7/gemini/auth/core/OAuthClientRef.java
UTF-8
219
1.8125
2
[ "Apache-2.0" ]
permissive
package it.at7.gemini.auth.core; public interface OAuthClientRef { String NAME = "OAUTHCLIENT"; interface FIELDS { String CLIENT_ID = "clientId"; String CLIENT_SECRET = "clientSecret"; } }
true
7c4bf6fc8af47135b29e14088580fa5494ae62cd
Java
LyakhnitskiyDP/BrightStream
/src/main/java/com/lod/brightstream/controller/taskControllers/DownloadTasksXLSXServlet.java
UTF-8
3,234
2.375
2
[]
no_license
package com.lod.brightstream.controller.taskControllers; import com.lod.brightstream.BE.Task; import com.lod.brightstream.BE.User; import com.lod.brightstream.DAL.TaskDA; import com.lod.brightstream.DAL.impl.TaskDAMySQL; import java.io.IOException; import java.io.OutputStream; import java.util.List; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.*; @WebServlet("/userPage/downloadTasksXLSX") public class DownloadTasksXLSXServlet extends HttpServlet { public static final int NUMBER_OF_COLUMS = 5; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) { Workbook workbook = new HSSFWorkbook(); Sheet sheet = workbook.createSheet("My Tasks"); Row row = sheet.createRow(0); User user = (User) getObjectFromSession(request, "user"); setUpHeaders(row); setUpContent(sheet, user.getId()); response.setHeader("content-disposition", "attachment; filename=MyTasks.xls"); response.setHeader("cache-control", "no-chache"); try (OutputStream out = response.getOutputStream()) { workbook.write(out); } catch (IOException ioException) { log("Workbook could not be loaded" + ioException); } } private void setUpHeaders(Row row) { List<String> headers = List.of("Name", "Content", "Completed", "Creation Date", "Completion Date"); for ( int i = 0; i < headers.size(); i++ ) { row.createCell(i).setCellValue(headers.get(i)); } } private void setUpContent(Sheet sheet, long userId) { TaskDA taskDA = new TaskDAMySQL(); List<Task> listOfTasks = taskDA.getTasksByUserId(userId); Row row; for (int i = 0; i < listOfTasks.size(); i++) { row = sheet.createRow(i + 1); setUpRow(row, listOfTasks.get(i)); } } private void setUpRow(Row row, Task task) { List<String> taskFields = List.of( task.getName(), task.getContent().replaceAll("<br />", " "), task.isCompleted() ? "Yes" : "No", task.getCreation_time().toString(), task.getCompletion_time() == null ? "-" : task.getCompletion_time().toString() ); for (int i = 0; i < NUMBER_OF_COLUMS; i++) { row.createCell(i).setCellValue(taskFields.get(i)); } } private Object getObjectFromSession(HttpServletRequest request, String name) { return request.getSession().getAttribute(name); } }
true
744abc7c4043cfab88979230f5352225c7472937
Java
zhang123w/OO
/microserver-1/src/main/java/com/pktech/controller/UserController.java
UTF-8
1,150
2.40625
2
[]
no_license
package com.pktech.controller; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.pktech.entity.User; import com.pktech.service.UserService; @RestController public class UserController { @Autowired private UserService userService; @RequestMapping(value="/login",method=RequestMethod.GET) public Map<String, Object> login(@RequestParam String phone,@RequestParam String password){ Map<String, Object> map = new HashMap<String, Object>(); User user = new User(); user=userService.findUserByPhone(phone); System.out.println(password+","+user.getPassword()); System.out.println(phone); System.out.println(user); if(password.equals(user.getPassword())) { map.put("0000", "登录成功"); }else { map.put("0001", "登录错误"); } return map; } }
true
9dd6eb888733b3535130d443a04ef0db3578f2c6
Java
RegularPrincess/Score-Counter
/app/src/main/java/com/example/jmfedorov/countergame/utils/SpeechResultProcessor.java
UTF-8
2,141
3.03125
3
[]
no_license
package com.example.jmfedorov.countergame.utils; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by jmfedorov on 07.12.17. */ public class SpeechResultProcessor { public static final int NIL = 0; public static final int RED = 2; public static final int BLUE = 1; static final String RED_NAME = "красн"; static final String BLUE_NAME = "син"; static final String MINUS = "минус"; static final String PLUS = "плюс"; public static int getWho(String res) { res = res.toLowerCase(); String[] res_arr = res.split(" "); for (String word : res_arr) { if (word.startsWith(RED_NAME)) { return RED; } if (word.startsWith(BLUE_NAME)) { return BLUE; } } return NIL; } public static int getHowmany(String res) { res = res.toLowerCase(); String[] res_arr = res.split(" "); String recogniseRes = ""; int index = 0; boolean foundSign = false; for (int i = 0; i < res_arr.length; i++) { String word = res_arr[i]; if (word.startsWith(MINUS) || word.startsWith("-")) { recogniseRes += "-"; index = i; foundSign = true; break; } if (word.startsWith(PLUS) || word.startsWith("+")) { recogniseRes += "+"; index = i; foundSign = true; break; } } int intRes = 0; if (foundSign) { recogniseRes += res_arr[index + 1]; intRes = Integer.decode(recogniseRes); return intRes; } else { Pattern pat = Pattern.compile("[-]?[0-9]+(.[0-9]+)?"); Matcher matcher = pat.matcher(res); if (matcher.find(0)) { String value = res.substring(matcher.start(), matcher.end()); intRes = Integer.parseInt(value); return intRes; } return intRes; } } }
true
a3189f29a2167a2ab3b64777a5f108d4e663c86b
Java
Fernando-Mota/agendafeliz
/app/src/main/java/br/com/halph/agendafeliz/formulariocontatos/FormularioContatoFragment.java
UTF-8
3,336
2.109375
2
[]
no_license
package br.com.halph.agendafeliz.formulariocontatos; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.AnimationUtils; import android.widget.EditText; import android.widget.LinearLayout; import java.util.UUID; import javax.inject.Inject; import br.com.halph.agendafeliz.MainActivityContainer; import br.com.halph.agendafeliz.R; import br.com.halph.agendafeliz.UpdateActionBarTitleListener; import br.com.halph.agendafeliz.contatos.data.Contato; /** * Created by Android on 20/02/2017. */ public class FormularioContatoFragment extends Fragment implements FormularioContatoContract.View{ @Inject FormularioContatoContract.Presenter presenter; private EditText edtNomeContato; private EditText edtSexoContato; private FloatingActionButton button; private Context context; @Override public void onAttach(Context context) { super.onAttach(context); this.context = context; } @Override public void onResume() { super.onResume(); ((UpdateActionBarTitleListener) context).updateActionbarTitle(getString(R.string.form_contato_add_title)); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.formulario_contato_fragment, container, false); edtNomeContato = (EditText) view.findViewById(R.id.nome_contato); edtSexoContato = (EditText) view.findViewById(R.id.sexo_contato); button = (FloatingActionButton) view.findViewById(R.id.grava_contato); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { gravaContatoClick(v); } }); MainActivityContainer.getContatoComponent().inject(this); LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.form_contato_holder); View view1 = LayoutInflater.from(getActivity()).inflate(R.layout.item_telefone, null); linearLayout.addView(view1); ViewGroup parent = (ViewGroup) view1.getParent(); Log.d("FORM_HOLDER_ID", "ID_CARD_VIEW: " + (parent.getId() == R.id.form_contato_holder)); return view; } @Override public void gravaContatoClick(View view) { view.startAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.anim_click)); Contato contato = new Contato(); contato.setId(UUID.randomUUID().toString()); contato.setNome(edtNomeContato.getText().toString()); contato.setSexo(edtSexoContato.getText().toString()); presenter.gravaContato(contato); retornaParaLista(); } @Override public void retornaParaLista() { getActivity().onBackPressed(); } public void setPresenter(FormularioContatoContract.Presenter presenter) { this.presenter = presenter; } @Override public void onDetach() { super.onDetach(); this.context = null; } }
true
706a230e3b109cf29a847adf9985c5de0aecc3d3
Java
christiandeange/Marathon
/marathon/src/main/java/com/deange/marathonapp/billing/AdDelegate.java
UTF-8
1,081
2.359375
2
[ "Apache-2.0" ]
permissive
package com.deange.marathonapp.billing; import com.google.android.gms.ads.AdListener; public class AdDelegate<T> extends AdListener { private Listener<T> mListener; private T mToken; public AdDelegate(final Listener<T> listener, final T token) { mListener = listener; mToken = token; } public void onAdClosed() { mListener.onAdClosed(mToken); } public void onAdFailedToLoad(final int errorCode) { mListener.onAdFailedToLoad(mToken, errorCode); } public void onAdLeftApplication() { mListener.onAdLeftApplication(mToken); } public void onAdOpened() { mListener.onAdOpened(mToken); } public void onAdLoaded() { mListener.onAdLoaded(mToken); } public interface Listener<T> { public void onAdClosed(final T token); public void onAdFailedToLoad(final T token, final int errorCode); public void onAdLeftApplication(final T token); public void onAdOpened(final T token); public void onAdLoaded(final T token); } }
true
300c774954fed4581c357f9f390bf8bcdb1ec5ee
Java
LightAndLight/little-language-interpreter
/src/main/java/interpreter/Interpreter.java
UTF-8
803
3.21875
3
[]
no_license
package interpreter; import java.util.Scanner; public class Interpreter { public static void main(String[] args) { Lexer lexer = new Lexer(); Parser parser = new Parser(); Scanner scanner = new Scanner(System.in); String input; while (true) { System.out.print(">> "); input = scanner.nextLine(); if (input.equals(":q")) { break; } if (!input.isEmpty()) { try { SyntaxTree tree = parser.parseString(lexer.tokenize(input)); System.out.println(tree.eval()); } catch (InterpreterException e) { System.out.println("Error: " + e.toString()); } } } } }
true
34c2486433d11b89c1784e293496e2bd2293cd3b
Java
weant/Tools
/hcop-ptn/src/main/java/com/hcop/ptn/service/NeService.java
UTF-8
2,791
2.328125
2
[]
no_license
package com.hcop.ptn.service; import com.hcop.ptn.common.db.dao.NeDao; import com.hcop.ptn.common.enums.DummyNeType_PKT; import com.hcop.ptn.common.exception.ServiceException; import com.hcop.ptn.common.utils.CollectionUtils; import com.hcop.ptn.restful.model.NE; import com.hcop.ptn.restful.model.NECommunicationState; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.Collection; import java.util.Map; public class NeService { private Log log = LogFactory.getLog(NeService.class); private static NeService ourInstance = new NeService(); public static NeService getInstance() { return ourInstance; } private NeService() { } public Collection<NE> getAllNes() throws ServiceException { try { Collection<NE> nes = NeDao.getInstance().getNeWith(null, null, null); setAttributes(nes); return nes; } catch (Exception e) { log.error(e.getMessage(), e); throw new ServiceException(500, e.getMessage()); } } public Collection<NE> getNeById(String neId) throws ServiceException { try { if (neId.trim().length() < 1) { throw new ServiceException( 400, "Parameter Error: empty ne id"); } Collection<NE> nes = NeDao.getInstance().getNeWith(null, neId, null); setAttributes(nes); return nes; } catch (Exception e) { log.error(e.getMessage(), e); throw new ServiceException(500, e.getMessage()); } } public Collection<NE> getNeByName(String neName) throws ServiceException { try { if (neName.trim().length() < 1) { throw new ServiceException( 400, "Parameter Error: empty ne name"); } Collection<NE> nes = NeDao.getInstance().getNeWith(neName, null, null); setAttributes(nes); return nes; } catch (Exception e) { log.error(e.getMessage(), e); throw new ServiceException(500, e.getMessage()); } } private void setAttributes(Collection<NE> nes) throws ServiceException { if(CollectionUtils.isEmpty(nes)) { return; } try { Map<String,String> map = NeDao.getInstance().queryNeCommunicationSate(); for(NE ne : nes){ ne.setCommunicationState(NECommunicationState.fromValue(map.get(ne.getNeName()).toLowerCase())); ne.setNeType(DummyNeType_PKT.fromInt(Integer.parseInt(ne.getNeType())).toString()); } } catch (Exception e) { log.error(e.getMessage(), e); throw new ServiceException(500, e.getMessage()); } } }
true
7fd3f1dac5ef0a7f22b260d78e60afe218e7b752
Java
bruneeeem/FTSOLUTIONTICKET
/FT/src/main/java/br/com/ftsolution/model/Tickets.java
UTF-8
2,231
2.265625
2
[ "MIT" ]
permissive
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package br.com.ftsolution.model; import java.sql.Date; /** * * @author Bruno */ public class Tickets { private int id; private Date dataIngresso; private String titulo; private String descricao; private int status; private int analista; private Date dataAlteracao; private int usuario; public Tickets(){ } public Tickets(String titulo,String descricao,int status,int analista,Date dataAlteracao,int usuario){ this.titulo=titulo; this.descricao=descricao; this.status=status; this.analista=analista; this.dataAlteracao=dataAlteracao; this.usuario=usuario; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitulo() { return titulo; } public void setTitulo(String titulo) { this.titulo = titulo; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public int getAnalista() { return analista; } public void setAnalista(int analista) { this.analista = analista; } public Date getDataAlteracao() { return dataAlteracao; } public void setDataAlteracao(Date dataAlteracao) { this.dataAlteracao = dataAlteracao; } public Date getDataIngresso() { return dataIngresso; } public void setDataIngresso(Date dataIngresso) { this.dataIngresso = dataIngresso; } public int getUsuario() { return usuario; } public void setUsuario(int usuario) { this.usuario = usuario; } }
true
f88c44e9f56826414f249e128b65f4fa32a68866
Java
Rumenpakov/personal-spring-angular-project
/library-application/src/test/java/eu/deltasource/library/controllers/BookControllerTest.java
UTF-8
4,598
2.625
3
[]
no_license
package eu.deltasource.library.controllers; import eu.deltasource.library.entities.EBookInfo; import eu.deltasource.library.entities.PaperBookInfo; import eu.deltasource.library.exceptions.IllegalInputException; import eu.deltasource.library.repositories.BookRepository; import eu.deltasource.library.util.BookFactory; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; class BookControllerTest { private BookController bookController; @BeforeEach public void initialiseBookController() { bookController = new BookController(new BookRepository()); } @Test void shouldReturnCorrectCountOfPaperBooks() { //given PaperBookInfo paperBookInfoToAddToRepository = BookFactory.createPaperBookInfo(1); //when bookController.addNewPaperBook(paperBookInfoToAddToRepository); //then long expectedPaperBooksCount = 1; long actualPaperBooksCount = bookController.getPaperBooksCount(); assertEquals(expectedPaperBooksCount, actualPaperBooksCount); } @Test void shouldReturnCorrectCountOfEBooks() { //given EBookInfo eBookInfoToAddToRepository = BookFactory.createEBookInfo(); //when bookController.addNewEBook(eBookInfoToAddToRepository); //then long expectedEBooksCount = 1; long actualEBooksCount = bookController.getEBooksCount(); assertEquals(expectedEBooksCount, actualEBooksCount); } @Test void shouldSuccessfullyFindExistingPaperBook() { //given PaperBookInfo paperBookInfoToAddToRepository = BookFactory.createPaperBookInfo(1); String paperBookIsbn = paperBookInfoToAddToRepository.getIsbn(); bookController.addNewPaperBook(paperBookInfoToAddToRepository); //when Optional<PaperBookInfo> actualPaperBookFound = bookController.findPaperBookByIsbn(paperBookIsbn); //then assertTrue(actualPaperBookFound.isPresent()); } @Test void shouldSuccessfullyFindExistingEBook() { //given EBookInfo eBookInfoToAddToRepository = BookFactory.createEBookInfo(); String eBookIsbn = eBookInfoToAddToRepository.getIsbn(); bookController.addNewEBook(eBookInfoToAddToRepository); //when Optional<EBookInfo> actualEBookFound = bookController.findEBookByIsbn(eBookIsbn); //then assertTrue(actualEBookFound.isPresent()); } @Test void shouldThrowCorrectExceptionWhenAddNewPaperBookWithNullParameter() { //given //when Exception actualExceptionThrown = assertThrows(IllegalInputException.class, () -> bookController.addNewPaperBook(null)); //then String expectedExceptionMessage = "Paper book to add can not be null"; String actualExceptionMessage = actualExceptionThrown.getMessage(); assertTrue(actualExceptionMessage.contains(expectedExceptionMessage)); } @Test void shouldThrowCorrectExceptionWhenAddNewEBookWithNullParamter() { //given //when Exception actualExceptionThrown = assertThrows(IllegalInputException.class, () -> bookController.addNewEBook(null)); //then String expectedExceptionMessage = "E-book to add can not be null"; String actualExceptionMessage = actualExceptionThrown.getMessage(); assertTrue(actualExceptionMessage.contains(expectedExceptionMessage)); } @Test void shouldThrowCorrectExceptionWhenFindPaperBookByIsbnWithNullParameter() { //given //when Exception actualExceptionThrown = assertThrows(IllegalInputException.class, () -> bookController.findPaperBookByIsbn(null)); //then String expectedExceptionMessage = "Isbn to search paper book by can not be null or empty"; String actualExceptionMessage = actualExceptionThrown.getMessage(); assertTrue(actualExceptionMessage.contains(expectedExceptionMessage)); } @Test void shouldThrowCorrectExceptionOnNullWhenFindEBookByIsbnWithNullParameter() { //given //when Exception actualExceptionThrown = assertThrows(IllegalInputException.class, () -> bookController.findEBookByIsbn(null)); //then String expectedExceptionMessage = "Isbn to search e-book by can not be null or empty"; String actualExceptionMessage = actualExceptionThrown.getMessage(); assertTrue(actualExceptionMessage.contains(expectedExceptionMessage)); } }
true
c854074d90fa8097ee74a737653c1f9e841b4ce7
Java
zhouziwen/MY_DDW
/app/src/main/java/com/example/bbacr/ddw/home/view/ComputerFragment.java
UTF-8
827
1.945313
2
[]
no_license
package com.example.bbacr.ddw.home.view; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.bbacr.ddw.R; import com.example.bbacr.ddw.base.BaseFragment; /** * A simple {@link Fragment} subclass. * 电脑 */ public class ComputerFragment extends BaseFragment { public ComputerFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_computer, container, false); } @Override public void onClick(View v) { } }
true
5fc007bbb7c07a8d39fac0894056b8a0b2051e46
Java
abdul-wahid789/Hospital-Mangement-System
/src/main/DoctorPanelUpdate.java
UTF-8
38,562
2.15625
2
[]
no_license
/* * 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 main; import java.util.ArrayList; import java.util.List; import javax.swing.JOptionPane; /** * * @author Parvez */ public class DoctorPanelUpdate extends javax.swing.JFrame { int n = 0, c = 0; List<Doctor> list = new ArrayList<Doctor>(); /** * Creates new form DoctorPanel */ public DoctorPanelUpdate() { initComponents(); set(); } public void set(){ NumberRead num=new NumberRead(); n=num.read(); System.out.println(n); FileRead fw = new FileRead(); list=fw.fileReadDoctor(); name.setText(list.get(n).getName()); clear(); list = fw.fileReadDoctor(); jUsername.setText(list.get(n).getUsername()); jPassword.setText(list.get(n).getPassword()); jFullName.setText(list.get(n).getName()); jAge.setText(list.get(n).getAge()); jGenderCombo.setSelectedItem(list.get(n).getGender()); jAddress.setText(list.get(n).getAddress()); jMaritialCombo.setSelectedItem(list.get(n).getMaritial()); jPhoneNo.setText(list.get(n).getPhone()); jQualification.setText(list.get(n).getQualification()); jSpecialization.setText(list.get(n).getSpecialization()); jBloodGroupCombo.setSelectedItem(list.get(n).getBlood()); jJoinningDate.setText(list.get(n).getJoinningDate()); jLeavingDate.setText(list.get(n).getLeavingDate()); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jPanel4 = new javax.swing.JPanel(); jLabel8 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); name = new javax.swing.JTextField(); jLabel13 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jMaritialCombo = new javax.swing.JComboBox<>(); jLabel10 = new javax.swing.JLabel(); jAddress = new javax.swing.JTextField(); jLabel11 = new javax.swing.JLabel(); jJoinningDate = new javax.swing.JTextField(); jLabel12 = new javax.swing.JLabel(); jGenderCombo = new javax.swing.JComboBox<>(); jLabel14 = new javax.swing.JLabel(); jAge = new javax.swing.JTextField(); jLabel15 = new javax.swing.JLabel(); jLeavingDate = new javax.swing.JTextField(); jLabel16 = new javax.swing.JLabel(); jQualification = new javax.swing.JTextField(); jLabel17 = new javax.swing.JLabel(); jSpecialization = new javax.swing.JTextField(); jLabelblood = new javax.swing.JLabel(); jBloodGroupCombo = new javax.swing.JComboBox<>(); jLabel4 = new javax.swing.JLabel(); jFullName = new javax.swing.JTextField(); jPhoneNo = new javax.swing.JTextField(); jUpdateButton = new javax.swing.JButton(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jPassword = new javax.swing.JTextField(); jUsername = new javax.swing.JTextField(); jPanel12 = new javax.swing.JPanel(); add4 = new javax.swing.JLabel(); update3 = new javax.swing.JLabel(); jPanel11 = new javax.swing.JPanel(); add1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Hospital Management System"); jPanel1.setBackground(new java.awt.Color(255, 255, 255)); jPanel4.setBackground(new java.awt.Color(24, 44, 97)); jLabel8.setBackground(new java.awt.Color(0, 204, 204)); jLabel8.setFont(new java.awt.Font("Arial Black", 1, 36)); // NOI18N jLabel8.setForeground(new java.awt.Color(255, 255, 255)); jLabel8.setText("Update Doctor Details"); jLabel1.setBackground(new java.awt.Color(0, 204, 204)); jLabel1.setFont(new java.awt.Font("Arial Black", 1, 24)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/hms60.png"))); // NOI18N jLabel1.setText("HMS"); name.setEditable(false); name.setBackground(new java.awt.Color(24, 44, 97)); name.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N name.setForeground(new java.awt.Color(255, 255, 255)); name.setHorizontalAlignment(javax.swing.JTextField.RIGHT); name.setText("Abdul Wahid"); name.setBorder(null); name.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { nameActionPerformed(evt); } }); jLabel13.setFont(new java.awt.Font("Arial Black", 0, 14)); // NOI18N jLabel13.setForeground(new java.awt.Color(232, 65, 24)); jLabel13.setText("(Logout)"); jLabel13.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel13MouseClicked(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() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(148, 148, 148) .addComponent(jLabel8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 67, Short.MAX_VALUE) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(name, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel13, javax.swing.GroupLayout.Alignment.TRAILING)) .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) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel13)) .addComponent(jLabel8))) .addContainerGap()) ); jLabel3.setFont(new java.awt.Font("Segoe UI Semibold", 0, 24)); // NOI18N jLabel3.setText("Age"); jLabel9.setFont(new java.awt.Font("Segoe UI Semibold", 0, 24)); // NOI18N jLabel9.setText("Gender"); jMaritialCombo.setFont(new java.awt.Font("Segoe UI Semibold", 0, 14)); // NOI18N jMaritialCombo.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Select", "Marrired", "Unmarried" })); jLabel10.setFont(new java.awt.Font("Segoe UI Semibold", 0, 24)); // NOI18N jLabel10.setText("Address"); jAddress.setFont(new java.awt.Font("Segoe UI Semibold", 0, 18)); // NOI18N jLabel11.setFont(new java.awt.Font("Segoe UI Semibold", 0, 24)); // NOI18N jLabel11.setText("Marital status "); jJoinningDate.setFont(new java.awt.Font("Segoe UI Semibold", 0, 18)); // NOI18N jJoinningDate.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jJoinningDateActionPerformed(evt); } }); jLabel12.setFont(new java.awt.Font("Segoe UI Semibold", 0, 24)); // NOI18N jLabel12.setText("Joinning Date"); jGenderCombo.setFont(new java.awt.Font("Segoe UI Semibold", 0, 14)); // NOI18N jGenderCombo.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Select", "Male", "Female", "Other" })); jLabel14.setFont(new java.awt.Font("Segoe UI Semibold", 0, 24)); // NOI18N jLabel14.setText("Phone No."); jAge.setFont(new java.awt.Font("Segoe UI Semibold", 0, 18)); // NOI18N jLabel15.setFont(new java.awt.Font("Segoe UI Semibold", 0, 24)); // NOI18N jLabel15.setText("Leaving Date"); jLeavingDate.setFont(new java.awt.Font("Segoe UI Semibold", 0, 18)); // NOI18N jLeavingDate.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jLeavingDateActionPerformed(evt); } }); jLabel16.setFont(new java.awt.Font("Segoe UI Semibold", 0, 24)); // NOI18N jLabel16.setText("Qualifications"); jQualification.setFont(new java.awt.Font("Segoe UI Semibold", 0, 18)); // NOI18N jLabel17.setFont(new java.awt.Font("Segoe UI Semibold", 0, 24)); // NOI18N jLabel17.setText("Specialization"); jSpecialization.setFont(new java.awt.Font("Segoe UI Semibold", 0, 18)); // NOI18N jSpecialization.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jSpecializationActionPerformed(evt); } }); jLabelblood.setFont(new java.awt.Font("Segoe UI Semibold", 0, 24)); // NOI18N jLabelblood.setText("Blood Group"); jBloodGroupCombo.setFont(new java.awt.Font("Segoe UI Semibold", 0, 14)); // NOI18N jBloodGroupCombo.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Select", "A+", "A-", "B+", "B-", "AB+", "AB-" })); jLabel4.setFont(new java.awt.Font("Segoe UI Semibold", 0, 24)); // NOI18N jLabel4.setText("Full Name"); jFullName.setFont(new java.awt.Font("Segoe UI Semibold", 0, 18)); // NOI18N jPhoneNo.setFont(new java.awt.Font("Segoe UI Semibold", 0, 18)); // NOI18N jPhoneNo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jPhoneNoActionPerformed(evt); } }); jUpdateButton.setBackground(new java.awt.Color(6, 82, 221)); jUpdateButton.setFont(new java.awt.Font("Arial Black", 1, 18)); // NOI18N jUpdateButton.setForeground(new java.awt.Color(255, 255, 255)); jUpdateButton.setText("Update"); jUpdateButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jUpdateButtonActionPerformed(evt); } }); jLabel5.setFont(new java.awt.Font("Segoe UI Semibold", 0, 24)); // NOI18N jLabel5.setText("Username"); jLabel6.setFont(new java.awt.Font("Segoe UI Semibold", 0, 24)); // NOI18N jLabel6.setText("Password"); jPassword.setFont(new java.awt.Font("Segoe UI Semibold", 0, 18)); // NOI18N jUsername.setFont(new java.awt.Font("Segoe UI Semibold", 0, 18)); // NOI18N jPanel12.setBackground(new java.awt.Color(24, 44, 97)); add4.setBackground(new java.awt.Color(0, 204, 204)); add4.setFont(new java.awt.Font("Arial Black", 1, 18)); // NOI18N add4.setForeground(new java.awt.Color(255, 255, 255)); add4.setText("Appointment"); add4.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { add4addMouseClicked(evt); } }); update3.setBackground(new java.awt.Color(0, 204, 204)); update3.setFont(new java.awt.Font("Arial Black", 1, 18)); // NOI18N update3.setForeground(new java.awt.Color(255, 255, 255)); update3.setText("Edit Profile"); update3.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { update3updateMouseClicked(evt); } }); jPanel11.setBackground(new java.awt.Color(255, 255, 255)); javax.swing.GroupLayout jPanel11Layout = new javax.swing.GroupLayout(jPanel11); jPanel11.setLayout(jPanel11Layout); jPanel11Layout.setHorizontalGroup( jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); jPanel11Layout.setVerticalGroup( jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 8, Short.MAX_VALUE) ); add1.setBackground(new java.awt.Color(0, 204, 204)); add1.setFont(new java.awt.Font("Arial Black", 1, 18)); // NOI18N add1.setForeground(new java.awt.Color(255, 255, 255)); add1.setText("List"); add1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { add1MouseClicked(evt); } }); javax.swing.GroupLayout jPanel12Layout = new javax.swing.GroupLayout(jPanel12); jPanel12.setLayout(jPanel12Layout); jPanel12Layout.setHorizontalGroup( jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel12Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel12Layout.createSequentialGroup() .addComponent(add4) .addContainerGap(20, Short.MAX_VALUE)) .addGroup(jPanel12Layout.createSequentialGroup() .addComponent(add1) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(jPanel12Layout.createSequentialGroup() .addComponent(update3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addComponent(jPanel11, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jPanel12Layout.setVerticalGroup( jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel12Layout.createSequentialGroup() .addGap(77, 77, 77) .addComponent(add4) .addGap(2, 2, 2) .addComponent(add1) .addGap(18, 18, 18) .addComponent(update3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(481, Short.MAX_VALUE)) ); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( 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(jPanel12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(29, 29, 29) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel17) .addComponent(jLabelblood)) .addGap(31, 31, 31) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jBloodGroupCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jUpdateButton, javax.swing.GroupLayout.PREFERRED_SIZE, 194, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jSpecialization, javax.swing.GroupLayout.PREFERRED_SIZE, 320, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)))) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel4) .addGap(70, 70, 70) .addComponent(jFullName, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel3) .addGap(137, 137, 137) .addComponent(jAge, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel9) .addGap(100, 100, 100) .addComponent(jGenderCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel10) .addGap(94, 94, 94) .addComponent(jAddress, javax.swing.GroupLayout.PREFERRED_SIZE, 483, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel11) .addGap(21, 21, 21) .addComponent(jMaritialCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel14) .addGap(66, 66, 66) .addComponent(jPhoneNo, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel16) .addGap(32, 32, 32) .addComponent(jQualification, javax.swing.GroupLayout.PREFERRED_SIZE, 320, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel5) .addGap(70, 70, 70) .addComponent(jUsername, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(52, 52, 52) .addComponent(jLabel12)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel6) .addGap(78, 78, 78) .addComponent(jPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(60, 60, 60) .addComponent(jLabel15))) .addGap(15, 15, 15) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLeavingDate, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jJoinningDate, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel12) .addComponent(jJoinningDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(10, 10, 10) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5) .addComponent(jUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(8, 8, 8) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel15) .addComponent(jLeavingDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(10, 10, 10) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel6) .addComponent(jPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(28, 28, 28) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addComponent(jFullName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(jAge, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel9) .addComponent(jGenderCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel10) .addComponent(jAddress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel11) .addComponent(jMaritialCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel14) .addComponent(jPhoneNo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(28, 28, 28) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel16) .addComponent(jQualification, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel17) .addGap(28, 28, 28) .addComponent(jLabelblood)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(jSpecialization, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(4, 4, 4) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jBloodGroupCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jUpdateButton, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jPanel12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 738, javax.swing.GroupLayout.PREFERRED_SIZE) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void jJoinningDateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jJoinningDateActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jJoinningDateActionPerformed private void jLeavingDateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jLeavingDateActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jLeavingDateActionPerformed private void jSpecializationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jSpecializationActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jSpecializationActionPerformed private void jPhoneNoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jPhoneNoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jPhoneNoActionPerformed private void jLabel13MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel13MouseClicked LoginAsFrame al = new LoginAsFrame(); al.setVisible(true); this.dispose(); }//GEN-LAST:event_jLabel13MouseClicked private void nameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nameActionPerformed // TODO add your handling code here: }//GEN-LAST:event_nameActionPerformed private void jUpdateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jUpdateButtonActionPerformed if (jUsername.getText().isEmpty() || jPassword.getText().isEmpty() || jFullName.getText().isEmpty() || jAge.getText().isEmpty() || jGenderCombo.getSelectedItem().toString().equalsIgnoreCase("select") || jAddress.getText().isEmpty() || jMaritialCombo.getSelectedItem().toString().equalsIgnoreCase("select") || jPhoneNo.getText().isEmpty() || jQualification.getText().isEmpty() || jLeavingDate.getText().isEmpty() || jJoinningDate.getText().isEmpty() || jBloodGroupCombo.getSelectedItem().toString().equalsIgnoreCase("select")) { JOptionPane.showMessageDialog(null, "Data Field is Empty", "ERROR", JOptionPane.WARNING_MESSAGE); } else { String username = jUsername.getText(); String password = jPassword.getText(); String name = jFullName.getText(); String age = jAge.getText(); String gender = jGenderCombo.getSelectedItem().toString(); String address = jAddress.getText(); String maritial = jMaritialCombo.getSelectedItem().toString(); String phone = jPhoneNo.getText(); String qualification = jQualification.getText(); String specialization = jSpecialization.getText(); String blood = jBloodGroupCombo.getSelectedItem().toString(); String joinDate = jJoinningDate.getText(); String leaveDate = jLeavingDate.getText(); Doctor dw = new Doctor(qualification, specialization, joinDate, leaveDate, name, age, gender, address, maritial, phone, blood, username, password); list.set(n, dw); FileUpdate fu=new FileUpdate(); fu.fileUpdateDoctor(n, dw); JOptionPane.showMessageDialog(null, "Updated Successfully", "Success", JOptionPane.WARNING_MESSAGE); clear(); } }//GEN-LAST:event_jUpdateButtonActionPerformed private void add4addMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_add4addMouseClicked DoctorPanelAppointment pa=new DoctorPanelAppointment(); pa.setVisible(true); this.dispose(); }//GEN-LAST:event_add4addMouseClicked private void update3updateMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_update3updateMouseClicked }//GEN-LAST:event_update3updateMouseClicked private void add1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_add1MouseClicked // TODO add your handling code here: }//GEN-LAST:event_add1MouseClicked public void clear() { jUsername.setText(""); jPassword.setText(""); jFullName.setText(""); jAge.setText(""); jGenderCombo.setSelectedItem("Select"); jAddress.setText(""); jMaritialCombo.setSelectedItem("Select"); jPhoneNo.setText(""); jQualification.setText(""); jSpecialization.setText(""); jBloodGroupCombo.setSelectedItem("Select"); jJoinningDate.setText(""); jLeavingDate.setText(""); } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(DoctorPanelUpdate.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(DoctorPanelUpdate.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(DoctorPanelUpdate.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(DoctorPanelUpdate.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new DoctorPanelUpdate().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel add1; private javax.swing.JLabel add4; private javax.swing.JTextField jAddress; private javax.swing.JTextField jAge; private javax.swing.JComboBox<String> jBloodGroupCombo; private javax.swing.JTextField jFullName; private javax.swing.JComboBox<String> jGenderCombo; private javax.swing.JTextField jJoinningDate; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel17; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JLabel jLabelblood; private javax.swing.JTextField jLeavingDate; private javax.swing.JComboBox<String> jMaritialCombo; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel11; private javax.swing.JPanel jPanel12; private javax.swing.JPanel jPanel4; private javax.swing.JTextField jPassword; private javax.swing.JTextField jPhoneNo; private javax.swing.JTextField jQualification; private javax.swing.JTextField jSpecialization; private javax.swing.JButton jUpdateButton; private javax.swing.JTextField jUsername; private javax.swing.JTextField name; private javax.swing.JLabel update3; // End of variables declaration//GEN-END:variables }
true
9097fcee01d7273e9508f3094976441dbf1e2c89
Java
ftcaicai/KaPai
/CodeProject/Server/ProjectCardServer/src/com/phoenixli/common/messageQueue/ServerMessageQueue.java
UTF-8
521
2.09375
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.phoenixli.common.messageQueue; import com.phoenixli.common.message.serverMessage.Message; import java.util.concurrent.LinkedTransferQueue; /** * * @author phoenix */ public class ServerMessageQueue { private static final LinkedTransferQueue<Message> messageQueue = new LinkedTransferQueue<Message>(); public static LinkedTransferQueue<Message> queue() { return messageQueue; } }
true
59a3c43abaa1cb4c115981560d15b5ee5b2a17d9
Java
qgzang/CompressionParser
/src/main/java/CompressionParser.java
UTF-8
6,155
2.46875
2
[]
no_license
import java.io.*; import java.util.List; /** * @author Sheng Li * Created on 14/12/8. */ public class CompressionParser { public CompressionPipe pipe; public CompressionDecoder decoder; public Parameters para; public int numIters; public int k_best; public String trainForest; private String modelName; private String predictedFile; public double rate; public boolean useRateDecoder; public CompressionParser(Options op, CompressionPipe p) { pipe = p; decoder = new CompressionDecoder(); para = new Parameters(pipe.dataAlphabet.size()); numIters = op.numIters; k_best = op.k_best; trainForest = op.trainForest; modelName = op.modelFile; predictedFile = op.predictedFile; rate = op.compression_rate; useRateDecoder = op.useRateDecoder; } public void train(List<CompressionInstance> instanceList) throws IOException { System.out.println("About Train"); System.out.println("Num of Features:" + pipe.dataAlphabet.size()); for (int i = 0; i < numIters; i++){ System.out.println("========================="); System.out.println("========Iteration:\t" + i); long start = System.currentTimeMillis(); trainIter(instanceList, trainForest, i+1); long end = System.currentTimeMillis(); System.out.printf("Training one Iteration took:%.4fs\n", (end - start) / 1000.0); } para.averageParameters(numIters * instanceList.size()); } private void trainIter(List<CompressionInstance> instanceList, String trainForest, int iter) throws IOException { ObjectInputStream in = new ObjectInputStream(new FileInputStream(trainForest)); for (int i = 0; i < instanceList.size(); i++) { if ((i+1) % 100 == 0) System.out.printf("Processed %d Instances\n", i+1); CompressionInstance instance = instanceList.get(i); int size = instance.size(); FeatureVector[][] feat_edge = new FeatureVector[size][size]; double[][] score_edge = new double[size][size]; pipe.getFeatureVector(in, instance, feat_edge, score_edge, para); double upd = instanceList.size() * numIters - (instanceList.size()* (iter - 1) + (i+1)) + 1; Object[][] d; if (useRateDecoder) { d = decoder.dynamic_search(instance, feat_edge, score_edge, k_best, rate); } else { d = decoder.dynamic_search(instance, feat_edge, score_edge, k_best); } para.updateParametersMIRA(instance, d, upd); } in.close(); System.out.printf("All %d Instances\n", instanceList.size()); } public void parse(List<CompressionInstance> instanceList, String outputFile) throws IOException { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8")); for (int i = 0; i < instanceList.size(); i++) { System.err.println(i); CompressionInstance instance = instanceList.get(i); int size = instance.size(); FeatureVector[][] feat_edge = new FeatureVector[size][size]; double[][] score_edge = new double[size][size]; pipe.getFeatureVector(instance, feat_edge, score_edge, para); Object[][] d; if (useRateDecoder) { d = decoder.dynamic_search(instance, feat_edge, score_edge, k_best, rate); } else { d = decoder.dynamic_search(instance, feat_edge, score_edge, k_best); } bw.write(getOutputString(instance, (List<Integer>) d[0][1])); bw.newLine(); } bw.close(); } private String getOutputString(CompressionInstance instance, List<Integer> parse){ //System.out.println(parse); String res = ""; for (int i = 1; i < parse.size() - 1; i++) { res += instance.words[parse.get(i)] + " "; } return res; } public void saveModel(String modelName) throws IOException{ ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(modelName)); out.writeObject(para.parameters); out.writeObject(pipe.dataAlphabet); out.close(); } public void loadModel(String modelName) throws IOException, ClassNotFoundException { ObjectInputStream in = new ObjectInputStream(new FileInputStream(modelName)); para.parameters = (double[])in.readObject(); pipe.dataAlphabet = (Alphabet)in.readObject(); in.close(); pipe.closeAlphabets(); } public static void main(String[] args) throws IOException, ClassNotFoundException { Options op = new Options(); op.processArguments(args); op.printOptions(); if (op.train){ CompressionPipe pipe = new CompressionPipe(); List<CompressionInstance> instanceList = pipe.createInstances(op.trainFile, op.trainParsedFile, op.trainForest); CompressionParser parser = new CompressionParser(op, pipe); pipe.closeAlphabets(); System.out.println("=============Start Training============"); parser.train(instanceList); System.out.println("==============Save Model==============="); parser.saveModel(parser.modelName); System.out.println("==============Done!===================="); } else if (op.test){ System.out.println("=============Loading Model============="); CompressionPipe pipe = new CompressionPipe(); CompressionParser parser = new CompressionParser(op, pipe); parser.loadModel(parser.modelName); List<CompressionInstance> instanceList = CompressionReader.read(op.testFile, true, false); //DependencyReader.read(op.testParsedFile, instanceList); parser.parse(instanceList, parser.predictedFile); System.out.println("============Parsed Done!==============="); } } }
true
e3d4296bd5c6e9a7aeda719c944176083cbe3667
Java
bellmit/yuyingzhijia
/src/main/java/javacommon/util/excel/ExcelUtils.java
UTF-8
5,019
2.84375
3
[]
no_license
package javacommon.util.excel; import java.io.IOException; import java.io.OutputStream; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Vector; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFDateUtil; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; /** * Excel工具类 。 * * @author wangzg * */ public class ExcelUtils { /** * 小数点后面 # 的个数代表转换模式后支持的小数位数 */ private static final String NUMBERFORMAT_DECIMAL = "#.####"; /** * 拿到单元格中的值 。 * * @param objCell * @return */ public static String getExcelCellData(HSSFCell objCell) { String strValue; if (objCell == null) { return ""; } switch (objCell.getCellType()) { case HSSFCell.CELL_TYPE_NUMERIC: // 0 { // 日期型 if (HSSFDateUtil.isCellDateFormatted(objCell)) { strValue = new SimpleDateFormat("yyyy-MM-dd").format(objCell.getDateCellValue()); } else { strValue = new DecimalFormat(NUMBERFORMAT_DECIMAL).format(objCell.getNumericCellValue()); } break; } case HSSFCell.CELL_TYPE_STRING: // 1 strValue = objCell.getRichStringCellValue().toString().replaceAll("'", "''"); break; case HSSFCell.CELL_TYPE_FORMULA: // 2 strValue = String.valueOf(objCell.getNumericCellValue()); break; case HSSFCell.CELL_TYPE_BLANK: // 3 strValue = objCell.getRichStringCellValue().toString(); break; case HSSFCell.CELL_TYPE_BOOLEAN: // 4 strValue = String.valueOf(objCell.getBooleanCellValue()); break; case HSSFCell.CELL_TYPE_ERROR: // 5 strValue = String.valueOf(objCell.getErrorCellValue()); break; default: strValue = ""; } // 去掉空格换行等 strValue = strValue.replaceAll(" ", "").replaceAll(" ", "").replaceAll("\n", "").replaceAll("\t", "").replaceAll("\r", "").replaceAll("\b", "").replaceAll("'", "").replaceAll("‘", ""); // 返回结果 return strValue; } /** * 判断Excel行是否为空。 * @param objDataRow * @return */ public static boolean isBlankRow(HSSFRow objDataRow) { boolean bResult = true; if (objDataRow == null) { return true; } for (int i = objDataRow.getFirstCellNum(); i < objDataRow.getLastCellNum(); i++) { HSSFCell objCell = objDataRow.getCell(i, HSSFRow.RETURN_BLANK_AS_NULL); String strValue = ""; if (objCell != null) { strValue = getExcelCellData(objCell); if (!strValue.trim().equals("")) { bResult = false; break; } } } return bResult; } /** * 复制excel行数据。 * @param objHSSFSheetWrong * @param nFaileSum 新建行号 * @param objDataRow 被复制行 * @param nTotalColumn 列数 */ public static void copyRow(HSSFSheet objHSSFSheetWrong, int nFaileSum, HSSFRow objDataRow, int nTotalColumn) { HSSFRow objHSSFRowAdd = objHSSFSheetWrong.createRow(nFaileSum); for (int i = 0; i < nTotalColumn; i++) { HSSFCell objCell = objHSSFRowAdd.createCell(i); objCell.setCellValue(ExcelUtils.getExcelCellData(objDataRow.getCell(i))); } } public static void getExcel(Vector<Vector<String>> vector, String[] fieldName, String sheetName, OutputStream output) { HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet(sheetName); HSSFRow row = sheet.createRow(0); for (int i = 0; i < fieldName.length; i++) { HSSFCell cell = row.createCell(i); cell.setCellType(1); cell.setCellValue(fieldName[i]); } for (int i = 0; i < vector.size(); i++) { row = sheet.createRow(i + 1); Vector v = (Vector)vector.get(i); for (int j = 0; j < v.size(); j++) { HSSFCell cell = row.createCell(j); cell.setCellType(1); cell.setCellValue((String)v.get(j)); } } try { output.flush(); workbook.write(output); } catch (IOException e) { e.printStackTrace(); System.out.println("Output is closed"); } } }
true
f24f23c153cffe3f0e80fe2afb68fb25a479cf79
Java
joao-lucas/Java-OO
/aulaOO20150908/src/aulaOO20150908/Teste.java
UTF-8
268
2.59375
3
[]
no_license
package aulaOO20150908; public class Teste { public static void main(String[] args) { Recipente r = new Recipente(); r.quantidade = 120; r.armazenar(100); System.out.println(r.quantidade); System.out.println("Quantidade: " + r.ObterQuantida()); } }
true
3b755713c068dfc38f9af39f126fbd06665c8106
Java
cjorellana/ApiA2
/app/src/main/java/gt/vidal/albacinema/PeliculaFragment.java
UTF-8
9,961
1.773438
2
[]
no_license
package gt.vidal.albacinema; import android.content.Context; import android.graphics.Bitmap; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.ScrollView; import android.widget.Spinner; import android.widget.TextView; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import java.net.URLEncoder; import java.util.ArrayList; import info.hoang8f.android.segmented.SegmentedGroup; /** * Created by alejandroalvarado on 16/09/16. */ public class PeliculaFragment extends BaseFragment { public JsonObject pelicula; public String fecha; public String cineNombre = ""; public int cineId; private View view; private TabLayout tabLayout; private TextView txtHeader; private ListView lstHorarios; private ScrollView scrSinopsis; public boolean bistro; private ArrayList<String> fechas = new ArrayList<>(); public boolean estreno; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_pelicula, container, false); tabLayout = (TabLayout) view.findViewById(R.id.tabLayout); txtHeader = (TextView) view.findViewById(R.id.txtHeader); lstHorarios = (ListView) view.findViewById(R.id.lstHorarios); scrSinopsis = (ScrollView) view.findViewById(R.id.scrSinopsis); txtHeader.setText("Horarios " + cineNombre); //setRetainInstance(true); return view; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); llenarHeader(); if (estreno) { scrSinopsis.setVisibility(View.VISIBLE); lstHorarios.setVisibility(View.GONE); tabLayout.setVisibility(View.GONE); txtHeader.setText("Sinopsis"); return; } setupTabs(); if (fecha != null) { fetchHorarios(); } else { this.estreno = true; fetchFechas(); } } private void fetchFechas() { StringBuilder path = new StringBuilder("/peliculas/filtrarFechas?idcine="); path.append(cineId); path.append("&pelicula="); path.append(URLEncoder.encode(pelicula.get("Name").getAsString())); new BackgroundTask<JsonElement>(() -> Api.instance.getJson(path.toString()), (json, exception) -> { if (exception != null) {throw new RuntimeException(exception);} if (json != null) { for (JsonElement f : json.getAsJsonArray()) { fechas.add(f.getAsJsonObject().get("fecha").getAsString()); } llenarFechas(); fetchHorarios(); } }).execute(); } private void llenarFechas() { getBaseActivity().getSupportActionBar().setDisplayShowCustomEnabled(true); LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View vi = inflater.inflate(R.layout.spinner_toolbar, null); Spinner spinnerFechas = (Spinner) vi.findViewById(R.id.spin); ArrayAdapter<String> spinneradapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_dropdown_item_1line, fechas); spinnerFechas.setAdapter(spinneradapter); getBaseActivity().getSupportActionBar().setCustomView(vi); spinneradapter.notifyDataSetChanged(); spinnerFechas.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { fecha = fechas.get(position); fetchHorarios(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } private void fetchHorarios() { String peliId = URLEncoder.encode(pelicula.get("Name").getAsString()); StringBuilder path = new StringBuilder("/peliculas/xhorario2/"); path.append(cineId + "/"); path.append(peliId); path.append("?fecha="); path.append(fecha); path.append(bistro ? "&bistro=1" : ""); Log.d("meow", path.toString()); new BackgroundTask<JsonArray>(() -> Api.instance.getJson(path.toString()).getAsJsonArray(), (arr, e) -> { if (e != null) throw new RuntimeException(e); if (arr != null) onHorariosFetched(arr); }).execute(); } private void onHorariosFetched(JsonArray arr) { lstHorarios.setAdapter(new HorariosAdapter(arr)); } private void llenarHeader() { ((TextView) view.findViewById(R.id.txtTitulo)).setText(pelicula.get("Name").getAsString()); ((TextView) view.findViewById(R.id.txtDuracion)).setText("Duración: " + pelicula.get("Duracion").getAsString() + " minutos"); ((TextView) view.findViewById(R.id.txtGenero)).setText("Género: " + Utils.firstCaptial(pelicula.get("Genero").getAsString())); ((TextView) view.findViewById(R.id.txtRating)).setText("Clasificación: " + pelicula.get("Rating").getAsString()); ((TextView) view.findViewById(R.id.txtSinopsis)).setText(pelicula.get("Sinopsis").getAsString()); String imgurl = pelicula.get("Url").getAsString(); new BackgroundTask<Bitmap>(() -> Images.get(imgurl), (b, e) -> { if (e != null) throw new RuntimeException(e); ((ImageView)view.findViewById(R.id.imgPelicula)).setImageBitmap(b); }).execute(); } @Override public String getTitle() { return fecha == null ? "" : "Horarios"; } private void setupTabs() { tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { if (tab.getText().equals("Sinopsis")) { txtHeader.setText("Sinopsis"); scrSinopsis.setVisibility(View.VISIBLE); lstHorarios.setVisibility(View.GONE); } else { txtHeader.setText("Horarios " + cineNombre); lstHorarios.setVisibility(View.VISIBLE); scrSinopsis.setVisibility(View.GONE); } } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); } class HorariosAdapter extends BaseAdapter { private final JsonArray data; HorariosAdapter(JsonArray data) { this.data = data; } @Override public int getCount() { return data.size(); } @Override public Object getItem(int position) { return data.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; LayoutInflater inflater = getBaseActivity().getLayoutInflater(); if(v == null) { v = inflater.inflate(R.layout.row_horario, parent, false); } JsonObject horario = ((JsonElement) getItem(position)).getAsJsonObject(); ((TextView)v.findViewById(R.id.txtSala)).setText(horario.get("Sala").getAsString()); ((TextView)v.findViewById(R.id.txtAtributos)) .setText(horario.get("Attributes").getAsString().replace(";", " | ")); SegmentedGroup sg = (SegmentedGroup) v.findViewById(R.id.sgmHoras); int i = 0; for (JsonElement h: horario.get("Horas").getAsJsonArray()) { RadioButton button = (RadioButton) inflater.inflate(R.layout.segment, null); String hora = h.getAsJsonObject().get("hora").getAsString(); hora = hora.substring(0, hora.lastIndexOf(":")); button.setText(hora); sg.addView(button); sg.updateBackground(); final int horarioIndex = i++; button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { BoletosFragment f = new BoletosFragment(); f.pelicula = pelicula; f.fecha = fecha; f.cineId = cineId; f.cineNombre = cineNombre; f.horario = horario; f.horarioSeleccionado = horarioIndex; getBaseActivity().changeFragment(f); } }); } return v; } } }
true
848a403697e29ee933dd6e1a58fd4db4f5775eab
Java
W-David/JianHan
/app/src/main/java/com/example/jianhan/di/component/QueryComponent.java
UTF-8
493
1.789063
2
[]
no_license
package com.example.jianhan.di.component; import com.example.jianhan.di.module.ActivityModule; import com.example.jianhan.di.module.QueryModule; import com.example.jianhan.di.scope.PreActivity; import com.example.jianhan.ui.activity.QueryActivity; import dagger.Component; @PreActivity @Component(dependencies = ApplicationComponent.class,modules = {ActivityModule.class, QueryModule.class}) public interface QueryComponent { void inject(QueryActivity queryActivity); }
true
a423c7ee4836d1a41a7583c6217a11671bb66b23
Java
radamp11/TheBomberman
/src/bmbremaster/tiles/players/Player.java
UTF-8
3,387
2.765625
3
[]
no_license
package bmbremaster.tiles.players; import java.awt.Graphics; import bmbremaster.graphics.Assets; import bmbremaster.server.Handler; import bmbremaster.server.Msg; import bmbremaster.tiles.Tiles; import bmbremaster.tiles.blocks.Bomb; public class Player extends Tiles{ public static final int PLAYER_SIZE_X = 56; public static final int PLAYER_SIZE_Y = 56; public static final int DEFAULT_HEALTH = 100; public static final int DEFAULT_SPEED = 8; private int id; private int health; private int speed; private int bombTime; private int speedX = 0, speedY = 0; private boolean direction; //left - false; right - true public Player(int x, int y, int id ) { super(x, y, PLAYER_SIZE_X, PLAYER_SIZE_Y); health = DEFAULT_HEALTH; this.id = id; speed = DEFAULT_SPEED; this.direction = true; } public void tick( Msg keys, Handler handler ) { if(keys.a) { speedX = -speed; if(keys.d) speedX = 0; if(speedY != 0) speedX = 0; x += speedX; x = clamp(x, 10 + Tiles.TILE_SIZE, 800 - Tiles.TILE_SIZE*2 - 10); direction = false; } if(keys.d) { speedX = speed; if(keys.a) speedX = 0; else if(speedY != 0) speedX = 0; x += speedX; x = clamp(x, 10 + Tiles.TILE_SIZE, 800 - Tiles.TILE_SIZE*2 - 10); direction = true; } if(keys.w) { speedY = -speed; if(keys.s) speedY = 0; if(speedX != 0) speedY = 0; y += speedY; y = clamp(y, 10 + Tiles.TILE_SIZE, 800 - Tiles.TILE_SIZE*2 - 10); direction = true; } if(keys.s) { speedY = speed; if(keys.w) speedY = 0; if(speedX != 0) speedY = 0; y += speedY; y = clamp(y, 10 + Tiles.TILE_SIZE, 800 - Tiles.TILE_SIZE*2 - 10); direction = false; } if(!keys.a && !keys.d) speedX = 0; if(!keys.w && !keys.s) speedY = 0; if(keys.space && bombTime <= 0) { bombTime = 120; Bomb newBomb = new Bomb((int) ( Math.round((float) this.x / (float) Tiles.TILE_SIZE)) * Tiles.TILE_SIZE + 10, (int) ( Math.round((float) this.y / (float) Tiles.TILE_SIZE)) * Tiles.TILE_SIZE + 10, Tiles.TILE_SIZE, Tiles.TILE_SIZE); newBomb.setOwner(this.id); handler.addBomb(newBomb); } --bombTime; } @Override public void tick(Tiles tile) {} @Override public void render(Graphics g) { if( id == 0 )//&& health > 0 ) { if( direction ) g.drawImage( Assets.player1, x, y, PLAYER_SIZE_X, PLAYER_SIZE_Y, null); //g.drawImage(Assets.player1, x, y, PLAYER_SIZE_X, PLAYER_SIZE_Y, null ); else g.drawImage(Assets.player1left, x, y, PLAYER_SIZE_X, PLAYER_SIZE_Y, null ); else if ( id == 1 ) //&& health > 0) { if( direction ) g.drawImage(Assets.player2, x, y, PLAYER_SIZE_X, PLAYER_SIZE_Y, null ); else g.drawImage(Assets.player2left, x, y, PLAYER_SIZE_X, PLAYER_SIZE_Y, null ); } public boolean getDirection() { return direction; } public void setDirection(boolean direction) { this.direction = direction; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getHealth() { return health; } public void setHealth(int health) { this.health = health; } @Override public void onCollision(Player player) { } public int getSpeed() { return speed; } public void setSpeed(int speed) { this.speed = speed; } public int getSpeedX() { return speedX; } public int getSpeedY() { return speedY; } }
true
2b75c61139999f681adbd1e5486cae04792d3bed
Java
borysenkox/JavaEE_Hillel_IT-School
/maven task/module-domain/src/main/java/com/hillel/Domain.java
UTF-8
561
2.875
3
[]
no_license
package com.hillel; import com.hillel.entity.Car; import com.hillel.entity.Employee; public class Domain { public static void main(String[] args) { Employee employee = new Employee(); employee.setId(1); employee.setFirstName("Sergey"); employee.setLastName("Borysenko"); Car car = new Car(); car.setManufacture("Tesla"); car.setModel("Model X"); car.setYearOfManufacture(2019); car.setTopSpeed(210); System.out.println(employee); System.out.println(car); } }
true
775aa6b2ed592fb30e368974fdfce143eb78afae
Java
d1m0s23/VimeWorld-src
/net/xtrafrancyz/mods/pvp/PvPMod.java
UTF-8
1,083
1.976563
2
[ "WTFPL" ]
permissive
package net.xtrafrancyz.mods.pvp; import net.minecraft.client.Minecraft; import net.xtrafrancyz.mods.pvp.gui.TEffectHudElement; import net.xtrafrancyz.mods.texteria.Texteria; import net.xtrafrancyz.mods.texteria.gui.GuiElementWrapper; import net.xtrafrancyz.mods.texteria.gui.TexteriaGui; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class PvPMod { public static final PvPMod instance = new PvPMod(); public static final Logger log = LogManager.getLogger("PvPMod"); public void init(Minecraft mc) { PvpOptions.load(mc); TEffectHudElement.applyOptions(); } public static void addOrRemove(GuiElementWrapper wrapper, boolean add) { TexteriaGui texteriagui = Texteria.instance.gui; if (add) { if (texteriagui.getElement(wrapper.element.id) == null) { texteriagui.addPersistentElement(wrapper); } } else { texteriagui.removePersistentElement(wrapper.element.id); } } }
true
2b6a780900526a6abb5b119654669bfdbc1ae9ce
Java
eloircorona/java-clustering
/src/clustering/algorithm/Cluster.java
UTF-8
1,226
3.421875
3
[]
no_license
package clustering.algorithm; import java.util.ArrayList; /** * Cluster */ public class Cluster { private int index = 0; private Centroid centroid; private ArrayList< Datapoint > points; public Cluster(int index) { setIndex(index); points = new ArrayList<>(); } public void setIndex(int index) { this.index = ( index >= 0 ) ? index : 0; } public void setCentroid(Centroid centroid) { this.centroid = centroid; } public void setPoints(ArrayList< Datapoint > points) { this.points = points; } public int getIndex() { return index; } public Centroid getCentroid() { return centroid; } public ArrayList< Datapoint > getPoints() { return points; } public void addPoint(Datapoint point) { points.add(point); point.setCluster(index); } public void clearCluster() { points.clear(); } public String toString() { return "-----\nCluster " + getIndex() + "\nCentroide (" + centroid.getX() + "," + centroid.getY() + ")"; } public String pointsToString() { String toReturn = "Puntos:"; for(Point p : points) toReturn += "\n(" + p.getX() + "," + p.getY() + ")"; return toReturn; } }
true
c92d8b97f804c2c5360ef655a0214d34fe23001e
Java
andre-geraldes/DSS-Trabalho
/src/Painel_Candidatura/Remover_Consultar_Candidatura.java
UTF-8
6,979
2.140625
2
[]
no_license
/* * 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 Painel_Candidatura; import javax.swing.JOptionPane; /** * * @author Tiago Cunha */ public class Remover_Consultar_Candidatura extends javax.swing.JPanel { /** * Creates new form Remover_Consutlar_Candidatura */ public Remover_Consultar_Candidatura() { initComponents(); this.setVisible(true); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel25 = new javax.swing.JLabel(); Dia_Submissao = new javax.swing.JFormattedTextField(); Mes_Submissao = new javax.swing.JFormattedTextField(); Ano_Submissao = new javax.swing.JFormattedTextField(); jLabel27 = new javax.swing.JLabel(); jLabel24 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); Observacoes = new javax.swing.JTextArea(); jLabel26 = new javax.swing.JLabel(); jScrollPane2 = new javax.swing.JScrollPane(); Documentos = new javax.swing.JTextArea(); jScrollPane3 = new javax.swing.JScrollPane(); Candidaturas = new javax.swing.JList(); Remover = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); Dia_Aprovacao = new javax.swing.JFormattedTextField(); Mes_Aprovacao = new javax.swing.JFormattedTextField(); Ano_Aprovacao = new javax.swing.JFormattedTextField(); jLabel28 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); Estado = new javax.swing.JFormattedTextField(); jLabel1 = new javax.swing.JLabel(); setLayout(null); jLabel25.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel25.setText("Data Submissão"); add(jLabel25); jLabel25.setBounds(330, 160, 110, 30); add(Dia_Submissao); Dia_Submissao.setBounds(460, 160, 40, 30); add(Mes_Submissao); Mes_Submissao.setBounds(510, 160, 40, 30); add(Ano_Submissao); Ano_Submissao.setBounds(560, 160, 40, 30); jLabel27.setText("(dd-mm-aaaa)"); add(jLabel27); jLabel27.setBounds(620, 160, 100, 30); jLabel24.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel24.setText("Observações:"); add(jLabel24); jLabel24.setBounds(330, 240, 110, 30); Observacoes.setColumns(20); Observacoes.setRows(5); jScrollPane1.setViewportView(Observacoes); add(jScrollPane1); jScrollPane1.setBounds(460, 240, 310, 96); jLabel26.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel26.setText("Nome Documentos:"); add(jLabel26); jLabel26.setBounds(330, 340, 130, 30); Documentos.setColumns(20); Documentos.setRows(5); jScrollPane2.setViewportView(Documentos); add(jScrollPane2); jScrollPane2.setBounds(460, 350, 310, 96); Candidaturas.setModel(new javax.swing.AbstractListModel() { String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; public int getSize() { return strings.length; } public Object getElementAt(int i) { return strings[i]; } }); jScrollPane3.setViewportView(Candidaturas); add(jScrollPane3); jScrollPane3.setBounds(50, 170, 120, 270); Remover.setText("Remover"); Remover.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { RemoverMouseClicked(evt); } }); Remover.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { RemoverActionPerformed(evt); } }); add(Remover); Remover.setBounds(50, 460, 120, 30); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel2.setText("Data Aprovação"); add(jLabel2); jLabel2.setBounds(330, 200, 110, 30); add(Dia_Aprovacao); Dia_Aprovacao.setBounds(460, 200, 40, 30); add(Mes_Aprovacao); Mes_Aprovacao.setBounds(510, 200, 40, 30); add(Ano_Aprovacao); Ano_Aprovacao.setBounds(560, 200, 40, 30); jLabel28.setText("(dd-mm-aaaa)"); add(jLabel28); jLabel28.setBounds(620, 200, 100, 30); jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel3.setText("Estado"); add(jLabel3); jLabel3.setBounds(340, 460, 110, 30); add(Estado); Estado.setBounds(460, 460, 310, 30); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/987.jpg"))); // NOI18N add(jLabel1); jLabel1.setBounds(0, 0, 960, 610); }// </editor-fold>//GEN-END:initComponents private void RemoverMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_RemoverMouseClicked // TODO add your handling code here: JOptionPane.showMessageDialog(null, "Removido!"); }//GEN-LAST:event_RemoverMouseClicked private void RemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RemoverActionPerformed // TODO add your handling code here: }//GEN-LAST:event_RemoverActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JFormattedTextField Ano_Aprovacao; private javax.swing.JFormattedTextField Ano_Submissao; private javax.swing.JList Candidaturas; private javax.swing.JFormattedTextField Dia_Aprovacao; private javax.swing.JFormattedTextField Dia_Submissao; private javax.swing.JTextArea Documentos; private javax.swing.JFormattedTextField Estado; private javax.swing.JFormattedTextField Mes_Aprovacao; private javax.swing.JFormattedTextField Mes_Submissao; private javax.swing.JTextArea Observacoes; private javax.swing.JButton Remover; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel24; private javax.swing.JLabel jLabel25; private javax.swing.JLabel jLabel26; private javax.swing.JLabel jLabel27; private javax.swing.JLabel jLabel28; private javax.swing.JLabel jLabel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; // End of variables declaration//GEN-END:variables }
true
840a169ecc86b7c18d65ec3b97b1a23445957c7f
Java
jphui/Maycraft
/Button.java
UTF-8
1,966
3.234375
3
[]
no_license
import mayflower.*; public class Button extends Actor { private Picture regular; //default image of button private Picture hovered; //image that is set when mouse is on button private Picture clicked; //image that is set when button is clicked private Sound clickSound; //sound that is played when button is clicked private Stage newWorld; //world that is set when button is clicked private boolean wasHovered; public Button(String path, String hoveredPath, String clickedPath, //sets all the aforementioned variables String clickSnd,Stage worldSet, int xsize, int ysize) { regular = new Picture(path); hovered = new Picture(hoveredPath); regular.resize(xsize,ysize); hovered.resize(xsize,ysize); if(clickedPath != null) { clicked = new Picture(clickedPath); clicked.resize(xsize,ysize); } clickSound = new Sound(clickSnd); newWorld = worldSet; setPicture(path); } public void update() { if(isHovered() && !wasHovered) //if the button is hovered for the first time set button to blue hovered image { setPicture(hovered); wasHovered = true; } else setPicture(regular); wasHovered = false; //if the button is not hovered set picture to default if(isClicked()) // if button is clicked set image to clicked image { if(clicked!=null)setPicture(clicked); clickSound.play(); if(newWorld!=null)getMayflower().setStage(newWorld); } } public boolean isHovered() //checks if the mouse is over the button { int x = 0,y = 0; if(getMouse()!=null)x = getMouse().getX(); //mouse's x coordinate if(getMouse()!=null)y = getMouse().getY(); //mouse's y coordinate if(isTouching(x,y)) return true; //if the button is making contact with the mouse's location return false; } }
true
f8db49517c0b5a344ddf2437f9cc8c21041fecc4
Java
TanerNonturner/TESTNG
/src/test/java/pages/DashboardPage.java
UTF-8
266
1.679688
2
[]
no_license
package pages; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import utils.CommonMethods; public class DashboardPage extends CommonMethods{ public WebElement OrangeHRMlogo = driver.findElement(By.xpath("//img[@alt='OrangeHRM']")); }
true
990b64b90254c6fa7a70f1b0b143041755a081df
Java
wangqiang6071/authorizecode
/src/test/java/com/zelu/authorizecode/AuthorizecodeApplicationTests.java
UTF-8
3,942
2.03125
2
[]
no_license
package com.zelu.authorizecode; import com.zelu.authorizecode.dao.AuthortySystemCodeMapper; import com.zelu.authorizecode.entity.AuthortySystemCode; import com.zelu.authorizecode.utils.Rquest.RestTemplateUtils; import com.zelu.authorizecode.utils.Rquest.entity.plugsList.ReturnPlugsListResult; import com.zelu.authorizecode.utils.Rquest.entity.redisdata.ResultFinalNotCleanData; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.web.client.RestTemplate; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.*; @SpringBootTest class AuthorizecodeApplicationTests { @Autowired private AuthortySystemCodeMapper systemCodeMapper; @Test void contextLoads() { //2021-09-06 16:53:34 LocalDateTime endTime = LocalDateTime.of(2021, 9, 6, 16, 53, 35); //LocalDateTime time=LocalDateTime.now(); DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String strDate2 = dtf2.format(endTime); System.out.println(strDate2); } @Test public void add(){ Map<String,Object>map=new HashMap<>(); final List<AuthortySystemCode> systemCodes = systemCodeMapper.selectByMap(map); if(systemCodes.size()==0){ System.out.println("====="); }else if(systemCodes.size()>0){ System.out.println("xxxxx"); } } @Test public void adds() throws IOException { ServerSocketChannel serverSocketChannel=ServerSocketChannel.open(); serverSocketChannel.socket().bind(new InetSocketAddress(9000)); serverSocketChannel.configureBlocking(false); Selector open = Selector.open(); serverSocketChannel.register(open, SelectionKey.OP_ACCEPT); open.select(); final Set<SelectionKey> selectionKeys = open.selectedKeys(); final Iterator<SelectionKey> iterator = selectionKeys.iterator(); final SelectionKey next = iterator.next(); } @Autowired @Qualifier("urlConnection") private RestTemplate restTemplate; @Test public void adds1() { RestTemplateUtils<ReturnPlugsListResult>request=new RestTemplateUtils<>(ReturnPlugsListResult.class,restTemplate); Map<String,Object>map=new HashMap<>(); ReturnPlugsListResult returnPlugsListResult = request.RestTemplate("http://192.168.50.254:5555/interface", "plugin_list", map); System.out.println(returnPlugsListResult); } @Test public void adds2() { //RedisTemplate redisTemplate = (RedisTemplate) ApplicationTextUtils.getBeanObj("redisTemplate"); Set<String>set=new HashSet<>(); set.add("A1"); set.add("A2"); set.add("A3"); set.add("A4"); // redisTemplate.opsForSet().add("A","B","C"); // redisTemplate.opsForSet().add("A",new String[]{"1","2"}); // final Set a = redisTemplate.opsForSet().members("A"); // System.out.println("A===>"+a); String[] array2 = set.stream().toArray(String[]::new); System.out.println("set===>"+array2[0]); } @Test public void adds3() { RestTemplateUtils<ResultFinalNotCleanData>request=new RestTemplateUtils<>(ResultFinalNotCleanData.class,restTemplate); Map<String,Object>map=new HashMap<>(); map.put("task_id","d8c1f970-6e44-48ca-8af3-2860cca61ca3"); ResultFinalNotCleanData returnPlugsListResult = request.RestTemplate("http://192.168.50.254:5555/interface", "get_task_result", map); System.out.println(returnPlugsListResult); } }
true
10e9f357de4e612bd69329cb6a90037916f95b92
Java
mins1031/spring-boot-jpa-mysql-minair
/src/main/java/com/minair/minair/repository/AirlineSearchRepositoryImpl.java
UTF-8
1,173
2.375
2
[]
no_license
package com.minair.minair.repository; import com.minair.minair.domain.Airline; import com.minair.minair.domain.dto.airline.AirlineSearchDto; import com.querydsl.jpa.impl.JPAQueryFactory; import javax.persistence.EntityManager; import java.util.List; import static com.minair.minair.domain.QAirline.airline; public class AirlineSearchRepositoryImpl implements AirlineSearchRepository{ private final JPAQueryFactory queryFactory; public AirlineSearchRepositoryImpl(EntityManager em) { queryFactory = new JPAQueryFactory(em); } @Override public List<Airline> searchResults(AirlineSearchDto airlineSearchDto) { int totalPerson = airlineSearchDto.getAdult() + airlineSearchDto.getChild(); return queryFactory .select(airline) .from(airline) .where(airline.departure.eq(airlineSearchDto.getDeparture()) .and(airline.distination.eq(airlineSearchDto.getDistination())) .and(airline.departDate.goe(airlineSearchDto.getDepart_date())) .and(airline.aboveSeat.goe(totalPerson))) .fetch(); } }
true
13de64a1c32d4cedcd2ff1d9fbc0856d8dbda821
Java
hmcts/ccpay-payment-app
/api/src/test/java/uk/gov/hmcts/payment/api/componenttests/RemissionDbBackdoor.java
UTF-8
913
2.015625
2
[]
no_license
package uk.gov.hmcts.payment.api.componenttests; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import uk.gov.hmcts.payment.api.dto.RemissionRequest; import uk.gov.hmcts.payment.api.model.Remission; import uk.gov.hmcts.payment.api.model.RemissionRepository; import uk.gov.hmcts.payment.api.v1.model.exceptions.RemissionNotFoundException; @Component public class RemissionDbBackdoor { @Autowired private RemissionRepository remissionRepository; public Remission findByHwfReference(String hwfReference) { return remissionRepository.findByHwfReference(hwfReference).orElseThrow(RemissionNotFoundException::new); } public Remission findByRemissionReference(String remissionReference) { return remissionRepository.findByRemissionReference(remissionReference).orElseThrow(RemissionNotFoundException::new); } }
true
b52c5b1fea68a9a55dc7de7256c171943d58a306
Java
Cing-self/PlaneWar
/src/com/Background.java
UTF-8
644
3.125
3
[]
no_license
package com; import javax.swing.*; public class Background { //图片(路径)起始坐标x,y,宽度、高度 private int x; private int y; private ImageIcon backgroundIcon = new ImageIcon("image/bg.jpg"); //构造方法 public Background(int x, int y){ this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } public ImageIcon getBackgroundIcon() { return backgroundIcon; } public void move(){ System.out.println("背景:" + x + "--" + y); this.y += 1;//背景移动速度 } }
true
330c4153d0b4f219fceebe55b2392d4ec2bd029e
Java
socratillos/corpus_parser
/src/java/com/socrates/corpus/parser/model/Sentence.java
UTF-8
1,084
3.28125
3
[]
no_license
package com.socrates.corpus.parser.model; import java.util.ArrayList; import java.util.List; public class Sentence { public Sentence() { words = new ArrayList<>(); } private List<Word> words; public void addWord(Word word) { words.add(word); } public List<Word> getWords() { return this.words; } public Word getWordByIndex(int index) { return words.get(index); } public boolean hasNegation() { for(Word word: words) { if(word.isNegation()) { return true; } } return false; } public boolean isEmpty() { return words.isEmpty(); } public boolean hastTwoNegation() { for(Word word: words) { if(word.getSecondNegation() != null) { return true; } } return false; } public int getNumberOfWords() { if(words != null) { return words.size(); } else { return 0; } } @Override public String toString() { StringBuilder builder = new StringBuilder(); for(Word word: words) { builder.append(word); builder.append("\n"); } return "Sentence words: \n" + builder.toString(); } }
true
6528e379d954c2ef986761775848cd56e5572d33
Java
Zeroh729/BlueBoothFairy
/Mobile/BlueBoothFairy_Buyer/app/src/main/java/android/zeroh729/com/blueboothfairy/buyers/presenters/base/BasePresenter.java
UTF-8
237
1.835938
2
[]
no_license
package android.zeroh729.com.blueboothfairy.buyers.presenters.base; public interface BasePresenter { void updateState(); void setState(int state); interface SystemInterface{ } interface ScreenInterface{ } }
true
dba3fe93d004db21a2d62d13f50db8125db5d1db
Java
expo/expo
/android/vendored/sdk48/react-native-svg/android/src/main/java/abi48_0_0/com/horcrux/svg/SVGLength.java
UTF-8
3,854
2.90625
3
[ "MIT", "BSD-3-Clause", "Apache-2.0" ]
permissive
package abi48_0_0.com.horcrux.svg; import abi48_0_0.com.facebook.react.bridge.Dynamic; import abi48_0_0.com.facebook.react.bridge.ReadableArray; import java.util.ArrayList; class SVGLength { // https://www.w3.org/TR/SVG/types.html#InterfaceSVGLength public enum UnitType { UNKNOWN, NUMBER, PERCENTAGE, EMS, EXS, PX, CM, MM, IN, PT, PC, } final double value; final UnitType unit; private SVGLength() { value = 0; unit = UnitType.UNKNOWN; } SVGLength(double number) { value = number; unit = UnitType.NUMBER; } private SVGLength(String length) { length = length.trim(); int stringLength = length.length(); int percentIndex = stringLength - 1; if (stringLength == 0 || length.equals("normal")) { unit = UnitType.UNKNOWN; value = 0; } else if (length.codePointAt(percentIndex) == '%') { unit = UnitType.PERCENTAGE; value = Double.valueOf(length.substring(0, percentIndex)); } else { int twoLetterUnitIndex = stringLength - 2; if (twoLetterUnitIndex > 0) { String lastTwo = length.substring(twoLetterUnitIndex); int end = twoLetterUnitIndex; switch (lastTwo) { case "px": unit = UnitType.NUMBER; break; case "em": unit = UnitType.EMS; break; case "ex": unit = UnitType.EXS; break; case "pt": unit = UnitType.PT; break; case "pc": unit = UnitType.PC; break; case "mm": unit = UnitType.MM; break; case "cm": unit = UnitType.CM; break; case "in": unit = UnitType.IN; break; default: unit = UnitType.NUMBER; end = stringLength; } value = Double.valueOf(length.substring(0, end)); } else { unit = UnitType.NUMBER; value = Double.valueOf(length); } } } static SVGLength from(Dynamic dynamic) { switch (dynamic.getType()) { case Number: return new SVGLength(dynamic.asDouble()); case String: return new SVGLength(dynamic.asString()); default: return new SVGLength(); } } static SVGLength from(String string) { return new SVGLength(string); } static SVGLength from(Double value) { return new SVGLength(value); } static String toString(Dynamic dynamic) { switch (dynamic.getType()) { case Number: return String.valueOf(dynamic.asDouble()); case String: return dynamic.asString(); default: return null; } } static ArrayList<SVGLength> arrayFrom(Dynamic dynamic) { switch (dynamic.getType()) { case Number: { ArrayList<SVGLength> list = new ArrayList<>(1); list.add(new SVGLength(dynamic.asDouble())); return list; } case Array: { ReadableArray arr = dynamic.asArray(); int size = arr.size(); ArrayList<SVGLength> list = new ArrayList<>(size); for (int i = 0; i < size; i++) { Dynamic val = arr.getDynamic(i); list.add(from(val)); } return list; } case String: { ArrayList<SVGLength> list = new ArrayList<>(1); list.add(new SVGLength(dynamic.asString())); return list; } default: return null; } } static ArrayList<SVGLength> arrayFrom(ReadableArray arr) { int size = arr.size(); ArrayList<SVGLength> list = new ArrayList<>(size); for (int i = 0; i < size; i++) { Dynamic val = arr.getDynamic(i); list.add(from(val)); } return list; } }
true
7978f73d00bc2cf81d8b7328342f6ab51b860675
Java
GreatDiscovery/ecs-app
/ecs-util/src/test/java/com/gavin/app/proxy/ClassModifier.java
UTF-8
938
2.578125
3
[]
no_license
package com.gavin.app.proxy; /** * 修改Class文件,只提供修改常量池功能 * * @author gavin * @date 2020/11/8 9:20 下午 */ public class ClassModifier { /** * 常量池的起始偏移 */ public static final int CONSTANT_POOL_COUNT_INDEX = 8; /** * utf8_info的tag标志 */ public static final int CONSTANT_UTF8_INFO = 1; /** * 常量池11中常量所占的宽度 */ public static final int[] CONSTANT_ITEM_LENGTH = {-1, -1, -1, 5, 5, 9, 9, 3, 3, 5, 5, 5, 5}; public static final int u1 = 1; public static final int u2 = 2; private byte[] classByte; public ClassModifier(byte[] classByte) { this.classByte = classByte; } /** * 修改常量池utf8_info的内容 * @param oldStr * @param newStr * @return */ public byte[] modifyURF8Constant(String oldStr, String newStr) { return null; } }
true
296207e5f9011bf861c9ee9f751f6824ee28ecdf
Java
wwjiang007/yugabyte-db
/managed/src/main/java/com/yugabyte/yw/controllers/PlatformInstanceController.java
UTF-8
7,755
1.921875
2
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "OpenSSL" ]
permissive
/* * Copyright 2021 YugaByte, Inc. and Contributors * * Licensed under the Polyform Free Trial License 1.0.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * https://github.com/YugaByte/yugabyte-db/blob/master/licenses/POLYFORM-FREE-TRIAL-LICENSE-1.0.0.txt */ package com.yugabyte.yw.controllers; import com.google.inject.Inject; import com.yugabyte.yw.common.CustomerTaskManager; import com.yugabyte.yw.common.PlatformServiceException; import com.yugabyte.yw.common.ha.PlatformReplicationManager; import com.yugabyte.yw.forms.PlatformInstanceFormData; import com.yugabyte.yw.forms.PlatformResults; import com.yugabyte.yw.forms.RestorePlatformBackupFormData; import com.yugabyte.yw.models.Audit; import com.yugabyte.yw.models.HighAvailabilityConfig; import com.yugabyte.yw.models.PlatformInstance; import java.io.File; import java.net.URL; import java.util.Objects; import java.util.Optional; import java.util.UUID; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import play.data.Form; import play.mvc.Http; import play.mvc.Result; public class PlatformInstanceController extends AuthenticatedController { public static final Logger LOG = LoggerFactory.getLogger(PlatformInstanceController.class); @Inject private PlatformReplicationManager replicationManager; @Inject CustomerTaskManager taskManager; public Result createInstance(UUID configUUID, Http.Request request) { Optional<HighAvailabilityConfig> config = HighAvailabilityConfig.getOrBadRequest(configUUID); Form<PlatformInstanceFormData> formData = formFactory.getFormDataOrBadRequest(request, PlatformInstanceFormData.class); // Cannot create a remote instance before creating a local instance. if (!formData.get().is_local && !config.get().getLocal().isPresent()) { throw new PlatformServiceException( BAD_REQUEST, "Cannot create a remote platform instance before creating local platform instance"); // Cannot create a remote instance if local instance is follower. } else if (!formData.get().is_local && !config.get().isLocalLeader()) { throw new PlatformServiceException( BAD_REQUEST, "Cannot create a remote platform instance on a follower platform instance"); // Cannot create multiple local platform instances. } else if (formData.get().is_local && config.get().getLocal().isPresent()) { throw new PlatformServiceException(BAD_REQUEST, "Local platform instance already exists"); // Cannot create multiple leader platform instances. } else if (formData.get().is_leader && config.get().isLocalLeader()) { throw new PlatformServiceException(BAD_REQUEST, "Leader platform instance already exists"); } PlatformInstance instance = PlatformInstance.create( config.get(), formData.get().getCleanAddress(), formData.get().is_leader, formData.get().is_local); // Mark this instance as "failed over to" initially since it is a leader instance. if (instance.getIsLeader()) { config.get().updateLastFailover(); } auditService() .createAuditEntry( request, Audit.TargetType.PlatformInstance, Objects.toString(instance.getUuid(), null), Audit.ActionType.Create); return PlatformResults.withData(instance); } public Result deleteInstance(UUID configUUID, UUID instanceUUID, Http.Request request) { Optional<HighAvailabilityConfig> config = HighAvailabilityConfig.getOrBadRequest(configUUID); Optional<PlatformInstance> instanceToDelete = PlatformInstance.get(instanceUUID); boolean instanceUUIDValid = instanceToDelete.isPresent() && config.get().getInstances().stream().anyMatch(i -> i.getUuid().equals(instanceUUID)); if (!instanceUUIDValid) { throw new PlatformServiceException(NOT_FOUND, "Invalid instance UUID"); } if (!config.get().isLocalLeader()) { throw new PlatformServiceException( BAD_REQUEST, "Follower platform instance cannot delete platform instances"); } if (instanceToDelete.get().getIsLocal()) { throw new PlatformServiceException(BAD_REQUEST, "Cannot delete local instance"); } auditService() .createAuditEntry( request, Audit.TargetType.PlatformInstance, instanceUUID.toString(), Audit.ActionType.Delete); PlatformInstance.delete(instanceUUID); return ok(); } public Result getLocal(UUID configUUID) { Optional<HighAvailabilityConfig> config = HighAvailabilityConfig.getOrBadRequest(configUUID); Optional<PlatformInstance> localInstance = config.get().getLocal(); if (!localInstance.isPresent()) { throw new PlatformServiceException(BAD_REQUEST, "No local platform instance for config"); } return PlatformResults.withData(localInstance.get()); } public Result promoteInstance( UUID configUUID, UUID instanceUUID, String curLeaderAddr, Http.Request request) throws java.net.MalformedURLException { Optional<HighAvailabilityConfig> config = HighAvailabilityConfig.getOrBadRequest(configUUID); Optional<PlatformInstance> instance = PlatformInstance.get(instanceUUID); boolean instanceUUIDValid = instance.isPresent() && config.get().getInstances().stream().anyMatch(i -> i.getUuid().equals(instanceUUID)); if (!instanceUUIDValid) { throw new PlatformServiceException(NOT_FOUND, "Invalid platform instance UUID"); } if (!instance.get().getIsLocal()) { throw new PlatformServiceException(BAD_REQUEST, "Cannot promote a remote platform instance"); } if (instance.get().getIsLeader()) { throw new PlatformServiceException(BAD_REQUEST, "Cannot promote a leader platform instance"); } Form<RestorePlatformBackupFormData> formData = formFactory.getFormDataOrBadRequest(request, RestorePlatformBackupFormData.class); if (StringUtils.isBlank(curLeaderAddr)) { Optional<PlatformInstance> leaderInstance = config.get().getLeader(); if (!leaderInstance.isPresent()) { throw new PlatformServiceException(BAD_REQUEST, "Could not find leader instance"); } curLeaderAddr = leaderInstance.get().getAddress(); } // Make sure the backup file provided exists. Optional<File> backup = replicationManager.listBackups(new URL(curLeaderAddr)).stream() .filter(f -> f.getName().equals(formData.get().backup_file)) .findFirst(); if (!backup.isPresent()) { throw new PlatformServiceException(BAD_REQUEST, "Could not find backup file"); } // Cache local instance address before restore so we can query to new corresponding model. String localInstanceAddr = instance.get().getAddress(); // Restore the backup. backup.ifPresent(replicationManager::restoreBackup); // Handle any incomplete tasks that may be leftover from the backup that was restored. taskManager.handleAllPendingTasks(); // Promote the local instance. PlatformInstance.getByAddress(localInstanceAddr) .ifPresent(replicationManager::promoteLocalInstance); // Start the new backup schedule. replicationManager.start(); // Finally, switch the prometheus configuration to read from swamper targets directly. replicationManager.switchPrometheusToStandalone(); auditService() .createAuditEntry( request, Audit.TargetType.PlatformInstance, instanceUUID.toString(), Audit.ActionType.Promote); return ok(); } }
true
559b63c880369eac7585e936ab30e2a3bf1a0c87
Java
jiangransoftdev/Leetcode
/158-Read-N-Characters-Given-Read4-II---Call-multiple-times/solution.java
UTF-8
889
3.265625
3
[]
no_license
/* The read4 API is defined in the parent class Reader4. int read4(char[] buf); */ public class Solution extends Reader4 { /** * @param buf Destination buffer * @param n Maximum number of characters to read * @return The number of characters read */ Queue<Character> q=new LinkedList<>(); public int read(char[] buf, int n) { int i=0; while(i<n&&!q.isEmpty()){ buf[i]=q.poll(); i++; } for(;i<n;i+=4){ char[] tmp=new char[4]; int len=read4(tmp); if(len>n-i){ System.arraycopy(tmp,0,buf,i,n-i); for(int j=n-i;j<len;j++) q.offer(tmp[j]); } else System.arraycopy(tmp,0,buf,i,len); if(len<4) return Math.min(i+len,n); } return n; } }
true
c3d17a44f9e091384c09efeb513a4eda14e04ae5
Java
newcoder-zhang/SimpleCircleDotView
/circledotview/src/main/java/cn/ucai/www/circledotview/MainActivity.java
UTF-8
1,568
2.421875
2
[]
no_license
package cn.ucai.www.circledotview; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private List<Fragment> fragmentList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initData(); initView(); } private void initData() { fragmentList = new ArrayList<>(); fragmentList.add(new Fragment1()); fragmentList.add(new Fragment2()); fragmentList.add(new Fragment3()); fragmentList.add(new Fragment4()); } private void initView() { ViewPager vp= (ViewPager) findViewById(R.id.vp); MyPagerAdapter adapter=new MyPagerAdapter(getSupportFragmentManager()); vp.setAdapter(adapter); } private class MyPagerAdapter extends FragmentPagerAdapter{ public MyPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { return fragmentList.get(position); } @Override public int getCount() { return fragmentList.size(); } } }
true
b1c480e239a42f190e34e0061ed1f69b7c6c745c
Java
valfridosilva/java
/src/br/com/ideia/util/FabricaConexao.java
ISO-8859-1
826
2.578125
3
[]
no_license
package br.com.ideia.util; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import org.apache.log4j.Logger; /** * Cria e fecha conexes com o BD * */ public class FabricaConexao { private static Logger logger = Logger.getLogger(FabricaConexao.class); private static EntityManager instance; public static EntityManager getEntityManager() { if (instance == null) { EntityManagerFactory factory = Persistence.createEntityManagerFactory("ideia"); instance = factory.createEntityManager(); } return instance; } public static void close() { if (instance != null && instance.isOpen()) { instance.close(); logger.debug("Conexo com o Banco de Dados fechada com sucesso!"); } } }
true
7ad71774f0dadd8182fa12ca085e2ad4432e212a
Java
worldbuilds/wb-cloud-project
/wb-cloud-auth-server/src/main/java/org/worldbuild/cloud/auth/modal/UserDTO.java
UTF-8
1,100
2.109375
2
[]
no_license
package org.worldbuild.cloud.auth.modal; import lombok.Data; import lombok.NoArgsConstructor; import org.apache.commons.codec.binary.Base32; import org.worldbuild.cloud.auth.JPA.entity.UserInfo; @Data @NoArgsConstructor public class UserDTO { Integer id; String username; String password; String confirm; String name; String email; String phone; String address; String secretKey; boolean enabled; boolean googleAuth; public static UserDTO generateUserDTO(UserInfo user) { UserDTO userDTO= new UserDTO(); userDTO.setId(user.getId()); userDTO.setName(user.getName()); userDTO.setEmail(user.getEmail()); userDTO.setPhone(user.getPhone()); user.setUsername(user.getUsername()); userDTO.setAddress(user.getAddress()); String encodedSecret = new Base32().encodeToString(user.getSecretKey().getBytes()); userDTO.setSecretKey(encodedSecret); // userDTO.setEnabled(user.isEnabled()); userDTO.setGoogleAuth(user.isGoogleAuth()); return userDTO; } }
true
9fcfdbd89a923f7b2783325dcfc95aa4e96a3780
Java
young-hee/pc_mlb
/workspace/ncp_framework/src/main/java/com/plgrim/ncp/commons/features/PurchaseTotalAmountActivationStrategy.java
UTF-8
2,382
1.953125
2
[]
no_license
package com.plgrim.ncp.commons.features; import org.springframework.beans.factory.annotation.Autowired; import org.togglz.core.activation.Parameter; import org.togglz.core.activation.ParameterBuilder; import org.togglz.core.repository.FeatureState; import org.togglz.core.spi.ActivationStrategy; import org.togglz.core.user.FeatureUser; import com.plgrim.ncp.framework.systems.UserContextInfo; import com.plgrim.ncp.framework.systems.UserContextInjector; import lombok.Data; import lombok.extern.slf4j.Slf4j; @Slf4j @Data public class PurchaseTotalAmountActivationStrategy implements ActivationStrategy { final static String KEY = "purchaseTotalAmount"; @Autowired UserContextInjector userInjector; @Autowired DecidedFeatures decidedFeatures; @Override public String getId() { return KEY; } @Override public String getName() { return "구매 금액"; } @Override public boolean isActive(FeatureState featureState, FeatureUser user) { try { UserContextInfo info = userInjector.getCurrentUser(); if (info == null) { return false; } Integer decidedAmount = decidedAmount(featureState); if (decidedAmount == null) { return false; } return testAmount(featureState, decidedAmount); } catch (Exception e) { log.warn("", e); return false; } } private Integer decidedAmount(FeatureState featureState) { if (decidedFeatures.hasDecided(KEY)) { return (Integer) decidedFeatures.decided(KEY); } else { Integer amount = fetchAmount(featureState); return amount; } } private Boolean testAmount(FeatureState featureState, Integer amount) { int targetPurchaseAmountFrom = Integer.parseInt(featureState.getParameter(KEY + "From")); int targetPurchaseAmountTo = Integer.parseInt(featureState.getParameter(KEY + "To")); Boolean isActive = targetPurchaseAmountFrom <= amount && amount <= targetPurchaseAmountTo; return isActive; } private Integer fetchAmount(FeatureState featureState) { String queryFrom = featureState.getParameter(KEY + "QueryFrom"); String queryTo = featureState.getParameter(KEY + "QueryTo"); Integer amount = userInjector.getCurrentUserPurchaseAmountHistory(queryFrom, queryTo); return amount; } @Override public Parameter[] getParameters() { return new Parameter[] { ParameterBuilder.create(KEY).label("총 구매 금액").description("총 구매 금액") }; } }
true
73897d2e2200791d72c4cd8b4b2de414f6c92a41
Java
cheemavi/PersonalMusicPlayer
/pmp/src/pmp/loopMHandler.java
UTF-8
988
2.40625
2
[]
no_license
package pmp; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; import javafx.util.Duration; public class loopMHandler implements EventHandler<ActionEvent> { SongEventHandler sE; boolean isLoop=false; Duration n= sE.getInstance().getTune().getM().getStartTime(); @Override public void handle(ActionEvent arg0) { SongEventHandler sE= SongEventHandler.getInstance(); MediaPlayer curr = sE.getTune().getM(); if(!this.isLoop) { System.out.println(curr.getCycleCount()+"this"); curr.setCycleCount(MediaPlayer.INDEFINITE); curr.setStartTime(Duration.ZERO); this.isLoop=true; } else { n=curr.getCurrentTime(); curr.stop(); this.isLoop=false; curr.setCycleCount(1); curr.setStartTime(n); System.out.println(curr.getStartTime()+"w"); curr.play(); curr.setStartTime(Duration.ZERO); } } }
true
865406401d174546831e7a9fff5db9ec1f4ef1e7
Java
mshashi/pkma-spring-core-training
/bean-post-processor-application/src/main/java/my/spring/main/MyBean.java
UTF-8
390
2.53125
3
[]
no_license
package my.spring.main; public class MyBean { private String message; public void setMessage(String message) { this.message = message; } public void getMessage() { System.out.println("Message : " + message); } public void init() { System.out.println("In init methood."); } public void destroy() { System.out.println("In destroy method."); } }
true
7bd057ce9da28396d56de837491301fd51b94e73
Java
kelasov/Java2020-Lab3
/src/human/Head.java
UTF-8
514
2.828125
3
[]
no_license
package human; public class Head { private int length; private int wide; public int getLength() { return length; } public void setLength(int length) { this.length = length; } public int getWide() { return wide; } public void setWide(int wide) { this.wide = wide; } @Override public String toString() { return "Head{" + "length=" + length + ", wide=" + wide + '}'; } }
true
8ce8d146b20775b4d1b586a24cc318217c807d43
Java
Mittal-Shivam/DataEntry
/Student/src/student/PG.java
UTF-8
189
1.640625
2
[]
no_license
package student; public class PG extends Student{ public float ResultPG; public String Publications; public String Book; public String Paper; public String Patent; }
true
cb1382f06f9a3c9ad4288161ca38420024013edc
Java
Zheil/Simple-chat
/app/src/main/java/app/zheil/com/testchat2/DialogActivity.java
UTF-8
2,790
2.359375
2
[]
no_license
package app.zheil.com.testchat2; import android.content.Intent; import android.graphics.Color; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import com.github.bassaer.chatmessageview.model.Message; import com.github.bassaer.chatmessageview.view.ChatView; import app.zheil.com.testchat2.CoreDialog.ControllerDialog; import app.zheil.com.testchat2.CoreDialog.iResponsable; /** * Активити диалога. Диалог может проходить в двух режимах - с человеком или с ботом */ public class DialogActivity extends AppCompatActivity implements iResponsable { private ChatView mChatView; private ControllerDialog mController; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dialog); Boolean isBot = getTypeChatFromIntent(); mChatView = findViewById(R.id.chat_view); mController = new ControllerDialog(isBot, this,this); setUi(); setListenersDialog(); } private boolean getTypeChatFromIntent() { Intent intent = getIntent(); return intent.getBooleanExtra("isBot", false); } @Override public void userMessage(Message message) { //Set to chat view mChatView.send(message); //Reset edit text mChatView.setInputText(""); } @Override public void botMessage(Message message) { mChatView.receive(message); } private void setListenersDialog() { //Click Send Button mChatView.setOnClickSendButtonListener(new View.OnClickListener() { @Override public void onClick(View view) { mController.sendUserMessage(mChatView.getInputText()); } }); } /*** * Set UI parameters */ private void setUi() { mChatView.setRightBubbleColor(ContextCompat.getColor(this, R.color.green500)); mChatView.setLeftBubbleColor(Color.WHITE); mChatView.setBackgroundColor(ContextCompat.getColor(this, R.color.blueGray500)); mChatView.setSendButtonColor(ContextCompat.getColor(this, R.color.cyan900)); mChatView.setSendIcon(R.drawable.ic_action_send); mChatView.setRightMessageTextColor(Color.WHITE); mChatView.setLeftMessageTextColor(Color.BLACK); mChatView.setUsernameTextColor(Color.WHITE); mChatView.setSendTimeTextColor(Color.WHITE); mChatView.setDateSeparatorColor(Color.WHITE); mChatView.setInputTextHint("new message..."); mChatView.setMessageMarginTop(5); mChatView.setMessageMarginBottom(5); } }
true
83c1f83f0df3ccea42323b5ad949f8ffccdca7c2
Java
sadekujjaman/DynamicProgramming
/Dynamic Programming/src/basic/LISVECTOR.java
UTF-8
913
3.15625
3
[]
no_license
package basic; import java.util.Collection; import java.util.Vector; public class LISVECTOR { public static void main(String[] args) { int[] array = {2, 6, 4, 5, 1,3 }; System.out.println("Data In"); calc_LIS(array); } static void calc_LIS(int nums[]) { String paths[] = new String[nums.length]; int sizes[] = new int[nums.length]; for (int i = 0; i < nums.length; i++) { paths[i] = nums[i] + " "; sizes[i] = 1; } int maxL = 1; for (int i = 1; i < nums.length; i++) { for (int j = 0; j < i; j++) { if (nums[i] > nums[j] && sizes[i] < sizes[j] + 1) { sizes[i] = sizes[j] + 1; paths[i] = paths[j] + nums[i] + " "; System.out.println(paths[i]); if (maxL < sizes[i]) maxL = sizes[i]; } } } for (int i = 1; i < nums.length; i++) { if (sizes[i] == maxL) System.out.println(paths[i]); } } }
true
aaf160b79118ceeb07822543347e33cf67da13cc
Java
exactpro/sailfish-core
/BackEnd/Service/service-fast/src/main/java/com/exactpro/sf/services/fast/converter/FastToIMessageConverter.java
UTF-8
11,835
1.734375
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/****************************************************************************** * 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.exactpro.sf.services.fast.converter; import com.exactpro.sf.common.impl.messages.xml.configuration.JavaType; import com.exactpro.sf.common.messages.IMessage; import com.exactpro.sf.common.messages.IMessageFactory; import com.exactpro.sf.common.messages.structures.IAttributeStructure; import com.exactpro.sf.common.messages.structures.IDictionaryStructure; import com.exactpro.sf.common.messages.structures.IFieldStructure; import com.exactpro.sf.common.messages.structures.IMessageStructure; import com.exactpro.sf.common.util.EPSCommonException; import com.exactpro.sf.util.DateTimeUtility; import com.google.common.base.Enums; import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.openfast.FieldValue; import org.openfast.GroupValue; import org.openfast.Message; import org.openfast.SequenceValue; import org.openfast.template.Field; import org.openfast.template.Group; import org.openfast.template.MessageTemplate; import org.openfast.template.Scalar; import org.openfast.template.Sequence; import org.openfast.template.type.StringType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.concurrent.TimeUnit; public class FastToIMessageConverter { private static final Logger logger = LoggerFactory.getLogger(FastToIMessageConverter.class); public static final String UNIT = "unit"; private final IMessageFactory messageFactory; private final IDictionaryStructure dictionary; public enum TIMESTAMP_UNIT { day, second, millisecond, microsecond, nanosecond } public FastToIMessageConverter( IMessageFactory messageFactory, IDictionaryStructure dictionary) { this.messageFactory = messageFactory; this.dictionary = dictionary; } public IMessage convert(Message fastMsg) throws ConverterException { MessageTemplate template = fastMsg.getTemplate(); String msgName = getIMessageName(template.getName()); IMessage message; try { message = messageFactory.createMessage(msgName, dictionary.getNamespace()); } catch (Exception e) { logger.warn("Can not create fast IMessage for template id {}", msgName); throw new ConverterException( "Can not create fast IMessage for template id " + msgName, e); } convertFields(fastMsg, message, msgName); return message; } private void convertFields(GroupValue fastMsg, IMessage message, String msgName) throws ConverterException { Group template = fastMsg.getGroup(); for (Field fastFld : template.getFields()) { convertField(fastFld, fastMsg, message, msgName); } } private void convertField( Field fastFld, GroupValue fastMsg, IMessage message, String msgName) throws ConverterException { String iMessageFieldName = getIMessageName(fastFld.getName()); //FIXME: Have not found any better way to get value of the QNamed field Group grp = fastMsg.getGroup(); int index = grp.getFieldIndex(fastFld); if (!fastMsg.isDefined(index)) { return; } FieldValue fieldValue = fastMsg.getValue(index); if (fieldValue == null) { // message.addField(iMessageFieldName, null); return; } if("scalar".equals(fastFld.getTypeName())) { setScalarValue((Scalar) fastFld, fastMsg, message, iMessageFieldName ); } else if("sequence".equals(fastFld.getTypeName())) { SequenceValue sqsValue = fastMsg.getSequence(index); convertSequence(sqsValue, iMessageFieldName, message, msgName); } else if("group".equals(fastFld.getTypeName())) { GroupValue grpValue = fastMsg.getGroup(index); convertGroup(grpValue, iMessageFieldName, message, msgName); } else if("decimal".equals(fastFld.getTypeName())) { BigDecimal bdVal = fastMsg.getBigDecimal(index); message.addField(iMessageFieldName, bdVal); } else { logger.error("Can not convert field with type {}", fastFld.getTypeName()); throw new ConverterException( "Can not convert field with type " + fastFld.getTypeName()); } } private void convertGroup(GroupValue grpValue, String iMessageFieldName, IMessage message, String msgName) throws ConverterException { IMessage innerMessage; String msgType = msgName + "_" + iMessageFieldName; try { innerMessage = messageFactory.createMessage(msgType, dictionary.getNamespace()); } catch (Exception e) { logger.error("Can not create message for id:{}", msgType, e); throw new ConverterException("Can not create message for id:" + msgType, e); } convertFields(grpValue, innerMessage, msgType); message.addField(iMessageFieldName, innerMessage); } private void convertSequence(SequenceValue sqsValue, String iMessageFieldName, IMessage message, String msgName) throws ConverterException { Sequence sqs = sqsValue.getSequence(); String lengthName = sqs.getLength().getName(); if(StringUtils.isEmpty(lengthName)) { lengthName = "length"; } lengthName = getIMessageName(lengthName); lengthName = getIMessageName(sqsValue.getSequence().getName()) + "_" + lengthName; message.addField(lengthName, sqsValue.getLength()); String msgType = msgName + "_" + iMessageFieldName; ArrayList<IMessage> collectionMessages = new ArrayList<IMessage>(); for(GroupValue groupVal:sqsValue.getValues()) { IMessage innerMessage; try { innerMessage = messageFactory.createMessage(msgType, dictionary.getNamespace()); } catch (Exception e) { logger.error("Can not create message for id:{}", msgType, e); throw new ConverterException("Can not create message for id:" + msgType, e); } convertFields(groupVal, innerMessage, msgType); collectionMessages.add(innerMessage); } message.addField(iMessageFieldName, collectionMessages); } private void setScalarValue(Scalar fastFld, GroupValue fastMsg, IMessage message, String iMessageFieldName) throws ConverterException { JavaType fieldType = getFieldType(message.getName(), iMessageFieldName); //FIXME: Have not found any better way getting value of QNamed field Group grp = fastMsg.getGroup(); int index = grp.getFieldIndex(fastFld); if("int8".equals(fastFld.getType().getName())) { Byte byteVal = fastMsg.getByte(index); if (byteVal != null) { message.addField(iMessageFieldName, byteVal); } } else if("int32".equals(fastFld.getType().getName())) { Integer intVal = fastMsg.getInt(index); if (intVal != null) { message.addField(iMessageFieldName, intVal); } } else if("uInt32".equals(fastFld.getType().getName())) { Long longVal = fastMsg.getLong(index); if (longVal != null) { if (fieldType == JavaType.JAVA_LANG_BOOLEAN) { Boolean boolVal = longVal != 0; message.addField(iMessageFieldName, boolVal); } else { message.addField(iMessageFieldName, longVal); } } } else if("int64".equals(fastFld.getType().getName())) { Long longVal = fastMsg.getLong(index); if (longVal != null) { message.addField(iMessageFieldName, longVal); } } else if("uInt64".equals(fastFld.getType().getName())) { // TypeCodec.UINT is parsed by UnsignedInteger class. It uses LongValue class for huge value. // LongValue class unsupported getBigDecimal method Long longVal = fastMsg.getLong(index); if (longVal != null) { if (fieldType == JavaType.JAVA_TIME_LOCAL_DATE_TIME) { String unitAttrValue = getFieldTimeUnit(dictionary, message.getName(), iMessageFieldName); //FAST 1.2. A unit may not exist, then the millisecond is used as the default unit. TIMESTAMP_UNIT timeUnit = unitAttrValue != null ? Enums.getIfPresent(TIMESTAMP_UNIT.class, unitAttrValue).orNull() : TIMESTAMP_UNIT.millisecond; if (timeUnit == null) { throw new EPSCommonException("Incorrect time unit = " + unitAttrValue + " for " + iMessageFieldName + " field"); } LocalDateTime dateTime = timestampToDateTime(longVal, timeUnit); message.addField(iMessageFieldName, dateTime); } else { BigDecimal bdVal = new BigDecimal(longVal); message.addField(iMessageFieldName, bdVal); } } } else if (fastFld.getType() instanceof StringType ) { String sVal = fastMsg.getString(index); if (sVal != null) { message.addField(iMessageFieldName, sVal); } } else if("decimal".equals(fastFld.getType().getName())) { BigDecimal bdVal = fastMsg.getBigDecimal(index); if (bdVal != null) { message.addField(iMessageFieldName, bdVal); } } else if("byteVector".equals(fastFld.getType().getName())) { byte[] bvVal = fastMsg.getBytes(index); if (bvVal != null) { //FIXME: in most cases a separate field contains encoding of the message // message.addField(iMessageFieldName, bvVal); message.addField(iMessageFieldName, new String(bvVal, StandardCharsets.US_ASCII)); } } else { throw new ConverterException("Can not convert field of type: " + fastFld.getType().getName()); } } private String getIMessageName(String name) { return name.replaceAll("[_ -]", ""); } @Nullable private JavaType getFieldType(String msgName, String fieldName){ IMessageStructure msgStructure = dictionary.getMessages().get(msgName); if(msgStructure == null) { return null; } IFieldStructure fieldStructure = msgStructure.getFields().get(fieldName); if(fieldStructure == null) { return null; } return fieldStructure.getJavaType(); } @Nullable public static String getFieldTimeUnit(@NotNull IDictionaryStructure structure, String msgName, String fieldName){ IMessageStructure msgStructure = structure.getMessages().get(msgName); if(msgStructure == null) { return null; } IFieldStructure fieldStructure = msgStructure.getFields().get(fieldName); if(fieldStructure == null) { return null; } IAttributeStructure attributeStructure = fieldStructure.getAttributes().get(UNIT); if(attributeStructure == null) { return null; } return attributeStructure.getValue(); } @NotNull private LocalDateTime timestampToDateTime(long timestamp, @NotNull TIMESTAMP_UNIT unit) { switch (unit) { case day: return DateTimeUtility.toLocalDateTime(TimeUnit.DAYS.toMillis(timestamp)); case second: return DateTimeUtility.toLocalDateTime(TimeUnit.SECONDS.toMillis(timestamp)); case millisecond: return DateTimeUtility.toLocalDateTime(timestamp); case microsecond: long millisecond = TimeUnit.MICROSECONDS.toSeconds(timestamp) * TimeUnit.SECONDS.toMillis(1); int nanos = (int) (TimeUnit.MICROSECONDS.toNanos(timestamp) % TimeUnit.SECONDS.toNanos(1)); return DateTimeUtility.toLocalDateTime(millisecond, nanos); case nanosecond: millisecond = TimeUnit.NANOSECONDS.toSeconds(timestamp) * TimeUnit.SECONDS.toMillis(1); nanos = (int) (timestamp % TimeUnit.SECONDS.toNanos(1)); return DateTimeUtility.toLocalDateTime(millisecond, nanos); } return DateTimeUtility.toLocalDateTime(timestamp); } }
true
c0e885b3d4bccf468c165d786197664896cfa2fc
Java
moutainhigh/QA_TA_MCS
/src/main/java/com/bill99/mcs/pageobject/.svn/text-base/MockCenterPage.java.svn-base
UTF-8
639
2.296875
2
[]
no_license
package com.bill99.mcs.pageobject; import org.openqa.selenium.WebDriver; import org.testng.Reporter; /** * Description: 登录成功后的Mock页 * Author: zhenfeng.liu * Date: 2017/10/11 20:09 */ public class MockCenterPage { private WebDriver driver; public MockCenterPage(WebDriver driver) { this.driver = driver; } public void checkIsLoginSuccess() { String title = this.driver.getTitle(); if (title.equals("ATE_MDP方式_收单测试")) { Reporter.log("登录ATE 3.0 Mock成功."); } else { Reporter.FALSE("登录ATE 3.0 Mock失败."); } } }
true
530073adf984347868b568c74ce2a3876584b92d
Java
MarlusVLC/MyGaemEngeine
/src/br/pucpr/Vector3.java
UTF-8
4,807
3.203125
3
[]
no_license
package br.pucpr; import java.util.Objects; import static br.pucpr.Util.*; public class Vector3 implements Cloneable { public float x; public float y; public float z; public Vector3() { } public Vector3(float x, float y, float z) { this.x = x; this.y = y; this.z = z; } public Vector3(Vector3 other) { this(other.x, other.y, other.z); } public Vector3 set(float xyz) { this.x = xyz; this.y = xyz; this.z = xyz; return this; } public Vector3 set(float x, float y, float z) { this.x = x; this.y = y; this.z = z; return this; } public Vector3 setX(float x) { this.x = x; return this; } public Vector3 setY(float y) { this.y = y; return this; } public Vector3 setZ(float z) { this.z = z; return this; } public Vector3 add(Vector3 other) { x += other.x; y += other.y; z += other.z; return this; } public static Vector3 add(Vector3 vector, Vector3 other) { return vector.clone().add(other); } public Vector3 add(float value) { x += value; y += value; z += value; return this; } public static Vector3 add(Vector3 vector, float value) { return vector.clone().add(value); } public static Vector3 add(float value, Vector3 vector) { return vector.clone().add(value); } public Vector3 subtract(Vector3 other) { x -= other.x; y -= other.y; z -= other.z; return this; } public static Vector3 subtract(Vector3 vector, Vector3 other) { return vector.clone().subtract(other); } public Vector3 subtract(float value) { x -= value; y -= value; z -= value; return this; } public static Vector3 subtract(Vector3 vector, float value) { return vector.clone().subtract(value); } public static Vector3 subtract(float value, Vector3 vector) { Vector3 r = new Vector3(); r.x = value - vector.x; r.y = value - vector.y; r.z = value - vector.z; return r; } public Vector3 multiply(float s) { x *= s; y *= s; z *= s; return this; } public static Vector3 multiply(Vector3 vector, float s) { return vector.clone().multiply(s); } public static Vector3 multiply(float s, Vector3 vector) { return vector.clone().multiply(s); } public Vector3 multiply(float x, float y, float z) { this.x *= x; this.y *= y; this.z *= z; return this; } public static Vector3 multiply(Vector3 vector, float x, float y, float z) { return vector.clone().multiply(x, y, z); } public Vector3 multiply(Vector3 other) { return multiply(other.x, other.y, other.z); } public static Vector3 multiply(Vector3 vector, Vector3 other) { return vector.clone().multiply(other); } public Vector3 divide(float s) { return multiply(1.0f / s); } public static Vector3 divide(Vector3 vector, float s) { return vector.clone().divide(s); } public float dot(Vector3 other) { return dot(other.x, other.y, other.z); } public float dot(float x, float y, float z) { return this.x * x + this.y * y + this.z * z; } public float sizeSqr() { return x * x + y * y + z * z; } public float size() { return (float) Math.sqrt(sizeSqr()); } public Vector3 clone() { return new Vector3(x, y, z); } public Vector3 abs() { this.x = Math.abs(x); this.y = Math.abs(y); this.z = Math.abs(z); return this; } public static Vector3 abs(Vector3 v) { return v.clone().abs(); } public static float distance(Vector3 v1, Vector3 v2) { return subtract(v1, v2).size(); } public static float distanceSqr(Vector3 v1, Vector3 v2) { return subtract(v1, v2).sizeSqr(); } public boolean equals(Vector3 o, float epsilon) { if (o == null) return false; if (this == o) return true; return floatEquals(x, o.x, epsilon) && floatEquals(y, o.y, epsilon) && floatEquals(z, o.z, epsilon); } @Override public boolean equals(Object o) { if (o.getClass() != Vector3.class) return false; return equals((Vector3) o, EPSILON); } @Override public int hashCode() { return Objects.hash((int)(x*250), (int)(y*250), (int)(z*250)); } @Override public String toString() { return String.format("[%.3f, %.3f, %.3f]", x, y, z); } }
true
d379ff90a99ee015ad50e1bb2c7f5e111625d06d
Java
toysant/mariomakergame
/src/util/utility/EditModeSettingsMenuConfirmButton.java
UTF-8
1,756
2.484375
2
[]
no_license
package util.utility; import util.Button; import util.Derivative; import util.Elements; import util.InfoPack; import java.util.ArrayList; import java.util.List; public class EditModeSettingsMenuConfirmButton extends Button { private int size; List<Elements> linkedList=new ArrayList<Elements>(); public EditModeSettingsMenuConfirmButton(){ setResource("Confirm"); setResourcetype("String"); setLength(230); } @Override public Derivative click(InfoPack pack) { pack.setMode("EditMode"); linkedList.forEach(elements -> { if (elements instanceof StringButton){ if (((StringButton)elements).getResourcename().equals("maxx")){ pack.setMaxx(Integer.parseInt(elements.getResource())); if (pack.getMaxx()>0) { pack.setXoffsetable(true); } } if (((StringButton)elements).getResourcename().equals("maxy")){ pack.setMaxy(Integer.parseInt(elements.getResource())); if (pack.getMaxy()>0) { pack.setYoffsetable(true); } } if (((StringButton)elements).getResourcename().equals("filename")){ pack.setConstructPack(new EditPack(100,"./res/assembly/"+elements.getResource()+".xml")); } } }); pack.setViewswitch(true); pack.setModeswitch(true); pack.setView(""); return null; } @Override public void hover() { } public void addLinked(Elements e){ linkedList.add(e); } }
true
d725c1ac30afef12a748e0ef0f99704ea212733c
Java
alpapad/ahome-titanium
/ahome-titanium/src/com/ait/toolkit/titanium/mobile/client/ui/interfaces/HasInteractionHandler.java
UTF-8
15,533
1.9375
2
[ "Apache-2.0" ]
permissive
/* Copyright (c) 2014 Ahomé Innovation Technologies. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ait.toolkit.titanium.mobile.client.ui.interfaces; import com.ait.toolkit.titanium.mobile.client.core.handlers.ui.BlurHandler; import com.ait.toolkit.titanium.mobile.client.core.handlers.ui.CallbackRegistration; import com.ait.toolkit.titanium.mobile.client.core.handlers.ui.ClickHandler; import com.ait.toolkit.titanium.mobile.client.core.handlers.ui.DoubleClickHandler; import com.ait.toolkit.titanium.mobile.client.core.handlers.ui.DoubleTapHandler; import com.ait.toolkit.titanium.mobile.client.core.handlers.ui.FocusHandler; import com.ait.toolkit.titanium.mobile.client.core.handlers.ui.InteractionHandler; import com.ait.toolkit.titanium.mobile.client.core.handlers.ui.LongClickHandler; import com.ait.toolkit.titanium.mobile.client.core.handlers.ui.LongPressHandler; import com.ait.toolkit.titanium.mobile.client.core.handlers.ui.SingleTapHandler; import com.ait.toolkit.titanium.mobile.client.core.handlers.ui.SwipeHandler; import com.ait.toolkit.titanium.mobile.client.core.handlers.ui.TouchEndHandler; import com.ait.toolkit.titanium.mobile.client.core.handlers.ui.TouchMoveHandler; import com.ait.toolkit.titanium.mobile.client.core.handlers.ui.TouchStartHandler; import com.ait.toolkit.titanium.mobile.client.core.handlers.ui.TwoFingerTapHandler; public interface HasInteractionHandler { public CallbackRegistration addClickHandler(ClickHandler handler) /*-{ var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()(); var listener = function(e) { var eventObject = @com.ait.toolkit.titanium.mobile.client.core.events.ui.ClickEvent::new(Lcom/google/gwt/core/client/JavaScriptObject;)(e); handler.@com.ait.toolkit.titanium.mobile.client.core.handlers.ui.ClickHandler::onClick(Lcom/ait/toolkit/titanium/mobile/client/core/events/ui/DashboardItemClickEvent;)(eventObject); }; var name = @com.ait.toolkit.titanium.mobile.client.core.events.ui.ClickEvent::EVENT_NAME; var v = jso .addEventListener( name, listener); var toReturn = @com.ait.toolkit.titanium.mobile.client.core.handlers.ui.CallbackRegistration::new(Lcom/ait/toolkit/titanium/mobile/client/core/events/EventDispatcher;Ljava/lang/String;Lcom/google/gwt/core/client/JavaScriptObject;)(this,name,listener); return toReturn; }-*/; public CallbackRegistration addDoubleClickHandler(DoubleClickHandler handler)/*-{ var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()(); var listener = function(e) { var eventObject = @com.ait.toolkit.titanium.mobile.client.core.events.ui.DoubleClickEvent::new(Lcom/google/gwt/core/client/JavaScriptObject;)(e); handler.@com.ait.toolkit.titanium.mobile.client.core.handlers.ui.DoubleClickHandler::onDoubleClick(Lcom/ait/toolkit/titanium/mobile/client/core/events/ui/DoubleClickEvent;)(eventObject); }; var name = @com.ait.toolkit.titanium.mobile.client.core.events.ui.DoubleClickEvent::EVENT_NAME; var v = jso .addEventListener( name, listener); var toReturn = @com.ait.toolkit.titanium.mobile.client.core.handlers.ui.CallbackRegistration::new(Lcom/ait/toolkit/titanium/mobile/client/core/events/EventDispatcher;Ljava/lang/String;Lcom/google/gwt/core/client/JavaScriptObject;)(this,name,listener); return toReturn; }-*/; public CallbackRegistration addDoubleTapHandler(DoubleTapHandler handler)/*-{ var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()(); var listener = function(e) { var eventObject = @com.ait.toolkit.titanium.mobile.client.core.events.ui.DoubleTapEvent::new(Lcom/google/gwt/core/client/JavaScriptObject;)(e); handler.@com.ait.toolkit.titanium.mobile.client.core.handlers.ui.DoubleTapHandler::onDoubleTap(Lcom/ait/toolkit/titanium/mobile/client/core/events/ui/DoubleTapEvent;)(eventObject); }; var name = @com.ait.toolkit.titanium.mobile.client.core.events.ui.DoubleTapEvent::EVENT_NAME; var v = jso .addEventListener( name, listener); var toReturn = @com.ait.toolkit.titanium.mobile.client.core.handlers.ui.CallbackRegistration::new(Lcom/ait/toolkit/titanium/mobile/client/core/events/EventDispatcher;Ljava/lang/String;Lcom/google/gwt/core/client/JavaScriptObject;)(this,name,listener); return toReturn; }-*/; public CallbackRegistration addLongClickHandler(LongClickHandler handler)/*-{ var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()(); var listener = function(e) { var eventObject = @com.ait.toolkit.titanium.mobile.client.core.events.ui.LongClickEvent::new(Lcom/google/gwt/core/client/JavaScriptObject;)(e); handler.@com.ait.toolkit.titanium.mobile.client.core.handlers.ui.LongClickHandler::onLongClick(Lcom/ait/toolkit/titanium/mobile/client/core/events/ui/LongClickEvent;)(eventObject); }; var name = @com.ait.toolkit.titanium.mobile.client.core.events.ui.LongClickEvent::EVENT_NAME; var v = jso .addEventListener( name, listener); var toReturn = @com.ait.toolkit.titanium.mobile.client.core.handlers.ui.CallbackRegistration::new(Lcom/ait/toolkit/titanium/mobile/client/core/events/EventDispatcher;Ljava/lang/String;Lcom/google/gwt/core/client/JavaScriptObject;)(this,name,listener); return toReturn; }-*/; public CallbackRegistration addLongPressHandler(LongPressHandler handler)/*-{ var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()(); var listener = function(e) { var eventObject = @com.ait.toolkit.titanium.mobile.client.core.events.ui.LongPressEvent::new(Lcom/google/gwt/core/client/JavaScriptObject;)(e); handler.@com.ait.toolkit.titanium.mobile.client.core.handlers.ui.LongPressHandler::onLongPress(Lcom/ait/toolkit/titanium/mobile/client/core/events/ui/LongPressEvent;)(eventObject); }; var name = @com.ait.toolkit.titanium.mobile.client.core.events.ui.LongPressEvent::EVENT_NAME; var v = jso .addEventListener( name, listener); var toReturn = @com.ait.toolkit.titanium.mobile.client.core.handlers.ui.CallbackRegistration::new(Lcom/ait/toolkit/titanium/mobile/client/core/events/EventDispatcher;Ljava/lang/String;Lcom/google/gwt/core/client/JavaScriptObject;)(this,name,listener); return toReturn; }-*/; public CallbackRegistration addSingleTapHandler(SingleTapHandler handler)/*-{ var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()(); var listener = function(e) { var eventObject = @com.ait.toolkit.titanium.mobile.client.core.events.ui.SingleTapEvent::new(Lcom/google/gwt/core/client/JavaScriptObject;)(e); handler.@com.ait.toolkit.titanium.mobile.client.core.handlers.ui.SingleTapHandler::onSingleTap(Lcom/ait/toolkit/titanium/mobile/client/core/events/ui/SingleTapEvent;)(eventObject); }; var name = @com.ait.toolkit.titanium.mobile.client.core.events.ui.SingleTapEvent::EVENT_NAME; var v = jso .addEventListener( name, listener); var toReturn = @com.ait.toolkit.titanium.mobile.client.core.handlers.ui.CallbackRegistration::new(Lcom/ait/toolkit/titanium/mobile/client/core/events/EventDispatcher;Ljava/lang/String;Lcom/google/gwt/core/client/JavaScriptObject;)(this,name,listener); return toReturn; }-*/; public CallbackRegistration addSwipeHandler(SwipeHandler handler)/*-{ var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()(); var listener = function(e) { var eventObject = @com.ait.toolkit.titanium.mobile.client.core.events.ui.SwipeEvent::new(Lcom/google/gwt/core/client/JavaScriptObject;)(e); handler.@com.ait.toolkit.titanium.mobile.client.core.handlers.ui.SwipeHandler::onSwipe(Lcom/ait/toolkit/titanium/mobile/client/core/events/ui/SwipeEvent;)(eventObject); }; var name = @com.ait.toolkit.titanium.mobile.client.core.events.ui.SwipeEvent::EVENT_NAME; var v = jso .addEventListener( name, listener); var toReturn = @com.ait.toolkit.titanium.mobile.client.core.handlers.ui.CallbackRegistration::new(Lcom/ait/toolkit/titanium/mobile/client/core/events/EventDispatcher;Ljava/lang/String;Lcom/google/gwt/core/client/JavaScriptObject;)(this,name,listener); return toReturn; }-*/; public CallbackRegistration addTouchCancelHandler(InteractionHandler handler)/*-{ var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()(); var listener = function(e) { var eventObject = @com.ait.toolkit.titanium.mobile.client.core.events.ui.TouchCancelEvent::new(Lcom/google/gwt/core/client/JavaScriptObject;)(e); handler.@com.ait.toolkit.titanium.mobile.client.core.handlers.ui.TouchCancelHandler::onCancel(Lcom/ait/toolkit/titanium/mobile/client/core/events/ui/TouchCancelEvent;)(eventObject); }; var name = @com.ait.toolkit.titanium.mobile.client.core.events.ui.TouchCancelEvent::EVENT_NAME; var v = jso .addEventListener( name, listener); var toReturn = @com.ait.toolkit.titanium.mobile.client.core.handlers.ui.CallbackRegistration::new(Lcom/ait/toolkit/titanium/mobile/client/core/events/EventDispatcher;Ljava/lang/String;Lcom/google/gwt/core/client/JavaScriptObject;)(this,name,listener); return toReturn; }-*/; public CallbackRegistration addTouchEndHandler(TouchEndHandler handler) /*-{ var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()(); var listener = function(e) { var eventObject = @com.ait.toolkit.titanium.mobile.client.core.events.ui.TouchEndEvent::new(Lcom/google/gwt/core/client/JavaScriptObject;)(e); handler.@com.ait.toolkit.titanium.mobile.client.core.handlers.ui.TouchEndHandler::onTouchEnd(Lcom/ait/toolkit/titanium/mobile/client/core/events/ui/TouchEndEvent;)(eventObject); }; var name = @com.ait.toolkit.titanium.mobile.client.core.events.ui.TouchEndEvent::EVENT_NAME; var v = jso .addEventListener( name, listener); var toReturn = @com.ait.toolkit.titanium.mobile.client.core.handlers.ui.CallbackRegistration::new(Lcom/ait/toolkit/titanium/mobile/client/core/events/EventDispatcher;Ljava/lang/String;Lcom/google/gwt/core/client/JavaScriptObject;)(this,name,listener); return toReturn; }-*/; public CallbackRegistration addTouchMoveHandler(TouchMoveHandler handler)/*-{ var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()(); var listener = function(e) { var eventObject = @com.ait.toolkit.titanium.mobile.client.core.events.ui.TouchMoveEvent::new(Lcom/google/gwt/core/client/JavaScriptObject;)(e); handler.@com.ait.toolkit.titanium.mobile.client.core.handlers.ui.TouchMoveHandler::onTouchMove(Lcom/ait/toolkit/titanium/mobile/client/core/events/ui/TouchMoveEvent;)(eventObject); }; var name = @com.ait.toolkit.titanium.mobile.client.core.events.ui.TouchMoveEvent::EVENT_NAME; var v = jso .addEventListener( name, listener); var toReturn = @com.ait.toolkit.titanium.mobile.client.core.handlers.ui.CallbackRegistration::new(Lcom/ait/toolkit/titanium/mobile/client/core/events/EventDispatcher;Ljava/lang/String;Lcom/google/gwt/core/client/JavaScriptObject;)(this,name,listener); return toReturn; }-*/; public CallbackRegistration addTouchStartHandler(TouchStartHandler handler)/*-{ var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()(); var listener = function(e) { var eventObject = @com.ait.toolkit.titanium.mobile.client.core.events.ui.TouchStartEvent::new(Lcom/google/gwt/core/client/JavaScriptObject;)(e); handler.@com.ait.toolkit.titanium.mobile.client.core.handlers.ui.TouchStartHandler::onTouchStart(Lcom/ait/toolkit/titanium/mobile/client/core/events/ui/TouchStartEvent;)(eventObject); }; var name = @com.ait.toolkit.titanium.mobile.client.core.events.ui.TouchStartEvent::EVENT_NAME; var v = jso .addEventListener( name, listener); var toReturn = @com.ait.toolkit.titanium.mobile.client.core.handlers.ui.CallbackRegistration::new(Lcom/ait/toolkit/titanium/mobile/client/core/events/EventDispatcher;Ljava/lang/String;Lcom/google/gwt/core/client/JavaScriptObject;)(this,name,listener); return toReturn; }-*/; public CallbackRegistration addTwoFingerTapHandler(TwoFingerTapHandler handler)/*-{ var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()(); var listener = function(e) { var eventObject = @com.ait.toolkit.titanium.mobile.client.core.events.ui.TwoFingerTapEvent::new(Lcom/google/gwt/core/client/JavaScriptObject;)(e); handler.@com.ait.toolkit.titanium.mobile.client.core.handlers.ui.TwoFingerTapHandler::onTwoFingerTap(Lcom/ait/toolkit/titanium/mobile/client/core/events/ui/TwoFingerTapEvent;)(eventObject); }; var name = @com.ait.toolkit.titanium.mobile.client.core.events.ui.TwoFingerTapEvent::EVENT_NAME; var v = jso .addEventListener( name, listener); var toReturn = @com.ait.toolkit.titanium.mobile.client.core.handlers.ui.CallbackRegistration::new(Lcom/ait/toolkit/titanium/mobile/client/core/events/EventDispatcher;Ljava/lang/String;Lcom/google/gwt/core/client/JavaScriptObject;)(this,name,listener); return toReturn; }-*/; public CallbackRegistration addFocusHandler(FocusHandler handler)/*-{ var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()(); var listener = function(e) { var eventObject = @com.ait.toolkit.titanium.mobile.client.core.events.ui.FocusEvent::new(Lcom/google/gwt/core/client/JavaScriptObject;)(e); handler.@com.ait.toolkit.titanium.mobile.client.core.handlers.ui.FocusHandler::onFocus(Lcom/ait/toolkit/titanium/mobile/client/core/events/ui/FocusEvent;)(eventObject); }; var name = @com.ait.toolkit.titanium.mobile.client.core.events.ui.FocusEvent::EVENT_NAME; var v = jso.addEventListener(name, listener); var toReturn = @com.ait.toolkit.titanium.mobile.client.core.handlers.ui.CallbackRegistration::new(Lcom/ait/toolkit/titanium/mobile/client/core/events/EventDispatcher;Ljava/lang/String;Lcom/google/gwt/core/client/JavaScriptObject;)(this,name,listener); return toReturn; }-*/; public CallbackRegistration addBlurHandler(BlurHandler handler)/*-{ var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()(); var listener = function(e) { var eventObject = @com.ait.toolkit.titanium.mobile.client.core.events.ui.BlurEvent::new(Lcom/google/gwt/core/client/JavaScriptObject;)(e); handler.@com.ait.toolkit.titanium.mobile.client.core.handlers.ui.BlurHandler::onBlur(Lcom/ait/toolkit/titanium/mobile/client/core/events/ui/BlurEvent;)(eventObject); }; var name = @com.ait.toolkit.titanium.mobile.client.core.events.ui.BlurEvent::EVENT_NAME; var v = jso.addEventListener(name, listener); var toReturn = @com.ait.toolkit.titanium.mobile.client.core.handlers.ui.CallbackRegistration::new(Lcom/ait/toolkit/titanium/mobile/client/core/events/EventDispatcher;Ljava/lang/String;Lcom/google/gwt/core/client/JavaScriptObject;)(this,name,listener); return toReturn; }-*/; }
true
9168a7fb4328f053f2ef806d6b8ad72854ca7d89
Java
binteezyy/OOP-Cellphone
/src/cellphone/PanganibanACM_LiveExerCellphone.java
UTF-8
3,208
2.921875
3
[]
no_license
package cellphone; import javax.swing.JOptionPane; public class PanganibanACM_LiveExerCellphone { public static void main(String[] args) { String number = ""; String error = ""; do { number = (String) JOptionPane.showInputDialog(null, error + "Enter your number: ", "Cellphone", JOptionPane.DEFAULT_OPTION, null, null,"09167618265"); if (number.isEmpty()) { System.exit(0); } try { long n = Long.parseLong(number); } catch (NumberFormatException | NullPointerException e) { error += "Invalid number! \n"; continue; } if(number.length() == 11) { break; } else { error += "Invalid number! \n"; } }while(true); Cellphone cp = new Cellphone(); cp.number = number; String choices[] = {"Re-Load", "Text/Message", "Check Balance", "Pasa-Load", "Exit"}; String title = cp.number; String input = ""; do { String choice = (String) JOptionPane.showInputDialog(null, "Choose one", title , JOptionPane.DEFAULT_OPTION, null, choices, choices[0]); if (choice.equals("Re-Load")) { try { input = (String) JOptionPane.showInputDialog(null, "Enter amount: ", title, JOptionPane.DEFAULT_OPTION, null, null,"amount"); if (input.isEmpty()) { continue; } cp.paLoad(Integer.parseInt(input), title); } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "Invalid input!", title, 0); } } else if (choice.equals("Text/Message")) { input = (String) JOptionPane.showInputDialog(null, "Enter message: ", title, JOptionPane.DEFAULT_OPTION, null, null,"msg"); if (input.isEmpty()) { continue; } try { number = (String) JOptionPane.showInputDialog(null, "To: ", title, JOptionPane.DEFAULT_OPTION, null, null,"number"); if (number.isEmpty()) { continue; } cp.txt(input, Integer.parseInt(number), title); } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "Invalid number!", title, 0); } } else if (choice.equals("Check Balance")) { cp.chkbal(title); } else if (choice.equals("Pasa-Load")) { int inp = 0; input = (String) JOptionPane.showInputDialog(null, "Enter amount: ", title, JOptionPane.DEFAULT_OPTION, null, null,"amount"); if (input.isEmpty()) { continue; } try { inp = Integer.parseInt(input); }catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "Invalid number!", title, 0); continue; } try { number = (String) JOptionPane.showInputDialog(null, "To: ", title, JOptionPane.DEFAULT_OPTION, null, null,"number"); if (number.isEmpty()) { continue; } } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "Invalid number!", title, 0); continue; } long num = 0; try { num = Long.parseLong(number); }catch (NumberFormatException | NullPointerException e) { JOptionPane.showMessageDialog(null, "Invalid number!", title, 0); continue; } if (number.length() == 11) { cp.pasaLoad(Integer.parseInt(input), num, title); } else { JOptionPane.showMessageDialog(null, "Invalid number!", title, 0); } } else { System.out.println("Exit normally !"); break; } } while(true); } }
true
c20fc0d7d0569e28c82ba29a17e8a2681a5a9745
Java
darsh2311/Test
/Test/src/test/resources/logicalView/ReadWriteDataExcel.java
UTF-8
2,792
2.4375
2
[]
no_license
package logicalView; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.openqa.selenium.support.PageFactory; import commonFunctions.ApplicationUtility; import testObjects.Loginobject; public class ReadWriteDataExcel extends ApplicationUtility{ static XSSFWorkbook workbook; static XSSFCell cell; static XSSFSheet sheet; public static void ReadWriteDataMethod() throws InterruptedException, IOException { Loginobject loginpage = PageFactory.initElements(driver, Loginobject.class); //Create an file object to open the excel file File excelfile=new File(System.getProperty("user.dir")+"\\src\\testData\\Testdata.xlsx"); //To load the file FileInputStream fileinput=new FileInputStream(excelfile); //load the workbook workbook =new XSSFWorkbook(fileinput); //load the sheet sheet = workbook.getSheetAt(0); for (int i=1 ; i<= sheet.getLastRowNum();i++) { //to load the row and cell no. of Username cell = sheet.getRow(i).getCell(1); cell.setCellType(Cell.CELL_TYPE_STRING); //Load the value of the Username loginpage.setEmailclear(); loginpage.setEmail(cell.getStringCellValue()); Thread.sleep(500); //to load the row and cell no. of Password cell = sheet.getRow(i).getCell(2); cell.setCellType(Cell.CELL_TYPE_STRING); //Load the value of the Password loginpage.setPasswordclear(); loginpage.setPassword(cell.getStringCellValue()); Thread.sleep(500); //To submit the entered data loginpage.setsubmitButton(); String title = driver.getPageSource(); // For writing data to the File FileOutputStream fos=new FileOutputStream(excelfile); //Condition to check the success message is correct or not to write the status as Pass if(title.contains("Welcome")) { //To set the value of the cell sheet.getRow(i).createCell(3).setCellValue(ApplicationUtility.getValueFromPropertyFile("Status_Pass")); workbook.write(fos); loginpage.setprofileDropdown(); Thread.sleep(500); loginpage.setSignoutButton(); Thread.sleep(500); } //If the condition is not correct then it will write Fail in the particular cell of testcase else { sheet.getRow(i).createCell(3).setCellValue(ApplicationUtility.getValueFromPropertyFile("Status_Fail")); workbook.write(fos); driver.get(ApplicationUtility.getValueFromPropertyFile("Url")); } } Thread.sleep(2000); //To close the browser driver.quit(); } }
true
7b26aaa0bd25555a229aaf7ad3284298cad708bb
Java
yuris7/java_pft
/addressbook-web-tests/src/test/java/ua/stqa/pft/addressbook/tests/ContactCreationTests.java
UTF-8
716
2.15625
2
[ "Apache-2.0" ]
permissive
package ua.stqa.pft.addressbook.tests; import org.testng.Assert; import org.testng.annotations.Test; import ua.stqa.pft.addressbook.model.ContactData; public class ContactCreationTests extends TestBase { @Test public void testContactCreation() { app.getNavigationHelper().gotoHomePage(); int before = app.getContactHelper().getContactCount(); app.getContactHelper().initContactCreation(); app.getContactHelper().fillContactForm(new ContactData("first name", "last name", "test1"), true); app.getContactHelper().submitContactCreation(); app.getContactHelper().returnHomePage(); int after = app.getContactHelper().getContactCount(); Assert.assertEquals(before, after - 1); } }
true
59e8bbcd9b00758545637ecf0c7ba9c09412b89e
Java
alexcwyu/algotrader
/algotrader-provider/algotrader-provider-ib/src/main/java/com/unisoft/algotrader/provider/ib/OrderRecord.java
UTF-8
645
2.421875
2
[]
no_license
package com.unisoft.algotrader.provider.ib; import com.unisoft.algotrader.model.event.execution.Order; /** * Created by alex on 9/17/15. */ public class OrderRecord { public Order order; public double filledQty; public double leaveQty; public double avgPrice; public OrderRecord(Order order){ this.order = order; leaveQty = order.ordQty; filledQty = 0; avgPrice = 0; } public void addFill(double lastPrice, double lastQty){ avgPrice = (avgPrice * filledQty + lastPrice * lastQty) / (lastQty+ filledQty); filledQty += lastQty; leaveQty -= lastQty; } }
true
1d5db31cd970c5952c4f2c3d4b8dcc82f1a6e497
Java
shadow-fire/cDHCP
/Source Code/src/DHCPServer.java
WINDOWS-1258
12,431
2.71875
3
[]
no_license
import java.io.*; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; /** * This class represents a C-DHCP server. * @author Tanushree & Mrunal * @version 1.0 */ public class DHCPServer { private static final int MAX_BUFFER_SIZE = 1024; private int listenPort = 1067; private static LinkedList<String> ipPool= new LinkedList<String>();//to maintain a pool of available IP addresses. private static HashMap<String,String> ipInfo = new HashMap<String,String>();//to store the paramters allocated to client. private static DatagramPacket p; private static String subnet1,subnet2;//The C-DHCP server is initialized with 2 subnets. private static String CMD; /*Constructor*/ public DHCPServer() { //Initialising the C-DHCP server with 2 sub-nets and a maximum of 25 class C IP addresses try { BufferedReader br = new BufferedReader(new FileReader("input.txt")); subnet1 = br.readLine(); subnet2 = br.readLine(); String line= br.readLine(); while(line != null) { ipPool.add(line); line = br.readLine(); } br.close(); } catch(FileNotFoundException fe) { System.out.println("File not found"); } catch(IOException ioe) { System.out.println("Cant read from file"); } //The first ip address in ipPool is assigned to the server. String s_ip = ipPool.get(0); ipPool.remove(s_ip); System.out.println("Server ip: "+s_ip+"\n"); CMD = "netsh int ip set address name = \"Wireless Network Connection\" source = static addr = "+s_ip+" mask = 255.255.255.0"; try { Runtime.getRuntime().exec(CMD); } catch (IOException e2) { e2.printStackTrace(); } DatagramSocket socket = null; try { socket = new DatagramSocket(listenPort); p = new DatagramPacket(new byte[MAX_BUFFER_SIZE], 50); System.out.println("Listening on port " + listenPort + "..."); while (true) { //Server gets DHCP discovery msg socket.receive(p); /*Thread ser = new Thread(){ public void run(){ } }; ser.start();*/ System.out.println("Connection established from " + p.getAddress()); System.out.println("\nDHCP Discovery: " + Arrays.toString(p.getData())); byte op = p.getData()[0];//retrieving opcode from the DHCPDISCOVER message if(op ==1)System.out.println("\nDHCP release recieved"); if(op ==5)System.out.println("\nRequest is for IP"); if(op ==9)System.out.println("\nRequest is for Subnet"); if(op ==13)System.out.println("\nRequest is for IP and Subnet"); byte[] xid = new byte[4]; for (int i=0; i < 4; i++) xid[i] = p.getData()[4+i]; byte[] mac = new byte[6]; for (int i=0; i < 6; i++)mac[i]=p.getData()[24+i]; byte[] ip = new byte[4]; for (int i=0; i < 4; i++) ip[i]=p.getData()[16+i]; if(op == 1)//DHCPRELEASE message sent by the client. { /* Removing the configuration information from ipInfo Hash Map and adding the ip back to the ipPool*/ ipInfo.remove(DHCPMessage.byteArrayToHex(xid)+","+ DHCPMessage.byteArrayToHex(mac)); String ip_free = ip[0]+"."+ip[1]+"."+ip[2]+"."+ip[3]; ipPool.add(ip_free); p.getData()[0] = (byte)(p.getData()[0] + 1);//BOOTREPLY for (int i=0; i < 4; i++) p.getData()[12+i]=p.getData()[16+i]=0;//setting yiaddr to 0.0.0.0 byte[] s_ip_b = InetAddress.getByName(s_ip).getAddress(); for (int i=0; i < 4; i++) p.getData()[20+i]= s_ip_b[i]; p.getData()[36] = (byte) 5;//DHCPNACK socket.send(p); System.out.println("DHCP Ack: " + Arrays.toString(p.getData())); } if(op == 9)//Client requests for subnet mask. { p.getData()[0] = (byte)(p.getData()[0] + 1);//BOOTREPLY_S p.getData()[36] = (byte)2;//message type = DHCPOFFER //Set siaddr field of DHCPOFFER message byte[] s_ip_b; try { s_ip_b = InetAddress.getByName(s_ip).getAddress(); for (int i=0; i < 4; i++) p.getData()[20+i]= s_ip_b[i]; } catch (UnknownHostException e1) { e1.printStackTrace(); } int c=0; byte[] ciaddr = new byte[4]; for (int i=0; i < 4; i++) { ciaddr[i] = p.getData()[12+i]; if(p.getData()[12+i] == 0) c++; } if(c == 4)//ciaddr == 0.0.0.0 (invalid) { p.getData()[36] = (byte) 6;//message type = DHCPNACK. socket.send(p); System.out.println("DHCP Nack: " + Arrays.toString(p.getData())); } else { byte[] subnet = new byte[4]; subnet = getSubnetMask(ciaddr[3]); int d =0; for(int i=0;i<4;i++) { if(subnet[i] == 0) d++; } System.out.println("Subnet Mask=" + (subnet[0]& 0xFF)+"."+(subnet[1]& 0xFF)+"."+(subnet[2]& 0xFF)+"."+(subnet[3]& 0xFF)+"\n"); if(d == 4)//If the client's ip doesnt lie in one of the 2 subnets offered by the server, a DHCPNACK is sent to the client. { p.getData()[36]=(byte)6; socket.send(p); System.out.println("DHCP Nack: " + Arrays.toString(p.getData())); System.exit(0); } for (int i =0;i<4;i++) p.getData()[39+i] = subnet[i];//setting the subnet mask in the options field. socket.send(p); System.out.println("DHCP Offer: " + Arrays.toString(p.getData())); socket.receive(p); System.out.println("DHCP Request: " + Arrays.toString(p.getData())); p.getData()[0] = (byte) (p.getData()[0]+1);//BOOTPREPLY_S p.getData()[10] = (byte) 128;//set broadcast bit to 1. p.getData()[36]= (byte) 5;//message type = DHCPACK. socket.send(p); System.out.println("DHCP Ack: " + Arrays.toString(p.getData())); } } if(op == 13 | op == 5)//request for IP address or IP address and subnet mask { if(ipPool.size() >1)//IP address is available with the server to be allocated to the client. { //Sending DHCPOFFER to client offerMsg(op,s_ip); p.setPort(1068); socket.send(p); System.out.println("DHCP Offer: " + Arrays.toString(p.getData())); //Receiving DHCPREQUEST from the client socket.receive(p); System.out.println("DHCP Request: " + Arrays.toString(p.getData())); //Server sending DHCPACK to client p.getData()[0] = (byte) (p.getData()[0]+1);//BOOTPREPLY p.getData()[10] = (byte) 128;//set broadcast bit to 1. p.getData()[36]= (byte) (p.getData()[36]+2);//message type = DHCPACK. String key = DHCPMessage.byteArrayToHex(xid)+","+ DHCPMessage.byteArrayToHex(mac) ;// key = xid,hardware address. byte[] ipaddr = new byte[4]; for (int i=0; i < 4; i++) ipaddr[i]=p.getData()[16+i]; String val = (ipaddr[0] & 0xff)+"."+(ipaddr[1] & 0xff)+"."+(ipaddr[2] & 0xff)+"."+(ipaddr[3] & 0xff); ipInfo.put(key,val);//storing allocated parameters in ipInfo Hash Map. ipPool.remove(val);//removing ip from free ip pool. System.out.println("key: "+key + "\t" + "Value: " + ipInfo.get(key)); socket.send(p); System.out.println("DHCP Ack: " + Arrays.toString(p.getData())); } else{ /*DHCPNACK sent to client if no free ip is available*/ p.getData()[0] = (byte)(p.getData()[0]+1); p.getData()[36] = (byte)6; socket.send(p); System.out.println("DHCP Nack: " + Arrays.toString(p.getData())); } } } } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * offerMsg() : Offer message sent by server. * @param op,s_ip: opcode and server ip address * @exception Unknown Host Exception * @see UnknownHostException */ public static void offerMsg(byte op,String s_ip) throws UnknownHostException { String ip; //Set siaddr field of DHCPOFFER message byte[] s_ip_b; try { s_ip_b = InetAddress.getByName(s_ip).getAddress(); for (int i=0; i < 4; i++) p.getData()[20+i]= s_ip_b[i]; } catch (UnknownHostException e1) { e1.printStackTrace(); } //Set yiaddr field of DHCPOFFER message ip = ipPool.get(0); ipPool.remove(ip); ipPool.addLast(ip); System.out.println("\nIP offered:"+ip+"\n"); byte[] ip_b; try { ip_b = InetAddress.getByName(ip).getAddress(); for (int i=0; i < 4; i++) p.getData()[16+i]= ip_b[i]; } catch (UnknownHostException e) { e.printStackTrace(); } if(op == 13)//Client has requested for both ip and subnet mask. { byte[] subnet = new byte[4]; subnet = getSubnetMask(p.getData()[19]); System.out.println("Subnet Mask=" + (subnet[0]& 0xFF)+"."+(subnet[1]& 0xFF)+"."+(subnet[2]& 0xFF)+"."+(subnet[3]& 0xFF)+"\n"); for (int i =0;i<4;i++) p.getData()[39+i] = subnet[i]; } if(op == 13 | op ==9)//Subnet request { p.getData()[43] = (byte) 51; p.getData()[44] = (byte) 4; for(int i=0;i<4;i++)p.getData()[45+i] = (byte) 0xff; p.getData()[49] = (byte) 0xff; } else { p.getData()[37] = (byte) 51; p.getData()[38] = (byte) 4; for(int i=0;i<4;i++)p.getData()[39+i] = (byte) 0xff; p.getData()[43] = (byte) 0xff; } p.getData()[0]= (byte) (op+1);//change op to BOOTPREPLY p.getData()[36]= (byte) (2);//change message type to DHCPOFFER } /** * getSubnetMask method returns the subnet of the client ip address. * @param ciaddr last octet of client ip address. * @return subnet mask in byte array form. */ public static byte[] getSubnetMask(byte ciaddr) throws UnknownHostException { System.out.println("\n"+subnet1 + "\t"+subnet2+"\n"); String[] parts1 = subnet1.split("/"); String ip1 = parts1[0]; int prefix1; if (parts1.length < 2) prefix1 = 0; else prefix1 = Integer.parseInt(parts1[1]); int mask1 = 0xffffffff << (32 - prefix1); int value1 = mask1; byte[] bytes1 = new byte[]{ (byte)(value1 >>> 24), (byte)(value1 >> 16 & 0xff), (byte)(value1 >> 8 & 0xff), (byte)(value1 & 0xff) }; String[] parts2 = subnet2.split("/"); String ip2 = parts2[0]; int prefix2; if (parts2.length < 2) prefix2 = 0; else prefix2 = Integer.parseInt(parts2[1]); int mask2 = 0xffffffff << (32 - prefix2); int value2 = mask2; byte[] bytes2 = new byte[]{ (byte)(value2 >>> 24), (byte)(value2 >> 16 & 0xff), (byte)(value2 >> 8 & 0xff), (byte)(value2 & 0xff) }; InetAddress netAddr1 = InetAddress.getByAddress(bytes1); System.out.println("Subnet Mask1=" + netAddr1.getHostAddress()+"\n"); InetAddress netAddr2 = InetAddress.getByAddress(bytes2); System.out.println("Subnet Mask2=" + netAddr2.getHostAddress()+"\n"); byte lastOct1 = InetAddress.getByName(ip1).getAddress()[3]; byte lastOct2 = InetAddress.getByName(ip2).getAddress()[3]; String s1 = toBinary(new byte[]{lastOct1}); String s2 = toBinary(new byte[]{lastOct2}); String p1 = s1.substring(0,prefix1-24); String p2 = s2.substring(0,prefix2-24); String c = toBinary(new byte[]{ciaddr}); if(c.startsWith(p1)) return (bytes1); else if(c.startsWith(p2)) return (bytes2); else return (new byte[]{0,0,0,0}); } /*Converts byte to binary string*/ public static String toBinary( byte[] bytes ) { StringBuilder sb = new StringBuilder(bytes.length * Byte.SIZE); for( int i = 0; i < Byte.SIZE * bytes.length; i++ ) sb.append((bytes[i / Byte.SIZE] << i % Byte.SIZE & 0x80) == 0 ? '0' : '1'); return sb.toString(); } public static void main(String[] args) { new DHCPServer(); } }
true
28aaf4ce019b57f3afe8a0cdc2b7b53ecbceffd1
Java
publicOlg/SolarimpactTelemety2
/src/myConnectables/MyButton.java
UTF-8
2,812
2.65625
3
[]
no_license
package myConnectables; import application.Main; import communication.Connectable; import communication.InfoPaket; import javafx.application.Platform; import javafx.event.EventHandler; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.Tooltip; import javafx.scene.input.MouseEvent; import java.util.ArrayList; /** * Created by fhopp on 30.06.2017. */ public class MyButton extends Button implements Connectable{ ArrayList<Connectable> connectables = new ArrayList<>(); private int id; private char sign; private void warning(){ Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error Dialog"); alert.setHeaderText("Send Process did not work!"); alert.setContentText("False input Value or missing Channel Information."); alert.showAndWait(); } public void addConnectale(Connectable connectable){ connectables.add(connectable); } public MyButton() { super(); this.setTooltip(new Tooltip("not connected")); id = Main.data.getIdForLabel(); if(Main.data.myLabelIsSet(id))setConnection(Main.data.getMyLabelReferenc(id)); setOnMouseClicked(new EventHandler<MouseEvent>(){ public void handle(MouseEvent event) { if(event.isPopupTrigger()) { sign = Main.controller.openSelectChannel(event.getScreenX(), event.getScreenY()); if (sign != Character.MIN_VALUE) { setConnection(sign); } return; } String message = sign + ""; for(int id = 0; id < connectables.size(); id++){ if(connectables.get(id).getValue().isEmpty()){ warning(); return; } message += connectables.get(id).getValue(); } Main.model.com.send(message); } }); } public InfoPaket setConnection(char sign){ Main.data.setMyLabelReferences(sign,id); this.sign = sign; this.getTooltip().setText(Main.model.getInfoPaketBySign(sign).getName() + " " + sign); return Connectable.super.setConnection(sign); } @Override public Connectable infoPaketDeleted() { Main.data.setMyLabelReferences(Character.MIN_VALUE,id); Platform.runLater(new Runnable() { @Override public void run() { getTooltip().setText("not connected"); } }); return this; } @Override public boolean send() { return false; } @Override public String getValue() { return null; } }
true
81549f7852c09090baa7e1bf233ed764db62d838
Java
luisrmac/services
/app/src/main/java/com/example/services/MyService.java
UTF-8
1,651
2.71875
3
[]
no_license
package com.example.services; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.util.Log; import java.util.Random; public class MyService extends Service { private static final String TAG = "MyService_TAG"; private boolean flag = false; private MyBinder binder = new MyBinder(); private Random generator = new Random(); public MyService() { } @Override public void onCreate() { super.onCreate(); Log.d(TAG, "onCreate: MyService is created"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(TAG, "onStartCommand: Service is started"); for(int i=0; i<1000; i++) { Log.d(TAG, "onStartCommand: working " + i); } // stopSelf(); // flag = true; // while(flag) { // // try { // Thread.sleep(1000); // Log.d(TAG, "onStartCommand: working..."); // } catch (InterruptedException ie) { // ie.printStackTrace(); // flag = false; // } // // } return START_NOT_STICKY; } @Override public IBinder onBind(Intent intent) { return binder; } @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy: service stopped and destroyed"); } public int getRandomNumber() { return generator.nextInt(100); } public class MyBinder extends Binder { MyService getService() { return MyService.this; } } }
true
526578e76bbf257f644f0c4647144e5e031695ec
Java
tfaneye/rs_comp_repo
/RSAcceptanceTest/src/test/java/com/online/rs/uk/rs_testSteps/SearchForAnItemTestSteps.java
UTF-8
1,582
2.421875
2
[]
no_license
package com.online.rs.uk.rs_testSteps; import com.online.rs.uk.pages.HomePage; import com.online.rs.uk.pages.SearchedItemDetailPage; import com.online.rs.uk.support.WorldHelper; import cucumber.api.DataTable; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import org.junit.Assert; import java.util.List; /** * Created by inet-tech on 10/01/18. */ public class SearchForAnItemTestSteps { private final WorldHelper helper; private HomePage homePage; private SearchedItemDetailPage searchItemDetailPage; public SearchForAnItemTestSteps(WorldHelper helper){ this.helper = helper; } @Given("^I am on the home page of the application$") public void iAmOnTheHomePageOfTheApplication() throws Throwable { homePage = helper .getBasePage() .loadHomePage(); } @When("^I search for an item by name$") public void iSearchForAnItemByName(DataTable table) throws Throwable { List<List<String>> productInfo = table.raw(); String itemName = productInfo.get(1).get(0); searchItemDetailPage = homePage .searchForAnItem(itemName); } @Then("^I should be able to see the Item price$") public void iShouldBeAbleToSeeTheItemPrice(DataTable table) throws Throwable { List<List<String>> productInfo = table.raw(); String itemPrice = productInfo.get(1).get(0); Assert.assertEquals("no such price", itemPrice, searchItemDetailPage.validateSearchedItem(itemPrice)); } }
true
2eb2dbb1014efd4e4bcf0ffa3cb0669aeb14aa4a
Java
mkolisnyk/aerial
/aerial/src/main/java/com/github/mkolisnyk/aerial/core/AerialGlobalProperties.java
UTF-8
591
1.546875
2
[ "Apache-2.0" ]
permissive
package com.github.mkolisnyk.aerial.core; public interface AerialGlobalProperties { String AERIAL_OUTPUT_FORMAT = "aerial.output.format"; String AERIAL_OUTPUT_CONFIG = "aerial.output.config"; String AERIAL_INPUT_FORMAT = "aerial.input.format"; String AERIAL_INPUT_CONFIG = "aerial.input.config"; String AERIAL_GEN_NWISE_SIZE = "aerial.gen.nwise.size"; String AERIAL_GEN_CUSTOM_CLASSES = "aerial.gen.custom.classes"; String AERIAL_TYPES_DATE_DEFAULT_FORMAT = "aerial.types.date.default"; String AERIAL_TYPES_CUSTOM_CLASSES = "aerial.types.custom.classes"; }
true
73241a5e6aca61c0a65b993eb2219c5b4797a112
Java
Bryan-Roy/Construccion_de_Software_1
/src/semana08/pratico/paleta/RegistroAnimal.java
UTF-8
9,021
2.28125
2
[]
no_license
/* * 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 semana08.pratico.paleta; import javax.swing.JOptionPane; /** * * @author BRYANROY */ public class RegistroAnimal extends javax.swing.JFrame { ListaAnimal lm = new ListaAnimal(); public RegistroAnimal() { initComponents(); setLocationRelativeTo(null); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jTextField2 = new javax.swing.JTextField(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); lblregisanimal = new javax.swing.JLabel(); btnregistrar = new javax.swing.JButton(); btnsiguiente = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); txtcodigo = new javax.swing.JTextField(); txtnombre = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); txtsexo = new javax.swing.JTextField(); btnsalir = new javax.swing.JButton(); jTextField2.setText("jTextField2"); jTextArea1.setColumns(20); jTextArea1.setRows(5); jScrollPane1.setViewportView(jTextArea1); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); lblregisanimal.setText(" REGISTRO DE ANIMALES"); getContentPane().add(lblregisanimal, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 10, -1, -1)); btnregistrar.setText("REGISTRAR"); btnregistrar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnregistrarActionPerformed(evt); } }); getContentPane().add(btnregistrar, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 230, -1, -1)); btnsiguiente.setText("SIGUIENTE"); btnsiguiente.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnsiguienteActionPerformed(evt); } }); getContentPane().add(btnsiguiente, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 230, -1, -1)); jLabel1.setText(" ANIMAL:"); getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 110, 70, 30)); jLabel2.setText(" CODIGO:"); getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 60, 70, 30)); txtcodigo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtcodigoActionPerformed(evt); } }); getContentPane().add(txtcodigo, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 60, 100, 30)); txtnombre.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtnombreActionPerformed(evt); } }); getContentPane().add(txtnombre, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 110, 100, 30)); jLabel3.setText(" SEXO:"); getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 170, 60, 30)); txtsexo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtsexoActionPerformed(evt); } }); getContentPane().add(txtsexo, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 170, 100, 30)); btnsalir.setText("SALIR"); btnsalir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnsalirActionPerformed(evt); } }); getContentPane().add(btnsalir, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 230, 80, -1)); pack(); }// </editor-fold>//GEN-END:initComponents private void btnregistrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnregistrarActionPerformed // TODO add your handling code here: String codigos=txtcodigo.getText(); String nombres=txtnombre.getText(); String sexos=txtsexo.getText(); lm.setAnimales(new Animal(codigos,nombres,sexos)); txtcodigo.setText(""); txtnombre.setText(""); txtsexo.setText(""); mensajeAlerta("ANIMAL REGISTRADO","REGISTRO"); }//GEN-LAST:event_btnregistrarActionPerformed private void btnsiguienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnsiguienteActionPerformed // TODO add your handling code here: //txamostrar.setText(); lm.setVisible(true); this.dispose(); }//GEN-LAST:event_btnsiguienteActionPerformed private void txtsexoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtsexoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtsexoActionPerformed private void txtcodigoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtcodigoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtcodigoActionPerformed private void txtnombreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtnombreActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtnombreActionPerformed private void btnsalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnsalirActionPerformed // TODO add your handling code here: dispose(); }//GEN-LAST:event_btnsalirActionPerformed public static void mensajeAlerta(String mensaje, String titulo){ JOptionPane.showMessageDialog(null, mensaje, titulo, JOptionPane.INFORMATION_MESSAGE); } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(RegistroAnimal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(RegistroAnimal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(RegistroAnimal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(RegistroAnimal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new RegistroAnimal().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnregistrar; private javax.swing.JButton btnsalir; private javax.swing.JButton btnsiguiente; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTextArea1; private javax.swing.JTextField jTextField2; private javax.swing.JLabel lblregisanimal; private javax.swing.JTextField txtcodigo; private javax.swing.JTextField txtnombre; private javax.swing.JTextField txtsexo; // End of variables declaration//GEN-END:variables }
true
ef7a9b40deee014a6784ede141d015dc08095685
Java
Nia292/tw-statistics
/src/main/java/com/thrallwars/statistics/config/ServiceConfig.java
UTF-8
960
2.046875
2
[]
no_license
package com.thrallwars.statistics.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpStatus; import org.springframework.web.client.HttpClientErrorException; import java.util.ArrayList; import java.util.List; @Data @Configuration @ConfigurationProperties(prefix = "thrallwars") public class ServiceConfig { private List<RconTarget> targets = new ArrayList<>(); private List<String> errorWebhookUrls = new ArrayList<>(); private List<String> infoWebhookUrls = new ArrayList<>(); public RconTarget findTarget(String name) { return targets.stream() .filter(rconTarget -> rconTarget.getName().equals(name)) .findAny() .orElseThrow(() -> new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Target " + name + " not configured!")); } }
true