text
stringlengths 10
2.72M
|
|---|
package com.company.service;
import com.company.config.trip.TripConfig;
import com.company.dao.DriverDao;
import com.company.dao.DriverLocationDao;
import com.company.dao.RiderDao;
import com.company.entities.Driver;
import com.company.entities.DriverLocation;
import com.company.entities.Rider;
import com.company.model.DriverModel;
import com.company.model.RideInputModel;
import com.company.util.DistanceUtil;
import com.company.util.MappingUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
@Slf4j
@Service
public class TripAssignmentService {
private final DriverDao driverDao;
private final DriverLocationDao driverLocationDao;
private final RiderDao riderDao;
private TripConfig tripConfig;
@Autowired
public TripAssignmentService(DriverDao driverDao, DriverLocationDao driverLocationDao, RiderDao riderDao, TripConfig tripConfig) {
this.driverDao = driverDao;
this.driverLocationDao = driverLocationDao;
this.riderDao = riderDao;
this.tripConfig = tripConfig;
}
public void validateRider(RideInputModel rideInputModel) throws Exception {
Rider rider = riderDao.findByUniqueId(rideInputModel.getRiderId());
if(rider==null)
throw new Exception("Invalid rider Details.");
if(rider.getEngaged()){
log.error("Rider : {} is already commuting. No trip assignment required.", rideInputModel.getRiderId());
throw new Exception("You are already commuting. Please complete this trip before starting another trip.");
}
}
public DriverModel getTripDetails(RideInputModel rideInputModel){
List<DriverLocation> driverLocationList = getDriverList(rideInputModel);
//TODO: use the commented section when spatial query is working
// List<DriverModel> driverModels = new ArrayList<>();
// for(DriverLocation dl : driverLocationList){
// driverModels.add(getConvertedDriverModel(dl, 0.0));
// }
//TODo: comment below line when spatial query is working
List<DriverModel> driverModels = filterDrivers(driverLocationList, rideInputModel);
if(driverModels!=null && !driverModels.isEmpty()){
DriverModel driverModel = driverModels.get(0);
Driver byUniqueId = driverDao.findByUniqueId(driverModel.getDriverUniqueId());
byUniqueId.setEngaged(true);
driverDao.saveOrUpdate(byUniqueId);
Rider rider = riderDao.findByUniqueId(rideInputModel.getRiderId());
rider.setEngaged(true);
//TODO: create a record in the Trip table
return driverModel;
}
return null;
}
private List<DriverModel> filterDrivers(List<DriverLocation> driverList, RideInputModel rideInputModel) {
List<DriverModel> filteredDrivers = new ArrayList<>();
double distanceInMeter = tripConfig.getRadiusInKm()*1000;
for (DriverLocation dl : driverList) {
applyRestrictions(dl, filteredDrivers, rideInputModel, distanceInMeter);
}
return filteredDrivers;
}
/**
* the gating criteria are checked to pick the most suitable driver for the trip.
* @param dl
* @param filteredDrivers
* @param rideInputModel
* @param distance
*/
private void applyRestrictions(DriverLocation dl, List<DriverModel> filteredDrivers, RideInputModel rideInputModel, double distance) {
Double actualDistance = DistanceUtil.distanceBetweenLatLong(rideInputModel.getSourceLatitude(), dl.getLatitude(), rideInputModel.getSourceLongitude(), dl.getLongitude());
if(actualDistance<=distance) {
filteredDrivers.add(getConvertedDriverModel(dl, actualDistance));
}
//TODO: the conditions like rating ratio, preferred transport, payment method can be checked here
if(!filteredDrivers.isEmpty()){
filteredDrivers.sort(Comparator.comparing(o -> o.getDriverLocationModel().getTime()));
}
// System.out.println(filteredDrivers);
}
private DriverModel getConvertedDriverModel(DriverLocation dl, double distance) {
Driver driver = driverDao.findById(dl.getDriverId());
DriverModel driverModel = MappingUtil.convertDriverToModel(driver);
driverModel.setDriverLocationModel(MappingUtil.convertDriverLocationToModel(dl));
driverModel.setDriverDistanceFromRider(distance);
return driverModel;
}
private List<DriverLocation> getDriverList(RideInputModel rideInputModel) {
List<Driver> nonEngagedDrivers = driverDao.findNonEngagedDrivers();
//TODO: use this commented section when spatial query is working
// return driverLocationDao.findDriversWithLocationCriteria(nonEngagedDrivers, tripConfig.getRadiusInKm(), rideInputModel.getSourceLatitude(), rideInputModel.getSourceLongitude(), tripConfig.getLocationConsiderationTimeInMinute());
//TODo: comment below line when spatial query is working
return driverLocationDao.findDriverLocations(nonEngagedDrivers, tripConfig.getLocationConsiderationTimeInMinute());
}
}
|
package com.mod.loan.model.DTO;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.io.Serializable;
import java.util.List;
/**
* 决策流处理结果
*
* @author lijing
* @date 2017/11/14 0014
*/
@Getter
@Setter
@ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public class DecisionResDetailDTO implements Serializable {
@JsonProperty("decision_no")
private String decision_no;
@JsonProperty("trans_id")
private String trans_id;
@JsonProperty("orderStatus")
private String orderStatus;
@JsonProperty("order_money")
private Long order_money;
@JsonProperty("fee")
private Boolean fee;
@JsonProperty("custom_grade")
private List<Object> custom_grade;
@JsonProperty("code")
private String code;
@JsonProperty("desc")
private String desc;
@JsonProperty("res_score")
private Double resScore;
@JsonProperty("strategies")
private List<StrategyDTO> strategies;
}
|
package com.zd.christopher.action;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.zd.christopher.bean.Entity;
import com.zd.christopher.transaction.NaturalIdTransaction;
@Controller
@Scope("prototype")
public class NaturalIdAction<TEntity extends Entity>
{
@Resource
private NaturalIdTransaction<TEntity> naturalIdTransaction;
private Class<TEntity> entityClass;
public Class<TEntity> getEntityClass()
{
return entityClass;
}
public void setEntityClass(Class<TEntity> entityClass)
{
this.entityClass = entityClass;
}
private void setParams()
{
naturalIdTransaction.setEntityClass(entityClass);
}
public TEntity findByNaturalId(TEntity entity)
{
setParams();
return naturalIdTransaction.findByNaturalId(entity);
}
public List<TEntity> findByNaturalIds(TEntity[] entities)
{
setParams();
return naturalIdTransaction.findByNaturalIds(entities);
}
public List<TEntity> findByNaturalIdsByPage(TEntity[] entities, Integer count, Integer page)
{
setParams();
return naturalIdTransaction.findByNaturalIdsByPage(entities, count, page);
}
}
|
package com.software3.servlet;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.software3.service.BookService;
import com.software3.service.impl.BookServiceImpl;
@WebServlet("/deletebook")
public class DeleteBookServlet extends HttpServlet
{
/**
*
*/
private static final long serialVersionUID = 1L;
BookService bs = new BookServiceImpl();
protected void doGet(HttpServletRequest request,HttpServletResponse response){
response.setCharacterEncoding("utf-8");
try
{
if(bs.deleteBook(Integer.parseInt(request.getParameter("bookid")),
request.getSession(true).getAttribute("studentid").toString())){
response.getWriter().write("操作成功");
}
else{
response.getWriter().write("操作失败");
}
} catch (IOException e)
{
e.printStackTrace();
}
}
}
|
package 飞毛腿外卖团;
import java.sql.*;
//与数据库获取连接
public class GetConnection {
//申明连接数据库中需要的变量
static ResultSet rs = null;
static Statement st = null;
static Connection con = null;
public Statement getStatement(){
//定义驱动路径
String driverName = "com.mysql.jdbc.Driver";
try {
//注册驱动
Class.forName(driverName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//定义用户名,密码及数据库路径
String user = "root";
String password = "root";
String url = "jdbc:mysql:///飞毛腿外卖团";
try {
//连接数据库
con = DriverManager.getConnection(url,user,password);
//通过con获取Statement对象
st = con.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
return st;
}
//释放资源
public void release()
{
try {
if(st != null)
st.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
if(con != null)
con.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
public void releaseAll(ResultSet rs)
{
try {
if(rs != null)
rs.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
release();
}
}
|
//good job!
//acceptable efficiency, but take too long to debug
//there is a faster solution, but hard to understand, try it next time!
public class Solution {
public String countAndSay(int n) {
if (n == 1)
return "1";
int count = 1;
char lastDigit = '1';//last digit number
String temp = "1";
//n - 1 times cycle
for (int i = 1; i < n; i++)
{
StringBuilder sb = new StringBuilder();
if (i == 1)
sb.append("11");
for (int j = 1; j < temp.length(); j++)
{
if (lastDigit == temp.charAt(j))
{
count++;
}
else
{
sb.append(count);
sb.append(lastDigit);
count = 1;
lastDigit = temp.charAt(j);
}
if (temp.length() == (j + 1))
{
sb.append(count);
sb.append(lastDigit);
count = 1;
}
}
count = 1;
temp = sb.toString();
lastDigit = temp.charAt(0);
// System.out.println("count = " + count + " lastDigit = " + lastDigit);
// System.out.println("return: " + temp + "\n");
}
return temp;
}
}
|
package ks.dto.feed.banks;
import ks.types.dataFeed.banks.IRegistroComplementario;
public class RegistroComplementario implements IRegistroComplementario {
private byte codigoRegistro;
private byte codigoDato;
private String concepto1;
private String concepto2;
public byte getCodigoRegistro() {return codigoRegistro;}
public byte getCodigoDato() {return codigoDato;}
public String getConcepto1() {return concepto1;}
public String getConcepto2() {return concepto2;}
public void setCodigoRegistro(byte codigoRegistro) {this.codigoRegistro = codigoRegistro;}
public void setCodigoDato(byte codigoDato) {this.codigoDato = codigoDato;}
public void setConcepto1(String concepto1) {this.concepto1 = concepto1;}
public void setConcepto2(String concepto2) {this.concepto2 = concepto2;}
}
|
package redisOperation;
import redis.clients.jedis.Jedis;
public class SimpleRedis {
public static void main(String[] args) {
Jedis jedis = new Jedis("localhost");
jedis.set("foo","tball");
String value = jedis.get("foo");
System.out.println(value);
}
}
|
package org.prk.domain;
public class ParentDomain {
private String createdTimeStamp;
private String updateTimeStamp;
private String createdBy;
private String updatedBy;
public String getCreatedTimeStamp() {
return createdTimeStamp;
}
public void setCreatedTimeStamp(String createdTimeStamp) {
this.createdTimeStamp = createdTimeStamp;
}
public String getUpdateTimeStamp() {
return updateTimeStamp;
}
public void setUpdateTimeStamp(String updateTimeStamp) {
this.updateTimeStamp = updateTimeStamp;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public String getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
}
|
package com.example.applicationnotes.View;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.applicationnotes.Model.Note;
import com.example.applicationnotes.R;
import com.example.applicationnotes.ViewModel.ViewModelNotesList;
import java.util.List;
public class FragmentNotesList extends Fragment {
ViewModelNotesList mViewModelNotesList;
AdapterNotesList mAdapter;
public static FragmentNotesList newInstance(){
Bundle args = new Bundle();
FragmentNotesList fragmentNotesList= new FragmentNotesList();
fragmentNotesList.setArguments(args);
return fragmentNotesList;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewModelNotesList = ViewModelProviders.of(getActivity()).get(ViewModelNotesList.class);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_notes_list, container, false);
RecyclerView rv = v.findViewById(R.id.notes_list);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
rv.setLayoutManager(linearLayoutManager);
mAdapter = new AdapterNotesList();
rv.setAdapter(mAdapter);
subscribeToModel();
return v;
}
private void subscribeToModel(){
mViewModelNotesList.getAllNotes().observe(this, new Observer<List<Note>>() {
@Override
public void onChanged(List<Note> notes) {
mAdapter.setData(notes);
}
});
}
}
|
package de.mq.vaadin.util;
import java.util.Locale;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.web.context.WebApplicationContext;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.WrappedHttpSession;
public class UIBeanInjectorTest {
final VaadinRequest request = Mockito.mock(VaadinRequest.class);
final WrappedHttpSession wrappedSession = Mockito.mock(WrappedHttpSession.class);
final AbstractUIBeanInjector uiBeanInjector = Mockito.mock(AbstractUIBeanInjector.class);
final HttpSession httpSession = Mockito.mock(HttpSession.class);
final ServletContext servletContext = Mockito.mock(ServletContext.class);
final WebApplicationContext ctx = Mockito.mock(WebApplicationContext.class);
final AutowireCapableBeanFactory autowireCapableBeanFactory = Mockito.mock(AutowireCapableBeanFactory.class);
@Before
public final void setup(){
Mockito.when(request.getWrappedSession()).thenReturn(wrappedSession);
Mockito.when(httpSession.getServletContext()).thenReturn(servletContext);
Mockito.when(wrappedSession.getHttpSession()).thenReturn(httpSession);
Mockito.when(servletContext.getAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)).thenReturn(ctx);
Mockito.when(ctx.getAutowireCapableBeanFactory()).thenReturn(autowireCapableBeanFactory);
}
@Test
public final void initWithoutLocale() {
uiBeanInjector.init(request);
Mockito.verify(autowireCapableBeanFactory, Mockito.times(1)).autowireBean(uiBeanInjector);
Mockito.verify(uiBeanInjector, Mockito.times(1)).init();
Assert.assertNull(uiBeanInjector.locale());
}
@Test
public final void initWithLocale() {
Mockito.when(request.getLocale()).thenReturn(Locale.GERMAN);
uiBeanInjector.init(request);
Assert.assertEquals(Locale.GERMAN, uiBeanInjector.locale());
}
}
|
package p0100;
import java.util.Scanner;
public class P0120 {
public static void main(String[] args)
{
System.out.printf("Veuillez entré un nombre entier! = ");
Scanner input = new Scanner(System.in);
int x = input.nextInt();
System.out.printf("Vous avez taper %d comme nombre et son carrée vaut %d\n", x, x*x);
input.close();
}
}
|
package com.softeem.utils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.springframework.util.StringUtils;
public class NetInfoUtil {
public static String callCmd(String[] cmd) {
String result = "";
String line = "";
try {
Process proc = Runtime.getRuntime().exec(cmd);
InputStreamReader is = new InputStreamReader(proc.getInputStream());
BufferedReader br = new BufferedReader(is);
while ((line = br.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* @param cmd
*/
public static String callCmd(String[] cmd, String[] another) {
String result = "";
String line = "";
try {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd);
proc.waitFor(); // 宸茬粡鎵ц瀹岀涓�釜鍛戒护锛屽噯澶囨墽琛岀浜屼釜鍛戒护
proc = rt.exec(another);
InputStreamReader is = new InputStreamReader(proc.getInputStream());
BufferedReader br = new BufferedReader(is);
while ((line = br.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
*
*/
public static String filterMacAddress(final String ip, final String sourceString, final String macSeparator) {
String result = "";
String regExp = "((([0-9,A-F,a-f]{1,2}" + macSeparator + "){1,5})[0-9,A-F,a-f]{1,2})";
Pattern pattern = Pattern.compile(regExp);
Matcher matcher = pattern.matcher(sourceString);
while (matcher.find()) {
result = matcher.group(1);
if (sourceString.indexOf(ip) <= sourceString.lastIndexOf(matcher.group(1))) {
break; //
}
}
return result;
}
/**
*
* @param ip
* @return Mac Address
*
*/
public static String getMacInWindows(final String ip) {
String result = "";
String[] cmd = { "cmd", "/c", "ping " + ip };
String[] another = { "cmd", "/c", "arp -a" };
String cmdResult = callCmd(cmd, another);
result = filterMacAddress(ip, cmdResult, "-");
return result;
}
/**
* @param ip
* @return Mac Address
*
*/
public static String getMacInLinux(final String ip) {
String result = "";
String[] cmd = { "/bin/sh", "-c", "ping " + ip + " -c 2 && arp -a" };
String cmdResult = callCmd(cmd);
result = filterMacAddress(ip, cmdResult, ":");
return result;
}
/**
* @param ip
*
* @return
*/
public static Map<String, String> getComputerInfo(final String ip) {
Map<String, String> result = new HashMap<String, String>();
String[] cmd = (isWinOs()) ? new String[] { "cmd", "/c", "nbtstat -a " + ip }
: new String[] { "/bin/sh", "-c", "nmblookup -A " + ip };
String cmdResult = callCmd(cmd);
if (cmdResult != null) {
Pattern pat = Pattern.compile("[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}");
Matcher mat = pat.matcher(cmdResult);
while (mat.find()) {
result.put("Address", mat.group(0).trim()); //
break;
}
pat = Pattern.compile("([^s *]+[ *]+<[0-9A-F]{2}>){1}");
mat = pat.matcher(cmdResult);
while (mat.find()) {
result.put("Name", mat.group(0).trim().replaceFirst("[ *]+<[0-9A-F]{2}>", "")); //
break;
}
}
return result;
}
/**
*
* @return
*/
public static String getMacAddress(String ip) {
String macAddress = "";
macAddress = getMacInWindows(ip).trim();
if (StringUtils.isEmpty(macAddress)) {
macAddress = getMacInLinux(ip).trim();
}
return macAddress;
}
/**
*
* @param request
* @return
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
/**
*
* @return
*/
public static String runShell(String shell) {
try {
Process ps = Runtime.getRuntime().exec(shell);
BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
} catch (Exception t) {
t.printStackTrace();
}
return null;
}
/***
* @param shell
* @return
*/
public static int runCmd(String shell) {
try {
// String[] cmd = new String[]{"/bin/sh","-c", shell};
Process ps = Runtime.getRuntime().exec(shell);
BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
int exitVal = ps.waitFor();
return exitVal;
} catch (Throwable t) {
t.printStackTrace();
}
return 0;
}
public static boolean isWinOs() {
String os = System.getProperties().getProperty("os.name");
boolean isWin = (os.toLowerCase().startsWith("win")) ? true : false;
return isWin;
}
}
|
package Functions.HomeWork;
/*
Sozdat class Dog v kotoro budet 3 polia: String clichka, String poroda, int skorost.
Sozdat vnutri klassa 2 metoda:
Method run() bez paraetrov tip void. Pri vizove dannogo metoda na ekran vivoditsia stroka 'begu, begu, begu...'. Slovo
begu dolzhno vivestis stolko raz, skilko ukazano v peremennoy skorost
Vtoroy metod String info() vozvraschaet stroku s polnoy informatsiey o sobake (klichka, poroda i skorost). Etot
metod nichego ne vivodit na ekran.
V klasse ain prodeonstrirovat rabotu dannih metodov
*/
public class Main {
public static void main(String[] args) {
Dog mydog = new Dog();
mydog.klichka = "Bobik";
mydog.poroda = "Ovcharka";
mydog.speed = 10;
String dogInfo = mydog.info();
System.out.println(dogInfo);
mydog.run();
}
}
|
package sonar.minimodem;
import java.io.IOException;
public class MinimodemReceiver extends MinimodemInstance {
public static final double CONFIDENCE = 3.0;
public MinimodemReceiver(BaudMode baudMode)
throws IOException, InterruptedException, MinimodemNotInPathException {
super(baudMode);
}
public Process initProcess() throws IOException {
ProcessBuilder processBuilder =
new ProcessBuilder(
"minimodem",
"--rx",
"--confidence",
String.valueOf(MinimodemReceiver.CONFIDENCE),
this.getBaudModeStr());
Process process = processBuilder.start();
return process;
}
}
|
package x20171011_Kivetelkezekles;
import java.util.Scanner;
/**
*
* @author Schwarczenberger Ferenc
*/
public class osztas {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Kérema az osztandót!");
int osztandó = sc.nextInt();
System.out.println("Kérem az osztót!");
int osztó = sc.nextInt();
boolean sikeres = false;
double hányados = 0.0;
try {
hányados = (double)(osztandó/osztó);
System.out.println(osztandó + " / "+ osztó + " = " + hányados);
sikeres = true; //ha már az első sorban kiakad, a többi sor nem fut le!!!
}
catch (ArithmeticException ae) {
System.out.println("hiba: "+ae.getMessage());
}
finally {
if (sikeres) {
System.out.println("Az osztás rendben lezajlott...");
}
else{
System.out.println("Az osztás sikertelen!");
}
}
}
}
|
package com.anglia0222.builder;
public class Product {
private String wall;
private String roof;
public String getWall() {
return wall;
}
public void setWall(String wall) {
this.wall = wall;
}
public String getRoof() {
return roof;
}
public void setRoof(String roof) {
this.roof = roof;
}
}
|
package com.niit.project.radiom.object;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import com.niit.project.radiom.object.BaseBullet.BulletType;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
/**
* 基本的飞机类,通过继承这个类,可以实现不同类型的飞机
* 如玩家飞机,boss飞机,喽啰飞机
*
* 对于爆炸效果的绘制,这里提供了两种实现方式:
* 一种是通过一系列图片构造多个位图对象,逐帧绘制,
* 另一种方式是通过一张长图构造一个位图对象,每帧绘制位图对象的一部分
* @author songhui
* @see drawBoom()函数
*
*/
public abstract class BasePlane {
/**
* 存储每种类型子弹的延迟时间,用于控制飞机发射子弹的间隔
*/
public static Map<BulletType, Integer>
bulletDelayMap = new HashMap<BulletType, Integer>();
/**
* 记录飞机所携带的每种类型子弹的数量
* */
protected Map<BaseBullet.BulletType, Integer> bulletsMap
= new HashMap<BaseBullet.BulletType, Integer>();
protected String imagePath;//飞机的图片路径
protected String[] boomImagePaths;//爆炸效果的系列图片路径
protected String boomImagePath;//爆炸效果的单张图片路径
protected Bitmap bitmap;//飞机的位图对象
protected Bitmap[] boomBitmaps;//存放爆炸位图对象的数组
protected Bitmap boomBitmap;//爆炸效果的单张图片位图对象
protected int boomFrameCount;//爆炸效果的帧数计数器,不断增加
protected long shootFrameCount;//发射子弹的帧数计数器,不断增加
protected AssetManager assetManager;
protected double speed = 0.1;//每毫秒前进的px
protected double currentX;
protected double currentY;
protected double destX;
protected double destY;
protected int blood;
protected int boomCount;
// /**
// * 通过传入一系列爆炸图片和其他参数来实例化对象
// * @param imagePath 飞机图片路径
// * @param boomImagePaths 系列爆炸图片路径
// * @param assetManager
// * @param speed 飞机速度,单位为每毫秒前进的像素数
// * @param currentX 当前X坐标
// * @param currentY 当前Y坐标
// * @param destX 目标X坐标
// * @param destY 目标Y坐标
// * @param blood 血量
// * @param boomFrameCount 绘制爆炸时的帧数计数器,会不断增加
// */
// public BasePlane(String imagePath, String[] boomImagePaths,
// AssetManager assetManager, float speed, int currentX, int currentY,
// int destX, int destY, int blood, int boomFrameCount) {
// if (imagePath == null)
// this.imagePath = "img/F22.png";
// else
// this.imagePath = imagePath;
// if (boomImagePaths == null)
// this.boomImagePaths = new String[]{"img/boom1.png", "img/boom1.png",
// "img/boom1.png", "img/boom1.png", "img/boom1.png" };
// else
// this.boomImagePaths = boomImagePaths;
// this.assetManager = assetManager;
// this.speed = speed;
// this.currentX = currentX;
// this.currentY = currentY;
// this.destX = destX;
// this.destY = destY;
// this.blood = blood;
// this.boomFrameCount = 0;
// this.shootFrameCount = 0;
//
// //获得飞机的Bitmap对象
// InputStream is = null;
// try {
// is = assetManager.open(imagePath);
// bitmap = BitmapFactory.decodeStream(is);
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// //获得飞机爆炸的Bitmap对象数组
// try {
// boomBitmaps = new Bitmap[this.boomImagePaths.length];
// for (int i = 0; i < this.boomImagePaths.length; i ++) {
// is = assetManager.open(this.boomImagePaths[i]);
// boomBitmaps[i] = BitmapFactory.decodeStream(is);
// }
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// //为每种类型的子弹添加射击延迟时间
// bulletDelayMap.put(BulletType.bullet1, Integer.valueOf(20));
// bulletDelayMap.put(BulletType.bullet1_left, Integer.valueOf(20));
// bulletDelayMap.put(BulletType.bullet1_right, Integer.valueOf(20));
// bulletDelayMap.put(BulletType.bullet2, Integer.valueOf(2));
// bulletDelayMap.put(BulletType.bullet2_left, Integer.valueOf(10));
// bulletDelayMap.put(BulletType.bullet2_right, Integer.valueOf(10));
// bulletDelayMap.put(BulletType.bullet3, Integer.valueOf(1));
// bulletDelayMap.put(BulletType.bullet3_left, Integer.valueOf(10));
// bulletDelayMap.put(BulletType.bullet3_right, Integer.valueOf(10));
// bulletDelayMap.put(BulletType.bullet4, Integer.valueOf(1));
// bulletDelayMap.put(BulletType.bullet4_left, Integer.valueOf(10));
// bulletDelayMap.put(BulletType.bullet4_right, Integer.valueOf(10));
// bulletDelayMap.put(BulletType.bullet5, Integer.valueOf(1));
// bulletDelayMap.put(BulletType.bullet5_left, Integer.valueOf(10));
// bulletDelayMap.put(BulletType.bullet5_right, Integer.valueOf(10));
// bulletDelayMap.put(BulletType.bullet6, Integer.valueOf(1));
// bulletDelayMap.put(BulletType.bullet6_left, Integer.valueOf(10));
// bulletDelayMap.put(BulletType.bullet6_right, Integer.valueOf(10));
// }
public BasePlane(String imagePath, String boomImagePath, int boomCount,
AssetManager assetManager, float speed, int currentX, int currentY,
int destX, int destY, int blood, int boomFrameCount) {
if (imagePath == null)
this.imagePath = "img/F22.png";
else
this.imagePath = imagePath;
boomImagePaths = null;
this.boomImagePath = boomImagePath;
this.assetManager = assetManager;
this.speed = speed;
this.currentX = currentX;
this.currentY = currentY;
this.destX = destX;
this.destY = destY;
this.blood = blood;
this.boomFrameCount = 0;
this.shootFrameCount = 0;
this.boomCount = boomCount;
//获得飞机的Bitmap对象
InputStream is = null;
try {
is = assetManager.open(imagePath);
bitmap = BitmapFactory.decodeStream(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//获得飞机爆炸的Bitmap对象
try {
is = assetManager.open(boomImagePath);
boomBitmap = BitmapFactory.decodeStream(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//为每种类型的子弹添加射击延迟时间
bulletDelayMap.put(BulletType.bullet1, Integer.valueOf(20));
bulletDelayMap.put(BulletType.bullet1_left, Integer.valueOf(20));
bulletDelayMap.put(BulletType.bullet1_right, Integer.valueOf(20));
bulletDelayMap.put(BulletType.bullet2, Integer.valueOf(4));
bulletDelayMap.put(BulletType.bullet2_left, Integer.valueOf(4));
bulletDelayMap.put(BulletType.bullet2_right, Integer.valueOf(4));
bulletDelayMap.put(BulletType.bullet3, Integer.valueOf(20));
bulletDelayMap.put(BulletType.bullet3_left, Integer.valueOf(20));
bulletDelayMap.put(BulletType.bullet3_right, Integer.valueOf(20));
bulletDelayMap.put(BulletType.bullet4, Integer.valueOf(20));
bulletDelayMap.put(BulletType.bullet4_left, Integer.valueOf(20));
bulletDelayMap.put(BulletType.bullet4_right, Integer.valueOf(20));
bulletDelayMap.put(BulletType.bullet5, Integer.valueOf(20));
bulletDelayMap.put(BulletType.bullet5_left, Integer.valueOf(20));
bulletDelayMap.put(BulletType.bullet5_right, Integer.valueOf(20));
bulletDelayMap.put(BulletType.bullet6, Integer.valueOf(20));
bulletDelayMap.put(BulletType.bullet6_left, Integer.valueOf(20));
bulletDelayMap.put(BulletType.bullet6_right, Integer.valueOf(20));
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public String[] getBoomImagePaths() {
return boomImagePaths;
}
public void setBoomImagePaths(String[] boomImagePaths) {
this.boomImagePaths = boomImagePaths;
}
public Bitmap getBitmap() {
return bitmap;
}
public void setBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
}
public Bitmap[] getBoomBitmaps() {
return boomBitmaps;
}
public void setBoomBitmaps(Bitmap[] boomBitmaps) {
this.boomBitmaps = boomBitmaps;
}
public AssetManager getAssetManager() {
return assetManager;
}
public void setAssetManager(AssetManager assetManager) {
this.assetManager = assetManager;
}
public double getSpeed() {
return speed;
}
public void setSpeed(double speed) {
this.speed = speed;
}
public double getCurrentX() {
return currentX;
}
public void setCurrentX(double currentX) {
this.currentX = currentX;
}
public double getCurrentY() {
return currentY;
}
public void setCurrentY(double currentY) {
this.currentY = currentY;
}
public double getDestX() {
return destX;
}
public void setDestX(double destX) {
this.destX = destX;
}
public double getDestY() {
return destY;
}
public void setDestY(double destY) {
this.destY = destY;
}
public int getBlood() {
return blood;
}
public void setBlood(int blood) {
this.blood = blood;
}
public void cutBlood(int harm) {
blood -= harm;
}
public int getBoomFrameCount() {
return boomFrameCount;
}
public void addBoomFrameCount() {
boomFrameCount ++;
}
public long getShootFrameCount() {
return shootFrameCount;
}
/**
* 每次射击一颗子弹,调用此函数来增加shootFrameCount
*/
public void addShootFrameCount() {
shootFrameCount ++;
}
public Map<BaseBullet.BulletType, Integer> getBulletsMap() {
return bulletsMap;
}
public void setBulletsMap(Map<BaseBullet.BulletType, Integer> bulletsMap) {
this.bulletsMap = bulletsMap;
}
public void addBullet(BulletType type, int number) {
bulletsMap.put( type, new Integer(number) );
}
public int getBoomCount() {
return boomCount;
}
public void setBoomCount(int boomCount) {
this.boomCount = boomCount;
}
/**
* 控制飞机的移动,在子类中可以实现飞机的不同移动类型
* @param time 每次移动的时间,单位为毫秒
* @param destX 目标位置X坐标
* @param destY 目标位置Y坐标
*/
public abstract void move (int time, int destX, int destY);
/**
* 控制飞机的移动,在子类中可以实现飞机的不同移动类型
* @param time 每次移动的时间,单位为毫秒
*/
public abstract void move (int time);
/**
* 绘制飞机
* @param canvas
*/
public abstract void drawSelf (Canvas canvas);
/**
* 绘制飞机爆炸的效果
* @param canvas
*/
public abstract void drawBoom (Canvas canvas);
/**
* 判断飞机当前能否发射某种类型的子弹
* @param type
* @return
*/
public abstract boolean canShoot (BaseBullet.BulletType type);
/**
* 产生某种类型的子弹,在调用次函数前应该通过
* canShoot(BaseBullet.BulletType type)函数来判断能否发射此种类型的子弹
* @param type 要产生的子弹类型
* @return
*/
public abstract BaseBullet createBullet (BaseBullet.BulletType type);
/**
* 检测飞机是否超过了指定的范围
* @param left
* @param top
* @param right
* @param bottom
* @return
*/
public abstract boolean isOverRange(int left, int top, int right, int bottom);
/**
* 检测飞机和另外一架飞机的碰撞
* @param plane
* @return
*/
public abstract boolean detectCrash (BasePlane plane);
/**
* 检测飞机和子弹的碰撞
* @param bullet
* @return
*/
public abstract boolean detectCrash (BaseBullet bullet);
}
|
package org.sky.sys.utils.schedule;
import java.util.List;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.sky.base.client.BaseChannelImgMapper;
import org.sky.base.client.BaseChannelMapper;
import org.sky.base.model.BaseChannel;
import org.sky.base.model.BaseChannelExample;
import org.sky.base.model.BaseChannelImgExample;
import org.sky.base.model.BaseChannelImgWithBLOBs;
import org.sky.sys.utils.AliyunIdCardResult;
import org.sky.sys.utils.AliyunIdCardUtils;
import org.sky.sys.utils.BspUtils;
/**
* 创建每天盘查计划(每周一执行一次)
* @author weifx
*
*/
public class QuartzRealNameAuthenticationJob implements Job {
private final Logger logger=Logger.getLogger(QuartzRealNameAuthenticationJob.class);
@Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {
// TODO Auto-generated method stub
//先查出待实名认证的渠道
BaseChannelMapper channelMapp = BspUtils.getBean(BaseChannelMapper.class);
BaseChannelImgMapper channelImgMapper = BspUtils.getBean(BaseChannelImgMapper.class);
BaseChannelExample bce = new BaseChannelExample();
bce.createCriteria().andStateEqualTo("05");
List<BaseChannel> list = channelMapp.selectByExample(bce);
for(BaseChannel channel:list){
//获取最新的上传图片进行校验
BaseChannelImgExample example = new BaseChannelImgExample();
example.createCriteria().andChannelCodeEqualTo(channel.getCode());
example.setOrderByClause("create_time desc");
List<BaseChannelImgWithBLOBs> tempList = channelImgMapper.selectByExampleWithBLOBs(example);
if(null==tempList || tempList.isEmpty()) {
logger.error(channel.getCode()+"为查到图像信息");
//设置为认证失败(更新时间不调整了)
channel.setState("04");
channelMapp.updateByPrimaryKeySelective(channel);
continue;
}
BaseChannelImgWithBLOBs temp = tempList.get(0);
//调用阿里云校验接口
AliyunIdCardUtils.readIdCard(channel,temp.getIdcardPic1());
}
}
}
|
package main.java.graphs;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import main.java.main.ConnectionStatus;
import main.java.main.Vector2;
public class StatusCanvas extends Canvas
{
private GraphicsContext gc;
private ConnectionStatus currentStatus = ConnectionStatus.INACTIVE;
private ConnectionStatus newStatus;
private int canvasSize;
private boolean isRunning = false;
private int rotationPoint = 360;
public StatusCanvas(Vector2 pos, int canvasSize)
{
super();
this.canvasSize = canvasSize;
setLayoutX(pos.getX());
setLayoutY(pos.getY());
setWidth(canvasSize * 4);
setHeight(canvasSize * 4);
gc = getGraphicsContext2D();
DrawCircle();
}
public void StartAnimation()
{
if (!isRunning)
{
isRunning = true;
currentStatus = ConnectionStatus.PENDING;
rotationPoint = 360;
Timer timer = new Timer();
TimerTask task = new TimerTask()
{
@Override
public void run()
{
rotationPoint -= 4;
if (rotationPoint == 0)
{
rotationPoint = 360;
}
// Time to turn the timer off
if (newStatus == ConnectionStatus.ACTIVE || newStatus == ConnectionStatus.INACTIVE)
{
currentStatus = newStatus;
timer.cancel();
isRunning = false;
}
DrawCircle();
}
};
timer.schedule(task, new Date(), 20);
}
}
public void DrawCircle()
{
gc.clearRect(0, 0, canvasSize, canvasSize);
gc.setFill(Color.CORNFLOWERBLUE);
switch (currentStatus)
{
case ACTIVE:
gc.setFill(Color.LIGHTGREEN);
break;
case PENDING:
gc.setFill(Color.CORNFLOWERBLUE);
break;
case INACTIVE:
gc.setFill(Color.INDIANRED);
break;
default:
gc.setFill(Color.RED);
break;
}
int oLW = 13;
gc.fillOval(oLW / 2, oLW / 2, canvasSize - oLW, canvasSize - oLW);
}
public void SetStatus(ConnectionStatus status)
{
newStatus = status;
}
}
|
package loja;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.is;
public class User {
public String lerJson(String caminhoJson) throws IOException {
return new String(Files.readAllBytes(Paths.get(caminhoJson)));
}
@Test
public void ordenarExecucao() throws IOException {
incluirUsuario();
consultarUsuario();
alterarUsuario();
excluirUsuario();
}
@Test
public void incluirUsuario() throws IOException {
String jsonBody = lerJson("data/user.json");
given()
.contentType("application/json") // Formato da transmissão Exemplo: .txt, .doc
.log().all() // Informa o que ta contecento
.body(jsonBody) // O que vai transmitir o conteúdo
.when()
.post("https://petstore.swagger.io/v2/user")// Ação
.then()
.log().all() // Mostrar tudo que foi recebido de volta
.statusCode(200)
.body("code", is(200))
.body("type", is("unknown"))
.body("message", is("5310"))
;
System.out.println("Executou o serviço");
}
@Test
public void consultarUsuario(){
String username = "drikateste";
given()
.contentType("application/json")
.log().all()
.when()
.get("https://petstore.swagger.io/v2/user/" + username)
.then()
.log().all()
.statusCode(200)
.body("id", is (5310))
.body("username", is ("drikateste"))
.body("firstName", is ("Adriane"))
.body("lastName", is ("Chaves"))
;
}
@Test
public void alterarUsuario() throws IOException {
String jsonBody = lerJson("data/userput.json");
String username = "drikateste";
given()
.log().all()
.contentType("application/json")
.body(jsonBody)
.when()
.put("https://petstore.swagger.io/v2/user/" + username)
.then()
.log().all()
.statusCode(200)
.body("code", is(200))
.body("type", is("unknown"))
.body("message", is("5310"))
;
}
@Test
public void excluirUsuario(){
String username = "drikateste";
given()
.log().all()
.contentType("application/json")
.when()
.delete("https://petstore.swagger.io/v2/user/" + username)
.then()
.log().all()
.statusCode(200)
.body("code", is(200))
.body("message", is(username))
;
}
}
|
package org.sunshinelibrary.turtle.taskmanager;
import android.text.TextUtils;
import android.util.Log;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;
import org.sunshinelibrary.turtle.TurtleManagers;
import org.sunshinelibrary.turtle.appmanager.WebAppException;
import org.sunshinelibrary.turtle.models.WebApp;
import org.sunshinelibrary.turtle.utils.Configurations;
import org.sunshinelibrary.turtle.utils.Logger;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
/**
* User: fxp
* Date: 10/14/13
* Time: 9:16 PM
*/
public class DownloadTask extends WebAppTask {
public DownloadTask(WebApp newApp) {
app = newApp;
}
@Override
public boolean isOk() {
return isOk;
}
@Override
public Object getResult() {
return result;
}
@Override
public String getState() {
return state; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public int getProgress() {
return progress;
}
@Override
public WebApp getWebApp() {
return app; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void execute() {
Logger.i("download this app start," + app);
String appId = null;
File tmpFile = null;
try {
state = "downloading";
// app.download_url = app.download_url;
// Download the app to temp directory
tmpFile = File.createTempFile("turtle_", ".tmp");
if (!app.download_url.startsWith("http://")) {
app.download_url = Configurations.serverHost + app.download_url;
}
URL url = new URL(app.download_url);
if (app.mirrors != null && app.mirrors.size()>0 && touch(new URL(app.mirrors.get(0)))){
URL mirror = new URL(app.mirrors.get(0));
state = "downloading from local cache";
app.download_url = mirror.toString();
downloadFileFromUrl(mirror, tmpFile);
} else {
state = "downloading from cloud";
downloadFileFromUrl(url, tmpFile);
}
// FileUtils.copyURLToFile(url, tmpFile);
File zipFile = tmpFile;
state = "installing";
// Add to AppManager
progress = 0;
WebApp app = TurtleManagers.appManager.installApp(zipFile);
progress = 100;
result = app;
isOk = true;
state = "completed";
Logger.i("app downloaded and installed," + app);
} catch (Exception e) {
progress = 0;
state = "failed";
result = e.getMessage();
Logger.e("download task failed," + e.getMessage());
if (tmpFile != null) {
FileUtils.deleteQuietly(tmpFile);
}
if (!TextUtils.isEmpty(appId)) {
try {
TurtleManagers.appManager.uninstallApp(appId);
} catch (WebAppException e1) {
e1.printStackTrace();
}
}
}
}
private boolean touch(URL url) {
HttpHead httpRequest = new HttpHead(url.toString());
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(httpRequest);
return (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) ;
} catch (ClientProtocolException e) {
Log.i("DownloadTask", e.getMessage());
return false;
} catch (IOException e) {
Log.i("DownloadTask", e.getMessage());
return false;
} catch (Exception e) {
Log.i("DownloadTask", e.getMessage());
return false;
}
}
private void downloadFileFromUrl(URL url, File dstFile) throws IOException {
int count;
/* URLConnection conection = url.openConnection();
conection.setConnectTimeout(5000);
conection.setReadTimeout(3000);
conection.connect();
// getting file length
//int lenghtOfFile = conection.getContentLength();
//input stream to read file - with 8k buffer
//InputStream input = new BufferedInputStream(url.openStream(), 8192);*/
//////////////////////////////////////////////////////// get wpk with cookie(token)
HttpClient client = TurtleManagers.cookieManager.client;
BasicHttpContext context = TurtleManagers.cookieManager.httpContext;
BasicCookieStore cookieStore = TurtleManagers.cookieManager.cookieStore;
if(cookieStore.getCookies().isEmpty()) {
Logger.e("There's something wrong, cookie not found");
return;
}
context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpGet request = new HttpGet(url.toString());
HttpResponse response = client.execute(request, context);
long lengthOfFile = response.getEntity().getContentLength();
InputStream input = new BufferedInputStream(response.getEntity().getContent(), 8192);
/////////////////////////////////////////////////////////
// Output stream to write file
OutputStream output = new FileOutputStream(dstFile);
byte data[] = new byte[1024 * 4];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
progress = (int) ((total * 100) / lengthOfFile);
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
}
}
|
package sample;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import java.net.URL;
import java.util.ResourceBundle;
public class HomepageController implements Initializable
{
Main application;
@Override
public void initialize(URL location, ResourceBundle resources) {
}
public void addStudent(ActionEvent event)
{
application.gotoAddstudent();
}
public void exit(ActionEvent event)
{
System.exit(0);
}
public void delete(ActionEvent event)
{
application.gotoDelete();
}
public void students(ActionEvent event)
{
application.gotoStudents();
}
public void update(ActionEvent event)
{
application.gotoUpdate();
}
}
|
package com.esum.framework.security.pki.keystore.info;
import java.io.IOException;
import java.sql.SQLException;
public class KeyStoreInfoXML extends KeyStoreInfo {
KeyStoreInfoXML(String configFile) throws IOException, SQLException {
super();
}
/* (non-Javadoc)
* @see com.esum.framework.security.crypto.keystore.info.KeyStoreInfo#init()
*/
void init() throws IOException, SQLException {
}
}
|
package com.tidestorm.blog.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class IndexController {
@GetMapping("/")
public String index() {
// int i=9/0;
// String blog = null;
// if (blog==null) {
// throw new NotFoundException("博客不存在");
// }
return "index";
}
@GetMapping("/blog")
public String blog() {
return "blog";
}
}
|
package com.git.cloud.resmgt.compute.dao;
import com.git.cloud.common.dao.ICommonDAO;
import com.git.cloud.common.exception.RollbackableBizException;
import com.git.cloud.resmgt.compute.model.po.RmCdpPo;
public interface IRmCdpDAO extends ICommonDAO{/*
public RmCdpPo findCdpById(String cdpId) throws RollbackableBizException;
*/}
|
import com.invitae.emr.services.Reporting;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
public class ReportingTest {
@Test
public void testLabReportToResult() {
assertEquals(3, 1 + 2);
final var result = Reporting.createResult(null);
assertNull(result);
}
}
|
/*
* Author: RINEARN (Fumihiro Matsui), 2021
* License: CC0
*/
package org.vcssl.nano.plugin.system.xfci1;
import java.util.Scanner;
import javax.swing.JOptionPane;
// Interface Specification: https://www.vcssl.org/en-us/dev/code/main-jimpl/api/org/vcssl/connect/ExternalFunctionConnectorInterface1.html
// インターフェース仕様書: https://www.vcssl.org/ja-jp/dev/code/main-jimpl/api/org/vcssl/connect/ExternalFunctionConnectorInterface1.html
public class AlertXfci1Plugin extends PopupXfci1Plugin {
// 関数名を返す
@Override
public String getFunctionName() {
return "alert";
}
// string型の引数を取るので String 型を返す
@Override
public Class<?>[] getParameterClasses() {
return new Class<?>[] { String.class };
}
// 任意型の引数は取らないので false を返す
@Override
public boolean[] getParameterDataTypeArbitrarinesses() {
return new boolean[]{ false };
}
// 関数が呼ばれた際に PopupXfci1Plugin の invoke 内で実行されるメッセージ表示処理
// (popup 関数とはウィンドウタイトルやガイドメッセージなどが少し異なる)
@Override
protected void showMessage(String message) {
// GUIモードでは、ポップアップウィンドウ上にメッセージを表示する
if (this.isGuiMode) {
if (this.isJapanese) {
JOptionPane.showMessageDialog(null, message, "スクリプトからの注意メッセージ", JOptionPane.WARNING_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, message, "WARNING FROM SCRIPT", JOptionPane.WARNING_MESSAGE);
}
// CUI モードでは、標準出力にメッセージを表示し、Enterキーが入力されるまで一時停止する
} else {
// メッセージを表示
if (this.isJapanese) {
this.stdoutStream.println("");
this.stdoutStream.println("スクリプトからの注意メッセージ:");
this.stdoutStream.println(message);
this.stdoutStream.println("");
this.stdoutStream.print("(Enterキーを押すと続行)");
} else {
this.stdoutStream.println("");
this.stdoutStream.println("WARNING FROM SCRIPT:");
this.stdoutStream.println(message);
this.stdoutStream.println("");
this.stdoutStream.print("(Press the \"Enter\" key to continue)");
}
// Enterキー入力を待つ
@SuppressWarnings("resource") // 注: 標準入力を close すると次回以降読めなくなる
Scanner scanner = new Scanner(this.stdinStream);
scanner.nextLine();
}
}
}
|
package ir.shayandaneshvar.jottery.converters;
import ir.shayandaneshvar.jottery.commands.LevelCommand;
import ir.shayandaneshvar.jottery.models.Level;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
@Component
public class LevelToLevelCommand implements Converter<Level, LevelCommand> {
@Override
public LevelCommand convert(Level level) {
if (level == null) {
return null;
}
LevelCommand levelCommand = new LevelCommand();
levelCommand.setId(level.getId());
levelCommand.setTag(level.getTag());
levelCommand.setMinimum(level.getMinimum());
levelCommand.setMaximum(level.getMaximum());
return levelCommand;
}
}
|
/**
* Copyright (C) 2011 Ovea <dev@ovea.com>
*
* 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.ovea.system.tunnel;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* @author Mathieu Carbou (mathieu.carbou@gmail.com)
*/
public final class TunnelListeners implements TunnelListener {
private final List<TunnelListener> listeners = new CopyOnWriteArrayList<TunnelListener>();
public TunnelListeners(TunnelListener... listeners) {
this(Arrays.asList(listeners));
}
public TunnelListeners(Iterable<? extends TunnelListener> listeners) {
add(listeners);
}
public void add(TunnelListener listener) {
listeners.add(listener);
}
public void add(TunnelListener... listeners) {
add(Arrays.asList(listeners));
}
public void add(Iterable<? extends TunnelListener> listeners) {
for (TunnelListener listener : listeners) {
this.listeners.add(listener);
}
}
@Override
public void onConnect(Tunnel tunnel) {
for (TunnelListener listener : listeners) {
listener.onConnect(tunnel);
}
}
@Override
public void onClose(Tunnel tunnel) {
for (TunnelListener listener : listeners) {
listener.onClose(tunnel);
}
}
@Override
public void onBroken(Tunnel tunnel, BrokenTunnelException e) {
for (TunnelListener listener : listeners) {
listener.onBroken(tunnel, e);
}
}
@Override
public void onInterrupt(Tunnel tunnel) {
for (TunnelListener listener : listeners) {
listener.onInterrupt(tunnel);
}
}
}
|
package com.Premium.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.Premium.bean.Employee;
import com.Premium.service.EmployeeService;
@RestController("")
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@PostMapping("/employee")
public void AddEmployee(@RequestBody Employee employee) {
employeeService.addEmployee(employee);
}
@GetMapping("/employee")
public List<Employee> GetEmployees(String name) {
List<Employee> employees = employeeService.getEmployees();
return employees;
}
@DeleteMapping("/employee/{id}")
public void DeleteEmployee(@PathVariable("id") int id) {
employeeService.deleteEmployee(id);
}
@PutMapping("/employee/{id}")
public void UpdateEmployee(@PathVariable("id") int id, @RequestBody Employee employee) {
employeeService.updateEmployee(id, employee);
}
}
|
package com.nextLevel.hero.mngWorkAttitude.model.dto;
import java.util.List;
public class MngAttitudeUpdateDTO {
private int idNo; //계정번호
private int memberNo; //사번
private String koreanName; //이름
private String departmenetName; //부서이름
private String rank; //직급
private String hireDate; //입사일
public MngAttitudeUpdateDTO() {
super();
}
public MngAttitudeUpdateDTO(int idNo, int memberNo, String koreanName, String departmenetName, String rank,
String hireDate) {
super();
this.idNo = idNo;
this.memberNo = memberNo;
this.koreanName = koreanName;
this.departmenetName = departmenetName;
this.rank = rank;
this.hireDate = hireDate;
}
public int getIdNo() {
return idNo;
}
public void setIdNo(int idNo) {
this.idNo = idNo;
}
public int getMemberNo() {
return memberNo;
}
public void setMemberNo(int memberNo) {
this.memberNo = memberNo;
}
public String getKoreanName() {
return koreanName;
}
public void setKoreanName(String koreanName) {
this.koreanName = koreanName;
}
public String getDepartmenetName() {
return departmenetName;
}
public void setDepartmenetName(String departmenetName) {
this.departmenetName = departmenetName;
}
public String getRank() {
return rank;
}
public void setRank(String rank) {
this.rank = rank;
}
public String getHireDate() {
return hireDate;
}
public void setHireDate(String hireDate) {
this.hireDate = hireDate;
}
@Override
public String toString() {
return "MngAttitudeUpdateDTO [idNo=" + idNo + ", memberNo=" + memberNo + ", koreanName=" + koreanName
+ ", departmenetName=" + departmenetName + ", rank=" + rank + ", hireDate=" + hireDate + "]";
}
}
|
package com.hrms.testCases;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.hrms.utils.CommonMethods;
import com.hrms.utils.ConfigsReader;
public class InvalidLoginTest extends CommonMethods{
@Test
public void invalidLogin() {
sendText(login.username, ConfigsReader.getProperty("username") );
sendText(login.password, "Asdasdasd");
click(login.loginBtn);
String expected="Invalid credentials";
Assert.assertEquals(login.errorMsg.getText(), expected,"error");
System.out.println("passed");
}
}
|
public class SnakePattern
{
public static void SnakePattern(int [][] mat)
{
for(int i=0;i<mat.length;i++)
{
if(i%2==0)
{
for(int j=0;j<mat[i].length;j++)
{
System.out.print(mat[i][j]+" ");
}
}
else{
for(int j=mat[i].length-1;j>=0;j--)
{
System.out.print(mat[i][j]+" ");
}
}
System.out.println();
}
}
public static void main(String [] args)
{
int [][] mat = { {1,2,3,4},{3,4,5},{7,5,2,0},{9,4,6,5,1,3}};
SnakePattern(mat);
}
}
|
package org.squonk.execution.steps.impl;
import com.github.dockerjava.api.model.AccessMode;
import com.github.dockerjava.api.model.Volume;
import org.apache.camel.CamelContext;
import org.squonk.core.DockerServiceDescriptor;
import org.squonk.execution.docker.DockerRunner;
import org.squonk.execution.steps.StepDefinitionConstants;
import org.squonk.execution.util.GroovyUtils;
import org.squonk.execution.variable.VariableManager;
import org.squonk.execution.variable.impl.FilesystemReadContext;
import org.squonk.execution.variable.impl.FilesystemWriteContext;
import org.squonk.io.IODescriptor;
import org.squonk.util.IOUtils;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Logger;
/**
* Created by timbo on 29/12/15.
*/
public class DefaultDockerExecutorStep extends AbstractDockerStep {
private static final Logger LOG = Logger.getLogger(DefaultDockerExecutorStep.class.getName());
private static final String OPTION_DOCKER_COMMAND = StepDefinitionConstants.DockerProcessDataset.OPTION_DOCKER_COMMAND;
protected String DOCKER_SERVICES_DIR = IOUtils.getConfiguration("SQUONK_DOCKER_SERVICES_DIR", "../../data/testfiles/docker-services");
@Override
public void execute(VariableManager varman, CamelContext context) throws Exception {
if (serviceDescriptor == null) {
throw new IllegalStateException("No service descriptor present ");
} else if (!(serviceDescriptor instanceof DockerServiceDescriptor)) {
throw new IllegalStateException("Expected service descriptor to be a " +
DockerServiceDescriptor.class.getName() +
" but it was a " + serviceDescriptor.getClass().getName());
}
DockerServiceDescriptor descriptor = (DockerServiceDescriptor) serviceDescriptor;
LOG.info("Input types are " + IOUtils.joinArray(descriptor.getServiceConfig().getInputDescriptors(), ","));
LOG.info("Output types are " + IOUtils.joinArray(descriptor.getServiceConfig().getOutputDescriptors(), ","));
// this executes this cell
doExecute(varman, context, descriptor);
//LOG.info(varman.getTmpVariableInfo());
}
protected void doExecute(VariableManager varman, CamelContext camelContext, DockerServiceDescriptor descriptor) throws Exception {
statusMessage = MSG_PREPARING_CONTAINER;
String image = getOption(StepDefinitionConstants.OPTION_DOCKER_IMAGE, String.class);
if (image == null || image.isEmpty()) {
image = descriptor.getImageName();
}
if (image == null || image.isEmpty()) {
statusMessage = "Error: Docker image not defined";
throw new IllegalStateException(
"Docker image not defined. Must be set as value of the executionEndpoint property of the ServiceDescriptor or as an option named "
+ StepDefinitionConstants.OPTION_DOCKER_IMAGE);
}
String imageVersion = getOption(StepDefinitionConstants.OPTION_DOCKER_IMAGE_VERSION, String.class);
if (imageVersion != null && !imageVersion.isEmpty()) {
image = image + ":" + imageVersion;
}
String command = getOption(OPTION_DOCKER_COMMAND, String.class);
if (command == null || command.isEmpty()) {
command = descriptor.getCommand();
}
if (command == null || command.isEmpty()) {
statusMessage = "Error: Docker command not defined";
throw new IllegalStateException(
"Run command is not defined. Must be set as value of the command property of the ServiceDescriptor as option named "
+ OPTION_DOCKER_COMMAND);
}
// command will be something like:
// screen.py 'c1(c2c(oc1)ccc(c2)OCC(=O)O)C(=O)c1ccccc1' 0.3 --d morgan2
// screen.py '${query}' ${threshold} --d ${descriptor}
Map<String, Object> args = new LinkedHashMap<>();
options.forEach((k, v) -> {
if (k.startsWith("arg.")) {
LOG.info("Found argument " + k + " = " + v);
args.put(k.substring(4), v);
}
});
// replace windows line end characters
command = command.replaceAll("\\r\\n", "\n");
LOG.info("Template: " + command);
String expandedCommand = GroovyUtils.expandTemplate(command, args);
LOG.fine("Command: " + expandedCommand);
String localWorkDir = "/source";
DockerRunner runner = createDockerRunner(image, localWorkDir);
LOG.info("Docker image: " + image + ", hostWorkDir: " + runner.getHostWorkDir() + ", command: " + expandedCommand);
try {
// create input files
statusMessage = MSG_PREPARING_INPUT;
// write the command that executes everything
LOG.info("Writing command file");
runner.writeInput("execute", "#!/bin/sh\n" + expandedCommand + "\n", true);
// add the resources
if (descriptor.getVolumes() != null) {
for (Map.Entry<String, String> e : descriptor.getVolumes().entrySet()) {
String dirToMount = e.getKey();
String mountAs = e.getValue();
Volume v = runner.addVolume(mountAs);
runner.addBind(DOCKER_SERVICES_DIR + "/" + dirToMount, v, AccessMode.ro);
LOG.info("Volume " + DOCKER_SERVICES_DIR + "/" + dirToMount + " mounted as " + mountAs);
}
}
// write the input data
handleInputs(camelContext, descriptor, varman, runner);
// run the command
statusMessage = MSG_RUNNING_CONTAINER;
LOG.info("Executing ...");
long t0 = System.currentTimeMillis();
int status = runner.execute(localWorkDir + "/execute");
long t1 = System.currentTimeMillis();
float duration = (t1 - t0) / 1000.0f;
LOG.info(String.format("Executed in %s seconds with return status of %s", duration, status));
if (status != 0) {
String log = runner.getLog();
statusMessage = "Error: " + log;
LOG.warning("Execution errors: " + log);
throw new RuntimeException("Container execution failed:\n" + log);
}
// handle the output
statusMessage = MSG_PREPARING_OUTPUT;
handleOutputs(camelContext, descriptor, varman, runner);
generateMetrics(runner, "output_metrics.txt", duration);
statusMessage = generateStatusMessage(numRecordsProcessed, numRecordsOutput, numErrors);
} finally {
// cleanup
if (DEBUG_MODE < 2) {
runner.cleanup();
LOG.info("Results cleaned up");
}
}
}
protected void handleInputs(CamelContext camelContext, DockerServiceDescriptor serviceDescriptor, VariableManager varman, DockerRunner runner) throws Exception {
IODescriptor[] inputDescriptors = serviceDescriptor.getServiceConfig().getInputDescriptors();
if (inputDescriptors != null) {
LOG.info("Handling " + inputDescriptors.length + " inputs");
for (IODescriptor d : inputDescriptors) {
LOG.info("Writing input for " + d.getName() + " " + d.getMediaType());
handleInput(camelContext, serviceDescriptor, varman, runner, d);
}
}
}
protected <P,Q> void handleInput(CamelContext camelContext, DockerServiceDescriptor serviceDescriptor, VariableManager varman, DockerRunner runner, IODescriptor<P,Q> ioDescriptor) throws Exception {
P value = fetchMappedInput(ioDescriptor.getName(), ioDescriptor.getPrimaryType(), varman, true);
FilesystemWriteContext writeContext = new FilesystemWriteContext(runner.getHostWorkDir(), ioDescriptor.getName());
varman.putValue(ioDescriptor.getPrimaryType(), value, writeContext);
}
protected <P,Q> void handleOutputs(CamelContext camelContext, DockerServiceDescriptor serviceDescriptor, VariableManager varman, DockerRunner runner) throws Exception {
IODescriptor[] outputDescriptors = serviceDescriptor.getServiceConfig().getOutputDescriptors();
if (outputDescriptors != null) {
LOG.info("Handling " + outputDescriptors.length + " outputs");
for (IODescriptor d : outputDescriptors) {
handleOutput(camelContext, serviceDescriptor, varman, runner, d);
}
}
}
protected <P,Q> void handleOutput(CamelContext camelContext, DockerServiceDescriptor serviceDescriptor, VariableManager varman, DockerRunner runner, IODescriptor<P,Q> ioDescriptor) throws Exception {
FilesystemReadContext readContext = new FilesystemReadContext(runner.getHostWorkDir(), ioDescriptor.getName());
P value = varman.getValue(ioDescriptor.getPrimaryType(), readContext);
createMappedOutput(ioDescriptor.getName(), ioDescriptor.getPrimaryType(), value, varman);
}
}
|
package com.itfacesystem.domain.org.query;
import com.itfacesystem.domain.common.BaseQuery;
/**
* Created by wangrongtao on 15/10/13.
*/
public class OrgQuery extends BaseQuery {
private Long id;
private String name;
private String orgtag;
/**
* 机构类型:1律所、2银行、3非银
*/
private Long parentorgid;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getParentorgid() {
return parentorgid;
}
public void setParentorgid(Long parentorgid) {
this.parentorgid = parentorgid;
}
public String getOrgtag() {
return orgtag;
}
public void setOrgtag(String orgtag) {
this.orgtag = orgtag;
}
public String toLogString() {
StringBuilder sb = new StringBuilder();
sb.append("id").append(":").append(id).append(",");
sb.append("name").append(":").append(name).append(",");
sb.append("parentorgid").append(":").append(parentorgid).append(",");
sb.append("startRow").append(":").append(startRow).append(",");
sb.append("pageSize").append(":").append(pageSize).append(",");
return sb.toString();
}
}
|
/**
* Created by YAO on 2019-06-04.
* 单例模式——兼顾线程安全和效率的写法-双重检查法
*/
public class Singleton1 {
private static volatile Singleton1 singleton=null;
private Singleton1(){}
public static Singleton1 getSingleton(){
if(singleton==null){
synchronized (Singleton1.class){
if(singleton==null){
singleton=new Singleton1();
}
}
}
return singleton;
}
}
|
package org.itst.service.impl;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.itst.dao.EquipmentRecordMapper;
import org.itst.domain.EquipmentRecord;
import org.itst.service.EquipmentRecordService;
import org.itst.utils.MyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class EquipmentRecordServiceImpl implements EquipmentRecordService {
@Autowired
private EquipmentRecordMapper mapper;
public int addEquipmentRecord(EquipmentRecord record) {
return mapper.addEquipmentRecord(record);
}
public void deleteRecordById(int id) {
mapper.deleteRecordById(id);
}
public EquipmentRecord getEquipmentRecordById(int id) {
return mapper.getEquipmentRecordById(id);
}
public String getEquipmentRecordsJsonByKeyWord(String key, int pageSize,
int pageNow) {
List<EquipmentRecord> list = mapper.getEquipmentRecordsByKeyWord(key, pageSize*(pageNow-1), pageSize*pageNow);
String res = "";
for(EquipmentRecord er : list) {
res += "{\"id\":\"" + er.getId()
+ "\",\"borrowedType\":\"" + er.getBorrowedType()
+ "\",\"number\":\""+ er.getNumber()
+ "\",\"unit\":\"" + er.getUsingUnit()
+ "\",\"startTime\":\""+ MyUtils.dateToString(er.getStartTime())
+ "\",\"endTime\":\""+ MyUtils.dateToString(er.getEndTime())
+ "\",\"username\":\""+ er.getPetitioner()
+ "\",\"contact\":\"" + er.getContact()
+ "\",\"usingFor\":\""+ er.getUsingFor()
+ "\",\"isOvertime\":\""+ (er.getEndTime().compareTo(new Date())<0?"是":"否")
+ "\"},";
}
if (!res.equals("")) {
res = res.substring(0, res.length() - 1);
}
return "{\"total\":" + mapper.getKeySearchCount(key) + ",\"rows\":[" + res + "]}";
}
public String getEquipmentRecordsJsonByPage(int pageSize, int pageNow) {
List<EquipmentRecord> list = mapper.getEquipmentRecordsByPage(pageSize*(pageNow-1), pageSize*pageNow);
String res = "";
for(EquipmentRecord er : list) {
res += "{\"id\":\"" + er.getId()
+ "\",\"borrowedType\":\"" + er.getBorrowedType()
+ "\",\"number\":\""+ er.getNumber()
+ "\",\"unit\":\"" + er.getUsingUnit()
+ "\",\"startTime\":\""+ MyUtils.dateToString(er.getStartTime())
+ "\",\"endTime\":\""+ MyUtils.dateToString(er.getEndTime())
+ "\",\"username\":\""+ er.getPetitioner()
+ "\",\"contact\":\"" + er.getContact()
+ "\",\"usingFor\":\""+ er.getUsingFor()
+ "\",\"isOvertime\":\""+ (er.getEndTime().compareTo(new Date())<0?"是":"否")
+ "\"},";
}
if (!res.equals("")) {
res = res.substring(0, res.length() - 1);
}
return "{\"total\":" + mapper.getEquipmentRecordCount() + ",\"rows\":[" + res + "]}";
}
}
|
import java.lang.*;
public class Primos {
public static boolean ehPrimo(int numero) {
for (int j = 2; j < numero; j++) {
if (numero % j == 0)
return false;
}
return true;
}
public static int[] obterPrimos(int n){
int j=0;
int[] numPrimos = new int[(n/2)+1];
for (int i = 2; i<n; i++){
if (ehPrimo(i)){
numPrimos[j] = i;
j++;
}
}
int[] numRealPrimos = new int[j];
for (int i = 0; i < j; i++){
if (numPrimos[i] != 0)
numRealPrimos[i] = numPrimos[i];
}
return numRealPrimos;
}
public static int[] obterPrimosViaCrivo(int n){
/*false para primo true para composto*/
int limite = (int) Math.sqrt(n);
int divisor;
int l = 0;
boolean[] listaComposto = new boolean[n];
for (int i = 2; i <= limite; i++) {
listaComposto[0]=true;
listaComposto[1]=true;
divisor = i;
for (int j = i + divisor; j < n; j += divisor) {
listaComposto[j] = true;
}
}
for (int k = 0; k < n; k++){
if (listaComposto[k] == false)
l++;
}
int[] listaPrimos = new int[l];
l=0;
for (int i = 0; i < n; i++){
if(listaComposto[i] == false)
listaPrimos[l] = i;
}
return listaPrimos;
}
public static void main(String[] args) {
//Execução sem crivo
double inicio = System.currentTimeMillis();
for(int n=10; n<=10_000; n*=10){
int[] primos = obterPrimos(n);
}
double fim = System.currentTimeMillis();
System.out.printf("tempo sem crivo: %.4f segundos\n", (fim - inicio)/1_000);
//Execução com crivo
inicio = System.currentTimeMillis();
for(int n=10; n<=10_000; n*=10){
int[] primos = obterPrimosViaCrivo(n);
}
fim = System.currentTimeMillis();
System.out.printf("tempo com crivo: %.4f segundos\n", (fim - inicio)/1_000);
}
}
|
package com.hotel.service;
public interface MyConnection {
String USERNAME = "root";
String PWD = "";
String URL = "jdbc:mysql://localhost:3306/Hotel";
}
|
/*
Copyright (C) 2013-2014, Securifera, Inc
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Securifera, Inc nor the names of its contributors may be
used to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
================================================================================
Pwnbrew is provided under the 3-clause BSD license above.
The copyright on this package is held by Securifera, Inc
*/
package pwnbrew.network;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.channels.AlreadyConnectedException;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Calendar;
import java.util.Date;
import java.util.EmptyStackException;
import java.util.logging.Level;
import pwnbrew.ClientConfig;
import pwnbrew.log.LoggableException;
import pwnbrew.log.RemoteLog;
import pwnbrew.manager.ConnectionManager;
import pwnbrew.manager.DataManager;
import pwnbrew.manager.OutgoingConnectionManager;
import pwnbrew.manager.PortManager;
import pwnbrew.selector.ConnectHandler;
import pwnbrew.selector.SocketChannelHandler;
import pwnbrew.utilities.Constants;
import pwnbrew.utilities.DebugPrinter;
import pwnbrew.utilities.ReconnectTimer;
/**
*
*
*/
public class ClientPortRouter extends PortRouter {
private static final int SLEEP_TIME = 1000;
private static final int CONNECT_RETRY = 3;
private static final String NAME_Class = ClientPortRouter.class.getSimpleName();
private OutgoingConnectionManager theOCM;
volatile boolean reconnectEnable = true;
//===============================================================
/**
* ClientComm constructor
*
* @param passedPortManager
* @param passedBool
* @throws IOException
*/
public ClientPortRouter( PortManager passedPortManager, boolean passedBool ) throws IOException {
super(passedPortManager, passedBool, Constants.Executor );
//Create server connection manager
theOCM = new OutgoingConnectionManager();
}
//===============================================================
/**
*
* @return
*/
public OutgoingConnectionManager getSCM() {
return theOCM;
}
//===============================================================
/**
* Recursive function for connecting to the server
*
* @return
* @throws IOException
*/
private boolean connect( int channelId, InetAddress hostAddress, int passedPort ) throws LoggableException {
SocketChannelHandler theSCH = theOCM.getSocketChannelHandler( channelId );
try {
if( theSCH == null || theSCH.getState() == Constants.DISCONNECTED ){
// Create a non-blocking socket channel
SocketChannel theSocketChannel = SocketChannel.open();
theSocketChannel.configureBlocking(false);
// Kick off connection establishment
try {
theSocketChannel.connect(new InetSocketAddress(hostAddress, passedPort));
} catch( AlreadyConnectedException ex ) {
return true;
}
// Register the server socket channel, indicating an interest in
// accepting new connections
ConnectHandler connectHandler = new ConnectHandler( this, channelId );
// Register the socket channel and handler with the selector
SelectionKey theSelKey = theSelectionRouter.register(theSocketChannel, SelectionKey.OP_CONNECT, connectHandler);
//Wait until the thread is notified or times out
boolean timedOut = waitForConnection();
if( timedOut )
DebugPrinter.printMessage( NAME_Class, "Connection timed out.");
else
DebugPrinter.printMessage( NAME_Class, "Connection made.");
//Return if the key was cancelled
if(!theSelKey.isValid()){
theSelKey.cancel();
return false;
}
//If we returned but we are not connected
theSCH = theOCM.getSocketChannelHandler( channelId );
if( theSCH == null || theSCH.getState() == Constants.DISCONNECTED){
DebugPrinter.printMessage( NAME_Class, "Invalid connection.");
//Shutdown the first connect handler and set it to null
theSelKey.cancel();
return false;
}
}
} catch(IOException ex){
throw new LoggableException(ex);
}
return true;
}
//===============================================================
/**
* Set reconnect enable
* @param passedFlag
*/
public void setReconnectFlag(boolean passedFlag ){
reconnectEnable = passedFlag;
}
//===============================================================
/**
* Adds an event for the selector that the client is interested in opening
* a connection.
*
* @return
* @throws IOException
*/
private boolean initiateConnection( int channedId, /**LockListener passedListener,**/ InetAddress hostAddress, int passedPort, int retry ) throws LoggableException {
int sleepTime = SLEEP_TIME;
boolean connected = false;
while( retry > 0 && !connected ){
connected = connect( channedId, hostAddress, passedPort );
//Sleep if not connected
if(!connected){
try {
//Intentially sleeping with lock held so there are no other attempts to
//connect to the server during this loop.
DebugPrinter.printMessage( NAME_Class, "Sleeping because of no connection.");
Thread.sleep(sleepTime);
} catch (InterruptedException ex) {
ex = null;
}
//Update counters and test
sleepTime += sleepTime;
retry--;
} else {
SocketChannelHandler aSC = theOCM.getSocketChannelHandler( channedId );
if( aSC != null ){
//DebugPrinter.printMessage( NAME_Class, "Registering id: " + Integer.toString(channedId));
//Check if certs didn't match
ClientConfig theConf = ClientConfig.getConfig();
byte stlth_val = 0;
if( theConf.useStealth() )
stlth_val = 1;
DebugPrinter.printMessage( NAME_Class, "Registering id: " + Integer.toString(channedId) + " Stealth: " + Integer.toString(stlth_val));
//Send register message
RegisterMessage aMsg = new RegisterMessage( RegisterMessage.REG, stlth_val, channedId);
DataManager.send( thePortManager, aMsg );
} else {
DebugPrinter.printMessage( NAME_Class, "Unable to get socket channel handler. Not sending Register Msg.");
connected = false;
}
}
}
return connected;
}
//===============================================================
/**
* Connection dropped.
*
* @param clientId
* @param channelId
*/
@Override
public void socketClosed( int clientId, int channelId ){
theOCM.removeHandler( channelId );
OutgoingConnectionManager aOCM = getConnectionManager();
if( aOCM != null )
aOCM.removeShell( channelId );
//Stop the keepalive
KeepAliveTimer aKAT = theOCM.getKeepAliveTimer( channelId );
if( aKAT != null )
aKAT.shutdown();
DebugPrinter.printMessage(NAME_Class, "Socket closed.");
ReconnectTimer aReconnectTimer = theOCM.getReconnectTimer(channelId);
//Create one if it doesn't exist
if( aReconnectTimer == null && channelId == ConnectionManager.COMM_CHANNEL_ID )
aReconnectTimer = new ReconnectTimer(ConnectionManager.COMM_CHANNEL_ID);
if( aReconnectTimer != null && !aReconnectTimer.isRunning() && reconnectEnable ){
DebugPrinter.printMessage(NAME_Class, "Starting Reconnect Timer");
aReconnectTimer.clearTimes();
//Create the calendar
Calendar theCalendar = Calendar.getInstance();
theCalendar.setTime( new Date() );
//Add 1 Minute
theCalendar.add( Calendar.MINUTE, 2);
Date aTime = theCalendar.getTime();
//Format and add to the queue
String dateStr = Constants.CHECKIN_DATE_FORMAT.format(aTime);
aReconnectTimer.addReconnectTime( dateStr );
//Add 5 Mins
theCalendar.add( Calendar.MINUTE, 5);
aTime = theCalendar.getTime();
//Format and add to the queue
dateStr = Constants.CHECKIN_DATE_FORMAT.format(aTime);
aReconnectTimer.addReconnectTime( dateStr );
//Add 10 Mins
theCalendar.add( Calendar.MINUTE, 10);
aTime = theCalendar.getTime();
//Format and add to the queue
dateStr = Constants.CHECKIN_DATE_FORMAT.format(aTime);
aReconnectTimer.addReconnectTime( dateStr );
//Add 15 Mins
theCalendar.add( Calendar.MINUTE, 15);
aTime = theCalendar.getTime();
//Format and add to the queue
dateStr = Constants.CHECKIN_DATE_FORMAT.format(aTime);
aReconnectTimer.addReconnectTime( dateStr );
for( int i= 0; i < 7 * 23; i++ ){
theCalendar.add( Calendar.HOUR_OF_DAY, 1 );
aTime = theCalendar.getTime();
//Format and add to the queue
dateStr = Constants.CHECKIN_DATE_FORMAT.format(aTime);
aReconnectTimer.addReconnectTime( dateStr );
}
//Execute it
aReconnectTimer.start();
} else if( !reconnectEnable ){
DebugPrinter.printMessage(NAME_Class, "Reconnect not enabled");
} else if (aReconnectTimer == null){
DebugPrinter.printMessage(NAME_Class, "ReconnectTimer is null");
} else if (aReconnectTimer.isRunning() && reconnectEnable){
aReconnectTimer.beNotified();
DebugPrinter.printMessage(NAME_Class, "ReconnectTimer is already running");
}
};
//===============================================================
/**
* Shuts down the handler and selector
*/
@Override
public void shutdown(){
theSelectionRouter.shutdown();
//Shut down the handler
theOCM.shutdown();
}
//===============================================================
/**
* Checks that a connection has been made to the passed port. If not it
* creates one.
*
* @param passedCallback
* @param passedIdArr
*/
public synchronized void ensureConnectivity( ConnectionCallback passedCallback, Integer... passedIdArr ) {
int channelId = 0;
int passedPort = passedCallback.getPort();
String serverIp = passedCallback.getServerIp();
try {
//Get the channelId
if( passedIdArr.length > 0){
channelId = passedIdArr[0];
} else {
channelId = theOCM.getNextChannelId();
}
//Get the handler
SocketChannelHandler aSC = theOCM.getSocketChannelHandler( channelId );
if(aSC == null || aSC.getState() == Constants.DISCONNECTED){
//Get the inet
InetAddress srvInet = InetAddress.getByName(serverIp);
DebugPrinter.printMessage( NAME_Class, "Attempting to connect to " + srvInet.getHostAddress() + ":" + passedPort);
//Set the callback
setConnectionCallback(channelId, passedCallback);
if( !initiateConnection( channelId, srvInet, passedPort, CONNECT_RETRY )){
RemoteLog.log(Level.INFO, NAME_Class, "ensureConnectivity()", "Unable to connect to port " + passedPort, null );
ConnectionCallback aCC = removeConnectionCallback(channelId);
aCC.handleConnection(0);
} else {
aSC = theOCM.getSocketChannelHandler( channelId );
if( aSC == null || aSC.getState() == Constants.DISCONNECTED ){
DebugPrinter.printMessage( NAME_Class, "Not connected.");
ConnectionCallback aCC = removeConnectionCallback(channelId);
aCC.handleConnection(0);
} else {
if( channelId == ConnectionManager.COMM_CHANNEL_ID ){
DebugPrinter.printMessage( NAME_Class, "Start keep alive.");
//Set the connected flag
KeepAliveTimer theKeepAliveTimer = new KeepAliveTimer( thePortManager, channelId);
theKeepAliveTimer.start();
//Set timer
theOCM.setKeepAliveTimer( channelId, theKeepAliveTimer );
}
}
}
}
} catch ( EmptyStackException | UnknownHostException | LoggableException ex) {
RemoteLog.log(Level.INFO, NAME_Class, "ensureConnectivity()", ex.getMessage(), ex );
if( channelId != 0 )
removeConnectionCallback(channelId);
//Call handler
passedCallback.handleConnection(0);
}
}
//==========================================================================
/**
*
* @param passedIdArr
* @return
*/
@Override
public OutgoingConnectionManager getConnectionManager( Integer... passedIdArr ) {
return theOCM;
}
//==========================================================================
/**
*
* @param aCM
* @param srcId
*/
@Override
public void setConnectionManager( ConnectionManager aCM, Integer... srcId ) {
if( aCM instanceof OutgoingConnectionManager ){
OutgoingConnectionManager anOCM = (OutgoingConnectionManager)aCM;
theOCM = anOCM;
}
}
}/* END CLASS ClientPortRouter */
|
package co.id.datascrip.mo_sam_div4_dts1.process.interfaces;
import java.util.ArrayList;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
/**
* Created by benny_aziz on 09/19/2016.
*/
public interface IC_Photo {
String URL_UPLOAD_PHOTO = "photo_upload";
@Multipart
@POST(URL_UPLOAD_PHOTO)
Call<ResponseBody> Upload(
@Part("count") RequestBody count,
@Part("json") RequestBody json,
@Part ArrayList<MultipartBody.Part> files);
}
|
package fr.iutinfo.skeleton.api;
import com.google.common.base.Charsets;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.Principal;
import java.security.SecureRandom;
public class User implements Principal {
final static Logger logger = LoggerFactory.getLogger(User.class);
private String nom;
private String prenom;
private String login;
private String password;
private String passwdHash;
private String salt;
private String role;
private static User anonymous = new User("Anonymous", "anonym","anne.onymous");
public User(String login) {
this.login=login;
}
public User(String name, String prenom, String login) {
this.nom = name;
this.prenom = prenom;
this.login=login;
}
public User() {
}
public String getName() {
return nom;
}
public void setName(String name) {
this.nom = name;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public void setPassword(String password) {
passwdHash = buildHash(password, getSalt());
this.password = password;
}
public String getPassword () {
return this.password;
}
private String buildHash(String password, String s) {
Hasher hasher = Hashing.md5().newHasher();
hasher.putString(password + s, Charsets.UTF_8);
return hasher.hash().toString();
}
public boolean isGoodPassword(String password) {
String hash = buildHash(password, getSalt());
return hash.equals(getPasswdHash());
}
public String getPasswdHash() {
return passwdHash;
}
public void setPasswdHash(String passwdHash) {
this.passwdHash = passwdHash;
}
@Override
public boolean equals(Object arg) {
if (getClass() != arg.getClass())
return false;
User user = (User) arg;
return nom.equals(user.nom) && prenom.equals(user.prenom) && passwdHash.equals(user.getPasswdHash()) && salt.equals((user.getSalt()));
}
@Override
public String toString() {
return login + ": " + prenom + ", " + nom ;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getSalt() {
if (salt == null) {
salt = generateSalt();
}
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
private String generateSalt() {
SecureRandom random = new SecureRandom();
Hasher hasher = Hashing.md5().newHasher();
hasher.putLong(random.nextLong());
return hasher.hash().toString();
}
public void resetPasswordHash() {
if (password != null && ! password.isEmpty()) {
setPassword(getPassword());
}
}
public static User getAnonymousUser() {
return anonymous ;
}
public static boolean isAnonymous(User currentUser) {
return currentUser.getLogin() == getAnonymousUser().getLogin();
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
|
package kickstart.model;
import org.javamoney.moneta.Money;
import org.salespointframework.catalog.Product;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.OneToMany;
import java.util.LinkedList;
import java.util.List;
//import org.salespointframework.quantity.Units;
//import org.salespointframework.quantity.Units;
@Entity
public class Article extends Product {
public enum ArticleType {
NOTEBOOK, COMPUTER, SOFTWARE, ZUBE;
}
private String model;
private String image;
private ArticleType type;
//@OneToMany für JPA
// cascade gibt an, was mit den Kindelementen (Comment) passieren soll wenn das Parentelement (Disc) mit der Datenbank
// "interagiert"
@OneToMany(cascade = CascadeType.ALL) private List<Comment> comments = new LinkedList<Comment>();
@SuppressWarnings("unused")
private Article() {}
public Article(String name, String image, Money price, String model, ArticleType type) {
//super(name, price, Units.METRIC);
super(name, price);
this.image = image;
this.model = model;
this.type = type;
}
public String getModel() {
return model;
}
public void addComment(Comment comment) {
comments.add(comment);
}
public Iterable<Comment> getComments() {
return comments;
}
public String getImage() {
return image;
}
public ArticleType getType() {
return type;
}
}
|
package hu.lamsoft.hms.common.restapi.restservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import hu.lamsoft.hms.common.service.customer.dto.CustomerDTO;
@Service
public class CustomerRestService {
private static final String CUSTOMER_SERVICE_URL = "http://CUSTOMER-APPLICATION";
@Autowired
@LoadBalanced
private RestTemplate restTemplate;
public CustomerDTO getCustomer(String email) {
return restTemplate.getForObject(CUSTOMER_SERVICE_URL + "/internal/customer?email="+email, CustomerDTO.class);
}
}
|
package com.g74.rollersplat.viewer.game;
import com.g74.rollersplat.model.level.Level;
import com.g74.rollersplat.viewer.gui.GUI;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.io.IOException;
public class LevelViewerTest {
private LevelViewer viewer;
private GUI gui;
@BeforeEach
void setUp() {
gui = Mockito.mock(GUI.class);
viewer = new LevelViewer(gui);
}
/*@Test
void draw() throws IOException {
viewer.draw(new Level());
}*/
}
|
package com.ytf.zk.util;
/**
* Created by yutianfang
* DATE: 17/4/23星期日.
*/
public class ZKUtil {
}
|
package de.cuuky.varo.listener;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerRespawnEvent;
import de.cuuky.varo.Main;
import de.cuuky.varo.player.VaroPlayer;
public class PlayerRespawnListener implements Listener {
@EventHandler
public void onPlayerRespawn(PlayerRespawnEvent event) {
Bukkit.getScheduler().scheduleSyncDelayedTask(Main.getInstance(), new Runnable() {
@Override
public void run() {
VaroPlayer.getPlayer(event.getPlayer()).setNormalAttackSpeed();
}
}, 20);
}
}
|
package com.deepakm.designpattern.strategy.sort;
import java.util.Comparator;
import java.util.List;
/**
* Created by dmarathe on 11/17/15.
*/
public interface Sort<Entity> {
public List<Entity> sort(List<Entity> collection);
public List<? extends Entity> sort(List<? extends Entity> collection, Comparator sortComparator);
}
|
package hu.mitro.persistence.service;
import java.util.List;
import javax.ejb.Local;
import hu.mitro.persistence.entity.Client;
import hu.mitro.persistence.exception.PersistenceLayerException;
@Local
public interface ClientService {
boolean exists(String email) throws PersistenceLayerException;
List<Client> readAllClients() throws PersistenceLayerException;
Client readClientById(Long id) throws PersistenceLayerException;
Client readClientByEmail(String email) throws PersistenceLayerException;
Client readClientByLastnameAndFirstname(String lastname, String firstname) throws PersistenceLayerException;
List<Client> readClientByLastname(String lastname) throws PersistenceLayerException;
Client createClient(Client client) throws PersistenceLayerException;
Client updateClient(Client client) throws PersistenceLayerException;
Client removeClient(Client client) throws PersistenceLayerException;
}
|
package com.wxt.designpattern.abstractfactory.nodp;
/**
* @Auther: weixiaotao
* @ClassName MainboardFactory
* @Date: 2018/10/22 20:51
* @Description: 创建主板的简单工厂
*/
public class MainboardFactory {
/**
* 创建主板接口对象的方法
* @param type 选择主板类型的参数
* @return 主板接口对象的方法
*/
public static MainboardApi createMainboardApi(int type){
MainboardApi mainboard = null;
//根据参数来选择并创建相应的主板对象
if(type==1){
mainboard = new GAMainboard(2048);
}else if(type==2){
mainboard = new MSIMainboard(1024);
}
return mainboard;
}
}
|
package com.sshfortress.common.entity;
import java.util.Date;
/**
* <p class="detail">
* 功能:SSH帐号信息
* </p>
* @ClassName: SshList
* @version V1.0
*/
public class SshList implements java.io.Serializable{
private static final long serialVersionUID = -7086092475909761449L;
/** */
private Long id;
/** ssh登录名 */
private String name;
/** ssh登录密码 */
private String password;
/** 备注 */
private String remark;
/** 是否删除 0正常 1删除 */
private Integer isDelete;
/** 创建时间 */
private Date createTime;
/** 更新时间 */
private Date updateTime;
/** 创建者 */
private String creator;
public SshList (){
super();
}
public SshList(Long id){
this.id=id;
}
public Long getId(){
return this.id;
}
public void setId(Long id){
this.id=id;
}
public String getName(){
return this.name;
}
public void setName(String name){
this.name=name;
}
public String getPassword(){
return this.password;
}
public void setPassword(String password){
this.password=password;
}
public String getRemark(){
return this.remark;
}
public void setRemark(String remark){
this.remark=remark;
}
public Integer getIsDelete(){
return this.isDelete;
}
public void setIsDelete(Integer isDelete){
this.isDelete=isDelete;
}
public Date getCreateTime(){
return this.createTime;
}
public void setCreateTime(Date createTime){
this.createTime=createTime;
}
public Date getUpdateTime(){
return this.updateTime;
}
public void setUpdateTime(Date updateTime){
this.updateTime=updateTime;
}
public String getCreator(){
return this.creator;
}
public void setCreator(String creator){
this.creator=creator;
}
}
|
package com.njxzc.dao;
public class TestDaoImpl implements TestDao{
@Override
public void sayHello() {
System.out.println("Hello, Study hard!");
}
}
|
package com.bofsoft.laio.customerservice.Adapter;
import android.content.Context;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import com.bofsoft.laio.customerservice.Activity.BaseVehicleActivity;
import com.bofsoft.laio.customerservice.DataClass.db.ClassTypeData;
import com.bofsoft.laio.customerservice.DataClass.index.ProductVASData;
import com.bofsoft.laio.customerservice.Database.DBCallBack;
import com.bofsoft.laio.customerservice.Database.PublicDBManager;
import com.bofsoft.laio.customerservice.Database.TableManager;
import com.bofsoft.laio.customerservice.R;
import java.util.ArrayList;
import java.util.List;
/**
* 培训产品增值服务
*
* @author admin
*/
public class TrainProVasListAdapter extends BaseAdapter {
Context mContext;
LayoutInflater mInflater;
List<ProductVASData> list;
List<ProductVASData> checkState = new ArrayList<ProductVASData>();
List<ClassTypeData> classTypeList;
SparseArray<String> classTypeArray = new SparseArray<String>();
public TrainProVasListAdapter(Context context) {
this.mContext = context;
mInflater = LayoutInflater.from(context);
PublicDBManager.getInstance(mContext).queryList(ClassTypeData.class,
TableManager.Laio_Class_Type, new DBCallBack<ClassTypeData>() {
@Override
public void onCallBackList(List<ClassTypeData> list) {
initClassTypeArray(list);
}
});
}
public void initClassTypeArray(List<ClassTypeData> classList) {
if (classList != null) {
for (ClassTypeData data : classList) {
classTypeArray.put(data.getId(), data.getName());
}
}
}
public List<ProductVASData> getList() {
return list;
}
public void setList(List<ProductVASData> list) {
this.checkState.clear();
this.list = list;
notifyDataSetChanged();
}
public void setClassTypeList(List<ClassTypeData> classTypeList) {
this.classTypeList = classTypeList;
}
/**
* 清除选择项
*/
public void clearCheckState() {
checkState.clear();
}
public List<ProductVASData> getCheckState() {
return this.checkState;
}
@Override
public int getCount() {
if (list == null) {
return 0;
}
return list.size();
}
@Override
public ProductVASData getItem(int position) {
if (list == null) {
return null;
}
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.activity_provas_list_item, null);
holder.textName = (TextView) convertView.findViewById(R.id.txt_name_Vas);
holder.textPrice = (TextView) convertView.findViewById(R.id.txtPrice_Vas);
holder.textSerContent = (TextView) convertView.findViewById(R.id.txt_ServerContent_Vas);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox_Vas);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final ProductVASData data = list.get(position);
String className = classTypeArray.get(data.getClassType());
if (!TextUtils.isEmpty(className)) {
holder.textName.setText(data.getName() + "(" + className + ")");
} else {
holder.textName.setText(data.getName());
}
holder.textPrice.setText(mContext.getString(R.string.account, data.getPrice()));
holder.textSerContent.setText(data.getContent());
holder.checkBox.setFocusable(false);
holder.checkBox.setChecked(checkState.contains(data));
holder.checkBox.setClickable(false);
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (classTypeList == null || classTypeList.size() < 1) {
((BaseVehicleActivity) mContext).showToastShortTime("请选择课程类型");
} else {
if (checkState.contains(data)) {
checkState.remove(data);
} else {
checkState.add(data);
}
notifyDataSetChanged();
}
}
});
return convertView;
}
class ViewHolder {
TextView textName;
TextView textPrice;
TextView textSerContent;
CheckBox checkBox;
}
}
|
package com.bcreagh.data;
public class BinaryNodeService implements NodeService {
private BlockService blockService;
public void setBlockService(BlockService blockService) {
this.blockService = blockService;
}
}
|
package edu.cb.climbingclub.macias.marcus;
import java.util.ArrayList;
import java.util.List;
import edu.jenks.dist.cb.climbingclub.AbstractClimbInfo;
import edu.jenks.dist.cb.climbingclub.AbstractClimbingClub;
public class ClimbingClubChronological extends AbstractClimbingClub {
public void addClimb(String peakName, int climbTime) {
ClimbInfo info = new ClimbInfo(peakName, climbTime);
// List<AbstractClimbingClub> list = getClimbList();
this.getClimbList().add(info);
}
public static void main(String[] args) {
ClimbingClubChronological run = new ClimbingClubChronological();
run.addClimb("Cooll", 3);
run.addClimb("Cooall", 3);
run.addClimb("Marcus", 3);
run.addClimb("Batman", 3);
run.addClimb("Cooll", 3);
run.addClimb("Cooll", 3);
System.out.println(run.distinctPeakNames());
for (int i = 0; i < run.getClimbList().size(); i++) {
System.out.println(run.getClimbList().get(i).getPeakName());
}
}
public int distinctPeakNames() {
List<String> names = new ArrayList<>();
for (int i = 0; i < getClimbList().size(); i++) {
String currentName = getClimbList().get(i).getPeakName();
boolean maybeAdd = true;
if (names.size() == 0) {
names.add(currentName);
continue;
}
for (int x = 0; x < names.size(); x++) {
String compareName = names.get(x);
if (currentName.equals(compareName)) {
maybeAdd = false;
break;
}
}
if (maybeAdd) {
names.add(currentName);
}
}
return names.size();
}
}
|
package no.nav.vedtak.sikkerhet.oidc.token.impl;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpRequest;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import no.nav.vedtak.sikkerhet.oidc.config.ConfigProvider;
import no.nav.vedtak.sikkerhet.oidc.config.OpenIDProvider;
import no.nav.vedtak.sikkerhet.oidc.token.OpenIDToken;
import no.nav.vedtak.sikkerhet.oidc.token.TokenString;
public class AzureSystemTokenKlient {
private static final Logger LOG = LoggerFactory.getLogger(AzureSystemTokenKlient.class);
private static AzureSystemTokenKlient INSTANCE;
private final URI tokenEndpoint;
private final String clientId;
private final String clientSecret;
private final URI azureProxy;
private final Map<String, OpenIDToken> accessToken = new LinkedHashMap<>();
public static synchronized AzureSystemTokenKlient instance() {
var inst = INSTANCE;
if (inst == null) {
inst = new AzureSystemTokenKlient();
INSTANCE = inst;
}
return inst;
}
private AzureSystemTokenKlient() {
var provider = ConfigProvider.getOpenIDConfiguration(OpenIDProvider.AZUREAD).orElseThrow();
this.tokenEndpoint = provider.tokenEndpoint();
this.azureProxy = provider.proxy();
this.clientId = provider.clientId();
this.clientSecret = provider.clientSecret();
}
public synchronized OpenIDToken hentAccessToken(String scope) {
// Expiry normalt 3599 ...
var heldToken = accessToken.get(scope);
if (heldToken != null && heldToken.isNotExpired()) {
return heldToken.copy();
}
var response = hentAccessToken(clientId, clientSecret, tokenEndpoint, azureProxy, scope);
LOG.info("AzureAD hentet token for scope {} fikk token av type {} utløper {}", scope, response.token_type(), response.expires_in());
var newToken = new OpenIDToken(OpenIDProvider.AZUREAD, response.token_type(), new TokenString(response.access_token()), scope,
response.expires_in());
accessToken.put(scope, newToken);
return newToken.copy();
}
private static OidcTokenResponse hentAccessToken(String clientId, String clientSecret, URI tokenEndpoint, URI proxy, String scope) {
var request = HttpRequest.newBuilder()
.header("Cache-Control", "no-cache")
.header(Headers.CONTENT_TYPE, Headers.APPLICATION_FORM_ENCODED)
.timeout(Duration.ofSeconds(10))
.uri(tokenEndpoint)
.POST(ofFormData(clientId, clientSecret, scope))
.build();
return GeneriskTokenKlient.hentToken(request, proxy);
}
private static HttpRequest.BodyPublisher ofFormData(String clientId, String clientSecret, String scope) {
var encodedScope = URLEncoder.encode(scope, UTF_8);
var formdata = "grant_type=client_credentials" + "&client_id=" + clientId + "&client_secret=" + clientSecret + "&scope=" + encodedScope;
return HttpRequest.BodyPublishers.ofString(formdata, UTF_8);
}
}
|
package com.spreadtrum.android.eng;
import android.app.Activity;
import android.os.Bundle;
import android.provider.Settings.System;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class CPRegister extends Activity implements OnClickListener {
Button close;
Button open;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setcpreg);
this.open = (Button) findViewById(R.id.setopenbutton);
this.close = (Button) findViewById(R.id.setclosebutton);
}
public void onClick(View v) {
if (v.getId() == R.id.setopenbutton) {
System.putString(getContentResolver(), "yulong.sms.background.register", "true");
this.open.setEnabled(false);
this.close.setEnabled(true);
} else if (v.getId() == R.id.setclosebutton) {
System.putString(getContentResolver(), "yulong.sms.background.register", "false");
this.close.setEnabled(false);
this.open.setEnabled(true);
}
}
protected void onDestroy() {
super.onDestroy();
}
}
|
package com.news.demo.controller;
import com.baomidou.mybatisplus.plugins.Page;
import com.news.demo.Utils.Result.ResultMap;
import com.news.demo.Utils.commonUtils;
import com.news.demo.model.Commdity;
import com.news.demo.model.MongoDbModel.CommdityDb;
import com.news.demo.module.BaseController;
import com.news.demo.resultSet.Result;
import com.news.demo.resultSet.ResultCode;
import com.news.demo.service.impl.CommdityServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* <p>
* 前端控制器
* </p>
*
* @author GEBILAOHU
* @since 2019-07-07
*/
@RestController
@RequestMapping("/commdity")
public class CommdityController extends BaseController {
@Autowired
private CommdityServiceImpl commdityService;
/**
* @Description: 分页查询推荐
* @UpdateUser: GEBILAOHU
* @UpdateDate:
* @UpdateRemark: 修改内容
* @Version: 1.0
*/
@CrossOrigin
@RequestMapping(value = "/getCommdity", method = RequestMethod.POST)
public List getCommdity(@RequestBody String currentDate){
if(Objects.nonNull(currentDate)||!"".equals(currentDate)){
currentDate = commonUtils.getStrNow();
}
Page page1 = new Page(1,4);
List<Map<String,String>> map= commdityService.getCommmdityPageNotic(page1);
return map;
}
/**
* @Description: 分页查询推荐
* @UpdateUser: GEBILAOHU
* @UpdateDate:
* @UpdateRemark: 修改内容
* @Version: 2.0
*/
@CrossOrigin
@RequestMapping(value = "/getCommditys", method = RequestMethod.POST)
public List getCommditys(@RequestBody Map<String,String> data){
String currentDate = data.get("currentDate");
if(Objects.nonNull(currentDate)){
currentDate = commonUtils.getStrNow();
}
Page page1 = new Page(Integer.valueOf(data.get("page")),4);
List<Map<String,String>> map= commdityService.getCommmdityPageNotic(page1);
return map;
}
@CrossOrigin
@RequestMapping(value = "/getRecommendCommditys", method = RequestMethod.POST)
public List<CommdityDb> getRecommendCommditys(@RequestBody Map<String,String> data){
List<CommdityDb> cdbs = new ArrayList<>();
try {
cdbs = commdityService.getCommmdityPageNoticV2();
}catch (Exception e){
e.printStackTrace();
}
return cdbs;
}
}
|
package com.pointinside.android.api.dao;
import android.database.Cursor;
import android.net.Uri;
import com.pointinside.android.api.maps.PixelCoordinate;
public class PixelCoordinateDataCursor
extends AbstractDataCursor
{
private static final AbstractDataCursor.Creator<PixelCoordinateDataCursor> CREATOR = new AbstractDataCursor.Creator()
{
public PixelCoordinateDataCursor init(Cursor paramAnonymousCursor)
{
return new PixelCoordinateDataCursor(paramAnonymousCursor);
}
};
private int mColumnAltitude;
private int mColumnLatitude;
private int mColumnLongitude;
private int mColumnPixelX;
private int mColumnPixelY;
private int mColumnSpecialAreaId;
private PixelCoordinateDataCursor(Cursor paramCursor)
{
super(paramCursor);
this.mColumnSpecialAreaId = paramCursor.getColumnIndex("special_area_id");
this.mColumnAltitude = paramCursor.getColumnIndex("altitude");
this.mColumnPixelX = paramCursor.getColumnIndex("pixel_x");
this.mColumnPixelY = paramCursor.getColumnIndex("pixel_y");
this.mColumnLatitude = paramCursor.getColumnIndex("latitude");
this.mColumnLongitude = paramCursor.getColumnIndex("longitude");
}
public static PixelCoordinateDataCursor getInstance(Cursor paramCursor)
{
return (PixelCoordinateDataCursor)CREATOR.newInstance(paramCursor);
}
public static PixelCoordinateDataCursor getInstance(PIMapDataset paramPIMapDataset, Uri paramUri)
{
return (PixelCoordinateDataCursor)CREATOR.newInstance(paramPIMapDataset, paramUri);
}
public float getAltitude()
{
return this.mCursor.getFloat(this.mColumnAltitude);
}
public double getLatitude()
{
return this.mCursor.getDouble(this.mColumnLatitude);
}
public double getLongitude()
{
return this.mCursor.getDouble(this.mColumnLongitude);
}
public PixelCoordinate getPixelCoordinate()
{
return new PixelCoordinate(getSpecialAreaId(), getAltitude(), getLatitude(), getLongitude(), getX(), getY());
}
public long getSpecialAreaId()
{
return this.mCursor.getLong(this.mColumnSpecialAreaId);
}
public Uri getUri()
{
return PIVenue.getMapPixelCoordinateUri(getId());
}
public int getX()
{
return this.mCursor.getInt(this.mColumnPixelX);
}
public int getY()
{
return this.mCursor.getInt(this.mColumnPixelY);
}
}
/* Location: D:\xinghai\dex2jar\classes-dex2jar.jar
* Qualified Name: com.pointinside.android.api.dao.PixelCoordinateDataCursor
* JD-Core Version: 0.7.0.1
*/
|
package com.example.qrcode;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseArray;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.TextView;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.text.TextBlock;
import com.google.android.gms.vision.text.TextRecognizer;
import java.io.IOException;
import java.util.regex.Pattern;
public class Main3Activity extends AppCompatActivity {
private SurfaceView cameraView;
private TextView textView;
private CameraSource cameraSource;
private static final int MY_CAMERA_REQUEST_CODE = 100;
private static final Pattern sPattern = Pattern.compile("^[0-9]*$");
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_CAMERA_REQUEST_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
try {
cameraSource.start(cameraView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static boolean IsNumeric(String str) {
return sPattern.matcher(str).matches();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
cameraView = findViewById(R.id.surface_view);
textView = findViewById(R.id.text_view);
TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
if (!textRecognizer.isOperational()) {
Log.w("MainActivity", "Detector dependencies are not yet available");
} else {
cameraSource = new CameraSource.Builder(getApplicationContext(), textRecognizer)
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedPreviewSize(1280, 1024)
.setRequestedFps(2.0f)
.setAutoFocusEnabled(true)
.build();
cameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_REQUEST_CODE);
}
cameraSource.start(cameraView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
textRecognizer.setProcessor(new Detector.Processor<TextBlock>() {
@Override
public void release() {
}
@Override
public void receiveDetections(Detector.Detections<TextBlock> detections) {
final SparseArray<TextBlock> itms = detections.getDetectedItems();
if (itms.size() != 0) {
textView.post(new Runnable() {
@SuppressLint("SetTextI18n")
@Override
public void run() {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < itms.size(); ++i) {
TextBlock item = itms.valueAt(i);
stringBuilder.append(item.getValue());
}
if (IsNumeric(stringBuilder.toString())) {
MainActivity.tv.setText(stringBuilder.toString());
onBackPressed();
}
}
});
}
}
});
}
}
}
|
package com.buddybank.mdw.dataobject.domain;
public enum AccountType
{
BANK_ACCOUNT(1), PIGGY_DEPOSIT(11);
public final int category;
private AccountType(final int category)
{
this.category = category;
}
public static AccountType getAccountTypeByCategory(final int category)
{
if (category==1)
{
return AccountType.BANK_ACCOUNT;
}
if (category==11)
{
return AccountType.PIGGY_DEPOSIT;
}
else
throw new IllegalArgumentException("category '"+category+"' is not a valid argument!");
}
}
|
package com.ecej.nove.base.sms;
public enum SmsSignEnum {
/**
* e城e家
*/
ECEJ(0),
/**
* 新奥-e城e家
*/
XINAO_ECEJ(1);
public Integer getValue() {
return value;
}
private final Integer value;
SmsSignEnum(Integer value) {
this.value = value;
}
}
|
package player.Equipe2;
import pacman.*;
import util.Counter;
import java.util.List;
public class GreedyPacManPlayer implements PacManPlayer, StateEvaluator {
@Override
public Move chooseMove(Game game) {
State s = game.getCurrentState();
List<Move> legalMoves = game.getLegalPacManMoves();
Counter<Move> scores = new Counter<Move>();
for (Move m : legalMoves){
List<State> stateList = Game.getProjectedStates(s, m);
State last = stateList.get(stateList.size() - 1);
scores.setCount(m, evaluateState(last));
}
return scores.argmax();
}
@Override
public double evaluateState(State s) {
return PacmanStateEvaluator.evaluateState(s);
}
}
|
package com.arrays;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Subsets {
public static void main(String[] args) {
Subsets sb = new Subsets();
int [] input = {1,2,3};
List<List<Integer>> res = sb.subsets(input);
for(List<Integer> s: res)
System.out.println(s);
}
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(nums);
backtrack(res,new ArrayList<>(),nums,0);
return res;
}
public void backtrack(List<List<Integer>> res, List<Integer> tempList, int[] nums, int start) {
res.add(new ArrayList<>(tempList));
for(int i=start;i<nums.length;i++) {
tempList.add(nums[i]);
backtrack(res, tempList, nums, i+1);
tempList.remove(tempList.size()-1);
}
}
}
|
package com.example.android.offline;
import android.app.Dialog;
import android.arch.lifecycle.Observer;
import android.arch.paging.LivePagedListBuilder;
import android.arch.paging.PagedList;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.CookieManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.sap.cloud.android.odata.espmcontainer.ESPMContainer;
import com.sap.cloud.android.odata.espmcontainer.ESPMContainerMetadata;
import com.sap.cloud.android.odata.espmcontainer.SalesOrderItem;
import com.sap.cloud.android.odata.espmcontainer.Supplier;
import com.sap.cloud.mobile.foundation.authentication.OAuth2Configuration;
import com.sap.cloud.mobile.foundation.authentication.OAuth2Interceptor;
import com.sap.cloud.mobile.foundation.authentication.OAuth2WebViewProcessor;
import com.sap.cloud.mobile.foundation.common.ClientProvider;
import com.sap.cloud.mobile.foundation.common.SettingsParameters;
import com.sap.cloud.mobile.foundation.logging.Logging;
import com.sap.cloud.mobile.foundation.networking.AppHeadersInterceptor;
import com.sap.cloud.mobile.foundation.networking.WebkitCookieJar;
import com.sap.cloud.mobile.foundation.user.UserInfo;
import com.sap.cloud.mobile.foundation.user.UserRoles;
import com.sap.cloud.mobile.odata.DataQuery;
import com.sap.cloud.mobile.odata.EntitySet;
import com.sap.cloud.mobile.odata.EntityType;
import com.sap.cloud.mobile.odata.EntityValue;
import com.sap.cloud.mobile.odata.EntityValueList;
import com.sap.cloud.mobile.odata.core.AndroidSystem;
import com.sap.cloud.mobile.odata.offline.OfflineODataDefiningQuery;
import com.sap.cloud.mobile.odata.offline.OfflineODataException;
import com.sap.cloud.mobile.odata.offline.OfflineODataParameters;
import com.sap.cloud.mobile.odata.offline.OfflineODataProvider;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import static com.example.android.offline.ChangeCustomerDetailActivity.customer;
import static com.example.android.offline.StorageManager.adapter;
public class MainActivity extends AppCompatActivity implements CustomerRecyclerViewAdapter.ItemClickListener {
private final static String USER_NUMBER = "p1743065160";
private final static String OAUTH_CLIENT_ID = "1149245f-2655-48ab-a597-d4ef45ceab71";
public final static String TAG = "myDebuggingTag";
public final static String APP_ID = "com.sap.offline";
public final static String SERVICE_URL = "https://hcpms-" + USER_NUMBER + "trial.hanatrial.ondemand.com";
public final static String CONNECTION_ID = "com.sap.edm.sampleservice.v2";
private final static String AUTH_END_POINT = "https://oauthasservices-" + USER_NUMBER + "trial.hanatrial.ondemand.com/oauth2/api/v1/authorize";
private final static String TOKEN_END_POINT = "https://oauthasservices-" + USER_NUMBER + "trial.hanatrial.ondemand.com/oauth2/api/v1/token";
private final static String OAUTH_REDIRECT_URL = "https://oauthasservices-" + USER_NUMBER + "trial.hanatrial.ondemand.com";
private final static String ZERO_QUANTITY_ERROR_MESSAGE = "The value of quantity should be greater than zero";
private Menu menu;
private String deviceID;
private boolean firstOpen;
private MenuItem syncMenuItem;
private MenuItem loginMenuItem;
private MenuItem logoutMenuItem;
private MenuItem createCustomerMenuItem;
private MenuItem zeroItemMenuItem;
private TextView loginTextView;
private TextView loadingTextView;
private LinearLayout loadingSpinnerParent;
private RecyclerView recyclerView;
private SettingsParameters settingsParameters;
public static String currentUser;
public static CustomerDataSourceFactory factory;
public StorageManager storageManager = StorageManager.getInstance();
protected static Toast mToast = null;
// Don't attempt to unbind from the service unless the client has received some
// information about the service's state.
private boolean shouldUnbind;
// To invoke the bound service, first make sure that this value
// is not null.
private OfflineODataForegroundService boundService;
private ServiceConnection connection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the service object we can use to
// interact with the service. Because we have bound to a explicit
// service that we know is running in our own process, we can
// cast its IBinder to a concrete class and directly access it.
boundService = ((OfflineODataForegroundService.LocalBinder) service).getService();
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
// Because it is running in our same process, we should never
// see this happen.
boundService = null;
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
doBindService();
// Setup the toolbar options
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Attempt to configure OAuth
deviceID = android.provider.Settings.Secure.getString(this.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
Logging.ConfigurationBuilder cb = new Logging.ConfigurationBuilder();
cb.logToConsole(true);
Logging.initialize(this.getApplicationContext(), cb);
OAuth2Configuration oAuth2Configuration = new OAuth2Configuration.Builder(getApplicationContext())
.clientId(OAUTH_CLIENT_ID)
.responseType("code")
.authUrl(AUTH_END_POINT)
.tokenUrl(TOKEN_END_POINT)
.redirectUrl(OAUTH_REDIRECT_URL)
.build();
SAPOAuthTokenStore oauthTokenStore = SAPOAuthTokenStore.getInstance();
try {
settingsParameters = new SettingsParameters(SERVICE_URL, APP_ID, deviceID, "1.0");
} catch (MalformedURLException e) {
Log.d(TAG, "Error creating the settings parameters: " + e.getMessage());
}
OkHttpClient myOkHttpClient = new OkHttpClient.Builder()
.addInterceptor(new AppHeadersInterceptor(APP_ID, deviceID, "1.0"))
.addInterceptor(new OAuth2Interceptor(new OAuth2WebViewProcessor(oAuth2Configuration), oauthTokenStore))
.cookieJar(new WebkitCookieJar())
.build();
ClientProvider.set(myOkHttpClient);
ch.qos.logback.classic.Logger myRootLogger = Logging.getRootLogger();
myRootLogger.setLevel(Level.ERROR); //levels in order are all, trace, debug, info, warn, error, off
loadingSpinnerParent = findViewById(R.id.loading_spinner_parent);
loadingTextView = findViewById(R.id.loading_text_view);
loginTextView = findViewById(R.id.login_text);
recyclerView = findViewById(R.id.rvCustomers);
LinearLayoutManager llm = new LinearLayoutManager(this);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), llm.getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);
recyclerView.setLayoutManager(llm);
// Passing in the finishLoading method so that the loading spinner can be dismissed by the adapter
adapter = new CustomerRecyclerViewAdapter(getApplicationContext(), () -> finishLoading());
adapter.setClickListener(this);
// Loads up the recycler view
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
recyclerView.setItemViewCacheSize(15);
recyclerView.setDrawingCacheEnabled(true);
firstOpen = savedInstanceState == null;
}
private void checkError(String error) {
if (error.contains("Unable to resolve host")) { // no wifi
Log.d(TAG, "Shared Offline Store failed to open. Check WiFi.");
runOnUiThread(() -> {
findViewById(R.id.loading_spinner).setVisibility(View.GONE);
((TextView) findViewById(R.id.loading_text_view)).setText("Failed to open Shared Offline Store. Make sure that you have Internet connection and restart the app.");
});
} else if (error.contains("HTTP status code: 503")) { // bad i number
Log.d(TAG, "Shared Offline Store failed to open. Check i-number in MainActivity.java file.");
runOnUiThread(() -> {
findViewById(R.id.loading_spinner).setVisibility(View.GONE);
((TextView) findViewById(R.id.loading_text_view)).setText("Failed to open Shared Offline Store. Make sure that you have the correct USER_NUMBER in MainActivity.java file.");
});
} else if (error.toString().contains("HTTP status code: 404")) {
Log.d(TAG, "Shared Offline Store failed to open. Check Cockpit for MultiUser project.");
runOnUiThread(() -> {
findViewById(R.id.loading_spinner).setVisibility(View.GONE);
((TextView) findViewById(R.id.loading_text_view)).setText("Failed to open Shared Offline Store. Make sure that the Offline project exists in the Mobile Servcies Cockpit.");
});
} else if (error.contains("unauthorized_client")) {
Log.d(TAG, "Shared Offline Store failed to open. Check OAUTH_CLIENT_ID in MainActivity.java file.");
runOnUiThread(() -> {
findViewById(R.id.loading_spinner).setVisibility(View.GONE);
((TextView) findViewById(R.id.loading_text_view)).setText("Failed to open Shared Offline Store. Make sure that you have the correct OAUTH_CLIENT_ID in MainActivity.java file.");
});
} else {
Log.d(TAG, "Shared Offline Store failed to open. Error not caught: " + error.toString());
runOnUiThread(() -> {
findViewById(R.id.loading_spinner).setVisibility(View.GONE);
((TextView) findViewById(R.id.loading_text_view)).setText("Failed to open Shared Offline Store. Error: " + error.toString());
});
}
}
@Override
protected void onDestroy() {
super.onDestroy();
doUnbindService();
}
void doBindService() {
// Attempts to establish a connection with the service. We use an
// explicit class name because we want a specific service
// implementation that we know will be running in our own process
// (and thus won't be supporting component replacement by other
// applications).
if (bindService(new Intent(MainActivity.this, OfflineODataForegroundService.class),
connection, Context.BIND_AUTO_CREATE)) {
shouldUnbind = true;
} else {
Log.e(TAG, "Error: The requested service doesn't " +
"exist, or this client isn't allowed access to it.");
}
}
void doUnbindService() {
if (shouldUnbind) {
// Release information about the service's state.
unbindService(connection);
shouldUnbind = false;
}
}
/**
* toastAMessageFromBackground is used to produce a toast message
* @param msg the string message to print
*/
private void toastAMessageFromBackground(String msg) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(() -> {
if (mToast != null) mToast.cancel();
mToast = Toast.makeText(getApplicationContext(),
msg,
Toast.LENGTH_SHORT);
mToast.show();
}
);
}
/**
* addDefiningQueryAfterOpening is used as an example to show how to add a defining query after
* the offline store has already been opened with its preset list of defining queries.
*/
private void addDefiningQueryAfterOpening() {
try {
OfflineODataDefiningQuery suppliersQuery = new OfflineODataDefiningQuery("Suppliers", "Suppliers", false);
storageManager.getOfflineODataProvider().addDefiningQuery(suppliersQuery);
storageManager.getOfflineODataProvider().download(() -> {
List<Supplier> suppliers = storageManager.getESPMContainer().getSuppliers();
Log.d(TAG, "Found these suppliers: ");
for (Supplier supplier : suppliers) {
Log.d(TAG, supplier.getSupplierName());
}
}, (error) -> {
Log.e(TAG, "Error occurred: " + error.getMessage());
});
} catch (OfflineODataException e) {
e.printStackTrace();
Log.e(TAG, "Exception encountered: " + e.getMessage());
}
}
/**
* setupOfflineStore simply sets up the offline store with a list of defining queries,
* which can be modified depending on the use case.
*/
private void setupOfflineStore() {
Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("com.sap.cloud.mobile.odata");
logger.setLevel(Level.ALL);
AndroidSystem.setContext(getApplicationContext());
try {
URL url = new URL(SERVICE_URL + "/" + CONNECTION_ID);
OfflineODataParameters offParam = new OfflineODataParameters();
offParam.setEnableRepeatableRequests(true);
// by setting the page size here, we enable server side paging of the data
offParam.setPageSize(10);
storageManager.setOfflineODataProvider(new OfflineODataProvider(url, offParam, ClientProvider.get(), null, null));
OfflineODataDefiningQuery productsQuery = new OfflineODataDefiningQuery("Products", "Products", false);
OfflineODataDefiningQuery customersQuery = new OfflineODataDefiningQuery("Customers", "Customers", false);
OfflineODataDefiningQuery salesOrderQuery = new OfflineODataDefiningQuery("SalesOrders", "SalesOrderHeaders", false);
OfflineODataDefiningQuery salesOrderItemsQuery = new OfflineODataDefiningQuery("SalesOrderItems", "SalesOrderItems", false);
storageManager.getOfflineODataProvider().addDefiningQuery(productsQuery);
storageManager.getOfflineODataProvider().addDefiningQuery(customersQuery);
storageManager.getOfflineODataProvider().addDefiningQuery(salesOrderQuery);
storageManager.getOfflineODataProvider().addDefiningQuery(salesOrderItemsQuery);
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, "Exception encountered setting up offline store: " + e.getMessage());
}
// Opens the offline store after defining all the "Defining Queries"
loadingTextView.setText("Opening the offline store.");
boundService.openStore(storageManager.getOfflineODataProvider(), () -> {
runOnUiThread(() -> loadingTextView.setText("Successfully opened the offline store, downloading the latest changes."));
storageManager.setESPMContainer(new ESPMContainer(storageManager.getOfflineODataProvider()));
Log.d(TAG, "Successfully opened offline store.");
boundService.downloadStore(storageManager.getOfflineODataProvider(), () -> {
runOnUiThread(() -> loadingTextView.setText("Successfully downloaded the latest changes."));
setupPagedList();
addUserToList();
}, (error) -> {
Log.d(TAG, "Failed to download offline store with error: " + error.toString());
android.app.AlertDialog.Builder alert = new android.app.AlertDialog.Builder(MainActivity.this, android.R.style.Theme_DeviceDefault_Dialog_NoActionBar_MinWidth)
.setMessage("Failed to download offline store. Ensure you have Internet connection and try again.")
.setCancelable(false)
.setOnKeyListener(new Dialog.OnKeyListener() {
@Override
public boolean onKey(DialogInterface arg0, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
finish();
}
return true;
}
})
.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
onRegister();
}
});
runOnUiThread(() -> {
alert.show();
});
});
}, (error) -> {
Log.d(TAG, "Failed to open offline store with error: " + error.toString());
checkError(error.toString());
});
}
private void setupPagedList() {
// placeholders are disabled to avoid the need to handle null placeholder values in the adapter
PagedList.Config config = new PagedList.Config.Builder().setPageSize(10).setEnablePlaceholders(false).build();
factory = new CustomerDataSourceFactory();
storageManager.setCustomersListToDisplay(new LivePagedListBuilder<>(factory, config).build());
storageManager.getCustomersListToDisplay().observe(this, new Observer<PagedList<CustomerListItem>>() {
@Override
public void onChanged(@Nullable PagedList<CustomerListItem> customerListItems) {
// called when the paged list is updated due to data being loaded
// this then notifies the adapter to allow the recycler view to updated
adapter.submitList(customerListItems);
}
});
}
/**
* onLogout attempts first to sync the user's changed data with the backend service, and then
* logs the user out.
*/
public void onLogout() {
Log.d(TAG, "In onLogout");
storageManager.getOfflineODataProvider().upload(() -> {
if (checkErrors()) {
runOnUiThread(() -> adapter.notifyDataSetChanged());
return;
}
Log.d(TAG, "Successfully uploaded customer data.");
toastAMessageFromBackground("Successfully synced all changed data.");
unRegisterLogic();
}, error -> {
Log.d(TAG, "Error while uploading personal store: " + error.getMessage());
toastAMessageFromBackground("Sync failed, please check your network connection and the current backend data.");
});
}
public void onRegister() {
Log.d(TAG, "In onRegister");
firstOpen = false;
loginMenuItem.setVisible(false);
loginTextView.setVisibility(View.GONE);
loadingSpinnerParent.setVisibility(View.VISIBLE);
setupOfflineStore();
}
private void addUserToList() {
Log.d(TAG, "In addUserToList");
UserRoles roles = new UserRoles(ClientProvider.get(), settingsParameters);
UserRoles.CallbackListener callbackListener = new UserRoles.CallbackListener() {
@Override
public void onSuccess(@NonNull UserInfo ui) {
Log.d(TAG, "Successfully registered");
Log.d(TAG, "Logged in User Id: " + ui.getId());
createCustomerMenuItem.setVisible(true);
syncMenuItem.setVisible(true);
zeroItemMenuItem.setVisible(true);
currentUser = ui.getId();
getSupportActionBar().setTitle(currentUser);
finishLoading();
}
@Override
public void onError(@NonNull Throwable throwable) {
toastAMessageFromBackground("UserRoles onFailure " + throwable.getMessage());
}
};
roles.load(callbackListener);
}
/**
* unRegisterLogic attempts to sign the user out of the application, and removes all cookies
*/
private void unRegisterLogic() {
CookieManager.getInstance().removeAllCookies(null);
Request request = new Request.Builder()
.post(RequestBody.create(null, ""))
.url(SERVICE_URL + "/mobileservices/sessions/logout")
.build();
Callback updateUICallback = new Callback() {
@Override
public void onFailure(@NonNull Call call, final IOException e) {
Log.d(TAG, "Log out failed: " + e.getLocalizedMessage());
toastAMessageFromBackground("Log out failed, please check your network connection.");
}
@Override
public void onResponse(@NonNull Call call, final Response response) {
if (response.isSuccessful()) {
Log.d(TAG, "Successfully logged out");
runOnUiThread(() -> {
adapter.notifyDataSetChanged();
loginMenuItem.setVisible(true);
createCustomerMenuItem.setVisible(false);
syncMenuItem.setVisible(false);
logoutMenuItem.setVisible(false);
zeroItemMenuItem.setVisible(false);
loginTextView.setVisibility(View.VISIBLE);
currentUser = null;
getSupportActionBar().setTitle("Offline");
});
} else {
Log.d(TAG, "Log out failed " + response.networkResponse());
toastAMessageFromBackground("Log out failed " + response.networkResponse());
}
}
};
ClientProvider.get().newCall(request).enqueue(updateUICallback);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
this.menu = menu;
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_activity_menu, menu);
loginMenuItem = menu.findItem(R.id.action_register);
logoutMenuItem = menu.findItem(R.id.action_unregister);
createCustomerMenuItem = menu.findItem(R.id.action_create_customer);
zeroItemMenuItem = menu.findItem(R.id.action_zero_items);
syncMenuItem = menu.findItem(R.id.action_sync_changes);
logoutMenuItem.setVisible(false);
if (firstOpen) {
onRegister();
} else if (storageManager.getOfflineODataProvider() != null) {
loginMenuItem.setVisible(false);
createCustomerMenuItem.setVisible(true);
syncMenuItem.setVisible(true);
zeroItemMenuItem.setVisible(true);
setupPagedList();
finishLoading();
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
// Determine which option was selected and handle the action accordingly
if (id == R.id.action_register) {
onRegister();
} else if (id == R.id.action_unregister) {
onLogout();
} else if (id == R.id.action_sync_changes) {
item.setVisible(false);
onSync();
} else if (id == R.id.action_create_customer) {
Intent intent = new Intent(this, CreateCustomerActivity.class);
intent.putExtra("parent_activity", "MainActivity");
startActivity(intent);
} else if (id == R.id.action_zero_items) {
zeroSalesOrderItems();
}
return super.onOptionsItemSelected(item);
}
/**
* checkErrors checks the ErrorArchive from the offline odata storage manager to see if the
* previous request returned errors
* @return true if errors were detected and not handled, false otherwise
*/
private boolean checkErrors() {
// These lines access the Error Archive
EntitySet errorArchiveSet = storageManager.getESPMContainer().getEntitySet("ErrorArchive");
EntityType errorArchiveType = errorArchiveSet.getEntityType();
com.sap.cloud.mobile.odata.Property methodProp = errorArchiveType.getProperty("RequestMethod");
com.sap.cloud.mobile.odata.Property messageProp = errorArchiveType.getProperty("Message");
com.sap.cloud.mobile.odata.Property requestBodyProp = errorArchiveType.getProperty("RequestBody");
com.sap.cloud.mobile.odata.Property affectedEntityProp = errorArchiveType.getProperty("AffectedEntity");
com.sap.cloud.mobile.odata.Property httpStatusCodeProp = errorArchiveType.getProperty("HTTPStatusCode");
// We then query the error archive
DataQuery errorArchiveQuery = new DataQuery().from(errorArchiveSet);
// Get the list of errors in the ErrorArchive
EntityValueList errors = storageManager.getESPMContainer().executeQuery(errorArchiveQuery).getEntityList();
// If there is at least one error: We get the first error in list for example, and handle it
if (errors.length() > 0) {
// In this if statement we handle the error
EntityValue error1 = errors.get(0);
String body = requestBodyProp.getNullableString(error1);
String method = methodProp.getNullableString(error1);
String message = messageProp.getNullableString(error1);
int statusCode = httpStatusCodeProp.getNullableInt(error1) != null ? httpStatusCodeProp.getNullableInt(error1) : 0;
// Log the error details to the console for debugging purposes
Log.e(TAG, "Message: " + message);
Log.e(TAG, "Body: " + body);
Log.e(TAG, "HTTP Status Code: " + statusCode);
Log.e(TAG, "Method: " + method);
// Based on the statusCode, we take different actions
if (statusCode == 404) {
// A status code of 404 means we need to remove the customer from the local list
for (CustomerListItem cli : storageManager.getCustomersListToDisplay().getValue()) {
if (cli.customer.equals(customer)) {
factory.postLiveData.getValue().invalidate();
break;
}
}
// getInfo() gives the user the option to create a new customer according to the latest changes,
// since the customer intended to be updated has been deleted in the back-end.
Log.d(TAG, customer.toString());
getInfo(customer.toString());
storageManager.getESPMContainer().deleteEntity(errors.get(0));
return true;
} else if (statusCode == 400) {
if (message.contains(ZERO_QUANTITY_ERROR_MESSAGE)) {
// A status code of 400 is a general error
storageManager.getESPMContainer().loadProperty(affectedEntityProp, error1, null);
SalesOrderItem errorSalesOrderItem = (SalesOrderItem) affectedEntityProp.getEntity(error1);
runOnUiThread(() -> changeQuantity(errorSalesOrderItem));
return false;
}
}
}
// We then check to see if the errors have been resolved
Log.d(TAG, "Number of errors: " + errors.length());
if (errors.length() > 0) {
storageManager.getESPMContainer().deleteEntity(errors.get(0));
}
return false;
}
/**
* changeQuantity allows a user who has entered 0 for a sales order quantity to amend their submission.
* AlertDialog logic sourced from: https://stackoverflow.com/questions/10903754/input-text-dialog-android
* @param salesOrderItem the sales order item that needs to be modified before pushed to the backend
*/
private void changeQuantity(SalesOrderItem salesOrderItem) {
// This dialog could also be provided by the Fiori Onboarding Library
// We create the dialog using an AlertDialog.Builder
AlertDialog.Builder builder = new AlertDialog.Builder(this, android.R.style.Theme_DeviceDefault_Dialog_NoActionBar_MinWidth);
builder.setMessage("The quantity must be greater than 0. Update the quantity below.");
builder.setTitle("Change Quantity");
// Set up the input
View viewInflated = LayoutInflater.from(this).inflate(R.layout.quantity_edit_text_layout, findViewById(android.R.id.content), false);
final EditText input = (EditText) viewInflated.findViewById(R.id.input);
input.setText(String.format("%.0f", salesOrderItem.getQuantity()));
input.setInputType(InputType.TYPE_CLASS_NUMBER);
builder.setView(viewInflated);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String inputQuantity = input.getText().toString();
BigDecimal newQuantity = new BigDecimal(inputQuantity);
salesOrderItem.setQuantity(newQuantity);
Log.d(TAG,"Updated bad request with new quantity: " + newQuantity);
// Attempt to update the entity and possibly call checkErrors()
storageManager.getESPMContainer().updateEntity(salesOrderItem);
onSync();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
storageManager.getESPMContainer().deleteEntity(salesOrderItem);
Log.d(TAG,"Removed bad request.");
}
});
// Finally, show the dialog
builder.show();
}
/**
* getInfo gets the info of a customer who the user is trying to edit, but has been deleted in
* the backend. The method allows the app user to take the customer details they were editing
* and create a new customer without filling in all the form data again.
* @param myMessage the JSON string that will be parsed into a customer
*/
private void getInfo(String myMessage) {
try {
JSONObject customerInfo = new JSONObject(myMessage);
String city = customerInfo.getString("City");
String country = customerInfo.getString("Country");
String email = customerInfo.getString("EmailAddress");
String firstName = customerInfo.getString("FirstName");
String lastName = customerInfo.getString("LastName");
String houseNumber = customerInfo.getString("HouseNumber");
String phoneNumber = customerInfo.getString("PhoneNumber");
String postalNumber = customerInfo.getString("PostalCode");
String street = customerInfo.getString("Street");
String dob = "2000-01-01T00:00:00";
Log.e(TAG, "city: " + city);
Log.e(TAG, "country: " + country);
Log.e(TAG, "email: " + email);
Log.e(TAG, "firstName: " + firstName);
Log.e(TAG, "lastName: " + lastName);
Log.e(TAG, "houseNumber: " + houseNumber);
Log.e(TAG, "phoneNumber: " + phoneNumber);
Log.e(TAG, "postalNumber: " + postalNumber);
Log.e(TAG, "street: " + street);
Log.e(TAG, "dob: " + dob);
Intent i = new Intent(this, ChangeCustomerWarningActivity.class);
i.putExtra("city", city);
i.putExtra("country", country);
i.putExtra("email", email);
i.putExtra("firstName", firstName);
i.putExtra("lastName", lastName);
i.putExtra("phoneNumber", phoneNumber);
i.putExtra("postalNumber", postalNumber);
i.putExtra("street", street);
i.putExtra("dob", dob);
i.putExtra("houseNumber", houseNumber);
// Pass information to customer create activity
this.startActivity(i);
} catch (JSONException e) {
e.printStackTrace();
Log.e(TAG, "JSON error encountered: " + e.getMessage());
}
}
/**
* onSync method performs the logic of syncing the app user's local changes and the backend,
* first performs and upload of the local data, and then a download to make sure both systems
* are in sync.
*/
private void onSync() {
// Going forward we might want to attach a delegate to the OfflineODataForegroundService so we
// can get feedback on our download progress. As of right now the backend OData service doesn't
// send information about % downloads.
// Tells the user the upload has started
toastAMessageFromBackground("Starting upload.");
Log.d(TAG, "Starting upload.");
// Attempts to upload the local offline store
boundService.uploadStore(storageManager.getOfflineODataProvider(), () -> {
Log.d(TAG, "Successfully uploaded local customer data to the backend.");
toastAMessageFromBackground("Upload completed, starting download");
// If the upload succeeds then we attempt to download
// This ensures that we obtain changes made by other users
boundService.downloadStore(storageManager.getOfflineODataProvider(), () -> {
toastAMessageFromBackground("Download completed, refreshing");
Log.d(TAG, "Local customer data has been updated from the backend.");
// We then check errors with the download/upload
checkErrors();
// Refresh the table to show us the newly downloaded data
factory.postLiveData.getValue().invalidate();
runOnUiThread(() -> menu.findItem(R.id.action_sync_changes).setVisible(true));
}, (error) -> {
toastAMessageFromBackground("Download failed, check network connection");
Log.d(TAG, "Error downloading customer data from the backend: " + error.getMessage());
factory.postLiveData.getValue().invalidate();
runOnUiThread(() -> menu.findItem(R.id.action_sync_changes).setVisible(true));
});
}, (error) -> {
toastAMessageFromBackground("Upload failed, check network connection");
Log.d(TAG, "Error uploading the local customer data to the backend: " + error.getMessage());
runOnUiThread(() -> menu.findItem(R.id.action_sync_changes).setVisible(true));
});
}
private void finishLoading() {
logoutMenuItem.setVisible(true);
recyclerView.setVisibility(View.VISIBLE);
loadingSpinnerParent.setVisibility(View.GONE);
loginTextView.setVisibility(View.GONE);
}
/**
* zeroSalesOrderItems is a hack that allows a user to create a sales order item with 0 quantity.
* Used only for showcasing the changeQuantity method's functionality in-app.
*/
private void zeroSalesOrderItems() {
// Setup the data query to get the sales order items
DataQuery productQuery = new DataQuery().from(ESPMContainerMetadata.EntitySets.salesOrderItems).top(1);
SalesOrderItem salesOrderItem = storageManager.getESPMContainer().getSalesOrderItem(productQuery);
// Update the quantity of the sales order to 0 -- this will create a BACKEND DATA VIOLATION
salesOrderItem.setQuantity(new BigDecimal(0));
// Attempts to update the entity
storageManager.getESPMContainer().updateEntity(salesOrderItem);
storageManager.getOfflineODataProvider().upload(() -> checkErrors(), (error) ->
Log.e(TAG, "Error occurred while uploading SalesOrderItem with zero quantity: " + error.getMessage()));
}
@Override
public void onItemClick(View view, int position) {
if (storageManager.getCustomersListToDisplay().getValue().size() >= position) {
customer = storageManager.getCustomersListToDisplay().getValue().get(position).customer;
Intent i = new Intent(this, ChangeCustomerDetailActivity.class);
startActivity(i);
}
}
@Override
protected void onResume() {
super.onResume();
recyclerView.getAdapter().notifyDataSetChanged();
}
}
|
package designpattern.factory.simple_factory;
/**
* 具体产品类BMW523:继承BMW
*/
public class BMW523 extends BMW {
public BMW523() {
System.out.println("制造--BMW523");
}
}
|
package co.edu.meli.domain.usecase;
import co.edu.meli.domain.model.Point;
import co.edu.meli.domain.model.SpaceshipReference;
import co.edu.meli.domain.provider.SatelliteProvider;
import co.edu.meli.domain.utilities.AngleCalculatorUtil;
import co.edu.meli.domain.utilities.CardinalCalculatorUtil;
import lombok.extern.slf4j.Slf4j;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
@Slf4j
@ApplicationScoped
public class CalculatePositionUseCase {
private final SatelliteProvider satellites;
@Inject
public CalculatePositionUseCase(SatelliteProvider satellites) {
this.satellites = satellites;
}
public Point process(final SpaceshipReference spaceship) {
try {
final var positionAlpha = findAlpha(spaceship);
final var positionBravo = findBravo(spaceship);
assertPositions(positionAlpha, positionBravo);
return positionAlpha;
} catch (AssertionError | Exception ex) {
log.error(ex.getLocalizedMessage(), ex);
return null;
}
}
private void assertPositions(Point positionAlpha, Point positionBravo) {
assert positionAlpha.getNorth() == positionBravo.getNorth();
assert positionAlpha.getEast() == positionBravo.getEast();
}
private Point findBravo(SpaceshipReference spaceship) {
final var beta = AngleCalculatorUtil.beta(satellites.getSato().getSkywalker(), spaceship.getToSkywalker(), spaceship.getToSato());
final var azimut = AngleCalculatorUtil.azimuts(satellites.getSato().getCoordinates(), satellites.getSkywalker().getCoordinates()) + beta;
final var north = CardinalCalculatorUtil.north(azimut, spaceship.getToSato(), satellites.getSato().getCoordinates());
final var east = CardinalCalculatorUtil.east(azimut, spaceship.getToSato(), satellites.getSato().getCoordinates());
return new Point(east, north);
}
private Point findAlpha(final SpaceshipReference spaceship) {
final var beta = AngleCalculatorUtil.beta(satellites.getKenobi().getSkywalker(), spaceship.getToSkywalker(), spaceship.getToKenobi());
final var azimut = AngleCalculatorUtil.azimuts(satellites.getKenobi().getCoordinates(), satellites.getSkywalker().getCoordinates()) - beta;
final var north = CardinalCalculatorUtil.north(azimut, spaceship.getToKenobi(), satellites.getKenobi().getCoordinates());
final var east = CardinalCalculatorUtil.east(azimut, spaceship.getToKenobi(), satellites.getKenobi().getCoordinates());
return new Point(east, north);
}
}
|
package sch.frog.calculator.platform;
public class IllegalLanguageRuleError extends Error{
public IllegalLanguageRuleError(String message) {
super(message);
}
}
|
package com.its.xfwdata.servlet;
import java.util.List;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import com.its.xfwdata.dao.CityDaoImpl;
import com.its.xfwdata.model.City;
public class JobRunner implements Job {
public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println("Hello, GetMessageJob is Executing @ "
+ new java.util.Date());
}
}
|
package com.cyou.paycallback.core;
public interface Channel {
PayCallBackHandler getChannel(String version);
void addVersion(String version, PayCallBackHandler handler);
}
|
package com.kevin.cloud.provider.api;
import com.kevin.cloud.provider.domain.Menu;
import java.util.List;
/**
* @program: vue-blog-backend
* @description: 博客管理模块菜单
* @author: kevin
* @create: 2020-01-14 20:47
**/
public interface MenuService {
public List<Menu> finlAllMenuByList();
}
|
package checkPt1.Model;
import java.awt.Graphics;
import javax.swing.JComponent;
public class Coordinate implements Drawable {
private float x;
private float y;
private float cost;
private int width;
private int height;
public Coordinate(float x, float y){
this.x = x;
this.y = y;
cost = -1;
width = 10;
height = 10;
}
public float getX(){
return x;
}
public void setX(float x){
this.x = x;
}
public float getY(){
return y;
}
public void setY(float y){
this.y = y;
}
public float getCost(){
return cost;
}
public void setCost(float cost){
this.cost = cost;
}
public String toString(){
return "("+x+" ,"+y+")";
}
@Override
public void update(JComponent comp){
return;
}
@Override
public void draw(Graphics g) {
g.fillRect((int)x, (int)y, width, height);
}
public static float getCostBetween(Coordinate coord1, Coordinate coord2){
return (float)(Math.sqrt( Math.pow((coord1.getX()-coord2.getX()),2) + Math.pow((coord1.getY()-coord2.getY()),2)));
}
}
|
package duverger.util.factories;
import duverger.util.ObjectUtilities;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.BiPredicate;
import java.util.function.Predicate;
public class ConstructorManager<KEY, T>
{
private int state;
private final BiPredicate<ConstructorManager<KEY, T>, KEY> predicateKeyValid;
private final Predicate<Class<?>[]> predicateArguments;
private final Map<KEY, Constructor<? extends T>> constructors;
public static final int STATE_PRE = 0, STATE_IN = 1, STATE_STOP = 2;
public ConstructorManager(BiPredicate<ConstructorManager<KEY, T>, KEY> parPredKey, Predicate<Class<?>[]> parPredArgs)
{
this.state = STATE_PRE;
this.predicateKeyValid = Objects.requireNonNull(parPredKey);
this.predicateArguments = Objects.requireNonNull(parPredArgs);
this.constructors = new HashMap<>();
}
public boolean stateIs(int i)
{
return this.state == i;
}
public boolean has(KEY key)
{
return this.constructors.containsKey(key);
}
public boolean startRegister()
{
if (this.state == STATE_PRE)
this.state = STATE_IN;
return this.state == STATE_IN;
}
public void stopRegister()
{
this.state = STATE_STOP;
}
public boolean register(KEY key, Class<? extends T> cls, Class<?>... parameterTypes)
{
if (this.state != STATE_IN) return false;
if (!this.predicateKeyValid.test(this, key)) return false;
if (!this.predicateArguments.test(parameterTypes)) return false;
return register(key, ObjectUtilities.getSafeOrNull( ()-> cls.getDeclaredConstructor(parameterTypes) ));
}
private boolean register(KEY key, Constructor<? extends T> constructor)
{
if (constructor == null) return false;
int m = constructor.getModifiers();
if (!Modifier.isPublic(m) || Modifier.isAbstract(m)) return false;
this.constructors.put(key, constructor);
return true;
}
public T get(KEY key, Object... args)
{
return ObjectUtilities.getSafeOrNull( ()-> this.constructors.get(key).newInstance(args) );
}
public static <K, X> boolean cannotOverWrite(ConstructorManager<K, X> manager, K key)
{
return !manager.constructors.containsKey(key);
}
}
|
package com.open.jniframework;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private JNITest mJNITest;
private Button mButton1 = null;
private Button mButton2 = null;
private Button mButton3 = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mJNITest = new JNITest();
}
@Override
public void onResume() {
super.onResume();
Log.i("JNIFramework", "call onResume");
mButton1 = (Button) findViewById(R.id.button1);
mButton1.setClickable(true);
mButton1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.i("JNIFramework", "call native JNITest1");
boolean result = mJNITest.JNITest1("Hello", "World");
Toast.makeText(MainActivity.this, result ? "Success" : "Failed", Toast.LENGTH_LONG).show();
}
});
mButton2 = (Button) findViewById(R.id.button2);
mButton2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.i("JNIFramework", "call native JNITest2");
boolean result = mJNITest.JNITest2();
Toast.makeText(MainActivity.this, result ? "Success" : "Failed", Toast.LENGTH_LONG).show();
}
});
mButton3 = (Button) findViewById(R.id.button3);
mButton3.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.i("JNIFramework", "call native JNITest3");
byte[] result = mJNITest.JNITest3(new String[]{"call", "JNITest3"}, new String("Test3").getBytes());
if (result != null && result.length > 0) {
String reslutValue = new String(result);
Log.i("JNIFramework", "result = " + reslutValue);
}
}
});
}
}
|
package ru.otus.sua.L09.forTest;
import java.util.List;
public class ComplexObjects {
private String name;
private int[] array;
private Long boxedLong;
private long primiLong;
private List<Double> doubleList;
private SimpleObjects simpleObject;
public ComplexObjects() {
}
public SimpleObjects getSimpleObject() {
return simpleObject;
}
public void setSimpleObject(SimpleObjects simpleObject) {
this.simpleObject = simpleObject;
}
public void setPrimiLong(long primiLong) {
this.primiLong = primiLong;
}
public void setDoubleList(List<Double> doubleList) {
this.doubleList = doubleList;
}
public void setBoxedLong(Long boxedLong) {
this.boxedLong = boxedLong;
}
public void setName(String name) {
this.name = name;
}
public void setArray(int[] array) {
this.array = array;
}
}
|
package com.soft1841.book.service;
import static org.junit.Assert.*;
public class ReaderServiceTest {
}
|
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i=0;i<n;i++)
{
String str = sc.next();
int len = str.length();
for(int j=0;j<len;j=j+2)
System.out.print(str.charAt(j));
System.out.print(" ");
for(int k=1;k<len;k=k+2)
System.out.print(str.charAt(k));
System.out.println();
}
}
}
|
package web.viewhelper.impl;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import classes.util.Resultado;
import dominio.endereco.Endereco;
import dominio.evento.IDominio;
import dominio.participantes.Participante;
import web.viewhelper.IViewHelper;
public class ParticipanteVH implements IViewHelper {
@Override
public IDominio getData(HttpServletRequest request) {
String operacao = request.getParameter("operacao");
Participante participante = new Participante();
if(operacao.equals("SALVAR") || operacao.equals("ATUALIZAR")) {
Endereco endereco = new Endereco();
if(operacao.equals("ATUALIZAR")) {
String participanteId = request.getParameter("part-id");
String enderecoId = request.getParameter("end-id");
participante.setId(Integer.parseInt(participanteId));
endereco.setId(Integer.parseInt(enderecoId));
System.out.println("ID do endereço no VH " + endereco.getId());
}
// insere informações sobre o evento
participante.setNome(request.getParameter("nome"));
participante.setEmail(request.getParameter("email"));
participante.setTelefone(request.getParameter("telefone"));
participante.setGenero(Integer.parseInt(request.getParameter("genero")));
participante.setCpf(request.getParameter("cpf"));
// insere informações sobre o endereço
endereco.setLogradouro(request.getParameter("logradouro"));
endereco.setRua(request.getParameter("rua"));
endereco.setNumero(request.getParameter("numero"));
endereco.setCEP(request.getParameter("cep"));
endereco.setBairro(request.getParameter("bairro"));
endereco.setCidade(request.getParameter("cidade"));
endereco.setEstado(request.getParameter("estado"));
// Formata a data
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
try {
participante.setDtNascimento(sd.parse(request.getParameter("data")));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // fim da formatação de datas
// insere o endereço dentro do obj participante
participante.setEndereco(endereco);
} // OPERACAO SALVAR E ALTERAR
else if(operacao.equals("CONSULTAR") || operacao.equals("EXCLUIR")) {
String participanteId = request.getParameter("part-id");
String nomeParticipante = request.getParameter("nome");
if(participanteId != null && participanteId != "") {
participante.setId(Integer.parseInt(participanteId));
} else if(nomeParticipante != null && nomeParticipante != "") {
participante.setNome(nomeParticipante);
}
if(operacao.equals("EXCLUIR")) {
Endereco endereco = new Endereco();
String enderecoId = request.getParameter("end-id");
endereco.setId(Integer.parseInt(enderecoId));
participante.setEndereco(endereco);
System.out.println("ID do participante no VH: " + participante.getId());
}
}
return participante;
}
@Override
public void formataView(Resultado resultado, HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
List<IDominio> recebido = null;
List<Participante> ptcRecebidos = null;
String msgErro = "";
String uri = request.getRequestURI();
if(resultado != null) {
msgErro = resultado.getMensagem();
recebido = resultado.getEntidades();
ptcRecebidos = (List<Participante>) (Object) recebido;
}
if(msgErro != null && msgErro != "") {
request.setAttribute("mensagem", msgErro);
request.getRequestDispatcher("erro.jsp").forward(request, response);
} else {
if(recebido == null || recebido.size() <= 0) {
request.setAttribute("erro", "Não há eventos");
request.getRequestDispatcher("lista-participantes.jsp").forward(request, response);
} else if(recebido.size() > 1) {
request.setAttribute("resultado", ptcRecebidos);
request.getRequestDispatcher("lista-participantes.jsp").forward(request, response);
} else {
String editavel = request.getParameter("editar");
System.out.println("Editável? " + editavel);
Participante participante = (Participante) recebido.get(0);
request.setAttribute("resultado", participante);
if(editavel != "" && editavel != null) {
if(editavel.equals("false"))
request.getRequestDispatcher("consulta-participante.jsp").forward(request, response);
else
request.getRequestDispatcher("atualiza-participante.jsp").forward(request, response);
} else {
request.getRequestDispatcher("sucesso.jsp").forward(request, response);
}
}
} // caso não tenha mensagem de erro
}
}
|
package benchmark.java.metrics.avro;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.avro.file.DataFileStream;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.DatumWriter;
import org.apache.avro.specific.SpecificDatumReader;
import org.apache.avro.specific.SpecificDatumWriter;
import benchmark.java.Config;
import benchmark.java.converters.AvroConverter;
import benchmark.java.converters.IDataConverter;
import benchmark.java.metrics.AMetric;
import benchmark.java.metrics.Info;
public class AvroMetric extends AMetric {
private DataFileWriter<PersonCollection> dataFileWriter;
private DatumReader<PersonCollection> datumReader;
private final Info info = new Info(Config.Format.AVRO, "Avro", "https://avro.apache.org/", "1.8.1");
@Override
public Info getInfo() {
return info;
}
@Override
protected void prepareBenchmark() {
DatumWriter<PersonCollection> userDatumWriter = new SpecificDatumWriter<>(PersonCollection.class);
dataFileWriter = new DataFileWriter<>(userDatumWriter);
datumReader = new SpecificDatumReader<>(PersonCollection.class);
}
@Override
protected Object prepareDataForSerialize() {
IDataConverter convertor = new AvroConverter();
return convertor.convertData(testDataFile);
}
@Override
public boolean serialize(Object data, OutputStream output) throws Exception {
PersonCollection persons = (PersonCollection) data;
dataFileWriter.create(persons.getSchema(), output);
dataFileWriter.append(persons);
dataFileWriter.close();
return true;
}
@Override
public Object deserialize(InputStream input, byte[] bytes) throws Exception {
DataFileStream<PersonCollection> dataReader = new DataFileStream<>(input, datumReader);
PersonCollection personCollection = dataReader.next();
return personCollection;
}
}
|
package com.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.beans.StockService;
import com.entities.Drugstore;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
* Servlet implementation class Drugstore
*/
@WebServlet("/Drugstore")
public class DrugstoreServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@EJB
StockService bean;
/**
* @see HttpServlet#HttpServlet()
*/
public DrugstoreServlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Drugstore> drugstores= bean.getDrugstores();
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String drugstoresJsonString = gson.toJson(drugstores);
PrintWriter out = response.getWriter();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
out.print(drugstoresJsonString);
out.flush();
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String address=request.getParameter("address");
String email=request.getParameter("email");
String name=request.getParameter("name");
String phone =request.getParameter("phone");
String uri=request.getParameter("uri");
if(bean.addDrugstore(address, email, name, phone, uri)) {
response.getWriter().append("success");
}else {
response.getWriter().append("failed");
}
}
protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int id=0;
try {
id=Integer.valueOf(request.getParameter("drugstore_id"));
}catch (Exception ignore) {
response.getWriter().append("no id");
return;
}
String address=request.getParameter("address");
String email=request.getParameter("email");
String name=request.getParameter("name");
String phone =request.getParameter("phone");
String uri=request.getParameter("uri");
if(bean.modifyDrugstore(id,address, email, name, phone, uri)) {
response.getWriter().append("success");
}else {
response.getWriter().append("failed");
}
}
protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int id=0;
try {
id=Integer.valueOf(request.getParameter("drugstore_id"));
}catch (Exception ignore) {
response.getWriter().append("no id");
return;
}
if(bean.deleteDrugstore(id)) {
response.getWriter().append("success");
}else {
response.getWriter().append("failed");
}
}
}
|
package app;
import view.FrmLogin;
public class App {
public static void main(String[] args) {
new FrmLogin().setVisible(true);
}
}
|
package com.hd.stepbar.indicator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Point;
import android.graphics.Rect;
import android.util.AttributeSet;
import com.hd.stepbar.StepBarConfig;
/**
* Created by hd on 2017/12/30 .
* horizontal step bar view indicator
*/
public class HorizontalStepBarViewIndicator extends StepBarViewIndicator {
public HorizontalStepBarViewIndicator(Context context) {
super(context, 0);
}
public HorizontalStepBarViewIndicator(Context context, AttributeSet attrs) {
super(context, attrs, 0);
}
public HorizontalStepBarViewIndicator(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr, 0);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (config != null && config.getIconCircleRadius() > 0 && config.getBeanList() != null) {
int beanSize = config.getBeanList().size();
int Height = MeasureSpec.getSize(heightMeasureSpec);
selectRightRadius(0, Height, beanSize);
int Width = (int) (outsideIconRingRadius * (beanSize * 3 + 1) + getPaddingLeft() + getPaddingRight());
setMeasuredDimension(Width, Height);
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (config != null && config.getBeanList() != null) {
centerPointList.clear();
int beanSize = config.getBeanList().size();
selectRightRadius(w, h, beanSize);
if (config.isAdjustTextSize())
adjustFontSize();
float[] textSizes = measureFontSize();
float textHeight = textSizes[1];
for (int index = 0, count = config.getBeanList().size(); index < count; index++) {
@SuppressLint("DrawAllocation") Point point = new Point();
point.x = (int) (paddingLeft + index * outsideIconRingRadius * 2 + index * connectLineLength + outsideIconRingRadius);
if (config.getTextLocation() == StepBarConfig.StepTextLocation.TOP) {
point.y = (int) (paddingTop + outsideIconRingRadius + textHeight + middleMargin);
} else {
point.y = (int) (paddingTop + outsideIconRingRadius);
}
centerPointList.add(point);
//add icon rect
iconRectArray[index] = new Rect(point.x - (int) iconRadius, point.y - (int) iconRadius, //
point.x + (int) iconRadius, point.y + (int) iconRadius);
}
//connect line
updateCurrentData();
}
}
}
|
package compilerproject;
import com.opencsv.CSVReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
public class Productions {
Prod_Array[] product = new Prod_Array[69];
String[][] table;
String[] terminals ,nonterminals;
// the grammar
public Productions(){
product[ 0 ] = new Prod_Array("error" , "error");
product[ 1 ] = new Prod_Array("prog-decl" , "heading declarations block .");
product[ 2 ] = new Prod_Array("heading" , "program program-name ;");
product[ 3 ] = new Prod_Array("block" , "begin stmt-list end");
product[ 4 ] = new Prod_Array("declarations" , "const-decl var-decl");
product[ 5 ] = new Prod_Array("const-decl" , "const const-list");
product[ 6 ] = new Prod_Array("const-decl" , "lambda");
product[ 7 ] = new Prod_Array("const-list" , "const-name = value ; const-list");
product[ 8 ] = new Prod_Array("const-list" , "lambda");
product[ 9 ] = new Prod_Array("var-decl" , "var var-list");
product[ 10 ] = new Prod_Array("var-decl" , "lambda");
product[ 11 ] = new Prod_Array("var-list" , "var-item ; var-list");
product[ 12 ] = new Prod_Array("var-list" , "lambda");
product[ 13 ] = new Prod_Array("var-item" , "name-list : data-type");
product[ 14 ] = new Prod_Array("name-list" , "var-name more-names");
product[ 15 ] = new Prod_Array("more-names" , ", name-list");
product[ 16 ] = new Prod_Array("more-names" , "lambda");
product[ 17 ] = new Prod_Array("data-type" , "integer");
product[ 18 ] = new Prod_Array("data-type" , "real");
product[ 19 ] = new Prod_Array("data-type" , "char");
product[ 20 ] = new Prod_Array("data-type" , "array [ range ]");
product[ 21 ] = new Prod_Array("range" , "int-value .. int-value");
product[ 22 ] = new Prod_Array("stmt-list" , "statement ; stmt-list");
product[ 23 ] = new Prod_Array("stmt-list" , "lambda");
product[ 24 ] = new Prod_Array("statement" , "ass-stmt");
product[ 25 ] = new Prod_Array("statement" , "read-stmt");
product[ 26 ] = new Prod_Array("statement" , "write-stmt");
product[ 27 ] = new Prod_Array("statement" , "if-stmt");
product[ 28 ] = new Prod_Array("statement" , "while-stmt");
product[ 29 ] = new Prod_Array("statement" , "repeat-stmt");
product[ 30 ] = new Prod_Array("statement" , "block");
product[ 31 ] = new Prod_Array("ass-stmt" , "var-name := exp");
product[ 32 ] = new Prod_Array("exp" , "term exp-prime");
product[ 33 ] = new Prod_Array("exp-prime" , "add-sign term exp-prime");
product[ 34 ] = new Prod_Array("exp-prime" , "lambda");
product[ 35 ] = new Prod_Array("term" , "factor term-prime");
product[ 36 ] = new Prod_Array("term-prime" , "mul-sign factor term-prime");
product[ 37 ] = new Prod_Array("term-prime" , "lambda");
product[ 38 ] = new Prod_Array("factor" , "( exp )");
product[ 39 ] = new Prod_Array("factor" , "var-name");
product[ 40 ] = new Prod_Array("factor" , "const-name");
product[ 41 ] = new Prod_Array("factor" , "value");
product[ 42 ] = new Prod_Array("add-sign" , "+");
product[ 43 ] = new Prod_Array("add-sign" , "-");
product[ 44 ] = new Prod_Array("mul-sign" , "*");
product[ 45 ] = new Prod_Array("mul-sign" , "/");
product[ 46 ] = new Prod_Array("mul-sign" , "mod");
product[ 47 ] = new Prod_Array("mul-sign" , "div");
product[ 48 ] = new Prod_Array("value" , "float-value");
product[ 49 ] = new Prod_Array("value" , "int-value");
product[ 50 ] = new Prod_Array("read-stmt" , "read ( name-list )");
product[ 51 ] = new Prod_Array("read-stmt" , "readln ( name-list )");
product[ 52 ] = new Prod_Array("write-stmt" , "write ( name-list )");
product[ 53 ] = new Prod_Array("write-stmt" , "writeln ( name-list )");
product[ 54 ] = new Prod_Array("if-stmt" , "if condition then statement else-part");
product[ 55 ] = new Prod_Array("else-part" , "else statement");
product[ 56 ] = new Prod_Array("else-part" , "lambda");
product[ 57 ] = new Prod_Array("while-stmt" , "while condition do statement");
product[ 58 ] = new Prod_Array("repeat-stmt" , "repeat stmt-list until condition");
product[ 59 ] = new Prod_Array("condition" , "name-value relational-oper name-value");
product[ 60 ] = new Prod_Array("name-value" , "var-name");
product[ 61 ] = new Prod_Array("name-value" , "const-name");
product[ 62 ] = new Prod_Array("name-value" , "value");
product[ 63 ] = new Prod_Array("relational-oper" , "=");
product[ 64 ] = new Prod_Array("relational-oper" , "<>");
product[ 65 ] = new Prod_Array("relational-oper" , "<");
product[ 66 ] = new Prod_Array("relational-oper" , "<=");
product[ 67 ] = new Prod_Array("relational-oper" , ">");
product[ 68 ] = new Prod_Array("relational-oper" , ">=");
// reads the table from scv.
try {
table = read_table();
} catch (IOException e) {
e.printStackTrace();
}
// due to problem in CSV reader.
table[0][8] = ",";
terminals = table[0];
nonterminals = new String[table.length];
for (int i = 0; i < nonterminals.length ; i++) {
nonterminals[i] = table[i][0];
}
}
public String getProductionValue(int nonTermeinal,int Termeinal){
String prod = table[nonTermeinal][Termeinal];
if (prod.equals("error"))
return "error";
return product[Integer.parseInt(prod)].getDest();
}
public int getIndexOfNonterminal(String non){
for (int i = 0; i <nonterminals.length ; i++) {
if (nonterminals[i].equalsIgnoreCase(non))
return i;
}
return -1;
}
public int getIndexOfTerminal(String non){
for (int i = 0; i < terminals.length; i++) {
if (terminals[i].equalsIgnoreCase(non))
return i;
}
return -1;
}
public String[][] read_table() throws IOException {
CSVReader csvReader = new CSVReader(new FileReader(new File("CompilerProject/table.csv")));
List<String[]> list = csvReader.readAll();
// Convert to 2D array
String[][] dataArr = new String[list.size()][];
dataArr = list.toArray(dataArr);
return dataArr;
}
}
|
package com.httpclient.controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
/**
* 资源Controller类,用于为IndexController提供资源
*/
@RequestMapping("/DateController")
@RestController
public class DateController {
@RequestMapping("/index")
public String index(){
return "success";
}
@ResponseBody
@RequestMapping("/datejosn")
public List<String> datejosn(@RequestBody String date){
System.out.println("传过来的Json为:"+date);
List<String> list = new ArrayList<String>();
list.add("datejosn1");
list.add("datejosn2");
list.add("datejosn3");
return list;
}
}
|
import java.awt.*;
public class Awt6 extends Frame{
{
setSize (400,150);
setVisible(true);
setTitle("List Test");
Panel P1=new Panel();
List ls= new List(3,false);
ls.add("Black");
ls.add("Blue");
ls.add("Cyan");
ls.add("Green");
ls.add("Pink");
P1.add(ls);
add(P1);
}
public static void main (String args[])
{
new Awt6();
}
}
|
package ohtu;
import javax.swing.JTextField;
import javax.swing.JButton;
public class Summa extends Laskuoperaatio {
public Summa(JTextField tuloskentta, JTextField syotekentta, JButton nollaa, JButton undo, Sovelluslogiikka sovellus) {
super(tuloskentta, syotekentta, nollaa, undo, sovellus);
}
@Override
protected void laske(int arvo) {
sovellus.plus(arvo);
}
}
|
/**
* JSON类型的模板加载实现.
*/
package xyz.noark.game.template.json;
|
package com.epita.socra.app.tools;
public class ToInt {
public int toint(String roman)
{
int res = OneRomanToInt(roman.charAt(0));
int len = roman.length();
if (len == 2)
{
if (OneRomanToInt(roman.charAt(1)) > res)
{
res = OneRomanToInt(roman.charAt(1)) - res;
}
else
{
res += OneRomanToInt(roman.charAt(1));
}
}
else
{
int i = 0;
res = 0;
while (i < len - 1)
{
if (OneRomanToInt(roman.charAt(i)) >= OneRomanToInt(roman.charAt(i + 1)))
{
res += OneRomanToInt(roman.charAt(i));
i++;
}
else
{
res += OneRomanToInt(roman.charAt(i + 1)) - OneRomanToInt(roman.charAt(i));
i+=2;
}
}
if (i == len - 1)
{
res += OneRomanToInt(roman.charAt(i));
}
}
return res;
}
String tostring(int a)
{
return Integer.toString(a);
}
int OneRomanToInt(char c)
{
int res = 0;
switch (c)
{
case 'I':
res = 1;
break;
case 'V':
res = 5;
break;
case 'X':
res = 10;
break;
case 'L':
res = 50;
break;
case 'C':
res = 100;
break;
case 'D':
res = 500;
break;
case 'M':
res = 1000;
break;
default:
System.exit(1);
}
return res;
}
}
|
class RaizQuadrada implements Expressao{
Expressao exp;
public RaizQuadrada(Expressao exp){
this.exp = exp;
}
public double avaliar(){
return Math.sqrt(exp.avaliar());
}
}
|
package com.app.AdminUI.ControlsUI;
import com.app.DBConnection;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class AddScreen extends JFrame {
private JPanel addPanel;
private JTextField textField1;
private JTextField textField2;
private JTextField textField3;
private JTextField textField4;
private JTextField textField5;
private JTextField textField6;
private JTextField textField7;
private JLabel label1;
private JLabel label2;
private JLabel label3;
private JLabel label4;
private JLabel label5;
private JLabel label6;
private JLabel label7;
private JButton addButton;
public AddScreen(int choice) {
add(addPanel);
setSize(400, 600);
setTitle("Music App / Admin ADD Data");
setScreen(choice);
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addRecords(choice);
}
});
}
public void setScreen(int choice) {
if (choice == 1) {
label1.setText("Album ID: ");
label2.setText("Genre ID: ");
label3.setText("Artist ID: ");
label4.setText("Name: ");
label5.setText("Release Date: ");
label6.setText("Length: ");
label7.setText("Play Count: ");
textField3.setEnabled(true);
textField4.setEnabled(true);
textField5.setEnabled(true);
textField6.setEnabled(true);
textField7.setEnabled(true);
} else if (choice == 2) {
label1.setText("Name: ");
label2.setText("Country: ");
} else if (choice == 3) {
label1.setText("Genre ID: ");
label2.setText("Artist ID: ");
label3.setText("Name: ");
label4.setText("Release Date: ");
textField3.setEnabled(true);
textField4.setEnabled(true);
}
}
public void addRecords(int choice) {
try {
Connection connection = DBConnection.getConnection();
String sqlQuery = null;
if (choice == 1) {
String album = textField1.getText();
String genre = textField2.getText();
String artist = textField3.getText();
String name = textField4.getText();
String releaseDate = textField5.getText();
String length = textField6.getText();
String plays = textField7.getText();
sqlQuery = "INSERT INTO songs(album_id, genre_id, artist_song_id, name, release_date, lenght, plays)"
+ "VALUES(?, ?, ?, ?, ?,?, ?)";
PreparedStatement songStatement = connection.prepareStatement(sqlQuery);
songStatement.setString(1, album);
songStatement.setString(2, genre);
songStatement.setString(3, artist);
songStatement.setString(4, name);
songStatement.setString(5, releaseDate);
songStatement.setString(6, length);
songStatement.setString(7, plays);
int resultSet = songStatement.executeUpdate();
} else if (choice == 2) {
String name = textField1.getText();
String country = textField2.getText();
sqlQuery = "INSERT INTO artists(name, country)"
+ "VALUES(?, ?)";
PreparedStatement artistStatement = connection.prepareStatement(sqlQuery);
artistStatement.setString(1, name);
artistStatement.setString(2, country);
int resultSet = artistStatement.executeUpdate();
} else if (choice == 3) {
String genre = textField1.getText();
String artist = textField2.getText();
String name = textField3.getText();
String releaseDate = textField4.getText();
sqlQuery = "INSERT INTO albums(genre_id, artist_song_id, name, release_date)"
+ "VALUES(?, ?, ?, ?)";
PreparedStatement albumStatement = connection.prepareStatement(sqlQuery);
albumStatement.setString(1, genre);
albumStatement.setString(2, artist);
albumStatement.setString(3, name);
albumStatement.setString(4, releaseDate);
int resultSet = albumStatement.executeUpdate();
}
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
|
package mainController;
import java.io.IOException;
import Classifier.dataClassifier;
public class controller {
public static void main(String args[]) throws IOException, ClassNotFoundException
{
new dataClassifier();
}
}
|
package encapsule;
/**
* @file_name : Casino.java
* @author : dingo44kr@gmail.com
* @date : 2015. 9. 23.
* @story : 도박장
*/
public class Casino {
public Casino(Card p1, Card p2) {
// TODO Auto-generated constructor stub
}
}
|
/**
*
*/
package com.beike.service;
import java.io.Serializable;
public interface GenericService<T, ID extends Serializable> {
T findById(ID id);
}
|
/*
* 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 jc.fog.logic.calculators;
import jc.fog.logic.RulesCalculator;
import java.sql.Connection;
import java.util.List;
import jc.fog.data.DbConnector;
import jc.fog.data.dao.MaterialDAO;
import jc.fog.exceptions.FogException;
import jc.fog.logic.BillItem;
import jc.fog.logic.dto.CarportRequestDTO;
import jc.fog.logic.dto.MaterialDTO;
import junit.framework.Assert;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Claus
*/
public class RulesCalculatorITest
{
static Connection connection;
public RulesCalculatorITest()
{
}
@BeforeClass
public static void setUpClass()
{
try
{
connection = DbConnector.getConnection();
System.out.println("Db forbindelse åbnet");
}
catch(Exception e)
{
System.out.println("No database connection established: " + e.getMessage());
}
}
@AfterClass
public static void tearDownClass()
{
try
{
DbConnector.closeConnection();
System.out.println("Db forbindelse lukket.");
}
catch(Exception e)
{
System.out.println("Database connection was not closed: " + e.getMessage());
}
}
@Before
public void setUp()
{
}
@After
public void tearDown()
{
}
/**
* Tester RulesCalculatorRoof med tagtype 3 (fladt plastic tag).
* @throws FogException
*/
@Test
public void testRoofCalculatorNoSlope() throws FogException
{
// Arrange
MaterialDAO dao = new MaterialDAO(connection); // forbindelse
List<MaterialDTO> materials = dao.getMaterials(); // materialer
List<BillItem> stykliste; // tom stykliste
CarportRequestDTO forespoergsel = new CarportRequestDTO(3, 0, 600, 210, 800, "carport 600 x 800 cm, intet skur, fladt plast tag", 0,0);
RulesCalculator.initializeMaterials(materials); // Initialiser RulesCalculator.
RulesCalculatorRoof roofCalculator = new RulesCalculatorRoof(); // Opret tag udregner.
// Act
stykliste = roofCalculator.calculate(forespoergsel);
BillItem billItem = stykliste.get(0);
// Assert
int expected = 6; // Vi forventer 6 tagplader, idet deres bredde er 109 cm.
Assert.assertEquals(expected, billItem.getCount());
}
@Test
public void testRoofCalculatorSloped() throws FogException
{
// Arrange
MaterialDAO dao = new MaterialDAO(connection); // forbindelse
List<MaterialDTO> materials = dao.getMaterials(); // materialer
List<BillItem> stykliste; // tom stykliste
CarportRequestDTO forespoergsel = new CarportRequestDTO(2, 45, 600, 210, 800, "carport 600 x 800 cm, skur 210 x 600 cm, 45 graders hældning på tag.", 210, 600);
RulesCalculator.initializeMaterials(materials);
RulesCalculatorRoof roofCalculator = new RulesCalculatorRoof();
// Act
stykliste = roofCalculator.calculate(forespoergsel);
BillItem billItem = null;
for(BillItem b : stykliste)
if (b.getMaterialDTO().getMaterialtypeDTO().getId() == 7) // tagfladebelægning
billItem = b;
// Assert
// Tagsten er 25 x 50 cm
// Taghældningens bredde er 300 / cos(45) ~ 424,264 cm => 424,264 / 50 = 9 hele rækker.
// Taglængden er 800 => 800 / 25 = 32 kolonner
// 9 rk a 32 kolonner = 288 teglsten.
int expectedTiles = 288;
Assert.assertEquals(expectedTiles, billItem.getCount() );
}
/**
* Tester stolpe udregning hvor skuret er i samme bredde som carporten.
*/
@Test
public void testPostCalculator() throws FogException
{
// Arrange
MaterialDAO dao = new MaterialDAO(connection); // forbindelse.
List<MaterialDTO> materials = dao.getMaterials(); // materialer.
List<BillItem> stykliste; // tom stykliste.
int shedWidth = 500; // skur vidde.
CarportRequestDTO forespoergsel = new CarportRequestDTO(2, 0, shedWidth, 210, 800, "Skur og carport i samme bredde.", 120, shedWidth); // carport, 500 x 800 cm., med plastic tag, med skur i fuld bredde.
//Initialiser materialer i rule calculator.
RulesCalculator.initializeMaterials(materials);
// Opret stolpeudregner.
RulesCalculatorPost postCalculator = new RulesCalculatorPost();
// Act
stykliste = postCalculator.calculate(forespoergsel);
BillItem billItem = stykliste.get(0);
// Assert
int expected = 9; // 3 på hver rem, 3 til skur.
assertEquals(expected, billItem.getCount());
}
/**
* Tester RulesCalculatorRoof med tagtype 3 (fladt plastic tag).
* @throws FogException
*/
@Test
public void testHeadCalculatorNoSlope() throws FogException
{
// Arrange
MaterialDAO dao = new MaterialDAO(connection); // forbindelse
List<MaterialDTO> materials = dao.getMaterials(); // materialer
List<BillItem> stykliste; // tom stykliste
// carport, 610 x 800 cm., med plastic tag, uden skur.
CarportRequestDTO forespoergsel = new CarportRequestDTO(3, 0, 610, 210, 800, "blabla", 0,0); // bredde 610 giver 1 brud på spær, dvs. 3 remme med 2 stk. træ i hver = 6.
RulesCalculator.initializeMaterials(materials); // Initialiser RulesCalculator.
RulesCalculatorHead headCalculator = new RulesCalculatorHead(); // Opret rem udregner.
// Act
stykliste = headCalculator.calculate(forespoergsel);
BillItem billItem = stykliste.get(0);
// Assert
int expected = 6; // Vi forventer 6 stk. træ, idet 2 remme i hver side + 1 hvor spær brydes = 3, og hver rem skal bruge 2 stk. træ.
Assert.assertEquals(expected, billItem.getCount());
}
}
|
package com.scatterlogical.AgentGo;
import java.util.*;
public class Milestone
{
String title;
String briefingWords;
String monitorBitToCheck; //this will tell us which monitor to, er... monitor
//Strings for success and failure
String failUp;
String inZoneFromUp;
String inZoneFromDown;
String failDown;
//Strings for target zone
String finishMilestoneWhen; //Check a monitor for this value
String alertLowWhen;
String AlertHighWhen;
//TODO: Some sort of array of SOUNDS, taken from the MileStoneToLoad
private boolean isFinished;
public Milestone(String MilestoneToLoad, Monitors reference){
//TODO: load all the blobs, set a thread to monitor the monitors
}
public Boolean IsFinished(){return isFinished;}
}
|
package com.example.lesson_6_fedin;
import android.os.Parcel;
import android.os.Parcelable;
public class DataDrawable implements Parcelable {
private String drawable;
private String text;
public DataDrawable(String drawable, String text){
this.drawable = drawable;
this.text = text;
}
public String getDrawable() {
return drawable;
}
public void setDrawable(String drawable) {
this.drawable = drawable;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.drawable);
dest.writeString(this.text);
}
public DataDrawable() {
}
protected DataDrawable(Parcel in) {
this.drawable = in.readString();
this.text = in.readString();
}
public static final Creator<DataDrawable> CREATOR = new Creator<DataDrawable>() {
@Override
public DataDrawable createFromParcel(Parcel source) {
return new DataDrawable(source);
}
@Override
public DataDrawable[] newArray(int size) {
return new DataDrawable[size];
}
};
}
|
/*
* #%L
* Diana UI Core
* %%
* Copyright (C) 2014 Diana UI
* %%
* 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.
* #L%
*/
package com.dianaui.universal.core.client.ui.gwt;
import com.dianaui.universal.core.client.ui.base.HasContextualBackground;
import com.dianaui.universal.core.client.ui.base.HasId;
import com.dianaui.universal.core.client.ui.base.HasInlineStyle;
import com.dianaui.universal.core.client.ui.base.HasResponsiveness;
import com.dianaui.universal.core.client.ui.base.helper.StyleHelper;
import com.dianaui.universal.core.client.ui.base.mixin.IdMixin;
import com.dianaui.universal.core.client.ui.constants.ContextualBackground;
import com.dianaui.universal.core.client.ui.constants.DeviceSize;
import com.google.gwt.dom.client.Style;
import com.google.gwt.safehtml.shared.SafeHtml;
/**
* @author Sven Jacobs
* @author Grant Slender
* @author <a href='mailto:donbeave@gmail.com'>Alexey Zhokhov</a>
*/
public class HTMLPanel extends com.google.gwt.user.client.ui.HTMLPanel implements HasId, HasResponsiveness,
HasInlineStyle, HasContextualBackground {
public HTMLPanel(final String html) {
super(html);
}
public HTMLPanel(final SafeHtml safeHtml) {
super(safeHtml);
}
public HTMLPanel(final String tag, final String html) {
super(tag, html);
}
@Override
public String getId() {
return IdMixin.getId(this);
}
@Override
public void setId(final String id) {
IdMixin.setId(this, id);
}
@Override
public void setVisibleOn(final DeviceSize deviceSize) {
StyleHelper.setVisibleOn(this, deviceSize);
}
@Override
public void setHiddenOn(final DeviceSize deviceSize) {
StyleHelper.setHiddenOn(this, deviceSize);
}
@Override
public void setMarginTop(final double margin) {
getElement().getStyle().setMarginTop(margin, Style.Unit.PX);
}
@Override
public void setMarginLeft(final double margin) {
getElement().getStyle().setMarginLeft(margin, Style.Unit.PX);
}
@Override
public void setMarginRight(final double margin) {
getElement().getStyle().setMarginRight(margin, Style.Unit.PX);
}
@Override
public void setMarginBottom(final double margin) {
getElement().getStyle().setMarginBottom(margin, Style.Unit.PX);
}
@Override
public void setPaddingTop(final double padding) {
getElement().getStyle().setPaddingTop(padding, Style.Unit.PX);
}
@Override
public void setPaddingLeft(final double padding) {
getElement().getStyle().setPaddingLeft(padding, Style.Unit.PX);
}
@Override
public void setPaddingRight(final double padding) {
getElement().getStyle().setPaddingRight(padding, Style.Unit.PX);
}
@Override
public void setPaddingBottom(final double padding) {
getElement().getStyle().setPaddingBottom(padding, Style.Unit.PX);
}
/**
* {@inheritDoc}
*/
@Override
public void setColor(String color) {
getElement().getStyle().setColor(color);
}
/**
* {@inheritDoc}
*/
@Override
public void setContextualBackground(ContextualBackground contextualBackground) {
StyleHelper.addUniqueEnumStyleName(this, ContextualBackground.class, contextualBackground);
}
/**
* {@inheritDoc}
*/
@Override
public ContextualBackground getContextualBackground() {
return ContextualBackground.fromStyleName(getStyleName());
}
}
|
package com.taim.content.mapper;
import com.taim.backendservice.model.Product;
import com.taim.content.model.ProductCreateInput;
public interface ProductCreateInputMapper {
Product doBackward(ProductCreateInput productCreateInput);
}
|
package com.cmi.bache24.util;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.cmi.bache24.data.model.Report;
import com.cmi.bache24.data.model.User;
import com.cmi.bache24.security.Security;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by omar on 12/2/15.
*/
public class PreferencesManager {
private SharedPreferences preferences;
private static PreferencesManager instance;
private String _TAG_PREFERENCES = "_DEFAULT_VALUES";
private String _TAG_USER_INFO = "_UI";
private String _TAG_USER_REGISTERED_WITH_EMAIL = "_TAG_USER_REGISTERED_WITH_EMAIL";
private String _TAG_GET_REPORTS = "_TAG_GET_REPORTS";
private String _TAG_TUTORIAL_FINISHED = "_TAG_TUTORIAL_FINISHED";
public static final String _TAG_PICTURE_TO_SHOW = "_TAG_PICTURE_TO_SHOW";
public static final String _TAG_REPORT_TUTORIAL_FINISHED = "_TAG_REPORT_TUTORIAL_FINISHED";
private static final String _DATABASE_IMPORTED = "_DATABASE_IMPORTED";
public static final String _ENABLE_NOTIFICATIONS = "_ENABLE_NOTIFICATIONS";
public static synchronized PreferencesManager getInstance() {
if (instance == null)
instance = new PreferencesManager();
return instance;
}
public void setUserInfo(Context context, User userInfo) {
if (context == null)
return;
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
Gson gson = new Gson();
String jsonProgram = gson.toJson(userInfo);
String encryptedUser = Security.encrypt(jsonProgram);
SharedPreferences.Editor e = preferences.edit();
e.putString(_TAG_USER_INFO, encryptedUser);
e.commit();
}
public User getUserInfo (Context context) {
User user = null;
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
String userString = preferences.getString(_TAG_USER_INFO, "");
if (userString != "") {
String decryptedUserString = Security.decrypt(userString);
Gson gson = new Gson();
user = gson.fromJson(decryptedUserString, User.class);
}
return user;
}
public void logoutSession(Context context) {
if (context == null) {
return;
}
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
SharedPreferences.Editor e = preferences.edit();
e.remove(_TAG_USER_INFO);
e.commit();
}
public void removeReports(Context context) {
// preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
//
// SharedPreferences.Editor e = preferences.edit();
// e.remove(_TAG_GET_REPORTS);
//
// e.commit();
}
public void setUserRegisteredWithEmail(Context context, boolean registerd) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
SharedPreferences.Editor e = preferences.edit();
e.putBoolean(_TAG_USER_REGISTERED_WITH_EMAIL, registerd);
e.commit();
}
public void addReports(Context context, List<Report> reports) {
// if (context == null)
// return;
//
// String jsonString = new Gson().toJson(reports);
//
// String reportsStringEncrypted = Security.encrypt(jsonString);
//
// preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
//
// SharedPreferences.Editor editor = preferences.edit();
// editor.putString(_TAG_GET_REPORTS, reportsStringEncrypted);
//
// editor.commit();
}
public void setTutorialFinished(Context context, boolean finished) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
SharedPreferences.Editor e = preferences.edit();
e.putBoolean(_TAG_TUTORIAL_FINISHED, finished);
e.commit();
}
public boolean isTutorialFinished (Context context) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
return preferences.getBoolean(_TAG_TUTORIAL_FINISHED, false);
}
public void setReportTutorialFinished(Context context, boolean finished) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
SharedPreferences.Editor e = preferences.edit();
e.putBoolean(_TAG_REPORT_TUTORIAL_FINISHED, finished);
e.commit();
}
public boolean isReportTutorialFinished(Context context) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
return preferences.getBoolean(_TAG_REPORT_TUTORIAL_FINISHED, false);
}
//Para saber cual es la ultima imagen a mostrar
public void setPictureToShow(Context context, int currentPictureToShow) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
SharedPreferences.Editor e = preferences.edit();
e.putInt(_TAG_PICTURE_TO_SHOW, currentPictureToShow);
e.commit();
}
public int getPictureToShow(Context context) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
return preferences.getInt(_TAG_PICTURE_TO_SHOW, Constants.NO_PICTURE_TO_SHOW);
}
public void setNewReportPicture(Context context, String tag, String value) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
SharedPreferences.Editor e = preferences.edit();
e.putString(tag, value);
e.commit();
}
public String getNewReportPicture(Context context, String tag) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
return preferences.getString(tag, "");
}
public void setDatabaseImported(Context context, boolean imported) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
SharedPreferences.Editor e = preferences.edit();
e.putBoolean(_DATABASE_IMPORTED, imported);
e.commit();
}
public boolean isDatabaseImported (Context context) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
boolean imported = preferences.getBoolean(_DATABASE_IMPORTED, false);
return imported;
}
/// CUADRILLA
/*private static final String _REPORT_ATTENTION_IN_PROGRESS = "_REPORT_ATTENTION_IN_PROGRESS";
public void setReportAttentionInProgress(Context context, boolean inProgress) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
SharedPreferences.Editor e = preferences.edit();
e.putBoolean(_REPORT_ATTENTION_IN_PROGRESS, inProgress);
e.commit();
}
public boolean isReportAttentionInProgress(Context context) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
boolean inProgress = preferences.getBoolean(_REPORT_ATTENTION_IN_PROGRESS, false);
return inProgress;
}
public void clearReportAttentionData(Context context) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
SharedPreferences.Editor e = preferences.edit();
e.remove(_REPORT_ATTENTION_IN_PROGRESS);
e.remove(_REPORT_OPTION_CLICKED);
e.remove(_REPORT_ATTENTION_FIRST_RESUME);
e.commit();
}
*/
public static final String _REPORT_ATTENTION_IN_PROGRESS = "_REPORT_ATTENTION_IN_PROGRESS";
public static final String _REPORT_ATTENTION_TICKET_VALUE = "_REPORT_ATTENTION_TICKET_VALUE";
private static final String _REPORT_ATTENTION_FIRST_RESUME = "_REPORT_ATTENTION_FIRST_RESUME";
private static final String _REPORT_OPTION_CLICKED = "_REPORT_OPTION_CLICKED";
private static final String _SELECTED_REPORT_FIRST_RESUME = "_SELECTED_REPORT_FIRST_RESUME";
private static final String _SELECTED_REPORT_COMPLETE_CLICKED = "_SELECTED_REPORT_COMPLETE_CLICKED";
public static final String _REPORT_CANCELED = "_REPORT_CANCELED";
// private static final String _SHOULD_SEND_REPORT_TO_STATUS_2 = "_SHOULD_SEND_REPORT_TO_STATUS_2";
public void setReportAttentionInProgress(Context context, boolean isInProcess) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
SharedPreferences.Editor e = preferences.edit();
e.putBoolean(_REPORT_ATTENTION_IN_PROGRESS, isInProcess);
e.commit();
}
public boolean isReportAttentionInProgress(Context context) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
boolean firstResume = preferences.getBoolean(_REPORT_ATTENTION_IN_PROGRESS, false);
return firstResume;
}
public void setReportAttentionTicketValue(Context context, String reportTicket) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
SharedPreferences.Editor e = preferences.edit();
e.putString(_REPORT_ATTENTION_TICKET_VALUE, reportTicket);
e.commit();
}
public String getReportAttentionTicketValue(Context context) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
String reportTicket = preferences.getString(_REPORT_ATTENTION_TICKET_VALUE, "");
return reportTicket;
}
public void clearReportAttentionData(Context context) {
if (context == null)
return;
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
SharedPreferences.Editor e = preferences.edit();
e.remove(_REPORT_ATTENTION_IN_PROGRESS);
e.remove(_REPORT_ATTENTION_TICKET_VALUE);
e.commit();
}
public boolean isReportOptionClicked(Context context) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
boolean reportOptionClicked = preferences.getBoolean(_REPORT_OPTION_CLICKED, false);
return reportOptionClicked;
}
/// CUADRILLA
public void setSelectedReportFirstResume(Context context, boolean firstResume) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
SharedPreferences.Editor e = preferences.edit();
e.putBoolean(_SELECTED_REPORT_FIRST_RESUME, firstResume);
e.commit();
}
public boolean isSelectedReportFirstResume(Context context) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
boolean firstResume = preferences.getBoolean(_SELECTED_REPORT_FIRST_RESUME, false);
return firstResume;
}
public void setSelectedReportCompleteClicked(Context context, boolean complete) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
SharedPreferences.Editor e = preferences.edit();
e.putBoolean(_SELECTED_REPORT_COMPLETE_CLICKED, complete);
e.commit();
}
public boolean isSelectedReportCompleteClicked(Context context) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
boolean reportOptionClicked = preferences.getBoolean(_SELECTED_REPORT_COMPLETE_CLICKED, false);
return reportOptionClicked;
}
public void clearSelectedReportAttentionData(Context context) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
SharedPreferences.Editor e = preferences.edit();
e.remove(_SELECTED_REPORT_FIRST_RESUME);
e.remove(_SELECTED_REPORT_COMPLETE_CLICKED);
e.commit();
}
public void setReportCanceled(String activity, Context context, boolean canceled) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
Log.i("VALID_REPORT_ACT_LOG", "FROM = " + activity + ", setReportCanceled = " + canceled);
SharedPreferences.Editor e = preferences.edit();
e.putBoolean(_REPORT_CANCELED, canceled);
e.commit();
}
public boolean isReportCanceled(Context context) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
boolean reportCanceled = preferences.getBoolean(_REPORT_CANCELED, false);
return reportCanceled;
}
/// STATUS LIST
private String _TAG_STATUS_MAP_PREFERENCES = "_TAG_STATUS_MAP_PREFERENCES";
public void setStatusMap(Context context, HashMap<Integer, String> statusMap) {
preferences = context.getSharedPreferences(_TAG_STATUS_MAP_PREFERENCES, context.MODE_PRIVATE);
SharedPreferences.Editor e = preferences.edit();
e.clear();
e.commit();
for (Map.Entry entry : statusMap.entrySet()) {
e.putString(entry.getKey().toString(), entry.getValue().toString());
}
e.commit();
}
public HashMap<Integer, String> getStatusMap(Context context) {
preferences = context.getSharedPreferences(_TAG_STATUS_MAP_PREFERENCES, context.MODE_PRIVATE);
HashMap<Integer, String> statusMap = new HashMap<>();
for (Map.Entry entry : preferences.getAll().entrySet()) {
statusMap.put(Integer.parseInt(entry.getKey().toString()), entry.getValue().toString());
}
return statusMap;
}
private HashMap<Integer, String> mStatusHashMap;
public String getStatusNameForId(Context context, int id) {
if (mStatusHashMap == null) {
mStatusHashMap = getStatusMap(context);
}
String statusName = mStatusHashMap.get(id);
if (statusName == null || statusName == "") {
statusName = Constants.REPORT_STATUS_MAP.get(id);
}
if (statusName == null || statusName == "") {
return "";
}
return statusName;
}
private static final String _SHOW_APPTENTIVE_MESSAGE_CENTER = "_SHOW_APPTENTIVE_MESSAGE_CENTER";
public void setShowApptentiveMessageCenter(Context context, boolean showApptentiveMessageCenter) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
SharedPreferences.Editor e = preferences.edit();
e.putBoolean(_SHOW_APPTENTIVE_MESSAGE_CENTER, showApptentiveMessageCenter);
e.commit();
}
public boolean showAppTentiveMessageCenter(Context context) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
boolean reportCanceled = preferences.getBoolean(_SHOW_APPTENTIVE_MESSAGE_CENTER, false);
return reportCanceled;
}
public void clearAppTentiveMessageCenterValues(Context context) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
SharedPreferences.Editor e = preferences.edit();
e.remove(_SHOW_APPTENTIVE_MESSAGE_CENTER);
e.commit();
}
/*public void setShouldSendReportToStatus2(Context context, boolean shouldSendReport) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
SharedPreferences.Editor e = preferences.edit();
e.putBoolean(_SHOULD_SEND_REPORT_TO_STATUS_2, shouldSendReport);
e.commit();
}
public boolean shouldSendReportToStatus2(Context context) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
return preferences.getBoolean(_SHOULD_SEND_REPORT_TO_STATUS_2, false);
}*/
private static final String _SEND_REPORT_TO_STATUS_2_NUMBER_OF_RETRIES = "_SEND_REPORT_TO_STATUS_2_NUMBER_OF_RETRIES";
public void setSendReportToStatusRetry(Context context, int currentNumber) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
SharedPreferences.Editor e = preferences.edit();
e.putInt(_SEND_REPORT_TO_STATUS_2_NUMBER_OF_RETRIES, currentNumber);
e.commit();
}
public int getCurrentNumberOfRetries(Context context) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
return preferences.getInt(_SEND_REPORT_TO_STATUS_2_NUMBER_OF_RETRIES, 0);
}
public void clearSendReportRetry(Context context) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
SharedPreferences.Editor e = preferences.edit();
e.remove(_SEND_REPORT_TO_STATUS_2_NUMBER_OF_RETRIES);
e.commit();
}
// LOCAL REPORTS - Start
private String _TAG_LOCAL_REPORTS = "_TAG_LOCAL_REPORTS";
public void addLocalReport(Context context, Report report) {
if (context == null)
return;
List<Report> allTemporaryReports = getLocalReports(context);
allTemporaryReports.add(report);
saveTemporaryReports(context, allTemporaryReports);
}
public List<Report> getLocalReports(Context context) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
String reportsEncrypted = preferences.getString(_TAG_LOCAL_REPORTS, "");
List<Report> allTemporaryReports = null;
if (reportsEncrypted != null && reportsEncrypted != "") {
reportsEncrypted = Security.decrypt(reportsEncrypted);
allTemporaryReports = new Gson().fromJson(reportsEncrypted, new TypeToken<List<Report>>(){}.getType());
}
else
{
allTemporaryReports = new ArrayList<>();
}
return allTemporaryReports;
}
private void saveTemporaryReports(Context context, List<Report> temporaryReports) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
String jsonString = new Gson().toJson(temporaryReports);
String reportsStringEncrypted = Security.encrypt(jsonString);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(_TAG_LOCAL_REPORTS, reportsStringEncrypted);
editor.commit();
}
public void deleteTemporaryReport(Context context, int position) {
if (position > -1) {
List<Report> allTemporaryReports = getLocalReports(context);
if (allTemporaryReports.size() > 0 && position < allTemporaryReports.size()) {
allTemporaryReports.remove(position);
saveTemporaryReports(context, allTemporaryReports);
}
}
}
private String _TAG_LOCAL_REPORTS_EDIT_ADDRESS = "_TAG_LOCAL_REPORTS_EDIT_ADDRESS";
private String _TAG_LOCAL_REPORTS_CANCEL = "_TAG_LOCAL_REPORTS_CANCEL";
public void setEditAddress(Context context, boolean editAddress) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
SharedPreferences.Editor e = preferences.edit();
e.putBoolean(_TAG_LOCAL_REPORTS_EDIT_ADDRESS, editAddress);
e.commit();
}
public boolean shouldEditAddress(Context context) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
return preferences.getBoolean(_TAG_LOCAL_REPORTS_EDIT_ADDRESS, false);
}
public void setCancelTemporaryReport(Context context, boolean cancel) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
SharedPreferences.Editor e = preferences.edit();
e.putBoolean(_TAG_LOCAL_REPORTS_CANCEL, cancel);
e.commit();
}
public boolean shouldCancelTemporaryReport(Context context) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
return preferences.getBoolean(_TAG_LOCAL_REPORTS_CANCEL, false);
}
// LOCAL REPORTS - End
public void setNotificationsEnabled(Context context, boolean notificationsEnabled) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(_ENABLE_NOTIFICATIONS, notificationsEnabled);
editor.apply();
}
public boolean notificationsEnabled(Context context) {
preferences = context.getSharedPreferences(_TAG_PREFERENCES, context.MODE_PRIVATE);
return preferences.getBoolean(_ENABLE_NOTIFICATIONS, true);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.