text
stringlengths
10
2.72M
package com.halilayyildiz.game; import java.util.UUID; import lombok.Data; @Data public class BasePlayer { protected String id; protected String name; public BasePlayer() { this.id = UUID.randomUUID().toString(); } }
package com.vrktech.springboot.gitactivities.constants; import org.springframework.stereotype.Component; @Component public class GitConstants { public static final String GIT_REPOS_SUCCESS = "Retrieves the statistics of the given Repository And Successfully saved into DB"; public static final String GIT_RETRIEVES_SUCCESS = "Retrieves the statistics of the given Repository And Successfully saved into DB"; }
package com.tencent.mm.plugin.appbrand.config; import android.os.HandlerThread; import android.os.Looper; import android.util.Pair; import com.tencent.mm.ab.a.a; class r$5 implements Runnable { final /* synthetic */ String dhF; final /* synthetic */ boolean frH; final /* synthetic */ r$b frI; final /* synthetic */ boolean frJ; r$5(String str, boolean z, r$b r_b, boolean z2) { this.dhF = str; this.frH = z; this.frI = r_b; this.frJ = z2; } public final void run() { int i = 1; String str = this.dhF; boolean z = this.frH && r.sb(this.dhF); Pair a = r.a(str, z, new 1(this)); if (this.frI != null) { if (a.second != null) { if (((a) a.second).errType == 0 && ((a) a.second).errCode == 0) { i = 2; } else { i = 3; } } this.frI.e(i, a.first); } if (this.frJ) { try { ((HandlerThread) Looper.myLooper().getThread()).quit(); } catch (Exception e) { } } } }
package com.flutterwave.raveandroid.rave_cache.di; import android.content.Context; import android.content.SharedPreferences; import com.flutterwave.raveandroid.rave_core.di.UiScope; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; @Module public class CacheModule { private String RAVE_PAY = "ravepay"; @Provides @UiScope public SharedPreferences providesSharedPreferences(Context context) { return context.getSharedPreferences( RAVE_PAY, Context.MODE_PRIVATE); } }
package common; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.aspectj.lang.ProceedingJoinPoint; import org.springframework.util.StopWatch; public class Aop { private Log log = LogFactory.getLog(getClass()); public Object aroundLogging(ProceedingJoinPoint point) throws Throwable { StopWatch sw = new StopWatch(); sw.start(); Object retValue = null; try { retValue = point.proceed(); } catch (Exception e) { log.error("common : "+e.getMessage(),e); throw e; } finally { sw.stop(); String className = point.getTarget().getClass().getName(); String methodName = point.getSignature().getName(); long time = sw.getLastTaskTimeMillis(); if (time < 10) { log.warn(" Level 1 (10↓) : "+className + ", methodName : " + methodName + ", time : " + time); } else if (time < 50) { log.warn(" Level 2 (50↓) : "+className + ", methodName : " + methodName + ", time : " + time); } else { log.warn(" Level 3 (50↑) : "+className + ", methodName : " + methodName + ", time : " + time); } } return retValue; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.awt.Point; import java.awt.Polygon; import java.util.ArrayList; import org.junit.Test; import static org.junit.Assert.*; /** * * @author adam.horan */ public class CentrePolygonTest { public CentrePolygonTest() { } @Test public void testFindCentreTriangle1() { ArrayList<Point> points = new ArrayList<Point>(); points.add(new Point(10,10)); points.add(new Point(30,30)); points.add(new Point(30,10)); Polygon poly = PolyUtils.CreatePolygonFromList(points); Point findCentre = CentrePolygon.findCentre(poly); assertEquals("Incentre should be 24.1,15.9", 24.1, findCentre.getX(), 1); assertEquals("Incentre should be 24.1,15.9", 15.9, findCentre.getY(), 1); } //Test results from wolframalpha searching on "Incenter {25,62}, {346,14}, {43,146}" @Test public void testFindCentreTriangle2() { ArrayList<Point> points = new ArrayList<Point>(); points.add(new Point(25,62)); points.add(new Point(346,14)); points.add(new Point(43,146)); Polygon poly = PolyUtils.CreatePolygonFromList(points); Point findCentre = CentrePolygon.findCentre(poly); assertEquals(70.1002, findCentre.getX(), 1); assertEquals( 93.2293, findCentre.getY(), 1); } //rectangles are hard, as there's a line that describes the max min distance from any edge... //and we might find any point on that line @Test public void testSimpleRectangle(){ ArrayList<Point> points = new ArrayList<Point>(); points.add(new Point(-100,-100)); points.add(new Point(200,-100)); points.add(new Point(200,50)); points.add(new Point(-100,50)); Polygon poly = PolyUtils.CreatePolygonFromList(points); Point findCentre = CentrePolygon.findCentre(poly); assertEquals(-25.0, findCentre.getY(), 1); //we can't assert an X for this rectangle //assertEquals(50.0, findCentre.getX(), 1); } }
package com.yida.design.Facade.generator.subsystem; /** ********************* * @author yangke * @version 1.0 * @created 2018年7月14日 下午5:40:15 *********************** */ public class ClassA { public void doSomethingA() { // 业务逻辑 } }
package org.processmining.plugins.PromMasterPlugin.processmining.plugins.improvediscovery.visualization; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.Arrays; import java.util.Iterator; import java.util.Map; import javax.swing.BorderFactory; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import org.processmining.framework.plugin.PluginContext; import org.processmining.framework.plugin.Progress; import org.processmining.models.heuristics.elements.Activity; import org.processmining.models.jgraph.ProMJGraph; import org.processmining.models.jgraph.ProMJGraphVisualizer; import org.processmining.models.jgraph.visualization.ProMJGraphPanel; import org.processmining.plugins.PromMasterPlugin.processmining.plugins.improvediscovery.CustomSocialNetworkAnalysisUI; import org.processmining.plugins.PromMasterPlugin.processmining.plugins.improvediscovery.ImproveDiscoveryClusterData; import org.processmining.plugins.PromMasterPlugin.processmining.plugins.improvediscovery.ImproveDiscoveryData; import org.processmining.plugins.PromMasterPlugin.processmining.plugins.improvediscovery.ImproveDiscoverySocialTransformation; import org.processmining.plugins.PromMasterPlugin.processmining.plugins.improvediscovery.ImproveDiscoveryTransformation; import org.processmining.plugins.socialnetwork.miner.miningoperation.UtilOperation; import com.fluxicon.slickerbox.components.SlickerButton; public class ImproveDiscoveryPanel extends JComponent { /** * */ private static final long serialVersionUID = 1L; private ImproveDiscoveryData DiscoveryData; private ProMJGraphPanel ModelPanel; //private ImproveDiscoveryModelPanel ModelPanel; private ImproveDiscoveryParametersPanel ParametersPanel; private PluginContext context; private ProMJGraphPanel comparator_panel; //private SocialNetworkAnalysisUI SNPanel; private CustomSocialNetworkAnalysisUI SNPanel; private CustomSocialNetworkAnalysisUI WorkingSNPanel; protected JLabel minSliderHeader; private ImproveDiscoveryTransformation Transformation; private ProMJGraph jgraph; private boolean IsHeuristicAnalysis=true; private boolean LargeView=false; private int HeuristicViewWidth=1020; private int HeuristicViewHeigth=350; private int HeuristicViewDistance=250; private int SocialViewWidth=450; private int SocialViewHeigth=570; private int SocialViewDistance=470; private String currentSocialAnalysist="Working Together"; public ImproveDiscoveryPanel(final ProMJGraph jgraph, final ImproveDiscoveryTransformation Transformation,final PluginContext context) { this.jgraph=jgraph; this.setLayout(null); this.Transformation=Transformation; this.context=context; this.DiscoveryData=Transformation.GetData(); this.SNPanel=new CustomSocialNetworkAnalysisUI(context,DiscoveryData.getSocialNetwork()); this.SNPanel.setSize(new Dimension(450,570)); this.SNPanel.setBounds(20, 20, 450,570); this.SNPanel.setBorder(BorderFactory.createLineBorder(Color.black)); this.SNPanel.repaint(); ModelPanel=ProMJGraphVisualizer.instance().visualizeGraphWithoutRememberingLayout(DiscoveryData.getHeuristicsNetGraph()); ModelPanel.remove(ModelPanel.getComponent(1)); ModelPanel.remove(ModelPanel.getComponent(1)); ModelPanel.remove(ModelPanel.getComponent(3)); ModelPanel.remove(ModelPanel.getComponent(3)); ModelPanel.getComponent(0).repaint(); ModelPanel.repaint(); ModelPanel.setAutoscrolls(false); ModelPanel.setBounds(0,0,this.HeuristicViewWidth ,this.HeuristicViewHeigth-50); ModelPanel.setSize(new Dimension(this.HeuristicViewWidth ,this.HeuristicViewHeigth-50)); ModelPanel.setPreferredSize(new Dimension(this.HeuristicViewWidth ,this.HeuristicViewHeigth-50)); // ModelPanel= new ImproveDiscoveryModelPanel(jgraph,this.DiscoveryData.getHeuristicNet(),this.DiscoveryData.getHMinerAVSettings()); ParametersPanel= new ImproveDiscoveryParametersPanel(Transformation, this.AddSocialTabEvents(), this.AddClusterTabEvent(), this.AddPerformanceTabEvent()); AddSocialCheckEvents(); basicSocialEvents(); this.add(ModelPanel); // this.add(ResetButton()); //this.add(ChangeViewAnalysistMode()); this.add(ParametersPanel); JPanel ButtonPanel= new JPanel(); ButtonPanel.setSize(new Dimension(350,50)); ButtonPanel.setBounds(1020, 0, 350,50); ButtonPanel.setBackground(new Color(100,100,100)); ButtonPanel.repaint(); ButtonPanel.add(ResourceBotton()); ButtonPanel.add(ResetButton()); ButtonPanel.add(FullScreen()); this.add(ButtonPanel); Transformation.SetXLogBackUpUnit(); } public SlickerButton FullScreen() { final SlickerButton detailButton = new SlickerButton(); detailButton.setToolTipText("click to view without compare"); detailButton.setAlignmentX(JLabel.CENTER_ALIGNMENT); detailButton.setMaximumSize(new Dimension(Integer.MAX_VALUE, 20)); detailButton.setMinimumSize(new Dimension(55, 55)); detailButton.setSize(new Dimension(55,55)); detailButton.setBounds(960,140 , 55,55); detailButton.setText("Large View"); detailButton.setBackground(Color.BLUE); detailButton.setFont(new Font("10f", 10, 9)); detailButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub if(LargeView) { detailButton.setText("Large View"); LargeView=false; AddBasePanels(); HeuristicViewDistance=250; HeuristicViewHeigth=350; SocialViewWidth=450; SocialViewDistance=480; BuiltGraph(); } else { detailButton.setText("Compare View"); LargeView=true; RemoveBaseHeuristicPanel(); HeuristicViewDistance=0; HeuristicViewHeigth=650; SocialViewWidth=900; SocialViewDistance=20; BuiltGraph(); } } }); return detailButton; } public SlickerButton ChangeViewAnalysistMode() { final SlickerButton detailButton = new SlickerButton(); detailButton.setToolTipText("click to view without compare"); detailButton.setAlignmentX(JLabel.CENTER_ALIGNMENT); detailButton.setMaximumSize(new Dimension(Integer.MAX_VALUE, 20)); detailButton.setMinimumSize(new Dimension(55, 55)); detailButton.setSize(new Dimension(55,55)); detailButton.setBounds(960,140 , 55,55); detailButton.setText("Not \n Compare"); detailButton.setBackground(Color.BLUE); detailButton.setFont(new Font("10f", 11, 9)); return detailButton; } public SlickerButton ResetButton() { final SlickerButton detailButton = new SlickerButton(); detailButton.setToolTipText("click to reset analysist"); detailButton.setAlignmentX(JLabel.CENTER_ALIGNMENT); detailButton.setMaximumSize(new Dimension(Integer.MAX_VALUE, 20)); detailButton.setMinimumSize(new Dimension(55, 55)); detailButton.setSize(new Dimension(55,55)); detailButton.setBounds(960, 70, 55,55); detailButton.setText("Reset"); detailButton.setBackground(Color.BLUE); detailButton.setFont(new Font("10f", 11, 9)); detailButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub Transformation.ResetLog(); //Performance update Transformation.GetData().InicializatePerformanceData(); Transformation.SetSocialTransformation(new ImproveDiscoverySocialTransformation(Transformation.GetData())); ParametersPanel.mainPerformanceContainer.ResetPanel(); ParametersPanel.mainPerformanceContainer.repaint(); ParametersPanel.repaint(); ParametersPanel.tabPane.selectTab("Organizational"); ParametersPanel.tabPane.selectTab("Performance"); AddPerformanceClickAction(); //Remove comparative view RemoveComparativeView(); BuiltGraph(); }}); return detailButton; } public void repaintThis() { this.repaint(); } public void UpdateBaseLog() { this.Transformation.GetData().SetTransformLogFromWorkingLog(); } public ActionListener AddSocialTabEvents() { ActionListener Action= new ActionListener(){ public void actionPerformed(ActionEvent arg0) { UpdateBaseLog(); Transformation.SetSocialTransformation( new ImproveDiscoverySocialTransformation(Transformation.GetData())); Transformation.GetSocialTransformation().WTCalculation(); ParametersPanel.mainSocialParameters.ResetPanel(); ParametersPanel.mainSocialParameters.repaint(); ParametersPanel.tabPane.repaint(); AddSocialCheckEvents(); Transformation.SetXLogBackUpUnit(); } }; return Action; } public ActionListener AddPerformanceTabEvent() { ActionListener Action= new ActionListener(){ public void actionPerformed(ActionEvent arg0) { UpdateBaseLog(); Transformation.GetData().InicializatePerformanceData(); ParametersPanel.mainPerformanceContainer.ResetPanel(); ParametersPanel.mainPerformanceContainer.repaint(); ParametersPanel.tabPane.repaint(); AddPerformanceClickAction(); } }; return Action; } public ActionListener AddClusterTabEvent() { ActionListener Action= new ActionListener(){ public void actionPerformed(ActionEvent arg0) { Progress progress = context.getProgress(); UpdateBaseLog(); Transformation.GetClusterTransformation().SetClusterData( new ImproveDiscoveryClusterData(Transformation.GetData().GetCurrentLog(), 1)); String message = "Obtain Log Event Class mapping and replay settings"; progress.setCaption(message); progress.setIndeterminate(false); progress.setMinimum(0); progress.setMaximum(Transformation.GetData().GetCurrentLog().size() + 2000); Transformation.GetClusterTransformation().MakeProcessAlign(); ParametersPanel.mainClusterParameters.ResetPanel(); ParametersPanel.mainClusterParameters.repaint(); ParametersPanel.tabPane.repaint(); AddClusterCheckEvents(); } }; return Action; } public boolean HeuristicViewIsVisibile() { return Arrays.asList(this.getComponents()).contains(ModelPanel); } public void RemoveComparativeView() { if(Arrays.asList(this.getComponents()).contains(comparator_panel)) { this.remove(comparator_panel); } if(Arrays.asList(this.getComponents()).contains(this.WorkingSNPanel)) { this.remove(this.WorkingSNPanel); } this.repaint(); } public SlickerButton ResourceBotton() { final SlickerButton detailButton = new SlickerButton(); detailButton.setToolTipText("click to show model detail inspector"); detailButton.setAlignmentX(JLabel.CENTER_ALIGNMENT); detailButton.setMaximumSize(new Dimension(Integer.MAX_VALUE, 20)); detailButton.setMinimumSize(new Dimension(55, 55)); detailButton.setSize(new Dimension(55,55)); detailButton.setBounds(960, 0, 55,55); detailButton.setText("Resources"); detailButton.setBackground(Color.BLUE); detailButton.setFont(new Font("10f", 11, 9)); detailButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub if(IsHeuristicAnalysis) { IsHeuristicAnalysis=false; detailButton.setText("Process"); RemoveHeuristicPanel(); AddSocialPanel(); } else { IsHeuristicAnalysis=true; RemoveSocialPanel(); detailButton.setText("Resources"); AddHeuristic(); } }}); return detailButton; } public void AddHeuristic() { this.Transformation.GenerateHeuristicModel(); if(this.comparator_panel!=null) this.add(comparator_panel); if(!this.LargeView) this.add(this.ModelPanel); this.revalidate(); this.repaint(); } public void AddSocialPanel() { if(!this.LargeView) { this.add(this.SNPanel); } else if (this.LargeView && this.WorkingSNPanel==null) { SocialPanelData(this.currentSocialAnalysist); this.WorkingSNPanel=new CustomSocialNetworkAnalysisUI(context,DiscoveryData.getSocialNetwork()); this.WorkingSNPanel.setSize(new Dimension(SocialViewWidth,SocialViewHeigth)); this.WorkingSNPanel.setBounds(SocialViewDistance, 20, SocialViewWidth,SocialViewHeigth); this.WorkingSNPanel.setBorder(BorderFactory.createLineBorder(Color.black)); this.WorkingSNPanel.repaint(); } if(this.WorkingSNPanel!=null) { if(!this.LargeView) { WorkingSNPanel.setSize(new Dimension(SocialViewWidth,SocialViewHeigth)); } this.add(this.WorkingSNPanel); } //this.add(WorkingSNPanel); this.validate(); this.repaint(); } public void RemoveSocialPanel() { if(this.WorkingSNPanel!=null) this.remove(this.WorkingSNPanel); this.remove(this.SNPanel); this.revalidate(); this.repaint(); } public void RemoveBaseHeuristicPanel() { if(IsHeuristicAnalysis) this.remove(this.ModelPanel); else this.remove(SNPanel); this.repaint(); } public void AddBasePanels() { if(IsHeuristicAnalysis) { this.add(this.ModelPanel); } else { this.remove(this.WorkingSNPanel); this.add(SNPanel); } this.repaint(); } public void RemoveHeuristicPanel() { this.remove(this.ModelPanel); if(this.comparator_panel!=null) this.remove(this.comparator_panel); this.revalidate(); this.repaint(); } public void AddPerformanceClickAction() { ParametersPanel.mainPerformanceContainer.maxTimeSlider.addMouseListener(new MouseListener(){ public void mouseClicked(MouseEvent arg0) { BuiltGraph();} public void mouseEntered(MouseEvent arg0) {} public void mouseExited(MouseEvent arg0) {} public void mousePressed(MouseEvent arg0) {} public void mouseReleased(MouseEvent arg0) {} }); ParametersPanel.mainPerformanceContainer.minTimeSlider.addMouseListener(new MouseListener(){ public void mouseClicked(MouseEvent arg0) { BuiltGraph(); } public void mouseEntered(MouseEvent arg0) { } public void mouseExited(MouseEvent arg0) { } public void mousePressed(MouseEvent arg0) { } public void mouseReleased(MouseEvent arg0) { } }); } public void LabelMouseListenerAction(JLabel label) { label.addMouseListener(new MouseListener(){ public void mouseClicked(MouseEvent arg0){ // Inicializar los checkbox de cases int value= -1; String key=""; JLabel label= (JLabel) arg0.getComponent(); value= Integer.parseInt(label.getName()); if(label.getText().equals("-")) { if(Transformation.GetClusterTransformation().GetClusterData().GetNumberOfCaseOnCluster(value)<15) { Map<String,JCheckBox> MapCase=ParametersPanel.mainClusterParameters.ClustersCasesCheckBoxes; for(int c=0;c<Transformation.GetClusterTransformation().GetClusterData().GetNumberOfCaseOnCluster(value);c++) { key=value+"-"+c; MapCase.get(key).addMouseListener(new MouseListener(){ public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) { //Buscar el name correcto para el CASE JCheckBox check=(JCheckBox) e.getComponent(); int caseIndex= Integer.parseInt( check.getName().substring(check.getName().indexOf("-")+1)); int value=Integer.parseInt( check.getName().substring(0,check.getName().indexOf("-"))); if(check.isSelected()) {// se selecciono para borrarlo redrawGraphWithTraces(value,caseIndex,true); } else { redrawGraphWithTraces(value,caseIndex,false); } } public void mouseReleased(MouseEvent e) {} }); } for(int c=0;c<ParametersPanel.mainClusterParameters.JLabelSubClusterArray.size();c++) { label=ParametersPanel.mainClusterParameters.JLabelSubClusterArray.get(c); } } else { } } else { } } public void mouseEntered(MouseEvent arg0) {} public void mouseExited(MouseEvent arg0) {} public void mousePressed(MouseEvent arg0) {} public void mouseReleased(MouseEvent arg0) {} }); } public void LabelMouseListenerSubCluster(JLabel label) { label.addMouseListener(new MouseListener(){ public void mouseClicked(MouseEvent arg0){ // Inicializar los checkbox de cases int value= -1; String key=""; JLabel label= (JLabel) arg0.getComponent(); value=Integer.parseInt(label.getName().substring(0,label.getName().indexOf("-"))); if(label.getText().equals("-")) { Map<String,JCheckBox> MapCase=ParametersPanel.mainClusterParameters.ClustersCasesCheckBoxes; for(int c=0;c<Transformation.GetClusterTransformation().GetClusterData().GetNumberOfCaseOnCluster(value);c++) { key=value+"-"+c; MapCase.get(key).addMouseListener(new MouseListener(){ public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) { //Buscar el name correcto para el CASE JCheckBox check=(JCheckBox) e.getComponent(); int caseIndex= Integer.parseInt( check.getName().substring(check.getName().indexOf("-")+1)); int value=Integer.parseInt( check.getName().substring(0,check.getName().indexOf("-"))); if(check.isSelected()) {// se selecciono para borrarlo redrawGraphWithTraces(value,caseIndex,true); } else { redrawGraphWithTraces(value,caseIndex,false); } } public void mouseReleased(MouseEvent e) {} }); } } } public void mouseEntered(MouseEvent arg0) {} public void mouseExited(MouseEvent arg0) {} public void mousePressed(MouseEvent arg0) {} public void mouseReleased(MouseEvent arg0) {} }); } public void AddLabelsEvent() { JLabel label; for(int j=0;j<ParametersPanel.mainClusterParameters.JLabelClusterArray.size();j++) { label=ParametersPanel.mainClusterParameters.JLabelClusterArray.get(j); LabelMouseListenerAction(label); } for(int c=0;c<ParametersPanel.mainClusterParameters.JLabelSubClusterArray.size();c++) { label=ParametersPanel.mainClusterParameters.JLabelSubClusterArray.get(c); LabelMouseListenerSubCluster(label); } } public void SocialGroupLabelEvents() { ParametersPanel.mainSocialParameters.filterSlider.addMouseListener(new MouseListener(){ public void mouseClicked(MouseEvent arg0) { // TODO Auto-generated method stub } public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub BuiltGraph(); } public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub }}); for(int j=0; j<ParametersPanel.mainSocialParameters.JCheckBoxGroups.size();j++) { ParametersPanel.mainSocialParameters.JCheckBoxGroups.get(j).addMouseListener(new MouseListener(){ public void mouseClicked(MouseEvent arg0) {} public void mouseEntered(MouseEvent arg0) {} public void mouseExited(MouseEvent arg0) {} public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub JCheckBox check=(JCheckBox) arg0.getComponent(); if(check.isSelected() && ParametersPanel.mainSocialParameters.RelationsPanel.getComponentCount()==0) {// se selecciono para borrarlo redrawGraphWithSocialGroupSelection(true,check.getName()); } else if(check.isSelected() && ParametersPanel.mainSocialParameters.RelationsPanel.getComponentCount()>0) { check.setSelected(false); } else { redrawGraphWithSocialGroupSelection(false,check.getName()); } } //aqui public void mouseReleased(MouseEvent arg0) {}}); } for(int k=0;k<ParametersPanel.mainSocialParameters.JLabelGroups.size();k++) { ParametersPanel.mainSocialParameters.JLabelGroups.get(k).addMouseListener(new MouseListener(){ public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) { AddResourcesEvent(); for(int j=0;j<ParametersPanel.mainSocialParameters.JLabelResources.size();j++) { ParametersPanel.mainSocialParameters.JLabelResources.get(j).addMouseListener(new MouseListener(){ public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) { AddResourcesEvent(); } public void mouseReleased(MouseEvent e) { }}); } } public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } }); } } public void AddResourcesEvent() { for(int j=0; j<ParametersPanel.mainSocialParameters.JCheckBoxResources.size();j++) { ParametersPanel.mainSocialParameters.JCheckBoxResources.get(j).addMouseListener(new MouseListener(){ public void mouseClicked(MouseEvent arg0) {} public void mouseEntered(MouseEvent arg0) {} public void mouseExited(MouseEvent arg0) {} public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub JCheckBox check=(JCheckBox) arg0.getComponent(); if(check.isSelected()) {// se selecciono para borrarlo redrawGraph(check.getName(),true); } else { redrawGraph(check.getName(),false); } } public void mouseReleased(MouseEvent arg0) {}}); } } public void AddSocialCheckEvents() { SocialGroupLabelEvents(); ParametersPanel.mainSocialParameters.filterSlider.addMouseListener(new MouseListener(){ public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) { SocialGroupLabelEvents(); } public void mouseReleased(MouseEvent e) {} }); } public void AddSubClusterEvents() { for(int u=0;u<ParametersPanel.mainClusterParameters.SubClusteredgesConcurrencyActiveBox.size();u++) { this.ParametersPanel.mainClusterParameters.SubClusteredgesConcurrencyActiveBox.get(u).addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { JCheckBox check=(JCheckBox) e.getComponent(); int cluster_number=Integer.parseInt( check.getName().substring(0,check.getName().indexOf("-"))); int number_of_cases=Transformation.GetClusterTransformation().GetClusterData().GetNumberOfCaseOnCluster(cluster_number); int subClusterIndex= Integer.parseInt(check.getName().substring(check.getName().indexOf("-")+1)); int subclusters=Math.round(number_of_cases/14); if(subclusters%14==0) subclusters--; int casesIniToRemove=0; int casesLastToRemove=0; if(subClusterIndex==subclusters) { casesIniToRemove=number_of_cases-number_of_cases%14; casesLastToRemove=number_of_cases; } else { for(int j=0;j<subClusterIndex;j++) { casesIniToRemove+=14; } casesLastToRemove=casesIniToRemove+14; } if(check.isSelected()) {// se selecciono para borrarlo redrawGraphWithSubCluster(cluster_number, casesIniToRemove,casesLastToRemove,true); } else { redrawGraphWithSubCluster(cluster_number, casesIniToRemove,casesLastToRemove,false); } } public void mouseReleased(MouseEvent e) { } }); } } public void AddClusterCheckEvents() { for(int u=0;u<ParametersPanel.mainClusterParameters.ClusteredgesConcurrencyActiveBox.size();u++) { this.ParametersPanel.mainClusterParameters.ClusteredgesConcurrencyActiveBox.get(u).addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) { JCheckBox check=(JCheckBox) e.getComponent(); if(check.isSelected()) {// se selecciono para borrarlo redrawGraphWithClusters(check.getName(),true); } else { redrawGraphWithClusters(check.getName(),false); } } public void mouseReleased(MouseEvent e) { } }); } } public void AddCheckBoxesClusterEvents() { ParametersPanel.mainClusterParameters.numberOfClusters.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { Transformation.ClearRemovedClusters(); Transformation.BuiltHeuristic(); //ParametersPanel.mainClusterParameters.RestoreSelects(); ParametersPanel.mainClusterParameters.AddClustersParameters(false); Transformation.GetData().ReturnToBaseLog(); AddClusterCheckEvents(); AddSubClusterEvents(); AddLabelsEvent(); BuiltGraph(); } }); AddClusterCheckEvents(); AddSubClusterEvents(); AddLabelsEvent(); } public void basicSocialEvents() { ParametersPanel.mainSocialParameters.Options.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent arg0) { JComboBox combo= ParametersPanel.mainSocialParameters.Options; Transformation.SetSocialTransformation( new ImproveDiscoverySocialTransformation(Transformation.GetData())); if(combo.getSelectedItem().toString().equals("Similar Task")) { currentSocialAnalysist="Similar Task"; Transformation.GetSocialTransformation().STCalculation(); } else if(combo.getSelectedItem().toString().equals("Working Together")) { currentSocialAnalysist="Working Together"; Transformation.GetSocialTransformation().WTCalculation(); } ParametersPanel.mainSocialParameters.ResetPanel(); ParametersPanel.mainSocialParameters.repaint(); ParametersPanel.tabPane.selectTab("Performance"); ParametersPanel.tabPane.selectTab("Organizational"); AddSocialCheckEvents(); BuiltGraph(); }}); } public void AddCheckBoxesEvent() { //Options for(int u=0;u<ParametersPanel.mainSocialParameters.edgesConcurrencyActiveBox.length;u++) { this.ParametersPanel.mainSocialParameters.edgesConcurrencyActiveBox[u].addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) { JCheckBox check=(JCheckBox) e.getComponent(); if(check.isSelected()) redrawGraph(check.getName(),true); else { redrawGraph(check.getName(),false); } } public void mouseReleased(MouseEvent e) { } }); } } public void redrawGraphWithSubCluster(int cluster, int trace_ini,int trace_last,boolean remove) { if(remove) { Transformation.RemoveTracesFromSubCluster(cluster,trace_ini,trace_last); } else { Transformation.RestoreSubCluster(cluster,trace_ini,trace_last); } BuiltGraph(); } public void redrawGraphWithTraces(int cluster,int trace,boolean remove) { if(remove) { Transformation.RemoveTraceAndFilter(trace,cluster); } else { Transformation.RestoreCase(cluster,trace); } BuiltGraph(); } public void redrawGraphWithSocialGroupSelection(boolean remove,String numberGroup) { if(remove) { Transformation.GroupFilter(numberGroup); } else { Transformation.RestoreGroup(numberGroup); } BuiltGraph(); } public void redrawGraphWithClusters(String number,boolean remove) { Transformation.setContext(context); if(remove) { Transformation.RemoveClusterAndFilter(number); } else { Transformation.RestoreCluster(number); } BuiltGraph(); } public void BuiltGraph() { if(IsHeuristicAnalysis) { if (comparator_panel!= null) { this.remove(comparator_panel); comparator_panel = null; this.revalidate(); } if (comparator_panel == null) { if(Transformation.GetFixCase()) { Iterator<Activity> iterador= this.DiscoveryData.getHeuristicsNetGraph().getActivities().iterator(); Activity ac= iterador.next(); this.DiscoveryData.getHeuristicsNetGraph().removeActivity(ac); } comparator_panel=ProMJGraphVisualizer.instance().visualizeGraphWithoutRememberingLayout(DiscoveryData.getHeuristicsNetGraph()); comparator_panel.remove(comparator_panel.getComponent(1)); comparator_panel.remove(comparator_panel.getComponent(1)); comparator_panel.getComponent(0).repaint(); comparator_panel.repaint(); comparator_panel.setAutoscrolls(false); comparator_panel.setBounds(0, this.HeuristicViewDistance,this.HeuristicViewWidth ,this.HeuristicViewHeigth); comparator_panel.setSize(new Dimension(this.HeuristicViewWidth ,this.HeuristicViewHeigth)); comparator_panel.setPreferredSize(new Dimension(this.HeuristicViewWidth ,this.HeuristicViewHeigth)); this.add(comparator_panel); this.revalidate(); } //update working panel SocialPanelData("Working Together"); this.CreateSocialWorkingView(); } //Social view else { SocialPanelData("Working Together"); if(WorkingSNPanel!=null) { this.remove(WorkingSNPanel); } this.repaint(); this.revalidate(); CreateSocialWorkingView(); this.add(WorkingSNPanel); this.repaint(); this.revalidate(); System.out.print("\n resource"); } } public void CreateSocialWorkingView() { this.WorkingSNPanel=new CustomSocialNetworkAnalysisUI(context,DiscoveryData.getSocialNetwork()); this.WorkingSNPanel.setSize(new Dimension(SocialViewWidth,SocialViewHeigth)); this.WorkingSNPanel.setBounds(SocialViewDistance, 20, SocialViewWidth,SocialViewHeigth); this.WorkingSNPanel.setBorder(BorderFactory.createLineBorder(Color.black)); this.WorkingSNPanel.repaint(); } public void redrawGraph(String id,boolean remove) { if(remove) { Transformation.SocialFilter(id); } else { Transformation.AddSocialResource(id); } BuiltGraph(); } /* (non-Javadoc) * @see javax.swing.JComponent#paintComponent(java.awt.Graphics) */ protected void paintComponent(Graphics g) { this.setBackground( new Color(60, 60, 60)); } public void itemStateChanged(ItemEvent e) { // TODO Auto-generated method stub } public void SocialPanelData(String type) { if(type.equals("Working Together")) { DiscoveryData.SetSocialNetwork(UtilOperation.generateSN( Transformation.GetSocialTransformation().GetMatrix2DToShow("WT"), Transformation.GetSocialTransformation().GetWorkingTogetherDataToShow().getOriginatorList())); } else if(type.equals("Similar Task")) { DiscoveryData.SetSocialNetwork(UtilOperation.generateSN( Transformation.GetSocialTransformation().GetMatrix2DToShow("ST"), Transformation.GetSocialTransformation().GetSimilarTaskDataToShow().getOriginatorList())); } } }
package com.websharp.dwtz.dao; import java.util.ArrayList; // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. Enable "keep" sections if you want to edit. /** * Entity mapped to table ENTITY_DISTRIBUTION_APPLY. */ public class EntityDistributionApply { public String InnerID; public String Distribution_LsNo; public String Breed; public String Old_QC_No; public String Distribution_Company; public String Distribution_Target_Address; public String Distribution_Count; public String Remark; public String Status; public String Apply_User_ID; public String Add_UserID; public String Add_Time; public String Add_IP; public String Update_UserID; public String Update_Time; public String Update_IP; public String Old_Distribution_Count; public String BreedForElse; public ArrayList<EntityDistributionApplyTarget> target_list; public ArrayList<EntityDistributionApplyTarget> getTarget_list() { return target_list; } public void setTarget_list(ArrayList<EntityDistributionApplyTarget> target_list) { this.target_list = target_list; } public EntityDistributionApply() { } public EntityDistributionApply(String InnerID, String Distribution_LsNo, String Breed, String Old_QC_No, String Distribution_Company, String Distribution_Target_Address, String Distribution_Count, String Remark, String Status, String Apply_User_ID, String Add_UserID, String Add_Time, String Add_IP, String Update_UserID, String Update_Time, String Update_IP, String Old_Distribution_Count, String BreedForElse) { this.InnerID = InnerID; this.Distribution_LsNo = Distribution_LsNo; this.Breed = Breed; this.Old_QC_No = Old_QC_No; this.Distribution_Company = Distribution_Company; this.Distribution_Target_Address = Distribution_Target_Address; this.Distribution_Count = Distribution_Count; this.Remark = Remark; this.Status = Status; this.Apply_User_ID = Apply_User_ID; this.Add_UserID = Add_UserID; this.Add_Time = Add_Time; this.Add_IP = Add_IP; this.Update_UserID = Update_UserID; this.Update_Time = Update_Time; this.Update_IP = Update_IP; this.Old_Distribution_Count = Old_Distribution_Count; this.BreedForElse = BreedForElse; } public String getInnerID() { return InnerID; } public void setInnerID(String InnerID) { this.InnerID = InnerID; } public String getDistribution_LsNo() { return Distribution_LsNo; } public void setDistribution_LsNo(String Distribution_LsNo) { this.Distribution_LsNo = Distribution_LsNo; } public String getBreed() { return Breed; } public void setBreed(String Breed) { this.Breed = Breed; } public String getOld_QC_No() { return Old_QC_No; } public void setOld_QC_No(String Old_QC_No) { this.Old_QC_No = Old_QC_No; } public String getDistribution_Company() { return Distribution_Company; } public void setDistribution_Company(String Distribution_Company) { this.Distribution_Company = Distribution_Company; } public String getDistribution_Target_Address() { return Distribution_Target_Address; } public void setDistribution_Target_Address(String Distribution_Target_Address) { this.Distribution_Target_Address = Distribution_Target_Address; } public String getDistribution_Count() { return Distribution_Count; } public void setDistribution_Count(String Distribution_Count) { this.Distribution_Count = Distribution_Count; } public String getRemark() { return Remark; } public void setRemark(String Remark) { this.Remark = Remark; } public String getStatus() { return Status; } public void setStatus(String Status) { this.Status = Status; } public String getApply_User_ID() { return Apply_User_ID; } public void setApply_User_ID(String Apply_User_ID) { this.Apply_User_ID = Apply_User_ID; } public String getAdd_UserID() { return Add_UserID; } public void setAdd_UserID(String Add_UserID) { this.Add_UserID = Add_UserID; } public String getAdd_Time() { return Add_Time; } public void setAdd_Time(String Add_Time) { this.Add_Time = Add_Time; } public String getAdd_IP() { return Add_IP; } public void setAdd_IP(String Add_IP) { this.Add_IP = Add_IP; } public String getUpdate_UserID() { return Update_UserID; } public void setUpdate_UserID(String Update_UserID) { this.Update_UserID = Update_UserID; } public String getUpdate_Time() { return Update_Time; } public void setUpdate_Time(String Update_Time) { this.Update_Time = Update_Time; } public String getUpdate_IP() { return Update_IP; } public void setUpdate_IP(String Update_IP) { this.Update_IP = Update_IP; } public String getOld_Distribution_Count() { return Old_Distribution_Count; } public void setOld_Distribution_Count(String Old_Distribution_Count) { this.Old_Distribution_Count = Old_Distribution_Count; } public String getBreedForElse() { return BreedForElse; } public void setBreedForElse(String BreedForElse) { this.BreedForElse = BreedForElse; } }
package com.categories.junit; public interface RegressionTests { }
package com.yzpc.interceptor; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; public class RegisterInterceptor extends AbstractInterceptor{ @Override public String intercept(ActionInvocation arg0) throws Exception { // TODO Auto-generated method stub System.out.println("interceptor is running"); String resultString = arg0.invoke(); System.out.println("interceptor is done"); return resultString; } }
package com.gr.jiang.todo.repository; import com.gr.jiang.todo.model.ToDoItem; import java.util.List; /** * Created by jiang on 16/9/5. */ public interface ToDoRepository { List<ToDoItem> findAll(); ToDoItem findById(Long id); Long insert(ToDoItem toDoItem); void update(ToDoItem toDoItem); void delete(ToDoItem toDoItem); }
package com.example.healthmanage.ui.activity.mytask.mytaskdetail.selectTaskReceiver; import android.os.Bundle; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.TextView; import androidx.lifecycle.Observer; import androidx.recyclerview.widget.LinearLayoutManager; import com.example.healthmanage.BR; import com.example.healthmanage.R; import com.example.healthmanage.base.BaseActivity; import com.example.healthmanage.base.BaseAdapter; import com.example.healthmanage.databinding.ActivitySelectTaskReceiverBinding; import com.example.healthmanage.utils.ToolUtil; import com.example.healthmanage.dialog.EditTextDialog; import com.example.healthmanage.bean.recyclerview.TaskReceiverRecyclerView; import com.jeremyliao.liveeventbus.LiveEventBus; import java.util.List; public class SelectTaskReceiverActivity extends BaseActivity<ActivitySelectTaskReceiverBinding, SelectTaskReceiverViewModel> implements View.OnClickListener { BaseAdapter taskReceiverAdapter; EditTextDialog editTextDialog; Bundle bundle; int taskId; String taskContent; @Override protected void initData() { bundle = this.getIntent().getExtras(); taskId = bundle.getInt("taskId"); taskContent = bundle.getString("taskContent"); viewModel.getTaskReceiverList(); } @Override protected void registerUIChangeEventObserver() { super.registerUIChangeEventObserver(); taskReceiverAdapter = new BaseAdapter(this, null, R.layout.recycler_view_item_task_receiver, BR.TaskReceiverRecyclerView); dataBinding.recyclerViewTaskReceiver.setLayoutManager(new LinearLayoutManager(this)); dataBinding.tvCancel.setOnClickListener(this::onClick); viewModel.taskReceiverMutableLiveData.observe(this, new Observer<List<TaskReceiverRecyclerView>>() { @Override public void onChanged(List<TaskReceiverRecyclerView> taskReceiverRecyclerViews) { taskReceiverAdapter.setRecyclerViewList(taskReceiverRecyclerViews); dataBinding.recyclerViewTaskReceiver.setAdapter(taskReceiverAdapter); } }); taskReceiverAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() { @Override public void onItemClick(View view, int position) { TaskReceiverRecyclerView taskReceiverRecyclerView = (TaskReceiverRecyclerView) taskReceiverAdapter.getRecyclerViewList().get(position); EditTextDialog selectTaskReceiverDialog = new EditTextDialog(SelectTaskReceiverActivity.this, R.layout.dialog_select_task_receiver, taskReceiverRecyclerView.getName(), taskReceiverRecyclerView.getAvatarUrl(), taskContent); selectTaskReceiverDialog.show(); selectTaskReceiverDialog.setOnEditTextDialogClickListener(new EditTextDialog.OnEditTextDialogClickListener() { @Override public void doCreate(List<String> content) { } @Override public void doSend() { viewModel.sendMyTask(taskId, taskReceiverRecyclerView.getReceiverId()); } }); } }); LiveEventBus.get("CloseKeyboard", Boolean.class).observe(this, new Observer<Boolean>() { @Override public void onChanged(Boolean aBoolean) { ToolUtil.hideKeyboard(dataBinding.includeSearch.etSearch); } }); dataBinding.includeSearch.ivClear.setOnClickListener(this::onClick); dataBinding.includeSearch.etSearch.setHint(R.string.hint_input_search); dataBinding.includeSearch.etSearch.setInputType(InputType.TYPE_CLASS_TEXT); dataBinding.includeSearch.etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_UNSPECIFIED) { viewModel.searchDoctor(v.getText().toString()); return true; } return false; } }); dataBinding.includeSearch.etSearch.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (s.length() > 0) { dataBinding.includeSearch.ivClear.setVisibility(View.VISIBLE); } else { dataBinding.includeSearch.ivClear.setVisibility(View.GONE); } } @Override public void afterTextChanged(Editable s) { } }); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.tv_cancel: finish(); break; case R.id.iv_clear: dataBinding.includeSearch.etSearch.setText(""); viewModel.getTaskReceiverList(); break; } } @Override protected int initVariableId() { return BR.ViewModel; } @Override protected int setContentViewSrc(Bundle savedInstanceState) { return R.layout.activity_select_task_receiver; } }
package com.itech.reconapp.heading; public interface HeadingEventListener { void onHeadingChanged(float heading); }
package com.lera.vehicle.reservation.repository.vehicle; import com.lera.vehicle.reservation.domain.vehicle.Model; import org.springframework.data.jpa.repository.JpaRepository; public interface ModelRepository extends JpaRepository<Model, Long> { }
package com.example.bratwurst.service; import org.springframework.stereotype.Service; @Service public interface EncryptionService { public String encrypt(String data); public String decrypt(String data); }
package co.staruml.handler; import co.staruml.core.DiagramControl; import co.staruml.core.EdgeView; import co.staruml.core.View; import co.staruml.graphics.*; public abstract class Manipulator { protected SelectHandler handler; protected boolean dragged; protected Point f1, f2; protected abstract void beginManipulate(DiagramControl diagramControl, Canvas canvas, View view, int x, int y); protected abstract void drawSkeleton(DiagramControl diagramControl, Canvas canvas); protected abstract void eraseSkeleton(DiagramControl diagramControl, Canvas canvas); protected abstract void moveSkeleton(DiagramControl diagramControl, Canvas canvas, View view, Point delta); protected abstract void endManipulate(DiagramControl diagramControl, Canvas canvas, View view, int dx, int dy); public void mousePressed(DiagramControl diagramControl, Canvas canvas, View view, MouseEvent e) { int x = e.getX(); int y = e.getY(); beginManipulate(diagramControl, canvas, view, x, y); dragged = false; Point z = new Point(x, y); Coord.coordRevTransform(canvas.getZoomFactor(), GridFactor.NO_GRID, z); f1 = new Point(z); f2 = new Point(z); } public void mouseReleased(DiagramControl diagramControl, Canvas canvas, View view, MouseEvent e) { if (dragged) { // erase skeleton eraseSkeleton(diagramControl, canvas); } endManipulate(diagramControl, canvas, view, f2.getX() - f1.getX(), f2.getY() - f1.getY()); } public void mouseDragged(DiagramControl diagramControl, Canvas canvas, View view, MouseEvent e) { Point z = new Point(e.getX(), e.getY()); Coord.coordRevTransform(canvas.getZoomFactor(), GridFactor.NO_GRID, z); Point delta = new Point(z.getX() - f2.getX(), z.getY() - f2.getY()); if (dragged) { // erase skeleton eraseSkeleton(diagramControl, canvas); } else { if ((delta.getX() != 0) || (delta.getY() != 0)) dragged = true; } moveSkeleton(diagramControl, canvas, view, delta); f2.setX(f2.getX() + delta.getX()); f2.setY(f2.getY() + delta.getY()); if (dragged) { // draw skeleton drawSkeleton(diagramControl, canvas); } } }
package quotationsoftware.util; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.EventHandler; import javafx.scene.control.ComboBox; import javafx.scene.control.DatePicker; import javafx.scene.control.TablePosition; import javafx.scene.control.TableView; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.util.StringConverter; /** * Utility class to implement custom behaviour on fx ui elements. */ public class FxUtil { public enum AutoCompleteMode { STARTS_WITH, CONTAINING; } /** * Specifies the auto complete feature on a specified combobox. * @param <T> * @param comboBox * @param mode */ public static <T> void autoCompleteComboBox(ComboBox<T> comboBox, AutoCompleteMode mode) { ObservableList<T> data = comboBox.getItems(); comboBox.setEditable(true); comboBox.addEventHandler(KeyEvent.KEY_PRESSED, t -> comboBox.hide()); comboBox.addEventHandler(KeyEvent.KEY_RELEASED, new EventHandler<KeyEvent>() { private boolean moveCaretToPos = false; private int caretPos; @Override public void handle(KeyEvent event) { if (event.getCode() == KeyCode.UP) { caretPos = -1; moveCaret(comboBox.getEditor().getText().length()); return; } else if (event.getCode() == KeyCode.DOWN) { if (!comboBox.isShowing()) { comboBox.show(); } caretPos = -1; moveCaret(comboBox.getEditor().getText().length()); return; } else if (event.getCode() == KeyCode.BACK_SPACE) { moveCaretToPos = true; caretPos = comboBox.getEditor().getCaretPosition(); } else if (event.getCode() == KeyCode.DELETE) { moveCaretToPos = true; caretPos = comboBox.getEditor().getCaretPosition(); } if (event.getCode() == KeyCode.RIGHT || event.getCode() == KeyCode.LEFT || event.isControlDown() || event.getCode() == KeyCode.HOME || event.getCode() == KeyCode.END || event.getCode() == KeyCode.TAB) { return; } ObservableList<T> list = FXCollections.observableArrayList(); data.stream().forEach((aData) -> { if (mode.equals(AutoCompleteMode.STARTS_WITH) && aData.toString().toLowerCase().startsWith(comboBox.getEditor().getText().toLowerCase())) { list.add(aData); } else if (mode.equals(AutoCompleteMode.CONTAINING) && aData.toString().toLowerCase().contains(comboBox.getEditor().getText().toLowerCase())) { list.add(aData); } }); String t = comboBox.getEditor().getText(); comboBox.setItems(list); comboBox.getEditor().setText(t); if (!moveCaretToPos) { caretPos = -1; } moveCaret(t.length()); if (!list.isEmpty()) { comboBox.show(); } } private void moveCaret(int textLength) { if (caretPos == -1) { comboBox.getEditor().positionCaret(textLength); } else { comboBox.getEditor().positionCaret(caretPos); } moveCaretToPos = false; } }); } /** * Convinient class which return null-safe combobox value. * @param <T> * @param comboBox * @return */ public static <T> T getComboBoxValue(ComboBox<T> comboBox) { if (comboBox.getSelectionModel().getSelectedIndex() < 0) { return null; } else { return comboBox.getItems().get(comboBox.getSelectionModel().getSelectedIndex()); } } /** * Sets format on a date picker. * A format is defined in the Formats class. * @param datePicker */ public static void setDatePickerFormat(DatePicker datePicker) { datePicker.setConverter(new StringConverter<LocalDate>() { DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(Formats.pattern); @Override public String toString(LocalDate date) { if (date != null) { return dateFormatter.format(date); } else { return ""; } } @Override public LocalDate fromString(String string) { if (string != null && !string.isEmpty()) { return LocalDate.parse(string, dateFormatter); } else { return null; } } }); } /** * Convinient method which forces table to start editing on keyboard key press. * @param tableView */ public static void setEditTableOnKeyPress(TableView tableView) { tableView.addEventFilter(KeyEvent.KEY_PRESSED, (KeyEvent event) -> { if (event.getCode() == KeyCode.ENTER) { return; } else if (event.getCode() == KeyCode.TAB && tableView.getEditingCell() == null) { event.consume(); tableView.getSelectionModel().selectNext(); } if (tableView.getEditingCell() == null) { if (event.getCode().isLetterKey() || event.getCode().isDigitKey()) { TablePosition focusedCellPosition = tableView.getFocusModel().getFocusedCell(); tableView.edit(focusedCellPosition.getRow(), focusedCellPosition.getTableColumn()); } } }); } }
package br.com.treinarminas.academicos.operadores; public class Comparacao { public static void main(String[] args) { int a = 5; int b = 1; System.out.println(a >= b); boolean maiorIgual = a >= b; System.out.println(maiorIgual); System.out.println(a >= b); int c = 8; int d = 10; System.out.println(c <= d); boolean menorIgual = c <= d; System.out.println(menorIgual); System.out.println(c <= d); int e = 13; int f = 4; System.out.println(e > f); boolean maior = e > f; System.out.println(maior); System.out.println(e > f); } }
// Sun Certified Java Programmer // Chapter 2, P113 // Object Orientation public class Animal { public void eat() { System.out.println("Generic Animal Eating Generically"); } }
package app; import api.TraqApi; import db.Database; import http.MusicServer; import log.Logger; import skyway.SkywayApi; import update.response.ResponseManager; public interface Bot { Database getDatabase(); Properties getProperties(); MusicServer getMusicServer(); TraqApi getTraqApi(); SkywayApi getSkywayApi(); Logger getLogger(); ResponseManager getResponseManager(); }
package com.google.android.gms.tagmanager; final class v<T> { final T bbK; final boolean bbL; v(T t, boolean z) { this.bbK = t; this.bbL = z; } }
package io.sugo.DriveRobot; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Random; /** * Created by qwe on 17-7-13. */ public class Util { private static final String numBase = "0123456789"; private static final String strBase = "abcdefghijklmnopqrstuvwxyz0123456789"; private static Random random = new Random(); public static MessageDigest md; public static String randomNumString(int length) { //length表示生成字符串的长度 StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; i++) { int number = random.nextInt(numBase.length()); sb.append(numBase.charAt(number)); } return sb.toString(); } public static String randomString(int length) { //length表示生成字符串的长度 StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; i++) { int number = random.nextInt(strBase.length()); sb.append(strBase.charAt(number)); } return sb.toString(); } public static String randomPhoneString() { StringBuffer sb = new StringBuffer(); sb.append( DataConst.phone_pre[random.nextInt(DataConst.phone_pre.length)] ); return sb.append(randomNumString(8)).toString(); } static String[] Surname = {"赵","钱","孙","李","周","吴","郑","王","冯","陈","褚","卫","蒋","沈","韩","杨","朱","秦","尤","许", "何","吕","施","张","孔","曹","严","华","金","魏","陶","姜","戚","谢","邹","喻","柏","水","窦","章","云","苏","潘","葛","奚","范","彭","郎", "鲁","韦","昌","马","苗","凤","花","方","俞","任","袁","柳","酆","鲍","史","唐","费","廉","岑","薛","雷","贺","倪","汤","滕","殷", "罗","毕","郝","邬","安","常","乐","于","时","傅","皮","卞","齐","康","伍","余","元","卜","顾","孟","平","黄","和", "穆","萧","尹","姚","邵","湛","汪","祁","毛","禹","狄","米","贝","明","臧","计","伏","成","戴","谈","宋","茅","庞","熊","纪","舒", "屈","项","祝","董","梁","杜","阮","蓝","闵","席","季","麻","强","贾","路","娄","危","江","童","颜","郭","梅","盛","林","刁","钟", "徐","邱","骆","高","夏","蔡","田","樊","胡","凌","霍","虞","万","支","柯","万俟","司马","上官","欧阳","夏侯","诸葛",}; public static String randomChineseName() { int index=random.nextInt(Surname.length-1); String name = Surname[index]; //获得一个随机的姓氏 /* 从常用字中选取一个或两个字作为名 */ if(random.nextBoolean()){ name+=getChinese()+getChinese(); }else { name+=getChinese(); } return name; } public static String getChinese(){ String str = null; int highPos, lowPos; Random random = new Random(); highPos = (176 + Math.abs(random.nextInt(71)));//区码,0xA0打头,从第16区开始,即0xB0=11*16=176,16~55一级汉字,56~87二级汉字 random=new Random(); lowPos = 161 + Math.abs(random.nextInt(94));//位码,0xA0打头,范围第1~94列 byte[] bArr = new byte[2]; bArr[0] = (new Integer(highPos)).byteValue(); bArr[1] = (new Integer(lowPos)).byteValue(); try { str = new String(bArr, "GB2312"); //区位码组合成汉字 } catch (Exception e) { e.printStackTrace(); } return str; } public static String getMd5Sum(String pos) { try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } StringBuffer sb = new StringBuffer(); md.reset(); md.update(pos.getBytes()); byte[] digest = md.digest(); for (byte b : digest) { sb.append(String.format("%02x", b & 0xff)); } return sb.toString(); } public static String getNameByRate(String[][] strings) { int index = random.nextInt(100); for(int i=0;i<strings.length;i++) { if(index < Integer.parseInt(strings[i][1])) { return strings[i][0]; } } return ""; } public static String getOrderId(int order) { String orderStr= order+""; int num = 12 - orderStr.length(); for(int i=0;i<num;i++) { orderStr += "0"; } return "SG"+orderStr; } }
package example.jamesb.moviessample.presentation; import android.os.Build; import android.os.Bundle; import javax.inject.Inject; import androidx.annotation.ColorInt; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.navigation.NavController; import androidx.navigation.Navigation; import dagger.android.AndroidInjection; import dagger.android.AndroidInjector; import dagger.android.DispatchingAndroidInjector; import dagger.android.support.HasSupportFragmentInjector; import example.jamesb.moviessample.R; public class MainActivity extends AppCompatActivity implements HasSupportFragmentInjector { @Inject DispatchingAndroidInjector<Fragment> dispatchingAndroidInjector; private NavController mNavController; @Override protected void onCreate(Bundle savedInstanceState) { AndroidInjection.inject(this); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mNavController = Navigation.findNavController(this, R.id.navigation_host_fragment); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public boolean setStatusBarColor(@ColorInt int targetColor) { int currentStatusBarColor = getWindow().getStatusBarColor(); if (currentStatusBarColor == targetColor) { return false; } getWindow().setStatusBarColor(targetColor); return true; } @Override public AndroidInjector<Fragment> supportFragmentInjector() { return dispatchingAndroidInjector; } @Override public boolean onSupportNavigateUp() { return mNavController.navigateUp(); } }
package com.rackspace.sl.suite; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.Period; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class Test { public static void main(String[] args) { ArrayList<String> l = new ArrayList<String>(); l.add("Pavan"); l.add("RaviTeja"); l.add("Chiranjeevi"); l.add("Venkatesh"); l.add("Nagarjuna"); System.out.println(l); List<String> l1 = l.stream().filter(s -> s.length() >= 9).collect(Collectors.toList()); System.out.println(l1); List<String> l4 = l.stream().filter(s -> s.length() <= 9).collect(Collectors.toList()); System.out.println(l4); List<String> l2 = l.stream().map(s -> s.toUpperCase()).collect(Collectors.toList()); System.out.println(l2); List<String> l3 = l.stream().map(s -> s.toLowerCase()).collect(Collectors.toList()); System.out.println(l3); long count = l.stream().filter(s -> s.length() >= 9).count(); System.out.println("The Number of Strings whose lenth is >=9 : " + count); // To Print Current System Date LocalDate date = LocalDate.now(); System.out.println("date " + date); int dd = date.getDayOfMonth(); int mm = date.getMonthValue(); int yyyy = date.getYear(); System.out.println(dd + "..." + mm + "..." + yyyy); System.out.printf("%d-%d-%d\n", dd, mm, yyyy); // To Print Current System Time LocalTime time = LocalTime.now(); System.out.println("time " + time); int hour = time.getHour(); int minute = time.getMinute(); int second = time.getSecond(); int nanoSecond = time.getNano(); System.out.printf("%d-%d-%d-%d", hour, minute, second, nanoSecond); LocalDateTime dt = LocalDateTime.now(); System.out.println("LocalDateTime === " + dt); int day = dt.getDayOfMonth(); int month = dt.getMonthValue(); int year = dt.getYear(); System.out.printf("\n Date : %d-%d-%d", day, month, year); int hours = dt.getHour(); int minutes = dt.getMinute(); int seconds = dt.getSecond(); int nanoSeconds = dt.getNano(); System.out.printf("\n Time : %d-%d-%d-%d", hours, minutes, seconds, nanoSeconds); LocalDateTime dt1 = LocalDateTime.of(1995, 05, 28, 12, 45); System.out.println("\n To Print perticular Date : " + dt1); System.out.println("\n After Six Months : " + dt1.plusMonths(6)); System.out.println("\n Before Six Months : " + dt1.minusMonths(6)); System.out.println("\n After Six Years : " + dt1.plusYears(6)); System.out.println("\n Before Six Years : " + dt1.minusYears(6)); LocalDate birthday = LocalDate.of(1989, 8, 28); LocalDate today = LocalDate.now(); Period p = Period.between(birthday, today); System.out.printf("\n Your Age Is %d Years %d Months and %d Days ", p.getYears(), p.getMonths(), p.getDays()); LocalDate deathday = LocalDate.of(1989, 8, 28); Period p1 = Period.between(today, deathday); int d = p1.getYears() * 365 + p1.getMonths() * 30 + p1.getDays(); System.out.printf("\n Your will be on earth only %d days,Hurry up to do more important things ", d); LocalDateTime localDateTime = LocalDateTime.of(birthday, time); System.out.println("\n localDateTime ==== " + localDateTime); } }
package com.technology.share.mapper; import com.technology.share.domain.RolePermission; public interface RolePermissionMapper extends MyMapper<RolePermission> { }
package com.kareo.ui.codingcapture.implementation.controller; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.*; import java.util.*; import com.kareo.ui.codingcapture.implementation.data.*; import org.joda.time.DateTime; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.fasterxml.jackson.databind.ObjectMapper; import com.kareo.library.kareoframework.error.exceptions.ServiceException; import com.kareo.library.kareoframework.error.exceptions.ValidationException; import com.kareo.library.kareoframework.helpers.RestClientHelper; import com.kareo.services.auxiliary.idtranslation.IdTranslationAuxiliaryClient; import com.kareo.services.auxiliary.idtranslation.Translation; import com.kareo.services.auxiliary.idtranslation.TranslationRequest; import com.kareo.services.auxiliary.idtranslation.TranslationResponse; import com.kareo.services.service.customer.CustomerServiceClient; import com.kareo.services.service.customer.Practice; import com.kareo.services.service.patient.PatientServiceClient; import com.kareo.services.service.patient.datacontracts.Address; import com.kareo.services.service.patient.datacontracts.requests.PatientSearchQuery; import com.kareo.services.service.patient.datacontracts.responses.PatientSearchQueryResponse; import com.kareo.ui.codingcapture.implementation.PatientTestData; import com.kareo.ui.codingcapture.implementation.util.IdTranslator; public class PatientControllerImplTest { @Mock private PatientServiceClient patientServiceClient; private PatientControllerImpl patientControllerToTest; @Mock private RestClientHelper restClient; @Mock private CustomerServiceClient customerServiceClient; @Mock private IdTranslationAuxiliaryClient idTranslationclient; public static final Random RANDOM = new Random(); public static final long PATIENTID = RANDOM.nextLong(); @BeforeMethod public void initialize() { MockitoAnnotations.initMocks(this); patientControllerToTest = new PatientControllerImpl(patientServiceClient, new IdTranslator(idTranslationclient), restClient, "local"); } @Test(expectedExceptions = ValidationException.class) public void searchPatients_shouldReturnValidationExceptionIfFilterIsEmpty() { //GIVEN String filter = ""; //THEN patientControllerToTest.searchPatients(1, PatientTestData.PRACTICEID, filter); } @Test(expectedExceptions = ValidationException.class) public void searchPatients_shouldReturnValidationExceptionIfInvalidPracticeId() { patientControllerToTest.searchPatients(1, 0, "asdf"); } @Test(expectedExceptions = ServiceException.class) public void searchPatients_shouldReturnServiceExceptionIfInvalidPatientId() { patientControllerToTest.getPatient(1, -1); } public void searchPatientsTest() { //given String filter = "aa"; PatientSearchQueryResponse serviceResponse = new PatientSearchQueryResponse(); List<com.kareo.services.service.patient.datacontracts.PatientSummary> patientSumaryListExpected = PatientTestData.createServicePatientSummaryList(); serviceResponse.setPatients(patientSumaryListExpected); given(patientServiceClient.getPatientsBySearch(any(PatientSearchQuery.class))) .willReturn(serviceResponse); //when List<PatientSummary> patientSummaryList = patientControllerToTest.searchPatients(1, PatientTestData.PRACTICEID, filter); //then Assert.assertNotNull(patientSummaryList); Assert.assertEquals(patientSumaryListExpected.size(), patientSummaryList.size()); } @Test public void getPatientTest() { //given com.kareo.services.service.patient.datacontracts.Patient patient = new com.kareo.services.service.patient.datacontracts.Patient(); List<com.kareo.services.service.patient.datacontracts.Address> addressList = new ArrayList<Address>(); com.kareo.services.service.patient.datacontracts.Address address = new com.kareo.services.service.patient.datacontracts.Address(); address.setStateId(137); addressList.add(address); given(patientServiceClient.getPatient(anyLong())).willReturn(patient); given(patientServiceClient.getPatientAddresses(anyLong())).willReturn(addressList); given(customerServiceClient.getPractice(anyLong())).willReturn(new Practice()); given(idTranslationclient.translate(any(TranslationRequest.class))).willReturn(getMockTranslation()); //when Patient mappedPatient = patientControllerToTest.getPatient(1, PATIENTID); //then Assert.assertNotNull(mappedPatient); } @Test public void testFindPatientCases() { PMPatientCaseResponse caseResponse = getPatientMockResponse(); //given given(restClient.sendHttpGet(anyString(), any(Class.class), any(ObjectMapper.class))).willReturn(caseResponse); //when List<PatientCase> result = patientControllerToTest.findPatientCases(1, 1); //then Assert.assertNotNull(result); Assert.assertEquals(result.size(), 2); } @Test(expectedExceptions = {ValidationException.class}) public void testFindPatientCasesInvalidCustomerId() { patientControllerToTest.findPatientCases(0, 1); } @Test(expectedExceptions = {ValidationException.class}) public void testFindPatientCasesInvalidPatientId() { patientControllerToTest.findPatientCases(1, 0); } @Test(expectedExceptions = {ValidationException.class}) public void testFindPatientInsurancePoliciesInvalidCustomerId() { patientControllerToTest.findPatientInsurancePolicies(0, 1); } @Test(expectedExceptions = {ValidationException.class}) public void testFindPatientInsurancePoliciesInvalidPatientId() { patientControllerToTest.findPatientInsurancePolicies(1, 0); } @Test public void testFindPatientInsurancePolicies() { PMPatientInsurancePolicyResponse insuranceResponse = getInsurancePolicies(); InsuranceCompanyPlan plan1 = getInsuranceCompanyPlan("Plan1"); InsuranceCompanyPlan plan2 = getInsuranceCompanyPlan("Plan2"); given(restClient.sendHttpGet(anyString(), any(Class.class), any(ObjectMapper.class))).willReturn(insuranceResponse, plan1, plan2); PatientInsurance result = patientControllerToTest.findPatientInsurancePolicies(1, 1); Assert.assertNotNull(result); Assert.assertNotNull(result.getPrimaryInsurance()); Assert.assertNotNull(result.getSecondaryInsurance()); } @Test public void testPatientPreferences(){ PatientPreference patientPreference = new PatientPreference(); patientPreference.setDefaultServiceLocationId(1); patientPreference.setPrimaryProviderId(2); given(restClient.sendHttpPost(anyString(), anyObject(), any(Class.class), any(ObjectMapper.class))).willReturn(patientPreference); given(idTranslationclient.translate(any(TranslationRequest.class))).willReturn(getMockTranslation()); PatientPreference result = patientControllerToTest.findPatientPreferences(100l, 123l); Assert.assertNotNull(result); Assert.assertEquals(patientPreference.getDefaultServiceLocationId(),result.getDefaultServiceLocationId()); Assert.assertEquals(patientPreference.getPrimaryProviderId(),result.getPrimaryProviderId()); } private InsuranceCompanyPlan getInsuranceCompanyPlan(String name) { InsuranceCompanyPlan companyPlan = new InsuranceCompanyPlan(); companyPlan.setPlanName(name); return companyPlan; } private PMPatientInsurancePolicyResponse getInsurancePolicies() { List<PatientInsurancePolicy> insurancePolicies = new ArrayList<PatientInsurancePolicy>(); insurancePolicies.add(getPatientInsurancePolicy()); insurancePolicies.add(getPatientInsurancePolicy()); PMPatientInsurancePolicyResponse policyResponse = new PMPatientInsurancePolicyResponse(insurancePolicies); return policyResponse; } private PatientInsurancePolicy getPatientInsurancePolicy() { PatientInsurancePolicy policy = new PatientInsurancePolicy(); policy.setActive(true); return policy; } private PMPatientCaseResponse getPatientMockResponse() { List<PatientCase> patientCases = new ArrayList<PatientCase>(); patientCases.add(getPatientCase(1, new DateTime(123456))); patientCases.add(getPatientCase(2, new DateTime(123456700))); PMPatientCaseResponse response = new PMPatientCaseResponse(patientCases); return response; } private PatientCase getPatientCase(long id, DateTime dateTime){ PatientCase case1 = new PatientCase(); case1.setPatientCaseId(id); case1.setActive(true); case1.setModifiedDate(dateTime); return case1; } private TranslationResponse getMockTranslation() { TranslationResponse response = new TranslationResponse(); response.setTranslations(new ArrayList<Translation>()); response.getTranslations().add(new Translation(){{setTo("1");}}); return response; } }
package com.penzias.entity; /** * 描述:用药历史<br> * 作者:ruibo <br> * 修改日期:2015年12月10日-下午9:28:28 <br> * E-mail: sireezhang@163.com<br> */ public class HistoryPharmacy { private Integer pharmacyid; private Integer crowdid; //用药类型(ZU--前2位) private String pharmacytype; //用药名称(ZU--4或6位) private String pharmacyname; //用药年限 private String pharmacyyear; //用药情况(0:规律;1:不规律) private String pharmacysituation; private String flag; public Integer getPharmacyid() { return pharmacyid; } public void setPharmacyid(Integer pharmacyid) { this.pharmacyid = pharmacyid; } public Integer getCrowdid() { return crowdid; } public void setCrowdid(Integer crowdid) { this.crowdid = crowdid; } public String getPharmacytype() { return pharmacytype; } public void setPharmacytype(String pharmacytype) { this.pharmacytype = pharmacytype; } public String getPharmacyname() { return pharmacyname; } public void setPharmacyname(String pharmacyname) { this.pharmacyname = pharmacyname; } public String getPharmacyyear() { return pharmacyyear; } public void setPharmacyyear(String pharmacyyear) { this.pharmacyyear = pharmacyyear; } public String getPharmacysituation() { return pharmacysituation; } public void setPharmacysituation(String pharmacysituation) { this.pharmacysituation = pharmacysituation; } public String getFlag() { return flag; } public void setFlag(String flag) { this.flag = flag; } }
package com.team_linne.digimov.model; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.FieldType; import org.springframework.data.mongodb.core.mapping.MongoId; @Document public class Cinema { @MongoId(FieldType.OBJECT_ID) private String id; private String name; private String address; private String imageUrl; private String openingHours; private String hotline; public Cinema(String name, String address, String imageUrl, String openingHours, String hotline) { this.name = name; this.address = address; this.imageUrl = imageUrl; this.openingHours = openingHours; this.hotline = hotline; } public Cinema() { } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getOpeningHours() { return openingHours; } public void setOpeningHours(String openingHours) { this.openingHours = openingHours; } public String getHotline() { return hotline; } public void setHotline(String hotline) { this.hotline = hotline; } }
package com.team.zhihu.controller; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.team.zhihu.bean.Comment; import com.team.zhihu.bean.Essay; import com.team.zhihu.bean.Topic; import com.team.zhihu.bean.User; import com.team.zhihu.bean.commentUser; import com.team.zhihu.mapper.CommentMapper; import com.team.zhihu.mapper.EssayMapper; import com.team.zhihu.mapper.TopicMapper; import com.team.zhihu.mapper.UserMapper; import com.team.zhihu.utils.DateUtil; @Controller public class wendaController { //@author 于增才 @Autowired EssayMapper essayMapper; @Autowired TopicMapper topicmapper; @Autowired UserMapper UserMapper; @Autowired CommentMapper commentMapper; @RequestMapping("wenda") public String towendaHtml(Integer id, Map<String,Object> map) { //查询诸多要素 System.out.println(id); Essay essay = essayMapper.selectByPrimaryKey(id); Topic topic =topicmapper.selectByPrimaryKey(essay.getTopictype()); map.put("topicName", topic); User user = UserMapper.selectByPrimaryKey(essay.getUserid()); map.put("myessay", essay); map.put("user",user); List<Comment> comments = commentMapper.selectByEssayid(essay.getId()); List<commentUser> commentUsers = new ArrayList<commentUser>(); for(Comment comment:comments) { User user1 = UserMapper.selectByPrimaryKey(comment.getUserid()); commentUser commentUser = new commentUser(comment.getId(), user1, comment.getContext(),comment.getDate()); commentUsers.add(commentUser); } map.put("commnentUsers", commentUsers); return "wenda"; } @RequestMapping("wenda/commment") public void wendaComment(Comment comment) { Date date = new Date(); String date1 = DateUtil.dateToString(date); comment.setDate(date1); System.out.println(comment.toString()); commentMapper.insert(comment); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.webbeans.test.discovery; import org.apache.webbeans.corespi.scanner.xbean.CdiArchive; import org.apache.webbeans.corespi.se.DefaultScannerService; import org.apache.webbeans.spi.BeanArchiveService; import org.apache.webbeans.spi.ScannerService; import org.apache.webbeans.test.AbstractUnitTest; import org.apache.webbeans.util.WebBeansUtil; import org.apache.webbeans.xml.DefaultBeanArchiveInformation; import org.apache.xbean.finder.AnnotationFinder; import org.junit.Test; import jakarta.annotation.Priority; import jakarta.enterprise.context.ApplicationScoped; import jakarta.interceptor.AroundInvoke; import jakarta.interceptor.Interceptor; import jakarta.interceptor.InterceptorBinding; import jakarta.interceptor.InvocationContext; import java.io.IOException; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; import java.util.Map; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.util.Arrays.asList; import static java.util.Collections.emptyMap; import static java.util.Collections.singletonMap; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; public class InterceptorAnnotatedDiscoveryTest extends AbstractUnitTest { @Test public void discover() { setClasses(FooInterceptor.class.getName(), FooMe.class.getName()); startContainer(); assertEquals("foo", getInstance(FooMe.class).foo()); } private void setClasses(final String... classes) { // replace the implicit BDA by an annotated one addService(ScannerService.class, new DefaultScannerService() { @Override protected AnnotationFinder initFinder() { if (finder != null) { return finder; } super.initFinder(); archive = new CdiArchive(webBeansContext().getBeanArchiveService(), WebBeansUtil.getCurrentClassLoader(), emptyMap(), null, null) { @Override public Map<String, FoundClasses> classesByUrl() { try { final String url = "openwebbeans://annotated"; return singletonMap(url, new FoundClasses( new URL("openwebbeans", null, -1, "annotated", new URLStreamHandler() { @Override protected URLConnection openConnection(final URL u) throws IOException { return new URLConnection(u) { @Override public void connect() throws IOException { // no-op } }; } }), asList(classes), new DefaultBeanArchiveInformation("openwebbeans://default") {{ setBeanDiscoveryMode(BeanArchiveService.BeanDiscoveryMode.ANNOTATED); }})); } catch (final MalformedURLException e) { fail(e.getMessage()); throw new IllegalStateException(e); } } }; return finder; } }); } @Interceptor @Foo @Priority(0) public static class FooInterceptor { @AroundInvoke public Object foo(final InvocationContext ic) { return "foo"; } } @Foo @ApplicationScoped public static class FooMe { String foo() { return "bar"; } } @InterceptorBinding @Retention(RUNTIME) @Target(TYPE) public @interface Foo { } }
package ru.otus.services; /* * Created by VSkurikhin at autumn 2018. */ import javax.websocket.Session; public interface DataBroadcaster extends AutoCloseable { void registerDataOrigin(String name, DataOrigin origin); void unregisterDataOrigin(String name); void registerDataUpdater(Session session, DataUpdater updater); void unregisterDataUpdater(Session session); void start(); void shutdown() throws InterruptedException; } /* vim: syntax=java:fileencoding=utf-8:fileformat=unix:tw=78:ts=4:sw=4:sts=4:et */ //EOF
package com.qd.mystudy.misc; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.util.TypeUtils; /** * Created by liqingdong on 15/10/27. */ public class TestFastjson { public static enum Enum { Test(-1, false), None(0x00, false), RegisteredDevice(0x0100, false), User(0x0200, true), UserTrustedDevice(0x0400, true), MobileOwner(0x0800, false), MobileOwnerTrustedDevice(0x1000, false), UserLogin(0x2000, true), UserLoginAndMobileOwner(UserLogin.code | MobileOwner.code, UserLogin.needUserToken | MobileOwner.needUserToken), Integrated(0x10000000, false); public int getCode() { return code; } private int code; private boolean needUserToken; private Enum(int code, boolean needUserToken) { this.code = code; this.needUserToken = needUserToken; } public boolean isNeedUserToken() { return needUserToken; } } public static class UserInfo{ public int i=1; public Long l = new Long(2); @Override public String toString() { return "UserInfo{" + "i=" + i + ", l=" + l + '}'; } } public static void main(String[] args) { UserInfo userInfo = new UserInfo(); System.out.println(JSON.toJSONString(userInfo)); String abc = "{\"i\":\"1\",\"l\":2}"; System.out.println(JSON.parseObject(abc, userInfo.getClass())); System.out.println(Enum.None.ordinal()); System.out.println(Enum.Test.ordinal()); System.out.println(Enum.valueOf("Test")); System.out.println(TypeUtils.castToEnum(1, Enum.class, null)); } }
package Aula11; import java.util.ArrayList; public class Prato implements MyComparable{ protected String nome; protected ArrayList<Alimento> ingredientes = new ArrayList<Alimento>(); public Prato(String aNome) { this.nome = aNome; } public String getNome() { return nome; } public ArrayList<Alimento> getIngredientes() { return ingredientes; } public double getMaxProteinas() { return 0; } public boolean addIngrediente(Alimento a) { if (this instanceof PratoVegetariano) { if (a instanceof Vegetariano) { this.ingredientes.add(a); return true; } else return false; } else if (this instanceof PratoDieta) { if ((this.calcularCalorias()+a.getCalorias())<=this.getMaxProteinas()) { this.ingredientes.add(a); return true; } else return false; } else if (this instanceof Prato) { this.ingredientes.add(a); return true; } return false; } private boolean equalsIngredientes(ArrayList<Alimento> a) { if (this.ingredientes.size()!=a.size()) return false; else { for(int i=0; i<this.ingredientes.size(); i++) if (!this.ingredientes.get(i).equals(a.get(i))) return false; } return true; } public double calcularCalorias() { double calorias=0; for (int i=0; i<this.ingredientes.size(); i++) calorias += this.ingredientes.get(i).getCalorias(); return calorias; } @Override public boolean equals(Object obj) { if (obj==null || getClass()!=obj.getClass()) return false; if (obj==this) return true; Prato p = (Prato) obj; return (this.nome.equals(p.getNome()) && this.equalsIngredientes(p.getIngredientes())); } @Override public String toString() { return this.nome + " composto por " + this.ingredientes.size() + " ingredientes"; } @Override public int compareTo(Object obj) { assert (getClass()!=obj.getClass() || obj==null); Prato p = (Prato) obj; if (this.calcularCalorias()>p.calcularCalorias()) return 1; else if (this.calcularCalorias()<p.calcularCalorias()) return -1; else return 0; } }
/** *Author Fys * *Time 2016-7-5-下午2:02:12 **/ package com.goldgov.dygl.module.partyMemberDuty.partyevaluatedata.dao; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Param; import com.goldgov.dygl.module.partyMemberDuty.mutualevaluation.service.PmUserQuery; import com.goldgov.dygl.module.partyMemberDuty.partyevaluatedata.domain.EvaluateData; import com.goldgov.gtiles.core.dao.mybatis.annotation.MybatisRepository; @MybatisRepository("iEvaluateDataDao") public interface IEvaluateDataDao { public Map<String, Object> getDatesByID(@Param("id")String id) ; public List<EvaluateData> getEvaluateDataListByEvaluateId(@Param("evaluateId")String ratedId) throws Exception; public List<String> getAllActiveLoginId() throws Exception; public void updateEvaluateData(EvaluateData newData) throws Exception; public void addEvaluateData(EvaluateData newData) throws Exception; public List<EvaluateData> findEvaluateList(@Param("query")PmUserQuery query) throws Exception; public Integer getMaxEvaluateYear(); public Integer getMaxMonthInYear(@Param("year")int maxYear); }
package com.algorithms; /** * Created by saml on 10/30/2017. */ public class Josephus { static class Node { int index; Node next; Node prev; public Node(int index) { this.index = index; } public void setNext(Node node) { this.next = node; } public void setPrev(Node node) { this.prev = node; } } public static Node kill(Node node, int count) { Node tmp = null; if (node.next != null && count < 6) { tmp = kill(node.next, ++count); } else if (node.next == null && node.prev == null) { System.out.println(node.index); tmp = node; } else { node.prev.next = node.next; node.next.prev = node.prev; tmp = node.prev.next; System.out.println(node.index+" be killed..."); node.next = null; node.prev = null; node = null; } return tmp; } public static void main(String[] args) { Node node1 = new Node(1); Node node2 = new Node(3); Node node3 = new Node(5); Node node4 = new Node(0); Node node5 = new Node(4); Node node6 = new Node(2); Node node7 = new Node(6); node1.setNext(node2); node2.setNext(node3); node3.setNext(node4); node4.setNext(node5); node5.setNext(node6); node6.setNext(node7); node7.setNext(node1); node1.setPrev(node7); node2.setPrev(node1); node3.setPrev(node2); node4.setPrev(node3); node5.setPrev(node4); node6.setPrev(node5); node7.setPrev(node6); Node node = null; do { if (node != null) { node = kill(node, 0); } else { node = kill(node1, 0); } } while (node.next != null && node.prev != null); System.out.println(node.index); } }
package ru.krasview.kvlib.adapter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.xmlpull.v1.XmlPullParserException; import ru.krasview.kvlib.indep.consts.AuthRequestConst; import ru.krasview.kvlib.indep.ListAccount; import com.example.kvlib.R; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer; import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer; import com.nostra13.universalimageloader.core.listener.ImageLoadingListener; import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.XmlResourceParser; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; public class CombineSimpleAdapter extends BaseAdapter { private DisplayImageOptions options; private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener(); protected int mCount; protected List<Map<String, Object>> mConstData; protected List<Map<String, Object>> mData = new ArrayList< Map<String, Object>>(); protected String mAddress; protected ru.krasview.kvlib.widget.List mParent; protected int withAuth = AuthRequestConst.AUTH_NONE; protected ColorStateList colors = null; private boolean mRecFocus = true; protected final void parseData(String doc, LoadDataToGUITask task) { mParent.parseData(doc, task); } protected void postExecute() {}; public CombineSimpleAdapter(ru.krasview.kvlib.widget.List parent, List<Map<String, Object>> constData, String address, int auth, boolean focus) { this(parent, constData, address, auth); mRecFocus = focus; } public CombineSimpleAdapter(ru.krasview.kvlib.widget.List parent, List<Map<String, Object>> constData, String address, int auth) { super(); options = new DisplayImageOptions.Builder() .showImageOnLoading(R.drawable.series) .showImageForEmptyUri(R.drawable.series) .showImageOnFail(null) .cacheInMemory(true) .cacheOnDisc(true) .considerExifParams(true) .displayer(new SimpleBitmapDisplayer()) .build(); if(constData == null) { constData = new ArrayList<Map<String, Object>>(); } mConstData = constData; mAddress = address; withAuth = auth; if(withAuth > 2 || withAuth < 0) { withAuth = 0; } mParent = parent; //noinspection ResourceType XmlResourceParser parser = mParent.getContext().getResources().getXml(R.color.text_selector); try { colors = ColorStateList.createFromXml(mParent.getContext().getResources(), parser); } catch (XmlPullParserException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public List<Map<String, Object>> getData() { return mData; } @SuppressWarnings("unchecked") @Override public View getView(int position, View convertView, ViewGroup parent) { Map<String,Object> map = (Map<String, Object>)getItem(position); View view; ViewHolder holder; if(convertView == null) { LayoutInflater inflater = (LayoutInflater) parent.getContext() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.kv_multi_item, parent, false); holder = new ViewHolder(); holder.background = view.findViewById(R.id.top); holder.name = (TextView) view.findViewById(R.id.txt); holder.image = (ImageView) view.findViewById(R.id.image); holder.progress = ((ProgressBar)view.findViewById(R.id.progress)); holder.time = ((TextView)view.findViewById(R.id.time)); holder.current_program = (TextView)view.findViewById(R.id.current_program); holder.currentLayout = view.findViewById(R.id.current_layout); holder.new_series = (TextView)view.findViewById(R.id.new_series); if(ListAccount.fromLauncher) { view.setBackgroundResource(R.drawable.selector); holder.name.setTextColor(colors); holder.current_program.setTextColor(colors); Drawable progress_tv = mParent.getContext().getResources().getDrawable(R.drawable.progress_tv); holder.progress.setProgressDrawable(progress_tv); } view.setTag(holder); } else { view = convertView; } return BindView(view, map); } private View BindView(View view, Map<String, Object> map) { ViewHolder holder = (ViewHolder) view.getTag(); //название if(map.get("name") != null) { holder.name.setVisibility(View.VISIBLE); holder.name.setText((CharSequence) map.get("name")); } else { holder.name.setVisibility(View.GONE); } String type = (String) map.get("type"); if(type == null) { holder.background.setVisibility(View.GONE); holder.image.setVisibility(View.GONE); holder.currentLayout.setVisibility(View.GONE); holder.new_series.setVisibility(View.GONE); return view; } if(type.equals("billing")) { holder.background.setVisibility(View.VISIBLE); holder.currentLayout.setVisibility(View.GONE); holder.new_series.setVisibility(View.GONE); } else { holder.background.setVisibility(View.GONE); } //статус if(map.get("state") != null) { if(map.get("state").equals("0")) { holder.background.setBackgroundColor(Color.argb(100, 100, 100, 100)); } else { holder.background.setBackgroundColor(Color.argb(0, 0, 0, 0)); } } //картинка if(map.get("img_uri") != null) { holder.image.setVisibility(View.VISIBLE); //загрузить картинку ImageLoader.getInstance().displayImage((String)map.get("img_uri"), holder.image, options, animateFirstListener); } else { holder.image.setVisibility(View.INVISIBLE); } //текущая программа if(type.equals("channel")) { holder.currentLayout.setVisibility(View.VISIBLE); if(map.get("current_program_name") == null) { if( map.get("current_program_name_old") != null) { map.put("current_program_name", map.get("current_program_name_old")); } else { map.put("current_program_name", ""); map.put("current_program_time", ""); map.put("current_program_progress", 0); } notifyDataSetChanged(); new LoadCurrentProgram(this, map).execute(); } else if(map.get("current_program_name") != null) { CharSequence pr = (CharSequence)map.get("current_program_name"); if(pr.equals("<пусто>")) { pr = ""; } holder.current_program.setText(pr); holder.progress.setProgress((Integer)map.get("current_program_progress")); holder.time.setText((CharSequence)map.get("current_program_time")); } } else { holder.currentLayout.setVisibility(View.GONE); } //число новых серий if(type.equals("series")) { if(map.get("new_series") == null) { holder.new_series.setVisibility(View.GONE); new LoadNewSeriesNumber(this,map).execute(); map.put("new_series", 0); } else if(map.get("new_series") != null && (Integer)map.get("new_series") == 0) { holder.new_series.setVisibility(View.GONE); } else { holder.new_series.setText("+" + map.get("new_series")); holder.new_series.setVisibility(View.VISIBLE); } } if(type.equals("video")) { holder.image.setVisibility(View.GONE); } return view; } class ViewHolder { View background; TextView name; ImageView image; TextView time; TextView current_program; ProgressBar progress; View currentLayout; TextView new_series; } @Override public int getCount() { return mConstData.size() + mData.size(); } public int getConstDataCount() { return mConstData.size(); } @Override public Object getItem(int position) { if(position >= 0 && position < mConstData.size()) { return mConstData.get(position); } else { Object obj; try { obj = mData.get(position - mConstData.size()); } catch(Exception e) { Log.e("Debug", "" + position + " " + (position - mConstData.size()) + " " + e.toString()); return null; } return obj; } } @Override public long getItemId(int position) { return position; } public void refresh() { String params = ""; if(mAddress == null) { return; }; mData.clear(); loadDataFromAddress(mAddress, params); } protected void loadDataFromAddress(String uri, String params) { LoadDataFromAddressTask task = new LoadDataFromAddressTask(this); task.execute(uri, params); } @Override public void notifyDataSetChanged () { int size = mData.size(); super.notifyDataSetChanged(); if(size == 1 && mRecFocus) { mParent.requestFocus(); } } public void setAddress(String address) { mAddress = address; } protected boolean emptyList(LoadDataToGUITask task) { return false; } public void editConstData() { if(mConstData.isEmpty()) { return; } mConstData.clear(); } private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener { static final java.util.List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>()); @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { if (loadedImage != null) { ImageView imageView = (ImageView) view; boolean firstDisplay = !displayedImages.contains(imageUri); if (firstDisplay) { FadeInBitmapDisplayer.animate(imageView, 500); if(displayedImages.size() > 100) { displayedImages.remove(0); } displayedImages.add(imageUri); Log.i("Debug", "" + displayedImages.size()); } } } } }
package com.hiwes.cores.thread.thread3.Thread0218; /** * 等待/通知 之 交叉备份。 */ public class MyThread21 extends Thread { private DBTools dbtools; public MyThread21(DBTools dbtools) { super(); this.dbtools = dbtools; } @Override public void run() { dbtools.backupA(); } } class MyThread21_2 extends Thread { private DBTools dbtools; public MyThread21_2(DBTools dbtools) { super(); this.dbtools = dbtools; } @Override public void run() { dbtools.backupB(); } } class DBTools { volatile private boolean prevIsA = false; // 作为标记,实现数据交替备份。 synchronized public void backupA() { try { while (prevIsA == true) { wait(); } for (int i = 0; i < 5; i++) { System.out.println("※ ※ ※ ※ ※"); } prevIsA = true; notifyAll(); } catch (InterruptedException e) { e.printStackTrace(); } } synchronized public void backupB() { try { while (prevIsA == false) { wait(); } for (int i = 0; i < 5; i++) { System.out.println("✨ ✨ ✨ ✨ ✨"); } prevIsA = false; notifyAll(); } catch (InterruptedException e) { e.printStackTrace(); } } } class Run21 { public static void main(String[] args) { DBTools dbtools = new DBTools(); for (int i = 0; i < 20; i++) { MyThread21 a = new MyThread21(dbtools); a.start(); MyThread21_2 b = new MyThread21_2(dbtools); b.start(); } } }
package second; public class A { int a; int b; public A() { System.out.println("Parent class constructor"); } public void display(){ System.out.println("Hai Jithin"); } public static void main(String[] args) { AcEx1 obj=new AcEx1(); String name=obj.getName(); obj.setName("jithin"); } }
package psk.com.mediaplayerdemo.adapter; import android.graphics.drawable.Drawable; import android.support.v4.content.ContextCompat; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import java.util.ArrayList; import psk.com.mediaplayerdemo.R; import psk.com.mediaplayerdemo.activity.MainActivity; import psk.com.mediaplayerdemo.model.MantraModel; /** * Created by Prashan on 02/12/2016. */ public class MantraListAdapter extends RecyclerView.Adapter<MantraListAdapter.ViewHolder> { private MainActivity activity; private final ArrayList<MantraModel> mantraModelList; public MantraListAdapter(MainActivity activity, ArrayList<MantraModel> mantraModelList) { this.activity = activity; this.mantraModelList = mantraModelList; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_song_list_row, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { final MantraModel model = mantraModelList.get(position); holder.tvMantraName.setText(model.getMantraName()); if (model.isPlaying()) { Drawable drawable = ContextCompat.getDrawable(activity, R.drawable.ic_pause_black_36dp); holder.ibPlayDownload.setImageDrawable(drawable); } else { Drawable drawable = ContextCompat.getDrawable(activity, R.drawable.ic_play_colored); holder.ibPlayDownload.setImageDrawable(drawable); } if (model.isDownloaded()) { if (!model.isPlaying()) { Drawable drawable = ContextCompat.getDrawable(activity, R.drawable.ic_play_colored); holder.ibPlayDownload.setImageDrawable(drawable); } } else { Drawable drawable = ContextCompat.getDrawable(activity, R.drawable.ic_download); holder.ibPlayDownload.setImageDrawable(drawable); } holder.ibPlayDownload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { activity.onSongClick(model); } }); Glide.with(activity).load(model.getMantraImage()).into(holder.ivMantraImage); } @Override public int getItemCount() { return mantraModelList.size(); } public static class ViewHolder extends RecyclerView.ViewHolder { public final TextView tvMantraName; public final ImageButton ibPlayDownload; public final ImageView ivMantraImage; public ViewHolder(View itemView) { super(itemView); tvMantraName = (TextView) itemView.findViewById(R.id.tvMantraName); ibPlayDownload = (ImageButton) itemView.findViewById(R.id.ibPlayDownload); ivMantraImage = (ImageView) itemView.findViewById(R.id.ivMantraImage); } } }
package pattern_test.abstract_factory; /** * Description: * * @author Baltan * @date 2019-04-02 11:14 */ public class Test1 { public static void main(String[] args) { BicycleAFactory bicycleAFactory = new BicycleAFactory(); bicycleAFactory.createWheel(); bicycleAFactory.createBrake(); BicycleBFactory bicycleBFactory = new BicycleBFactory(); bicycleBFactory.createWheel(); bicycleAFactory.createBrake(); } }
/* * 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 view; import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.swing.JOptionPane; import model.Activitate; import model.Locatie; import model.Oras; import model.Perioada; import service.MainService; /** * * @author Valentin */ //Utilizam clasa jFrame pentru expunere utilizand builderul oferit. public class MainFrame extends javax.swing.JFrame { //Am declarat-o static pentru a ma asigura ca fi o singura lista de locatii private static List<Locatie> listaLocatii = new ArrayList<>(); public MainFrame() { initComponents(); //Pentru adaugarea functionalitatilor pe butoane am folosit expresiile lambda pentrua a evita jButton1.addActionListener(ev->adaugaLocatie()); //suprascrierea manuala a metodei actionPerformed din clasa ActionListener jButton2.addActionListener(ev->veziLocatie()); jButton3.addActionListener(ev->getTopLocatii()); jButton4.addActionListener(ev->getCheapestLocation()); setLocationRelativeTo(null); setVisible(true); } public void adaugaLocatie( ){ String nume = jTextField1.getText(); Oras oras = new Oras(jTextField2.getText()); int pret = Integer.parseInt(jTextField3.getText()); String activitati = jTextField4.getText(); String [] activitatiVect = activitati.split(","); // Activitatile vor fi scrise cu virgula intre ele //Pentru o mai usoara manipulare, incarcam activitatile intr-o lista de activitati. List<Activitate> listaActivitati = new ArrayList<>(); for(String activitate:activitatiVect){ listaActivitati.add(new Activitate(activitate)); } LocalDate startDate = LocalDate.parse(jTextField5.getText()); // inputul il transformam din String in LocalDate LocalDate endDate = LocalDate.parse(jTextField6.getText()); Perioada perioada = new Perioada(startDate,endDate); Locatie locatie = new Locatie.Builder() .setNume(nume) //Am creat o instanta de Locatie pe baza inputurilor, utilizand patternul creational Builder .setOras(oras) .setActivitati(listaActivitati) .setPret(pret) .setPerioada(perioada) .build(); listaLocatii.add(locatie); //Am adaugat locatia in lista JOptionPane.showMessageDialog(null, "A fost adaugata locatia"); //Afisam si un mesaj la adaugare } //Metoda ce se ocupa de expunerea functionalitatii public void veziLocatie(){ String numeLocatie = jTextField7.getText(); Locatie locatie = MainService.getInstance().getLocatie(listaLocatii, numeLocatie); System.out.println("Nume locatie: "+locatie.getNume()); System.out.println("Oras: "+locatie.getOras()); System.out.println("Pret mediu/zi: "+locatie.getPret()); for(Activitate activitate:locatie.getListaActivitati()){ System.out.print(activitate.getNume()+" "); } System.out.println( ); System.out.println("Perioada de la: "+locatie.getPerioada().getFirstDate()+" la: "+locatie.getPerioada().getEndDate()); } //Aceasta metoda va fi apelata la apasarea butonului "Top 5 locatii" public void getTopLocatii(){ LocalDate startDate = LocalDate.parse(jTextField9.getText()); LocalDate endDate = LocalDate.parse(jTextField10.getText()); List<Locatie> listaTopLocatii = MainService.getInstance().getTopLocatii(listaLocatii, startDate, endDate); if(!listaTopLocatii.isEmpty()){ //Se afiseaza top 5 locatii System.out.println("Top 5 locatii"); for(int i = 0;i<listaTopLocatii.size();i++){ if(i<5) System.out.println("Nume locatie: "+listaTopLocatii.get(i).getNume()); } }else{ System.out.println("Nu exista locatii in acest oras. "); } } public void getCheapestLocation(){ Activitate activitate = new Activitate(jTextField11.getText().toLowerCase()); Locatie locatie = MainService.getInstance().getCheapestLocation(listaLocatii, activitate); if(locatie.getNume()!=null){ System.out.println("Cea mai ieftina locatie se numeste: "+locatie.getNume()); }else System.out.println("Nu exista o locatie care sa aiba disponibile 10 zile si care dispun de activitatea cautata"); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jTextField2 = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jTextField3 = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jTextField4 = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); jTextField5 = new javax.swing.JTextField(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jTextField6 = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jLabel10 = new javax.swing.JLabel(); jTextField7 = new javax.swing.JTextField(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jLabel11 = new javax.swing.JLabel(); jTextField8 = new javax.swing.JTextField(); jLabel12 = new javax.swing.JLabel(); jTextField9 = new javax.swing.JTextField(); jLabel13 = new javax.swing.JLabel(); jTextField10 = new javax.swing.JTextField(); jLabel14 = new javax.swing.JLabel(); jTextField11 = new javax.swing.JTextField(); jLabel15 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setText("Formular de adaugare locatii:"); jLabel2.setText("Nume locatie"); jLabel3.setText("Oras:"); jTextField2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField2ActionPerformed(evt); } }); jLabel4.setText("Pret mediu/zi "); jLabel5.setText("Activitati:"); jLabel6.setText("Activitatile se vor scrie cu virgula intre ele!"); jLabel7.setText("Data de inceput:"); jTextField5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField5ActionPerformed(evt); } }); jLabel8.setText("Formatul date este: an-luna-zi "); jLabel9.setText("Data finala:"); jTextField6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField6ActionPerformed(evt); } }); jButton1.setText("Adauga locatia"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jLabel10.setText("Nume locatie cautata:"); jButton2.setText("Afla informatii"); jButton3.setText("Top 5 locatii din acest oras"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jButton4.setText("Cea mai ieftina locatie "); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); jLabel11.setText("Nume oras: "); jLabel12.setText("Data de inceput:"); jTextField9.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField9ActionPerformed(evt); } }); jLabel13.setText("Data finala:"); jTextField10.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField10ActionPerformed(evt); } }); jLabel14.setText("Activitate cautata:"); jTextField11.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField11ActionPerformed(evt); } }); jLabel15.setText("Exemplu: 2018-01-01"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap(88, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGap(10, 10, 10) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addGap(29, 29, 29) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jTextField11, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField8, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField9, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField10, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addGap(34, 34, 34)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel14) .addGap(0, 0, Short.MAX_VALUE))) .addGap(20, 20, 20)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel11) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7) .addComponent(jLabel9)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jTextField5) .addComponent(jTextField4, javax.swing.GroupLayout.DEFAULT_SIZE, 114, Short.MAX_VALUE) .addComponent(jTextField6))) .addComponent(jLabel12) .addComponent(jLabel13) .addComponent(jLabel2) .addComponent(jLabel3) .addComponent(jLabel4) .addGroup(layout.createSequentialGroup() .addComponent(jLabel10) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel6) .addComponent(jLabel15) .addComponent(jLabel8)) .addGap(102, 102, 102)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(72, 72, 72) .addComponent(jButton1)) .addGroup(layout.createSequentialGroup() .addGap(39, 39, 39) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(46, 46, 46) .addComponent(jButton3)) .addGroup(layout.createSequentialGroup() .addGap(31, 31, 31) .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jLabel6) .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel8)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel9) .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel15)) .addGap(18, 18, 18) .addComponent(jButton1) .addGap(33, 33, 33) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel10) .addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 13, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel11)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel13)) .addGap(5, 5, 5) .addComponent(jButton3) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel14) .addComponent(jTextField11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(7, 7, 7) .addComponent(jButton4) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField2ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField2ActionPerformed private void jTextField5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField5ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField5ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jButton1ActionPerformed private void jTextField6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField6ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField6ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jButton3ActionPerformed private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jButton4ActionPerformed private void jTextField11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField11ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField11ActionPerformed private void jTextField10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField10ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField10ActionPerformed private void jTextField9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField9ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField9ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; 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 jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField10; private javax.swing.JTextField jTextField11; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField3; private javax.swing.JTextField jTextField4; private javax.swing.JTextField jTextField5; private javax.swing.JTextField jTextField6; private javax.swing.JTextField jTextField7; private javax.swing.JTextField jTextField8; private javax.swing.JTextField jTextField9; // End of variables declaration//GEN-END:variables }
package com.legalzoom.api.test.integration.ProductsService; import org.testng.Assert; import org.testng.annotations.Test; import com.legalzoom.api.test.client.ResponseData; import com.legalzoom.api.test.dto.CreateProcessIdDTO; public class CoreProductsProductTypesProcessProcessIdGetIT extends ProductsTest{ @Test public void testProductsByProcessId() throws Exception{ CreateProcessIdDTO createProcessId = new CreateProcessIdDTO(); createProcessId.setProcessId("6"); ResponseData responseData = coreProductsServiceClient.getCoreProductsProductTypesProcessProcessId(createProcessId); Assert.assertEquals(responseData.getStatus(), 200); } @Test public void testProductsByProcessIdWithNoData() throws Exception{ CreateProcessIdDTO createProcessId = new CreateProcessIdDTO(); createProcessId.setProcessId(" "); ResponseData responseData = coreProductsServiceClient.getCoreProductsProductTypesProcessProcessId(createProcessId); Assert.assertEquals(responseData.getStatus(), 400); } @Test public void testProductsByProcessIdWithNoBlankValue() throws Exception{ CreateProcessIdDTO createProcessId = new CreateProcessIdDTO(); //createProcessId.setProcessId(" "); ResponseData responseData = coreProductsServiceClient.getCoreProductsProductTypesProcessProcessId(createProcessId); Assert.assertEquals(responseData.getStatus(), 400); } @Test public void testProductsByProcessIdWithSpace() throws Exception{ CreateProcessIdDTO createProcessId = new CreateProcessIdDTO(); createProcessId.setProcessId("11 5"); ResponseData responseData = coreProductsServiceClient.getCoreProductsProductTypesProcessProcessId(createProcessId); Assert.assertEquals(responseData.getStatus(), 400); } @Test public void testProductsByProcessIdWithSpecialCharacter() throws Exception{ CreateProcessIdDTO createProcessId = new CreateProcessIdDTO(); createProcessId.setProcessId("1&5"); ResponseData responseData = coreProductsServiceClient.getCoreProductsProductTypesProcessProcessId(createProcessId); Assert.assertEquals(responseData.getStatus(), 400); } @Test public void testProductsByProcessIdWithCharacter() throws Exception{ CreateProcessIdDTO createProcessId = new CreateProcessIdDTO(); createProcessId.setProcessId("LLC"); ResponseData responseData = coreProductsServiceClient.getCoreProductsProductTypesProcessProcessId(createProcessId); Assert.assertEquals(responseData.getStatus(), 400); } @Test public void testProductsByProcessIdWithInValidValue() throws Exception{ CreateProcessIdDTO createProcessId = new CreateProcessIdDTO(); createProcessId.setProcessId("-14"); ResponseData responseData = coreProductsServiceClient.getCoreProductsProductTypesProcessProcessId(createProcessId); Assert.assertEquals(responseData.getStatus(), 404); } }
package com.rc.adapter.message; import com.rc.components.*; import com.rc.components.message.RCLeftImageMessageBubble; import com.rc.res.Colors; import com.rc.utils.FontUtil; import javax.swing.*; import java.awt.*; /** * Created by song on 17-6-2. */ public class MessageLeftAttachmentViewHolder extends MessageAttachmentViewHolder { public JLabel sender = new JLabel(); public MessageLeftAttachmentViewHolder() { initComponents(); initView(); } private void initComponents() { messageBubble = new RCLeftImageMessageBubble(); /*timePanel.setBackground(Colors.WINDOW_BACKGROUND); messageAvatarPanel.setBackground(Colors.WINDOW_BACKGROUND); size.setForeground(Colors.FONT_GRAY); size.setFont(FontUtil.getDefaultFont(12));*/ sender.setFont(FontUtil.getDefaultFont(12)); sender.setForeground(Colors.FONT_GRAY); //sender.setVisible(false); /*attachmentPanel.setOpaque(false); progressBar.setMaximum(100); progressBar.setMinimum(0); progressBar.setValue(100); progressBar.setUI(new GradientProgressBarUI()); progressBar.setVisible(false); messageBubble.setCursor(new Cursor(Cursor.HAND_CURSOR)); sizeLabel.setFont(FontUtil.getDefaultFont(12)); sizeLabel.setForeground(Colors.FONT_GRAY);*/ messageBubble.setCursor(new Cursor(Cursor.HAND_CURSOR)); } private void initView() { setLayout(new BorderLayout()); timePanel.add(time); attachmentPanel.setLayout(new GridBagLayout()); attachmentPanel.add(attachmentIcon, new GBC(0, 0).setWeight(1, 1).setInsets(5,5,5,0)); attachmentPanel.add(attachmentTitle, new GBC(1, 0).setWeight(100, 1).setAnchor(GBC.NORTH) .setInsets(5, 8, 5, 5)); attachmentPanel.add(progressBar, new GBC(1, 1).setWeight(1, 1).setFill(GBC.HORIZONTAL) .setAnchor(GBC.SOUTH).setInsets(0, 8, 5, 5)); attachmentPanel.add(sizeLabel, new GBC(1, 1).setWeight(1, 1).setFill(GBC.HORIZONTAL).setAnchor(GBC.SOUTH).setInsets(-20,8,3,0)); messageBubble.add(attachmentPanel); JPanel senderMessagePanel = new JPanel(); senderMessagePanel.setBackground(Colors.WINDOW_BACKGROUND); senderMessagePanel.setLayout(new VerticalFlowLayout(VerticalFlowLayout.TOP, 0,0,true, false)); senderMessagePanel.add(sender); senderMessagePanel.add(messageBubble); messageAvatarPanel.setLayout(new GridBagLayout()); messageAvatarPanel.add(avatar, new GBC(1, 0).setWeight(1, 1).setAnchor(GBC.NORTH).setInsets(4, 20,0,0)); messageAvatarPanel.add(senderMessagePanel, new GBC(2, 0) .setWeight(1000, 1) .setAnchor(GBC.WEST) .setInsets(0,5,5,0)); add(timePanel, BorderLayout.NORTH); add(messageAvatarPanel, BorderLayout.CENTER); } }
/* * 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 teg.view; import java.io.File; import java.util.Optional; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.Dialog; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.GridPane; import javafx.stage.FileChooser; import javafx.util.Pair; import static teg.StartupConstants.PATH_IMAGES; import static teg.StartupConstants.PATH_VIDEOES; import teg.model.Vd; /** * * @author HTC */ public class VideoEditStage extends Dialog<ButtonType>{ Button bt;// = new Button("Select a video"); Label lb; TextField captionTF; TextField heightTF; TextField widthTF; EPortfolioGeneratorView ui; File videoFile; Vd video; GridPane gp; private Label L3; private Label L2; private Label L1; public VideoEditStage(EPortfolioGeneratorView initUI){ ui = initUI; initWindow(); /*this.setTitle("Edit Video"); this.setHeaderText(null); this.setGraphic(null); this.getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL); bt = new Button("Select a video");*/ bt.setOnAction(e->{ handleSelectVideoRequest(); }); /* GridPane gp = new GridPane(); gp.setAlignment(Pos.CENTER); gp.setHgap(5.5); gp.setVgap(5.5); Label L1 =new Label("Enter the caption: "); Label L2 = new Label("Enter the height: "); Label L3 = new Label("Enter the width: "); captionTF = new TextField(); heightTF = new TextField(); widthTF = new TextField(); lb = new Label("3.mp4"); gp.add(bt, 0, 0); gp.add(L1, 0, 1); gp.add(L2, 0, 2); gp.add(L3, 0, 3); gp.add(lb, 1, 0); gp.add(captionTF, 1, 1); gp.add(heightTF, 1, 2); gp.add(widthTF, 1, 3); this.getDialogPane().setContent(gp); */ Optional<ButtonType> result = this.showAndWait(); if (result.isPresent()) { handleEditRequest(); } } private void handleSelectVideoRequest() { FileChooser videoFileChooser = new FileChooser(); // SET THE STARTING DIRECTORY videoFileChooser.setInitialDirectory(new File(PATH_VIDEOES)); // LET'S ONLY SEE IMAGE FILES FileChooser.ExtensionFilter mp4Filter = new FileChooser.ExtensionFilter("MP4 files (*.mp4)", "*.mp4"); videoFileChooser.getExtensionFilters().addAll(mp4Filter); // LET'S OPEN THE FILE CHOOSER videoFile = videoFileChooser.showOpenDialog(null); lb = new Label(videoFile.getName()); gp.getChildren().clear(); gp.add(bt, 0, 0); gp.add(L1, 0, 1); gp.add(L2, 0, 2); gp.add(L3, 0, 3); gp.add(lb, 1, 0); gp.add(captionTF, 1, 1); gp.add(heightTF, 1, 2); gp.add(widthTF, 1, 3); } public void initWindow() { this.setTitle("Edit Video"); this.setHeaderText(null); this.setGraphic(null); this.getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL); bt = new Button("Select a video"); video = ui.getEPModel().selectedSite.getSelectedContent().component.video; videoFile = new File(video.videoPath + video.videoName); captionTF = new TextField(video.videoCaptions); heightTF = new TextField(video.videoHeight); widthTF = new TextField(video.videoWidth); gp = new GridPane(); gp.setAlignment(Pos.CENTER); gp.setHgap(5.5); gp.setVgap(5.5); L1 =new Label("Enter the caption: "); L2 = new Label("Enter the height: "); L3 = new Label("Enter the width: "); captionTF = new TextField(video.videoCaptions); heightTF = new TextField(video.videoHeight); widthTF = new TextField(video.videoWidth); lb = new Label(videoFile.getName()); gp.add(bt, 0, 0); gp.add(L1, 0, 1); gp.add(L2, 0, 2); gp.add(L3, 0, 3); gp.add(lb, 1, 0); gp.add(captionTF, 1, 1); gp.add(heightTF, 1, 2); gp.add(widthTF, 1, 3); this.getDialogPane().setContent(gp); } public void handleEditRequest() { video.videoCaptions = captionTF.getText(); video.videoHeight = heightTF.getText(); video.videoWidth = widthTF.getText(); video.videoName = videoFile.getName(); video.videoPath = videoFile.getPath().substring(0, videoFile.getPath().indexOf(video.videoName)); } }
package edu.iit.cs445.StateParking.UnitTest; import static org.junit.Assert.*; import org.junit.Test; import edu.iit.cs445.StateParking.Objects.Address; import edu.iit.cs445.StateParking.ObjectsEnum.State; public class AddressTest { private Address address = new Address("8763 E. Canyon Rd", "Apple River", State.IL, "61001"); @Test public void test() { assertEquals("8763 E. Canyon Rd",address.getStreet()); assertEquals("Apple River",address.getCity()); assertEquals(State.IL,address.getState()); assertEquals("61001",address.getZipcode()); assertEquals("8763 E. Canyon Rd,Apple River,IL 61001",address.toString()); assertTrue(address.isMatch("Apple River")); assertFalse(address.isMatch("Object Oriented Design")); } }
/*********************************************************************************** Deck class. Simulates a standard 52 card deck. ------------------------------------------------------------------------------------ Lori Nyland CS 110 Homework 10 ***********************************************************************************/ import java.util.Random; //for shuffling the deck of cards import java.util.LinkedList; //for implementing a linked list import javax.swing.JOptionPane; //for dialog boxes public class Deck { //fields ======================================================================== private LinkedList<Card> deck; // the deck of cards // constructor ================================================================== /** Constructor - initialize the deck as unshuffled. */ public Deck() { int ct = 0; // card counter deck = new LinkedList<Card>(); // create an empty deck of cards array // fill the deck of cards array with the standard cards for (int i=Card.Suit.CLUBS.ordinal(); i<=Card.Suit.SPADES.ordinal(); i++) { for (int j=Card.Rank.TWO.ordinal(); j<=Card.Rank.ACE.ordinal(); j++) { Card card = new Card(j, i); // create a card deck.add(card); // add it to the deck ct++; // increment the card counter } } } // methods ====================================================================== /** Shuffles the deck of cards. Implements Fisher-Yates shuffle. */ public void shuffle() { // Implementing Fisher–Yates shuffle { Random rnd = new Random(); for (int i=deck.size()-1; i>0; i--) { int index = rnd.nextInt(i + 1); // Simple swap Card c = new Card(deck.get(index).getRank().ordinal(),deck.get(index).getSuit().ordinal()); deck.set(index,deck.get(i)); deck.set(i,c); } } } /** Remove top card from deck. @return A Card object that was first in the deck */ public Card removeTop() { Card card = new Card(); try { card = deck.remove(); } catch(Exception e) { JOptionPane.showMessageDialog(null, "Empty Deck - Cannot remove top card"); } return card; } /** Return a card to bottom of deck. @param card A Card object to be placed at the current last index of the deck */ public void returnToBottom(Card card) { deck.add(card); } /** Return a copy of card at top of deck without altering the deck. @return A Card object - copy of first card in deck. */ public Card peekTopCard() { Card newCard = new Card(deck.peek()); return newCard; } /** Get number of cards in deck. @return An integer for the number of cards currently in deck. */ public int getSize() { return deck.size(); } }
public class HelloWorld { public static void main( String[] args ) { // Les variables // nom donné à un espace mémoire, contenant une valeur // déclaration de la variable 'a' // qui est de type "int" (nombre entier) int a; // affectation de la variable 'a' à la valeur 4 a = 4; // déclaration + affectation int b = a * a; System.out.println( "La variable a vaut " + a ); System.out.println( "La variable b vaut " + b ); // les types primitifs boolean g = false; // booléen (consomme 8 bits généralement) boolean h = true; byte f; // entiers signé sur8 bits short d; // entiers signé sur 16 bits int c; // entiers signé sur 32 bits long e; // entier signé sur 64 bits float i = 10.424f; // nombre flottant sur 32 bits (norme IEEE754) double j = 5.33d; // nombre flottant sur 64 bits (norme IEEE754) char k = 'a'; // représente un caractère sur 16 bits (unicode UTF-16) k = 'b' + 1; // Conversions entre types primitifs byte l = (byte) 2366; int m = l; System.out.println( "l vaut " + l ); // Chaines de caractères String n = "Bonjour"; // On a le droit de concaténer les String avec n'importe quoi d'autre String o = "La valeur de m est " + m + " et celle de n: " + n; System.out.println( o ); } }
package com.kodilla.restaurantfrontend.service; import com.kodilla.restaurantfrontend.OrderMainView; import com.kodilla.restaurantfrontend.domain.Menu; import com.kodilla.restaurantfrontend.domain.Product; import com.vaadin.flow.component.UI; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.grid.Grid; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.component.textfield.TextField; import com.vaadin.flow.data.value.ValueChangeMode; import com.vaadin.flow.router.Route; @Route("Menu") public class MenuMainView extends VerticalLayout { private MenuService menuService = MenuService.getInstance(); private Grid<Menu> grid = new Grid<>(Menu.class); private TextField filter = new TextField(); private TextField filter1 = new TextField(); private Button order = new Button("Order"); private OrderMainView orderMainView = new OrderMainView(); public MenuMainView() { filter.setPlaceholder("Filter by product name"); filter1.setPlaceholder("Filter by price"); filter.setClearButtonVisible(true); filter1.setClearButtonVisible(true); filter.setValueChangeMode(ValueChangeMode.EAGER); filter1.setValueChangeMode(ValueChangeMode.EAGER); filter.addValueChangeListener(e -> updateName()); filter1.addValueChangeListener(e -> updatePrice()); grid.setColumns("productName", "price", "available", "quantity", "type"); order.addClickListener(e -> { UI.getCurrent().navigate("Order"); }); HorizontalLayout toolbar = new HorizontalLayout(filter, filter1, order); HorizontalLayout mainContent = new HorizontalLayout(grid); mainContent.setSizeFull(); grid.setSizeFull(); add(toolbar, mainContent); setSizeFull(); refresh(); } private void updateName() { grid.setItems(menuService.findByProductName(filter.getValue())); } private void updatePrice() { grid.setItems(menuService.findByProductPrice(filter1.getValue())); } public void refresh() { grid.setItems(menuService.getMenus()); } }
package com.mimi.mimigroup.model; public class DM_Tree { int TreeID; String TreeCode; String TreeGroupCode; String TreeName; public DM_Tree() { } public DM_Tree(int treeID, String treeCode, String treeName) { this.TreeID =treeID; this.TreeCode =treeCode; this.TreeName =treeName; } public int getTreeID() { return TreeID; } public void setTreeID(int treeID) { TreeID = treeID; } public String getTreeCode() { return TreeCode; } public void setTreeCode(String treeCode) { TreeCode = treeCode; } public String getTreeGroupCode() { return TreeGroupCode; } public void setTreeGroupCode(String treeGroupCode) { TreeGroupCode = treeGroupCode; } public String getTreeName() { return TreeName; } public void setTreeName(String treeName) { TreeName = treeName; } }
package com.smxknife.flink.table.demo.demo03; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.apache.flink.api.common.eventtime.WatermarkStrategy; import org.apache.flink.streaming.api.TimeCharacteristic; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.table.api.Table; import org.apache.flink.table.api.bridge.java.StreamTableEnvironment; import org.apache.flink.types.Row; import java.time.Duration; import static org.apache.flink.table.api.Expressions.$; /** * @author smxknife * 2020/9/14 */ public class _13_1_TableGroupSQLWindow { public static void main(String[] args) throws Exception { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setParallelism(1); env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env); // 第一种方式就是利用DataStream的时间窗口 DataStream<Sensor> dataStream = env.readTextFile(_13_1_TableGroupSQLWindow.class.getResource("/Sensor.csv").getPath()) .map((input) -> { String[] array = input.split(","); return new Sensor(array[0], Double.valueOf(array[1]), Long.valueOf(array[2])); }) .assignTimestampsAndWatermarks(WatermarkStrategy.<Sensor>forBoundedOutOfOrderness(Duration.ofSeconds(1)).withTimestampAssigner((sensor, processTime) -> sensor.getTimestamp())); Table table = tableEnv.fromDataStream(dataStream, $("id"), $("value"), $("timestamp"), $("event_time").rowtime(), $("process_time").proctime()); tableEnv.createTemporaryView("sensor", table); Table table1 = tableEnv.sqlQuery("select id, count(id), sum(`value`) as val, tumble_end(event_time, interval '2' second) as w from sensor group by tumble(event_time, interval '2' second), id"); tableEnv.toAppendStream(table1, Row.class).print("table1"); env.execute("table window test job"); } @Data @AllArgsConstructor @NoArgsConstructor public static class Sensor { private String id; private Double value; private Long timestamp; } }
package com.yc.easyui.dao; import java.util.List; import com.yc.easyui.bean.Dept; public class DeptDao { public List<Dept> findByPage(int pageNo, int pageSize) { DBHelper db = new DBHelper(); String sql = "select * from (select a.*, rownum rn from (" + "select * from dept order by deptno) a where rownum<=?) where rn >?"; return db.finds(Dept.class, sql, pageNo * pageSize, (pageNo-1)*pageSize); } public int getTotal() { DBHelper db = new DBHelper(); String sql = "select count(deptno) from dept"; return db.getTotal(sql); } public int add(String deptno, String dname, String loc) { DBHelper db = new DBHelper(); String sql = "insert into dept values(?,?,?)"; return db.update(sql, deptno, dname, loc); } public int update(String deptno, String dname, String loc) { DBHelper db = new DBHelper(); String sql = "update dept set dname=?,loc=? where deptno=?"; return db.update(sql, dname, loc, deptno); } public int deleteDept(String deptno) { DBHelper db = new DBHelper(); String sql = "delete from dept where deptno=?"; return db.update(sql, deptno); } public List<Dept> findAll() { DBHelper db = new DBHelper(); String sql ="select deptno, dname from dept"; return db.finds(Dept.class, sql); } }
//Q: A song with words "I AM X" can transform into a dubstep remix as "WUBWUBIWUBAMWUBWUBX" and cannot transform into "WUBWUBIAMWUBX". Return the words of the initial song! public class RemoveAllWUBFromSong { public static String SongDecoder (String song) { return song.replaceAll("(WUB)+", " ").trim(); } }
package com.foobarspam.nif; import static org.junit.Assert.*; import org.junit.Test; public class IdentificadorUtilsTest { @Test public void testComprobarExpresion() { String dni = "43197056C"; Boolean resultado = IdentificadorUtils.ComprobarExpresion(dni); assertTrue(resultado); } @Test public void testComprobarExpresion2() { String dni = "43197056"; Boolean resultado = IdentificadorUtils.ComprobarExpresion(dni); assertFalse(resultado); } /* @Test public void testComprobarLetra() { fail("Not yet implemented"); } */ }
package com.yoandypv.elasticsearch.geoinfo.web; import com.yoandypv.elasticsearch.geoinfo.model.Area; import com.yoandypv.elasticsearch.geoinfo.service.AreaService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("/api/v1") public class AreaResource { @Autowired private AreaService areaService; @RequestMapping(method = RequestMethod.POST, value = "/areas") public ResponseEntity<Area> save(@RequestBody Area area) { System.out.println(area.toString()); return ResponseEntity.ok(areaService.save(area)); } @RequestMapping(method = RequestMethod.GET, value = "/areas") public ResponseEntity<List<Area>> list() { return ResponseEntity.ok(areaService.list()); } }
package ba.bitcamp.LabS10D01; import java.awt.Color; import java.awt.Component; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JFrame; import javax.swing.JPanel; public class DrawUndo { public static void main(String[] args) { JFrame window = new JFrame(); window.setSize(400, 400); JPanel panel = new JPanel(); window.add(panel); MouseHandler mh = new MouseHandler(); panel.addMouseListener(mh); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setVisible(true); } public static class MouseHandler implements MouseListener { @Override public void mouseClicked(MouseEvent e) { Component c = (Component)e.getSource(); c.getGraphics().setColor(new Color(50, 50, 50)); c.getGraphics().fillRect(e.getX(), e.getY(), 50, 50); } @Override public void mouseEntered(MouseEvent arg0) {} @Override public void mouseExited(MouseEvent arg0) {} @Override public void mousePressed(MouseEvent arg0) {} @Override public void mouseReleased(MouseEvent arg0) {} } }
public class QuadraticEquation { private double a; private double b; private double c; public QuadraticEquation(double a, double b, double c) { this.a = a; this.b = b; this.c = c; } public double getA() { return a; } public double getB() { return b; } public double getC() { return c; } public double getDiscriminant() { double delta = this.b*2 - 4*this.a*this.c; return delta; } public void printRoot() { if(this.getDiscriminant() >0) { System.out.println("r1 = " + ((-1*this.b + Math.pow(Math.pow(this.b, 2) - 4*this.a*this.c, 0.5)) / (2*this.a))); System.out.println("r2 = " + ((-1*this.b - Math.pow(Math.pow(this.b, 2) - 4*this.a*this.c, 0.5)) / (2*this.a))); } else if (this.getDiscriminant() ==0) { System.out.println("r = " + ((-1*this.b) / (2*this.a))); } else { System.out.println("The equation has no roots"); } } public static void main(String[] args) { QuadraticEquation quadra1 = new QuadraticEquation(1.0, 3, 1); quadra1.printRoot(); QuadraticEquation quadra2 = new QuadraticEquation(1, 2.0, 1); quadra2.printRoot(); } }
package checkdictionary; import java.util.HashSet; import java.util.Set; public class Solution { public boolean canBreak(String input, String[] dict) { // Write your solution here. Set<String> dictset = toset(dict); boolean [] indic = new boolean[input.length()+1]; indic[0] = true; for (int i = 1; i < indic.length; i++){ for(int j = 0; j < i; j++) { if(dictset.contains(input.substring(j,i))) { if(indic[j] == true) { indic[i] = true; } } } } return indic[indic.length - 1]; } private Set<String> toset(String [] dict) { Set<String> set = new HashSet<>(); for(String c : dict) { set.add(c); } return set; } public static void main (String [] args) { Solution s = new Solution(); String input = "bobrob"; String [] dic = {"bob","rob"}; System.out.println(s.canBreak(input, dic)); } }
package odeSolver; import java.util.Hashtable; import Exceptions.WrongCalculationException; import Exceptions.WrongExpressionException; import Exceptions.WrongInputException; import MathExpr.MathExpr; import MathToken.MathTokenSymbol; import MatrixMathExpr.ArrayExprC; import Parser.MathEvaluator; public abstract class RangeKutta extends GLM { /** Range-Kutta Matrix */ protected double[][] A; /** Weight Array */ protected double[] b; /** Nodes Array */ protected double[] c; public RangeKutta (DifferentialEquation diff, String methodName, String methodType, String methodOrder, int r) throws WrongInputException { super(diff, methodName, methodType, methodOrder, r, 0); // Range-Kutta Matrix Definition this.A = new double[r][r]; for (int i = 0; i < r; i++) { for (int j = 0; j < r; j++) { this.A[i][j] = 0.0; } } // Weights Array Definition this.b = new double[r]; for (int i = 0; i < r; i++) { this.b[i] = 0.0; } // Nodes Array Definition this.c = new double[r]; for (int i = 0; i < r; i++) { this.c[i] = 0.0; } // Fields Initialization this.tableInitialize(); } public RangeKutta (DifferentialEquation diff, String methodName, String methodType, String methodOrder) throws WrongInputException { this (diff, methodName, methodType, methodOrder, 1); } protected abstract void tableInitialize (); @Override protected double[] solveODE() { int stepNumber = diff.getStepNumber(); double step = diff.getStep(); double[] yk = new double[stepNumber]; yk[0] = diff.getY0(); double[] timeInterval = diff.getTimeInterval(); MathTokenSymbol t = diff.getT(); MathTokenSymbol y = diff.getY(); Hashtable<MathTokenSymbol, Double> hashTab = new Hashtable<MathTokenSymbol, Double>(); double[] k = new double[this.r]; for (int i = 0; i < this.r; i++) { k[i] = 0; } // sum (bi*ki) double kb_sum; // sum (ai*ki) double ka_sum; try { // Explicit Method if (this.getMethodType().equals("explicit")) { // y[n+1] = y[n] + SUM (i=1..r) {b[i]*k[i]} // k[0] = f (t[n], y[n]) # c[0] = 0, a[0][0] = 0 // k[1] = f (t[n] + c[1]*h, y[n] + h*(a[1][0]*k[0]) // k[2] = f (t[n] + c[2]*h, y[n] + h*(a[2][0]*k[0] + a[2][1]*k[1]) // k[i] = f (t[n] + c[i]*h, y[n] + h*(a[i][0]*k[0] + a[i][1]*k[1] + .. + a[i][i-1]*k[i-1]) for (int i = 1; i < stepNumber; i++) { ka_sum = 0; kb_sum = 0; hashTab.clear(); hashTab.put(t, timeInterval[i-1]); hashTab.put(y, yk[i-1]); // k0 = f (tn, yn) -> Euler Esplicit k[0] = (new MathEvaluator (this.diff.getFunc(), hashTab)).getResult().getOperandDouble(); kb_sum = this.b[0]*k[0]; // Ks Loop Calculator // Starts from 1 because c[0] = 0 for (int j = 1; j < this.r; j++) { hashTab.clear(); // tn + h*c[j] hashTab.put(t, timeInterval[i-1] + step*this.c[j]); // ka_sum Computing for (int l = 0; l <= j; l++) { ka_sum += this.A[j][l]*k[l]; } hashTab.put(y, yk[i-1] + step*ka_sum); k[j] = (new MathEvaluator (this.diff.getFunc(), hashTab)).getResult().getOperandDouble(); } // kb_sum Computing for (int j = 1; j < r; j++) { kb_sum += this.b[j]*k[j]; } // Yk[i] Computation yk[i] = yk[i-1] + step*kb_sum; } // Implicit Method if (this.getMethodType().equals("implicit")) { // y[n+1] = y[n] + h*SUM (i=1..r) {b[i]*k[i]} // k[i] = f (t[n] + c[i]*h, y[n] + h*(a[i][0]*k[0] + a[i][1]*k[1] + .. + a[i][i-1]*k[r]) // k[i] = f(Z[i], y[n] + h*SUM (j=0...r) {A[i]*k[j]) // It Has To Be Solved Numerically In Respect To k = k[i] // Z[i] Definition double[] Z = new double[r]; // Function Array With The Evaluation t -> Z[i] MathExpr[] funcEl = new MathExpr[this.r]; ArrayExprC funcArrC = null; for (int i = 1; i < stepNumber; i++) { // KB Sum Initialization kb_sum = 0; // Z[j] = t[i-1] + c[j] for (int j = 1; j < r; j++) { Z[j] = timeInterval[i-1] + this.c[j]; funcEl[j] = this.diff.getFunc().evalSymbolic(Z[j], t); } funcArrC = new ArrayExprC (funcEl, this.r); // kb_sum Computing for (int j = 1; j < r; j++) { kb_sum += this.b[j]*k[j]; } // Yk[i] Computation yk[i] = yk[i-1] + step*kb_sum; } } } } catch (WrongCalculationException | WrongExpressionException | WrongInputException e) { e.printStackTrace(); } this.diff.setSolved(true); this.diff.setYk(yk); this.diff.setMethodName(this.methodName); this.diff.setMethodType(this.methodType); return yk; } public String tableToString () { String s = new String(); s += "Method Name: " + this.getMethodName() + "\n"; s += "Method Type: " + this.getMethodType() + "\n"; s += "Method Order: " + this.getMethodOrder() + "\n"; s += "Method r: " + this.r + "\n"; s += "\n"; for (int i = 0; i < this.r; i++) { for (int j = 0; j < this.r; j++) s += "A[" + i + "][" + j + "] = " + A[i][j] + "\n"; } s += "\n"; for (int i = 0; i < this.b.length; i++) { s += "b[" + i + "] = " + b[i] + "\n"; } s += "\n"; for (int i = 0; i < this.c.length; i++) { s += "c[" + i + "] = " + c[i] + "\n"; } return s; } }
package com.example.userportal.repository; import com.example.userportal.domain.Customer; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.util.Optional; public interface CustomerRepository extends JpaRepository<Customer, Integer> { @Query("SELECT o.customer FROM Order o WHERE o.id=:orderId") Customer findCustomerByOrderId(@Param("orderId") int orderId); Optional<Customer> findOneByEmailIgnoreCase(String email); Optional<Customer> findOneWithAuthoritiesById(Integer id); Optional<Customer> findOneWithAuthoritiesByEmail(String email); boolean existsByEmail(String email); }
package oop9; //인터페이스 - 기획서 //사운드 출력 기능이 지원되는 모든 모니터가 갖춰야 하는 기능을 정의한다. // 모든 모니터는 최소/최대 범위 내의 소리크기만을 가지도록 상수를 정의한다. public interface Speakable { public static final int MAX_VOLUME = 100; public static final int MIN_VOLUME = 0; void sound(); void volumeUp(); void volumeDown(); }
package com.tencent.mm.plugin.account.ui; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.text.TextUtils; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; import com.tencent.mm.ab.e; import com.tencent.mm.ab.l; import com.tencent.mm.al.b; import com.tencent.mm.kernel.g; import com.tencent.mm.model.at; import com.tencent.mm.model.bg; import com.tencent.mm.model.bt; import com.tencent.mm.modelsimple.q; import com.tencent.mm.platformtools.aa; import com.tencent.mm.platformtools.ah; import com.tencent.mm.platformtools.d; import com.tencent.mm.plugin.account.a.a; import com.tencent.mm.plugin.account.a.f; import com.tencent.mm.plugin.account.a.i; import com.tencent.mm.plugin.account.a.j; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.pluginsdk.model.app.p; import com.tencent.mm.protocal.GeneralControlWrapper; import com.tencent.mm.protocal.JsapiPermissionWrapper; import com.tencent.mm.sdk.b.c; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.ag; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.w; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.MMActivity; import com.tencent.mm.ui.applet.SecurityImage; import com.tencent.mm.ui.base.MMClearEditText; import com.tencent.mm.ui.base.MMFormInputView; import com.tencent.mm.ui.widget.a.d$a; import com.tencent.smtt.sdk.TbsMediaPlayer$TbsMediaPlayerListener; public class LoginUI extends MMActivity implements e { private TextWatcher UE = new 1(this); private String bLe = null; private String cbP = ""; private ProgressDialog eHw = null; private String eHy; private SecurityImage eIX = null; private String eOW; protected Button eQU; protected Button eQV; private View eQW; protected Button eQX; private f eQY = new f(); private c eQf = new 12(this); private MMClearEditText eRX; private MMClearEditText eRY; private MMFormInputView eRZ; private String eRa; private String eRb; private ResizeLayout eRf; private d eRi; private Button eRo; private MMFormInputView eSa; private Button eSb; private Button eSc; protected View eSd; private String eSe; private boolean eSf; private com.tencent.mm.ui.widget.a.d eSg; private MMKeyboardUperView eSh; private boolean eSi = false; private final int eSj = 128; private int sceneType = 0; static /* synthetic */ void a(LoginUI loginUI) { if (bi.oW(loginUI.eRX.getText().toString()) || bi.oW(loginUI.eRY.getText().toString())) { loginUI.eSb.setEnabled(false); } else { loginUI.eSb.setEnabled(true); } } static /* synthetic */ void b(LoginUI loginUI) { View currentFocus = loginUI.getWindow().getCurrentFocus(); if (currentFocus != null) { int[] iArr = new int[2]; currentFocus.getLocationInWindow(iArr); int height = (iArr[1] - loginUI.getSupportActionBar().getHeight()) - 128; if (height > 0) { loginUI.eSh.post(new 11(loginUI, height)); } } } static /* synthetic */ void l(LoginUI loginUI) { g.Ek().gi(""); Intent intent = new Intent(); intent.putExtra("Intro_Switch", true).addFlags(67108864); loginUI.finish(); a.ezn.q(intent, loginUI); } protected final int getLayoutId() { return com.tencent.mm.plugin.account.a.g.login; } public void onCreate(Bundle bundle) { super.onCreate(bundle); String str = ""; if (com.tencent.mm.protocal.d.qVQ) { str = getString(j.app_name) + getString(j.alpha_version_alpha); } this.sceneType = getIntent().getIntExtra("login_type", 0); setMMTitle(str); lF(getResources().getColor(com.tencent.mm.plugin.account.a.c.normal_actionbar_color)); cqh(); a.ezo.vo(); this.eHy = com.tencent.mm.plugin.c.a.Zu(); initView(); this.eRi = new d(); this.eSf = getIntent().getBooleanExtra("from_switch_account", false); this.eSe = at.dBv.I("login_weixin_username", ""); if (getIntent().getIntArrayExtra("kv_report_login_method_data") != null) { h.mEJ.h(14262, new Object[]{Integer.valueOf(r0[0]), Integer.valueOf(r0[1]), Integer.valueOf(r0[2]), Integer.valueOf(r0[3]), Integer.valueOf(r0[4])}); } } public void onResume() { com.tencent.mm.sdk.b.a.sFg.b(this.eQf); super.onResume(); StringBuilder stringBuilder; if (this.sceneType == 0) { stringBuilder = new StringBuilder(); g.Eg(); stringBuilder = stringBuilder.append(com.tencent.mm.kernel.a.DA()).append(",").append(getClass().getName()).append(",L100_100_logout,"); g.Eg(); com.tencent.mm.plugin.c.a.d(true, stringBuilder.append(com.tencent.mm.kernel.a.gd("L100_100_logout")).append(",1").toString()); com.tencent.mm.plugin.c.a.pT("L100_100_logout"); } else if (this.sceneType == 1) { stringBuilder = new StringBuilder(); g.Eg(); stringBuilder = stringBuilder.append(com.tencent.mm.kernel.a.DA()).append(",").append(getClass().getName()).append(",L400_100_login,"); g.Eg(); com.tencent.mm.plugin.c.a.d(true, stringBuilder.append(com.tencent.mm.kernel.a.gd("L400_100_login")).append(",1").toString()); com.tencent.mm.plugin.c.a.pT("L400_100_login"); } } public void onPause() { super.onPause(); com.tencent.mm.sdk.b.a.sFg.c(this.eQf); StringBuilder stringBuilder; if (this.sceneType == 0) { stringBuilder = new StringBuilder(); g.Eg(); stringBuilder = stringBuilder.append(com.tencent.mm.kernel.a.DA()).append(",").append(getClass().getName()).append(",L100_100_logout,"); g.Eg(); com.tencent.mm.plugin.c.a.d(false, stringBuilder.append(com.tencent.mm.kernel.a.gd("L100_100_logout")).append(",2").toString()); } else if (this.sceneType == 1) { stringBuilder = new StringBuilder(); g.Eg(); stringBuilder = stringBuilder.append(com.tencent.mm.kernel.a.DA()).append(",").append(getClass().getName()).append(",L400_100_login,"); g.Eg(); com.tencent.mm.plugin.c.a.d(false, stringBuilder.append(com.tencent.mm.kernel.a.gd("L400_100_login")).append(",2").toString()); } } public void onDestroy() { if (this.eRi != null) { this.eRi.close(); } g.DF().b(TbsMediaPlayer$TbsMediaPlayerListener.MEDIA_INFO_BUFFERING_START, this); super.onDestroy(); } protected final void initView() { this.eRZ = (MMFormInputView) findViewById(f.login_account_auto); this.eSa = (MMFormInputView) findViewById(f.login_password_et); this.eRX = (MMClearEditText) this.eRZ.getContentEditText(); this.eRY = (MMClearEditText) this.eSa.getContentEditText(); com.tencent.mm.ui.tools.a.c.d(this.eRY).Gi(16).a(null); this.eSb = (Button) findViewById(f.login_btn); this.eSb.setEnabled(false); this.eSc = (Button) findViewById(f.login_by_other); this.eRo = (Button) findViewById(f.login_as_other_device_btn); this.eSd = findViewById(f.login_bottom_container); this.eSd.setVisibility(0); this.eQU = (Button) findViewById(f.login_find_password_btn); this.eQW = findViewById(f.free_btn_container); this.eQV = (Button) findViewById(f.login_freeze_account_btn); this.eQX = (Button) findViewById(f.login_more_btn); this.eRf = (ResizeLayout) findViewById(f.resize_lv); this.eSh = (MMKeyboardUperView) findViewById(f.scrollView); this.eRf.setOnSizeChanged(new 20(this)); boolean PA = b.PA(); View findViewById = findViewById(f.fblogin_tip); findViewById.setVisibility(!PA ? 8 : 0); findViewById.setOnClickListener(new OnClickListener() { public final void onClick(View view) { LoginUI.this.startActivity(new Intent(LoginUI.this, FacebookLoginUI.class)); } }); this.eQU.setOnClickListener(new 22(this)); this.eQV.setOnClickListener(new OnClickListener() { public final void onClick(View view) { LoginUI.P(LoginUI.this, LoginUI.this.getString(j.freeze_account_url, new Object[]{w.chP()})); } }); this.eSg = new com.tencent.mm.ui.widget.a.d(this, 1, false); this.eSg.ofp = new 24(this); this.eSg.uJQ = new d$a() { public final void onDismiss() { LoginUI.this.eSg.bzW(); } }; this.eSg.ofq = new 26(this); if (w.chM()) { this.eQX.setOnClickListener(new 2(this)); } else { this.eQW.setVisibility(8); this.eQX.setText(j.login_by_more); this.eQX.setOnClickListener(new 3(this)); } setMMTitle(""); setBackBtn(new 4(this), i.actionbar_icon_close_black); this.eSb.setOnClickListener(new 5(this)); this.eSc.setOnClickListener(new 6(this)); this.eOW = getIntent().getStringExtra("auth_ticket"); if (!bi.oW(this.eOW)) { this.eRX.setText(bi.oV(f.YF())); this.eRY.setText(bi.oV(f.YG())); new ag().postDelayed(new 7(this), 500); } this.eRX.addTextChangedListener(this.UE); this.eRY.addTextChangedListener(this.UE); this.eRY.setOnEditorActionListener(new 8(this)); this.eRY.setOnKeyListener(new 9(this)); if (com.tencent.mm.sdk.platformtools.e.sFE) { a.ezo.g(this); } CharSequence stringExtra = getIntent().getStringExtra("login_username"); this.eSi = getIntent().getBooleanExtra("from_deep_link", false); if (!bi.oW(stringExtra)) { this.eRX.setText(stringExtra); } if (com.tencent.mm.sdk.platformtools.d.EX_DEVICE_LOGIN) { this.eRo.setVisibility(0); this.eRo.setOnClickListener(new 10(this)); } } private static void P(Context context, String str) { Intent intent = new Intent(); intent.putExtra("rawUrl", str); intent.putExtra("showShare", false); intent.putExtra("show_bottom", false); intent.putExtra("needRedirect", false); intent.putExtra("neverGetA8Key", true); intent.putExtra("hardcode_jspermission", JsapiPermissionWrapper.qWa); intent.putExtra("hardcode_general_ctrl", GeneralControlWrapper.qVX); com.tencent.mm.bg.d.b(context, "webview", "com.tencent.mm.plugin.webview.ui.tools.WebViewUI", intent); } public boolean onKeyDown(int i, KeyEvent keyEvent) { if (i != 4) { return super.onKeyDown(i, keyEvent); } goBack(); return true; } private void goBack() { YC(); com.tencent.mm.plugin.c.a.pU(this.eHy); p.cbS(); finish(); } private boolean e(int i, int i2, String str) { if (a.ezo.a(this.mController.tml, i, i2, str)) { return true; } if (i == 4) { switch (i2) { case -311: case -310: case -6: g.DF().a(TbsMediaPlayer$TbsMediaPlayerListener.MEDIA_INFO_BUFFERING_START, this); if (this.eIX == null) { this.eIX = SecurityImage.a.a(this, j.regbyqq_secimg_title, this.eQY.eRQ, this.eQY.eIZ, this.eQY.eJa, this.eQY.eJb, new 13(this), null, new 14(this), this.eQY); } else { x.d("MicroMsg.LoginUI", "imgSid:" + this.eQY.eJa + " img len" + this.eQY.eIZ.length + " " + com.tencent.mm.compatible.util.g.Ac()); this.eIX.a(this.eQY.eRQ, this.eQY.eIZ, this.eQY.eJa, this.eQY.eJb); } return true; case -205: x.i("MicroMsg.LoginUI", "summerphone MM_ERR_QQ_OK_NEED_MOBILE authTicket[%s], closeShowStyle[%s]", new Object[]{bi.Xf(this.eOW), this.eRb}); f.a(this.eQY); com.tencent.mm.plugin.c.a.pU("L600_100"); Intent intent = new Intent(); intent.putExtra("auth_ticket", this.eOW); intent.putExtra("binded_mobile", this.eRa); intent.putExtra("close_safe_device_style", this.eRb); intent.putExtra("from_source", 1); a.ezn.g(this, intent); return true; case -140: if (!bi.oW(this.cbP)) { aa.n(this, str, this.cbP); } return true; case -100: String af; com.tencent.mm.kernel.a.hold(); ActionBarActivity actionBarActivity = this.mController.tml; g.Eg(); if (TextUtils.isEmpty(com.tencent.mm.kernel.a.Dh())) { af = com.tencent.mm.bp.a.af(this.mController.tml, j.main_err_another_place); } else { g.Eg(); af = com.tencent.mm.kernel.a.Dh(); } com.tencent.mm.ui.base.h.a(actionBarActivity, af, this.mController.tml.getString(j.app_tip), new DialogInterface.OnClickListener() { public final void onClick(DialogInterface dialogInterface, int i) { LoginUI.l(LoginUI.this); } }, new 16(this)); return true; case -75: aa.ch(this.mController.tml); return true; case -72: com.tencent.mm.ui.base.h.i(this.mController.tml, j.regbyqq_auth_err_failed_niceqq, j.app_tip); return true; case -9: com.tencent.mm.ui.base.h.i(this, j.login_err_mailnotverify, j.login_err_title); return true; case -3: com.tencent.mm.ui.base.h.i(this, j.errcode_password, j.login_err_title); return true; case -1: if (g.DF().Lg() != 5) { return false; } com.tencent.mm.ui.base.h.i(this, j.net_warn_server_down_tip, j.net_warn_server_down); return true; } } return this.eRi.a(this, new ah(i, i2, str)); } public final void a(int i, int i2, String str, l lVar) { x.i("MicroMsg.LoginUI", "onSceneEnd: errType = " + i + " errCode = " + i2 + " errMsg = " + str); if (this.eHw != null) { this.eHw.dismiss(); this.eHw = null; } if (lVar.getType() == TbsMediaPlayer$TbsMediaPlayerListener.MEDIA_INFO_BUFFERING_START) { int i3; g.DF().b(TbsMediaPlayer$TbsMediaPlayerListener.MEDIA_INFO_BUFFERING_START, this); this.cbP = ((q) lVar).Rd(); this.eQY.eJa = ((q) lVar).Re(); this.eQY.eIZ = ((q) lVar).Rf(); this.eQY.eJb = ((q) lVar).Rg(); this.eQY.eRQ = ((q) lVar).getSecCodeType(); this.eQY.account = ((q) lVar).account; if (i2 == -205) { this.eOW = ((q) lVar).Ok(); this.eRa = ((q) lVar).Rh(); this.eRb = ((q) lVar).Rk(); } if (i == 4 && (i2 == -16 || i2 == -17)) { g.DF().a(new bg(new 17(this)), 0); i3 = 1; } else { boolean i32 = false; } if (i32 != 0 || (i == 0 && i2 == 0)) { com.tencent.mm.kernel.a.unhold(); aa.oS(this.eQY.account); String I = at.dBv.I("login_weixin_username", ""); com.tencent.mm.platformtools.x.bZ(this); if (this.eSf) { bt.dDs.W(this.eSe, I); bt.dDs.d(com.tencent.mm.model.q.GF(), com.tencent.mm.model.q.Ho()); h.mEJ.h(14978, new Object[]{Integer.valueOf(1), Integer.valueOf(9), bt.dDs.II()}); } aa.showAddrBookUploadConfirm(this, new 18(this, lVar), false, 2); StringBuilder stringBuilder = new StringBuilder(); g.Eg(); stringBuilder = stringBuilder.append(com.tencent.mm.kernel.a.DA()).append(",").append(getClass().getName()).append(",R200_900_phone,"); g.Eg(); com.tencent.mm.plugin.c.a.pV(stringBuilder.append(com.tencent.mm.kernel.a.gd("R200_900_phone")).append(",4").toString()); if (this.eSi) { I = ad.getContext().getSharedPreferences("randomid_prefs", 4).getString("randomID", ""); h.mEJ.h(11930, new Object[]{I, Integer.valueOf(4)}); } } else if (i2 == -106) { aa.e(this, str, 32644); } else if (i2 == -217) { aa.a(this, com.tencent.mm.platformtools.f.a((q) lVar), i2); } else if (!e(i, i2, str)) { if (i2 == -5) { Toast.makeText(this, getString(j.loginby_access_denied), 0).show(); return; } com.tencent.mm.h.a eV = com.tencent.mm.h.a.eV(str); if (eV == null || !eV.a(this, null, null)) { Toast.makeText(this, getString(j.fmt_auth_err, new Object[]{Integer.valueOf(i), Integer.valueOf(i2)}), 0).show(); } } } } private void Yz() { this.eQY.account = this.eRX.getText().toString().trim(); this.eQY.eIY = this.eRY.getText().toString(); if (this.eQY.account.equals("")) { com.tencent.mm.ui.base.h.i(this, j.verify_username_null_tip, j.login_err_title); } else if (this.eQY.eIY.equals("")) { com.tencent.mm.ui.base.h.i(this, j.verify_password_null_tip, j.login_err_title); } else { YC(); g.DF().a(TbsMediaPlayer$TbsMediaPlayerListener.MEDIA_INFO_BUFFERING_START, this); q qVar = new q(this.eQY.account, this.eQY.eIY, this.eOW, 2); g.DF().a(qVar, 0); getString(j.app_tip); this.eHw = com.tencent.mm.ui.base.h.a(this, getString(j.login_logining), true, new 19(this, qVar)); } } public void finish() { super.finish(); overridePendingTransition(com.tencent.mm.plugin.account.a.a.anim_not_change, com.tencent.mm.plugin.account.a.a.anim_not_change); } protected void onActivityResult(int i, int i2, Intent intent) { int i3 = 0; super.onActivityResult(i, i2, intent); String str = "MicroMsg.LoginUI"; String str2 = "onActivityResult, requestCode:%d, resultCode:%d, data==null:%b"; Object[] objArr = new Object[3]; objArr[0] = Integer.valueOf(i); objArr[1] = Integer.valueOf(i2); objArr[2] = Boolean.valueOf(intent == null); x.d(str, str2, objArr); if (i2 != -1) { return; } if (i == 1024 && intent != null) { String stringExtra = intent.getStringExtra("VoiceLoginAuthPwd"); int intExtra = intent.getIntExtra("KVoiceHelpCode", 0); str2 = "MicroMsg.LoginUI"; String str3 = "onActivityResult, do voiceprint auth, authPwd is null:%b, authPwd.len:%d, lastErrCode:%d"; Object[] objArr2 = new Object[3]; objArr2[0] = Boolean.valueOf(bi.oW(stringExtra)); if (!bi.oW(stringExtra)) { i3 = stringExtra.length(); } objArr2[1] = Integer.valueOf(i3); objArr2[2] = Integer.valueOf(intExtra); x.d(str2, str3, objArr2); if (intExtra == -217) { this.eQY.eIY = stringExtra; Yz(); } } else if (i == 32644 && intent != null) { Bundle bundleExtra = intent.getBundleExtra("result_data"); if (bundleExtra != null && bundleExtra.getString("go_next", "").equals("auth_again")) { if (!bi.oW(bundleExtra.getString("VoiceLoginAuthPwd"))) { this.eQY.eIY = intent.getStringExtra("VoiceLoginAuthPwd"); } Yz(); } } } }
package com.goldgov.gtiles.core.dao.mybatis; import java.beans.Introspector; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.BeanNameGenerator; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.util.ClassUtils; import com.goldgov.gtiles.core.dao.mybatis.annotation.MybatisRepository; /** * MyBatis的Bean名称定义规则类,用于定义在MyBatis的数据访问对象在Spring中作为Bean的ID值, * 如不指定,则类名以首字母小写作为Bean的ID值 * @author LiuHG * @version 1.0 */ public class MyBatisMapperNameGenerator implements BeanNameGenerator { @Override public String generateBeanName(BeanDefinition arg0, BeanDefinitionRegistry arg1) { String shortClassName = ClassUtils.getShortName(arg0.getBeanClassName()); Class<?> mappingClass = null; try { mappingClass = Class.forName(arg0.getBeanClassName()); } catch (ClassNotFoundException e) { throw new RuntimeException("class not found",e); } MybatisRepository annos = AnnotationUtils.findAnnotation(mappingClass, MybatisRepository.class); if("".equals(annos.value())){ return Introspector.decapitalize(shortClassName); } return annos.value(); } }
package com.redhat.vizuri.insurance; import java.io.Serializable; import java.util.Date; public class Incident implements Serializable { private static final long serialVersionUID = -1164413366918727474L; private Long id; private IncidentType type; private String description; private Date incidentDate; private String stateCode; private String zipCode; public Incident() { super(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public IncidentType getType() { return type; } public void setType(IncidentType type) { this.type = type; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Date getIncidentDate() { return incidentDate; } public void setIncidentDate(Date incidentDate) { this.incidentDate = incidentDate; } public String getStateCode() { return stateCode; } public void setStateCode(String stateCode) { this.stateCode = stateCode; } public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } @Override public String toString() { return "Incident [id=" + id + ", type=" + type + ", description=" + description + ", incidentDate=" + incidentDate + ", stateCode=" + stateCode + ", zipCode=" + zipCode + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((description == null) ? 0 : description.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((incidentDate == null) ? 0 : incidentDate.hashCode()); result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Incident other = (Incident) obj; if (description == null) { if (other.description != null) return false; } else if (!description.equals(other.description)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (incidentDate == null) { if (other.incidentDate != null) return false; } else if (!incidentDate.equals(other.incidentDate)) return false; if (type != other.type) return false; return true; } }
package com.theta360.sample.v2; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.app.FragmentManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.net.ConnectivityManager; import android.net.Network; import android.net.NetworkCapabilities; import android.net.NetworkInfo; import android.net.NetworkRequest; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; import android.widget.Toolbar; import com.theta360.sample.v2.model.ImageSize; import com.theta360.sample.v2.network.DeviceInfo; import com.theta360.sample.v2.network.HttpConnector; import com.theta360.sample.v2.network.HttpEventListener; import com.theta360.sample.v2.network.ImageInfo; import com.theta360.sample.v2.network.StorageInfo; import com.theta360.sample.v2.view.ConfigurationDialog; import com.theta360.sample.v2.view.ImageListArrayAdapter; import com.theta360.sample.v2.view.ImageRow; //import com.theta360.sample.v2.view.LogView; import com.theta360.sample.v2.view.MJpegInputStream; import com.theta360.sample.v2.view.MJpegView; import org.json.JSONException; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; /** * Activity that displays the photo list */ public class ImageListActivity extends Activity { private ListView objectList; private String cameraIpAddress; private boolean mConnectionSwitchEnabled = false; private LoadObjectListTask sampleTask = null; private GetImageSizeTask getImageSizeTask = null; /** * onCreate Method * @param savedInstanceState onCreate Status value */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override protected void onPause() { super.onPause(); //mMv.stopPlay(); } @Override protected void onResume() { super.onResume(); setContentView(R.layout.activity_object_list); cameraIpAddress = getResources().getString(R.string.theta_ip_address); getActionBar().setTitle("Image List"); forceConnectToWifi(); objectList = (ListView) findViewById(R.id.object_list); ImageListArrayAdapter empty = new ImageListArrayAdapter(ImageListActivity.this, R.layout.listlayout_object, new ArrayList<ImageRow>()); objectList.setAdapter(empty); sampleTask = new LoadObjectListTask(); sampleTask.execute(); //mMv.play(); /* if (livePreviewTask != null) { livePreviewTask.cancel(true); livePreviewTask = new ShowLiveViewTask(); livePreviewTask.execute(cameraIpAddress); } */ } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == GLPhotoActivity.REQUEST_REFRESH_LIST) { if (sampleTask != null) { sampleTask.cancel(true); } sampleTask = new LoadObjectListTask(); sampleTask.execute(); } } @Override protected void onDestroy() { if (sampleTask != null) { sampleTask.cancel(true); } if (getImageSizeTask != null) { getImageSizeTask.cancel(true); } super.onDestroy(); } /** * onCreateOptionsMenu Method * @param menu Menu initialization object * @return Menu display feasibility status value */ @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.connection, menu); Switch connectionSwitch = (Switch) menu.findItem(R.id.connection).getActionView().findViewById(R.id.connection_switch); connectionSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { objectList = (ListView) findViewById(R.id.object_list); ImageListArrayAdapter empty = new ImageListArrayAdapter(ImageListActivity.this, R.layout.listlayout_object, new ArrayList<ImageRow>()); objectList.setAdapter(empty); if (isChecked) { //layoutCameraArea.setVisibility(View.VISIBLE); if (sampleTask == null) { sampleTask = new LoadObjectListTask(); sampleTask.execute(); } /* if (livePreviewTask == null) { livePreviewTask = new ShowLiveViewTask(); livePreviewTask.execute(cameraIpAddress); } */ if (getImageSizeTask == null) { getImageSizeTask = new GetImageSizeTask(); getImageSizeTask.execute(); } } else { //layoutCameraArea.setVisibility(View.INVISIBLE); if (sampleTask != null) { sampleTask.cancel(true); sampleTask = null; } /* if (livePreviewTask != null) { livePreviewTask.cancel(true); livePreviewTask = null; } */ if (getImageSizeTask != null) { getImageSizeTask.cancel(true); getImageSizeTask = null; } new DisConnectTask().execute(); //mMv.stopPlay(); } } }); return true; } /** * onOptionsItemSelected Method * @param item Process menu * @return Menu process continuation feasibility value */ @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { case R.id.takePhoto: // 写真撮影画面(Activity)に遷移 Intent intent = new Intent(getApplication(), TakePhotoActivity.class); startActivity(intent); break; default: break; } return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { Switch connectionSwitch = (Switch) menu.findItem(R.id.connection).getActionView().findViewById(R.id.connection_switch); if (!mConnectionSwitchEnabled) { connectionSwitch.setChecked(false); } connectionSwitch.setEnabled(mConnectionSwitchEnabled); return true; } private void changeCameraStatus(final int resid) { runOnUiThread(new Runnable() { public void run() { //textCameraStatus.setText(resid); } }); } // // 返り値:IMAGE_SIZE_5376x2688 (THETA Vでは固定) // private class GetImageSizeTask extends AsyncTask<Void, String, ImageSize> { @Override protected ImageSize doInBackground(Void... params) { publishProgress("get current image size"); HttpConnector camera = new HttpConnector(cameraIpAddress); ImageSize imageSize = camera.getImageSize(); return imageSize; } @Override protected void onProgressUpdate(String... values) { } @Override protected void onPostExecute(ImageSize imageSize) { if (imageSize != null) { } } } private class LoadObjectListTask extends AsyncTask<Void, String, List<ImageRow>> { private ProgressBar progressBar; // コンストラクタ // progressBarの設定 public LoadObjectListTask() { progressBar = (ProgressBar) findViewById(R.id.loading_object_list_progress_bar); } // 実行前処理 // progressBarの可視化 @Override protected void onPreExecute() { progressBar.setVisibility(View.VISIBLE); } // メイン処理 // 返り値:List<ImageRow> @Override protected List<ImageRow> doInBackground(Void... params) { try { String storagePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/image/thumbnail"; File[] _files = new File(storagePath).listFiles(); ArrayList<File> files = new ArrayList<File>(); for (File file : _files){ Log.d("debug",file.getName()); if(file.isFile()) { files.add(file); Log.d("debug",file.getName()); } } //HttpConnector camera = new HttpConnector(cameraIpAddress); //changeCameraStatus(R.string.text_camera_standby); List<ImageRow> imageRows = new ArrayList<>(); //StorageInfo storage = camera.getStorageInfo(); ImageRow storageCapacity = new ImageRow(); //int freeSpaceInImages = storage.getFreeSpaceInImages(); int megaByte = 1024 * 1024; //long freeSpace = storage.getFreeSpaceInBytes() / megaByte; //long maxSpace = storage.getMaxCapacity() / megaByte; //storageCapacity.setFileName("Free space: " + freeSpaceInImages + "[shots] (" + freeSpace + "/" + maxSpace + "[MB])"); imageRows.add(storageCapacity); //ArrayList<ImageInfo> objects = camera.getList(); //int objectSize = objects.size(); for (int i = 0; i < files.size(); i++) { ImageRow imageRow = new ImageRow(); //ImageInfo object = objects.get(i); //imageRow.setFileSize(object.getFileSize()); // TODO // imageRowの情報が十分か確認する String fname = getfilename(files.get(i).getAbsoluteFile().toString()); fname = fname.substring(fname.length() - 12); //imageRow.setFileName(object.getFileName()); imageRow.setFileName(fname); imageRow.setFileId(fname); //imageRow.setCaptureDate(object.getCaptureDate()); //publishProgress("<ImageInfo: File ID=" + object.getFileId() + ", filename=" + object.getFileName() + ", capture_date=" + object.getCaptureDate() // + ", image_pix_width=" + object.getWidth() + ", image_pix_height=" + object.getHeight() + ", object_format=" + object.getFileFormat() // + ">"); //if (object.getFileFormat().equals(ImageInfo.FILE_FORMAT_CODE_EXIF_JPEG)) { imageRow.setIsPhoto(true); // Bitmap thumbnail = camera.getThumb(object.getFileId()); // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, baos); // final byte[] thumbnailImage = baos.toByteArray(); byte[] thumbnailImage = convertFile(files.get(i)); imageRow.setThumbnail(thumbnailImage); //} else { // imageRow.setIsPhoto(false); //} imageRows.add(imageRow); //publishProgress("getList: " + (i + 1) + "/" + objectSize); } return imageRows; } catch (Throwable throwable) { String errorLog = Log.getStackTraceString(throwable); publishProgress(errorLog); return null; } } String getfilename(String fileId) { String[] list = fileId.split("/",0); String fname = list[list.length-1]; return fname; } public byte[] convertFile(File file) { try (FileInputStream inputStream = new FileInputStream(file);) { ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; while(true) { int len = inputStream.read(buffer); if(len < 0) { break; } bout.write(buffer, 0, len); } return bout.toByteArray(); } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onProgressUpdate(String... values) { } @Override protected void onPostExecute(List<ImageRow> imageRows) { if (imageRows != null) { imageRows.remove(0); ImageListArrayAdapter imageListArrayAdapter = new ImageListArrayAdapter(ImageListActivity.this, R.layout.listlayout_object, imageRows); objectList.setAdapter(imageListArrayAdapter); objectList.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ImageRow selectedItem = (ImageRow) parent.getItemAtPosition(position); if (selectedItem.isPhoto()) { byte[] thumbnail = selectedItem.getThumbnail(); String fileId = selectedItem.getFileId(); GLPhotoActivity.startActivityForResult(ImageListActivity.this, cameraIpAddress, fileId, thumbnail, false); } else { Toast.makeText(getApplicationContext(), "This isn't a photo.", Toast.LENGTH_SHORT).show(); } } }); objectList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { private String mFileId; @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { ImageRow selectedItem = (ImageRow) parent.getItemAtPosition(position); mFileId = selectedItem.getFileId(); String fileName = selectedItem.getFileName(); new AlertDialog.Builder(ImageListActivity.this) .setTitle(fileName) .setMessage(R.string.delete_dialog_message) .setPositiveButton(R.string.dialog_positive_button, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { DeleteObjectTask deleteTask = new DeleteObjectTask(); deleteTask.execute(mFileId); } }) .show(); return true; } }); } //else { // logViewer.append("failed to get image list"); //} progressBar.setVisibility(View.GONE); } @Override protected void onCancelled() { progressBar.setVisibility(View.GONE); } } private class DeleteObjectTask extends AsyncTask<String, String, Void> { @Override protected Void doInBackground(String... fileId) { publishProgress("start delete file"); DeleteEventListener deleteListener = new DeleteEventListener(); HttpConnector camera = new HttpConnector(getResources().getString(R.string.theta_ip_address)); camera.deleteFile(fileId[0], deleteListener); return null; } @Override protected void onProgressUpdate(String... values) { //for (String log : values) { // logViewer.append(log); //} } @Override protected void onPostExecute(Void aVoid) { //logViewer.append("done"); } private class DeleteEventListener implements HttpEventListener { @Override public void onCheckStatus(boolean newStatus) { //if (newStatus) { // appendLogView("deleteFile:FINISHED"); //} else { // appendLogView("deleteFile:IN PROGRESS"); //} } @Override public void onObjectChanged(String latestCapturedFileId) { // appendLogView("delete " + latestCapturedFileId); } @Override public void onCompleted() { // appendLogView("deleted."); runOnUiThread(new Runnable() { @Override public void run() { new LoadObjectListTask().execute(); } }); } @Override public void onError(String errorMessage) { //appendLogView("delete error " + errorMessage); } } } private class DisConnectTask extends AsyncTask<Void, String, Boolean> { @Override protected Boolean doInBackground(Void... params) { try { publishProgress("disconnected."); return true; } catch (Throwable throwable) { String errorLog = Log.getStackTraceString(throwable); publishProgress(errorLog); return false; } } @Override protected void onProgressUpdate(String... values) { } } /** * Force this applicatioin to connect to Wi-Fi */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) private void forceConnectToWifi() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { if ((info != null) && info.isAvailable()) { NetworkRequest.Builder builder = new NetworkRequest.Builder(); builder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI); NetworkRequest requestedNetwork = builder.build(); ConnectivityManager.NetworkCallback callback = new ConnectivityManager.NetworkCallback() { @Override public void onAvailable(Network network) { super.onAvailable(network); ConnectivityManager.setProcessDefaultNetwork(network); mConnectionSwitchEnabled = true; invalidateOptionsMenu(); // appendLogView("connect to Wi-Fi AP"); } @Override public void onLost(Network network) { super.onLost(network); mConnectionSwitchEnabled = false; invalidateOptionsMenu(); // appendLogView("lost connection to Wi-Fi AP"); } }; cm.registerNetworkCallback(requestedNetwork, callback); } } else { mConnectionSwitchEnabled = true; invalidateOptionsMenu(); } } }
package com.example.corei7.nacimientos; import com.example.corei7.nacimientos.model.DatosResponse; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; /** * Created by Core i7 on 19/09/2017. */ public interface DatosGobBoService { @GET("action/datastore_search") Call<DatosResponse> Nacimientos(@Query("resource_id") String resourceId, @Query("limit") int limit); @GET("action/datastore_search") Call<DatosResponse> Nacimientos(@Query("resource_id") String resourceId, @Query("q") String query); }
package com.tencent.mm.plugin.fav.a; import com.tencent.mm.kernel.g; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.aa.a; class d$1 implements Runnable { final /* synthetic */ d iVC; d$1(d dVar) { this.iVC = dVar; } public final void run() { ((ae) g.n(ae.class)).getFavItemInfoStorage().aLI(); d.a(this.iVC, System.currentTimeMillis()); x.d("MicroMsg.FavCleanFirstLoader", "calDataBaseDataTotalLength, used: %dms", new Object[]{Long.valueOf(d.a(this.iVC) - d.b(this.iVC))}); d.a(this.iVC, -1); d.c(this.iVC); synchronized (d.d(this.iVC)) { g.Ei().DT().a(a.sRp, Boolean.valueOf(true)); d.e(this.iVC); } this.iVC.mHandler.sendEmptyMessage(0); } }
package scriptinterface; import global.StringRepresentation; import scriptinterface.execution.returnvalues.ExecutionError; /** * Parser for signatures which are given as string. * * @author Andreas Fender */ public interface SignatureInterface extends StringRepresentation { /** * Parses the given string and extracts key, parameters etc. to store it and making it easy to access. * * @param signatureString the string to parse. * @param scriptSystem the script system to calculate default values. * @return null, if no error occurs. The error otherwise. */ public ExecutionError createSignature(String signatureString, ScriptSystemInterface<?, ?> scriptSystem); /** * Returns the parameter tuple, including parameter keys, types and default values. * * @return the parameter tuple. */ public ParameterTuple getParameterTuple(); /** * Returns the main key of the signature. * * @return the main key. */ public String getMainKey(); /** * Returns the main key and the aliases separated by a |. * * @return the main key and the aliases. */ public String getKeysAsString(); /** * Returns the string representation of the return type, whereas no return type yields "void". * * @return the string representation of the return type. */ public String getReturnValueAsString(); /** * Returns the main key and the aliases as an array. * * @return the main key and the aliases. */ public String[] getKeyArray(); }
package main; import daos.EmpDeptDao; import pojos.Dept; import pojos.Emp; import utils.HbUtil; public class Hb01Main { public static void main(String[] args) { EmpDeptDao dao = new EmpDeptDao(); //get emp using empno // try { // HbUtil.beginTransaction(); // Emp e = dao.getEmp(7900); // System.out.println("Found : " + e); // HbUtil.commitTransaction(); // } catch (Exception e) { // e.printStackTrace(); // HbUtil.rollbackTransaction(); // } //get dept based on deptno // try { // HbUtil.beginTransaction(); // Dept d = dao.getDept(10); // System.out.println("Found : " + d); // HbUtil.commitTransaction(); // } catch (Exception e) { // e.printStackTrace(); // HbUtil.rollbackTransaction(); // } //OneToMany = one dept has MANY emp //get deptno=10 and find all emp with same deptno. try { HbUtil.beginTransaction(); Dept d = dao.getDept(10); System.out.println("Found : " + d); for (Emp e : d.getEmpList()) System.out.println(e); HbUtil.commitTransaction(); } catch (Exception e) { e.printStackTrace(); HbUtil.rollbackTransaction(); } // try { // HbUtil.beginTransaction(); // Emp e = dao.getEmp(7900); // System.out.println("Found : " + e); // int d = e.getDeptno(); // System.out.println("Found : " + d); // HbUtil.commitTransaction(); // } catch (Exception e) { // e.printStackTrace(); // HbUtil.rollbackTransaction(); // } HbUtil.shutdown(); } }
package pl.cwanix.opensun.agentserver.packets.processors.status; import io.netty.channel.ChannelHandlerContext; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.slf4j.Marker; import org.slf4j.MarkerFactory; import pl.cwanix.opensun.agentserver.packets.c2s.status.C2SAskStatSelectPacket; import pl.cwanix.opensun.agentserver.packets.s2c.status.S2CAnsStatSelectPacket; import pl.cwanix.opensun.agentserver.packets.s2c.status.S2CErrStatSelectPacket; import pl.cwanix.opensun.agentserver.server.AgentServerChannelHandler; import pl.cwanix.opensun.agentserver.server.session.AgentServerSession; import pl.cwanix.opensun.commonserver.packets.SUNPacketProcessor; import pl.cwanix.opensun.commonserver.packets.annotations.PacketProcessor; import pl.cwanix.opensun.model.character.CharacterDataSource; @SuppressWarnings("checkstyle:MagicNumber") @Slf4j @RequiredArgsConstructor @PacketProcessor(packetClass = C2SAskStatSelectPacket.class) public class C2SAskStatSelectProcessor implements SUNPacketProcessor<C2SAskStatSelectPacket> { private static final Marker MARKER = MarkerFactory.getMarker("C2S -> STAT SELECT"); private final CharacterDataSource characterDataSource; @Override public void process(final ChannelHandlerContext ctx, final C2SAskStatSelectPacket packet) { AgentServerSession session = ctx.channel().attr(AgentServerChannelHandler.SESSION_ATTRIBUTE).get(); log.debug(MARKER, "Updating character statistics: {}", packet.getAttributeCode()); int responseCode = characterDataSource.updateCharacterStatistics(session.getCharacter().getId(), packet.getAttributeCode().toByte()); if (responseCode == 0) { ctx.writeAndFlush(new S2CAnsStatSelectPacket(packet.getAttributeCode().toByte(), 99)); } else { ctx.writeAndFlush(new S2CErrStatSelectPacket(packet.getAttributeCode().toByte(), responseCode)); } } }
package resource; import lombok.Data; import java.io.Serializable; import java.util.Map; import java.util.TreeMap; /** * Player class - contains Player details and scores */ @Data public class Player implements Serializable { private String name; private int id; private static int playerIds = 1; private Map<Integer,Integer> scores; public Player(String name){ this.name = name; scores = new TreeMap<>(); id = playerIds++; } /** * Add a score to the internal map * @param quizId - the id of the quiz played * @param newScore - the score */ public int addScore(int quizId, int newScore){ //check to see if the quiz already has a score associated with it // if the existing score is HIGHER just leave the existing high score for that quiz if (scores.containsKey(quizId) && (scores.get(quizId) > newScore)) { return scores.get(quizId); } scores.put(quizId,newScore); return newScore; } public int getHighScore(){ return scores.values().stream().max((x,y) -> x > y ? 1:-1).get(); } /** * Override equals to allow for easy comparison * @param other - the other object to be compared * @return true or false depending on whether they are equal */ @Override public boolean equals(Object other){ if (this.getClass() != other.getClass()){ return false; } if (this == other) { return true; } Player player2 = (Player) other; if (this.getId()!=player2.getId()){ return false; } if (!this.getName().equals(player2.getName())){ return false; } return true; } /** * Override hashcode because equals overridden * @return hashcode */ @Override public int hashCode() { int hash = 3; hash = 12 * hash + this.name.hashCode(); return hash; } }
package materialdesign.practice.com.recyclerfragment.Activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import java.io.Serializable; import materialdesign.practice.com.recyclerfragment.R; import materialdesign.practice.com.recyclerfragment.Util.ModelClass; public class SEShowActivity extends AppCompatActivity { TextView tvName, tvTitle, tvDescp, tvLink; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_seshow); supportPostponeEnterTransition(); /* Intent i = new Intent(); Bundle b = new Bundle(); ModelClass modelClass = (ModelClass) i.getSerializableExtra("title"); //("title"); String transition = b.getString("transition"); */ tvName = findViewById(R.id.tvName); tvTitle = findViewById(R.id.tvTitle); tvDescp = findViewById(R.id.tvDescp); tvLink = findViewById(R.id.tvLink); ModelClass obj = new ModelClass(); tvLink.setText(obj.getLink()); /*tvName.setTransitionName(transition); tvTitle.setTransitionName(transition); tvDescp.setTransitionName(transition); tvLink.setTransitionName(transition); tvName.setText(modelClass.getName()); tvTitle.setText(modelClass.getTitle()); tvDescp.setText(modelClass.getDescp()); tvLink.setText(modelClass.getLink());*/ } }
package com.tkb.elearning.dao.impl; import java.util.ArrayList; import java.util.List; import com.tkb.elearning.dao.AboutLawDao; import com.tkb.elearning.model.AboutLaw; import sso.ojdbc.dao.impl.PagingDaoImpl; /** * 相關法規Dao實作類 * @author Admin * @version 創建時間:2016-03-14 */ public class AboutLawDaoImpl extends PagingDaoImpl implements AboutLawDao { @SuppressWarnings("unchecked") public List<AboutLaw> getList(int pageCount, int pageStart, AboutLaw aboutLaw) { List<Object> args = new ArrayList<Object>(); String sql = " SELECT * FROM about_law "; if(aboutLaw.getTitle() != null && !"".equals(aboutLaw.getTitle())) { sql += " WHERE TITLE LIKE ? "; args.add("%" + aboutLaw.getTitle() + "%"); } sql += " ORDER BY ID LIMIT ?, ? "; // sql = " SELECT * FROM " // + " (SELECT a.*, ROWNUM rn FROM( " + sql +")a " // + " WHERE ROWNUM <= ?) WHERE rn >= ? "; args.add(pageStart); args.add(pageCount); return getJdbcTemplate().query(sql, args.toArray(), getRowMapper()); } public Integer getCount(AboutLaw aboutLaw) { List<Object> args = new ArrayList<Object>(); String sql = " SELECT COUNT(*) FROM about_law "; if(aboutLaw.getTitle() != null && !"".equals(aboutLaw.getTitle())) { sql += " WHERE TITLE LIKE ? "; args.add("%" + aboutLaw.getTitle() + "%"); } return getJdbcTemplate().queryForInt(sql, args.toArray()); } public AboutLaw getData(AboutLaw aboutLaw) { String sql = " SELECT * FROM about_law WHERE ID = ? "; return (AboutLaw)getJdbcTemplate().query(sql, new Object[]{ aboutLaw.getId() }, getRowMapper()).get(0); } public void add(AboutLaw aboutLaw) { String sql = " INSERT INTO about_law(TITLE, CONTENT, FILE, " + " CREATE_DATE, UPDATE_DATE)VALUES(?, ?, ?, NOW(), NOW()) "; getJdbcTemplate().update(sql, new Object[] { aboutLaw.getTitle(), aboutLaw.getContent(), aboutLaw.getFile() }); } public void update(AboutLaw aboutLaw) { String sql = " UPDATE about_law SET TITLE = ?,CONTENT = ?, " + " FILE = ?, UPDATE_DATE = NOW() WHERE ID = ? "; getJdbcTemplate().update(sql, new Object[] { aboutLaw.getTitle(), aboutLaw.getContent(), aboutLaw.getFile(), aboutLaw.getId() }); } public void delete(Integer id) { String sql = " DELETE FROM about_law WHERE ID = ? "; getJdbcTemplate().update(sql, new Object[] { id }); } }
public class Card { public final static int SPADE = 0; public final static int CLUB = 1; public final static int DIAMOND = 2; public final static int HEART = 3; private int suit; private int rank; public Card(int suit, int rank) { this.suit = suit; this.rank = rank; } public int getSuite() { return suit; } public int getRank() { return rank; } public String toString() { String suitString = "", rankString = ""; switch(rank) { case 1: rankString = "Ace"; break; case 2: rankString = "Two"; break; case 3: rankString = "Three"; break; case 4: rankString = "Four"; break; case 5: rankString = "Five"; break; case 6: rankString = "Six"; break; case 7: rankString = "Seven"; break; case 8: rankString = "Eight"; break; case 9: rankString = "Nine"; break; case 10: rankString = "Ten"; break; case 11: rankString = "Jack"; break; case 12: rankString = "Queen"; break; case 13: rankString = "King"; break; } switch(suit) { case Card.SPADE: suitString = "Spade"; break; case Card.CLUB: suitString = "Club"; break; case Card.DIAMOND: suitString = "Diamond"; break; case Card.HEART: suitString = "Heart"; break; } return rankString + " of " + suitString; } }
package ru.otus.adapters.function; import org.junit.Assert; import org.junit.Test; import ru.otus.models.StatisticEntity; import java.util.function.Function; public class CreateStatisticEntityTest { @Test(expected = IndexOutOfBoundsException.class) public void exeption() { Function<String[], StatisticEntity> f = new CreateStatisticEntity(); f.apply( new String[]{"13", "test", "test", "test", "test", "NULL", "NULL", "0", "NULL"} ); } @Test public void apply() { StatisticEntity expected = new StatisticEntity(); expected.setId(13L); expected.setNameMarker("test"); expected.setJspPageName("test"); expected.setIpAddress("test"); expected.setUserAgent("test"); expected.setClientTime(null); expected.setServerTime(null); expected.setSessionId("0"); expected.setUser(null); expected.setPreviousId(13L); Function<String[], StatisticEntity> f = new CreateStatisticEntity(); StatisticEntity entity = f.apply( new String[]{"13", "test", "test", "test", "test", "NULL", "NULL", "0", "NULL", "13"}); Assert.assertEquals(expected, entity); } }
package customer.gajamove.com.gajamove_customer; import androidx.appcompat.app.AppCompatActivity; import customer.gajamove.com.gajamove_customer.adapter.AdditionalPriceServicesAdapter; import customer.gajamove.com.gajamove_customer.adapter.BigSidePointAdapter; import customer.gajamove.com.gajamove_customer.adapter.MultiLocationAdapter; import customer.gajamove.com.gajamove_customer.adapter.StopInfoAdapter; import customer.gajamove.com.gajamove_customer.auth.CreatePassword; import customer.gajamove.com.gajamove_customer.models.BumbleRideInformation; import customer.gajamove.com.gajamove_customer.models.FireBaseChatHead; import customer.gajamove.com.gajamove_customer.models.MyOrder; import customer.gajamove.com.gajamove_customer.models.Prediction; import customer.gajamove.com.gajamove_customer.utils.Constants; import customer.gajamove.com.gajamove_customer.utils.RideDirectionPointsDB; import customer.gajamove.com.gajamove_customer.utils.UtilsManager; import cz.msebera.android.httpclient.Header; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import com.google.firebase.database.FirebaseDatabase; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.squareup.picasso.Picasso; import org.json.JSONObject; import java.util.ArrayList; public class OrderDetailScreen extends BaseActivity { MyOrder myOrder = null; TextView total_cost,cust_name,base_price,total_km,extra_km_lbl,pick_header,main_service_name,pick_location,dest_header,dest_location; ImageView cust_image; private void setupToolBar(){ ImageView back = findViewById(R.id.backBtn); back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); TextView title = findViewById(R.id.title); title.setVisibility(View.VISIBLE); title.setText(getResources().getString(R.string.order_details)); } LinearLayout back_btn; ListView services_listview,stop_list,side_point_list; AdditionalPriceServicesAdapter additionalPriceServicesAdapter; Button cancel_btn; AlertDialog alertDialog; LinearLayout driver_lay; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_order_detail_screen); myOrder = (MyOrder) getIntent().getSerializableExtra("order"); setupToolBar(); Constants.enableSSL(asyncHttp); total_cost = findViewById(R.id.total_cost); total_km = findViewById(R.id.total_km); pick_header = findViewById(R.id.pickup_header_text); pick_location = findViewById(R.id.pickup_location_txt); dest_header = findViewById(R.id.destination_header_text); dest_location = findViewById(R.id.destination_location_txt); extra_km_lbl = findViewById(R.id.extra_km_label); base_price = findViewById(R.id.base_price); main_service_name = findViewById(R.id.main_service_name); services_listview = findViewById(R.id.services_list_view); stop_list = findViewById(R.id.stop_list); side_point_list = findViewById(R.id.side_point_list); cancel_btn = findViewById(R.id.cancel_order_btn); driver_lay = findViewById(R.id.driver_lay); driver_lay.setVisibility(View.VISIBLE); if (myOrder.isIs_assigned()){ driver_lay.setVisibility(View.VISIBLE); ((TextView) driver_lay.getChildAt(1)).setText(myOrder.getDriver_name()); Picasso.with(this).load(Constants.SERVICE_IMAGE_BASE_PATH+myOrder.getDriver_image()).into(((ImageView) driver_lay.getChildAt(0))); }else { driver_lay.setVisibility(View.GONE); } cancel_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { alertDialog = new AlertDialog.Builder(OrderDetailScreen.this) .setTitle("Cancel Job") .setMessage("Are you sure you want to cancel job?") // Specifying a listener allows you to take an action before dismissing the dialog. // The dialog is automatically dismissed when a dialog button is clicked. .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Continue with delete operation CancelOrderApi(myOrder.getOrder_id()); alertDialog.dismiss(); } }) // A null listener allows the button to dismiss the dialog and take no further action. .setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { alertDialog.dismiss(); } }) .show(); } }); try { if (myOrder.getAdditional_services().equalsIgnoreCase("")){ services_listview.setVisibility(View.GONE); }else { additionalPriceServicesAdapter = new AdditionalPriceServicesAdapter(myOrder.getAdditional_services().split(","), myOrder.getAdditional_prices().split(","), this); services_listview.setAdapter(additionalPriceServicesAdapter); UtilsManager.updateListHeight(this, 30, services_listview, myOrder.getAdditional_services().split(",").length); // UtilsManager.setListViewHeightBasedOnChildren(services_listview); } } catch (Exception e){ e.printStackTrace(); services_listview.setVisibility(View.GONE); } total_cost.setText("RM"+myOrder.getOrder_total()); total_km.setText(myOrder.getTotal_distance()+"KM"); pick_location.setText(myOrder.getPick_location()); dest_location.setText(myOrder.getDest_location()); main_service_name.setText(myOrder.getMain_service_name()); base_price.setText("RM"+myOrder.getBasic_price()); String[] pick_header_arr = myOrder.getPick_location().split("\\s+"); String[] dest_header_arr = myOrder.getDest_location().split("\\s+"); pick_header.setText((pick_header_arr[0] + " " + pick_header_arr[1]).replaceAll(",","")); dest_header.setText((dest_header_arr[0] + " " + dest_header_arr[1]).replaceAll(",","")); ArrayList<Prediction> predictions = new ArrayList<>(); String[] header; Prediction prediction; if (myOrder.getPredictionArrayList()!=null){ for (int i=0;i<myOrder.getPredictionArrayList().size();i++){ prediction = new Prediction(); header = myOrder.getPredictionArrayList().get(i).getLocation_name().split("\\s+"); prediction.setLocation_title(header[0]+" "+header[1].replaceAll(",","")); prediction.setLocation_name(myOrder.getPredictionArrayList().get(i).getLocation_name()); prediction.setAddress(myOrder.getPredictionArrayList().get(i).getAddress()); prediction.setContact(myOrder.getPredictionArrayList().get(i).getContact()); predictions.add(prediction); } } MultiLocationAdapter stopInfoAdapter = new MultiLocationAdapter(predictions,this); stop_list.setAdapter(stopInfoAdapter); UtilsManager.setListViewHeightBasedOnItems(stop_list); //UtilsManager.updateListHeight(this,60,stop_list,predictions.size()); /*BigSidePointAdapter sidePointAdapter = new BigSidePointAdapter(predictions.size(), this); side_point_list.setAdapter(sidePointAdapter); UtilsManager.updateListHeight(this,55,side_point_list,predictions.size()); */ if (myOrder.isIs_assigned() && UtilsManager.isCancelable(myOrder.getOrder_date())){ cancel_btn.setVisibility(View.VISIBLE); }else if (!myOrder.isIs_assigned()){ cancel_btn.setVisibility(View.VISIBLE); }else if (myOrder.isIs_assigned() && !UtilsManager.isCancelable(myOrder.getOrder_date())){ cancel_btn.setVisibility(View.GONE); } } AsyncHttpClient asyncHttp = new AsyncHttpClient(); private void CancelOrderApi(String order_number) { asyncHttp.setConnectTimeout(20000); Log.e("CANCEL_CURRENT_JOB", Constants.Host_Address + "orders/cancel_current_order/"+UtilsManager.getApiKey(OrderDetailScreen.this)+"/" + order_number); asyncHttp.get(OrderDetailScreen.this, Constants.Host_Address + "orders/cancel_current_order/"+UtilsManager.getApiKey(OrderDetailScreen.this)+"/" + order_number, new AsyncHttpResponseHandler() { @Override public void onStart() { super.onStart(); showDialog("Cancelling Ride"); } @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { try { hideLoader(); finish(); } catch (Exception e) { e.printStackTrace(); } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { try { hideLoader(); String response = new String(responseBody); Log.e("failure response",response); UtilsManager.showAlertMessage(OrderDetailScreen.this,"","Could not cancel order."); } catch (Exception e) { e.printStackTrace(); } } }); } private ProgressDialog progress; private void showDialog(String message) { progress = new ProgressDialog(OrderDetailScreen.this); progress.setCanceledOnTouchOutside(false); progress.setMessage(message); progress.show(); } private void hideLoader() { if (progress!=null) if (progress.isShowing()) progress.dismiss(); } }
/* Дано вещественное число A и целое число N (> 0). Используя один цикл, найти значение выражения 1 - A + A2 - A3 + ... + (-1)^N*A^N. Условный оператор не использовать. Для реализации использовать функции. */ public class Ex_32_func { public static double lineSum(double A, int N){ double line = 1d; int plusMinus = -1; int bufMark = -1; double sum = 1d; System.out.print("A = " + A + ", N = " + N + ". \nLine: " + line + " "); for(int i = 0; i < N; i++){ line *= ((double)A)*bufMark; bufMark *= plusMinus; sum += line; System.out.print(line + " "); } return sum; } public static boolean cond(int N, double A){ boolean cond = false; if (N < 0){ System.err.println("One of entered digits doesn't satisfy condition. Second digit must be positive!"); cond = true; return cond; } if (A == 0){ System.out.print("A = " + A + ", N = " + N + ". \nLine: 1.0 "); for(int i = 0; i < N; i++) System.out.print(A*A +" "); System.out.println("\b.\nSum of this line would be 1."); cond = true; } return cond; } public static boolean generalCond(String[] args, int conditionLength){ boolean cond = false; if (args.length < conditionLength) { System.err.println("You haven't entered arguments! The task requires entering two arguments."); cond = true; } if (args.length > conditionLength) System.out.println("You entered more arguments, than programm needs. \nIt will use only first two."); return cond; } public static void main(String[] args) { if(generalCond(args,2)) return; Double A = Double.parseDouble(args[0]); Integer N = Integer.parseInt(args[1]); if (cond(N,A)) return; System.out.println("\b.\nSum of this line would be: " + lineSum(A,N)); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.net.examples.cidr; import java.util.Arrays; import java.util.Scanner; import org.apache.commons.net.util.SubnetUtils; import org.apache.commons.net.util.SubnetUtils.SubnetInfo; /** * Example class that shows how to use the {@link SubnetUtils} class. */ public class SubnetUtilsExample { public static void main(final String[] args) { final String subnet = "192.168.0.3/31"; final SubnetUtils utils = new SubnetUtils(subnet); final SubnetInfo info = utils.getInfo(); System.out.printf("Subnet Information for %s:%n", subnet); System.out.println("--------------------------------------"); System.out.printf("IP Address:\t\t\t%s\t[%s]%n", info.getAddress(), Integer.toBinaryString(info.asInteger(info.getAddress()))); System.out.printf("Netmask:\t\t\t%s\t[%s]%n", info.getNetmask(), Integer.toBinaryString(info.asInteger(info.getNetmask()))); System.out.printf("CIDR Representation:\t\t%s%n%n", info.getCidrSignature()); System.out.printf("Supplied IP Address:\t\t%s%n%n", info.getAddress()); System.out.printf("Network Address:\t\t%s\t[%s]%n", info.getNetworkAddress(), Integer.toBinaryString(info.asInteger(info.getNetworkAddress()))); System.out.printf("Broadcast Address:\t\t%s\t[%s]%n", info.getBroadcastAddress(), Integer.toBinaryString(info.asInteger(info.getBroadcastAddress()))); System.out.printf("Low Address:\t\t\t%s\t[%s]%n", info.getLowAddress(), Integer.toBinaryString(info.asInteger(info.getLowAddress()))); System.out.printf("High Address:\t\t\t%s\t[%s]%n", info.getHighAddress(), Integer.toBinaryString(info.asInteger(info.getHighAddress()))); System.out.printf("Total usable addresses: \t%d%n", Long.valueOf(info.getAddressCountLong())); System.out.printf("Address List: %s%n%n", Arrays.toString(info.getAllAddresses())); final String prompt = "Enter an IP address (e.g. 192.168.0.10):"; System.out.println(prompt); try (final Scanner scanner = new Scanner(System.in)) { while (scanner.hasNextLine()) { final String address = scanner.nextLine(); System.out.println("The IP address [" + address + "] is " + (info.isInRange(address) ? "" : "not ") + "within the subnet [" + subnet + "]"); System.out.println(prompt); } } } }
package com.vilio.nlbs.todo.service.impl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.vilio.nlbs.commonMapper.dao.NlbsLoginInfoMapper; import com.vilio.nlbs.commonMapper.dao.NlbsPendingUserDistributorMapper; import com.vilio.nlbs.commonMapper.dao.NlbsTodoMapper; import com.vilio.nlbs.commonMapper.pojo.NlbsLoginInfo; import com.vilio.nlbs.todo.service.NlbsTODOService; import com.vilio.nlbs.util.Constants; import com.vilio.nlbs.util.Fields; import com.vilio.nlbs.util.ReturnCode; import org.apache.commons.collections.map.HashedMap; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by dell on 2017/6/20/0020. */ @Service public class NlbsTODOServiceImpl implements NlbsTODOService { @Resource NlbsPendingUserDistributorMapper nlbsPendingUserDistributorMapper; @Resource NlbsTodoMapper nlbsTodoMapper; @Resource NlbsLoginInfoMapper nlbsLoginInfoMapper; /** * 根据配置,查找待处理人列表,并生成待办任务 * @param serialNo * @param userNo * @param address * @return * @throws Exception */ @Override public int insertTodoTask(String serialNo, String userNo, String address) throws Exception { if(StringUtils.isBlank(userNo)){ return 0; } List<Map<String, Object>> userList = new ArrayList<>(); NlbsLoginInfo nlbsLoginInfo = nlbsLoginInfoMapper.queryNlbsUserByUserNo(userNo); if(nlbsLoginInfo != null){ userList = nlbsPendingUserDistributorMapper.getUserListByDistributorCode(nlbsLoginInfo.getDistributorCode()); } if(userList != null && userList.size() > 0){ Map paramMap = new HashMap(); paramMap.put(Fields.PARAM_SERIAL_NO, serialNo); paramMap.put(Fields.PARAM_CONTENT, "房产“" + address + "”待评估"); paramMap.put(Fields.PARAM_TODO_TYPE, Constants.TODO_TYPE_TOINQUIRY); paramMap.put(Fields.PARAM_USER_LIST, userList); return nlbsTodoMapper.getInsertPrmMap(paramMap); } return 0; } /** * 删除待办任务 * @param serialNo * @param userNo * @param isExcept 是否是删除除userNo以外的用户的任务 * @return */ @Override public int deleteTask(String serialNo, String userNo, boolean isExcept) throws Exception { Map paramMap = new HashMap(); if(isExcept){ paramMap.put(Fields.PARAM_EXCEPT_USER_NO, userNo); } else { paramMap.put(Fields.PARAM_USER_NO, userNo); } paramMap.put(Fields.PARAM_SERIAL_NO, serialNo); return nlbsTodoMapper.deleteTask(paramMap); } /** * 待办任务列表初始化 * @return * @throws Exception */ @Override public Map initTodoTaskList() throws Exception { Map returnMap = new HashMap(); List<Map<String, Object>> todoTypeList = nlbsTodoMapper.getTodoType(); returnMap.put(Fields.PARAM_TODO_TASK_LIST, todoTypeList == null ? new ArrayList<Map<String, Object>>() : todoTypeList); returnMap.put(Fields.PARAM_MESSAGE_ERR_CODE, ReturnCode.SUCCESS_CODE); returnMap.put(Fields.PARAM_MESSAGE_ERR_MESG, "获取待办任务类型成功!"); return returnMap; } /** * 获取待办任务列表 * @param paramMap * @return * @throws Exception */ @Override public Map getTodoTaskList(Map paramMap) throws Exception { Map returnMap = new HashMap(); List<Map> todoTaskList = new ArrayList<Map>(); Integer pageNo = null != paramMap.get(Fields.PARAM_PAGE_NO) ? new Integer(paramMap.get(Fields.PARAM_PAGE_NO).toString()) : 1; Integer pageSize = null != paramMap.get(Fields.PARAM_PAGE_SIZE) ? new Integer(paramMap.get(Fields.PARAM_PAGE_SIZE).toString()) : 10; //Step 1 获取分页查询结果 PageHelper.startPage(pageNo, pageSize); todoTaskList = nlbsTodoMapper.getTodoListWithSelective(paramMap); PageInfo pageInfo = new PageInfo(todoTaskList); returnMap.put(Fields.PARAM_TODO_TASK_LIST,todoTaskList); returnMap.put(Fields.PARAM_PAGES,pageInfo.getPages()); returnMap.put(Fields.PARAM_TOTAL,pageInfo.getTotal()); returnMap.put(Fields.PARAM_CURRENT_PAGE,pageInfo.getPageNum()); returnMap.put(Fields.PARAM_MESSAGE_ERR_CODE, ReturnCode.SUCCESS_CODE); returnMap.put(Fields.PARAM_MESSAGE_ERR_MESG, "获取待办任务列表成功!"); return returnMap; } }
package com.prudential.car.controller.bean; import java.util.Date; public class RentalCarRequest { private long carId; private String rentalCode; private Date startRentalDate; private Date endRenttalDate; public long getCarId() { return carId; } public void setCarId(long carId) { this.carId = carId; } public String getRentalCode() { return rentalCode; } public void setRentalCode(String rentalCode) { this.rentalCode = rentalCode; } public Date getStartRentalDate() { return startRentalDate; } public void setStartRentalDate(Date startRentalDate) { this.startRentalDate = startRentalDate; } public Date getEndRenttalDate() { return endRenttalDate; } public void setEndRenttalDate(Date endRenttalDate) { this.endRenttalDate = endRenttalDate; } }
package com.hxzy.service.impl; import com.hxzy.entity.JobtableViews; import com.hxzy.mapper.JobtableViewsMapper; import com.hxzy.service.JobtableViewsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class JobtableViewsServiceImpl implements JobtableViewsService { @Autowired private JobtableViewsMapper jobtableViewsMapper; @Override public boolean deleteByPrimaryKey(Integer jobTableId) { return this.jobtableViewsMapper.deleteByPrimaryKey(jobTableId)>0; } @Override public boolean insert(JobtableViews record) { return this.jobtableViewsMapper.insert(record)>0; } @Transactional(propagation = Propagation.SUPPORTS) @Override public JobtableViews selectByPrimaryKey(Integer jobTableId) { return this.jobtableViewsMapper.selectByPrimaryKey(jobTableId); } @Override public boolean updateByPrimaryKeySelective(JobtableViews record) { return this.jobtableViewsMapper.updateByPrimaryKeySelective(record)>0; } @Override public boolean updateByPrimaryKey(JobtableViews record) { return this.jobtableViewsMapper.updateByPrimaryKey(record)>0; } }
package com.ibeiliao.trade.impl.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import com.ibeiliao.pay.datasource.MyBatisDao; import com.ibeiliao.trade.impl.entity.OrderLogPO; /** * t_order_log 表的操作接口 * * @author linyi 2016-07-12 */ @MyBatisDao public interface OrderLogDao { /** * 保存数据 * * @param po 要保存的对象 */ void insert(OrderLogPO po); /** * 修改数据,以主键更新 * * @param po - 要更新的数据 * @return 更新的行数 */ int update(OrderLogPO po); /** * 根据主键读取记录 */ OrderLogPO get(@Param("logId") long logId); }
/** * The Location class is used create a location object which has an xCoord and yCoord to determine position. * * @author Administrator * */ public class Location { private int xCoord; private int yCoord; /** * This is an empty Location constructor that initializes the xCoord and yCoord to 0. */ public Location() { xCoord=0; yCoord=0; } /** * This is the desired Location constructor. * @param xCoord Determines the position in the x-plane (West or East). * @param yCoord Determines the position in the y-plane (North or South). */ public Location(int xCoord, int yCoord) { InvalidCoordinateException coordProblem = new InvalidCoordinateException("Invalid coordinates used. Try positive values."); //InvalidCoordinateException is thrown if xCoord and yCoord are less than 0. if (xCoord > -1 && yCoord > -1) { this.xCoord=xCoord; this.yCoord=yCoord; } else if (xCoord < 0 || yCoord < 0) { throw coordProblem; } } /** * This method is used to update the coordinates of the location. * @param xCoord Determines the position in the x-plane (West or East). * @param yCoord Determines the position in the y-plane (North or South). */ public void update(int xCoord, int yCoord) { InvalidCoordinateException coordProblem = new InvalidCoordinateException("Invalid coordinates used. Try positive values."); //InvalidCoordinateException is thrown if xCoord and yCoord are less than 0. if (xCoord > -1 && yCoord > -1) { this.xCoord=xCoord; this.yCoord=yCoord; } else if (xCoord < 0 || yCoord < 0) { throw coordProblem; } } /** * This method returns an array with the xCoord and yCoord. * @return Returns coordArray which has xCoord and yCoord as elements. */ public int[] getCoordinates () { int [] coordArray = new int[] {xCoord, yCoord}; return coordArray; } }
package com.example.ahmed.octopusmart.Model.ServiceModels.Home; import java.io.Serializable; /** * Created by sotra on 12/19/2017. */ public class HomeBase implements Serializable { String display_model_tybe ; public String getDisplay_model_tybe() { return display_model_tybe; } public void setDisplay_model_tybe(String display_model_tybe) { this.display_model_tybe = display_model_tybe; } public boolean isCat(){ return display_model_tybe.equals("category"); } public boolean isArrivals(){ return display_model_tybe.equals("new_arraivals"); } public boolean isPopular(){ return display_model_tybe.equals("popular"); } public boolean isSlider(){ return display_model_tybe.equals("slider"); } public boolean isLoading(){ return display_model_tybe.equals("loading"); } }
/* * 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 dao; import common.AccessBdd; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import model.CrenelModel; /** * * @author bynan */ public class CrenelDao { public List<CrenelModel> crenels() throws SQLException{ CrenelModel crenelModel = null; List crenelsOf = new ArrayList(); String sql = "SELECT * FROM crenels"; AccessBdd accessBdd = new AccessBdd(); accessBdd.loadDriver(); var rs = accessBdd.executeSelect(sql); while(rs.next()){ String libel = rs.getString("libel"); int id = Integer.parseInt(rs.getString("id")); crenelModel = new CrenelModel(id,libel); crenelsOf.add(crenelModel); } return crenelsOf; } public CrenelModel selectById(int idParam) throws SQLException{ CrenelModel crenModel = null; String sql = "SELECT * FROM crenels WHERE id = "+idParam; AccessBdd accessBdd = new AccessBdd(); accessBdd.loadDriver(); var rs = accessBdd.executeSelect(sql); while(rs.next()){ int id = rs.getInt("id"); String libel = rs.getString("libel"); crenModel = new CrenelModel(id, libel); } return crenModel; } }
package com.jim.multipos.ui.consignment.view; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SimpleItemAnimator; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; import com.jim.mpviews.MpEditText; import com.jim.multipos.R; import com.jim.multipos.core.BaseFragment; import com.jim.multipos.data.DatabaseManager; import com.jim.multipos.data.db.model.inventory.OutcomeProduct; import com.jim.multipos.data.db.model.products.Product; import com.jim.multipos.data.db.model.products.Vendor; import com.jim.multipos.ui.consignment.adapter.ReturnItemsListAdapter; import com.jim.multipos.ui.consignment.dialogs.ProductsForIncomeDialog; import com.jim.multipos.ui.consignment.dialogs.StockPositionsDialog; import com.jim.multipos.ui.consignment.presenter.ReturnConsignmentPresenter; import com.jim.multipos.utils.BarcodeStack; import com.jim.multipos.utils.RxBus; import com.jim.multipos.utils.WarningDialog; import com.jim.multipos.utils.rxevents.inventory_events.BillingOperationEvent; import com.jim.multipos.utils.rxevents.inventory_events.ConsignmentWithVendorEvent; import com.jim.multipos.utils.rxevents.inventory_events.InventoryStateEvent; import com.jim.multipos.utils.rxevents.main_order_events.GlobalEventConstants; import java.text.DecimalFormat; import java.util.List; import javax.inject.Inject; import butterknife.BindView; import butterknife.OnClick; import eu.inmite.android.lib.validations.form.annotations.NotEmpty; import static com.jim.multipos.ui.consignment.ConsignmentActivity.PRODUCT_ID; import static com.jim.multipos.ui.consignment.ConsignmentActivity.STOCK_QUEUE_ID; import static com.jim.multipos.ui.consignment.ConsignmentActivity.VENDOR_ID; /** * Created by Sirojiddin on 24.11.2017. */ public class ReturnConsignmentFragment extends BaseFragment implements ReturnConsignmentView { @Inject ReturnConsignmentPresenter presenter; @Inject DecimalFormat decimalFormat; @Inject RxBus rxBus; @Inject BarcodeStack barcodeStack; @Inject ReturnItemsListAdapter adapter; @Inject DatabaseManager databaseManager; @BindView(R.id.rvReturnProducts) RecyclerView rvReturnProducts; @NotEmpty(messageId = R.string.consignment_number_is_empty) @BindView(R.id.etReturnNumber) MpEditText etReturnNumber; @BindView(R.id.etReturnDescription) EditText etReturnDescription; @BindView(R.id.tvTotalReturnSum) TextView tvTotalReturnSum; @BindView(R.id.tvVendorName) TextView tvVendorName; @BindView(R.id.tvCurrencyAbbr) TextView tvCurrencyAbbr; @BindView(R.id.ivBarcodeScanner) ImageView ivBarcodeScanner; private ProductsForIncomeDialog dialog; private boolean forDialog = false; @Override protected int getLayout() { return R.layout.return_consignment_fragment; } @Override protected void init(Bundle savedInstanceState) { if (getArguments() != null) { Long productId = (Long) getArguments().get(PRODUCT_ID); Long vendorId = (Long) getArguments().get(VENDOR_ID); Long stockQueueId = (Long) getArguments().get(STOCK_QUEUE_ID); presenter.setData(productId, vendorId, stockQueueId); } rvReturnProducts.setLayoutManager(new LinearLayoutManager(getContext())); rvReturnProducts.setAdapter(adapter); ((SimpleItemAnimator) rvReturnProducts.getItemAnimator()).setSupportsChangeAnimations(false); adapter.setListener(new ReturnItemsListAdapter.OnOutComeItemSelectListener() { @Override public void onSumChanged() { presenter.calculateConsignmentSum(); } @Override public void onDelete(int position) { WarningDialog warningDialog = new WarningDialog(getContext()); warningDialog.setWarningMessage(getContext().getString(R.string.do_you_want_delete)); warningDialog.setOnYesClickListener(view1 -> { presenter.deleteFromList(position); adapter.notifyDataSetChanged(); warningDialog.dismiss(); }); warningDialog.setOnNoClickListener(view -> warningDialog.dismiss()); warningDialog.show(); } @Override public void onCustomStock(OutcomeProduct outcomeProduct, int position) { presenter.openCustomStockPositionsDialog(outcomeProduct, position); } }); barcodeStack.register(barcode -> { if (isAdded() && isVisible()) presenter.onBarcodeScanned(barcode); }); ivBarcodeScanner.setOnClickListener(v -> initScan()); } @OnClick(R.id.btnBack) public void onBack() { presenter.checkChanges(etReturnNumber.getText().toString(), etReturnDescription.getText().toString()); } @OnClick(R.id.btnAddProductToReturnConsignment) public void onAddProductToReturnConsignment() { presenter.loadVendorProducts(); } @OnClick(R.id.btnAddReturn) public void onAddReturn() { if (isValid()) presenter.saveReturnConsignment(etReturnNumber.getText().toString(), etReturnDescription.getText().toString()); } @Override public void setTotalProductsSum(double sum) { tvTotalReturnSum.setText(decimalFormat.format(sum)); } @Override public void fillDialogItems(List<Product> productList, List<Product> vendorProducts) { dialog = new ProductsForIncomeDialog(getContext(), productList, vendorProducts, barcodeStack, databaseManager); dialog.setListener(new ProductsForIncomeDialog.OnSelectClickListener() { @Override public void onSelect(Product product) { presenter.setReturnItem(product); } @Override public void onBarcodeClick() { initScan(); } }); dialog.show(); } private void initScan() { IntentIntegrator.forSupportFragment(this).initiateScan(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); if (intentResult != null) { if (intentResult.getContents() != null) { if (forDialog) { dialog.setBarcode(intentResult.getContents()); } else presenter.onBarcodeScanned(intentResult.getContents()); } } } @Override public void setError(String string) { WarningDialog warningDialog = new WarningDialog(getContext()); warningDialog.onlyText(true); warningDialog.setWarningMessage(getString(R.string.add_product_to_consignment)); warningDialog.setOnYesClickListener(view1 -> warningDialog.dismiss()); warningDialog.show(); } @Override public void setVendorName(String name) { tvVendorName.setText(name); } @Override public void openDiscardDialog() { WarningDialog warningDialog = new WarningDialog(getContext()); warningDialog.setWarningMessage(getString(R.string.warning_discard_changes)); warningDialog.setDialogTitle(getString(R.string.discard_changes)); warningDialog.setOnYesClickListener(view1 -> { warningDialog.dismiss(); getActivity().finish(); }); warningDialog.setOnNoClickListener(view -> warningDialog.dismiss()); warningDialog.show(); } @Override public void closeFragment(Vendor vendor) { rxBus.send(new ConsignmentWithVendorEvent(vendor, GlobalEventConstants.UPDATE)); rxBus.send(new BillingOperationEvent(GlobalEventConstants.BILLING_IS_DONE)); rxBus.send(new InventoryStateEvent(GlobalEventConstants.UPDATE)); getActivity().finish(); } @Override public void setConsignmentNumberError() { etReturnNumber.setError(getString(R.string.consignment_with_such_number_exists)); } @Override public void onDetach() { barcodeStack.unregister(); super.onDetach(); } @Override public void setConsignmentNumber(int number) { etReturnNumber.setText(String.valueOf(number)); } @Override public void setCurrency(String abbr) { tvCurrencyAbbr.setText(abbr); } @Override public void fillReturnList(List<OutcomeProduct> outcomeProduct) { adapter.setItems(outcomeProduct); } @Override public void openCustomStockPositionsDialog(OutcomeProduct outcomeProduct, List<OutcomeProduct> outcomeProductList, List<OutcomeProduct> exceptionList,int position) { StockPositionsDialog dialog = new StockPositionsDialog(getContext(), outcomeProduct, outcomeProductList, exceptionList, databaseManager); dialog.setListener(new StockPositionsDialog.OnStockPositionsChanged() { @Override public void onConfirm(OutcomeProduct outcomeProduct) { presenter.setOutcomeProduct(outcomeProduct); } }); dialog.show(); } @Override public void updateChangedPosition(int position) { adapter.notifyItemChanged(position); } @Override public void closeFragment() { Toast.makeText(getContext(), getString(R.string.vendor_is_not_active), Toast.LENGTH_SHORT).show(); getActivity().finish(); } }
package com.te.HibernateAssignment; import java.util.Scanner; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import com.te.HibernateAssignment.bean.Employee; public class MainEmploye { public static void main(String[] args) { EmployeeData data = new EmployeeData(); Scanner scanner = new Scanner(System.in); for(;;) { System.out.println("For All Data=1 / Perticular Data=2 / update=3 / Delete=4 / Exit=5"); int no = scanner.nextInt(); if (no == 1) { data.allData(); } else if (no == 2) { data.readData(); } else if (no == 3) { data.upData(); } else if (no == 4) { data.delData(); } else if (no == 5) { break; } } } }
package com.takshine.wxcrm.message.sugar; import java.util.ArrayList; import java.util.List; /** * 查询产品类别接口 从crm响应回来的参数 * * @author huangpeng * */ public class ProductTypeResp extends BaseCrm { private String count = null;// 数字 private String currpage = "1";// 当前页 private String pagecount = "5";// 每页的条数 private List<ProductTypeAdd> porductTypes = new ArrayList<ProductTypeAdd>();// 产品列表 public String getCount() { return count; } public void setCount(String count) { this.count = count; } public String getCurrpage() { return currpage; } public void setCurrpage(String currpage) { this.currpage = currpage; } public String getPagecount() { return pagecount; } public void setPagecount(String pagecount) { this.pagecount = pagecount; } public List<ProductTypeAdd> getPorductTypes() { return porductTypes; } public void setPorductTypes(List<ProductTypeAdd> porductTypes) { this.porductTypes = porductTypes; } }
package sickbook.ui.dashboard; import android.app.AlertDialog; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.provider.MediaStore; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.widget.AppCompatImageView; import androidx.fragment.app.Fragment; import com.comp.sickbook.AppContext; import com.comp.sickbook.Background.Group; import com.comp.sickbook.Background.Person; import com.comp.sickbook.Background.SendMail; import com.comp.sickbook.R; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FieldValue; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.installations.FirebaseInstallations; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import java.io.ByteArrayOutputStream; import java.util.ArrayList; /** * Class for the fragment which houses the groups section * Used to manage the UI and logic of that fragment */ public class DashboardFragment extends Fragment { DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference(); FirebaseFirestore db = FirebaseFirestore.getInstance(); String gString; String userID; int numGroups; View root; private Uri mImageUri = null; LinearLayout list; private AlertDialog.Builder dialogBuilder; private AlertDialog dialog; private EditText groupName; private EditText groupPassword; private Button closeDialog, createGroup; Handler handler = new Handler(); Runnable runnable; String meetUpGroup; /** * On the creation of this page it will load the previous savedInstanceState * @param savedInstanceState : the saved instance from previous use */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } /** *Called when the View is created * Fills the view with the fragment_dashboard.xml layout * Binds views from layout to objects * Sets the onClickListeners for the buttons in the layout * @param inflater * @param container : the container of which this view was created * @param savedInstanceState : the saved instance from previous use * @return : returns the root view */ public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { root = inflater.inflate(R.layout.fragment_dashboard, container, false); list = root.findViewById(R.id.group_list); makeGroupList(); AppCompatImageView AddButton = root.findViewById(R.id.makeButton); AddButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { createNewGroupUI(); } }); AppCompatImageView NotifyButton = root.findViewById(R.id.alertButton); NotifyButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { makeNotifyGroupPopup(); } }); return root; } /** * Creates the popup for the notify groups UI * Attaches each button and textview to a corresponding object * It will go through every group the user is in and create a list of toggleable views * User must input a name for the sickness they are reporting * At the end when the user selects the groups to notify then it will add those groups to pickGroups which will be passed to the notifyGroups method * This is the self report feature */ public void makeNotifyGroupPopup() { dialogBuilder = new AlertDialog.Builder(getContext()); final View notifyPopup = getLayoutInflater().inflate(R.layout.alert_group_popup, null); // Inflates the alert_group_popup.xml file into a view LinearLayout notifyList = notifyPopup.findViewById(R.id.groupNotifyList); // Makes the LinearLayout in the layout file an object ArrayList < String > pickGroups = new ArrayList < > (); dialogBuilder.setView(notifyPopup); // sets the view for the dialog builder to the popup view dialog = dialogBuilder.create(); //creates the dialog object dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); EditText text = notifyPopup.findViewById(R.id.sickText); // The user enters the sickness name into this Button cancelNotify = (Button) notifyPopup.findViewById(R.id.cancelNotifyButton); cancelNotify.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); //dismisses the popup when clicked } }); Button notifyButton = notifyPopup.findViewById(R.id.notifyButton); notifyButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!text.getText().toString().equals("") && !pickGroups.isEmpty()) { //makes sure sickness name has correct syntax notifyGroups(pickGroups, text.getText().toString()); // notifies the groups in pickGroups when clicked dialog.dismiss(); } } }); FirebaseInstallations.getInstance().getId() // attempt to get unique firebase user ID .addOnCompleteListener(new OnCompleteListener < String > () { @Override public void onComplete(@NonNull Task < String > task) { if (task.isSuccessful()) { userID = task.getResult(); // sets the firebase ID to userID. Firebase ID used to identify user DatabaseReference userRef = rootRef.child("people").child(userID); ValueEventListener eventListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // runs when data in reference changes if (dataSnapshot.child("numGroups").getValue() == null) { userRef.child("numGroups").setValue(0); //Gives reference a value so not null } if (dataSnapshot.child("groupString").getValue() == null) { userRef.child("groupString").setValue(""); //Gives reference a value so not null } gString = dataSnapshot.child("groupString").getValue(String.class); if (gString == null) gString = "";//Gives reference a value so not null if (dataSnapshot.child("numGroups").getValue() != null) numGroups = dataSnapshot.child("numGroups").getValue(Integer.class); int base = 0; for (int x = 0; x < numGroups; x++) { // goes through each group that that user is in View view = LayoutInflater.from(AppContext.getAppContext()).inflate(R.layout.notify_group_temp, null); // inflates a smaller view into the popup (It goes in the linearlayout) //links UI elements to their objects TextView textTest = view.findViewById(R.id.notify_group_name); LinearLayout layout = view.findViewById(R.id.group); final Boolean[] isButtonClicked = { false }; int i = gString.indexOf(",", base); String groupName = gString.substring(base, i); base = i + 1; textTest.setText(groupName); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // sets on click listener. When clicked then the group will be "selected" from the list isButtonClicked[0] = !isButtonClicked[0]; // toggle the boolean layout.setBackgroundResource(isButtonClicked[0] ? R.drawable.notify_group_list_bg : R.drawable.notification_border); // changes color when selected if (isButtonClicked[0]) { pickGroups.add(groupName); // adds to pickGroups if selected } else { pickGroups.remove(groupName); } } }); notifyList.addView(view); // adds the group to the list } } @Override public void onCancelled(DatabaseError databaseError) {} }; userRef.addListenerForSingleValueEvent(eventListener); // adds the listener created earlier } else { Log.e("Installations", "Unable to get Installation ID"); } dialog.show(); // displays the dialog (popup) } }); } /** * Goes through each selected group that the user chose and sends an in-app notification * Also sends an email to that user if they are signed in * @param groupArray : array that hold the groups that need to be notified * @param message : the message is the name of the sickness the user chose */ public void notifyGroups(ArrayList < String > groupArray, String message) { for (String groupName: groupArray) { // for each group DocumentReference groupRef = db.collection("groups").document(groupName); groupRef.get().addOnSuccessListener(new OnSuccessListener < DocumentSnapshot > () { @Override public void onSuccess(DocumentSnapshot documentSnapshot) { Group group = documentSnapshot.toObject(Group.class); for (String ID: group.getPeopleID()) { // for each person in that group DocumentReference personRef = db.collection("people").document(ID); if (ID.equals(userID)) { // If the user is the current user using the app (they get a different notification) personRef.update("notifications", FieldValue.arrayUnion("SickBook,Your notification has successfully sent to the group " + group.getName())); } else { personRef.update("notifications", FieldValue.arrayUnion(group.getName() + ",Someone in this group has " + message)); personRef.get().addOnSuccessListener(new OnSuccessListener < DocumentSnapshot > () { @Override public void onSuccess(DocumentSnapshot documentSnapshot) { Person person = documentSnapshot.toObject(Person.class); // gets the person reference from firebase and makes it a usable object sendEmail(person.getEmail(), "SickBook Notification", "Someone in the group " + group.getName() + " has " + message + ". Stay Safe!"); } }); } } } }); } } /** * Creates a SandMail object, which launches an async task * We do not have access to an online server so the mail has to be sent through the users device * @param email : the email of the recipient * @param subject : the subject of the email * @param message : the message of the email */ private void sendEmail(String email, String subject, String message) { SendMail sm = new SendMail(AppContext.getAppContext(), email, subject, message); sm.execute(); //starts async task } /** * Sets up the main list of groups * Each group in the list is its own separate view * Sets on click listeners for the group views * Also sets up the options popup when a group is clicked on */ public void makeGroupList() { FirebaseInstallations.getInstance().getId() // attempt to get unique firebase user ID .addOnCompleteListener(new OnCompleteListener < String > () { @Override public void onComplete(@NonNull Task < String > task) { // process here is very similar to the one in makeNotifyGroupPopup if (task.isSuccessful()) { userID = task.getResult(); //gets firebase ID, unique to user's device DatabaseReference userRef = rootRef.child("people").child(userID); userRef.child("test").setValue("game"); ValueEventListener eventListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.child("numGroups").getValue() == null) { userRef.child("numGroups").setValue(0); //Gives reference a value so not null } if (dataSnapshot.child("groupString").getValue() == null) { userRef.child("groupString").setValue(""); //Gives reference a value so not null } gString = dataSnapshot.child("groupString").getValue(String.class); if (dataSnapshot.child("numGroups").getValue() != null) numGroups = dataSnapshot.child("numGroups").getValue(Integer.class); int base = 0; for (int x = 0; x < numGroups; x++) { // goes through each group the user is in View view = LayoutInflater.from(AppContext.getAppContext()).inflate(R.layout.group_temp, null); //inflates the group_temp layout into a view TextView textTest = view.findViewById(R.id.notify_group_name); // Links UI elements to objects TextView sideNote = view.findViewById(R.id.notif_text); view.setOnClickListener(new View.OnClickListener() { // adds an on click listener for each group view in the list @Override public void onClick(View v) { dialogBuilder = new AlertDialog.Builder(getContext()); //makes a popup when clicked final View optionsPopup = getLayoutInflater().inflate(R.layout.options_popup, null); // inflates the options layout into a view for the popup Button removeButton = optionsPopup.findViewById(R.id.startSurvey); removeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // removes the group from the list and also the firebase String name = textTest.getText().toString(); if (gString.contains(name + ",")) { int i = gString.indexOf(name + ","); gString = gString.substring(0, i) + gString.substring(i + name.length() + 1); numGroups--; userRef.child("groupString").setValue(gString); userRef.child("numGroups").setValue(numGroups); } removeGroup(name); dialog.dismiss(); // closes the group options popup list.removeAllViews(); makeGroupList(); //refresh the list } }); Button meetupButton = optionsPopup.findViewById(R.id.startMeetupButton); meetupButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Starts the meet up for that group (includes a survey and mask check) dialog.dismiss(); // closes the options popup final View meetUpPopup = getLayoutInflater().inflate(R.layout.meetup_popup, null); // inflates the meetup popup into a view Button maskCheck = meetUpPopup.findViewById(R.id.startMeetupButton); maskCheck.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { meetUpGroup = textTest.getText().toString();; Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, 0); // starts the picture taking process, will run onActivityResult when finished } }); dialogBuilder.setView(meetUpPopup); dialog = dialogBuilder.create(); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); dialog.show(); // shows the meet up popup } }); dialogBuilder.setView(optionsPopup); dialog = dialogBuilder.create(); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); dialog.show(); // shows the group options popup } }); int i = gString.indexOf(",", base); String groupNameInView = gString.substring(base, i); base = i + 1; textTest.setText(groupNameInView); DocumentReference docRef = db.collection("groups").document(groupNameInView); docRef.get().addOnSuccessListener(new OnSuccessListener < DocumentSnapshot > () { @Override public void onSuccess(DocumentSnapshot documentSnapshot) { Group group = documentSnapshot.toObject(Group.class); sideNote.setText("Number Of People In Group: " + group.getNumPeople()); // Lets the usder know how many people are in that group } }); list.addView(view); // ats the view to the scrolling view } } @Override public void onCancelled(DatabaseError databaseError) {} }; userRef.addListenerForSingleValueEvent(eventListener); } else { Log.e("Installations", "Unable to get Installation ID"); } } }); } /** * This method is called when the camera application is done taking a photo * The thumbnail of the photo is temporarily uploaded to the firebase * The image is used by external python code to determine if a face is wearing a mask * The result of that code is them passed into the doSurvey method * @param requestCode : needed to know what activity was preformed * @param resultCode : also needed to know what activity way preformed * @param data : the data from the activity, contains the results */ @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); FirebaseStorage storage = FirebaseStorage.getInstance(); StorageReference storageRef = storage.getReferenceFromUrl("gs://sickbook-56291.appspot.com"); StorageReference imageRef = storageRef.child(userID + ".jpg"); //creates a reference to the image file in the firebase if (requestCode == 0 && resultCode == -1) { Bitmap bitmap = (Bitmap) data.getExtras().get("data"); //gets the bitmap of the image from the camera activity ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] bytes = baos.toByteArray(); // converts to a byte array to send to firebase UploadTask uploadTask = imageRef.putBytes(bytes);// creates an upload task to firebase storage uploadTask.addOnSuccessListener(new OnSuccessListener < UploadTask.TaskSnapshot > () { // saves the image to the image reference created earlier @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { imageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener < Uri > () { // gets uri of the image in the firebase @Override public void onSuccess(Uri uri) { DatabaseReference userRef = rootRef.child("people").child(userID); Toast.makeText(AppContext.getAppContext(), "Loading...", Toast.LENGTH_LONG).show(); dialog.dismiss(); // closes the current popup on the screen (the meet up popup) userRef.child("faceimg").setValue(uri + ""); // sets the value of faceimg to the the uri of the image in the firebase storage userRef.child("new").setValue("true"); // the value of "new" in the firebase is used to track if the python code has finished running for that photo userRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { // this will run when a value in the userRef from firebase changes Boolean bool; bool = Boolean.valueOf(snapshot.child("new").getValue(String.class)); if (!bool) { // if the value of "new" changes to false, the python code is done and this code runs handler.post(runnable = new Runnable() { @Override public void run() { final View startSurveyPopup = getLayoutInflater().inflate(R.layout.start_survey_popup, null); //inflates the start survey popup into a view dialogBuilder.setView(startSurveyPopup); dialog = dialogBuilder.create(); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); dialog.show(); // shows the start survey popup Button startSurvey = startSurveyPopup.findViewById(R.id.startSurvey); startSurvey.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); // closes the start survey popup boolean maskResult = Boolean.parseBoolean(snapshot.child("MaskOn").getValue(String.class)); // gets the vlaue of "MaskOn" from the firebase doSurvey(maskResult); } }); } }); userRef.removeEventListener(this); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } }); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { // Handle any errors } }); } } /** * Creates a survey popup that checks if the user is at risk of having a disease * @param maskResult : The result of the photo mask check, used to determine if a meeting is safe or not */ public void doSurvey(boolean maskResult){ final View surveyPopup = getLayoutInflater().inflate(R.layout.survey_popup, null); //inflates layout survey popup into a view dialogBuilder.setView(surveyPopup); dialog = dialogBuilder.create(); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); //sets UI elements into objects CheckBox cough, fever, headache, dryThroat, chestPain, muscleAches, diarrhea, fatigue; Switch question1, question2, question3; Button submit; cough = surveyPopup.findViewById(R.id.checkBox1); fever = surveyPopup.findViewById(R.id.checkBox2); headache = surveyPopup.findViewById(R.id.checkBox3); dryThroat = surveyPopup.findViewById(R.id.checkBox4); chestPain = surveyPopup.findViewById(R.id.checkBox5); muscleAches = surveyPopup.findViewById(R.id.checkBox6); diarrhea = surveyPopup.findViewById(R.id.checkBox7); fatigue = surveyPopup.findViewById(R.id.checkBox8); question1 = surveyPopup.findViewById(R.id.switch1); question2 = surveyPopup.findViewById(R.id.switch2); question3 = surveyPopup.findViewById(R.id.switch3); submit = surveyPopup.findViewById(R.id.button); // Checks if any of the checkboxes and switches are checked. If any are checked, return true. Else, return false. submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // user submits answers to the survey boolean badResult = false; if((cough.isChecked() || fever.isChecked() || headache.isChecked() || dryThroat.isChecked() || chestPain.isChecked() || muscleAches.isChecked() || diarrhea.isChecked() || fatigue.isChecked() || question1.isChecked() || question2.isChecked() || question3.isChecked())) { badResult = true; } if (!maskResult){ badResult = true; } DocumentReference docRef = db.collection("groups").document(meetUpGroup); boolean finalBadResult = badResult; docRef.get().addOnSuccessListener(new OnSuccessListener < DocumentSnapshot > () { @Override public void onSuccess(DocumentSnapshot documentSnapshot) { if (documentSnapshot.exists()) { Group group = documentSnapshot.toObject(Group.class); int numComplete = group.getNumComplete() +1; int numBad =group.getNumBadComplete(); if(finalBadResult){ //runs if the person has no mask or if they show symptoms or are at risk group.setNumBadComplete(group.getNumBadComplete()+1); DocumentReference personRef = db.collection("people").document(userID); personRef.update("notifications", FieldValue.arrayUnion("SickBook,You failed the requirements for this meet up. It is recommended that you do not attend. " ));// adds a notification in-app for that person numBad += 1; //adds one to the number of badResults } if (numComplete >= group.getNumPeople()){ // if everyone in the group has completed the meet up check group.setNumBadComplete(numBad); group.setNumComplete(0); // sets the number of people who completed the check to 0 for the next time it is used numComplete = 0; docRef.set(group); for (String ID: group.getPeopleID()) { // for each person in that group DocumentReference personRef = db.collection("people").document(ID); personRef.update("notifications", FieldValue.arrayUnion(group.getName()+ ",Everyone in this group has completed the meet up requirements. " + numBad + " failed the requirements." ));// adds a notification in-app for that person int finalNumBad = numBad; personRef.get().addOnSuccessListener(new OnSuccessListener < DocumentSnapshot > () { @Override public void onSuccess(DocumentSnapshot documentSnapshot) { Person person = documentSnapshot.toObject(Person.class); // gets the person reference from firebase and makes it a usable object sendEmail(person.getEmail(), "SickBook Notification", "Everyone in the group " + group.getName()+" has completed the meet up requirements. " + finalNumBad + " failed the requirements."); //sends an email to user about the results after everyone in the group completed the meet check } }); } group.setNumBadComplete(0); } else{ for (String ID: group.getPeopleID()) { // for each person in that group DocumentReference personRef = db.collection("people").document(ID); if (!ID.equals(userID)) personRef.update("notifications", FieldValue.arrayUnion(group.getName()+ ",Someone in this group has completed a meet up check. Go to the group page to complete it." )); // adds a notification in-app for that person } } group.setNumComplete(numComplete); docRef.set(group); // updates the group reference in firebase to the current group (changes values) } } }); dialog.dismiss(); // closes the survey popup } }); dialog.show(); // shows the survey popup } /** * Creates the popup for creating or joining a new group * User inputs a name and password * If that group exist and the password is correct then the user joins the group * If the group does not exist then it makes a new group with the entered name and password */ public void createNewGroupUI() { DocumentReference personRef = db.collection("people").document(userID); personRef.get().addOnSuccessListener(new OnSuccessListener < DocumentSnapshot > () { @Override public void onSuccess(DocumentSnapshot documentSnapshot) { if (!documentSnapshot.exists()) { // makes a person reference if one is not there already Person person = new Person(); personRef.set(person); } } }); dialogBuilder = new AlertDialog.Builder(getContext()); final View createPopup = getLayoutInflater().inflate(R.layout.create_popup, null); groupName = (EditText) createPopup.findViewById(R.id.sickText); groupPassword = (EditText) createPopup.findViewById(R.id.groupPassword); closeDialog = (Button) createPopup.findViewById(R.id.cancelCreateButton); createGroup = (Button) createPopup.findViewById(R.id.createButton); dialogBuilder.setView(createPopup); dialog = dialogBuilder.create(); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); dialog.show(); closeDialog.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } // close the create group popup }); createGroup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String name = groupName.getText().toString(); String password = groupPassword.getText().toString(); DocumentReference docRef = db.collection("groups").document(name); docRef.get().addOnSuccessListener(new OnSuccessListener < DocumentSnapshot > () { @Override public void onSuccess(DocumentSnapshot documentSnapshot) { String realPassword = password; if (documentSnapshot.exists()) { Group group = documentSnapshot.toObject(Group.class); group.getPassword(); realPassword = group.getPassword(); } if (!name.equals("") && !name.contains(",") && !gString.contains(name + ",") && password.equals(realPassword)) { //check syntax and password to see if they are correct rootRef.child("people").child(userID).child("groupString").setValue(gString + name + ","); rootRef.child("people/" + userID + "/numGroups").setValue(numGroups + 1); addGroup(name, password); list.removeAllViews(); makeGroupList(); //refresh dialog.dismiss(); //closes the create group popup } else if (!password.equals(realPassword)) { Toast toast = Toast.makeText(AppContext.getAppContext(), "That is not the correct password", Toast.LENGTH_LONG); toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); //tells user if password is correct } } }); } }); } /** * Adds a group to the list in the groups page * Also adds the group to firebase * If the group exists then user will join that group * If the group does not exist then a new group will be made with the passoword given * @param groupName : the name of the group to create/join * @param pass : the password to the created group */ public void addGroup(String groupName, String pass) { DocumentReference docRef = db.collection("groups").document(groupName); docRef.get().addOnSuccessListener(new OnSuccessListener < DocumentSnapshot > () { @Override public void onSuccess(DocumentSnapshot documentSnapshot) { if (documentSnapshot.exists()) { //if group is already made Group group = documentSnapshot.toObject(Group.class); group.addPerson(userID); docRef.set(group); } else { Group group = new Group(groupName, pass); group.addPerson(userID); docRef.set(group); Toast toast = Toast.makeText(AppContext.getAppContext(), "You have made a new group", Toast.LENGTH_LONG); toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); } } }); } /** * removes a group from the list in the groups page * also removes the group from the firebase * If no one is left in the group then it removes the group entirely * @param groupName : the name of the group to remove for that person */ public void removeGroup(String groupName) { DocumentReference docRef = db.collection("groups").document(groupName); docRef.get().addOnSuccessListener(new OnSuccessListener < DocumentSnapshot > () { @Override public void onSuccess(DocumentSnapshot documentSnapshot) { if (documentSnapshot.exists()) { //checks to see if group exists Group group = documentSnapshot.toObject(Group.class); group.removePerson(userID); docRef.set(group); if (group.getNumPeople() <= 0) docRef.delete(); } } }); } }
package com.tinyurl.service; import java.security.NoSuchAlgorithmException; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import com.tinyurl.utils.TinyUrlConverter; import static org.junit.jupiter.api.Assertions.assertEquals; @SpringBootTest public class TinyUrlTest { @Autowired TinyUrlConverter converter; @DisplayName("Test Tiny Url conversion algorithm") @Test void testGet() throws NoSuchAlgorithmException { assertEquals("BRRbYby",converter.convertToBase62Url("www.google.com")); } }
package com.van.web.interceptor; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 日志记录 */ public class LogInterceptor extends HandlerInterceptorAdapter { private final static Logger log = LogManager.getLogger(LogInterceptor.class); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { return true; } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { log.info("开始记录请求日志..."); } }
package gov.virginia.dmas.validation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; @Target({ ElementType.TYPE, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = { IdConditionalValidator.class }) public @interface IdConditional { String message() default "This field is required."; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; String selected(); String verifyCreatedBy(); String verifyUpdatedBy(); @Target({ ElementType.TYPE, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) public @interface List { IdConditional[] value(); } }
/* Copyright 2018 Lucas Antonio Xavier Silva 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.example.lucas.prototipo; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.util.Log; import com.example.lucas.prototipo.histogram.Globals; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private SectionsPageAdapter mSectionsPageAdapter; private ViewPager mViewPager; Globals g = Globals.getInstance(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d(TAG, "onCreate: Starting."); mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager()); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.container); setupViewPager(mViewPager); TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(mViewPager); //getSupportActionBar().hide(); } private void setupViewPager(ViewPager viewPager) { SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager()); adapter.addFragment(new Tab1Fragment(), "TAB1"); adapter.addFragment(new Tab2Fragment(), "TAB2"); adapter.addFragment(new Tab3Fragment(), "TAB3"); viewPager.setAdapter(adapter); } }
package corgi.hub.core.mqtt.bean; /** * Created by Terry LIANG on 2017/1/15. */ public class NotifyEvent { private long storeMsgId; private long createTime; private int nodeNumberStart; private int nodeNumberEnd; public long getStoreMsgId() { return storeMsgId; } public void setStoreMsgId(long storeMsgId) { this.storeMsgId = storeMsgId; } public long getCreateTime() { return createTime; } public void setCreateTime(long createTime) { this.createTime = createTime; } public int getNodeNumberStart() { return nodeNumberStart; } public void setNodeNumberStart(int nodeNumberStart) { this.nodeNumberStart = nodeNumberStart; } public int getNodeNumberEnd() { return nodeNumberEnd; } public void setNodeNumberEnd(int nodeNumberEnd) { this.nodeNumberEnd = nodeNumberEnd; } }
package com.cg.javafillstack.collection.set; import java.util.TreeSet; public class TreeSetEx { public static void main(String[] args) { TreeSet ts=new TreeSet(); ts.add(89); ts.add(98); ts.add(12); ts.add(2); for(Object o:ts) { System.out.println(o); } } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.commerceservices.order.impl; import de.hybris.platform.commerceservices.order.CommerceCartMergingException; import de.hybris.platform.commerceservices.order.CommerceCartModification; import de.hybris.platform.commerceservices.order.CommerceCartModificationException; import de.hybris.platform.commerceservices.order.CommerceCartModificationStatus; import de.hybris.platform.commerceservices.order.strategies.EntryMergeStrategy; import de.hybris.platform.commerceservices.service.data.CommerceCartParameter; import de.hybris.platform.core.model.order.AbstractOrderEntryModel; import de.hybris.platform.core.model.order.AbstractOrderModel; import de.hybris.platform.core.model.order.CartEntryModel; import de.hybris.platform.core.model.order.CartModel; import de.hybris.platform.core.model.product.ProductModel; import de.hybris.platform.core.model.product.UnitModel; import de.hybris.platform.servicelayer.exceptions.ModelNotFoundException; import de.hybris.platform.servicelayer.exceptions.UnknownIdentifierException; import de.hybris.platform.servicelayer.util.ServicesUtil; import de.hybris.platform.storelocator.model.PointOfServiceModel; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import javax.annotation.Nonnull; import org.fest.util.Collections; import org.springframework.beans.factory.annotation.Required; public class DefaultCommerceAddToCartStrategy extends AbstractCommerceAddToCartStrategy { private EntryMergeStrategy entryMergeStrategy; @Override public List<CommerceCartModification> addToCart(final List<CommerceCartParameter> parameterList) throws CommerceCartMergingException { final List<CommerceCartModification> modifications = new ArrayList<>(); try { if (!Collections.isEmpty(parameterList)) { // add items to cart final Map<CommerceCartParameter, CommerceCartModification> paramModificationMap = new HashMap<>(); for (final CommerceCartParameter parameter : parameterList) { final CommerceCartModification modification = doAddToCart(parameter); paramModificationMap.put(parameter, modification); modifications.add(modification); } // calculate the cart. Using recalculateCart() to force calculate the entries getCommerceCartCalculationStrategy().recalculateCart(parameterList.get(0)); // after add to cart for (final Entry<CommerceCartParameter, CommerceCartModification> entry : paramModificationMap.entrySet()) { final CommerceCartParameter storedParameter = entry.getKey(); final CommerceCartModification storedModification = entry.getValue(); afterAddToCart(storedParameter, storedModification); mergeEntry(storedModification, storedParameter); } } } catch (final CommerceCartModificationException e) { throw new CommerceCartMergingException(e.getMessage(), e); } return modifications; } /** * Adds an item to the cart for pickup in a given location * * @param parameter * Cart parameters * @return Cart modification information * @throws de.hybris.platform.commerceservices.order.CommerceCartModificationException * */ @Override public CommerceCartModification addToCart(final CommerceCartParameter parameter) throws CommerceCartModificationException { final CommerceCartModification modification = doAddToCart(parameter); getCommerceCartCalculationStrategy().calculateCart(parameter); afterAddToCart(parameter, modification); // Here the entry is fully populated, so we can search for a similar one and merge. mergeEntry(modification, parameter); return modification; } /** * Do add to cart. * * @param parameter * the parameter * @return the commerce cart modification * @throws CommerceCartModificationException * the commerce cart modification exception */ protected CommerceCartModification doAddToCart(final CommerceCartParameter parameter) throws CommerceCartModificationException { CommerceCartModification modification; final CartModel cartModel = parameter.getCart(); final ProductModel productModel = parameter.getProduct(); final long quantityToAdd = parameter.getQuantity(); final PointOfServiceModel deliveryPointOfService = parameter.getPointOfService(); this.beforeAddToCart(parameter); validateAddToCart(parameter); if (isProductForCode(parameter).booleanValue()) { // So now work out what the maximum allowed to be added is (note that this may be negative!) final long actualAllowedQuantityChange = getAllowedCartAdjustmentForProduct(cartModel, productModel, quantityToAdd, deliveryPointOfService); final Integer maxOrderQuantity = productModel.getMaxOrderQuantity(); final long cartLevel = checkCartLevel(productModel, cartModel, deliveryPointOfService); final long cartLevelAfterQuantityChange = actualAllowedQuantityChange + cartLevel; if (actualAllowedQuantityChange > 0) { // We are allowed to add items to the cart final CartEntryModel entryModel = addCartEntry(parameter, actualAllowedQuantityChange); getModelService().save(entryModel); final String statusCode = getStatusCodeAllowedQuantityChange(actualAllowedQuantityChange, maxOrderQuantity, quantityToAdd, cartLevelAfterQuantityChange); modification = createAddToCartResp(parameter, statusCode, entryModel, actualAllowedQuantityChange); } else { // Not allowed to add any quantity, or maybe even asked to reduce the quantity // Do nothing! final String status = getStatusCodeForNotAllowedQuantityChange(maxOrderQuantity, maxOrderQuantity); modification = createAddToCartResp(parameter, status, createEmptyCartEntry(parameter), 0); } } else { modification = createAddToCartResp(parameter, CommerceCartModificationStatus.UNAVAILABLE, createEmptyCartEntry(parameter), 0); } return modification; } protected Boolean isProductForCode(final CommerceCartParameter parameter) { final ProductModel productModel = parameter.getProduct(); try { getProductService().getProductForCode(productModel.getCode()); } catch (final UnknownIdentifierException e) { return Boolean.FALSE; } return Boolean.TRUE; } protected CommerceCartModification createAddToCartResp(final CommerceCartParameter parameter, final String status, final CartEntryModel entry, final long quantityAdded) { final long quantityToAdd = parameter.getQuantity(); final CommerceCartModification modification = new CommerceCartModification(); modification.setStatusCode(status); modification.setQuantityAdded(quantityAdded); modification.setQuantity(quantityToAdd); modification.setEntry(entry); return modification; } protected UnitModel getUnit(final CommerceCartParameter parameter) throws CommerceCartModificationException { final ProductModel productModel = parameter.getProduct(); try { return getProductService().getOrderableUnit(productModel); } catch (final ModelNotFoundException e) { throw new CommerceCartModificationException(e.getMessage(), e); } } protected CartEntryModel addCartEntry(final CommerceCartParameter parameter, final long actualAllowedQuantityChange) throws CommerceCartModificationException { if (parameter.getUnit() == null) { parameter.setUnit(getUnit(parameter)); } final CartEntryModel cartEntryModel = getCartService().addNewEntry(parameter.getCart(), parameter.getProduct(), actualAllowedQuantityChange, parameter.getUnit(), APPEND_AS_LAST, false); cartEntryModel.setDeliveryPointOfService(parameter.getPointOfService()); return cartEntryModel; } protected void mergeEntry(@Nonnull final CommerceCartModification modification, @Nonnull final CommerceCartParameter parameter) throws CommerceCartModificationException { ServicesUtil.validateParameterNotNullStandardMessage("modification", modification); if (modification.getEntry() == null || Objects.equals(modification.getEntry().getQuantity(), Long.valueOf(0L))) { // nothing to merge return; } ServicesUtil.validateParameterNotNullStandardMessage("parameter", parameter); if (parameter.isCreateNewEntry()) { return; } final AbstractOrderModel cart = modification.getEntry().getOrder(); if (cart == null) { // The entry is not in cart (most likely it's a stub) return; } final AbstractOrderEntryModel mergeTarget = getEntryMergeStrategy().getEntryToMerge(cart.getEntries(), modification.getEntry()); if (mergeTarget == null) { if (parameter.getEntryNumber() != CommerceCartParameter.DEFAULT_ENTRY_NUMBER) { throw new CommerceCartModificationException( "The new entry can not be merged into the entry #" + parameter.getEntryNumber() + ". Give a correct value or " + CommerceCartParameter.DEFAULT_ENTRY_NUMBER + " to accept any suitable entry."); } } else { // Merge the original entry into the merge target and remove the original entry. final Map<Integer, Long> entryQuantities = new HashMap<>(2); entryQuantities.put(mergeTarget.getEntryNumber(), Long.valueOf(modification.getEntry().getQuantity().longValue() + mergeTarget.getQuantity().longValue())); entryQuantities.put(modification.getEntry().getEntryNumber(), Long.valueOf(0L)); getCartService().updateQuantities(parameter.getCart(), entryQuantities); modification.setEntry(mergeTarget); } } protected String getStatusCodeAllowedQuantityChange(final long actualAllowedQuantityChange, final Integer maxOrderQuantity, final long quantityToAdd, final long cartLevelAfterQuantityChange) { // Are we able to add the quantity we requested? if (isMaxOrderQuantitySet(maxOrderQuantity) && (actualAllowedQuantityChange < quantityToAdd) && (cartLevelAfterQuantityChange == maxOrderQuantity.longValue())) { return CommerceCartModificationStatus.MAX_ORDER_QUANTITY_EXCEEDED; } else if (actualAllowedQuantityChange == quantityToAdd) { return CommerceCartModificationStatus.SUCCESS; } else { return CommerceCartModificationStatus.LOW_STOCK; } } protected String getStatusCodeForNotAllowedQuantityChange(final Integer maxOrderQuantity, final Integer cartLevelAfterQuantityChange) { if (isMaxOrderQuantitySet(maxOrderQuantity) && (cartLevelAfterQuantityChange.longValue() == maxOrderQuantity.longValue())) { return CommerceCartModificationStatus.MAX_ORDER_QUANTITY_EXCEEDED; } else { return CommerceCartModificationStatus.NO_STOCK; } } protected CartEntryModel createEmptyCartEntry(final CommerceCartParameter parameter) { final ProductModel productModel = parameter.getProduct(); final PointOfServiceModel deliveryPointOfService = parameter.getPointOfService(); final CartEntryModel entry = new CartEntryModel() { @Override public Double getBasePrice() { return null; } @Override public Double getTotalPrice() { return null; } }; entry.setProduct(productModel); entry.setDeliveryPointOfService(deliveryPointOfService); return entry; } protected EntryMergeStrategy getEntryMergeStrategy() { return entryMergeStrategy; } @Required public void setEntryMergeStrategy(final EntryMergeStrategy entryMergeStrategy) { this.entryMergeStrategy = entryMergeStrategy; } }
package mnm.mods.tabbychat.settings; import mnm.mods.util.Color; import mnm.mods.util.config.Setting; import mnm.mods.util.config.SettingObject; import mnm.mods.util.config.SettingValue; public class ColorSettings extends SettingObject<ColorSettings> { @Setting public SettingValue<Color> chatBoxColor = value(new Color(0, 0, 0, 127)); @Setting public SettingValue<Color> chatTextColor = value(new Color(255, 255, 255, 255)); }
package graphSeries; import java.util.ArrayList; @SuppressWarnings("unused") public class GraphRepAdj { public static void main(String[] args) { int n = 3; int m = 3; ArrayList<ArrayList<Integer>> adj = new ArrayList<>(); for (int i = 0; i <= n; i++) { adj.add(new ArrayList<Integer>()); } // Edge between 1 and 2 adj.get(1).add(2); adj.get(2).add(1); // Edge between 2 and 3 adj.get(2).add(3); adj.get(3).add(2); // Edge between 1 and 3 adj.get(1).add(3); adj.get(3).add(1); for (int i = 1; i < n; i++) { for (int j = 0; j < adj.get(i).size(); j++) { System.out.print(adj.get(i).get(j) + " "); } System.out.println(); } } }
package day49_AbstractionIntro; public class Square extends Shape{ double side; public Square(double side) { this.side=side; } @Override protected void Area() { double area=side*side; System.out.println("Square area is "+area); } @Override protected void perimeter() { double perimeter=side*4; System.out.println("Square perimeter is "+perimeter); } }
package cn.canlnac.onlinecourse.presentation.internal.di.modules; import java.io.File; import cn.canlnac.onlinecourse.domain.executor.PostExecutionThread; import cn.canlnac.onlinecourse.domain.executor.ThreadExecutor; import cn.canlnac.onlinecourse.domain.interactor.DownloadUseCase; import cn.canlnac.onlinecourse.domain.interactor.UseCase; import cn.canlnac.onlinecourse.domain.repository.UploadRepository; import cn.canlnac.onlinecourse.presentation.internal.di.PerActivity; import dagger.Module; import dagger.Provides; /** * 注入模块. */ @Module public class DownloadModule { private final String fileUrl; private final File targetFile; public DownloadModule( String fileUrl, File targetFile ) { this.fileUrl = fileUrl; this.targetFile = targetFile; } @Provides @PerActivity UseCase provideDownloadUseCase(UploadRepository uploadRepository, ThreadExecutor threadExecutor, PostExecutionThread postExecutionThread){ return new DownloadUseCase(fileUrl, targetFile, uploadRepository, threadExecutor, postExecutionThread); } }