text stringlengths 10 2.72M |
|---|
package com.awstechguide.cms.springjpah2.rest;
public class PermissionRestController {
}
|
package com.master;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
/**
* Created by Administrator on 2015/2/6.
*/
public class BaseActivty extends AppCompatActivity {
private Toolbar mActionBarToolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
protected Toolbar getActionBarToolbar() {
if (mActionBarToolbar == null) {
mActionBarToolbar = (Toolbar) findViewById(R.id.tb_custom);
if (mActionBarToolbar != null) {
setSupportActionBar(mActionBarToolbar);
}
}
return mActionBarToolbar;
}
}
|
package be.openclinic.healthrecord;
import be.mxs.common.util.db.MedwanQuery;
import be.mxs.common.util.system.ScreenHelper;
import java.sql.Connection;
import java.sql.Timestamp;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.util.Vector;
import java.util.Hashtable;
/**
* Created by IntelliJ IDEA.
* User: mxs_david
* Date: 12-jan-2007
* Time: 16:52:34
* To change this template use Options | File Templates.
*/
public class RiskCode {
private int id;
private String code;
private String messageKey;
private int showDefault;
private String NL;
private String FR;
private int active;
private Timestamp updatetime;
private Timestamp deletedate;
private int updateuserid;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessageKey() {
return messageKey;
}
public void setMessageKey(String messageKey) {
this.messageKey = messageKey;
}
public int getShowDefault() {
return showDefault;
}
public void setShowDefault(int showDefault) {
this.showDefault = showDefault;
}
public String getNL() {
return NL;
}
public void setNL(String NL) {
this.NL = NL;
}
public String getFR() {
return FR;
}
public void setFR(String FR) {
this.FR = FR;
}
public int getActive() {
return active;
}
public void setActive(int active) {
this.active = active;
}
public Timestamp getUpdatetime() {
return updatetime;
}
public void setUpdatetime(Timestamp updatetime) {
this.updatetime = updatetime;
}
public Timestamp getDeletedate() {
return deletedate;
}
public void setDeletedate(Timestamp deletedate) {
this.deletedate = deletedate;
}
public int getUpdateuserid() {
return updateuserid;
}
public void setUpdateuserid(int updateuserid) {
this.updateuserid = updateuserid;
}
public static Vector selectTranslations(String sLanguage){
PreparedStatement ps = null;
ResultSet rs = null;
Vector vResults = new Vector();
Hashtable hResults;
String sSelect = "SELECT id, ";
if(sLanguage.equalsIgnoreCase("N")) sSelect+= " NL";
else sSelect+= " FR";
sSelect+= " AS Translation FROM RiskCodes WHERE active=1 AND deletedate IS NULL";
Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection();
try{
ps = oc_conn.prepareStatement(sSelect);
rs = ps.executeQuery();
while(rs.next()){
hResults = new Hashtable();
hResults.put("id",ScreenHelper.checkString(rs.getString("id")));
if(sLanguage.equalsIgnoreCase("N")) hResults.put("translation",ScreenHelper.checkString("NL"));
else hResults.put("translation",ScreenHelper.checkString("FR"));
vResults.addElement(hResults);
}
rs.close();
ps.close();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(rs!=null)rs.close();
if(ps!=null)ps.close();
oc_conn.close();
}catch(Exception e){
e.printStackTrace();
}
}
return vResults;
}
}
|
package com.google;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindAll;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import java.util.List;
public class GoogleFirstPF {
private WebDriver wd;
@FindBy(how= How.NAME, name = "q")
WebElement inputField;
@FindAll(@FindBy(how= How.XPATH, using = "//div[@class='g']//h3"))
List<WebElement> resultSearch;
public GoogleFirstPF(WebDriver wd) {
this.wd = wd;
wd.get("https://www.google.com/");
}
public void googleSearch(String requestStr) {
inputField.click();
inputField.sendKeys(requestStr);
inputField.submit();
}
public List<WebElement> getResultSearch() {
return resultSearch;
}
}
|
package uow.finalproject.webapp.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class WebController {
@RequestMapping(value= {"/", "index"})
public String index() {
return "index";
}
/*
@RequestMapping(value= {"/searchresultstest"})
public String search_test() {
return "searchresultstest";
}
*/
@RequestMapping(value= {"/index_login"})
public String index_login() {
return "index_login";
}
@RequestMapping(value= {"/register"})
public String register() {
return "register";
}
@RequestMapping(value= {"/recommendation"})
public String recommendation() {
return "recommendation";
}
@RequestMapping(value= {"/prod_list"})
public String prod_list() {
return "prod_list";
}
@RequestMapping(value= {"/member_index"})
public String member_index() {
return "member_index";
}
}
|
/*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2011 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ActiveEon Team
* http://www.activeeon.com/
* Contributor(s):
*
* ################################################################
* $$ACTIVEEON_INITIAL_DEV$$
*/
package org.ow2.proactive.resourcemanager.nodesource.infrastructure;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.StringTokenizer;
import org.ow2.proactive.resourcemanager.nodesource.common.Configurable;
import org.ow2.proactive.utils.FileToBytesConverter;
/**
* This class implements a wrapper for user defined BatchJobInfrastructure. You must provide
* a class file and classname of a class that implements a {@link BatchJobInfrastructure}.
*/
public class GenericBatchJobInfrastructure extends BatchJobInfrastructure {
/** */
private static final long serialVersionUID = 31L;
@Configurable(description = "Fully qualified classname\nof the implementation")
protected String implementationClassname;
@Configurable(fileBrowser = true, description = "Absolute path to the\nclass file of the implementation")
protected String implementationFile;
// the actual implementation of the infrastructure
private BatchJobInfrastructure implementation;
@Override
public void configure(Object... parameters) {
super.configure(parameters);
this.implementationClassname = parameters[9].toString();
byte[] implemtationClassfile = (byte[]) parameters[10];
// read the class file and create a BatchJobInfrastructure instance
try {
//create dir for tmp classpath
File f = File.createTempFile("BatchJobClassDir", "GENERATED");
f.delete();
f.mkdir();
f.deleteOnExit();
// if the class name contains the ".class", remove it
if (this.implementationClassname.endsWith(".class")) {
this.implementationClassname = this.implementationClassname.substring(0,
this.implementationClassname.lastIndexOf("."));
}
int lastIndexOfDot = this.implementationClassname.lastIndexOf(".");
boolean inPackage = lastIndexOfDot != -1;
StringBuffer currentDirName = new StringBuffer(f.getAbsolutePath());
// create hierarchy for class file
if (inPackage) {
StringTokenizer packages = new StringTokenizer(this.implementationClassname.substring(0,
lastIndexOfDot), ".");
while (packages.hasMoreTokens()) {
currentDirName.append(File.separator + packages.nextToken());
File currentDir = new File(currentDirName.toString());
currentDir.mkdir();
currentDir.deleteOnExit();
}
}
//create the classfile
File classFile = new File(currentDirName +
File.separator +
this.implementationClassname.substring(lastIndexOfDot + 1, this.implementationClassname
.length()) + ".class");
classFile.deleteOnExit();
if (logger.isDebugEnabled()) {
logger.debug("Created class file for generic BatchJobInfrastructure : " +
classFile.getAbsolutePath());
}
FileToBytesConverter.convertByteArrayToFile(implemtationClassfile, classFile);
URLClassLoader cl = new URLClassLoader(new URL[] { f.toURL() }, this.getClass().getClassLoader());
Class<? extends BatchJobInfrastructure> implementationClass = (Class<? extends BatchJobInfrastructure>) cl
.loadClass(this.implementationClassname);
this.implementation = implementationClass.newInstance();
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Class " + this.implementationClassname + " does not exist", e);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("Implementation class file does not exist", e);
} catch (InstantiationException e) {
throw new IllegalArgumentException("Class " + this.implementationClassname + " cannot be loaded",
e);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException("Class " + this.implementationClassname + " cannot be loaded",
e);
} catch (IOException e) {
throw new IllegalArgumentException("Cannot create temp file for class " +
this.implementationClassname, e);
}
}
@Override
protected String extractSubmitOutput(String output) {
return implementation.extractSubmitOutput(output);
}
@Override
protected String getBatchinJobSystemName() {
if (implementation != null) {
return implementation.getBatchinJobSystemName();
} else {
return "GENERIC";
}
}
@Override
protected String getDeleteJobCommand() {
return implementation.getDeleteJobCommand();
}
@Override
protected String getSubmitJobCommand() {
return implementation.getSubmitJobCommand();
}
}
|
package com.amundi.tech.onsite.model.usage;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
import java.util.Set;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class RestaurantUsageReport implements RestaurantUsage {
private LocalDate date;
private int h1130;
private int h1200;
private int h1230;
private int h1300;
private int h1330;
private Set<String> h1130_users;
private Set<String> h1200_users;
private Set<String> h1230_users;
private Set<String> h1300_users;
private Set<String> h1330_users;
public int getH1130_u() {
return h1130_users.size();
}
public int getH1200_u() {
return h1200_users.size();
}
public int getH1230_u() {
return h1230_users.size();
}
public int getH1300_u() {
return h1300_users.size();
}
public int getH1330_u() {
return h1330_users.size();
}
}
|
/*
### PROGRAMMKOPF ###
Lineare Programmierung
Aufgabe 3
FS23
Marc Freytag
Version: 1.3
20121019
Berechnung des Bezugspreises für Einzelhändler
### ENDE PROGRAMMKOPF ###
*/
// class aslp3 wird eingeleitet
public class aslp3
{
// ### HAUPTFUNKTION ###
public static void main(String[] args )
{
// ### DEKLARATIONSTEIL ###
// Variablen werden deklariert
// int steht für Integerzahlen
// float für Kommazahlen
// double Variablen sind doppelt so groß wie float
// allen float Variablen wird der Wert 0f (f für float) zugewiesen
// int hundert bekommt den Wert 100
int hundert = 100;
float listeneinkaufspreis = 0f;
float lieferantenrabatt = 0f;
float lieferantenskonto = 0f;
float bezugskosten = 0f;
float zieleinkaufspreis = 0f;
float bareinkaufspreis = 0f;
float bezugspreis = 0f;
float lrabatt = 0f;
float lrab = 0f;
float lskonto = 0f;
float lsko = 0f;
// ### ENDE DEKLARATIONSTEIL ###
// gibt Text auf Bildschirm aus, System.out.println() auch möglich
System.out.print("Listeneinkaufspreis (EUR): ");
// wartet auf Eingabe eines Eurobetrags via Tastatur.lies.Int/Float
listeneinkaufspreis = Tastatur.liesFloat();
// gibt Text auf Bildschirm aus
System.out.print("Lieferantenrabatt (%): ");
// wartet auf Eingabe einer Prozentzahl
lieferantenrabatt = Tastatur.liesFloat();
// gibt Text auf Bildschirm aus
System.out.print("Lieferantenskonto (%): ");
// wartet auf Eingabe einer Prozentzahl
lieferantenskonto = Tastatur.liesFloat();
// gibt Text auf Bildschirm aus
System.out.print("Bezugskosten (EUR): ");
// wartet auf Eingabe eines Eurobetrags
bezugskosten = Tastatur.liesFloat();
// Platzhalter: \n fügt einen Zeilenumbruch ein
System.out.print("\n\n");
// weitere Steuerungszeichen:
// /a Bell
// /b Backspace
// /f Form Feed (Seitenvorschub)
// /r Carriage Return
// /t Tabulator horizontal
// /v Tabulator vertikal
// \\ Backslash
// \' Apostroph
// \" Anführungszeichen
// \? Fragezeichen
//
// Berechnung Lieferantenrabatt
// Java rechnet von rechts nach links, Ergebnisvariable also immer links
// Divisionszeichen: "/"
lrabatt = listeneinkaufspreis / hundert;
// Multiplikationszeichen: "*"
lrab = lrabatt * lieferantenrabatt;
// formatierte Ausgabe der vorhergehenden Berechnung
// System.out.printf bzw System.out.format geben Variablen formatiert aus
// Bsp: %10.2f
// % an dieser Stelle wird die Variable formatiert eingefügt
// 10 Stellen für Formatierung reserviert
// .2f float Variable wird auf zwei Nachkommastellen gerundet
System.out.printf(" Listeneinkaufspreis: %10.2f Euro \n", listeneinkaufspreis);
System.out.printf(" - Lieferantenrabatt: %10.2f Euro \n \n", lrab);
// Berechnung Zieleinkaufspreis und Lieferantenskonto
zieleinkaufspreis = listeneinkaufspreis - lrab;
lskonto = zieleinkaufspreis / hundert;
lsko = lskonto * lieferantenskonto;
// formatierte Ausgabe der vorhergehenden Berechnungen
System.out.printf(" Zieleinkaufspreis: %10.2f Euro \n", zieleinkaufspreis);
System.out.printf(" - Lieferantenskonto: %10.2f Euro \n \n", lsko);
// Berechnung Bareinkaufspreis
// Subtraktionszeichen: "-"
bareinkaufspreis = zieleinkaufspreis - lsko;
// formatierte Ausgabe
System.out.printf(" Bareinkaufspreis: %10.2f Euro \n", bareinkaufspreis);
System.out.printf(" + Bezugskosten: %10.2f Euro \n \n", bezugskosten);
// Berechnung Bezugspreis
// Additionszeichen: "+"
bezugspreis = bareinkaufspreis + bezugskosten;
// weitere Operatoren:
// % Restwert (Rest der ganzzahligen Division)
// + Positives Vorzeichen, z.B. +4
// - Negatives Vorzeichen, z.B. -4
// ++ Inkrement, z.B. ++a entspricht a+1 und erhöht a um 1
// -- Dekrement, z.B. a-- entspricht a und verringert a um 1
// formatierte Ausgabe des Ergebnisses
System.out.printf(" Bezugspreis: %10.2f Euro \n", bezugspreis);
System.out.print("=====================================");
}
// ### ENDE HAUPTFUNKTION ###
} |
package com.si.ha.vaadin.security;
import jcifs.dcerpc.msrpc.netdfs;
import com.si.ha.vaadin.security.LoginComp.LoginListener;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.TabSheet;
import com.vaadin.ui.VerticalLayout;
public class LandingPage extends CustomComponent {
public LandingPage() {
setSizeFull();
VerticalLayout root = new VerticalLayout();
root.setSizeFull();
TabSheet ts = new TabSheet();
ts.setSizeUndefined();
ts.addTab(new LoginComp(), "Sign In");
ts.addTab(new RegistrationComp(), "Registration");
root.addComponent(ts);
root.setComponentAlignment(ts, Alignment.MIDDLE_CENTER);
setCompositionRoot(root);
}
}
|
package com.common.adapter;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import java.util.List;
/**
* Generic ListView adapter, but currently only supports the single layout of the form,
* the follow-up will increase the layout of the support. you can use just like the following:
* <pre>
* <code>
* mListView.setAdapter(new CommonAdapter<Person>(this, persons, R.layout.list_item) {
@Override
public void convert(ViewHolder viewHolder, Person item, int position) {
viewHolder.setText(R.id.name, item.getName());
viewHolder.setImageResource(R.id.head, item.getHeadId());
}
});
* </code>
* </pre>
*
* @param <T>
* @author sky
* @version 1.0
*/
public abstract class CommonAdapter<T> extends BaseAdapter {
/** use List cache data */
private List<T> mData;
/** single layout id */
private int mLayoutId;
private Context mContext;
public CommonAdapter(Context context, List<T> data, int layoutId) {
this.mContext = context;
this.mData = data;
this.mLayoutId = layoutId;
}
@Override
public int getCount() {
return mData == null ? 0 : mData.size();
}
@Override
public T getItem(int position) {
return mData == null ? null : mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = ViewHolder.get(mContext, convertView, parent, mLayoutId);
convert(viewHolder, getItem(position), position);
return viewHolder.getConvertView();
}
/**
* subclass need to rewrite it, the process of rewriting, you can define the value of the control
* @param viewHolder @see ViewHolder
* @param item ListView item
* @param position Item view position
*/
public abstract void convert(ViewHolder viewHolder, T item, int position);
}
|
/* StandardThemeProvider.java
{{IS_NOTE
Purpose:
Description:
History:
Mar 17, 2011 8:49:08 AM
}}IS_NOTE
Copyright (C) 2011 Potix Corporation. All Rights Reserved.
{{IS_RIGHT
This program is distributed under LGPL Version 2.1 in the hope that
it will be useful, but WITHOUT ANY WARRANTY.
}}IS_RIGHT
*/
package org.zkoss.zkplus.theme;
import java.util.Collection;
import java.util.List;
import java.util.ListIterator;
import org.zkoss.lang.Strings;
import org.zkoss.zk.ui.Execution;
import org.zkoss.zul.Messagebox;
/**
* A standard implementation of ThemeProvider, which works with the Breeze series
* themes.
* @author simonpai
*/
public class StandardThemeProvider implements org.zkoss.zk.ui.util.ThemeProvider {
public final static String DEFAULT_WCS = "~./zul/css/zk.wcs";
public final static String DEFAULT_MSGBOX_TEMPLATE_URI = "~./zul/html/messagebox.zul";
public Collection getThemeURIs(Execution exec, List uris) {
String suffix = getThemeFileSuffix();
if (Strings.isEmpty(suffix)) {
Messagebox.setTemplate(DEFAULT_MSGBOX_TEMPLATE_URI);
return uris;
}
if (isUsingDefaultTemplate(suffix))
Messagebox.setTemplate(getThemeMsgBoxURI(suffix));
bypassURI(uris, suffix);
return uris;
}
private static String getThemeFileSuffix() {
String suffix = Themes.getCurrentTheme();
return Themes.CLASSICBLUE_NAME.equals(suffix) ? null : suffix;
}
private static String getThemeMsgBoxURI(String suffix) {
return "~./zul/html/messagebox." + suffix + ".zul";
}
private static boolean isUsingDefaultTemplate(String suffix){
return getThemeMsgBoxURI(suffix).equals(Messagebox.getTemplate()) ||
DEFAULT_MSGBOX_TEMPLATE_URI.equals(Messagebox.getTemplate());
}
private void bypassURI(List uris, String suffix) {
for (ListIterator it = uris.listIterator(); it.hasNext();) {
final String uri = (String)it.next();
if (uri.startsWith(DEFAULT_WCS)) {
it.set(Aide.injectURI(uri, suffix));
break;
}
}
}
public int getWCSCacheControl(Execution exec, String uri) {
return 8760; // a year. (JVM will utilize it, don't have to count the answer)
}
public String beforeWCS(Execution exec, String uri) {
return uri;
}
public String beforeWidgetCSS(Execution exec, String uri) {
String suffix = getThemeFileSuffix();
if (Strings.isEmpty(suffix)) return uri;
if(uri.startsWith("~./zul/css/") ||
uri.startsWith("~./js/zul/") ||
uri.startsWith("~./js/zkex/") ||
uri.startsWith("~./js/zkmax/")){
return uri.replaceFirst(".css.dsp", getWidgetCSSName(suffix));
}
return uri;
}
private static String getWidgetCSSName(String suffix) {
return "." + suffix + ".css.dsp";
}
}
|
package de.scads.gradoop_service.server.helper.constructor;
import java.util.List;
import java.util.Map;
import org.gradoop.flink.io.impl.json.JSONDataSource;
import org.gradoop.flink.util.GradoopFlinkConfig;
import org.uni_leipzig.biggr.builder.GraphObjectType;
import org.uni_leipzig.biggr.builder.InvalidSettingsException;
import org.uni_leipzig.biggr.builder.constructors.AbstractFileDataSourceConstructor;
import de.scads.gradoop_service.server.RequestHandler;
import de.scads.gradoop_service.server.helper.GraphHelper;
import de.scads.gradoop_service.server.helper.RDFGraphHelper;
public class RDFDataSourceConstructor extends AbstractFileDataSourceConstructor {
public static final String RDF_GRAPH_CONFIG = "rdfGraphConfig";
//public static final String IDENTIFIER = "identifier";
@Override
public Object construct(final GradoopFlinkConfig gfc, final Map<String, Object> arguments, final List<Object> dependencies) throws InvalidSettingsException{
String rdfGraphConfig = (String)arguments.get(RDF_GRAPH_CONFIG);
//String identifier = (String)arguments.get(IDENTIFIER);
Object result = null;
try {
result = RDFGraphHelper.getRDFGraph(rdfGraphConfig, gfc);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
@Override
public Object coerce(final Object graph, final GraphObjectType got) {
return graph;
}
}
|
package com.alura.exception;
public class AutenticacaoNotFoundException extends RuntimeException{
public AutenticacaoNotFoundException(String message){
super(message);
}
}
|
package com.karya.service;
import java.util.List;
import com.karya.model.Budget001MB;
import com.karya.model.BudgetAccountType001MB;
import com.karya.model.BudgetMonthlyDistribution001MB;
import com.karya.model.BudgetVarianceReport001MB;
import com.karya.model.CostCenter001MB;
public interface IBudgetCostCenterService {
public void addcostcenter(CostCenter001MB costcenter001MB);
public List<CostCenter001MB> listcostcenter();
public CostCenter001MB getcostcenter(int centId);
public void deletecostcenter(int centId);
//Budget account type
public void addbudgetaccounttype(BudgetAccountType001MB budgetaccounttype001MB);
public List<BudgetAccountType001MB> listbudgetaccounttype();
public BudgetAccountType001MB getbudgetaccounttype(int bgaccId);
public void deletebudgetaccounttype(int bgaccId);
//budget
public void addbudget(Budget001MB budget001MB);
public List<Budget001MB> listbudget();
public Budget001MB getbudget(int bgId);
public void deletebudget(int bgId);
//Budget monthly distribution
public void addbudgetmonthlydistribution(BudgetMonthlyDistribution001MB budgetmonthlydistribution001MB);
public List<BudgetMonthlyDistribution001MB> listbudgetmonthlydistribution();
public BudgetMonthlyDistribution001MB getbudgetmonthlydistribution(int bmdId);
public void deletebudgetmonthlydistribution(int bmdId);
//budget variance report
public void addbudgetvariancereport(BudgetVarianceReport001MB budgetvariancereport001MB);
public List<BudgetVarianceReport001MB> listbudgetvariancereport();
public BudgetVarianceReport001MB getbudgetvariancereport(int varId);
public void deletebudgetvariancereport(int varId);
}
|
package com.snowinpluto.tools.generator;
import com.google.common.base.Strings;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.snowinpluto.tools.Constants;
import com.snowinpluto.tools.analysis.BeanSnapshot;
import com.snowinpluto.tools.analysis.ColumnType;
import com.snowinpluto.tools.analysis.FieldAnalyst;
import com.snowinpluto.tools.util.CamelCaseUtil;
import org.dom4j.Element;
import org.dom4j.QName;
import org.dom4j.dom.DOMAttribute;
import org.dom4j.dom.DOMElement;
import java.lang.reflect.Field;
import java.util.List;
@Singleton
public class ResultMapGenerator {
@Inject
private FieldAnalyst fieldAnalyst;
/**
* 生成 ResultMap 的节点
* @param snapshot
* @return
*/
public Element generateResultMap(BeanSnapshot snapshot) {
Element element = new DOMElement(Constants.MAPPER_RESULT_MAP_NAME);
element.add(new DOMAttribute(new QName(Constants.MAPPER_RESULT_MAP_ID),
generateMapId(snapshot.getSimpleName())));
element.add(new DOMAttribute(new QName(Constants.MAPPER_RESULT_MAP_TYPE),
snapshot.getSimpleName()));
for (Field f : snapshot.getFields()) {
String fName = f.getName();
String fColumn = CamelCaseUtil.getUnderLineName(f.getName());
if (Constants.BEAN_ID_NAME.equals(f.getName())) {
Element e = new DOMElement(Constants.MAPPER_RESULT_MAP_SUB_ID);
e.add(new DOMAttribute(new QName(Constants.MAPPER_RESULT_MAP_SUB_PROPERTY),
fName));
e.add(new DOMAttribute(new QName(Constants.MAPPER_RESULT_MAP_SUB_COLUMN),
fColumn));
element.add(e);
}
else {
Element e = new DOMElement(Constants.MAPPER_RESULT_MAP_SUB_RESULT);
e.add(new DOMAttribute(new QName(Constants.MAPPER_RESULT_MAP_SUB_PROPERTY),
fName));
e.add(new DOMAttribute(new QName(Constants.MAPPER_RESULT_MAP_SUB_COLUMN),
fColumn));
ColumnType columnType = fieldAnalyst.analyst(f);
if (columnType != null) {
e.add(new DOMAttribute(new QName(Constants.MAPPER_RESULT_MAP_SUB_JDBC_TYPE),
columnType.name()));
}
element.add(e);
}
}
return element;
}
/**
* 生成 ResultMap 的 ID
* @param name
* @return
*/
public static String generateMapId(String name) {
if (!Strings.isNullOrEmpty(name)) {
List<String> words = CamelCaseUtil.split(name);
String mapId = "";
for (int i = 0; i < words.size(); i++) {
if (i == 0) {
mapId += words.get(i).toLowerCase();
}
else {
mapId += words.get(i);
}
}
return mapId + "Map";
}
return "";
}
}
|
// Sample Java code for user authorization
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.PlaylistItem;
import com.google.api.services.youtube.model.PlaylistItemListResponse;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
/** Application name. */
private static final String APPLICATION_NAME = "API Sample";
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
/** Global instance of the HTTP transport. */
private static HttpTransport HTTP_TRANSPORT;
/**
* Global instance of the scopes required by this quickstart.
* <p>
* If modifying these scopes, delete your previously saved credentials
* at ~/.credentials/drive-java-quickstart
*/
private static final Collection<String> SCOPES = Arrays.asList("https://www.googleapis.com/auth/youtube.readonly");
static {
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
} catch (Throwable t) {
t.printStackTrace();
System.exit(1);
}
}
/**
* Creates an authorized Credential object.
*
* @return an authorized Credential object.
* @throws IOException
*/
public static Credential authorize() throws IOException {
//System.setProperty("GOOGLE_APPLICATION_CREDENTIALS", "src/resources/client_secret.json");
System.out.println(new File(".").getAbsolutePath());
return GoogleCredential.getApplicationDefault(HTTP_TRANSPORT, JSON_FACTORY).createScoped(SCOPES);
}
/**
* Build and return an authorized API client service, such as a YouTube
* Data API client service.
*
* @return an authorized API client service
* @throws IOException
*/
public static YouTube getYouTubeService() throws IOException {
Credential credential = authorize();
return new YouTube.Builder(
HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
}
public static void main(String[] args) throws IOException {
YouTube youtube = getYouTubeService();
try {
/*System.out.println(youtube.playlists().list("snippet")//.setChannelId("UCR-ENZ64WL1vB8KU4YzdmTQ")
.setId("PLru1HAOKPcjJQr4lsCh2eU9F2lhSX23F_").execute().getItems().get(0).);*/
//System.out.println(youtube.playlistItems().list("snippet").setPlaylistId("PLru1HAOKPcjJQr4lsCh2eU9F2lhSX23F_").execute());
final Supplier<YouTube.PlaylistItems.List> getReq = () ->
{
try {
return youtube.playlistItems().list("snippet,contentDetails").setPlaylistId("PLru1HAOKPcjJQr4lsCh2eU9F2lhSX23F_")
.setFields("items(contentDetails/videoId,snippet/title,snippet/description),nextPageToken").setMaxResults(50L);
} catch (IOException e) {
throw new RuntimeException(e);
}
};
PlaylistItemListResponse vids = getReq.get().execute();
//final Pattern pat = Pattern.compile("[-\u00AD]{10,}\\n.*[Cc]omment.*\"(.+)\".*[^-]*[-\u00AD]{10,}");
final Pattern pat = Pattern.compile("[Cc]omment[,\\s.:]*[\"'“]((?:\\w|\\s|[^\"”.])+)[\"'”.]|\\(If you (?:read|see) this, comment: (.*)\\)");
int C = 0, CV = 0;
do {
for (PlaylistItem item : vids.getItems()) {
CV++;
String desc = item.getSnippet().getDescription();
Matcher matcher = pat.matcher(desc);
String phrase = null;
while (matcher.find()) { //There may be other "comment xy" messages but this should be always the last one
phrase = matcher.group(1);
if (phrase == null) phrase = matcher.group(2);
phrase = phrase.replace("\"", "").trim(); //Easier this way
}
if (phrase == null) {
//System.out.println("\n\n\n\n"+desc+"\n\n\n\n");
continue;
}
//System.out.println(phrase + "\t" + item.getSnippet().getTitle()+"\t"+"https://www.youtube.com/watch?v="+item.getContentDetails().getVideoId());
System.out.println(phrase + "\t" + item.getSnippet().getTitle() + "\t" + item.getContentDetails().getVideoId());
/*if (item.getSnippet().getTitle().contains("Rude - MAGIC!")) System.out.println(desc);
int ind = desc.indexOf(SEPARATOR_STR);
int ind2 = desc.indexOf(SEPARATOR_STR, ind + SEPARATOR_STR.length());
if (item.getSnippet().getTitle().contains("Rude - MAGIC!")) {
System.out.println("Ind: " + ind + " " + ind2);
int x = desc.indexOf("-------------------");
System.out.println("- ind: " + x);
for (int i = x; i < desc.length(); i++) System.out.print(" " + (int) desc.charAt(i));
}
if (ind == -1 || ind2 == -1) continue;
String section = desc.substring(ind, ind2);
if (!section.toLowerCase().contains("comment")) continue;
ind = section.indexOf("\"");
ind2 = section.indexOf("\"", ind + 1);
if (ind == -1 || ind2 == -1) continue;
String word = section.substring(ind + 1, ind2);
System.out.println(word);
if (word.equals("Without Warning")) System.out.println(section);
if (word.equals("Teddy bears are my friends")) System.out.println(item.getSnippet().getTitle());
if (word.equals("#BuyLegacyOniTunes")) System.out.println(item.getSnippet().getTitle());
if (word.equals("HALO")) System.out.println(item.getSnippet().getTitle());*/
C++;
}
if (vids.getNextPageToken() == null) break;
vids = getReq.get().setPageToken(vids.getNextPageToken()).execute();
} while (true);
System.out.println("\nWords/phrases: " + C + "\nVideos: " + CV);
} catch (GoogleJsonResponseException e) {
e.printStackTrace();
System.err.println("There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
} catch (Throwable t) {
t.printStackTrace();
}
}
} |
package com.sshfortress.dao.system.mapper;
import java.util.List;
import com.sshfortress.common.beans.SysRoleMenu;
public interface SysRoleMenuMapper {
int deleteByPrimaryKey(Long id);
int insert(SysRoleMenu record);
int insertSelective(SysRoleMenu record);
SysRoleMenu selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(SysRoleMenu record);
int updateByPrimaryKey(SysRoleMenu record);
int insertBatch(List<SysRoleMenu> list);
int deleteByRoleId(Long roleId);
} |
package com.example.isvirin.storeclient.data.entity.daoconverter;
import org.greenrobot.greendao.converter.PropertyConverter;
public class ProductTypeConverter implements PropertyConverter<ProductType, String>{
@Override
public ProductType convertToEntityProperty(String databaseValue) {
return ProductType.valueOf(databaseValue);
}
@Override
public String convertToDatabaseValue(ProductType entityProperty) {
return entityProperty.name();
}
}
|
public class MyLockExample {
private MyLock lock = new MyLock();
private int counter = 0;
private class Runner implements Runnable {
public void run() {
for (int i = 0; i < 1000; i++) {
lock.lock();
counter++;
lock.unlock();
}
}
}
public void runExample() {
Runner r = new Runner();
Thread[] threads = new Thread[3];
for (int i = 0; i < 3; i++) {
threads[i] = new Thread(r);
threads[i].start();
}
for (Thread t : threads)
Util.justJoin(t);
System.out.println(counter);
}
public static void main(String[] args) {
new MyLockExample().runExample();
}
}
|
package me.hotjoyit.user.dao;
import me.hotjoyit.user.domain.Level;
import me.hotjoyit.user.domain.User;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
/**
* Created by hotjoyit on 2016-07-20
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = "/applicationContext.xml")
public class UserDaoTest {
// UserDaoTest 객체는 Test마다 새로 생성하지만 JUnit 테스트 컨텍스트 프레임워크에서 관리하는 Bean들은 한 번만 생성된다
@Autowired
private ApplicationContext context;
@Autowired
private UserDao dao;
private User user1, user2, user3;
@Before
public void setUp() {
user1 = new User("no1", "홍길동", "pw01", Level.BASIC, login(1), recommend(0));
user2 = new User("no2", "임꺽정", "pw02", Level.SILVER, login(55), recommend(10));
user3 = new User("no3", "손오공", "pw03", Level.GOLD, login(100), recommend(40));
}
@Test
public void addAndGet() {
dao.deleteAll();
assertThat(dao.getCount(), is(0));
dao.add(user1);
dao.add(user2);
assertThat(dao.getCount(), is(2));
User userget1 = dao.get(user1.getId());
checkSameUser(user1, userget1);
User userget2 = dao.get(user2.getId());
checkSameUser(user2, userget2);
}
@Test
public void count() {
dao.deleteAll();
assertThat(dao.getCount(), is(0));
dao.add(user1);
assertThat(dao.getCount(), is(1));
dao.add(user2);
assertThat(dao.getCount(), is(2));
dao.add(user3);
assertThat(dao.getCount(), is(3));
}
@Test(expected = EmptyResultDataAccessException.class)
public void getUserFailure() {
dao.deleteAll();
assertThat(dao.getCount(), is(0));
dao.get("unknown_id");
}
@Test
public void getAllIdAscending() {
dao.deleteAll();
dao.add(user1);
List<User> users1 = dao.getAll();
assertThat(users1.size(), is(1));
checkSameUser(user1, users1.get(0));
dao.add(user3);
List<User> users2 = dao.getAll();
assertThat(users2.size(), is(2));
checkSameUser(user1, users1.get(0));
dao.add(user2);
List<User> users3 = dao.getAll();
assertThat(users3.size(), is(3));
checkSameUser(user2, users3.get(1));
}
@Test
public void getAllEmpty() {
dao.deleteAll();
List<User> users = dao.getAll();
assertThat(users.size(), is(0));
}
private void checkSameUser(User user1, User user2) {
assertThat(user1.getId(), is(user2.getId()));
assertThat(user1.getName(), is(user2.getName()));
assertThat(user2.getPassword(), is(user2.getPassword()));
assertThat(user2.getLevel(), is(user2.getLevel()));
assertThat(user2.getLogin(), is(user2.getLogin()));
assertThat(user2.getRecommend(), is(user2.getRecommend()));
}
@Test(expected = DuplicateKeyException.class)
public void duplicatedInsert() {
dao.deleteAll();
dao.add(user1);
dao.add(user1);
}
@Test
public void update() {
dao.deleteAll();
dao.add(user1);
dao.add(user2); // 수정하지 않을 User
user1.setName("빙구");
user1.setPassword("빙구빙구");
user1.setLevel(Level.GOLD);
user1.setLogin(21124);
user1.setRecommend(31233);
dao.update(user1);
User updated = dao.get(user1.getId());
checkSameUser(updated, user1);
User notUpdated = dao.get(user2.getId());
checkSameUser(notUpdated, user2);
}
private int login(int n) {
return n;
}
private int recommend(int n) {
return n;
}
} |
package edu.fudan.ml.classifier.struct.inf;
import edu.fudan.ml.classifier.Predict;
import edu.fudan.ml.classifier.linear.inf.Inferencer;
import edu.fudan.ml.types.Instance;
/**
* 抽象最优序列解码器
* @author Feng Ji
*
*/
public abstract class AbstractViterbi extends Inferencer {
private static final long serialVersionUID = 2627448350847639460L;
/**
* 抽象最优解码算法实现
* @param inst 样本实例
*/
public abstract Predict getBest(Instance inst);
/**
* Viterbi解码算法不支持K-Best解码
*/
@Override
public Predict getBest(Instance inst, int nbest) {
return getBest(inst);
}
}
|
package xyz.noark.core.lock;
import xyz.noark.core.exception.UnrealizedException;
import xyz.noark.core.util.ThreadUtils;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
/**
* 分布式锁.
*
* @author 小流氓[176543888@qq.com]
*/
public abstract class DistributedLock implements Lock, AutoCloseable {
@Override
public void lock() {
// 尝试获取锁,拿不到就等着...
while (!tryLock()) {
ThreadUtils.sleep(100);
}
}
@Override
public void close() {
this.unlock();
}
@Override
public void lockInterruptibly() {
throw new UnrealizedException("暂不实现的方案,请勿使用此方法获取锁.");
}
@Override
public Condition newCondition() {
return null;
}
}
|
package com.beike.action.lucene.search;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.beike.action.LogAction;
import com.beike.page.Pager;
import com.beike.page.PagerHelper;
import com.beike.service.lucene.search.LuceneAlertService;
import com.beike.service.lucene.search.LuceneSearchFacadeService;
import com.beike.util.WebUtils;
import com.beike.util.cache.cachedriver.service.MemCacheService;
import com.beike.util.cache.cachedriver.service.impl.MemCacheServiceImpl;
import com.beike.util.ipparser.CityUtils;
import com.beike.util.lucene.IndexDatasourcePathUtil;
import com.beike.util.lucene.LuceneSearchConstants;
import com.beike.util.lucene.QueryWordFilter;
@Controller
public class LuceneSearchAction {
@Autowired
private LuceneSearchFacadeService facadeService;
@Autowired
private LuceneAlertService luceneAlertService;
static final String ALERT_SUBJECT = "千品网搜索服务异常告警邮件";
static final String ALERT_EMAILCODE = "SEARCH_SERVICE_ALERT";
Logger logger = Logger.getLogger(LuceneSearchAction.class);
MemCacheService mm = MemCacheServiceImpl.getInstance();
@RequestMapping(value = { "/search/searchGoods.do" })
public String SearchGoodsResult(HttpServletRequest request, HttpServletResponse response) throws Exception {
String goods_keyword = null;
String city_en_name = null;
try {
request.setCharacterEncoding("utf-8");
// 当前页
String currentPage = request.getParameter("pn");
city_en_name = WebUtils.getCookieValue(CityUtils.CITY_COOKIENAME, request);
goods_keyword = request.getParameter("kw");
goods_keyword = QueryWordFilter.decodeQueryWord(goods_keyword);
goods_keyword = StringUtils.trim(goods_keyword);
//搜索关键词不允许?,*开头
String goods_keyword_query = QueryWordFilter.filterQueryWord(goods_keyword);
goods_keyword_query = StringUtils.trim(goods_keyword_query);
if (currentPage == null || "".equals(currentPage)) {
currentPage = "1";
}
request.setAttribute("pn", currentPage);
if (city_en_name == null || "".equals(city_en_name) || !Pattern.matches("^[1-9]\\d*$", currentPage) || goods_keyword_query == null || "".equals(goods_keyword_query) || goods_keyword == null || "".equals(goods_keyword)) {
return "redirect:/goods/searchGoodsByProperty.do";
}
int currentPageNo = Integer.parseInt(currentPage);
//加入统计代码 by janwen at 2012-1-17 11:49:25
printLog(request, response, URLDecoder.decode(goods_keyword, "utf-8"), "g", currentPage);
Map<String, Object> searchMap = facadeService.getSearchGoodsMap(goods_keyword_query, city_en_name, currentPageNo, LuceneSearchConstants.GOODS_PAGE_SIZE);
// 计算分页
int totalCount = 0;
totalCount = Integer.parseInt(searchMap.get(LuceneSearchConstants.SEARCH_RESULTS_COUNT).toString());
Pager pager = PagerHelper.getPager(currentPageNo, totalCount, LuceneSearchConstants.GOODS_PAGE_SIZE);
List<Long> nextPageid = (List<Long>) searchMap.get(LuceneSearchConstants.SEARCH_RESULT_NEXTPAGE_ID);
request.setAttribute("pager", pager);
request.setAttribute("totalResults", totalCount);
request.setAttribute("searchedGoods", facadeService.getSearchGoodsResult(nextPageid));
request.setAttribute("keyword", goods_keyword);
//搜索统计结束
return "search/searchgoods";
} catch (IllegalArgumentException e) {
return "redirect:/goods/searchGoodsByProperty.do";
} catch (Exception e) {
// 发送告警邮件
e.printStackTrace();
Map<String, String[]> alertmail = IndexDatasourcePathUtil.getAlertEmail(city_en_name, LuceneSearchConstants.SEARCH_TYPE_GOODS, goods_keyword);
String[] mailaddress = alertmail.get("alertaddress");
for (int i = 0; i < mailaddress.length; i++) {
luceneAlertService.sendMail(ALERT_SUBJECT, mailaddress[i], alertmail.get("emailparams"), ALERT_EMAILCODE);
}
return "redirect:/404.html";
}
}
@RequestMapping(value = { "/search/searchBrand.do" })
public String SearchBrandResult(HttpServletRequest request, HttpServletResponse response) throws Exception {
String city_en_name = null;
String brand_keyword = null;
try {
request.setCharacterEncoding("utf-8");
// 当前页
String currentPage = request.getParameter("pn");
if (currentPage == null || "".equals(currentPage)) {
currentPage = "1";
}
;
int currentPageNo = Integer.parseInt(currentPage);
city_en_name = WebUtils.getCookieValue(CityUtils.CITY_COOKIENAME, request);
brand_keyword = request.getParameter("kw");
brand_keyword = QueryWordFilter.decodeQueryWord(brand_keyword);
//加入统计代码 by janwen at 2012-1-17 11:49:25
printLog(request, response, URLDecoder.decode(brand_keyword, "utf-8"), "b", currentPage);
brand_keyword = StringUtils.trim(brand_keyword);
//搜索关键词不允许?,*开头
String brand_keyword_query = QueryWordFilter.filterQueryWord(brand_keyword);
brand_keyword_query = StringUtils.trim(brand_keyword_query);
if (city_en_name == null || "".equals(city_en_name) || !Pattern.matches("^[1-9]\\d*$", currentPage) || brand_keyword == null || "".equals(brand_keyword) || brand_keyword_query == null || "".equals(brand_keyword_query)) {
return "redirect:/brand/searchBrandsByProperty.do";
}
Map<String, Object> searchMap = facadeService.getSearchBrandMap(brand_keyword_query, city_en_name, currentPageNo, LuceneSearchConstants.BRAND_PAGE_SIZE);
// 计算分页
int totalCount = 0;
totalCount = Integer.parseInt(searchMap.get(LuceneSearchConstants.SEARCH_RESULTS_COUNT).toString());
Pager pager = PagerHelper.getPager(currentPageNo, totalCount, LuceneSearchConstants.BRAND_PAGE_SIZE);
List<Long> nextPageid = (List<Long>) searchMap.get(LuceneSearchConstants.SEARCH_RESULT_NEXTPAGE_ID);
request.setAttribute("pager", pager);
request.setAttribute("totalResults", totalCount);
request.setAttribute("searchedBrand", facadeService.getSearchBrandResult(nextPageid));
request.setAttribute("keyword", brand_keyword);
return "search/searchbrand";
} catch (IllegalArgumentException e) {
return "redirect:/brand/searchBrandsByProperty.do";
} catch (Exception e) {
e.printStackTrace();
// 发送告警邮件
Map<String, String[]> alertmail = IndexDatasourcePathUtil.getAlertEmail(city_en_name, LuceneSearchConstants.SEARCH_TYPE_BRAND, brand_keyword);
String[] mailaddress = alertmail.get("alertaddress");
for (int i = 0; i < mailaddress.length; i++) {
luceneAlertService.sendMail(ALERT_SUBJECT, mailaddress[i], alertmail.get("emailparams"), ALERT_EMAILCODE);
}
return "redirect:/404.html";
}
}
private void printLog(HttpServletRequest request, HttpServletResponse response, String keyword, String type, String pageNo) {
Map<String, String> mapLog = LogAction.getLogMap(request, response);
mapLog.put("action", "p_list");
mapLog.put("keyword", keyword);
mapLog.put("p", pageNo);
mapLog.put("type", type);
LogAction.printLog(mapLog);
}
}
|
package org.gaoshin.openflier.util;
import java.lang.reflect.Field;
public interface FieldFoundCallback {
void field(Object o, Field field) throws Exception;
}
|
package Models;
public class Aititseis {
private String TuposAitisis;
public Aititseis(String TuposAitisis) {
this.TuposAitisis = TuposAitisis;
}
public String getTuposAitisis() {
return TuposAitisis;
}
public void setTuposAitisis(String TuposAitisis) {
this.TuposAitisis = TuposAitisis;
}
public void EmfanisiAitisis(){
}
public void ApostoliAitisis(){
}
public void NeaAitisi(){
}
}
|
package model;
public interface Figur
{
public abstract double berechneUmfang();
public abstract double berechneFlache();
}
|
package fj.swsk.cn.eqapp.main.C;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.esri.android.map.Callout;
import com.esri.android.map.FeatureLayer;
import com.esri.android.map.ogc.WMSLayer;
import com.esri.core.geodatabase.ShapefileFeatureTable;
import com.esri.core.geometry.Envelope;
import com.esri.core.geometry.Geometry;
import com.esri.core.geometry.Point;
import com.esri.core.geometry.SpatialReference;
import com.esri.core.map.Feature;
import com.esri.core.map.FeatureResult;
import com.esri.core.map.Graphic;
import com.esri.core.renderer.Renderer;
import com.esri.core.renderer.SimpleRenderer;
import com.esri.core.symbol.PictureMarkerSymbol;
import com.esri.core.symbol.SimpleFillSymbol;
import com.esri.core.symbol.SimpleLineSymbol;
import com.esri.core.symbol.Symbol;
import com.esri.core.tasks.SpatialRelationship;
import com.esri.core.tasks.query.QueryParameters;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;
import fj.swsk.cn.eqapp.R;
import fj.swsk.cn.eqapp.map.DeathTheaticInfo;
import fj.swsk.cn.eqapp.map.DeathTheaticSearchActivity;
import fj.swsk.cn.eqapp.map.DeathThematicCalloutContent;
import fj.swsk.cn.eqapp.map.PoiCalloutContent;
import fj.swsk.cn.eqapp.util.CommonUtils;
import fj.swsk.cn.eqapp.util.FileUtils;
/**
* Created by apple on 16/6/30.
*/
public class MainMapHandler {
public static void onDistributionPopClicked(MainActivity ac,int position){
if(ac.disaDamageWmsLayerPos!=-1){
ac.mMapView.removeLayer(ac.disaDamageWmsLayerLevel);
}
if(ac.disaDamageWmsLayerPos==position){
ac.disaDamageWmsLayerPos=-1;
return ;
}
WMSLayer wmsLayer=new WMSLayer(ac.getResources().getString(R.string.dis_themMap_url),
SpatialReference.create(4326));
int levelnameids[]={R.string.buiCollapseDis_themMap,
R.string.deathsDis_themMap,
R.string.injDis_themMap,
R.string.ecoLoss_themMap};
if(position>levelnameids.length-1){
CommonUtils.toast("无法加载当前图层");
return ;
}
wmsLayer.setVisibleLayer(new String[]{ac.getResources().getString(levelnameids[position])});
wmsLayer.setImageFormat("image/png");
wmsLayer.setOpacity(0.5f);
ac.mMapView.addLayer(wmsLayer,ac.disaDamageWmsLayerLevel);
ac.disaDamageWmsLayerPos=position;
}
public static void onControlflowPopClicked(MainActivity ac,int pos){
if(ac.layerIdMap.containsKey(pos)){
ac.mMapView.removeLayer(ac.mMapView.getLayerByID(ac.layerIdMap.get(pos)));
ac.layerIdMap.remove(pos);
}else{
DeathTheaticInfo info = getShapefileInfo(ac,pos);
for (Map.Entry<String,Object> en:info.map.entrySet()){
long layerid = addDeathThematicLayer(ac,en.getKey(), (Symbol) en.getValue());
if(layerid!=-1){
ac.layerIdMap.put(pos,layerid);
}
}
}
}
public static long addDeathThematicLayer(MainActivity ac,String sharpFilePath, Symbol symbol) {
try {
String SDPath = FileUtils.getSDPath();
ShapefileFeatureTable shapefileFeatureTable = new ShapefileFeatureTable(
SDPath + "/" + sharpFilePath);
FeatureLayer featureLayer = new FeatureLayer(shapefileFeatureTable);
Renderer renderer = new SimpleRenderer(symbol);
featureLayer.setRenderer(renderer);
ac.mMapView.addLayer(featureLayer);
return featureLayer.getID();
} catch (Exception e) {
Log.e("MainActivity", e.toString());
Toast.makeText(ac, "加载shp图层失败", Toast.LENGTH_SHORT);
}
return -1;
}
public static DeathTheaticInfo getShapefileInfo(Context context, int position) {
Map<String, Object> map = new HashMap<>();
switch (position) {
case 0:
map.put(context.getResources().getString(R.string.road),
new SimpleLineSymbol(Color.BLUE, 1));
break;
case 1:
map.put(context.getResources().getString(R.string.gas_station),
new PictureMarkerSymbol(context.getResources().getDrawable(R.mipmap.gas_station)));
break;
case 2:
map.put(context.getResources().getString(R.string.hydr_station),
new PictureMarkerSymbol(context.getResources().getDrawable(R.mipmap.mark)));
break;
case 3:
map.put(context.getResources().getString(R.string.natgas_station),
new PictureMarkerSymbol(context.getResources().getDrawable(R.mipmap.mark)));
break;
case 4:
map.put(context.getResources().getString(R.string.school),
new PictureMarkerSymbol(context.getResources().getDrawable(R.mipmap.school)));
break;
case 5:
map.put(context.getResources().getString(R.string.hospital),
new PictureMarkerSymbol(context.getResources().getDrawable(R.mipmap.mark)));
break;
case 6:
map.put(context.getResources().getString(R.string.shelter),
new PictureMarkerSymbol(context.getResources().getDrawable(R.mipmap.shelters)));
break;
case 7:
map.put(context.getResources().getString(R.string.resettlement_region),
new SimpleFillSymbol(Color.RED));
break;
case 8:
//map.put(context.getResources().getString(R.string.road),
// new SimpleLineSymbol(Color.BLUE, 1));
map.put(context.getResources().getString(R.string.gas_station),
new PictureMarkerSymbol(context.getResources().getDrawable(R.mipmap.gas_station)));
map.put(context.getResources().getString(R.string.hydr_station),
new PictureMarkerSymbol(context.getResources().getDrawable(R.mipmap.mark)));
map.put(context.getResources().getString(R.string.natgas_station),
new PictureMarkerSymbol(context.getResources().getDrawable(R.mipmap.mark)));
map.put(context.getResources().getString(R.string.school),
new PictureMarkerSymbol(context.getResources().getDrawable(R.mipmap.school)));
map.put(context.getResources().getString(R.string.hospital),
new PictureMarkerSymbol(context.getResources().getDrawable(R.mipmap.mark)));
map.put(context.getResources().getString(R.string.shelter),
new PictureMarkerSymbol(context.getResources().getDrawable(R.mipmap.shelters)));
//map.put(context.getResources().getString(R.string.resettlement_region),
// new SimpleFillSymbol(Color.RED));
break;
default:
return null;
}
DeathTheaticInfo inf = new DeathTheaticInfo();
inf.map = map;
return inf;
}
public static void initBottomMenuPop(final MainActivity ac){
View view =ac. mLayoutInflater.inflate(R.layout.bottom_pop_view,
null,false);
ImageView imgbtn = (ImageView)view.findViewById(R.id.peripheralQuery);
ac.hideView=(TextView)ac.findViewById(R.id.hideView);
imgbtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("x",ac.p.getX());
intent.putExtra("y",ac. p.getY());
intent.setClass(ac, DeathTheaticSearchActivity.class);
ac.startActivity(intent);
}
});
ac. bottom_pop=new PopupWindow(view,-1,-2,true);
ac.bottom_pop.setAnimationStyle(R.style.MenuAnimationFade);
ac.bottom_pop.setBackgroundDrawable(new BitmapDrawable());
ac.bottom_pop.setOutsideTouchable(true);
ac.bottom_pop.setFocusable(true);
ac.bottom_pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
ac.poiLayer.removeAll();
}
});
}
public static Future<FeatureResult> queryShapeFileFeatures(MainActivity ac,ShapefileFeatureTable featureTable,
float var1,float var2,int tolerance){
QueryParameters queryParam = new QueryParameters();
Point minPoint = ac.mMapView.toMapPoint(var1 - tolerance, var2 - tolerance);
Point maxPoint = ac.mMapView.toMapPoint(var1 + tolerance, var2 + tolerance);
queryParam.setGeometry(new Envelope(minPoint.getX()
, minPoint.getY()
, maxPoint.getX()
, maxPoint.getY()));
queryParam.setSpatialRelationship(SpatialRelationship.CONTAINS);
queryParam.setOutFields(new String[]{"*"});
queryParam.setReturnGeometry(true);
Future<FeatureResult> resultFuture = featureTable.queryFeatures(queryParam, null);
return resultFuture;
}
public static void queryDeathThetimacFeatures(MainActivity ac,float f1,float f2,long layerid){
FeatureLayer layer = (FeatureLayer)ac.mMapView.getLayerByID(layerid);
final ShapefileFeatureTable featureTable = (ShapefileFeatureTable)layer.getFeatureTable();
try {
Future<FeatureResult> resultFuture = queryShapeFileFeatures(ac,featureTable, f1, f2, 50);
for (Object result : resultFuture.get()) {
Feature feature = (Feature) result;
Callout mCallout = ac.mMapView.getCallout();
mCallout.setStyle(R.xml.calloutstyle);
Geometry geo = feature.getGeometry();
Map<String, Object> attributes = feature.getAttributes();
ViewGroup deathCalloutContent = DeathThematicCalloutContent.getDeathCalloutContent(
ac,
ac.mLayoutInflater,
attributes);
mCallout.setContent(deathCalloutContent);
mCallout.show((Point) geo);
break;
}
} catch (Exception e) {
Log.e("MainActivity", e.toString());
}
}
public static void queryPoiFeatures(MainActivity ac,float f1,float f2){
int[] poiIDs = ac.poiLayer.getGraphicIDs(f1,f2,50);
if(poiIDs!=null && poiIDs.length>0){
Graphic g=ac.poiLayer.getGraphic(poiIDs[0]);
Callout mcallout = ac.mMapView.getCallout();
mcallout.setStyle(R.xml.calloutstyle);
mcallout.setContent(PoiCalloutContent.getPoiCalloutContent(ac.mLayoutInflater, g.getAttributes()));
mcallout.show((Point)g.getGeometry());
}
}
}
|
package slimeknights.tconstruct.library.client;
import com.google.common.collect.Lists;
import net.minecraft.item.ItemStack;
import org.lwjgl.util.Point;
import java.util.List;
import javax.annotation.Nonnull;
import slimeknights.tconstruct.library.tinkering.TinkersItem;
public class ToolBuildGuiInfo {
@Nonnull
public final ItemStack tool;
// the positions where the slots are located
public final List<Point> positions = Lists.newArrayList();
public ToolBuildGuiInfo() {
// for repairing
this.tool = ItemStack.EMPTY;
}
public ToolBuildGuiInfo(@Nonnull TinkersItem tool) {
this.tool = tool.buildItemForRenderingInGui();
}
public static ToolBuildGuiInfo default3Part(@Nonnull TinkersItem tool) {
ToolBuildGuiInfo info = new ToolBuildGuiInfo(tool);
info.addSlotPosition(33 - 20, 42 + 20);
info.addSlotPosition(33 + 20, 42 - 20);
info.addSlotPosition(33, 42);
return info;
}
/**
* Add another slot at the specified position for the tool.
* The positions are usually located between:
* X: 7 - 69
* Y: 18 - 64
*/
public void addSlotPosition(int x, int y) {
positions.add(new Point(x, y));
}
}
|
/**
* MIT License
* <p>
* Copyright (c) 2017-2018 nuls.io
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package network.nerve.converter.heterogeneouschain.lib.context;
import io.nuls.core.constant.ErrorCode;
import io.nuls.core.rpc.model.ModuleE;
import org.web3j.abi.TypeReference;
import org.web3j.abi.Utils;
import org.web3j.abi.datatypes.*;
import org.web3j.abi.datatypes.generated.Uint256;
import org.web3j.abi.datatypes.generated.Uint8;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author: PierreLuo
* @date: 2021-03-22
*/
public interface HtgConstant {
byte VERSION_MULTY_SIGN_LATEST = 3;
String ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
String PUBLIC_KEY_UNCOMPRESSED_PREFIX = "04";
String HEX_PREFIX = "0x";
String EMPTY_STRING = "";
int RESEND_TIME = 50;
int DEFAULT_INTERVAL_WAITTING = 5;
int MAX_MANAGERS = 15;
String METHOD_HASH_CREATEORSIGNWITHDRAW = "0xab6c2b10";
String METHOD_HASH_CREATEORSIGNMANAGERCHANGE = "0x00719226";
String METHOD_HASH_CREATEORSIGNUPGRADE = "0x408e8b7a";
String METHOD_HASH_CROSS_OUT = "0x0889d1f0";
String METHOD_HASH_CROSS_OUT_II = "0x38615bb0";
String METHOD_HASH_TRANSFER = "0xa9059cbb";
String METHOD_HASH_TRANSFER_FROM = "0x23b872dd";
String METHOD_HASH_ONE_CLICK_CROSS_CHAIN = "0x7d02ce34";
String METHOD_HASH_ADD_FEE_CROSS_CHAIN = "0x0929f4c6";
String METHOD_CREATE_OR_SIGN_WITHDRAW = "createOrSignWithdraw";
String METHOD_CREATE_OR_SIGN_MANAGERCHANGE = "createOrSignManagerChange";
String METHOD_CREATE_OR_SIGN_UPGRADE = "createOrSignUpgrade";
String METHOD_CROSS_OUT = "crossOut";
String METHOD_CROSS_OUT_II = "crossOutII";
String METHOD_VIEW_IS_MINTER_ERC20 = "isMinterERC20";
String METHOD_ONE_CLICK_CROSS_CHAIN = "oneClickCrossChain";
String METHOD_ADD_FEE_CROSS_CHAIN = "addFeeCrossChain";
String METHOD_VIEW_ALL_MANAGERS_TRANSACTION = "allManagers";
String METHOD_VIEW_IS_COMPLETED_TRANSACTION = "isCompletedTx";
String METHOD_VIEW_PENDING_WITHDRAW = "pendingWithdrawTx";
String METHOD_VIEW_PENDING_MANAGERCHANGE = "pendingManagerChangeTx";
String METHOD_VIEW_ERC20_NAME = "name";
String METHOD_VIEW_ERC20_SYMBOL = "symbol";
String METHOD_VIEW_ERC20_DECIMALS = "decimals";
String EVENT_HASH_HT_DEPOSIT_FUNDS = "0xd241e73300212f6df233a8e6d3146b88a9d4964e06621d54b5ff6afeba7b1b88";
String EVENT_HASH_ERC20_TRANSFER = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";
String EVENT_HASH_TRANSFERFUNDS = "0xc95f8b91b103304386b955ef73fadac189f8ad66b33369b6c34a17a60db7bd0a";
String EVENT_HASH_TRANSACTION_WITHDRAW_COMPLETED = "0x8ed8b1f0dd3babfdf1477ba2b27a5b0d2f1c9148448fd22cf2c75e658293c7b1";
String EVENT_HASH_TRANSACTION_MANAGER_CHANGE_COMPLETED = "0xac9b82db4e104d515319a481096bfd91a4f40ee10837d5a2c8d51b9a03dc48ae";
String EVENT_HASH_TRANSACTION_UPGRADE_COMPLETED = "0x5e06c4b22547d430736ce834764dbfee08f1c4cf7ae3d53178aa56effa593ed0";
String EVENT_HASH_CROSS_OUT_FUNDS = "0x5ddf9724d8fe5d9e12499be2867f93d41a582733dcd65f74a486ad7e30667146";
String EVENT_HASH_CROSS_OUT_II_FUNDS = "0x692e6a6e27573f2a2a757e34cb16ae101c5fca8834f9b8a6cdbcf64b8450d870";
String EVENT_HASH_UNKNOWN_ON_POLYGON = "0x4dfe1bbbcf077ddc3e01291eea2d5c70c2b422b415d95645b9adcfd678cb1d63";
String EVENT_HASH_UNKNOWN_ON_REI = "0x873c82cd37aaacdcf736cbb6beefc8da36d474b65ad23aaa1b1c6fbd875f7076";
Set<String> TRANSACTION_COMPLETED_TOPICS = Set.of(
EVENT_HASH_TRANSACTION_WITHDRAW_COMPLETED,
EVENT_HASH_TRANSACTION_MANAGER_CHANGE_COMPLETED,
EVENT_HASH_TRANSACTION_UPGRADE_COMPLETED
);
List<TypeReference<Type>> INPUT_WITHDRAW = Utils.convert(
List.of(
new TypeReference<Utf8String>(){},
new TypeReference<Address>(){},
new TypeReference<Uint256>(){},
new TypeReference<Bool>(){},
new TypeReference<Address>(){},
new TypeReference<DynamicBytes>(){}
)
);
List<TypeReference<Type>> INPUT_CHANGE = Utils.convert(
List.of(
new TypeReference<Utf8String>(){},
new TypeReference<DynamicArray<Address>>(){},
new TypeReference<DynamicArray<Address>>(){},
new TypeReference<Uint8>(){},
new TypeReference<DynamicBytes>(){}
)
);
List<TypeReference<Type>> INPUT_UPGRADE = Utils.convert(
List.of(
new TypeReference<Utf8String>(){},
new TypeReference<Address>(){},
new TypeReference<DynamicBytes>(){}
)
);
List<TypeReference<Type>> INPUT_CROSS_OUT = Utils.convert(
List.of(
new TypeReference<Utf8String>(){},
new TypeReference<Uint256>(){},
new TypeReference<Address>(){}
)
);
List<TypeReference<Type>> INPUT_CROSS_OUT_II = Utils.convert(
List.of(
new TypeReference<Utf8String>(){},
new TypeReference<Uint256>(){},
new TypeReference<Address>(){},
new TypeReference<DynamicBytes>(){}
)
);
List<TypeReference<Type>> INPUT_ERC20_TRANSFER = Utils.convert(
List.of(
new TypeReference<Address>(){},
new TypeReference<Uint256>(){}
)
);
List<TypeReference<Type>> INPUT_ERC20_TRANSFER_FROM = Utils.convert(
List.of(
new TypeReference<Address>(){},
new TypeReference<Address>(){},
new TypeReference<Uint256>(){}
)
);
List<TypeReference<Type>> INPUT_ONE_CLICK_CROSS_CHAIN = Utils.convert(
List.of(
new TypeReference<Uint256>(){},
new TypeReference<Uint256>(){},
new TypeReference<Utf8String>(){},
new TypeReference<Uint256>(){},
new TypeReference<Utf8String>(){},
new TypeReference<DynamicBytes>(){}
)
);
List<TypeReference<Type>> INPUT_ADD_FEE_CROSS_CHAIN = Utils.convert(
List.of(
new TypeReference<Utf8String>(){},
new TypeReference<DynamicBytes>(){}
)
);
Event EVENT_TRANSACTION_WITHDRAW_COMPLETED = new Event("TxWithdrawCompleted",
Arrays.<TypeReference<?>>asList(
new TypeReference<Utf8String>(false) {}
));
Event EVENT_TRANSACTION_MANAGER_CHANGE_COMPLETED = new Event("TxManagerChangeCompleted",
Arrays.<TypeReference<?>>asList(
new TypeReference<Utf8String>(false) {}
));
Event EVENT_TRANSACTION_UPGRADE_COMPLETED = new Event("TxUpgradeCompleted",
Arrays.<TypeReference<?>>asList(
new TypeReference<Utf8String>(false) {}
));
Event EVENT_CROSS_OUT_FUNDS = new Event("CrossOutFunds",
Arrays.<TypeReference<?>>asList(
new TypeReference<Address>(false) {},
new TypeReference<Utf8String>(false) {},
new TypeReference<Uint>(false) {},
new TypeReference<Address>(false) {}
));
Event EVENT_CROSS_OUT_II_FUNDS = new Event("CrossOutIIFunds",
Arrays.<TypeReference<?>>asList(
new TypeReference<Address>(false) {},
new TypeReference<Utf8String>(false) {},
new TypeReference<Uint>(false) {},
new TypeReference<Address>(false) {},
new TypeReference<Uint>(false) {},
new TypeReference<DynamicBytes>(false) {}
));
Event EVENT_DEPOSIT_FUNDS = new Event("DepositFunds",
Arrays.<TypeReference<?>>asList(
new TypeReference<Address>(false) {},
new TypeReference<Uint>(false) {}
));
Event EVENT_TRANSFER_FUNDS = new Event("TransferFunds",
Arrays.<TypeReference<?>>asList(
new TypeReference<Address>(false) {},
new TypeReference<Uint>(false) {}
//new TypeReference<Uint>(false) {}
));
byte[] EMPTY_BYTE = new byte[]{1};
long HOURS_3 = 3L * 60L * 60L * 1000L;
long MINUTES_20 = 20 * 60 * 1000L;
long MINUTES_5 = 5 * 60 * 1000L;
long MINUTES_3 = 3 * 60 * 1000L;
long MINUTES_2 = 2 * 60 * 1000L;
long MINUTES_1 = 1 * 60 * 1000L;
long SECOND_30 = 30 * 1000L;
long SECOND_20 = 20 * 1000L;
long SECOND_10 = 10 * 1000L;
long WAITING_MINUTES = MINUTES_2;
BigDecimal NUMBER_1_DOT_1 = new BigDecimal("1.1");
BigDecimal NUMBER_0_DOT_1 = new BigDecimal("0.1");
BigDecimal BD_20K = BigDecimal.valueOf(20000L);
Long ROLLBACK_NUMER = 100L;
BigInteger GWEI_DOT_01 = BigInteger.valueOf(1L).multiply(BigInteger.TEN.pow(7));
BigInteger GWEI_DOT_1 = BigInteger.valueOf(1L).multiply(BigInteger.TEN.pow(8));
BigInteger GWEI_DOT_3 = BigInteger.valueOf(1L).multiply(BigInteger.TEN.pow(8));
BigInteger GWEI_1 = BigInteger.valueOf(1L).multiply(BigInteger.TEN.pow(9));
BigInteger GWEI_2 = BigInteger.valueOf(2L).multiply(BigInteger.TEN.pow(9));
BigInteger GWEI_3 = BigInteger.valueOf(3L).multiply(BigInteger.TEN.pow(9));
BigInteger GWEI_5 = BigInteger.valueOf(5L).multiply(BigInteger.TEN.pow(9));
BigInteger GWEI_10 = BigInteger.valueOf(10L).multiply(BigInteger.TEN.pow(9));
BigInteger GWEI_11 = BigInteger.valueOf(11L).multiply(BigInteger.TEN.pow(9));
BigInteger GWEI_20 = BigInteger.valueOf(20L).multiply(BigInteger.TEN.pow(9));
BigInteger GWEI_30 = BigInteger.valueOf(20L).multiply(BigInteger.TEN.pow(9));
BigInteger GWEI_100 = BigInteger.valueOf(100L).multiply(BigInteger.TEN.pow(9));
BigInteger GWEI_150 = BigInteger.valueOf(150L).multiply(BigInteger.TEN.pow(9));
BigInteger GWEI_200 = BigInteger.valueOf(200L).multiply(BigInteger.TEN.pow(9));
BigInteger GWEI_300 = BigInteger.valueOf(300L).multiply(BigInteger.TEN.pow(9));
BigInteger GWEI_750 = BigInteger.valueOf(750L).multiply(BigInteger.TEN.pow(9));
BigInteger GWEI_1000 = BigInteger.valueOf(1000L).multiply(BigInteger.TEN.pow(9));
BigInteger GWEI_5000 = BigInteger.valueOf(5000L).multiply(BigInteger.TEN.pow(9));
BigInteger HIGH_GAS_PRICE = GWEI_200;
BigInteger MAX_HTG_GAS_PRICE = GWEI_300;
ErrorCode TX_ALREADY_EXISTS_0 = ErrorCode.init(ModuleE.TX.getPrefix() + "_0013");
ErrorCode TX_ALREADY_EXISTS_1 = ErrorCode.init(ModuleE.CV.getPrefix() + "_0040");
ErrorCode TX_ALREADY_EXISTS_2 = ErrorCode.init(ModuleE.CV.getPrefix() + "_0048");
byte[] ZERO_BYTES = new byte[]{0};
}
|
package com.demo.services;
import com.demo.model.Group;
import com.demo.model.User;
import com.demo.repositories.GroupRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Set;
@Service
public class GroupServiceJpaImpl implements GroupService {
@Autowired
private GroupRepository groupRepo;
@Override
public List<Group> findAll() {
return groupRepo.findAll();
}
@Override
public Group findById(Long id) {
return groupRepo.findOne(id);
}
@Override
public Group create(Group group) {
return groupRepo.save(group);
}
@Override
public Group edit(Group group) {
return groupRepo.save(group);
}
@Override
@Transactional
public void deleteById(Long id) {
Group group = groupRepo.findOne(id);
Set<User> users = group.getUsers();
for (User u : users) {
u.getGroups().remove(group);
}
groupRepo.delete(group);
}
}
|
package com.arrays;
public class BinarySearchInArrayIterative {
public static void main(String[] args) {
int a[] = {12,23,34,45,56,67,78,89,99};
BinarySearchInArrayIterative b = new BinarySearchInArrayIterative();
int i = b.binarySearchArrayIterative(a,2);
if (i == -1) {
System.out.println("value doen's exist in Array");
}else {
System.out.println("the value position is : "+i);
}
}
public int binarySearchArrayIterative(int[] a, int vaule) {
int start = 0;
int end = a.length-1;
if (a.length == 0 ||start > end) {
return -1;
}
while(start<= end){
int mid = (start + end)/2;// or start+((end - start)/2)
if (vaule == a[mid]) {
return mid;
}
if (vaule < a[mid]) {
end = mid-1;
//return binarySearchArrayIterative(a, vaule, start, mid-1);
}else {
start = mid+1;
//return binarySearchArrayIterative(a, vaule, mid+1, end);
}
}
return -1;
}
}
|
package com.test.hplus.converters;
import org.springframework.core.convert.converter.Converter;
import com.test.beans.Gender;
public class StringToEnumConverter implements Converter<String, Gender>{
@Override
public Gender convert(String source) {
// TODO Auto-generated method stub
if(source.equalsIgnoreCase("MALE")) {
return Gender.MALE;
}else if(source.equalsIgnoreCase("FEMALE")) {
return Gender.FEMALE;
}else {
return Gender.OTHER;
}
}
}
|
/*
* 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 tccthainan;
import guarana.framework.message.Message;
import guarana.toolkit.engine.Scheduler;
import guarana.util.xml.XMLHandler;
import java.text.DecimalFormat;
import java.util.ArrayList;
import org.w3c.dom.Document;
//import tcc.integration.solution.TccIntegrationSolution;
/**
*
* @author Edinaldo
*/
public class StartApp {
public static String STATS_FOLDER;
public static String ENTRY_XML = "./entry.xml";
public static String GUARANA_CONF = "./guarana-conf.xml";
//private Message<Document> msgList;
private ArrayList<Message<Document>> msgList;
String msg = null;
public static void main(String[] args) throws InterruptedException {
new StartApp().start();
System.out.println("Acabou");
}
public void start() throws InterruptedException {
//try {
int i = 0;
String summaryFile = STATS_FOLDER + "execution-summary.txt";
// Document doc = XMLHandler.readXmlFile(ENTRY_XML);
msg = ">>> Building messages... ";
System.out.println(msg);
this.msgList = buildMessages(2);
//Document doc = XMLHandler.readXmlFile(GUARANA_CONF);
//XMLHandler.writeXmlFile( doc, GUARANA_CONF );
Scheduler exec = new Scheduler("Scheduler");
Integration prc = new Integration();
exec.registerProcess(prc);
msg = "Starting workers... ";
System.out.println(msg);
exec.start();
for (Message<Document> m : msgList) {
prc.communicatorEntry.pushRead(m);
Thread.sleep(1000);
// XMLHandler.writeXmlFile(m.getBody(), "test.xml");
i++;
System.out.println("Construiu "+i+" mensagens");
}
// prc.communicatorEntry.pushRead(msgList);
//System.out.println( msgList.getBody().getXmlEncoding());
exec.stop();
Thread.sleep(60 * 1000);
}
// private Message<Document> buildMessages(long messages) throws XPathExpressionException {
// long start = System.currentTimeMillis();
//
// Document docX1 = XMLHandler.readXmlFile("./entry.xml");
//
//
//
// Message<Document> m = new Message<Document>();
// m.setBody(docX1);
//
//
// long end = System.currentTimeMillis();
// DecimalFormat df = new DecimalFormat("####.##");
// System.out.println(">>> Time to build the message: " + df.format(((end - start) / 1000f / 60f)) + " min");
//
// return m;
//
// }
private ArrayList<Message<Document>> buildMessages(long messages) {
ArrayList<Message<Document>> result = new ArrayList<Message<Document>>();
long start = System.currentTimeMillis();
for (int i = 0; i < messages; i++) {
Document msg1 = XMLHandler.readXmlFile("./entry.xml");
Message<Document> m = new Message<Document>();
m.setBody(msg1);
result.add(m);
}
long end = System.currentTimeMillis();
DecimalFormat df = new DecimalFormat("####.##");
System.out.println(">>> Time to build messages: " + df.format(((end - start) / 1000f / 60f)) + " min");
return result;
}
}
|
package config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
@org.springframework.context.annotation.Configuration
@ComponentScan("com.itheima")
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
@EnableAspectJAutoProxy
public class Configuration {
}
|
package maven_ssm.generation.mappers;
import java.util.List;
import java.util.Map;
import maven_ssm.generation.entity.FieldEntity;
public interface FieldMapper {
List<FieldEntity> findFieldByTable(Map<String,String> map);
}
|
package tw.org.iii.AbnerJava;
public class Seventh {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a[][] = new int[4][13];
}
}
|
package com.xsc.springbootintegration.service;
import com.xsc.springbootintegration.common.IPUtil;
import com.xsc.springbootintegration.model.Article;
import com.xsc.springbootintegration.model.Setting;
import com.xsc.springbootintegration.repository.ArticleRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
* @author: XSC
* @date: 2018/4/25 下午2:15
*/
@Service
public class ArticleService {
@Autowired
private ArticleRepository articleRepository;
@Autowired
private SettingService settingService;
private static final Logger LOGGER = LoggerFactory.getLogger(ArticleService.class);
private RedisTemplate redisTemplate;
public ArticleService(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
/**
* 加入redis缓存
*
* @param uuid
* @return
*/
public Article findByuuid(String uuid, HttpServletRequest request) {
String ipAddress = IPUtil.getRemoteIpAddress(request);
String macAddress = IPUtil.getMACAddressByIp(ipAddress);
// 以IP+MAC+UUID作为key,缓存redis中
String mac = (String) redisTemplate.opsForValue().get(ipAddress + macAddress + uuid);
LOGGER.info("redis中IP+MAC+UUID的key值:{}", mac);
// 1小时之内,相同MAC地址的用户阅读相同的文章,不计阅读数
if (mac == null) {
articleRepository.increaseViewCount(uuid);
redisTemplate.opsForValue().set(ipAddress + macAddress + uuid, uuid);
redisTemplate.expire(ipAddress + macAddress + uuid, 1, TimeUnit.HOURS);
}
Article article = (Article) redisTemplate.opsForValue().get(uuid);
if (article == null) {
article = articleRepository.findByuuid(uuid);
// 进行缓存,时间30分钟
redisTemplate.opsForValue().set(uuid, article);
redisTemplate.expire(uuid, 30, TimeUnit.MINUTES);
}
return article;
}
public int insert(Article article) {
return articleRepository.insert(article);
}
public int update(Article article) {
return articleRepository.update(article);
}
public int delete(Integer id){
return articleRepository.delete(id);
}
public int delList(List<Integer> ids) {
return articleRepository.delList(ids);
}
public List<Article> findAll(){
return articleRepository.findAll();
}
public int findAllCount(){
return articleRepository.findAllCount();
}
public Article findById(Integer id) {
return articleRepository.findById(id);
}
public int findByCategoryIdCount(int categoryId) {
return articleRepository.findByCategoryIdCount(categoryId);
}
public Page<Article> findByPage(Pageable pageable) {
List<Article> list = articleRepository.findByPage(pageable);
Setting setting = settingService.findByName("article-face-default-pic");
List<Article> newList = list.stream().map(x->{
if (x.getCover() == null || "".equals(x.getCover())){
x.setCover(setting.getVal());
}
return x;
}).collect(Collectors.toList());
Integer total = articleRepository.findAllCount();
Page<Article> page = new PageImpl<Article>(newList, pageable, total);
return page;
}
public int findArticleCountByConsumerId(Integer consumerId) {
return articleRepository.findArticleCountByConsumerId(consumerId);
}
public List<Article> findArticleHot5ByCategoryId(Integer categoryId) {
List<Article> list = articleRepository.findArticleHot5ByCategoryId(categoryId);
Setting setting = settingService.findByName("article-face-default-pic");
List<Article> newList = list.stream().map(x->{
if (x.getCover() == null || "".equals(x.getCover())){
x.setCover(setting.getVal());
}
return x;
}).collect(Collectors.toList());
return newList;
}
public Page<Article> findAllArticlePageByCategoryId(Pageable pageable, Integer categoryId) {
List<Article> list = articleRepository.findAllArticlePageByCategoryId(pageable,categoryId);
Setting setting = settingService.findByName("article-face-default-pic");
List<Article> newList = list.stream().map(x->{
if (x.getCover() == null || "".equals(x.getCover())){
x.setCover(setting.getVal());
}
return x;
}).collect(Collectors.toList());
Integer total = articleRepository.findByCategoryIdCount(categoryId);
Page<Article> page = new PageImpl<>(list, pageable, total);
return page;
}
public List<Article> findArticleBroadcast() {
List<Article> list = articleRepository.findArticleBroadcast();
Setting setting = settingService.findByName("article-face-default-pic");
List<Article> newList = list.stream().map(x->{
if (x.getCover() == null || "".equals(x.getCover())){
x.setCover(setting.getVal());
}
return x;
}).collect(Collectors.toList());
return newList;
}
public List<Article> findArticleHot5() {
List<Article> list = articleRepository.findArticleHot5();
Setting setting = settingService.findByName("article-face-default-pic");
List<Article> newList = list.stream().map(x->{
if (x.getCover() == null || "".equals(x.getCover())){
x.setCover(setting.getVal());
}
return x;
}).collect(Collectors.toList());
return newList;
}
public List<Article> findArticlHot5WitRecomendhHot() {
List<Article> list = articleRepository.findArticlHot5WitRecomendhHot();
Setting setting = settingService.findByName("article-face-default-pic");
List<Article> newList = list.stream().map(x->{
if (x.getCover() == null || "".equals(x.getCover())){
x.setCover(setting.getVal());
}
return x;
}).collect(Collectors.toList());
return newList;
}
public int increaseViewCount(String uuid) {
return articleRepository.increaseViewCount(uuid);
}
public int findViewcountByuuid(String uuid) {
return articleRepository.findViewcountByuuid(uuid);
}
}
|
package com.edu.realestate.dao;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.jdbc.ReturningWork;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.edu.realestate.model.Advertisement;
import com.edu.realestate.model.City;
import com.edu.realestate.model.RealEstateType;
import com.edu.realestate.model.SearchCriteria;
@Repository
public class SearchDaoHib extends AbstractDaoHib implements SearchDao {
@Autowired
CityDao cdao;
@Override
public List<Advertisement> search(SearchCriteria sc) {
Session session = getSession();
List<Advertisement> lads = new ArrayList<>();
String otherReq = "";
String exclude = "";
String sort = " releaseDate DESC";
boolean apt = sc.getRealEstateType().equals(RealEstateType.valueOf("Apartment"));
boolean house = sc.getRealEstateType().equals(RealEstateType.valueOf("House"));
if (sc.getRealEstateType() != null) {
otherReq += " AND realEstate.id IN (SELECT id from " + sc.getRealEstateType() + ")";
}
if (sc.getCityId() != 0) {
otherReq += " AND realEstate.city.id IN ";
if (sc.getDistance() != 0) {
sc.setDistance(Math.min(50, sc.getDistance()));
City c = cdao.read(sc.getCityId());
ReturningWork<List<Integer>> rw = new ReturningWork<List<Integer>>() {
@Override
public List<Integer> execute(Connection connection) throws SQLException {
try (CallableStatement function = connection.prepareCall(
"{ SELECT id FROM City c WHERE greatcircle(c.latitude, c.longitude, ?, ?) < ?"
+ " OR greatcircle(c.latitude, c.longitude, ?, ?) IS NULL }")) {
function.registerOutParameter(1, Types.ARRAY);
function.setDouble(1, c.getLatitude());
function.setDouble(2, c.getLongitude());
function.setDouble(3, sc.getDistance());
function.execute();
List<Integer> list = new ArrayList<>();
ResultSet rs = function.getResultSet();
while (rs.next())
list.add(rs.getInt("id"));
return list;
}
}
};
List<Integer> cityInDistance = session.doReturningWork(rw);
String cityList = cityInDistance.toString();
otherReq += "(" + cityList.substring(1, cityList.length() - 1) + ")";
} else
otherReq += "(" + sc.getCityId() + ")";
}
if (sc.getQuery() != null)
otherReq += " AND ( description LIKE '%" + sc.getQuery() + "%'" + " OR title LIKE '%" + sc.getQuery()
+ "%' )";
if (sc.getTransactionType() != null)
otherReq += " AND transactionType = '" + sc.getTransactionType() + "'";
if (sc.getAreaMin() < 0)
sc.setAreaMin(0);
if (sc.getAreaMax() > 10000)
sc.setAreaMax(10000);
if (sc.getAreaMin() > sc.getAreaMax() && sc.getAreaMax() > 0) {
int tmp = sc.getAreaMin();
sc.setAreaMin(sc.getAreaMax());
sc.setAreaMax(tmp);
}
if (sc.getAreaMin() > 0)
otherReq += " AND realEstate.area >= " + sc.getAreaMin();
if (sc.getAreaMax() > 0)
otherReq += " AND realEstate.area <= " + sc.getAreaMax();
if (sc.getPriceMin() < 0)
sc.setPriceMin(0);
if (sc.getPriceMax() > 100000000)
sc.setPriceMax(100000000);
if (sc.getPriceMin() > sc.getPriceMax() && sc.getPriceMax() > 0) {
int tmp = sc.getPriceMin();
sc.setPriceMin(sc.getPriceMax());
sc.setPriceMax(tmp);
}
if (sc.getPriceMin() > 0)
otherReq += " AND realEstate.price >= " + sc.getPriceMin();
if (sc.getPriceMax() > 0)
otherReq += " AND realEstate.price <= " + sc.getPriceMax();
if (house) {
if (sc.getLandMin() < 0)
sc.setLandMin(0);
if (sc.getLandMax() > 1000000)
sc.setLandMax(1000000);
if (sc.getLandMin() > sc.getLandMax() && sc.getLandMax() > 0) {
int tmp = sc.getLandMin();
sc.setLandMin(sc.getLandMax());
sc.setLandMax(tmp);
}
if (sc.getLandMin() > 0 || sc.getLandMax() > 0) {
if (sc.getLandMin() > 0)
otherReq += " AND realEstate.landArea >= " + sc.getLandMin();
if (sc.getLandMax() > 0)
otherReq += " AND realEstate.landArea <= " + sc.getLandMax();
}
}
if (apt || house) {
if (sc.getRoomsMin() < 0)
sc.setRoomsMin(0);
if (sc.getRoomsMax() > 100)
sc.setRoomsMax(100);
if (sc.getRoomsMin() > sc.getRoomsMax() && sc.getRoomsMax() > 0) {
int tmp = sc.getRoomsMin();
sc.setRoomsMin(sc.getRoomsMax());
sc.setRoomsMax(tmp);
}
if (sc.getRoomsMin() > 0 || sc.getRoomsMax() > 0) {
if (apt) {
if (sc.getRoomsMin() > 0)
otherReq += " AND realEstate.rooms >= " + sc.getRoomsMin();
if (sc.getRoomsMax() > 0)
otherReq += " AND realEstate.rooms <= " + sc.getRoomsMax();
}
if (house) {
if (sc.getRoomsMin() > 0)
otherReq += " AND realEstate.rooms >= " + sc.getRoomsMin();
if (sc.getRoomsMax() > 0)
otherReq += " AND realEstate.rooms <= " + sc.getRoomsMax();
}
}
}
/* OPTIONS */
if (apt || house) {
if (apt) {
if (sc.hasElevator())
otherReq += " AND realEstate.elevator = 'Y'";
if (sc.hasIntercom())
otherReq += " AND realEstate.intercom = 'Y'";
if (sc.hasBalcony())
otherReq += " AND realEstate.balcony = 'Y'";
if (sc.hasTerrace())
otherReq += " AND realEstate.terrace = 'Y'";
if (sc.hasGarage())
otherReq += " AND realEstate.garage = 'Y'";
if (sc.hasParking())
otherReq += " AND realEstate.parking = 'Y'";
if (sc.hasAlarm())
otherReq += " AND realEstate.alarm = 'Y'";
if (sc.hasDigicode())
otherReq += " AND realEstate.digicode = 'Y'";
}
if (house) {
if (sc.hasCellar())
otherReq += " AND realEstate.cellar = 'Y'";
if (sc.hasAlarm())
otherReq += " AND realEstate.alarm = 'Y'";
if (sc.hasSwimmingPool())
otherReq += " AND realEstate.swimming_pool = 'Y'";
}
}
if (apt || house) {
if (apt) {
if ((int) sc.getEnergyLevel() != 0)
otherReq += " AND realEstate.energyLevel REGEXP '[A-" + sc.getEnergyLevel() + "]'";
if ((int) sc.getGasLevel() != 0)
otherReq += " AND realEstate.gasLevel REGEXP '[A-" + sc.getGasLevel() + "]'";
}
if (house) {
if ((int) sc.getEnergyLevel() != 0)
otherReq += " AND realEstate.energyLevel REGEXP '[A-" + sc.getEnergyLevel() + "]'";
;
if ((int) sc.getGasLevel() != 0)
otherReq += " AND realEstate.gasLevel REGEXP '[A-" + sc.getGasLevel() + "]'";
;
}
}
/* SORT AND PAGINATION */
if (sc.getSort() != null)
sort = sc.getSort();
/* IN DETAILS, EXCLUDE THE AD DETAILED IN THE SEARCH */
if (sc.getExclude() != 0) {
exclude = " AND id != " + sc.getExclude();
}
String req = "FROM Advertisement WHERE realEstate.available = 'Y' AND status = 'Validated' " + exclude
+ otherReq + " ORDER BY " + sort;
if (sc.getLimit() > 0)
lads = session.createQuery(req, Advertisement.class).setMaxResults(sc.getLimit()).list();
else
lads = session.createQuery(req, Advertisement.class).list();
return lads;
}
}
|
package com.cs.casino.promotion;
import com.cs.audit.AuditService;
import com.cs.audit.PlayerActivityType;
import com.cs.casino.security.CurrentPlayer;
import com.cs.casino.security.PlayerUser;
import com.cs.player.PlayerService;
import com.cs.promotion.PlayerPromotion;
import com.cs.promotion.Promotion;
import com.cs.promotion.PromotionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import static org.springframework.http.HttpStatus.OK;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
/**
* @author Hadi Movaghar
*/
@RestController
@RequestMapping(value = "/api/promotions", consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
public class PromotionController {
private final PlayerService playerService;
private final PromotionService promotionService;
private final AuditService auditService;
@Autowired
public PromotionController(final PlayerService playerService, final PromotionService promotionService, final AuditService auditService) {
this.playerService = playerService;
this.promotionService = promotionService;
this.auditService = auditService;
}
@RequestMapping(method = GET, value = "/list")
@ResponseStatus(OK)
public List<PromotionDto> getPlayerPromotions(@CurrentPlayer final PlayerUser currentPlayer, @RequestHeader("X-Forwarded-For") final String host) {
final Map<PlayerPromotion, Promotion> playerPromotions = promotionService.getPlayerPromotions(currentPlayer.getId());
auditService.trackPlayerActivityWithIpAddress(playerService.getPlayer(currentPlayer.getId()), PlayerActivityType.REQ_GET_PLAYER_PROMOTIONS, host);
return getAllPromotions(playerPromotions);
}
private List<PromotionDto> getAllPromotions(final Map<PlayerPromotion, Promotion> playerPromotions) {
final List<PromotionDto> bonusList = new ArrayList<>();
for (final Entry<PlayerPromotion, Promotion> entry : playerPromotions.entrySet()) {
final PromotionDto promotionDto = new PromotionDto();
promotionDto.setName(entry.getValue().getName());
promotionDto.setValidTo(entry.getValue().getValidTo());
promotionDto.setActivationDate(entry.getKey().getActivationDate());
promotionDto.setBonusList(entry.getValue().getBonusList());
bonusList.add(promotionDto);
}
return bonusList;
}
}
|
package AnnotationsInTestNG;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Reporter;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;
public class ActiLogin {
WebDriver driver;
@Test//Annotation-Login
public void login() { //3.
driver.findElement(By.name("username")).sendKeys("admin");
driver.findElement(By.name("pwd")).sendKeys("manager");
driver.findElement(By.id("loginButton")).click();
}
@Test//Annotation-InvalidLogin //6.
public void loginInvalid() {
driver.findElement(By.name("username")).sendKeys("admin");
driver.findElement(By.name("pwd")).sendKeys("managsr");
driver.findElement(By.id("loginButton")).click();
}
@BeforeMethod
public void beforeMethod() { //2. //5.
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("http://desktop-a3rr3tc/login.do");
}
@AfterMethod
public void afterMethod() { //4. //7.
driver.quit();
}
@BeforeTest
public void beforeTest() { //1.
System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
}
@AfterTest
public void afterTest() { //8.
Reporter.log("generate the report", true);
}
}
|
package cn.kim.common.attr;
/**
* Created by 余庚鑫 on 2019/3/27
* 全局URL
*/
public class Url {
/**
* URL地址
*/
public static final String MANAGER_URL = "admin/";
public static final String EDIT_USER = MANAGER_URL + "editUser";
public static final String EDIT_PASSWORD = MANAGER_URL + "editPwd";
public static final String EDIT_HEADPORTRAIT = MANAGER_URL + "headPortrait";
/**
* 获取ID
*/
public static final String SEQUENCE_ID_URL = "getSequenceId";
/**
* 图片地址url
*/
public static final String IMG_URL = AttributePath.FILE_PREVIEW_URL;
public static final String DOWN_URL = AttributePath.FILE_DOWNLOAD_URL;
public static final String DOWN_CACHE_URL = AttributePath.FILE_DOWNLOAD_URL + AttributePath.FILE_SERVICE_CACHE_PATH;
/**
* 图片服务器预览地址
*/
public static final String FILE_SERVER_PREVIEW_URL = "preview/";
public static final String FILE_SERVER_PLAYER_URL = "player/";
public static final String FILE_SERVER_DOWNLOAD_URL = "download/";
public static final String FILE_SERVER_UPLOAD_URL = "upload/";
public static final String FILE_SERVER_UPDATE_URL = "file/update";
/**
* excel导出地址
*/
public static final String EXPORT_URL = "file/export/";
/**
* 列表地址
*/
public static final String DATA_GRID_URL = MANAGER_URL + "dataGrid/data/";
public static final String TREE_GRID_URL = MANAGER_URL + "treeGrid/data/";
public static final String DIFF_URL = MANAGER_URL + "diff";
/**
* 系统配置管理
*/
public static final String ALLOCATION_BASE_URL = MANAGER_URL + "allocation/";
/**
* 邮箱配置管理
*/
public static final String EMAIL_BASE_URL = ALLOCATION_BASE_URL + "email";
public static final String EMAIL_CACHE_URL = EMAIL_BASE_URL + "/cache";
/**
* 网站配置地址
*/
public static final String WEBCONFIG_BASE_URL = ALLOCATION_BASE_URL + "webConfig";
/**
* 前端管理管理
*/
public static final String MOBILE_BOTTOM_MENU_BASE_URL = ALLOCATION_BASE_URL + "mobileBottomMenu";
/**
* 授权
*/
public static final String AUTHORIZATION_BASE_URL = MANAGER_URL + "authorization/";
public static final String AUTHORIZATION_TREE_URL = AUTHORIZATION_BASE_URL + "tree";
public static final String AUTHORIZATION_UPDATE_URL = AUTHORIZATION_BASE_URL + "update";
/**
* 日志
*/
public static final String LOG_BASE_URL = MANAGER_URL + "log/";
/**
* 变动记录
*/
public static final String LOG_VALUE_RECORD_BASE_URL = LOG_BASE_URL + "valueRecord/";
public static final String LOG_VALUE_RECORD_DETAIL_URL = LOG_VALUE_RECORD_BASE_URL + "detail/column";
/**
* 菜单管理
*/
public static final String MENU_BASE_URL = MANAGER_URL + "menu/";
public static final String MENU_LIST_URL = MENU_BASE_URL + "list";
public static final String MENU_TREE_DATA_URL = MENU_BASE_URL + "getMenuTreeData";
public static final String MENU_TREE_BUTTON_DATA_URL = MENU_BASE_URL + "getMenuButtonTreeData";
public static final String MENU_TREE_BUTTON_DATA_UPDATE_URL = MENU_BASE_URL + "updateMenuButton";
public static final String MENU_ADD_URL = MENU_BASE_URL + "add";
public static final String MENU_UPDATE_URL = MENU_BASE_URL + "update";
public static final String MENU_COPY_URL = MENU_BASE_URL + "copy";
public static final String MENU_SWITCH_STATUS_URL = MENU_BASE_URL + "switchStatus";
public static final String MENU_DELETE_URL = MENU_BASE_URL + "delete";
/**
* 配置列表
*/
public static final String CONFIGURE_BASE_URL = MANAGER_URL + "configure/";
public static final String CONFIGURE_TREE_DATA_URL = CONFIGURE_BASE_URL + "getConfigureTreeData";
public static final String CONFIGURE_ADD_URL = CONFIGURE_BASE_URL + "add";
public static final String CONFIGURE_UPDATE_URL = CONFIGURE_BASE_URL + "update";
public static final String CONFIGURE_COPY_URL = CONFIGURE_BASE_URL + "copy";
public static final String CONFIGURE_DELETE_URL = CONFIGURE_BASE_URL + "delete";
/**
* 配置列表列
*/
public static final String CONFIGURE_COLUMN_BASE_URL = CONFIGURE_BASE_URL + "column/";
public static final String CONFIGURE_COLUMN_ADD_URL = CONFIGURE_COLUMN_BASE_URL + "add";
public static final String CONFIGURE_COLUMN_UPDATE_URL = CONFIGURE_COLUMN_BASE_URL + "update";
public static final String CONFIGURE_COLUMN_DELETE_URL = CONFIGURE_COLUMN_BASE_URL + "delete";
/**
* 配置列表搜索
*/
public static final String CONFIGURE_SEARCH_BASE_URL = CONFIGURE_BASE_URL + "search/";
public static final String CONFIGURE_SEARCH_ADD_URL = CONFIGURE_SEARCH_BASE_URL + "add";
public static final String CONFIGURE_SEARCH_UPDATE_URL = CONFIGURE_SEARCH_BASE_URL + "update";
public static final String CONFIGURE_SEARCH_DELETE_URL = CONFIGURE_SEARCH_BASE_URL + "delete";
/***
* 配置列表文件
*/
public static final String CONFIGURE_FILE_BASE_URL = CONFIGURE_BASE_URL + "file/";
public static final String CONFIGURE_FILE_ADD_URL = CONFIGURE_FILE_BASE_URL + "add";
public static final String CONFIGURE_FILE_UPDATE_URL = CONFIGURE_FILE_BASE_URL + "update";
public static final String CONFIGURE_FILE_SWITCH_STATUS_URL = CONFIGURE_FILE_BASE_URL + "switchStatus";
public static final String CONFIGURE_FILE_DELETE_URL = CONFIGURE_FILE_BASE_URL + "delete";
/**
* 按钮列表
*/
public static final String BUTTON_BASE_URL = MANAGER_URL + "button/";
public static final String BUTTON_ADD_URL = BUTTON_BASE_URL + "add";
public static final String BUTTON_UPDATE_URL = BUTTON_BASE_URL + "update";
public static final String BUTTON_DELETE_URL = BUTTON_BASE_URL + "delete";
/**
* 角色
*/
public static final String ROLE_BASE_URL = MANAGER_URL + "role/";
public static final String ROLE_LIST_URL = ROLE_BASE_URL + "list";
public static final String ROLE_TREE_DATA_URL = ROLE_BASE_URL + "tree";
public static final String ROLE_ADD_URL = ROLE_BASE_URL + "add";
public static final String ROLE_UPDATE_URL = ROLE_BASE_URL + "update";
public static final String ROLE_PERMISSION_TREE_MENU = ROLE_BASE_URL + "menuTree/";
public static final String ROLE_PERMISSION_TREE_MENU_DATA = ROLE_BASE_URL + "getMenuTreeData/";
public static final String ROLE_PERMISSION_TREE_MENU_UPDATE = ROLE_BASE_URL + "updateRoleMenuPermission";
public static final String ROLE_PERMISSION_TREE_BUTTON = ROLE_BASE_URL + "buttonTree/";
public static final String ROLE_PERMISSION_TREE_BUTTON_DATA = ROLE_BASE_URL + "getButtonTreeData/";
public static final String ROLE_PERMISSION_TREE_BUTTON_UPDATE = ROLE_BASE_URL + "updateRoleButtonPermission";
public static final String ROLE_SWITCH_STATUS_URL = ROLE_BASE_URL + "switchStatus";
public static final String ROLE_DELETE_URL = ROLE_BASE_URL + "delete";
/**
* 验证
*/
public static final String VALIDATE_BASE_URL = MANAGER_URL + "validate/";
public static final String VALIDATE_ADD_URL = VALIDATE_BASE_URL + "add";
public static final String VALIDATE_UPDATE_URL = VALIDATE_BASE_URL + "update";
public static final String VALIDATE_SWITCH_STATUS_URL = VALIDATE_BASE_URL + "switchStatus";
public static final String VALIDATE_DELETE_URL = VALIDATE_BASE_URL + "delete";
/**
* 验证字段
*/
public static final String VALIDATE_FIELD_BASE_URL = VALIDATE_BASE_URL + "field/";
public static final String VALIDATE_FIELD_LIST_URL = VALIDATE_FIELD_BASE_URL + "list";
public static final String VALIDATE_FIELD_ADD_URL = VALIDATE_FIELD_BASE_URL + "add";
public static final String VALIDATE_FIELD_UPDATE_URL = VALIDATE_FIELD_BASE_URL + "update";
public static final String VALIDATE_FIELD_SWITCH_STATUS_URL = VALIDATE_FIELD_BASE_URL + "switchStatus";
public static final String VALIDATE_FIELD_DELETE_URL = VALIDATE_FIELD_BASE_URL + "delete";
/**
* 验证组
*/
public static final String VALIDATE_GROUP_BASE_URL = VALIDATE_BASE_URL + "group/";
public static final String VALIDATE_GROUP_ADD_URL = VALIDATE_GROUP_BASE_URL + "add";
public static final String VALIDATE_GROUP_UPDATE_URL = VALIDATE_GROUP_BASE_URL + "update";
public static final String VALIDATE_GROUP_DELETE_URL = VALIDATE_GROUP_BASE_URL + "delete";
/**
* 验证正则
*/
public static final String VALIDATE_REGEX_BASE_URL = VALIDATE_BASE_URL + "regex/";
public static final String VALIDATE_REGEX_TREE_DATA_URL = VALIDATE_REGEX_BASE_URL + "tree";
public static final String VALIDATE_REGEX_ADD_URL = VALIDATE_REGEX_BASE_URL + "add";
public static final String VALIDATE_REGEX_UPDATE_URL = VALIDATE_REGEX_BASE_URL + "update";
public static final String VALIDATE_REGEX_SWITCH_STATUS_URL = VALIDATE_REGEX_BASE_URL + "switchStatus";
public static final String VALIDATE_REGEX_DELETE_URL = VALIDATE_REGEX_BASE_URL + "delete";
/**
* 字典
*/
public static final String DICT_BASE_URL = MANAGER_URL + "dict/";
public static final String DICT_ADD_URL = DICT_BASE_URL + "add";
public static final String DICT_UPDATE_URL = DICT_BASE_URL + "update";
public static final String DICT_SWITCH_STATUS_URL = DICT_BASE_URL + "switchStatus";
public static final String DICT_DELETE_URL = DICT_BASE_URL + "delete";
public static final String DICT_CACHE_URL = DICT_BASE_URL + "cache";
/**
* 字典信息
*/
public static final String DICT_INFO_BASE_URL = DICT_BASE_URL + "info/";
public static final String DICT_INFO_TREE_URL = DICT_INFO_BASE_URL + "tree";
public static final String DICT_INFO_ADD_URL = DICT_INFO_BASE_URL + "add";
public static final String DICT_INFO_UPDATE_URL = DICT_INFO_BASE_URL + "update";
public static final String DICT_INFO_SWITCH_STATUS_URL = DICT_INFO_BASE_URL + "switchStatus";
public static final String DICT_INFO_DELETE_URL = DICT_INFO_BASE_URL + "delete";
/**
* 操作员列表
*/
public static final String OPERATOR_BASE_URL = MANAGER_URL + "operator/";
public static final String OPERATOR_ADD_URL = OPERATOR_BASE_URL + "add";
public static final String OPERATOR_UPDATE_URL = OPERATOR_BASE_URL + "update";
public static final String OPERATOR_SWITCH_STATUS_URL = OPERATOR_BASE_URL + "switchStatus";
public static final String OPERATOR_RESET_PWD_URL = OPERATOR_BASE_URL + "resetPwd";
public static final String OPERATOR_DELETE_URL = OPERATOR_BASE_URL + "delete";
public static final String OPERATOR_TREE_ROLE_DATA_URL = OPERATOR_BASE_URL + "roles";
public static final String OPERATOR_TREE_ROLE_DATA_UPDATE_URL = OPERATOR_BASE_URL + "updateOperatorRoles";
public static final String OPERATOR_LIST_URL = OPERATOR_BASE_URL + "list";
/**
* 操作员账号列表
*/
public static final String OPERATOR_SUB_BASE_URL = OPERATOR_BASE_URL + "sub/";
public static final String OPERATOR_SUB_ADD_URL = OPERATOR_SUB_BASE_URL + "add";
public static final String OPERATOR_SUB_UPDATE_URL = OPERATOR_SUB_BASE_URL + "update";
public static final String OPERATOR_SUB_SWITCH_STATUS_URL = OPERATOR_SUB_BASE_URL + "switchStatus";
public static final String OPERATOR_SUB_DELETE_URL = OPERATOR_SUB_BASE_URL + "delete";
/**
* 格式管理
*/
public static final String FORMAT_BASE_URL = MANAGER_URL + "format/";
public static final String FORMAT_ADD_URL = FORMAT_BASE_URL + "add";
public static final String FORMAT_UPDATE_URL = FORMAT_BASE_URL + "update";
public static final String FORMAT_DELETE_URL = FORMAT_BASE_URL + "delete";
/**
* 格式详细管理
*/
public static final String FORMAT_DETAIL_BASE_URL = FORMAT_BASE_URL + "detail/";
public static final String FORMAT_DETAIL_TREE_URL = FORMAT_DETAIL_BASE_URL + "tree";
public static final String FORMAT_DETAIL_ADD_URL = FORMAT_DETAIL_BASE_URL + "add";
public static final String FORMAT_DETAIL_UPDATE_URL = FORMAT_DETAIL_BASE_URL + "update";
public static final String FORMAT_DETAIL_SWITCH_STATUS_URL = FORMAT_DETAIL_BASE_URL + "switchStatus";
public static final String FORMAT_DETAIL_DELETE_URL = FORMAT_DETAIL_BASE_URL + "delete";
/**
* 流程列表
*/
public static final String PROCESS_BASE_URL = MANAGER_URL + "process/";
public static final String PROCESS_DATAGRID_BTN = PROCESS_BASE_URL + "showDataGridBtn";
public static final String PROCESS_DATAGRID_IS_EDIT = PROCESS_BASE_URL + "showDataGridIsEdit";
public static final String PROCESS_PROCESS_STATUS = PROCESS_BASE_URL + "getProcessAuditStatus";
public static final String PROCESS_SHOW_HOME = PROCESS_BASE_URL + "showDataGridProcess";
public static final String PROCESS_SUBMIT = PROCESS_BASE_URL + "submit";
public static final String PROCESS_WITHDRAW = PROCESS_BASE_URL + "withdraw";
public static final String PROCESS_LOG = PROCESS_BASE_URL + "log";
public static final String PROCESS_LOG_LIST = PROCESS_BASE_URL + "log/list";
/**
* 流程定义列表
*/
public static final String PROCESS_DEFINITION_BASE_URL = PROCESS_BASE_URL + "definition/";
public static final String PROCESS_DEFINITION_TREE_DATA = PROCESS_DEFINITION_BASE_URL + "tree";
public static final String PROCESS_DEFINITION_ADD_URL = PROCESS_DEFINITION_BASE_URL + "add";
public static final String PROCESS_DEFINITION_UPDATE_URL = PROCESS_DEFINITION_BASE_URL + "update";
public static final String PROCESS_DEFINITION_SWITCH_STATUS_URL = PROCESS_DEFINITION_BASE_URL + "switchStatus";
public static final String PROCESS_DEFINITION_COPY_URL = PROCESS_DEFINITION_BASE_URL + "copy";
/**
* 流程定义列表
*/
public static final String PROCESS_STEP_BASE_URL = PROCESS_BASE_URL + "step/";
public static final String PROCESS_STEP_ADD_URL = PROCESS_STEP_BASE_URL + "add";
public static final String PROCESS_STEP_UPDATE_URL = PROCESS_STEP_BASE_URL + "update";
public static final String PROCESS_STEP_DELETE_URL = PROCESS_STEP_BASE_URL + "delete";
/**
* 流程启动角色列表
*/
public static final String PROCESS_START_BASE_URL = PROCESS_BASE_URL + "start/";
public static final String PROCESS_START_ADD_URL = PROCESS_START_BASE_URL + "add";
public static final String PROCESS_START_UPDATE_URL = PROCESS_START_BASE_URL + "update";
public static final String PROCESS_START_DELETE_URL = PROCESS_START_BASE_URL + "delete";
/**
* 流程时间控制
*/
public static final String PROCESS_TIME_CONTROL_BASE_URL = PROCESS_BASE_URL + "timeControl/";
public static final String PROCESS_TIME_CONTROL_ADD_URL = PROCESS_TIME_CONTROL_BASE_URL + "add";
public static final String PROCESS_TIME_CONTROL_UPDATE_URL = PROCESS_TIME_CONTROL_BASE_URL + "update";
public static final String PROCESS_TIME_CONTROL_SWITCH_STATUS_URL = PROCESS_TIME_CONTROL_BASE_URL + "switchStatus";
public static final String PROCESS_TIME_CONTROL_DELETE_URL = PROCESS_TIME_CONTROL_BASE_URL + "delete";
/**
* 流程进度列表
*/
public static final String PROCESS_SCHEDULE_BASE_URL = PROCESS_BASE_URL + "schedule/";
public static final String PROCESS_SCHEDULE_CANCEL_URL = PROCESS_SCHEDULE_BASE_URL + "cancel";
/**
* 主页图片
*/
public static final String MAINIMAGE_BASE_URL = MANAGER_URL + "mainImage/";
public static final String MAINIMAGE_ADD_URL = MAINIMAGE_BASE_URL + "add";
public static final String MAINIMAGE_UPDATE_URL = MAINIMAGE_BASE_URL + "update";
public static final String MAINIMAGE_SWITCHSTATUS_URL = MAINIMAGE_BASE_URL + "switchStatus";
public static final String MAINIMAGE_DELETE_URL = MAINIMAGE_BASE_URL + "delete";
/**
* 主页图片关联成就墙
*/
public static final String MAINIMAGE_TREE_DATA_URL = MAINIMAGE_BASE_URL + "achievementTreeData";
public static final String MAINIMAGE_TREE_UPDATE_URL = MAINIMAGE_BASE_URL + "updateAchievementMainImage";
/**
* 主页图片区域管理
*/
public static final String MAINIMAGE_AREA_UPDATE_URL = MAINIMAGE_BASE_URL + "area/update";
/**
* 成就墙
*/
public static final String ACHIEVEMENT_BASE_URL = MANAGER_URL + "achievement/";
public static final String ACHIEVEMENT_ADD_URL = ACHIEVEMENT_BASE_URL + "add";
public static final String ACHIEVEMENT_UPDATE_URL = ACHIEVEMENT_BASE_URL + "update";
public static final String ACHIEVEMENT_SWITCHSTATUS_URL = ACHIEVEMENT_BASE_URL + "switchStatus";
public static final String ACHIEVEMENT_DELETE_URL = ACHIEVEMENT_BASE_URL + "delete";
/**
* 成就墙分享管理
*/
public static final String ACHIEVEMENT_SHARE_HTML_UPDATE_URL = ACHIEVEMENT_BASE_URL + "share/updateHtml";
public static final String ACHIEVEMENT_SHARE_UPDATE_URL = ACHIEVEMENT_BASE_URL + "share/update";
/**
* 打卡记录
*/
public static final String CLOCKIN_BASE_URL = MANAGER_URL + "clockin/";
public static final String CLOCKIN_ADD_URL = CLOCKIN_BASE_URL + "add";
public static final String CLOCKIN_UPDATE_URL = CLOCKIN_BASE_URL + "update";
public static final String CLOCKIN_DELETE_URL = CLOCKIN_BASE_URL + "delete";
/**
* 微信用户管理
*/
public static final String WECHAT_BASE_URL = MANAGER_URL + "wechat/";
public static final String WECHAT_SWITCHSTATUS_URL = WECHAT_BASE_URL + "switchStatus";
/**
* 活动
*/
public static final String ACTIVITY_BASE_URL = MANAGER_URL + "activity/";
public static final String ACTIVITY_ADD_URL = ACTIVITY_BASE_URL + "add";
public static final String ACTIVITY_UPDATE_URL = ACTIVITY_BASE_URL + "update";
public static final String ACTIVITY_SWITCHSTATUS_URL = ACTIVITY_BASE_URL + "switchStatus";
public static final String ACTIVITY_DELETE_URL = ACTIVITY_BASE_URL + "delete";
}
|
package blog.dreamland.com.service.impl;
import blog.dreamland.com.common.PageHelper;
import blog.dreamland.com.dao.UserContentMapper;
import blog.dreamland.com.entity.Comment;
import blog.dreamland.com.entity.UserContent;
import blog.dreamland.com.service.UserContentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @auther SyntacticSugar
* @data 2019/3/1 0001下午 3:56
*/
@Service
public class UserContentServiceImpl implements UserContentService {
@Autowired
private UserContentMapper userContentMapper;
// todo
@Override
public PageHelper.Page<UserContent> findAll(UserContent content, Integer pageNum, Integer pageSize) {
return null;
}
@Override
public PageHelper.Page<UserContent> findAll(UserContent content, Comment comment, Integer pageNum, Integer pageSize) {
return null;
}
@Override
public PageHelper.Page<UserContent> findAllByUpvote(UserContent content, Integer pageNum, Integer pageSize) {
return null;
}
@Override
public List<UserContent> findByUserId(Long uid) {
return null;
}
@Override
public List<UserContent> findAll() {
return null;
}
@Override
public List<UserContent> findCategoryByUserId(Long uid) {
List<UserContent> categoryByUserId = userContentMapper.findCategoryByUserId(uid);
return categoryByUserId;
}
@Override
public PageHelper.Page<UserContent> findByCategory(String category, Long uid, Integer pageSize, Integer pageNum) {
UserContent userContent = new UserContent();
//判断category非空
if (StringUtils.isNotBlank(category) &&!category.equals("")) {
userContent.setCategory(category);
}
userContent.setuId(uid);
userContent.setPersonal("0");//
PageHelper.startPage(pageNum, pageSize);
userContentMapper.select(userContent);
PageHelper.Page endPage = PageHelper.endPage();
return endPage;
}
@Override
public PageHelper.Page<UserContent> findPersonal(Long uid, Integer pageNum, Integer pageSize) {
UserContent userContent = new UserContent();
userContent.setuId(uid);
userContent.setPersonal("1");
PageHelper.startPage(pageNum, pageSize);
userContentMapper.select(userContent);
PageHelper.Page endPage = PageHelper.endPage();
return endPage;
}
}
|
/*
* Copyright 2016 TeddySoft Technology. All rights reserved.
*
*/
package tw.teddysoft.gof.Composite;
public class LineBullet extends Bullet {
@Override
public void fire() {
System.out.println("發射直線子彈.");
}
}
|
package suppliers;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.util.HashMap;
import java.util.Map;
public class MoodleLoginSupplier implements LoginSupplier {
@Override
public Map<String, String> login(String url, String username, String password) throws Exception {
Map<String, String> result = new HashMap<>();
MoodleWSConnection moodleWS = new MoodleWSConnection();
// Gets the user's token (as a response)
String tokenResponse = moodleWS.getTokenResponse(url, username, password);
// Check if the response contains the user's token:
JsonObject jsonResponse = new JsonParser().parse(tokenResponse).getAsJsonObject();
if (jsonResponse.has("errorcode")) {
// An error happened, throw that error back
String error = jsonResponse.get("errorcode").toString();
throw new Exception(error);
}
// Everything went correctly
String token = jsonResponse.get("token").getAsString();
result.put("token", token);
// Add the userid to the response
JsonObject infoJson = moodleWS.getMoodleInfo(url, token);
result.put("userid", infoJson.get("userid").getAsString());
result.put("sitename", infoJson.get("sitename").getAsString());
System.out.println(result);
// Return the response + userid
return result;
}
} |
import java.io.File;
import java.util.Scanner;
import java.io.FileWriter;
public class main
{
public static void main(String[] args) {
File f = new File("Result.txt");
try{
Scanner in = new Scanner(System.in); //Make Scanner object
String name;
int sub1,sub2,sub3,sub4,sub5;
FileWriter file = new FileWriter(f);
f.createNewFile();
//-------------------------------------------------------------
//--------------------------Student1---------------------------
//-------------------------------------------------------------
System.out.print("\n* Enter name of the Student 1 : ");
name = in.next();
System.out.print("* Enter 1st marks of the Student 1 : ");
sub1 = in.nextInt();
System.out.print("* Enter 2nd marks of the Student 1 : ");
sub2 = in.nextInt();
System.out.print("* Enter 3rd marks of the Student 1 : ");
sub3 = in.nextInt();
System.out.print("* Enter 4th marks of the Student 1 : ");
sub4 = in.nextInt();
System.out.print("* Enter 5th marks of the Student 1 : ");
sub5 = in.nextInt();
funcs std1 = new funcs(name,sub1,sub2,sub3,sub4,sub5);
System.out.println("\n\n============================================\n");
System.out.println(std1.getName());
System.out.println("Sum : "+std1.getSum());
System.out.println("Average : "+std1.getAvg());
System.out.println("\n============================================\n\n\n");
file.write("\nName : "+name);
file.write("\nSubject 1 marks : "+sub1);
file.write("\nSubject 2 marks : "+sub2);
file.write("\nSubject 3 marks : "+sub3);
file.write("\nSubject 4 marks : "+sub4);
file.write("\nSubject 5 marks : "+sub5);
file.write("\n===================================================\n");
file.write("Sum : "+std1.getSum());
file.write("\nAverage : "+std1.getAvg());
file.write("\n===================================================\n\n\n");
//-------------------------------------------------------------
//--------------------------Student2---------------------------
//-------------------------------------------------------------
System.out.print("\n* Enter name of the Student 2 : ");
name = in.next();
System.out.print("* Enter 1st marks of the Student 2 : ");
sub1 = in.nextInt();
System.out.print("* Enter 2nd marks of the Student 2 : ");
sub2 = in.nextInt();
System.out.print("* Enter 3rd marks of the Student 2 : ");
sub3 = in.nextInt();
System.out.print("* Enter 4th marks of the Student 2 : ");
sub4 = in.nextInt();
System.out.print("* Enter 5th marks of the Student 2 : ");
sub5 = in.nextInt();
funcs std2 = new funcs(name,sub1,sub2,sub3,sub4,sub5);
System.out.println("\n\n============================================\n");
System.out.println(std2.getName());
System.out.println("Sum : "+std2.getSum());
System.out.println("Average : "+std2.getAvg());
System.out.println("\n============================================\n\n\n");
file.write("\nName : "+name);
file.write("\nSubject 1 marks : "+sub1);
file.write("\nSubject 2 marks : "+sub2);
file.write("\nSubject 3 marks : "+sub3);
file.write("\nSubject 4 marks : "+sub4);
file.write("\nSubject 5 marks : "+sub5);
file.write("\n===================================================\n");
file.write("Sum : "+std2.getSum());
file.write("\nAverage : "+std2.getAvg());
file.write("\n===================================================\n\n\n");
//-------------------------------------------------------------
//--------------------------Student3---------------------------
//-------------------------------------------------------------
System.out.print("\n* Enter name of the Student 3 : ");
name = in.next();
System.out.print("* Enter 1st marks of the Student 3 : ");
sub1 = in.nextInt();
System.out.print("* Enter 2nd marks of the Student 3 : ");
sub2 = in.nextInt();
System.out.print("* Enter 3rd marks of the Student 3 : ");
sub3 = in.nextInt();
System.out.print("* Enter 4th marks of the Student 3 : ");
sub4 = in.nextInt();
System.out.print("* Enter 5th marks of the Student 3 : ");
sub5 = in.nextInt();
funcs std3 = new funcs(name,sub1,sub2,sub3,sub4,sub5);
System.out.println("\n\n============================================\n");
System.out.println(std3.getName());
System.out.println("Sum : "+std3.getSum());
System.out.println("Average : "+std3.getAvg());
System.out.println("\n============================================\n\n\n");
file.write("\nName : "+name);
file.write("\nSubject 1 marks : "+sub1);
file.write("\nSubject 2 marks : "+sub2);
file.write("\nSubject 3 marks : "+sub3);
file.write("\nSubject 4 marks : "+sub4);
file.write("\nSubject 5 marks : "+sub5);
file.write("\n===================================================\n");
file.write("Sum : "+std3.getSum());
file.write("\nAverage : "+std3.getAvg());
file.write("\n===================================================\n\n\n");
//-------------------------------------------------------------
//--------------------------Student4---------------------------
//-------------------------------------------------------------
System.out.print("\n* Enter name of the Student 4 : ");
name = in.next();
System.out.print("* Enter 1st marks of the Student 4 : ");
sub1 = in.nextInt();
System.out.print("* Enter 2nd marks of the Student 4 : ");
sub2 = in.nextInt();
System.out.print("* Enter 3rd marks of the Student 4 : ");
sub3 = in.nextInt();
System.out.print("* Enter 4th marks of the Student 4 : ");
sub4 = in.nextInt();
System.out.print("* Enter 5th marks of the Student 4 : ");
sub5 = in.nextInt();
funcs std4 = new funcs(name,sub1,sub2,sub3,sub4,sub5);
System.out.println("\n\n============================================\n");
System.out.println(std4.getName());
System.out.println("Sum : "+std4.getSum());
System.out.println("Average : "+std4.getAvg());
System.out.println("\n============================================\n\n\n");
file.write("\nName : "+name);
file.write("\nSubject 1 marks : "+sub1);
file.write("\nSubject 2 marks : "+sub2);
file.write("\nSubject 3 marks : "+sub3);
file.write("\nSubject 4 marks : "+sub4);
file.write("\nSubject 5 marks : "+sub5);
file.write("\n===================================================\n");
file.write("Sum : "+std4.getSum());
file.write("\nAverage : "+std4.getAvg());
file.write("\n===================================================\n\n\n");
//-------------------------------------------------------------
//--------------------------Student5---------------------------
//-------------------------------------------------------------
System.out.print("\n* Enter name of the Student 5 : ");
name = in.next();
System.out.print("* Enter 1st marks of the Student 5 : ");
sub1 = in.nextInt();
System.out.print("* Enter 2nd marks of the Student 5 : ");
sub2 = in.nextInt();
System.out.print("* Enter 3rd marks of the Student 5 : ");
sub3 = in.nextInt();
System.out.print("* Enter 4th marks of the Student 5 : ");
sub4 = in.nextInt();
System.out.print("* Enter 5th marks of the Student 5 : ");
sub5 = in.nextInt();
funcs std5 = new funcs(name,sub1,sub2,sub3,sub4,sub5);
System.out.println("\n\n============================================\n");
System.out.println(std5.getName());
System.out.println("Sum : "+std5.getSum());
System.out.println("Average : "+std5.getAvg());
System.out.println("\n============================================\n\n\n");
file.write("\nName : "+name);
file.write("\nSubject 1 marks : "+sub1);
file.write("\nSubject 2 marks : "+sub2);
file.write("\nSubject 3 marks : "+sub3);
file.write("\nSubject 4 marks : "+sub4);
file.write("\nSubject 5 marks : "+sub5);
file.write("\n===================================================\n");
file.write("Sum : "+std5.getSum());
file.write("\nAverage : "+std5.getAvg());
file.write("\n===================================================\n\n\n");
file.close();
}catch(Exception e){
System.out.println("\n====> An error occurred!\n====> Check your Inputs!");
f.delete();
}
}
}
|
package ru.vyarus.dropwizard.guice.module.context.debug.report.stat;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import ru.vyarus.dropwizard.guice.module.GuiceyConfigurationInfo;
import ru.vyarus.dropwizard.guice.module.context.ConfigItem;
import ru.vyarus.dropwizard.guice.module.context.Filters;
import ru.vyarus.dropwizard.guice.module.context.debug.report.ReportRenderer;
import ru.vyarus.dropwizard.guice.module.context.debug.util.TreeNode;
import ru.vyarus.dropwizard.guice.module.context.info.ExtensionItemInfo;
import ru.vyarus.dropwizard.guice.module.installer.install.JerseyInstaller;
import javax.inject.Inject;
import javax.inject.Singleton;
import static ru.vyarus.dropwizard.guice.module.context.stat.Stat.*;
import static ru.vyarus.dropwizard.guice.module.installer.util.Reporter.NEWLINE;
/**
* Renders startup statistics. Overall guicey time is composed from bundle time and hk time and so
* Hk execution time is shown also below guicey.
* <p>
* Installers implementing {@link JerseyInstaller} are executed (also) as part of jersey context startup
* and so reported separately.
*
* @author Vyacheslav Rusakov
* @since 28.07.2016
*/
@Singleton
@SuppressFBWarnings("RV_RETURN_VALUE_IGNORED_INFERRED")
public class StatsRenderer implements ReportRenderer<Boolean> {
private final GuiceyConfigurationInfo info;
@Inject
public StatsRenderer(final GuiceyConfigurationInfo info) {
this.info = info;
}
/**
* @param hideTiny hide sections with time less then 1ms
* @return rendered statistics report
*/
@Override
public String renderReport(final Boolean hideTiny) {
final TreeNode root = new TreeNode("GUICEY started in %s", info.getStats().humanTime(GuiceyTime));
renderTimes(root, hideTiny);
final StringBuilder res = new StringBuilder().append(NEWLINE).append(NEWLINE);
root.render(res);
return res.toString();
}
private void renderTimes(final TreeNode root, final boolean hideTiny) {
long remaining = info.getStats().time(GuiceyTime);
final double percent = remaining / 100d;
remaining -= renderClasspathScanInfo(root, hideTiny, percent);
remaining -= renderBundlesProcessing(root, hideTiny, percent);
remaining -= renderCommandsRegistration(root, hideTiny, percent);
remaining -= renderInstallersRegistration(root, hideTiny, percent);
remaining -= renderExtensionsRegistration(root, hideTiny, percent);
remaining -= renderInjectorCreation(root, percent);
remaining -= renderJerseyPart(root, hideTiny, percent);
if (show(hideTiny, remaining)) {
root.child("[%.2g%%] remaining %s ms", remaining / percent, remaining);
}
}
private long renderClasspathScanInfo(final TreeNode root, final boolean hideTiny, final double percent) {
final long scan = info.getStats().time(ScanTime);
if (show(hideTiny, scan)) {
final TreeNode node = root.child("[%.2g%%] CLASSPATH scanned in %s",
scan / percent, info.getStats().humanTime(ScanTime));
final int classes = info.getStats().count(ScanClassesCount);
node.child("scanned %s classes", classes);
final int recognized = info.getData().getItems(Filters.fromScan()).size();
node.child("recognized %s classes (%.2g%% of scanned)",
recognized, recognized / (classes / 100f));
}
return scan;
}
private long renderBundlesProcessing(final TreeNode root, final boolean hideTiny, final double percent) {
final long bundle = info.getStats().time(BundleTime);
if (show(hideTiny, bundle)) {
final TreeNode node = root.child("[%.2g%%] BUNDLES processed in %s",
bundle / percent, info.getStats().humanTime(BundleTime));
// if no bundles were actually resolved, resolution time would be tiny
final long resolved = info.getStats().time(BundleResolutionTime);
if (show(hideTiny, resolved)) {
node.child("%s resolved in %s",
info.getBundlesFromLookup().size(),
info.getStats().humanTime(BundleResolutionTime));
}
node.child("%s processed", info.getBundles().size());
}
return bundle;
}
private long renderCommandsRegistration(final TreeNode root, final boolean hideTiny, final double percent) {
final long command = info.getStats().time(CommandTime);
// most likely if commands search wasn't register then processing time will be less then 1 ms and so
// no commands processing will be shown
if (show(hideTiny, command)) {
final TreeNode node = root.child("[%.2g%%] COMMANDS processed in %s",
command / percent, info.getStats().humanTime(CommandTime));
final int registered = info.getCommands().size();
if (registered > 0) {
node.child("registered %s commands", registered);
}
}
return command;
}
private long renderInstallersRegistration(final TreeNode root, final boolean hideTiny, final double percent) {
final long installers = info.getStats().time(InstallersTime);
if (show(hideTiny, installers)) {
final TreeNode node = root.child("[%.2g%%] INSTALLERS initialized in %s",
installers / percent, info.getStats().humanTime(InstallersTime));
final int registered = info.getInstallers().size();
if (registered > 0) {
node.child("registered %s installers", registered);
}
}
return installers;
}
private long renderExtensionsRegistration(final TreeNode root, final boolean hideTiny, final double percent) {
final long extensions = info.getStats().time(ExtensionsRecognitionTime);
if (show(hideTiny, extensions)) {
final TreeNode node = root.child("[%.2g%%] EXTENSIONS initialized in %s",
extensions / percent, info.getStats().humanTime(ExtensionsRecognitionTime));
final int manual = info.getExtensions().size() - info.getExtensionsFromScan().size();
node.child("from %s classes", info.getStats().count(ScanClassesCount) + manual);
}
return extensions;
}
private long renderInjectorCreation(final TreeNode root, final double percent) {
final long injector = info.getStats().time(InjectorCreationTime);
final TreeNode node = root.child("[%.2g%%] INJECTOR created in %s",
injector / percent, info.getStats().humanTime(InjectorCreationTime));
node.child("from %s guice modules", info.getModules().size());
node.child("%s extensions installed in %s", info.getExtensions().size(),
info.getStats().humanTime(ExtensionsInstallationTime));
return injector;
}
private long renderJerseyPart(final TreeNode root, final boolean hideTiny, final double percent) {
final long hk = info.getStats().time(JerseyTime);
if (show(hideTiny, hk)) {
final TreeNode node = root.child("[%.2g%%] JERSEY bridged in %s",
hk / percent, info.getStats().humanTime(JerseyTime));
final int installers = info.getData()
.getItems(ConfigItem.Installer, it -> JerseyInstaller.class.isAssignableFrom(it.getType())).size();
if (installers > 0) {
node.child("using %s jersey installers", installers);
final int extensions = info.getData()
.getItems(ConfigItem.Extension, (ExtensionItemInfo it) -> it.isEnabled()
&& JerseyInstaller.class.isAssignableFrom(it.getInstalledBy())).size();
node.child("%s jersey extensions installed in %s",
extensions, info.getStats().humanTime(JerseyInstallerTime));
}
}
return hk;
}
private boolean show(final boolean hideTiny, final long value) {
return !hideTiny || value > 0;
}
}
|
package de.haydin.model.entities;
import java.io.Serializable;
import java.util.Date;
/**
*
* @author aydins
*/
public class DataJoke implements Serializable {
int joke_id;
String category;
int user_id;
String date;
String joke;
short rating;
int numRating;
int numComments;
boolean active;
short bewertungVon;
public DataJoke() {
}
public DataJoke(int joke_id, String category, int user_id, String date, String joke, short rating, int numRating, int numComments, boolean active, short bewertungVon) {
this.joke_id = joke_id;
this.category = category;
this.user_id = user_id;
this.date = date;
this.joke = joke;
this.rating = rating;
this.numRating = numRating;
this.numComments = numComments;
this.active = active;
this.bewertungVon = bewertungVon;
}
public DataJoke(Object[] list) {
this.joke_id = Integer.parseInt((String) list[0]);
this.category = (String) list[1];
this.user_id = Integer.parseInt((String) list[2]);
this.date = (String) list[3];
this.joke = (String) list[4];
this.numRating = Integer.parseInt((String) list[5]);
this.rating = Short.parseShort((String) list[6]);
this.active = Boolean.parseBoolean((String) list[7]);
}
public int getJoke_id() {
return joke_id;
}
public void setJoke_id(int joke_id) {
this.joke_id = joke_id;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public void setDate(Date date) {
this.date = date == null ? "" : date.toString();
}
public String getJoke() {
return joke;
}
public void setJoke(String joke) {
this.joke = joke;
}
public short getRating() {
return rating;
}
public void setRating(short rating) {
this.rating = rating;
}
public int getNumRating() {
return numRating;
}
public void setNumRating(int numRating) {
this.numRating = numRating;
}
public int getNumComments() {
return numComments;
}
public void setNumComments(int numComments) {
this.numComments = numComments;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public short getBewertungVon() {
return bewertungVon;
}
public void setBewertungVon(short bewertungVon) {
this.bewertungVon = bewertungVon;
}
@Override
public String toString() {
return "DataWitz [joke_id=" + joke_id + ", category=" + category + ", user_id=" + user_id +
", date=" + date + ", joke=" + joke + ", rating=" + rating + ", numRating=" + numRating +
", numComments=" + numComments + ", active=" + active + ", bewertungVon=" + bewertungVon + "]";
}
}
|
package nl.guuslieben.circle.persistence;
import org.springframework.data.repository.CrudRepository;
public interface UserRepository extends CrudRepository<PersistentUser, String> {
}
|
package com.oracle.iot.sample.mydriveapp.service;
import android.app.Notification;
import android.app.PendingIntent;
import android.arch.lifecycle.LifecycleService;
import android.arch.lifecycle.Observer;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.SensorManager;
import android.location.Location;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.NotificationCompat;
import com.oracle.iot.sample.mydriveapp.R;
import com.oracle.iot.sample.mydriveapp.activity.HomeActivity;
import com.oracle.iot.sample.mydriveapp.prefs.Constants;
import com.oracle.iot.sample.mydriveapp.prefs.PrefUtils;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import static java.lang.Math.abs;
public class VehicleTrackerService extends LifecycleService {
AccelerationData mAccelerationData;
GPSData gpsData;
CargoData mCargoData;
private volatile float[] mAccelerationValues;
private volatile float[] mCargoDataValues;
private double mSpeed; //In KM/H
private Location mLocation;
private Location mStartLocation;
private long mTripStartTime, mEngineONDuration; //mEngineONDuration in seconds
private double mDistanceSinceEngineON = 0; //In KM
private double mOdometerValue; //In KM
private double mFuelEconomyValue;
private double mFuelConsumed;
private boolean overSpeedAlert = false;
private Location overSpeedStartLocation = new Location ("overspeedingstart");
private boolean idlingAlert = false;
private long idlingStartTime;
//Threshold preference settings
double mManeuveringAccelerationThreshold, mOverspeedingThreshold, mIdlingTimeThreshold;
int mOrientationPref = 0;
private Timer timer;
private TimerTask timerTask;
public static boolean IS_SERVICE_RUNNING = false;
public static final String ACTION_LOCATION_BROADCAST = "LocationBroadcast";
public static final String ACTION_ACCELERATION_BROADCAST = "AccelerationBroadcast";
public static final String ACTION_CARGODATA_BROADCAST = "CargoDataBroadcast";
public static final String ACTION_ALERT = "DriverAlertBroadcast";
public static final String EXTRA_ACCELVALUES = "accel_values";
public static final String EXTRA_CARGODATAVALUES = "cargo_values";
public static final String EXTRA_LOCATIONVALUES = "location_values";
public static final String EXTRA_ALERTTYPE = "alert_type";
public static final String EXTRA_ALERTVALUE = "alert_value";
private OracleIoTCloudPublisher mOracleIoTCloudPublisher;
public static final String EVENT_HARSHBRAKING = "harshBraking";
public static final String EVENT_HARSHACCLERATION = "harshAccleration";
public static final String EVENT_OVERSPEEDING = "overSpeeding";
public static final String EVENT_OVERIDLING = "overIdling";
public static final String EVENT_HARSHCORNERING = "harshCornering";
private long previousBrakingTimestamp, previousAccleratingTimestamp, previousCorneringTimestamp = 0;
public VehicleTrackerService() {
super();
mAccelerationValues = new float[3];
}
public VehicleTrackerService(Context applicationContext) {
super();
mAccelerationValues = new float[3];
}
@Override
public void onCreate(){
super.onCreate();
mAccelerationValues = new float [3];
mCargoDataValues = new float [5];
mLocation = new Location("Dummy");
//mLocation = null;
mOracleIoTCloudPublisher = new OracleIoTCloudPublisher(this);
setupLocationUpdates();
setupAccelerationUpdates();
setupCargoDataUpdates();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
super.onBind(intent);
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
IS_SERVICE_RUNNING = true;
showForegroundServiceNotification();
readDrivingPreferences();
startTimerForIoTCloudSync();
} else if (intent.getAction().equals(Constants.ACTION.STOPFOREGROUND_ACTION)) {
stopForeground(true);
IS_SERVICE_RUNNING = false;
stopSelf();
}
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
PrefUtils.setOdometerValue(getApplicationContext(), Double.toString(mOdometerValue));
gpsData.removeUpdates();
mCargoData.removeUpdates();
mAccelerationData.removeUpdates();
mOracleIoTCloudPublisher.cleanup();
stopTimerTask();
}
public void onLocationChanged(Location newLoc) {
mLocation = newLoc;
calculateTripDistanceAndTime();
broadcastUpdate(ACTION_LOCATION_BROADCAST);
checkSpeedBehavior();
}
public void onAccelerationChanged(float[] accelerationValues) {
synchronized (mAccelerationValues) {
System.arraycopy(accelerationValues, 0, mAccelerationValues, 0, accelerationValues.length);
broadcastUpdate(ACTION_ACCELERATION_BROADCAST);
checkAccelerationBehavior();
}
}
public void onCargoDataChanged(float[] values) {
synchronized (mCargoDataValues) {
System.arraycopy(values, 0, mCargoDataValues, 0, values.length);
broadcastUpdate(ACTION_CARGODATA_BROADCAST);
}
}
private void startTimerForIoTCloudSync() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//schedule the timer, to wake up every 10 second
//timer.schedule(timerTask, 5000, 10000);
int freqSeconds = PrefUtils.getIoTDataMessageFrequency(getApplicationContext());
timer.schedule(timerTask, 5000, freqSeconds * 1000);
}
private void initializeTimerTask(){
timerTask = new TimerTask() {
boolean isSetupIoTCloud = false;
public void run() {
if(!isSetupIoTCloud){
isSetupIoTCloud = mOracleIoTCloudPublisher.setupIoTCloudConnect();
}
if(isSetupIoTCloud){
Properties vehicleMessageValues = new Properties();
vehicleMessageValues.put(Constants.SPEED_ATTRIBUTE, String.valueOf(mSpeed));
vehicleMessageValues.put(Constants.TIME_SINCE_ENGINE_START, String.valueOf(mEngineONDuration));
vehicleMessageValues.put(Constants.ODOMETER_VALUE, String.valueOf(mOdometerValue));
vehicleMessageValues.put(Constants.FUEL_CONSUMED, String.valueOf(mFuelConsumed));
vehicleMessageValues.put(Constants.LATITUDE_ATTRIBUTE, String.valueOf(mLocation.getLatitude()));
vehicleMessageValues.put(Constants.LONGITUDE_ATTRIBUTE, String.valueOf(mLocation.getLongitude()));
Properties cargoMessageValues = new Properties();
cargoMessageValues.put(Constants.CARGO_TEMP_VALUE, String.valueOf(mCargoDataValues[0]));
cargoMessageValues.put(Constants.CARGO_HUMIDITY_VALUE, String.valueOf(mCargoDataValues[1]));
cargoMessageValues.put(Constants.CARGO_LIGHT_VALUE, String.valueOf(mCargoDataValues[2]));
cargoMessageValues.put(Constants.CARGO_PRESSURE_VALUE, String.valueOf(mCargoDataValues[3]));
cargoMessageValues.put(Constants.CARGO_PROXIMITY_VALUE, String.valueOf(mCargoDataValues[4]));
//Check if we have a valid location fix and send the device message to cloud
if(!(mLocation.getLatitude() == 0 && mLocation.getLongitude() == 0)){
mOracleIoTCloudPublisher.sendDeviceDataMessagesToCloud(Constants.IOT_VEHICLE_MESSAGE_TYPE, vehicleMessageValues);
mOracleIoTCloudPublisher.sendDeviceDataMessagesToCloud(Constants.IOT_CARGO_MESSAGE_TYPE, cargoMessageValues);
}
}
}
};
}
private void stopTimerTask() {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer = null;
}
}
private void calculateTripDistanceAndTime(){
if(mStartLocation == null) {
mStartLocation = mLocation;
mTripStartTime = System.currentTimeMillis();
}
double distanceBetweenLocationPings = (mStartLocation.distanceTo(mLocation))/1000; //distance in KM
long mTimeBetweenLocationPings = (mLocation.getTime() - mStartLocation.getTime())/1000; //time in sec
mFuelConsumed = distanceBetweenLocationPings/mFuelEconomyValue;
/*
if (!mLocation.hasSpeed()){
if(mTimeBetweenLocationPings != 0){
mSpeed = (mDistanceBetweenLocationPings/mTimeBetweenLocationPings)*3.6;
}
} else {
mSpeed = mLocation.getSpeed()*3.6;
}
*/
//Convert from m/s to km/h
mSpeed = mLocation.getSpeed()*3.6;
mDistanceSinceEngineON = mDistanceSinceEngineON + distanceBetweenLocationPings;
mStartLocation = mLocation;
mOdometerValue = mOdometerValue + distanceBetweenLocationPings;
mEngineONDuration = System.currentTimeMillis() - mTripStartTime;
mEngineONDuration = TimeUnit.MILLISECONDS.toSeconds(mEngineONDuration);
}
private void broadcastUpdate(final String action, String... more ) {
Intent intent = new Intent(action);
switch(action){
case ACTION_LOCATION_BROADCAST:
double [] locValues = new double [7];
locValues[0] = mSpeed;
locValues[1] = mLocation.getLatitude();
locValues[2] = mLocation.getLongitude();
locValues[3] = mOdometerValue;
locValues[4] = mDistanceSinceEngineON;
locValues[5] = mEngineONDuration;
locValues[6] = mFuelConsumed;
intent.putExtra(EXTRA_LOCATIONVALUES, locValues);
break;
case ACTION_ACCELERATION_BROADCAST:
intent.putExtra(EXTRA_ACCELVALUES, mAccelerationValues);
break;
case ACTION_CARGODATA_BROADCAST:
intent.putExtra(EXTRA_CARGODATAVALUES, mCargoDataValues);
break;
case ACTION_ALERT :
String alertType = (more.length < 1) ? "" : more[0];
intent.putExtra(EXTRA_ALERTTYPE, alertType);
break;
}
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
private void setupAccelerationUpdates(){
mAccelerationData = new AccelerationData(getApplicationContext());
updateAccelerationConfiguration();
mAccelerationData.getLiveData().observe(this, new Observer<float[]>() {
@Override
public void onChanged(@Nullable float[] accelValues) {
onAccelerationChanged(accelValues);
}
});
}
private void setupLocationUpdates() {
gpsData = new GPSData(this);
gpsData.getLocation().observe(this, new Observer<Location>() {
@Override
public void onChanged(@Nullable Location location) {
onLocationChanged(location);
}
});
}
private void setupCargoDataUpdates(){
mCargoData = new CargoData(this);
mCargoData.getLiveData().observe(this, new Observer<float[]>() {
@Override
public void onChanged(@Nullable float [] values) {
onCargoDataChanged (values);
}
});
}
private void checkSpeedBehavior (){
//Over idling Alert
if (mSpeed < Constants.IDLING_SPEED){
if (!idlingAlert){
idlingAlert = true;
idlingStartTime = mLocation.getTime();
}
} else{
if (idlingAlert) {
long idlingTime = mLocation.getTime() - idlingStartTime;
//if (idlingTime > Constants.IDLING_TIME_LIMIT) {
if (idlingTime > mIdlingTimeThreshold) {
mOracleIoTCloudPublisher.sendDeviceAlertMessagesToCloud(EVENT_OVERIDLING, idlingTime/1000);
broadcastUpdate(ACTION_ALERT, EVENT_OVERIDLING);
}
idlingAlert = false;
}
}
//Over speeding Alert
//if (mSpeed > Constants.SPEED_LIMIT){
if (mSpeed > mOverspeedingThreshold){
if (!overSpeedAlert){
overSpeedAlert = true;
overSpeedStartLocation = mLocation;
}
} else{
if (overSpeedAlert) {
double distanceInOverSpeed = (overSpeedStartLocation.distanceTo(mLocation))/1000; //Overspeeding distance in KM
mOracleIoTCloudPublisher.sendDeviceAlertMessagesToCloud(EVENT_OVERSPEEDING, distanceInOverSpeed);
broadcastUpdate(ACTION_ALERT, EVENT_OVERSPEEDING);
overSpeedAlert = false;
}
}
}
private void checkAccelerationBehavior(){
/*
double totalAcceleration = Math.sqrt(Math.pow(mAccelerationValues[0], 2)
+ Math.pow(mAccelerationValues[1], 2)
+ Math.pow(mAccelerationValues[2], 2));
*/
if (mAccelerationValues[2] > mManeuveringAccelerationThreshold){
long latestBrakingTimestamp = System.currentTimeMillis();
if (((latestBrakingTimestamp - previousBrakingTimestamp) < 3000) ||
((latestBrakingTimestamp - previousAccleratingTimestamp) < 3000)){
//drop the message
} else {
mOracleIoTCloudPublisher.sendDeviceAlertMessagesToCloud(EVENT_HARSHBRAKING, mAccelerationValues[2]);
broadcastUpdate(ACTION_ALERT, EVENT_HARSHBRAKING);
}
previousBrakingTimestamp = latestBrakingTimestamp;
}
if (mAccelerationValues[2] < (mManeuveringAccelerationThreshold * -1)){
long latestAccleratingTimestamp = System.currentTimeMillis();
if (((latestAccleratingTimestamp - previousAccleratingTimestamp) < 3000) ||
((latestAccleratingTimestamp - previousBrakingTimestamp) < 3000)){
//drop the message
} else {
mOracleIoTCloudPublisher.sendDeviceAlertMessagesToCloud(EVENT_HARSHACCLERATION, mAccelerationValues[2]);
broadcastUpdate(ACTION_ALERT, EVENT_HARSHACCLERATION);
}
previousAccleratingTimestamp = latestAccleratingTimestamp;
}
float corneringAxis = mAccelerationValues[0];
if(mOrientationPref == Constants.LANDSCAPE)
corneringAxis = mAccelerationValues[1];
if (abs(corneringAxis) > mManeuveringAccelerationThreshold){
long latestCorneringTimestamp = System.currentTimeMillis();
if ((latestCorneringTimestamp - previousCorneringTimestamp) < 3000){
//drop the message
} else {
mOracleIoTCloudPublisher.sendDeviceAlertMessagesToCloud(EVENT_HARSHCORNERING, corneringAxis);
broadcastUpdate(ACTION_ALERT, EVENT_HARSHCORNERING);
}
previousCorneringTimestamp = latestCorneringTimestamp;
}
}
private void readDrivingPreferences(){
mManeuveringAccelerationThreshold = PrefUtils.getManeuveringAccelerationThreshold(getApplicationContext());
mOverspeedingThreshold = PrefUtils.getSpeedingThreshold(getApplicationContext());
mOverspeedingThreshold = PrefUtils.getSpeedingThreshold(getApplicationContext());
mIdlingTimeThreshold = PrefUtils.getIdlingTimeThreshold(getApplicationContext()) * 60 * 1000; //minutes converted to milliseconds
mOrientationPref = PrefUtils.getPhoneOrientationPrefs(getApplicationContext());
mOdometerValue = Double.valueOf(PrefUtils.getOdometerValue(getApplicationContext()));
mFuelEconomyValue = Double.valueOf(PrefUtils.getFuelEconomyValue(getApplicationContext()));
}
private void updateAccelerationConfiguration() {
mAccelerationData.setSensorFrequency(SensorManager.SENSOR_DELAY_NORMAL);
mAccelerationData.setAxisInverted(false);
mAccelerationData.enableLinearAcceleration(true);
mAccelerationData.setLinearAccelerationTimeConstant(0.5f);
mAccelerationData.enableLowPassFiltering(true);
mAccelerationData.setLowPassFilterSmoothingTimeConstant(0.5f);
}
private void showForegroundServiceNotification() {
Intent notificationIntent = new Intent(this, HomeActivity.class);
notificationIntent.setAction(Constants.ACTION.MAIN_ACTION);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Intent stopIntent = new Intent(this, VehicleTrackerService.class);
stopIntent.setAction(Constants.ACTION.STOPFOREGROUND_ACTION);
PendingIntent pStopIntent = PendingIntent.getService(this, 0,
stopIntent, 0);
Bitmap icon = BitmapFactory.decodeResource(getResources(),
R.drawable.iot_fm);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("MyDrive App")
.setTicker("MyDrive App")
.setContentText("Vehicle Tracker Service is Running")
.setSmallIcon(R.drawable.iot_fm)
//.setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
.setContentIntent(pendingIntent)
.setOngoing(true)
.addAction(android.R.drawable.ic_lock_power_off, "Stop Service",
pStopIntent).build();
startForeground(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE, notification);
}
}
|
package com.pooyaco.person.bs;
import com.pooyaco.gazelle.bs.BaseServiceImpl;
import com.pooyaco.person.da.PersonDao;
import com.pooyaco.person.dto.PersonDto;
import com.pooyaco.person.entity.Person;
import com.pooyaco.person.si.PersonService;
import org.springframework.stereotype.Service;
/**
* Created with IntelliJ IDEA.
* User: h.rostami
* Date: 28/01/15
* Time: 02:44 م
* To change this template use File | Settings | File Templates.
*/
@Service
public class PersonServiceImpl extends BaseServiceImpl<PersonDto, Person, PersonDao> implements PersonService<PersonDto> {
}
|
package com.dassa.service;
import java.util.ArrayList;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.dassa.mapper.FaqMapper;
import com.dassa.vo.FaqPageData;
import com.dassa.vo.FaqVO;
import com.dassa.vo.NoticePageData;
import com.dassa.vo.NoticeVO;
import com.dassa.vo.SearchNoticeVO;
@Service("faqService")
public class FaqService {
@Resource(name="faqMapper")
private FaqMapper faqMapper;
public FaqPageData selectAllList(int reqPage, int code) throws Exception {
//페이지 당 게시물 수
int numPerPage = 5;
//총 게시물 수 구하기
int totalCount = faqMapper.totalCount(code);
//총 페이지 수 구하기
int totalPage = (totalCount%numPerPage==0)?(totalCount/numPerPage):(totalCount/numPerPage)+1;
//요청 페이지의 시작 게시물 번호와 끝 게시물 번호 구하기
//시작 게시물 번호
int start = (reqPage-1)*numPerPage +1;
int end = reqPage*numPerPage;
System.out.println(start+"/"+end);
ArrayList<FaqVO> list = faqMapper.selectAllList(start,end,code);
System.out.println("서비스list-"+list);
//페이지 네비 작성
String pageNavi = "";
//페이지 네비의 수
int pageNaviSize = 5;
//페이지 번호
int pageNo = ((reqPage-1)/pageNaviSize)*pageNaviSize+1;
//이전 버튼 생성
if(pageNo !=1) {
if(code==1) { //부동산이면
pageNavi += "<li class='prev arrow'>";
pageNavi += "<a href='/manage/board/faq/faqManageList?reqPage="+(pageNo-1)+"&code=1'>이전</a>";
pageNavi += "</li>";
}else if(code==2) { //기사면
pageNavi += "<li class='prev arrow'>";
pageNavi += "<a href='/manage/board/faq/faqManageList?reqPage="+(pageNo-1)+"&code=2'>이전</a>";
pageNavi += "</li>";
}else { //회원문의면
pageNavi += "<li class='prev arrow'>";
pageNavi += "<a href='/manage/board/faq/faqManageList?reqPage="+(pageNo-1)+"'>이전</a>";
pageNavi += "</li>";
}
}
//페이지 번호 버튼 생성 ( 1 2 3 4 5 )
int i = 1;
while( !(i++>pageNaviSize || pageNo>totalPage) ) { //둘 중 하나라도 만족하면 수행하지 않겠다
if(reqPage == pageNo) {
pageNavi += "<li class='on'>";
pageNavi += "<a>"+pageNo+"</a>"; //4페이지 상태에서 4페이지를 누를수가 없도록 하기 위해서 a태그 없애줌
pageNavi += "</li>";
}else {
if(code==1) { //부동산이면
pageNavi += "<li class=''>";
pageNavi += "<a href='/manage/board/faq/faqManageList?reqPage="+pageNo+"&code=1'>"+pageNo+"</a>";
pageNavi += "</li>";
}else if(code==2) { //기사면
pageNavi += "<li class=''>";
pageNavi += "<a href='/manage/board/faq/faqManageList?reqPage="+pageNo+"&code=2'>"+pageNo+"</a>";
pageNavi += "</li>";
}else { //회원문의면
pageNavi += "<li class=''>";
pageNavi += "<a href='/manage/board/faq/faqManageList?reqPage="+pageNo+"'>"+pageNo+"</a>";
pageNavi += "</li>";
}
}
pageNo++;
}
//다음 버튼 생성
if(pageNo <= totalPage) {
if(code==1) { //부동산이면
pageNavi += "<li class='next arrow'>";
pageNavi +="<a href='/manage/board/faq/faqManageList?reqPage="+pageNo+"&code=1'>다음</a>";
pageNavi += "</li>";
}else if(code==2) { //기사면
pageNavi += "<li class='next arrow'>";
pageNavi +="<a href='/manage/board/faq/faqManageList?reqPage="+pageNo+"&code=2'>다음</a>";
pageNavi += "</li>";
}else { //회원문의면
pageNavi += "<li class='next arrow'>";
pageNavi +="<a href='/manage/board/faq/faqManageList?reqPage="+pageNo+"'>다음</a>";
pageNavi += "</li>";
}
}
FaqPageData pd = new FaqPageData(list,pageNavi);
System.out.println("서비스pd-"+pd);
return pd;
}
//하나에 정보를 상세보기
public FaqVO faqView(int faqIndex) throws Exception {
return faqMapper.faqView(faqIndex);
}
//업데이트
public int faqUpdate(FaqVO f) throws Exception{
System.out.println("서비스업데이트-"+f);
return faqMapper.faqUpdate(f);
}
//인서트
public int faqInsert(FaqVO f) throws Exception{
return faqMapper.faqInsert(f);
}
//삭제
public int faqDelete(int faqIndex) throws Exception {
return faqMapper.faqDelete(faqIndex);
}
//faq검색
public FaqPageData searchKeyword(int reqPage, SearchNoticeVO s) throws Exception {
int numPerPage = 5;
int totalCount = faqMapper.titleCount(s);
System.out.println("서비스 토탈 : "+totalCount);
int totalPage = (totalCount%numPerPage==0)?(totalCount/numPerPage):(totalCount/numPerPage)+1;;
int start = (reqPage-1)*numPerPage+1;;
int end = reqPage*numPerPage;
int code=s.getCode();
s.setStart(start);
s.setEnd(end);
ArrayList<FaqVO> list = faqMapper.searchKeywordTitle(s);
System.out.println("서비스-"+list.size());
String pageNavi = "";
int pageNaviSize = 5;
int pageNo = ((reqPage-1)/pageNaviSize)*pageNaviSize+1;
if(pageNo !=1) {
if(code==1) { //부동산이면
pageNavi += "<li class='prev arrow'>";
pageNavi += "<a href='/manage/board/faq/faqManageList?reqPage="+(pageNo-1)+"&code=1&keyword="+s.getKeyWord()+"'>이전</a>";
pageNavi += "</li>";
}else if(code==2) { //기사면
pageNavi += "<li class='prev arrow'>";
pageNavi += "<a href='/manage/board/faq/faqManageList?reqPage="+(pageNo-1)+"&code=2&keyword="+s.getKeyWord()+"'>이전</a>";
pageNavi += "</li>";
}else { //사용자면
pageNavi += "<li class='prev arrow'>";
pageNavi += "<a href='/manage/board/faq/faqManageList?reqPage="+(pageNo-1)+"&keyword="+s.getKeyWord()+"'>이전</a>";
pageNavi += "</li>";
}
}
//페이지 번호 버튼 생성 ( 1 2 3 4 5 )
int i = 1;
while( !(i++>pageNaviSize || pageNo>totalPage) ) { //둘 중 하나라도 만족하면 수행하지 않겠다
if(reqPage == pageNo) {
pageNavi += "<li class='on'>";
pageNavi += "<a>"+pageNo+"</a>"; //4페이지 상태에서 4페이지를 누를수가 없도록 하기 위해서 a태그 없애줌
pageNavi += "</li>";
}else {
if(code==1) { //부동산이면
pageNavi += "<li class=''>";
pageNavi += "<a href='/manage/board/faq/faqManageList?reqPage="+pageNo+"&code=1&keyword="+s.getKeyWord()+"'>"+pageNo+"</a>";
pageNavi += "</li>";
}else if(code==2) { //기사면
pageNavi += "<li class=''>";
pageNavi += "<a href='/manage/board/faq/faqManageList?reqPage="+pageNo+"&code=2&keyword="+s.getKeyWord()+"'>"+pageNo+"</a>";
pageNavi += "</li>";
}else { //사용자면
pageNavi += "<li class=''>";
pageNavi += "<a href='/manage/board/faq/faqManageList?reqPage="+pageNo+"&keyword="+s.getKeyWord()+"'>"+pageNo+"</a>";
pageNavi += "</li>";
}
}
pageNo++;
}
//다음 버튼 생성
if(pageNo <= totalPage) {
if(code==1) {//부동산이면
pageNavi += "<li class='next arrow'>";
pageNavi +="<a href='/manage/board/faq/faqManageList?reqPage="+pageNo+"&code=1&keyword="+s.getKeyWord()+"'>다음</a>";
pageNavi += "</li>";
}else if(code==2) {//기사면
pageNavi += "<li class='next arrow'>";
pageNavi +="<a href='/manage/board/faq/faqManageList?reqPage="+pageNo+"&code=2&keyword="+s.getKeyWord()+"'>다음</a>";
pageNavi += "</li>";
}else {//사용자면
pageNavi += "<li class='next arrow'>";
pageNavi +="<a href='/manage/board/faq/faqManageList?reqPage="+pageNo+"&keyword="+s.getKeyWord()+"'>다음</a>";
pageNavi += "</li>";
}
}
FaqPageData pd = new FaqPageData(list,pageNavi);
return pd;
}
}
|
package com.beike.dao.adweb;
import com.beike.common.entity.adweb.AdWeb;
import com.beike.dao.GenericDao;
/**
* <p>Title:广告联盟 </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2011</p>
* <p>Company: Sinobo</p>
* @date Feb 29, 2012
* @author ye.tian
* @version 1.0
*/
public interface AdWebDao extends GenericDao<AdWeb, Long>{
/**
* 根据web
* @param code
* @return
*/
public AdWeb getAdWebByCode(String code);
}
|
package pers.mine.scratchpad;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.http.HttpUtil;
import java.net.http.HttpClient;
public class Application {
public static void main(String[] args) throws InterruptedException {
Thread.UncaughtExceptionHandler ueh = (t, e) -> {
String msg = "ueh thread: %s ,target thread: %s \n %s"
.formatted(Thread.currentThread(), t, ExceptionUtil.stacktraceToString(e));
System.err.println(msg);
};
Runnable r = () -> {
System.out.println(Thread.currentThread());
throw new IllegalArgumentException();
};
Thread pThread = Thread.ofPlatform().uncaughtExceptionHandler(ueh).unstarted(r);
Thread vThread = Thread.ofVirtual().uncaughtExceptionHandler(ueh).unstarted(r);
pThread.start();
vThread.start();
pThread.join();
vThread.join();
Thread.sleep(10);
System.out.println("end");
}
}
|
package controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/search/")
public class SearchController {
ModelAndView mv = new ModelAndView();
@RequestMapping("search")
public ModelAndView search() {
mv.setViewName("search/search");
return mv;
}
}
|
package com.pawelv.basecrm.model;
import java.util.List;
import junit.framework.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class MainPage {
protected static WebDriver driver;
// navigation
@FindBy(css = "a#nav-leads")
private WebElement navLeads;
// new lead items
@FindBy(css = "input#lead-first-name")
private WebElement newLead_FirstName;
@FindBy(css = "input#lead-last-name")
private WebElement newLead_LastName;
@FindBy(css = "input#lead-company-name")
private WebElement newLead_CompanyName;
@FindBy(css = "div.tags-field input")
private WebElement newLead_Tag;
public static final String newLead_SaveButton_Locator = "div.edit-toolbar a.save";
//@FindBy(css = newLead_SaveButton_Locator)
//private WebElement newLead_SaveButton;
// lead detail items
@FindBy(css = "h1 span.detail-title")
private WebElement leadDetail_title;
//settings leads
public static final String prefsStatus_first_Locator = "button.edit:eq(0)";
//@FindBy(css = prefsStatus_first_Locator)
//private WebElement prefsStatus_firstButton;
@FindBy(css = "div#lead-status input#name")
private WebElement prefsStatus;
public static final String prefsStatusSave_Locator = "div#lead-status button.save:eq(0)";
//@FindBy(css = prefsStatusSave_Locator)
//private WebElement prefsStatusSave;
// leads - main list
public static final String leadsFilter_header="ul.filter-categories li.status-filter a.filter-heading";
@FindBy(css = "span.term-filter input")
private WebElement LeadsFilterInput;
// assume that it would be only element given random first lead name
public static final String LeadsFirstResultName_Locator="ul.leads h3 a";
@FindBy(css = LeadsFirstResultName_Locator)
private WebElement LeadsFirstResultName;
@FindBy(css = "ul.object-details span.lead-status")
private WebElement LeadsDetailsStatus;
// static
public static final String LEADS_URL = "https://app.futuresimple.com/leads";
public static final String NEW_LEADS_URL = "https://app.futuresimple.com/leads/new";
public static final String PREFS_LEADS_STATUS_URL = "https://app.futuresimple.com/settings/leads/lead-status";
public MainPage(WebDriver driver) {
MainPage.driver = driver;
}
private void openPrefsLeadsStatus() {
driver.navigate().to(PREFS_LEADS_STATUS_URL);
(new WebDriverWait(driver, 10)).until(new
ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) {
return d.getTitle().toLowerCase().contains("customize leads"); } });
}
private void openLead() {
driver.navigate().to(LEADS_URL);
(new WebDriverWait(driver, 10)).until(new
ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) {
return d.getTitle().toLowerCase().contains("leads"); } });
}
private void openNewLead() {
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.visibilityOf(navLeads));
driver.navigate().to(NEW_LEADS_URL);
(new WebDriverWait(driver, 10)).until(new
ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) {
return d.getTitle().toLowerCase().contains("leads"); } });
}
public static void selectValue(String valToBeSelected) {
List<WebElement> options = driver.findElements(By.tagName("option"));
for (WebElement option : options) {
if (valToBeSelected.equalsIgnoreCase(option.getText())) {
option.click();
}
}
}
// jQuery click()
private void jClick(String csslocator) {
((JavascriptExecutor) driver).executeScript("$('" + csslocator
+ "').click()");
}
/*private void mouseOver(WebElement element) {
String code = "var fireOnThis = arguments[0];"
+ "var evObj = document.createEvent('MouseEvents');"
+ "evObj.initEvent( 'mouseover', true, true );"
+ "fireOnThis.dispatchEvent(evObj);";
((JavascriptExecutor) driver).executeScript(code, element);
}*/
// type new sample lead and save it
public void newSampleLead(final String firstName, String lastName,
String companyName, String tagName) {
openNewLead();
newLead_FirstName.sendKeys(firstName);
newLead_LastName.sendKeys(lastName);
newLead_CompanyName.sendKeys(companyName);
newLead_Tag.sendKeys(tagName);
this.jClick(newLead_SaveButton_Locator);
(new WebDriverWait(driver, 10)).until(new
ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) {
return leadDetail_title.getText().toLowerCase().contains(firstName);
} });
}
// change first status
public void setPrefsStatus(String firstStatusText) {
openPrefsLeadsStatus();
this.jClick(prefsStatus_first_Locator);
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.visibilityOf(prefsStatus));
prefsStatus.clear();
prefsStatus.sendKeys(firstStatusText);
this.jClick(prefsStatusSave_Locator);
}
public void verifyStatus(String status, final String firstNameRandom) {
openLead();
this.jClick(leadsFilter_header);
LeadsFilterInput.sendKeys(firstNameRandom);
// wait until results are shown
(new WebDriverWait(driver, 10)).until(new
ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) {
return LeadsFirstResultName.getText().startsWith(firstNameRandom); } });
// go to details of the lead
this.jClick(LeadsFirstResultName_Locator);
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.visibilityOf(LeadsDetailsStatus));
Assert.assertEquals(status, LeadsDetailsStatus.getText());
}
}
|
package classesState;
import lab6.Pessoa;
public class TomarPrimeiraDose extends EstadoVacinacao {
@Override
public void alteraEstado(Pessoa pessoa) {
pessoa.setEstadoVacinacao(new TomouPrimeiraDose());
pessoa.atualizaEstadoVacina(pessoa);
}
@Override
public String toString() {
return "A pessoa irá tomar a primeira dose.";
}
} |
package com.yunk.stupidcounter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import com.hanks.htextview.evaporate.EvaporateTextView;
import com.hanks.htextview.line.LineTextView;
import mehdi.sakout.fancybuttons.FancyButton;
public class MainActivity extends AppCompatActivity {
EvaporateTextView etv;
FancyButton next, previous, toZero, goToNum;
EditText goToCertainNum, step;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etv = findViewById(R.id.etv_1);
etv.animateText("0");
etv.animate();
next=findViewById(R.id.btn_next);
previous=findViewById(R.id.btn_previous);
toZero=findViewById(R.id.btn_zero);
goToNum=findViewById(R.id.btn_goto);
goToCertainNum=findViewById(R.id.et_gotonum);
step=findViewById(R.id.et_step);
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int currentNum=Integer.parseInt(etv.getText().toString());
currentNum+=Integer.parseInt(step.getText().toString());
etv.animateText(String.valueOf(currentNum));
}
});
previous.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int currentNum=Integer.parseInt(etv.getText().toString());
currentNum--;
etv.animateText(String.valueOf(currentNum));
}
});
toZero.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
etv.animateText("0");
}
});
goToNum.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
etv.animateText(goToCertainNum.getText().toString());
}
});
}
}
|
/**
* Copyright (C) 2008 Atlassian
*
* 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.atlassian.theplugin.idea.jira;
import com.intellij.openapi.ui.DialogWrapper;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import java.awt.*;
import java.util.Calendar;
import java.util.Date;
/**
* @author Jacek Jaroczynski
*/
public class DatePicker extends DialogWrapper implements CaretListener {
private JPanel panel = new JPanel();
private com.michaelbaranov.microba.calendar.DatePicker dateChooser;
private JPanel bottomPanel = new JPanel();
private boolean allowEmptyDate;
public DatePicker(final String title, final Date dateToSelect) {
this(title, dateToSelect, false);
}
public DatePicker(final String title, final Date dateToSelect, boolean allowEmptyDate) {
super(false);
init();
this.allowEmptyDate = allowEmptyDate;
setTitle(title);
createCalendar(dateToSelect);
createPanel();
}
private void createCalendar(final Date dateToSelect) {
// calculate time to midnight
Calendar nowcal = Calendar.getInstance();
nowcal.setTime(dateToSelect);
nowcal.set(Calendar.HOUR_OF_DAY, 12);
nowcal.set(Calendar.MINUTE, 11);
nowcal.set(Calendar.SECOND, 9);
nowcal.set(Calendar.MILLISECOND, 0);
Date nowZeroZero = nowcal.getTime();
dateChooser = new com.michaelbaranov.microba.calendar.DatePicker(nowZeroZero);
}
private void createPanel() {
panel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.CENTER;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
gbc.weightx = 1;
panel.add(new JLabel("Day", SwingConstants.CENTER), gbc);
gbc.gridy = 1;
panel.add(dateChooser, gbc);
gbc.gridy = 2;
panel.add(bottomPanel, gbc);
}
@Override
protected JComponent createCenterPanel() {
return panel;
}
/**
* @return JPanel which can hold additional controls (for inheritance purposes)
*/
protected JPanel getPanelComponent() {
return bottomPanel;
}
/**
* @return Date selected in the calendar control or null if empty
*/
@Nullable
public Date getSelectedDate() {
return dateChooser.getDate();
}
public void caretUpdate(CaretEvent event) {
}
}
|
package com.isg.ifrend.jms;
import java.util.List;
import javax.jms.JMSException;
import com.isg.ifrend.exception.IfrendMLIException;
import com.isg.ifrend.model.mli.account.Account;
import com.isg.ifrend.model.mli.customer.Address;
import com.isg.ifrend.model.mli.customer.Contact;
import com.isg.ifrend.model.mli.customer.Customer;
import com.isg.ifrend.wrapper.mli.request.account.GetAccount;
import com.isg.ifrend.wrapper.mli.request.customer.GetAddress;
import com.isg.ifrend.wrapper.mli.request.customer.GetContactDetail;
import com.isg.ifrend.wrapper.mli.request.customer.GetCustomer;
import com.isg.ifrend.wrapper.mli.request.customer.GetRelationship;
import com.isg.ifrend.wrapper.mli.request.customer.SearchCustomer;
public interface CustomerMLIService {
/**
* @throws JMSException
* @throws IfrendMLIException
*/
public abstract List<Customer> requestSearchCustomer(SearchCustomer wrapper) throws IfrendMLIException, JMSException;
public abstract Customer requestGetCustomer(GetCustomer wrapper) throws IfrendMLIException, JMSException;
public abstract List<Account> requestRelationship(GetRelationship wrapper) throws IfrendMLIException;
public abstract Address requestAddressDetail(GetAddress wrapper) throws IfrendMLIException;
public abstract Contact requestContactDetail(GetContactDetail wrapper) throws IfrendMLIException;
/**
* @throws IfrendMLIException
*/
public abstract Account requestAccount(GetAccount wrapper) throws IfrendMLIException;
}
|
package com.hardcoded.plugin.json;
import java.util.ArrayList;
import java.util.List;
public class JsonArray extends JsonObject {
private final List<Object> array;
public JsonArray() {
array = new ArrayList<>();
}
public JsonObject getJsonObject(int index) {
return (JsonObject)array.get(index);
}
public JsonArray getJsonArray(int index) {
return (JsonArray)array.get(index);
}
public JsonMap getJsonMap(int index) {
return (JsonMap)array.get(index);
}
public Object getObject(int index) {
return array.get(index);
}
public String getString(int index) {
return (String)array.get(index);
}
public Boolean getBoolean(int index) {
return (Boolean)array.get(index);
}
public Long getLong(int index) {
return (Long)array.get(index);
}
public boolean isJsonObject(int index) {
return array.get(index) instanceof JsonObject;
}
public boolean isArray(int index) {
return array.get(index) instanceof JsonArray;
}
public boolean isMap(int index) {
return array.get(index) instanceof JsonMap;
}
public boolean isString(int index) {
return array.get(index) instanceof String;
}
public boolean isBoolean(int index) {
return array.get(index) instanceof Boolean;
}
public boolean isLong(int index) {
return array.get(index) instanceof Long;
}
public boolean isNull(int index) {
return array.get(index) == null;
}
public boolean isArray() {
return true;
}
public boolean isMap() {
return false;
}
public void add(Object obj) {
if(obj instanceof String) {
array.add(obj);
} else if(obj instanceof Number) {
array.add(((Number)obj).longValue());
} else if(obj instanceof JsonObject) {
array.add(obj);
} else if(obj instanceof Boolean) {
array.add(obj);
} else if(obj == null) {
array.add(null);
}
}
public void remove(int index) {
array.remove(index);
}
public int getSize() {
return array.size();
}
public List<Object> copyOf() {
return List.copyOf(array);
}
protected String toNormalString() {
int size = getSize();
if(size == 0) return "[]";
StringBuilder sb = new StringBuilder();
sb.append("[\n\t");
for(int i = 0; i < size; i++) {
Object obj = array.get(i);
if(obj instanceof String) {
sb.append("\"").append(obj).append("\"");
} else if(obj instanceof Long) {
sb.append(obj);
} else if(obj instanceof Boolean) {
sb.append(obj);
} else if(obj instanceof JsonObject) {
sb.append(((JsonObject)obj).toString(false).replace("\n", "\n\t"));
} else if(obj == null) {
sb.append("null");
} else {
}
if(i < size - 1) sb.append(",\n\t");
}
sb.append("\n]");
return sb.toString();
}
protected String toCompactString() {
int size = getSize();
if(size == 0) return "[]";
StringBuilder sb = new StringBuilder();
sb.append("[");
for(int i = 0; i < size; i++) {
Object obj = array.get(i);
if(obj instanceof String) {
sb.append("\"").append(obj).append("\"");
} else if(obj instanceof Long) {
sb.append(obj);
} else if(obj instanceof Boolean) {
sb.append(obj);
} else if(obj instanceof JsonObject) {
sb.append(((JsonObject)obj).toString(true).replace("\n", "\n\t"));
} else if(obj == null) {
sb.append("null");
} else {
}
if(i < size - 1) sb.append(",");
}
sb.append("]");
return sb.toString();
}
}
|
package Metaphase01;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* 快速失败机制的避免方式:
* CopyOnWriteArrayList与ArrayList不同:
*
* (01) 和ArrayList继承于AbstractList不同,CopyOnWriteArrayList没有继承于AbstractList,它仅仅只是实现了List接口。
* (02) ArrayList的iterator()函数返回的Iterator是在AbstractList中实现的;而CopyOnWriteArrayList是自己实现Iterator。
* (03) ArrayList的Iterator实现类中调用next()时,会“调用checkForComodification()比较‘expectedModCount’和‘modCount’的大小”;
* 但是,CopyOnWriteArrayList的Iterator实现类中,没有所谓的checkForComodification(),更不会抛出
* ConcurrentModificationException异常!
*/
public class TestDemo05 {
public static void main(String[] args) {
List<Integer> list = new CopyOnWriteArrayList<>();
for (int i = 0; i < 5; i++) {
list.add(i);
}
new MyThread1(list).start();
new MyThread2(list).start();
}
}
class MyThread1 extends Thread {
private List<Integer> list;
public MyThread1( List<Integer> list) {
this.list = list;
}
@Override
public void run() {
for (Integer integer : list) {
System.out.println("MyThread1 大小:" + list.size() + " 当前值:" + integer);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class MyThread2 extends Thread {
private List<Integer> list;
public MyThread2( List<Integer> list) {
this.list = list;
}
@Override
public void run() {
for (int i = 5; i < 10; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
list.add(i);
System.out.println("MyThread2 大小:" + list.size());
}
}
} |
public class Solution{
//addition is equal to addition without carry + only do the carry rather than addition.
public static int addWithoutPlus1(int x,int y){
if(y==0){return x;}
int sumWithoutCarry = x^y;
int onlyCarry = (a&b)<<1;
addWithoutPlus(sumWithoutCarry,onlyCarry);
}
//based on recursive solution, we can derive iterative version of solution.
public static int addWithoutPlus2(int x,int y){
while(y!=0){
int sum = x^y; //add without carry.
int carry = (a&b)<<1; //carry but don't add.
int x = sum;
int y = carry;
}
return x;
}
} |
package com.grocery.codenicely.vegworld_new.referral.model;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.grocery.codenicely.vegworld_new.helper.Urls;
import com.grocery.codenicely.vegworld_new.referral.OnReferralDataRecievedCallback;
import com.grocery.codenicely.vegworld_new.referral.api.ReferralApi;
import com.grocery.codenicely.vegworld_new.referral.data.ReferralResponse;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by ujjwal on 28/9/17.
*/
public class RetrofitRefferalDataProvider implements ReferralDataProvider {
Retrofit retrofit;
ReferralApi referralApi;
public RetrofitRefferalDataProvider() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).connectTimeout(5, TimeUnit.MINUTES)
.readTimeout(5, TimeUnit.MINUTES).build();
Gson gson = new GsonBuilder()
.setLenient()
.create();
retrofit = new Retrofit.Builder()
.baseUrl(Urls.BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
referralApi = retrofit.create(ReferralApi.class);
}
@Override
public void requestRefferalData(String accessToken, final OnReferralDataRecievedCallback onReferralDataRecievedCallback) {
Call<ReferralResponse> referralResponseCall = referralApi.getReferralData(accessToken);
referralResponseCall.enqueue(new Callback<ReferralResponse>() {
@Override
public void onResponse(Call<ReferralResponse> call, Response<ReferralResponse> response) {
onReferralDataRecievedCallback.onSuccess(response.body());
}
@Override
public void onFailure(Call<ReferralResponse> call, Throwable t) {
t.printStackTrace();
onReferralDataRecievedCallback.onFailure();
}
});
}
}
|
package com.assignment.nalin.service;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.assignment.nalin.entity.Course;
import com.assignment.nalin.entity.Instructor;
import com.assignment.nalin.entity.Student;
import com.assignment.nalin.repository.CourseRepository;
import com.assignment.nalin.repository.InstructorRepository;
import com.assignment.nalin.repository.StudentRepository;
@Service
public class UtilityService {
@Autowired
private StudentRepository studentRepository;
@Autowired
private CourseRepository courseRepository;
@Autowired
private InstructorRepository instructorRepository;
//to get the list of course for a particular student id
public List<Course> findCoursesByStudentId(Long id){
Student student = studentRepository.findById(id).orElseThrow(() -> new EntityNotFoundException("student not found"));
List<Course> courses = (List<Course>) student.getCourses();
return courses;
}
//to get the list of students for a particular instructor id
public List<Student> findStudentsByInstructorId(Long id) {
Instructor instructor = instructorRepository.findById(id)
.orElseThrow(() -> new EntityNotFoundException("instructor not found"));
List<Course> courses = courseRepository.findByInstructorId(id);
List<Student> allStudents = new ArrayList<>();
for( Course c : courses ) {
List<Student> students = (List<Student>) c.getStudents();
allStudents.addAll(students);
}
return allStudents;
}
//to get the total course duration for a particular student id
//to get the list of students for a particular instructor id
public Long findCourseDurationByStudentId(Long id) {
List<Course> courses = findCoursesByStudentId(id);
Long duration = courses.stream().mapToLong(c ->c.getDuration().longValue()).sum();
return duration;
}
}
|
/*
* Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.identity.governance.service.notification;
import org.apache.commons.lang.StringUtils;
import org.wso2.carbon.identity.governance.IdentityMgtConstants;
import org.wso2.carbon.identity.governance.exceptions.notiification.NotificationChannelManagerClientException;
/**
* Enum contains the supported notification channels by the identity server.
*/
public enum NotificationChannels {
EMAIL_CHANNEL("EMAIL", "http://wso2.org/claims/emailaddress",
"http://wso2.org/claims/identity/emailVerified"),
SMS_CHANNEL("SMS", "http://wso2.org/claims/mobile",
"http://wso2.org/claims/identity/phoneVerified"),
EXTERNAL_CHANNEL("EXTERNAL", StringUtils.EMPTY, StringUtils.EMPTY);
// Type of the channel. Eg: EMAIL or SMS.
private String channelType;
// Verification claim url of the channel.
private String verifiedClaimUrl;
// Claim url of the channel.
private String claimUrl;
/**
* Get claim url of the channel.
*
* @return Claim url of the channel
*/
public String getClaimUri() {
return claimUrl;
}
/**
* Get claim url of the channel.
*
* @return Claim url of the channel
*/
public String getVerifiedClaimUrl() {
return verifiedClaimUrl;
}
/**
* Get channel type/name of the channel.
*
* @return Claim url of the channel
*/
public String getChannelType() {
return channelType;
}
NotificationChannels(String type, String claimUrl, String verifiedClaimUrl) {
this.channelType = type;
this.claimUrl = claimUrl;
this.verifiedClaimUrl = verifiedClaimUrl;
}
/**
* Get NotificationChannels enum which matches the channel type.
*
* @param channelType Type of the channel
* @return NotificationChannel which matches the given channel type
*/
public static NotificationChannels getNotificationChannel(String channelType)
throws NotificationChannelManagerClientException {
if (EMAIL_CHANNEL.getChannelType().equals(channelType)) {
return EMAIL_CHANNEL;
} else if (SMS_CHANNEL.getChannelType().equals(channelType)) {
return SMS_CHANNEL;
} else if (EXTERNAL_CHANNEL.getChannelType().equals(channelType)) {
return EXTERNAL_CHANNEL;
} else {
throw new NotificationChannelManagerClientException(
IdentityMgtConstants.ErrorMessages.ERROR_CODE_NO_NOTIFICATION_CHANNELS.getCode(),
IdentityMgtConstants.ErrorMessages.ERROR_CODE_NO_NOTIFICATION_CHANNELS.getMessage());
}
}
}
|
package heylichen.searching.bst;
import java.util.Set;
/**
* @author lichen
* @date 2020/5/27 15:32
* @desc
*/
public interface SymbolTable<K extends Comparable<K>, V> {
V get(K key);
int size();
boolean isEmpty();
boolean containsKey(K key);
void put(K key, V value);
Set<K> keySet();
void deleteMin();
void deleteMax();
void delete(K key);
//---------------------------order operations -------------
K min();
K max();
//largest key less than or equal to key
K floor(K key);
K ceiling(K key);
//number of keys less than key
int rank(K key);
//key of rank k
K select(int rank);
}
|
package com.arkaces.ark_eth_channel_service.contract;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface ContractRepository extends PagingAndSortingRepository<ContractEntity, Long> {
ContractEntity findOneById(String id);
ContractEntity findOneBySubscriptionId(String subscriptionId);
}
|
package com.mobiledev.realmdatabasesample.utils;
import android.app.Application;
import com.mobiledev.realmdatabasesample.db.RealmHelper;
import io.realm.Realm;
import io.realm.RealmConfiguration;
/**
* Created by Manu on 11/6/2017.
*/
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
initRealm();
}
private void initRealm() {
Realm.init(this);
RealmConfiguration configuration=new RealmConfiguration.Builder()
.name(RealmHelper.DB_NAME)
.deleteRealmIfMigrationNeeded()
.build();
Realm.setDefaultConfiguration(configuration);
}
} |
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
public abstract class CollisionManager {
protected LevelManager levelManager;
protected List<Image> explosions = new ArrayList<Image>();
protected List<Integer> explosionXs = new ArrayList<Integer>();
protected List<Integer> explosionYs = new ArrayList<Integer>();
protected Image scaledExplosionImage;
public CollisionManager(LevelManager levelManager) {
this.levelManager = levelManager;
BufferedImage explosionImage = ImageConstants.explosionImage;
scaledExplosionImage = explosionImage.getScaledInstance(200, 200, Image.SCALE_SMOOTH);
}
public abstract void handleCollision(GameObject obj1, GameObject obj2, Graphics g);
public abstract void drawExplosions(Graphics g);
public abstract void removeExplosions();
}
|
package net.davoleo.javagui.games.animation;
import java.awt.*;
import java.util.ArrayList;
/*************************************************
* Author: Davoleo
* Date / Hour: 03/07/2019 / 08:10
* Class: Animation
* Project: JavaGUI
* Copyright - © - Davoleo - 2019
**************************************************/
public class Animation {
private ArrayList scenes;
private int sceneIndex;
private long movieTime;
private long totalTime;
//Constructor
public Animation() {
scenes = new ArrayList();
totalTime = 0;
start();
}
/**
* Adds a scene to the scenes
* synchronized: makes sure it doesn't run concurrently on other threads
*/
public synchronized void addScene(Image img, long time)
{
totalTime += time;
scenes.add(new Scene(img, totalTime));
}
//Starts the animation
private synchronized void start()
{
movieTime = 0;
sceneIndex = 0;
}
//update the animation (changes frame)
public synchronized void update(long timePassed)
{
if (scenes.size() > 1)
{
movieTime += timePassed;
if (movieTime >= totalTime)
start();
while (movieTime > getScene(sceneIndex).endTime)
sceneIndex++;
}
}
//Current animation frame AKA Scene
public synchronized Image getFrame()
{
if (scenes.size() == 0)
return null;
else
return getScene(sceneIndex).pic;
}
//get scene
private Scene getScene(int index)
{
return (Scene) scenes.get(index);
}
///////// Private inner Scene Class /////////////
private class Scene {
private Image pic;
private long endTime;
Scene(Image pic, long endTime)
{
this.pic = pic;
this.endTime = endTime;
}
}
}
|
package xtrus.ex.mci.channel;
import java.net.ConnectException;
import org.apache.commons.lang.StringUtils;
import org.jboss.netty.channel.ChannelException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xtrus.ex.mci.ExMciCode;
import xtrus.ex.mci.ExMciConfig;
import xtrus.ex.mci.ExMciException;
import xtrus.ex.mci.client.MciClient;
import xtrus.ex.mci.client.MciClientFactory;
import xtrus.ex.mci.handler.MciMessageHandler;
import xtrus.ex.mci.message.MciMessage;
import xtrus.ex.mci.message.Message;
import xtrus.ex.mci.message.NonStdMciMessage;
import xtrus.ex.mci.message.StdMciMessage;
import xtrus.ex.mci.table.ExMciClientInfoRecord;
import xtrus.ex.mci.table.ExMciClientInfoTable;
import xtrus.ex.mci.table.ExMciIfInfoRecord;
import xtrus.ex.mci.table.ExMciIfInfoTable;
import com.esum.framework.common.util.ClassUtil;
import com.esum.framework.core.component.ComponentException;
import com.esum.framework.core.component.config.ComponentConfigFactory;
import com.esum.framework.core.component.table.InfoTableManager;
import com.esum.framework.core.event.RoutingStatus;
import com.esum.framework.core.event.log.ErrorInfo;
import com.esum.framework.core.event.log.LoggingEvent;
import com.esum.framework.core.event.message.MessageEvent;
import com.esum.framework.core.event.message.Payload;
import com.esum.framework.core.event.util.LoggingEventUtil;
import com.esum.framework.core.exception.SystemException;
import com.esum.router.RouterUtil;
import com.esum.router.handler.OutboundHandlerAdapter;
/**
* Copyright(c) eSum Technologies, Inc. All rights reserved.
*/
public class ExMciOutboundHandler extends OutboundHandlerAdapter {
private Logger logger = LoggerFactory.getLogger(ExMciOutboundHandler.class);
private ExMciClientInfoTable infoTable = null;
private ExMciIfInfoTable ifTable = null;
private MciMessage responseMessage;
protected ExMciOutboundHandler(String componentId) {
super(componentId);
this.setLog(logger);
}
protected LoggingEvent onPostProcess(MessageEvent messageEvent, Object[] params, String status) throws SystemException {
LoggingEvent logEvent = LoggingEventUtil.makeLoggingEvent(messageEvent.getEventHeader().getType(),
messageEvent.getMessageControlId(),
getComponentId(),
messageEvent,
status);
if(status.equals(RoutingStatus.QRSP_STATUS))
logEvent.getLoggingInfo().getMessageLog().setPullSendFlag("Y");
if(params!=null && params.length==1) {
// logEvent.getLoggingInfo().getMessageLog().setOutMessageId(params[0].toString());
// logEvent.getLoggingInfo().getMessageLog().setMessageNumber(params[0].toString());
}
return logEvent;
}
public void onProcess(MessageEvent messageEvent) {
this.traceId = "[" + messageEvent.getMessageControlId() + "]";
if(logger.isDebugEnabled())
logger.debug(traceId+"Processing MCI Message.");
ExMciClientInfoRecord infoRecord = null;
ExMciIfInfoRecord ifInfoRecord = null;
try {
ExMciConfig mcaConfig = (ExMciConfig)ComponentConfigFactory.getInstance(getComponentId());
String fromSvcId = messageEvent.getMessage().getHeader().getFromParty().getUserId();
String toSvcId = messageEvent.getMessage().getHeader().getToParty().getUserId();
String inMsgId = messageEvent.getMessage().getHeader().getInMessageId();
String msgName = messageEvent.getMessage().getHeader().getMessageName();
String targetIfId = messageEvent.getRoutingInfo().getTargetInterfaceId();
if (StringUtils.isEmpty(targetIfId))
targetIfId = RouterUtil.getTargetInterfaceId(fromSvcId, toSvcId, msgName);
this.setInterfaceId(targetIfId);
if(infoTable==null)
infoTable = (ExMciClientInfoTable)InfoTableManager.getInstance().getInfoTable(ExMciConfig.MCI_CLIENT_INFO_TABLE_ID);
if(logger.isDebugEnabled())
logger.debug(traceId+"Searching "+getInterfaceId()+" interface.");
infoRecord = (ExMciClientInfoRecord)infoTable.getMciClientInfo(getInterfaceId());
traceId = traceId + "[" + infoRecord.getInterfaceId() + "]";
if(ifTable==null)
ifTable = (ExMciIfInfoTable)InfoTableManager.getInstance().getInfoTable(ExMciConfig.MCI_IF_INFO_TABLE_ID);
final Payload payload = messageEvent.getMessage().getPayload();
if(logger.isDebugEnabled())
logger.debug(traceId+"Searching if document. id : "+payload.getDataInfo().getDocumentName());
ifInfoRecord = (ExMciIfInfoRecord)ifTable.getMciIfInfo(payload.getDataInfo().getDocumentName());
byte[] reqMessage = null;
if(ifInfoRecord!=null) {
if(logger.isDebugEnabled())
logger.debug(traceId+"If class : "+ifInfoRecord.getIfClass());
MciMessage mciMessage = null;
if(StringUtils.isNotEmpty(ifInfoRecord.getIfClass())) {
Class<MciMessage> ifClass = ClassUtil.forName(ifInfoRecord.getIfClass(), null, MciMessage.class);
mciMessage = ifClass.newInstance();
try {
mciMessage.marshal(messageEvent.getMessage().getPayload().getData());
} catch (Exception e) {
throw new ExMciException(ExMciCode.ERROR_GENERATE_MESSAGE, "onProcess()", "Could not parsing from payload data. details :"+e.getMessage(), e);
}
}
if(logger.isDebugEnabled())
logger.debug(traceId+"Use a IF handling. Request Handling class : "+ifInfoRecord.getIfHandlerClass());
Class<MciMessageHandler> handlerClass = ClassUtil.forName(
ifInfoRecord.getIfHandlerClass(), null, MciMessageHandler.class);
MciMessageHandler ifHandler = handlerClass.newInstance();
ifHandler.setMciIfInfoRecord(ifInfoRecord);
reqMessage = ifHandler.outbound(messageEvent, mciMessage);
} else {
if(logger.isDebugEnabled())
logger.debug(traceId+"Not use If handling.");
reqMessage = payload.getData();
}
logger.info(traceId + "Sending data to " + infoRecord.getHost() + ":"+infoRecord.getPort()+"...");
long stime = System.currentTimeMillis();
MciClient client = MciClientFactory.getInstance().getMciClient(infoRecord.getSystemCode());
this.responseMessage = client.send(reqMessage);
log.info(traceId+"Message sent and received response.");
if(logger.isDebugEnabled()) {
logger.debug("----------<<EXMCI RESPONSE MESSAGE>>-----------------"+System.lineSeparator()
+responseMessage.toString());
logger.debug("----------<<END OF MESSAGE>>----------");
}
if (reqMessage != null)
messageEvent.getMessage().getPayload().setData(reqMessage);
logger.info(traceId+"Message transfer time. "+(System.currentTimeMillis()-stime)+" ms.");
processSucess(messageEvent, new Object[] {reqMessage},
mcaConfig.getReqMsgOutputStatus(), mcaConfig.getSyncOutputStatus(), true);
} catch (ChannelException e) {
logger.error(traceId + "Could not connect. "+e.getMessage(), e);
ExMciException se = new ExMciException(ExMciCode.ERROR_CLIENT_CONNECT, "process()", e.getMessage(), e);
processError(messageEvent, se);
messageEvent.getMessage().getHeader().setErrorInfo(
new ErrorInfo(se.getErrorCode(), se.getErrorLocation(), se.getErrorMessage()));
} catch (ConnectException e) {
ExMciException se = new ExMciException(ExMciCode.ERROR_CLIENT_CONNECT, "process()", e.getMessage(), e);
processError(messageEvent, se);
messageEvent.getMessage().getHeader().setErrorInfo(
new ErrorInfo(se.getErrorCode(), se.getErrorLocation(), se.getErrorMessage()));
} catch (ComponentException e) {
logger.error(traceId + "EXMCI Info Handling Error!!", e);
processError(messageEvent, e);
messageEvent.getMessage().getHeader().setErrorInfo(
new ErrorInfo(e.getErrorCode(), e.getErrorLocation(), e.getErrorMessage()));
} catch (ExMciException e) {
logger.error(traceId + "EXMCI Message Transfer Error!!", e);
processError(messageEvent, e);
messageEvent.getMessage().getHeader().setErrorInfo(
new ErrorInfo(e.getErrorCode(), e.getErrorLocation(), e.getErrorMessage()));
} catch (Exception e) {
logger.error(traceId + "Undefined Error!!", e);
ExMciException se = new ExMciException(ExMciCode.ERROR_UNDEFINED, "process()", e.getMessage(), e);
processError(messageEvent, se);
messageEvent.getMessage().getHeader().setErrorInfo(
new ErrorInfo(se.getErrorCode(), se.getErrorLocation(), se.getErrorMessage()));
}
}
@Override
public MessageEvent processResponse(MessageEvent messageEvent) {
messageEvent = super.processResponse(messageEvent);
if(responseMessage==null)
return null;
byte[] rawBytes = responseMessage.getRawBytes();
ErrorInfo errorInfo = null;
if(responseMessage.getType().equals(Message.STANDARD_TYPE)) {
StdMciMessage stdMessage = (StdMciMessage)responseMessage;
if(stdMessage.getHandlingResultCode().equals(Message.HANDLING_RESULT_E)) {
errorInfo = new ErrorInfo(ExMciCode.ERROR_GENERATING_RESP_MESSAGE,
"responseFailed()",
"Received '"+stdMessage.getErrorCode()+"' error code by client with '"+stdMessage.getErrorSystemCode()+"' system.");
}
} else if(responseMessage.getType().equals(Message.NON_STANDARD_TYPE)) {
NonStdMciMessage nonStdMessage = (NonStdMciMessage)responseMessage;
if(!nonStdMessage.getResponseCode().equals("0000")) {
errorInfo = new ErrorInfo(ExMciCode.ERROR_GENERATING_RESP_MESSAGE,
"responseFailed()",
"Received '"+nonStdMessage.getResponseCode()+"' error code by client with '"+nonStdMessage.getSenderSystemCode()+"' system.");
}
}
if(errorInfo!=null)
messageEvent.getMessage().getHeader().setErrorInfo(errorInfo);
Payload payload = messageEvent.getMessage().getPayload();
payload.setData(rawBytes);
return messageEvent;
}
} |
package ru.orbot90.guestbook.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import ru.orbot90.guestbook.exception.DataNotFoundException;
import ru.orbot90.guestbook.model.ImageUploadResponse;
import ru.orbot90.guestbook.services.ImageService;
import javax.validation.constraints.NotEmpty;
import java.io.IOException;
/**
* @author Iurii Plevako orbot90@gmail.com
**/
@Controller
@RequestMapping(ImageController.IMAGE_CONTEXT)
@CrossOrigin(origins = "*", allowedHeaders = "Origin, X-Requested-With, Content-Type, Accept")
public class ImageController {
static final String IMAGE_CONTEXT = "/image";
private final String imageHost;
private final ImageService imageService;
public ImageController(@Value("${guestbook.images.host}") String imageHost,
ImageService imageService) {
this.imageService = imageService;
this.imageHost = imageHost;
}
@PreAuthorize("isAuthenticated()")
@PostMapping(produces = "application/json")
@ResponseBody
public ImageUploadResponse uploadImage(@RequestParam("upload") MultipartFile file,
Authentication authentication) throws IOException {
String savedName = imageService.saveImage(file.getBytes(), authentication.getName());
return new ImageUploadResponse(imageHost + IMAGE_CONTEXT + "/" + savedName);
}
@GetMapping
@RequestMapping(path = {"/{name}"}, produces = "image/webp")
@ResponseBody
public ResponseEntity<byte[]> getImage(@PathVariable("name") @NotEmpty String name) {
try {
byte[] image = this.imageService.getImageByName(name);
return new ResponseEntity<>(image, HttpStatus.OK);
} catch (DataNotFoundException e) {
return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
}
}
}
|
package com.bd2001.jzl;
import java.sql.*;
public class test {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/climb_channel_order";
static final String USER = "root";
static final String PASS = "root";
static private Connection conn = null;
static private Statement stmt = null;
public static void main(String[] args) {
try{
// 注册 JDBC 驱动
Class.forName(JDBC_DRIVER);
// 打开链接
conn = DriverManager.getConnection(DB_URL,USER,PASS);
// 执行查询
stmt = conn.createStatement();
String sql;
// sql = "SELECT id, city_id, city_name,airport_name,loccd, locsubcd,airport_longitude,,airport_latitude,address ,longitude,latitude,distance ,create_time FROM ctrip_param_info";
sql = "SELECT * FROM ctrip_param_info";
ResultSet rs = stmt.executeQuery(sql);
// 展开结果集数据库
while(rs.next()){
int flag = 17; //17 接机 18 送机
int id = rs.getInt("id");
int city_id = rs.getInt("city_id");
String city_name = rs.getString("city_name");
String airport_name = rs.getString("airport_name");
String loccd = rs.getString("loccd");
int locsubcd = rs.getInt("locsubcd");
String airport_longitude = rs.getString("airport_longitude");
String airport_latitude = rs.getString("airport_latitude");
String address = rs.getString("address");
String longitude = rs.getString("longitude");
String latitude = rs.getString("latitude");
String distance = rs.getString("distance");
String create_time = rs.getString("create_time");
System.out.println(id);
System.out.println(city_id);
System.out.println(city_name);
System.out.println(airport_name);
System.out.println(loccd);
System.out.println(locsubcd);
System.out.println(airport_longitude);
System.out.println(airport_latitude);
System.out.println(address);
System.out.println(longitude);
System.out.println(latitude);
System.out.println(distance);
System.out.println(create_time);
}
// 完成后关闭
rs.close();
stmt.close();
conn.close();
}catch(
SQLException se){
// 处理 JDBC 错误
se.printStackTrace();
}catch(Exception e){
// 处理 Class.forName 错误
e.printStackTrace();
}finally{
// 关闭资源
try{
if(stmt!=null) stmt.close();
}catch(SQLException se2){
}// 什么都不做
try{
if(conn!=null) conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
}
|
/**
*
*/
package com.needii.dashboard.controller;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.DoubleSummaryStatistics;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.needii.dashboard.helper.ExcelHelper;
import com.needii.dashboard.helper.ResponseStatusEnum;
import com.needii.dashboard.model.BalanceDue;
import com.needii.dashboard.model.BaseResponse;
import com.needii.dashboard.model.Income;
import com.needii.dashboard.model.OrderDetail;
import com.needii.dashboard.model.PaymentMethodTypeEnum;
import com.needii.dashboard.model.Supplier;
import com.needii.dashboard.model.search.BalanceDueSearchCriteria;
import com.needii.dashboard.model.search.IncomeSearchCriteria;
import com.needii.dashboard.service.CustomerBalanceService;
import com.needii.dashboard.service.CustomerService;
import com.needii.dashboard.service.FlashSaleService;
import com.needii.dashboard.service.IncomeService;
import com.needii.dashboard.service.OrderDetailService;
import com.needii.dashboard.service.OrderService;
import com.needii.dashboard.service.ProductService;
import com.needii.dashboard.service.PromotionService;
import com.needii.dashboard.service.SupplierService;
import com.needii.dashboard.utils.ChartData;
import com.needii.dashboard.utils.Constants;
import com.needii.dashboard.utils.KeyValue;
import com.needii.dashboard.utils.Pagination;
import com.needii.dashboard.utils.Utils;
import com.needii.dashboard.utils.ValidationUtil;
import com.needii.dashboard.view.IncomeExportExcel;
/**
* @author kelvin
*
*/
@Controller
@RequestMapping(value = "/incomes")
@PreAuthorize("hasAnyAuthority('INCOME_MANAGER', 'BALANCE_DUE_MANAGER', 'SUPERADMIN')")
public class IncomeController extends BaseController {
@Autowired
ServletContext context;
@Autowired
private SupplierService supplierService;
@Autowired
private IncomeService incomeService;
@Autowired
private CustomerService customerService;
@Autowired
private ProductService productService;
@Autowired
private OrderService orderService;
@Autowired
private FlashSaleService flashSaleService;
@Autowired
private OrderDetailService orderDetailService;
@Autowired
private CustomerBalanceService customerBalanceService;
@Autowired
private PromotionService promotionService;
@ModelAttribute("supplierList")
public Map<Long, String> supplierList() {
List<Supplier> suppliers = supplierService.findAll();
Map<Long, String> supplierList = new LinkedHashMap<>();
supplierList.put((long) 0, "Chọn nhà cung cấp");
for (Supplier supplier : suppliers) {
supplierList.put(supplier.getId(), supplier.getFullName());
}
return supplierList;
}
@PreAuthorize("hasAnyAuthority('INCOME_MANAGER', 'SUPERADMIN')")
@RequestMapping(value = { "" }, method = RequestMethod.GET)
public String index(Model model,
@RequestParam(name="supplierId", required=false, defaultValue="0") long supplierId,
@RequestParam(name="from", required=false, defaultValue="") String from,
@RequestParam(name="to", required=false, defaultValue="") String to,
@RequestParam(name="orderId", required=false) String orderId,
@RequestParam(name="page", required=false, defaultValue="1") int page) {
Date fromDate = null;
Date toDate = null;
if(!from.isEmpty()) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm");
fromDate = formatter.parseDateTime(from).toDate();
}
if(!to.isEmpty()) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm");
toDate = formatter.parseDateTime(to).toDate();
}
IncomeSearchCriteria searchCriteria = new IncomeSearchCriteria(supplierId, orderId, fromDate, toDate);
model.addAttribute("searchCriteria", searchCriteria);
if (orderId!= null && !orderId.isEmpty() && !ValidationUtil.isInteger(orderId)) {
model.addAttribute("incomes", new ArrayList<Income>());
return "incomeIndex";
}
Pagination pagination = new Pagination(page, this.getNumberPage());
List<Income> incomes = incomeService.findAll(searchCriteria, pagination);
List<KeyValue> chartData = prepareDataForWeek();
model.addAttribute("totalRecord", incomeService.count(searchCriteria));
model.addAttribute("limit", this.getNumberPage());
model.addAttribute("currentPage", page);
model.addAttribute("incomes", incomes);
model.addAttribute("chartData", chartData);
model.addAttribute("totalCustomer", customerService.count());
model.addAttribute("totalProduct", productService.count());
model.addAttribute("totalFlashSale", flashSaleService.count());
model.addAttribute("totalOrder", orderService.count());
model.addAttribute("totalTransaction", customerBalanceService.count());
model.addAttribute("totalPromotion", promotionService.count());
model.addAttribute("totalOrderAmount", Utils.stringVietnameseMoneyFormatWithFloat((float)incomes.stream().mapToDouble(x -> x.getOrderDetailTotalPrice()).sum()));
model.addAttribute("totalIncome", Utils.stringVietnameseMoneyFormatWithFloat((float)incomes.stream().mapToDouble(x -> x.getIncomeAmount()).sum()));
return "incomeIndex";
}
@PreAuthorize("hasAnyAuthority('BALANCE_DUE_MANAGER', 'SUPERADMIN')")
@RequestMapping(value = { "/supplier-balance-due" }, method = RequestMethod.GET)
public String supplierBalanceDue(Model model,
@RequestParam(name="supplier_id", required=false, defaultValue="0") long supplierId,
@RequestParam(name="from", required=false, defaultValue="") String from,
@RequestParam(name="to", required=false, defaultValue="") String to) {
Date fromDate = null;
Date toDate = null;
if(!from.isEmpty()) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm");
fromDate = formatter.parseDateTime(from).toDate();
}
if(!to.isEmpty()) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm");
toDate = formatter.parseDateTime(to).toDate();
}
BalanceDueSearchCriteria searchCriteria = new BalanceDueSearchCriteria(new Integer[] {PaymentMethodTypeEnum.NEEDII_CASH.getValue(), PaymentMethodTypeEnum.CREDIT_CARD.getValue(), PaymentMethodTypeEnum.ATM.getValue()}, supplierId, fromDate, toDate);
List<Supplier> suppliers = supplierService.findAll();
List<OrderDetail> orderDetails = orderDetailService.findByPaymentMethodIds(searchCriteria);
List<BalanceDue> data = new ArrayList<BalanceDue>();
Map<Object, DoubleSummaryStatistics> stat = orderDetails.stream().collect(Collectors.groupingBy(
od -> od.getSupplier().getId(),
Collectors.summarizingDouble(od -> od.getTotalAmount())));
stat.entrySet().forEach(it ->
data.add(new BalanceDue(
Long.valueOf(String.valueOf(it.getKey())),
suppliers.stream().filter(x -> x.getId() == Long.valueOf(String.valueOf(it.getKey()))).findFirst().get().getFullName(),
Float.parseFloat(String.valueOf(it.getValue().getSum())))
)
);
model.addAttribute("totalRecord", orderDetailService.countByPaymentMethodIds(searchCriteria));
model.addAttribute("data", data);
model.addAttribute("suppliers", suppliers);
model.addAttribute("searchCriteria", searchCriteria);
return "supplierBalanceDue";
}
@RequestMapping(value = { "/balance-due-detail" }, method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<BaseResponse> balanceDueDetail(
HttpServletRequest request,
@RequestParam(name="supplier_id") long supplierId,
@RequestParam(name="from", required=false, defaultValue="") String from,
@RequestParam(name="to", required=false, defaultValue="") String to,
Model model){
BaseResponse response = new BaseResponse();
response.setStatus(ResponseStatusEnum.SUCCESS);
response.setMessage(ResponseStatusEnum.SUCCESS);
response.setData(null);
try {
Date fromDate = null;
Date toDate = null;
if(!from.isEmpty()) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm");
fromDate = formatter.parseDateTime(from).toDate();
}
if(!to.isEmpty()) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm");
toDate = formatter.parseDateTime(to).toDate();
}
BalanceDueSearchCriteria searchCriteria = new BalanceDueSearchCriteria(new Integer[] {PaymentMethodTypeEnum.NEEDII_CASH.getValue(), PaymentMethodTypeEnum.CREDIT_CARD.getValue(), PaymentMethodTypeEnum.ATM.getValue()}, supplierId, fromDate, toDate);
List<OrderDetail> orderDetails = orderDetailService.findByPaymentMethodIds(searchCriteria);
model.addAttribute("orderDetails", orderDetails);
String viewStringContent = this.renderViewString("pages/income/_balanceDueDetail", model.asMap(), request);
response.setData(viewStringContent);
} catch(Exception ex) {
response.setStatus(ResponseStatusEnum.FAIL);
response.setMessageError(ex.getMessage());
ex.printStackTrace();
}
return new ResponseEntity<>(response, HttpStatus.OK);
}
@RequestMapping(value = { "/export-income" }, method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<BaseResponse> exportIncome(
@RequestParam(name="supplier_id", required=false, defaultValue="0") long supplierId,
@RequestParam(name="from", required=false, defaultValue="") String from,
@RequestParam(name="to", required=false, defaultValue="") String to) {
BaseResponse response = new BaseResponse();
response.setStatus(ResponseStatusEnum.SUCCESS);
response.setMessage(ResponseStatusEnum.SUCCESS);
response.setData(null);
try {
Date fromDate = null;
Date toDate = null;
if(!from.isEmpty()) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm");
fromDate = formatter.parseDateTime(from).toDate();
}
if(!to.isEmpty()) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm");
toDate = formatter.parseDateTime(to).toDate();
}
Pagination pagination = new Pagination(1, 9999);
IncomeSearchCriteria searchCriteria = new IncomeSearchCriteria(supplierId, fromDate, toDate);
List<Income> incomes = incomeService.findAll(searchCriteria, pagination);
String savePath = Constants.SAVE_EXPORT_FILE;
String filePath = context.getRealPath(savePath);
Object[] header = {
"Mã",
"Nhà cung cấp(NCC)",
"Mã đơn hàng",
"Mã đơn hàng NCC",
"Giá trị đơn hàng NCC",
"Phần trăm chiết khấu đơn hàng",
"Số tiền chiết khấu(VND)",
"Thời gian tạo"
};
Object[][] data = new Object[incomes.size() + 1][header.length];
data[0] = header;
int indexRow = 1;
for (Income item : incomes) {
Object[] excelData = {
item.getId(),
item.getSupplier().getFullName(),
String.valueOf(item.getOrderId()),
String.valueOf(item.getOrderDetailId()),
String.valueOf(item.getOrderDetailTotalPrice()),
String.valueOf(item.getIncomePercent()),
String.valueOf(item.getIncomeAmount()),
Utils.getDatetimeFormatVN(item.getCreatedAt())
};
if(excelData.length == header.length) {
data[indexRow] = excelData;
}
indexRow++;
}
String fileName = ExcelHelper.writeExcel(data, "excel_data", filePath);
if(!fileName.isEmpty()) {
response.setData(String.format("%s/%s", savePath, fileName));
}
} catch (Exception ex) {
response.setStatus(ResponseStatusEnum.FAIL);
response.setMessageError(ex.getMessage());
}
return new ResponseEntity<BaseResponse>(response, HttpStatus.OK);
}
@RequestMapping(value = { "/export-balance-due" }, method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<BaseResponse> exportBalanceDue(
@RequestParam(name="supplier_id", required=false, defaultValue="0") long supplierId,
@RequestParam(name="from", required=false, defaultValue="") String from,
@RequestParam(name="to", required=false, defaultValue="") String to) {
BaseResponse response = new BaseResponse();
response.setStatus(ResponseStatusEnum.SUCCESS);
response.setMessage(ResponseStatusEnum.SUCCESS);
response.setData(null);
try {
Date fromDate = null;
Date toDate = null;
if(!from.isEmpty()) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm");
fromDate = formatter.parseDateTime(from).toDate();
}
if(!to.isEmpty()) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm");
toDate = formatter.parseDateTime(to).toDate();
}
BalanceDueSearchCriteria searchCriteria = new BalanceDueSearchCriteria(new Integer[] {PaymentMethodTypeEnum.NEEDII_CASH.getValue(), PaymentMethodTypeEnum.CREDIT_CARD.getValue(), PaymentMethodTypeEnum.ATM.getValue()}, supplierId, fromDate, toDate);
List<Supplier> suppliers = supplierService.findAll();
List<OrderDetail> orderDetails = orderDetailService.findByPaymentMethodIds(searchCriteria);
List<BalanceDue> balanceDueData = new ArrayList<BalanceDue>();
Map<Object, DoubleSummaryStatistics> stat = orderDetails.stream().collect(Collectors.groupingBy(
od -> od.getSupplier().getId(),
Collectors.summarizingDouble(od -> od.getTotalAmount())));
stat.entrySet().forEach(it ->
balanceDueData.add(new BalanceDue(
Long.valueOf(String.valueOf(it.getKey())),
suppliers.stream().filter(x -> x.getId() == Long.valueOf(String.valueOf(it.getKey()))).findFirst().get().getFullName(),
Float.parseFloat(String.valueOf(it.getValue().getSum())))
)
);
String savePath = Constants.SAVE_EXPORT_FILE;;
String filePath = context.getRealPath(savePath);
Object[] header = {
"Mã NCC",
"Nhà cung cấp(NCC)",
"Dư nợ(VND)"
};
Object[][] data = new Object[balanceDueData.size() + 1][header.length];
data[0] = header;
int indexRow = 1;
for (BalanceDue item : balanceDueData) {
Object[] excelData = {
(int)item.getSupplierId(),
item.getSupplierName(),
String.valueOf(item.getTotalAmount())
};
if(excelData.length == header.length) {
data[indexRow] = excelData;
}
indexRow++;
}
String fileName = ExcelHelper.writeExcel(data, "excel_data", filePath);
if(!fileName.isEmpty()) {
response.setData(String.format("%s/%s", savePath, fileName));
}
} catch (Exception ex) {
response.setStatus(ResponseStatusEnum.FAIL);
response.setMessageError(ex.getMessage());
}
return new ResponseEntity<BaseResponse>(response, HttpStatus.OK);
}
@RequestMapping(value = { "/export/excel/" }, method = RequestMethod.GET)
public ModelAndView exportExcel(Model model,
@RequestParam(name="supplier_id", required=false, defaultValue="0") long supplierId,
@RequestParam(name="from", required=false, defaultValue="") String from,
@RequestParam(name="to", required=false, defaultValue="") String to) {
Date fromDate = null;
Date toDate = null;
if(!from.isEmpty()) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm");
fromDate = formatter.parseDateTime(from).toDate();
}
if(!to.isEmpty()) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm");
toDate = formatter.parseDateTime(to).toDate();
}
IncomeSearchCriteria searchCriteria = new IncomeSearchCriteria(supplierId, fromDate, toDate);
Pagination pagination = new Pagination(1, (int) incomeService.count(searchCriteria));
List<Income> incomes = incomeService.findAll(searchCriteria, pagination);
return new ModelAndView(new IncomeExportExcel(), "incomes", incomes);
}
public List<KeyValue> prepareDataForWeek() {
List<KeyValue> chartData = new ArrayList<KeyValue>();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
String firstDay = "";
String lastDay = "";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
for (int i = 0; i < 7; i++) {
if (i == 0) {
firstDay = df.format(cal.getTime());
}
if (i == 6) {
lastDay = df.format(cal.getTime());
}
chartData.add(new KeyValue(df.format(cal.getTime()), "0"));
cal.add(Calendar.DATE, 1);
}
List<ChartData> list = incomeService.findInWeek(firstDay, lastDay);
for (ChartData item : list) {
for (KeyValue chart : chartData) {
if (item.getChartKey().equals(chart.getKey())) {
chart.setValue(item.getChartValue());
break;
}
}
}
return chartData;
}
public List<KeyValue> prepareDataForMonth() {
List<KeyValue> chartData = new ArrayList<KeyValue>();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
String firstDay = "";
String lastDay = "";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
firstDay = df.format(cal.getTime());
cal.add(Calendar.MONTH, 1);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.add(Calendar.DATE, -1);
lastDay = df.format(cal.getTime());
List<ChartData> list = incomeService.findInMonth(firstDay, lastDay);
for (int i = 0; i < list.size(); i++) {
chartData.add(new KeyValue(list.get(i).getChartKey(), list.get(i).getChartValue()));
}
return chartData;
}
public List<KeyValue> prepareDataForYear() {
List<KeyValue> chartData = new ArrayList<KeyValue>();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_YEAR, 1);
String firstDay = "";
String lastDay = "";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
firstDay = df.format(cal.getTime());
cal.add(Calendar.YEAR, 1);
cal.set(Calendar.DAY_OF_YEAR, 1);
cal.add(Calendar.DATE, -1);
lastDay = df.format(cal.getTime());
List<ChartData> list = incomeService.findInYear(firstDay, lastDay);
for (int i = 0; i < list.size(); i++) {
chartData.add(new KeyValue(list.get(i).getChartKey(), list.get(i).getChartValue()));
}
return chartData;
}
@RequestMapping(value = { "/report/" }, method = RequestMethod.GET)
@ResponseBody
public Object report(Model model, @RequestParam(name="type", required=false, defaultValue="week") String type) {
List<KeyValue> chartData = new ArrayList<KeyValue>();
if (type.equals("week")) {
chartData = prepareDataForWeek();
}
if (type.equals("month")) {
chartData = prepareDataForMonth();
}
if (type.equals("year")) {
chartData = prepareDataForYear();
}
model.addAttribute("chartData", chartData);
return chartData;
}
}
|
package com.lenovohit.hcp.hrp.model;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.lenovohit.hcp.base.annotation.RedisSequence;
import com.lenovohit.hcp.base.model.Company;
import com.lenovohit.hcp.base.model.Department;
import com.lenovohit.hcp.base.model.HcpBaseModel;
@Entity
@Table(name = "INSTRM_OUTPUTINFO")
public class InstrmOutputInfo extends HcpBaseModel {
private static final long serialVersionUID = -2604267547538227262L;
private String outBill;
private Integer billNo;
private String applyNo;
private String appBill;
private Department deptInfo;
private Department toDept;
private String outType;
private Integer plusMinus;
private String storeId;
private String instrmCode;
private InstrmInfo instrmInfo;
private String tradeName;
private String instrmType;
private String batchNo;
private String approvalNo;
private Date produceDate;
private Company producerInfo;
private Date validDate;
private Company companyInfo;
private BigDecimal buyPrice;
private BigDecimal salePrice;
private BigDecimal outSum;
private String minUnit;
private BigDecimal buyCost;
private BigDecimal saleCost;
private String outOper;
private Date outTime;
private String outputState;
private String comm;
private String deptId;
private String instrmId;
private String instrmSpecs;
private String producer;
private String company;
private String outId;
public String getOutId() {
return outId;
}
public void setOutId(String outId) {
this.outId = outId;
}
private Date purchaseDate;
@Transient
public String getDeptId() {
return deptId;
}
public void setDeptId(String deptId) {
this.deptId = deptId;
}
@Transient
public String getInstrmId() {
return instrmId;
}
public void setInstrmId(String instrmId) {
this.instrmId = instrmId;
}
public String getInstrmSpecs() {
return instrmSpecs;
}
public void setInstrmSpecs(String instrmSpecs) {
this.instrmSpecs = instrmSpecs;
}
@Transient
public String getProducer() {
return producer;
}
public void setProducer(String producer) {
this.producer = producer;
}
@Transient
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
@ManyToOne
@JoinColumn(name = "PRODUCER", nullable = true)
@NotFound(action = NotFoundAction.IGNORE)
public Company getProducerInfo() {
return producerInfo;
}
public void setProducerInfo(Company producerInfo) {
this.producerInfo = producerInfo;
}
@ManyToOne
@JoinColumn(name = "COMPANY", nullable = true)
@NotFound(action = NotFoundAction.IGNORE)
public Company getCompanyInfo() {
return companyInfo;
}
public void setCompanyInfo(Company companyInfo) {
this.companyInfo = companyInfo;
}
@RedisSequence
public String getOutBill() {
return outBill;
}
public void setOutBill(String outBill) {
this.outBill = outBill == null ? null : outBill.trim();
}
public Integer getBillNo() {
return billNo;
}
public void setBillNo(Integer billNo) {
this.billNo = billNo;
}
public String getApplyNo() {
return applyNo;
}
public void setApplyNo(String applyNo) {
this.applyNo = applyNo == null ? null : applyNo.trim();
}
public String getAppBill() {
return appBill;
}
public void setAppBill(String appBill) {
this.appBill = appBill;
}
public String getOutType() {
return outType;
}
public void setOutType(String outType) {
this.outType = outType == null ? null : outType.trim();
}
public Integer getPlusMinus() {
return plusMinus;
}
public void setPlusMinus(Integer plusMinus) {
this.plusMinus = plusMinus;
}
public String getStoreId() {
return storeId;
}
public void setStoreId(String storeId) {
this.storeId = storeId == null ? null : storeId.trim();
}
public String getInstrmCode() {
return instrmCode;
}
public void setInstrmCode(String instrmCode) {
this.instrmCode = instrmCode == null ? null : instrmCode.trim();
}
public String getTradeName() {
return tradeName;
}
public void setTradeName(String tradeName) {
this.tradeName = tradeName == null ? null : tradeName.trim();
}
public String getInstrmType() {
return instrmType;
}
public void setInstrmType(String instrmType) {
this.instrmType = instrmType == null ? null : instrmType.trim();
}
public String getBatchNo() {
return batchNo;
}
public void setBatchNo(String batchNo) {
this.batchNo = batchNo == null ? null : batchNo.trim();
}
public String getApprovalNo() {
return approvalNo;
}
public void setApprovalNo(String approvalNo) {
this.approvalNo = approvalNo == null ? null : approvalNo.trim();
}
@Column(name = "PRODUCE_DATE")
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
public Date getProduceDate() {
return produceDate;
}
public void setProduceDate(Date produceDate) {
this.produceDate = produceDate;
}
@Column(name = "VALID_DATE")
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
public Date getValidDate() {
return validDate;
}
public void setValidDate(Date validDate) {
this.validDate = validDate;
}
public BigDecimal getBuyPrice() {
return buyPrice;
}
public void setBuyPrice(BigDecimal buyPrice) {
this.buyPrice = buyPrice;
}
public BigDecimal getSalePrice() {
return salePrice;
}
public void setSalePrice(BigDecimal salePrice) {
this.salePrice = salePrice;
}
public BigDecimal getOutSum() {
return outSum;
}
public void setOutSum(BigDecimal outSum) {
this.outSum = outSum;
}
public String getMinUnit() {
return minUnit;
}
public void setMinUnit(String minUnit) {
this.minUnit = minUnit == null ? null : minUnit.trim();
}
public BigDecimal getBuyCost() {
return buyCost;
}
public void setBuyCost(BigDecimal buyCost) {
this.buyCost = buyCost;
}
public BigDecimal getSaleCost() {
return saleCost;
}
public void setSaleCost(BigDecimal saleCost) {
this.saleCost = saleCost;
}
public String getOutOper() {
return outOper;
}
public void setOutOper(String outOper) {
this.outOper = outOper == null ? null : outOper.trim();
}
@Column(name = "OUT_TIME")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
public Date getOutTime() {
return outTime;
}
public void setOutTime(Date outTime) {
this.outTime = outTime;
}
public String getOutputState() {
return outputState;
}
public void setOutputState(String outputState) {
this.outputState = outputState == null ? null : outputState.trim();
}
public String getComm() {
return comm;
}
public void setComm(String comm) {
this.comm = comm == null ? null : comm.trim();
}
@ManyToOne
@JoinColumn(name = "DEPT_ID", nullable = true)
@NotFound(action = NotFoundAction.IGNORE)
public Department getDeptInfo() {
return deptInfo;
}
public void setDeptInfo(Department deptInfo) {
this.deptInfo = deptInfo;
}
@ManyToOne
@JoinColumn(name = "TO_DEPT", nullable = true)
@NotFound(action = NotFoundAction.IGNORE)
public Department getToDept() {
return toDept;
}
public void setToDept(Department toDept) {
this.toDept = toDept;
}
@ManyToOne
@JoinColumn(name = "INSTRM_ID", nullable = true)
@NotFound(action = NotFoundAction.IGNORE)
public InstrmInfo getInstrmInfo() {
return instrmInfo;
}
public void setInstrmInfo(InstrmInfo instrmInfo) {
this.instrmInfo = instrmInfo;
}
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
public Date getPurchaseDate() {
return purchaseDate;
}
public void setPurchaseDate(Date purchaseDate) {
this.purchaseDate = purchaseDate;
}
} |
package com.zl.util;
/**
* @program: FruitSales
* @description: 整个应用常量类
* @author: ZhuLlin
* @create: 2019-01-08 15:16
**/
public class Constants {
//密码
public static final Integer HASHITERATIONS = 1024;
public static final String PASSWORD = "000000";
//权限等级
public static final Integer ROLE_PEASANT = 1;
public static final Integer ROLE_DEALER = 2;
//合同状态
public static final Integer CONTRACT_CONFIRM = 1;
public static final Integer CONTRACT_CANCEL = 2;
//异常错误提示
public static final String ERROR_CODE = "999";
public static final String ERROR_MSG = "通信异常,请及时联系系统管理员QQ:1320291471!";
public static final String ERROR_DELETE = "存在合同,无法直接删除";
//用户相关提示信息
public static final Integer ERROR_COUNT_MAX = 5;
public static final String ERROR_COUNT = "输入密码错误五次,锁定账号时长还剩";
public static final String EMPTY_USER = "当前用户不存在。";
public static final String ERROR_PASSWORD_BEFORE = "密码错误";
public static final String ERROR_PASSWORD_AFTER = "次,五次将锁定账号一小时。";
public static final String LOCK_USER = "当前用户已被锁定,请及时联系系统管理员QQ:1320291471!";
public static final String SUCCESS_RESET_PASSWORD = "密码重置成功";
public static final String SUCCESS_UPDATE_PASSWORD = "密码修改成功,请重新登录";
public static final String ERROR_USERINFO = "信息填写错误";
//系统相关信息
public static final String SYSINFO = "SysInfo";
public static final String SYSINFO_DEALER = "SysDealer";
public static final String SYSINFO_GARDEN = "SysGarden";
public static final String SYSINFO_CONTRACT = "SysContract";
public static final String SYSINFO_PEASANT = "SysPeasant";
public static final String SUCCESS_SYSINFO = "修改系统信息成功";
public static final String SUCCESS_MESSAGE = "成功";
//农民相关提示信息
public static final String SUCCESS_UPDATE = "修改成功";
public static final String SUCCESS_DELETE = "删除成功";
public static final String SUCCESS_INSERT = "添加成功,默认密码为000000";
public static final String ERROR_NUMBER = "不能超过剩余库存";
}
|
package jaolho.data.lma;
import solo.Vector2D;
public final class QuickLineFitter extends QuickLMA<Vector2D> {
/**
* @param parameters
* @param x
* @param y
* @param weights
* @param from
* @param to
*/
public QuickLineFitter(double[] parameters, Vector2D[] x, double[] y,
double[] weights, int from, int to) {
super(parameters, x, y, weights, from, to);
// TODO Auto-generated constructor stub
}
public QuickLineFitter(double[] parameters, Vector2D[] x, int from, int to) {
super(parameters, x, new double[to], from, to);
}
public QuickLineFitter(double[] parameters, Vector2D[] x) {
super(parameters, x, new double[x.length]);
}
/**
* @param parameters
* @param x
* @param y
* @param weights
*/
public QuickLineFitter(double[] parameters, Vector2D[] x, double[] y,
double[] weights) {
super(parameters, x, y, weights);
// TODO Auto-generated constructor stub
}
/**
* @param parameters
* @param x
* @param y
* @param from
* @param to
*/
public QuickLineFitter(double[] parameters, Vector2D[] x, double[] y,
int from, int to) {
super(parameters, x, y, from, to);
// TODO Auto-generated constructor stub
}
/**
* @param parameters
* @param x
* @param y
*/
public QuickLineFitter(double[] parameters, Vector2D[] x, double[] y) {
super(parameters, x, y);
// TODO Auto-generated constructor stub
}
@Override
public double getPartialDerivate(Vector2D xInput, double[] params, int paramIndex) {
switch (paramIndex){
case 0:return xInput.x;
case 1:return 1;
}
return 1;
}
@Override
public double getY(Vector2D x, double[] params) {
// TODO Auto-generated method stub
return x.y - (params[0]*x.x+params[1]);
}
public final double getA(){
return parameters[0];
}
public final double getB(){
return parameters[1];
}
}
|
package yinq.Initialize;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
import com.yinq.cherrydialyrecord.MainActivity;
import java.lang.reflect.InvocationTargetException;
import yinq.Request.HttpRequestManager;
import yinq.Request.HttpRequestObservice;
import yinq.datamodel.User.UserAccountModel;
import yinq.datamodel.User.UserInfoModel;
import yinq.datamodel.UserDefaults;
import yinq.ui.activity.ActivityUtil;
import yinq.ui.activity.UserLoginActivity;
import yinq.userModule.UserUtil;
import yinq.userModule.requests.UserInfoRequest;
import yinq.userModule.requests.UserLoginRequest;
/**
* Created by YinQ on 2018/11/28.
*/
public class InitializeUtil {
private Context context;
public InitializeUtil(Context context){
this.context = context;
}
public void startInitialize(){
UserDefaults userDefaults = new UserDefaults(context);
UserAccountModel userAccountModel = userDefaults.getLoginedUserAccount();
if (userAccountModel == null){
//用户还没有登录,需要跳转到登录界面
System.out.println("startInitialize user has not been logined.");
Intent intent = new Intent(context, UserLoginActivity.class);
context.startActivity(intent);
ActivityUtil activityUtil = ActivityUtil.shareActivityUtil();
Activity topActivity = activityUtil.getTopActivity();
activityUtil.intentAcitvity(UserLoginActivity.class);
topActivity.finish();
}
else {
//用户已经登录
//startLoadUserInfo(userAccountModel.getUserId());
startAutoLogin();
}
}
protected void startAutoLogin(){
UserDefaults userDefaults = new UserDefaults(context);
UserLoginRequest.LoginParam loginParam = userDefaults.getLoginParam();
HttpRequestObservice observice = new HttpRequestObservice() {
UserDefaults defaults = new UserDefaults(context);
@Override
public void onRequestSuccess(Object result) {
//保存登录账号信息
UserAccountModel accountModel = (UserAccountModel) result;
System.out.println("login success userId:" + accountModel.getUserId());
defaults.saveUserAccount(accountModel);
}
@Override
public void onRequestFail(int errCode, String errMsg) {
Toast.makeText(context, errMsg, Toast.LENGTH_SHORT).show();
}
@Override
public void onRequestComplete(int errCode) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
if (errCode == 0){
UserAccountModel accountModel = defaults.getLoginedUserAccount();
startLoadUserInfo(accountModel.getUserId());
}
}
};
UserUtil userUtil = new UserUtil();
try {
userUtil.startLogin(loginParam.getAccount(), loginParam.getPassword(), observice);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
public void startLoadUserInfo(String userId){
System.out.println("InitializeUtil::startLoadUserInfo");
if (userId == null || userId.isEmpty()){
return;
}
HttpRequestObservice observice = new HttpRequestObservice() {
@Override
public void onRequestSuccess(Object result) {
//保存登录的用户信息
UserDefaults userDefaults = new UserDefaults(context);
userDefaults.saveLoginedUserModel((UserInfoModel) result);
}
@Override
public void onRequestFail(int errCode, String errMsg) {
Toast.makeText(context, errMsg, Toast.LENGTH_SHORT).show();
}
@Override
public void onRequestComplete(int errCode) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
if (errCode == 0){
//跳转到主界面
Activity topActivity = ActivityUtil.shareActivityUtil().getTopActivity();
ActivityUtil.shareActivityUtil().intentAcitvity(MainActivity.class);
topActivity.finish();
}
}
};
UserUtil userUtil = new UserUtil();
try {
userUtil.startGetUserInfo(userId, observice);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
|
package com.example.a77354.android_final_project.PartnerAsking;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.example.a77354.android_final_project.HttpServiceInterface.GetArticleServiceInterface;
import com.example.a77354.android_final_project.HttpServiceInterface.GetPlanServiceInterface;
import com.example.a77354.android_final_project.R;
import com.example.a77354.android_final_project.RunPlan.PlanEntity;
import com.example.a77354.android_final_project.RunPlan.RunPlanActivity;
import com.example.a77354.android_final_project.ToolClass.HttpTool;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import me.imid.swipebacklayout.lib.SwipeBackLayout;
import me.imid.swipebacklayout.lib.Utils;
import me.imid.swipebacklayout.lib.app.SwipeBackActivityBase;
import me.imid.swipebacklayout.lib.app.SwipeBackActivityHelper;
import retrofit2.Retrofit;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* Created by shujunhuai on 2018/1/4.
*/
public class PartnerAskingActivity extends AppCompatActivity implements SwipeBackActivityBase {
class temp {
private String publisher;
private String content;
private String publishTime;
//还有两个变量,一个是发布者的头像、一个是有记得人点"约",即点"约"列表
public temp(String publisher, String content, String publishTime) {
this.publisher = publisher;
this.content = content;
this.publishTime = publishTime;
}
public String getContent() {
return content;
}
public String getPublisher() {
return publisher;
}
public String getPublishTime() {
return publishTime;
}
}
private SwipeBackActivityHelper swipeBackActivityHelper;
private List<PartnerAskingActivity.temp> dataList = new ArrayList<>();
private RecyclerView.Adapter adapter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.partner_asking_layout);
//顶部返回键的配置
swipeBackActivityHelper = new SwipeBackActivityHelper(this);
swipeBackActivityHelper.onActivityCreate();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setTitle("同校约跑");
//recyclerView伪数据填充
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.partner_asking_list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = getAdapter();
recyclerView.setAdapter(adapter);
//点击编辑一条新的帖子
FloatingActionButton addNewAskingBtn = (FloatingActionButton) findViewById(R.id.add_new_asking);
addNewAskingBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(PartnerAskingActivity.this, NewAskingActivity.class));
}
});
// 准备用来处理约跑功能
LayoutInflater factor = LayoutInflater.from(PartnerAskingActivity.this);
final View view_in = factor.inflate(R.layout.partner_asking_item_layout, null);
ImageButton yue = (ImageButton) view_in.findViewById(R.id.yue);
yue.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
private void prepareDataList() {
Retrofit retrofit = HttpTool.createRetrofit("http://112.124.47.197:4000/api/runner/", getApplicationContext(), "en");
GetArticleServiceInterface service = retrofit.create(GetArticleServiceInterface.class);
service.getArticle()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<Map<String, Map<String, String>>>(){
@Override
public final void onCompleted() {
Log.e("test", "完成传输");
}
@Override
public void onError(Throwable e) {
Toast.makeText(PartnerAskingActivity.this, e.hashCode() + "确认信息是否符合标准", Toast.LENGTH_SHORT).show();
Log.e("test", e.getMessage());
}
@Override
public void onNext(Map<String, Map<String, String>> responseBody) {
Log.e("test", responseBody.toString());
String articleid = "", title = "", author = "", content = "", addtime = "";
for (Map.Entry<String, Map<String, String>> entry : responseBody.entrySet()) {
for (Map.Entry<String, String> plan : entry.getValue().entrySet()) {
switch (plan.getKey()) {
case "articleid":
articleid = plan.getValue();
break;
case "title":
title = plan.getValue();
break;
case "author":
author = plan.getValue();
break;
case "content":
content = plan.getValue();
break;
case "addtime":
addtime = plan.getValue();
break;
default:
Toast.makeText(getApplicationContext(), "Error!", Toast.LENGTH_SHORT).show();
}
}
dataList.add(new PartnerAskingActivity.temp(author, title, addtime));
}
adapter.notifyDataSetChanged();
}
});
}
protected void onStart() {
super.onStart();
dataList.clear();
prepareDataList();
}
private RecyclerView.Adapter getAdapter() {
final LayoutInflater inflater = LayoutInflater.from(this);
RecyclerView.Adapter adapter = new RecyclerView.Adapter() {
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.partner_asking_item_layout, parent, false);
return new PartnerAskingActivity.MyViewHolder(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
PartnerAskingActivity.MyViewHolder myHolder = (PartnerAskingActivity.MyViewHolder) holder;
myHolder.bindData(dataList.get(position));
}
@Override
public int getItemCount() {
return dataList.size();
}
};
return adapter;
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView publisher;
TextView content;
TextView publishTime;
public MyViewHolder(View itemView) {
super(itemView);
this.publisher = (TextView) itemView.findViewById(R.id.publisher_nickname);
this.content = (TextView) itemView.findViewById(R.id.publish_content);
this.publishTime = (TextView) itemView.findViewById(R.id.publish_time);
}
public void bindData(PartnerAskingActivity.temp temp) {
publisher.setText(temp.getPublisher());
content.setText(temp.getContent());
publishTime.setText(temp.getPublishTime());
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return true;
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
swipeBackActivityHelper.onPostCreate();
}
@Override
public View findViewById(int id) {
View v = super.findViewById(id);
if (v == null && swipeBackActivityHelper != null)
return swipeBackActivityHelper.findViewById(id);
return v;
}
@Override
public SwipeBackLayout getSwipeBackLayout() {
return swipeBackActivityHelper.getSwipeBackLayout();
}
@Override
public void setSwipeBackEnable(boolean enable) {
getSwipeBackLayout().setEnableGesture(enable);
}
@Override
public void scrollToFinishActivity() {
Utils.convertActivityToTranslucent(this);
getSwipeBackLayout().scrollToFinishActivity();
}
}
|
package com.imagsky.v81j.domain.serialized;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Expose;
public abstract class BaseSerializedDomain {
@Expose
protected String sys_guid;
protected String getJsonString(Class thisClass, Object thisObj){
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String jsonStr = gson.toJson(thisObj, thisClass);
return jsonStr;
}
public abstract String getJsonString();
}
|
package com.online.jdbcconnection;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBConnection {
static Connection connection;
static String driverName="com.mysql.jdbc.Driver";
static String url="jdbc:mysql://localhost:3306/database?autoReconnect=true&useSSL=false";
static String user="root";
static String password="root";
public static Connection createConnection(){
try {
Class.forName(driverName);
connection=DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
}
|
package com.daydvr.store.view.person;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import com.daydvr.store.R;
import com.daydvr.store.base.BaseActivity;
import com.daydvr.store.bean.GameListBean;
import com.daydvr.store.presenter.person.ExchangeContract;
import com.daydvr.store.presenter.person.ExchangeContract.Presenter;
import com.daydvr.store.presenter.person.ExchangePresenter;
import com.daydvr.store.view.adapter.ExchangeListAdapter;
import com.daydvr.store.view.custom.CommonToolbar;
import com.daydvr.store.view.game.GameDetailActivity;
import java.util.ArrayList;
import java.util.List;
public class ExchangeRecordsActivity extends BaseActivity implements ExchangeContract.View {
private CommonToolbar mToolBar;
private RecyclerView mRecyclerView;
private ExchangeListAdapter mAppListAdapter;
private ExchangePresenter mPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exchange_records);
mPresenter = new ExchangePresenter(this);
initView();
initData();
}
private void initData() {
mPresenter.loadExchangeAppList();
}
private void initView() {
mToolBar = findViewById(R.id.toolbar);
mRecyclerView = findViewById(R.id.rv_exchange_records);
configComponent();
}
private void configComponent() {
mToolBar.setCenterTitle(getResources().getString(R.string.exchange_record));
mToolBar.initmToolBar(this,true);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayout.VERTICAL,false));
}
@Override
public void setPresenter(Presenter presenter) {
mPresenter = (ExchangePresenter) presenter;
}
@Override
public <T> void showExchangeList(List<T> beans) {
if (mAppListAdapter == null) {
mAppListAdapter = new ExchangeListAdapter();
mAppListAdapter.setListener(mItemListener);
mRecyclerView.setAdapter(mAppListAdapter);
mAppListAdapter.setDatas((ArrayList<GameListBean>) beans);
}
mAppListAdapter.notifyDataSetChanged();
}
@Override
protected void onDestroy() {
super.onDestroy();
mPresenter.freeView();
mPresenter = null;
}
@Override
public Context getViewContext() {
return this;
}
@Override
public void jumpGameDetail() {
Intent i = new Intent(this, GameDetailActivity.class);
startActivity(i);
}
private ExchangeListAdapter.ItemOnClickListener mItemListener = new ExchangeListAdapter.ItemOnClickListener() {
@Override
public void onItemClick(View view, int position) {
mPresenter.intoAppDetail(position);
}
@Override
public void onButtonClick(View view, int position) {
}
};
}
|
package com.explore.common;
public class Const {
public static String CURRENT_USER = "current_user";
public interface ExamStatus{
//等待审核通过
int WAIT_CHECK_PASS = 0;
//审核通过
int CHECK_PASS = 1;
//审核不通过
int CHECK_NO_PASS = 2;
//考试通过
int EXAM_PASS = 3;
//考试不通过
int EXAM_NO_PASS = 4;
}
/**
* 配置类型
*/
public enum CONF_TYPE{
//
VEHICLE(2000,"车辆配置"),
SOURCE(2001,"物资配置"),
COACH(3001,"教练配置"),
STUDENT(3002,"学员配置"),
STAFF(3003,"员工配置");
private int code;
private String desc;
CONF_TYPE(int code, String desc) {
this.code = code;
this.desc = desc;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}}
}
|
package ui;
import ui.Board;
import javax.swing.*;
import java.awt.*;
public class Game extends JPanel {
private JLayeredPane layeredPane;
JLabel scoreLabel;
JSlider cellSizeSlider;
Board board;
GameOver gameOver;
int margin = 50;
public Game() {
scoreLabel = new JLabel("0");
layeredPane = new JLayeredPane();
layeredPane.setPreferredSize(new Dimension(Board.getBoardWidth(), Board.getBoardHeight()));
board = new Board(score -> scoreLabel.setText(Integer.toString(score)), new OnGameOverListener());
gameOver = new GameOver(() -> {
board.reset();
layeredPane.remove(gameOver);
scoreLabel.setText("0");
});
layeredPane.add(board, JLayeredPane.DEFAULT_LAYER);
this.setLayout(new BorderLayout());
this.add(layeredPane, BorderLayout.CENTER);
this.add(scoreLabel, BorderLayout.NORTH);
}
class OnGameOverListener implements Board.OnGameOverListener {
@Override
public void onGameOver() {
layeredPane.add(gameOver, JLayeredPane.POPUP_LAYER);
}
}
}
|
package com.cxxt.mickys.playwithme.presenter.login;
import android.content.Context;
/**
* 登录 presenter 层接口
*
* @author huangyz0918
*/
public interface LoginPresenter {
void validateCredentials(String username, Context context, String password);
void onDestroy();
} |
package cn;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* Created by max.lu on 2016/3/23.
*/
public class MessageServiceTest {
private MessageService messageService;
@Before
public void init() {
messageService = new MessageService();
}
@Test
public void testGetMessage() {
Assert.assertEquals("max1", messageService.getMessage());
}
}
|
package cn.algerfan;
/**
* 10- II. 青蛙跳台阶问题
一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶。求该青蛙跳上一个 n 级的台阶总共有多少种跳法。
答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。
示例 1:
输入:n = 2
输出:2
示例 2:
输入:n = 7
输出:21
* @author algerfan
*/
public class Offer10_2 {
public int numWays(int n) {
if(n == 0) {
return 1;
}
if(n <= 2) {
return n;
}
int pre1 = 1, pre2 = 2;
int num = 0;
for (int i = 2; i < n; i++) {
num = (pre1 + pre2) % 1000000007;
pre1 = pre2;
pre2 = num;
}
return num;
}
}
|
/**
*
*/
package com.vinodborole.portal.web.error;
/**
* @author vinodborole
*
*/
public class RoleAlreadyExistException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = -3223019491169042346L;
public RoleAlreadyExistException() {
super();
}
public RoleAlreadyExistException(final String message, final Throwable cause) {
super(message, cause);
}
public RoleAlreadyExistException(final String message) {
super(message);
}
public RoleAlreadyExistException(final Throwable cause) {
super(cause);
}
}
|
package share.wifi.csz.com.wifishare.permission;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Binder;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import share.wifi.csz.com.wifishare.permission.support.ManufacturerSupportUtil;
import share.wifi.csz.com.wifishare.permission.support.PermissionsPageManager;
import share.wifi.csz.com.wifishare.permission.support.apply.PermissionsChecker;
/**
* Created by csz on 2018/5/18.
*/
public class PermissionHelper {
/**
* 对国产orm的定制化权限适配
* @return 返回未授权的权限集合
*/
public static boolean checkPermissions(SmartPermission.Body requestBody) {
return getNoGrantPermissions(requestBody).isEmpty();
}
/**
* 对国产orm的定制化权限适配
* @return 返回未授权的权限集合
*/
public static List<String> getNoGrantPermissions(SmartPermission.Body requestBody) {
List<String> noGrantPermission = new ArrayList<>();
//匹配5.0-6.0的国产定制orm
if (ManufacturerSupportUtil.isUnderMNeedChecked(true)) {
for (String permission : requestBody.getPers()) {
if (PermissionsChecker.isPermissionGranted(requestBody.getActivity(), permission)) {
//允许
} else {
//拒绝
noGrantPermission.add(permission);
}
}
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
for (String permission : requestBody.getPers()) {
if (ContextCompat.checkSelfPermission(requestBody.getActivity(), permission) == PackageManager.PERMISSION_GRANTED) {
//允许
if (!PermissionsChecker.isPermissionGranted(requestBody.getActivity(), permission)) {
noGrantPermission.add(permission);
}
} else {
noGrantPermission.add(permission);
}
}
} else {
//其他情况都为允许
}
return noGrantPermission;
}
/**
* 对国产orm的定制化权限适配
*/
public static void requestPermissionWithListener(SmartPermission.Body requestBody,List<String> noGrantList) {
List<String> noGrantPermission = noGrantList;
//被用户拒绝权限后做额外的处理
if (!noGrantPermission.isEmpty()) {
int pageType = requestBody.getPageType();
Intent intent = null;
if (pageType == SmartPermission.PageType.MANAGER_PAGE) {
intent = PermissionsPageManager.getIntent(requestBody.getActivity());
} else if (pageType == SmartPermission.PageType.ANDROID_SETTING_PAGE) {
intent = PermissionsPageManager.getSettingIntent(requestBody.getActivity());
}
//国产5.0-6.0
if (ManufacturerSupportUtil.isUnderMNeedChecked(true)) {
} else {
//国产6.0及以上版本 及 被系统拒绝
requestPermission(requestBody.getActivity(), noGrantPermission, requestBody.getRequestCode());
}
}
}
/**
* 检查运行时权限并且请求权限 (Activity)
*
* @param activity
* @param permissions
* @param requestCode
* @return
*/
public static boolean requestAftercheckPermission(Activity activity, String[] permissions, int requestCode) {
List<String> list = new ArrayList<>();
for (String per : permissions) {
int code = ContextCompat.checkSelfPermission(activity, per);
if (code != PackageManager.PERMISSION_GRANTED) {
list.add(per);
}
}
if (list.isEmpty()) {
return true;
}
String[] ungrabted = new String[list.size()];
ActivityCompat.requestPermissions(activity, list.toArray(ungrabted), requestCode);
return false;
}
/**
* 检查运行时权限并且请求权限 (Fragment)
*
* @param fragment
* @param permissions
* @param requestCode
* @return
*/
public static boolean requestAftercheckPermission(Fragment fragment, String[] permissions, int requestCode) {
List<String> list = new ArrayList<>();
for (String per : permissions) {
int code = ContextCompat.checkSelfPermission(fragment.getActivity(), per);
if (code != PackageManager.PERMISSION_GRANTED) {
list.add(per);
}
}
if (list.isEmpty()) {
return true;
}
String[] ungrabted = new String[list.size()];
fragment.requestPermissions(list.toArray(ungrabted), requestCode);
return false;
}
/**
* 请求运行时权限 (Activity)
*
* @param activity
* @param permissions
* @param requestCode
* @return
*/
public static boolean requestPermission(Activity activity, List<String> permissions, int requestCode) {
String[] ungrabted = new String[permissions.size()];
ActivityCompat.requestPermissions(activity, permissions.toArray(ungrabted), requestCode);
return false;
}
/**
* 检查权限列表
*
* @param op 这个值被hide了,去AppOpsManager类源码找,如位置权限 AppOpsManager.OP_GPS==2
* 0是网络定位权限,1是gps定位权限,2是所有定位权限
* 返回值:0代表有权限,1代表拒绝权限 ,3代表询问是否有 ,-1代表出错
*/
public static int checkOp(Context context, int op) {
final int version = Build.VERSION.SDK_INT;
if (version >= 19) {
Object object = context.getSystemService(Context.APP_OPS_SERVICE);
Class c = object.getClass();
try {
Class[] cArg = new Class[3];
cArg[0] = int.class;
cArg[1] = int.class;
cArg[2] = String.class;
Method lMethod = c.getDeclaredMethod("checkOp", cArg);
return (Integer) lMethod.invoke(object, op, Binder.getCallingUid(), context.getPackageName());
} catch (Exception e) {
e.printStackTrace();
}
}
return -1;
}
/**
* Activity调用这个方法监听
*
* @param requestCode
* @param permissions
* @param grantResults
*/
public static void onReqPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
//DialogHelper.dismiss();
if (grantResults.length <= 0) {
return;
}
ISuccess success = RequestManager.getSuccess(requestCode);
IFailure failure = RequestManager.getFailure(requestCode);
boolean allowed = checkGranted(grantResults);
if (allowed) {
if (success != null) {
success.onSuccess();
}
} else {
if (failure != null) {
failure.onFailure();
}
}
RequestManager.removeSuccess(requestCode);
RequestManager.removeFailure(requestCode);
}
/**
* 用户的授权结果
*/
private static boolean checkGranted(int[] grantResults) {
boolean allowed = true;
for (int result : grantResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
allowed = false;
break;
}
}
return allowed;
}
}
|
/**
* <p>This package contains Spring's JSP standard tag library for JSP 2.0+.
* Supports JSP view implementations within Spring's Web MVC framework.
* For more details on each tag, see the list of tags below with links to
* individual tag classes, or check the {@code spring.tld} file:
*
* <ul>
* <li>{@link org.springframework.web.servlet.tags.ArgumentTag The argument tag}
* <li>{@link org.springframework.web.servlet.tags.BindTag The bind tag}
* <li>{@link org.springframework.web.servlet.tags.BindErrorsTag The hasBindErrors tag}
* <li>{@link org.springframework.web.servlet.tags.EscapeBodyTag The escapeBody tag}
* <li>{@link org.springframework.web.servlet.tags.EvalTag The eval tag}
* <li>{@link org.springframework.web.servlet.tags.HtmlEscapeTag The htmlEscape tag}
* <li>{@link org.springframework.web.servlet.tags.MessageTag The message tag}
* <li>{@link org.springframework.web.servlet.tags.NestedPathTag The nestedPath tag}
* <li>{@link org.springframework.web.servlet.tags.ParamTag The param tag}
* <li>{@link org.springframework.web.servlet.tags.ThemeTag The theme tag}
* <li>{@link org.springframework.web.servlet.tags.TransformTag The transform tag}
* <li>{@link org.springframework.web.servlet.tags.UrlTag The url tag}
* </ul>
*
* <p>Please note that the various tags generated by this form tag library are
* compliant with https://www.w3.org/TR/xhtml1/ and attendant
* https://www.w3.org/TR/xhtml1/dtds.html#a_dtd_XHTML-1.0-Strict.
*/
@NonNullApi
@NonNullFields
package org.springframework.web.servlet.tags;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;
|
package com.beike.wap.dao.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.stereotype.Repository;
import com.beike.dao.GenericDaoImpl;
import com.beike.entity.user.User;
import com.beike.entity.user.UserProfile;
import com.beike.form.ProfileForm;
import com.beike.form.UserForm;
import com.beike.wap.dao.MUserDao;
/**
* <p>
* Title: 用户数据库基本操作
* </p>
* <p>
* Description:
* </p>
* <p>
* Copyright: Copyright (c) 2011
* </p>
* <p>
* Company: Sinobo
* </p>
*
* @date 2011-09-22
* @author kun.wang
* @version 1.0
*/
@Repository("mUserDao")
public class MUserDaoImpl extends GenericDaoImpl<User, Long> implements MUserDao {
@Override
public User findUserByEmail(String email) {
String sql = "select * from beiker_user where email=?";
User user = null;
try {
List<User> userList = getSimpleJdbcTemplate().query(sql,
new RowMapperImpl(), email);
if (userList.size() > 0) {
user = userList.get(0);
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return user;
}
@Override
public User findUserByMobile(String mobile) {
String sql = "select * from beiker_user where mobile=?";
User user = null;
try {
List<User> userList = getSimpleJdbcTemplate().query(sql,
new RowMapperImpl(), mobile);
if (userList.size() > 0) {
user = userList.get(0);
}
} catch (Exception e) {
e.printStackTrace();
}
return user;
}
protected class RowMapperImpl implements ParameterizedRowMapper<User> {
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setEmail(rs.getString("email"));
user.setEmail_isavalible(rs.getLong("email_isavalible"));
user.setId(rs.getInt("user_id"));
user.setIsavalible(rs.getLong("isavalible"));
user.setMobile(rs.getString("mobile"));
user.setMobile_isavalible(rs.getLong("mobile_isavalible"));
user.setPassword(rs.getString("password"));
user.setCustomerkey(rs.getString("customerkey"));
return user;
}
}
@Override
public void addUser(UserForm userForm) {
String sql = "insert into beiker_user (email,mobile,email_isavalible,mobile_isavalible,password,isavalible,customerkey,createdate) values (?,?,?,?,?,?,?,?)";
getSimpleJdbcTemplate().update(sql, userForm.getEmail(),
userForm.getMobile(),
userForm.getEmail_isavalible() + "",
userForm.getMobile_isavalible() + "",
userForm.getPassword(),
userForm.getIsavalible() + "",
userForm.getCustomerKey(),
new Date());
}
@Override
public User findById(long userId) {
String sql = "select * from beiker_user where user_id=?";
User user = null;
try {
List<User> userList = getSimpleJdbcTemplate().query(sql,
new RowMapperImpl(), userId);
if (userList.size() > 0) {
user = userList.get(0);
}
} catch (Exception e) {
e.printStackTrace();
}
return user;
}
@Override
public void addProfile(ProfileForm proFileForm) {
String sql = "insert into beiker_userprofile (name,value,profiletype,userid,profiledate) values(?,?,?,?,?)";
Date date = new Date();
getSimpleJdbcTemplate().update(sql, proFileForm.getName(),
proFileForm.getValue(),
proFileForm.getProFileType().toString(),
proFileForm.getUserid(), date);
}
@Override
public void updateUserProfile(UserProfile userProfile) {
String sql = "update beiker_userprofile b set b.name=?,b.value=? where b.id=?";
getSimpleJdbcTemplate().update(sql, userProfile.getName(),
userProfile.getValue(), userProfile.getId());
}
@Override
public UserProfile getUserProfile(Long userid, String name) {
String sql = "select * from beiker_userprofile where userid=? and name=?";
UserProfile up = null;
try {
List<UserProfile> upList = getSimpleJdbcTemplate().query(sql,
new ProfileRowMapperImpl(), userid, name);
if (upList.size() > 0) {
up = upList.get(0);
}
} catch (Exception e) {
e.printStackTrace();
}
return up;
}
protected class ProfileRowMapperImpl implements ParameterizedRowMapper<UserProfile> {
public UserProfile mapRow(ResultSet rs, int rowNum) throws SQLException {
UserProfile userProfile = new UserProfile();
userProfile.setId(rs.getLong("id"));
userProfile.setName(rs.getString("name"));
userProfile.setValue(rs.getString("value"));
userProfile.setUserid(rs.getLong("userid"));
userProfile.setProfiledate(rs.getDate("profiledate"));
return userProfile;
}
}
}
|
package dados;
import java.util.ArrayList;
import java.util.List;
import negocios.beans.Produto;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Collections;
public class RepositorioProduto implements IRepositorioProduto, Serializable {
/**
*
*/
private static final long serialVersionUID = -4891963491984056414L;
private ArrayList<Produto> listaProdutos;
private static RepositorioProduto instance;
public RepositorioProduto() {
this.listaProdutos = new ArrayList<Produto>();
}
public static RepositorioProduto getInstance() {
if (instance == null) {
instance = new RepositorioProduto();
instance = lerDoArquivo();
}
return instance;
}
public ArrayList<Produto> getListaProdutos() {
return listaProdutos;
}
private static RepositorioProduto lerDoArquivo() {
RepositorioProduto instanciaLocal = null;
File in = new File("produtos.dat");
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream(in);
ois = new ObjectInputStream(fis);
Object o = ois.readObject();
instanciaLocal = (RepositorioProduto) o;
} catch (Exception e) {
instanciaLocal = new RepositorioProduto();
} finally {
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
System.out.println("Não foi possível fechar o arquivo!");
e.printStackTrace();
}
}
}
return instanciaLocal;
}
public void salvarArquivo() {
if (instance == null) {
return;
}
File out = new File("produtos.dat");
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream(out);
oos = new ObjectOutputStream(fos);
oos.writeObject(instance);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
System.out.println("Não foi possível fechar o arquivo!");
e.printStackTrace();
}
}
}
}
public boolean inserir(Produto produto) {
try {
listaProdutos.add(produto);
} catch (Exception e) {
return false;
}
return true;
}
public boolean alterar(Produto novoProduto) {
ArrayList<Produto> listaRemovidos = new ArrayList<Produto>();
boolean alt = false;
for (Produto produto : listaProdutos) {
if (produto.getCodigo() == novoProduto.getCodigo()) {
listaRemovidos.add(produto);
alt = true;
}
}
listaProdutos.removeAll(listaRemovidos);
listaProdutos.add(novoProduto);
return alt;
}
public Produto buscar(int codigo) {
for (Produto produto : listaProdutos) {
if (produto.getCodigo() == codigo) {
return produto;
}
}
return null;
}
public boolean remover(int codigo) {
boolean igual = false;
for (int i = 0; i < listaProdutos.size(); i++) {
if (listaProdutos.get(i).getCodigo() == codigo) {
listaProdutos.remove(i);
igual = true;
}
}
return igual;
}
public boolean produtoContem(Produto produto) {
boolean contem = false;
if (listaProdutos.contains(produto)) {
contem = true;
}
return contem;
}
public boolean existe(int codigo) {
int p;
boolean x = false;
for (Produto produto : listaProdutos) {
p = produto.getCodigo();
if (p == codigo) {
x = true;
}
}
return x;
}
public List<Produto> listar() {
return Collections.unmodifiableList(this.listaProdutos);
}
@Override
public String toString() {
return "RepositorioProduto [listaProdutos = " + listaProdutos + "]";
}
} |
package ratio;
import java.util.List;
import java.util.stream.Collectors;
import storage.Game;
public class SimpleRatio implements Ratio {
@Override
public List<Rating> get(List<Game> games, List<String> players) {
return WinLoss.getWinLoss(games, players).stream().map(this::cast)
.collect(Collectors.toList());
}
/**
* calculate wins/losses
* @param wins
* @param losses
* @return
*/
public double ratio(int wins, int losses) {
if (wins == 0)
return 0;
if (losses == 0)
return 1 / Math.exp(wins);
return (double) wins / (double) losses;
}
private Rating cast(WinLoss wl) {
return new Rating(wl.player, ratio(wl.wins, wl.losses));
}
}
|
package com.appmanage.mapper;
import com.appmanage.entity.DataDictionary;
import com.appmanage.entity.DataDictionaryExample;
import java.util.List;
public interface DataDictionaryMapper {
int deleteByPrimaryKey(Long id);
int insert(DataDictionary record);
int insertSelective(DataDictionary record);
List<DataDictionary> selectByExample(DataDictionaryExample example);
DataDictionary selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(DataDictionary record);
int updateByPrimaryKey(DataDictionary record);
} |
/*************************************************/
// for demo generated by maven 3.2.5
// 2015-01-30
// GitHub - Bamboo/JIRA CLOUD integration
// When commit,
// commit with JIRA KEY such like @HELLO-3
// smart commit
/*************************************************/
// for JIRA-Fecru Integration Test
// 2015-05-26 13:13 N.Chihara
// 2015-08-18 13:51 N.Chihara :: Bamboo test
// 2015-12-03 11:35 N.Chihara :: Confluence Integration Test with "Git for Confluenc"e
package com.go2group.g2gjp.demo;
/**
* Hello world
*
*/
public class App
{
public static void main( String[] args )
{
/* DEMO : */
/* these 2 lines causes type mis-match error on compile */
int i=0;
// this line causes type mis-match error on compile
// i = "This line causes Error!";
String str = "This line causes Error!";
// is this enough for DEMO?
System.out.println( "*** Hello World! ***" );
// System.out.println( "*** JIRA-Fecru Integration Test ****");
}
}
|
package lawscraper.server.entities.caselaw;
import lawscraper.server.entities.superclasses.Document.DocumentPart;
import lawscraper.shared.DocumentListItem;
import lawscraper.shared.DocumentPartType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.HashSet;
/**
* Created by erik, IT Bolaget Per & Per AB
* <p/>
* Date: 6/13/12
* Time: 6:42 PM
*/
@Entity
@Table(name = "caseLaw")
public class CaseLaw extends CaseLawDocumentPart implements DocumentListItem {
private String publicationYear;
private String publisher;
private String creator;
private String relation;
private String caseIdentifier;
private String casePublication;
private String caseNumber;
private String decisionDate;
private String pageNumber;
public String getPublicationYear() {
return publicationYear;
}
public CaseLaw() {
this.setPartType(DocumentPartType.CASELAW);
}
@Column(length = 255)
public String getCreator() {
return creator;
}
@Column(length = 1024)
public String getRelation() {
return relation;
}
@Column(length = 255)
public String getCaseIdentifier() {
return caseIdentifier;
}
@Column(length = 255)
public String getCasePublication() {
return casePublication;
}
@Column(length = 255)
public String getDecisionDate() {
return decisionDate;
}
@Column(length = 20)
public String getPageNumber() {
return pageNumber;
}
public void setPageNumber(String pageNumber) {
this.pageNumber = pageNumber;
}
@Column(length = 255)
public String getPublisher() {
return publisher;
}
@Column(length = 255)
public String getCaseNumber() {
return caseNumber;
}
public void setCaseNumber(String caseNumber) {
this.caseNumber = caseNumber;
}
public void setPublicationYear(String publicationYear) {
this.publicationYear = publicationYear;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public void setCreator(String creator) {
this.creator = creator;
}
public void setRelation(String relation) {
this.relation = relation;
}
public void setCaseIdentifier(String caseIdentifier) {
this.caseIdentifier = caseIdentifier;
}
public void addSubject(DocumentPart subject) {
subject.addDocumentReference(this);
}
public void setCasePublication(String casePublication) {
this.casePublication = casePublication;
}
public void setDecisionDate(String decisionDate) {
this.decisionDate = decisionDate;
}
public void addCaseLawDocumentPart(CaseLawDocumentPart part) {
if (getParts() == null) {
setParts(new HashSet<CaseLawDocumentPart>());
}
part.setListOrder(getParts().size());
getParts().add(part);
}
}
|
/**
* Enumeration class Suit - write a description of the enum class here
*
* @colinbowen
* @0.1
*/
public enum Suit
{
HEARTS,
CLUBS,
DIAMONDS,
SPADES
}
|
package DataFactoryService;
import dataservice.matchdataservice.MatchDataService;
import dataservice.playerdataservice.PlayerDataService;
import dataservice.teamdataservice.TeamDataService;
public interface NBADataFactory
{
public MatchDataService getMatchData();
public PlayerDataService getPlayerData();
public TeamDataService getTeamData();
}
|
package com.dbs.portal.ui.component.pagetable;
import java.util.Map;
import com.dbs.portal.ui.component.application.IApplication;
public interface PagedTableComponentVisibility {
public boolean showComponent(Map<String, Object> data);
public void setApplication(IApplication application);
}
|
/**
*
*/
package com.vinodborole.portal.products;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
/**
* @author vinodborole
*
*/
public class PortalRestTemplate<T> {
private IPortalProductSession productSession;
private RestTemplate rest;
private HttpHeaders headers;
private HttpStatus status;
private String server;
public PortalRestTemplate(IPortalProductSession productSession) {
this.productSession = productSession;
this.rest = new RestTemplate();
this.headers = new HttpHeaders();
headers.add("Accept", "*/*");
if (productSession.getProductToken() != null)
headers.add("Authorization", "Bearer " + productSession.getProductToken());
if (productSession.getProductConfig() != null)
this.server = productSession.getProductConfig().get("host");
}
public void setContentType(MediaType mediaType) {
headers.setContentType(mediaType);
}
public void addHeader(String key, String value) {
headers.add(key, value);
}
public ResponseEntity get(String uri) {
HttpEntity<String> requestEntity = new HttpEntity<String>("", headers);
ResponseEntity<String> responseEntity = rest.exchange(server + uri, HttpMethod.GET, requestEntity,
String.class);
this.setStatus(responseEntity.getStatusCode());
return responseEntity;
}
public ResponseEntity post(String uri, T entity) {
HttpEntity<T> request = new HttpEntity<T>(entity, headers);
ResponseEntity<String> response = rest.postForEntity(server + uri, request, String.class);
return response;
}
public ResponseEntity put(String uri, String json) {
HttpEntity<String> requestEntity = new HttpEntity<String>(json, headers);
ResponseEntity<String> responseEntity = rest.exchange(server + uri, HttpMethod.PUT, requestEntity,
String.class);
return responseEntity;
}
public ResponseEntity delete(String uri) {
HttpEntity<String> requestEntity = new HttpEntity<String>("", headers);
ResponseEntity<String> responseEntity = rest.exchange(server + uri, HttpMethod.DELETE, requestEntity,
String.class);
return responseEntity;
}
public HttpStatus getStatus() {
return status;
}
public void setStatus(HttpStatus status) {
this.status = status;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.