text
stringlengths 10
2.72M
|
|---|
package com.madrapps.dagger.subcomponent.direct;
import dagger.Component;
@Component(modules = SampleModule.class)
public interface EmptyRootComponent {
EmptySubComponent component();
}
|
package com.cxc.canvasdemo;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
/**
* Created by cxc on 2017/4/28.
*/
public class MyView extends View {
private Paint mPaint;
public MyView(Context context, AttributeSet attrs){
super(context,attrs);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
}
@Override
protected void onDraw(Canvas canvas) {
mPaint.setColor(Color.BLUE);
canvas.drawRect(0,0,getWidth(),getHeight(),mPaint);
mPaint.setColor(Color.WHITE);
mPaint.setTextSize(80);
String text = "My View";
canvas.drawText(text,getWidth()/4,getHeight()/2,mPaint);
}
}
|
package Exam_2019_07_27_28_Kiko;
import java.util.Scanner;
public class Pro_06_Trip_Expenses {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Въведете броя на дните за ваканция: ");
int holidaysNum = Integer.parseInt(scanner.nextLine());
double moneyLeft = 60.0;
for (int countDay = 1; countDay <= holidaysNum; countDay++) {
int purchaseCount = 0;
while (moneyLeft != 0) {
System.out.print("Въведи Day over или стойност на покупката: ");
String infoText = scanner.nextLine();
if ("Day over".equals(infoText)) {
System.out.printf("Money left from today: %.2f. " +
"You've bought %d products.%n", moneyLeft, purchaseCount);
break;
} else {
int singlePrice = Integer.parseInt(infoText);
double currentMoneyLeft = moneyLeft;
currentMoneyLeft -= singlePrice;
if (currentMoneyLeft < 0) {
currentMoneyLeft = moneyLeft;
} else {
moneyLeft = currentMoneyLeft;
purchaseCount++;
if (moneyLeft == 0) {
System.out.printf("Daily limit exceeded! " +
"You've bought %d products.%n", purchaseCount);
}
}
}
}
moneyLeft += 60.0;
}
}
}
|
package com.xiaoxz;
import com.alibaba.fastjson.JSON;
import com.xiaoxz.constant.FileConstant;
import com.xiaoxz.pjo.AmqMsg;
import com.xiaoxz.pjo.AmqType;
import com.xiaoxz.pjo.Result;
import com.xiaoxz.service.impl.BaseServiceImpl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
@RunWith(SpringRunner.class)
@SpringBootTest
public class XzzappApplicationTests {
@Autowired
private AmqpTemplate amqpTemplate;
@Test
public void contextLoads() throws UnsupportedEncodingException {
System.out.println("--------------开始发送信息------------");
this.amqpTemplate.convertAndSend(FileConstant.RABBIT_MQ, JSON.toJSONString(new AmqMsg(AmqType.type1)).getBytes("UTF-8"));
}
@Autowired
private RedisTemplate redisTemplate;
@Test
public void test() {
List<String> imeiList = new ArrayList<>();
imeiList.add("x1");
imeiList.add("x2");
imeiList.add("x3");
redisTemplate.opsForSet().add("imeiList", "x1", "x2", "x3");
Set<String> list = redisTemplate.opsForSet().members(imeiList);
System.out.println(list);
Long l = redisTemplate.opsForSet().remove("imeiList", imeiList);
System.out.println(l);
}
}
|
/******************************************************************************
* __ *
* <-----/@@\-----> *
* <-< < \\// > >-> *
* <-<-\ __ /->-> *
* Data / \ Crow *
* ^ ^ *
* info@datacrow.net *
* *
* This file is part of Data Crow. *
* Data Crow is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public *
* License as published by the Free Software Foundation; either *
* version 3 of the License, or any later version. *
* *
* Data Crow is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public *
* License along with this program. If not, see http://www.gnu.org/licenses *
* *
******************************************************************************/
package net.datacrow.util.freedb;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
import net.datacrow.core.DcRepository;
import net.datacrow.core.data.DataManager;
import net.datacrow.core.http.HttpConnection;
import net.datacrow.core.http.HttpConnectionUtil;
import net.datacrow.core.modules.DcModules;
import net.datacrow.core.objects.DcObject;
import net.datacrow.core.objects.helpers.AudioCD;
import net.datacrow.core.objects.helpers.AudioTrack;
import net.datacrow.core.resources.DcResources;
import net.datacrow.util.Utilities;
public class Freedb {
private String userLogin = formatProperty(System.getProperty("user.name"));
private String userDomain = formatProperty(System.getProperty("os.name"));
private String clientName = "DataCrow";
private String clientVersion = "1.0";
private String protocol = "6";
private String server = "freedb.freedb.org";
public Freedb() {}
public DcObject[] queryDiscId(String discID) throws Exception {
return query(discID);
}
public String[] getCategories() throws Exception {
String answer = askFreedb("cddb+lscat");
StringTokenizer st = new StringTokenizer(answer, "\n");
List<String> l = new LinkedList<String>();
while(st.hasMoreTokens()) {
String line = st.nextToken();
if(!line.startsWith("2") && !line.startsWith("."))
l.add(line);
}
return l.toArray(new String[0]);
}
// private String[] getAvailableServers() throws Exception {
// String answer = askFreedb("sites");
// StringTokenizer st = new StringTokenizer(answer, "\n");
//
// List<String> l = new LinkedList<String>();
// while(st.hasMoreTokens()) {
// String line = st.nextToken();
// if(!line.startsWith("2") && !line.startsWith(".") ) {
// String[] sline = line.split(" ", 7);
// if(sline[1].equals("http"))
// l.add(sline[0]);
// }
// }
//
// return l.toArray(new String[0]);
// }
/**
* Queries the freedb server for the full id:
* Client command:
* -> cddb query discid ntrks off1 off2 ... nsecs
*
* After querying, the cd is queried by its discid and genre
*
* @param id full disc id
* @throws Exception
*/
public net.datacrow.core.objects.DcObject[] query(String id) throws Exception {
//Create the command to be sent to freedb
String command = getReadCommand(id);
//Send the command, and read the answer
String queryAnswer = askFreedb(command);
StringTokenizer st = new StringTokenizer(queryAnswer, "\n" );
String[] answers = new String[st.countTokens()];
for (int i = 0; i < answers.length; i++) {
answers[i] = st.nextToken();
}
int counter = 0;
String[][] data = new String[answers.length][];
for (int i = 0; i < answers.length; i++) {
String answer = answers[i];
if (answer.startsWith("200")) {
answer = answer.substring(3, answer.length());
}
if (!answer.startsWith("211") && !answer.startsWith("210") && !answer.startsWith(".")) {
st = new StringTokenizer(answer, " " );
String[] row = new String[st.countTokens()];
for (int j = 0; j < 2; j++) {
row[j] = st.nextToken();
}
data[i] = row;
counter++;
}
}
DcObject[] audioCDs = new AudioCD[counter];
counter = 0;
for (int i = 0; i < data.length; i++) {
if (data[i] != null) {
String genre = data[i][0];
String discid = data[i][1];
FreedbReadResult result = read(genre, discid);
audioCDs[counter++] = convertToDcObject(result);
}
}
return audioCDs;
}
public FreedbReadResult read(String genre, String id) throws Exception {
//Create the command to be sent to freedb
String command = getReadCommand(genre, id);
//Send the command, and read the answer
String queryAnswer = askFreedb(command);
//Parse the result
return new FreedbReadResult(queryAnswer, genre);
}
public FreedbReadResult read(FreedbQueryResult query) throws Exception {
//Create the command to be sent to freedb
String command = getReadCommand(query);
// logger.info(DcResources.getText("msgSendCommandToServer", command));
//Send the command, and read the answer
String queryAnswer = askFreedb(command);
//logger.info(DcResources.getText("msgGotResult"));
//Parse the result
return new FreedbReadResult(queryAnswer, query.isExactMatch());
}
private String askFreedb(String command) throws Exception {
URL url = null;
try {
url = new URL( "http://" + server + "/~cddb/cddb.cgi" );
} catch (MalformedURLException e) {
throw new Exception(DcResources.getText("msgInvalidURLChangeSetting", "http://" + server + "/~cddb/cddb.cgi"));
}
HttpConnection connection = HttpConnectionUtil.getConnection(url);
try {
PrintWriter out = new PrintWriter(connection.getOutputStream());
String query = "cmd=" + command + "&hello=" + userLogin + "+" + userDomain + "+" +
clientName + "+" + clientVersion + "&proto="+ protocol;
out.println(query);
out.flush();
out.close();
} catch ( IOException e ) {
throw new Exception(DcResources.getText("msgFreeDBServerUnreachable", e.getMessage()));
}
String output = connection.getString();
//Preliminary freedb error check, error codes 4xx and 5xx indicate an error
if (output.startsWith("4") || output.startsWith("5") || output.startsWith("202")) {
throw new Exception(DcResources.getText("msgFreeDBServerReturnedError", output));
}
return output;
}
private String getReadCommand(FreedbQueryResult query) {
return "cddb+read+" + query.getCategory() + "+" + query.getDiscId();
}
private String getReadCommand(String id) {
return "cddb+query+"+ id;
}
private String getReadCommand(String genre, String id) {
return "cddb+read+" + genre + "+" + id;
}
private String formatProperty(String s) {
if(s.length() == 0)
return "default";
int i = s.indexOf(" ");
return (i == -1) ? s : s.substring(0, i);
}
/**
* Converts a query result (not detailed) to a Data Crow Object
* @param result query result
*/
public DcObject convertToDcObject(FreedbQueryResult result) {
DcObject audioCD = DcModules.get(DcModules._AUDIOCD).getItem();
audioCD.setValue(AudioCD._A_TITLE, result.getAlbum());
audioCD.setValue(AudioCD._F_ARTISTS, result.getArtist());
audioCD.setValue(AudioCD._G_GENRES, result.getCategory());
audioCD.addExternalReference(DcRepository.ExternalReferences._DISCID, result.getDiscId());
return audioCD;
}
private void setGenres(DcObject dco, String genre) {
DataManager.createReference(dco, AudioCD._G_GENRES, genre);
}
/**
* Converts a read result (detailed) to a Data Crow Object
* @param result read result
*/
public DcObject convertToDcObject(FreedbReadResult result) {
DcObject audioCD = DcModules.get(DcModules._AUDIOCD).getItem();
String title = result.getAlbum();
if (title != null && title.length() > 0)
title = title.endsWith("\r") || title.endsWith("\n") ? title.substring(0, title.length() - 1) : title;
audioCD.setValue(AudioCD._A_TITLE, title);
DataManager.createReference(audioCD, AudioCD._F_ARTISTS, result.getArtist());
audioCD.addExternalReference(DcRepository.ExternalReferences._DISCID, result.getDiscId());
setGenres(audioCD, result.getCategory());
int year = Utilities.getIntegerValue(result.getYear());
audioCD.setValue(AudioCD._C_YEAR, new Integer(year));
for (int i = 0; i < result.getTracksNumber(); i++) {
DcObject track = DcModules.get(DcModules._AUDIOTRACK).getItem();
String lyric = result.getTrackComment(i);
track.setValue(AudioTrack._F_TRACKNUMBER, new Integer(i + 1));
track.setValue(AudioTrack._A_TITLE, result.getTrackTitle(i));
track.setValue(AudioTrack._G_LYRICS, lyric);
track.setValue(AudioTrack._H_PLAYLENGTH, result.getTrackSeconds(i));
audioCD.addChild(track);
}
audioCD.setIDs();
return audioCD;
}
}
|
package de.rexlManu.System.Commands;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import de.rexlManu.System.Island.Island;
public class IslandCMD implements CommandExecutor{
@Override
public boolean onCommand(CommandSender cs, Command c, String s, String[] ss) {
if(!(cs instanceof Player)){
cs.sendMessage("blabla");
}
Player p = (Player)cs;
Island.createIsland(p);
return false;
}
}
|
package com.wzk.demo.springboot.shardingswagger.controller;
import com.wzk.demo.springboot.shardingswagger.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
public class OrderController {
@Autowired
private OrderService orderService;
@RequestMapping("getOrderList")
@ResponseBody
public Map<Object,Object> getOrderList(){
Map<Object, Object> map = new HashMap<>();
orderService.getOrderService();
return map;
};
}
|
package cn.appInfo.controller;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import cn.appInfo.entity.AppInfo;
import cn.appInfo.entity.App_Category;
import cn.appInfo.entity.App_Version;
import cn.appInfo.entity.BackendUser;
import cn.appInfo.entity.Data_Dictionary;
import cn.appInfo.service.BackendUserService;
import cn.appInfo.service.DevUserService;
import cn.appInfo.utils.Constants;
import cn.appInfo.utils.PageSupport;
@Controller
public class backendController {
@Resource
private BackendUserService backendUserService;
@Resource
private DevUserService devUserService;
@RequestMapping(value="/sys2/backend.html",method=RequestMethod.GET)
public String main(Model model,HttpSession session){
BackendUser b = (BackendUser)session.getAttribute(Constants.USER_SESSION);
PageSupport pages = new PageSupport();
pages.setCurrentPageNo(1);
pages.setPageSize(Constants.pageSize);
pages.setTotalCount(backendUserService.getTotalCount(null, null, null, null, null, b.getId()));
List<Data_Dictionary> list2 = devUserService.findFlatform();
List<App_Category> list3 = devUserService.findLevel1();
List<AppInfo> list4 = backendUserService.findAllAppInfo(b.getId(), pages);
model.addAttribute("pages",pages);
model.addAttribute("flatFormList",list2);
model.addAttribute("categoryLevel1List",list3);
model.addAttribute("appInfoList",list4);
return "backendjsp/applist";
}
@RequestMapping(value="/backend/getLevel2",method=RequestMethod.GET)
@ResponseBody
public Object Getlevel2(@RequestParam Integer pid){
List<App_Category> list = devUserService.findLevel2(pid);
return JSON.toJSON(list);
}
@RequestMapping(value="/backend/getLevel3",method=RequestMethod.GET)
@ResponseBody
public Object Getlevel3(@RequestParam Integer pid){
List<App_Category> list = devUserService.findLevel3(pid);
return JSON.toJSON(list);
}
@RequestMapping(value="/backend/list",method=RequestMethod.POST)
public String pages(@RequestParam Integer pageIndex,
@RequestParam(required=false) String querySoftwareName,
@RequestParam(required=false) Integer queryFlatformId,
@RequestParam(required=false) Integer queryCategoryLevel1,
@RequestParam(required=false) Integer queryCategoryLevel2,
@RequestParam(required=false) Integer queryCategoryLevel3,
HttpSession session,
Model model){
BackendUser b = (BackendUser)session.getAttribute(Constants.USER_SESSION);
int zt = backendUserService.getTotalCount(querySoftwareName,queryFlatformId,queryCategoryLevel1,queryCategoryLevel2,queryCategoryLevel3,b.getId());
int zy = zt%Constants.pageSize==0?zt/Constants.pageSize:zt/Constants.pageSize+1;
if(pageIndex<=0){
pageIndex = 1;
}
if(pageIndex>=zy){
pageIndex = zy;
}
List<AppInfo> list4 = null;
if(zt==0){
list4 = null;
}else{
list4 = backendUserService.findAppInfoByStatus(querySoftwareName,
queryCategoryLevel1,
queryCategoryLevel2,
queryCategoryLevel3,
queryFlatformId,
b.getId(),
pageIndex,
5);
}
PageSupport pages = new PageSupport();
pages.setCurrentPageNo(pageIndex);
pages.setPageSize(Constants.pageSize);
pages.setTotalCount(zt);
List<Data_Dictionary> list2 = devUserService.findFlatform();
List<App_Category> list3 = devUserService.findLevel1();
if(querySoftwareName!=null || querySoftwareName!=""){
model.addAttribute("querySoftwareName",querySoftwareName);
}
if(queryFlatformId!=null){
model.addAttribute("queryFlatformId",queryFlatformId);
}
if(queryCategoryLevel1!=null){
model.addAttribute("queryCategoryLevel1",queryCategoryLevel1);
}
if(queryCategoryLevel2!=null){
List<App_Category> categoryLevel2List = devUserService.findLevel2(queryCategoryLevel1);
model.addAttribute("categoryLevel2List",categoryLevel2List);
model.addAttribute("queryCategoryLevel2",queryCategoryLevel2);
}
if(queryCategoryLevel3!=null){
List<App_Category> categoryLevel3List = devUserService.findLevel3(queryCategoryLevel2);
model.addAttribute("categoryLevel3List",categoryLevel3List);
model.addAttribute("queryCategoryLevel3",queryCategoryLevel3);
}
model.addAttribute("pages",pages);
model.addAttribute("flatFormList",list2);
model.addAttribute("categoryLevel1List",list3);
model.addAttribute("appInfoList",list4);
return "backendjsp/applist";
}
@RequestMapping(value="/backend/check",method=RequestMethod.GET)
public String check(@RequestParam Integer aid,Model model){
AppInfo appInfo = backendUserService.getBackendView(aid);
App_Version v = backendUserService.getView2(appInfo.getVersionId());
model.addAttribute("appInfo",appInfo);
model.addAttribute("appVersion",v);
return "backendjsp/backendView";
}
@RequestMapping(value="/backend/checksave",method=RequestMethod.POST)
public String checksave(@RequestParam Integer status,@RequestParam Integer id,Model model){
int line = backendUserService.updateStatus(id, status);
if(line>0){
return "redirect:/sys2/backend.html";
}
return "backendjsp/backendView";
}
}
|
package ru.otus.sua.L15.cache;
import lombok.extern.slf4j.Slf4j;
import ru.otus.sua.L15.entity.DataSet;
import ru.otus.sua.L15.starting.Startup;
import javax.enterprise.context.ApplicationScoped;
@Slf4j
@ApplicationScoped
public class CacheBean extends CacheSoftHashMap<Long, DataSet> implements Startup {
public CacheBean(){
this(10,2222,2345,false);
}
private CacheBean(int maxElements, long lifeTimeMs, long idleTimeMs, boolean isEternal){
super(maxElements, lifeTimeMs, idleTimeMs, isEternal);
}
}
|
package com.combination.common.example;
/**
* 树叶构件
*/
public class Leaf extends Component {
}
|
package org.example.codingtest.oneLevel;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class MinNumRemove {
public static void main(String[] args) {
int[] arr = {4,3,2,1};
int[] solution = solution(arr);
Arrays.stream(solution).forEach(System.out::println);
}
public static int[] solution(int[] arr) {
int[] answer = new int[arr.length];
if(arr.length==1){
answer[0] = -1;
return answer;
}
List<Integer> list = Arrays.stream(arr).boxed().collect(Collectors.toList());
int min = Arrays.stream(arr).min().getAsInt();
list.removeIf(i->i==min);
return list.stream().mapToInt(Integer::intValue).toArray();
}
}
|
package com.mrc.oauth2Java.dto;
import com.mrc.oauth2Java.domain.member.Member;
import com.mrc.oauth2Java.domain.member.MemberRole;
import lombok.*;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
@NoArgsConstructor
@Getter
@Setter
public class MemberJoinRequestDto {
@NotEmpty
private String email;
@NotEmpty
private String password;
@NotEmpty
private String name;
@NotNull
private MemberRole role;
@Builder
public MemberJoinRequestDto(String email, String password, String name, MemberRole role) {
this.email = email;
this.password = password;
this.name = name;
this.role = role;
}
}
|
package com.shahinnazarov.gradle.models.k8s;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonPropertyOrder(
{
"claimName",
"readOnly"
}
)
public final class PodVolumePersistentVolumeClaim<R extends DefaultK8sObject> extends AbstractK8sObject<R, PodVolumePersistentVolumeClaim<R>> {
public PodVolumePersistentVolumeClaim(R result, ChangeListener<PodVolumePersistentVolumeClaim<R>> listener) {
super(result, listener);
}
@JsonProperty("claimName")
private String claimName;
@JsonProperty("readOnly")
private Boolean readOnly;
public PodVolumePersistentVolumeClaim<R> claimName(String claimName) {
this.claimName = claimName;
return this;
}
public PodVolumePersistentVolumeClaim<R> readOnly(Boolean readOnly) {
this.readOnly = readOnly;
return this;
}
public R buildPvc() {
listener.apply(this);
return result;
}
}
|
package com.fhsoft.system.dao;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Repository;
import com.fhsoft.base.dao.BaseDao;
import com.fhsoft.model.Users;
/**
*
* @author hjb
* @date 2015-11-19 下午3:54:44
*/
@Repository
public class SysDao extends BaseDao {
public Users login (String name , String password){
Users u=null;
String sql=" select * from users where name=? ";
Object obj=jdbcTemplate.queryForObject(sql, new Object[] { name }, new BeanPropertyRowMapper<Users>(Users.class));
if(obj!=null){
u=(Users)obj;
}
return u;
}
}
|
package com.lucianoscilletta.battleship.ui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import com.lucianoscilletta.battleship.graphics.*;
import com.lucianoscilletta.battleship.music.*;
import com.lucianoscilletta.battleship.*;
import com.lucianoscilletta.battleship.ui.*;
public class WaitingPanel extends MessagePanel{
public WaitingPanel(int width, int height){
super("Please wait", "The other player is getting ready", MessagePanel.action.NONE);
(new Thread(new WaitForPlayer())).start();
}
class WaitForPlayer implements Runnable{
public void run(){
while (GraphicsEngine.isWaiting()){
try {
Thread.sleep(200);
} catch (Exception e) {
}
}
GraphicsEngine.loadScreen(new MainPanel(GraphicsEngine.getWidth(), GraphicsEngine.getHeight()));
}
}
}
|
import java.util.*;
import java.io.*;
import classfile.*;
public class AllTest{
public static void main(String[] args) {
test0_extractEmail();
test1_extractEmail();
test2_extractEmail();
test3_extractEmail();
test4_extractEmail();
test0_extractPhoneNumber();
test1_extractPhoneNumber();
test2_extractPhoneNumber();
test3_extractPhoneNumber();
test4_extractPhoneNumber();
}
public static void test0_extractEmail(){
Aron.beg();
String str = "dog@dog.com";
String email = Aron.extractEmail(str);
Test.t(email, str);
Aron.end();
}
public static void test1_extractEmail(){
Aron.beg();
String str = "dog_cat@dog.com";
String email = Aron.extractEmail(str);
Test.t(email, str);
Aron.end();
}
public static void test2_extractEmail(){
Aron.beg();
String str = "Santa Monica CA dog.cat@dog.com. call me baby";
String email = Aron.extractEmail(str);
Test.t(email, "dog.cat@dog.com");
Aron.end();
}
public static void test3_extractEmail(){
Aron.beg();
String str = "A third of food producted worldwild never get eaten dog-cat@dog.co, this is that cool";
String email = Aron.extractEmail(str);
Test.t(email, "dog-cat@dog.co");
Aron.end();
}
public static void test4_extractEmail(){
Aron.beg();
String str = "A third of food producted worldwild never get eaten 3344dog-cat@d334og.co, this is that cool";
String email = Aron.extractEmail(str);
Test.t(email, "3344dog-cat@d334og.co");
Aron.end();
}
public static void test0_extractPhoneNumber(){
Aron.beg();
String str = "call me baby 426-334-3345 call";
String number = Aron.extractPhoneNumber(str);
Test.t(number, "426-334-3345");
Aron.end();
}
public static void test1_extractPhoneNumber(){
Aron.beg();
String str = "call me baby 4263343345call";
String number = Aron.extractPhoneNumber(str);
Test.t(number, "4263343345");
Aron.end();
}
public static void test2_extractPhoneNumber(){
Aron.beg();
String str = "call me baby 426 334 3345call";
String number = Aron.extractPhoneNumber(str);
Test.t(number, "426 334 3345");
Aron.end();
}
public static void test3_extractPhoneNumber(){
Aron.beg();
String str = "call me baby426-334 3345call";
String number = Aron.extractPhoneNumber(str);
Test.t(number, "426-334 3345");
Aron.end();
}
public static void test4_extractPhoneNumber(){
Aron.beg();
String str = "call me baby426 334-3345call";
String number = Aron.extractPhoneNumber(str);
Test.t(number, "426 334-3345");
Aron.end();
}
}
|
package com.atguigu.entity;
public class Employee2 {
private Integer id;
private String name;
private String sex;
private String emailAddress;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public Employee2() {
}
@Override
public String toString() {
return "Employee2 [id=" + id + ", name=" + name + ", sex=" + sex + ", emailAddress=" + emailAddress + "]";
}
}
|
package com.lbo.foursquare.response;
import com.lbo.foursquare.model.ExtendedCategory;
import java.io.Serializable;
import java.util.List;
/**
* User: lbouin
* Date: 24/09/12
* Time: 21:35
*/
public class CategoriesResponse implements Serializable {
public List<ExtendedCategory> categories;
}
|
package com.edasaki.rpg.items;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import com.edasaki.core.utils.RFormatter;
import com.edasaki.core.utils.RParticles;
import com.edasaki.core.utils.RScheduler;
import com.edasaki.core.utils.RScheduler.Halter;
import com.edasaki.core.utils.RSound;
import com.edasaki.core.utils.RTicks;
import com.edasaki.rpg.PlayerDataRPG;
import com.edasaki.rpg.SakiRPG;
import com.edasaki.rpg.players.HealType;
import com.edasaki.rpg.warps.WarpLocation;
import de.slikey.effectlib.util.ParticleEffect;
public class EtcItem extends RPGItem {
public static SakiRPG plugin = null;
@Override
public ItemStack generate() {
ItemStack item = new ItemStack(material);
ItemMeta im = item.getItemMeta();
im.setDisplayName(name);
ArrayList<String> lore = new ArrayList<String>();
if (soulbound) {
lore.add(ChatColor.RED + ChatColor.ITALIC.toString() + "Soulbound");
}
if (description.length() > 0)
lore.addAll(RFormatter.stringToLore(description, ChatColor.GRAY));
im.setLore(lore);
im.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
im.addItemFlags(ItemFlag.HIDE_POTION_EFFECTS);
item.setItemMeta(im);
return item;
}
private static HashMap<UUID, Long> lastOldPlayer = new HashMap<UUID, Long>();
private static HashMap<UUID, Long> lastVoteReward = new HashMap<UUID, Long>();
private static HashMap<UUID, Long> lastManaPot = new HashMap<UUID, Long>();
private static HashMap<UUID, HashMap<String, Long>> eatTimers = new HashMap<UUID, HashMap<String, Long>>();
/*
* This is run AFTER all items are loaded. Items that require special listeners should be
* have their listeners within this method. For example, basically every item that has a
* right-click effect should be in here. Potions, special effects, etc.
*/
public static void postInitialize() {
// Mark of the Veteran - usable once every 30 seconds, shoots fireworks
ItemManager.registerItemRunnable("old_player", new ItemRunnable() {
@Override
public void run(Event e, Player p, PlayerDataRPG pd) {
if (lastOldPlayer.containsKey(p.getUniqueId())) {
if (System.currentTimeMillis() - lastOldPlayer.get(p.getUniqueId()) < 30000) {
p.sendMessage("");
p.sendMessage(ChatColor.RED + "The item can only be used once every 30 seconds!");
p.sendMessage(ChatColor.RED + "You can use it again in " + String.format("%.1f", 30 - (System.currentTimeMillis() - lastOldPlayer.get(p.getUniqueId())) / 1000.0) + " seconds.");
p.sendMessage(ChatColor.RED + "P.S. Thanks for sticking around!");
return;
}
}
lastOldPlayer.put(p.getUniqueId(), System.currentTimeMillis());
ArrayList<Location> locs = new ArrayList<Location>();
locs.add(p.getLocation().add(-2, 0, 2));
locs.add(p.getLocation().add(-2, 0, 1));
locs.add(p.getLocation().add(-2, 0, 0));
locs.add(p.getLocation().add(-2, 0, -1));
locs.add(p.getLocation().add(-2, 0, -2));
locs.add(p.getLocation().add(-1, 0, 2));
locs.add(p.getLocation().add(-1, 0, -2));
locs.add(p.getLocation().add(0, 0, 2));
locs.add(p.getLocation().add(0, 0, -2));
locs.add(p.getLocation().add(1, 0, 2));
locs.add(p.getLocation().add(1, 0, -2));
locs.add(p.getLocation().add(2, 0, 2));
locs.add(p.getLocation().add(2, 0, 1));
locs.add(p.getLocation().add(2, 0, 0));
locs.add(p.getLocation().add(2, 0, -1));
locs.add(p.getLocation().add(2, 0, -2));
for (Location loc : locs)
RParticles.spawnRandomFirework(loc);
p.sendMessage(ChatColor.GOLD + p.getName() + " is a true Zentrela veteran!");
for (Entity p2 : p.getNearbyEntities(10, 10, 10))
if (p2 instanceof Player)
((Player) p2).sendMessage(ChatColor.GOLD + p.getName() + " is a true Zentrela veteran!");
}
});
ItemManager.registerItemRunnable("july_2014_voter", new ItemRunnable() {
@Override
public void run(Event event, final Player p, PlayerDataRPG pd) {
if (lastVoteReward.containsKey(p.getUniqueId())) {
if (System.currentTimeMillis() - lastVoteReward.get(p.getUniqueId()) < 60000) {
p.sendMessage("");
p.sendMessage(ChatColor.RED + "This can only be used once every 60 seconds!");
p.sendMessage(ChatColor.RED + "You can use it again in " + String.format("%.1f", 60 - (System.currentTimeMillis() - lastVoteReward.get(p.getUniqueId())) / 1000.0) + " seconds.");
return;
}
}
lastVoteReward.put(p.getUniqueId(), System.currentTimeMillis());
p.sendMessage(ChatColor.GREEN + "ay bay bay grats");
Location loc = p.getLocation();
RParticles.show(ParticleEffect.CRIT, loc);
RParticles.show(ParticleEffect.FIREWORKS_SPARK, loc);
RParticles.show(ParticleEffect.NOTE, loc);
RParticles.show(ParticleEffect.SNOWBALL, loc);
RParticles.show(ParticleEffect.HEART, loc);
final Halter halter = new Halter();
RScheduler.scheduleRepeating(plugin, new Runnable() {
int count = 0;
public void run() {
if (p.isValid())
RParticles.spawnRandomFirework(p.getLocation());
count++;
if (!p.isValid() || count >= 10)
halter.halt = true;
}
}, RTicks.seconds(0.5), halter);
p.sendMessage(ChatColor.GOLD + "majd777 - winner of the July 2014 voting contest!");
for (Entity p2 : p.getNearbyEntities(10, 10, 10))
if (p2 instanceof Player)
((Player) p2).sendMessage(ChatColor.GOLD + "Congratulations to majd777, winner of the July 2014 voting contest!");
}
});
ItemManager.registerItemRunnable("hp_potion_1", new ItemRunnable() {
@Override
public void run(Event event, Player p, PlayerDataRPG pd) {
healWithPotion((int) Math.ceil(pd.getCurrentMaxHP() * 0.1), "hp_potion_1", event, p);
}
});
ItemManager.registerItemRunnable("hp_potion_2", new ItemRunnable() {
@Override
public void run(Event event, Player p, PlayerDataRPG pd) {
healWithPotion((int) Math.ceil(pd.getCurrentMaxHP() * 0.15), "hp_potion_2", event, p);
}
});
ItemManager.registerItemRunnable("hp_potion_3", new ItemRunnable() {
@Override
public void run(Event event, Player p, PlayerDataRPG pd) {
healWithPotion((int) Math.ceil(pd.getCurrentMaxHP() * 0.2), "hp_potion_3", event, p);
}
});
ItemManager.registerItemRunnable("hp_potion_4", new ItemRunnable() {
@Override
public void run(Event event, Player p, PlayerDataRPG pd) {
healWithPotion((int) Math.ceil(pd.getCurrentMaxHP() * 0.35), "hp_potion_4", event, p);
}
});
ItemManager.registerItemRunnable("hp_potion_5", new ItemRunnable() {
@Override
public void run(Event event, Player p, PlayerDataRPG pd) {
healWithPotion((int) Math.ceil(pd.getCurrentMaxHP() * 0.5), "hp_potion_5", event, p);
}
});
ItemManager.registerItemRunnable("melon", new ItemRunnable() {
@Override
public void run(Event event, Player p, PlayerDataRPG pd) {
if (justAte(pd, "melon"))
return;
takeOneItemInstant(p);
pd.heal(80);
RSound.playSound(p, Sound.ENTITY_GENERIC_EAT);
}
});
ItemManager.registerItemRunnable("melon_slice", new ItemRunnable() {
@Override
public void run(Event event, Player p, PlayerDataRPG pd) {
if (justAte(pd, "melon_slice"))
return;
takeOneItemInstant(p);
pd.heal(20);
RSound.playSound(p, Sound.ENTITY_GENERIC_EAT);
}
});
ItemManager.registerItemRunnable("roasted_chicken", new ItemRunnable() {
@Override
public void run(Event event, Player p, PlayerDataRPG pd) {
if (justAte(pd, "roasted_chicken"))
return;
takeOneItemInstant(p);
pd.heal(250);
RSound.playSound(p, Sound.ENTITY_GENERIC_EAT);
}
});
ItemManager.registerItemRunnable("maru_milk", new ItemRunnable() {
@Override
public void run(Event event, Player p, PlayerDataRPG pd) {
takeOneItemInstant(p);
pd.heal(pd.getCurrentMaxHP());
p.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, RTicks.seconds(30), 1), false);
p.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, RTicks.seconds(30), 2), false);
p.addPotionEffect(new PotionEffect(PotionEffectType.SLOW_DIGGING, RTicks.seconds(30), 0), false);
}
});
ItemManager.registerItemRunnable("tortuga_ale", new ItemRunnable() {
@Override
public void run(Event event, Player p, PlayerDataRPG pd) {
takeOneItemInstant(p);
pd.heal(pd.getCurrentMaxHP());
p.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, RTicks.seconds(15), 1), false);
p.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, RTicks.seconds(15), 2), false);
p.addPotionEffect(new PotionEffect(PotionEffectType.SLOW_DIGGING, RTicks.seconds(15), 0), false);
pd.sendMessage(ChatColor.GRAY + "> " + "The ale tastes terrible, and now you feel a little tipsy.");
}
});
ItemManager.registerItemRunnable("juicy_apple", new ItemRunnable() {
@Override
public void run(Event event, Player p, PlayerDataRPG pd) {
if (justAte(pd, "juicy_apple"))
return;
takeOneItemInstant(p);
pd.heal(300);
RSound.playSound(p, Sound.ENTITY_GENERIC_EAT);
}
});
ItemManager.registerItemRunnable("rotten_apple", new ItemRunnable() {
@Override
public void run(Event event, Player p, PlayerDataRPG pd) {
if (justAte(pd, "rotten_apple"))
return;
takeOneItemInstant(p);
pd.heal(300);
if (Math.random() < 0.5) {
p.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, RTicks.seconds(10), 1), false);
p.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, RTicks.seconds(10), 2), false);
}
}
});
ItemManager.registerItemRunnable("mana_pot_1", new ItemRunnable() {
@Override
public void run(Event event, Player p, PlayerDataRPG pd) {
if (lastManaPot.containsKey(p.getUniqueId()) && System.currentTimeMillis() - lastManaPot.get(p.getUniqueId()) < 500)
return;
lastManaPot.put(p.getUniqueId(), System.currentTimeMillis());
if (pd.mana < PlayerDataRPG.MAX_MANA) {
takeOneItemInstant(p);
pd.recoverMana(2);
}
}
});
ItemManager.registerItemRunnable("mana_pot_2", new ItemRunnable() {
@Override
public void run(Event event, Player p, PlayerDataRPG pd) {
if (lastManaPot.containsKey(p.getUniqueId()) && System.currentTimeMillis() - lastManaPot.get(p.getUniqueId()) < 500)
return;
lastManaPot.put(p.getUniqueId(), System.currentTimeMillis());
if (pd.mana < PlayerDataRPG.MAX_MANA) {
takeOneItemInstant(p);
pd.recoverMana(3);
}
}
});
ItemManager.registerItemRunnable("mana_pot_3", new ItemRunnable() {
@Override
public void run(Event event, Player p, PlayerDataRPG pd) {
if (lastManaPot.containsKey(p.getUniqueId()) && System.currentTimeMillis() - lastManaPot.get(p.getUniqueId()) < 500)
return;
lastManaPot.put(p.getUniqueId(), System.currentTimeMillis());
if (pd.mana < PlayerDataRPG.MAX_MANA) {
takeOneItemInstant(p);
pd.recoverMana(4);
}
}
});
ItemManager.registerItemRunnable("warp_korwyn", new WarpItemRunnable(WarpLocation.KORWYN.getLocation(), ItemManager.itemIdentifierToRPGItemMap.get("warp_korwyn").generate()));
ItemManager.registerItemRunnable("warp_lemia", new WarpItemRunnable(WarpLocation.OLD_LEMIA.getLocation(), ItemManager.itemIdentifierToRPGItemMap.get("warp_lemia").generate()));
ItemManager.registerItemRunnable("warp_erlen", new WarpItemRunnable(WarpLocation.OLD_ERLEN.getLocation(), ItemManager.itemIdentifierToRPGItemMap.get("warp_erlen").generate()));
ItemManager.registerItemRunnable("warp_maru_island", new WarpItemRunnable(WarpLocation.OLD_MARU_ISLAND.getLocation(), ItemManager.itemIdentifierToRPGItemMap.get("warp_maru_island").generate()));
ItemManager.registerItemRunnable("warp_perion", new WarpItemRunnable(WarpLocation.OLD_PERION.getLocation(), ItemManager.itemIdentifierToRPGItemMap.get("warp_perion").generate()));
ItemManager.registerItemRunnable("warp_kobaza", new WarpItemRunnable(WarpLocation.OLD_KOBAZA.getLocation(), ItemManager.itemIdentifierToRPGItemMap.get("warp_kobaza").generate()));
ItemManager.registerItemRunnable("warp_liptus", new WarpItemRunnable(WarpLocation.OLD_LIPTUS.getLocation(), ItemManager.itemIdentifierToRPGItemMap.get("warp_liptus").generate()));
ItemManager.registerItemRunnable("warp_ellinia", new WarpItemRunnable(WarpLocation.OLD_ELLINIA.getLocation(), ItemManager.itemIdentifierToRPGItemMap.get("warp_ellinia").generate()));
}
private static boolean justAte(PlayerDataRPG pd, String id) {
if (!eatTimers.containsKey(pd.getUUID()))
eatTimers.put(pd.getUUID(), new HashMap<String, Long>());
HashMap<String, Long> map = eatTimers.get(pd.getUUID());
long diff = System.currentTimeMillis() - map.getOrDefault(id, 0l);
if (diff < 10000) {
pd.sendMessage(ChatColor.GRAY + "> " + ChatColor.RED + "You just ate a stackable food! Try again in " + String.format("%.1f", 10 - (diff / 1000.0)) + "s.");
return true;
}
map.put(id, System.currentTimeMillis());
return false;
}
private static HashMap<String, Long> lastHealItem = new HashMap<String, Long>();
public static void healWithPotion(int amount, String name, Event event, Player p) {
if (!(event instanceof PlayerInteractEvent))
return;
PlayerInteractEvent e = (PlayerInteractEvent) event;
if (!(e.getAction() == Action.RIGHT_CLICK_AIR || e.getAction() == Action.RIGHT_CLICK_BLOCK))
return;
if (lastHealItem.containsKey(p.getName()) && System.currentTimeMillis() - lastHealItem.get(p.getName()) < 500) {
return;
}
lastHealItem.put(p.getName(), System.currentTimeMillis());
p.getEquipment().setItemInMainHand(new ItemStack(Material.AIR));
PlayerDataRPG pd = plugin.getPD(p);
pd.heal(amount, HealType.POTION);
for (int k = 0; k < p.getInventory().getContents().length; k++) {
if (ItemManager.isItem(p.getInventory().getItem(k), name)) {
p.getEquipment().setItemInMainHand(p.getInventory().getItem(k));
p.getInventory().setItem(k, new ItemStack(Material.AIR));
break;
}
}
RSound.playSound(p, Sound.ENTITY_GENERIC_DRINK);
}
}
|
package mvc;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import entity.User;
import security.SecurityService;
import security.UserSecurityService;
import service.UserService;
import validation.EmailExistsException;
import validation.EmailNotValidException;
@Controller
public class RegistrationController {
@Autowired
private UserService srv;
@Autowired
private UserDetailsService uds;
@Autowired
RequestCache requestCache;
@Autowired
private AuthenticationManager authManager;
private final static Logger logger = Logger.getLogger(LoginController.class.getName());
@RequestMapping("/reg")
public String registerUserAccount(@ModelAttribute("user") @Valid entity.User account, BindingResult result,
Model model, HttpServletRequest request, HttpServletResponse response)
throws EmailExistsException {
logger.debug("Registering user account with information: {}" + account.getEmail());
User registered = new User();
if (!result.hasErrors()) {
if ((!account.getEmail().isEmpty()) && (!account.getReal_name().isEmpty())
&& (!account.getPassword().isEmpty())) {
registered = detectEmail(account);
} else {
model.addAttribute("email", "Fill in all the fields");
return "index";
}
}
if (registered == null) {
model.addAttribute("email", "Email is already exist : " + account.getEmail());
return "index";
}else if (registered.getEmail().equals("EmailNotValidException") == true) {
model.addAttribute("email", "Your email is not correct: " + account.getEmail());
return "index";
}
logger.debug("begin auto logIn");
doAutoLogin(registered.getEmail(), registered.getPassword(), request);
return "redirect:/mypage.html";
}
private entity.User detectEmail(final entity.User account) {
User registered = null;
try {
registered = srv.createUserAccount(account);
} catch (final EmailExistsException e) {
return null;
} catch (EmailNotValidException e) {
registered = new User();
registered.setEmail("EmailNotValidException");
return registered;
}
return registered;
}
private void doAutoLogin(String username, String password, HttpServletRequest request) {
try {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
token.setDetails(new WebAuthenticationDetails(request));
Authentication authentication = authManager.authenticate(token);
logger.debug("Logging in with "+ authentication.getPrincipal());
SecurityContext sc = SecurityContextHolder.getContext();
sc.setAuthentication(authentication);
HttpSession session = request.getSession(true);
session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, sc);
} catch (Exception e) {
SecurityContextHolder.getContext().setAuthentication(null);
logger.error("Failure in autoLogin", e);
}
}
}
|
package net.suncaper.sparkairline;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.mllib.recommendation.ALS;
import org.apache.spark.mllib.recommendation.MatrixFactorizationModel;
import org.apache.spark.mllib.recommendation.Rating;
import org.codehaus.janino.Java;
import scala.Tuple2;
import java.util.Arrays;
@SpringBootApplication
public class SparkAirlineApplication {
public static void main(String[] args) {
SpringApplication.run(SparkAirlineApplication.class, args);
}
}
|
package mandelbrot.rendering;
// @author Gregoire & Raphael
import geometry.Vector2D;
import java.awt.image.BufferedImage;
import mandelbrot.config.ZoomedFrame;
import mandelbrot.config.color.ColorPalette;
import mandelbrot.rendering.iterationcalculator.IterationCalculator;
import mandelbrot.rendering.iterationcalculator.IterationResult;
import mandelbrot.rendering.parameterscalculator.ParameterResult;
import mandelbrot.rendering.parameterscalculator.ParametersCalculator;
public class MdbRendererSimple extends MdbRenderer
{
public MdbRendererSimple(ZoomedFrame currentFrame, int width, int height, IterationCalculator iterationCalculator, ParametersCalculator parametersCalculator, ColorPalette palette) {
super(currentFrame, width, height, iterationCalculator, parametersCalculator, palette);
}
@Override
public void computeImage()
{
Vector2D upLeftCorner = getEffectiveUpperLeftCorner();
double resolution = getResolution();
mdbImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for(int Y = 0; Y < height; Y++)
{
for(int X = 0; X < width; X++)
{
IterationResult res= iterationCalculator.computeIteration(upLeftCorner.getX()+X/resolution,upLeftCorner.getY()-Y/resolution);
ParameterResult parameterResult = parametersCalculator.computeParameters(res);
mdbImage.setRGB(X, Y, palette.getColorFromParam(parameterResult));
}
}
sendCanRepaintSignal();
}
@Override
protected void computeImage(int X, int Y, double zoomMultiplier, boolean zoomIn)
{
computeImage();
}
@Override
public void declarePixelInMandelbrotSet(int X, int Y)
{
}
@Override
public void renderImage() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
|
/**
* Kaydee Gilson
* Final Project
* WatchOpponentPlayer: strategy that watches opponent's score closely and makes decisions based off that
*/
public class WatchOpponentPlayer extends PigPlayer {
//instance data
private int closeToWin = 74;
private int holdValue = 19;
private int divideAmount = 42;
//constructors
//default constructor
public WatchOpponentPlayer() {
super("player");
}
//constructor with name
public WatchOpponentPlayer(String name) {
super(name);
this.holdValue = holdValue;
}
//constructor with name, holdValue, and divideAmount
public WatchOpponentPlayer (String name, int closeToWin, int holdValue, int divideAmount) {
super(name);
this.closeToWin = 74;
this.holdValue = 19;
this.divideAmount = 42;
}
//automated isRolling method that closely watches opponent
public boolean isRolling(int turnTotal, int opponentScore) {
int difference = opponentScore - getScore();
int updatedHoldValue = holdValue + (difference / divideAmount);
if (turnTotal + this.getScore() < PigGame.GOAL) { //if nobody has won &&
if (this.getScore() >= closeToWin || opponentScore >= closeToWin) { //if someone is close to winning
return true;
}
if (turnTotal < updatedHoldValue) { //if turnTotal has not yet reached the determined hold value for this turn
return true;
}
}
return false;
}
}
|
/**
*
*/
package partieConsole;
import java.util.List;
/**
* @author Mamadou bobo
*
*/
public class suiviPedagogique {
private int idSuivi;
private Etudiant etudiant;
private Inscription inscription;
private List<Session> listSession;
private List <Matiere> listmatiereValide;
private List <Etudiant> listAbsence;
public suiviPedagogique(int idSuivi, Etudiant etudiant, Inscription inscription, List<Session> listSession,
List<Matiere> listmatiereValide, List<Etudiant> listAbsence) {
super();
this.idSuivi = idSuivi;
this.etudiant = etudiant;
this.inscription = inscription;
this.listSession = listSession;
this.listmatiereValide = listmatiereValide;
this.listAbsence = listAbsence;
}
public int getIdSuivi() {
return idSuivi;
}
public void setIdSuivi(int idSuivi) {
this.idSuivi = idSuivi;
}
public Etudiant getEtudiant() {
return etudiant;
}
public void setEtudiant(Etudiant etudiant) {
this.etudiant = etudiant;
}
public Inscription getInscription() {
return inscription;
}
public void setInscription(Inscription inscription) {
this.inscription = inscription;
}
public List<Session> getListSession() {
return listSession;
}
public void setListSession(List<Session> listSession) {
this.listSession = listSession;
}
public List<Matiere> getListmatiereValide() {
return listmatiereValide;
}
public void setListmatiereValide(List<Matiere> listmatiereValide) {
this.listmatiereValide = listmatiereValide;
}
public List<Etudiant> getListAbsence() {
return listAbsence;
}
public void setListAbsence(List<Etudiant> listAbsence) {
this.listAbsence = listAbsence;
}
@Override
public String toString() {
return "suiviPedagogique [idSuivi=" + idSuivi + ", etudiant=" + etudiant + ", inscription=" + inscription
+ ", listSession=" + listSession + ", listmatiereValide=" + listmatiereValide + ", listAbsence="
+ listAbsence + "]";
}
}
|
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
public class BinaryTreeRightsideView {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null) return result;
//result.add(root.val);
ArrayDeque<TreeNode> arrayDeque1 = new ArrayDeque<>();
ArrayDeque<TreeNode> arrayDeque2 = new ArrayDeque<>();
arrayDeque1.add(root);
while (!arrayDeque1.isEmpty() || !arrayDeque2.isEmpty()) {
TreeNode levelLast = new TreeNode(0);
while (!arrayDeque1.isEmpty()) {
TreeNode tmp = arrayDeque1.pollFirst();
if (tmp.left != null) arrayDeque2.add(tmp.left);
if (tmp.right != null) arrayDeque2.add(tmp.right);
levelLast = tmp;
}
result.add(levelLast.val);
ArrayDeque<TreeNode> tmpQueue = arrayDeque1;
arrayDeque1 = arrayDeque2;
arrayDeque2 = tmpQueue;
}
return result;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.right = new TreeNode(5);
root.right.right = new TreeNode(4);
System.out.println(new BinaryTreeRightsideView().rightSideView(root));
}
}
|
/*
* Copyright 2018 the original author or authors.
*
* 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.sandy.infrastructure.common;
import java.io.Serializable;
/**
* abstract date entity
*
* @author Sandy
* @param <K>
* @since 1.0.0 11th 10 2018
*/
public abstract class AbstractIdEntity<PK> implements Serializable {
private static final long serialVersionUID = -7200609014851715015L;
private PK id;
public PK getId() {
return id;
}
public void setId(PK id) {
this.id = id;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
AbstractIdEntity<?> other = (AbstractIdEntity<?>) obj;
if (null == id) {
if (null != other.id) {
return false;
}
}
return id.equals(other.id);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
}
|
/*
* work_wx
* wuhen 2020/1/16.
* Copyright (c) 2020 jianfengwuhen@126.com All Rights Reserved.
*/
package com.work.wx.controller.api.token;
import com.google.gson.Gson;
import com.work.wx.controller.modle.CorpModel;
import com.work.wx.controller.modle.TokenModel;
import com.work.wx.server.TokenServer;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ApplicationAccessToken {
private final static Logger logger = LoggerFactory.getLogger(ApplicationAccessToken.class);
public static final int CONTACT_TOKEN_TYPE = 3;
public static final String BASE_ADDRESS = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
public String getApplicationAccessToken(TokenServer tokenServer, CorpModel corpModel) {
TokenModel tokenModel = tokenServer.getTokenModel(new TokenModel(corpModel.getCorp(),CONTACT_TOKEN_TYPE));
if (null != tokenModel) {
if (tokenModel.getLoseTime() > System.currentTimeMillis()) {
return tokenModel.getAccess_token();
}
}
boolean status = requestContactToken(tokenServer,corpModel);
return status ? getApplicationAccessToken(tokenServer,corpModel) : "";
}
private boolean setApplicationAccessToken(TokenModel queryModel, TokenModel tokenModel, TokenServer tokenServer) {
return tokenServer.updateInsertToken(queryModel,tokenModel) > 0;
}
private boolean requestContactToken(TokenServer tokenServer,CorpModel corpModel) {
String url = BASE_ADDRESS + "?" + "corpid=" + corpModel.getCorp() +"&" + "corpsecret=" + corpModel.getApplicationSecret();
try {
Response response = new OkHttpClient().newCall(new Request.Builder().url(url).get().build()).execute();
if (response.code() == 200) {
TokenModel tokenModel = new Gson().fromJson(response.body().string(), TokenModel.class);
if (tokenModel.getErrcode() == 0) {
logger.debug(tokenModel.toString());
tokenModel.setLoseTime(System.currentTimeMillis() + tokenModel.getExpires_in() * 1000);
tokenModel.setCorpId(corpModel.getCorp());
tokenModel.setToken_type(CONTACT_TOKEN_TYPE);
setApplicationAccessToken(new TokenModel(corpModel.getCorp(),CONTACT_TOKEN_TYPE),tokenModel,tokenServer);
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
|
package org.mbmg;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.simpledb.AmazonSimpleDB;
import com.amazonaws.services.simpledb.AmazonSimpleDBClient;
import com.amazonaws.services.simpledb.model.BatchPutAttributesRequest;
import com.amazonaws.services.simpledb.model.CreateDomainRequest;
import com.amazonaws.services.simpledb.model.Item;
import com.amazonaws.services.simpledb.model.ReplaceableAttribute;
import com.amazonaws.services.simpledb.model.ReplaceableItem;
import com.amazonaws.services.simpledb.model.SelectRequest;
public class MyServiceTest {
static AmazonSimpleDB sdb;
static String domain;
@BeforeClass
public static void init() throws Exception {
domain = "MuhuruBay";
String userHome = System.getenv("HOME");
Path homePath = Paths.get(userHome, "AwsCredentials.properties");
sdb = new AmazonSimpleDBClient(new PropertiesCredentials(
homePath.toFile()));
}
@Test
public void createDB() throws Exception {
sdb.createDomain(new CreateDomainRequest(domain));
}
@Test
public void insertTestData() throws Exception {
List<ReplaceableItem> data = new ArrayList<ReplaceableItem>();
data.add(new ReplaceableItem().withName("Wind_Turbine_01")
.withAttributes(
new ReplaceableAttribute().withName("Power").withValue(
"10"),
new ReplaceableAttribute().withName("Units").withValue(
"KW")));
sdb.batchPutAttributes(new BatchPutAttributesRequest(domain, data));
}
@Test
public void queryDB() throws Exception {
String qry = "select * from `" + domain + "` where Units = 'KW'";
SelectRequest selectRequest = new SelectRequest(qry);
for (Item item : sdb.select(selectRequest).getItems()) {
System.out.println("Power=: " + item.getName());
}
}
}
|
package com.example.user.javaolympics;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Created by user on 17/09/2017.
*/
public class AthleteTest {
Athlete athlete;
@Before
public void before() {
athlete = new Athlete(0, 0, 0, Country.BRITAIN, "John Smith", 8, Discipline.JAVELIN);
}
@Test
public void hasAName() {
assertEquals("John Smith", athlete.getName());
}
@Test
public void hasNoBronzeMedals() {
assertEquals(0, athlete.getBronzeMedalCount());
}
@Test
public void hasNoSilverMedals() {
assertEquals(0, athlete.getSilverMedalCount());
}
@Test
public void hasNoGoldMedals() {
assertEquals(0, athlete.getGoldMedalCount());
}
@Test
public void hasACountry() {
assertEquals(Country.BRITAIN, athlete.getCountry());
}
@Test
public void hasSkillLevel() {
assertEquals(8, athlete.getSkill());
}
@Test
public void hasDiscipline() {
assertEquals( Discipline.JAVELIN, athlete.getDiscipline());
}
@Test
public void awardBronze() {
athlete.awardBronze();
assertEquals( 1, athlete.bronzeMedalCount);
}
@Test
public void awardSilver() {
athlete.awardSilver();
assertEquals(1, athlete.silverMedalCount);
}
@Test
public void awardGold() {
athlete.awardGold();
assertEquals(1, athlete.goldMedalCount);
}
@Test
public void award2Bronzes1SilverAnd3Golds() {
athlete.awardBronze();
athlete.awardBronze();
athlete.awardSilver();
athlete.awardGold();
athlete.awardGold();
athlete.awardGold();
assertEquals(6, athlete.howManyMedals());
assertEquals(2, athlete.bronzeMedalCount);
assertEquals(1, athlete.silverMedalCount);
assertEquals(3, athlete.goldMedalCount);
}
}
|
/*
* 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 implement;
/**
*
* @author ASUS
*/
public interface implementLogin {
public boolean login(String userid, String password);
}
|
package mx.infornet.smartgym;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.textfield.TextInputEditText;
public class ReportarActivity extends AppCompatActivity {
private TextInputEditText mensaje;
private MaterialButton btn_send;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reportar);
MaterialToolbar toolbar = findViewById(R.id.toolbarReport);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Reportar un problema");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
mensaje = findViewById(R.id.mensaje_report);
btn_send = findViewById(R.id.btn_enviar_report);
btn_send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String mens = mensaje.getText().toString();
if (TextUtils.isEmpty(mens)){
mensaje.setError("Introduzca el mensaje del reporte");
mensaje.requestFocus();
} else {
Intent itSend = new Intent(Intent.ACTION_SEND);
itSend.setData(Uri.parse("mailito"));
itSend.setType("plain/text");
itSend.putExtra(Intent.EXTRA_EMAIL, new String[] {"jor.martinez.salgado@gmail.com"});
itSend.putExtra(Intent.EXTRA_SUBJECT, "Reporte App Smart Gym miembro");
itSend.putExtra(Intent.EXTRA_TEXT, mens);
try {
startActivity(Intent.createChooser(itSend, "Enviar email"));
Log.i("EMAIL", "Enviando email...");
} catch (android.content.ActivityNotFoundException e){
Toast.makeText(getApplicationContext(), "NO existe ningún cliente de email instalado!.", Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
|
package edu.uha.miage.core.service.impl;
import edu.uha.miage.core.entity.StatutDemande;
import edu.uha.miage.core.repository.StatutDemandeRepository;
import edu.uha.miage.core.service.StatutDemandeService;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
*
* @author victo
*/
@Service
public class StatutDemandeServiceImpl implements StatutDemandeService {
@Autowired
StatutDemandeRepository statutDemandeRepository;
@Override
public StatutDemande save(StatutDemande entity) {
return statutDemandeRepository.save(entity);
}
@Override
public void delete(Long id) {
statutDemandeRepository.deleteById(id);
}
@Override
public List<StatutDemande> findAll() {
return (List<StatutDemande>) statutDemandeRepository.findAll();
}
@Override
public Optional<StatutDemande> findById(Long id) {
return statutDemandeRepository.findById(id);
}
@Override
public StatutDemande findByLibelle(String libelle) {
return statutDemandeRepository.findByLibelle(libelle);
}
@Override
public StatutDemande getOne(Long id) {
return statutDemandeRepository.getOne(id);
}
}
|
package graficos;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class PruevaVarios {
public static void main(String[] args) {
// TODO Auto-generated method stub
Marco_principal mimarco=new Marco_principal();
mimarco.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mimarco.setVisible(true);
}
}
class Marco_principal extends JFrame{
public Marco_principal(){
setTitle("Prueva Varios");
setBounds(1300, 100, 300, 200);
Lamina_Principal lamina=new Lamina_Principal();
add(lamina);
}
}
class Lamina_Principal extends JPanel{
public Lamina_Principal(){
JButton boton_nuevo=new JButton("Nuevo");
boton_cerrar=new JButton("cerrar todo");
add(boton_nuevo);
add(boton_cerrar);
OyenteNuevo miOyente=new OyenteNuevo();
boton_nuevo.addActionListener(miOyente);
}
private class OyenteNuevo implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Marco_Emergente marco=new Marco_Emergente(boton_cerrar);
marco.setVisible(true);
}
}
JButton boton_cerrar;
}
class Marco_Emergente extends JFrame{
public Marco_Emergente(JButton boton_de_principal){
contador++;
setTitle("Ventana " + contador);
setBounds(40*contador, 40*contador, 300, 150);
CierraTodos oyenteCerrar=new CierraTodos();
boton_de_principal.addActionListener(oyenteCerrar);
}
private class CierraTodos implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
dispose();// cuando se llama a este metodo cirra todo y livera memoria
}
}
private static int contador=0;
}
|
package com.assignment.java;
public class Transaction {
private String transactionId;
private String clientId;
private String securityId;
private TransactionType tType;
private String date;
private Double marketValue;
private String priorityFlag;
public String getTransactionId() {
return transactionId;
}
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getSecurityId() {
return securityId;
}
public void setSecurityId(String securityId) {
this.securityId = securityId;
}
public TransactionType gettType() {
return tType;
}
public void settType(TransactionType tType) {
this.tType = tType;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public Double getMarketValue() {
return marketValue;
}
public void setMarketValue(double marketValue) {
this.marketValue = marketValue;
}
public String getPriorityFlag() {
return priorityFlag;
}
public void setPriorityFlag(String priorityFlag) {
this.priorityFlag = priorityFlag;
}
public Transaction(String transactionId, String clientId, String securityId, TransactionType tType, String date,
Double marketValue, String priorityFlag) {
this.transactionId = transactionId;
this.clientId = clientId;
this.securityId = securityId;
this.tType = tType;
this.date = date;
this.marketValue = marketValue;
this.priorityFlag = priorityFlag;
}
//For Summary Report
public Transaction(String clientId, TransactionType tType, String date, String priorityFlag) {
this.clientId = clientId;
this.tType = tType;
this.date = date;
this.priorityFlag = priorityFlag;
}
}
|
package com.example.ecommerceapp.buyers;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.ecommerceapp.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.HashMap;
public class RegisterActivity extends AppCompatActivity {
Button btn_create;
EditText et_name,et_phone,et_password;
ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
progressDialog =new ProgressDialog(RegisterActivity.this);
et_name = findViewById(R.id.register_name_et);
et_phone = findViewById(R.id.register_phone_et);
et_password = findViewById(R.id.register_password_et);
btn_create = findViewById(R.id.register_create_btn);
btn_create.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
createAccount();
}
});
}
private void createAccount() {
String name = et_name.getText().toString().trim();
String phone = et_phone.getText().toString().trim();
String password = et_password.getText().toString().trim();
if(TextUtils.isEmpty(name)){
Toast.makeText(RegisterActivity.this, "name is empty ", Toast.LENGTH_SHORT).show();
}else if(TextUtils.isEmpty(phone)){
Toast.makeText(RegisterActivity.this, "phone is empty ", Toast.LENGTH_SHORT).show();
}else if(TextUtils.isEmpty(password)){
Toast.makeText(RegisterActivity.this, "password is empty ", Toast.LENGTH_SHORT).show();
}else {
validationAccount(name,phone,password);
}
}
private void validationAccount(String name, String phone, String password) {
progressDialog.setTitle("Creation");
progressDialog.setMessage("wait for register your account ....");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
DatabaseReference dataReference = FirebaseDatabase.getInstance().getReference();
dataReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if(!(snapshot.child("Users").child(phone)).exists()){
HashMap<String,Object> map = new HashMap<>();
map.put("name", name);
map.put("phone", phone);
map.put("password", password);
dataReference.child("Users").child(phone).updateChildren(map).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
progressDialog.dismiss();
Toast.makeText(RegisterActivity.this, " Congratulation, Account is created", Toast.LENGTH_LONG).show();
startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
}else {
progressDialog.dismiss();
Toast.makeText(RegisterActivity.this, " Network error", Toast.LENGTH_LONG).show();
startActivity(new Intent(RegisterActivity.this, MainActivity.class));
}
}
});
}else{
progressDialog.dismiss();
Toast.makeText(RegisterActivity.this, "this "+ phone+" is already exists", Toast.LENGTH_LONG).show();
startActivity(new Intent(RegisterActivity.this,MainActivity.class));
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
progressDialog.dismiss();
}
});
}
}
|
package service.impl;
import com.google.common.util.concurrent.SettableFuture;
import service.PriceService;
import service.domain.Price;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Future;
/**
* Created by i303874 on 3/20/15.
*/
public class PriceServiceImpl implements PriceService {
@Override
public Future<List<Price>> get(SettableFuture<List<Price>> result, String id) {
result.set(Arrays.asList(new Price[]{
new Price(UUID.randomUUID().toString(), "EUR", new BigDecimal(123))
}));
return result;
}
}
|
package com.zxhy.xjl.rna.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zxhy.xjl.rna.business.RealNameAuthTask;
import com.zxhy.xjl.rna.mapper.RealNameAuthMapper;
import com.zxhy.xjl.rna.model.Admin;
import com.zxhy.xjl.rna.model.ManualAudit;
import com.zxhy.xjl.rna.model.RealNameAuth;
import com.zxhy.xjl.rna.service.RealNameAuthService;
@Service("realNameAuthService")
public class RealNameAuthServiceImpl implements RealNameAuthService {
@Autowired
private RealNameAuthMapper mapper;
public void register(String phone, String passwd) {
RealNameAuth realNameAuth = new RealNameAuth();
realNameAuth.setPhone(phone);
realNameAuth.setPasswd(passwd);
mapper.save(realNameAuth);
}
public void updatePhoto(String phone, String photoUrl){
RealNameAuth realNameAuth = new RealNameAuth();
realNameAuth.setPhone(phone);
realNameAuth.setIdPhotoUrl(photoUrl);
this.mapper.updatePhoto(realNameAuth);
}
public void updateFace(String phone, String faceUrl) {
RealNameAuth realNameAuth = new RealNameAuth();
realNameAuth.setPhone(phone);
realNameAuth.setFaceUrl(faceUrl);
this.mapper.updateFace(realNameAuth);
}
public void delete(String phone) {
this.mapper.delete(phone);
}
public RealNameAuth findByPhone(String phone) {
return this.mapper.findByPhone(phone);
}
@Override
public void updateRealName(String phone, String idCode, String idName) {
RealNameAuth realNameAuth = new RealNameAuth();
realNameAuth.setPhone(phone);
realNameAuth.setIdCode(idCode);
realNameAuth.setIdName(idName);
this.mapper.updateRealName(realNameAuth);
}
@Override
public RealNameAuthTask getRegisterLinkByPhone(String phone) {
return this.mapper.getRegisterLinkByPhone(phone);
}
@Override
public Admin adminLogin(String accountNumber) {
return this.mapper.adminLogin(accountNumber);
}
@Override
public void updatePassword(String phone, String password) {
RealNameAuth realNameAuth = new RealNameAuth();
realNameAuth.setPhone(phone);
realNameAuth.setPasswd(password);
this.mapper.updatePassword(realNameAuth);
}
@Override
public List<ManualAudit> manualAudit(String processname) {
if(processname.equals("1")){
processname="审核中";
}
if(processname.equals("2")){
processname="审核通过";
}
if(processname.equals("3")){
processname="审核不通过";
}
if(null!=this.mapper.manualAudit(processname)){
return this.mapper.manualAudit(processname);
}
return null;
}
@Override
public void manualAuditState(String phone, String processname) {
if(processname.equals("yes")){
processname="审核通过";
}
if(processname.equals("no")){
processname="审核不通过";
}
ManualAudit manualAudit=new ManualAudit();
manualAudit.setPhone(phone);
manualAudit.setProcessname(processname);
this.mapper.updateManualAuditState(manualAudit);
}
}
|
package com.isteel.myfaceit.data.remote;
import com.isteel.myfaceit.data.model.ResponseGame;
import com.isteel.myfaceit.data.model.ResponseMatch;
import com.isteel.myfaceit.data.model.ResponsePlayer;
import io.reactivex.Single;
public interface ApiService {
Single<ResponsePlayer> getPlayerByNick(String query, String game);
Single<ResponseGame> getGames();
Single<ResponseMatch> getRecentMatches(String id);
Single<ResponseMatch> getRecentMatchesStats(String id);
Single<ResponseGame.Csgo> getStats(String player_id, String game);
Single<ResponsePlayer.Player> getPlayerProfile(String id);
Single<ResponsePlayer> getTop(String game, String region);
ApiHeader getApiHeader();
}
|
package com.hfjy.framework.common.util;
import java.util.ArrayList;
public class StringUtils {
public static boolean isEmpty(String string) {
return string == null || string.trim().length() < 1;
}
public static boolean isEmpty(Object object) {
return null == object || isEmpty(object + "");
}
public static boolean isNotEmpty(String string) {
return string != null && string.trim().length() > 0;
}
public static boolean isNotEmpty(Object object) {
return object != null && object.toString().length() > 0;
}
public static boolean isNotEmpty(Object[] object) {
return object != null && object.length > 0;
}
public static String unite(Object... values) {
if (values == null) {
return "";
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < values.length; i++) {
sb.append(values[i]);
}
return sb.toString();
}
/**
* @author chumingqiang
* @date 2014年5月6日 下午1:58:03
* @version V1.0
* @param strValue
* @return 字符串长度
*/
public static int length(String strValue) {
if (strValue == null) {
return 0;
}
return strValue.length();
}
/**
* @author chumingqiang
* @date 2014年5月6日 下午1:58:35
* @version V1.0
* @param strValue1
* @param strValue2
* @param bIgnoreCase
* 是否忽略大小写
* @return
*/
public static int compare(String strValue1, String strValue2, boolean bIgnoreCase) {
if (strValue1 == null || strValue2 == null) {
return -1;
}
if (bIgnoreCase) {
return strValue1.compareToIgnoreCase(strValue2);
} else {
return strValue1.compareTo(strValue2);
}
}
/**
* 通过字符拆分字符串
*
* @author chumingqiang
* @date 2014年5月6日 下午2:00:32
* @version V1.0
* @param strValue
* @param chSeperator
* @return
*/
public static String[] split(String strValue, char chSeperator) {
if (length(strValue) == 0)
return null;
ArrayList<String> arrList = new ArrayList<String>();
while (true) {
int nPos = strValue.indexOf(chSeperator);
if (nPos != -1) {
String strPartA = strValue.substring(0, nPos);
arrList.add(strPartA);
strValue = strValue.substring(nPos + 1);
} else {
arrList.add(strValue);
break;
}
}
String[] strList = new String[arrList.size()];
arrList.toArray(strList);
return strList;
}
/**
* 取左边空格
*
* @author chumingqiang
* @date 2014年5月6日 下午2:01:05
* @version V1.0
* @param strValue
* @return
*/
public static String trimLeft(String strValue) {
return trimLeft(strValue, ' ');
}
/**
* 去右边指定字符
*
* @author chumingqiang
* @date 2014年5月6日 下午2:01:19
* @version V1.0
* @param strValue
* @param ch
* @return
*/
public static String trimLeft(String strValue, char ch) {
while (strValue.length() > 0) {
if (strValue.charAt(0) == ch) {
strValue = strValue.substring(1);
} else
break;
}
return strValue;
}
/**
* 把第一个字母变成大写
*
* @author chumingqiang
* @date 2014年5月6日 下午2:06:20
* @version V1.0
* @param strValue
* @return
*/
public static String makeStrFirstToUp(String strValue) {
char[] tempArray = strValue.toCharArray();
tempArray[0] = Character.toUpperCase(tempArray[0]);
return new String(tempArray);
}
/**
* 把第一个字母变成小写
*
* @author chumingqiang
* @date 2014年5月6日 下午2:06:50
* @version V1.0
* @param strValue
* @return
*/
public static String makeStrFirstToLower(String strValue) {
char[] tempArray = strValue.toCharArray();
tempArray[0] = Character.toLowerCase(tempArray[0]);
return new String(tempArray);
}
/**
* 截取字符串前段部分
*
* @author cmq
* @date 2014年12月30日 下午4:54:59
* @throws
* @param strValue
* @param ch
*/
public static String substringBefore(String strValue, String ch) {
return strValue.substring(0, strValue.indexOf(ch));
}
/**
* 截取字符串后段部分
*
* @author cmq
* @date 2014年12月30日 下午4:55:23
* @throws
* @param strValue
* @param ch
* @return
*/
public static String substringAfter(String strValue, String ch) {
return strValue.substring(strValue.indexOf(ch) + 1);
}
/**
* 比较字符串忽略大小写
*
* @author cmq
* @date 2014年12月30日 下午4:59:09
* @throws
* @param strValue1
* @param strValue2
* @return
*/
public static boolean equalsIgnoreCase(String strValue1, String strValue2) {
if (strValue1 == null || strValue2 == null) {
return false;
} else {
return strValue1.equalsIgnoreCase(strValue2);
}
}
/**
* 把中文转成Unicode码
*
* @param str
* @return
*/
public static String chinaToUnicode(String str) {
String result = "";
for (int i = 0; i < str.length(); i++) {
int chr1 = (char) str.charAt(i);
if (chr1 >= 19968 && chr1 <= 171941) {// 汉字范围 \u4e00-\u9fa5 (中文)
result += "\\u" + Integer.toHexString(chr1);
} else {
result += str.charAt(i);
}
}
return result;
}
/**
* 判断是否为中文字符
*
* @param c
* @return
*/
public static boolean isChinese(char c) {
Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
return true;
}
return false;
}
public static float getSimilarityRatio(String thisString, String thatString) {
return 1 - (float) compare(thisString, thatString) / Math.max(thisString.length(), thatString.length());
}
private static int compare(String thisString, String thatString) {
int n = thisString.length();
int m = thatString.length();
if (n == 0) {
return m;
}
if (m == 0) {
return n;
}
int[][] ints = new int[n + 1][m + 1];
int i;
for (i = 0; i <= n; i++) {
ints[i][0] = i;
}
int j;
for (j = 0; j <= m; j++) {
ints[0][j] = j;
}
int temp;
for (i = 1; i <= n; i++) {
char a = thisString.charAt(i - 1);
for (j = 1; j <= m; j++) {
char b = thatString.charAt(j - 1);
if (a == b) {
temp = 0;
} else {
temp = 1;
}
int one = ints[i - 1][j] + 1;
int two = ints[i][j - 1] + 1;
int three = ints[i - 1][j - 1] + temp;
ints[i][j] = (one = one < two ? one : two) < three ? one : three;
}
}
return ints[n][m];
}
/**
* @param thisString 当前的字符串,中间以regex规则分割 不支持有些特殊的分隔符
* @param regex 字符串截取的规则
* @param extraItem 要去除的多余重复的元素
* @return
*/
public static String removeStrExtraItems(String thisString,String regex,String extraItem){
StringBuffer versionNum=new StringBuffer();
String[] strs;
if (regex.endsWith(".")) {
strs = thisString.split("\\"+regex);
}else {
strs = thisString.split(regex);
}
for (String str : strs) {
if (str.startsWith(extraItem)) {
char ch = str.charAt(1);
versionNum.append(regex).append(ch);
}else {
versionNum.append(regex).append(str);
}
}
return versionNum.toString().substring(1);
}
}
|
package org.valdi.entities.disguise;
import java.util.Locale;
import org.valdi.entities.management.VersionHelper;
/**
* Represents a disguise as a boat.
*
* @since 5.7.1
* @author RobinGrether
*/
public class BoatDisguise extends ObjectDisguise {
private BoatType boatType;
/**
* @since 5.7.1
*/
public BoatDisguise() {
this(BoatType.OAK);
}
/**
* @since 5.7.1
* @param boatType change the wood type of the boat (works in Minecraft 1.9+ only)
*/
public BoatDisguise(BoatType boatType) {
super(DisguiseType.BOAT);
this.boatType = boatType;
}
/**
* @since 5.7.1
*/
public BoatType getBoatType() {
return boatType;
}
/**
* @since 5.7.1
* @param boatType change the wood type of the boat (works in Minecraft 1.9+ only)
*/
public void setBoatType(BoatType boatType) {
this.boatType = boatType;
}
/**
* {@inheritDoc}
*/
public String toString() {
return String.format("%s; %s", super.toString(), boatType.name().toLowerCase(Locale.ENGLISH).replace('_', '-'));
}
/**
* Different types of wood a boat can be made out of.
*
* @since 5.7.1
* @author RobinGrether
*/
public enum BoatType {
OAK, SPRUCE, BIRCH, JUNGLE, ACACIA, DARK_OAK;
}
static {
if(VersionHelper.require1_9()) {
for(BoatType boatType : BoatType.values()) {
Subtypes.registerSubtype(BoatDisguise.class, "setBoatType", boatType, boatType.name().toLowerCase(Locale.ENGLISH).replace('_', '-'));
}
}
}
}
|
package com.example.dolly0920.item5.carstore;
import com.example.dolly0920.item5.Car;
import com.example.dolly0920.item5.CarStore;
import com.example.dolly0920.item5.carfactory.Buggati.BuggatiGeneralClassCar;
import com.example.dolly0920.item5.carfactory.Buggati.BuggatiPremiumClassCar;
public class BuggatiCarStore extends CarStore {
@Override
public Car createCar(String type) { // custom factory
if (type.equals("premium")) {
return new BuggatiPremiumClassCar();
} else if (type.equals("general")) {
return new BuggatiGeneralClassCar();
}
return null;
}
}
|
package com.superoback.controller;
import com.superoback.dto.TaskDTO;
import com.superoback.service.TaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(value = "/task")
@CrossOrigin(origins = "*")
@Api(tags = "Task endpoints")
public class TaskController {
@Autowired
private TaskService taskService;
@GetMapping
@ApiOperation("Returns task list")
public ResponseEntity<?> findAll(){
return ResponseEntity.ok(taskService.findAll());
}
@PostMapping
@ApiOperation("Save task to database")
public TaskDTO save(@RequestBody TaskDTO task) {
return taskService.save(task.toModel());
}
@PutMapping
@ApiOperation("Update task to database")
public TaskDTO update(@RequestBody TaskDTO task) {
return taskService.save(task.toModel());
}
@GetMapping("/{id}")
@ApiOperation("Find task in the database")
public ResponseEntity<?> findOne(@PathVariable(value = "id") long id){
return ResponseEntity.ok(taskService.findOne(id));
}
@DeleteMapping("/{id}")
@ApiOperation("Delete task from database")
public void delete(@PathVariable(value = "id") long id) {
taskService.delete(id);
}
}
|
package com.grocery.codenicely.vegworld_new.products.view;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.crashlytics.android.answers.AddToCartEvent;
import com.crashlytics.android.answers.Answers;
import com.grocery.codenicely.vegworld_new.R;
import com.grocery.codenicely.vegworld_new.cart.view.CartFragment;
//import com.grocery.codenicely.vegworld_new.helper.NetworkUtils;
import com.grocery.codenicely.vegworld_new.helper.Keys;
import com.grocery.codenicely.vegworld_new.helper.SharedPrefs;
import com.grocery.codenicely.vegworld_new.home.view.HomeActivity;
import com.grocery.codenicely.vegworld_new.products.model.ProductSizeData;
import com.grocery.codenicely.vegworld_new.products.provider.RetrofitProductListDetailsProvider;
import com.grocery.codenicely.vegworld_new.products.provider.RetrofitProductQuantityUpdator;
import com.grocery.codenicely.vegworld_new.products.model.ProductListDetails;
import com.grocery.codenicely.vegworld_new.products.model.ProductQuantityUpdateData;
import com.grocery.codenicely.vegworld_new.products.model.ProductSizeUpdateData;
import com.grocery.codenicely.vegworld_new.products.presenter.AddSubProductPresenter;
import com.grocery.codenicely.vegworld_new.products.presenter.AddSubProductPresenterImpl;
import com.grocery.codenicely.vegworld_new.products.presenter.ProductListPresenterImplementation;
import com.grocery.codenicely.vegworld_new.products.presenter.ProductsListPresenter;
import com.grocery.codenicely.vegworld_new.sub_category.view.SubCategoryFragment;
import java.math.BigDecimal;
import java.util.Currency;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Activities that contain this fragment must implement the
* {@link ProductsListFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link ProductsListFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ProductsListFragment extends Fragment implements ProductListView {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String SUB_CATEGORY_ID = "subCategoryId";
private static final String SUB_CATEGORY_NAME = "subCategoryName";
@BindView(R.id.recyclerView)
RecyclerView recyclerView;
@BindView(R.id.progressBar)
ProgressBar progressBar;
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.layout_not_available)
LinearLayout layout_not_available;
@BindView(R.id.checkout_layout)
LinearLayout checkout_layout;
@BindView(R.id.total_bill)
TextView total_bill;
@BindView(R.id.number_of_items)
TextView cart_count;
private SearchView searchView;
private Context context;
// TODO: Rename and change types of parameters
private int subCategoryId = -1;
private ProductsRecyclerAdapter productsRecyclerAdapter;
private OnFragmentInteractionListener mListener;
private ProductsListPresenter productsListPresenter;
private ProgressDialog progressDialog;
private SharedPrefs sharedPrefs;
private AddSubProductPresenter addSubProductPresenter;
private String subCategoryName;
public ProductsListFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @return A new instance of fragment ProductsListFragment.
*/
// TODO: Rename and change types and number of parameters
public static ProductsListFragment newInstance(int subCategoryId, String subCategoryName) {
ProductsListFragment fragment = new ProductsListFragment();
Bundle args = new Bundle();
args.putInt(SUB_CATEGORY_ID, subCategoryId);
args.putString(SUB_CATEGORY_NAME, subCategoryName);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
subCategoryId = getArguments().getInt(SUB_CATEGORY_ID,-1);
subCategoryName = getArguments().getString(SUB_CATEGORY_NAME,"");
}
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_products, container, false);
ButterKnife.bind(this, view);
context = getContext();
/*if (!NetworkUtils.isNetworkAvailable(context)) {
((HomeActivity) getActivity()).addFragment(new NoInternetConnectionFragment(), "No Connection");
}*/
sharedPrefs = new SharedPrefs(context);
initialize();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().onBackPressed();
}
});
checkout_layout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (getActivity() instanceof HomeActivity) {
((HomeActivity) context).addFragment(new CartFragment(), "Cart");
((HomeActivity) context).getSupportActionBar().hide();
}
}
});
String search_query = "";
try {
Bundle bundle = this.getArguments();
search_query = bundle.getString(Keys.KEY_SEARCH_QUERY);
} catch (Exception e) {
e.printStackTrace();
}
if (subCategoryId == -1) {
toolbar.setVisibility(View.VISIBLE);
productsListPresenter.requestProductList(search_query, sharedPrefs.getAccessToken(), subCategoryId);
checkout_layout.setVisibility(View.VISIBLE);
} else {
toolbar.setVisibility(View.GONE);
productsListPresenter.requestProductList(search_query, sharedPrefs.getAccessToken(), subCategoryId);
checkout_layout.setVisibility(View.GONE);
}
return view;
}
private void initialize() {
productsListPresenter = new ProductListPresenterImplementation(this, new RetrofitProductListDetailsProvider());
addSubProductPresenter = new AddSubProductPresenterImpl(this, new RetrofitProductQuantityUpdator());
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 3);
recyclerView.setLayoutManager(gridLayoutManager);
progressDialog = new ProgressDialog(context);
// RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(TrackOrder.this);
// recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
productsRecyclerAdapter = new ProductsRecyclerAdapter(context, this);
/*productsRecyclerAdapter = new ProductsRecyclerAdapter(context, new ListItemListener() {
@Override
public void addButtonListener(View v, int product_id, int product_quantity, int position) {
requestProductQuantityUpdate(v, sharedPrefs.getAccessToken(), product_id, product_quantity, 1, position);
}
@Override
public void minusButtonListener(View v, int product_id, int product_quantity, int position) {
requestProductQuantityUpdate(v, sharedPrefs.getAccessToken(), product_id, product_quantity, -1, position);
}
}, this);*/
recyclerView.setAdapter(productsRecyclerAdapter);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
/*
dataPasser = (OnDataPass) context;
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
*/
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
if (productsListPresenter != null) {
productsListPresenter.onDestroy();
//Keys.product_position=-1;
}
if (addSubProductPresenter != null) {
addSubProductPresenter.onDestroy();
}
onDestroy();
}
@Override
public void showMessage(String message) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
@Override
public void showProgressbar(boolean show) {
if (show) {
progressBar.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.GONE);
} else {
progressBar.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
}
}
@Override
public void showProgressDialog(boolean show, String message) {
if (show) {
progressDialog.setTitle(message);
progressDialog.setCancelable(false);
progressDialog.show();
} else {
progressDialog.cancel();
}
}
@Override
public void setProductData(List<ProductListDetails> productListDetails) {
if (productListDetails.size() == 0) {
layout_not_available.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.INVISIBLE);
// return;
} else {
layout_not_available.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
}
productsRecyclerAdapter.setData(productListDetails);
if(Keys.product_position!=-1&&Keys.sub_category_id!=-1){
if(Keys.sub_category_id==subCategoryId){
recyclerView.smoothScrollToPosition(Keys.product_position);
}//recyclerView.scrollToPosition(Keys.product_position);
}
productsRecyclerAdapter.notifyDataSetChanged();
}
@Override
public void updateAdapter(ProductQuantityUpdateData productQuantityUpdateData, int operation) {
/*
SubCategoryFragment subCategoryFragment = (SubCategoryFragment) getChildFragmentManager()
.findFragmentByTag("SubCategoryFragment");
*/
if (getParentFragment() instanceof SubCategoryFragment) {
((SubCategoryFragment) getParentFragment()).updateCartLayout(productQuantityUpdateData.getCart_count(), productQuantityUpdateData.getTotal_discounted());
} else {
total_bill.setText("₹ ");
total_bill.append(String.valueOf(String.valueOf(productQuantityUpdateData.getTotal_discounted())));
this.cart_count.setText(String.valueOf(productQuantityUpdateData.getCart_count()));
this.cart_count.append(" Items");
}
/*
if (subCategoryFragment != null) {
subCategoryFragment.updateCartLayout(productQuantityUpdateData.getCart_count(),productQuantityUpdateData.getTotal());
showMessage("Success");
}else{
showMessage("Failed");
}
*/
productsRecyclerAdapter.updateQuantityData(productQuantityUpdateData, operation);
productsRecyclerAdapter.notifyItemChanged(productQuantityUpdateData.getPosition());
productsRecyclerAdapter.notifyDataSetChanged();
}
@Override
public void updateAdapter(ProductSizeUpdateData productSizeUpdateData) {
if (getParentFragment() instanceof SubCategoryFragment) {
((SubCategoryFragment) getParentFragment()).updateCartLayout(
productSizeUpdateData.getCart_count(),
productSizeUpdateData.getTotal_discounted());
} else {
total_bill.setText("₹ ");
total_bill.append(String.valueOf(String.valueOf(productSizeUpdateData.getTotal_discounted())));
this.cart_count.setText(String.valueOf(productSizeUpdateData.getCart_count()));
this.cart_count.append(" Items");
}
productsRecyclerAdapter.updateSizeData(productSizeUpdateData);
productsRecyclerAdapter.notifyItemChanged(productSizeUpdateData.getPosition());
productsRecyclerAdapter.notifyDataSetChanged();
}
protected void requestProductQuantityUpdate(View v, String access_token, int product_id, int product_size_id, int product_quantity, int update_type, int position) {
addSubProductPresenter.requestProductUpdate(v, access_token, product_id, product_size_id, product_quantity, update_type, position);
}
protected void requestProductSizeChange(String access_token, int product_id, int product_size_id, int position) {
addSubProductPresenter.requestProductSizeUpdate(access_token, product_id, product_size_id, position);
}
public void answersLog(ProductListDetails productListDetails) {
List<ProductSizeData> productSizeDataList = productListDetails.getProduct_size_list();
ProductSizeData productSizeData = null;
if (productSizeDataList.size() == 1) {
productSizeData = productSizeDataList.get(0);
} else if (productSizeDataList.size() > 1) {
for (int i = 0; i < productSizeDataList.size(); i++) {
ProductSizeData productSizeDataLocal = productSizeDataList.get(i);
if (productSizeDataLocal.getProduct_size_id() == productListDetails.getProduct_size_id()) {
productSizeData = productSizeDataLocal;
}
}
}
if (productSizeData != null) {
Answers.getInstance().logAddToCart(new AddToCartEvent()
.putItemPrice(BigDecimal.valueOf(productSizeData.getDiscounted_price()))
.putCurrency(Currency.getInstance("INR"))
.putItemName(productListDetails.getName())
.putItemType(subCategoryName)
.putItemId("product_id-" + productListDetails.getProduct_id() + " size_id-" + productSizeData.getProduct_size_id()));
}
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Add your menu entries here
super.onCreateOptionsMenu(menu, inflater);
toolbar.inflateMenu(R.menu.search_menu);
final MenuItem myActionMenuItem = toolbar.getMenu().findItem(R.id.action_search);
// Associate searchable configuration with the SearchView
SearchManager searchManager =
(SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) myActionMenuItem.getActionView();
SearchView.SearchAutoComplete theTextArea = (SearchView.SearchAutoComplete) searchView.findViewById(R.id.search_src_text);
theTextArea.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));//or any color that you want
theTextArea.setHintTextColor(ContextCompat.getColor(context, R.color.dullWhite));
searchView.setQueryHint("Search Products");
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getActivity().getComponentName()));
searchView.setIconifiedByDefault(false);
// searchView.requestFocus();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String s) {
productsListPresenter.requestProductList(s, sharedPrefs.getAccessToken(), -1);
return false;
}
});
}
// MenuItem searchItem = toolbar.getMenu().findItem(R.id.action_search);
/* inflater.inflate(R.menu.search_menu, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
*/
/* searchItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(context, "Search", Toast.LENGTH_SHORT).show();
return true;
}
});*/
// }
/*
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.search_menu, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
searchItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(context, "Search", Toast.LENGTH_SHORT).show();
return false;
}
});
super.onCreateOptionsMenu(menu, inflater);
}
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_search:
return true;
default:
break;
}
return super.onOptionsItemSelected(item);
}
private void hideKeyboard() {
View view = getActivity().getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
}
|
package com.pointinside.android.api.nav;
import android.location.Location;
import android.net.Uri;
import com.pointinside.android.api.net.JSONWebRequester;
import com.pointinside.android.api.net.JSONWebRequester.RestResponseException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Route
{
private float mDistance;
private RouteEndpoint mEnd;
private boolean mIsDistanceCalculated;
private ArrayList<RoutePoint> mPoints;
private RouteEndpoint mStart;
private String mVenueUUID;
private int mWalkingTimeInMinutes;
private static void addEndpointToRequest(JSONObject paramJSONObject, String paramString, RouteEndpoint paramRouteEndpoint)
throws JSONException
{
if (paramRouteEndpoint.placeUUID != null)
{
paramJSONObject.put(paramString, paramRouteEndpoint.placeUUID);
return;
}
if (paramRouteEndpoint.point != null)
{
paramJSONObject.put(paramString, "");
JSONObject localJSONObject = new JSONObject();
RoutePoint localRoutePoint = paramRouteEndpoint.point;
localJSONObject.put("latitude", String.valueOf(localRoutePoint.latitude));
localJSONObject.put("longitude", String.valueOf(localRoutePoint.longitude));
localJSONObject.put("zoneUuid", localRoutePoint.zoneUUID);
StringBuilder localStringBuilder = new StringBuilder();
localStringBuilder.append(Character.toUpperCase(paramString.charAt(0)));
localStringBuilder.append(paramString.substring(1));
localStringBuilder.append("ArbitraryPoint");
paramJSONObject.put(localStringBuilder.toString(), localJSONObject);
return;
}
throw new IllegalArgumentException("Invalid endpoint for " + paramString);
}
public static Route calculate(String paramString, RouteEndpoint paramRouteEndpoint1, RouteEndpoint paramRouteEndpoint2)
throws JSONWebRequester.RestResponseException
{
HttpPost localHttpPost = getRouteRequest(paramString, paramRouteEndpoint1, paramRouteEndpoint2);
JSONObject localJSONObject1 = RouteAPI.getWebRequester().execute(localHttpPost);
if ((localJSONObject1 == null) || (localJSONObject1.length() == 0)) {
throw new NoRouteException("No route provided by server");
}
Route localRoute = new Route();
localRoute.mVenueUUID = paramString;
JSONObject localJSONObject2;
JSONArray localJSONArray;
int i;
try
{
localJSONObject2 = localJSONObject1.getJSONArray("navigation").getJSONObject(0).getJSONArray("subroutes").getJSONArray(0).getJSONObject(0);
localJSONArray = localJSONObject2.getJSONArray("points").getJSONArray(0);
i = localJSONArray.length();
if (i == 0) {
throw new NoRouteException("Empty route provided by server");
}
ArrayList localArrayList = new ArrayList();
for (int j = 0;; j++)
{
if (j >= i)
{
localRoute.mStart = RouteEndpoint.fromRoutePoint((RoutePoint)localArrayList.get(0), paramRouteEndpoint1.placeUUID);
localRoute.mEnd = RouteEndpoint.fromRoutePoint((RoutePoint)localArrayList.get(i - 1), paramRouteEndpoint2.placeUUID);
localRoute.mPoints = localArrayList;
localRoute.mWalkingTimeInMinutes = localJSONObject2.getJSONArray("time").getInt(0);
return localRoute;
}
localArrayList.add(new RoutePoint(localJSONArray.getJSONObject(j)));
}
}
catch (JSONException localJSONException)
{
throw new JSONWebRequester.RestResponseException(localJSONException);
}
}
public static Route calculate(String paramString1, String paramString2, String paramString3)
throws JSONWebRequester.RestResponseException
{
return calculate(paramString1, RouteEndpoint.fromPlaceUUID(paramString2), RouteEndpoint.fromPlaceUUID(paramString3));
}
private float calculateDistance()
{
int i = getPointsCount();
float f = 0.0F;
RoutePoint localObject = null;
for (int j = 0;; j++)
{
if (j >= i) {
return f;
}
RoutePoint localRoutePoint = getPoint(j);
if (localObject != null)
{
float[] arrayOfFloat = new float[1];
Location.distanceBetween(localObject.getLatitude(), localObject.getLongitude(), localRoutePoint.getLatitude(), localRoutePoint.getLongitude(), arrayOfFloat);
f += arrayOfFloat[0];
}
localObject = localRoutePoint;
}
}
private static HttpPost getRouteRequest(String paramString, RouteEndpoint paramRouteEndpoint1, RouteEndpoint paramRouteEndpoint2)
{
try
{
HttpPost localHttpPost = new HttpPost(RouteAPI.getMethodUri("jsonroute").toString());
JSONObject localJSONObject1 = new JSONObject();
JSONObject localJSONObject2 = new JSONObject();
localJSONObject2.put("venue", paramString);
addEndpointToRequest(localJSONObject2, "start", paramRouteEndpoint1);
addEndpointToRequest(localJSONObject2, "end", paramRouteEndpoint2);
localJSONObject1.put("navigation", localJSONObject2);
StringEntity localStringEntity = new StringEntity(localJSONObject1.toString());
localStringEntity.setContentType("application/json");
localHttpPost.setEntity(localStringEntity);
return localHttpPost;
}
catch (JSONException localJSONException)
{
throw new AssertionError();
}
catch (UnsupportedEncodingException localUnsupportedEncodingException)
{
throw new AssertionError();
}
}
public float getDistance()
{
if (!this.mIsDistanceCalculated)
{
this.mDistance = calculateDistance();
this.mIsDistanceCalculated = true;
}
return this.mDistance;
}
public RouteEndpoint getEnd()
{
return this.mEnd;
}
public String getEndPlaceUUID()
{
return this.mEnd.placeUUID;
}
public RoutePoint getPoint(int paramInt)
{
return (RoutePoint)this.mPoints.get(paramInt);
}
public int getPointsCount()
{
return this.mPoints.size();
}
public RouteEndpoint getStart()
{
return this.mStart;
}
public String getStartPlaceUUID()
{
return this.mStart.placeUUID;
}
public String getVenueUUID()
{
return this.mVenueUUID;
}
public int getWalkingTimeInMinutes()
{
return this.mWalkingTimeInMinutes;
}
public static class NoRouteException
extends JSONWebRequester.RestResponseException
{
public NoRouteException(String paramString)
{
super(paramString);
}
}
public static class RouteEndpoint
{
public final String placeUUID;
public final Route.RoutePoint point;
private RouteEndpoint(Route.RoutePoint paramRoutePoint, String paramString)
{
this.point = paramRoutePoint;
this.placeUUID = paramString;
}
public static RouteEndpoint fromArbitraryLocation(String paramString, double paramDouble1, double paramDouble2)
{
return new RouteEndpoint(new Route.RoutePoint(paramDouble1, paramDouble2, null, 0, 0, paramString), null);
}
public static RouteEndpoint fromPlaceUUID(String paramString)
{
return new RouteEndpoint(null, paramString);
}
private static RouteEndpoint fromRoutePoint(Route.RoutePoint paramRoutePoint, String paramString)
{
return new RouteEndpoint(paramRoutePoint, paramString);
}
public String toString()
{
if (this.placeUUID != null) {
return this.placeUUID;
}
if (this.point != null) {
return this.point.toString();
}
return "{}";
}
}
public static class RoutePoint
{
private final double latitude;
private final double longitude;
private final String name;
private final int pixelX;
private final int pixelY;
private final String zoneUUID;
private RoutePoint(double paramDouble1, double paramDouble2, String paramString1, int paramInt1, int paramInt2, String paramString2)
{
this.latitude = paramDouble1;
this.longitude = paramDouble2;
this.name = paramString1;
this.pixelX = paramInt1;
this.pixelY = paramInt2;
this.zoneUUID = paramString2;
}
private RoutePoint(RoutePoint paramRoutePoint)
{
this(paramRoutePoint.latitude, paramRoutePoint.longitude, paramRoutePoint.name, paramRoutePoint.pixelX, paramRoutePoint.pixelY, paramRoutePoint.zoneUUID);
}
private RoutePoint(JSONObject paramJSONObject)
throws JSONException
{
this.latitude = paramJSONObject.getJSONArray("lat").getDouble(0);
this.longitude = paramJSONObject.getJSONArray("lon").getDouble(0);
this.name = paramJSONObject.getJSONArray("name").getString(0);
this.pixelX = paramJSONObject.getJSONArray("pixelX").getInt(0);
this.pixelY = paramJSONObject.getJSONArray("pixelY").getInt(0);
this.zoneUUID = paramJSONObject.getJSONArray("zoneUuid").getString(0);
}
public double getLatitude()
{
return this.latitude;
}
public double getLongitude()
{
return this.longitude;
}
public String getName()
{
return this.name;
}
public int getPixelX()
{
return this.pixelX;
}
public int getPixelY()
{
return this.pixelY;
}
public String getZoneUUID()
{
return this.zoneUUID;
}
public String toString()
{
StringBuilder localStringBuilder = new StringBuilder();
localStringBuilder.append('{');
localStringBuilder.append("latitude=").append(this.latitude).append(';');
localStringBuilder.append("longitude=").append(this.longitude).append(';');
localStringBuilder.append("name=").append(this.name).append(';');
localStringBuilder.append("pixelX=").append(this.pixelX).append(';');
localStringBuilder.append("pixelY=").append(this.pixelY).append(';');
localStringBuilder.append("zoneUUID=").append(this.zoneUUID);
localStringBuilder.append('}');
return localStringBuilder.toString();
}
}
}
/* Location: D:\xinghai\dex2jar\classes-dex2jar.jar
* Qualified Name: com.pointinside.android.api.nav.Route
* JD-Core Version: 0.7.0.1
*/
|
package edu.cuny.csi.csc330.discordbot.bot;
public class Unit {
private int name; // Unit name/ID
private String faction; // Faction the unit is apart of
private int factionID; // Unit's faction ID
private int position1; // Position 1 of the unit
private int position2; // Position 2 of the unit
private Long playerID; // Identifies what player the unit belongs to
public Unit(String faction, int factionID, Long playerID) {
this.faction = faction;
this.factionID = factionID;
this.playerID = playerID;
generateCodeName();
if (factionID == 1) { // Hawks start at (0,0)
this.position1 = 1;
this.position2 = 1;
} else if (factionID == 2) { // Owls start at (5,5)
this.position1 = 5;
this.position2 = 5;
} else if (factionID == 3) { // Root starts at (1,5)
this.position1 = 1;
this.position2 = 5;
} else { // Default
this.position1 = 1;
this.position2 = 1;
}
}
public int getName() {
return name;
}
protected void setName(int name) {
this.name = name;
}
public String getFaction() {
return faction;
}
protected void setFaction(String faction) {
this.faction = faction;
}
public int getFactionID() {
return factionID;
}
protected void setFactionID(int factionID) {
this.factionID = factionID;
}
public int getPosition1() {
return position1;
}
protected void setPosition1(int position1) {
this.position1 = position1;
}
public int getPosition2() {
return position2;
}
protected void setPosition2(int position2) {
this.position2 = position2;
}
public Long getPlayerID() {
return playerID;
}
protected void setPlayerID(Long playerID) {
this.playerID = playerID;
}
/**
*
* Randomly generate a number or code name to identify a unit
*
*/
public void generateCodeName() { // Generate code name for unit
int nameGen = Randomizer.generateInt(1000, 9999); // Generate a number from 1000-9999
this.name = nameGen; // Set Unit name/ID
}
}
|
package simple.textgui;
// follow up for https://www.youtube.com/watch?v=e0X00EoFQbE
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int option;
int number1, number2;
while(true){
System.out.println("Enter your choice. 1: Addition 2. Subtraction 3.Division 4.Multiplication 5. Exit : \n");
option =Integer.parseInt(in.next());
if(option==1){
askForNumbers();
number1 = Integer.parseInt(in.next());
number2 = Integer.parseInt(in.next());
float sum = number1 + number2;
System.out.println("The sum is :" + sum);
}
else if(option == 2){
askForNumbers();
number1 = Integer.parseInt(in.next());
number2 = Integer.parseInt(in.next());
float diff = number1 - number2;
System.out.println("The difference is :" + diff);
}
else if(option == 3){
askForNumbers();
number1 = Integer.parseInt(in.next());
number2 = Integer.parseInt(in.next());
float quotient = number1/number2;
System.out.println("The quotient is :" + quotient);
}
else if(option == 4){
askForNumbers();
number1 = Integer.parseInt(in.next());
number2 = Integer.parseInt(in.next());
float quotient = number1*number2;
System.out.println("The product is :" + quotient);
}else{
break;
}
}
}
public static void askForNumbers(){
System.out.println("Enter 2 numbers:");
}
}
|
package com.d2magicos.carrobluetooth.service;
import android.app.Notification;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import com.d2magicos.carrobluetooth.R;
import com.d2magicos.carrobluetooth.event.UiToastEvent;
import com.d2magicos.carrobluetooth.helper.NotificationHelper;
import com.d2magicos.carrobluetooth.util.Constants;
import org.greenrobot.eventbus.EventBus;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.UUID;
public class MyBluetoothSerialService extends Service {
private static final String TAG = MyBluetoothSerialService.class.getSimpleName();
public static final String KEY_MAC_ADDRESS = "KEY_MAC_ADDRESS";
private static final UUID MY_UUID_SECURE = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static final UUID MY_UUID_INSECURE = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
BluetoothAdapter mAdapter; // Adaptador de nuestro bluetooth
//Begin Hilos
private Handler mHandlerActivity; // Hilo para comunicar el estado de la conexion al hilo principal de activity
private ConnectThread mConnectThread; // Hilo para intentar conectarse
private ConnectedThread mConnectedThread; // Hilo cuando ya se conecto
//End Hilos
private int mState;
private int mNewState;
public static final int STATE_NONE = 0; // we're doing nothing
public static final int STATE_LISTEN = 1; // now listening for incoming connections
public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
public static final int STATE_CONNECTED = 3; // now connected to a remote device
private final IBinder mBinder = new MySerialServiceBinder();
private long statusUpdatePoolInterval = Constants.STATUS_UPDATE_INTERVAL;
@Override
public void onCreate() {
super.onCreate();
mAdapter = BluetoothAdapter.getDefaultAdapter();
mState = STATE_NONE;
mNewState = mState;
if (mAdapter == null) {
EventBus.getDefault().post(new UiToastEvent(getString(R.string.text_bluetooth_adapter_error), true, true));
stopSelf(); //Detener el servicio
} else {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1) {
startForeground(Constants.BLUETOOTH_SERVICE_NOTIFICATION_ID, this.getNotification(null));
}
}
}
private Notification getNotification(String message){
if(message == null) message = getString(R.string.text_bluetooth_service_foreground_message);
return new NotificationCompat.Builder(getApplicationContext(), NotificationHelper.CHANNEL_SERVICE_ID)
.setContentTitle(getString(R.string.text_bluetooth_service))
.setContentText(message)
.setSmallIcon(R.mipmap.ic_launcher)
.setColor(getResources().getColor(R.color.colorPrimary))
.setAutoCancel(true).build();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
this.start();
if (intent != null) {
String deviceAddress = intent.getStringExtra(KEY_MAC_ADDRESS);
if (deviceAddress != null) {
try {
BluetoothDevice device = mAdapter.getRemoteDevice(deviceAddress.toUpperCase());
this.connect(device, true); // Conexion al modulo bluetooth
} catch (IllegalArgumentException e) {
EventBus.getDefault().post(new UiToastEvent(e.getMessage(), true, true));
disconnectService(); // Desconecta el servicio
stopSelf(); // Detiene por completo el servicio
}
}
} else {
EventBus.getDefault().post(new UiToastEvent(getString(R.string.text_unknown_error), true, true));
disconnectService(); // Desconecta el servicio
stopSelf(); // Detiene por completo el servicio
}
return Service.START_NOT_STICKY; //Le indica al servicio cuando se sale de la app se cierre el servicio
}
synchronized void start() {
// Cancel any thread attempting to make a connection
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
// Update UI title
updateUserInterfaceTitle();
}
synchronized void connect(BluetoothDevice device, boolean secure) {
// Cancel any thread attempting to make a connection
if (mState == STATE_CONNECTING) {
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
// Start the thread to connect with the given device
mConnectThread = new ConnectThread(device, secure);
mConnectThread.start();
// Update UI title
updateUserInterfaceTitle();
}
public void disconnectService() {
this.stop();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public synchronized int getState() {
return mState;
}
public class MySerialServiceBinder extends Binder {
public MyBluetoothSerialService getService() {
return MyBluetoothSerialService.this;
}
}
public void setMessageHandler(Handler myServiceMessageHandler) {
this.mHandlerActivity = myServiceMessageHandler;
}
//Crear una conexion como cliente
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
private final String mSocketType;
public ConnectThread(BluetoothDevice device, boolean secure) {
mmDevice = device;
BluetoothSocket tmp = null;
mSocketType = secure ? "Secure" : "Insecure";
try {
if (secure) {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
} else {
tmp = device.createInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE);
}
} catch (IOException | NullPointerException e) {
Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
}
mmSocket = tmp;
mState = STATE_CONNECTING;
}
public void run() {
Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType);
setName("ConnectThread" + mSocketType);
// Cancelamos siempre la busqueda de dispositivos para evitar que relentize la conexion actual
mAdapter.cancelDiscovery();
// Realizamos la conexion al BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect(); //Conexion establecida con el blFuetooth
} catch (IOException | NullPointerException e) {
// Close the socket
try {
mmSocket.close();
} catch (IOException | NullPointerException e2) {
Log.e(TAG, "unable to close() " + mSocketType +" socket during connection failure", e2);
}
connectionFailed();
return;
}
//Reiniciamos el Thread porque hemos terminado con la conexion
synchronized (this) {
mConnectThread = null;
}
// Start the connected thread
connected(mmSocket, mmDevice, mSocketType);
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException | NullPointerException e) {
Log.e(TAG, "close() of connect " + mSocketType + " socket failed", e);
}
}
}
private synchronized void connected(BluetoothSocket socket, BluetoothDevice device, final String socketType) {
// Cancel the thread that completed the connection
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
// Start the thread to manage the connection and perform transmissions
mConnectedThread = new ConnectedThread(socket, socketType);
mConnectedThread.start();
// Enviamos el nombre del dispositivo al cual nos hemos conectado a nuestro activity
if(mHandlerActivity != null){
Message msg = mHandlerActivity.obtainMessage(Constants.MESSAGE_DEVICE_NAME);
Bundle bundle = new Bundle();
bundle.putString(Constants.DEVICE_NAME, device.getName());
msg.setData(bundle);
mHandlerActivity.sendMessage(msg);
}
updateUserInterfaceTitle();
try {
wait(250);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* Este hilo se ejecuta durante una conexión con un dispositivo remoto.
* Maneja todas las transmisiones entrantes y salientes.
*/
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket, String socketType) {
Log.d(TAG, "create ConnectedThread: " + socketType);
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException | NullPointerException e) {
Log.e(TAG, "temp sockets not created", e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
mState = STATE_CONNECTED;
}
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
// Colocar el codigo para escuchar cuando ingresan datos nuevos (InputStream)
}
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer); //Enviamos el dato al arduino
} catch (IOException | NullPointerException e) {
Log.e(TAG, "Exception during write", e);
}
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException | NullPointerException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
synchronized void stop() {
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
mState = STATE_NONE;
updateUserInterfaceTitle();
}
private void connectionFailed() {
// Send a failure message back to the Activity
if(mHandlerActivity != null){
Message msg = mHandlerActivity.obtainMessage(Constants.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(Constants.TOAST, getString(R.string.text_unable_to_connect_to_device));
msg.setData(bundle);
mHandlerActivity.sendMessage(msg);
}
mState = STATE_NONE;
updateUserInterfaceTitle();
this.start();
}
private void connectionLost() {
// Send a failure message back to the Activity
if(mHandlerActivity != null){
Message msg = mHandlerActivity.obtainMessage(Constants.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(Constants.TOAST, getString(R.string.text_device_connection_was_lost));
msg.setData(bundle);
mHandlerActivity.sendMessage(msg);
}
mState = STATE_NONE;
// Update UI title
updateUserInterfaceTitle();
this.start();
}
private void serialWriteBytes(byte[] b) {
ConnectedThread r;
synchronized (this) {
if (mState != STATE_CONNECTED) return;
r = mConnectedThread;
}
r.write(b);
}
public void serialWriteString(String s){
byte buffer[] = s.getBytes();
this.serialWriteBytes(buffer);
Log.d("send_data: ", "caracter enviado " + s);
}
public void serialWriteByte(byte b){
byte[] c = {b};
serialWriteBytes(c);
}
/**
* Actualizamos el estado global del servicio para actualizar el titulo del activity
*/
private synchronized void updateUserInterfaceTitle() {
mState = getState();
mNewState = mState;
//Si el hilo del activity sigue activo le enviamos el estado del Servicio actual
if(mHandlerActivity != null){
mHandlerActivity.obtainMessage(Constants.MESSAGE_STATE_CHANGE, mNewState, -1).sendToTarget();
}
}
public long getStatusUpdatePoolInterval(){
return this.statusUpdatePoolInterval;
}
public void setStatusUpdatePoolInterval(long poolInterval){
this.statusUpdatePoolInterval = poolInterval;
}
}
|
package com.esum.wp.ims.chubuainfo.struts.action;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.esum.appcommon.resource.application.Config;
import com.esum.appcommon.session.SessionMgr;
import com.esum.appframework.exception.ApplicationException;
import com.esum.appframework.struts.action.BaseDelegateAction;
import com.esum.appframework.struts.actionform.BeanUtilForm;
import com.esum.framework.core.management.ManagementException;
import com.esum.imsutil.util.ReloadXTrusAdmin;
import com.esum.wp.ims.chubuainfo.ChubUaInfo;
import com.esum.wp.ims.chubuainfo.service.IChubUaInfoService;
import com.esum.wp.ims.config.XtrusConfig;
import com.esum.wp.ims.tld.XtrusLangTag;
/**
*
* Copyright(c) eSum Technologies, Inc. All rights reserved.
*/
public class ChubUaInfoAction extends BaseDelegateAction {
protected ActionForward doService(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
if (method.equals("other method")) {
/**
*/
return null;
} else if (method.equals("selectPageList")) {
ChubUaInfo chubUaInfo = null;
BeanUtilForm beanUtilForm = (BeanUtilForm)form;
request.removeAttribute("inputObject");
request.removeAttribute("outputObject");
Object inputObject = null;
if (beanUtilForm != null) {
inputObject = beanUtilForm.getBean();
}else {
beanUtilForm = new BeanUtilForm();
}
int itemCountPerPage = Config.getInt("Common", "LIST.COUNT_PER_PAGE");
if(inputObject == null) {
chubUaInfo = new ChubUaInfo();
chubUaInfo.setCurrentPage(new Integer(1));
chubUaInfo.setItemCountPerPage(new Integer(itemCountPerPage));
}else {
chubUaInfo = (ChubUaInfo)inputObject;
if(chubUaInfo.getCurrentPage() == null || chubUaInfo.getCurrentPage() == 0) {
chubUaInfo.setCurrentPage(new Integer(1));
}
if(chubUaInfo.getItemCountPerPage() == null) {
chubUaInfo.setItemCountPerPage(new Integer(itemCountPerPage));
}
}
// db
SessionMgr sessMgr = new SessionMgr(request);
chubUaInfo.setDbType(sessMgr.getValue("dbType"));
String searchInterfaceId = request.getParameter("searchInterfaceId");
if (searchInterfaceId != null) {
chubUaInfo.setInterfaceId(searchInterfaceId);
}
//search
if(chubUaInfo.getInterfaceId() != null){
if(chubUaInfo.getInterfaceId().equals("null")){
chubUaInfo.setInterfaceId("");
}
}else if(chubUaInfo.getInterfaceId() == null){
chubUaInfo.setInterfaceId("");
}
if (chubUaInfo.getInterfaceId().indexOf("%") == -1) {
chubUaInfo.setInterfaceId(chubUaInfo.getInterfaceId() + "%");
}
beanUtilForm.setBean(chubUaInfo);
request.setAttribute("inputObject", chubUaInfo);
return super.doService(mapping, beanUtilForm, request, response);
} else if (method.equals("chubUaInfoDetail")) {
ChubUaInfo chubUaInfo = null;
BeanUtilForm beanUtilForm = (BeanUtilForm)form;
request.removeAttribute("inputObject");
request.removeAttribute("outputObject");
Object inputObject = null;
if (beanUtilForm != null) {
inputObject = beanUtilForm.getBean();
}else {
beanUtilForm = new BeanUtilForm();
}
if(inputObject == null) {
chubUaInfo = new ChubUaInfo();
}else {
chubUaInfo = (ChubUaInfo)inputObject;
}
beanUtilForm.setBean(chubUaInfo);
request.setAttribute("inputObject", chubUaInfo);
return super.doService(mapping, beanUtilForm, request, response);
} else if (method.equals("insert")) {
ChubUaInfo chubUaInfo = null;
BeanUtilForm beanUtilForm = (BeanUtilForm) form;
request.removeAttribute("inputObject");
request.removeAttribute("outputObject");
Object inputObject = null;
if (beanUtilForm != null) {
inputObject = beanUtilForm.getBean();
} else {
beanUtilForm = new BeanUtilForm();
}
if (inputObject == null) {
chubUaInfo = new ChubUaInfo();
} else {
chubUaInfo = (ChubUaInfo) inputObject;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
chubUaInfo.setRegDate(sdf.format(new Date()));
chubUaInfo.setModDate(sdf.format(new Date()));
beanUtilForm.setBean(chubUaInfo);
request.setAttribute("inputObject", chubUaInfo);
ActionForward forward = super.doService(mapping, beanUtilForm, request, response);
try {
String ids[] = new String[2];
ids[0] = XtrusConfig.CHUBUA_INFO_TABLE_ID;
ids[1] = chubUaInfo.getInterfaceId();
String configId = XtrusConfig.CHUBUA_COMPONENT_ID;
ReloadXTrusAdmin reload = ReloadXTrusAdmin.getInstance();
reload.reloadComponent(ids, configId);
}catch (ManagementException me) {
String errorMsg = XtrusLangTag.getMessage("error.management.exception");
ApplicationException are = new ApplicationException(me);
ApplicationException ae = new ApplicationException(errorMsg);
are.printException("");
request.setAttribute("servletpath", request.getServletPath());
request.setAttribute("exception", ae);
return mapping.findForward("failure");
} catch (RuntimeException re) {
String errorMsg = XtrusLangTag.getMessage("error.runtime.exception");
ApplicationException are = new ApplicationException(re);
ApplicationException ae = new ApplicationException(errorMsg);
are.printException("");
request.setAttribute("servletpath", request.getServletPath());
request.setAttribute("exception", ae);
return mapping.findForward("failure");
}catch(Exception e){
e.printStackTrace();
ApplicationException ae = new ApplicationException(e);
request.setAttribute("servletpath", request.getServletPath());
request.setAttribute("exception", ae);
return mapping.findForward("failure");
}
return forward;
} else if (method.equals("update")) {
ChubUaInfo chubUaInfo = null;
BeanUtilForm beanUtilForm = (BeanUtilForm) form;
request.removeAttribute("inputObject");
request.removeAttribute("outputObject");
Object inputObject = null;
if (beanUtilForm != null) {
inputObject = beanUtilForm.getBean();
} else {
beanUtilForm = new BeanUtilForm();
}
if (inputObject == null) {
chubUaInfo = new ChubUaInfo();
} else {
chubUaInfo = (ChubUaInfo) inputObject;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
chubUaInfo.setModDate(sdf.format(new Date()));
beanUtilForm.setBean(chubUaInfo);
request.setAttribute("inputObject", chubUaInfo);
ActionForward forward = super.doService(mapping, beanUtilForm, request, response);
try {
String ids[] = new String[2];
ids[0] = XtrusConfig.CHUBUA_INFO_TABLE_ID;
ids[1] = chubUaInfo.getInterfaceId();
String configId = XtrusConfig.CHUBUA_COMPONENT_ID;
ReloadXTrusAdmin reload = ReloadXTrusAdmin.getInstance();
reload.reloadComponent(ids, configId);
}catch (ManagementException me) {
String errorMsg = XtrusLangTag.getMessage("error.management.exception");
ApplicationException are = new ApplicationException(me);
ApplicationException ae = new ApplicationException(errorMsg);
are.printException("");
request.setAttribute("servletpath", request.getServletPath());
request.setAttribute("exception", ae);
return mapping.findForward("failure");
} catch (RuntimeException re) {
String errorMsg = XtrusLangTag.getMessage("error.runtime.exception");
ApplicationException are = new ApplicationException(re);
ApplicationException ae = new ApplicationException(errorMsg);
are.printException("");
request.setAttribute("servletpath", request.getServletPath());
request.setAttribute("exception", ae);
return mapping.findForward("failure");
}catch(Exception e){
e.printStackTrace();
ApplicationException ae = new ApplicationException(e);
request.setAttribute("servletpath", request.getServletPath());
request.setAttribute("exception", ae);
return mapping.findForward("failure");
}
return forward;
} else if (method.equals("delete")) {
ChubUaInfo chubUaInfo = null;
BeanUtilForm beanUtilForm = (BeanUtilForm) form;
request.removeAttribute("inputObject");
request.removeAttribute("outputObject");
Object inputObject = null;
if (beanUtilForm != null) {
inputObject = beanUtilForm.getBean();
} else {
beanUtilForm = new BeanUtilForm();
}
if (inputObject == null) {
chubUaInfo = new ChubUaInfo();
} else {
chubUaInfo = (ChubUaInfo) inputObject;
}
beanUtilForm.setBean(chubUaInfo);
request.setAttribute("inputObject", chubUaInfo);
ActionForward forward = super.doService(mapping, beanUtilForm, request, response);
try {
String ids[] = new String[2];
ids[0] = XtrusConfig.CHUBUA_INFO_TABLE_ID;
ids[1] = chubUaInfo.getInterfaceId();
String configId = XtrusConfig.CHUBUA_COMPONENT_ID;
ReloadXTrusAdmin reload = ReloadXTrusAdmin.getInstance();
reload.reloadComponent(ids, configId);
}catch (ManagementException me) {
String errorMsg =XtrusLangTag.getMessage("error.management.exception");
ApplicationException are = new ApplicationException(me);
ApplicationException ae = new ApplicationException(errorMsg);
are.printException("");
request.setAttribute("servletpath", request.getServletPath());
request.setAttribute("exception", ae);
return mapping.findForward("failure");
} catch (RuntimeException re) {
String errorMsg = XtrusLangTag.getMessage("error.runtime.exception");
ApplicationException are = new ApplicationException(re);
ApplicationException ae = new ApplicationException(errorMsg);
are.printException("");
request.setAttribute("servletpath", request.getServletPath());
request.setAttribute("exception", ae);
return mapping.findForward("failure");
}catch(Exception e){
e.printStackTrace();
ApplicationException ae = new ApplicationException(e);
request.setAttribute("servletpath", request.getServletPath());
request.setAttribute("exception", ae);
return mapping.findForward("failure");
}
return forward;
} else if(method.equals("saveChubUaInfoExcel")){
ChubUaInfo chubUaInfo = null;
BeanUtilForm beanUtilForm = (BeanUtilForm) form;
request.removeAttribute("inputObject");
request.removeAttribute("outputObject");
Object inputObject = null;
if (beanUtilForm != null) {
inputObject = beanUtilForm.getBean();
}else {
beanUtilForm = new BeanUtilForm();
}
if(inputObject == null) {
chubUaInfo = new ChubUaInfo();
} else {
chubUaInfo = (ChubUaInfo)inputObject;
}
SessionMgr sessMgr = new SessionMgr(request);
chubUaInfo.setDbType(sessMgr.getValue("dbType"));
chubUaInfo.setLangType(sessMgr.getValue("langType"));
chubUaInfo.setRootPath(getServlet().getServletContext().getRealPath("/"));
IChubUaInfoService service = (IChubUaInfoService)iBaseService;
service.saveChubUaInfoExcel(chubUaInfo, request, response);
return null;
} else {
return super.doService(mapping, form, request, response);
}
}
}
|
package com.example.tweetscraper;
import androidx.appcompat.app.AppCompatActivity;
import org.jsoup.*;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Scanner;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private EditText handleInput;
private Button search;
private List<Tweet> tweets;
private ListView listViewTweets;
private TextView userName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
handleInput = (EditText) findViewById(R.id.textBoxHandle);
search = findViewById(R.id.search);
listViewTweets = findViewById(R.id.listViewTweets);
search.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String handle = handleInput.getText().toString();
List<Tweet> tweets = scrapeUser(handle);
TweetList tweetsAdapter = new TweetList(MainActivity.this, tweets);
listViewTweets.setAdapter(tweetsAdapter);
}
});
}
public String[] remove(String[] text, String removal, String name){
String[] temp;
for(int i = 0; i < text.length; i++){
temp = text[i].split(removal);
if(temp.length >= 2) {
text[i] = temp[0] + temp[1];
}
}
return text;
}
public List<Tweet> scrapeUser(String userHandle){
Document test = null;
List<Tweet> list = new ArrayList<>();
userName = findViewById(R.id.textViewName);
try {
test = Jsoup.connect("http://www.twitter.com/" + userHandle).get();
String title = test.title();
System.out.println("--------------");
System.out.println(title);
System.out.println("--------------");
String name = title.split("@")[0];
name = name.substring(0, name.length()-2);
System.out.println(name);
Element timeline = test.select("div#timeline").first();
String text = timeline.text();
System.out.println("Tweet "+ name);
userName.setText("showing tweets from " +name);
String[] tweets = text.split("More Copy link to Tweet Embed Tweet");
tweets = remove(tweets, "Reply Retweet Retweeted Like Liked Thanks. Twitter will use this to make your timeline better. Undo Undo " + name, name);
tweets = remove(tweets, "Reply Retweet Retweeted Like Liked Show this thread Show this thread Thanks. Twitter will use this to make your timeline better. Undo Undo " + name, name);
tweets = remove(tweets, "Verified account @" + userHandle + " ", name);
String[] splitTweet;
System.out.println("--------------------------------------");
ArrayList<Tweet> tweetObjects = new ArrayList<Tweet>();
for(int i = 1; i <tweets.length -1;i++){
Tweet currentTweet = new Tweet(tweets[i]);
tweetObjects.add(currentTweet);
System.out.println(currentTweet);
list.add(currentTweet);
}
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
}
|
package com.needii.dashboard.validator;
import com.needii.dashboard.model.Banner;
import com.needii.dashboard.model.form.BannerForm;
import com.needii.dashboard.service.BannerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
@Component
public class BannerFormValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return BannerForm.class.isAssignableFrom(clazz);
}
@Autowired
private BannerService bannerService;
@Override
public void validate(Object target, Errors errors) {
BannerForm bannerForm = (BannerForm) target;
Banner banner = bannerService.findOne(bannerForm.getId());
if(bannerForm.getBannerDataForm().getName() == null || bannerForm.getBannerDataForm().getName().isEmpty()){
errors.rejectValue("bannerDataForm.name", "Validator.notBlank");
}
if(bannerForm.getFromStringDate().isEmpty()){
errors.rejectValue("fromStringDate", "Validator.notBlank");
}
if(bannerForm.getToStringDate().isEmpty()){
errors.rejectValue("toStringDate", "Validator.notBlank");
}
if(bannerForm.getContentType() != 4 && banner == null && bannerForm.getContentId() == 0){
errors.rejectValue("contentId", "Validator.notBlank");
}
if(banner != null && banner.getContentType() != 4 && bannerForm.getContentId() == 0){
errors.rejectValue("contentId", "Validator.notBlank");
}
if(bannerForm.getStatus() == null){
errors.rejectValue("status", "Validator.notBlank");
}
}
}
|
package utn.sau.hp.com.beans;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import utn.sau.hp.com.dao.ConvenioDao;
import utn.sau.hp.com.modelo.Conveniosparticulares;
/**
*
* @author christian
*/
@Named(value = "convenioBean")
@SessionScoped
public class ConvenioBean implements Serializable {
private List<Conveniosparticulares> listaConvenios;
private ConvenioDao dao;
@Inject
private LoginBean alumno;
private String fechaFilter;
public ConvenioBean() {
this.listaConvenios = new ArrayList<Conveniosparticulares>();
this.dao = new ConvenioDao();
}
public List<Conveniosparticulares> getListaConvenios() {
System.out.println(alumno.getUserLoggedIn().getId().toString());
this.listaConvenios = dao.findByAlumno(alumno.getUserLoggedIn().getId().toString());
return listaConvenios;
}
public void setListaConvenios(List<Conveniosparticulares> listaConvenios) {
this.listaConvenios = listaConvenios;
}
public String getFechaFilter() {
return fechaFilter;
}
public void setFechaFilter(String fechaFilter) {
this.fechaFilter = fechaFilter;
}
public void doFiltrar(){
getListaConvenios();
}
}
|
package Teatrus.model;
import java.io.Serializable;
public class Loc implements Serializable {
private int idLoc,idSpectacol;
private Pozitie pozitie;
private int pret;
private StatusLoc valabilitate;
public Loc(int idLoc, int idSpectacol, Pozitie pozitie, int pret, StatusLoc valabilitate) {
this.idLoc = idLoc;
this.idSpectacol = idSpectacol;
this.pozitie = pozitie;
this.pret = pret;
this.valabilitate = valabilitate;
}
public int getIdLoc() {
return idLoc;
}
public void setIdLoc(int idLoc) {
this.idLoc = idLoc;
}
public int getIdSpectacol() {
return idSpectacol;
}
public void setIdSpectacol(int idSpectacol) {
this.idSpectacol = idSpectacol;
}
public Pozitie getPozitie() {
return pozitie;
}
public void setPozitie(Pozitie pozitie) {
this.pozitie = pozitie;
}
public int getPret() {
return pret;
}
public void setPret(int pret) {
this.pret = pret;
}
public StatusLoc getValabilitate() {
return valabilitate;
}
public void setValabilitate(StatusLoc valabilitate) {
this.valabilitate = valabilitate;
}
}
|
package com.siscom.service;
import com.siscom.controller.dto.EstatisticaDto;
import com.siscom.dao.CompraRepository;
import com.siscom.dao.PessoaRepository;
import com.siscom.dao.ProdutoRepository;
import com.siscom.dao.VendaRepository;
import com.siscom.exception.SisComException;
import com.siscom.service.model.Cliente;
import com.siscom.service.model.Compra;
import com.siscom.service.model.Estatistica;
import com.siscom.service.model.FormaPgto;
import com.siscom.service.model.Fornecedor;
import com.siscom.service.model.ItemCompra;
import com.siscom.service.model.ItemVenda;
import com.siscom.service.model.NomeData;
import com.siscom.service.model.Pessoa;
import com.siscom.service.model.Produto;
import com.siscom.service.model.TipoPessoa;
import com.siscom.service.model.Venda;
import com.siscom.service.model.Vendedor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Service
public class ComercialService {
private static final int[] pesoCPF = { 11, 10, 9, 8, 7, 6, 5, 4, 3, 2 };
private static final int[] pesoCNPJ = { 6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2 };
@Autowired
private PessoaRepository pessoaRepository;
@Autowired
private CompraRepository compraRepository;
@Autowired
private ProdutoRepository produtoRepository;
@Autowired
private VendaRepository vendaRepository;
public ComercialService() {
}
//Add
/**
* Add a Person
*
* @param pessoa
* @return
* @throws Exception
*/
public void addPessoa(Pessoa pessoa) throws Exception {
if (pessoa instanceof Cliente) {
final Cliente cliente = (Cliente) pessoa;
if (pessoaRepository.buscarCliente(cliente.getCpf()) != null) {
throw new Exception("Client already in system.");
} else {
pessoaRepository.addCliente(cliente);
}
} else if (pessoa instanceof Fornecedor) {
final Fornecedor fornecedor = (Fornecedor) pessoa;
if (pessoaRepository.buscarFornecedor(fornecedor.getCnpj()) != null) {
throw new Exception("Provider already in system.");
} else {
pessoaRepository.addFornecedor(fornecedor);
}
} else {
final Vendedor vendedor = (Vendedor) pessoa;
if (pessoaRepository.buscarVendedor(vendedor.getCpf()) != null) {
throw new Exception("Sales person already in system.");
} else if (vendedor.getMetaMensal() <= 0) {
throw new Exception("Sales goal must be greater than 0");
} else {
pessoaRepository.addVendedor(vendedor);
}
}
}
/**
* Add a Product
*
* @param produto
*/
public void addProduto(Produto produto) {
produtoRepository.addProduto(produto);
}
public void fazerVendaParaCliente(Integer codCliente,
Integer codVendedor,
FormaPgto formaPgto,
List<ItemVenda> listaItensVenda) throws Exception {
Cliente cliente = (Cliente) pessoaRepository.buscarPessoa(codCliente);
Vendedor vendedor = (Vendedor) pessoaRepository.buscarPessoa(codVendedor);
double valorTotal = 0;
for (ItemVenda itemVenda : listaItensVenda) {
valorTotal = +itemVenda.getValorVenda() * itemVenda.getQuantVenda();
}
if (formaPgto.equals(FormaPgto.PAGAMENTO_A_PRAZO) && cliente.getLimiteCredito() < valorTotal) {
throw new Exception("Venda não pode ser feita.");
} else {
Venda venda = new Venda(0, cliente, vendedor, listaItensVenda, formaPgto.getCodigo(), new Date());
vendaRepository.fazerVenda(venda);
for (ItemVenda itemVenda : listaItensVenda) {
excluirEstoque(itemVenda.getCodProduto(), itemVenda.getQuantVenda());
}
}
}
/**
* Add item to Stock
*
* @param codProduto
* @param quantidade
*/
public void addItemEstoque(Integer codProduto, Integer quantidade) {
Produto produto = buscarProduto(codProduto);
produto.addEstoque(quantidade);
produtoRepository.atualizarEstoque(produto.getCodigo(), produto.getEstoque());
}
/**
* Add a Purchase
*
* @param codFornecedor
* @param listaItensCompra
* @throws SisComException
*/
public void criarCompra(Integer codFornecedor, List<ItemCompra> listaItensCompra) throws SisComException {
for (ItemCompra itemCompra : listaItensCompra) {
Produto produto = buscarProduto(itemCompra.getCodProduto());
produto.removeEstoque(itemCompra.getQuantCompra());
produtoRepository.atualizarEstoque(produto.getCodigo(), produto.getEstoque());
}
Compra compra = new Compra(null, codFornecedor, listaItensCompra, new Date());
compraRepository.fazerCompra(compra);
}
//Remove
/**
* Delete a Person
*
* @param codPessoa
* @throws Exception
*/
public void excluirPessoa(Integer codPessoa) throws Exception {
Pessoa pessoa = pessoaRepository.buscarPessoa(codPessoa);
if (pessoa instanceof Fornecedor) {
excluirFornecedor(codPessoa);
return;
}
if (pessoa instanceof Cliente) {
excluirCliente(codPessoa);
return;
}
if (pessoa instanceof Vendedor) {
excluirVendedor(codPessoa);
return;
}
}
private void excluirFornecedor(Integer codPessoa) throws Exception {
Integer qtdCompras = compraRepository.buscarQtdCompras(codPessoa);
if (qtdCompras > 0) {
throw new Exception("Fornecedor tem compra registrada para ele. Nao pode excluir.");
} else {
pessoaRepository.excluirPessoa(codPessoa);
}
}
private void excluirCliente(Integer codPessoa) throws Exception {
Integer qtdVendas = vendaRepository.buscarQtdVendasCliente(codPessoa);
if (qtdVendas > 0) {
throw new Exception("Cliente tem venda registrada para ele. Nao pode excluir.");
} else {
pessoaRepository.excluirPessoa(codPessoa);
}
}
private void excluirVendedor(Integer codPessoa) throws Exception {
Integer qtdVendas = vendaRepository.buscarQtdVendasVendedor(codPessoa);
if (qtdVendas > 0) {
throw new Exception("Vendedor tem venda registrada para ele. Nao pode excluir.");
} else {
pessoaRepository.excluirPessoa(codPessoa);
}
}
/**
* Delete a Product
*
* @param codigo
* @throws Exception
*/
public void excluirProduto(Integer codigo) throws Exception {
Produto produto = buscarProduto(codigo);
if (vendaRepository.buscarQtdProdutosVenda(codigo) > 0 ||
compraRepository.buscarQtdProdutosCompra(codigo) > 0) {
throw new Exception("Não podemos excluir o produto, pois pertence a uma venda/compra");
} else {
produtoRepository.excluirProduto(codigo);
}
}
/**
* Delete a Product from Stock
*
* @param codProduto
* @param quantidade
* @throws SisComException
*/
public void excluirEstoque(Integer codProduto, Integer quantidade) throws SisComException {
Produto produto = buscarProduto(codProduto);
produto.removeEstoque(quantidade);
produtoRepository.atualizarEstoque(produto.getCodigo(), produto.getEstoque());
}
/**
* Delete a Purchase DONE
*
* @param numCompra
*/
public void excluirCompra(Integer numCompra) {
for (ItemCompra itemCompra : compraRepository.buscarItens(numCompra)) {
addItemEstoque(itemCompra.getCodProduto(), itemCompra.getQuantCompra());
}
compraRepository.excluirCompra(numCompra);
}
/**
* Delete a Sale
*
* @param numVenda
*/
public void excluirVenda(Integer numVenda) {
for (ItemVenda itemVenda : vendaRepository.buscarItens(numVenda)) {
addItemEstoque(itemVenda.getCodProduto(), itemVenda.getQuantVenda());
}
vendaRepository.excluirVenda(numVenda);
}
//Search
public Pessoa buscarPessoa(String cpfCnpj) {
if (isValidCPF(cpfCnpj)) {
Pessoa vendedor = pessoaRepository.buscarVendedor(cpfCnpj);
if (vendedor != null) {
return vendedor;
}
return pessoaRepository.buscarCliente(cpfCnpj);
}
if (isValidCNPJ(cpfCnpj)) {
return pessoaRepository.buscarFornecedor(cpfCnpj);
}
return null;
}
public ArrayList<Pessoa> buscarPessoaOrdemAlfabetica(String query, TipoPessoa tipoPessoa) {
return new ArrayList<>(pessoaRepository.buscarPessoasOrdemAlfabetica(query, tipoPessoa));
}
/**
* Search for a Product
*
* @param codigo
* @return
*/
public Produto buscarProduto(Integer codigo) {
return produtoRepository.buscarProduto(codigo);
}
public ArrayList<Produto> buscarProdutoOrdemAlfabetica(String query, Boolean emFalta) {
return new ArrayList<>(produtoRepository.buscarProdutosOrdemAlfabetica(query, emFalta));
}
public ArrayList<NomeData> obterListaVendas(TipoPessoa tipoPessoa, String query, Date de, Date para)
throws Exception {
if (tipoPessoa == TipoPessoa.CLIENTE) {
return new ArrayList<>(vendaRepository.obterListaVendasCliente(query, de, para));
}
if (tipoPessoa == TipoPessoa.VENDEDOR) {
return new ArrayList<>(vendaRepository.obterListaVendasVendedor(query, de, para));
}
throw new Exception("Fornecedores não possuem vendas!");
}
public ArrayList<NomeData> obterListaCompras(String nomeFornecedor, Date de, Date para) {
return new ArrayList<>(compraRepository.obterListaCompras(nomeFornecedor, de, para));
}
public ArrayList<Estatistica> buscarEstatisticaVendas(TipoPessoa tipoPessoa, Date de, Date para) throws Exception {
if (tipoPessoa == TipoPessoa.FORNECEDOR) {
throw new Exception("Fornecedores não possuem vendas!");
}
return new ArrayList<>(vendaRepository.obterEstatisticasVenda(de, para, tipoPessoa));
}
public ArrayList<Estatistica> buscarEstatisticaCompras(Date de, Date para) {
return new ArrayList<>(compraRepository.buscarEstatisticaCompras(de, para));
}
private boolean isValidCPF(String cpf) {
return !((cpf == null) || (cpf.length() != 11));
}
private boolean isValidCNPJ(String cnpj) {
return !((cnpj == null) || (cnpj.length() != 14));
}
}
|
package beakjoon11;
import java.util.Scanner;
public class Hw_10872 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N;
int result=1;
do {
N=sc.nextInt();
}while(!(N>=0&&N<=12));
if(N==0) {
result=1;
}else {
for(int i=1; i<=N;i++) {
result=result*i;
}
}
System.out.println(result);
}
}
|
/* ###
* IP: GHIDRA
* REVIEWED: YES
*
* 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 ghidra.app.plugin.core.references;
import ghidra.app.cmd.refs.UpdateExternalNameCmd;
import ghidra.framework.cmd.Command;
import ghidra.framework.plugintool.PluginTool;
import ghidra.program.model.listing.Library;
import ghidra.program.model.listing.Program;
import ghidra.program.model.symbol.ExternalManager;
import ghidra.program.model.symbol.SourceType;
import ghidra.util.Msg;
import java.awt.Window;
import java.util.*;
import javax.swing.table.AbstractTableModel;
/**
* TableModel for the external program names and corresponding ghidra path names.
*/
class ExternalNamesTableModel extends AbstractTableModel {
final static int NAME_COL = 0;
final static int PATH_COL = 1;
final static String EXTERNAL_NAME = "Name";
final static String PATH_NAME = "Ghidra Program";
private final String[] columnNames = { EXTERNAL_NAME, PATH_NAME };
private List<String> nameList = new ArrayList<String>();
private List<String> pathNameList = new ArrayList<String>();
private Program program;
private PluginTool tool;
public ExternalNamesTableModel(PluginTool tool) {
this.tool = tool;
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return nameList.size();
}
@Override
public String getColumnName(int column) {
return columnNames[column];
}
public Object getValueAt(int rowIndex, int columnIndex) {
if (rowIndex >= nameList.size()) {
return "";
}
switch (columnIndex) {
case NAME_COL:
return nameList.get(rowIndex);
case PATH_COL:
return pathNameList.get(rowIndex);
}
return "Unknown Column!";
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
if (columnIndex == NAME_COL) {
return true;
}
return false;
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
String extName = ((String) aValue).trim();
if ("".equals(extName)) {
return;
}
if (nameList.contains(extName)) {
if (nameList.indexOf(extName) != rowIndex) {
Window window = tool.getActiveWindow();
Msg.showInfo(getClass(), window, "Duplicate Name", "Name already exists: " +
extName);
}
return;
}
Command cmd =
new UpdateExternalNameCmd(nameList.get(rowIndex), extName, SourceType.USER_DEFINED);
if (!tool.execute(cmd, program)) {
tool.setStatusInfo(cmd.getStatusMsg());
}
}
void setProgram(Program program) {
this.program = program;
updateTableData();
}
///////////////////////////////////////////////////////////////////////////
void updateTableData() {
nameList.clear();
pathNameList.clear();
if (program == null) {
fireTableDataChanged();
return;
}
ExternalManager extMgr = program.getExternalManager();
String[] programNames = extMgr.getExternalLibraryNames();
Arrays.sort(programNames);
for (int i = 0; i < programNames.length; i++) {
if (Library.UNKNOWN.equals(programNames[i])) {
continue;
}
nameList.add(programNames[i]);
pathNameList.add(extMgr.getExternalLibraryPath(programNames[i]));
}
fireTableDataChanged();
}
}
|
package org.activiti.services.core.model.commands;
import java.util.UUID;
public class SuspendProcessInstanceCmd implements Command {
private String id;
private String processInstanceId;
public SuspendProcessInstanceCmd() {
this.id = UUID.randomUUID().toString();
}
public SuspendProcessInstanceCmd(String processInstanceId) {
this();
this.processInstanceId = processInstanceId;
}
@Override
public String getId() {
return id;
}
public String getProcessInstanceId() {
return processInstanceId;
}
}
|
package com.example.administrator.mytechnologyproject.fragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import com.example.administrator.mytechnologyproject.R;
import com.example.administrator.mytechnologyproject.activity.HomeActivity;
import com.example.administrator.mytechnologyproject.activity.NewsShowActivity;
import com.example.administrator.mytechnologyproject.adapter.MyImageGridViewAdapter;
import com.example.administrator.mytechnologyproject.model.News;
import com.example.administrator.mytechnologyproject.util.DBManager.DBTools;
import java.util.ArrayList;
import java.util.List;
public class ImageFragment extends Fragment {
private List<News> newsList;
private List<String> imageList;
private GridView gv_imageGridView;
private MyImageGridViewAdapter myAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_image, container, false);
gv_imageGridView = (GridView) view.findViewById(R.id.gv_imageGridView);
myAdapter = new MyImageGridViewAdapter(getContext());
gv_imageGridView.setAdapter(myAdapter);
gv_imageGridView.setOnItemClickListener(onItemClickListener);
loadDate();
return view;
}
private void loadDate() {
DBTools dbTools = new DBTools(getContext());
newsList = dbTools.getLocalNews();
imageList = new ArrayList<>();
for (int i = 0; i<newsList.size(); i++) {
imageList.add(newsList.get(i).getIcon());
}
if (imageList == null
|| imageList.size() <= 0) {
((HomeActivity)getActivity()).showToast("当前无新闻图片!");
} else {
myAdapter.appendDataed(imageList, true);
myAdapter.updateAdapter();
}
}
private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
Bundle bundle = new Bundle();
News news = newsList.get(i);
bundle.putSerializable("news", news);
((HomeActivity) getActivity()).openActivity(NewsShowActivity.class, bundle);
}
};
}
|
package com.trump.auction.trade.api.impl;
import com.alibaba.dubbo.config.annotation.Service;
import com.cf.common.util.page.Paging;
import com.cf.common.utils.JsonResult;
import com.trump.auction.trade.api.AuctionInfoStubService;
import com.trump.auction.trade.model.*;
import com.trump.auction.trade.service.AuctionInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
/**
* @description: 拍品信息
* @author: zhangqingqiang
* @date: 2018-01-06 11:41
**/
@Service(version = "1.0.0")
public class AuctionInfoStubServiceImpl implements AuctionInfoStubService{
@Autowired
private AuctionInfoService auctionInfoService;
@Override
public Paging<AuctionInfoModel> queryAuctionInfoByClassify(AuctionInfoQuery auctionQuery, int pageNum, int pageSize) {
return auctionInfoService.queryAuctionInfoByClassify(auctionQuery,pageNum,pageSize);
}
@Override
public Paging<AuctionInfoModel> queryNewestAuctionInfo(AuctionInfoQuery auctionQuery, int pageNum, int pageSize) {
return auctionInfoService.queryNewestAuctionInfo(auctionQuery,pageNum,pageSize);
}
@Override
public List<AuctionInfoModel> queryHotAuctionInfo(AuctionInfoQuery auctionQuery) {
return auctionInfoService.queryHotAuctionInfo(auctionQuery);
}
@Override
public JsonResult saveAuctionInfo(AuctionInfoModel auctionInfoModel) {
return auctionInfoService.saveAuctionInfo(auctionInfoModel);
}
@Override
public AuctionInfoModel queryAuctionByProductIdAndNo(AuctionInfoQuery auctionQuery) {
return auctionInfoService.queryAuctionByProductIdAndNo(auctionQuery);
}
/**
* 获取拍品信息通过拍品期数ID
* @param auctionId
* @return
*/
@Override
public AuctionInfoModel getAuctionInfoById(Integer auctionId) {
return auctionInfoService.getAuctionInfoById(auctionId);
}
@Override
public Integer findAuctionById(Integer auctionProdId) {
return auctionInfoService.findAuctionById(auctionProdId);
}
@Override
public JsonResult doAuctionTask(AuctionProductInfoModel prod, AuctionRuleModel rule, AuctionInfoModel auctionInfo,
AuctionProductRecordModel lastRecord) {
return auctionInfoService.doAuctionTask(prod,rule,auctionInfo,lastRecord);
}
}
|
package home_work_2.txt.arrays;
public class Txt_2_2_1_all_array {
public static void main(String[] args) {
ArraysUtils adg = new ArraysUtils();
int[] arr = adg.arrayFromConsole();
int n = 0;
System.out.println();
do {
System.out.print(arr[n] + " ");
n++;
} while (n != arr.length);
//while
System.out.println();
n = 0;
while (n != arr.length) {
System.out.print(arr[n] + " ");
n++;
}
//for
System.out.println();
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
//foreach
System.out.println();
for (int element : arr) {
System.out.print(element + " ");
}
}
}
|
/*
* Copyright 2015 Arie Timmerman
*/
package com.passbird.activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.IconTextView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.joanzapata.android.iconify.Iconify;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.passbird.helpers.Logger;
import com.passbird.model.Password;
import com.passbird.R;
import com.passbird.helpers.Utils;
import com.passbird.helpers.DatabaseHelper;
public class MainActivity extends ListActivity {
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private GoogleCloudMessaging gcm;
private String regid;
private Context context;
private final String SENDER_ID = "449435541952";
private ArrayList<Password> passwordList;
private PasswordArrayAdapter passwordArrayAdapter;
private class PasswordArrayAdapter extends ArrayAdapter{
@Override
public int getCount() {
return passwordList.size();
}
public PasswordArrayAdapter(Context context, List objects) {
super(context, android.R.layout.simple_list_item_single_choice, objects);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.list_item_password, parent, false);
}
TextView textView = (TextView)convertView.findViewById(android.R.id.text1);
TextView textViewDomain = (TextView)convertView.findViewById(android.R.id.text2);
IconTextView icon = (IconTextView)convertView.findViewById(R.id.icon_text_view);
Password password = passwordList.get(position);
LinearLayout listItem = (LinearLayout) convertView.findViewById(R.id.primary_target);
textView.setText(password.getValue(Password.KEY_TITLE));
textViewDomain.setText(password.getValue(Password.KEY_DOMAIN));
icon.setText("{fa-" + password.getValue(Password.KEY_ICON) + "}");
Iconify.addIcons(icon);
listItem.setTag(position);
listItem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Integer position = (Integer)view.getTag();
Log.w("Clicked", String.format("id: %d", position));
showEdit(position);
}
});
return convertView;
}
}
private void showEdit(Integer position){
Password password = passwordList.get(position);
Intent intent = new Intent(this, Edit.class);
intent.putExtra("id", password.getId());
intent.putExtra("action","edit");
startActivity(intent);
}
@Override
protected void onStart() {
super.onStart();
passwordList = DatabaseHelper.getInstance(this).getAllPasswords();
passwordArrayAdapter.notifyDataSetChanged();
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getApplicationContext();
if (checkPlayServices()) {
gcm = GoogleCloudMessaging.getInstance(this);
regid = Utils.getRegistrationId(context);
if (regid.isEmpty()) {
registerInBackground();
}
} else {
Log.i("main", "No valid Google Play Services APK found.");
}
setContentView(R.layout.main);
passwordList = DatabaseHelper.getInstance(this).getAllPasswords();
passwordArrayAdapter = new PasswordArrayAdapter(this, passwordList);
setListAdapter(passwordArrayAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void showMessage(String title, String message){
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Well done!");
alertDialog.setMessage(message);
alertDialog.show();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.weblogin:
startActivity(new Intent(this, LoginActivity.class));
return true;
case R.id.browsers:
startActivity(new Intent(this, BrowsersActivity.class));
return true;
case R.id.register_browser:
startActivityForResult(new Intent(this, RegisterActivity.class), 1);
return true;
case R.id.import_passwords:
startActivityForResult(new Intent(this, ImportActivity.class), 1);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
showMessage("Browser registered",data.getStringExtra("message"));
}
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
showMessage("Device not supported","Seems like your device does not support push messages");
finish();
}
return false;
}
return true;
}
private void registerInBackground() {
new AsyncTask() {
@Override
protected Object doInBackground(Object[] params) {
Logger.log("main", "start async task");
String msg;
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regid = gcm.register(SENDER_ID);
msg = "Device registered, registration ID=" + regid;
storeRegistrationId(context, regid);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
}
return msg;
}
}.execute(null, null, null);
}
private void storeRegistrationId(Context context, String regId) {
final SharedPreferences prefs = Utils.getGCMPreferences(context);
int appVersion = Utils.getAppVersion(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(Utils.PROPERTY_REG_ID, regId);
editor.putInt(Utils.PROPERTY_APP_VERSION, appVersion);
editor.apply();
}
public void newPassword(View view){
startActivity(new Intent(this, Edit.class));
}
}
|
package egovframework.adm.rep.dao;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Repository;
import egovframework.rte.psl.dataaccess.EgovAbstractDAO;
@Repository("reportProfDAO")
public class ReportProfDAO extends EgovAbstractDAO{
public List selectReportProfList(Map<String, Object> commandMap) throws Exception{
return list("reportProfDAO.selectReportProfList", commandMap);
}
public void insertReportProfData(Map<String, Object> commandMap) throws Exception{
insert("reportProfDAO.insertReportProfData", commandMap);
}
public void insertFilesData(Map<String, Object> commandMap) throws Exception{
insert("reportProfDAO.insertFilesData", commandMap);
}
public Map selectReportProfData(Map<String, Object> commandMap) throws Exception{
return (Map)selectByPk("reportProfDAO.selectReportProfData", commandMap);
}
public List selectProfFiles(Map<String, Object> commandMap) throws Exception{
return list("reportProfDAO.selectProfFiles", commandMap);
}
public int updateReportProfData(Map<String, Object> commandMap) throws Exception{
return update("reportProfDAO.updateReportProfData", commandMap);
}
public int reportProfWeightUpdateData(Map<String, Object> commandMap) throws Exception{
return update("reportProfDAO.reportProfWeightUpdateData", commandMap);
}
public List selectReportQuestionList(Map<String, Object> commandMap) throws Exception{
return list("reportProfDAO.selectReportQuestionList", commandMap);
}
public Map selectReportQuestionView(Map<String, Object> commandMap) throws Exception{
return (Map)selectByPk("reportProfDAO.selectReportQuestionView", commandMap);
}
/**
* 과제 문항 등록
* @param commandMap
* @return
* @throws Exception
*/
public Object insertTzReportQues(Map<String, Object> commandMap) throws Exception{
return insert("reportProfDAO.insertTzReportQues", commandMap);
}
//과제문항 과정의 문항 조회
public List selectReportQuestionSubjList(Map<String, Object> commandMap) throws Exception{
return list("reportProfDAO.selectReportQuestionSubjList",commandMap);
}
public Map selectReportProfView(Map<String, Object> commandMap) throws Exception{
return (Map)selectByPk("reportProfDAO.selectReportProfView", commandMap);
}
//과제 문항 리스트
public List selectReportQuesList(Map<String, Object> commandMap) throws Exception{
return list("reportProfDAO.selectReportQuesList", commandMap);
}
//과제 등록
public void insertReportProf(Map<String, Object> commandMap) throws Exception{
insert("reportProfDAO.insertReportProf", commandMap);
}
//평가과제문항 등록
public void insertProjordSheet(Map<String, Object> commandMap) throws Exception{
insert("reportProfDAO.insertProjordSheet", commandMap);
}
//과제 수정
public int updateReportProf(Map<String, Object> commandMap) throws Exception{
return update("reportProfDAO.updateReportProf", commandMap);
}
//과제 출제문항 삭제
public int deleteProjordSheet(Map<String, Object> commandMap) throws Exception{
return delete("reportProfDAO.deleteProjordSheet", commandMap);
}
//과제 첨부파일 삭제
public int deleteReportProfFiles(Map<String, Object> commandMap) throws Exception{
return delete("reportProfDAO.deleteReportProfFiles", commandMap);
}
//과제 문항 수정
public int updateTzReportQues(Map<String, Object> commandMap) throws Exception{
return update("reportProfDAO.updateTzReportQues", commandMap);
}
//과제 문항 삭제
public int deleteTzReportQues(Map<String, Object> commandMap) throws Exception{
return delete("reportProfDAO.deleteTzReportQues", commandMap);
}
//과제 출제 문항 리스트
public List selectReportQuesSubjseqList(Map<String, Object> commandMap) throws Exception{
return list("reportProfDAO.selectReportQuesSubjseqList", commandMap);
}
}
|
package com.bshare.ui;
import java.util.ArrayList;
import java.util.List;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.Toast;
import com.bshare.core.BSShareItem;
import com.bshare.core.BShareShareListAdapter;
import com.bshare.core.BShareWindowHandler;
import com.bshare.core.Config;
import com.bshare.core.Constants;
import com.bshare.core.PlatformType;
import com.bshare.platform.GeneralPlatform;
import com.bshare.platform.Platform;
import com.bshare.platform.PlatformFactory;
import com.bshare.utils.BSUtils;
/**
*
* @author chris.xue
*
*/
public class ShareListDialog extends Dialog implements android.view.View.OnClickListener {
public ShareListDialog(Context context, BSShareItem shareItem) {
super(context, BSUtils.getResourseIdByName(context, "style", "bshare_dialog"));
this.shareItem = shareItem;
}
public ShareListDialog(Context context, BSShareItem shareItem, BShareWindowHandler windowHandler) {
this(context, shareItem);
registerWindowHandler(windowHandler);
}
public void registerWindowHandler(BShareWindowHandler windowHandler) {
if (windowHandler != null) {
windowHandlers.add(windowHandler);
}
}
public void unregisterWindowHandler(BShareWindowHandler windowHandler) {
if (windowHandler != null) {
windowHandlers.remove(windowHandler);
}
}
protected BSShareItem shareItem;
private List<BShareWindowHandler> windowHandlers = new ArrayList<BShareWindowHandler>();
protected View btnMore;
protected ListView lvPlatform;
protected List<PlatformType> platformList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setCanceledOnTouchOutside(true);
requestWindowFeature(Window.FEATURE_NO_TITLE);
View content = LayoutInflater.from(getContext()).inflate(
BSUtils.getResourseIdByName(getContext(), "layout", "bshare_share_list"), null);
setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
if (windowHandlers.isEmpty()) {
for (BShareWindowHandler h : windowHandlers) {
if (h != null) {
h.onWindowClose(this);
}
}
windowHandlers.clear();
}
}
});
Display display = getWindow().getWindowManager().getDefaultDisplay();
float scale = getContext().getResources().getDisplayMetrics().density;
float[] dimensions = display.getWidth() < display.getHeight() ? Constants.DIMENSIONS_PORTRAIT
: Constants.DIMENSIONS_LANDSCAPE;
addContentView(content, new FrameLayout.LayoutParams((int) (dimensions[0] * scale + 0.5f),
(int) (dimensions[1] * scale + 0.5f)));
// setContentView(content);
platformList = new ArrayList<PlatformType>(Config.instance().getShareList());
btnMore = findViewById(BSUtils.getResourseIdByName(getContext(), "id", "bs_share_button_more"));
lvPlatform = (ListView) findViewById(BSUtils.getResourseIdByName(getContext(), "id",
"bs_share_button_list_view"));
BShareShareListAdapter adapter = new BShareShareListAdapter(getContext(), platformList, this);
lvPlatform.setAdapter(adapter);
if (btnMore != null) {
if (Config.instance().isShouldDisplayMore()) {
btnMore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Dialog moreList = Config.instance().getDialogBuilder()
.buildMoreListDialog(getContext(), shareItem, null);
moreList.show();
if (isShowing()) {
dismiss();
}
}
});
} else {
btnMore.setVisibility(View.GONE);
}
}
}
public void share(PlatformType platformType) {
final Platform platform = PlatformFactory.getPlatform(getContext(), platformType);
platform.setShareItem(shareItem);
if (!BSUtils.isOnline(getContext())) {
Toast.makeText(getContext(),
BSUtils.getResourseIdByName(getContext(), "string", "bshare_error_msg_offline"), Toast.LENGTH_SHORT)
.show();
} else {
if ((platform instanceof GeneralPlatform) == true) {
platform.share();
} else {
platform.setAccessTokenAndSecret(getContext());
if (platform.validation(true)) {
AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
@Override
protected Object doInBackground(Object... params) {
platform.share();
return null;
}
};
task.execute();
}
}
}
if (Config.instance().isAutoCloseShareList() && isShowing()) {
dismiss();
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (isShowing()) {
dismiss();
}
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public void onClick(View item) {
PlatformType p = (PlatformType) item.getTag();
if (p != null) {
final Platform platform = PlatformFactory.getPlatform(getContext(), p);
platform.setShareItem(shareItem);
if (!BSUtils.isOnline(getContext())) {
Toast.makeText(getContext(),
BSUtils.getResourseIdByName(getContext(), "string", "bshare_error_msg_offline"),
Toast.LENGTH_SHORT).show();
} else {
if ((platform instanceof GeneralPlatform) == true) {
platform.share();
} else {
platform.setAccessTokenAndSecret(getContext());
if (platform.validation(true)) {
AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
@Override
protected Object doInBackground(Object... params) {
platform.share();
return null;
}
};
task.execute();
}
}
}
if (Config.instance().isAutoCloseShareList() && isShowing()) {
dismiss();
}
}
}
}
|
package org.atlasapi.remotesite.metabroadcast.similar;
import java.util.List;
import org.atlasapi.media.entity.ChildRef;
import org.atlasapi.media.entity.Described;
public interface SimilarContentProvider {
void initialise();
List<ChildRef> similarTo(Described described);
}
|
package com.careercup.facebook;
import java.awt.Point;
public class FindPath {
int x;
int y;
Point p;
public FindPath(int _x,int _y){
x=_x;
y=_y;
p=new Point(x,y);
}
public static void main(String[] args){
//current position
FindPath fp= new FindPath(1,1);
//starting point of grid
Point start=new Point(0,0);
//destination point of grid
Point end=new Point(5,5);
//grid
char[][] grid= new char[7][7];
//set some barrier , "X"
for(int i=0;i<grid.length;i++){
for(int j=0;j<grid[i].length;j++){
if(i==j+1)
grid[i][j]='X';
else
grid[i][j]='0';
}
}
//print the grid
for(int i=0;i<grid.length;i++){
for(int j=0;j<grid[i].length;j++){
System.out.print (" "+grid[i][j] + " ");
}
System.out.println("\r\n");
}
fp.solve(start,end,fp.p,grid);
}
public boolean solve(Point start,Point end,Point current,char[][] grid){
//check current position is within the grid
if(current.x<0 ||
current.y<0 ||
current.x>(grid[current.y].length -1) ||
current.y> (grid.length-1) ||
grid[current.y][current.x] == 'X'
)
return false;
//check current position reaches the destination
if(current.x==end.x &&
current.y==end.y
){
System.out.println(current.x + " , "+ current.y);
return false;
}
//move right
if(current.x<end.x){
System.out.println(current.x + " , "+ current.y);
return solve(start,end,new Point(current.x+1,current.y),grid);
}
//move up
else if(current.y<end.y){
System.out.println(current.x + " , "+ current.y);
return solve(start,end,new Point(current.x,current.y+1),grid);
}
//move left
else if(current.x<end.x){
System.out.println(current.x + " , "+ current.y);
return solve(start,end,new Point(current.x-1,current.y),grid);
}
//move down
else if(current.y>end.y){
System.out.println(current.x + " , "+ current.y);
return solve(start,end,new Point(current.x,current.y-1),grid);
}
else
return false;
}
}
|
package com.myth.springboot.service;
import com.myth.springboot.dao.TypeMapper;
import com.myth.springboot.entity.Type;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class TypeService {
@Autowired
TypeMapper mapper;
public int typeInsert(Type type){
return mapper.typeInsert(type);
}
public int typeUpdate(Type type){
return mapper.typeUpdate(type);
}
public List<Type> typeSelect(Type type){
return mapper.typeSelect(type);
}
//用户的操作
public int typeDelete(Type type){
return mapper.typeDelete(type);
}
}
|
package de.deepamehta.plugins.eduzen.service;
import de.deepamehta.core.Topic;
import de.deepamehta.core.RelatedTopic;
import de.deepamehta.core.ResultSet;
import de.deepamehta.core.model.TopicModel;
import de.deepamehta.core.service.ClientState;
import de.deepamehta.core.service.PluginService;
import de.deepamehta.plugins.eduzen.model.Resource;
import de.deepamehta.plugins.eduzen.model.ResourceTopic;
public interface EduzenService extends PluginService {
Resource createContent(ResourceTopic topic, ClientState clientState);
// Queries for correctors ...
ResultSet<Topic> getAllExercises(ClientState clientState);
ResultSet<Topic> getAllNewExercises(ClientState clientState);
ResultSet<Topic> getAllUncommentedExercises(ClientState clientState);
ResultSet<Topic> getAllUnapproachedExercises(ClientState clientState);
String getApproachState(long approachId, ClientState clientState);
String getExerciseState(long exerciseId, ClientState clientState);
String getExerciseTextState(long exerciseTextId, ClientState clientState);
ResultSet<RelatedTopic> getExerciseObjects(long exerciseTextId, ClientState clientState);
}
|
package com.example.qiumishequouzhan.MainView;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.SoundPool;
import android.net.Uri;
import android.os.*;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.*;
import android.webkit.DownloadListener;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.qiumishequouzhan.*;
import com.example.qiumishequouzhan.Utils.*;
import com.example.qiumishequouzhan.webviewpage.MainFragment;
import com.gotye.bean.GotyeSex;
import com.gotye.sdk.GotyeSDK;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshWebView;
import com.umeng.analytics.MobclickAgent;
import com.umeng.fb.FeedbackAgent;
import net.simonvt.menudrawer.MenuDrawer;
import net.simonvt.menudrawer.Position;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
public class MainActivity extends BaseListMenu {
/**
* Called when the activity is first created.
*/
ShakeListener mShakeListener = null;
public static long lastUpdateTime;
private String pamars;
public static WebView obj_web;
private static MainActivity p_MainActivity;
private static PullToRefreshWebView p_PushInstance;
public static Bitmap HeadPic = null;
public TextView titleView;
private boolean isExit = false;
public TextView ButtonText;
public ImageButton Rightbutton;
public ImageButton bt_openmenu;
private String titlecount;
public boolean isInMainView;
private String DeviceId;
private SoundPool sp;//声明一个SoundPool
private int music, music2;//;来设置suondID
public String shareCount;//分享的内容
public String imgPath;
public String pathURL;
public static int shakecount;
public String startName;
public static String usercountUrl;
public int select_menu_index;
public Bitmap headimg;
private Handler NetWorkhandler = new Handler() {
@Override
//当有消息发送出来的时候就执行Handler的这个方法
public void handleMessage(Message msg) {
super.handleMessage(msg);
//处理UI
obj_web.loadUrl(ExampleApplication.GetInstance().getString(R.string.MainView) + "?UserID=" + LocalDataObj.GetUserLocalData("UserID") + "&Code=" + LocalDataObj.GetUserLocalData("UserToken"));
}
};
public static PullToRefreshWebView GetPushInstance() {
return p_PushInstance;
}
private void setListeners() {
mShakeListener.setOnShakeListener(new ShakeListener.OnShakeListener() {
public void onShake() {
long currentUpdateTime = System.currentTimeMillis();
long timeInterval = currentUpdateTime - lastUpdateTime;
if (timeInterval < 3000)
return;
lastUpdateTime = currentUpdateTime;
//开始调用摇一摇接口 Shake.aspx
String url = obj_web.getUrl();
if (url.contains("Shake") && isInMainView == true) {
// url = obj_web.getUrl();
String uid = LocalDataObj.GetUserLocalData("UserID");
if (uid.equalsIgnoreCase("100") == true) { //说明是游客用户
Intent intent = new Intent(MainActivity.this, MainFragment.class);
intent.putExtra(MainFragment.EXTRA_VIEW_URL, ExampleApplication.GetInstance().getString(R.string.denglu_view));
intent.putExtra(MainFragment.EXTRA_FRAGMENT, MainFragment.FRAGMENT_ONEPAGEWEBVIEW);
// startActivity(intent);
startActivityForResult(intent, 0);
} else {
if (shakecount <= 0) {
Toast.makeText(MainActivity.this, "请购买次数", Toast.LENGTH_LONG).show();
return;
} else {
sp.play(music, 1, 1, 0, 0, 1);//播放声音
new Thread() {
@Override
public void run() {
//你要执行的方法
//执行完毕后给handler发送一个空消息
String Url = getString(R.string.serverurl) + "/ShakeStarIfno";
byte[] data = HttpUtils.GetWebServiceJsonContent(Url, "{\"UserId\":" + LocalDataObj.GetUserLocalData("UserID") + "," +
" \"Code\":\"" + LocalDataObj.GetUserLocalData("UserToken") + "\"}");
String Result = FileUtils.Bytes2String(data);
int nTemp = 0;
JSONObject Json = JsonUtils.Str2Json(Result);
try {
Json = Json.getJSONObject("d");
Json = Json.getJSONObject("Data");
// shakecount = Json.getInt("ShakeCount");
startName = Json.getString("StarName");
try {
sleep(800);
sp.pause(music);
if (!"".equals(startName)) {
sp.play(music2, 1, 1, 0, 0, 1);
}
Url = "javascript:ShakeStarIfno(" + Result + ")";
obj_web.loadUrl(Url);
shakecount--;
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (JSONException e) {
LogUitls.WriteLog("FileUtils", "WriteFile2Store", Json.toString(), e);
}
}
}.start();
}
}
}
}
});
}
private void initState() {
sp = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);//第一个参数为同时播放数据流的最大个数,第二数据流类型,第三为声音质量
music = sp.load(this, R.raw.shake_sound_male, 1); //把你的声音素材放到res/raw里,第2个参数即为资源文件,第3个为音乐的优先级
music2 = sp.load(this, R.raw.shake_sound, 1);
mShakeListener = new ShakeListener(this);
getShakecount();
setListeners();
}
//获取umeng统计测试设备信息
public static String getDeviceInfo(Context context) {
try{
org.json.JSONObject json = new org.json.JSONObject();
android.telephony.TelephonyManager tm = (android.telephony.TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
String device_id = tm.getDeviceId();
android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) context.getSystemService(Context.WIFI_SERVICE);
String mac = wifi.getConnectionInfo().getMacAddress();
json.put("mac", mac);
Log.d("MAC",mac);
if( TextUtils.isEmpty(device_id) ){
device_id = mac;
}
if( TextUtils.isEmpty(device_id) ){
device_id = android.provider.Settings.Secure.getString(context.getContentResolver(),android.provider.Settings.Secure.ANDROID_ID);
}
json.put("device_id", device_id);
return json.toString();
}catch(Exception e){
e.printStackTrace();
}
return null;
}
@Override
protected void onStop() {
super.onStop();
if (mShakeListener != null) {
mShakeListener.stop();//停止检测
}
}
@Override
protected void onPause() {
super.onPause();
MobclickAgent.onPause(this);//umeng统计
}
@Override
protected void onResume() {
super.onResume();
mShakeListener.start();
MobclickAgent.onResume(this); //umeng统计时长
}
View.OnClickListener button_listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.right_button:
String url = obj_web.getUrl();
if (url.contains("Guess")) {
url = ExampleApplication.GetInstance().getString(R.string.paihangbang_view) + "?UserID=" + LocalDataObj.GetUserLocalData("UserID") + "&Code=" + LocalDataObj.GetUserLocalData("UserToken");
Intent intent = new Intent(MainActivity.this, MainFragment.class);
intent.putExtra(MainFragment.EXTRA_VIEW_URL, url);
intent.putExtra(MainFragment.EXTRA_FRAGMENT, MainFragment.FRAGMENT_ONEPAGEWEBVIEW);
// startActivity(intent);
startActivityForResult(intent, 0);
}
break;
case R.id.bt_openmenu:
mMenuDrawer.openMenu();
getNewsCounts();//这个是得到个人中心的counts
break;
default:
break;
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isInMainView = true;
p_MainActivity = this;
getDeviceInfo(this);//获取测试设备信息,进行umeng统计分析
mMenuDrawer.setContentView(R.layout.main);
mMenuDrawer.setTouchMode(MenuDrawer.TOUCH_MODE_FULLSCREEN);
mMenuDrawer.setSlideDrawable(R.drawable.ic_drawer);
mMenuDrawer.setDrawerIndicatorEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
// getActionBar().setDisplayHomeAsUpEnabled(true);
}
bt_openmenu = (ImageButton) findViewById(R.id.bt_openmenu);
bt_openmenu.setOnClickListener(button_listener);
p_PushInstance = (PullToRefreshWebView) findViewById(R.id.webView);
titleView = (TextView) findViewById(R.id.titlename);
titleView.setText(R.string.maintitle);
ButtonText = (TextView) findViewById(R.id.buttontextView);
Rightbutton = (ImageButton) findViewById(R.id.right_button);
Rightbutton.setOnClickListener(button_listener);
// Rightbutton.setImageDrawable(getResources().getDrawable(R.drawable.tittlebtn));
Rightbutton.setImageDrawable(getResources().getDrawable(R.drawable.caifubang));
Rightbutton.setVisibility(View.GONE);
ButtonText.setVisibility(View.GONE);
p_PushInstance.setGravity(Gravity.BOTTOM);
obj_web = p_PushInstance.getRefreshableView();
p_PushInstance.setMode(PullToRefreshBase.Mode.BOTH);
p_PushInstance.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
p_PushInstance.getLoadingLayoutProxy(true, false).setPullLabel("下拉刷新");
p_PushInstance.getLoadingLayoutProxy(false, true).setPullLabel("上拉加载更多");
p_PushInstance.getLoadingLayoutProxy(true, true).setReleaseLabel("释放开始加载");
p_PushInstance.getLoadingLayoutProxy(true, true).setRefreshingLabel("正在加载");
p_PushInstance.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<WebView>() {
@Override
public void onPullDownToRefresh(PullToRefreshBase<WebView> refreshView) {
SetRefreshTitle(false);
// String Url = "javascript:CallBackData(0,'PullDownToRefresh',true,'')";
// p_PushInstance.onRefreshComplete();
obj_web.reload();
p_PushInstance.onRefreshComplete();
}
@Override
public void onPullUpToRefresh(PullToRefreshBase<WebView> refreshView) {
SetRefreshTitle(true);
String Url = "javascript:OnLoad()";
obj_web.loadUrl(Url);
}
public void SetRefreshTitle(Boolean mIsUp) {
//获取刷新时间,设置刷新时间格式
String str = DateUtils.formatDateTime(MainActivity.GetInstance(), System.currentTimeMillis(), (DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_NUMERIC_DATE));
// 设置刷新文本说明(刷新过程中)
if (mIsUp) {
p_PushInstance.getLoadingLayoutProxy(false, true).setLastUpdatedLabel("最后加载时间:" + str);
} else {
p_PushInstance.getLoadingLayoutProxy(true, false).setLastUpdatedLabel("最后更新时间:" + str);
}
}
});
obj_web.requestFocus();
WebSettings mWebSetting = obj_web.getSettings();
mWebSetting.setJavaScriptEnabled(true);
// mWebSetting.setUseWideViewPort(true);
mWebSetting.setDefaultTextEncodingName("UTF-8");
// mWebSetting.setLoadWithOverviewMode(true);
// mWebSetting.setCacheMode(WebSettings.LOAD_DEFAULT);
// mWebSetting.setAppCacheMaxSize(1024 * 1024 * 8);
// String appCacheDir = this.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();
// mWebSetting.setAppCachePath(appCacheDir);
// mWebSetting.setAllowFileAccess(true);
// mWebSetting.setAppCacheEnabled(true);
// //设置加载进来的页面自适应手机屏幕
// mWebSetting.setUseWideViewPort(true);
// mWebSetting.setLoadWithOverviewMode(true);
//
// mWebSetting.setJavaScriptCanOpenWindowsAutomatically(true);
// mWebSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
// mWebSetting.setSupportZoom(false);
// mWebSetting.setBuiltInZoomControls(false);
// mWebSetting.setGeolocationEnabled(true);
// mWebSetting.setDatabaseEnabled(true);
// String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
// mWebSetting.setDatabasePath(dir);
// mWebSetting.setDomStorageEnabled(true);
// obj_web.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
obj_web.addJavascriptInterface(new JavaScriptInterface(), "javatojs");
obj_web.setWebChromeClient(new UserWebClient());
obj_web.setWebViewClient(new NormalWebViewClient(this));
obj_web.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
MainActivity.GetInstance().startActivity(intent);
}
});
mMenuDrawer.setOnInterceptMoveEventListener(new MenuDrawer.OnInterceptMoveEventListener() {
@Override
public boolean isViewDraggable(View v, int dx, int x, int y) {
getNewsCounts();//这个是得到个人中心的counts
return v instanceof SeekBar;
}
});
String uid = LocalDataObj.GetUserLocalData("UserID");
if (uid.equalsIgnoreCase("") == true) {
new Thread() {
@Override
public void run() {
//你要执行的方法
//执行完毕后给handler发送一个空消息
String Url = getString(R.string.serverurl) + "/AutoLogin";
byte[] data = HttpUtils.GetWebServiceJsonContent(Url, null);
String Result = FileUtils.Bytes2String(data);
int nTemp = 0;
JSONObject Json = JsonUtils.Str2Json(Result);
try {
Json = Json.getJSONObject("d").getJSONObject("Data");
String uid = Json.getString("UserId");
String Code = Json.getString("Code");
LocalDataObj.SetUserLocalData("UserID", uid);
LocalDataObj.SetUserLocalData("UserToken", Code);
} catch (JSONException e) {
LogUitls.WriteLog("FileUtils", "WriteFile2Store", Json.toString(), e);
}
NetWorkhandler.sendEmptyMessage(0);
}
}.start();
} else {
NetWorkhandler.sendEmptyMessage(0);
}
initState();
getNewsCounts();//这个是得到个人中心的counts
}
public void getShakecount() {
new Thread() {
@Override
public void run() {
//获取摇一摇之前的次数
String Url = getString(R.string.serverurl) + "/GetShakeCount";
byte[] data = HttpUtils.GetWebServiceJsonContent(Url, "{\"UserId\":" + LocalDataObj.GetUserLocalData("UserID") + "," +
" \"Code\":\"" + LocalDataObj.GetUserLocalData("UserToken") + "\"}");
String Result = FileUtils.Bytes2String(data);
JSONObject Json = JsonUtils.Str2Json(Result);
try {
if (Json == null) {
return;
}
Json = Json.getJSONObject("d");
Json = Json.getJSONObject("Data");
int num = Json.getInt("ShakeCount");
Message MSG = new Message();
MSG.arg1 = 5;
MSG.arg2 = num;
updateHandler.sendMessage(MSG);
} catch (JSONException e) {
LogUitls.WriteLog("FileUtils", "WriteFile2Store", Json.toString(), e);
}
}
}.start();
}
public void getNewsCounts() {
new Thread() {
@Override
public void run() {
//执行完毕后给得到个人中心的评论条数
String Url = getString(R.string.serverurl) + "/GetUserCanReadData";
byte[] data = HttpUtils.GetWebServiceJsonContent(Url, "{\"UserId\":" + LocalDataObj.GetUserLocalData("UserID") + "," +
" \"Code\":\"" + LocalDataObj.GetUserLocalData("UserToken") + "\"}");
String Result = FileUtils.Bytes2String(data);
JSONObject Json = JsonUtils.Str2Json(Result);
try {
if (Json == null) {
return;
}
Json = Json.getJSONObject("d");//.getJSONObject("Data");
JSONArray jsonArray = Json.getJSONArray("Data");
int news = jsonArray.getInt(0);
int commentManagerCounts = jsonArray.getInt(1);
int counts = news + commentManagerCounts;
Message MSG = new Message();
MSG.arg1 = 3;
MSG.arg2 = counts;
updateHandler.sendMessage(MSG);
} catch (JSONException e) {
LogUitls.WriteLog("FileUtils", "WriteFile2Store", Json.toString(), e);
}
}
}.start();
}
//创建Handler对象,用来处理消息
Handler mExitHandler = new Handler() {
@Override
public void handleMessage(Message msg) {//处理消息
// TODO Auto-generated method stub
super.handleMessage(msg);
isExit = false;
}
};
public void SendCallBack(String path) {
String Url = "javascript:SetHeadPhoto(\"" + path + "\")";
obj_web.loadUrl(Url);
LocalDataObj.SetUserLocalData("UserHeadImg", path);//将此图像设置并保存到本地
}
public boolean onKeyDown(int keyCoder, KeyEvent event) {
if (keyCoder == KeyEvent.KEYCODE_BACK) {
ToQuitTheApp();
return false;
}
return true;
}
//封装ToQuitTheApp方法
private void ToQuitTheApp() {
if (isExit) {
// ACTION_MAIN with category CATEGORY_HOME 启动主屏幕
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
System.exit(0);// 使虚拟机停止运行并退出程序
} else {
isExit = true;
Toast.makeText(MainActivity.this, "再按一次退出APP", Toast.LENGTH_SHORT).show();
mExitHandler.sendEmptyMessageDelayed(0, 3000);// 3秒后发送消息
}
}
Handler updateHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.arg1) {
case 1://登陆wancheng
// Intent intent=new Intent();
// intent.setClass(MainFragment.GetInstance(), MainActivity.class);
// startActivity(intent);
MainFragment.GetInstance().finish();
break;
case 2: //通知页面停止刷新
if (p_PushInstance.isRefreshing())
p_PushInstance.onRefreshComplete();
break;
case 3://通知menu的新消息数量
titlecount = msg.arg2 + "";//得到个人中新消息数目
MenuAdapter.titleCount[6] = titlecount;
mAdapter.notifyDataSetChanged();
break;
case 4://个人中心每日任务的邀请好友分享
UMengUtils.InitUMengConfig(p_MainActivity);
UMengUtils.ShareContent(shareCount, ExampleApplication.GetInstance().getString(R.string.BaseIP) +
imgPath, ExampleApplication.GetInstance().getString(R.string.BaseIP) +
pathURL);//添加分享能容
break;
case 5://获取摇一摇的次数
shakecount = msg.arg2;
break;
}
}
};
public static MainActivity GetInstance() {
return p_MainActivity;
}
public static WebView GetWebView() {
return obj_web;
}
@Override
protected void onMenuItemClicked(int position, Item item) {
// mContentTextView.setText(item.mTitle);
Rightbutton.setVisibility(View.GONE);
ButtonText.setVisibility(View.GONE);
View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.menu_row_category, null, false);
View view1 = LayoutInflater.from(MainActivity.this).inflate(R.layout.menu_row_item, null, false);
view.setVisibility(View.GONE);
view1.setVisibility(View.GONE);
// mMenuDrawer.closeMenu();
select_menu_index = position;
switch (select_menu_index) {
case 0: //中超资讯
obj_web.loadUrl(ExampleApplication.GetInstance().getString(R.string.MainView) + "?UserID=" + LocalDataObj.GetUserLocalData("UserID") + "&Code=" + LocalDataObj.GetUserLocalData("UserToken"));
titleView.setText(R.string.maintitle);
p_PushInstance.setMode(PullToRefreshBase.Mode.BOTH);
break;
case 1: //中超竞猜
obj_web.loadUrl(ExampleApplication.GetInstance().getString(R.string.jingcai_view) + "?UserID=" + LocalDataObj.GetUserLocalData("UserID") + "&Code=" + LocalDataObj.GetUserLocalData("UserToken"));
titleView.setText(R.string.jingcaititle);
p_PushInstance.setMode(PullToRefreshBase.Mode.DISABLED);
Rightbutton.setVisibility(View.VISIBLE);
ButtonText.setVisibility(View.VISIBLE);
// ButtonText.setText(R.string.string2);
ButtonText.setText("");
break;
case 2: //中超球队
obj_web.loadUrl(ExampleApplication.GetInstance().getString(R.string.qiudui_view) + "?UserID=" + LocalDataObj.GetUserLocalData("UserID") + "&Code=" + LocalDataObj.GetUserLocalData("UserToken"));
titleView.setText(R.string.quiduititle);
p_PushInstance.setMode(PullToRefreshBase.Mode.DISABLED);
break;
case 3: //语音聊球
{
String uid = LocalDataObj.GetUserLocalData("UserID");
if (uid.equalsIgnoreCase("100") == true) { //说明是游客用户
Intent intent = new Intent(MainActivity.this, MainFragment.class);
intent.putExtra(MainFragment.EXTRA_VIEW_URL, ExampleApplication.GetInstance().getString(R.string.denglu_view));
intent.putExtra(MainFragment.EXTRA_FRAGMENT, MainFragment.FRAGMENT_ONEPAGEWEBVIEW);
startActivityForResult(intent, 0);
} else {
String UserNick = LocalDataObj.GetUserLocalData("UserNick");
String UserHeadImg = LocalDataObj.GetUserLocalData("UserHeadImg");
String download = getString(R.string.BaseIP) + UserHeadImg;
downloadImageByAsyncTask(download);
/*if(headimg == null){
headimg = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
}
GotyeSDK.getInstance().startGotyeSDK(MainActivity.this, LocalDataObj.GetUserLocalData("UserID"), LocalDataObj.GetUserLocalData("UserNick"), GotyeSex.NOT_SET, headimg, null);*/
}
}
break;
case 4: //趣味竞猜
obj_web.loadUrl(ExampleApplication.GetInstance().getString(R.string.quweijingcai_view) + "?UserID=" + LocalDataObj.GetUserLocalData("UserID") + "&Code=" + LocalDataObj.GetUserLocalData("UserToken"));
titleView.setText(R.string.quweijingcaititle);
p_PushInstance.setMode(PullToRefreshBase.Mode.DISABLED);
break;
case 5: //摇球星卡
obj_web.loadUrl(ExampleApplication.GetInstance().getString(R.string.qiuxingka_view) + "?UserID=" + LocalDataObj.GetUserLocalData("UserID") + "&Code=" + LocalDataObj.GetUserLocalData("UserToken"));
titleView.setText(R.string.qiuxingkatitle);
p_PushInstance.setMode(PullToRefreshBase.Mode.DISABLED);
break;
case 6: //个人中心
String uid = LocalDataObj.GetUserLocalData("UserID");
if (uid.equalsIgnoreCase("100") == true) { //说明是游客用户
Intent intent = new Intent(MainActivity.this, MainFragment.class);
intent.putExtra(MainFragment.EXTRA_VIEW_URL, ExampleApplication.GetInstance().getString(R.string.denglu_view));
intent.putExtra(MainFragment.EXTRA_FRAGMENT, MainFragment.FRAGMENT_ONEPAGEWEBVIEW);
// startActivity(intent);
startActivityForResult(intent, 0);
} else {
String sUrl = ExampleApplication.GetInstance().getString(R.string.gerenzhongxin_view) + "?UserID=" + LocalDataObj.GetUserLocalData("UserID") + "&Code=" + LocalDataObj.GetUserLocalData("UserToken");
obj_web.loadUrl(sUrl);
titleView.setText(R.string.gerenzhongxintitle);
p_PushInstance.setMode(PullToRefreshBase.Mode.DISABLED);
}
break;
case 7: //关于我们
obj_web.loadUrl(ExampleApplication.GetInstance().getString(R.string.guanyuwomen_view) + "?UserID=" + LocalDataObj.GetUserLocalData("UserID") + "&Code=" + LocalDataObj.GetUserLocalData("UserToken"));
titleView.setText(R.string.guanyuwomentitle);
p_PushInstance.setMode(PullToRefreshBase.Mode.DISABLED);
break;
}
// }
// }, 50);
mMenuDrawer.closeMenu();
}
private void downloadImageByAsyncTask(final String url) {
AsyncTask<String, Integer, Boolean> asyncTask = new AsyncTask<String, Integer, Boolean>() {
private String filePath = null;
@Override
protected void onProgressUpdate(Integer... values) {
}
@Override
protected Boolean doInBackground(String... params) {
try {
String downloadUrl = params[0];
HttpGet request = new HttpGet(downloadUrl);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = null;
response = httpClient.execute(request);
InputStream inputStream = response.getEntity().getContent();
filePath = Environment.getExternalStorageDirectory().getPath() + "/Head.jpg";
FileOutputStream outputStream = new FileOutputStream(filePath);
byte[] buf = new byte[1024];
int length;
while ((length = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, length);
publishProgress(length);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
Log.d("TAG", "运气不太好,异常了", e);
return false;
}
return true;
}
//该方法运行在UI线程当中,并且运行在UI线程当中 可以对UI空间进行设置
@Override
protected void onPreExecute() {
}
@Override
protected void onPostExecute(Boolean result) {
if (result) {
// Uri uri = Uri.fromFile(new File(filePath));
headimg = BitmapFactory.decodeFile(filePath, null);
if (headimg == null) {
headimg = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
}
GotyeSDK.getInstance().startGotyeSDK(MainActivity.this, LocalDataObj.GetUserLocalData("UserID"), LocalDataObj.GetUserLocalData("UserNick"), GotyeSex.NOT_SET, headimg, null);
} else {
headimg = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
GotyeSDK.getInstance().startGotyeSDK(MainActivity.this, LocalDataObj.GetUserLocalData("UserID"), LocalDataObj.GetUserLocalData("UserNick"), GotyeSex.NOT_SET, headimg, null);
}
}
};
asyncTask.execute(url);
}
@Override
protected int getDragMode() {
return MenuDrawer.MENU_DRAG_CONTENT;
}
@Override
protected Position getDrawerPosition() {
return Position.LEFT;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// outState.putString(STATE_CONTENT_TEXT, mContentText);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mMenuDrawer.toggleMenu();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
final int drawerState = mMenuDrawer.getDrawerState();
if (drawerState == MenuDrawer.STATE_OPEN || drawerState == MenuDrawer.STATE_OPENING) {
mMenuDrawer.closeMenu();
return;
}
super.onBackPressed();
}
public void StartChat(final String[] uInfo) {
new Thread(
new Runnable() {
@Override
public void run() {
byte[] BitArray = HttpUtils.GetURLContent(uInfo[1]);
// byte[] BitArray = HttpUtils.GetURLContent_img("http://img4.duitang.com/uploads/item/201207/13/20120713173422_VNZ4Q.thumb.600_0.jpeg");
// Bitmap HeadPic = null;
if (BitArray != null) {
HeadPic = BitmapFactory.decodeByteArray(BitArray, 0, BitArray.length);
}
}
}
).start();
String username = uInfo[0] + android.provider.Settings.Secure.getString(MainActivity.GetInstance().getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
GotyeSDK.getInstance().startGotyeSDK(MainActivity.GetInstance(), username, uInfo[0], GotyeSex.NOT_SET, HeadPic, null);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
isInMainView = true;
try {
switch (resultCode) { //resultCode为回传的标记,我在B中回传的是RESULT_OK
case RESULT_CANCELED:
if (data != null) {
Bundle bundle = data.getExtras();
int ChangeState = bundle.getInt("ChangeState");
switch (ChangeState) {
case 1: //选择用户返回
String sUrl = ExampleApplication.GetInstance().getString(R.string.gerenzhongxin_view) + "?UserID=" + LocalDataObj.GetUserLocalData("UserID") + "&Code=" + LocalDataObj.GetUserLocalData("UserToken");
obj_web.loadUrl(sUrl);
titleView.setText(R.string.gerenzhongxintitle);
p_PushInstance.setMode(PullToRefreshBase.Mode.DISABLED);
break;
case 2: //登陆以后的返回
String url = obj_web.getUrl();
String a[] = url.split("\\?");
url = url + "?UserID=" + LocalDataObj.GetUserLocalData("UserID") + "&Code=" + LocalDataObj.GetUserLocalData("UserToken");
obj_web.loadUrl(url);
//设置jpush推送的别名
ExampleApplication.GetInstance().SetJpushAlias(LocalDataObj.GetUserLocalData("UserID"));
break;
case 3: //普通返回不需要处理
String uri = obj_web.getUrl();
if (uri.contains("PageUserInfoData")) {//当查看完信息后返回时页面重新加载,提示消息消失
obj_web.loadUrl(uri);
} else if (uri.contains("Guess")) {//当竞猜支持后返回竞猜列表时页面的刷新
obj_web.reload();
}
break;
}
}
break;
case RESULT_OK: {
switch (requestCode) {
case Constant.REQUEST_CODE_TAKE_PICTURE:
ContentResolver resolver = getContentResolver();
Uri originalUri = data.getData(); //获得图片的uri
Bitmap MediaPic = null;
try {
MediaPic = MediaStore.Images.Media.getBitmap(resolver, originalUri);
UserPhotoUtils.UploadSubmit(MediaPic, pamars);
} catch (Exception e) {
e.printStackTrace();
}
break;
case Constant.REQUEST_CODE_TAKE_CAPTURE:
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(UserPhotoUtils.GetTempFileUri(), "image/*");
// crop为true是设置在开启的intent中设置显示的view可以剪裁
intent.putExtra("crop", "true");
// aspectX aspectY 是宽高的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// outputX,outputY 是剪裁图片的宽高
intent.putExtra("outputX", Constant.OUT_PUT_PIC_WIDTH);
intent.putExtra("outputY", Constant.OUT_PUT_PIC_HEGITH);
intent.putExtra("return-data", true);
intent.putExtra("noFaceDetection", true);
startActivityForResult(intent, Constant.REQUEST_CODE_REUSLT_PICTURE);
break;
case Constant.REQUEST_CODE_REUSLT_PICTURE:
Bitmap ResultPic = data.getParcelableExtra("data");
UserPhotoUtils.UploadSubmit(ResultPic, pamars);
break;
}
break;
}
default:
break;
}
} catch (ArrayIndexOutOfBoundsException e) {
Log.d("ArrayIndexOutOfBoundsException", e.getLocalizedMessage());
}
}
public class JavaScriptInterface {
@JavascriptInterface
public void RunAndroidFunction(String JsonParams) throws JSONException {
Log.i("COMMAND", JsonParams);
JSONObject Json = JsonUtils.Str2Json(JsonParams);
if (Json == null) return;
try {
int Type = Json.getInt("Type");
String Name = Json.getString("Name");
String Params = Json.getString("Parms");
JSONObject objectParams;
switch (Type) {
case 1:
break;
case 0:
if (Name.equalsIgnoreCase("PayInfo"))//支付宝支付
{
JSONArray array = Json.getJSONArray("Parms");
String Content = array.getString(0);
AlipayPayinfo alipay = new AlipayPayinfo();
alipay.AlipayPay(GetInstance(), Content);
break;
}
if (Name.equalsIgnoreCase("ShearContent")) {//个人中心中的邀请好友分享
objectParams = JsonUtils.Str2Json(Params);
shareCount = objectParams.getString("Title");
imgPath = objectParams.getString("NewsImg");
pathURL = objectParams.getString("Url");
Message MSG = new Message();
MSG.arg1 = 4;
updateHandler.sendMessage(MSG);
break;
}
if (Name.equalsIgnoreCase("GetDriverToken")) {//这是返回手机Token
TelephonyManager tm = (TelephonyManager) GetInstance().getSystemService(Context.TELEPHONY_SERVICE);
DeviceId = tm.getDeviceId();
String Url = "javascript:SetToken(" + DeviceId + ")";
obj_web.loadUrl(Url);
break;
}
if (Name.equalsIgnoreCase("MobileUserAdvice")) {//关于我们中的意见反馈
//意见反馈的启动
FeedbackAgent agent = new FeedbackAgent(MainActivity.GetInstance());
agent.startFeedbackActivity();
break;
}
if (Name.equalsIgnoreCase("ShowSelectPic")) {//个人中心的图像上传接口
// chooise();
pamars = Params + "UserId=" + LocalDataObj.GetUserLocalData("UserID") + "&Code=" + LocalDataObj.GetUserLocalData("UserToken");
UserPhotoUtils.StartUploadPhoto();
break;
}
//判断是否带参数
if (Name.equalsIgnoreCase("AccountManager") == true) {
String url = null;
String jsonStr = LocalDataObj.GetUserLocalData("LocalUserJson");
JSONArray userArray;
userArray = JsonUtils.Str2JsonArray(jsonStr);
if (userArray.length() < 2) {
url = ExampleApplication.GetInstance().getString(R.string.denglu_view);
} else {
String nameList = "";
for (int i = 0; i < userArray.length(); i++) {
JSONObject user = (JSONObject) userArray.get(i);
nameList += user.getString("UserNick");
// try {
// nameList = new String(nameList.getBytes("gb2312"), "utf-8");
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
if (i != userArray.length() - 1)
nameList += ",";
}
try {
nameList = new String(nameList.getBytes(), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
url = ExampleApplication.GetInstance().getString(R.string.guanlizhanghao_view) + "?nameList=" + nameList + "&UserNick=" + LocalDataObj.GetUserLocalData("UserNick");
}
if (url != null) {
usercountUrl = url;//多个账号选择时返回处理
Intent intent = new Intent(MainActivity.this, MainFragment.class);
intent.putExtra(MainFragment.EXTRA_VIEW_URL, url);
intent.putExtra(MainFragment.EXTRA_FRAGMENT, MainFragment.FRAGMENT_ONEPAGEWEBVIEW);
startActivityForResult(intent, 0);
// startActivity(intent);
}
break;
}
if (Name.equalsIgnoreCase("OnLoadFinish") == true) {
Message MSG = new Message();
MSG.arg1 = 2;
updateHandler.sendMessage(MSG);
break;
}
//跳转球队
if (Name.equalsIgnoreCase("JumpCampStar") == true) {
objectParams = JsonUtils.Str2Json(Params);
String url = ExampleApplication.GetInstance().getString(R.string.MainIP)
+ objectParams.getString("PageName")
+ ".aspx"
+ objectParams.getString("Parms")
+ "&UserID="
+ LocalDataObj.GetUserLocalData("UserID")
+ "&Code="
+ LocalDataObj.GetUserLocalData("UserToken");
if (url != null) {
Intent intent = new Intent(MainActivity.this, MainFragment.class);
intent.putExtra(MainFragment.EXTRA_VIEW_URL, url);
intent.putExtra(MainFragment.EXTRA_FRAGMENT, MainFragment.FRAGMENT_ONEPAGEWEBVIEW);
intent.putExtra(MainFragment.EXTRA_FRAGMENTTITLE, objectParams.getString("Title"));
startActivityForResult(intent, 0);
}
}
//跳转页进行判断
if (Name.equalsIgnoreCase("JumpPage") == true) {
objectParams = JsonUtils.Str2Json(Params);
String isSelf = objectParams.getString("IsSelf");
//自身子菜单跳转
if (isSelf.equalsIgnoreCase("true") == true) {
String url;
if (objectParams.getString("Parms").equalsIgnoreCase("?") == true) {
url = ExampleApplication.GetInstance().getString(R.string.MainIP)
+ objectParams.getString("PageName")
+ ".aspx"
+ objectParams.getString("Parms")
+ "UserID="
+ LocalDataObj.GetUserLocalData("UserID")
+ "&Code="
+ LocalDataObj.GetUserLocalData("UserToken");
} else {
url = ExampleApplication.GetInstance().getString(R.string.MainIP)
+ objectParams.getString("PageName")
+ ".aspx"
+ objectParams.getString("Parms")
+ "&UserID="
+ LocalDataObj.GetUserLocalData("UserID")
+ "&Code="
+ LocalDataObj.GetUserLocalData("UserToken");
}
obj_web.loadUrl(url);
} else {
String url = ExampleApplication.GetInstance().getString(R.string.MainIP)
+ objectParams.getString("PageName")
+ ".aspx"
+ objectParams.getString("Parms")
+ "&UserID="
+ LocalDataObj.GetUserLocalData("UserID")
+ "&Code="
+ LocalDataObj.GetUserLocalData("UserToken");
if (url != null) {
if (url.contains("AboutPage")) {
String s1[] = url.split("\\?");
s1 = s1[1].split("\\&");
s1 = s1[0].split("\\=");
int type = Integer.parseInt(s1[1]);
switch (type) {
case 1://obj_web.loadUrl("http://t.qq.com/cslapp");//腾讯微博
{
Intent intent = new Intent(MainActivity.this, MainFragment.class);
intent.putExtra(MainFragment.EXTRA_VIEW_URL, "http://t.qq.com/cslapp");
intent.putExtra(MainFragment.EXTRA_FRAGMENT, MainFragment.FRAGMENT_ONEPAGEWEBVIEW);
startActivityForResult(intent, 0);
}
break;
case 2://obj_web.loadUrl("http://weibo.com/cslapp");//新浪微博
{
Intent intent = new Intent(MainActivity.this, MainFragment.class);
intent.putExtra(MainFragment.EXTRA_VIEW_URL, "http://weibo.com/cslapp");
intent.putExtra(MainFragment.EXTRA_FRAGMENT, MainFragment.FRAGMENT_ONEPAGEWEBVIEW);
startActivityForResult(intent, 0);
}
break;
case 3: {
Intent intent = new Intent(MainActivity.this, MainFragment.class);
intent.putExtra(MainFragment.EXTRA_VIEW_URL, url);
intent.putExtra(MainFragment.EXTRA_FRAGMENT, MainFragment.FRAGMENT_ONEPAGEWEBVIEW);
startActivityForResult(intent, 0);
}
break;
}
return;
}
Intent intent = new Intent(MainActivity.this, MainFragment.class);
intent.putExtra(MainFragment.EXTRA_VIEW_URL, url);
if (url.contains("SelectNews")) {
intent.putExtra(MainFragment.EXTRA_FRAGMENT, MainFragment.FRAGMENT_EDITPAGEWEBVIEW);
} else {
intent.putExtra(MainFragment.EXTRA_FRAGMENT, MainFragment.FRAGMENT_ONEPAGEWEBVIEW);
}
isInMainView = false;
// startActivity(intent);
startActivityForResult(intent, 0);
}
}
break;
}
break;
}
} catch (JSONException e) {
LogUitls.WriteLog("FileUtils", "WriteFile2Store", Json.toString(), e);
}
}
}
}
|
package blue.sparse.minecraft;
import blue.sparse.minecraft.module.ModuleManager;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Plugin class for the SparseMC API
*/
public final class SparseMCAPIPlugin extends JavaPlugin {
private static final List<Runnable> disableHooks = new ArrayList<>();
private static SparseMCAPIPlugin plugin;
public static void addDisableHook(Runnable runnable) {
disableHooks.add(runnable);
}
public static File getDependenciesFolder() {
return new File(dataFolder(), "dependencies");
}
public static File dataFolder() {
return getPlugin().getDataFolder();
}
/**
* @return the instance of SparseMCAPIPlugin
*/
public static SparseMCAPIPlugin getPlugin() {
return plugin;
}
public void onLoad() {
plugin = this;
KotlinLoader.load(getDependenciesFolder());
}
public void onEnable() {
ModuleManager.INSTANCE.onPluginEnable();
}
public void onDisable() {
ModuleManager.INSTANCE.onPluginDisable();
disableHooks.forEach(Runnable::run);
System.gc();
}
}
|
public class Main{
public static void main(String arg[]){
Something object = new Something();
/*
Counter.countNow();
Counter.countNow();
*/
}
}
/*консоль:
Ivan@Ivan19981305 MINGW64 /d/repos/Netcracker-2021-Georgiev/15.03.21 (main)
$ javac Main.java
Ivan@Ivan19981305 MINGW64 /d/repos/Netcracker-2021-Georgiev/15.03.21 (main)
$ java Main
static block
Constructor
*/
class Counter{
static int count = 0;
public static void countNow(){
count++;
System.out.println("now - " + count);
}
}
class Something{
static int count = 0;
public Something(){
System.out.println("Constructor");
}
static{
System.out.println("static block");
}
}
|
package com.sparshik.yogicapple;
import android.content.Context;
import android.support.multidex.MultiDex;
import android.util.Log;
import com.google.firebase.FirebaseApp;
import com.google.firebase.crash.FirebaseCrash;
import com.google.firebase.database.FirebaseDatabase;
import timber.log.Timber;
/**
* Includes one-time initialization of Firebase related code
*/
public class YogicAppleApplication extends android.app.Application{
@Override
public void onCreate() {
super.onCreate();
if (!FirebaseApp.getApps(this).isEmpty()) {
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
// FirebaseDatabase.getInstance().setLogLevel(Logger.Level.DEBUG);
}
if (BuildConfig.DEBUG) {
Timber.plant(new Timber.DebugTree() {
@Override
protected String createStackElementTag(StackTraceElement element) {
return super.createStackElementTag(element) + ":" + element.getLineNumber();
}
});
} else {
Timber.plant(new CrashReportingTree());
}
}
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
/**
* A tree which logs important information for crash reporting.
*/
private static class CrashReportingTree extends Timber.Tree {
@Override
protected void log(int priority, String tag, String message, Throwable t) {
if (priority == Log.VERBOSE || priority == Log.DEBUG) {
return;
}
if (t != null) {
if (priority == Log.ERROR) {
FirebaseCrash.logcat(Log.ERROR, tag, message);
} else if (priority == Log.WARN) {
FirebaseCrash.logcat(Log.WARN, tag, message);
}
}
}
}
}
|
package com.aliam3.polyvilleactive.dsl.events;
/**
* Classe enum des differents alea qui peuvent survenir. Un rang de priorite est applique pour chaque alea.
* Ce rang est utilise pour regler les potentiels conflits de regles.
* @author vivian
*
*/
public enum Alea {
PANNE("PANNE", Integer.MAX_VALUE),
AVANCE("AVANCE", 2),
NEIGE("NEIGE", 2),
PLUIE("PLUIE", 2),
RETARD("RETARD", 1),
REMPLI("REMPLI", 1),
SOLEIL("SOLEIL", -1);
private final String type;
private final int priority; // the higher the better
Alea(String type, int priority) {
this.type = type;
this.priority = priority;
}
public String getType() {
return type;
}
public int getPriority() {
return priority;
}
@Override
public String toString() {
return type;
}
}
|
package com.cts.airline.reservation.entities;
import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
/**
* The persistent class for the airline_info database table.
*
*/
@Entity
@Table(name="airline_info")
public class AirlineInfo implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name="airline_id")
@GeneratedValue
private long airlineId;
@Column(name="airline_logo")
private String airlineLogo;
@Column(name="name_of_airline")
private String nameOfAirline;
//bi-directional many-to-many association to FlightInfo
@ManyToMany
@JoinTable(
name="flights_info"
, joinColumns={
@JoinColumn(name="airline_id")
}
, inverseJoinColumns={
@JoinColumn(name="flight_infoid")
}
)
private List<FlightInfo> flightInfos;
public AirlineInfo() {
}
public long getAirlineId() {
return this.airlineId;
}
public void setAirlineId(long airlineId) {
this.airlineId = airlineId;
}
public String getAirlineLogo() {
return this.airlineLogo;
}
public void setAirlineLogo(String airlineLogo) {
this.airlineLogo = airlineLogo;
}
public String getNameOfAirline() {
return this.nameOfAirline;
}
public void setNameOfAirline(String nameOfAirline) {
this.nameOfAirline = nameOfAirline;
}
public List<FlightInfo> getFlightInfos() {
return this.flightInfos;
}
public void setFlightInfos(List<FlightInfo> flightInfos) {
this.flightInfos = flightInfos;
}
}
|
/**
*
*/
package com.binarysprite.evemat.page.character;
import java.util.Collection;
import org.seasar.doma.jdbc.tx.LocalTransaction;
import com.beimin.eveapi.account.characters.CharactersParser;
import com.beimin.eveapi.account.characters.EveCharacter;
import com.beimin.eveapi.core.ApiAuth;
import com.beimin.eveapi.core.ApiAuthorization;
import com.beimin.eveapi.core.ApiException;
import com.binarysprite.evemat.DB;
import com.binarysprite.evemat.entity.AccountCharacter;
import com.binarysprite.evemat.entity.AccountCharacterDao;
import com.binarysprite.evemat.entity.AccountCharacterDaoImpl;
/**
* @author Tabunoki
*
*/
public class CharacterAddPageService {
/**
* 指定の user ID と varification code からキャラクター情報を取得し、データベースへ登録します。
*
* @param userID
* User ID
* @param varificationCode
* Varification code
* @throws Exception
*/
public void register(int userID, String varificationCode) throws Exception {
final ApiAuthorization apiAuthorization = new ApiAuthorization(userID, varificationCode);
final Collection<EveCharacter> eveCharacters;
eveCharacters = getEveCharacters(apiAuthorization);
if (eveCharacters == null || eveCharacters.isEmpty()) {
throw new Exception("CharacterRegisterService でエラーが発生しました");
}
addCharacter(eveCharacters, apiAuthorization);
}
/**
* EVE API より取得したキャラクター情報をデータベースへ追加します。
*
* @param eveCharacters
* EVE API より取得したキャラクター情報
*/
private void addCharacter(Collection<EveCharacter> eveCharacters, ApiAuth<ApiAuthorization> apiAuth) {
LocalTransaction transaction = DB.getLocalTransaction();
try {
// トランザクションの開始
transaction.begin();
AccountCharacterDao dao = new AccountCharacterDaoImpl();
for (EveCharacter eveCharacter : eveCharacters) {
AccountCharacter character = new AccountCharacter();
character.setCharacterId(eveCharacter.getCharacterID());
character.setCharacterName(eveCharacter.getName());
character.setCorporationId(eveCharacter.getCorporationID());
character.setCoporationName(eveCharacter.getCorporationName());
character.setApiId(apiAuth.getKeyID());
character.setApiVerificationCode(apiAuth.getVCode());
dao.insert(character);
}
transaction.commit();
} finally {
transaction.rollback();
}
}
/**
* EVE API よりキャラクター情報を取得します。
*
* @param apiAuth
* EVE API の認証情報
* @return
*/
private Collection<EveCharacter> getEveCharacters(ApiAuth<ApiAuthorization> apiAuth) {
Collection<EveCharacter> eveCharacters = null;
try {
eveCharacters = CharactersParser.getInstance().getResponse(apiAuth).getAll();
} catch (ApiException e) {
e.printStackTrace();
}
return eveCharacters;
}
}
|
package com.acompanhamento.api.web.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TerapeutaDTO {
private Long id;
private String nomeCompleto;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy")
private Date dataNascimento;
private Long telefone;
private Long crfa;
private String cpf;
private String especialidade;
private String formacao;
private String loginEmail;
private EnderecoDTO endereco;
}
|
package com.bofsoft.laio.customerservice.Widget;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.bofsoft.laio.customerservice.R;
public class IndexTabBarView extends RelativeLayout {
private Context context;
private int resIdSelected;
private int resIdNormal;
private TextView titleTv;
private int cnt = 0;
private ImageView ico;
private TextView cntTv;
public IndexTabBarView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
}
public IndexTabBarView(Context context, int resId) {
super(context, null);
this.context = context;
init(resId);
}
public void setResource(int normalId, int selectedId, String title) {
this.resIdNormal = normalId;
this.resIdSelected = selectedId;
this.titleTv.setText(title);
setNormal();
}
public void setCnt(int cnt) {
this.cnt = cnt;
if (cnt <= 0) {
cntTv.setVisibility(View.GONE);
} else {
cntTv.setVisibility(View.VISIBLE);
if (cnt >= 1000) {
cntTv.setText(" ");
} else {
cntTv.setText(cnt + "");
}
}
}
public void init(int resId) {
LayoutInflater.from(context).inflate(resId, this, true);
ico = (ImageView) findViewById(R.id.ico_iv);
titleTv = (TextView) findViewById(R.id.title_tv);
cntTv = (TextView) findViewById(R.id.cnt_tv);
setCnt(0);
}
public void setSelected() {
ico.setImageDrawable(getResources().getDrawable(resIdSelected));
titleTv.setTextColor(getResources().getColor(R.color.textcolor_green));
}
public void setNormal() {
ico.setImageDrawable(getResources().getDrawable(resIdNormal));
titleTv.setTextColor(getResources().getColor(R.color.textcolor_gray));
}
}
|
import java.util.Vector;
import static org.junit.Assert.*;
/**
* Created by HP on 17/10/2017.
*/
public class VectorHelperTest {//these are testes i want to add
@org.junit.Test
public void inverser_vector() throws Exception {
//voici un commentaire
Vector<Integer> inppuut = new Vector<Integer>();
inppuut.add(1);
inppuut.add(2);
inppuut.add(3);
inppuut.add(4);
Vector<Integer> expec = new Vector<Integer>();
expec.add(4);
expec.add(3);
expec.add(2);
expec.add(1);
VectorHelper.inverser_vector(inppuut);
assertEquals(expec, inppuut);
}
}
|
package com.wencheng.service;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import com.wencheng.domain.Project;
public interface ProjectService {
public boolean create(HttpServletRequest request);
public boolean delete();
public boolean checkName(HttpServletRequest request);
public boolean checkNum(HttpServletRequest request);
public Project find(HttpServletRequest request);
public List<Project> list(int start,int rows);
public List<Project> listSchool(int school,int start,int rows);
public List<Project> listTeacher(HttpServletRequest request,int start,int rows);
public int getRows();
public int getTeacherRows(HttpServletRequest request);
public Project findProject(HttpServletRequest request);
public boolean addTeacher(HttpServletRequest request);
public Project findOther(HttpServletRequest request);
public List<String> getGrades();
}
|
package common;
import java.awt.Rectangle;
import java.util.ArrayList;
import weapon.Weapon;
import enitity.Entity;
public class CollisionHandler {
private ArrayList EntityObjects, weaponObjects;
public CollisionHandler(){
EntityObjects = new ArrayList();
weaponObjects = new ArrayList();
}
public void addCollision(ArrayList<? extends Entity> EntityList, ArrayList<? extends Weapon> weaponList){
EntityObjects.add(EntityList);
weaponObjects.add(weaponList);
}
public void collisionCheck(){
for(int i = 0; i < EntityObjects.size(); i++){
ArrayList<Entity> entityList1 = (ArrayList<Entity>)EntityObjects.get(i);
ArrayList<Weapon> entityList2 = (ArrayList<Weapon>)weaponObjects.get(i);
for(int j = 0; j < entityList1.size(); j++){
Rectangle hitBox1 = entityList1.get(j).getHitBox();
for(int k = 0; k < entityList2.size(); k++){
Rectangle hitBox2 = entityList2.get(k).getHitBox();
if(hitBox1.intersects(hitBox2)){
entityList1.get(j).doDamage(entityList2.get(k));
}
}
}
}
}
}
|
package com.zjf.myself.codebase.thirdparty.parallaxView;
import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewConfiguration;
import android.view.animation.DecelerateInterpolator;
/**
* Created by XiaoJianjun on 2017/6/17.
* 视差RecyclerView.
*/
public class ParallaxRecyclerView extends RecyclerView {
private boolean isRestoring;
private int mActivePointerId;
private float mInitialMotionY;
private boolean isBeingDragged;
private float mScale;
private float mDistance;
private int mTouchSlop;
public ParallaxRecyclerView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
int action = MotionEventCompat.getActionMasked(event);
if (isRestoring && action == MotionEvent.ACTION_DOWN) {
isRestoring = false;
}
if (!isEnabled() || isRestoring || (!isScrollToTop() && !isScrollToBottom())) {
return super.onInterceptTouchEvent(event);
}
switch (action) {
case MotionEvent.ACTION_DOWN: {
mActivePointerId = event.getPointerId(0);
isBeingDragged = false;
float initialMotionY = getMotionEventY(event);
if (initialMotionY == -1) {
return super.onInterceptTouchEvent(event);
}
mInitialMotionY = initialMotionY;
break;
}
case MotionEvent.ACTION_MOVE: {
if (mActivePointerId == MotionEvent.INVALID_POINTER_ID) {
return super.onInterceptTouchEvent(event);
}
final float y = getMotionEventY(event);
if (y == -1f) {
return super.onInterceptTouchEvent(event);
}
if (isScrollToTop() && !isScrollToBottom()) {
// 在顶部不在底部
float yDiff = y - mInitialMotionY;
if (yDiff > mTouchSlop && !isBeingDragged) {
isBeingDragged = true;
}
} else if (!isScrollToTop() && isScrollToBottom()) {
// 在底部不在顶部
float yDiff = mInitialMotionY - y;
if (yDiff > mTouchSlop && !isBeingDragged) {
isBeingDragged = true;
}
} else if (isScrollToTop() && isScrollToBottom()) {
// 在底部也在顶部
float yDiff = y - mInitialMotionY;
if (Math.abs(yDiff) > mTouchSlop && !isBeingDragged) {
isBeingDragged = true;
}
} else {
// 不在底部也不在顶部
return super.onInterceptTouchEvent(event);
}
break;
}
case MotionEventCompat.ACTION_POINTER_UP:
onSecondaryPointerUp(event);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
mActivePointerId = MotionEvent.INVALID_POINTER_ID;
isBeingDragged = false;
break;
}
return isBeingDragged || super.onInterceptTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (MotionEventCompat.getActionMasked(event)) {
case MotionEvent.ACTION_DOWN:
mActivePointerId = event.getPointerId(0);
isBeingDragged = false;
break;
case MotionEvent.ACTION_MOVE: {
float y = getMotionEventY(event);
if (isScrollToTop() && !isScrollToBottom()) {
// 在顶部不在底部
mDistance = y - mInitialMotionY;
if (mDistance < 0) {
return super.onTouchEvent(event);
}
mScale = calculateRate(mDistance);
pull(mScale);
} else if (!isScrollToTop() && isScrollToBottom()) {
// 在底部不在顶部
mDistance = mInitialMotionY - y;
if (mDistance < 0) {
return super.onTouchEvent(event);
}
mScale = calculateRate(mDistance);
push(mScale);
} else if (isScrollToTop() && isScrollToBottom()) {
// 在底部也在顶部
mDistance = y - mInitialMotionY;
if (mDistance > 0) {
mScale = calculateRate(mDistance);
pull(mScale);
} else {
mScale = calculateRate(-mDistance);
push(mScale);
}
} else {
// 不在底部也不在顶部
return super.onTouchEvent(event);
}
break;
}
case MotionEventCompat.ACTION_POINTER_DOWN:
mActivePointerId = event.getPointerId(MotionEventCompat.getActionIndex(event));
break;
case MotionEventCompat.ACTION_POINTER_UP:
onSecondaryPointerUp(event);
break;
case MotionEvent.ACTION_UP: {
if (isScrollToTop() && !isScrollToBottom()) {
animateRestore(true);
} else if (!isScrollToTop() && isScrollToBottom()) {
animateRestore(false);
} else if (isScrollToTop() && isScrollToBottom()) {
if (mDistance > 0) {
animateRestore(true);
} else {
animateRestore(false);
}
} else {
return super.onTouchEvent(event);
}
break;
}
}
return true;
}
private boolean isScrollToTop() {
return !ViewCompat.canScrollVertically(this, -1);
}
private boolean isScrollToBottom() {
return !ViewCompat.canScrollVertically(this, 1);
}
private float getMotionEventY(MotionEvent event) {
int index = event.findPointerIndex(mActivePointerId);
return index < 0 ? -1f : event.getY(index);
}
private void onSecondaryPointerUp(MotionEvent event) {
final int pointerIndex = MotionEventCompat.getActionIndex(event);
final int pointerId = event.getPointerId(pointerIndex);
if (pointerId == mActivePointerId) {
int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mActivePointerId = event.getPointerId(newPointerIndex);
}
}
private float calculateRate(float distance) {
int screenHeight = getResources().getDisplayMetrics().heightPixels;
float originalDragPercent = distance / screenHeight;
float dragPercent = Math.min(1f, originalDragPercent);
float rate = 2f * dragPercent - (float) Math.pow(dragPercent, 2f);
return 1 + rate / 5f;
}
private void animateRestore(final boolean isPullRestore) {
ValueAnimator animator = ValueAnimator.ofFloat(mScale, 1f);
animator.setDuration(300);
animator.setInterpolator(new DecelerateInterpolator(2f));
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float value = (float) animation.getAnimatedValue();
if (isPullRestore) {
pull(value);
} else {
push(value);
}
}
});
animator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
isRestoring = true;
}
@Override
public void onAnimationEnd(Animator animation) {
isRestoring = false;
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
animator.start();
}
private void pull(float scale) {
this.setPivotY(0);
this.setScaleY(scale);
}
private void push(float scale) {
this.setPivotY(this.getHeight());
this.setScaleY(scale);
}
}
|
// https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/solution/
class Solution {
public String removeDuplicates(String S) {
StringBuilder sb = new StringBuilder();
int sbLength = 0;
for(char character : S.toCharArray()) {
if (sbLength != 0 && character == sb.charAt(sbLength - 1))
sb.deleteCharAt(sbLength-- - 1);
else {
sb.append(character);
sbLength++;
}
}
return sb.toString();
}
}
|
package com.b.test.entry;
import com.b.test.common.BaseBean;
import java.io.Serializable;
import java.util.Date;
/**
*
* 2018-11-23 11:11:54
* @author Mr.Auto
*/
public class Comment extends BaseBean implements Serializable{
/**
*
*/
private Long id;
/**
*
*/
private Long blogId;
/**
*
*/
private String commentContent;
public void setId(Long id) {
this.id = id;
}
public Long getId() {
return this.id;
}
public void setBlogId(Long blogId) {
this.blogId = blogId;
}
public Long getBlogId() {
return this.blogId;
}
public void setCommentContent(String commentContent) {
this.commentContent = commentContent;
}
public String getCommentContent() {
return this.commentContent;
}
}
|
package algorithm;
import java.util.LinkedList;
import java.util.List;
import org.opencv.core.Mat;
import org.opencv.core.MatOfDMatch;
import org.opencv.core.MatOfKeyPoint;
import org.opencv.core.Point;
import org.opencv.features2d.DMatch;
import org.opencv.features2d.DescriptorExtractor;
import org.opencv.features2d.DescriptorMatcher;
import org.opencv.features2d.FeatureDetector;
import org.opencv.features2d.KeyPoint;
import utils.MatchList;
/*
* Calcul la MatchList des images im1 et im2 en Mat par l'algorithme SIFT
* Modifié à partir de : http://dummyscodes.blogspot.fr/2015/12/using-siftsurf-for-object-recognition.html
*/
public class FDetector {
public static void sift(Mat im1, Mat im2, MatchList output) {
FeatureDetector featureDetector;
DescriptorMatcher descriptorMatcher;
MatOfKeyPoint im1KeyPoints, im1Descriptors, im2KeyPoints, im2Descriptors;
MatOfDMatch goodMatches, matofDMatch;
List<MatOfDMatch> matches;
LinkedList<DMatch> goodMatchesList;
List<KeyPoint> im1Keypointlist, im2Keypointlist;
LinkedList<Point> im1Points, im2Points;
DMatch[] dmatcharray;
DMatch m1,m2;
KeyPoint kpt;
float nndrRatio = 0.7f; // Valeur hérité du code original
//Recherche des points clé de la première image
featureDetector = FeatureDetector.create(FeatureDetector.SIFT);
im1KeyPoints = new MatOfKeyPoint();
im1Descriptors = new MatOfKeyPoint();
featureDetector.detect(im1, im1KeyPoints);
DescriptorExtractor descriptorExtractor = DescriptorExtractor.create(DescriptorExtractor.SIFT);
descriptorExtractor.compute(im1, im1KeyPoints, im1Descriptors);
//Recherche des points clé de la deuxième image
im2KeyPoints = new MatOfKeyPoint();
im2Descriptors = new MatOfKeyPoint();
featureDetector.detect(im2, im2KeyPoints);
descriptorExtractor.compute(im2, im2KeyPoints, im2Descriptors);
//Mise en corrélation des points clé de chaques images
matches = new LinkedList<MatOfDMatch>();
descriptorMatcher = DescriptorMatcher.create(DescriptorMatcher.FLANNBASED);
descriptorMatcher.knnMatch(im1Descriptors, im2Descriptors, matches, 2);
goodMatchesList = new LinkedList<DMatch>();
for (int i = 0; i < matches.size(); i++) {
matofDMatch = (MatOfDMatch) matches.get(i);
dmatcharray = matofDMatch.toArray();
m1 = dmatcharray[0];
m2 = dmatcharray[1];
if (m1.distance <= m2.distance * nndrRatio) goodMatchesList.addLast(m1);
}
//Si on trouve suffisemment de point (valeur fixé arbitrairement, hérité du code original)
if (goodMatchesList.size() >= 7){
im1Keypointlist = im1KeyPoints.toList();
im2Keypointlist = im2KeyPoints.toList();
im1Points = new LinkedList<Point>();
im2Points = new LinkedList<Point>();
for (int i = 0; i < goodMatchesList.size(); i++){
kpt = (KeyPoint)(im1Keypointlist.get(((DMatch)goodMatchesList.get(i)).queryIdx));
im1Points.addLast(kpt.pt);
kpt = (KeyPoint)(im2Keypointlist.get(((DMatch)goodMatchesList.get(i)).trainIdx));
im2Points.addLast(kpt.pt);
}
//Ajout des points trouvé à la liste ouput
goodMatches = new MatOfDMatch();
goodMatches.fromList(goodMatchesList);
KeyPoint[] kpIm1 = (KeyPoint[]) im1Keypointlist.toArray();
KeyPoint[] kpIm2 = (KeyPoint[]) im2Keypointlist.toArray();
for (int i = 0; i < goodMatchesList.size(); ++i) {
output.addIn1(kpIm1[((DMatch)(goodMatchesList.get(i))).queryIdx]);
output.addIn2(kpIm2[((DMatch)(goodMatchesList.get(i))).trainIdx]);
}
}
else
{
System.out.println("Not Found");
}
System.out.println("Ended");
}
}
|
package com.esum.imsutil.util;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import javax.management.remote.JMXConnector;
import org.apache.commons.collections.OrderedMap;
import org.apache.commons.collections.map.ListOrderedMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.esum.appcommon.resource.application.Config;
import com.esum.framework.common.util.SequenceProperties;
import com.esum.framework.core.component.ComponentConstants;
import com.esum.framework.core.component.ComponentStatus;
import com.esum.framework.core.exception.SystemException;
import com.esum.framework.core.management.ManagementException;
import com.esum.framework.core.management.admin.XTrusAdmin;
import com.esum.framework.core.management.admin.XtrusAdminFactory;
import com.esum.wp.ims.componentinfo.ComponentInfo;
import com.esum.wp.ims.config.XtrusConfig;
import com.esum.wp.ims.nodeinfo.NodeInfo;
public class ReloadXTrusAdmin {
private Logger log = LoggerFactory.getLogger(ReloadXTrusAdmin.class);
private static ReloadXTrusAdmin instance;
public static ReloadXTrusAdmin getInstance() {
if(instance==null)
return instance = new ReloadXTrusAdmin();
return instance;
}
private List<NodeInfo> nodeInfoList = null;
private List<ComponentInfo> compInfoList = null;
private List<XTrusAdmin> adminList = null;
private ReloadXTrusAdmin() {
initNodeInfos();
}
private void initNodeInfos() {
if(log.isDebugEnabled())
log.debug("Node information initializing");
this.nodeInfoList = XtrusConfig.loadNodeInfoList();
this.compInfoList = XtrusConfig.loadComponentInfoList();
try {
loadXtrusAdmin();
} catch (ManagementException e) {
log.error(e.getMessage(), e);
}
log.info("Node/Component info loaded.");
}
public void reloadNodeInfos() {
this.nodeInfoList.clear();
this.compInfoList.clear();
initNodeInfos();
}
private List<NodeInfo> getMainNodeInfoList() {
if(this.nodeInfoList==null || this.nodeInfoList.size()==0)
return null;
List<NodeInfo> mainNodes = new ArrayList<NodeInfo>();
for(int i=0;i<this.nodeInfoList.size();i++) {
NodeInfo nodeInfo = this.nodeInfoList.get(i);
if(nodeInfo.getNode_type().equals("M"))
mainNodes.add(nodeInfo);
}
return mainNodes;
}
private NodeInfo getMainNodeInfo(String mainNodeId) {
if(this.nodeInfoList==null || this.nodeInfoList.size()==0)
return null;
for(int i=0;i<this.nodeInfoList.size();i++) {
NodeInfo nodeInfo = this.nodeInfoList.get(i);
if(nodeInfo.getNode_type().equals("M") && nodeInfo.getNodeId().equals(mainNodeId))
return nodeInfo;
}
return null;
}
public NodeInfo getNodeInfo(String nodeId) {
if(this.nodeInfoList==null || this.nodeInfoList.size()==0)
return null;
for(int i=0;i<this.nodeInfoList.size();i++) {
NodeInfo nodeInfo = this.nodeInfoList.get(i);
if(nodeInfo.getNodeId().equals(nodeId))
return nodeInfo;
}
return null;
}
public NodeInfo getMainNodeInfoByNodeId(String nodeId) {
if(nodeId == null) {
nodeId = Config.getString("Common", "LICENSE_NODE.ID");
}
if(this.nodeInfoList==null || this.nodeInfoList.size()==0)
return null;
NodeInfo found = null;
for(int i=0;i<this.nodeInfoList.size();i++) {
NodeInfo nodeInfo = this.nodeInfoList.get(i);
if(nodeInfo.getNodeId().equals(nodeId)) {
found = nodeInfo;
break;
}
}
if(found==null)
return null;
if(found.getNode_type().equals("S")) {
return getMainNodeInfo(found.getMainNodeId());
}
return found;
}
public List<NodeInfo> getMainNodeListByCompId(String compId) {
List<String> mainNodeIdList = new ArrayList<String>();
for (int i=0; i<this.compInfoList.size(); i++) {
ComponentInfo compInfo = compInfoList.get(i);
if (compInfo.getCompId().equals(compId)) {
String mainNodeId = compInfo.getMainNodeId();
if (!mainNodeIdList.contains(mainNodeId))
mainNodeIdList.add(mainNodeId);
}
}
List<NodeInfo> mainNodeList = new ArrayList<NodeInfo>();
for (int i=0; i<mainNodeIdList.size(); i++) {
NodeInfo mainNodeInfo = getMainNodeInfoByNodeId(mainNodeIdList.get(i));
if (mainNodeInfo != null)
mainNodeList.add(mainNodeInfo);
}
return mainNodeList;
}
/**
* XtrusAdmin 정보를 로드한다.
*/
public List<XTrusAdmin> loadXtrusAdmin() throws ManagementException {
List<NodeInfo> mainNodeInfoList = getMainNodeInfoList();
if(this.adminList!=null) {
return this.adminList;
}
this.adminList = new ArrayList<XTrusAdmin>();
for (int i=0;i<mainNodeInfoList.size(); i++) {
NodeInfo nodeInfo = mainNodeInfoList.get(i);
XTrusAdmin xtrusAdmin = XtrusAdminFactory.getInstance().getXtrusAdmin(
nodeInfo.getNodeId(), nodeInfo.getHostName(), Integer.parseInt(nodeInfo.getPort()));
this.adminList.add(xtrusAdmin);
}
return this.adminList;
}
/**
* 특정 노드에 대한 XtrusAdmin객체를 생성한다.
*/
public XTrusAdmin getXtrusAdminByNodeId(String nodeId) throws ManagementException {
NodeInfo nodeInfo = getMainNodeInfoByNodeId(nodeId);
if (nodeInfo == null) {
log.error("Could not find MainNodeId from nodeId '"+nodeId+"'");
throw new ManagementException("xTrusAdminLoad()", "Could not find MainNodeId from nodeId '"+nodeId+"'");
}
XTrusAdmin xtrusAdmin = XtrusAdminFactory.getInstance().getXtrusAdmin(
nodeInfo.getNodeId(), nodeInfo.getHostName(), Integer.parseInt(nodeInfo.getPort()));
return xtrusAdmin;
}
/**
* 입력받은 mainNodeId에 대한 xTrus 엔진이 중지된 상태라며, 다른 MAIN 노드를 찾아서 연결을 시도한다.
* 연결이 되면 XtrusAdmin을 리턴하고, 그렇지 않다면 Exception을 리턴한다.
*/
public XTrusAdmin getAvailableAdmin(String mainNodeId) throws ManagementException {
if(mainNodeId == null) {
mainNodeId = Config.getString("Common", "LICENSE_NODE.ID");
}
XTrusAdmin admin = getXtrusAdminByNodeId(mainNodeId);
JMXConnector connector = null;
try {
connector = admin.connect();
} catch (ManagementException e) {
log.warn("'"+mainNodeId+"' is not available. Get the next main node.");
List<NodeInfo> mainNodeInfos = getMainNodeInfoList();
for(NodeInfo n : mainNodeInfos) {
if(n.getNodeId().equals(mainNodeId))
continue;
log.info("'"+n.getNodeId()+"' connecting...");
admin = getXtrusAdminByNodeId(n.getNodeId());
try {
connector = admin.connect();
break;
} catch (ManagementException ex) {
log.warn("'"+mainNodeId+"' is not available. Get the next main node.");
}
}
} finally {
try {
if(connector!=null)
connector.close();
} catch (IOException e) {
}
}
if(admin==null)
throw new ManagementException("getAvailableAdmin()", "All Main node id was not avaiable.");
return admin;
}
public List<XTrusAdmin> loadXtrusAdminListByCompId(String componentId) throws ManagementException {
List<NodeInfo> mainNodeInfoList = getMainNodeListByCompId(componentId);
List<XTrusAdmin> xTrusAdminList = new ArrayList<XTrusAdmin>();
int size = mainNodeInfoList.size();
for (int i=0; i<size; i++) {
NodeInfo nodeInfo = mainNodeInfoList.get(i);
XTrusAdmin xtrusAdmin = XtrusAdminFactory.getInstance().getXtrusAdmin(
nodeInfo.getNodeId(), nodeInfo.getHostName(), Integer.parseInt(nodeInfo.getPort()));
xTrusAdminList.add(xtrusAdmin);
}
return xTrusAdminList;
}
public boolean getRemoteStatus(String mainNodeId, String compid) throws ManagementException {
return getRemoteStatus(getXtrusAdminByNodeId(mainNodeId), compid);
}
public Map<String, Boolean> getRemoteStatus(String mainNodeId) throws ManagementException {
return getRemoteStatus(getXtrusAdminByNodeId(mainNodeId));
}
public Map<String, Boolean> getRemoteStatus(XTrusAdmin xtrusAdmin) {
Map<String, Boolean> resultMap = new HashMap<String, Boolean>();
try{
List<ComponentStatus> statusMap = xtrusAdmin.getComponentListStatus();
Iterator<ComponentStatus> i = statusMap.iterator();
while(i.hasNext()) {
ComponentStatus compStatus = i.next();
String status = compStatus.getStatus();
if(!ComponentConstants.STATUS_RUNNING.equals(status)){
resultMap.put(compStatus.getNodeId()+":"+compStatus.getCompId(), Boolean.FALSE);
} else {
resultMap.put(compStatus.getNodeId()+":"+compStatus.getCompId(), Boolean.TRUE);
}
}
} catch(Exception e){
log.error(" ReloadXTrusAdmin Remote Fail Exception", e);
}
return resultMap;
}
public boolean getRemoteStatus(XTrusAdmin xtrusAdmin, String compid) {
if(StringUtils.isEmpty(compid))
return false;
if(compid.equals(ComponentConstants.MAIN_COMPONENT_ID))
return true;
try{
String status = xtrusAdmin.getComponentStatus(compid);
return status.equals(ComponentConstants.STATUS_RUNNING);
} catch(Exception e){
log.error(" ReloadXTrusAdmin Remote Fail Exception", e);
}
return false;
}
public void reloadInfoRecord(String[] ids, String configId) throws SystemException {
this.reloadInfoRecord(null, ids, configId);
}
private boolean isLoadSecurityInfoRecord(String configId) {
if(XtrusConfig.PKI_STORE_TABLE_ID.equals(configId) ||
XtrusConfig.XML_DSIG_INFO_TABLE_ID.equals(configId) ||
XtrusConfig.XML_ENC_INFO_TABLE_ID.equals(configId) ||
XtrusConfig.SSH_AUTH_INFO_TABLE_ID.equals(configId) ||
XtrusConfig.FTP_AUTH_INFO_TABLE_ID.equals(configId) ||
XtrusConfig.HTTP_AUTH_INFO_TABLE_ID.equals(configId) ||
XtrusConfig.SAP_FUNCTION_INFO_TABLE_ID.equals(configId)) {
return true;
}
return false;
}
/**
* System에서 사용하는 보안정보들을 Reload하도록 호출한다.
* @param ids reload할 id목록
* @param configId 공통 Config ID
* @throws SystemException
*/
public void reloadSecurityInfoRecord(String[] ids, String configId) throws SystemException {
log.info("Reloading Security InfoRecords... configId : "+configId);
if(!isLoadSecurityInfoRecord(configId))
return;
int size = this.adminList.size();
for (int i=0; i<size; i++) {
XTrusAdmin xtrusAdmin = adminList.get(i);
boolean isServerRunning = this.getComponentStatus(xtrusAdmin, ComponentConstants.MAIN_COMPONENT_ID);
if(isServerRunning) {
xtrusAdmin.reloadSecurityInfo(configId, ids);
}
}
}
/**
* IMS의 설정정보가 신규/변경/삭제 되었을 경우, 서버에게 reload할 수 있도록 알려준다.
*/
public void reloadInfoRecord(String nodeId, String[] ids, String configId) throws SystemException {
log.info("Reloading InfoRecords. configId : "+configId);
if(isLoadSecurityInfoRecord(configId))
reloadSecurityInfoRecord(ids, configId);
else {
if(StringUtils.isNotEmpty(nodeId)) {
XTrusAdmin admin = getXtrusAdminByNodeId(nodeId);
if(getComponentStatus(admin, ComponentConstants.MAIN_COMPONENT_ID))
admin.reloadInfoRecord(configId, ids);
} else {
// 모든 MAIN 노드 들에게 알려준다.
int size = adminList.size();
for (int i=0; i<size; i++) {
XTrusAdmin xtrusAdmin = adminList.get(i);
log.info("Calling to '"+xtrusAdmin.getNodeId()+" for reloading InfoRecord");
boolean isstarted = getComponentStatus(xtrusAdmin, ComponentConstants.MAIN_COMPONENT_ID);
if(isstarted){
xtrusAdmin.reloadInfoRecord(configId, ids);
}
}
}
}
}
public void reloadComponent(String[] ids, String componentId) throws SystemException {
int size = this.adminList.size();
for (int i=0; i<size; i++) {
XTrusAdmin xtrusAdmin = this.adminList.get(i);
boolean isstarted = this.getRemoteStatus(xtrusAdmin, componentId);
if(isstarted){
xtrusAdmin.reloadComponent(componentId, ids, true, true);
}
}
}
/**
* 컴포넌트의 로그 레벨을 설정한다.
*
* @param nodeId 변경할 node ID
* @param compId 컴포넌트 ID
* @param compPackages 컴포넌트의 패키지 정보(,으로 구분)
* @param logLevel 설정할 로그 레벨 - D(DEBUG), I(INFO), E(ERROR)
* @throws SystemException
*/
public void reloadLogLevel(String nodeId, String compId, String compPackages, String logLevel) throws SystemException {
XTrusAdmin admin = getXtrusAdminByNodeId(nodeId);
if (admin == null) {
log.error("reloadLogLevel()", "Could not get the xTrusAdmin with '" + nodeId + "'.");
return;
}
boolean isStarted = this.getRemoteStatus(admin, compId);
if (isStarted) {
admin.setLogLevel(compId, compPackages, logLevel);
}
}
/**
* 시스템의 로그 레벨을 설정한다.
*
* @param nodeId 변경할 node ID
* @param appenderType 변경할 appender 타입 - FRAMEWORK, TRACE, UDC
* @param logLevel 설정할 로그 레벨 - D(DEBUG), I(INFO), E(ERROR)
* @throws SystemException
*/
public void reloadSystemLogLevel(String nodeId, String appenderType, String logLevel) throws SystemException {
XTrusAdmin admin = getXtrusAdminByNodeId(nodeId);
if (admin == null) {
log.error("reloadSystemLogLevel()", "Could not get the xTrusAdmin with '" + nodeId + "'.");
return;
}
admin.setSystemLogLevel(nodeId, appenderType, logLevel);
}
public boolean getComponentStatus(String mainNodeId, String componentId) throws ManagementException {
return getComponentStatus(getXtrusAdminByNodeId(mainNodeId), componentId);
}
public boolean getComponentStatus(XTrusAdmin xtrusAdmin, String componentId){
boolean isstarted = false;
if(componentId.equals(ComponentConstants.MAIN_COMPONENT_ID)){
try{
String status = xtrusAdmin.getComponentStatus(ComponentConstants.MAIN_COMPONENT_ID);
status = status.substring(status.lastIndexOf(":")+1);
log.info("Main Component Id ("+componentId+") status : "+status);
isstarted = status.equals(ComponentConstants.STATUS_RUNNING) ? true : false;
} catch(Exception e){
log.error("status checking error", e);
isstarted = false;
}
} else {
isstarted = this.getRemoteStatus(xtrusAdmin, componentId);
}
return isstarted;
}
public void startupComponent(String mainNodeId, String componentId) throws ManagementException {
XTrusAdmin xtrusAdmin = getXtrusAdminByNodeId(mainNodeId);
xtrusAdmin.startupComponent(componentId);
}
public void shutdownComponent(String mainNodeId, String componentId) throws ManagementException {
XTrusAdmin xtrusAdmin = getXtrusAdminByNodeId(mainNodeId);
xtrusAdmin.shutdownComponent(componentId);
}
/**
* Get the status information of Queue.
*
* @param nodeId
* @return OrderedMap<ComponentStatus, List<QueueStatus>>
* @throws SystemException
*/
public OrderedMap getQueueStatusList(String nodeId) throws SystemException {
XTrusAdmin xtrusAdmin = getXtrusAdminByNodeId(nodeId);
try {
return xtrusAdmin.getQueueStatusList();
} catch (Exception e) {
log.error(" ReloadXTrusAdmin getQueueStatusList Fail Exception", e);
return new ListOrderedMap();
}
}
/**
* Purge Queue.
*/
public boolean purgeQueue(String mainNodeId, String queueName) throws SystemException {
XTrusAdmin xtrusAdmin = getXtrusAdminByNodeId(mainNodeId);
try{
return xtrusAdmin.purgeQueue(queueName);
} catch(Exception e){
log.error(" ReloadXTrusAdmin purgeQueue Fail Exception", e);
}
return false;
}
public List<Map<String, String>> viewQueueMessage(String mainNodeId, String queueName) throws SystemException {
XTrusAdmin xtrusAdmin = getXtrusAdminByNodeId(mainNodeId);
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
try{
list = xtrusAdmin.viewQueue(queueName);
} catch(Exception e){
log.error(" ReloadXTrusAdmin viewQueueMessage Fail Exception", e);
}
return list;
}
public Map<String, String> removeQueueMessage(String mainNodeId, String queueName, String messageId) throws SystemException {
XTrusAdmin xtrusAdmin = getXtrusAdminByNodeId(mainNodeId);
Map<String, String> map = new HashMap<String, String>();
try{
map = xtrusAdmin.removeMessage(queueName, messageId);
} catch(Exception e){
log.error(" ReloadXTrusAdmin removeQueueMessage Fail Exception", e);
}
return map;
}
public String getComponentProperty(String componentId, String key) throws SystemException {
String result = "";
List<XTrusAdmin> xtrusAdminList = loadXtrusAdminListByCompId(componentId);
if (xtrusAdminList.size() > 0) {
XTrusAdmin xtrusAdmin = xtrusAdminList.get(0);
result = xtrusAdmin.getComponentProperty(componentId, key);
}
return result;
}
public Map<String, Object> getMessage(String mainNodeId, String fileLocation, String encoding) throws ManagementException {
return getXtrusAdminByNodeId(mainNodeId).getMessage(fileLocation, encoding);
}
public Map<String, String> processMessageReProcess(String mainNodeId, List<String> msgCtrlIdList) throws ManagementException {
XTrusAdmin admin = getAvailableAdmin(mainNodeId);
return admin.processMessageReProcess(msgCtrlIdList);
}
public Map<String, String> processMessageReSend(String mainNodeId, List<String> msgCtrlIdList) throws ManagementException {
XTrusAdmin admin = getAvailableAdmin(mainNodeId);
return admin.processMessageReSend(msgCtrlIdList);
}
public Map<String, String> resendResponse(String mainNodeId, List<String> msgCtrlIdList) throws ManagementException {
XTrusAdmin admin = getAvailableAdmin(mainNodeId);
return admin.resendResponse(msgCtrlIdList);
}
public Map<String, String> processDocumentReProcess(String mainNodeId, List<String> msgCtrlIdList, List<String> docSeqList) throws ManagementException {
XTrusAdmin admin = getAvailableAdmin(mainNodeId);
return admin.processDocumentReProcess(msgCtrlIdList, docSeqList);
}
public Map<String, String> processNotifyReSend(String mainNodeId, List<String> msgCtrlIdList) throws ManagementException {
return getXtrusAdminByNodeId(mainNodeId).processNotifyReSend(msgCtrlIdList);
}
/** PKI **/
public boolean isKeyEntry(String nodeid, String path, char[] bytes, String type, String alias) throws SystemException {
return getXtrusAdminByNodeId(nodeid).isKeyEntry(nodeid, path, bytes, type, alias);
}
public Map<String, String> createCertificateStore(String nodeid, String keystoreType, String alias, String path, String password, String certPath)
throws SystemException, FileNotFoundException, IOException {
return getXtrusAdminByNodeId(nodeid).createCertificateStore(nodeid, keystoreType, alias, path, password, certPath);
}
/** SSL **/
public SequenceProperties getSSLSequencePropertiesConfig(String path) throws SystemException {
return getXtrusAdminByNodeId(null).getSSLSequencePropertiesConfig(path);
}
public String replacePropertyToValue(String nodeId, String path) throws SystemException {
return getXtrusAdminByNodeId(nodeId).replacePropertyToValue(nodeId, path);
}
public void loadAllStore(String path1, char[] bytes1, String type1, String path2, char[] bytes2, String type2)
throws SystemException {
getXtrusAdminByNodeId(null).loadAllStore(path1, bytes1, type1, path2, bytes2, type2);
}
public Map<String, Vector<String>> getStoreValueList(String alias) throws SystemException {
return getXtrusAdminByNodeId(null).getStoreValueList(alias, 0, -1);
}
public Map<String, Vector<String>> getStoreValueList(String alias, int startIdx, int endIdx) throws SystemException {
return getXtrusAdminByNodeId(null).getStoreValueList(alias, startIdx, endIdx);
}
public Map<String, String> getStoreValue(String alias) throws SystemException {
return getXtrusAdminByNodeId(null).getStoreValue(alias);
}
public void loadTrustStore(String path, char[] bytes, String type) throws SystemException {
getXtrusAdminByNodeId(null).loadTrustStore(path, bytes, type);
}
public void deleteEntry(String nodeId, String alias) throws SystemException {
getXtrusAdminByNodeId(nodeId).deleteEntry(nodeId, alias);
}
public void loadKeyStore(String path, char[] bytes, String type) throws SystemException {
getXtrusAdminByNodeId(null).loadKeyStore(path, bytes, type);
}
public void setCertificateEntry(String nodeId, byte[] items, String alias) throws SystemException {
getXtrusAdminByNodeId(nodeId).setCertificateEntry(nodeId, items, alias);
}
public void setSSLProperty(String key, String value, String path) throws SystemException {
getXtrusAdminByNodeId(null).setSSLProperty(key, value, path);
}
public Map<String, Object> readDocuments(String mainNodeId, List<String> msgCtrlIdList) throws ManagementException {
return null;
// return xTrusAdminLoad(mainNodeId).readDocuments(msgCtrlIdList);
}
public Map<String, Object> changeResponseStatus(String mainNodeId, List<String> msgCtrlIdList, String status) throws ManagementException {
// return xTrusAdminLoad(mainNodeId).changeResponseStatus(msgCtrlIdList, status);
return null;
}
public Map<String, String> moveMessage(String nodeId, String queueName, String targetName) throws SystemException {
XTrusAdmin xtrusAdmin = getXtrusAdminByNodeId(nodeId);
return xtrusAdmin.moveMessage(queueName, targetName);
}
public void restartQueueListener(String nodeId, String componentId, String channelName) throws SystemException {
XTrusAdmin xtrusAdmin = getXtrusAdminByNodeId(nodeId);
xtrusAdmin.restartQueueListener(componentId, channelName);
}
/**
* 배치를 실행한다.
*
* @param nodeId 실행할 노드 ID
* @param batchIfId 실행할 배치IF ID
* @return 실행결과 (true: 성공, false: 실패)
* @throws SystemException
*/
public boolean executeBatch(String nodeId, String batchIfId) throws SystemException {
XTrusAdmin admin = getXtrusAdminByNodeId(nodeId);
if (admin == null) {
log.error("executeBatch()", "Could not get the xTrusAdmin with '" + nodeId + "'.");
return false;
}
boolean isStarted = this.getRemoteStatus(admin, XtrusConfig.BATCH_COMPONENT_ID);
if (isStarted) {
return admin.executeBatch(batchIfId);
}
return false;
}
}
|
package core.server.game.controllers.mechanics;
import java.util.HashSet;
import java.util.Set;
import cards.basics.Attack;
import core.event.game.basic.AttackLockedSourceSkillsCheckEvent;
import core.event.game.basic.AttackLockedSourceWeaponAbilitiesCheckEvent;
import core.event.game.basic.AttackLockedTargetSkillsCheckEvent;
import core.event.game.basic.AttackOnDodgedWeaponAbilitiesCheckEvent;
import core.event.game.basic.AttackPreDamageWeaponAbilitiesCheckEvent;
import core.event.game.basic.AttackTargetEquipmentCheckEvent;
import core.event.game.damage.AttackDamageModifierEvent;
import core.player.PlayerCompleteServer;
import core.server.game.BattleLog;
import core.server.game.Damage;
import core.server.game.GameInternal;
import core.server.game.controllers.AbstractGameController;
import core.server.game.controllers.DodgeUsableGameController;
import core.server.game.controllers.GameControllerStage;
import exceptions.server.game.GameFlowInterruptedException;
public class AttackResolutionGameController
extends AbstractGameController<AttackResolutionGameController.AttackResolutionStage>
implements DodgeUsableGameController {
public static enum AttackResolutionStage implements GameControllerStage<AttackResolutionStage> {
TARGET_LOCKED_SOURCE_HERO_SKILLS,
TARGET_LOCKED_TARGET_HERO_SKILLS,
TARGET_LOCKED_SOURCE_WEAPON_ABILITIES,
TARGET_LOCKED_TARGET_EQUIPMENT_ABILITIES,
DODGE,
ATTACK_DODGED_SOURCE_WEAPON_ABILITIES,
PRE_DAMAGE_SOURCE_WEAPON_ABILITIES,
PRE_DAMAGE_SOURCE_WEAPON_DAMAGE_MODIFIERS,
APPLY_DAMAGE,
END;
}
private final PlayerCompleteServer source;
private final PlayerCompleteServer target;
private final Damage damage;
private final Attack attack;
private final Set<AttackResolutionStage> skippedStages;
public final DodgeGameController dodgeController;
public final DamageGameController damageController;
public AttackResolutionGameController(PlayerCompleteServer source, PlayerCompleteServer target, Attack card, int damage) {
this.source = source;
this.target = target;
this.attack = card;
this.damage = new Damage(damage, this.attack.getElement(), this.source, this.target);
this.skippedStages = new HashSet<>();
this.dodgeController = new DodgeGameController(
this,
this.target,
this.source + " used " + this.attack + " on you, use Dodge to counter?"
);
this.damageController = new DamageGameController(this.damage);
}
@Override
protected void handleStage(GameInternal game, AttackResolutionStage stage) throws GameFlowInterruptedException {
if (this.skippedStages.contains(stage)) {
this.nextStage();
return;
}
switch(stage) {
case TARGET_LOCKED_SOURCE_HERO_SKILLS:
this.nextStage();
game.emit(new AttackLockedSourceSkillsCheckEvent(source, target, this));
break;
case TARGET_LOCKED_TARGET_HERO_SKILLS:
this.nextStage();
game.emit(new AttackLockedTargetSkillsCheckEvent(this.source, this.target, this));
break;
case TARGET_LOCKED_SOURCE_WEAPON_ABILITIES:
this.nextStage();
game.emit(new AttackLockedSourceWeaponAbilitiesCheckEvent(this.source, this.target, this));
break;
case TARGET_LOCKED_TARGET_EQUIPMENT_ABILITIES:
this.nextStage();
game.emit(new AttackTargetEquipmentCheckEvent(this.target.getPlayerInfo(), this.attack, this));
break;
case DODGE:
game.pushGameController(this.dodgeController);
break;
case ATTACK_DODGED_SOURCE_WEAPON_ABILITIES:
// by default, an Attack does not apply damage if dodged
this.setStage(AttackResolutionStage.END);
game.log(BattleLog.playerADidX(target, "Dodged the Attack"));
game.emit(new AttackOnDodgedWeaponAbilitiesCheckEvent(this.source, this.target, this));
break;
case PRE_DAMAGE_SOURCE_WEAPON_ABILITIES:
this.nextStage();
game.emit(new AttackPreDamageWeaponAbilitiesCheckEvent(this.source, this.target, this));
break;
case PRE_DAMAGE_SOURCE_WEAPON_DAMAGE_MODIFIERS:
this.nextStage();
game.emit(new AttackDamageModifierEvent(this.damage));
break;
case APPLY_DAMAGE:
this.nextStage();
game.pushGameController(this.damageController);
break;
case END:
break;
default:
break;
}
}
@Override
public void onDodged() {
this.setStage(AttackResolutionStage.ATTACK_DODGED_SOURCE_WEAPON_ABILITIES);
}
@Override
public void onNotDodged() {
this.setStage(AttackResolutionStage.PRE_DAMAGE_SOURCE_WEAPON_ABILITIES);
}
public void skipStage(AttackResolutionStage stage) {
this.skippedStages.add(stage);
if (stage == AttackResolutionStage.DODGE) {
// if dodge is skipped, also skip post-dodge stages
this.skippedStages.add(AttackResolutionStage.ATTACK_DODGED_SOURCE_WEAPON_ABILITIES);
}
}
public Attack getAttackCard() {
return this.attack;
}
@Override
protected AttackResolutionStage getInitialStage() {
return AttackResolutionStage.TARGET_LOCKED_SOURCE_HERO_SKILLS;
}
}
|
package gameVoiceHandler.intents.handlers.Utils;
import com.amazon.speech.speechlet.SpeechletResponse;
import gameVoiceHandler.intents.speeches.Speeches;
import gameVoiceHandler.intents.speeches.SpeechesGenerator;
/**
* Created by corentinl on 2/22/16.
*/
public class BadIntentUtil {
public static SpeechletResponse initializationUnexpected() {
String speechOutput = Speeches.NO_INITIALIZATION;
return SpeechesGenerator.newAskResponse(speechOutput, false, speechOutput, false);
}
public static SpeechletResponse parameterizationAdvancedGameUnexpected() {
String speechOutput = Speeches.NO_ADVANCED_GAME_SETUP;
return SpeechesGenerator.newAskResponse(speechOutput, false, speechOutput, false);
}
public static SpeechletResponse fireUnexpected() {
String speechOutput = Speeches.NO_FIRE_YET;
return SpeechesGenerator.newAskResponse(speechOutput, false, speechOutput, false);
}
}
|
package itsalerts.rti.com.itsalerts;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.common.io.ByteStreams;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import itsalerts.rti.com.itsalerts.itsalerts.rti.com.itsalerts.network.HTTPConnection;
public class LoginActivity extends AppCompatActivity {
EditText et_username, et_password;
Button btn_submit;
Handler mHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
et_username = (EditText) findViewById(R.id.username);
et_password = (EditText) findViewById(R.id.password);
btn_submit = (Button) findViewById(R.id.submit);
btn_submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendRequest();
}
});
}
private void sendRequest() {
new Thread(new Runnable() {
@Override
public void run() {
sendSoapRequest();
}
}).start();
}
private void sendSoapRequest() {
try {
URL url = new URL("https://www.americanexpress.com/in/");
HttpURLConnection urlConnection = HTTPConnection.getHttpURLConnection(url);
InputStream in = urlConnection.getInputStream();
System.out.println("Response:: "+new String(ByteStreams.toByteArray(in)));
}catch (IOException e){
e.printStackTrace();
}
}
}
|
package com.game.cwtetris.data;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import java.util.HashMap;
import static com.game.cwtetris.CWTApp.getAppContext;
/**
* Created by gena on 12/12/2016.
*/
public class ImageCache {
private static HashMap<String, Bitmap> cache = new HashMap<String, Bitmap>();
public static Bitmap getImage(String pictureName){
Context context = getAppContext();
Bitmap bitmap = cache.get(pictureName);
if (bitmap == null) {
int drawableResourceId = context.getResources().getIdentifier(pictureName, "drawable", context.getPackageName());
bitmap = BitmapFactory.decodeResource(context.getResources(), drawableResourceId);
addImage(pictureName, bitmap);
}
return bitmap;
}
public static Bitmap addImage(String pictureName, Bitmap bitmap){
return cache.put(pictureName, bitmap);
}
public static int getColor(int color){
switch (color) {
case 1: return Color.rgb(255, 0, 0);
case 2: return Color.rgb(181, 230, 29);
case 3: return Color.rgb(163, 73, 164);
case 4: return Color.rgb(255, 201, 27);
case 5: return Color.rgb(63, 72, 204);
case 6: return Color.rgb(255, 87, 27);
case 7: return Color.rgb(200, 0, 125);
case 8: return Color.rgb(40, 215, 166);
case 9: return Color.rgb(70, 5, 110);
case 10: return Color.rgb(0, 200, 25);
case 11: return Color.rgb(0, 255, 255);
case 12: return Color.rgb(150, 0, 255);
}
return Color.rgb(195, 195, 195);
};
}
|
package com.ipincloud.iotbj.srv.service;
import com.ipincloud.iotbj.srv.domain.Accesslog;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSONObject;
//(Iotbj)访问记录 服务接口
//generate by redcloud,2020-07-24 19:59:20
public interface AccesslogService {
//@param id 主键
//@return 实例对象Accesslog
Accesslog queryById(Long id);
//@param jsonObj 过滤条件等
//@return 实例对象Accesslog
List<Map> accesslogQuery(JSONObject jsonObj);
}
|
/**
*
*/
package com.android.aid;
import android.content.Context;
/**
* @author wangpeifeng
*
*/
public class InitPreferences extends MainSharedPref{
private static final String PREF_KEY_DATA_INIT = "data_init";
public static final int VAL_DATA_NULL = 0;
public static final int VAL_DATA_INITING = 1;
public static final int VAL_DATA_INITED = 2;
private static final int VAL_DEF_DATA_INIT = VAL_DATA_NULL;
public InitPreferences(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
@Override
protected String getPrefFileName() {
// TODO Auto-generated method stub
return "pref_init";
}
public int getDataInit(){
return getInt(PREF_KEY_DATA_INIT, VAL_DEF_DATA_INIT);
}
public void setDataInit(int init){
putInt(PREF_KEY_DATA_INIT, init);
}
public boolean isDataNull(){
if (getDataInit()==VAL_DATA_NULL){
return true;
}
else{
return false;
}
}
public boolean isDataInited(){
if (getDataInit()==VAL_DATA_INITED){
return true;
}
else{
return false;
}
}
public boolean isDataIniting(){
if (getDataInit()==VAL_DATA_INITING){
return true;
}
else{
return false;
}
}
}
|
package com.jia.bigdata;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.Job;
/**
* @author tanjia
* @email 378097217@qq.com
* @date 2019/7/15 2:04
*/
public class JobFactory {
public static final Job create(final Class driver, final Class mapper, final Class reducer, final Class mapperKey, final Class mapperValue, final Class outKey, final Class outValue) throws Exception {
System.setProperty("HADOOP_USER_NAME", "root");
System.setProperty("HADOOP_HOME", "D:\\hadoop\\winutils\\hadoop-2.6.0");
System.setProperty("hadoop.home.dir", "D:\\hadoop\\winutils\\hadoop-2.6.0");
final Configuration configuration = new Configuration();
configuration.set("fs.defaultFS", "hdfs://123.207.9.164:8020");
configuration.set("fs.hdfs.impl", "org.apache.hadoop.hdfs.DistributedFileSystem");
configuration.set("dfs.client.block.write.replace-datanode-on-failure.policy", "NEVER");
configuration.set("dfs.replication", "1");
final Job job = Job.getInstance(configuration);
job.setJarByClass(driver);
job.setMapperClass(mapper);
job.setReducerClass(reducer);
job.setCombinerClass(reducer);
job.setMapOutputKeyClass(mapperKey);
job.setMapOutputValueClass(mapperValue);
job.setOutputKeyClass(outKey);
job.setOutputValueClass(outValue);
return job;
}
}
|
/**
* <object operation util.>
* Copyright (C) <2009> <Wang XinFeng,ACC http://androidos.cc/dev>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package cn.itcreator.android.reader.util;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* object operation util
*
* @author Wang XinFeng
* @version 1.0
*/
public class ObjectUtil {
/**object output stream*/
private ObjectOutputStream mObjectOutputStream = null;
/**object input stream*/
private ObjectInputStream mObjectInputStream = null;
/**the file path*/
private String filePath;
/**
*
* @param filePath
* file path when read a object or save object file
*/
public ObjectUtil(String filePath) {
this.filePath = filePath;
}
/**
* save object to file
*
* @param o
* a object u wanna save
* @return if save successful ,return true ,otherwise false
*/
public boolean saveToFile(Object o) {
boolean flag = true;
try {
mObjectOutputStream = new ObjectOutputStream(new FileOutputStream(
filePath));
mObjectOutputStream.writeObject(o);
mObjectOutputStream.flush();
mObjectOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
flag = false;
}
return flag;
}
/**
* read a file to java object
* @return the java object
*/
public Object fileToObject() {
Object ob = null;
try {
mObjectInputStream = new ObjectInputStream(new FileInputStream(
filePath));
ob = mObjectInputStream.readObject();
mObjectInputStream.close();
} catch (IOException e) {
ob = null;
} catch (ClassNotFoundException e) {
ob = null;
}
return ob;
}
}
|
package com.example.p0601alertdialogsimple;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
final int DIALOG_EXIT = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onclick(View view) {
showDialog(DIALOG_EXIT);
}
@Override
public void onBackPressed() {
showDialog(DIALOG_EXIT);
}
protected Dialog onCreateDialog(int id) {
if (id == DIALOG_EXIT) {
AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setTitle(R.string.exit);
adb.setMessage(R.string.save_data);
adb.setIcon(android.R.drawable.ic_dialog_info);
adb.setPositiveButton(R.string.yes,clickListener);
adb.setNegativeButton(R.string.no,clickListener);
adb.setNeutralButton(R.string.cancel,clickListener);
return adb.create();
} else return super.onCreateDialog(id);
}
DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case Dialog
.BUTTON_POSITIVE:
saveData();
break;
case Dialog.BUTTON_NEGATIVE:
finish();
break;
case Dialog.BUTTON_NEUTRAL:
break;
}
}
};
private void saveData() {
Toast.makeText(this,R.string.saved,Toast.LENGTH_SHORT).show();
}
}
|
package classes;
/**
* Enumeration TypeReaps - écrire ici la description de l'énumération
*
* @author (votre nom)
* @version (numéro de version ou date)
*/
public enum TypeRepas
{
ENTREE,PLAT,DESSERT
}
|
package com.pacoapp.paco.js.bridge;
import java.io.IOException;
import java.util.List;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import android.content.Context;
import android.webkit.JavascriptInterface;
import com.pacoapp.paco.sensors.android.AndroidInstalledApplications;
import com.pacoapp.paco.shared.model2.JsonConverter;
public class JavascriptPackageManager {
private Context context;
public JavascriptPackageManager(Context context) {
this.context = context;
}
/**
* get a list of all the short names of the installed applications
* on the phone.
*/
@JavascriptInterface
public String getNamesOfInstalledApplications() {
final List<String> namesOfInstalledApplications = new AndroidInstalledApplications(context).getNamesOfInstalledApplications();
ObjectMapper mapper = JsonConverter.getObjectMapper();
String json = null;
try {
json = mapper.writeValueAsString(namesOfInstalledApplications);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
}
|
package com.example.springcoreconcepts.beanlifecycle;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import java.util.Arrays;
public class AwareBeanImpl implements ApplicationContextAware, BeanNameAware, BeanFactoryAware, InitializingBean, DisposableBean {
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
System.out.println("setBeanFactory method of AwareBeanImpl is called");
System.out.println("setBeanFactory:: AwareBeanImpl singleton = " + beanFactory.isSingleton("awareBean"));
}
@Override
public void setBeanName(String beanName) {
System.out.println("setBeanName method of AwareBeanImpl is called");
System.out.println("setBeanName:: Bean Name defined in context = " + beanName);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
System.out.println("setApplicationContext method of AwareBeanImpl is called");
System.out.println("setApplicationContext:: Bean Definition Names = " + Arrays.toString(applicationContext.getBeanDefinitionNames()));
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("afterPropertiesSet method of AwareBeanImpl bean called !! ");
}
@Override
public void destroy() throws Exception {
System.out.println("Destroy method of AwareBeanImpl bean called !! ");
}
public void customInit() throws Exception {
System.out.println("Custom Init method of AwareBeanImpl called !! ");
}
public void customDestroy() throws Exception {
System.out.println("Custom destroy method of AwareBeanImpl called !! ");
}
}
|
/*
* Copyright 2002-2019 the original author or authors.
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.i18n;
import java.util.Locale;
import java.util.TimeZone;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Juergen Hoeller
*/
public class LocaleContextHolderTests {
@Test
public void testSetLocaleContext() {
LocaleContext lc = new SimpleLocaleContext(Locale.GERMAN);
LocaleContextHolder.setLocaleContext(lc);
assertThat(LocaleContextHolder.getLocaleContext()).isSameAs(lc);
assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.GERMAN);
assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getDefault());
lc = new SimpleLocaleContext(Locale.GERMANY);
LocaleContextHolder.setLocaleContext(lc);
assertThat(LocaleContextHolder.getLocaleContext()).isSameAs(lc);
assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.GERMANY);
assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getDefault());
LocaleContextHolder.resetLocaleContext();
assertThat(LocaleContextHolder.getLocaleContext()).isNull();
assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.getDefault());
assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getDefault());
}
@Test
public void testSetTimeZoneAwareLocaleContext() {
LocaleContext lc = new SimpleTimeZoneAwareLocaleContext(Locale.GERMANY, TimeZone.getTimeZone("GMT+1"));
LocaleContextHolder.setLocaleContext(lc);
assertThat(LocaleContextHolder.getLocaleContext()).isSameAs(lc);
assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.GERMANY);
assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+1"));
LocaleContextHolder.resetLocaleContext();
assertThat(LocaleContextHolder.getLocaleContext()).isNull();
assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.getDefault());
assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getDefault());
}
@Test
public void testSetLocale() {
LocaleContextHolder.setLocale(Locale.GERMAN);
assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.GERMAN);
assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getDefault());
boolean condition1 = LocaleContextHolder.getLocaleContext() instanceof TimeZoneAwareLocaleContext;
assertThat(condition1).isFalse();
assertThat(LocaleContextHolder.getLocaleContext().getLocale()).isEqualTo(Locale.GERMAN);
LocaleContextHolder.setLocale(Locale.GERMANY);
assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.GERMANY);
assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getDefault());
boolean condition = LocaleContextHolder.getLocaleContext() instanceof TimeZoneAwareLocaleContext;
assertThat(condition).isFalse();
assertThat(LocaleContextHolder.getLocaleContext().getLocale()).isEqualTo(Locale.GERMANY);
LocaleContextHolder.setLocale(null);
assertThat(LocaleContextHolder.getLocaleContext()).isNull();
assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.getDefault());
assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getDefault());
LocaleContextHolder.setDefaultLocale(Locale.GERMAN);
assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.GERMAN);
LocaleContextHolder.setDefaultLocale(null);
assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.getDefault());
}
@Test
public void testSetTimeZone() {
LocaleContextHolder.setTimeZone(TimeZone.getTimeZone("GMT+1"));
assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.getDefault());
assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+1"));
boolean condition1 = LocaleContextHolder.getLocaleContext() instanceof TimeZoneAwareLocaleContext;
assertThat(condition1).isTrue();
assertThat(LocaleContextHolder.getLocaleContext().getLocale()).isNull();
assertThat(((TimeZoneAwareLocaleContext) LocaleContextHolder.getLocaleContext()).getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+1"));
LocaleContextHolder.setTimeZone(TimeZone.getTimeZone("GMT+2"));
assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.getDefault());
assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+2"));
boolean condition = LocaleContextHolder.getLocaleContext() instanceof TimeZoneAwareLocaleContext;
assertThat(condition).isTrue();
assertThat(LocaleContextHolder.getLocaleContext().getLocale()).isNull();
assertThat(((TimeZoneAwareLocaleContext) LocaleContextHolder.getLocaleContext()).getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+2"));
LocaleContextHolder.setTimeZone(null);
assertThat(LocaleContextHolder.getLocaleContext()).isNull();
assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.getDefault());
assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getDefault());
LocaleContextHolder.setDefaultTimeZone(TimeZone.getTimeZone("GMT+1"));
assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+1"));
LocaleContextHolder.setDefaultTimeZone(null);
assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getDefault());
}
@Test
public void testSetLocaleAndSetTimeZoneMixed() {
LocaleContextHolder.setLocale(Locale.GERMANY);
assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.GERMANY);
assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getDefault());
boolean condition5 = LocaleContextHolder.getLocaleContext() instanceof TimeZoneAwareLocaleContext;
assertThat(condition5).isFalse();
assertThat(LocaleContextHolder.getLocaleContext().getLocale()).isEqualTo(Locale.GERMANY);
LocaleContextHolder.setTimeZone(TimeZone.getTimeZone("GMT+1"));
assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.GERMANY);
assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+1"));
boolean condition3 = LocaleContextHolder.getLocaleContext() instanceof TimeZoneAwareLocaleContext;
assertThat(condition3).isTrue();
assertThat(LocaleContextHolder.getLocaleContext().getLocale()).isEqualTo(Locale.GERMANY);
assertThat(((TimeZoneAwareLocaleContext) LocaleContextHolder.getLocaleContext()).getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+1"));
LocaleContextHolder.setLocale(Locale.GERMAN);
assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.GERMAN);
assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+1"));
boolean condition2 = LocaleContextHolder.getLocaleContext() instanceof TimeZoneAwareLocaleContext;
assertThat(condition2).isTrue();
assertThat(LocaleContextHolder.getLocaleContext().getLocale()).isEqualTo(Locale.GERMAN);
assertThat(((TimeZoneAwareLocaleContext) LocaleContextHolder.getLocaleContext()).getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+1"));
LocaleContextHolder.setTimeZone(null);
assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.GERMAN);
assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getDefault());
boolean condition4 = LocaleContextHolder.getLocaleContext() instanceof TimeZoneAwareLocaleContext;
assertThat(condition4).isFalse();
assertThat(LocaleContextHolder.getLocaleContext().getLocale()).isEqualTo(Locale.GERMAN);
LocaleContextHolder.setTimeZone(TimeZone.getTimeZone("GMT+2"));
assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.GERMAN);
assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+2"));
boolean condition1 = LocaleContextHolder.getLocaleContext() instanceof TimeZoneAwareLocaleContext;
assertThat(condition1).isTrue();
assertThat(LocaleContextHolder.getLocaleContext().getLocale()).isEqualTo(Locale.GERMAN);
assertThat(((TimeZoneAwareLocaleContext) LocaleContextHolder.getLocaleContext()).getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+2"));
LocaleContextHolder.setLocale(null);
assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.getDefault());
assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+2"));
boolean condition = LocaleContextHolder.getLocaleContext() instanceof TimeZoneAwareLocaleContext;
assertThat(condition).isTrue();
assertThat(LocaleContextHolder.getLocaleContext().getLocale()).isNull();
assertThat(((TimeZoneAwareLocaleContext) LocaleContextHolder.getLocaleContext()).getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+2"));
LocaleContextHolder.setTimeZone(null);
assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.getDefault());
assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getDefault());
assertThat(LocaleContextHolder.getLocaleContext()).isNull();
}
}
|
package com.genetictest;
import org.junit.Test;
import com.genetic.*;
import static org.junit.Assert.*;
public class GenomeTest {
@Test
public void TestingCompareTo(){
String answer = "unicorn";
Genome big = Genome.createGenome(answer,"unijorm");
Genome small = Genome.createGenome(answer,"popcorn");
assertEquals(1,big.compareTo(small));
assertEquals(-1,small.compareTo(big));
assertEquals(0,big.compareTo(big));
}
}
|
package com.swapp.dao;
import org.springframework.beans.factory.annotation.Autowired;
import com.swapp.vo.MemberVO;
public class MemberDAOImpl {
@Autowired
private MemberDAO memberDAO;
//회원가입 쿼리 테스트 메서드
public void memberJoin() throws Exception{
MemberVO vo = new MemberVO();
vo.setMemberId("test"); //회원 id
vo.setMemberPw("test"); //회원 비밀번호
vo.setMemberName("test"); //회원 이름
vo.setMemberMail("test"); //회원 메일
vo.setMemberAddr1("test"); //회원 우편번호
vo.setMemberAddr2("test"); //회원 주소
vo.setMemberAddr3("test"); //회원 상세주소
memberDAO.MemberJoin(vo); //쿼리 메서드 실행
}
}
|
package mistaomega.jahoot.server;
import java.io.Serializable;
/**
* Serializable question object which stores all question information
*
* @author Jack Nash
* @version 1.0
*/
public class Question implements Serializable {
private static final long serialVersionUID = 123456789L;
String QuestionName;
String[] QuestionChoices;
int Correct;
/**
* Constructor
*
* @param questionName Name of the question
* @param questionChoices Possible choices for the question
* @param correct Index of the correct answer
*/
public Question(String questionName, String[] questionChoices, int correct) {
this.QuestionName = questionName;
this.QuestionChoices = questionChoices;
this.Correct = correct;
}
public int getCorrect() {
return Correct;
}
public String getQuestionName() {
return QuestionName;
}
public String[] getQuestionChoices() {
return QuestionChoices;
}
@Override
public String toString() {
return this.QuestionName;
}
}
|
package ObjectPractice2;
public class Joker extends Card{
public Joker(){
super(0,0);
}
public void setNumber(int number){
this.number_=number;
}
public void setSuit(int suit){
this.suit_=suit;
}
public String toString(){
return "JK";
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.